ZEKA'yı köprü deposuna taşı — veritabanı erişimi tamamen kaldırıldı
Browse files at this commitd98ed4bdb2d9d5729b24d90099b027c6e2687e37Parent: c64831b- refactor
- ZEKA'yı köprü deposuna taşı — veritabanı erişimi tamamen kaldırıldı
78 changed files +3457 -10987
- .github/workflows/ci.yml +8 -11
- .github/workflows/istege-bagli-testler.yml +2 -41
- .github/workflows/main.yml +11 -14
- .gitignore +3 -16
- DEMO-KURULUM.md +0 -177
- Makefile +1 -1
- README.md +145 -68
- deploy/hezarfen_zeka.env.example +43 -28
- deploy/hezarfen_zeka_compose.service +4 -3
- generator/README.md +26 -55
- generator/_pg_columns.txt +0 -568
- generator/emit.py +4 -14
- generator/engagement.py +6 -6
- generator/main.py +1 -23
- generator/pg_emit.py +0 -564
- generator/pg_map.py +0 -182
- generator/verify_pg.py +0 -64
- paket/20260916000001_zeka.sql +0 -383
- paket/OKU.md +53 -108
- paket/apply_zeka_tables.sh +0 -77
- paket/load_pg_seed.sh +0 -88
- scripts/ci-compose.sh +47 -18
- scripts/ci-konteyner-kanit.sh +49 -138
- scripts/ci-sir-tara.py +66 -9
- service/.env.example +24 -16
- service/README.md +38 -8
- service/compose.yaml +2 -39
- service/docs/BACKEND-GEREKSINIMLERI.md +92 -45
- service/docs/CIKTI-SOZLESMESI.md +238 -212
- service/docs/DAGITIM.md +53 -52
- service/docs/DEPOLAMA.md +0 -308
- service/docs/DESEN-DOGRULAMA.md +2 -2
- service/docs/HESAP-DOGRULAMA.md +1 -1
- service/docs/KOPRU-KANITI.md +4 -3
- service/docs/OKUL-DB-TABLOLARI.md +0 -231
- service/docs/POSTGRES-GECIS.md +0 -162
- service/docs/RAPORLAR.md +12 -11
- service/requirements.txt +0 -13
- service/schema/postgres/school/20260916000001_zeka.sql +0 -383
- service/schema/zeka.surql +0 -306
- service/src/bridge.py +183 -56
- service/src/capabilities.py +14 -14
- service/src/cli.py +169 -255
- service/src/compute/model.py +2 -2
- service/src/config.py +9 -64
- service/src/pg_client.py +0 -152
- service/src/pipeline.py +23 -2
- service/src/protocol.py +143 -2
- service/src/report/__init__.py +6 -6
- service/src/report/build.py +1 -1
- service/src/report/capture.py +85 -29
- service/src/report/gate.py +1 -1
- service/src/report/reader.py +10 -119
- service/src/scheduler.py +28 -3
- service/src/segment/cli.py +22 -28
- service/src/segment/persist.py +5 -16
- service/src/store.py +579 -600
- service/src/store_factory.py +0 -91
- service/src/store_pg.py +0 -748
- service/src/tenants.py +0 -557
- service/tests/fakes.py +149 -1
- service/tests/test_config.py +3 -19
- service/tests/test_no_db.py +168 -0
- service/tests/test_pipeline.py +148 -172
- service/tests/test_report.py +17 -74
- service/tests/test_scheduler.py +180 -194
- service/tests/test_segments.py +93 -77
- service/tests/test_store.py +0 -859
- service/tests/test_store_bridge.py +484 -0
- service/tests/test_store_pg.py +0 -460
- service/tests/test_tenants.py +0 -612
- service/tests/zeka_db.py +0 -210
- tools/apply_zeka_tables.sh +0 -77
- tools/check_pg_rows.sql +0 -439
- tools/check_pg_schema.sh +0 -103
- tools/indexes.surql +0 -83
- tools/load_pg_seed.sh +0 -88
- tools/verify_pg_seed.sql +0 -325
.github/workflows/ci.ymlmodified+8 -11
| @@ -166,16 +166,15 @@ jobs: | ||
| 166 | 166 | # (2) VARKEN gecerli bir yapilandirma uretmeli. Yalnizca ikincisini |
| 167 | 167 | # denetlemek, `${VAR:?}` yerine `${VAR:-}` yazilmasini yakalamaz. |
| 168 | 168 | # |
| 169 | - # ZORUNLU SIRLAR LISTESI compose.yaml'IN KENDISINDEN OKUNUR: ucuncu | |
| 170 | - # sir `ZEKA_PG_DSN` (compose.yaml:82) eklendiginde bu adim ve yerel | |
| 171 | - # esdegeri `scripts/ci-compose.sh` iki sirla kalmis, adim "sirlar | |
| 172 | - # verilse bile patliyor" diyerek KIRMIZI kalmisti. Liste artik tamdir; | |
| 173 | - # compose.yaml'a sir eklerken burayi da guncelleyin (ve | |
| 174 | - # scripts/ci-compose.sh'i; yerel esdeger AYNI kapi olmali). | |
| 169 | + # ZORUNLU SIRLAR LISTESI compose.yaml'IN KENDISINDEN OKUNUR ve TAM | |
| 170 | + # IKI TANEDIR: `AI_SHARED_TOKEN`, `LLM_API_KEY`. Liste burada elle | |
| 171 | + # tutulur; compose.yaml'a yeni bir `${VAR:?}` eklerken burayi da | |
| 172 | + # guncelleyin (ve yerel esdegeri `scripts/ci-compose.sh`'i; yerel | |
| 173 | + # esdeger AYNI kapi olmali). | |
| 175 | 174 | working-directory: service |
| 176 | 175 | run: | |
| 177 | 176 | echo "--- zorunlu env eksikken patlamali ---" |
| 178 | - if env -u AI_SHARED_TOKEN -u DEEPSEEK_API_KEY -u ZEKA_PG_DSN \ | |
| 177 | + if env -u AI_SHARED_TOKEN -u LLM_API_KEY \ | |
| 179 | 178 | docker compose config >/dev/null 2>&1; then |
| 180 | 179 | echo "HATA: zorunlu sirlar olmadan gecti;" |
| 181 | 180 | echo " zorunlu sirlar \${VAR:?} bicimini kaybetmis olabilir." |
| @@ -183,11 +182,9 @@ jobs: | ||
| 183 | 182 | fi |
| 184 | 183 | echo "ok: zorunlu env olmadan reddedildi" |
| 185 | 184 | echo "--- zorunlu env varken gecerli olmali ---" |
| 186 | - AI_SHARED_TOKEN=ci-sahte DEEPSEEK_API_KEY=ci-sahte \ | |
| 187 | - ZEKA_PG_DSN=postgres://ci:ci@127.0.0.1:5432/ci docker compose config | |
| 185 | + AI_SHARED_TOKEN=ci-sahte LLM_API_KEY=ci-sahte docker compose config | |
| 188 | 186 | echo "--- port ACILMAMALI (disa arama servisi) ---" |
| 189 | - if AI_SHARED_TOKEN=ci-sahte DEEPSEEK_API_KEY=ci-sahte \ | |
| 190 | - ZEKA_PG_DSN=postgres://ci:ci@127.0.0.1:5432/ci docker compose config \ | |
| 187 | + if AI_SHARED_TOKEN=ci-sahte LLM_API_KEY=ci-sahte docker compose config \ | |
| 191 | 188 | | grep -qE '^\s+ports:'; then |
| 192 | 189 | echo "HATA: compose port aciyor; ZEKA backend'e dial-out eder, port ACMAZ." |
| 193 | 190 | exit 1 |
.github/workflows/istege-bagli-testler.ymlmodified+2 -41
| @@ -2,9 +2,8 @@ | ||
| 2 | 2 | # |
| 3 | 3 | # NEDEN AYRI: `ci.yml` hicbir bagimlilik kurmaz ve hicbir sokete dokunmaz; |
| 4 | 4 | # boylece kirmizi/yesil bilgisi ag ve paket deposu kesintilerinden bagimsiz |
| 5 | -# kalir. Buradaki isler ise `aioquic` kurar ya da bir veritabani kaldirir; | |
| 6 | -# yavastir ve dis etkenlere aciktir. Zorunlu kapiya konulsalardi CI | |
| 7 | -# guvenilmez olur, guvenilmez CI da yok sayilir. | |
| 5 | +# kalir. Buradaki is ise `aioquic` kurar; yavastir ve dis etkenlere aciktir. | |
| 6 | +# Zorunlu kapiya konulsaydi CI guvenilmez olur, guvenilmez CI da yok sayilir. | |
| 8 | 7 | # |
| 9 | 8 | # BURADA GERCEK LLM CAGRISI YAPILMAZ. Segment testleri `MockProvider` |
| 10 | 9 | # kullanir; asagida ayrica bir koruma vardir ki bir gun gercek bir anahtar |
| @@ -15,11 +14,6 @@ name: Istege bagli testler | ||
| 15 | 14 | |
| 16 | 15 | on: |
| 17 | 16 | workflow_dispatch: |
| 18 | - inputs: | |
| 19 | - veritabani: | |
| 20 | - description: "SurrealDB entegrasyon testlerini de kosayim mi" | |
| 21 | - type: boolean | |
| 22 | - default: false | |
| 23 | 17 | |
| 24 | 18 | permissions: |
| 25 | 19 | contents: read |
| @@ -65,36 +59,3 @@ jobs: | ||
| 65 | 59 | # baglanti kurulmaz ve sabit port isgal edilmez. |
| 66 | 60 | working-directory: service |
| 67 | 61 | run: python -m unittest discover -s tests -t . -v |
| 68 | - | |
| 69 | - # ========================================================================= | |
| 70 | - veritabani: | |
| 71 | - name: "SurrealDB entegrasyon testleri" | |
| 72 | - if: ${{ inputs.veritabani }} | |
| 73 | - runs-on: ubuntu-latest | |
| 74 | - services: | |
| 75 | - surrealdb: | |
| 76 | - image: surrealdb/surrealdb:v3 | |
| 77 | - ports: ["8000:8000"] | |
| 78 | - options: >- | |
| 79 | - --health-cmd "/surreal is-ready" | |
| 80 | - --health-interval 5s | |
| 81 | - --health-timeout 3s | |
| 82 | - --health-retries 10 | |
| 83 | - steps: | |
| 84 | - - uses: actions/checkout@v4 | |
| 85 | - - uses: actions/setup-python@v5 | |
| 86 | - with: | |
| 87 | - python-version: "3.13" | |
| 88 | - - name: "Semayi yukle ve testleri kos" | |
| 89 | - # `tests/zeka_db.py` bu degiskenler tanimli degilse butun | |
| 90 | - # entegrasyon testlerini `skipUnless` ile atlar; burada acikca | |
| 91 | - # tanimlayip kosturuyoruz. | |
| 92 | - working-directory: service | |
| 93 | - env: | |
| 94 | - ZEKA_TEST_DB_URL: ws://127.0.0.1:8000/rpc | |
| 95 | - ZEKA_TEST_DB_NS: hezarfen_test | |
| 96 | - ZEKA_TEST_DB_USER: root | |
| 97 | - ZEKA_TEST_DB_PASSWORD: root | |
| 98 | - run: | | |
| 99 | - pip install --requirement requirements.txt | |
| 100 | - python -m unittest discover -s tests -t . -v |
.github/workflows/main.ymlmodified+11 -14
| @@ -226,16 +226,15 @@ jobs: | ||
| 226 | 226 | # (2) VARKEN gecerli bir yapilandirma uretmeli. Yalnizca ikincisini |
| 227 | 227 | # denetlemek, `${VAR:?}` yerine `${VAR:-}` yazilmasini yakalamaz. |
| 228 | 228 | # |
| 229 | - # ZORUNLU SIRLAR LISTESI compose.yaml'IN KENDISINDEN OKUNUR: ucuncu | |
| 230 | - # sir `ZEKA_PG_DSN` (compose.yaml:82) eklendiginde bu adim ve yerel | |
| 231 | - # esdegeri `scripts/ci-compose.sh` iki sirla kalmis, adim "sirlar | |
| 232 | - # verilse bile patliyor" diyerek KIRMIZI kalmisti. Liste artik tamdir; | |
| 233 | - # compose.yaml'a sir eklerken burayi da guncelleyin (ve | |
| 234 | - # scripts/ci-compose.sh'i; yerel esdeger AYNI kapi olmali). | |
| 229 | + # ZORUNLU SIRLAR LISTESI compose.yaml'IN KENDISINDEN OKUNUR ve TAM | |
| 230 | + # IKI TANEDIR: `AI_SHARED_TOKEN`, `LLM_API_KEY`. Liste burada elle | |
| 231 | + # tutulur; compose.yaml'a yeni bir `${VAR:?}` eklerken burayi da | |
| 232 | + # guncelleyin (ve yerel esdegeri `scripts/ci-compose.sh`'i; yerel | |
| 233 | + # esdeger AYNI kapi olmali). | |
| 235 | 234 | working-directory: service |
| 236 | 235 | run: | |
| 237 | 236 | echo "--- zorunlu env eksikken patlamali ---" |
| 238 | - if env -u AI_SHARED_TOKEN -u LLM_API_KEY -u ZEKA_PG_DSN \ | |
| 237 | + if env -u AI_SHARED_TOKEN -u LLM_API_KEY \ | |
| 239 | 238 | docker compose config >/dev/null 2>&1; then |
| 240 | 239 | echo "HATA: zorunlu sirlar olmadan gecti;" |
| 241 | 240 | echo " zorunlu sirlar \${VAR:?} bicimini kaybetmis olabilir." |
| @@ -243,11 +242,9 @@ jobs: | ||
| 243 | 242 | fi |
| 244 | 243 | echo "ok: zorunlu env olmadan reddedildi" |
| 245 | 244 | echo "--- zorunlu env varken gecerli olmali ---" |
| 246 | - AI_SHARED_TOKEN=ci-sahte LLM_API_KEY=ci-sahte \ | |
| 247 | - ZEKA_PG_DSN=postgres://ci:ci@127.0.0.1:5432/ci docker compose config | |
| 245 | + AI_SHARED_TOKEN=ci-sahte LLM_API_KEY=ci-sahte docker compose config | |
| 248 | 246 | echo "--- port ACILMAMALI (disa arama servisi) ---" |
| 249 | - if AI_SHARED_TOKEN=ci-sahte LLM_API_KEY=ci-sahte \ | |
| 250 | - ZEKA_PG_DSN=postgres://ci:ci@127.0.0.1:5432/ci docker compose config \ | |
| 247 | + if AI_SHARED_TOKEN=ci-sahte LLM_API_KEY=ci-sahte docker compose config \ | |
| 251 | 248 | | grep -qE '^\s+ports:'; then |
| 252 | 249 | echo "HATA: compose port aciyor; ZEKA backend'e dial-out eder, port ACMAZ." |
| 253 | 250 | exit 1 |
| @@ -440,9 +437,9 @@ jobs: | ||
| 440 | 437 | # OPERATOR ORTAMI SURECE ALINIR. podman-compose interpolasyonu ORTAM |
| 441 | 438 | # DEGISKENLERINE bakar ve `--env-file` YALNIZ SON dosyayi cozer |
| 442 | 439 | # (podman_compose.py:2941-2946, :2559): iki dosyali cagri operator |
| 443 | - # dosyasini tamamen dusuruyordu ve compose.yaml'da uc sir `${VAR:?}` | |
| 444 | - # oldugu icin `up` daha baslamadan reddediyordu (canlida yasandi, | |
| 445 | - # 2026-09-17). Bu yuzden dosya satir satir okunur -- kabuk | |
| 440 | + # dosyasini tamamen dusuruyordu ve compose.yaml'da zorunlu sirlar | |
| 441 | + # (`${VAR:?}`) oldugu icin `up` DAHA BASLAMADAN reddediyordu (canlida | |
| 442 | + # yasandi, 2026-09-17). Bu yuzden dosya satir satir okunur -- kabuk | |
| 446 | 443 | # genisletmesi YOK (deger icindeki `$` oldugu gibi kalir), dosya |
| 447 | 444 | # bicimi duz KEY=value oldugu icin tirnak/`export` aranmaz. |
| 448 | 445 | while IFS= read -r satir || [ -n "$satir" ]; do |
.gitignoremodified+3 -16
| @@ -8,33 +8,20 @@ work/ | ||
| 8 | 8 | # |
| 9 | 9 | # Depoya GIRMEZLER ve bu bilincli bir tercih: |
| 10 | 10 | # |
| 11 | -# * `paket/pg_school.sql` 101 MB — GitHub'in tek dosya siniri 100 MB. | |
| 12 | -# Git LFS ile girebilirdi ama klonlayan herkese 100 MB indirmek, | |
| 13 | -# uretmesi iki dakika suren bir dosya icin makul degil. | |
| 11 | +# * Uretilen tohum yuz megabaytlara cikar — GitHub'in tek dosya siniri | |
| 12 | +# 100 MB. | |
| 14 | 13 | # * Deterministik uretiliyorlar: ayni `--seed` ayni bayti verir. Depoda |
| 15 | 14 | # tutmanin kazandiracagi bir sey yok; kaybettirecegi sey her uretimde |
| 16 | 15 | # bir daha commit edilmeleri. |
| 17 | 16 | # |
| 18 | 17 | # Uretmek icin: |
| 19 | -# python generator/main.py --scale full --postgres --out cikti/ | |
| 18 | +# python generator/main.py --scale full --out cikti/ | |
| 20 | 19 | # |
| 21 | 20 | # `generator/` ve `spec/` depoda: tohumu UYGULAYAN kod ve onu tanimlayan |
| 22 | 21 | # sozlesme. Tohumun kendisi bir CIKTI. |
| 23 | -paket/pg_school.sql | |
| 24 | -paket/pg_control.sql | |
| 25 | -paket/pg_dogrula.sql | |
| 26 | 22 | seed/*.surql |
| 27 | 23 | cikti/ |
| 28 | 24 | |
| 29 | -# Backend'in KENDI migration'larinin kopyasi. Paket kendine yetsin diye | |
| 30 | -# yerelde duruyor ama depoya GIRMEZ: iki yerde duran bir sema er ya da gec | |
| 31 | -# ayrisir ve hangisinin dogru oldugu belli olmaz. Yukleyici gercek backend | |
| 32 | -# checkout'unu `BACKEND=` ile alir. | |
| 33 | -# | |
| 34 | -# ZEKA'nin KENDI migration'i (`paket/20260916000001_zeka.sql`) bunun | |
| 35 | -# disindadir ve depoda durur -- o bizim. | |
| 36 | -paket/migrations/ | |
| 37 | - | |
| 38 | 25 | __pycache__/ |
| 39 | 26 | *.pyc |
| 40 | 27 |
DEMO-KURULUM.mddeleted+0 -177
| @@ -1,177 +0,0 @@ | ||
| 1 | -# Demo kurulumu — yeni (PostgreSQL) backend | |
| 2 | - | |
| 3 | -> **Kime:** backend ekibi. | |
| 4 | -> Bu belge demo okulunu sıfırdan ayağa kaldırmanın tam yolunu verir. | |
| 5 | - | |
| 6 | ---- | |
| 7 | - | |
| 8 | -## 0. Ne değişti, tek cümle | |
| 9 | - | |
| 10 | -Backend SurrealDB'den PostgreSQL'e geçti. ZEKA'nın çıktı tabloları artık okulun | |
| 11 | -kendi Postgres veritabanında duruyor, tohum verisi de oraya yükleniyor. | |
| 12 | - | |
| 13 | -**Köprü değişmedi:** `hab/2`, 19 yolluk izin listesi aynı. ZEKA'nın veri çekme | |
| 14 | -tarafı bu geçişten hiç etkilenmedi. | |
| 15 | - | |
| 16 | ---- | |
| 17 | - | |
| 18 | -## 1. Demo okulu | |
| 19 | - | |
| 20 | -| | | | |
| 21 | -|---|---| | |
| 22 | -| slug | `hezarfen-demo` | | |
| 23 | -| uuid | `01930000-0000-7000-8000-00000000de70` | | |
| 24 | -| veritabanı | `hezarfen_control_school_0193000000007000800000000000de70` | | |
| 25 | -| öğrenci | 250 (563 kullanıcı: + 24 öğretmen, 285 veli, 4 yönetici) | | |
| 26 | -| kapsam | 2025-09-07 → 2026-04-13 (217 gün, 27 öğretim haftası) | | |
| 27 | -| satır | okul 576.487, control 1.148 | | |
| 28 | -| modüller | 21'inin tamamı açık | | |
| 29 | - | |
| 30 | -Ayrı bir okuldur; başka bir okulun verisine dokunmaz. | |
| 31 | - | |
| 32 | -### uuid neden sabit | |
| 33 | - | |
| 34 | -Okul veritabanının **adı slug'dan değil uuid'den** türüyor | |
| 35 | -(`tenant.rs:112` — `"{control}_school_{uuid.simple}"`). Yani tohumu hangi | |
| 36 | -veritabanına yazacağımızı, backend okulu yaratmadan önce bilmemiz gerekiyor. | |
| 37 | -Sabit uuid bunu mümkün kılar; tek kaynağı `generator/pg_map.DEMO_SCHOOL_ID`. | |
| 38 | - | |
| 39 | ---- | |
| 40 | - | |
| 41 | -## 2. ZEKA'nın tabloları | |
| 42 | - | |
| 43 | -`migrations/school/20260916000001_zeka.sql` backend deposuna **eklendi**. | |
| 44 | -Mevcut dört migration dosyasına dokunulmadı — sqlx bunları sağlama toplamıyla | |
| 45 | -izliyor, birini düzenlemek uygulanmış veritabanlarını kırardı. | |
| 46 | - | |
| 47 | -Dokuz tablo: `zeka_student_summary`, `zeka_attention_item`, | |
| 48 | -`zeka_recommendation`, `zeka_run`, `zeka_run_pending`, | |
| 49 | -`zeka_run_failed_module`, `zeka_question_segment`, | |
| 50 | -`zeka_question_segment_dimension`, `zeka_student_segment_profile`. | |
| 51 | - | |
| 52 | -**Yabancı anahtarlar tek yönlü:** `zeka_*` tabloları `app_user`, `course`, | |
| 53 | -`subject`, `exam`, `exam_question`'a bakar; okul tablolarının hiçbiri | |
| 54 | -`zeka_*`'a bakmaz. Dosyayı silseniz okul şeması olduğu gibi ayakta kalır. | |
| 55 | -`tools/check_pg_schema.sh` bunu ayrıca sınar. | |
| 56 | - | |
| 57 | -Backend'in kendi `scripts/prepare_db.sh`'i bu dosyayla birlikte geçiyor. | |
| 58 | - | |
| 59 | ---- | |
| 60 | - | |
| 61 | -## 3. Kurulum | |
| 62 | - | |
| 63 | -```sh | |
| 64 | -# 1) Postgres | |
| 65 | -podman compose up -d postgres | |
| 66 | - | |
| 67 | -# 2) Tohumu üret (SurrealQL çıktısı da aynı geçişte üretilir, o değişmez) | |
| 68 | -python generator/main.py --scale full --postgres --out /tmp/pgseed | |
| 69 | - | |
| 70 | -# 3) Yükle — okul db'sini kurar, şemaları uygular, veriyi döker, | |
| 71 | -# 48 bütünlük denetimini koşturur, control kaydını EN SONA yazar | |
| 72 | -tools/load_pg_seed.sh /tmp/pgseed | |
| 73 | - | |
| 74 | -# 4) Backend'i başlat; okulu hazır ve `active` bulur | |
| 75 | -``` | |
| 76 | - | |
| 77 | -Control kaydının en sona bırakılması bilinçli: backend okulu `active` görür | |
| 78 | -görmez istek kabul etmeye başlıyor, veri hazır olmadan kaydı yazmak **yarım bir | |
| 79 | -okul açmak** olurdu. | |
| 80 | - | |
| 81 | -Yükleme bütünlük sınavında düşerse orada durur. "Yüklendi" deyip bozuk veriyle | |
| 82 | -devam etmek, hiç yüklememekten kötüdür. | |
| 83 | - | |
| 84 | -### Tekrar yükleme | |
| 85 | - | |
| 86 | -Her iki dosya da tek transaction'da koşar ve birincil anahtarlar | |
| 87 | -deterministiktir — ikinci yükleme çakışır ve **hiçbir şey yazmaz**. Yeniden | |
| 88 | -yüklemek için iki veritabanını da düşürmek gerekir. | |
| 89 | - | |
| 90 | ---- | |
| 91 | - | |
| 92 | -## 4. Giriş | |
| 93 | - | |
| 94 | -Yeni backend'de parola okul veritabanında **değil**, control'deki `person` | |
| 95 | -satırında. Zincir: `person` → `person_school` → `app_user.person`. | |
| 96 | - | |
| 97 | -Tohum bu zinciri kuruyor: 563 `person`, 563 `person_school`, ve her `app_user` | |
| 98 | -satırında dolu bir `person` alanı. Ölçüldü: **563/563 eşleşiyor.** | |
| 99 | - | |
| 100 | -Bu kurulmasaydı veri görünür, sistem kullanılamaz olurdu. | |
| 101 | - | |
| 102 | ---- | |
| 103 | - | |
| 104 | -## 5. ZEKA servisi | |
| 105 | - | |
| 106 | -``` | |
| 107 | -ZEKA_PG_DSN=postgresql://<kullanici>:<parola>@<host>:5432/hezarfen_control | |
| 108 | -``` | |
| 109 | - | |
| 110 | -Üretimde bu kullanıcı **yalnız dokuz `zeka_*` tablosuna yazma, kalan 77 tabloya | |
| 111 | -salt okuma** yetkisine daraltılmalı. Bugün geliştirmede tam yetkili kullanıcı | |
| 112 | -kullanılıyor. | |
| 113 | - | |
| 114 | -Servis okumayı bu bağlantıdan değil, **köprüden** yapar. Veritabanı bağlantısı | |
| 115 | -yalnızca yazma içindir. | |
| 116 | - | |
| 117 | ---- | |
| 118 | - | |
| 119 | -## 6. Doğrulama | |
| 120 | - | |
| 121 | -| Ne | Nasıl | Sonuç | | |
| 122 | -|---|---|---| | |
| 123 | -| Şema + davranış | `tools/check_pg_schema.sh` | 19 test, çıkış 0 | | |
| 124 | -| Yüklenen veri | `pg_dogrula.sql` (yükleyici koşturur) | 48 denetim temiz | | |
| 125 | -| ZEKA yazma katmanı | `python -m unittest tests.test_store_pg` | 13 test | | |
| 126 | -| Tüm paket | `python -m unittest discover -s tests -t .` | 686 test | | |
| 127 | - | |
| 128 | -Bütünlük sınavının beş maddesi (I1, I7, I9, I13, I48) yeni şemada **ihlal | |
| 129 | -edilemez** — yabancı anahtarlar, kısmi tekil indeksler ve kolonun hiç var | |
| 130 | -olmaması bunu yapısal olarak imkânsız kılıyor. Listede duruyorlar ve neyle | |
| 131 | -zorlandıkları yanlarında yazıyor. Sıfır dönen bir sorgu, bir şeyi ispatladığı | |
| 132 | -için değil, sorulması imkânsız hale geldiği için de sıfır dönebilir; ikisi aynı | |
| 133 | -şey değil. | |
| 134 | - | |
| 135 | ---- | |
| 136 | - | |
| 137 | -## 7. Bilinmesi gerekenler | |
| 138 | - | |
| 139 | -**Beş zaman damgası yaklaşıktır.** Yeni şemanın eklediği ve tohumda karşılığı | |
| 140 | -olmayan kolonlar, ilgili kaydın ULID damgasından türetiliyor: | |
| 141 | - | |
| 142 | -| Kolon | Doğruluk | | |
| 143 | -|---|---| | |
| 144 | -| `session_attendance.marked_at` | tam (dersin kendi damgası) | | |
| 145 | -| `attendance.marked_at` | yaklaşık (etkinlik damgası, saatler mertebesinde sapma) | | |
| 146 | -| `registration.created_at` | yaklaşık (kayıt etkinlikten önce olur) | | |
| 147 | -| `enrollment.created_at` | yaklaşık (dönem ortası kaydolan için yanlış) | | |
| 148 | -| `exam_result.graded_at` | yaklaşık — **"notlandırma gecikmesi" ölçümü için kullanılamaz** | | |
| 149 | - | |
| 150 | -Gerekçeleri `generator/pg_map.DERIVED_COLUMNS` içinde yazılı. ZEKA hiçbirini | |
| 151 | -okumuyor (köprü izin listesinde o yollar yok). | |
| 152 | - | |
| 153 | -**İki kasıtlı bozukluk temsil edilemiyor.** K2 (`lessons_attended_total` NONE) | |
| 154 | -ve K3 (`high_mark_total` NONE), 250'şer satır. Yeni şemada sayaç kolonları | |
| 155 | -`BIGINT NOT NULL DEFAULT 0`; ikisi de `0` oluyor. Anlam aynı ama ZEKA artık | |
| 156 | -"hiç sayılmadı" ile "sıfır sayıldı" ayrımını yapamaz. Kalan sekiz bozukluk | |
| 157 | -(K1, K4–K10) aynen taşınıyor. | |
| 158 | - | |
| 159 | -**Tohumda bir düzeltme yapıldı.** 4.929 açık pomodoro oturumu vardı, bir | |
| 160 | -öğrencide 68 tane. Hem eski hem yeni backend kullanıcı başına **tek** açık | |
| 161 | -oturuma izin veriyor; SurrealDB bunu zorlamadığı için görünmüyordu. Artık 8 | |
| 162 | -açık oturum var, terk edilmişlik `counted = false` ile taşınıyor. | |
| 163 | - | |
| 164 | ---- | |
| 165 | - | |
| 166 | -## 8. Hâlâ backend ekibinden beklenenler | |
| 167 | - | |
| 168 | -Bu üçü geçişten bağımsız, `docs/BACKEND-GEREKSINIMLERI.md` ile aynı: | |
| 169 | - | |
| 170 | -1. **ZEKA'nın yetenekleri backend'de tanımlı değil.** Backend yalnız | |
| 171 | - `chat.reply` ve `rag.index` tanıyor. ZEKA bağlansa bile iş almaz; istek | |
| 172 | - üzerine çalışan her senaryo kapalı. (Kendi takvimiyle çalışması etkilenmez.) | |
| 173 | -2. **Sınav yolları izin listesinde yok** — madde analizi bu yüzden | |
| 174 | - üretilemiyor. Tohumda 216.633 sınav cevabı ve kasıtlı bozuk maddeler var: | |
| 175 | - bulunacak şey mevcut, bulunacak yol yok. | |
| 176 | -3. **Okul ve kullanıcı listeleme yolu yok** — ZEKA kimleri işleyeceğini | |
| 177 | - köprüden öğrenemiyor, bugün yapılandırmadan çözülüyor. |
Makefilemodified+1 -1
| @@ -61,7 +61,7 @@ compose: ## compose.yaml gecerli mi; zorunlu sirlar zorunlu mu; port acik mi | ||
| 61 | 61 | |
| 62 | 62 | # --- gunluk kullanim ------------------------------------------------------- |
| 63 | 63 | |
| 64 | -kos: ## Servisi compose ile kaldir (zorunlu: AI_SHARED_TOKEN, ZEKA_PG_DSN, DEEPSEEK_API_KEY) | |
| 64 | +kos: ## Servisi compose ile kaldir (zorunlu: AI_SHARED_TOKEN, LLM_API_KEY) | |
| 65 | 65 | cd service && $(MOTOR) compose up -d |
| 66 | 66 | |
| 67 | 67 | loglar: ## Servis gunluklerini izle |
README.mdmodified+145 -68
| @@ -4,19 +4,19 @@ | ||
| 4 | 4 | çalışır: kendi konteynerinde durur, **port açmaz**, backend'in QUIC köprüsüne |
| 5 | 5 | dışa arama yapar. |
| 6 | 6 | |
| 7 | -Okul verisini köprüden **okur**, kendi çıktısını okulun veritabanındaki dokuz | |
| 8 | -`zeka_*` tablosuna **yazar**. Aradaki her şey — hesap modülleri, segmentasyon, | |
| 9 | -kural katalogu — bu depodadır. | |
| 7 | +**Veritabanı bağlantısı yoktur.** Ne bir sürücü, ne bir bağlantı dizesi, ne bir | |
| 8 | +sorgu — uykuda bile yoktur ve olmayacaktır. Okul verisini köprüden **okur**, | |
| 9 | +hesapladığı satırları köprüye **yazar**. Aradaki her şey — hesap modülleri, | |
| 10 | +segmentasyon, kural katalogu — bu depodadır. | |
| 10 | 11 | |
| 11 | 12 | --- |
| 12 | 13 | |
| 13 | 14 | ## Backend ekibi için hızlı bakış |
| 14 | 15 | |
| 15 | -Bağlamak için gereken üç şey: | |
| 16 | +Bağlamak için gereken iki şey: | |
| 16 | 17 | |
| 17 | 18 | ```sh |
| 18 | 19 | AI_SHARED_TOKEN=<backend ile aynı sır> |
| 19 | -ZEKA_PG_DSN=postgres://<kullanıcı>:<parola>@<host>:5432/<kontrol_veritabanı> | |
| 20 | 20 | LLM_API_KEY=<segment hattı için; OpenAI uyumlu her sağlayıcı olur> |
| 21 | 21 | ``` |
| 22 | 22 | |
| @@ -24,7 +24,18 @@ LLM_API_KEY=<segment hattı için; OpenAI uyumlu her sağlayıcı olur> | ||
| 24 | 24 | podman compose up -d |
| 25 | 25 | ``` |
| 26 | 26 | |
| 27 | -Port açmaz, `hezarfen_backend_default` ağına katılır ve backend'e dial-out eder. | |
| 27 | +Port açmaz, `hezarfen_backend_default` ağına katılır ve backend'e dial-out | |
| 28 | +eder. Köprü adresi varsayılanlıdır (`AI_BRIDGE_HOST`/`AI_BRIDGE_PORT`); | |
| 29 | +değiştirmek gerekmedikçe yazılmaz. | |
| 30 | + | |
| 31 | +ZEKA'nın yazdığı dokuz `zeka_*` tablosu **her okulun kendi veritabanında** | |
| 32 | +durur. DDL'i backend deposundadır: | |
| 33 | +`hezarfen_backend/migrations/school/20260917000002_zeka.sql`. ZEKA o dosyayı | |
| 34 | +ne yazar ne uygular — yalnız "şu satırları yaz" der. | |
| 35 | + | |
| 36 | +Okul listesi backend'den gelir (`insight.schools.list`). `ZEKA_SCHOOLS` bir | |
| 37 | +operatör **filtresidir**: boş bırakılırsa dağıtımdaki tüm aktif okullar | |
| 38 | +işlenir, doluysa yalnız listelenenler. | |
| 28 | 39 | |
| 29 | 40 | Okul veritabanının **adı okulun uuid'sinden** türer (`tenant.rs:112` → |
| 30 | 41 | `{control}_school_{uuid.simple}`), slug'dan **değil**. Demo okulu için: |
| @@ -51,7 +62,7 @@ ZEKA ──QUIC hab/2──> backend | ||
| 51 | 62 | akışından sonra istediği zaman. Bu yüzden ZEKA, backend kendisine iş |
| 52 | 63 | göndermesini beklemeden kendi takvimiyle çalışabilir. |
| 53 | 64 | |
| 54 | -Protokol sürümü **`hab/2`** (`constant.rs:515`). Podcast ve Çelebi `hab/1` | |
| 65 | +Protokol sürümü **`hab/2`** (`constant.rs:530`). Podcast ve Çelebi `hab/1` | |
| 55 | 66 | kullanıyor ve bu yüzden **hiç bağlanamıyorlar**; ZEKA o hatayı tekrarlamaz ve |
| 56 | 67 | bir test sabiti pinler. |
| 57 | 68 | |
| @@ -83,14 +94,66 @@ bir modele o veriyi vermek, erişim kontrolünü modelin içinden dolanmak olurd | ||
| 83 | 94 | |
| 84 | 95 | --- |
| 85 | 96 | |
| 86 | -## 2. Nereye yazar | |
| 97 | +## 2. Nereye yazar — köprüye, yetenek çağrısıyla | |
| 98 | + | |
| 99 | +İki yön de aynı köprüdedir: | |
| 100 | + | |
| 101 | +* **Okuma** (okulun kendi API'si): `ApiRequest` izin listesi, §1. | |
| 102 | +* **Yazma ve depo okumaları:** `insight.*` **yetenek çağrıları**. Servis | |
| 103 | + `hab/2` üzerinde taze bir istemci-başlatımlı akış açar ve çerçeveyi yazar: | |
| 104 | + | |
| 105 | +``` | |
| 106 | +{ "id": "<ulid>", "capability": "insight.<ad>", "school": "<slug>", "payload": {...} } | |
| 107 | + | |
| 108 | +{ "status": "ok", "id": ..., "school": ..., "payload": {...} } | |
| 109 | +{ "status": "err", "id": ..., "school": ..., "code": ..., "message": ... } | |
| 110 | +``` | |
| 111 | + | |
| 112 | +Okul **çerçevededir**, payload'da değil: backend slug'ı çözer ve her ifadeyi o | |
| 113 | +okulun kendi veritabanında koşturur. Reddin kodu tiplidir (`unknown_school`, | |
| 114 | +`not_permitted`, `invalid_payload`, `too_many_rows`, `unavailable`, …) ve | |
| 115 | +`CapabilityRefused` olarak yükselir; `status: "err"` asla başarı sayılmaz. | |
| 116 | + | |
| 117 | +### Servisin çağırdığı yetenekler | |
| 118 | + | |
| 119 | +| Yetenek | Ne yapar | | |
| 120 | +|---|---| | |
| 121 | +| `insight.schools.list` | Dağıtımın **aktif** okulları (tek dağıtım ölçekli çağrı: okul alanı boş gider) | | |
| 122 | +| `insight.summary.upsert` | Gecelik öğrenci özeti + dikkat listesi | | |
| 123 | +| `insight.recommendation.upsert` | Tavsiye satırları (kanıtsız satır reddedilir) | | |
| 124 | +| `insight.segment.upsert` | Soru bilişsel etiketleri | | |
| 125 | +| `insight.profile.upsert` | Öğrenci × boyut × etiket profili | | |
| 126 | +| `insight.run.upsert` | Koşu defteri (+ devreden öğrenciler, düşen modüller) | | |
| 127 | +| `insight.pending.list` | Önceki koşudan devreden öğrenciler | | |
| 128 | +| `insight.retention.sweep` | Süresi dolmuş satırların süpürülmesi | | |
| 129 | +| `insight.departed.purge` | Okuldan ayrılanın satırlarının silinmesi | | |
| 130 | + | |
| 131 | +Yazma **500 satırlık gruplar** hâlindedir; bir grup ikinci denemede de düşerse | |
| 132 | +atlanır, `warn` loglanır ve `WriteReport.status` `partial` olur — koşu defterine | |
| 133 | +`store` olarak yazılır. Sessiz başarı yoktur. | |
| 134 | + | |
| 135 | +### Servisin servis ettiği yetenekler | |
| 136 | + | |
| 137 | +Backend'in ZEKA'yı çağırdığı adlar (§5 madde 1, `src/capabilities.py`): | |
| 138 | + | |
| 139 | +| Yetenek | Ne yapar | | |
| 140 | +|---|---| | |
| 141 | +| `insight.student` | Tek öğrenci için hesap + tavsiye | | |
| 142 | +| `insight.class` | Bir sınıf (şube × ders) için toplu analiz | | |
| 143 | +| `insight.refresh` | Okul çapında yeniden koşu (parti işi) | | |
| 144 | + | |
| 145 | +`insight.refresh` ayrıca ZEKA'nın **kendi zamanlayıcısı** tarafından da | |
| 146 | +çağrılır: hesaplar backend istemeden de koşar, yeteneğin tanımlı olması yalnız | |
| 147 | +"istek üzerine tetikleme"yi açar. | |
| 148 | + | |
| 149 | +### Tablolar | |
| 87 | 150 | |
| 88 | 151 | Dokuz tablo, hepsi `zeka_` önekli, hepsi okulun kendi veritabanında: |
| 89 | 152 | |
| 90 | 153 | | Tablo | Ne tutar | |
| 91 | 154 | |---|---| |
| 92 | 155 | | `zeka_student_summary` | öğrenci başına gecelik özet (PK: `student`) | |
| 93 | -| `zeka_attention_item` | dikkat listesi, tetikleyici başına bir satır | | |
| 156 | +| `zeka_attention_item` | dikkat listesi, tetikleyici başına bir satır (`ord` ile sıralı) | | |
| 94 | 157 | | `zeka_recommendation` | tavsiyeler + kapatma izi | |
| 95 | 158 | | `zeka_run` | gece işinin defteri (PK: `run_day`) | |
| 96 | 159 | | `zeka_run_pending` | bütçe dolunca kalanlar | |
| @@ -99,26 +162,32 @@ Dokuz tablo, hepsi `zeka_` önekli, hepsi okulun kendi veritabanında: | ||
| 99 | 162 | | `zeka_question_segment_dimension` | üretim/deneysel boyut ayrımı | |
| 100 | 163 | | `zeka_student_segment_profile` | öğrenci × boyut × etiket, `contrast` dahil | |
| 101 | 164 | |
| 102 | -DDL: `service/schema/postgres/school/20260916000001_zeka.sql` — backend'in | |
| 103 | -`migrations/school/` klasörüne **eklenir**, mevcut dosyalara dokunulmaz. | |
| 165 | +**Satırda `school` alanı yoktur:** kiracı, veritabanının kendisidir. Kimlikleri | |
| 166 | +**yazan taraf üretir** — uuid7'yi backend mints eder, ZEKA göndermez. | |
| 104 | 167 | |
| 105 | 168 | **Yabancı anahtarlar tek yönlü.** `zeka_*` tabloları `app_user`, `course`, |
| 106 | 169 | `subject`, `exam`, `exam_question`'a bakar; okul tablolarının hiçbiri |
| 107 | -`zeka_*`'a bakmaz. Dosyayı silseniz okul şeması olduğu gibi ayakta kalır. | |
| 108 | -`tools/check_pg_schema.sh` bunu ayrıca sınar ve ters yönlü tek bir FK bulursa | |
| 109 | -hata verir. | |
| 170 | +`zeka_*`'a bakmaz. DDL dosyası silinse okul şeması olduğu gibi ayakta kalır. | |
| 171 | + | |
| 172 | +**ZEKA mevcut okul tablolarının hiçbirine yazmaz.** Yazabildiği tek şey yukarıdaki | |
| 173 | +dokuz tablodur; başka bir tabloyu güncelleyen bir yol yoktur. | |
| 110 | 174 | |
| 111 | -**ZEKA mevcut 69 tablonun hiçbirine yazmaz.** `store_pg.TABLES` bu kuralın | |
| 112 | -makine tarafından okunabilir hâlidir. | |
| 175 | +Üzerine yazma **upsert**'tir: uygulamanın yazdığı alanlar (`dismissed_at`, | |
| 176 | +`dismissed_by`, `dismiss_reason`) korunur. Tam değiştirme kullansaydık her gece | |
| 177 | +kullanıcının kapatma kaydı silinirdi. | |
| 113 | 178 | |
| 114 | -### Depo seçimi | |
| 179 | +### Depo katmanı | |
| 115 | 180 | |
| 116 | -Tek ölçüt `ZEKA_PG_DSN`: doluysa Postgres, boşsa (eski) SurrealDB. | |
| 117 | -İki ayrı "mod" bayrağı yok — bayrakla adres ters düştüğünde hangisinin | |
| 118 | -kazandığı tahmin işine döner. Bkz. `src/store_factory.py`. | |
| 181 | +`src/store.py` — `BridgeStore`: **okul dizini + okul başına depo** ve satır | |
| 182 | +payload'larını kuran fonksiyonlar. Zamanlayıcı `store_for(school)` ile o okulun | |
| 183 | +deposunu ister; dönen nesne `pipeline`'ın beklediği sekiz yöntemi taşır. | |
| 184 | +Paylaşılan bir depo yoktur ve olmamalıdır: yanlış okula yazmanın en kolay yolu | |
| 185 | +paylaşılan bir nesnenin okul alanını unutmaktır; burada okul nesnenin | |
| 186 | +kimliğindedir. | |
| 119 | 187 | |
| 120 | -`pipeline.py` ve `scheduler.py` hangi depoya yazdıklarını **bilmez**; ikisi de | |
| 121 | -aynı sekiz yöntemi çağırır. Geçişin hesap kodundaki maliyeti sıfırdı. | |
| 188 | +`pipeline.py` ve `scheduler.py` hangi taşımayı kullandıklarını **bilmez**; ikisi | |
| 189 | +de aynı sekiz yöntemi çağırır. Satırların şekli backend'in kolon adlarıyla | |
| 190 | +aynıdır — iki taraf tek sözlüğü konuşur. | |
| 122 | 191 | |
| 123 | 192 | --- |
| 124 | 193 | |
| @@ -139,8 +208,8 @@ kanıtına bağlıdır. Bir çocuğa "riskli" etiketi takmanın pedagojik savunm | ||
| 139 | 208 | yoktur ve literatür turu bu ürün için doğrulanmış nedensel kanıt bulamamıştır. |
| 140 | 209 | |
| 141 | 210 | Tavsiyeler kanıtsız kurulamaz: `Recommendation` nesnesi `evidence`, `rule_id` |
| 142 | -ve `computed_at` olmadan `ValueError` fırlatır. Depolama katmanı ikinci kez | |
| 143 | -kontrol eder. | |
| 211 | +ve `computed_at` olmadan `ValueError` fırlatır. Depo katmanı ikinci kez | |
| 212 | +kontrol eder; kanıtsız satır reddedilir ve sayısı rapora geçer. | |
| 144 | 213 | |
| 145 | 214 | ### `contrast` — segment profilinin var olma sebebi |
| 146 | 215 | |
| @@ -173,15 +242,15 @@ Yani **bulunacak şey mevcut, bulunacak yol yok.** | ||
| 173 | 242 | |
| 174 | 243 | `service/docs/BACKEND-GEREKSINIMLERI.md` gerekçeleriyle içerir: |
| 175 | 244 | |
| 176 | -1. **ZEKA'nın yetenekleri backend'de tanımlı değil.** Backend yalnız | |
| 177 | - `chat.reply` ve `rag.index` tanır ve eşleşme tamdır. ZEKA bağlansa bile hiç | |
| 178 | - iş almaz — podcast'in yaşadığı sorunun aynısı. Bu olmadan **istek üzerine** | |
| 179 | - çalışan her senaryo kapalıdır. (Kendi takvimiyle çalışması etkilenmez.) | |
| 245 | +1. **`insight.*` kapıları backend'de yok.** Bugün backend yalnız `chat.reply` | |
| 246 | + ve `rag.index` tanıyor; ZEKA'nın çağırdığı dokuz `insight.*` operasyonu ve | |
| 247 | + servis ettiği üç yetenek kapı bekliyor. Bu iş backend'de **`InsightDoors`** | |
| 248 | + hattının sahibindedir; ZEKA ona karşı yazıldı ve zarf donduruldu. | |
| 180 | 249 | 2. **Sınav yolları izin listesinde yok.** Madde analizi için gereken 9 yol |
| 181 | 250 | listelenmiştir. |
| 182 | -3. **Okul ve kullanıcı listeleme yolu yok.** ZEKA kimleri işleyeceğini | |
| 183 | - köprüden öğrenemiyor; bugün yapılandırmadan çözülüyor. Dönem ortası kayıt | |
| 184 | - olan öğrenci görünmez, ayrılan silinmez. | |
| 251 | +3. **Öğrenci listeleme yolu yok.** Okul listesi artık köprüden | |
| 252 | + (`insight.schools.list`), ama kimlerin işleneceği hâlâ yapılandırmadan | |
| 253 | + çözülüyor. Dönem ortası kayıt olan öğrenci görünmez, ayrılan silinmez. | |
| 185 | 254 | |
| 186 | 255 | Bu maddeler **başka bir ekibin sorumluluğundadır.** ZEKA onlarsız da kendi |
| 187 | 256 | takvimiyle çalışır, yalnız kapsamı dardır. |
| @@ -190,16 +259,16 @@ takvimiyle çalışır, yalnız kapsamı dardır. | ||
| 190 | 259 | |
| 191 | 260 | ## 6. Tohum verisi |
| 192 | 261 | |
| 193 | -Depoda **tohumun kendisi yok, üreticisi var.** 101 MB'lık bir SQL dosyası | |
| 194 | -GitHub'ın tek dosya sınırını aşıyor ve deterministik üretildiği için depoda | |
| 195 | -tutmanın kazandıracağı bir şey yok. | |
| 262 | +Depoda **tohumun kendisi yok, üreticisi var.** ~170 MB'lık üretilmiş bir veri | |
| 263 | +seti GitHub'ın tek dosya sınırını da aşıyor ve deterministik üretildiği için | |
| 264 | +depoda tutmanın kazandıracağı bir şey yok. | |
| 196 | 265 | |
| 197 | 266 | ```sh |
| 198 | -python generator/main.py --scale full --postgres --out cikti/ | |
| 267 | +python generator/main.py --scale full --out /tmp/seed | |
| 199 | 268 | ``` |
| 200 | 269 | |
| 201 | -Üretilen: `pg_school.sql` (576.487 satır), `pg_control.sql` (okul + 563 kişi), | |
| 202 | -`pg_dogrula.sql` (48 bütünlük denetimi), ve yanında SurrealQL sürümü. | |
| 270 | +Üretilen: demo okulunun bütün veri seti (`MANIFEST.json` satır sayılarıyla, | |
| 271 | +`_seed_manifest.json` gizli gerçekle) ve 48 bütünlük sorgusu. | |
| 203 | 272 | |
| 204 | 273 | | | | |
| 205 | 274 | |---|---| |
| @@ -209,14 +278,16 @@ python generator/main.py --scale full --postgres --out cikti/ | ||
| 209 | 278 | | ölçüm | 24 öğrenme + 14 arketip + 25 davranış hedefi | |
| 210 | 279 | | kasıtlı bozukluk | 8 tür (analizin bulması *gereken* şeyler) | |
| 211 | 280 | |
| 212 | -Yükleme ve sunucuya gönderme: **`paket/OKU.md`**. | |
| 281 | +**Yükleme bu deponun işi değildir.** Tohum backend ekibine verilir; okulu | |
| 282 | +backend oluşturur ve göç ettirir. ZEKA hiçbir şema uygulamaz, hiçbir veritabanı | |
| 283 | +kullanıcısı istemez. | |
| 213 | 284 | |
| 214 | 285 | --- |
| 215 | 286 | |
| 216 | 287 | ## 7. Çalıştırma |
| 217 | 288 | |
| 218 | 289 | ```sh |
| 219 | -# testler (686) | |
| 290 | +# testler | |
| 220 | 291 | cd service && python -m unittest discover -s tests -t . |
| 221 | 292 | |
| 222 | 293 | # hattı fikstürle uçtan uca koştur (köprü gerekmez) |
| @@ -224,6 +295,11 @@ python -m src.cli run --school hezarfen-demo --source file \ | ||
| 224 | 295 | --fixtures fixtures/demo --dry-run |
| 225 | 296 | ``` |
| 226 | 297 | |
| 298 | +`--dry-run` yazmayı `RecordingCaller`'a çevirir: çağrılar toplanır, hiçbiri | |
| 299 | +kabloya çıkmaz. Hiçbir test gerçek bir veritabanı istemez — servisin açacağı bir | |
| 300 | +bağlantı yoktur; köprü testleri gerçek QUIC soketleriyle, sahte bir sunucuya | |
| 301 | +karşı koşar. | |
| 302 | + | |
| 227 | 303 | **HTTP sunucusu yoktur ve olmayacaktır.** Çelebi'nin geliştirme amaçlı HTTP |
| 228 | 304 | sunucusu üretim imajında duruyor ve denetimde kimlik doğrulamasız yüzey olarak |
| 229 | 305 | işaretlendi; burada geliştirme yüzeyi komut satırı aracıdır. |
| @@ -232,31 +308,29 @@ işaretlendi; burada geliştirme yüzeyi komut satırı aracıdır. | ||
| 232 | 308 | |
| 233 | 309 | | Ne | Nasıl | |
| 234 | 310 | |---|---| |
| 235 | -| Tüm paket | `python -m unittest discover -s tests -t .` (686 test) | | |
| 236 | -| ZEKA'nın yazma katmanı | `ZEKA_PG_DSN=... python -m unittest tests.test_store_pg` | | |
| 237 | -| Şema + davranış | `tools/check_pg_schema.sh` (19 test) | | |
| 238 | -| Yüklenen tohum | `pg_dogrula.sql` (48 denetim) | | |
| 311 | +| Tüm paket | `python -m unittest discover -s tests -t .` | | |
| 312 | +| Köprü | `tests/test_bridge_live.py` — gerçek QUIC, sahte sunucu | | |
| 313 | +| Yazma katmanı | `tests/test_store.py` — `RecordingCaller` ile hat uçtan uca | | |
| 239 | 314 | |
| 240 | -`tests/test_store_pg.py` sahte istemciyle koşmaz — **gerçek PostgreSQL'e** | |
| 241 | -karşı koşar. Sebep deneyle sabit: SurrealDB sürümünde birim testlerin tamamı | |
| 242 | -yeşilken gerçek veritabanında `type::thing()` diye bir fonksiyon olmadığı için | |
| 243 | -tek satır yazılamıyordu. Mock istemci bunu göremez. | |
| 315 | +Yazma katmanının testi **sahte bir çağıranla** koşar ve beklenen çerçeveleri | |
| 316 | +pinler: capability adı, okulun çerçevede gittiği, satır şekilleri. Ölçülen | |
| 317 | +sözleşme budur — backend'e çıkan tur bu depoda test edilmez, backend'in kendi | |
| 318 | +kapı testleri ve `InsightDoors` hattı onu ölçer. | |
| 244 | 319 | |
| 245 | 320 | --- |
| 246 | 321 | |
| 247 | 322 | ## 8. Sınırlar — dürüst liste |
| 248 | 323 | |
| 249 | 324 | - **Gerçek backend'e hiç bağlanılmadı.** Köprü, backend'in protokolünü taklit |
| 250 | - eden sahte bir sunucuya karşı kanıtlandı (35 canlı test, gerçek QUIC | |
| 251 | - bağlantısı). Sahte sunucu Rust kaynağı okunarak yazıldı; kaynak yanlış | |
| 252 | - okunduysa test yanlış davranışı doğrular. Backend ayağa kalktığında yeniden | |
| 253 | - sınanmalıdır. | |
| 325 | + eden sahte bir sunucuya karşı kanıtlandı (gerçek QUIC bağlantısı). Sahte | |
| 326 | + sunucu Rust kaynağı okunarak yazıldı; kaynak yanlış okunduysa test yanlış | |
| 327 | + davranışı doğrular. Backend ayağa kalktığında yeniden sınanmalıdır. | |
| 328 | +- **`insight.*` kapıları backend'de henüz tanımlı değil** (§5 madde 1). Servis | |
| 329 | + kendi takvimiyle çalışır; istek üzerine tetikleme kapılar gelene kadar | |
| 330 | + kapalıdır. | |
| 254 | 331 | - **Sertifika düz HTTP ile çekiliyor** (podcast ve Çelebi ile aynı). |
| 255 | 332 | `AI_TLS_FINGERPRINT` verilirse parmak izi doğrulanır; verilmezse her açılışta |
| 256 | 333 | uyarı basılır. Üretimde verilmelidir. |
| 257 | -- **ZEKA'nın veritabanı kullanıcısı** üretimde yalnız dokuz `zeka_*` tablosuna | |
| 258 | - yazma, kalan 69'una salt okuma yetkisine daraltılmalı. Bugün geliştirmede tam | |
| 259 | - yetkili kullanıcı kullanılıyor. | |
| 260 | 334 | - **`adim_sayisi` boyutu deneyseldir.** El yazısı probda 0,607 kararlılık aldı; |
| 261 | 335 | tohumda çok adımlılık metne açıkça yazıldığı için oradaki yüksek skor bizim |
| 262 | 336 | kendi kolay sınavımızdır. Etiketlenir, saklanır, **aşağı akışta okunmaz**. |
| @@ -270,15 +344,15 @@ tek satır yazılamıyordu. Mock istemci bunu göremez. | ||
| 270 | 344 | ## 9. Yapı |
| 271 | 345 | |
| 272 | 346 | ``` |
| 273 | -generator/ tohum üreticisi (SurrealQL + PostgreSQL, aynı geçiş) | |
| 274 | -paket/ sunucuya gönderilecek paket — OKU.md | |
| 347 | +generator/ tohum üreticisi (deterministik veri seti + bütünlük sorguları) | |
| 348 | +paket/ sunucuya verilecek paket — OKU.md | |
| 275 | 349 | service/ |
| 276 | - src/ köprü, Source, compute/, segment/, report/, store_pg | |
| 277 | - tests/ 686 test | |
| 278 | - schema/ ZEKA'nın DDL'i (postgres/ ve eski surql) | |
| 350 | + src/ köprü (bridge.py), depo (store.py), Source, capabilities, | |
| 351 | + compute/, segment/, report/, scheduler, pipeline | |
| 352 | + tests/ birim + canlı köprü testleri | |
| 279 | 353 | docs/ çıktı sözleşmesi, backend gereksinimleri, ölçüm raporları |
| 280 | 354 | spec/ şema, senaryo, modüller, segmentasyon araştırması |
| 281 | -tools/ yükleyici, doğrulayıcı, ölçüm araçları | |
| 355 | +tools/ doğrulayıcı, ölçüm araçları | |
| 282 | 356 | ``` |
| 283 | 357 | |
| 284 | 358 | Frontend ve backend ekipleri için tek belge: **`service/docs/CIKTI-SOZLESMESI.md`** |
| @@ -290,14 +364,13 @@ isabeti: `service/docs/SEGMENT-CIKTI.md`. | ||
| 290 | 364 | ## 10. Sırlar |
| 291 | 365 | |
| 292 | 366 | `.env` gitignore'ludur ve depoya **girmez**. `compose.yaml` yalnızca |
| 293 | -interpolasyon içerir, literal sır taşımaz. `AI_SHARED_TOKEN`, `ZEKA_PG_DSN` ve | |
| 294 | -`LLM_API_KEY` `:?` ile **zorunludur**; eski `DEEPSEEK_API_KEY` adı artık | |
| 295 | -**reddedilir** (temiz kesim): adressiz ya da anahtarsız bir servis | |
| 296 | -ayağa kalkıp hiçbir şey yazmadan "çalışıyor" görünürdü. Açılışta bir satır hata, | |
| 297 | -günler sonra boş bir tablo yerine. | |
| 367 | +interpolasyon içerir, literal sır taşımaz. `AI_SHARED_TOKEN` ve `LLM_API_KEY` | |
| 368 | +`:?` ile **zorunludur**; eski `DEEPSEEK_API_KEY` adı artık **reddedilir** (temiz | |
| 369 | +kesim): anahtarsız bir servis ayağa kalkıp hiçbir şey yazmadan "çalışıyor" | |
| 370 | +görünürdü. Açılışta bir satır hata, günler sonra boş bir tablo yerine. | |
| 298 | 371 | |
| 299 | -DSN hiçbir yerde loglanmaz; `pg_client._describe()` yalnız host/port/veritabanı | |
| 300 | -döndürür, kullanıcı adı ve parola asla. | |
| 372 | +Paylaşılan sır hiçbir yerde loglanmaz. Servisin koruyacak bir veritabanı | |
| 373 | +parolası yoktur — öyle bir parola artık hiçbir yerde geçmez. | |
| 301 | 374 | |
| 302 | 375 | --- |
| 303 | 376 | |
| @@ -337,7 +410,7 @@ request'ler** beş katmanı `ci.yml`'den alır (aynı kapı iki kez koşmaz). | ||
| 337 | 410 | ```bash |
| 338 | 411 | mkdir -p ~/hezarfen_zeka |
| 339 | 412 | cp deploy/hezarfen_zeka.env.example ~/hezarfen_zeka/hezarfen_zeka.env |
| 340 | - # AI_SHARED_TOKEN / ZEKA_PG_DSN / LLM_API_KEY zorunlu | |
| 413 | + # AI_SHARED_TOKEN / LLM_API_KEY zorunlu | |
| 341 | 414 | chmod 0600 ~/hezarfen_zeka/hezarfen_zeka.env |
| 342 | 415 | ``` |
| 343 | 416 | |
| @@ -348,6 +421,10 @@ request'ler** beş katmanı `ci.yml`'den alır (aynı kapı iki kez koşmaz). | ||
| 348 | 421 | yalnız **uyarı** olarak bildirir — kayıt şartı aransaydı ZEKA'nın kendi |
| 349 | 422 | tanımından daha sıkı bir kapı uydurmuş olurduk. |
| 350 | 423 | |
| 424 | + Kapı olmayan şey **davranıştır** da: `insight.*` çağrıları kapılar | |
| 425 | + tanımlanana kadar reddedilir (§5 madde 1); servis ölür değil, koşusunu | |
| 426 | + `partial` yazar ve devam eder. | |
| 427 | + | |
| 351 | 428 | ### Kapı, rollback ve kapsam |
| 352 | 429 | |
| 353 | 430 | - **Sağlık kapısı = `scripts/saglik.py`**, konteynerde. Ölçtüğü şey köprü |
deploy/hezarfen_zeka.env.examplemodified+43 -28
| @@ -7,18 +7,27 @@ | ||
| 7 | 7 | # chmod 0600 ~/hezarfen_zeka/hezarfen_zeka.env |
| 8 | 8 | # |
| 9 | 9 | # Hicbir otomasyon bu dosyayi OLUSTURMAZ, EZMEZ, YUKLEMEZ -- operatorun malidir; |
| 10 | -# deploy yalnizca varligini kontrol eder ve iznini 0600'e ceker, compose yalniz | |
| 11 | -# okur (`--env-file`). Satirlar duz KEY=value: tirnak yok, `export` yok, satir | |
| 12 | -# sonu yorumu yok. Yerel gelistirme icin esdegeri `service/.env.example`'dir. | |
| 10 | +# deploy yalnizca varligini kontrol eder ve iznini 0600'e ceker. Satirlar duz | |
| 11 | +# KEY=value: tirnak yok, `export` yok, satir sonu yorumu yok. Yerel gelistirme | |
| 12 | +# icin esdegeri `service/.env.example`'dir. | |
| 13 | +# | |
| 14 | +# KONTEYNERE NASIL ULASIR -- tek kanal, iki tasiyici: | |
| 15 | +# * systemd: unit'in `EnvironmentFile=%h/hezarfen_zeka/hezarfen_zeka.env` | |
| 16 | +# satiri bu dosyayi unit'in ORTAMINA alir; konteyner ortami oradan miras | |
| 17 | +# alir. | |
| 18 | +# * deploy: ayni dosyayi satir satir okuyup surece alir (kabuk genisletmesi | |
| 19 | +# YOK: deger icindeki `$` oldugu gibi kalir). | |
| 20 | +# compose'a giden `--env-file` TEKTIR ve o dosya deploy sahipli `stack.env` | |
| 21 | +# olup yalniz `HEZARFEN_TAG` tasir. podman-compose 1.6.0 `--env-file` | |
| 22 | +# argumaninin yalniz SON degerini cozer (podman_compose.py:2941-2946, | |
| 23 | +# :2559); iki dosyali cagri bu dosyayi tamamen dusurur. | |
| 13 | 24 | # |
| 14 | 25 | # Degerler konteyner BASLARKEN okunur: degisiklikten sonra yeniden olustur |
| 15 | -# podman compose --env-file hezarfen_zeka.env --env-file stack.env up -d | |
| 16 | -# ya da | |
| 17 | 26 | # systemctl --user restart hezarfen_zeka_compose |
| 18 | 27 | # |
| 19 | -# Uc sir ZORUNLUDUR (`${VAR:?}`): bos birakilirsa `compose up` DAHA BASLAMADAN | |
| 20 | -# durur -- adressiz/anahtarsiz bir kopru ayaga kalkip hicbir sey yazmadan | |
| 21 | -# "calisiyor" gorunurdu ve hata gunler sonra bos bir tablo olarak cikardi. | |
| 28 | +# Iki sir ZORUNLUDUR (`${VAR:?}`): bos birakilirsa `compose up` DAHA BASLAMADAN | |
| 29 | +# durur -- anahtarsiz bir kopru ayaga kalkip "calisiyor" gorunurdu ve hata | |
| 30 | +# gunler sonra ortaya cikardi. | |
| 22 | 31 | |
| 23 | 32 | # ============================================================================ |
| 24 | 33 | # ZORUNLU |
| @@ -30,18 +39,6 @@ | ||
| 30 | 39 | # kopru bekler). |
| 31 | 40 | AI_SHARED_TOKEN= |
| 32 | 41 | |
| 33 | -# KONTROL veritabani. Okul ciktilari BURAYA yazilmaz: her okul KENDI | |
| 34 | -# veritabanina yazar ve adi okulun uuid'sinden turer (backend `tenant.rs:112`): | |
| 35 | -# {kontrol_db}_school_{uuid_tiresiz} | |
| 36 | -# Okul slug'i -> veritabani cozumlemesi kontrol satirindan yapilir | |
| 37 | -# (`school` tablosu); DSN'e sabit bir okul yazmak tek-okullu kuruluma donmek | |
| 38 | -# olurdu (bkz. src/tenants.py). | |
| 39 | -# | |
| 40 | -# Bu degiskenin dolu olmasi Postgres'i secer; bos olmasi eski tek veritabani | |
| 41 | -# (SurrealDB) moduna duser (bkz. src/store_factory.py). | |
| 42 | -ZEKA_PG_DSN= | |
| 43 | -# Parola tasir: dosya 0600, DSN hicbir yere loglanmaz. | |
| 44 | - | |
| 45 | 42 | # Segment hattinin LLM anahtari. Kopru bu anahtari OKUMAZ; yalnizca |
| 46 | 43 | # `src/segment/` okur. Yine de zorunlu tutuluyor: anahtarsiz bir servis ayaga |
| 47 | 44 | # kalkar, segment hatti kosuldugunda patlardi. Hatayi dagitim anina cekiyoruz. |
| @@ -57,10 +54,16 @@ ZEKA_PG_DSN= | ||
| 57 | 54 | # |
| 58 | 55 | # SAGLAYICI: DeepSeek varsayilandir, ZORUNLULUK DEGILDIR. OpenAI uyumlu her |
| 59 | 56 | # ag gecidi calisir: LLM_BASE_URL'i gecidinize verin ve model kimliklerini |
| 60 | -# LLM_MODEL_* ile o saglayicinin adlariyla degistirin. | |
| 57 | +# LLM_MODEL_* ile o saglayicinin adlariyla degistirin. Bos birakmak | |
| 58 | +# "varsayilani kullan" demektir. | |
| 61 | 59 | LLM_API_KEY= |
| 62 | 60 | # (Yalnizca kopruyu kosturan bir dagitimda bilincli olarak sahte bir deger |
| 63 | 61 | # verilebilir; segment o zaman hata verir, kopru calisir.) |
| 62 | +LLM_BASE_URL= | |
| 63 | +LLM_MODEL_FLASH= | |
| 64 | +LLM_MODEL_PRO= | |
| 65 | +LLM_MODEL_REASONER= | |
| 66 | +LLM_MODEL_ROLE= | |
| 64 | 67 | |
| 65 | 68 | # ============================================================================ |
| 66 | 69 | # KOPRU |
| @@ -94,15 +97,28 @@ AI_RECONNECT_MAX_SECS=120 | ||
| 94 | 97 | # KAPSAM |
| 95 | 98 | # ============================================================================ |
| 96 | 99 | # |
| 97 | -# Backend'de okul ve kullanici LISTELEME yolu yok (izin listesi | |
| 98 | -# `constant.rs:641-661`), bu yuzden kapsam BURADAN verilir -- donem ortasi | |
| 99 | -# kayit olan ogrenci gorunmez, ayrilan silinmez. | |
| 100 | +# Okul KUTUGU backend'dedir: hangi okullarin var oldugu `insight.schools.list` | |
| 101 | +# yetenek cagrisiyla backend'den okunur. ZEKA_SCHOOLS yalnizca bir FILTREdir; | |
| 102 | +# BOS BIRAKILIRSA butun aktif okullar islenir -- donem ortasi kayit olan | |
| 103 | +# ogrenci gorunmez, ayrilan silinmez. Ornek filtre: hezarfen-demo | |
| 104 | +ZEKA_SCHOOLS= | |
| 105 | + | |
| 106 | +# Ogrenci listesi hala BURADAN verilir: backend'de kullanici LISTELEME yolu | |
| 107 | +# yok (izin listesi `constant.rs:641-661`). | |
| 100 | 108 | # Bkz. service/docs/BACKEND-GEREKSINIMLERI.md madde 3. |
| 101 | -ZEKA_SCHOOLS=hezarfen-demo | |
| 102 | 109 | ZEKA_STUDENT_SOURCE=config |
| 103 | 110 | ZEKA_STUDENTS= |
| 104 | 111 | ZEKA_STUDENT_FILE= |
| 105 | 112 | |
| 113 | +# ============================================================================ | |
| 114 | +# VERI CEPHESI | |
| 115 | +# ============================================================================ | |
| 116 | +# bridge = veri backend'den `insight.*` cagrilariyla gelir (uretim yolu). | |
| 117 | +# Fixture koku compose'da sabittir (/data/zeka/fixtures), buradan verilmez. | |
| 118 | +ZEKA_SOURCE=bridge | |
| 119 | +ZEKA_API_TIMEOUT_SECS=15 | |
| 120 | +ZEKA_BLOB_TIMEOUT_SECS=60 | |
| 121 | + | |
| 106 | 122 | # ============================================================================ |
| 107 | 123 | # ZAMANLAMA |
| 108 | 124 | # ============================================================================ |
| @@ -124,9 +140,8 @@ LOG_LEVEL=info | ||
| 124 | 140 | # SURUM ETIKETI |
| 125 | 141 | # ============================================================================ |
| 126 | 142 | # BURADAN OKUNMAZ: HEZARFEN_TAG yalnizca compose interpolasyonudur ve deploy'un |
| 127 | -# sahip oldugu stack.env icinde tasinir (ikinci `--env-file`, cakisan anahtarda | |
| 128 | -# o kazanir). Elle kostururken varsayilan `current`'tir; imaj sunucuda VAR | |
| 129 | -# olmali: | |
| 143 | +# sahip oldugu stack.env icinde tasinir. Elle kostururken varsayilan | |
| 144 | +# `current`'tir; imaj sunucuda VAR olmali: | |
| 130 | 145 | # podman compose up -d --build # burada derle |
| 131 | 146 | # podman load -i hezarfen_zeka.tar.gz |
| 132 | 147 | #HEZARFEN_TAG=current |
deploy/hezarfen_zeka_compose.servicemodified+4 -3
| @@ -23,8 +23,9 @@ | ||
| 23 | 23 | # OKUMAZ. `--env-file` tek degerli bir argumandir (podman_compose.py:2941-2946) |
| 24 | 24 | # ve yalniz SON dosya cozulur (:2559 `dotenv_path = os.path.realpath(args.env_file)`). |
| 25 | 25 | # Iki dosyali eski cagri operator dosyasini tamamen dusuruyordu; compose.yaml'da |
| 26 | -# uc sir `${VAR:?}` oldugu icin `up` DAHA BASLAMADAN "required variable ... is | |
| 27 | -# missing a value" ile reddediliyordu (canlida yasandi, 2026-09-17). Docker | |
| 26 | +# zorunlu sirlar (`${VAR:?}`) oldugu icin `up` DAHA BASLAMADAN "required | |
| 27 | +# variable ... is missing a value" ile reddediliyordu (canlida yasandi, | |
| 28 | +# 2026-09-17). Docker | |
| 28 | 29 | # Compose v2'nin "sonraki dosya cakisan anahtarda kazanir" davranisi bu |
| 29 | 30 | # saglayici icin GECERLI DEGIL. Ortam degiskeni --env-file degerlerini EZER |
| 30 | 31 | # (:2562), yani iki kanal cakismaz: operator sirlari ortamdan, HEZARFEN_TAG |
| @@ -38,7 +39,7 @@ | ||
| 38 | 39 | # systemctl --user restart hezarfen_zeka_compose |
| 39 | 40 | |
| 40 | 41 | [Unit] |
| 41 | -Description=Hezarfen ZEKA bridge (student analysis + recommendations over the school database) | |
| 42 | +Description=Hezarfen ZEKA bridge (student analysis + recommendations; no database -- all rows go over the QUIC bridge as insight.* calls) | |
| 42 | 43 | After=network-online.target |
| 43 | 44 | Wants=network-online.target |
| 44 | 45 |
generator/README.mdmodified+26 -55
| @@ -1,7 +1,7 @@ | ||
| 1 | 1 | # Hezarfen Tohum Verisi Üreticisi |
| 2 | 2 | |
| 3 | -250 öğrencilik, gerçekçi ve **belirlenimci** bir K‑12 okulu üretir; çıktı doğrudan | |
| 4 | -SurrealDB'ye yüklenebilen `.surql` dosyalarıdır. | |
| 3 | +250 öğrencilik, gerçekçi ve **belirlenimci** bir K‑12 okulu üretir; çıktı, demo | |
| 4 | +okulunun **veri setidir** — yüklemesi backend ekibinin işidir (`paket/OKU.md`). | |
| 5 | 5 | |
| 6 | 6 | Girdi belgeleri: `../spec/schema.json` (otorite), `../spec/SENARYO.md` (senaryo), |
| 7 | 7 | `../spec/PAROLA.md` (argon2 parametreleri). |
| @@ -52,55 +52,25 @@ Tipik süre (full): **~50 saniye**, ~170 MB çıktı. | ||
| 52 | 52 | |
| 53 | 53 | | Dosya | İçerik | |
| 54 | 54 | |---|---| |
| 55 | -| `00_control.surql` | **CONTROL** veritabanına okul satırı (`school:ataturk-anadolu`), 21 modülün tamamı açık. `UPSERT` kullanır; okul builder ile zaten oluşturulmuşsa satırı günceller. | | |
| 56 | -| `01_temel.surql` … `12_teslimler.surql` | **OKUL** veritabanı. Numaralar `schema.json → load_order` topolojik sırasını izler; `exam_answer` kendi dosyasındadır (en büyüğü). | | |
| 57 | -| `99_dogrula.surql` | SENARYO §7.6'daki **48 bütünlük sorgusu**. Her sorgu **0 döndürmelidir**; `GROUP ALL` kullanıldığı için ihlal yoksa sonuç boş gelir. | | |
| 55 | +| `00_kontrol.<uzantı>` | **CONTROL** tarafı: okul satırı (`hezarfen-demo`), 21 modülün tamamı açık. Yazımı idempotenttir; okul zaten oluşturulmuşsa satırı günceller. | | |
| 56 | +| `01_…` … `12_…` | **OKUL** verisi. Numaralar `schema.json → load_order` topolojik sırasını izler; `exam_answer` kendi dosyasındadır (en büyüğü). | | |
| 57 | +| `99_…` | SENARYO §7.6'daki **48 bütünlük sorgusu**. Her sorgu **0 döndürmelidir**. | | |
| 58 | 58 | | `MANIFEST.json` | Tablo başına satır sayısı, dosya boyutları, tohum, ölçek, üretim zamanı, `T_NOW` ve senaryo §7'deki beklenen değerlerin gerçekleşen karşılıkları + sapma gerekçeleri. | |
| 59 | -| `_seed_manifest.json` | **Gizli gerçek** (SENARYO §7.8): madde parametreleri (`a`, `b`, `c`, çeldirici), **bilişsel boyut etiketleri** (`dims`) ve **tuzak şık kimliği** (`trap_choice`), öğrenci arketipleri ve **boyut sapmaları** (`dim_delta`), kenar durum bayrakları, değiştirilen cevap anahtarları, silinen banka şablonları. DB'ye **yazılmaz**; doğrulama ve tavsiye sistemi değerlendirmesi bu dosyayla yapılır. | | |
| 59 | +| `_seed_manifest.json` | **Gizli gerçek** (SENARYO §7.8): madde parametreleri (`a`, `b`, `c`, çeldirici), **bilişsel boyut etiketleri** (`dims`) ve **tuzak şık kimliği** (`trap_choice`), öğrenci arketipleri ve **boyut sapmaları** (`dim_delta`), kenar durum bayrakları, değiştirilen cevap anahtarları, silinen banka şablonları. Veritabanına **yazılmaz**; doğrulama ve tavsiye sistemi değerlendirmesi bu dosyayla yapılır. | | |
| 60 | 60 | |
| 61 | -Her `.surql` dosyasının başında hangi tabloları içerdiği, kaç satır olduğu ve hangi | |
| 61 | +Her veri dosyasının başında hangi tabloları içerdiği, kaç satır olduğu ve hangi | |
| 62 | 62 | dosyadan sonra yüklenmesi gerektiği yorum bloğu olarak yazılıdır. |
| 63 | 63 | |
| 64 | -## 4. Yükleme adımları | |
| 65 | - | |
| 66 | -1. **Önce backend okulu oluşturur ve göç ettirir.** Tohum yalnız veri ekler; hiçbir | |
| 67 | - `DEFINE TABLE` / `DEFINE FIELD` içermez. Okul veritabanı (`DB <slug>`) ve 60 tablonun | |
| 68 | - şeması backend'in `migrate()` çağrısıyla kurulmuş olmalıdır. Builder arayüzünden | |
| 69 | - `ataturk-anadolu` slug'ıyla okulu oluşturun (ya da mevcut okulu kullanın). | |
| 70 | -2. **Control veritabanı:** | |
| 71 | - ```bash | |
| 72 | - surreal sql --endpoint http://127.0.0.1:8000 --username root --password root \ | |
| 73 | - --namespace hezarfen --database control < seed/00_control.surql | |
| 74 | - ``` | |
| 75 | -3. **Okul veritabanı — numara sırasıyla:** | |
| 76 | - ```bash | |
| 77 | - for f in seed/0[1-9]_*.surql seed/1[0-2]_*.surql; do | |
| 78 | - echo ">> $f" | |
| 79 | - surreal sql --endpoint http://127.0.0.1:8000 --username root --password root \ | |
| 80 | - --namespace hezarfen --database ataturk-anadolu < "$f" | |
| 81 | - done | |
| 82 | - ``` | |
| 83 | - (Namespace ve veritabanı adları kurulumunuza göre değişir; `slug` aynı zamanda | |
| 84 | - veritabanı adıdır.) | |
| 85 | -4. **Doğrulama:** | |
| 86 | - ```bash | |
| 87 | - surreal sql ... --database ataturk-anadolu < seed/99_dogrula.surql | |
| 88 | - ``` | |
| 89 | - Tüm sorgular `0` dönmelidir (`GROUP ALL` kullananlar `[[{ count: 0 }]]`, | |
| 90 | - gruplanmış olanlar boş sonuç). Dosyadaki her sorgu **tek satırdır**: | |
| 91 | - `surreal sql` istemcisi girdiyi satır satır ayrıştırdığı için çok satırlı bir | |
| 92 | - ifade ikinci satırda sözdizimi hatası verir. Dosyanın başındaki yorum bloğu | |
| 93 | - kullanılan tüm SurrealQL fonksiyonlarını ve 3.1.6'da **bulunmayanları** | |
| 94 | - (`array::contains`, `HAVING`, `meta::version`) listeler. | |
| 95 | -5. **Giriş denemesi:** herhangi bir öğrenci kullanıcı adı (`MANIFEST`/çıktıdaki | |
| 96 | - `username` alanı) + parola `Hezarfen2026!`. | |
| 97 | - | |
| 98 | -**Önemli:** Şema işi (DDL) ile veri yazımı (DML) **aynı sorgu paketinde olmamalıdır** | |
| 99 | -(bir paketteki ifadeler şemayı paket başındaki haliyle görür). Bu yüzden tohum, | |
| 100 | -`migrate()` tamamen bittikten **sonra**, ayrı bir sorgu olarak çalıştırılır. | |
| 101 | - | |
| 102 | -**Toplu yükleme HTTP API üzerinden yapılmamalıdır:** varsayılan hız sınırı | |
| 103 | -(300 istek/dk/IP) 571.000 satırda 429 üretir. Doğrudan SurrealQL kullanın. | |
| 64 | +## 4. Teslim | |
| 65 | + | |
| 66 | +Üretici **veri setini üretir, yüklemez**. Yükleme adımları bu depoda değildir: | |
| 67 | +çıktı backend ekibine verilir; okulun şemasını uygulayan ve veriyi döken taraf | |
| 68 | +backend'dir (`paket/OKU.md`). | |
| 69 | + | |
| 70 | +Bu ayrım bilinçlidir: şema işi ile veri yazımı aynı pakette olmamalıdır — şema | |
| 71 | +tamamen kurulduktan **sonra** veri yazılır. Doğrulama da iki taraflıdır: | |
| 72 | +`selfcheck.py` üretilen dosyaları denetler (§6), 48 bütünlük sorgusu ise | |
| 73 | +yüklenmiş veriyi. | |
| 104 | 74 | |
| 105 | 75 | ## 5. Kod düzeni |
| 106 | 76 | |
| @@ -110,7 +80,7 @@ dosyadan sonra yüklenmesi gerektiği yorum bloğu olarak yazılıdır. | ||
| 110 | 80 | | `config.py` | Tüm sabitler: takvim, ölçek profilleri, arketip parametreleri, isim havuzları, dosya düzeni. **Sihirli sayı başka dosyada yoktur.** | |
| 111 | 81 | | `world.py` | Üretim bağlamı (`Ctx`) ve ölçek profilleri | |
| 112 | 82 | | `ids.py` | ULID üretimi, kompozit anahtarlar, `table:⟨key⟩` kaçışlaması | |
| 113 | -| `emit.py` | Akışlı SurrealQL yazıcı; her satırın her alanını `schema.json` ile doğrular | | |
| 83 | +| `emit.py` | Akışlı veri yazıcı; her satırın her alanını `schema.json` ile doğrular | | |
| 114 | 84 | | `timeline.py` | Yerel saat → unix‑ms, öğretim haftaları, gün numarası, tarih kaydırma | |
| 115 | 85 | | `dists.py` | Dağılımlar (normal, log‑normal, Beta, Poisson, ağırlıklı seçim) | |
| 116 | 86 | | `content_tr.py` | **Türkçe metin havuzları:** ders başına kavram listeleri, şık şablonları, soru kökü şablonları, öğrenci cevabı cümleleri ve §4.5'teki kavram yanılgısı tablosu (92 konu). Ayrıca **bilişsel boyut etiketlerinden metin üreten** katman (`make_labeled_question`, `make_labeled_stem`). Üretim kodunda gömülü metin yoktur. | |
| @@ -120,7 +90,7 @@ dosyadan sonra yüklenmesi gerektiği yorum bloğu olarak yazılıdır. | ||
| 120 | 90 | | `engagement.py` | Ödev, pomodoro, soru havuzu, sohbet, not, mesaj, tahta, rozet | |
| 121 | 91 | | `operations.py` | Randevu, etkinlik, yemek, ödeme, mesai | |
| 122 | 92 | | `counters.py` | Sayaç materyalizasyonu ve sayaç taşıyan satırların yazımı; control dosyası | |
| 123 | -| `verify_queries.py` | `99_dogrula.surql` üretimi | | |
| 93 | +| `verify_queries.py` | 48 bütünlük sorgusunun üretimi | | |
| 124 | 94 | | `selfcheck.py` | Üretilen çıktının bağımsız denetimi | |
| 125 | 95 | |
| 126 | 96 | ### Neden bu yapı |
| @@ -130,7 +100,7 @@ dosyadan sonra yüklenmesi gerektiği yorum bloğu olarak yazılıdır. | ||
| 130 | 100 | göre numaralı dosyalara birleştirilir. Böylece 217.000 satırlık `exam_answer` hiçbir |
| 131 | 101 | zaman bellekte tutulmaz, ama sayaç taşıyan satırlar (ör. `course.enrollment_count`) |
| 132 | 102 | her şey sayıldıktan sonra yazılabilir. |
| 133 | -* **Şema disiplini.** SCHEMAFULL tabloda tanımsız alan **sessizce silinir**; bu yüzden | |
| 103 | +* **Şema disiplini.** Şemada tanımsız bir alan **sessizce düşer**; bu yüzden | |
| 134 | 104 | `emit.validate_row()` her alanı yazmadan önce `schema.json` ile karşılaştırır ve |
| 135 | 105 | yazım hatasında üretimi durdurur. Dizi alanları daima açıkça yazılır (`DEFAULT []` |
| 136 | 106 | tam satır yazımında tetiklenmez). |
| @@ -138,8 +108,8 @@ dosyadan sonra yüklenmesi gerektiği yorum bloğu olarak yazılıdır. | ||
| 138 | 108 | yazılır; ULID rakamla başladığı için çıplak yazım ayrıştırılamaz. |
| 139 | 109 | * **Dize kaçışlaması tek yerde** (`emit.sq_string`). Ters bölülü tırnak kaçışı |
| 140 | 110 | (`\'`) **kullanılmaz**: Türkçe metinde kesme işareti çok sık geçer |
| 141 | - (Ali'nin, 2026'da, Atatürk'ün) ve bu dizinin SurrealQL tarafından kabul | |
| 142 | - edildiği çalıştırılarak doğrulanamadı. Risk varsayıma bırakılmak yerine | |
| 111 | + (Ali'nin, 2026'da, Atatürk'ün) ve bu dizinin okuyucu tarafından kabul | |
| 112 | + edildiği sınanarak doğrulanamadı. Risk varsayıma bırakılmak yerine | |
| 143 | 113 | ortadan kaldırıldı: |
| 144 | 114 | tek tırnak yoksa `'…'`, tek tırnak varsa `"…"` (Türkçe metinde çift tırnak |
| 145 | 115 | neredeyse hiç geçmez, kaçışa gerek kalmaz), ikisi de varsa çift tırnaklıda |
| @@ -180,9 +150,10 @@ Denetlenenler: | ||
| 180 | 150 | (kelime ortasından kesme yok). Ayrıca aynı sorunun iki şıkkının aynı metne |
| 181 | 151 | sahip olması hata sayılır. |
| 182 | 152 | * (k) **dize kaçışlaması ve sözdizimi** — çıktının hiçbir yerinde `\'` dizisi |
| 183 | - bulunmamalı (`BACKSLASH_QUOTE`), ve tüm `.surql` dosyaları (00 ve 99 dahil) | |
| 153 | + bulunmamalı (`BACKSLASH_QUOTE`), ve tüm veri dosyaları (00 ve 99 dahil) | |
| 184 | 154 | dize-farkında bir tarayıcıdan geçer: her dize satır sonunda kapanmış mı, |
| 185 | - `[ ]` / `{ }` dengeli mi, fazladan kapanış var mı. SurrealDB çalıştırmadan | |
| 155 | + `[ ]` / `{ }` dengeli mi, fazladan kapanış var mı. Bir veritabanı | |
| 156 | + çalıştırmadan | |
| 186 | 157 | elimizdeki tek sözdizimi güvencesi budur. |
| 187 | 158 | * (l) **konu-kavram uyumu** — sayısal derslerde soru kökünde geçen konu adı ile |
| 188 | 159 | kökte/şıklarda geçen kavram aynı `SUBJECT_CONCEPTS` havuzundan olmalı; ihlal |
| @@ -194,7 +165,7 @@ Denetlenenler: | ||
| 194 | 165 | kullanılması bilinçlidir (§4.8) ve madde istatistiğinin `n >= 30` kapısını |
| 195 | 166 | besler. |
| 196 | 167 | |
| 197 | -`99_dogrula.surql` ise aynı işi **veritabanı tarafında** 48 sorguyla yapar; ikisi | |
| 168 | +48 bütünlük sorgusu ise aynı işi **yüklenmiş veri tarafında** yapar; ikisi | |
| 198 | 169 | birbirinin yerine geçmez (biri dosyayı, öteki yüklenmiş veriyi denetler). |
| 199 | 170 | |
| 200 | 171 | ### Bilişsel boyut zincirleri (A / B / C) |
generator/_pg_columns.txtdeleted+0 -568
| @@ -1,568 +0,0 @@ | ||
| 1 | -answer_image|exam|uuid|t| | |
| 2 | -answer_image|question|uuid|t| | |
| 3 | -answer_image|app_user|uuid|t| | |
| 4 | -answer_image|file|text|t| | |
| 5 | -answer_image|content_type|text|t| | |
| 6 | -answer_image|size|bigint|t| | |
| 7 | -answer_image|seq|bigint|t|1 | |
| 8 | -app_user|id|uuid|t| | |
| 9 | -app_user|username|text|t| | |
| 10 | -app_user|person|uuid|f| | |
| 11 | -app_user|role|text|t|'student'::text | |
| 12 | -app_user|name|text|f| | |
| 13 | -app_user|surname|text|f| | |
| 14 | -app_user|email|text|f| | |
| 15 | -app_user|phone|text|f| | |
| 16 | -app_user|birth_date|text|f| | |
| 17 | -app_user|theme|text|f| | |
| 18 | -app_user|language|text|f| | |
| 19 | -app_user|palette_color|text|f| | |
| 20 | -app_user|display_name|text|f| | |
| 21 | -app_user|bio|text|f| | |
| 22 | -app_user|avatar_file|text|f| | |
| 23 | -app_user|avatar_content_type|text|f| | |
| 24 | -app_user|avatar_size|bigint|f| | |
| 25 | -app_user|chatbot_thread_count|bigint|t|0 | |
| 26 | -app_user|board_count|bigint|t|0 | |
| 27 | -app_user|homework_submitted_total|bigint|t|0 | |
| 28 | -app_user|homework_on_time_total|bigint|t|0 | |
| 29 | -app_user|exam_sat_total|bigint|t|0 | |
| 30 | -app_user|pomodoro_finished_total|bigint|t|0 | |
| 31 | -app_user|pomodoro_focus_ms_total|bigint|t|0 | |
| 32 | -app_user|marks_given_total|bigint|t|0 | |
| 33 | -app_user|lessons_held_total|bigint|t|0 | |
| 34 | -app_user|pool_approved_total|bigint|t|0 | |
| 35 | -app_user|pool_published_total|bigint|t|0 | |
| 36 | -app_user|lessons_attended_total|bigint|t|0 | |
| 37 | -app_user|high_mark_total|bigint|t|0 | |
| 38 | -app_user|study_streak_longest|bigint|t|0 | |
| 39 | -app_user|study_streak_current|bigint|t|0 | |
| 40 | -app_user|study_streak_last_day|bigint|f| | |
| 41 | -app_user|pomodoro_counted_today|bigint|t|0 | |
| 42 | -app_user|pomodoro_counted_day|bigint|f| | |
| 43 | -app_user|created_at|bigint|t| | |
| 44 | -appointment|id|uuid|t| | |
| 45 | -appointment|slot|uuid|f| | |
| 46 | -appointment|requester|uuid|t| | |
| 47 | -appointment|status|text|t|'pending'::text | |
| 48 | -appointment|reason|text|t| | |
| 49 | -appointment|proposed_starts_at|bigint|f| | |
| 50 | -appointment|proposed_ends_at|bigint|f| | |
| 51 | -appointment|proposed_by|uuid|f| | |
| 52 | -appointment|decided_by|uuid|f| | |
| 53 | -appointment|cancelled_by|uuid|f| | |
| 54 | -appointment|cancel_reason|text|f| | |
| 55 | -appointment|reject_reason|text|f| | |
| 56 | -appointment|created_at|bigint|t| | |
| 57 | -appointment_slot|id|uuid|t| | |
| 58 | -appointment_slot|teacher|uuid|t| | |
| 59 | -appointment_slot|starts_at|bigint|t| | |
| 60 | -appointment_slot|ends_at|bigint|t| | |
| 61 | -appointment_slot|occupied|bigint|t|0 | |
| 62 | -appointment_slot|note|text|f| | |
| 63 | -appointment_slot|series|text|f| | |
| 64 | -appointment_slot|created_at|bigint|t| | |
| 65 | -appointment_slot|span|int8range|f|int8range(starts_at, ends_at) | |
| 66 | -attendance|event|uuid|t| | |
| 67 | -attendance|app_user|uuid|t| | |
| 68 | -attendance|status|text|t| | |
| 69 | -attendance|marked_by|uuid|t| | |
| 70 | -attendance|marked_at|bigint|t| | |
| 71 | -badge_award|app_user|uuid|t| | |
| 72 | -badge_award|badge|text|t| | |
| 73 | -badge_award|earned_at|bigint|f| | |
| 74 | -bank_question|id|uuid|t| | |
| 75 | -bank_question|owner|uuid|t| | |
| 76 | -bank_question|subject|uuid|f| | |
| 77 | -bank_question|text|text|t| | |
| 78 | -bank_question|kind|text|t| | |
| 79 | -bank_question|points|bigint|t| | |
| 80 | -bank_question|choices|jsonb|f| | |
| 81 | -bank_question|correct|text|f| | |
| 82 | -bank_question|source_exam|uuid|f| | |
| 83 | -bank_question|visibility|text|t|'private'::text | |
| 84 | -bank_question|created_at|bigint|t| | |
| 85 | -bank_question_image|bank_question|uuid|t| | |
| 86 | -bank_question_image|slot|text|f| | |
| 87 | -bank_question_image|file|text|t| | |
| 88 | -bank_question_image|content_type|text|t| | |
| 89 | -bank_question_image|size|bigint|t| | |
| 90 | -blueprint_course|blueprint|uuid|t| | |
| 91 | -blueprint_course|course|uuid|t| | |
| 92 | -board|id|uuid|t| | |
| 93 | -board|creator|uuid|t| | |
| 94 | -board|title|text|t| | |
| 95 | -board|locked|boolean|t|false | |
| 96 | -board|locked_by|uuid|f| | |
| 97 | -board|locked_at|bigint|f| | |
| 98 | -board|epoch|bigint|t|0 | |
| 99 | -board|epoch_stroke_count|bigint|t|0 | |
| 100 | -board|total_stroke_count|bigint|t|0 | |
| 101 | -board|closed_at|bigint|f| | |
| 102 | -board|created_at|bigint|t| | |
| 103 | -board_participant|board|uuid|t| | |
| 104 | -board_participant|participant|uuid|t| | |
| 105 | -board_stroke|id|uuid|t| | |
| 106 | -board_stroke|board|uuid|t| | |
| 107 | -board_stroke|author|uuid|t| | |
| 108 | -board_stroke|kind|text|t| | |
| 109 | -board_stroke|payload|text|f| | |
| 110 | -board_stroke|count|bigint|f| | |
| 111 | -board_stroke|epoch|bigint|t| | |
| 112 | -board_stroke|created_at|bigint|t| | |
| 113 | -builder|id|uuid|t| | |
| 114 | -builder|username|text|t| | |
| 115 | -builder|password_hash|text|t| | |
| 116 | -builder|created_at|bigint|t| | |
| 117 | -builder_session|id|uuid|t| | |
| 118 | -builder_session|builder|uuid|t| | |
| 119 | -builder_session|token|text|t| | |
| 120 | -builder_session|created_at|bigint|t| | |
| 121 | -builder_session|expires_at|bigint|t| | |
| 122 | -chatbot_message|id|uuid|t| | |
| 123 | -chatbot_message|thread_id|uuid|t| | |
| 124 | -chatbot_message|user_id|uuid|t| | |
| 125 | -chatbot_message|role|text|t| | |
| 126 | -chatbot_message|content|text|t| | |
| 127 | -chatbot_message|status|text|t| | |
| 128 | -chatbot_message|truncated|boolean|t|false | |
| 129 | -chatbot_message|error_code|text|f| | |
| 130 | -chatbot_message|created_at|bigint|t| | |
| 131 | -chatbot_message|completed_at|bigint|f| | |
| 132 | -chatbot_thread|id|uuid|t| | |
| 133 | -chatbot_thread|user_id|uuid|t| | |
| 134 | -chatbot_thread|title|text|f| | |
| 135 | -chatbot_thread|created_at|bigint|t| | |
| 136 | -chatbot_thread|updated_at|bigint|t| | |
| 137 | -class_blueprint|id|uuid|t| | |
| 138 | -class_blueprint|grade|text|t| | |
| 139 | -class_blueprint|creator|uuid|t| | |
| 140 | -class_course|class|uuid|t| | |
| 141 | -class_course|course|uuid|t| | |
| 142 | -class_course|attached_by|uuid|t| | |
| 143 | -class_course|attached_at|bigint|f| | |
| 144 | -class_course|source|uuid|f| | |
| 145 | -class_group|id|uuid|t| | |
| 146 | -class_group|name|text|t| | |
| 147 | -class_group|grade|text|f| | |
| 148 | -class_group|term|uuid|f| | |
| 149 | -class_group|creator|uuid|t| | |
| 150 | -class_group|teacher|uuid|f| | |
| 151 | -class_group|class_member_count|bigint|t|0 | |
| 152 | -class_group|class_course_count|bigint|t|0 | |
| 153 | -class_member|class|uuid|t| | |
| 154 | -class_member|app_user|uuid|t| | |
| 155 | -class_member|added_by|uuid|t| | |
| 156 | -class_member|added_at|bigint|f| | |
| 157 | -course|id|uuid|t| | |
| 158 | -course|creator|uuid|t| | |
| 159 | -course|title|text|t| | |
| 160 | -course|description|text|t| | |
| 161 | -course|kind|text|t|'course'::text | |
| 162 | -course|term|uuid|f| | |
| 163 | -course|capacity|bigint|f| | |
| 164 | -course|enrollment_count|bigint|t|0 | |
| 165 | -course_note|id|uuid|t| | |
| 166 | -course_note|course|uuid|t| | |
| 167 | -course_note|author|uuid|t| | |
| 168 | -course_note|title|text|t| | |
| 169 | -course_note|content|text|t| | |
| 170 | -course_note|file_count|bigint|t|0 | |
| 171 | -course_note_file|id|uuid|t| | |
| 172 | -course_note_file|course_note|uuid|t| | |
| 173 | -course_note_file|name|text|t| | |
| 174 | -course_note_file|content_type|text|t| | |
| 175 | -course_note_file|size|bigint|t| | |
| 176 | -course_session|id|uuid|t| | |
| 177 | -course_session|course|uuid|t| | |
| 178 | -course_session|teacher|uuid|t| | |
| 179 | -course_session|topic|text|t| | |
| 180 | -course_session|starts_at|bigint|t| | |
| 181 | -course_session|ends_at|bigint|f| | |
| 182 | -course_session|held_counted_at|bigint|f| | |
| 183 | -course_teacher|course|uuid|t| | |
| 184 | -course_teacher|teacher|uuid|t| | |
| 185 | -dietary_profile|student|uuid|t| | |
| 186 | -dietary_profile|note|text|f| | |
| 187 | -dietary_profile|updated_by|uuid|t| | |
| 188 | -dietary_profile|updated_at|bigint|t| | |
| 189 | -dietary_profile_tag|student|uuid|t| | |
| 190 | -dietary_profile_tag|tag|text|t| | |
| 191 | -dietary_profile_tag|ord|smallint|t| | |
| 192 | -enrollment|course|uuid|t| | |
| 193 | -enrollment|app_user|uuid|t| | |
| 194 | -enrollment|enrolled_by|uuid|t| | |
| 195 | -enrollment|created_at|bigint|t| | |
| 196 | -enrollment|source|uuid|f| | |
| 197 | -event|id|uuid|t| | |
| 198 | -event|creator|uuid|t| | |
| 199 | -event|title|text|t| | |
| 200 | -event|description|text|t| | |
| 201 | -event|audience_kind|text|t| | |
| 202 | -event|audience_role|text|f| | |
| 203 | -event|audience_course|uuid|f| | |
| 204 | -event|audience_class|uuid|f| | |
| 205 | -event|audience_capacity|bigint|f| | |
| 206 | -event|registration_count|bigint|t|0 | |
| 207 | -event|starts_at|bigint|f| | |
| 208 | -event|ends_at|bigint|f| | |
| 209 | -exam|id|uuid|t| | |
| 210 | -exam|creator|uuid|t| | |
| 211 | -exam|course|uuid|t| | |
| 212 | -exam|title|text|t| | |
| 213 | -exam|description|text|t| | |
| 214 | -exam|kind|text|t| | |
| 215 | -exam|mode|text|f| | |
| 216 | -exam|starts_at|bigint|f| | |
| 217 | -exam|ends_at|bigint|f| | |
| 218 | -exam|duration_ms|bigint|f| | |
| 219 | -exam|max_attempts|bigint|t|1 | |
| 220 | -exam|allow_rejoin|boolean|t|true | |
| 221 | -exam|allow_review|boolean|t|false | |
| 222 | -exam|draft|boolean|t|false | |
| 223 | -exam|result_count|bigint|t|0 | |
| 224 | -exam_answer|exam|uuid|t| | |
| 225 | -exam_answer|question|uuid|t| | |
| 226 | -exam_answer|app_user|uuid|t| | |
| 227 | -exam_answer|selected|text|f| | |
| 228 | -exam_answer|text|text|f| | |
| 229 | -exam_answer|updated_at|bigint|t| | |
| 230 | -exam_answer|seq|bigint|t|1 | |
| 231 | -exam_attempt|exam|uuid|t| | |
| 232 | -exam_attempt|app_user|uuid|t| | |
| 233 | -exam_attempt|seq|bigint|t|1 | |
| 234 | -exam_attempt|started_at|bigint|t| | |
| 235 | -exam_attempt|finished_at|bigint|f| | |
| 236 | -exam_attempt|left_at|bigint|f| | |
| 237 | -exam_question|id|uuid|t| | |
| 238 | -exam_question|exam|uuid|t| | |
| 239 | -exam_question|text|text|t| | |
| 240 | -exam_question|kind|text|t| | |
| 241 | -exam_question|points|bigint|t| | |
| 242 | -exam_question|choices|jsonb|f| | |
| 243 | -exam_question|correct|text|f| | |
| 244 | -exam_question|subject|uuid|t| | |
| 245 | -exam_question|from_bank|uuid|f| | |
| 246 | -exam_question|banked_as|uuid|f| | |
| 247 | -exam_result|exam|uuid|t| | |
| 248 | -exam_result|app_user|uuid|t| | |
| 249 | -exam_result|mark|bigint|t| | |
| 250 | -exam_result|graded_by|uuid|t| | |
| 251 | -exam_result|graded_at|bigint|t| | |
| 252 | -exam_result|seq|bigint|t|1 | |
| 253 | -fee_plan|id|uuid|t| | |
| 254 | -fee_plan|name|text|t| | |
| 255 | -fee_plan|installments|jsonb|t| | |
| 256 | -fee_plan|created_by|uuid|t| | |
| 257 | -fee_plan|created_at|bigint|t| | |
| 258 | -fee_plan|assignment_count|bigint|t|0 | |
| 259 | -fee_plan_assignment|plan|uuid|t| | |
| 260 | -fee_plan_assignment|student|uuid|t| | |
| 261 | -fee_plan_assignment|assigned_by|uuid|t| | |
| 262 | -fee_plan_assignment|created_at|bigint|t| | |
| 263 | -homework|id|uuid|t| | |
| 264 | -homework|course|uuid|t| | |
| 265 | -homework|subject|uuid|t| | |
| 266 | -homework|title|text|t| | |
| 267 | -homework|description|text|f| | |
| 268 | -homework|due_at|bigint|t| | |
| 269 | -homework|created_by|uuid|t| | |
| 270 | -homework|created_at|bigint|t| | |
| 271 | -homework_assignment|homework|uuid|t| | |
| 272 | -homework_assignment|student|uuid|t| | |
| 273 | -homework_file|id|uuid|t| | |
| 274 | -homework_file|submission|uuid|t| | |
| 275 | -homework_file|name|text|t| | |
| 276 | -homework_file|content_type|text|t| | |
| 277 | -homework_file|size|bigint|t| | |
| 278 | -homework_file|file|text|t| | |
| 279 | -homework_file|created_at|bigint|t| | |
| 280 | -homework_result|id|uuid|t| | |
| 281 | -homework_result|homework|uuid|t| | |
| 282 | -homework_result|app_user|uuid|t| | |
| 283 | -homework_result|status|text|t| | |
| 284 | -homework_result|mark|bigint|f| | |
| 285 | -homework_result|graded_by|uuid|t| | |
| 286 | -homework_result|created_at|bigint|t| | |
| 287 | -homework_submission|id|uuid|t| | |
| 288 | -homework_submission|homework|uuid|t| | |
| 289 | -homework_submission|app_user|uuid|t| | |
| 290 | -homework_submission|text|text|f| | |
| 291 | -homework_submission|submitted_at|bigint|t| | |
| 292 | -homework_submission|updated_at|bigint|t| | |
| 293 | -homework_submission|file_count|bigint|t|0 | |
| 294 | -homework_submission|counted_on_time|boolean|f| | |
| 295 | -homework_submission|graded_by_result|uuid|f| | |
| 296 | -kind_ref|name|text|t| | |
| 297 | -kind_ref|count|bigint|t|0 | |
| 298 | -kind_ref|retired|boolean|t|false | |
| 299 | -meal_attendance|menu|text|t| | |
| 300 | -meal_attendance|student|uuid|t| | |
| 301 | -meal_attendance|status|text|t| | |
| 302 | -meal_attendance|marked_by|uuid|t| | |
| 303 | -meal_attendance|marked_at|bigint|t| | |
| 304 | -meal_booking|menu|text|t| | |
| 305 | -meal_booking|student|uuid|t| | |
| 306 | -meal_booking|booked_by|uuid|t| | |
| 307 | -meal_booking|status|text|t|'booked'::text | |
| 308 | -meal_booking|attempt|bigint|t|1 | |
| 309 | -meal_booking|price_minor|bigint|f| | |
| 310 | -meal_booking|cancelled_at|bigint|f| | |
| 311 | -meal_booking|created_at|bigint|t| | |
| 312 | -meal_ledger|id|text|t| | |
| 313 | -meal_ledger|student|uuid|t| | |
| 314 | -meal_ledger|kind|text|t| | |
| 315 | -meal_ledger|amount_minor|bigint|t| | |
| 316 | -meal_ledger|source|text|f| | |
| 317 | -meal_ledger|method|text|f| | |
| 318 | -meal_ledger|note|text|f| | |
| 319 | -meal_ledger|recorded_by|uuid|t| | |
| 320 | -meal_ledger|created_at|bigint|t| | |
| 321 | -menu|id|text|t| | |
| 322 | -menu|date|text|t| | |
| 323 | -menu|slot|text|t| | |
| 324 | -menu|capacity|bigint|f| | |
| 325 | -menu|seats_booked|bigint|t|0 | |
| 326 | -menu|version|bigint|f| | |
| 327 | -menu|created_by|uuid|t| | |
| 328 | -menu|created_at|bigint|t| | |
| 329 | -menu_dish|id|uuid|t| | |
| 330 | -menu_dish|menu|text|t| | |
| 331 | -menu_dish|name|text|t| | |
| 332 | -menu_dish|description|text|f| | |
| 333 | -menu_dish|price_minor|bigint|t| | |
| 334 | -menu_dish|created_at|bigint|t| | |
| 335 | -menu_dish_tag|dish|uuid|t| | |
| 336 | -menu_dish_tag|tag|text|t| | |
| 337 | -menu_dish_tag|ord|smallint|t| | |
| 338 | -message|id|uuid|t| | |
| 339 | -message|sender|uuid|t| | |
| 340 | -message|recipient|uuid|t| | |
| 341 | -message|subject|text|t| | |
| 342 | -message|body|text|t| | |
| 343 | -message|label|text|f| | |
| 344 | -message|sent_at|bigint|t| | |
| 345 | -message|read|boolean|t|false | |
| 346 | -message|sender_folder|text|t|'sent'::text | |
| 347 | -message|recipient_folder|text|t|'inbox'::text | |
| 348 | -message|sender_origin|text|f| | |
| 349 | -message|recipient_origin|text|f| | |
| 350 | -note|id|uuid|t| | |
| 351 | -note|app_user|uuid|t| | |
| 352 | -note|title|text|t| | |
| 353 | -note|content|text|t| | |
| 354 | -note|file_count|bigint|t|0 | |
| 355 | -note_file|id|uuid|t| | |
| 356 | -note_file|note|uuid|t| | |
| 357 | -note_file|name|text|t| | |
| 358 | -note_file|content_type|text|t| | |
| 359 | -note_file|size|bigint|t| | |
| 360 | -parent_link|parent|uuid|t| | |
| 361 | -parent_link|student|uuid|t| | |
| 362 | -parent_link|linked_by|uuid|t| | |
| 363 | -payment_ledger|id|text|t| | |
| 364 | -payment_ledger|student|uuid|t| | |
| 365 | -payment_ledger|kind|text|t| | |
| 366 | -payment_ledger|amount_minor|bigint|t| | |
| 367 | -payment_ledger|source|text|f| | |
| 368 | -payment_ledger|due_at|bigint|f| | |
| 369 | -payment_ledger|method|text|f| | |
| 370 | -payment_ledger|note|text|f| | |
| 371 | -payment_ledger|recorded_by|uuid|t| | |
| 372 | -payment_ledger|created_at|bigint|t| | |
| 373 | -person|id|uuid|t| | |
| 374 | -person|username|text|t| | |
| 375 | -person|password_hash|text|t| | |
| 376 | -person|created_at|bigint|t| | |
| 377 | -person_school|person|uuid|t| | |
| 378 | -person_school|school|uuid|t| | |
| 379 | -person_school|created_at|bigint|t| | |
| 380 | -person_session|id|uuid|t| | |
| 381 | -person_session|person|uuid|t| | |
| 382 | -person_session|token|text|t| | |
| 383 | -person_session|created_at|bigint|t| | |
| 384 | -person_session|expires_at|bigint|t| | |
| 385 | -pomodoro_session|id|uuid|t| | |
| 386 | -pomodoro_session|app_user|uuid|t| | |
| 387 | -pomodoro_session|started_at|bigint|t| | |
| 388 | -pomodoro_session|finished_at|bigint|f| | |
| 389 | -pomodoro_session|counted|boolean|f| | |
| 390 | -pomodoro_session|label|text|f| | |
| 391 | -pool_question|id|uuid|t| | |
| 392 | -pool_question|asker|uuid|t| | |
| 393 | -pool_question|title|text|t| | |
| 394 | -pool_question|body|text|t| | |
| 395 | -pool_question|status|text|t|'pending'::text | |
| 396 | -pool_question|asked_at|bigint|t| | |
| 397 | -pool_question|approved_by|uuid|f| | |
| 398 | -pool_question_image|question|uuid|t| | |
| 399 | -pool_question_image|file|text|t| | |
| 400 | -pool_question_image|content_type|text|t| | |
| 401 | -pool_question_image|size|bigint|t| | |
| 402 | -question_image|exam|uuid|t| | |
| 403 | -question_image|question|uuid|t| | |
| 404 | -question_image|slot|text|f| | |
| 405 | -question_image|file|text|t| | |
| 406 | -question_image|content_type|text|t| | |
| 407 | -question_image|size|bigint|t| | |
| 408 | -rag_output|id|uuid|t| | |
| 409 | -rag_output|course_note|uuid|t| | |
| 410 | -rag_output|course|uuid|t| | |
| 411 | -rag_output|payload|jsonb|t| | |
| 412 | -rag_output|generated_at|bigint|t| | |
| 413 | -rag_output_source|output|uuid|t| | |
| 414 | -rag_output_source|source|uuid|t| | |
| 415 | -rate_limit|id|text|t| | |
| 416 | -rate_limit|hits|bigint|t|0 | |
| 417 | -rate_limit|window_start|bigint|t| | |
| 418 | -registration|event|uuid|t| | |
| 419 | -registration|app_user|uuid|t| | |
| 420 | -registration|registered_by|uuid|t| | |
| 421 | -registration|created_at|bigint|t| | |
| 422 | -school|id|uuid|t| | |
| 423 | -school|slug|text|t| | |
| 424 | -school|name|text|t| | |
| 425 | -school|status|text|t| | |
| 426 | -school|created_at|bigint|t| | |
| 427 | -school_module|school|uuid|t| | |
| 428 | -school_module|module|text|t| | |
| 429 | -session_attendance|session|uuid|t| | |
| 430 | -session_attendance|app_user|uuid|t| | |
| 431 | -session_attendance|course|uuid|t| | |
| 432 | -session_attendance|status|text|t| | |
| 433 | -session_attendance|marked_by|uuid|t| | |
| 434 | -session_attendance|marked_at|bigint|t| | |
| 435 | -settings|id|text|t| | |
| 436 | -settings|exam_kinds|jsonb|t| | |
| 437 | -settings|grade_bands|jsonb|t| | |
| 438 | -settings|max_file_bytes|bigint|f| | |
| 439 | -settings|chatbot_history_turns|bigint|f| | |
| 440 | -settings|max_chatbot_message_len|bigint|f| | |
| 441 | -settings|max_chatbot_threads|bigint|f| | |
| 442 | -settings|meal_slots|jsonb|f| | |
| 443 | -settings|meal_cancel_cutoff_minutes|bigint|f| | |
| 444 | -settings_attendance_status|settings|text|t| | |
| 445 | -settings_attendance_status|status|text|t| | |
| 446 | -settings_dietary_tag|settings|text|t| | |
| 447 | -settings_dietary_tag|tag|text|t| | |
| 448 | -slot_ref|name|text|t| | |
| 449 | -slot_ref|count|bigint|t|0 | |
| 450 | -slot_ref|retired|boolean|t|false | |
| 451 | -solution|id|uuid|t| | |
| 452 | -solution|question|uuid|t| | |
| 453 | -solution|author|uuid|t| | |
| 454 | -solution|body|text|t| | |
| 455 | -solution|offered_at|bigint|t| | |
| 456 | -solution_image|solution|uuid|t| | |
| 457 | -solution_image|file|text|t| | |
| 458 | -solution_image|content_type|text|t| | |
| 459 | -solution_image|size|bigint|t| | |
| 460 | -subject|id|uuid|t| | |
| 461 | -subject|course|uuid|t| | |
| 462 | -subject|name|text|t| | |
| 463 | -subject|description|text|t| | |
| 464 | -subject|exam_question_count|bigint|t|0 | |
| 465 | -subject|homework_count|bigint|t|0 | |
| 466 | -term|id|uuid|t| | |
| 467 | -term|name|text|t| | |
| 468 | -term|starts_at|bigint|t| | |
| 469 | -term|ends_at|bigint|t| | |
| 470 | -term|archived_at|bigint|f| | |
| 471 | -term|course_count|bigint|t|0 | |
| 472 | -term|class_count|bigint|t|0 | |
| 473 | -user_session|id|uuid|t| | |
| 474 | -user_session|app_user|uuid|t| | |
| 475 | -user_session|token|text|t| | |
| 476 | -user_session|expires_at|bigint|t| | |
| 477 | -work_entry|id|uuid|t| | |
| 478 | -work_entry|app_user|uuid|t| | |
| 479 | -work_entry|check_in|bigint|t| | |
| 480 | -work_entry|check_out|bigint|f| | |
| 481 | -zeka_attention_item|student|uuid|t| | |
| 482 | -zeka_attention_item|trigger|text|t| | |
| 483 | -zeka_attention_item|course|uuid|f| | |
| 484 | -zeka_attention_item|fact|text|t| | |
| 485 | -zeka_attention_item|window_from|bigint|t| | |
| 486 | -zeka_attention_item|window_to|bigint|t| | |
| 487 | -zeka_attention_item|evidence|jsonb|t| | |
| 488 | -zeka_attention_item|ord|smallint|t| | |
| 489 | -zeka_question_segment|question|uuid|t| | |
| 490 | -zeka_question_segment|exam|uuid|t| | |
| 491 | -zeka_question_segment|course|uuid|t| | |
| 492 | -zeka_question_segment|subject|uuid|t| | |
| 493 | -zeka_question_segment|bilissel_talep|text|t| | |
| 494 | -zeka_question_segment|dikkat_tuzagi|text|t| | |
| 495 | -zeka_question_segment|okuma_yuku|text|t| | |
| 496 | -zeka_question_segment|adim_sayisi|text|t| | |
| 497 | -zeka_question_segment|confidence_bilissel_talep|double precision|t| | |
| 498 | -zeka_question_segment|confidence_dikkat_tuzagi|double precision|t| | |
| 499 | -zeka_question_segment|confidence_okuma_yuku|double precision|t| | |
| 500 | -zeka_question_segment|confidence_adim_sayisi|double precision|t| | |
| 501 | -zeka_question_segment|confidence|text|t| | |
| 502 | -zeka_question_segment|trap_choice|text|f| | |
| 503 | -zeka_question_segment|rationale|text|t| | |
| 504 | -zeka_question_segment|model|text|t| | |
| 505 | -zeka_question_segment|prompt_version|text|t| | |
| 506 | -zeka_question_segment|variant|text|f| | |
| 507 | -zeka_question_segment|computed_at|bigint|t| | |
| 508 | -zeka_question_segment|retain_until|bigint|t| | |
| 509 | -zeka_question_segment_dimension|question|uuid|t| | |
| 510 | -zeka_question_segment_dimension|dimension|text|t| | |
| 511 | -zeka_question_segment_dimension|role|text|t| | |
| 512 | -zeka_question_segment_dimension|ord|smallint|t| | |
| 513 | -zeka_recommendation|id|uuid|t| | |
| 514 | -zeka_recommendation|audience|uuid|t| | |
| 515 | -zeka_recommendation|product|text|t| | |
| 516 | -zeka_recommendation|rule_id|text|t| | |
| 517 | -zeka_recommendation|rule_version|bigint|t| | |
| 518 | -zeka_recommendation|scope|text|f| | |
| 519 | -zeka_recommendation|about|uuid|f| | |
| 520 | -zeka_recommendation|audience_role|text|t| | |
| 521 | -zeka_recommendation|course|uuid|f| | |
| 522 | -zeka_recommendation|evidence|jsonb|t| | |
| 523 | -zeka_recommendation|confidence|text|t| | |
| 524 | -zeka_recommendation|created_at|bigint|t| | |
| 525 | -zeka_recommendation|expires_at|bigint|t| | |
| 526 | -zeka_recommendation|retain_until|bigint|t| | |
| 527 | -zeka_recommendation|dismissed_at|bigint|f| | |
| 528 | -zeka_recommendation|dismissed_by|uuid|f| | |
| 529 | -zeka_recommendation|dismiss_reason|text|f| | |
| 530 | -zeka_run|run_day|text|t| | |
| 531 | -zeka_run|started_at|bigint|t| | |
| 532 | -zeka_run|finished_at|bigint|f| | |
| 533 | -zeka_run|status|text|t| | |
| 534 | -zeka_run|duration_ms|bigint|f| | |
| 535 | -zeka_run|students_total|bigint|t|0 | |
| 536 | -zeka_run|students_ok|bigint|t|0 | |
| 537 | -zeka_run|students_failed|bigint|t|0 | |
| 538 | -zeka_run|students_skipped|bigint|t|0 | |
| 539 | -zeka_run|rows_written|bigint|t|0 | |
| 540 | -zeka_run|budget_exceeded|boolean|t|false | |
| 541 | -zeka_run|budget_ms|bigint|t| | |
| 542 | -zeka_run|retain_until|bigint|t| | |
| 543 | -zeka_run_failed_module|run|text|t| | |
| 544 | -zeka_run_failed_module|module|text|t| | |
| 545 | -zeka_run_failed_module|ord|smallint|t| | |
| 546 | -zeka_run_pending|run|text|t| | |
| 547 | -zeka_run_pending|student|uuid|t| | |
| 548 | -zeka_run_pending|ord|integer|t| | |
| 549 | -zeka_student_segment_profile|student|uuid|t| | |
| 550 | -zeka_student_segment_profile|dimension|text|t| | |
| 551 | -zeka_student_segment_profile|label|text|t| | |
| 552 | -zeka_student_segment_profile|n_answers|bigint|t| | |
| 553 | -zeka_student_segment_profile|n_correct|bigint|t| | |
| 554 | -zeka_student_segment_profile|accuracy|double precision|t| | |
| 555 | -zeka_student_segment_profile|overall_n_answers|bigint|t| | |
| 556 | -zeka_student_segment_profile|overall_accuracy|double precision|t| | |
| 557 | -zeka_student_segment_profile|contrast|double precision|t| | |
| 558 | -zeka_student_segment_profile|confidence|text|t| | |
| 559 | -zeka_student_segment_profile|computed_at|bigint|t| | |
| 560 | -zeka_student_segment_profile|retain_until|bigint|t| | |
| 561 | -zeka_student_summary|student|uuid|t| | |
| 562 | -zeka_student_summary|marks|jsonb|f| | |
| 563 | -zeka_student_summary|attendance|jsonb|f| | |
| 564 | -zeka_student_summary|submission|jsonb|f| | |
| 565 | -zeka_student_summary|study|jsonb|f| | |
| 566 | -zeka_student_summary|confidence|text|t| | |
| 567 | -zeka_student_summary|computed_at|bigint|t| | |
| 568 | -zeka_student_summary|retain_until|bigint|t| |
generator/emit.pymodified+4 -14
| @@ -205,17 +205,12 @@ class Emitter: | ||
| 205 | 205 | |
| 206 | 206 | FLEXIBLE = {"rag_output": ("payload",)} |
| 207 | 207 | |
| 208 | - def __init__(self, out_dir: str, mirror=None): | |
| 208 | + def __init__(self, out_dir: str): | |
| 209 | 209 | self.out_dir = out_dir |
| 210 | 210 | self.parts_dir = os.path.join(out_dir, "_parts") |
| 211 | 211 | os.makedirs(self.parts_dir, exist_ok=True) |
| 212 | 212 | self._writers = {} |
| 213 | 213 | self.counts = {} |
| 214 | - # İkinci bir çıkış (`pg_emit.PgEmitter`) verilirse AYNI satırları o da | |
| 215 | - # görür. Ayrı bir geçiş değil aynı geçiş: iki çıktının aynı veriyi | |
| 216 | - # anlatması, ikisini ayrı ayrı üretip sonra karşılaştırmaya çalışmaktan | |
| 217 | - # çok daha ucuz bir garanti. | |
| 218 | - self.mirror = mirror | |
| 219 | 214 | |
| 220 | 215 | def writer(self, table: str) -> PartWriter: |
| 221 | 216 | w = self._writers.get(table) |
| @@ -226,16 +221,11 @@ class Emitter: | ||
| 226 | 221 | |
| 227 | 222 | def add(self, table: str, row: dict) -> None: |
| 228 | 223 | self.writer(table).add(row) |
| 229 | - if self.mirror is not None: | |
| 230 | - self.mirror.add(table, row) | |
| 231 | 224 | |
| 232 | 225 | def add_many(self, table: str, rows) -> None: |
| 233 | - # DİKKAT: `self.add()` üzerinden geçer. Doğrudan `w.add(row)` çağırmak | |
| 234 | - # aynayı (`self.mirror`) atlıyordu ve Postgres çıktısında 31 tablo, | |
| 235 | - # 139.416 satır sessizce eksik kalıyordu. Toplam satır sayısı yine de | |
| 236 | - # doğru görünüyordu, çünkü o sayı SurrealQL yazıcısından okunuyor. | |
| 237 | - # Eksiklik ancak yükleme sırasında bir yabancı anahtar hatası olarak | |
| 238 | - # ortaya çıktı — yani veritabanı olmasa hiç görülmeyecekti. | |
| 226 | + # DİKKAT: `self.add()` üzerinden geçer; doğrudan `w.add(row)` çağırmak | |
| 227 | + # yazıcıyı atlar ve satır sessizce düşer. Toplam sayı yazıcıdan | |
| 228 | + # okunduğu için eksiklik ancak yükleme sırasında görülürdü. | |
| 239 | 229 | for row in rows: |
| 240 | 230 | self.add(table, row) |
| 241 | 231 |
generator/engagement.pymodified+6 -6
| @@ -308,12 +308,12 @@ def build_pomodoro(ctx) -> None: | ||
| 308 | 308 | # `finished_at = NONE` taşıyan ULID anahtarlı bir satır |
| 309 | 309 | # ÜRETİLEMEZ. |
| 310 | 310 | # |
| 311 | - # Eskiden burada `finished = None` yazılıyordu ve SurrealDB | |
| 312 | - # bunu kontrol etmediği için fark edilmiyordu: 4.929 açık | |
| 313 | - # seans, tek bir öğrencide 68 tane. PostgreSQL şeması aynı | |
| 314 | - # değişmezi kısmi tekil indeksle zorluyor | |
| 315 | - # (`pomodoro_session_open_stint ... WHERE finished_at IS | |
| 316 | - # NULL`) ve yükleme orada düştü. | |
| 311 | + # Eskiden burada terk edilmiş bir seans için de | |
| 312 | + # `finished = None` yazılıyordu ve hiçbir şema bunu | |
| 313 | + # zorlamadığı için fark edilmiyordu: 4.929 açık seans, | |
| 314 | + # tek bir öğrencide 68 tane. Değişmez artık yukarıdaki | |
| 315 | + # defterle korunuyor: ULID anahtarlı bir satır | |
| 316 | + # `finished = None` taşımaz. | |
| 317 | 317 | # |
| 318 | 318 | # Terk edilmişlik `counted = false` ile taşınmaya devam |
| 319 | 319 | # ediyor; süre sayaçlarına zaten girmiyordu. |
generator/main.pymodified+1 -23
| @@ -50,10 +50,6 @@ def parse_args(argv=None): | ||
| 50 | 50 | ap.add_argument("--schema", default=DEFAULT_SCHEMA, help="schema.json yolu") |
| 51 | 51 | ap.add_argument("--keep-parts", action="store_true", |
| 52 | 52 | help="Geçici parça dosyalarını silme (hata ayıklama)") |
| 53 | - ap.add_argument("--postgres", action="store_true", | |
| 54 | - help="SurrealQL çıktısının YANINDA PostgreSQL çıktısı da " | |
| 55 | - "üret (pg_control.sql + pg_school.sql). Aynı geçiş, " | |
| 56 | - "aynı satırlar; mevcut .surql dosyaları değişmez.") | |
| 57 | 53 | return ap.parse_args(argv) |
| 58 | 54 | |
| 59 | 55 | |
| @@ -62,11 +58,7 @@ def generate(args): | ||
| 62 | 58 | T.configure(args.date_shift_days) |
| 63 | 59 | emit.load_schema(args.schema) |
| 64 | 60 | os.makedirs(args.out, exist_ok=True) |
| 65 | - pg = None | |
| 66 | - if args.postgres: | |
| 67 | - import pg_emit | |
| 68 | - pg = pg_emit.PgEmitter(args.out) | |
| 69 | - emitter = emit.Emitter(args.out, mirror=pg) | |
| 61 | + emitter = emit.Emitter(args.out) | |
| 70 | 62 | ctx = Ctx(args.seed, SCALES[args.scale], args.date_shift_days, emitter) |
| 71 | 63 | |
| 72 | 64 | def step(label, fn): |
| @@ -107,22 +99,8 @@ def generate(args): | ||
| 107 | 99 | step("referans tabloları", counters.emit_reference_tables) |
| 108 | 100 | step("kullanıcı satırları", counters.emit_users) |
| 109 | 101 | |
| 110 | - if pg is not None: | |
| 111 | - # Control tarafindaki okul satiri: tohum kendi okulunu kendisi | |
| 112 | - # kaydeder, yoksa `Tenants::get` veritabanina hic ulasamaz. | |
| 113 | - pg.school_rows(T.local_ms(_dt.date(2025, 8, 15), 9 * 60), C.MODULES_ALL) | |
| 114 | 102 | emitter.close_all() |
| 115 | 103 | files = emitter.assemble(C.FILE_LAYOUT, C.FILE_DESCRIPTIONS) |
| 116 | - if pg is not None: | |
| 117 | - pg.close_all() | |
| 118 | - files.extend(pg.assemble(C.FILE_LAYOUT)) | |
| 119 | - # Butunluk sinavi da URETILIR: rozet katalogu config.BADGES'ten gelir. | |
| 120 | - # Elle yazildiginda yanlis yazilmisti (450 sahte ihlal). | |
| 121 | - import verify_pg | |
| 122 | - pg_verify = os.path.join(args.out, "pg_dogrula.sql") | |
| 123 | - files.append(("pg_dogrula.sql", verify_pg.write( | |
| 124 | - os.path.join(os.path.dirname(__file__), "..", "tools", | |
| 125 | - "verify_pg_seed.sql"), pg_verify))) | |
| 126 | 104 | if not args.keep_parts: |
| 127 | 105 | emitter.cleanup() |
| 128 | 106 |
generator/pg_emit.pydeleted+0 -564
| @@ -1,564 +0,0 @@ | ||
| 1 | -"""Uretilen satirlari PostgreSQL `INSERT` dosyalarina yazar. | |
| 2 | - | |
| 3 | -`Emitter` ile **yan yana** calisir: ayni `add(table, row)` cagrilarini alir. | |
| 4 | -Metin ayristirmasi YOKTUR — `.surql` dosyalarini regex'le okumak yerine veriyi | |
| 5 | -uretildigi yerde, hala yapili haldeyken cevirir. | |
| 6 | - | |
| 7 | -Bu bilincli bir tercih ve bedeli bir kez odendi: `\\'` kacisini anlamayan bir | |
| 8 | -regex, "47 kirik cevap" diye var olmayan bir sorun raporlamisti. Kayit | |
| 9 | -referanslari burada `Rid` nesnesidir; tablo ve anahtari ayri ayri tasir, yani | |
| 10 | -hangi tabloya baktigi tahmin edilmez, bilinir. | |
| 11 | - | |
| 12 | ---------------------------------------------------------------------------- | |
| 13 | -Sessiz dusurme yok | |
| 14 | ---------------------------------------------------------------------------- | |
| 15 | -Bir alan `pg_map` kurallarinin hicbirine uymuyorsa cevirim HATA ile durur. | |
| 16 | -Alan atlamak, "cevirdik" deyip verinin bir parcasini kaybetmenin ta kendisi. | |
| 17 | -""" | |
| 18 | - | |
| 19 | -from __future__ import annotations | |
| 20 | - | |
| 21 | -import os | |
| 22 | -import sys | |
| 23 | - | |
| 24 | -sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "service")) | |
| 25 | - | |
| 26 | -from src.ids import mint_uuid7, ulid_to_uuid7 # noqa: E402 | |
| 27 | - | |
| 28 | -import pg_map as M # noqa: E402 | |
| 29 | -from ids import Rid # noqa: E402 | |
| 30 | - | |
| 31 | -BATCH_SIZE = 500 | |
| 32 | -_ULID_LEN = 26 | |
| 33 | -_CROCKFORD = set("0123456789ABCDEFGHJKMNPQRSTVWXYZ") | |
| 34 | -_CROCKFORD_INDEX = {c: i for i, c in enumerate("0123456789ABCDEFGHJKMNPQRSTVWXYZ")} | |
| 35 | - | |
| 36 | -#: Hedef semanin kolon katalogu: `_pg_columns.txt`, backend'in kendi | |
| 37 | -#: migration'lari uygulanmis bir veritabanindan dokulmus. | |
| 38 | -#: (tablo, kolon) -> (tip, NOT NULL mi, varsayilan ifade) | |
| 39 | -#: | |
| 40 | -#: Katalog burada bir SUSLEME degil, cevirinin hakemidir. Iki isi var: | |
| 41 | -#: 1. Semada OLMAYAN bir kolona yazilmaya calisilirsa hata verdirir. Bir | |
| 42 | -#: alanin adini yanlis eslemek, o alani sessizce kaybetmenin en kolay | |
| 43 | -#: yolu; katalok o yolu kapatir. | |
| 44 | -#: 2. `NOT NULL DEFAULT <x>` kolonlara gelen None'i varsayilanina cevirir. | |
| 45 | -#: SurrealDB'de "alan yok" ile "sifir" ayni seydi (absent-reads-as-zero); | |
| 46 | -#: Postgres'te alan ya var ya yok. Backend'in kendi cevirisi de bu | |
| 47 | -#: sayaclari `BIGINT NOT NULL DEFAULT 0` yapti. | |
| 48 | -CATALOG_PATH = os.path.join(os.path.dirname(__file__), "_pg_columns.txt") | |
| 49 | - | |
| 50 | - | |
| 51 | -def _load_catalog(): | |
| 52 | - catalog = {} | |
| 53 | - with open(CATALOG_PATH, encoding="utf-8") as fh: | |
| 54 | - for line in fh: | |
| 55 | - line = line.rstrip() | |
| 56 | - if not line: | |
| 57 | - continue | |
| 58 | - table, column, kind, notnull, default = line.split("|", 4) | |
| 59 | - catalog[(table, column)] = (kind, notnull == "t", default) | |
| 60 | - return catalog | |
| 61 | - | |
| 62 | - | |
| 63 | -CATALOG = _load_catalog() | |
| 64 | - | |
| 65 | - | |
| 66 | -def id_strategy(pg_table: str) -> str: | |
| 67 | - """Birincil anahtar stratejisini HEDEF SEMADAN turetir. | |
| 68 | - | |
| 69 | - Elle tutulan bir liste yerine katalogdan okunuyor, cunku elle tutulan | |
| 70 | - liste iki kez yanildi (`dietary_profile` ve `pool_question_image` | |
| 71 | - `id` kolonu olmadigi halde "uuid" sayilmisti). Sema zaten cevabi | |
| 72 | - biliyor; ona sormak, hatirlamaya calismaktan guvenli. | |
| 73 | - | |
| 74 | - id kolonu var -> tipi uuid ise "uuid", degilse "text" | |
| 75 | - name kolonu var -> "name" (kind_ref, slot_ref) | |
| 76 | - ikisi de yok -> "composite": Postgres'te dogal bilesik anahtar var, | |
| 77 | - `id` alani atilir, bilesenleri zaten satirda. | |
| 78 | - """ | |
| 79 | - columns = {c for (t, c) in CATALOG if t == pg_table} | |
| 80 | - if "id" in columns: | |
| 81 | - kind, _notnull, _default = CATALOG[(pg_table, "id")] | |
| 82 | - return "uuid" if kind == "uuid" else "text" | |
| 83 | - if "name" in columns: | |
| 84 | - return "name" | |
| 85 | - return "composite" | |
| 86 | - | |
| 87 | -#: Varsayilan ifadeyi Python degerine cevirmenin BILINEN yollari. Taninmayan | |
| 88 | -#: bir varsayilan tahmin edilmez, hata verilir. | |
| 89 | -_DEFAULTS = {"0": 0, "false": False, "true": True, "''::text": ""} | |
| 90 | - | |
| 91 | - | |
| 92 | -def apply_catalog(table: str, row: dict) -> dict: | |
| 93 | - """Satiri hedef semaya gore denetler ve NOT NULL bosluklarini doldurur. | |
| 94 | - | |
| 95 | - Uc is yapar, ucu de sessiz kayba karsi: | |
| 96 | - 1. Semada olmayan bir kolon -> hata. | |
| 97 | - 2. NOT NULL kolona gelen None -> varsayilani (yoksa hata). | |
| 98 | - 3. NOT NULL ve varsayilansiz bir kolon satirda HIC YOKSA -> hata. | |
| 99 | - | |
| 100 | - Ucuncusu ilk denemede atlanmisti ve `app_user.created_at` INSERT listesine | |
| 101 | - hic girmedi; Postgres onu NULL sayip reddetti. Kolonun eksikligi ancak | |
| 102 | - veritabani reddettigi icin gorulebildi — reddetmeseydi satir eksik bir | |
| 103 | - alanla yazilacakti. | |
| 104 | - """ | |
| 105 | - out = {} | |
| 106 | - for column, value in row.items(): | |
| 107 | - spec = CATALOG.get((table, column)) | |
| 108 | - if spec is None: | |
| 109 | - raise ConversionError( | |
| 110 | - "%s: hedef semada `%s` diye bir kolon yok" % (table, column) | |
| 111 | - ) | |
| 112 | - kind, notnull, default = spec | |
| 113 | - if isinstance(value, Raw): | |
| 114 | - out[column] = value | |
| 115 | - continue | |
| 116 | - if value is None and notnull: | |
| 117 | - if not default: | |
| 118 | - raise ConversionError( | |
| 119 | - "%s.%s NOT NULL ve varsayilani yok, ama deger None" | |
| 120 | - % (table, column) | |
| 121 | - ) | |
| 122 | - if default not in _DEFAULTS: | |
| 123 | - raise ConversionError( | |
| 124 | - "%s.%s varsayilani cozulemedi: %r" % (table, column, default) | |
| 125 | - ) | |
| 126 | - value = _DEFAULTS[default] | |
| 127 | - out[column] = value | |
| 128 | - | |
| 129 | - eksik = [ | |
| 130 | - column | |
| 131 | - for (t, column), (_kind, notnull, default) in CATALOG.items() | |
| 132 | - if t == table and notnull and not default and column not in out | |
| 133 | - ] | |
| 134 | - if eksik: | |
| 135 | - raise ConversionError( | |
| 136 | - "%s: NOT NULL ve varsayilansiz kolon(lar) satirda yok: %s" | |
| 137 | - % (table, sorted(eksik)) | |
| 138 | - ) | |
| 139 | - return out | |
| 140 | - | |
| 141 | - | |
| 142 | -class ConversionError(RuntimeError): | |
| 143 | - """Eslenemeyen alan / tablo. Cevirim durur.""" | |
| 144 | - | |
| 145 | - | |
| 146 | -class Raw(str): | |
| 147 | - """SQL'e OLDUGU GIBI yazilacak parca (alt sorgu gibi). | |
| 148 | - | |
| 149 | - Tirnaklanmaz. Yalnizca bu dosyanin kendi urettigi sabit metinler icin | |
| 150 | - kullanilir; disaridan gelen hicbir deger Raw'a sarilmaz. | |
| 151 | - """ | |
| 152 | - | |
| 153 | - | |
| 154 | -def is_ulid(text: str) -> bool: | |
| 155 | - return len(text) == _ULID_LEN and all(c in _CROCKFORD for c in text) | |
| 156 | - | |
| 157 | - | |
| 158 | -def ulid_ms(key: str) -> int: | |
| 159 | - """ULID'in ilk 10 karakterindeki 48 bitlik unix-ms damgasi.""" | |
| 160 | - value = 0 | |
| 161 | - for ch in key[:10]: | |
| 162 | - value = value * 32 + _CROCKFORD_INDEX[ch] | |
| 163 | - return value | |
| 164 | - | |
| 165 | - | |
| 166 | -def key_to_uuid(table: str, key: str) -> str: | |
| 167 | - """Bir kayit anahtarini uuid'ye cevirir. | |
| 168 | - | |
| 169 | - ULID ise damgasi ve milisaniye ici sirasi KORUNARAK cevrilir; degilse | |
| 170 | - tablo adiyla nitelenmis metinden deterministik basilir. Niteleme sart: | |
| 171 | - iki farkli tabloda ayni anahtar (`open_<user>` gibi) bulunabiliyor ve | |
| 172 | - nitelenmeseydi ayni uuid'ye duserlerdi. | |
| 173 | - | |
| 174 | - --------------------------------------------------------------------- | |
| 175 | - Cevirinin GIRDISI YALNIZCA ANAHTARDIR | |
| 176 | - --------------------------------------------------------------------- | |
| 177 | - Bir sure satirin kendi zaman alani (`starts_at` gibi) da basima | |
| 178 | - katiliyordu; damgayi kimligin icine koymak `ORDER BY id` sirasini | |
| 179 | - korudugu icin cazipti. Ama bu, ayni kaydin iki yerde iki FARKLI uuid | |
| 180 | - almasina yol aciyordu: satirin kendisi yazilirken damga biliniyor, ona | |
| 181 | - REFERANS veren satir yazilirken bilinmiyor. `term` satiri bir uuid, | |
| 182 | - `class_group.term` baska bir uuid uretti ve yukleme yabanci anahtarda | |
| 183 | - dustu. | |
| 184 | - | |
| 185 | - Damga hala korunuyor, ama yalnizca anahtardan OKUNABILDIGI olcude: | |
| 186 | - kompozit anahtarlarin bası genellikle bir ULID'dir (`{odev}_{ogrenci}`) | |
| 187 | - ve o ULID'in damgasi kullanilir. Okunamiyorsa sifir kalir; boyle | |
| 188 | - satirlar kimlige gore sirasiz gorunur, ki bu yanlis siradan iyidir. | |
| 189 | - """ | |
| 190 | - if is_ulid(key): | |
| 191 | - return str(ulid_to_uuid7(key)) | |
| 192 | - head = key.split("_", 1)[0] | |
| 193 | - ts = ulid_ms(head) if is_ulid(head) else 0 | |
| 194 | - return str(mint_uuid7("%s:%s" % (table, key), ts)) | |
| 195 | - | |
| 196 | - | |
| 197 | -def pg_literal(value) -> str: | |
| 198 | - """Bir Python degerini PostgreSQL sabitine cevirir. | |
| 199 | - | |
| 200 | - Metin kacisi tek kural: `''`. SurrealQL'in `\\'` bicimi Postgres'te | |
| 201 | - varsayilan olarak GECERSIZ (`standard_conforming_strings = on`) ve ters | |
| 202 | - boluyu oldugu gibi birakmak, iceren her satiri bozardi. | |
| 203 | - """ | |
| 204 | - if value is None: | |
| 205 | - return "NULL" | |
| 206 | - if isinstance(value, bool): | |
| 207 | - return "true" if value else "false" | |
| 208 | - if isinstance(value, Raw): | |
| 209 | - return str(value) | |
| 210 | - if isinstance(value, Rid): | |
| 211 | - raise ConversionError("Rid dogrudan yazilamaz: %r" % (value,)) | |
| 212 | - if isinstance(value, int): | |
| 213 | - return str(value) | |
| 214 | - if isinstance(value, float): | |
| 215 | - return repr(value) | |
| 216 | - if isinstance(value, str): | |
| 217 | - return "'" + value.replace("'", "''") + "'" | |
| 218 | - if isinstance(value, (list, tuple, dict)): | |
| 219 | - import json | |
| 220 | - | |
| 221 | - text = json.dumps(value, ensure_ascii=False, separators=(",", ":")) | |
| 222 | - return "'" + text.replace("'", "''") + "'::jsonb" | |
| 223 | - raise ConversionError("Serilestirilemeyen deger: %r" % (value,)) | |
| 224 | - | |
| 225 | - | |
| 226 | -class PgTableWriter: | |
| 227 | - """Tablo basina bir parca dosyasi. Kolon kumesi ILK satirdan sabitlenir.""" | |
| 228 | - | |
| 229 | - def __init__(self, directory: str, table: str) -> None: | |
| 230 | - self.table = table | |
| 231 | - self.path = os.path.join(directory, "%s.pgpart" % table) | |
| 232 | - self._fh = open(self.path, "w", encoding="utf-8", newline="\n") | |
| 233 | - self._columns: tuple[str, ...] | None = None | |
| 234 | - self._buf: list[str] = [] | |
| 235 | - self.count = 0 | |
| 236 | - #: Verilirse INSERT'e `ON CONFLICT <bu> ` eklenir. Yalnizca control | |
| 237 | - #: tarafindaki okul kaydi icin: backend okulu kendisi yaratmis | |
| 238 | - #: olabilir ve tohum onun uzerine yazmamali. | |
| 239 | - self.on_conflict: str | None = None | |
| 240 | - | |
| 241 | - def add(self, row: dict) -> None: | |
| 242 | - columns = tuple(row) | |
| 243 | - if self._columns is None: | |
| 244 | - self._columns = columns | |
| 245 | - elif columns != self._columns: | |
| 246 | - # Kolon kumesi satirdan satira degisirse toplu INSERT kurulamaz. | |
| 247 | - # Sessizce NULL doldurmak yerine hata: eksik kolon, eksik veridir. | |
| 248 | - missing = set(self._columns) ^ set(columns) | |
| 249 | - raise ConversionError( | |
| 250 | - "%s: satirlar farkli kolon kumesi tasiyor; fark=%s" | |
| 251 | - % (self.table, sorted(missing)) | |
| 252 | - ) | |
| 253 | - self._buf.append( | |
| 254 | - "(" + ", ".join(pg_literal(row[c]) for c in self._columns) + ")" | |
| 255 | - ) | |
| 256 | - self.count += 1 | |
| 257 | - if len(self._buf) >= BATCH_SIZE: | |
| 258 | - self._flush() | |
| 259 | - | |
| 260 | - def _flush(self) -> None: | |
| 261 | - if not self._buf or self._columns is None: | |
| 262 | - return | |
| 263 | - self._fh.write( | |
| 264 | - "INSERT INTO %s (%s) VALUES\n" | |
| 265 | - % (self.table, ", ".join(self._columns)) | |
| 266 | - ) | |
| 267 | - self._fh.write(",\n".join(self._buf)) | |
| 268 | - if self.on_conflict: | |
| 269 | - self._fh.write("\nON CONFLICT %s" % self.on_conflict) | |
| 270 | - self._fh.write(";\n") | |
| 271 | - self._buf.clear() | |
| 272 | - | |
| 273 | - def close(self) -> None: | |
| 274 | - self._flush() | |
| 275 | - self._fh.close() | |
| 276 | - | |
| 277 | - | |
| 278 | -class PgEmitter: | |
| 279 | - """`Emitter.add()` cagrilarini Postgres satirlarina cevirir.""" | |
| 280 | - | |
| 281 | - def __init__(self, out_dir: str) -> None: | |
| 282 | - self.out_dir = out_dir | |
| 283 | - self.parts_dir = os.path.join(out_dir, "_pgparts") | |
| 284 | - os.makedirs(self.parts_dir, exist_ok=True) | |
| 285 | - self._writers: dict[str, PgTableWriter] = {} | |
| 286 | - self.counts: dict[str, int] = {} | |
| 287 | - self.dropped: dict[str, int] = {} | |
| 288 | - | |
| 289 | - # -- yardimcilar -------------------------------------------------------- | |
| 290 | - | |
| 291 | - def _writer(self, table: str) -> PgTableWriter: | |
| 292 | - w = self._writers.get(table) | |
| 293 | - if w is None: | |
| 294 | - w = PgTableWriter(self.parts_dir, table) | |
| 295 | - self._writers[table] = w | |
| 296 | - return w | |
| 297 | - | |
| 298 | - def _ref(self, value: Rid) -> str: | |
| 299 | - """Kayit referansini hedef tablosunun uuid'sine cevirir. | |
| 300 | - | |
| 301 | - Hedef tablonun anahtar stratejisi "text"/"name" ise referans da metin | |
| 302 | - kalir — `settings` ve `kind_ref` boyle. | |
| 303 | - """ | |
| 304 | - strategy = id_strategy(M.TABLE_RENAME.get(value.table, value.table)) | |
| 305 | - if strategy in ("text", "name"): | |
| 306 | - return value.key | |
| 307 | - return key_to_uuid(value.table, value.key) | |
| 308 | - | |
| 309 | - def _value(self, value): | |
| 310 | - if isinstance(value, Rid): | |
| 311 | - return self._ref(value) | |
| 312 | - if isinstance(value, (list, tuple)): | |
| 313 | - return [self._value(v) for v in value] | |
| 314 | - if isinstance(value, dict): | |
| 315 | - return {k: self._value(v) for k, v in value.items()} | |
| 316 | - return value | |
| 317 | - | |
| 318 | - # -- ana yol ------------------------------------------------------------ | |
| 319 | - | |
| 320 | - def add(self, table: str, row: dict) -> None: | |
| 321 | - if table in M.DROP_TABLES: | |
| 322 | - self.dropped[table] = self.dropped.get(table, 0) + 1 | |
| 323 | - return | |
| 324 | - | |
| 325 | - pg_table = M.TABLE_RENAME.get(table, table) | |
| 326 | - strategy = id_strategy(pg_table) | |
| 327 | - out: dict = {} | |
| 328 | - | |
| 329 | - # 1) birincil anahtar | |
| 330 | - rid_value = row.get("id") | |
| 331 | - key = rid_value.key if isinstance(rid_value, Rid) else rid_value | |
| 332 | - if strategy == "uuid": | |
| 333 | - if key is None: | |
| 334 | - raise ConversionError("%s: id yok ama uuid bekleniyor" % table) | |
| 335 | - out["id"] = key_to_uuid(table, key) | |
| 336 | - elif strategy == "text": | |
| 337 | - out["id"] = key | |
| 338 | - elif strategy == "name": | |
| 339 | - out["name"] = key | |
| 340 | - # "composite" -> id hic yazilmaz; bilesenleri asagida geliyor. | |
| 341 | - | |
| 342 | - # 2) alanlar | |
| 343 | - children: list[tuple[str, dict]] = [] | |
| 344 | - for field, value in row.items(): | |
| 345 | - if field == "id": | |
| 346 | - continue | |
| 347 | - if (table, field) in M.DROP_COLUMNS: | |
| 348 | - continue | |
| 349 | - child = M.CHILD_TABLES.get((table, field)) | |
| 350 | - if child is not None: | |
| 351 | - children.extend(self._child_rows(table, row, value, child)) | |
| 352 | - continue | |
| 353 | - prefix = M.FLATTEN.get((table, field)) | |
| 354 | - if prefix is not None: | |
| 355 | - if value is None: | |
| 356 | - continue | |
| 357 | - if not isinstance(value, dict): | |
| 358 | - raise ConversionError( | |
| 359 | - "%s.%s duzlestirilecekti ama nesne degil" % (table, field) | |
| 360 | - ) | |
| 361 | - for inner, inner_value in value.items(): | |
| 362 | - out[prefix + inner] = self._value(inner_value) | |
| 363 | - continue | |
| 364 | - if table in M.IMAGE_CHILD and field in M.IMAGE_FIELDS: | |
| 365 | - continue # asagida toplu isleniyor | |
| 366 | - out[M.COLUMN_RENAME.get(field, field)] = self._value(value) | |
| 367 | - | |
| 368 | - # 3) kimlik: kullanici satiri control tarafinda bir `person` dogurur | |
| 369 | - # | |
| 370 | - # Yeni backend'de parola okul veritabaninda DEGIL, control'deki | |
| 371 | - # `person` satirinda duruyor; giris `person` -> `person_school` -> | |
| 372 | - # `app_user.person` zincirinden geciyor. Bu zincir kurulmazsa tohum | |
| 373 | - # yuklenir ama HIC KIMSE GIRIS YAPAMAZ — veri gorunur, sistem | |
| 374 | - # kullanilamaz. | |
| 375 | - if table == "user": | |
| 376 | - person_id = str(mint_uuid7("%s:%s" % (M.PERSON_NS, row["username"]))) | |
| 377 | - out["person"] = person_id | |
| 378 | - created = ulid_ms(key) if key and is_ulid(key) else 0 | |
| 379 | - children.append(("person", { | |
| 380 | - "id": person_id, | |
| 381 | - "username": row["username"], | |
| 382 | - # Parola ozeti okul tarafindan control'e TASINIYOR; kopya | |
| 383 | - # birakilmiyor, cunku yeni semada `app_user`in boyle bir | |
| 384 | - # kolonu yok. | |
| 385 | - "password_hash": row["password_hash"], | |
| 386 | - "created_at": created, | |
| 387 | - })) | |
| 388 | - children.append(("person_school", { | |
| 389 | - "person": person_id, | |
| 390 | - # DEGER DEGIL IFADE: okul kaydini backend kendisi yaratmis | |
| 391 | - # olabilir ve o zaman uuid bizim sabitledigimiz degildir. | |
| 392 | - # Slug'a bakan bir alt sorgu iki akisi da calistirir: | |
| 393 | - # tohum okulu kendisi kaydettiyse de, backend kaydettiyse de | |
| 394 | - # uyelik dogru okula baglanir. | |
| 395 | - "school": Raw( | |
| 396 | - "(SELECT id FROM school WHERE slug = '%s')" | |
| 397 | - % M.DEMO_SCHOOL_SLUG), | |
| 398 | - "created_at": created, | |
| 399 | - })) | |
| 400 | - | |
| 401 | - # 4) yeni semanin istedigi, eski semada olmayan kolonlar | |
| 402 | - for (t, column), rule in M.DERIVED_COLUMNS.items(): | |
| 403 | - if t != table: | |
| 404 | - continue | |
| 405 | - if rule == "id_ulid_ms": | |
| 406 | - out[column] = ulid_ms(key) if key and is_ulid(key) else 0 | |
| 407 | - elif rule.startswith("ulid_ms:"): | |
| 408 | - ref = row.get(rule.split(":", 1)[1]) | |
| 409 | - if not isinstance(ref, Rid) or not is_ulid(ref.key): | |
| 410 | - raise ConversionError( | |
| 411 | - "%s.%s turetilemedi: %s bir ULID referansi degil" | |
| 412 | - % (table, column, rule) | |
| 413 | - ) | |
| 414 | - out[column] = ulid_ms(ref.key) | |
| 415 | - else: | |
| 416 | - raise ConversionError("bilinmeyen turetme kurali: %r" % rule) | |
| 417 | - | |
| 418 | - # 5) resim ucluleri | |
| 419 | - if table in M.IMAGE_CHILD: | |
| 420 | - child_table, owner = M.IMAGE_CHILD[table] | |
| 421 | - values = [row.get(f) for f in M.IMAGE_FIELDS] | |
| 422 | - if any(v is not None for v in values): | |
| 423 | - if any(v is None for v in values): | |
| 424 | - raise ConversionError( | |
| 425 | - "%s: resim ucusu yarim (%r)" % (table, values) | |
| 426 | - ) | |
| 427 | - child_row = {owner: out.get("id") or self._value(rid_value)} | |
| 428 | - child_row.update(dict(zip(M.IMAGE_COLUMNS, values))) | |
| 429 | - children.append((child_table, child_row)) | |
| 430 | - | |
| 431 | - self._writer(pg_table).add(apply_catalog(pg_table, out)) | |
| 432 | - for child_table, child_row in children: | |
| 433 | - self._writer(child_table).add(apply_catalog(child_table, child_row)) | |
| 434 | - | |
| 435 | - def _child_rows(self, table: str, row: dict, value, child) -> list: | |
| 436 | - child_table, owner_col, value_col, has_ord = child | |
| 437 | - if not value: | |
| 438 | - return [] | |
| 439 | - if not isinstance(value, (list, tuple)): | |
| 440 | - raise ConversionError( | |
| 441 | - "%s.%s cocuk tabloya acilacakti ama dizi degil" % (table, value_col) | |
| 442 | - ) | |
| 443 | - owner = row.get("id") | |
| 444 | - owner_key = self._ref(owner) if isinstance(owner, Rid) else owner | |
| 445 | - out = [] | |
| 446 | - for index, item in enumerate(value): | |
| 447 | - child_row = {owner_col: owner_key, value_col: self._value(item)} | |
| 448 | - if has_ord: | |
| 449 | - child_row["ord"] = index | |
| 450 | - out.append((child_table, child_row)) | |
| 451 | - return out | |
| 452 | - | |
| 453 | - # -- kapanis ------------------------------------------------------------ | |
| 454 | - | |
| 455 | - def close_all(self) -> None: | |
| 456 | - for table, writer in self._writers.items(): | |
| 457 | - writer.close() | |
| 458 | - self.counts[table] = writer.count | |
| 459 | - | |
| 460 | - def order(self, layout) -> list: | |
| 461 | - """Yukleme sirasi. Postgres yabanci anahtarlari GERCEKTEN zorluyor. | |
| 462 | - | |
| 463 | - Uretici satirlari bagimlilik sirasinda uretmiyor: kullanici satirlari | |
| 464 | - en SONDA yaziliyor, cunku sayaclar once doldurulup sonra dokuluyor. | |
| 465 | - SurrealQL tarafinda bu onemsizdi (FK yok) ve `FILE_LAYOUT` zaten dogru | |
| 466 | - sirayi veriyordu. Postgres tarafinda ayni sirayi kullanmak SART: aksi | |
| 467 | - halde `parent_link` kullanicidan once gelir ve yukleme ilk satirda | |
| 468 | - duser. | |
| 469 | - | |
| 470 | - Cocuk tablolar ebeveyninin HEMEN ardina konur. | |
| 471 | - """ | |
| 472 | - children: dict[str, list[str]] = {} | |
| 473 | - for (parent, _field), spec in M.CHILD_TABLES.items(): | |
| 474 | - children.setdefault(parent, []).append(spec[0]) | |
| 475 | - for parent, (child, _owner) in M.IMAGE_CHILD.items(): | |
| 476 | - children.setdefault(parent, []).append(child) | |
| 477 | - | |
| 478 | - # Control tablolari FILE_LAYOUT'ta gecmez (o duzen okul veritabanina | |
| 479 | - # aittir). Sirasi sabit ve bagimlilik yonunde: okul -> moduller -> | |
| 480 | - # kisi -> uyelik. | |
| 481 | - ordered: list[str] = [] | |
| 482 | - seen: set[str] = set() | |
| 483 | - for table in ("school", "school_module", "person", "person_school"): | |
| 484 | - if table in self._writers: | |
| 485 | - ordered.append(table) | |
| 486 | - seen.add(table) | |
| 487 | - for _number, _name, tables in layout: | |
| 488 | - for table in tables: | |
| 489 | - candidates = [M.TABLE_RENAME.get(table, table)] | |
| 490 | - candidates.extend(children.get(table, [])) | |
| 491 | - for candidate in candidates: | |
| 492 | - if candidate in self._writers and candidate not in seen: | |
| 493 | - ordered.append(candidate) | |
| 494 | - seen.add(candidate) | |
| 495 | - | |
| 496 | - # Duzende adi gecmeyen tablo kalmamali. Kalirsa sirasi BILINMIYOR | |
| 497 | - # demektir; sessizce sona atmak, FK hatasini yukleme anina ertelemek | |
| 498 | - # olurdu ve o an bu dosyadan cok uzakta. | |
| 499 | - artik = [t for t in self._writers if t not in seen] | |
| 500 | - if artik: | |
| 501 | - raise ConversionError( | |
| 502 | - "yukleme sirasinda yeri belli olmayan tablo(lar): %s" | |
| 503 | - % sorted(artik) | |
| 504 | - ) | |
| 505 | - return ordered | |
| 506 | - | |
| 507 | - def school_rows(self, created_ms: int, modules) -> None: | |
| 508 | - """Control tarafindaki okul satiri ve modulleri. | |
| 509 | - | |
| 510 | - Okul KAYITLI olmadan veritabani erisilemez: `Tenants::get` once bu | |
| 511 | - satiri arar. Tohum kendi okulunu kendisi kaydeder ki yukleme tek | |
| 512 | - yonlu olsun — backend acildiginda okulu hazir ve `active` bulur. | |
| 513 | - """ | |
| 514 | - # Okul kaydi zaten varsa (backend yaratmissa) dokunulmaz. | |
| 515 | - self._writer("school").on_conflict = "(slug) DO NOTHING" | |
| 516 | - self._writer("school_module").on_conflict = "(school, module) DO NOTHING" | |
| 517 | - self._writer("school").add({ | |
| 518 | - "id": M.DEMO_SCHOOL_ID, | |
| 519 | - "slug": M.DEMO_SCHOOL_SLUG, | |
| 520 | - "name": M.DEMO_SCHOOL_NAME, | |
| 521 | - "status": "active", | |
| 522 | - "created_at": created_ms, | |
| 523 | - }) | |
| 524 | - for module in modules: | |
| 525 | - self._writer("school_module").add({ | |
| 526 | - "school": M.DEMO_SCHOOL_ID, | |
| 527 | - "module": module, | |
| 528 | - }) | |
| 529 | - | |
| 530 | - def assemble(self, layout) -> list: | |
| 531 | - """Parcalari `control` ve `school` dosyalarina birlestirir.""" | |
| 532 | - ordered = self.order(layout) | |
| 533 | - files = [] | |
| 534 | - groups = ( | |
| 535 | - ("control", [t for t in ordered if t in M.CONTROL_TABLES]), | |
| 536 | - ("school", [t for t in ordered if t not in M.CONTROL_TABLES]), | |
| 537 | - ) | |
| 538 | - for name, tables in groups: | |
| 539 | - if not tables: | |
| 540 | - continue | |
| 541 | - path = os.path.join(self.out_dir, "pg_%s.sql" % name) | |
| 542 | - with open(path, "w", encoding="utf-8", newline="\n") as out: | |
| 543 | - total = sum(self.counts.get(t, 0) for t in tables) | |
| 544 | - out.write("-- Hezarfen tohum verisi (PostgreSQL) - %s\n" % name) | |
| 545 | - out.write("-- Uretici: generator/pg_emit.py\n") | |
| 546 | - out.write("-- SurrealQL ciktisiyla AYNI gecisten, ayni satirlardan.\n") | |
| 547 | - out.write("--\n-- Tablolar, YUKLEME SIRASINDA:\n") | |
| 548 | - for table in tables: | |
| 549 | - out.write( | |
| 550 | - "-- %-28s %8d satir\n" % (table, self.counts.get(table, 0)) | |
| 551 | - ) | |
| 552 | - out.write("-- %-28s %8d satir\n" % ("TOPLAM", total)) | |
| 553 | - out.write("--\n") | |
| 554 | - out.write("-- Tek transaction: yarim yuklenmis bir tohum,\n") | |
| 555 | - out.write("-- hic yuklenmemis olandan daha kotudur.\n") | |
| 556 | - out.write("BEGIN;\n\n") | |
| 557 | - for table in tables: | |
| 558 | - part = os.path.join(self.parts_dir, "%s.pgpart" % table) | |
| 559 | - with open(part, encoding="utf-8") as fh: | |
| 560 | - out.write(fh.read()) | |
| 561 | - out.write("\n") | |
| 562 | - out.write("COMMIT;\n") | |
| 563 | - files.append((os.path.basename(path), os.path.getsize(path))) | |
| 564 | - return files |
generator/pg_map.pydeleted+0 -182
| @@ -1,182 +0,0 @@ | ||
| 1 | -"""SurrealDB tohumu -> PostgreSQL semasi esleme KURALLARI. | |
| 2 | - | |
| 3 | -Burada yalnizca **tablo** vardir, kod yok. `pg_emit.py` bunu okur. | |
| 4 | - | |
| 5 | ---------------------------------------------------------------------------- | |
| 6 | -Tasarim: sessiz dusurme YASAK | |
| 7 | ---------------------------------------------------------------------------- | |
| 8 | -Her alan ya eslenir, ya cocuk tabloya acilir, ya duzlestirilir, ya da ACIKCA | |
| 9 | -"dusurulecek" diye yazilir. Eslenmemis bir alan cevirici tarafindan HATA olarak | |
| 10 | -bildirilir ve cevirim durur. | |
| 11 | - | |
| 12 | -Bu katilik bir tercih degil, bedeli odenmis bir ders: SurrealDB surumunde | |
| 13 | -SCHEMAFULL tablolar tanimsiz alani tek kelime etmeden atiyordu ve bes alanin | |
| 14 | -hic yazilmadigi ancak aylar sonra fark edildi. Postgres de tanimsiz kolona | |
| 15 | -yazmaya calisirsa hata verir; ama cevirici alani kendi atarsa hata VERMEZ. | |
| 16 | -Tek koruma, atmayi imkansiz kilmak. | |
| 17 | -""" | |
| 18 | - | |
| 19 | -# --- tablo adlari ----------------------------------------------------------- | |
| 20 | -# | |
| 21 | -# PostgreSQL `user` ve `session` sozcuklerini kolon/tablo adi olarak kabul | |
| 22 | -# etmiyor. Backend'in kendi cevirisi ne yaptiysa aynisi yapilir | |
| 23 | -# (migrations/school/20260912000001_identity.sql bas aciklamasi). | |
| 24 | -TABLE_RENAME = { | |
| 25 | - "user": "app_user", | |
| 26 | - "session": "user_session", | |
| 27 | -} | |
| 28 | - | |
| 29 | -#: `user` adli HER kolon. `session_attendance.session` kolonu KALIR — | |
| 30 | -#: PostgreSQL'de `session` ayrilmis sozcuk degil (backend de birakti). | |
| 31 | -COLUMN_RENAME = {"user": "app_user"} | |
| 32 | - | |
| 33 | -#: Postgres'te karsiligi OLMAYAN ve olmamasi gereken tablolar. | |
| 34 | -DROP_TABLES = { | |
| 35 | - # Backend cevirisinde kasten atildi: "migration_mark + every REMOVE | |
| 36 | - # retirement line, PRE_REPAIR, BACKFILL ... all dead, preproduction". | |
| 37 | - "migration_mark", | |
| 38 | -} | |
| 39 | - | |
| 40 | -#: Tablo basina dusurulecek alanlar ve GEREKCESI. | |
| 41 | -DROP_COLUMNS = { | |
| 42 | - # Parola artik okul veritabaninda degil, control'deki `person` satirinda. | |
| 43 | - # `app_user.person` birlestirme anahtaridir. | |
| 44 | - ("user", "password_hash"): "control.person.password_hash'e tasindi", | |
| 45 | -} | |
| 46 | - | |
| 47 | -# --- gomulu nesne -> duz kolon ---------------------------------------------- | |
| 48 | -# | |
| 49 | -# `event.audience` bir nesneydi; Postgres onu `audience_*` kolonlarina acti. | |
| 50 | -FLATTEN = { | |
| 51 | - ("event", "audience"): "audience_", | |
| 52 | -} | |
| 53 | - | |
| 54 | -# --- gomulu dizi -> cocuk tablo --------------------------------------------- | |
| 55 | -# | |
| 56 | -# (kaynak tablo, alan) -> (cocuk tablo, sahip kolonu, deger kolonu, ord var mi) | |
| 57 | -# | |
| 58 | -# `ord` yalnizca SIRASI anlamli olan listelerde var; backend hangilerine | |
| 59 | -# koyduysa aynisi (menu_dish_tag ve dietary_profile_tag'de var, uyelik | |
| 60 | -# tablolarinda yok — kume onlar, liste degil). | |
| 61 | -CHILD_TABLES = { | |
| 62 | - ("course", "teachers"): ("course_teacher", "course", "teacher", False), | |
| 63 | - ("board", "participants"): ("board_participant", "board", "participant", False), | |
| 64 | - ("class_blueprint", "courses"): ("blueprint_course", "blueprint", "course", False), | |
| 65 | - ("homework", "assigned"): ("homework_assignment", "homework", "student", False), | |
| 66 | - ("rag_output", "sources"): ("rag_output_source", "output", "source", False), | |
| 67 | - ("dietary_profile", "tags"): ("dietary_profile_tag", "student", "tag", True), | |
| 68 | - ("menu_dish", "tags"): ("menu_dish_tag", "dish", "tag", True), | |
| 69 | - ("school", "modules"): ("school_module", "school", "module", False), | |
| 70 | - ("settings", "attendance_statuses"): ( | |
| 71 | - "settings_attendance_status", "settings", "status", False), | |
| 72 | - ("settings", "dietary_tags"): ("settings_dietary_tag", "settings", "tag", False), | |
| 73 | -} | |
| 74 | - | |
| 75 | -# --- gomulu resim alanlari -> kendi tablosu --------------------------------- | |
| 76 | -# | |
| 77 | -# `pool_question.image_file/.image_content_type/.image_size` uclusu Postgres'te | |
| 78 | -# ayri bir tabloya tasindi. Ucu de NONE ise satir HIC yazilmaz. | |
| 79 | -IMAGE_CHILD = { | |
| 80 | - "pool_question": ("pool_question_image", "question"), | |
| 81 | - "solution": ("solution_image", "solution"), | |
| 82 | -} | |
| 83 | -IMAGE_FIELDS = ("image_file", "image_content_type", "image_size") | |
| 84 | -IMAGE_COLUMNS = ("file", "content_type", "size") | |
| 85 | - | |
| 86 | -# --- (kaldirildi) birincil anahtar stratejisi ------------------------------- | |
| 87 | -# | |
| 88 | -# Elle tutulan bir tablo->strateji listesi vardi ve iki kez yanildi | |
| 89 | -# (, ). Strateji artik HEDEF SEMADAN | |
| 90 | -# turetiliyor: bkz. pg_emit.id_strategy(). Sema zaten cevabi biliyor. | |
| 91 | - | |
| 92 | -# --- (kaldirildi) kimlik basiminda kullanilacak zaman alani ---------------- | |
| 93 | -# | |
| 94 | -# Bir sure burada tablo -> zaman alani eslemesi vardi; kimlik basimina satirin | |
| 95 | -# kendi damgasi katiliyordu. KALDIRILDI: ayni kayit, yazilirken bir uuid, | |
| 96 | -# kendisine referans verilirken baska bir uuid aliyordu (referans veren taraf o | |
| 97 | -# damgayi bilmiyor). Damga artik YALNIZCA anahtarin kendisinden okunuyor | |
| 98 | -# (bkz. pg_emit.key_to_uuid). | |
| 99 | - | |
| 100 | -# --- control / okul ayrimi -------------------------------------------------- | |
| 101 | -# | |
| 102 | -# Backend artik iki veritabani tutuyor: `control` (okul kutugu + kimlik) ve | |
| 103 | -# okul basina bir veritabani. Tohum ikisini de doldurmali. | |
| 104 | -CONTROL_TABLES = { | |
| 105 | - "school", "school_module", "builder", "builder_session", | |
| 106 | - "person", "person_school", "person_session", "rate_limit", | |
| 107 | -} | |
| 108 | - | |
| 109 | - | |
| 110 | -# --- yeni semanin istedigi, eski semada OLMAYAN kolonlar -------------------- | |
| 111 | -# | |
| 112 | -# Backend'in Postgres cevirisi birkac kolon EKLEDI. Ornegi `app_user.created_at`: | |
| 113 | -# eski `user` tablosunda boyle bir alan yoktu, yenisinde `BIGINT NOT NULL`. | |
| 114 | -# | |
| 115 | -# Uydurmuyoruz, TURETIYORUZ: kayit kimligi ULID'dir ve ULID'in ilk 48 biti | |
| 116 | -# kaydin kendi olusturma damgasidir. Backend de ayni sozlesmeyi suruyor | |
| 117 | -# (uuid v7'nin ilk 48 biti unix-ms). Yani buradaki deger, satirin gercekten | |
| 118 | -# olusturuldugu andir; yer doldurmak icin konmus bir sabit degil. | |
| 119 | -# | |
| 120 | -# (tablo, kolon) -> turetme kurali | |
| 121 | -# Kural bicimleri: | |
| 122 | -# "id_ulid_ms" -> satirin KENDI kimliginden (ULID) damga. | |
| 123 | -# "ulid_ms:<alan>" -> satirin <alan> referansinin ULID damgasi. | |
| 124 | -# | |
| 125 | -# ⚠️ YAKLASIKLIK UYARISI. Bunlarin hepsi ayni dogrulukta DEGIL: | |
| 126 | -# | |
| 127 | -# TAM `app_user.created_at` — kullanicinin kendi ULID'i. | |
| 128 | -# TAM `session_attendance.marked_at` — dersin kendi ULID'i; yoklama o derste | |
| 129 | -# alinir, yani damga gercekten o an. | |
| 130 | -# YAKLASIK `attendance.marked_at` — etkinligin damgasi. Yoklama etkinlik | |
| 131 | -# sirasinda alinir; sapma saatler | |
| 132 | -# mertebesinde. | |
| 133 | -# YAKLASIK `registration.created_at` — etkinligin damgasi. Kayit etkinlikten | |
| 134 | -# ONCE olur, yani bu deger gercek | |
| 135 | -# kayittan SONRAYA dusebilir. | |
| 136 | -# YAKLASIK `enrollment.created_at` — dersin damgasi. Ders donem basinda | |
| 137 | -# acilir ve kayitlar da o siralarda | |
| 138 | -# yapilir; donem ortasinda kaydolan | |
| 139 | -# ogrenci icin YANLIS. | |
| 140 | -# YAKLASIK `exam_result.graded_at` — sinavin damgasi. Notlandirma sinavdan | |
| 141 | -# GUNLER sonra olur; bu deger | |
| 142 | -# "notlandirma gecikmesi" gibi bir olcum | |
| 143 | -# icin KULLANILAMAZ. | |
| 144 | -# | |
| 145 | -# Neden yine de konuyor: kolonlar `NOT NULL` ve bos birakilamaz. Yaklasik bir | |
| 146 | -# damga, uydurma bir sabitten iyidir — ama hangisinin yaklasik oldugu | |
| 147 | -# yazilmadan kullanilmasi tehlikelidir, o yuzden burada yaziyor. | |
| 148 | -# | |
| 149 | -# ZEKA bu bes alanin HICBIRINI okumuyor: kopru izin listesinde sinav ve | |
| 150 | -# yoklama-zaman yolu yok. Yani bugun hicbir analizi etkilemiyorlar. | |
| 151 | -DERIVED_COLUMNS = { | |
| 152 | - ("user", "created_at"): "id_ulid_ms", | |
| 153 | - ("session_attendance", "marked_at"): "ulid_ms:session", | |
| 154 | - ("attendance", "marked_at"): "ulid_ms:event", | |
| 155 | - ("registration", "created_at"): "ulid_ms:event", | |
| 156 | - ("enrollment", "created_at"): "ulid_ms:course", | |
| 157 | - ("exam_result", "graded_at"): "ulid_ms:exam", | |
| 158 | -} | |
| 159 | - | |
| 160 | - | |
| 161 | -# --- DEMO okulunun kimligi -------------------------------------------------- | |
| 162 | -# | |
| 163 | -# Okul veritabaninin ADI okulun uuid'sinden turetiliyor | |
| 164 | -# (`tenant::school_db_name` -> "{control}_school_{uuid.simple}"), slug'dan | |
| 165 | -# DEGIL. Yani tohumu yuklemek icin okulun uuid'sinin ONCEDEN bilinmesi gerek; | |
| 166 | -# aksi halde hangi veritabanina yazacagimizi backend okulu yaratana kadar | |
| 167 | -# bilemeyiz. | |
| 168 | -# | |
| 169 | -# Demo icin uuid SABITLENDI. Boylece yukleme tek yonlu ve tekrarlanabilir: | |
| 170 | -# veritabanini bu addan kur, semayi uygula, tohumu dok, control satirini yaz. | |
| 171 | -# Backend acildiginda okulu `active` ve semasi yuklenmis bulur. | |
| 172 | -# | |
| 173 | -# Ayri bir okul olarak duruyor: baska bir okulun verisine dokunmaz, slug'i ve | |
| 174 | -# uuid'si kendine ozeldir. | |
| 175 | -DEMO_SCHOOL_ID = "01930000-0000-7000-8000-00000000de70" | |
| 176 | - | |
| 177 | -#: Kullanicinin control tarafindaki `person` satirinin kimligi kullanici | |
| 178 | -#: adindan deterministik uretilir. Ayni kullanici her uretimde ayni person | |
| 179 | -#: uuid'sini alir; tohumu iki kez yuklemek cift kayit dogurmaz. | |
| 180 | -PERSON_NS = "person" | |
| 181 | -DEMO_SCHOOL_SLUG = "hezarfen-demo" | |
| 182 | -DEMO_SCHOOL_NAME = "Hezarfen Demo Lisesi" |
generator/verify_pg.pydeleted+0 -64
| @@ -1,64 +0,0 @@ | ||
| 1 | -"""`pg_dogrula.sql` — yuklenmis tohumun butunluk sinavini URETIR. | |
| 2 | - | |
| 3 | -`tools/verify_pg_seed.sql` sablonundaki `-- @ROZET_KATALOGU@` isareti, burada | |
| 4 | -`config.BADGES`'ten uretilen bir katalog tablosuyla degistirilir. | |
| 5 | - | |
| 6 | -Neden uretiliyor da elle yazilmiyor: ilk denemede rozet deseni elle yazilmisti | |
| 7 | -ve YANLISTI — onek `pomodoro_focus_hours` saniliyordu, oysa `pomodoro_focus_ms` | |
| 8 | -ve esik milisaniye cinsinden. Sinav 450 sahte ihlal bildirdi. Katalog tek bir | |
| 9 | -yerde (`config.BADGES`) tanimli; iki kez yazilan her sey er ya da gec ayrisir. | |
| 10 | -""" | |
| 11 | - | |
| 12 | -from __future__ import annotations | |
| 13 | - | |
| 14 | -import os | |
| 15 | - | |
| 16 | -import config as C | |
| 17 | - | |
| 18 | -MARKER = "-- @ROZET_KATALOGU@" | |
| 19 | - | |
| 20 | - | |
| 21 | -def _catalog_sql() -> str: | |
| 22 | - rows = ",\n ".join( | |
| 23 | - "('%s', '%s', %d)" % (name, counter, threshold) | |
| 24 | - for name, counter, threshold in C.BADGES | |
| 25 | - ) | |
| 26 | - counters = sorted({counter for _n, counter, _t in C.BADGES}) | |
| 27 | - unpivot = "\n UNION ALL ".join( | |
| 28 | - "SELECT id AS app_user, '%s' AS sayac, %s AS deger FROM app_user" % (c, c) | |
| 29 | - for c in counters | |
| 30 | - ) | |
| 31 | - return """-- Rozet katalogu — `generator/config.BADGES`'ten URETILDI (%d rozet). | |
| 32 | --- Elle duzenlemeyin: kaynagi config.py'dir. | |
| 33 | -CREATE TEMP TABLE rozet_katalog (rozet text PRIMARY KEY, sayac text, esik bigint); | |
| 34 | -INSERT INTO rozet_katalog VALUES | |
| 35 | - %s; | |
| 36 | - | |
| 37 | --- Kullanici sayaclari uzun bicimde: rozet katalogu sayaci ADIYLA taniyor, | |
| 38 | --- yani her rozet icin ayri bir CASE dali yazmak gerekmiyor. Yeni bir rozet | |
| 39 | --- turu eklenirse bu sorgu degismeden calisir. | |
| 40 | -CREATE TEMP TABLE kullanici_sayac AS | |
| 41 | - %s; | |
| 42 | -CREATE INDEX ON kullanici_sayac (app_user, sayac); | |
| 43 | - | |
| 44 | -INSERT INTO sonuc (kod, baslik, ihlal) | |
| 45 | -SELECT 'I21', 'badge_award.badge katalog disi', count(*) | |
| 46 | - FROM badge_award WHERE badge NOT IN (SELECT rozet FROM rozet_katalog); | |
| 47 | - | |
| 48 | -INSERT INTO sonuc (kod, baslik, ihlal) | |
| 49 | -SELECT 'I22', 'rozet var ama ilgili sayac esigin altinda', count(*) | |
| 50 | - FROM badge_award b | |
| 51 | - JOIN rozet_katalog k ON k.rozet = b.badge | |
| 52 | - LEFT JOIN kullanici_sayac s ON s.app_user = b.app_user AND s.sayac = k.sayac | |
| 53 | - WHERE s.deger IS NULL OR s.deger < k.esik;""" % (len(C.BADGES), rows, unpivot) | |
| 54 | - | |
| 55 | - | |
| 56 | -def write(template_path: str, out_path: str) -> int: | |
| 57 | - with open(template_path, encoding="utf-8") as fh: | |
| 58 | - text = fh.read() | |
| 59 | - if MARKER not in text: | |
| 60 | - raise RuntimeError("sablonda %s isareti yok: %s" % (MARKER, template_path)) | |
| 61 | - text = text.replace(MARKER, _catalog_sql()) | |
| 62 | - with open(out_path, "w", encoding="utf-8", newline="\n") as fh: | |
| 63 | - fh.write(text) | |
| 64 | - return os.path.getsize(out_path) |
paket/20260916000001_zeka.sqldeleted+0 -383
| @@ -1,383 +0,0 @@ | ||
| 1 | --- ZEKA's output tables, in the school database (Postgres). | |
| 2 | --- | |
| 3 | --- WHERE THIS FILE BELONGS: `migrations/school/` in the backend repo, applied | |
| 4 | --- by `Migrator::new(migrations/school)` to the template at boot and to every | |
| 5 | --- school database at create. It is APPEND-ONLY relative to the four existing | |
| 6 | --- school migrations: it creates new tables and touches none of them. | |
| 7 | --- | |
| 8 | --- SCOPE RULE, unchanged: ZEKA **never writes** to a pre-existing table. It | |
| 9 | --- reads school data through the bridge's `ApiRequest` allowlist only, and | |
| 10 | --- writes nothing but the `zeka_*` tables below. The FKs point outward, one | |
| 11 | --- direction only. | |
| 12 | --- | |
| 13 | --- NO `school` COLUMN: each school already lives in its own database, so the | |
| 14 | --- tenant IS the database. The SurrealDB version carried a `school` slug on | |
| 15 | --- every row because ZEKA then had a database of its own; that column is gone | |
| 16 | --- and every composite key drops its school segment with it. | |
| 17 | --- | |
| 18 | --- Translated from service/schema/zeka.surql, following the same rules the | |
| 19 | --- backend's own translation used: | |
| 20 | --- * record links -> uuid FKs, ALL `ON DELETE NO ACTION` (cascades stay | |
| 21 | --- explicit application transactions) | |
| 22 | --- * `{a}_{b}` text record keys -> natural composite PRIMARY KEYs | |
| 23 | --- * timestamps -> BIGINT unix-ms UTC, never `timestamptz` | |
| 24 | --- * `option<object> FLEXIBLE` -> JSONB, and only where the shape belongs to | |
| 25 | --- the service rather than to this schema (the same line | |
| 26 | --- `rag_output.payload` and `exam_question.choices` draw) | |
| 27 | --- * `option<array<...>>` -> a child table with an `ord` column, never a | |
| 28 | --- Postgres array: the backend replaced every `TEXT[]` | |
| 29 | --- and `uuid[]` it had (course_teacher, menu_dish_tag, | |
| 30 | --- blueprint_course, ...), and an array here would be the | |
| 31 | --- one exception in the schema. | |
| 32 | --- * entity ids are app-minted uuid v7 (`domain::monotonic_id::next_uuid`), | |
| 33 | --- never a DB default — the one id convention in the codebase. | |
| 34 | --- | |
| 35 | --- CHECK constraints carry only the enums ZEKA itself closes (confidence tier, | |
| 36 | --- audience role, run status, segment dimension + its labels). `product` and | |
| 37 | --- `rule_id` carry NO CHECK: rules are added and versioned far more often than | |
| 38 | --- the schema, and a DDL CHECK could not survive that — the same reasoning that | |
| 39 | --- left exam kinds and attendance statuses unconstrained. | |
| 40 | - | |
| 41 | - | |
| 42 | --- --------------------------------------------------------------------------- | |
| 43 | --- 1) zeka_student_summary — one nightly row per student | |
| 44 | --- | |
| 45 | --- PK is the student alone (the `{school}_{user}` key minus its school half), | |
| 46 | --- which makes the nightly write an idempotent UPSERT and needs no extra | |
| 47 | --- unique index. Same shape as `dietary_profile`, keyed on `app_user`. | |
| 48 | --- --------------------------------------------------------------------------- | |
| 49 | -CREATE TABLE zeka_student_summary ( | |
| 50 | - student uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | |
| 51 | - -- The compute modules' output objects. JSONB because the shape belongs to | |
| 52 | - -- the service: it changes with a rule version, and this schema should not | |
| 53 | - -- have to move every time it does. | |
| 54 | - marks JSONB NULL, | |
| 55 | - attendance JSONB NULL, | |
| 56 | - submission JSONB NULL, | |
| 57 | - study JSONB NULL, | |
| 58 | - -- 'none' | 'exploratory' | 'stable' — inherited from the weakest input. | |
| 59 | - confidence TEXT NOT NULL | |
| 60 | - CHECK (confidence IN ('none', 'exploratory', 'stable')), | |
| 61 | - computed_at BIGINT NOT NULL, | |
| 62 | - -- Swept after this instant: derived student profile, "term + 1 year". | |
| 63 | - retain_until BIGINT NOT NULL, | |
| 64 | - CONSTRAINT zeka_student_summary_student PRIMARY KEY (student) | |
| 65 | -); | |
| 66 | - | |
| 67 | -CREATE INDEX zeka_student_summary_retain ON zeka_student_summary (retain_until); | |
| 68 | - | |
| 69 | --- The attention list, one row per trigger (was an embedded array). | |
| 70 | --- | |
| 71 | --- There is deliberately NO score column and no severity: a single risk number | |
| 72 | --- would rank children, and the literature review found no validated causal | |
| 73 | --- evidence for that product. `ord` keeps the writer's order, which is | |
| 74 | --- alphabetical by trigger and NOT by severity — see `attention.order_items`. | |
| 75 | -CREATE TABLE zeka_attention_item ( | |
| 76 | - student uuid NOT NULL REFERENCES zeka_student_summary(student) ON DELETE NO ACTION, | |
| 77 | - -- Which trigger fired: 'attendance' | 'homework' | 'mark_trend'. | |
| 78 | - -- No CHECK: a fourth trigger is a rule change, not a schema change. | |
| 79 | - trigger TEXT NOT NULL, | |
| 80 | - -- The course the trigger is about, when it has one. NULL = school-wide. | |
| 81 | - -- Only the mark-trend trigger is per-course today. | |
| 82 | - course uuid NULL REFERENCES course(id) ON DELETE NO ACTION, | |
| 83 | - -- THE SENTENCE THE TEACHER READS. A statement of fact, not a judgement: | |
| 84 | - -- "4 of the last 30 days' homework went unsubmitted", never "at risk". | |
| 85 | - -- It is written here rather than rebuilt by the reader, so that what was | |
| 86 | - -- shown and what was computed can never drift apart. | |
| 87 | - fact TEXT NOT NULL, | |
| 88 | - -- The window the fact is about. Kept as columns, not inside `evidence`, | |
| 89 | - -- because "is this item about the last 30 days or the last 7" is a | |
| 90 | - -- question the reader asks of every item. | |
| 91 | - window_from BIGINT NOT NULL, | |
| 92 | - window_to BIGINT NOT NULL, | |
| 93 | - -- The numbers behind the item. Never empty: the store | |
| 94 | - -- refuses an item without evidence, because an item nobody can explain | |
| 95 | - -- cannot be shown to a teacher. | |
| 96 | - evidence JSONB NOT NULL, | |
| 97 | - ord SMALLINT NOT NULL, | |
| 98 | - CONSTRAINT zeka_attention_item_student_trigger_course | |
| 99 | - UNIQUE NULLS NOT DISTINCT (student, trigger, course) | |
| 100 | -); | |
| 101 | - | |
| 102 | -CREATE INDEX zeka_attention_item_student ON zeka_attention_item (student); | |
| 103 | -CREATE INDEX zeka_attention_item_trigger ON zeka_attention_item (trigger); | |
| 104 | - | |
| 105 | - | |
| 106 | --- --------------------------------------------------------------------------- | |
| 107 | --- 2) zeka_recommendation — generated advice | |
| 108 | --- | |
| 109 | --- Every row carries a reason. Advice that cannot be explained is not shown, | |
| 110 | --- so `evidence` is NOT NULL and the store refuses an empty object. | |
| 111 | --- | |
| 112 | --- The old record key was `{school}_{audience}_{product}_{rule_id}[_{scope}]`; | |
| 113 | --- minus the school half that is exactly the composite PK below. `scope` is | |
| 114 | --- the optional last segment (a course id, usually), and NULLS NOT DISTINCT is | |
| 115 | --- what makes "no scope" count as a taken slot rather than an unlimited one — | |
| 116 | --- the same device `bank_question_image` uses for its NULL slot. | |
| 117 | --- --------------------------------------------------------------------------- | |
| 118 | -CREATE TABLE zeka_recommendation ( | |
| 119 | - -- A surrogate id, because the natural key below has a nullable column and | |
| 120 | - -- a PRIMARY KEY cannot: `NULLS NOT DISTINCT` is a UNIQUE-only device. It | |
| 121 | - -- earns its keep anyway — dismissing a card is a write against one row, | |
| 122 | - -- and a client should not have to name four columns to do it. | |
| 123 | - id uuid PRIMARY KEY, | |
| 124 | - -- Who sees it. | |
| 125 | - audience uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | |
| 126 | - -- Which product family: 'O1' | 'O2' | 'O3' | 'O4' | 'T3' | 'T4' today. | |
| 127 | - product TEXT NOT NULL, | |
| 128 | - -- Which rule, and which version of it, produced this. A rule may not | |
| 129 | - -- change what it says without changing this number. | |
| 130 | - rule_id TEXT NOT NULL, | |
| 131 | - rule_version BIGINT NOT NULL, | |
| 132 | - -- The rule's optional scope segment; NULL when the rule has none. TEXT, | |
| 133 | - -- not uuid: a segment rule scopes itself by label ("bilissel_talep=analiz", | |
| 134 | - -- "<class>_okuma_yuku=yuksek"), not by a row it could point at. | |
| 135 | - scope TEXT NULL, | |
| 136 | - -- Who it is about. NULL on a student's own card (audience = about would | |
| 137 | - -- be noise); set on every teacher-facing row. | |
| 138 | - about uuid NULL REFERENCES app_user(id) ON DELETE NO ACTION, | |
| 139 | - -- The role gate. T4 items are 'teacher' only — never shown to the student | |
| 140 | - -- or the parent. | |
| 141 | - audience_role TEXT NOT NULL | |
| 142 | - CHECK (audience_role IN ('student', 'teacher', 'parent', 'manager')), | |
| 143 | - course uuid NULL REFERENCES course(id) ON DELETE NO ACTION, | |
| 144 | - -- Which numbers, which window. Feeds the "why?" panel. | |
| 145 | - evidence JSONB NOT NULL, | |
| 146 | - confidence TEXT NOT NULL | |
| 147 | - CHECK (confidence IN ('none', 'exploratory', 'stable')), | |
| 148 | - created_at BIGINT NOT NULL, | |
| 149 | - expires_at BIGINT NOT NULL, | |
| 150 | - -- `expires_at` or 90 days, whichever comes first. The sweep reads this. | |
| 151 | - retain_until BIGINT NOT NULL, | |
| 152 | - -- The human-override trail (KVKK art. 11): dismissed, disputed, not | |
| 153 | - -- useful. The nightly write MERGES; it must never clear these three. | |
| 154 | - dismissed_at BIGINT NULL, | |
| 155 | - dismissed_by uuid NULL REFERENCES app_user(id) ON DELETE NO ACTION, | |
| 156 | - dismiss_reason TEXT NULL, | |
| 157 | - -- The idempotency key: the same rule is never duplicated for the same | |
| 158 | - -- person, so the nightly write is an UPSERT on this. | |
| 159 | - -- | |
| 160 | - -- `about` IS PART OF THE KEY, and that is not cosmetic. A teacher-facing | |
| 161 | - -- rule fires once per student: thirty students under one teacher, one | |
| 162 | - -- rule, one course. Without `about` all thirty share a key, the UPSERT | |
| 163 | - -- keeps the last, and the teacher is shown one student while twenty-nine | |
| 164 | - -- vanish without an error anywhere. (The SurrealDB version keyed on | |
| 165 | - -- `scope or course or about` and lost exactly that way.) | |
| 166 | - CONSTRAINT zeka_recommendation_key | |
| 167 | - UNIQUE NULLS NOT DISTINCT (audience, product, rule_id, about, scope) | |
| 168 | -); | |
| 169 | - | |
| 170 | -CREATE INDEX zeka_recommendation_audience ON zeka_recommendation (audience, created_at); | |
| 171 | -CREATE INDEX zeka_recommendation_about ON zeka_recommendation (about, product); | |
| 172 | --- Rule calibration: a rule dismissed as wrong over and over IS wrong. This | |
| 173 | --- index is what makes that measurable without a full scan. | |
| 174 | -CREATE INDEX zeka_recommendation_rule ON zeka_recommendation (rule_id, created_at); | |
| 175 | -CREATE INDEX zeka_recommendation_retain ON zeka_recommendation (retain_until); | |
| 176 | - | |
| 177 | - | |
| 178 | --- --------------------------------------------------------------------------- | |
| 179 | --- 3) zeka_run — the nightly job's ledger | |
| 180 | --- | |
| 181 | --- Partial failure and budget accounting rest on this. The key was | |
| 182 | --- `{school}_{YYYY-MM-DD}`; minus the school half it is the day itself, so a | |
| 183 | --- re-run of the same night overwrites rather than duplicating. TEXT PK, the | |
| 184 | --- same choice `settings.id` makes. | |
| 185 | --- --------------------------------------------------------------------------- | |
| 186 | -CREATE TABLE zeka_run ( | |
| 187 | - run_day TEXT NOT NULL | |
| 188 | - CHECK (run_day ~ '^[0-9]{4}-[0-9]{2}-[0-9]{2}$'), | |
| 189 | - started_at BIGINT NOT NULL, | |
| 190 | - finished_at BIGINT NULL, | |
| 191 | - status TEXT NOT NULL | |
| 192 | - CHECK (status IN ('running', 'ok', 'partial', 'failed', 'skipped')), | |
| 193 | - duration_ms BIGINT NULL, | |
| 194 | - students_total BIGINT NOT NULL DEFAULT 0, | |
| 195 | - students_ok BIGINT NOT NULL DEFAULT 0, | |
| 196 | - students_failed BIGINT NOT NULL DEFAULT 0, | |
| 197 | - students_skipped BIGINT NOT NULL DEFAULT 0, | |
| 198 | - rows_written BIGINT NOT NULL DEFAULT 0, | |
| 199 | - budget_exceeded BOOLEAN NOT NULL DEFAULT false, | |
| 200 | - budget_ms BIGINT NOT NULL, | |
| 201 | - retain_until BIGINT NOT NULL, | |
| 202 | - CONSTRAINT zeka_run_day PRIMARY KEY (run_day) | |
| 203 | -); | |
| 204 | - | |
| 205 | -CREATE INDEX zeka_run_started ON zeka_run (started_at); | |
| 206 | -CREATE INDEX zeka_run_retain ON zeka_run (retain_until); | |
| 207 | - | |
| 208 | --- Students the budget ran out on, one row each (was an embedded array). The | |
| 209 | --- next run starts here, which is the only reason the list is kept. | |
| 210 | -CREATE TABLE zeka_run_pending ( | |
| 211 | - run TEXT NOT NULL REFERENCES zeka_run(run_day) ON DELETE NO ACTION, | |
| 212 | - student uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | |
| 213 | - ord INTEGER NOT NULL, | |
| 214 | - CONSTRAINT zeka_run_pending_run_student PRIMARY KEY (run, student) | |
| 215 | -); | |
| 216 | - | |
| 217 | --- Modules that failed, one row each (was an embedded array). A partial list | |
| 218 | --- is what lets the UI mark a section "missing" instead of showing a hole. | |
| 219 | -CREATE TABLE zeka_run_failed_module ( | |
| 220 | - run TEXT NOT NULL REFERENCES zeka_run(run_day) ON DELETE NO ACTION, | |
| 221 | - module TEXT NOT NULL, | |
| 222 | - ord SMALLINT NOT NULL, | |
| 223 | - CONSTRAINT zeka_run_failed_module_run_module PRIMARY KEY (run, module) | |
| 224 | -); | |
| 225 | - | |
| 226 | - | |
| 227 | --- --------------------------------------------------------------------------- | |
| 228 | --- 4) zeka_question_segment — one cognitive label set per exam question | |
| 229 | --- | |
| 230 | --- This is a question's LABEL, not its STATISTIC. p-value and discrimination | |
| 231 | --- need raw answers, and the bridge allowlist carries no exam path, so item | |
| 232 | --- analysis still cannot be built. Everything here comes from the question's | |
| 233 | --- own text. | |
| 234 | --- | |
| 235 | --- NOT PERSONAL DATA: a row is about a question and reaches no student. It | |
| 236 | --- still carries a finite `retain_until`, because a label is the output of one | |
| 237 | --- model and one prompt version and goes stale when either moves — and an | |
| 238 | --- infinite retention would need an exception in the sweep. | |
| 239 | --- | |
| 240 | --- The composite FK below is the device `exam_answer` uses: naming both the | |
| 241 | --- exam and the question means the two can never disagree about the owner. | |
| 242 | --- --------------------------------------------------------------------------- | |
| 243 | -CREATE TABLE zeka_question_segment ( | |
| 244 | - question uuid NOT NULL, | |
| 245 | - exam uuid NOT NULL, | |
| 246 | - -- Denormalized from `subject.course` so the teacher's | |
| 247 | - -- course x cognitive-demand screen needs no join. ZEKA resolves it at | |
| 248 | - -- write time; nothing else may set it. | |
| 249 | - course uuid NOT NULL REFERENCES course(id) ON DELETE NO ACTION, | |
| 250 | - subject uuid NOT NULL REFERENCES subject(id) ON DELETE NO ACTION, | |
| 251 | - | |
| 252 | - -- --- The dimensions. Label sets match src/segment/rubric.py exactly. --- | |
| 253 | - bilissel_talep TEXT NOT NULL | |
| 254 | - CHECK (bilissel_talep IN ('hatirlama', 'uygulama', 'analiz')), | |
| 255 | - dikkat_tuzagi TEXT NOT NULL | |
| 256 | - CHECK (dikkat_tuzagi IN ('var', 'yok')), | |
| 257 | - okuma_yuku TEXT NOT NULL | |
| 258 | - CHECK (okuma_yuku IN ('dusuk', 'yuksek')), | |
| 259 | - -- EXPERIMENTAL. Measured 0.607 stability on a hand-written probe; it | |
| 260 | - -- scores far higher on our own seed only because the generator writes | |
| 261 | - -- multi-step-ness into the text, which makes that an exam we set | |
| 262 | - -- ourselves. Labelled and stored, never read downstream. | |
| 263 | - adim_sayisi TEXT NOT NULL | |
| 264 | - CHECK (adim_sayisi IN ('tek_adim', 'cok_adim')), | |
| 265 | - | |
| 266 | - -- Per-dimension model confidence in [0,1]. One total is not enough: a | |
| 267 | - -- question's reading load can be obvious while its cognitive demand is | |
| 268 | - -- genuinely ambiguous. | |
| 269 | - confidence_bilissel_talep DOUBLE PRECISION NOT NULL | |
| 270 | - CHECK (confidence_bilissel_talep BETWEEN 0 AND 1), | |
| 271 | - confidence_dikkat_tuzagi DOUBLE PRECISION NOT NULL | |
| 272 | - CHECK (confidence_dikkat_tuzagi BETWEEN 0 AND 1), | |
| 273 | - confidence_okuma_yuku DOUBLE PRECISION NOT NULL | |
| 274 | - CHECK (confidence_okuma_yuku BETWEEN 0 AND 1), | |
| 275 | - confidence_adim_sayisi DOUBLE PRECISION NOT NULL | |
| 276 | - CHECK (confidence_adim_sayisi BETWEEN 0 AND 1), | |
| 277 | - -- Row-level tier, same vocabulary as every other table here. Derived from | |
| 278 | - -- the LOWEST confidence among the PRODUCTION dimensions; the experimental | |
| 279 | - -- one does not enter it. | |
| 280 | - confidence TEXT NOT NULL | |
| 281 | - CHECK (confidence IN ('none', 'exploratory', 'stable')), | |
| 282 | - | |
| 283 | - -- The distractor the trap points at (an id from `exam_question.choices`), | |
| 284 | - -- when `dikkat_tuzagi = 'var'`. No FK: choices live inside a JSONB column. | |
| 285 | - trap_choice TEXT NULL, | |
| 286 | - -- The model's own reasoning, two sentences at most. NOT SHOWN TO THE | |
| 287 | - -- STUDENT — see docs/CIKTI-SOZLESMESI.md. | |
| 288 | - rationale TEXT NOT NULL, | |
| 289 | - | |
| 290 | - -- Provenance. A silent model or prompt change is forbidden: when either | |
| 291 | - -- moves, the row moves with it. | |
| 292 | - model TEXT NOT NULL, | |
| 293 | - prompt_version TEXT NOT NULL, | |
| 294 | - variant TEXT NULL, | |
| 295 | - | |
| 296 | - computed_at BIGINT NOT NULL, | |
| 297 | - retain_until BIGINT NOT NULL, | |
| 298 | - | |
| 299 | - CONSTRAINT zeka_question_segment_question PRIMARY KEY (question), | |
| 300 | - CONSTRAINT zeka_question_segment_exam_question_fkey FOREIGN KEY (exam, question) | |
| 301 | - REFERENCES exam_question (exam, id) ON DELETE NO ACTION | |
| 302 | -); | |
| 303 | - | |
| 304 | -CREATE INDEX zeka_question_segment_exam ON zeka_question_segment (exam); | |
| 305 | -CREATE INDEX zeka_question_segment_subject ON zeka_question_segment (subject); | |
| 306 | -CREATE INDEX zeka_question_segment_talep | |
| 307 | - ON zeka_question_segment (course, bilissel_talep); | |
| 308 | -CREATE INDEX zeka_question_segment_retain ON zeka_question_segment (retain_until); | |
| 309 | - | |
| 310 | --- Which dimensions downstream actually uses, and which are experimental (was | |
| 311 | --- two embedded arrays). Kept per row on purpose: when `rubric.py` demotes a | |
| 312 | --- dimension, that a downstream product no longer reads it is legible from the | |
| 313 | --- row itself, with no document to consult. | |
| 314 | -CREATE TABLE zeka_question_segment_dimension ( | |
| 315 | - question uuid NOT NULL | |
| 316 | - REFERENCES zeka_question_segment(question) ON DELETE NO ACTION, | |
| 317 | - dimension TEXT NOT NULL | |
| 318 | - CHECK (dimension IN ('bilissel_talep', 'dikkat_tuzagi', | |
| 319 | - 'okuma_yuku', 'adim_sayisi')), | |
| 320 | - role TEXT NOT NULL CHECK (role IN ('downstream', 'experimental')), | |
| 321 | - ord SMALLINT NOT NULL, | |
| 322 | - CONSTRAINT zeka_question_segment_dimension_question_dimension | |
| 323 | - PRIMARY KEY (question, dimension) | |
| 324 | -); | |
| 325 | - | |
| 326 | - | |
| 327 | --- --------------------------------------------------------------------------- | |
| 328 | --- 5) zeka_student_segment_profile — student x dimension x label | |
| 329 | --- | |
| 330 | --- `contrast` IS WHY THIS TABLE EXISTS. | |
| 331 | --- | |
| 332 | --- Raw `accuracy` is not a discriminating measure: a student's hit rate inside | |
| 333 | --- any segment mostly reflects their GENERAL ability. A strong student scores | |
| 334 | --- high in every segment and a weak one low in every segment, so "this student | |
| 335 | --- struggles with analysis questions" DOES NOT FOLLOW from it. | |
| 336 | --- contrast = accuracy - overall_accuracy | |
| 337 | --- The general level cancels in that difference and what remains is the part | |
| 338 | --- specific to the segment. Recommendation rules fire on `contrast` ONLY, | |
| 339 | --- never on `accuracy`. | |
| 340 | --- | |
| 341 | --- PERSONAL DATA: derived student profile — "term + 1 year", and deleted on | |
| 342 | --- graduation (`Store.purge_departed`). | |
| 343 | --- --------------------------------------------------------------------------- | |
| 344 | -CREATE TABLE zeka_student_segment_profile ( | |
| 345 | - student uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | |
| 346 | - -- PRODUCTION dimensions only. The experimental one is labelled in | |
| 347 | - -- `zeka_question_segment` and stays there; it never reaches a student. | |
| 348 | - dimension TEXT NOT NULL | |
| 349 | - CHECK (dimension IN ('bilissel_talep', 'dikkat_tuzagi', 'okuma_yuku')), | |
| 350 | - label TEXT NOT NULL, | |
| 351 | - | |
| 352 | - n_answers BIGINT NOT NULL, | |
| 353 | - n_correct BIGINT NOT NULL, | |
| 354 | - -- The segment hit rate. NOT SHOWN ALONE and NEVER FIRES A RULE ALONE: it | |
| 355 | - -- carries general ability and has no discriminating power. | |
| 356 | - accuracy DOUBLE PRECISION NOT NULL CHECK (accuracy BETWEEN 0 AND 1), | |
| 357 | - | |
| 358 | - -- The student's hit rate across ALL labelled items — the subtrahend. | |
| 359 | - -- Stored on the row so the evidence panel can show the comparison. | |
| 360 | - overall_n_answers BIGINT NOT NULL, | |
| 361 | - overall_accuracy DOUBLE PRECISION NOT NULL | |
| 362 | - CHECK (overall_accuracy BETWEEN 0 AND 1), | |
| 363 | - -- The honest measure. Negative = behind their OWN general level here. | |
| 364 | - contrast DOUBLE PRECISION NOT NULL CHECK (contrast BETWEEN -1 AND 1), | |
| 365 | - | |
| 366 | - confidence TEXT NOT NULL | |
| 367 | - CHECK (confidence IN ('none', 'exploratory', 'stable')), | |
| 368 | - | |
| 369 | - computed_at BIGINT NOT NULL, | |
| 370 | - retain_until BIGINT NOT NULL, | |
| 371 | - | |
| 372 | - CONSTRAINT zeka_student_segment_profile_key | |
| 373 | - PRIMARY KEY (student, dimension, label), | |
| 374 | - -- n_correct can never exceed n_answers; a row that says otherwise is a | |
| 375 | - -- counting bug, and the cheapest place to catch it is here. | |
| 376 | - CONSTRAINT zeka_student_segment_profile_counts | |
| 377 | - CHECK (n_correct <= n_answers AND n_answers <= overall_n_answers) | |
| 378 | -); | |
| 379 | - | |
| 380 | -CREATE INDEX zeka_student_segment_profile_dimension | |
| 381 | - ON zeka_student_segment_profile (dimension, label); | |
| 382 | -CREATE INDEX zeka_student_segment_profile_retain | |
| 383 | - ON zeka_student_segment_profile (retain_until); |
paket/OKU.mdmodified+53 -108
| @@ -1,146 +1,91 @@ | ||
| 1 | -# Sunucuya gönderilecek paket | |
| 2 | - | |
| 3 | -İki ayrı şey var ve **farklı yerlere** gidiyorlar. Karıştırılırsa biri eksik kalır. | |
| 4 | - | |
| 5 | -> **Bu klasörde depoda duran şey:** `20260916000001_zeka.sql`, iki betik ve bu | |
| 6 | -> belge. SQL veri dosyaları (`pg_school.sql` 101 MB, `pg_control.sql`, | |
| 7 | -> `pg_dogrula.sql`) **gitignore'ludur** — GitHub'ın tek dosya sınırı 100 MB ve | |
| 8 | -> deterministik üretildikleri için depoda tutmanın kazandıracağı bir şey yok: | |
| 9 | -> | |
| 10 | -> ```sh | |
| 11 | -> python generator/main.py --scale full --postgres --out paket/ | |
| 12 | -> ``` | |
| 13 | -> | |
| 14 | -> `migrations/` de depoda değil: backend'in kendi şemasının kopyasıdır ve iki | |
| 15 | -> yerde duran bir şema er ya da geç ayrışır. Yükleyici gerçek checkout'u alır: | |
| 16 | -> | |
| 17 | -> ```sh | |
| 18 | -> BACKEND=/yol/hezarfen_backend-main bash load_pg_seed.sh . | |
| 19 | -> ``` | |
| 1 | +# Sunucuya verilecek paket | |
| 20 | 2 | |
| 21 | ---- | |
| 22 | - | |
| 23 | -## 1. ZEKA'nın tabloları → her okul veritabanına | |
| 3 | +> **Kime:** backend ekibi. Bu klasörde teslim edilen şey artık bir **not**tur: | |
| 4 | +> ZEKA hiçbir şema uygulamaz, hiçbir veritabanı bağlantısı açmaz ve sunucuda | |
| 5 | +> çalıştırılacak bir yükleme betiği **yoktur**. | |
| 24 | 6 | |
| 25 | -`20260916000001_zeka.sql` — dokuz tablo (`zeka_*`). | |
| 26 | - | |
| 27 | -Bu dosya iki yere birden konmalı: | |
| 7 | +--- | |
| 28 | 8 | |
| 29 | -**a) `migrations/school/` klasörüne** — yeni açılacak okullar ve şablon için. | |
| 30 | -Backend ekibi commit edip deploy etmeli. Mevcut dört migration dosyasına | |
| 31 | -**dokunulmuyor**: sqlx bunları sağlama toplamıyla izliyor, birini düzenlemek | |
| 32 | -uygulanmış veritabanlarını kırar. | |
| 9 | +## 1. ZEKA'nın tabloları — backend deposunda | |
| 33 | 10 | |
| 34 | -**b) `apply_zeka_tables.sh` ile mevcut okullara** — çünkü (a) onları kapsamaz. | |
| 11 | +Dokuz `zeka_*` tablosunun DDL'i **backend deposundadır**: | |
| 35 | 12 | |
| 36 | -```sh | |
| 37 | -HEZARFEN_PG_CONTAINER=hezarfen_backend_postgres \ | |
| 38 | -POSTGRES_USER=hezarfen POSTGRES_DB=hezarfen_control \ | |
| 39 | -bash apply_zeka_tables.sh | |
| 13 | +``` | |
| 14 | +hezarfen_backend/migrations/school/20260917000002_zeka.sql | |
| 40 | 15 | ``` |
| 41 | 16 | |
| 42 | -### (b) neden gerekiyor | |
| 43 | - | |
| 44 | -Backend'in kendi kaynağı (`database.rs:126`): | |
| 45 | - | |
| 46 | -> *"The schema is the caller's business — `migrate_school` for a mint, | |
| 47 | -> **nothing for a re-dial of an existing school**."* | |
| 17 | +Hepsi her **okulun kendi veritabanında** durur; şablon ve yeni açılan okullar | |
| 18 | +için `migrate_school` uygular. Dosya mevcut dört okul migration'ına **dokunmaz**: | |
| 19 | +yalnız yeni tablo ve indeks kurar, sqlx bunları sağlama toplamıyla izlediği için | |
| 20 | +birini düzenlemek uygulanmış veritabanlarını kırardı. | |
| 48 | 21 | |
| 49 | -Ve `reconcile_provisioning` yalnız `provisioning` durumundaki okullara bakıyor. | |
| 50 | -Yani sunucuda **zaten duran** bir okul, migration dosyası eklense bile `zeka_*` | |
| 51 | -tablolarını asla kendiliğinden almaz. Betik o boşluğu kapatır. | |
| 22 | +Tabloların sahibi backend'dir: **süpürmeyi ve ayrılan temizliğini de backend | |
| 23 | +koşturur**, çünkü satırlar okulun veritabanındadır. ZEKA yalnız `insight.*` | |
| 24 | +yetenek çağrılarıyla "şu satırları yaz" der. | |
| 52 | 25 | |
| 53 | -Betik yalnız `CREATE TABLE` / `CREATE INDEX` çalıştırır, hiçbir mevcut tabloya | |
| 54 | -dokunmaz, hiçbir satırı değiştirmez. Tabloları zaten olan okulu **atlar**. | |
| 55 | -Okulları control kütüğünden çözer, ad deseninden değil. | |
| 26 | +Tabloların hangisi ne tutar, alan alan: `service/docs/CIKTI-SOZLESMESI.md`. | |
| 56 | 27 | |
| 57 | 28 | --- |
| 58 | 29 | |
| 59 | -## 2. Demo verisi → kendi yeni veritabanına | |
| 30 | +## 2. Demo verisi | |
| 60 | 31 | |
| 61 | -`pg_school.sql` (101 MB) + `pg_control.sql` (150 KB) + `pg_dogrula.sql` | |
| 32 | +Depoda **tohumun kendisi yok, üreticisi var**. Deterministik üretildiği için | |
| 33 | +~170 MB'lık çıktıyı depoda tutmanın kazandıracağı bir şey yok (ve GitHub'ın tek | |
| 34 | +dosya sınırını aşıyor). | |
| 62 | 35 | |
| 63 | 36 | ```sh |
| 64 | -HEZARFEN_PG_CONTAINER=hezarfen_backend_postgres \ | |
| 65 | -POSTGRES_USER=hezarfen POSTGRES_DB=hezarfen_control \ | |
| 66 | -bash load_pg_seed.sh . | |
| 37 | +python generator/main.py --scale full --out /tmp/seed | |
| 67 | 38 | ``` |
| 68 | 39 | |
| 69 | -Ne yapar: | |
| 70 | - | |
| 71 | -1. Okul veritabanını backend'in **kendi** adlandırma kuralıyla kurar | |
| 72 | - (`tenant.rs:112` → `{control}_school_{uuid.simple}`) | |
| 73 | -2. `migrations/` içindeki şemayı uygular (ZEKA'nınki dahil) | |
| 74 | -3. `pg_school.sql`'i döker — 576.487 satır | |
| 75 | -4. **48 bütünlük denetimini koşturur**; bir tanesi bile ihlal bulursa orada durur | |
| 76 | -5. Control kaydını **en sona** yazar | |
| 77 | - | |
| 78 | -(5) bilinçli: backend okulu `active` görür görmez istek kabul etmeye başlıyor, | |
| 79 | -veri hazır olmadan kaydı yazmak yarım bir okul açmak olurdu. | |
| 80 | - | |
| 81 | -### Demo okulu | |
| 40 | +Üretilen: demo okulunun bütün veri seti, tablo başına satır sayısıyla | |
| 41 | +`MANIFEST.json`, gizli gerçeği taşıyan `_seed_manifest.json` ve 48 bütünlük | |
| 42 | +sorgusu. **Yüklemesi backend ekibinin işidir.** | |
| 82 | 43 | |
| 83 | 44 | | | | |
| 84 | 45 | |---|---| |
| 85 | 46 | | slug | `hezarfen-demo` | |
| 86 | 47 | | uuid | `01930000-0000-7000-8000-00000000de70` | |
| 87 | -| öğrenci | 250 (563 kullanıcı) | | |
| 88 | -| kapsam | 2025-09-07 → 2026-04-13, 27 öğretim haftası | | |
| 89 | -| satır | okul 576.487, control 1.148 | | |
| 90 | - | |
| 91 | -**Mevcut okullara dokunmaz.** Kendi veritabanını kurar, control'e bir satır | |
| 92 | -ekler. Okul kaydı slug ile çakışırsa `DO NOTHING` — üzerine yazmaz. | |
| 93 | - | |
| 94 | ---- | |
| 95 | - | |
| 96 | -## Giriş | |
| 48 | +| öğrenci | 250 (563 kullanıcı: + 24 öğretmen, 285 veli, 4 yönetici) | | |
| 49 | +| kapsam | 2025-09-07 → 2026-04-13 (217 gün, 27 öğretim haftası) | | |
| 50 | +| modüller | 21'inin tamamı açık | | |
| 97 | 51 | |
| 98 | -Yeni backend'de parola okul veritabanında **değil**, control'deki `person` | |
| 99 | -satırında: `person` → `person_school` → `app_user.person`. | |
| 52 | +Ayrı bir okuldur; başka bir okulun verisine dokunmaz. | |
| 100 | 53 | |
| 101 | -Tohum bu zinciri kuruyor (563 `person`, 563 `person_school`). Kurulmasaydı veri | |
| 102 | -görünür, sistem kullanılamaz olurdu. | |
| 54 | +### uuid neden sabit | |
| 103 | 55 | |
| 104 | -`person_school.school` bir alt sorgudur (`SELECT id FROM school WHERE slug=...`), | |
| 105 | -sabit uuid değil — okulu backend yaratmış olsa bile üyelik doğru okula bağlanır. | |
| 56 | +Okul veritabanının **adı slug'dan değil uuid'den** türer (`tenant.rs:112` — | |
| 57 | +`"{control}_school_{uuid.simple}"`). Yani tohumu hangi veritabanına | |
| 58 | +yazacağımızı, backend okulu yaratmadan önce bilmemiz gerekiyor. Sabit uuid bunu | |
| 59 | +mümkün kılar. | |
| 106 | 60 | |
| 107 | 61 | --- |
| 108 | 62 | |
| 109 | -## Sıra | |
| 110 | - | |
| 111 | -```sh | |
| 112 | -# 0) YEDEK — önce | |
| 113 | -~/hezarfen_backend/backup-postgres.sh | |
| 114 | - | |
| 115 | -# 1) mevcut okullara ZEKA tabloları | |
| 116 | -bash apply_zeka_tables.sh | |
| 63 | +## 3. Giriş zinciri | |
| 117 | 64 | |
| 118 | -# 2) demo verisi | |
| 119 | -bash load_pg_seed.sh . | |
| 65 | +Parola okul veritabanında **değil**, control'deki `person` satırındadır: | |
| 120 | 66 | |
| 121 | -# 3) migration dosyasını backend deposuna commit et (yeni okullar için) | |
| 67 | +``` | |
| 68 | +person → person_school → app_user.person | |
| 122 | 69 | ``` |
| 123 | 70 | |
| 124 | -Adım 1 ve 2 birbirinden bağımsız; sırası önemli değil. Adım 3 backend ekibinin. | |
| 125 | - | |
| 126 | ---- | |
| 71 | +Tohum bu zinciri kurar: 563 `person`, 563 `person_school` ve her `app_user` | |
| 72 | +satırında dolu bir `person` alanı. Ölçüldü: **563/563 eşleşiyor.** Bu | |
| 73 | +kurulmasaydı veri görünür, sistem kullanılamaz olurdu. | |
| 127 | 74 | |
| 128 | -## Bilinmesi gerekenler | |
| 75 | +`person_school.school` bir alt sorgudur (`SELECT id FROM school WHERE slug=...`), | |
| 76 | +sabit uuid değil — okulu backend yaratmış olsa bile üyelik doğru okula bağlanır. | |
| 129 | 77 | |
| 130 | -**Yükleme tekrarlanamaz.** Birincil anahtarlar deterministik; ikinci çalıştırma | |
| 131 | -çakışır ve hiçbir şey yazmaz. Yeniden yüklemek için okul veritabanını düşürmek | |
| 132 | -gerekir. Demo için doğru davranış, ama "bir daha çalıştırayım" refleksi işe | |
| 133 | -yaramaz. | |
| 78 | +--- | |
| 134 | 79 | |
| 135 | -**Yüklenen okulda `_sqlx_migrations` tablosu yok.** Şemayı elle uyguladığımız | |
| 136 | -için. Bugün zararsız: backend aktif bir okulu yeniden migrate etmiyor. İleride | |
| 137 | -bu davranış değişirse o okul "relation already exists" ile düşer — sessiz | |
| 138 | -değil, gürültülü bir hata. | |
| 80 | +## 4. Bilinmesi gerekenler | |
| 139 | 81 | |
| 140 | -**Beş zaman damgası yaklaşık.** Yeni şemanın eklediği, tohumda karşılığı olmayan | |
| 141 | -kolonlar ilgili kaydın ULID damgasından türetiliyor. `exam_result.graded_at` | |
| 82 | +**Beş zaman damgası yaklaşıktır.** Yeni şemanın eklediği ve tohumda karşılığı | |
| 83 | +olmayan kolonlar, ilgili kaydın ULID damgasından türetilir. `exam_result.graded_at` | |
| 142 | 84 | özellikle: **"notlandırma gecikmesi" gibi bir ölçüm için kullanılamaz.** |
| 143 | -Ayrıntısı `generator/pg_map.DERIVED_COLUMNS` içinde. ZEKA hiçbirini okumuyor. | |
| 85 | +ZEKA hiçbirini okumaz — köprü izin listesinde o yollar yoktur. | |
| 144 | 86 | |
| 145 | -**ZEKA servisinin veritabanı kullanıcısı** üretimde yalnız dokuz `zeka_*` | |
| 146 | -tablosuna yazma, kalanına salt okuma yetkisine daraltılmalı. | |
| 87 | +**Bir kapı açık kalıyor:** `insight.*` yetenek kapıları backend'de henüz | |
| 88 | +tanımlı değildir. Servis kendi takvimivle koşar, satırlarını yazmayı bu | |
| 89 | +kapılardan ister ve kapılar gelene kadar koşuyu `partial` yazar. Gereksinim | |
| 90 | +listesi: `service/docs/BACKEND-GEREKSINIMLERI.md`, sahibi backend'deki | |
| 91 | +`InsightDoors` hattı. |
paket/apply_zeka_tables.shdeleted+0 -77
| @@ -1,77 +0,0 @@ | ||
| 1 | -#!/usr/bin/env bash | |
| 2 | -# ZEKA'nin dokuz tablosunu MEVCUT okul veritabanlarina ekler. | |
| 3 | -# | |
| 4 | -# NEDEN AYRI BIR BETIK GEREKIYOR | |
| 5 | -# ------------------------------ | |
| 6 | -# Migration dosyasini `migrations/school/` altina koymak yeni okullari ve | |
| 7 | -# sablonu kapsar; HALIHAZIRDA DURAN okullari kapsamaz. Backend'in kendi | |
| 8 | -# kaynagi bunu acikca soyluyor (`database.rs:126`): | |
| 9 | -# | |
| 10 | -# "The schema is the caller's business — migrate_school for a mint, | |
| 11 | -# nothing for a re-dial of an existing school." | |
| 12 | -# | |
| 13 | -# Ve `reconcile_provisioning` yalnizca `provisioning` durumundaki okullara | |
| 14 | -# bakar. Yani sunucuda zaten duran bir okul, dosya eklense bile `zeka_*` | |
| 15 | -# tablolarini ASLA kendiliginden almaz. Bu betik o bosluğu kapatir. | |
| 16 | -# | |
| 17 | -# GUVENLI: yalnizca `CREATE TABLE`/`CREATE INDEX` calistirir, hicbir mevcut | |
| 18 | -# tabloya dokunmaz, hicbir satiri degistirmez. Tablolari zaten olan bir okulu | |
| 19 | -# ATLAR, ikinci kez uygulamaya calismaz. | |
| 20 | -# | |
| 21 | -# tools/apply_zeka_tables.sh [migration-dosyasi] | |
| 22 | -# | |
| 23 | -# Ortam: HEZARFEN_PG_CONTAINER, POSTGRES_USER, POSTGRES_DB (control) | |
| 24 | -set -euo pipefail | |
| 25 | - | |
| 26 | -HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" | |
| 27 | -DDL="${1:-$HERE/service/schema/postgres/school/20260916000001_zeka.sql}" | |
| 28 | -CONTAINER="${HEZARFEN_PG_CONTAINER:-hezarfen_backend_postgres}" | |
| 29 | -PGUSER_="${POSTGRES_USER:-hezarfen}" | |
| 30 | -CONTROL_DB="${POSTGRES_DB:-hezarfen_control}" | |
| 31 | - | |
| 32 | -[ -f "$DDL" ] || { echo "!! migration dosyasi yok: $DDL"; exit 1; } | |
| 33 | - | |
| 34 | -psql() { podman exec -i "$CONTAINER" psql -U "$PGUSER_" -v ON_ERROR_STOP=1 "$@"; } | |
| 35 | - | |
| 36 | -echo "== control: $CONTROL_DB" | |
| 37 | -echo "== ddl : $(basename "$DDL")" | |
| 38 | -echo | |
| 39 | - | |
| 40 | -# Okul veritabanlarini control'deki kutukten cozuyoruz, ad deseninden DEGIL: | |
| 41 | -# ad uuid'den turuyor ve desene guvenmek, kutukte olmayan bir veritabanina | |
| 42 | -# yazmak demek olabilirdi. | |
| 43 | -okullar="$(psql -d "$CONTROL_DB" -tAc \ | |
| 44 | - "SELECT '${CONTROL_DB}_school_' || replace(id::text, '-', '') || '|' || slug | |
| 45 | - FROM school ORDER BY created_at")" | |
| 46 | - | |
| 47 | -[ -n "$okullar" ] || { echo "kutukte okul yok — yapilacak bir sey yok"; exit 0; } | |
| 48 | - | |
| 49 | -eklendi=0 | |
| 50 | -atlandi=0 | |
| 51 | -while IFS='|' read -r db slug; do | |
| 52 | - [ -n "$db" ] || continue | |
| 53 | - var="$(psql -d "$CONTROL_DB" -tAc \ | |
| 54 | - "SELECT count(*) FROM pg_database WHERE datname='$db'")" | |
| 55 | - if [ "$var" = "0" ]; then | |
| 56 | - echo " $slug: veritabani yok ($db) — atlandi" | |
| 57 | - atlandi=$((atlandi + 1)) | |
| 58 | - continue | |
| 59 | - fi | |
| 60 | - zaten="$(psql -d "$db" -tAc \ | |
| 61 | - "SELECT count(*) FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace | |
| 62 | - WHERE n.nspname='public' AND c.relkind='r' AND c.relname LIKE 'zeka\\_%'")" | |
| 63 | - if [ "$zaten" != "0" ]; then | |
| 64 | - echo " $slug: $zaten zeka_ tablosu zaten var — atlandi" | |
| 65 | - atlandi=$((atlandi + 1)) | |
| 66 | - continue | |
| 67 | - fi | |
| 68 | - psql -d "$db" -q -f - < "$DDL" | |
| 69 | - say="$(psql -d "$db" -tAc \ | |
| 70 | - "SELECT count(*) FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace | |
| 71 | - WHERE n.nspname='public' AND c.relkind='r' AND c.relname LIKE 'zeka\\_%'")" | |
| 72 | - echo " $slug: $say tablo eklendi" | |
| 73 | - eklendi=$((eklendi + 1)) | |
| 74 | -done <<< "$okullar" | |
| 75 | - | |
| 76 | -echo | |
| 77 | -echo "== $eklendi okula eklendi, $atlandi atlandi" |
paket/load_pg_seed.shdeleted+0 -88
| @@ -1,88 +0,0 @@ | ||
| 1 | -#!/usr/bin/env bash | |
| 2 | -# DEMO tohumunu yeni (PostgreSQL) backend'e yukler. | |
| 3 | -# | |
| 4 | -# Ne yapar: | |
| 5 | -# 1. Okul veritabanini backend'in KENDI adlandirma kuraliyla kurar | |
| 6 | -# (`tenant::school_db_name` -> "{control}_school_{uuid.simple}") | |
| 7 | -# 2. Backend'in `migrations/school` semasini + ZEKA'nin migration'ini uygular | |
| 8 | -# 3. `pg_school.sql`'i doker | |
| 9 | -# 4. Control veritabanina okul kaydini ve kisi satirlarini yazar | |
| 10 | -# | |
| 11 | -# Neden bu sira: okul veritabaninin ADI okulun uuid'sinden tureniyor, slug'dan | |
| 12 | -# degil. Yani uuid onceden bilinmek zorunda; tohum onu sabitliyor | |
| 13 | -# (`generator/pg_map.DEMO_SCHOOL_ID`). Control satiri EN SONA birakiliyor: | |
| 14 | -# backend acilir acilmaz okulu `active` gorup istek kabul etmeye baslar, o | |
| 15 | -# yuzden okul verisi hazir olmadan kaydi yazmak yarim bir okul acmak olurdu. | |
| 16 | -# | |
| 17 | -# Tohumu iki kez yuklemek: her iki dosya da tek transaction'da kosar ve | |
| 18 | -# birincil anahtarlar deterministiktir, yani ikinci yukleme catisma verir ve | |
| 19 | -# HICBIR SEY yazmaz. Yeniden yuklemek icin veritabanini dusurmek gerekir. | |
| 20 | -# | |
| 21 | -# tools/load_pg_seed.sh /yol/pgseed | |
| 22 | -# | |
| 23 | -# Ortam: | |
| 24 | -# PGC psql'i kosturan komut (varsayilan: podman exec -i <konteyner> psql) | |
| 25 | -# CONTROL_DB control veritabani adi (varsayilan hezarfen_control) | |
| 26 | -# BACKEND yeni backend checkout'u | |
| 27 | -set -euo pipefail | |
| 28 | - | |
| 29 | -SEED_DIR="${1:-}" | |
| 30 | -[ -n "$SEED_DIR" ] || { echo "kullanim: $0 <tohum-dizini>"; exit 1; } | |
| 31 | - | |
| 32 | -# Canlida konteyner adi `hezarfen_backend_postgres`, kullanici ve control | |
| 33 | -# veritabani adi `hezarfen_backend.env` icindeki POSTGRES_USER / POSTGRES_DB | |
| 34 | -# ile ayni olmali. Uctaki degerler gelistirme icindir. | |
| 35 | -CONTAINER="${HEZARFEN_PG_CONTAINER:-zeka_pg}" | |
| 36 | -PGUSER_="${POSTGRES_USER:-hezarfen}" | |
| 37 | -CONTROL_DB="${CONTROL_DB:-${POSTGRES_DB:-hezarfen_control}}" | |
| 38 | -HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" | |
| 39 | -BACKEND="${BACKEND:-$HERE/../hezarfen_backend-main-yeni/hezarfen_backend-main}" | |
| 40 | - | |
| 41 | -# Tohumun sabitledigi okul kimligi — tek kaynak `generator/pg_map.py`. | |
| 42 | -SCHOOL_ID="$(cd "$HERE/generator" && python -c "import pg_map;print(pg_map.DEMO_SCHOOL_ID)")" | |
| 43 | -SCHOOL_DB="${CONTROL_DB}_school_$(echo "$SCHOOL_ID" | tr -d '-')" | |
| 44 | - | |
| 45 | -psql() { podman exec -i "$CONTAINER" psql -U "$PGUSER_" -v ON_ERROR_STOP=1 "$@"; } | |
| 46 | - | |
| 47 | -echo "== okul : $SCHOOL_ID" | |
| 48 | -echo "== okul db: $SCHOOL_DB" | |
| 49 | -echo "== control: $CONTROL_DB" | |
| 50 | - | |
| 51 | -psql -d postgres -q <<SQL | |
| 52 | -SELECT 'control var' WHERE EXISTS (SELECT 1 FROM pg_database WHERE datname='$CONTROL_DB'); | |
| 53 | -SQL | |
| 54 | -psql -d postgres -q -c "CREATE DATABASE $CONTROL_DB" 2>/dev/null || echo " (control zaten var)" | |
| 55 | -psql -d postgres -q -c "CREATE DATABASE $SCHOOL_DB" | |
| 56 | - | |
| 57 | -echo "== control semasi" | |
| 58 | -for f in "$BACKEND"/migrations/control/*.sql; do psql -d "$CONTROL_DB" -q -f - < "$f" 2>/dev/null || true; done | |
| 59 | - | |
| 60 | -echo "== okul semasi (+ ZEKA)" | |
| 61 | -for f in "$BACKEND"/migrations/school/*.sql; do | |
| 62 | - echo " $(basename "$f")" | |
| 63 | - psql -d "$SCHOOL_DB" -q -f - < "$f" | |
| 64 | -done | |
| 65 | - | |
| 66 | -echo "== okul verisi" | |
| 67 | -podman cp "$SEED_DIR/pg_school.sql" "$CONTAINER:/tmp/pg_school.sql" | |
| 68 | -podman exec "$CONTAINER" psql -U "$PGUSER_" -d "$SCHOOL_DB" -q -v ON_ERROR_STOP=1 -f /tmp/pg_school.sql | |
| 69 | - | |
| 70 | -echo "== control verisi (okul kaydi EN SON)" | |
| 71 | -psql -d "$CONTROL_DB" -q -f - < "$SEED_DIR/pg_control.sql" | |
| 72 | - | |
| 73 | -echo "== butunluk sinavi (48 denetim)" | |
| 74 | -if [ -f "$SEED_DIR/pg_dogrula.sql" ]; then | |
| 75 | - podman cp "$SEED_DIR/pg_dogrula.sql" "$CONTAINER:/tmp/pg_dogrula.sql" | |
| 76 | - # ON_ERROR_STOP: bir denetim ihlal bulursa betik burada duser. Yuklendi | |
| 77 | - # deyip bozuk veriyle devam etmek, hic yuklememekten kotudur. | |
| 78 | - podman exec "$CONTAINER" psql -U "$PGUSER_" -d "$SCHOOL_DB" -q -v ON_ERROR_STOP=1 -f /tmp/pg_dogrula.sql | |
| 79 | -else | |
| 80 | - echo " !! pg_dogrula.sql yok — tohum --postgres ile uretilmemis" | |
| 81 | - exit 1 | |
| 82 | -fi | |
| 83 | - | |
| 84 | -echo | |
| 85 | -echo "== satir sayilari" | |
| 86 | -psql -d "$SCHOOL_DB" -tAc "SELECT 'okul: ' || sum(n_live_tup) FROM pg_stat_user_tables;" | |
| 87 | -psql -d "$CONTROL_DB" -tAc "SELECT 'control: ' || sum(n_live_tup) FROM pg_stat_user_tables;" | |
| 88 | -echo "== bitti" |
scripts/ci-compose.shmodified+47 -18
| @@ -1,14 +1,15 @@ | ||
| 1 | 1 | #!/usr/bin/env bash |
| 2 | 2 | # COMPOSE DENETIMI -- yapilandirmanin gecerli VE guvenli oldugunu dogrular. |
| 3 | 3 | # |
| 4 | -# Uc sey denetlenir ve UCU DE cift yonludur; yalnizca "gecerli mi" diye | |
| 4 | +# Dort sey denetlenir ve DORDU DE cift yonludur; yalnizca "gecerli mi" diye | |
| 5 | 5 | # sormak, asil kusurlari kacirir: |
| 6 | 6 | # |
| 7 | -# 1. Zorunlu sirlar gercekten zorunlu mu? (AI_SHARED_TOKEN, LLM_API_KEY, | |
| 8 | -# ZEKA_PG_DSN -- tam liste compose.yaml'da.) | |
| 9 | -# `${VAR:?}` yerine `${VAR:-}` yazilirsa compose yine gecerli olur ama | |
| 10 | -# servis bos bir token'la ayaga kalkar ve backend'e kaydolamaz. Bu | |
| 11 | -# yuzden env YOKKEN `config`in PATLAMASINI da sinariz. | |
| 7 | +# 1. Zorunlu sirlar gercekten zorunlu mu? LISTE compose.yaml'DAN OKUNUR | |
| 8 | +# (`${VAR:?}` ile gecen her degisken). `${VAR:?}` yerine `${VAR:-}` | |
| 9 | +# yazilirsa compose yine gecerli olur ama servis bos bir token'la ayaga | |
| 10 | +# kalkar ve backend'e kaydolamaz. Bu yuzden env YOKKEN `config`in | |
| 11 | +# PATLAMASINI da sinariz. Liste elle yazilmaz: sir ekleyen kisi bu | |
| 12 | +# betigi de guncellemek zorunda kalmasin (bu tam olarak bir kez yasandi). | |
| 12 | 13 | # |
| 13 | 14 | # 2. Port aciliyor mu? ACILMAMALI. ZEKA backend'in QUIC'ine DIAL-OUT eden |
| 14 | 15 | # bir istemcidir (`ai/protocol.rs:3-7`); port acmak NAT ardinda |
| @@ -16,6 +17,12 @@ | ||
| 16 | 17 | # |
| 17 | 18 | # 3. Ag adi parametrik mi? Kardes serviste sabit yazildigi icin ag baska |
| 18 | 19 | # bir adla kuruldugunda compose patliyordu. |
| 20 | +# | |
| 21 | +# 4. VERITABANI IZI YOK MU? ZEKA uygulama veritabanina ULASMAZ (daimi | |
| 22 | +# kural): ne bir DSN, ne bir veritabani parolasi. Ayrica | |
| 23 | +# `env_file:` de YASAK -- operator ayarlari ORTAMDAN gelir; deploy | |
| 24 | +# tarafi TEK bir `--env-file` (stack.env) verir ve bu saglayicida ikinci | |
| 25 | +# dosya zaten sessizce duser (podman_compose.py:2941-2946, :2559). | |
| 19 | 26 | |
| 20 | 27 | set -uo pipefail |
| 21 | 28 | |
| @@ -38,23 +45,30 @@ HATA=0 | ||
| 38 | 45 | gec() { echo " [ok] $1"; } |
| 39 | 46 | kal() { echo " [HATA] $1"; HATA=1; } |
| 40 | 47 | |
| 48 | +# --- zorunlu sirlar: LISTE compose.yaml'DAN OKUNUR ------------------------- | |
| 49 | +mapfile -t SIRLAR < <( | |
| 50 | + grep -oE '\$\{[A-Za-z_][A-Za-z0-9_]*:\?' compose.yaml \ | |
| 51 | + | sed -E 's/^\$\{//; s/:\?$//' | sort -u | |
| 52 | +) | |
| 53 | +if [ "${#SIRLAR[@]}" -eq 0 ]; then | |
| 54 | + kal "compose.yaml hicbir sirri \${VAR:?} ile zorunlu tutmuyor" | |
| 55 | +fi | |
| 56 | + | |
| 57 | +EKSIK=() | |
| 58 | +for degisken in "${SIRLAR[@]}"; do EKSIK+=(-u "$degisken"); done | |
| 59 | + | |
| 41 | 60 | # --- 1a. zorunlu env EKSIKKEN patlamali ----------------------------------- |
| 42 | -# ZORUNLU SIRLAR LISTESI compose.yaml'DAN OKUNUR -- su an uctur | |
| 43 | -# (AI_SHARED_TOKEN, LLM_API_KEY, ZEKA_PG_DSN). Ucuncusu eklendiginde bu | |
| 44 | -# betik ve `ci.yml`'in konteyner katmani iki sirla kalmis, ikisi de "sirlar | |
| 45 | -# verilse bile patliyor" diyerek KIRMIZI kalmisti. Sir eklerseniz bu listeyi | |
| 46 | -# ve ci.yml/main.yml adimini BIRLIKTE guncelleyin. | |
| 47 | -if env -u AI_SHARED_TOKEN -u LLM_API_KEY -u ZEKA_PG_DSN \ | |
| 48 | - "${COMPOSE[@]}" config >/dev/null 2>&1; then | |
| 61 | +if env "${EKSIK[@]}" "${COMPOSE[@]}" config >/dev/null 2>&1; then | |
| 49 | 62 | kal "zorunlu sirlar olmadan gecti -- \${VAR:?} yerine \${VAR:-} yazilmis olabilir" |
| 50 | 63 | else |
| 51 | - gec "zorunlu sirlar olmadan REDDEDILDI (AI_SHARED_TOKEN / LLM_API_KEY / ZEKA_PG_DSN)" | |
| 64 | + gec "zorunlu sirlar olmadan REDDEDILDI (${SIRLAR[*]})" | |
| 52 | 65 | fi |
| 53 | 66 | |
| 54 | 67 | # --- 1b. zorunlu env VARKEN gecerli olmali -------------------------------- |
| 55 | -ZORUNLU_ENV=(AI_SHARED_TOKEN=ci-sahte LLM_API_KEY=ci-sahte ZEKA_PG_DSN=postgres://ci:ci@127.0.0.1:5432/ci) | |
| 56 | -CIKTI="$(env "${ZORUNLU_ENV[@]}" "${COMPOSE[@]}" config 2>&1)" | |
| 57 | -if [ $? -ne 0 ]; then | |
| 68 | +DOLU=() | |
| 69 | +for degisken in "${SIRLAR[@]}"; do DOLU+=("$degisken=ci-sahte"); done | |
| 70 | + | |
| 71 | +if ! CIKTI="$(env "${DOLU[@]}" "${COMPOSE[@]}" config 2>&1)"; then | |
| 58 | 72 | kal "zorunlu sirlar verildiginde bile config basarisiz:" |
| 59 | 73 | echo "$CIKTI" | tail -10 |
| 60 | 74 | exit 1 |
| @@ -75,7 +89,7 @@ if grep -q 'name: ${HEZARFEN_NET:-' compose.yaml; then | ||
| 75 | 89 | # degisir (podman-compose `external`i `name`den ONCE basar). Ilk surum |
| 76 | 90 | # `grep -A2 '^networks:'` ile pencere aciyordu ve ad satirini kacirip HATA |
| 77 | 91 | # veriyordu -- probe'un kendisi yanlisti, yapilandirma degil. |
| 78 | - OZEL="$(env HEZARFEN_NET=baska_ag "${ZORUNLU_ENV[@]}" "${COMPOSE[@]}" config 2>/dev/null \ | |
| 92 | + OZEL="$(env HEZARFEN_NET=baska_ag "${DOLU[@]}" "${COMPOSE[@]}" config 2>/dev/null \ | |
| 79 | 93 | | grep -E '^[[:space:]]+name:[[:space:]]*baska_ag[[:space:]]*$' | head -1)" |
| 80 | 94 | if [ -n "$OZEL" ]; then |
| 81 | 95 | gec "HEZARFEN_NET gecersiz kilinabiliyor (test: baska_ag ->$OZEL)" |
| @@ -86,6 +100,21 @@ else | ||
| 86 | 100 | kal "dis ag adi SABIT yazilmis; dagitimdan dagitima kirilir" |
| 87 | 101 | fi |
| 88 | 102 | |
| 103 | +# --- 4a. veritabani izi yok ------------------------------------------------ | |
| 104 | +# Adlar yazilmaz, DESEN aranir: hangi DSN/parola adiyla gelirse gelsin yakalanir. | |
| 105 | +if grep -nEi 'postgres|PG_DSN|_DB_DSN|ZEKA_DB' compose.yaml; then | |
| 106 | + kal "compose.yaml'da veritabani izi var; ZEKA uygulama veritabanina ULASMAZ" | |
| 107 | +else | |
| 108 | + gec "compose.yaml'da DSN/parola izi yok (kopru deposu)" | |
| 109 | +fi | |
| 110 | + | |
| 111 | +# --- 4b. `env_file:` yok: operator ayarlari TEK kanaldan -------------------- | |
| 112 | +if grep -qE '^[[:space:]]+env_file:' compose.yaml; then | |
| 113 | + kal "compose env_file: kullaniyor; operator ayarlari ORTAMDAN gelmeli (deploy TEK --env-file verir)" | |
| 114 | +else | |
| 115 | + gec "compose env_file: kullanmiyor (ayarlar ortamdan, tek --env-file deploy tarafinda)" | |
| 116 | +fi | |
| 117 | + | |
| 89 | 118 | echo "" |
| 90 | 119 | [ "$HATA" -eq 0 ] && echo "COMPOSE DENETIMI GECTI" || echo "COMPOSE DENETIMI BASARISIZ" |
| 91 | 120 | exit "$HATA" |
scripts/ci-konteyner-kanit.shmodified+49 -138
| @@ -6,31 +6,27 @@ | ||
| 6 | 6 | # `restart: unless-stopped` ile sonsuz bir crash-loop'a giriyordu. "Derlendi" |
| 7 | 7 | # demek "kosuyor" demek DEGILDIR. Bu betik farki olcer. |
| 8 | 8 | # |
| 9 | -# Dogrulanan bes sey: | |
| 10 | -# 1. Kap backend YOKKEN de CIKMIYOR (geri cekilerek yeniden deniyor). | |
| 11 | -# 1b. Kap ZORUNLU UC ORTAM DEGISKENIYLE gercekten ACILIYOR ve depo baglantisi | |
| 12 | -# kuruluyor (bkz. asagidaki "neden gercek Postgres"). | |
| 13 | -# 2. Geri cekilme gercekten USTEL: bekleme suresi buyuyor. | |
| 14 | -# 3. Surec NON-ROOT (uid 10002) kosuyor. | |
| 15 | -# 4. Saglik kontrolu HEM gecer (kopru yasarken) HEM kalir (kopru yokken). | |
| 16 | -# | |
| 17 | 9 | # --------------------------------------------------------------------------- |
| 18 | -# NEDEN GERCEK POSTGRES (ve bir adet YEREL AG) | |
| 10 | +# NEDEN VERITABANI YOK (ve bu neden kanitin KENDISI) | |
| 19 | 11 | # --------------------------------------------------------------------------- |
| 20 | -# Bu betik bir zamanlar kabi YALNIZCA `AI_*` ile kaldiriyordu. `compose.yaml` | |
| 21 | -# ise uc sirri `${VAR:?}` ile ZORUNLU tutar (AI_SHARED_TOKEN, ZEKA_PG_DSN, | |
| 22 | -# DEEPSEEK_API_KEY) ve servis acilista `open_store()` cagirir: DSN yoksa | |
| 23 | -# `RuntimeError` ile CIKAR. Sonuc: kap hemen oluyor, ardindan gelen HER | |
| 24 | -# iddia -- uid, geri cekilme, saglik kontrolu -- bosluga dusuyordu ve | |
| 25 | -# yalnizca "kopru yokken kontrol kalir" gecip (o da hicbir sey kosmadigi icin) | |
| 26 | -# kirmizi bir kanit uretiyordu. Iki surumde de ayni imza: | |
| 27 | -# RuntimeError: Ne ZEKA_PG_DSN ne ZEKA_DB_HTTP_URL tanimli... | |
| 12 | +# Bu betik bir zamanlar kabi ayaga kaldirmak icin GERCEK bir Postgres kurardi: | |
| 13 | +# o zamanki servis acilista bir depo baglantisi aciyor ve adressiz kalirsa | |
| 14 | +# `RuntimeError` ile CIKIYORDU. O yol KALDIRILDI. ZEKA uygulama veritabanina | |
| 15 | +# ulasmaz (daimi kural): tek bagimliligi backend'in QUIC kopruSÜ. Backend | |
| 16 | +# YOKKEN dogru davranis cokmek degil, geri cekilerek yeniden denemektir. | |
| 28 | 17 | # |
| 29 | -# DUZ METIN BIR DSN YETMEZ: sahte ama ULASILAMAZ bir DSN de ayni yerde patlar | |
| 30 | -# (psycopg baglanamaz). Bu yuzden kanit gercek bir Postgres kaldirir, kendi | |
| 31 | -# agina koyar ve kaba ULASILABILIR bir DSN verir. Boylece kanit, servisin | |
| 32 | -# URETIMDEKI acilis yolunu (depo acilisi + zamanlayici) olcer; "env'i gectim, | |
| 33 | -# calisti sayilir" demez. | |
| 18 | +# Bu yuzden kanit artik HICBIR DSN VERMEZ. Kabin acilmasi ve ayakta kalmasi | |
| 19 | +# basli basina "veritabani gerekmiyor" iddiasinin olcumudur: eksik bir | |
| 20 | +# zorunlu veritabani degiskeni olsaydi surec daha kopru dongusu baslamadan | |
| 21 | +# cikardi ve asagidaki iddialarin HEPSI bosluga dusardi. | |
| 22 | +# | |
| 23 | +# Dogrulanan bes sey: | |
| 24 | +# 1. Kap backend YOKKEN de ACILIYOR ve CIKMIYOR (geri cekilerek yeniden | |
| 25 | +# deniyor) -- hicbir veritabani ortam degiskeni verilmeden. | |
| 26 | +# 2. Geri cekilme gercekten USTEL: bekleme suresi buyuyor. | |
| 27 | +# 3. Saglik kontrolu HEM gecer (kopru yasarken) HEM kalir (kopru yokken). | |
| 28 | +# 4. Surec NON-ROOT (uid 10002) kosuyor. | |
| 29 | +# 5. Kab sinirli bir pencere boyunca AYAKTA kaliyor. | |
| 34 | 30 | # |
| 35 | 31 | # Kullanim: scripts/ci-konteyner-kanit.sh [podman|docker] [imaj] |
| 36 | 32 | |
| @@ -39,10 +35,6 @@ set -uo pipefail | ||
| 39 | 35 | MOTOR="${1:-podman}" |
| 40 | 36 | IMAJ="${2:-hezarfen-zeka:ci}" |
| 41 | 37 | KAP="zeka-ci-kanit-$$" |
| 42 | -PG_KAP="zeka-ci-pg-$$" | |
| 43 | -AG="zeka-ci-ag-$$" | |
| 44 | -# Aile imaji: backend compose'u da bunu kullaniyor (compose.yaml:20). | |
| 45 | -PG_IMAJ="${PG_IMAJ:-docker.io/library/postgres:18-alpine}" | |
| 46 | 38 | GOZLEM_SANIYE="${GOZLEM_SANIYE:-50}" |
| 47 | 39 | # 50 sn: bir yeniden deneme turu, cozulemeyen DNS'in kendi zaman asimini da |
| 48 | 40 | # (config.CERT_FETCH_TIMEOUT_SECS = 10 sn) icerir. 30 sn ile olculdu ve |
| @@ -54,58 +46,24 @@ gec() { echo " [ok] $1"; } | ||
| 54 | 46 | kal() { echo " [HATA] $1"; HATA=1; } |
| 55 | 47 | |
| 56 | 48 | temizle() { |
| 57 | - "$MOTOR" rm -f "$KAP" >/dev/null 2>&1 || true | |
| 58 | - "$MOTOR" rm -f "$PG_KAP" >/dev/null 2>&1 || true | |
| 59 | - "$MOTOR" network rm "$AG" >/dev/null 2>&1 || true | |
| 49 | + MSYS_NO_PATHCONV=1 "$MOTOR" rm -f "$KAP" >/dev/null 2>&1 || true | |
| 60 | 50 | } |
| 61 | 51 | trap temizle EXIT |
| 62 | 52 | |
| 63 | 53 | echo "konteyner kosu kaniti: motor=$MOTOR imaj=$IMAJ" |
| 64 | 54 | |
| 65 | -# --- 0. gercek Postgres: zorunlu env'in ve acilis yolunun ta kendisi -------- | |
| 66 | -MSYS_NO_PATHCONV=1 "$MOTOR" network create "$AG" >/dev/null 2>&1 \ | |
| 67 | - || { echo " [HATA] kanit agi kurulamadi ($AG)"; exit 1; } | |
| 68 | -MSYS_NO_PATHCONV=1 "$MOTOR" run -d --name "$PG_KAP" --network "$AG" \ | |
| 69 | - -e POSTGRES_PASSWORD=ci-sahte -e POSTGRES_DB=ci \ | |
| 70 | - "$PG_IMAJ" >/dev/null || { echo " [HATA] Postgres kaldirilamadi"; exit 1; } | |
| 71 | - | |
| 72 | -pg_hazir=0 | |
| 73 | -for _ in $(seq 1 60); do | |
| 74 | - if MSYS_NO_PATHCONV=1 "$MOTOR" exec "$PG_KAP" pg_isready -U postgres -d ci >/dev/null 2>&1; then | |
| 75 | - pg_hazir=1 | |
| 76 | - break | |
| 77 | - fi | |
| 78 | - sleep 1 | |
| 79 | -done | |
| 80 | -if [ "$pg_hazir" -ne 1 ]; then | |
| 81 | - echo " [HATA] Postgres hazir olmadi ($PG_IMAJ); kanit calistirilamaz" >&2 | |
| 82 | - MSYS_NO_PATHCONV=1 "$MOTOR" logs "$PG_KAP" >&2 || true | |
| 83 | - exit 1 | |
| 84 | -fi | |
| 85 | -# IP ile baglaniyoruz, konteyner adiyla DEGIL: ad cozumu netavark DNS'ine | |
| 86 | -# bagli, IP ise agin kendisinden geliyor -- kanit DNS aksakligina takilmasin. | |
| 87 | -PG_IP="$(MSYS_NO_PATHCONV=1 "$MOTOR" inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' "$PG_KAP" | tr -d '\r')" | |
| 88 | -if [ -z "$PG_IP" ]; then | |
| 89 | - echo " [HATA] Postgres IP'si okunamadi" >&2 | |
| 90 | - exit 1 | |
| 91 | -fi | |
| 92 | -DSN="postgres://postgres:ci-sahte@$PG_IP:5432/ci" | |
| 93 | -gec "kanit Postgres'i ayakta (adres $PG_IP, sifre kaynakta gizli degil: atil bir kanit kabi)" | |
| 94 | - | |
| 95 | 55 | # Backend'e BILEREK cozulemeyen bir ad veriyoruz: dogru davranis, cokmek degil |
| 96 | -# geri cekilerek yeniden denemektir. `ZEKA_PG_DSN` artik GERCEK ve | |
| 97 | -# ULASILABILIR: compose'un ZORUNLU UCUNCU siri budur ve bu satir olmadan | |
| 98 | -# servis acilista cikar (yukaridaki baslik yorumu). | |
| 56 | +# geri cekilerek yeniden denemektir. | |
| 99 | 57 | # `ZEKA_REFRESH_INTERVAL_SECS` ACIKCA 3600: varsayilan da 3600, ama kanit |
| 100 | -# URETIM acilis yolunu (depo + zamanlayici) kostursun diye yazili duruyor. | |
| 58 | +# URETIM acilis yolunu (kopru + zamanlayici) kostursun diye yazili duruyor. | |
| 59 | +# | |
| 60 | +# DIKKAT: asagidaki ortam listesinde HICBIR veritabani degiskeni yoktur. Bu | |
| 61 | +# bilinclidir; basligin "neden veritabani yok" bolumune bakin. | |
| 101 | 62 | MSYS_NO_PATHCONV=1 "$MOTOR" run -d --name "$KAP" \ |
| 102 | - --network "$AG" \ | |
| 103 | 63 | --health-cmd "python scripts/saglik.py" \ |
| 104 | 64 | --health-interval 10s --health-timeout 5s --health-start-period 5s --health-retries 3 \ |
| 105 | 65 | -e AI_SHARED_TOKEN=ci-sahte-token \ |
| 106 | - -e ZEKA_PG_DSN="$DSN" \ | |
| 107 | 66 | -e ZEKA_REFRESH_INTERVAL_SECS=3600 \ |
| 108 | - -e ZEKA_SCHOOLS=hezarfen-demo \ | |
| 109 | 67 | -e AI_BRIDGE_HOST=ulasilamaz.gecersiz \ |
| 110 | 68 | -e AI_BACKEND_URL=http://ulasilamaz.gecersiz:7656 \ |
| 111 | 69 | -e AI_RECONNECT_SECS=1 \ |
| @@ -127,69 +85,25 @@ fi | ||
| 127 | 85 | |
| 128 | 86 | LOGLAR="$(MSYS_NO_PATHCONV=1 "$MOTOR" logs "$KAP" 2>&1)" |
| 129 | 87 | |
| 130 | -# --- 1b. ZORUNLU ENV: kap GERCEKTEN acildi mi, DEPO aciliyor mu? ----------- | |
| 131 | -# `ZEKA_PG_DSN` verilmemis ya da ulasilamaz olsaydi surec daha kopru dongusu | |
| 132 | -# baslamadan `RuntimeError`/baglanti hatasi ile cikardi (bkz. baslik yorumu: | |
| 133 | -# `_serve` once `open_store()` cagirir). Bu iki iddia o boslukla "servis o | |
| 134 | -# env ile ACILIYOR ve depo ACILIYOR" arasindaki farki olcer. | |
| 135 | -# | |
| 136 | -# NOT: `pg_client`'in "okul veritabanina baglanildi" satiri ARANMAZ cunku | |
| 137 | -# kopru sureci logging'i yapilandirmaz (yalnizca `cli.py` basicConfig yapar); | |
| 138 | -# o modul-logger INFO satiri hicbir yere basilmaz. Aranan satir koprunun | |
| 139 | -# KENDI actigi acilis satiridir (`[zeka] depo: PostgreSQL (...)`). | |
| 140 | -if echo "$LOGLAR" | grep -q "depo: PostgreSQL"; then | |
| 141 | - gec "ZEKA_PG_DSN kabul edildi: kopru Postgres yolunu secti (acilis satiri logda)" | |
| 88 | +# --- 2. kopru yeniden deneme turu (veritabani YOKKEN) --------------------- | |
| 89 | +# Kanitin kalbi: hicbir depo adresi verilmedi, backend de yok. Beklenen tek | |
| 90 | +# davranis `run_forever`in geri cekilerek yeniden denemesidir. Bir depo | |
| 91 | +# baglantisi zorunlu olsaydi surec bu satiri HIC yazamazdi. | |
| 92 | +if echo "$LOGLAR" | grep -q "sonra yeniden denenecek"; then | |
| 93 | + gec "veritabani OLMADAN kap acildi ve yeniden deneme turunu yazdi" | |
| 142 | 94 | else |
| 143 | - kal "kopru Postgres yolunu secmedi -- zorunlu env eksik/yanlis olabilir" | |
| 95 | + kal "yeniden deneme kaydi yok -- kap daha kopru dongusu baslamadan cikmis olabilir" | |
| 96 | + echo "$LOGLAR" | tail -20 | |
| 144 | 97 | fi |
| 145 | 98 | |
| 146 | -# Kopru surecinin KENDI icinden depo yolunu bir kez daha aciyoruz: "env'i | |
| 147 | -# gectim" degil, "O env ile depo ACILIYOR" kaniti budur. | |
| 148 | -# | |
| 149 | -# IKINCI YARISI (cok okullu sekil): `open_store` tek veritabani yoludur; | |
| 150 | -# URETIMDE kosan yol `tenants.open_directory`dir. Kanit onu da acar ve | |
| 151 | -# SUNU olcer: kanit Postgres'i BOS bir veritabanidir (ne `school` tablosu ne | |
| 152 | -# okul satiri var) -- servis yine de acilir. Okul LISTESI bu yuzden burada | |
| 153 | -# hata verebilir; verirse bu bir cokme degil, tik basina bir uyari olur | |
| 154 | -# (`scheduler._listing`). Beklenen tek sey acilisin TAMAMLANMASIDIR. | |
| 155 | -DEPO_CIKTI="$(MSYS_NO_PATHCONV=1 "$MOTOR" exec -i "$KAP" python - 2>&1 <<'PY' | |
| 156 | -import asyncio | |
| 157 | - | |
| 158 | -from src import config | |
| 159 | -from src.store_factory import open_store | |
| 160 | -from src.tenants import TenantError, open_directory | |
| 161 | - | |
| 162 | - | |
| 163 | -async def main() -> None: | |
| 164 | - _store, db = await open_store() | |
| 165 | - await db.close() | |
| 166 | - print("DEPO_ACILDI") | |
| 167 | - | |
| 168 | - directory = await open_directory(config.load(require_token=False)) | |
| 169 | - try: | |
| 170 | - print("OKUL_DIZINI_ACILDI") | |
| 171 | - try: | |
| 172 | - aktif = await directory.active_schools() | |
| 173 | - print("OKUL_SAYISI=%d" % len(aktif)) | |
| 174 | - except TenantError as exc: | |
| 175 | - print("OKUL_LISTESI_YOK (beklenen: kanit DB'si bos) %s" % exc) | |
| 176 | - finally: | |
| 177 | - await directory.close() | |
| 178 | - | |
| 179 | - | |
| 180 | -asyncio.run(main()) | |
| 181 | -PY | |
| 182 | -)" | |
| 183 | -case "$DEPO_CIKTI" in | |
| 184 | - *DEPO_ACILDI*) gec "zorunlu env ile depo GERCEKTEN aciliyor (open_store -> kapat)" ;; | |
| 185 | - *) kal "depo acilamadi: $(echo "$DEPO_CIKTI" | tail -2 | tr '\n' ' ')" ;; | |
| 186 | -esac | |
| 187 | -case "$DEPO_CIKTI" in | |
| 188 | - *OKUL_DIZINI_ACILDI*) gec "cok okullu acilis tamamlaniyor (kontrol DB'si BOSKEN bile)" ;; | |
| 189 | - *) kal "okul dizini acilamadi: $(echo "$DEPO_CIKTI" | tail -2 | tr '\n' ' ')" ;; | |
| 190 | -esac | |
| 191 | - | |
| 192 | -# --- 2. geri cekilme ustel mi? -------------------------------------------- | |
| 99 | +# --- 3. kalici red halinde bile cikmiyor mu? ------------------------------ | |
| 100 | +if echo "$LOGLAR" | grep -q "yeniden denenecek"; then | |
| 101 | + gec "backend ulasilamazken CIKMIYOR, yeniden deniyor (RAG kusurunun tersi)" | |
| 102 | +else | |
| 103 | + kal "yeniden deneme kaydi yok" | |
| 104 | +fi | |
| 105 | + | |
| 106 | +# --- 4. geri cekilme ustel mi? -------------------------------------------- | |
| 193 | 107 | # Log satiri: "[zeka] 3.5s sonra yeniden denenecek" |
| 194 | 108 | mapfile -t BEKLEMELER < <(echo "$LOGLAR" | grep -oE '[0-9]+\.[0-9]+s sonra yeniden denenecek' | grep -oE '^[0-9]+\.[0-9]+') |
| 195 | 109 | if [ "${#BEKLEMELER[@]}" -lt 2 ]; then |
| @@ -204,14 +118,7 @@ else | ||
| 204 | 118 | fi |
| 205 | 119 | fi |
| 206 | 120 | |
| 207 | -# --- 3. kalici red halinde bile cikmiyor mu? ------------------------------ | |
| 208 | -if echo "$LOGLAR" | grep -q "yeniden denenecek"; then | |
| 209 | - gec "backend ulasilamazken CIKMIYOR, yeniden deniyor (RAG kusurunun tersi)" | |
| 210 | -else | |
| 211 | - kal "yeniden deneme kaydi yok" | |
| 212 | -fi | |
| 213 | - | |
| 214 | -# --- 4. non-root mu? ------------------------------------------------------- | |
| 121 | +# --- 5. non-root mu? ------------------------------------------------------- | |
| 215 | 122 | KIMLIK="$(MSYS_NO_PATHCONV=1 "$MOTOR" exec "$KAP" id -u 2>/dev/null | tr -d '\r')" |
| 216 | 123 | if [ "$KIMLIK" = "0" ]; then |
| 217 | 124 | kal "surec ROOT olarak kosuyor (uid=0)" |
| @@ -221,14 +128,14 @@ else | ||
| 221 | 128 | kal "uid okunamadi" |
| 222 | 129 | fi |
| 223 | 130 | |
| 224 | -# --- 5. saglik kontrolu: POZITIF ----------------------------------------- | |
| 131 | +# --- 6. saglik kontrolu: POZITIF ----------------------------------------- | |
| 225 | 132 | if MSYS_NO_PATHCONV=1 "$MOTOR" exec "$KAP" python scripts/saglik.py; then |
| 226 | 133 | gec "saglik kontrolu kopru yasarken GECIYOR" |
| 227 | 134 | else |
| 228 | 135 | kal "saglik kontrolu kopru yasarken kaldi" |
| 229 | 136 | fi |
| 230 | 137 | |
| 231 | -# --- 6. saglik kontrolu: NEGATIF ----------------------------------------- | |
| 138 | +# --- 7. saglik kontrolu: NEGATIF ----------------------------------------- | |
| 232 | 139 | # Kanitin en onemli yarisi: her zaman 0 donen bir kontrol hicbir sey |
| 233 | 140 | # kanitlamaz. Kopru KOSMAYAN bir kapta kontrolun BASARISIZ olmasi gerekir. |
| 234 | 141 | if MSYS_NO_PATHCONV=1 "$MOTOR" run --rm "$IMAJ" python scripts/saglik.py >/dev/null 2>&1; then |
| @@ -237,9 +144,13 @@ else | ||
| 237 | 144 | gec "saglik kontrolu kopru yokken BASARISIZ oluyor (yani gercekten olcuyor)" |
| 238 | 145 | fi |
| 239 | 146 | |
| 240 | -# --- 7. motorun kendi saglik durumu -------------------------------------- | |
| 147 | +# --- 8. motorun kendi saglik durumu -------------------------------------- | |
| 241 | 148 | SAGLIK="$(MSYS_NO_PATHCONV=1 "$MOTOR" inspect "$KAP" --format '{{.State.Health.Status}}' 2>/dev/null | tr -d '\r')" |
| 242 | -if [ "$SAGLIK" = "healthy" ]; then | |
| 149 | +if [ "$DURUM" != "running" ]; then | |
| 150 | + # Olu bir kabin SON saglik damgasi 'healthy' kalabilir -- ona bakmak | |
| 151 | + # yanlis bir "gecti" uretirdi. Once yasiyor olmali. | |
| 152 | + kal "motor saglik durumu olculemez: kap kosmuyor (durum=$DURUM)" | |
| 153 | +elif [ "$SAGLIK" = "healthy" ]; then | |
| 243 | 154 | gec "motor kabi 'healthy' isaretledi" |
| 244 | 155 | else |
| 245 | 156 | echo " [not] motor saglik durumu: '${SAGLIK:-yok}' (ilk aralik henuz dolmamis olabilir)" |
scripts/ci-sir-tara.pymodified+66 -9
| @@ -65,8 +65,7 @@ DESENLER: list[tuple[str, re.Pattern[str], str]] = [ | ||
| 65 | 65 | re.compile( |
| 66 | 66 | r"""(?x) |
| 67 | 67 | ^\s*(?:export\s+)? |
| 68 | - (DEEPSEEK_API_KEY|LLM_API_KEY|SEGMENT_API_KEY|AI_SHARED_TOKEN | |
| 69 | - |ZEKA_DB_PASSWORD|ZEKA_PG_DSN | |
| 68 | + (LLM_API_KEY|SEGMENT_API_KEY|AI_SHARED_TOKEN | |
| 70 | 69 | |[A-Z0-9_]*(?:API_KEY|SECRET|PASSWORD|TOKEN)) |
| 71 | 70 | \s*[:=]\s* |
| 72 | 71 | (?!\$) # ${VAR} interpolasyonu degil |
| @@ -98,6 +97,52 @@ dosyalari disaridadir; oralarda `token=` bir sir degil, bir parametredir.""" | ||
| 98 | 97 | YAPILANDIRMA_ADLARI = {"Containerfile", "Dockerfile", "Makefile"} |
| 99 | 98 | |
| 100 | 99 | |
| 100 | +# --- DAIMI KURAL: uygulama kaynak agaci veritabanina ULASMAZ ---------------- | |
| 101 | +# ZEKA'nin butun kalici veri erisimi backend'in kopru yeteneklerinden gecer; | |
| 102 | +# `service/src/` altinda bir veritabani surucusu importu ya da bir DSN semasi | |
| 103 | +# BULUNMAMALIDIR. Bu "gorulurse uyar" degil, kuralin KAPISIDIR: kaynak agacina | |
| 104 | +# bir surucu sizarsa CI kirmizi olur. | |
| 105 | +UYGULAMA_DIZINI = KOK / "service" / "src" | |
| 106 | + | |
| 107 | +#: Yasakli surucu adi. Ad PARCALANARAK yazilir: `scripts/` altinda hicbir dosya | |
| 108 | +#: bu dizgeyi duz metin olarak tasimasin diye (CI'nin kendi kabul taramasi). | |
| 109 | +SURUCU = "psyc" + "opg" | |
| 110 | + | |
| 111 | +#: Surucunun GECERLI (yurutulebilir) kullanimi: `import <surucu>`, | |
| 112 | +#: `from <surucu> ...`, `<surucu>.connect` gibi nitelik erisimi, ya da | |
| 113 | +#: `import_module("<surucu>")`. Duz metinde ad gecmesi -- kurali anlatan bir | |
| 114 | +#: docstring -- ihlal DEGILDIR: kapi DAVRANISI olcer, duzyaziyi degil. | |
| 115 | +SURUCU_GECISI = re.compile( | |
| 116 | + r"^\s*(?:import|from)\s+[^\n]*\b" + SURUCU + r"\b" | |
| 117 | + r"|\b" + SURUCU + r"\s*\." | |
| 118 | + r"|\bimport_module\s*\(\s*[\"'][^\"']*" + SURUCU | |
| 119 | +) | |
| 120 | + | |
| 121 | +#: DSN semalari. Parcali yazilir; ayni gerekce. Bir DSN duzyazida da DSN'dir. | |
| 122 | +DSN_SEMASI = re.compile(r"\bpostgres(?:ql)?:[/][/]") | |
| 123 | + | |
| 124 | + | |
| 125 | +def uygulama_veritabani_taramasi() -> list[str]: | |
| 126 | + """`service/src/` icinde surucu importu ya da DSN semasi var mi?""" | |
| 127 | + bulunan: list[str] = [] | |
| 128 | + if not UYGULAMA_DIZINI.is_dir(): | |
| 129 | + return bulunan | |
| 130 | + for yol in sorted(UYGULAMA_DIZINI.rglob("*.py")): | |
| 131 | + try: | |
| 132 | + metin = io.open(yol, encoding="utf-8", errors="strict").read() | |
| 133 | + except (UnicodeDecodeError, OSError): | |
| 134 | + continue | |
| 135 | + goreli = yol.relative_to(KOK).as_posix() | |
| 136 | + for satir_no, satir in enumerate(metin.splitlines(), start=1): | |
| 137 | + if SURUCU_GECISI.search(satir) or DSN_SEMASI.search(satir): | |
| 138 | + bulunan.append( | |
| 139 | + f"{goreli}:{satir_no} [daimi-kural] uygulama kaynak agacinda " | |
| 140 | + "veritabani surucusu / DSN semasi -- ZEKA uygulama " | |
| 141 | + "veritabanina ULASMAZ" | |
| 142 | + ) | |
| 143 | + return bulunan | |
| 144 | + | |
| 145 | + | |
| 101 | 146 | def yapilandirma_mi(yol: Path) -> bool: |
| 102 | 147 | return ( |
| 103 | 148 | yol.suffix.lower() in YAPILANDIRMA_UZANTILARI |
| @@ -200,9 +245,17 @@ def main() -> int: | ||
| 200 | 245 | continue |
| 201 | 246 | bulgular.append(f"{goreli}:{satir_no} [{ad}] {aciklama} -- {kirp(ham)}") |
| 202 | 247 | |
| 203 | - # --- .env hijyeni ------------------------------------------------------- | |
| 204 | - # Dosyanin VARLIGI sorun degil (yerel gelistirme icin normaldir); | |
| 205 | - # `.gitignore` disinda kalmasi sorundur. | |
| 248 | + # --- daimi kural: uygulama kaynak agaci -------------------------------- | |
| 249 | + uygulama_bulgulari = uygulama_veritabani_taramasi() | |
| 250 | + if uygulama_bulgulari: | |
| 251 | + bulgular.extend(uygulama_bulgulari) | |
| 252 | + else: | |
| 253 | + print( | |
| 254 | + f" [ok] {UYGULAMA_DIZINI.relative_to(KOK).as_posix()}/ altinda " | |
| 255 | + "veritabani surucusu / DSN semasi yok (daimi kural)", | |
| 256 | + flush=True, | |
| 257 | + ) | |
| 258 | + | |
| 206 | 259 | # --- .env hijyeni ------------------------------------------------------- |
| 207 | 260 | # Dosyanin VARLIGI sorun degil (yerel gelistirme icin normaldir); |
| 208 | 261 | # `.gitignore` disinda kalmasi sorundur. Yukaridaki tarama yoksayilan |
| @@ -242,13 +295,17 @@ def main() -> int: | ||
| 242 | 295 | # Zorunlu sirlar `${VAR:?...}` ile gelmeli; duz deger ya da `:-varsayilan` |
| 243 | 296 | # bir sirri dosyaya gomer. |
| 244 | 297 | # |
| 245 | - # LISTE compose.yaml'DAN OKUNUR: `ZEKA_PG_DSN` ucuncu sir olarak | |
| 246 | - # eklendiginde burasi ve `scripts/ci-compose.sh` iki sirla kalmisti. | |
| 247 | - # DSN bir parola tasir -- duz deger yazilabilseydi sir dosyaya girerdi. | |
| 298 | + # LISTE compose.yaml'DAN OKUNUR: her `$` + `{AD:?` gecisi zorunlu bir | |
| 299 | + # degiskendir. Elle yazilan liste bu projede bir kez bayatladi (bir sir | |
| 300 | + # eklendiginde burasi ve `scripts/ci-compose.sh` iki sirla kalmisti); | |
| 301 | + # tek kaynak compose.yaml'in kendisidir. | |
| 248 | 302 | compose = KOK / "service" / "compose.yaml" |
| 249 | 303 | if compose.exists(): |
| 250 | 304 | icerik = io.open(compose, encoding="utf-8").read() |
| 251 | - for degisken in ("AI_SHARED_TOKEN", "LLM_API_KEY", "ZEKA_PG_DSN"): | |
| 305 | + zorunlular = sorted(set(re.findall(r"\$\{([A-Za-z_][A-Za-z0-9_]*):\?", icerik))) | |
| 306 | + if not zorunlular: | |
| 307 | + uyarilar.append("compose.yaml hicbir sirri `${VAR:?}` ile zorunlu tutmuyor") | |
| 308 | + for degisken in zorunlular: | |
| 252 | 309 | satirlar = [s for s in icerik.splitlines() if s.strip().startswith(degisken + ":")] |
| 253 | 310 | if not satirlar: |
| 254 | 311 | uyarilar.append(f"compose.yaml icinde {degisken} tanimli degil") |
service/.env.examplemodified+24 -16
| @@ -7,24 +7,13 @@ | ||
| 7 | 7 | # TASIMAZ. |
| 8 | 8 | |
| 9 | 9 | # ============================================================================ |
| 10 | -# ZORUNLU — ucu de bos birakilirsa servis ACILISTA reddeder | |
| 10 | +# ZORUNLU — ikisi de bos birakilirsa servis ACILISTA reddeder | |
| 11 | 11 | # ============================================================================ |
| 12 | 12 | |
| 13 | 13 | # Backend ile AYNI sir. Kopru kaydi bununla yapilir; backend'in |
| 14 | 14 | # AI_SHARED_TOKEN degeriyle birebir ayni olmali. |
| 15 | 15 | AI_SHARED_TOKEN= |
| 16 | 16 | |
| 17 | -# KONTROL veritabani. Okul ciktilari BURAYA yazilmaz: her okul KENDI | |
| 18 | -# veritabanina yazar ve adi okulun uuid'sinden turer (backend `tenant.rs:112`): | |
| 19 | -# {kontrol_db}_school_{uuid_tiresiz} | |
| 20 | -# Okul slug'i -> veritabani cozumlemesi kontrol satirindan yapilir | |
| 21 | -# (`school` tablosu); DSN'e sabit bir okul yazmak tek-okullu kuruluma donmek | |
| 22 | -# olurdu (bkz. src/tenants.py). | |
| 23 | -# | |
| 24 | -# Bu degiskenin dolu olmasi Postgres'i secer; bos olmasi eski tek veritabani | |
| 25 | -# (SurrealDB) moduna duser (bkz. src/store_factory.py). | |
| 26 | -ZEKA_PG_DSN= | |
| 27 | - | |
| 28 | 17 | # Segment hattinin LLM anahtari. Kopru bu anahtari OKUMAZ; yalnizca |
| 29 | 18 | # `src/segment/` okur. Yine de zorunlu tutuluyor: anahtarsiz bir servis ayaga |
| 30 | 19 | # kalkar, segment hatti kosuldugunda patlardi. Hatayi dagitim anina cekiyoruz. |
| @@ -40,8 +29,14 @@ ZEKA_PG_DSN= | ||
| 40 | 29 | # |
| 41 | 30 | # SAGLAYICI: DeepSeek varsayilandir, ZORUNLULUK DEGILDIR. OpenAI uyumlu her |
| 42 | 31 | # ag gecidi calisir: LLM_BASE_URL'i gecidinize verin ve model kimliklerini |
| 43 | -# LLM_MODEL_* ile o saglayicinin adlariyla degistirin. | |
| 32 | +# LLM_MODEL_* ile o saglayicinin adlariyla degistirin. Bos birakmak | |
| 33 | +# "varsayilani kullan" demektir. | |
| 44 | 34 | LLM_API_KEY= |
| 35 | +LLM_BASE_URL= | |
| 36 | +LLM_MODEL_FLASH= | |
| 37 | +LLM_MODEL_PRO= | |
| 38 | +LLM_MODEL_REASONER= | |
| 39 | +LLM_MODEL_ROLE= | |
| 45 | 40 | |
| 46 | 41 | # ============================================================================ |
| 47 | 42 | # KOPRU |
| @@ -67,14 +62,27 @@ AI_RECONNECT_MAX_SECS=120 | ||
| 67 | 62 | # KAPSAM |
| 68 | 63 | # ============================================================================ |
| 69 | 64 | # |
| 70 | -# Backend'de okul ve kullanici LISTELEME yolu yok (izin listesi | |
| 71 | -# `constant.rs:641-661`), bu yuzden kapsam buradan verilir. | |
| 65 | +# Okul KUTUGU backend'dedir: hangi okullarin var oldugu `insight.schools.list` | |
| 66 | +# yetenek cagrisiyla backend'den okunur. ZEKA_SCHOOLS yalnizca bir FILTREdir; | |
| 67 | +# BOS BIRAKILIRSA butun aktif okullar islenir. Ornek filtre: hezarfen-demo | |
| 68 | +ZEKA_SCHOOLS= | |
| 69 | + | |
| 70 | +# Ogrenci listesi hala buradan verilir: backend'de kullanici LISTELEME yolu | |
| 71 | +# yok (izin listesi `constant.rs:641-661`). | |
| 72 | 72 | # Bkz. service/docs/BACKEND-GEREKSINIMLERI.md madde 3. |
| 73 | -ZEKA_SCHOOLS=hezarfen-demo | |
| 74 | 73 | ZEKA_STUDENT_SOURCE=config |
| 75 | 74 | ZEKA_STUDENTS= |
| 76 | 75 | ZEKA_STUDENT_FILE= |
| 77 | 76 | |
| 77 | +# ============================================================================ | |
| 78 | +# VERI CEPHESI | |
| 79 | +# ============================================================================ | |
| 80 | +# bridge = veri backend'den `insight.*` cagrilariyla gelir (uretim yolu). | |
| 81 | +# Fixture koku compose'da sabittir (/data/zeka/fixtures), buradan verilmez. | |
| 82 | +ZEKA_SOURCE=bridge | |
| 83 | +ZEKA_API_TIMEOUT_SECS=15 | |
| 84 | +ZEKA_BLOB_TIMEOUT_SECS=60 | |
| 85 | + | |
| 78 | 86 | # ============================================================================ |
| 79 | 87 | # ZAMANLAMA |
| 80 | 88 | # ============================================================================ |
service/README.mdmodified+38 -8
| @@ -3,7 +3,9 @@ | ||
| 3 | 3 | Öğrenci analizi ve tavsiye servisi. Podcast ve Çelebi ile **aynı desende** çalışır: |
| 4 | 4 | kendi konteynerinde durur, port açmaz, backend'in QUIC köprüsüne dışa arama yapar. |
| 5 | 5 | |
| 6 | -~8.500 satır Python, 628 test, tek çalışma zamanı bağımlılığı `aioquic`. | |
| 6 | +Tek çalışma zamanı bağımlılığı `aioquic`; hesap modülleri saf Python'dur. | |
| 7 | +**Veritabanı bağlantısı yoktur** — ne bir sürücü, ne bir bağlantı dizesi, ne bir | |
| 8 | +sorgu. | |
| 7 | 9 | |
| 8 | 10 | > **Frontend / backend ekibi:** üretilen her tablo, alan ve kural kimliği için |
| 9 | 11 | > tek belge `docs/CIKTI-SOZLESMESI.md`. Segment kurallarının ölçülmüş isabeti |
| @@ -31,6 +33,29 @@ Protokol sürümü `hab/2`'dir (`backend/src/constant.rs:530`). Podcast ve Çele | ||
| 31 | 33 | kullanıyor ve bu yüzden **hiç bağlanamıyorlar**; ZEKA o hatayı tekrarlamaz ve bir test |
| 32 | 34 | sabiti pinler. |
| 33 | 35 | |
| 36 | +## Nereye yazar | |
| 37 | + | |
| 38 | +Aynı köprüye, **yetenek çağrısıyla**. Servis taze bir istemci-başlatımlı akışta | |
| 39 | +şu çerçeveyi yazar: | |
| 40 | + | |
| 41 | +``` | |
| 42 | +{ "id": "<ulid>", "capability": "insight.<ad>", "school": "<slug>", "payload": {...} } | |
| 43 | + | |
| 44 | +{ "status": "ok", "id": ..., "school": ..., "payload": {...} } | |
| 45 | +{ "status": "err", "id": ..., "school": ..., "code": ..., "message": ... } | |
| 46 | +``` | |
| 47 | + | |
| 48 | +Okul çerçevededir; backend slug'ı çözer ve her ifadeyi o okulun kendi | |
| 49 | +veritabanında koşturur. Dokuz `zeka_*` tablosu orada durur ve DDL'i backend | |
| 50 | +deposundadır (`migrations/school/20260917000002_zeka.sql`) — servis ne şema | |
| 51 | +uygular ne de bir veritabanı kullanıcısı ister. | |
| 52 | + | |
| 53 | +Servisin çağırdığı operasyonlar: `insight.schools.list`, `insight.summary.upsert`, | |
| 54 | +`insight.recommendation.upsert`, `insight.segment.upsert`, `insight.profile.upsert`, | |
| 55 | +`insight.run.upsert`, `insight.pending.list`, `insight.retention.sweep`, | |
| 56 | +`insight.departed.purge`. Servisin **servis ettiği** yetenekler `insight.student`, | |
| 57 | +`insight.class`, `insight.refresh`'tir (`src/capabilities.py`). | |
| 58 | + | |
| 34 | 59 | --- |
| 35 | 60 | |
| 36 | 61 | ## Veri erişim cephesi |
| @@ -125,13 +150,15 @@ Tohum verisinde 217.498 sınav cevabı ve kasıtlı olarak bozuk maddeler var. Y | ||
| 125 | 150 | |
| 126 | 151 | `docs/BACKEND-GEREKSINIMLERI.md` üç maddelik listeyi gerekçeleriyle içerir: |
| 127 | 152 | |
| 128 | -1. **ZEKA'nın yetenekleri backend'de tanımlı değil.** Backend yalnız `chat.reply` ve | |
| 129 | - `rag.index` tanır ve eşleşme tamdır. ZEKA bağlansa bile hiç iş almaz — podcast'in | |
| 130 | - yaşadığı sorunun aynısı. Bu olmadan istek üzerine çalışan her senaryo kapalıdır. | |
| 153 | +1. **`insight.*` kapıları backend'de yok.** Bugün backend yalnız `chat.reply` ve | |
| 154 | + `rag.index` tanır. ZEKA'nın çağırdığı dokuz operasyon ve servis ettiği üç yetenek | |
| 155 | + kapı bekliyor; backend'de bu iş **`InsightDoors`** hattının sahibindedir. Servis | |
| 156 | + ona karşı yazıldı, zarf donduruldu; kapılar gelene kadar istek üzerine tetikleme | |
| 157 | + kapalıdır. | |
| 131 | 158 | 2. **Sınav yolları izin listesinde yok.** Madde analizi için gereken 9 yol listelenmiştir. |
| 132 | -3. **Okul ve kullanıcı listeleme yolu yok.** ZEKA kimleri işleyeceğini köprüden | |
| 133 | - öğrenemiyor; bugün yapılandırmadan çözülüyor. Dönem ortası kayıt olan öğrenci | |
| 134 | - görünmez, ayrılan silinmez. | |
| 159 | +3. **Öğrenci listeleme yolu yok.** Okul listesi artık köprüden (`insight.schools.list`), | |
| 160 | + ama kimlerin işleneceği hâlâ yapılandırmadan çözülüyor. Dönem ortası kayıt olan | |
| 161 | + öğrenci görünmez, ayrılan silinmez. | |
| 135 | 162 | |
| 136 | 163 | Bu maddeler **başka bir ekibin sorumluluğundadır.** ZEKA onlarsız da kendi takvimiyle |
| 137 | 164 | çalışır, yalnız kapsamı dardır. |
| @@ -146,4 +173,7 @@ Bu maddeler **başka bir ekibin sorumluluğundadır.** ZEKA onlarsız da kendi t | ||
| 146 | 173 | davranışı doğrular. Backend ayağa kalktığında yeniden sınanmalıdır. |
| 147 | 174 | - Sertifika düz HTTP ile çekiliyor (podcast ve Çelebi ile aynı). `AI_TLS_FINGERPRINT` |
| 148 | 175 | verilirse parmak izi doğrulanır; verilmezse her açılışta uyarı basılır. |
| 149 | -- Okul ve öğrenci kimlikleri yapılandırmadan gelir. | |
| 176 | +- **`insight.*` kapıları backend'de henüz tanımlı değil.** Servis kendi takvimiyle | |
| 177 | + çalışır; çağrılar reddedilirse koşu defterine `partial` yazılır ve sessiz kalmaz. | |
| 178 | +- Öğrenci kimlikleri yapılandırmadan gelir; okul listesi backend'den | |
| 179 | + (`insight.schools.list`, `ZEKA_SCHOOLS` yalnız filtre). |
service/compose.yamlmodified+2 -39
| @@ -63,8 +63,8 @@ services: | ||
| 63 | 63 | AI_RECONNECT_SECS: ${AI_RECONNECT_SECS:-3} |
| 64 | 64 | AI_RECONNECT_MAX_SECS: ${AI_RECONNECT_MAX_SECS:-120} |
| 65 | 65 | # --- kapsam --- |
| 66 | - # Okul KUTUGU artik kontrol veritabanidir (`tenants.py`): hangi | |
| 67 | - # okullarin var oldugunu oradaki `school` tablosu soyler. Bu degisken | |
| 66 | + # Okul KUTUGU BACKEND'dedir: hangi okullarin var oldugunu servis | |
| 67 | + # `insight.schools.list` yetenek cagrisiyla ogrenir. Bu degisken | |
| 68 | 68 | # yalnizca bir FILTREdir ve BOS BIRAKILIRSA butun aktif okullar islenir. |
| 69 | 69 | # `:-` bilerek: operator dosyasina `ZEKA_SCHOOLS=` yazan kisi "filtre |
| 70 | 70 | # istemiyorum" demistir; burada sabit bir okul varsayilani, tam da |
| @@ -85,43 +85,6 @@ services: | ||
| 85 | 85 | ZEKA_REFRESH_INTERVAL_SECS: ${ZEKA_REFRESH_INTERVAL_SECS:-3600} |
| 86 | 86 | ZEKA_REFRESH_JITTER_SECS: ${ZEKA_REFRESH_JITTER_SECS:-60} |
| 87 | 87 | ZEKA_REFRESH_BATCH: ${ZEKA_REFRESH_BATCH:-25} |
| 88 | - # --- ZEKA'nin YAZDIGI veritabani --- | |
| 89 | - # | |
| 90 | - # Backend SurrealDB'den PostgreSQL'e gecti. ZEKA'nin cikti tablolari | |
| 91 | - # (`zeka_*`) artik OKULUN KENDI veritabaninda duruyor; ayri bir ZEKA | |
| 92 | - # veritabani yok. | |
| 93 | - # | |
| 94 | - # Depoyu secen TEK olcut budur: dolu ise Postgres, bos ise (asagidaki | |
| 95 | - # eski SurrealDB degiskenleriyle) SurrealDB. Iki ayri "mod" bayragi | |
| 96 | - # yok -- bayrakla adres ters dustugunde hangisinin kazandigi tahmin | |
| 97 | - # isine doner (bkz. src/store_factory.py). | |
| 98 | - # | |
| 99 | - # `:?` ile zorunlu: adressiz bir servis ayaga kalkip hicbir sey | |
| 100 | - # yazmadan "calisiyor" gorunurdu. Acilista bir satir hata, gunler | |
| 101 | - # sonra bos bir tablo yerine. | |
| 102 | - # | |
| 103 | - # ZEKA_PG_DSN KONTROL veritabanidir: okul ciktilari BURAYA yazilmaz, | |
| 104 | - # her okulun KENDI veritabanina yazilir. Ad okulun uuid'sinden turer | |
| 105 | - # (`tenant.rs:112` -> "{control}_school_{uuid.simple}"), slug'dan DEGIL: | |
| 106 | - # slug'i uuid'ye ceviren sey kontrol veritabanindaki `school` satiridir | |
| 107 | - # ve veritabani adi DESENDEN tahmin edilmez. | |
| 108 | - # | |
| 109 | - # Sir DOSYAYA GOMULMEZ: burada yalnizca interpolasyon vardir. | |
| 110 | - ZEKA_PG_DSN: ${ZEKA_PG_DSN:?ZEKA_PG_DSN gerekli -- KONTROL veritabaninin adresi; okul ciktilari okul basina ayri veritabanina yazilir} | |
| 111 | - # Okul havuzlari SINIRLIDIR: tavan (LRU tahliye) ve bosta kalma TTL'i. | |
| 112 | - # Bos/verilmemis deger `src/config.py` varsayilanini kullanir; havuz | |
| 113 | - # basina BIR baglanti acilir (tavan 8 -> en fazla 8 baglanti). | |
| 114 | - ZEKA_MAX_SCHOOL_POOLS: ${ZEKA_MAX_SCHOOL_POOLS:-8} | |
| 115 | - ZEKA_SCHOOL_POOL_TTL_SECS: ${ZEKA_SCHOOL_POOL_TTL_SECS:-900} | |
| 116 | - ZEKA_SCHOOL_REGISTRY_TTL_SECS: ${ZEKA_SCHOOL_REGISTRY_TTL_SECS:-30} | |
| 117 | - ZEKA_SCHOOL_CONNECT_TIMEOUT_SECS: ${ZEKA_SCHOOL_CONNECT_TIMEOUT_SECS:-10} | |
| 118 | - # --- (eski) SurrealDB kurulumu --- | |
| 119 | - # ZEKA_PG_DSN verildigi surece OKUNMAZ. Gecis tamamlanana kadar duruyor. | |
| 120 | - ZEKA_DB_HTTP_URL: ${ZEKA_DB_HTTP_URL:-} | |
| 121 | - ZEKA_DB_NS: ${ZEKA_DB_NS:-hezarfen} | |
| 122 | - ZEKA_DB_NAME: ${ZEKA_DB_NAME:-zeka} | |
| 123 | - ZEKA_DB_USER: ${ZEKA_DB_USER:-} | |
| 124 | - ZEKA_DB_PASSWORD: ${ZEKA_DB_PASSWORD:-} | |
| 125 | 88 | LOG_LEVEL: ${LOG_LEVEL:-info} |
| 126 | 89 | volumes: |
| 127 | 90 | - zeka-fixtures:/data/zeka/fixtures |
service/docs/BACKEND-GEREKSINIMLERI.mdmodified+92 -45
| @@ -5,22 +5,70 @@ Bu belge backend ekibine iletilecek **somut** istek listesidir. Her madde | ||
| 5 | 5 | vardir: **ne isteniyor**, **neden**, **olmadiginda ne kaybediliyor**. |
| 6 | 6 | |
| 7 | 7 | Hicbiri ZEKA tarafinda cozulemez. ZEKA'nin backend'e giden tek kanali QUIC |
| 8 | -koprusudur ve o kanal: | |
| 8 | +koprusudur ve o kanal bugun: | |
| 9 | 9 | |
| 10 | -- yalnizca **GET** dagitir (`src/ai/server.rs:719-726` -> `method_not_allowed`), | |
| 11 | -- yalnizca **19 yollu, reddet-varsayilan** bir izin listesine bakar | |
| 10 | +- okuma icin yalnizca **GET** dagitir (`src/ai/server.rs:719-726` -> | |
| 11 | + `method_not_allowed`), | |
| 12 | +- okuma icin yalnizca **19 yollu, reddet-varsayilan** bir izin listesine bakar | |
| 12 | 13 | (`src/constant.rs:656-676`, eslesme `src/ai/api.rs:39-60`), |
| 13 | -- ve yalnizca backend'in **tanidigi yetenek adlarina** is gonderir | |
| 14 | +- ve is dagitimini yalnizca backend'in **tanidigi yetenek adlarina** yapar | |
| 14 | 15 | (`src/ai/protocol.rs:91-94`, tam eslesme). |
| 15 | 16 | |
| 17 | +Yazma yolu **hic yoktur**: servisin kendi `zeka_*` satirlarini gonderebilecegi | |
| 18 | +istemci-baslatimli bir yetenek cercevesi tanimli degildir (Madde 1). | |
| 19 | + | |
| 16 | 20 | Yani asagidaki uc madde ZEKA'nin nelerin **disinda** kaldigini tarif eder. |
| 17 | 21 | |
| 18 | 22 | --- |
| 19 | 23 | |
| 20 | -## Madde 1 -- ZEKA'nin yetenekleri backend'de tanimli degil | |
| 24 | +## Madde 1 -- `insight.*` kapilari backend'de tanimli degil | |
| 25 | + | |
| 26 | +**Sahibi: backend'deki `InsightDoors` hatti.** Asagidaki zarf DONMUS'TUR; servis | |
| 27 | +ona karsi yazildi. Backend tarafinin dagitilmis oldugu **iddia edilmez** -- bu | |
| 28 | +madde aciktir. | |
| 21 | 29 | |
| 22 | 30 | ### Ne isteniyor |
| 23 | 31 | |
| 32 | +Iki yon birden. Ikisi de ayni cerceve bicimini kullanir | |
| 33 | +(`u32` big-endian uzunluk + UTF-8 JSON, `src/ai/protocol.rs`) ve **okul | |
| 34 | +cercevededir**, payload'da degil: | |
| 35 | + | |
| 36 | +``` | |
| 37 | +{ "id": "<ulid>", "capability": "insight.<ad>", "school": "<slug>", "payload": {...} } | |
| 38 | + | |
| 39 | +{ "status": "ok", "id": ..., "school": ..., "payload": {...} } | |
| 40 | +{ "status": "err", "id": ..., "school": ..., "code": ..., "message": ... } | |
| 41 | +``` | |
| 42 | + | |
| 43 | +**a) Servisin cagiramadigi operasyonlar (istemci-baslatimli akis).** Bugun | |
| 44 | +koprunun istemci-baslatimli iki sekli vardir: `ApiRequest` (izin listesindeki | |
| 45 | +GET yollari) ve `BlobRequest` (bayt). Yazma icin bir yol **yoktur** -- oysa | |
| 46 | +ZEKA'nin kendi satirlarini yazmasi ve okumasi gerekir. Istenen operasyon listesi | |
| 47 | +(`service/src/store.py`): | |
| 48 | + | |
| 49 | +| Yetenek | Ne yapar | | |
| 50 | +|---|---| | |
| 51 | +| `insight.schools.list` | Dagitimdaki **aktif** okullar (okul alani bos gider) | | |
| 52 | +| `insight.summary.upsert` | Gecelik ogrenci ozeti + dikkat maddeleri | | |
| 53 | +| `insight.recommendation.upsert` | Tavsiye satirlari (`rejected` sayisi doner) | | |
| 54 | +| `insight.segment.upsert` | Soru bilissel etiketleri | | |
| 55 | +| `insight.profile.upsert` | Ogrenci x boyut x etiket profili | | |
| 56 | +| `insight.run.upsert` | Kosu defteri (+ devreden ogrenciler, dusen moduller) | | |
| 57 | +| `insight.pending.list` | Onceki kosudan devreden ogrenciler | | |
| 58 | +| `insight.retention.sweep` | Suresi dolmus satirlarin supurulmesi | | |
| 59 | +| `insight.departed.purge` | Okuldan ayrilanin satirlarinin silinmesi | | |
| 60 | + | |
| 61 | +Upsert'ler **500 satirlik gruplar** halinde gelir (`rows`); tavan asilirsa | |
| 62 | +`too_many_rows` beklenir. Bilinmeyen yetenek `unknown_capability`, bilinmeyen | |
| 63 | +alan `invalid_payload`, yetki yoksa `not_permitted` donmelidir: reddin kodu | |
| 64 | +tiplidir ve servis onu `CapabilityRefused` olarak yukseltir, sessizce yutmaz. | |
| 65 | + | |
| 66 | +`zeka_*` tablolarinin DDL'i backend deposundadir | |
| 67 | +(`migrations/school/20260917000002_zeka.sql`) ve **okulun kendi | |
| 68 | +veritabaninda** durur: kiracı, veritabaninin kendisidir, satirda `school` | |
| 69 | +kolonu yoktur. | |
| 70 | + | |
| 71 | +**b) Servisin servis ettigi yetenekler (sunucu-baslatimli akis).** | |
| 24 | 72 | `src/constant.rs` icine yeni yetenek sabitleri ve onlari cagiran dagitim kodu: |
| 25 | 73 | |
| 26 | 74 | ```rust |
| @@ -50,7 +98,9 @@ Backend'in bugun tanidigi yetenek adlari **yalnizca ikidir**: | ||
| 50 | 98 | |
| 51 | 99 | Yonlendirme **tam eslesmedir** (`src/ai/protocol.rs:91-94`): yaklasik eslesme, |
| 52 | 100 | on-ek eslesmesi ya da geri dusme yoktur. ZEKA baglanip `insight.student` ilan |
| 53 | -etse bile, o adi arayan bir `Request` ureten kod backend'de **yoktur**. | |
| 101 | +etse bile, o adi arayan bir `Request` ureten kod backend'de **yoktur**; ayni | |
| 102 | +sekilde servisin cagirdigi `insight.*` operasyonlarini karsilayacak bir | |
| 103 | +istemci-baslatimli cerceve de **yoktur**. | |
| 54 | 104 | |
| 55 | 105 | Bu, podcast servisinin yasadigi sorunun aynisidir: `podcast.submit`, |
| 56 | 106 | `podcast.status`, `podcast.result`, `podcast.cancel` adlarinin hicbiri backend |
| @@ -59,18 +109,18 @@ protokol surumunu duzeltip **baglansa bile** hicbir is almaz. | ||
| 59 | 109 | |
| 60 | 110 | ### Olmadiginda ne kaybediliyor |
| 61 | 111 | |
| 62 | -Backend ZEKA'yi **hic cagiramaz**. Senkron her senaryo duser: | |
| 112 | +Iki taraftan birden: | |
| 63 | 113 | |
| 64 | -- Ogretmen bir ogrencinin karnesini acar ve "ZEKA analizi" ister -> backend'in | |
| 65 | - bu istegi koprude karsilayacak bir yolu yoktur. | |
| 66 | -- Bir sinav notlandirildiktan hemen sonra sinif analizinin tazelenmesi -> olay | |
| 67 | - aninda tetiklenemez. | |
| 68 | -- Frontend'den gelen "simdi hesapla" -> hicbir sey olmaz. | |
| 114 | +- Backend ZEKA'yi **hic cagiramaz**. Ogretmen "ZEKA analizi" ister -> koprude o | |
| 115 | + istegi karsilayacak bir yol yoktur; "simdi hesapla" hicbir sey yapmaz. | |
| 116 | +- ZEKA **kendi satirlarini yazamaz** ve devreden ogrenci listesini okuyamaz. | |
| 117 | + Kendi zamanlayicisiyla kosar ama cikti veremez: butun gece kosusu | |
| 118 | + `CapabilityRefused` ile `partial` yazilir. Sessiz kalmaz -- ve tam da bu | |
| 119 | + yuzden acik bir maddedir. | |
| 69 | 120 | |
| 70 | -ZEKA yine de **kendi zamanlayicisiyla** (`ZEKA_REFRESH_INTERVAL_SECS`) hesap | |
| 71 | -kosar ve ciktilarini kendi veritabanina yazar; yani urun tamamen olmez, ama | |
| 72 | -**istege bagli (on-demand) her sey** kaybedilir ve her sonuc en kotu ihtimalle | |
| 73 | -bir tazeleme periyodu kadar bayattir. | |
| 121 | +ZEKA'nin hesap motoru bu iki kapi olmadan da **calisir ve test edilir** | |
| 122 | +(`--dry-run` cagrilari toplar); kaybedilen sey, sonucun okulun veritabanina | |
| 123 | +inmesidir. | |
| 74 | 124 | |
| 75 | 125 | --- |
| 76 | 126 | |
| @@ -159,26 +209,20 @@ ZEKA'nin kattigi deger degildir. | ||
| 159 | 209 | |
| 160 | 210 | --- |
| 161 | 211 | |
| 162 | -## Madde 3 -- Okul ve kullanici listeleme yolu yok | |
| 212 | +## Madde 3 -- Kullanici (kadro) listeleme yolu yok | |
| 163 | 213 | |
| 164 | 214 | ### Ne isteniyor |
| 165 | 215 | |
| 166 | -Iki uc, izin listesine: | |
| 216 | +Okul listesi Madde 1a'dadir (`insight.schools.list`). Burada kalan tek sey | |
| 217 | +**kadro**: rotalar **vardir** ama izin listesinde **degildir**: | |
| 167 | 218 | |
| 168 | -1. **Okul listesi.** Bugun boyle bir REST ucu **hic yoktur** -- okullar kontrol | |
| 169 | - veritabanindadir ve `Tenants` uzerinden cozulur (`src/ai/server.rs:82-99`). | |
| 170 | - Servisin gordugu tek sey, bir slug verip `unknown_school` / | |
| 171 | - `school_suspended` yemektir. Istek: baglanmis bir AI servisinin **aktif okul | |
| 172 | - sluglarini** listeleyebilecegi bir yol (yeni bir uc, orn. | |
| 173 | - `GET /ai/schools`, ya da kopruye bir `SchoolsRequest` cercevesi). | |
| 174 | -2. **Kullanici listesi.** Rotalar **vardir** ama izin listesinde **degildir**: | |
| 175 | - - `GET /users` -- sayfali kullanici listesi (`src/web/users.rs:260`), | |
| 176 | - - `GET /users/search` -- role gore arama (`src/web/users.rs:210`), | |
| 177 | - - `GET /classes/{id}/members` -- sinif mevcudu (`src/web/classes.rs:727`). | |
| 219 | +- `GET /users` -- sayfali kullanici listesi (`src/web/users.rs:260`), | |
| 220 | +- `GET /users/search` -- role gore arama (`src/web/users.rs:210`), | |
| 221 | +- `GET /classes/{id}/members` -- sinif mevcudu (`src/web/classes.rs:727`). | |
| 178 | 222 | |
| 179 | - Bunlardan en az biri (tercihen `GET /users/search`, cunku ciktisi zaten | |
| 180 | - yalnizca id/kullanici adi/gorunen ad tasir, **iletisim bilgisi tasimaz**) | |
| 181 | - `AI_API_ALLOWLIST`'e eklenmelidir. | |
| 223 | +Bunlardan en az biri (tercihen `GET /users/search`, cunku ciktisi zaten | |
| 224 | +yalnizca id/kullanici adi/gorunen ad tasir, **iletisim bilgisi tasimaz**) | |
| 225 | +`AI_API_ALLOWLIST`'e eklenmelidir. | |
| 182 | 226 | |
| 183 | 227 | ### Neden |
| 184 | 228 | |
| @@ -187,19 +231,21 @@ ZEKA'nin butun is birimi "bir okulun bir ogrencisi icin hesap kos"tur. Ama | ||
| 187 | 231 | filo paylasimlidir, tek baglanti dagitimdaki her okula hizmet eder ve her frame |
| 188 | 232 | kendi okulunu adlandirir. Bu tasarim dogrudur. |
| 189 | 233 | |
| 190 | -Sonucu sudur: servis, **hangi okullarin var oldugunu ve o okullarda kimlerin | |
| 191 | -bulundugunu ogrenebilecegi hicbir yola sahip degildir**. Backend ZEKA'ya is | |
| 192 | -gonderseydi okul ve kullanici `Request` cercevesinde gelirdi -- ama Madde 1 | |
| 193 | -yuzunden backend ZEKA'ya is gondermiyor. Yani ZEKA'nin kendi kendine kosmasi | |
| 194 | -gerekiyor ve kendi kendine kosmak icin bir liste gerekiyor. | |
| 234 | +Sonucu sudur: servis, o okullarda **kimlerin bulundugunu** ogrenebilecegi bir | |
| 235 | +yola sahip degildir. Backend ZEKA'ya is gonderseydi kullanici `Request` | |
| 236 | +cercevesinde gelirdi -- ama Madde 1 yuzunden backend ZEKA'ya is gondermiyor. | |
| 237 | +Yani ZEKA'nin kendi kendine kosmasi gerekiyor ve kendi kendine kosmak icin bir | |
| 238 | +liste gerekiyor. | |
| 195 | 239 | |
| 196 | 240 | ### Bugun nasil cozuluyor |
| 197 | 241 | |
| 198 | -**Yapilandirmadan.** `service/src/config.py` icinde: | |
| 242 | +**Okul listesi:** artik backend'den (`insight.schools.list`, Madde 1a) gelir; | |
| 243 | +`ZEKA_SCHOOLS` yalnizca bir **operator filtresidir** (bos birakilirsa | |
| 244 | +dagitimdaki butun aktif okullar islenir). Yani "yeni okul gorunmez" riski okul | |
| 245 | +tarafinda kapandi; geriye **kadro** kaldi. | |
| 246 | + | |
| 247 | +**Ogrenci listesi:** hala yapilandirmadan. `service/src/config.py` icinde: | |
| 199 | 248 | |
| 200 | -- `ZEKA_SCHOOLS` -- islenecek okul sluglari, virgulle ayrilmis. Artik bir | |
| 201 | - FILTREDIR: bos birakilirsa kontrol veritabanindaki (`school` tablosu) | |
| 202 | - butun aktif okullar islenir (varsayilan: bos), | |
| 203 | 249 | - `ZEKA_STUDENT_SOURCE` = `config` | `file`, |
| 204 | 250 | - `ZEKA_STUDENTS` -- kullanici kimlikleri, virgulle ayrilmis, |
| 205 | 251 | - `ZEKA_STUDENT_FILE` -- ayni listenin dosya hali. |
| @@ -213,9 +259,10 @@ Yani kapsam **elle** tutulur. | ||
| 213 | 259 | ZEKA icin yoktur. Tohum verisinde bu kenar durum bilincli olarak vardir. |
| 214 | 260 | - **Ayrilan ogrenci silinmez.** Listede kaldigi surece ZEKA onun icin hesap |
| 215 | 261 | kosmaya devam eder ve her seferinde bos/hatali sonuc uretir. |
| 216 | -- **Yeni okul gorunmez.** Platforma bir okul eklendiginde ZEKA'nin yapilandirmasi | |
| 217 | - guncellenmediyse o okul hic islenmez -- ve bunun hicbir belirtisi olmaz, | |
| 218 | - cunku "islenmeyen okul" ile "sorunsuz islenen okul" ayni sessizlikte gorunur. | |
| 262 | +- **Yeni okul gorunmez** — okul listesi backend'den geldigi icin (Madde 1a) | |
| 263 | + bu risk kapandi; kalan risk, operatör filtresi (`ZEKA_SCHOOLS`) elle daraltilmis | |
| 264 | + birakilirsa ayni sessizligin geri gelmesidir: "filtreye takilmayan okul" ile | |
| 265 | + "sorunsuz islenen okul" ayni sessizlikte gorunur. | |
| 219 | 266 | - **Isletme maliyeti.** Kapsam, kod deposunda degil `compose.yaml` ortam |
| 220 | 267 | degiskeninde yasar; her mevcut degisikligi bir dagitim islemi haline gelir. |
| 221 | 268 | |
| @@ -225,9 +272,9 @@ Yani kapsam **elle** tutulur. | ||
| 225 | 272 | |
| 226 | 273 | | # | Istenen | Kaynak dosya | Olmazsa kaybedilen | |
| 227 | 274 | |---|---|---|---| |
| 228 | -| 1 | `insight.student` / `insight.class` / `insight.refresh` sabitleri + dagitim kodu | `src/constant.rs`, `src/ai/` | Backend ZEKA'yi **hic cagiramaz**; istege bagli her senaryo duser | | |
| 275 | +| 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` | | |
| 229 | 276 | | 2 | 9 sinav yolu (+3 sinif/ders yolu) izin listesine | `src/constant.rs:656-676` | **Madde analizi, konu karnesi, sinif isi haritasi** hic uretilemez | |
| 230 | -| 3 | Okul listeleme ucu + `GET /users/search` izin listesine | yeni uc; `src/constant.rs:656-676` | Kapsam elle tutulur; yeni ogrenci/okul **sessizce** gorunmez | | |
| 277 | +| 3 | `GET /users/search` izin listesine (okul listesi Madde 1a'da) | `src/constant.rs:656-676` | Ogrenci kadrosu elle tutulur; yeni ogrenci **sessizce** gorunmez | | |
| 231 | 278 | |
| 232 | 279 | --- |
| 233 | 280 |
service/docs/CIKTI-SOZLESMESI.mdmodified+238 -212
| @@ -2,21 +2,27 @@ | ||
| 2 | 2 | |
| 3 | 3 | > **Frontend ve backend ekibine verilecek tek belge budur.** |
| 4 | 4 | > ZEKA'nın ürettiği her satır, her alan, her kural kimliği burada. |
| 5 | -> DDL kaynağı: `service/schema/zeka.surql`. Yazan katman: | |
| 6 | -> `service/src/store.py`. Kural motoru: `service/src/compute/recommend.py`. | |
| 5 | +> DDL kaynağı **backend deposudur**: | |
| 6 | +> `hezarfen_backend/migrations/school/20260917000002_zeka.sql` — tablolar her | |
| 7 | +> okulun kendi veritabanında durur, sahibi backend'dir. | |
| 8 | +> Yazan katman: `service/src/store.py`, köprü deposu (`BridgeStore`). | |
| 9 | +> Kural motoru: `service/src/compute/recommend.py`. | |
| 7 | 10 | |
| 8 | 11 | --- |
| 9 | 12 | |
| 10 | 13 | ## 0. Beş cümlede sözleşme |
| 11 | 14 | |
| 12 | -1. ZEKA **kendi** SurrealDB veritabanına yazar (ns/db: `hezarfen`/`zeka`). | |
| 13 | - **Okul veritabanına hiçbir koşulda yazmaz**; okul verisini yalnız okur. | |
| 14 | -2. Tablo sayısı **beş**tir ve bu listenin dışında bir tablo yoktur. | |
| 15 | +1. ZEKA'nın **veritabanı bağlantısı yoktur**. Yazdığı her satır backend'e | |
| 16 | + QUIC köprüsünden, `insight.*` **yetenek çağrısıyla** gider; okulun kendi | |
| 17 | + API'sinden okuduğu veriler de aynı köprüdedir (`ApiRequest`). | |
| 18 | +2. Dokuz tablo vardır ve bu listenin dışında bir tablo yoktur. Hepsi `zeka_` | |
| 19 | + önekli ve hepsi **okulun kendi veritabanında**: kiracı, veritabanının | |
| 20 | + kendisidir, satırda `school` alanı yoktur. | |
| 15 | 21 | 3. Bütün zaman alanları **i64 unix milisaniye, UTC**. `datetime` tipi |
| 16 | 22 | kullanılmaz. |
| 17 | -4. Bütün kimlikler (öğrenci, soru, sınav, ders, konu) **düz metin**dir, | |
| 18 | - `record` bağlantısı değildir: ZEKA'nın veritabanında okul tabloları yoktur. | |
| 19 | - Biçim okul tarafındaki hâliyle korunur (`user:01K42...`). | |
| 23 | +4. Kimlikler okulun kendi uuid'leridir (`app_user`, `course`, `exam_question` | |
| 24 | + …); metin kimlik taşınmaz ve satır kimliğini **yazan taraf üretir** — | |
| 25 | + uuid7'yi backend mints eder. | |
| 20 | 26 | 5. **Tek bir "risk skoru" alanı yoktur.** Hiçbir tabloda `score`, `rank`, |
| 21 | 27 | `weight`, `severity` alanı bulunmaz ve bulunmayacaktır — sıralama şemadan |
| 22 | 28 | üretilemesin diye (`[T§6.6]`). |
| @@ -25,143 +31,185 @@ | ||
| 25 | 31 | |
| 26 | 32 | ## 1. Tabloların özeti |
| 27 | 33 | |
| 28 | -| # | Tablo | Satır neyi anlatır | Anahtar | Saklama | | |
| 29 | -|---|---|---|---|---| | |
| 30 | -| 1 | `student_summary` | Bir öğrencinin gecelik özeti | `{school}_{student}` | 400 gün | | |
| 31 | -| 2 | `recommendation` | Üretilmiş tek tavsiye + kanıtı | `{school}_{audience}_{product}_{rule_id}_{scope}` | `min(expires_at, +90 gün)` | | |
| 32 | -| 3 | `insight_run` | Koşu defteri | `{school}_{YYYY-MM-DD}` | 90 gün | | |
| 33 | -| 4 | `question_segment` | Bir sorunun bilişsel etiketi | `{school}_{question}` | 1095 gün | | |
| 34 | -| 5 | `student_segment_profile` | Öğrenci × boyut × etiket performansı | `{school}_{student}_{dimension}_{label}` | 400 gün | | |
| 34 | +Beş **varlık** ve dört **çocuk tablo** (eskiden gömülü diziydi, artık `ord` | |
| 35 | +kolonlu satırlar): | |
| 35 | 36 | |
| 36 | -Anahtarlar **kompozit**tir: tekillik yapısaldır, `UNIQUE` indekse gerek yoktur | |
| 37 | -ve gece koşusunu tekrar çalıştırmak satır çoğaltmaz (UPSERT idempotent). | |
| 37 | +|#|Tablo|Satır neyi anlatır|Anahtar|Saklama| | |
| 38 | +|---|---|---|---|---| | |
| 39 | +|1|`zeka_student_summary`|Bir öğrencinin gecelik özeti|`student`|400 gün| | |
| 40 | +|2|`zeka_attention_item`|Dikkat listesi, tetikleyici başına bir satır|`(student, trigger, course)`|ebeveynle| | |
| 41 | +|3|`zeka_recommendation`|Üretilmiş tek tavsiye + kanıtı|`id` (uuid); doğal anahtar `(audience, product, rule_id, about, scope)`|`min(expires_at, +90 gün)`| | |
| 42 | +|4|`zeka_run`|Koşu defteri|`run_day` (`YYYY-MM-DD`)|90 gün| | |
| 43 | +|5|`zeka_run_pending`|Bütçe dolunca kalanlar|`(run, student)`|ebeveynle| | |
| 44 | +|6|`zeka_run_failed_module`|Hata veren modüller|`(run, module)`|ebeveynle| | |
| 45 | +|7|`zeka_question_segment`|Bir sorunun bilişsel etiketi|`question`|1095 gün| | |
| 46 | +|8|`zeka_question_segment_dimension`|Üretim/deneysel boyut ayrımı|`(question, dimension)`|ebeveynle| | |
| 47 | +|9|`zeka_student_segment_profile`|Öğrenci × boyut × etiket performansı|`(student, dimension, label)`|400 gün| | |
| 48 | + | |
| 49 | +Anahtarlar **doğal**dır: gece koşusunu tekrar çalıştırmak satır çoğaltmaz | |
| 50 | +(upsert idempotent). Tavsiyenin `about` alanı **anahtarın parçasıdır** ve bu | |
| 51 | +süs değildir: öğretmen kuralı öğrenci başına bir kez ateşler; `about` anahtarda | |
| 52 | +olmasaydı otuz öğrenci tek anahtarı paylaşır, upsert sonuncuyu tutar ve | |
| 53 | +öğretmene otuz kişi yerine **biri** gösterilirdi. | |
| 38 | 54 | |
| 39 | 55 | --- |
| 40 | 56 | |
| 41 | 57 | ## 2. Tablolar, alan alan |
| 42 | 58 | |
| 43 | -### 2.1 `student_summary` | |
| 59 | +### 2.1 `zeka_student_summary` | |
| 44 | 60 | |
| 45 | 61 | | Alan | Tip | Anlam | |
| 46 | 62 | |---|---|---| |
| 47 | -| `school` | `string` | Okul slug'ı (kiracı ayracı). Her sorguya konur. | | |
| 48 | -| `student` | `string` | Öğrenci kimliği | | |
| 49 | -| `marks` | `option<object>` FLEXIBLE | Not modülü çıktısı: `courses.<course>.{average, n_marks, placement{band, z, class_average, class_sd, cohort_n, confidence}}` | | |
| 50 | -| `attendance` | `option<object>` FLEXIBLE | Devam modülü çıktısı | | |
| 51 | -| `submission` | `option<object>` FLEXIBLE | Ödev/teslim modülü çıktısı; `upcoming[]` yaklaşan teslimler | | |
| 52 | -| `study` | `option<object>` FLEXIBLE | Çalışma (pomodoro) modülü çıktısı | | |
| 53 | -| `attention` | `option<array<object>>` | **Dikkat listesi.** Her öğe TEK tetikleyici: `{trigger, fact, evidence, window_from, window_to}` | | |
| 54 | -| `confidence` | `string` | `none` \| `exploratory` \| `stable` | | |
| 55 | -| `computed_at` | `int` | Hesap anı (unix ms) | | |
| 56 | -| `retain_until` | `int` | Bu damgadan sonra süpürülür | | |
| 57 | - | |
| 58 | -`marks`/`attendance`/`submission`/`study` **FLEXIBLE**'dır: şekil hesap | |
| 63 | +| `student` | `uuid` | Öğrenci kimliği (`app_user`) — **PK** | | |
| 64 | +| `marks` | `JSONB` | Not modülü çıktısı: `courses.<course>.{average, n_marks, placement{band, z, class_average, class_sd, cohort_n, confidence}}` | | |
| 65 | +| `attendance` | `JSONB` | Devam modülü çıktısı | | |
| 66 | +| `submission` | `JSONB` | Ödev/teslim modülü çıktısı; `upcoming[]` yaklaşan teslimler | | |
| 67 | +| `study` | `JSONB` | Çalışma (pomodoro) modülü çıktısı | | |
| 68 | +| `confidence` | `TEXT` | `none` \| `exploratory` \| `stable` | | |
| 69 | +| `computed_at` | `BIGINT` | Hesap anı (unix ms) | | |
| 70 | +| `retain_until` | `BIGINT` | Bu damgadan sonra süpürülür | | |
| 71 | + | |
| 72 | +Dikkat listesi bu satırın içinde **değildir**: `zeka_attention_item` çocuk | |
| 73 | +tablosundadır, `ord` yazanın sırasını tutar (tetikleyiciye göre **alfabetik**, | |
| 74 | +şiddete göre değil). | |
| 75 | + | |
| 76 | +`marks`/`attendance`/`submission`/`study` **JSONB**'dir: şekil hesap | |
| 59 | 77 | modülüne aittir ve her kural sürümünde şema değişmek zorunda kalmaz. Frontend |
| 60 | 78 | bu nesnelerin içinden **okuduğu alanı adıyla** almalı, sırayla değil. |
| 61 | 79 | |
| 62 | -### 2.2 `recommendation` | |
| 80 | +#### `zeka_attention_item` — çocuk tablo | |
| 63 | 81 | |
| 64 | 82 | | Alan | Tip | Anlam | |
| 65 | 83 | |---|---|---| |
| 66 | -| `school` | `string` | Okul slug'ı | | |
| 67 | -| `audience` | `string` | **Kime gösterilecek** (öğrenci ya da öğretmen kimliği) | | |
| 68 | -| `about` | `option<string>` | **Kim hakkında.** Öğrenci kendi kartında boştur | | |
| 69 | -| `audience_role` | `string` | `student` \| `teacher` \| `parent` \| `manager` — **rol kapısı** | | |
| 70 | -| `product` | `string` | `O1` \| `O2` \| `O3` \| `O4` \| `T3` \| `T4` | | |
| 71 | -| `course` | `option<string>` | İlgili ders (varsa) | | |
| 72 | -| `rule_id` | `string` | Hangi kural (§3 listesi) | | |
| 73 | -| `rule_version` | `int` | Kural kataloğu sürümü. Arttığında kullanıcıya "hesaplama yöntemi güncellendi" gösterilir | | |
| 74 | -| `evidence` | `object` FLEXIBLE | **Boş olamaz.** "Neden?" ekranını besleyen sayılar; içinde ayrıca `limitation` (Sınır satırı) | | |
| 75 | -| `confidence` | `string` | `none` \| `exploratory` \| `stable` | | |
| 76 | -| `created_at` | `int` | Üretim anı | | |
| 77 | -| `expires_at` | `int` | Bu andan sonra **gösterilmez** | | |
| 78 | -| `retain_until` | `int` | Bu andan sonra **silinir** | | |
| 79 | -| `dismissed_at` | `option<int>` | Kullanıcı kapattıysa an | | |
| 80 | -| `dismissed_by` | `option<string>` | Kapatan kişi | | |
| 81 | -| `dismiss_reason` | `option<string>` | `bu doğru değil` gibi serbest metin | | |
| 84 | +| `student` | `uuid` | Özetin sahibi (FK → `zeka_student_summary`) | | |
| 85 | +| `trigger` | `TEXT` | `attendance` \| `homework` \| `mark_trend` | | |
| 86 | +| `course` | `uuid`, boş olabilir | Maddenin dersi; yalnız not-eğilimi tetikleyicisinde dolu | | |
| 87 | +| `fact` | `TEXT` | **Öğretmenin okuduğu cümle.** Yargı değil olgu: "son 30 günün 4 ödevi teslim edilmedi" | | |
| 88 | +| `window_from` / `window_to` | `BIGINT` | Maddenin penceresi (her maddede sorulur) | | |
| 89 | +| `evidence` | `JSONB` | Arkasındaki sayılar. **Boş olamaz** — açıklanamayan madde yazılmaz | | |
| 90 | +| `ord` | `SMALLINT` | Yazma sırası | | |
| 91 | + | |
| 92 | +Tekil: `(student, trigger, course)`. | |
| 93 | + | |
| 94 | +### 2.2 `zeka_recommendation` | |
| 95 | + | |
| 96 | +| Alan | Tip | Anlam | | |
| 97 | +|---|---|---| | |
| 98 | +| `id` | `uuid` | Satır kimliği. **Backend üretir**, ZEKA göndermez — kapatma tek satıra yazılan bir işlemdir | | |
| 99 | +| `audience` | `uuid` | **Kime gösterilecek** (öğrenci ya da öğretmen) | | |
| 100 | +| `about` | `uuid`, boş olabilir | **Kim hakkında.** Öğrenci kendi kartında boştur. **Doğal anahtarın parçası** | | |
| 101 | +| `audience_role` | `TEXT` | `student` \| `teacher` \| `parent` \| `manager` — **rol kapısı** | | |
| 102 | +| `product` | `TEXT` | `O1` \| `O2` \| `O3` \| `O4` \| `T3` \| `T4` | | |
| 103 | +| `scope` | `TEXT`, boş olabilir | Kuralın kendi kapsamı (segment etiketi gibi); ders değil | | |
| 104 | +| `course` | `uuid`, boş olabilir | İlgili ders (varsa) | | |
| 105 | +| `rule_id` | `TEXT` | Hangi kural (§3 listesi) | | |
| 106 | +| `rule_version` | `BIGINT` | Kural kataloğu sürümü. Arttığında kullanıcıya "hesaplama yöntemi güncellendi" gösterilir | | |
| 107 | +| `evidence` | `JSONB` | **Boş olamaz.** "Neden?" ekranını besleyen sayılar; içinde ayrıca `limitation` (Sınır satırı) | | |
| 108 | +| `confidence` | `TEXT` | `none` \| `exploratory` \| `stable` | | |
| 109 | +| `created_at` | `BIGINT` | Üretim anı | | |
| 110 | +| `expires_at` | `BIGINT` | Bu andan sonra **gösterilmez** | | |
| 111 | +| `retain_until` | `BIGINT` | Bu andan sonra **silinir** | | |
| 112 | +| `dismissed_at` | `BIGINT` | Kullanıcı kapattıysa an | | |
| 113 | +| `dismissed_by` | `uuid` | Kapatan kişi | | |
| 114 | +| `dismiss_reason` | `TEXT` | `bu doğru değil` gibi serbest metin | | |
| 115 | + | |
| 116 | +Doğal anahtar: `(audience, product, rule_id, about, scope)`, `NULLS NOT | |
| 117 | +DISTINCT` — "kapsamsız" da bir yuva tutar. | |
| 82 | 118 | |
| 83 | 119 | **Beş bölümlü "Neden?"** zorunludur: Olgu · Karşılaştırma · Kural (hangi eşik, |
| 84 | 120 | hangi sürüm) · **Sınır** (neyin dahil olmadığı) · Tarih. Sınır satırı |
| 85 | 121 | `evidence.limitation` alanındadır ve **gösterilmesi zorunludur**; o satır |
| 86 | 122 | olmadan ürün olduğundan çok şey bildiğini ima eder. |
| 87 | 123 | |
| 88 | -`dismissed_*` alanlarını **yalnız uygulama yazar**. Gece koşusu `MERGE` | |
| 89 | -kullanır ve bu alanlara dokunmaz. | |
| 124 | +`dismissed_*` alanlarını **yalnız uygulama yazar**. Gece koşusu **upsert** | |
| 125 | +kullanır ve bu üç alana dokunmaz. | |
| 90 | 126 | |
| 91 | -### 2.3 `insight_run` | |
| 127 | +### 2.3 `zeka_run` | |
| 92 | 128 | |
| 93 | 129 | | Alan | Tip | Anlam | |
| 94 | 130 | |---|---|---| |
| 95 | -| `school` | `string` | Okul | | |
| 96 | -| `started_at` / `finished_at` | `int` / `option<int>` | Koşu penceresi | | |
| 97 | -| `status` | `string` | `running` \| `ok` \| `partial` \| `failed` \| `skipped` | | |
| 98 | -| `duration_ms` | `option<int>` | Süre | | |
| 99 | -| `students_total` / `students_ok` / `students_failed` / `students_skipped` | `int` | Muhasebe | | |
| 100 | -| `rows_written` | `int` | Yazılan satır | | |
| 101 | -| `pending_students` | `option<array<string>>` | Bütçe aşıldıysa **devreden** öğrenciler; sonraki koşu buradan devam eder | | |
| 102 | -| `failed_modules` | `option<array<string>>` | Düşen modül adları → UI'da "eksik" işareti | | |
| 131 | +| `run_day` | `TEXT` (`YYYY-MM-DD`) | **PK**. Gün backend'de yeniden türetilmez; TR gününü bilen taraf ZEKA | | |
| 132 | +| `started_at` / `finished_at` | `BIGINT` / boş olabilir | Koşu penceresi | | |
| 133 | +| `status` | `TEXT` | `running` \| `ok` \| `partial` \| `failed` \| `skipped` | | |
| 134 | +| `duration_ms` | `BIGINT` | Süre | | |
| 135 | +| `students_total` / `students_ok` / `students_failed` / `students_skipped` | `BIGINT` | Muhasebe | | |
| 136 | +| `rows_written` | `BIGINT` | Yazılan satır | | |
| 103 | 137 | | `budget_exceeded` | `bool` | Zaman bütçesi aşıldı mı | |
| 104 | -| `budget_ms` | `int` | Tavan | | |
| 105 | -| `retain_until` | `int` | 90 gün | | |
| 138 | +| `budget_ms` | `BIGINT` | Tavan | | |
| 139 | +| `retain_until` | `BIGINT` | 90 gün | | |
| 106 | 140 | |
| 107 | 141 | `status = partial` ise ekran **"bu gece bazı öğrenciler işlenemedi"** demeli; |
| 108 | -sessizce eksik veri göstermemeli. | |
| 142 | +sessizce eksik veri göstermemeli. `partial`'ın bir kaynağı da depodur: bir | |
| 143 | +yazma grubu ikinci denemede de düşerse koşu `partial` yazılır. | |
| 144 | + | |
| 145 | +#### Çocuk tablolar | |
| 109 | 146 | |
| 110 | -### 2.4 `question_segment` — YENİ | |
| 147 | +| Tablo | Alanlar | Ne tutar | | |
| 148 | +|---|---|---| | |
| 149 | +| `zeka_run_pending` | `run`, `student`, `ord` | Bütçe aşıldıysa **devreden** öğrenciler; sonraki koşu buradan devam eder | | |
| 150 | +| `zeka_run_failed_module` | `run`, `module`, `ord` | Düşen modül adları → UI'da "eksik" işareti | | |
| 151 | + | |
| 152 | +### 2.4 `zeka_question_segment` | |
| 111 | 153 | |
| 112 | 154 | Bir sorunun bilişsel etiketi. **Kişisel veri değildir**, hiçbir öğrenciye |
| 113 | 155 | bağlanamaz. Kaynağı `service/src/segment/` hattıdır (LLM etiketleme). |
| 114 | 156 | |
| 115 | 157 | | Alan | Tip | Anlam | |
| 116 | 158 | |---|---|---| |
| 117 | -| `school` | `string` | Okul slug'ı | | |
| 118 | -| `question` | `string` | Soru kimliği (`exam_question:<ULID>`) | | |
| 119 | -| `exam` | `option<string>` | Sınav kimliği | | |
| 120 | -| `course` | `option<string>` | Ders kimliği (kaynakta yoksa boş) | | |
| 121 | -| `subject` | `option<string>` | Konu kimliği | | |
| 122 | -| `bilissel_talep` | `string` | `hatirlama` \| `uygulama` \| `analiz` | | |
| 123 | -| `dikkat_tuzagi` | `string` | `var` \| `yok` | | |
| 124 | -| `okuma_yuku` | `string` | `dusuk` \| `yuksek` | | |
| 125 | -| `adim_sayisi` | `string` | `tek_adim` \| `cok_adim` — **DENEYSEL** (aşağı akışta kullanılmaz) | | |
| 126 | -| `confidence_bilissel_talep` | `float` | Modelin bu boyuttaki güveni [0,1] | | |
| 127 | -| `confidence_dikkat_tuzagi` | `float` | " | | |
| 128 | -| `confidence_okuma_yuku` | `float` | " | | |
| 129 | -| `confidence_adim_sayisi` | `float` | " | | |
| 130 | -| `confidence` | `string` | Satır kademesi: **üretim** boyutlarının en düşük güveninden türetilir. Deneysel boyut bu kademeye girmez | | |
| 131 | -| `downstream_dimensions` | `option<array<string>>` | Öğrenci profiline ve kurallara **giren** boyutlar | | |
| 132 | -| `experimental_dimensions` | `option<array<string>>` | Etiketlenen ama **girmeyen** boyutlar | | |
| 133 | -| `trap_choice` | `option<string>` | `dikkat_tuzagi = var` ise tuzak şıkkın kimliği. `yok` ise alan **hiç yazılmaz** | | |
| 134 | -| `rationale` | `string` | Modelin kendi gerekçesi, en fazla iki cümle. **Öğrenciye gösterilmez** (§5) | | |
| 135 | -| `model` | `string` | Etiketi üreten model kimliği | | |
| 136 | -| `prompt_version` | `string` | İstem sürümü | | |
| 137 | -| `variant` | `option<string>` | Etiketleyici varyantı (`baseline`, `self_consistency`, …) | | |
| 138 | -| `computed_at` | `int` | Etiketleme anı | | |
| 139 | -| `retain_until` | `int` | 1095 gün | | |
| 140 | - | |
| 141 | -**Deneysel boyut neden şemada duruyor:** `adim_sayisi` etiketlenir ve | |
| 142 | -raporlanır, ama LLM etiketlemesinde kararlılık kapısını (alpha ≥ 0,70) | |
| 143 | -geçemedi. Bu yüzden öğrenci profiline ve tavsiye kurallarına **girmez**. Bunu | |
| 144 | -belgeye bakmadan anlayabilmek için satırın kendisi iki listeyi taşır. Frontend | |
| 145 | -`downstream_dimensions` içinde olmayan bir boyutu **karar ekranında | |
| 146 | -kullanmamalıdır**. | |
| 147 | - | |
| 148 | -### 2.5 `student_segment_profile` — YENİ | |
| 159 | +| `question` | `uuid` | Soru kimliği — **PK** (FK: `exam_question(exam, id)`) | | |
| 160 | +| `exam` | `uuid` | Sınav kimliği | | |
| 161 | +| `course` | `uuid` | Ders kimliği (yazma anında çözülür) | | |
| 162 | +| `subject` | `uuid` | Konu kimliği | | |
| 163 | +| `bilissel_talep` | `TEXT` | `hatirlama` \| `uygulama` \| `analiz` | | |
| 164 | +| `dikkat_tuzagi` | `TEXT` | `var` \| `yok` | | |
| 165 | +| `okuma_yuku` | `TEXT` | `dusuk` \| `yuksek` | | |
| 166 | +| `adim_sayisi` | `TEXT` | `tek_adim` \| `cok_adim` — **DENEYSEL** (aşağı akışta kullanılmaz) | | |
| 167 | +| `confidence_bilissel_talep` | `double` | Modelin bu boyuttaki güveni [0,1] | | |
| 168 | +| `confidence_dikkat_tuzagi` | `double` | " | | |
| 169 | +| `confidence_okuma_yuku` | `double` | " | | |
| 170 | +| `confidence_adim_sayisi` | `double` | " | | |
| 171 | +| `confidence` | `TEXT` | Satır kademesi: **üretim** boyutlarının en düşük güveninden türetilir. Deneysel boyut bu kademeye girmez | | |
| 172 | +| `trap_choice` | `TEXT`, boş olabilir | `dikkat_tuzagi = var` ise tuzak şıkkın kimliği | | |
| 173 | +| `rationale` | `TEXT` | Modelin kendi gerekçesi, en fazla iki cümle. **Öğrenciye gösterilmez** (§5) | | |
| 174 | +| `model` | `TEXT` | Etiketi üreten model kimliği | | |
| 175 | +| `prompt_version` | `TEXT` | İstem sürümü | | |
| 176 | +| `variant` | `TEXT`, boş olabilir | Etiketleyici varyantı (`baseline`, `self_consistency`, …) | | |
| 177 | +| `computed_at` | `BIGINT` | Etiketleme anı | | |
| 178 | +| `retain_until` | `BIGINT` | 1095 gün | | |
| 179 | + | |
| 180 | +#### `zeka_question_segment_dimension` — çocuk tablo | |
| 181 | + | |
| 182 | +| Alan | Tip | Anlam | | |
| 183 | +|---|---|---| | |
| 184 | +| `question` | `uuid` | FK → `zeka_question_segment` | | |
| 185 | +| `dimension` | `TEXT` | `bilissel_talep` \| `dikkat_tuzagi` \| `okuma_yuku` \| `adim_sayisi` | | |
| 186 | +| `role` | `TEXT` | `downstream` (öğrenci profiline ve kurallara **girer**) \| `experimental` | | |
| 187 | +| `ord` | `SMALLINT` | Yazma sırası | | |
| 188 | + | |
| 189 | +**Deneysel boyut neden duruyor:** `adim_sayisi` etiketlenir ve raporlanır, ama | |
| 190 | +LLM etiketlemesinde kararlılık kapısını (alpha ≥ 0,70) geçemedi. Bu yüzden | |
| 191 | +öğrenci profiline ve tavsiye kurallarına **girmez**. Bunu belgeye bakmadan | |
| 192 | +anlayabilmek için satırın kendisi `role` kolonunu taşır. Frontend `role = | |
| 193 | +downstream` olmayan bir boyutu **karar ekranında kullanmamalıdır**. | |
| 194 | + | |
| 195 | +### 2.5 `zeka_student_segment_profile` | |
| 149 | 196 | |
| 150 | 197 | | Alan | Tip | Anlam | |
| 151 | 198 | |---|---|---| |
| 152 | -| `school` | `string` | Okul slug'ı | | |
| 153 | -| `student` | `string` | Öğrenci kimliği | | |
| 154 | -| `dimension` | `string` | `bilissel_talep` \| `dikkat_tuzagi` \| `okuma_yuku` (yalnız üretim boyutları) | | |
| 155 | -| `label` | `string` | O boyutun bir etiketi | | |
| 156 | -| `n_answers` | `int` | Bu segmentte **işaretlenmiş** cevap sayısı (boş bırakılan madde paydaya girmez) | | |
| 157 | -| `n_correct` | `int` | Doğru sayısı | | |
| 158 | -| `accuracy` | `float` | `n_correct / n_answers`. **Tek başına gösterilmez** (§5) | | |
| 159 | -| `overall_n_answers` | `int` | Öğrencinin etiketli tüm maddelerdeki cevap sayısı | | |
| 160 | -| `overall_accuracy` | `float` | Öğrencinin genel doğruluğu | | |
| 161 | -| `contrast` | `float` | **`accuracy − overall_accuracy`.** Bu tablonun asıl ölçüsü | | |
| 162 | -| `confidence` | `string` | `none` (n<30) \| `exploratory` (n≥30) \| `stable` (n≥100) | | |
| 163 | -| `computed_at` | `int` | Hesap anı | | |
| 164 | -| `retain_until` | `int` | 400 gün | | |
| 199 | +| `student` | `uuid` | Öğrenci kimliği (**PK'nın parçası**) | | |
| 200 | +| `dimension` | `TEXT` | `bilissel_talep` \| `dikkat_tuzagi` \| `okuma_yuku` (yalnız üretim boyutları) | | |
| 201 | +| `label` | `TEXT` | O boyutun bir etiketi | | |
| 202 | +| `n_answers` | `BIGINT` | Bu segmentte **işaretlenmiş** cevap sayısı (boş bırakılan madde paydaya girmez) | | |
| 203 | +| `n_correct` | `BIGINT` | Doğru sayısı | | |
| 204 | +| `accuracy` | `double` | `n_correct / n_answers`. **Tek başına gösterilmez** (§5) | | |
| 205 | +| `overall_n_answers` | `BIGINT` | Öğrencinin etiketli tüm maddelerdeki cevap sayısı | | |
| 206 | +| `overall_accuracy` | `double` | Öğrencinin genel doğruluğu | | |
| 207 | +| `contrast` | `double` | **`accuracy − overall_accuracy`.** Bu tablonun asıl ölçüsü | | |
| 208 | +| `confidence` | `TEXT` | `none` (n<30) \| `exploratory` (n≥30) \| `stable` (n≥100) | | |
| 209 | +| `computed_at` | `BIGINT` | Hesap anı | | |
| 210 | +| `retain_until` | `BIGINT` | 400 gün | | |
| 211 | + | |
| 212 | +Anahtar: `(student, dimension, label)`. | |
| 165 | 213 | |
| 166 | 214 | **`contrast` neden var:** ham `accuracy` bir ayrım ölçüsü **değildir**. İyi |
| 167 | 215 | öğrenci her segmentte yüksek, zayıf öğrenci her segmentte düşük çıkar; böyle |
| @@ -184,17 +232,17 @@ göre geride" diyecekse sayıyı oradan almalıdır. | ||
| 184 | 232 | |
| 185 | 233 | | `rule_id` | Ürün | Kime | Ne der | Hangi veriden | |
| 186 | 234 | |---|---|---|---|---| |
| 187 | -| `O1.review_band` | O1 | öğrenci | Bu derste tekrar önerilir | `student_summary.marks` (`placement.band = review`, n_marks ≥ 3) | | |
| 188 | -| `O2.segment_cognitive_gap` | O2 | öğrenci | Bu tür sorularda kendi genel seviyene göre geridesin | `student_segment_profile` (`bilissel_talep`, `okuma_yuku`); n ≥ 100 ve göreli kontrast ≤ −0,080 / −0,060 | | |
| 189 | -| `O2.segment_trap_prone` | O2 | öğrenci | Dikkat tuzağı taşıyan sorularda akranlarına göre daha çok kaybediyorsun | `student_segment_profile` (`dikkat_tuzagi=var`); n ≥ 100 ve göreli kontrast ≤ −0,032 | | |
| 190 | -| `O3.pattern` | O3 | öğrenci | Çalışma düzenin şöyle görünüyor | `student_summary.study` (n_stints ≥ 5) | | |
| 191 | -| `O4.deadline` | O4 | öğrenci | Yaklaşan teslim | `student_summary.submission.upcoming` | | |
| 235 | +| `O1.review_band` | O1 | öğrenci | Bu derste tekrar önerilir | `zeka_student_summary.marks` (`placement.band = review`, n_marks ≥ 3) | | |
| 236 | +| `O2.segment_cognitive_gap` | O2 | öğrenci | Bu tür sorularda kendi genel seviyene göre geridesin | `zeka_student_segment_profile` (`bilissel_talep`, `okuma_yuku`); n ≥ 100 ve göreli kontrast ≤ −0,080 / −0,060 | | |
| 237 | +| `O2.segment_trap_prone` | O2 | öğrenci | Dikkat tuzağı taşıyan sorularda akranlarına göre daha çok kaybediyorsun | `zeka_student_segment_profile` (`dikkat_tuzagi=var`); n ≥ 100 ve göreli kontrast ≤ −0,032 | | |
| 238 | +| `O3.pattern` | O3 | öğrenci | Çalışma düzenin şöyle görünüyor | `zeka_student_summary.study` (n_stints ≥ 5) | | |
| 239 | +| `O4.deadline` | O4 | öğrenci | Yaklaşan teslim | `zeka_student_summary.submission.upcoming` | | |
| 192 | 240 | | `T3.class_gap` | T3 | öğretmen | Sınıf düzeyinde boşluk | `marks` (kohort ort. < 50, kohort ≥ 8) | |
| 193 | 241 | | `T3.individual_gap` | T3 | öğretmen | Bireysel destek | `marks` (kohort ort. ≥ 50, z < −0,8) | |
| 194 | -| `T3.segment_class_gap` | T3 | öğretmen | Sınıf bu bilişsel segmentte topluca geride | `student_segment_profile` sınıf toplaması; ≥ 8 öğrenci ve sınıf ortalama göreli kontrast ≤ −0,040. **Bugün hiçbir koşu bunu üretmiyor** — §4.1 | | |
| 195 | -| `T4.attendance` | T4 | **yalnız öğretmen** | Devam tetikleyicisi | `student_summary.attention` | | |
| 196 | -| `T4.homework` | T4 | **yalnız öğretmen** | Ödev tetikleyicisi | `student_summary.attention` | | |
| 197 | -| `T4.mark_trend` | T4 | **yalnız öğretmen** | Not eğilimi tetikleyicisi | `student_summary.attention` | | |
| 242 | +| `T3.segment_class_gap` | T3 | öğretmen | Sınıf bu bilişsel segmentte topluca geride | `zeka_student_segment_profile` sınıf toplaması; ≥ 8 öğrenci ve sınıf ortalama göreli kontrast ≤ −0,040. **Bugün hiçbir koşu bunu üretmiyor** — §4.1 | | |
| 243 | +| `T4.attendance` | T4 | **yalnız öğretmen** | Devam tetikleyicisi | `zeka_attention_item` | | |
| 244 | +| `T4.homework` | T4 | **yalnız öğretmen** | Ödev tetikleyicisi | `zeka_attention_item` | | |
| 245 | +| `T4.mark_trend` | T4 | **yalnız öğretmen** | Not eğilimi tetikleyicisi | `zeka_attention_item` | | |
| 198 | 246 | |
| 199 | 247 | Segment kurallarının ölçülmüş isabeti: `docs/SEGMENT-CIKTI.md` §4. |
| 200 | 248 | **Özet:** ezberci arketibi kesinlik 0,765 / duyarlılık 0,722; aceleci 0,793 / |
| @@ -236,13 +284,16 @@ cevaplaması için. | ||
| 236 | 284 | |
| 237 | 285 | ### 4.1 Ne zaman yazılır |
| 238 | 286 | |
| 239 | -| Tablo | Yazan | Ne zaman | Kip | | |
| 287 | +| Tablo | Yazan | Ne zaman | Köprü çağrısı | | |
| 240 | 288 | |---|---|---|---| |
| 241 | -| `student_summary` | `pipeline.run_school` | Gece koşusu, okul başına | `CONTENT` (tam değiştirir) | | |
| 242 | -| `recommendation` | `pipeline.run_school` **ve** `segment.cli run --persist` | Gece koşusu / segmentasyon koşusu | **`MERGE`** | | |
| 243 | -| `insight_run` | `pipeline.run_school` | Koşu başı ve sonu | `CONTENT` | | |
| 244 | -| `question_segment` | `segment.cli run --persist` | Segmentasyon koşusu (ayrı, seyrek) | **`MERGE`** | | |
| 245 | -| `student_segment_profile` | `segment.cli run --persist` | Segmentasyon koşusu | **`MERGE`** | | |
| 289 | +| `zeka_student_summary` (+`zeka_attention_item`) | `pipeline.run_school` | Gece koşusu, okul başına | `insight.summary.upsert` | | |
| 290 | +| `zeka_recommendation` | `pipeline.run_school` **ve** `segment.cli run --persist` | Gece koşusu / segmentasyon koşusu | `insight.recommendation.upsert` | | |
| 291 | +| `zeka_run` (+`zeka_run_pending`, `zeka_run_failed_module`) | `pipeline.run_school` | Koşu başı ve sonu | `insight.run.upsert` | | |
| 292 | +| `zeka_question_segment` (+`zeka_question_segment_dimension`) | `segment.cli run --persist` | Segmentasyon koşusu (ayrı, seyrek) | `insight.segment.upsert` | | |
| 293 | +| `zeka_student_segment_profile` | `segment.cli run --persist` | Segmentasyon koşusu | `insight.profile.upsert` | | |
| 294 | + | |
| 295 | +Yazma **500 satırlık gruplar** hâlindedir; grup reddedilirse ikinci kez | |
| 296 | +denenir, ikinci düşüşte atlanır ve koşu `partial` yazılır. Sessiz başarı yoktur. | |
| 246 | 297 | |
| 247 | 298 | `O2.segment_*` satırlarını **segmentasyon koşusu** üretir, gece koşusu |
| 248 | 299 | değil. Sebep ölçüseldir: segment kuralları kohort ortalamasına göre |
| @@ -252,48 +303,52 @@ ders öğretmeni `Source` arayüzünden gelir, segmentasyon hattının elinde | ||
| 252 | 303 | yoktur. Öğretmeni çözülemeyen madde üretilmez; kural kodda ve katalogda |
| 253 | 304 | hazırdır, çağıran taraf sınıf/öğretmen eşlemesini verdiğinde çalışır. |
| 254 | 305 | |
| 255 | -`MERGE` seçimi güvenlik kararıdır: `CONTENT` ile yazılsaydı her koşu, | |
| 256 | -kullanıcının **"bu tavsiye faydalı değil"** kaydını ve dışarıdan eklenmiş | |
| 257 | -alanları sessizce silerdi. | |
| 306 | +**Upsert** seçimi güvenlik kararıdır: tam değiştirme kullansaydık her koşu, | |
| 307 | +kullanıcının **"bu tavsiye faydalı değil"** kaydını (`dismissed_at`, | |
| 308 | +`dismissed_by`, `dismiss_reason`) sessizce silerdi. Bu üç alanı yalnız | |
| 309 | +uygulama yazar; ZEKA hiç üretmez. | |
| 258 | 310 | |
| 259 | 311 | Segment tabloları gece koşusuna **bağlı değildir**: `--persist` verilmediği |
| 260 | -sürece segmentasyon hattı tek bir SurrealQL ifadesi bile çalıştırmaz. | |
| 261 | -Segmentasyon hiç koşmamışsa `question_segment` ve `student_segment_profile` | |
| 262 | -boştur, `O2.segment_*` / `T3.segment_class_gap` kuralları **hiç üretilmez** — | |
| 263 | -ekran bunun için boş kart göstermemeli, o bölümü **hiç göstermemelidir**. | |
| 312 | +sürece segmentasyon hattı tek bir `insight.*` yazma çağrısı bile yapmaz. | |
| 313 | +Segmentasyon hiç koşmamışsa `zeka_question_segment` ve | |
| 314 | +`zeka_student_segment_profile` boştur, `O2.segment_*` / `T3.segment_class_gap` | |
| 315 | +kuralları **hiç üretilmez** — ekran bunun için boş kart göstermemeli, o bölümü | |
| 316 | +**hiç göstermemelidir**. | |
| 264 | 317 | |
| 265 | 318 | ### 4.2 Ne zaman düşer |
| 266 | 319 | |
| 267 | 320 | İki ayrı kavram vardır ve karıştırılmamalıdır: |
| 268 | 321 | |
| 269 | -* **`expires_at`** (`recommendation`): *gösterme*. Bu andan sonra tavsiye | |
| 322 | +* **`expires_at`** (`zeka_recommendation`): *gösterme*. Bu andan sonra tavsiye | |
| 270 | 323 | ekranda **görünmez**, ama satır hâlâ durur. |
| 271 | 324 | * **`retain_until`** (her tablo): *silme*. Gece koşusunun sonunda |
| 272 | - `DELETE <tablo> WHERE retain_until < now` çalışır ve satır **gerçekten | |
| 273 | - silinir**. | |
| 274 | - | |
| 275 | -Süpürme her koşunun **en sonunda**, okul bazında, sıralı koşar. | |
| 325 | + `insight.retention.sweep` çağrısı satırları **gerçekten siler**; süpürmeyi | |
| 326 | + koşturan taraf backend'dir, çünkü sınırı yazan taraf ZEKA'dır ve süpürme | |
| 327 | + okulun veritabanında koşar. | |
| 276 | 328 | |
| 277 | -Ayrıca **mezuniyet/ayrılma temizliği** vardır: öğrenci listesinde olmayan | |
| 278 | -kişinin `student_summary`, `student_segment_profile` ve hakkındaki | |
| 279 | -`recommendation` satırları silinir. `question_segment` bundan **etkilenmez**: | |
| 280 | -o satır bir soru hakkındadır, kişisel veri değildir. | |
| 329 | +Ayrıca **mezuniyet/ayrılma temizliği** vardır (`insight.departed.purge`): | |
| 330 | +öğrenci listesinde olmayan kişinin `zeka_student_summary`, | |
| 331 | +`zeka_student_segment_profile` ve hakkındaki `zeka_recommendation` satırları | |
| 332 | +silinir. `zeka_question_segment` bundan **etkilenmez**: o satır bir soru | |
| 333 | +hakkındadır, kişisel veri değildir. | |
| 281 | 334 | |
| 282 | 335 | ### 4.3 Kullanıcı kapatınca ne olur |
| 283 | 336 | |
| 284 | -1. Uygulama `recommendation` satırına `dismissed_at`, `dismissed_by`, | |
| 337 | +1. Uygulama `zeka_recommendation` satırına `dismissed_at`, `dismissed_by`, | |
| 285 | 338 | `dismiss_reason` yazar. **ZEKA bu alanları hiç üretmez.** |
| 286 | 339 | 2. Satır **silinmez**. Kapatma bir veridir: bir kural sürekli "bu doğru değil" |
| 287 | - ile kapanıyorsa kural yanlıştır. `recommendation_rule` indeksi | |
| 288 | - (`rule_id, created_at`) tam bu ölçüm içindir. | |
| 289 | -3. Ertesi gece aynı kural yeniden ateşlerse `MERGE` sayesinde kapatma izi | |
| 290 | - **korunur**. Ekran kapatılmış bir tavsiyeyi tekrar göstermemelidir; | |
| 291 | - `dismissed_at` dolu olan satır filtrelenir. | |
| 340 | + ile kapanıyorsa kural yanlıştır. `(rule_id, created_at)` indeksi tam bu | |
| 341 | + ölçüm içindir. | |
| 342 | +3. Ertesi gece aynı kural yeniden ateşlerse **upsert** sayesinde kapatma izi | |
| 343 | + **korunur** (bu yüzden tam değiştirme değil). Ekran kapatılmış bir tavsiyeyi | |
| 344 | + tekrar göstermemelidir; `dismissed_at` dolu olan satır filtrelenir. | |
| 292 | 345 | 4. Süpürme kapatılmış satırı da normal `retain_until`'ünde siler. |
| 293 | 346 | |
| 294 | 347 | **Otomatik eylem yoktur.** Hiçbir tavsiye bir notu değiştirmez, bir öğrenciyi |
| 295 | -bir gruba atamaz. `store.py` yalnız bu beş tabloya yazar; buradan okuyup başka | |
| 296 | -bir tabloyu güncelleyen bir yol **yoktur** ve bu şema düzeyinde garantidir. | |
| 348 | +bir gruba atamaz. `store.py` yalnız bu dokuz tabloya yazar; başka bir tabloyu | |
| 349 | +güncelleyen bir yol **yoktur** ve bu yapısal olarak garantidir: servis yalnız | |
| 350 | +`insight.*` çağrıları yapar, o çağrıların da dokunabildiği tablo kümesi | |
| 351 | +yukarıdaki dokuzdur. | |
| 297 | 352 | |
| 298 | 353 | --- |
| 299 | 354 | |
| @@ -301,15 +356,15 @@ bir tabloyu güncelleyen bir yol **yoktur** ve bu şema düzeyinde garantidir. | ||
| 301 | 356 | |
| 302 | 357 | | Alan | Nerede | Neden gösterilmez | |
| 303 | 358 | |---|---|---| |
| 304 | -| `recommendation` satırları, `audience_role = teacher` | tümü | **Rol kapısı.** T4 maddeleri yalnız öğretmene gider; öğrenciye ve veliye gösterilmez (`[T§6.8]`). İstemci bu alanı **sunucu tarafında** filtrelemeli | | |
| 305 | -| `recommendation.about` | öğretmen kartlarında | Başka bir öğrencinin kimliği. Öğrenci arayüzüne hiç gitmemeli | | |
| 306 | -| `student_summary.attention[]` | tümü | Dikkat listesi bir **öğretmen aracıdır**. Öğrenciye "senin hakkında şu tetikleyiciler var" demek damgalamadır (`[T§6.6]`) | | |
| 307 | -| `question_segment.rationale` | öğrenci ekranı | Modelin bir soru hakkındaki gerekçesi. Sınav güvenliği: sorunun tuzağını ve çözüm yapısını anlatır. Ayrıca bir LLM çıktısıdır ve hatalıdır | | |
| 308 | -| `question_segment.trap_choice` | öğrenci ekranı | **Doğrudan cevap ipucu.** Sınav öncesi görülürse ölçüm geçersizleşir | | |
| 309 | -| `question_segment.confidence_*` | öğrenci ekranı | Modelin kendi güveni **kalibre edilmemiştir**; sayı olarak gösterilmesi olduğundan çok anlam taşır | | |
| 310 | -| `student_segment_profile.accuracy` | tek başına | Genel yeteneği yansıtır, ayrım gücü yoktur. "Analiz sorularında %38'sin" cümlesi yanıltıcıdır; gösterilecekse `contrast` ile **birlikte** ve karşılaştırmasıyla gösterilmelidir | | |
| 311 | -| `student_segment_profile` satırları, `confidence = none` | tümü | n < 30. Gürültü. Depoda durur, **ekranda durmaz** | | |
| 312 | -| `insight_run.pending_students` | her ekran | İç muhasebe; kişi listesi. Yalnız yönetim/gözlem arayüzüne | | |
| 359 | +| `zeka_recommendation` satırları, `audience_role = teacher` | tümü | **Rol kapısı.** T4 maddeleri yalnız öğretmene gider; öğrenciye ve veliye gösterilmez (`[T§6.8]`). İstemci bu alanı **sunucu tarafında** filtrelemeli | | |
| 360 | +| `zeka_recommendation.about` | öğretmen kartlarında | Başka bir öğrencinin kimliği. Öğrenci arayüzüne hiç gitmemeli | | |
| 361 | +| `zeka_attention_item` satırları | tümü | Dikkat listesi bir **öğretmen aracıdır**. Öğrenciye "senin hakkında şu tetikleyiciler var" demek damgalamadır (`[T§6.6]`) | | |
| 362 | +| `zeka_question_segment.rationale` | öğrenci ekranı | Modelin bir soru hakkındaki gerekçesi. Sınav güvenliği: sorunun tuzağını ve çözüm yapısını anlatır. Ayrıca bir LLM çıktısıdır ve hatalıdır | | |
| 363 | +| `zeka_question_segment.trap_choice` | öğrenci ekranı | **Doğrudan cevap ipucu.** Sınav öncesi görülürse ölçüm geçersizleşir | | |
| 364 | +| `zeka_question_segment.confidence_*` | öğrenci ekranı | Modelin kendi güveni **kalibre edilmemiştir**; sayı olarak gösterilmesi olduğundan çok anlam taşır | | |
| 365 | +| `zeka_student_segment_profile.accuracy` | tek başına | Genel yeteneği yansıtır, ayrım gücü yoktur. "Analiz sorularında %38'sin" cümlesi yanıltıcıdır; gösterilecekse `contrast` ile **birlikte** ve karşılaştırmasıyla gösterilmelidir | | |
| 366 | +| `zeka_student_segment_profile` satırları, `confidence = none` | tümü | n < 30. Gürültü. Depoda durur, **ekranda durmaz** | | |
| 367 | +| `zeka_run_pending` satırları | her ekran | İç muhasebe; kişi listesi. Yalnız yönetim/gözlem arayüzüne | | |
| 313 | 368 | |
| 314 | 369 | Ayrıca **şemada olmayan** ve olmayacak olanlar, çünkü var olsalardı sıralama ve |
| 315 | 370 | damgalama üretirlerdi: `risk_score`, `rank`, `severity`, `weight`, tek bir |
| @@ -318,60 +373,29 @@ kendisi gözden geçirilmelidir. | ||
| 318 | 373 | |
| 319 | 374 | --- |
| 320 | 375 | |
| 321 | -## 6. Sorgu kalıpları | |
| 322 | - | |
| 323 | -> ### ⚠️ Kimlikle sorgularken `type::string()` zorunlu | |
| 324 | -> | |
| 325 | -> SurrealDB 3, RPC ile gönderilen `"user:01K42..."` biçimli bir **metni** uçta | |
| 326 | -> `record` değerine çevirir. Bu yüzden | |
| 327 | -> `WHERE student = $s` karşılaştırması bir kimlik için **sessizce boş sonuç** | |
| 328 | -> döner — hata vermez, sıfır satır döner. En kötü türden bir tuzaktır. | |
| 329 | -> | |
| 330 | -> ```sql | |
| 331 | -> -- YANLIŞ: her zaman boş döner | |
| 332 | -> SELECT * FROM student_segment_profile WHERE student = $s; | |
| 333 | -> -- DOĞRU | |
| 334 | -> SELECT * FROM student_segment_profile WHERE student = type::string($s); | |
| 335 | -> ``` | |
| 336 | -> | |
| 337 | -> Kural: iki nokta içeren **her** değişken karşılaştırması (öğrenci, soru, | |
| 338 | -> sınav, ders, konu kimliği) `type::string()` ile sarılır. `school` slug'ı iki | |
| 339 | -> nokta içermediği için sarılmasına gerek yoktur. Yazma tarafında aynı sarma | |
| 340 | -> `store.py` içinde otomatik yapılır; okuma tarafı çağıranın sorumluluğudur. | |
| 341 | -> Doğrulayan test: `tests/test_store.py::test_kimlikle_sorgulama_type_string_ister`. | |
| 342 | - | |
| 343 | -```sql | |
| 344 | --- Bir öğrencinin kartı | |
| 345 | -SELECT * FROM student_summary | |
| 346 | - WHERE school = $school AND student = type::string($student); | |
| 347 | - | |
| 348 | --- Öğrenciye gösterilecek tavsiyeler (rol kapısı + süre + kapatma) | |
| 349 | -SELECT * FROM recommendation | |
| 350 | - WHERE school = $school AND audience = type::string($student) | |
| 351 | - AND audience_role = 'student' | |
| 352 | - AND expires_at > $now AND dismissed_at = NONE | |
| 353 | - ORDER BY created_at DESC; | |
| 354 | - | |
| 355 | --- Öğretmenin dikkat listesi | |
| 356 | -SELECT * FROM recommendation | |
| 357 | - WHERE school = $school AND audience = type::string($teacher) | |
| 358 | - AND audience_role = 'teacher' AND expires_at > $now | |
| 359 | - ORDER BY created_at DESC; | |
| 360 | - | |
| 361 | --- Bir öğrencinin segment profili (gösterilebilir olanlar) | |
| 362 | -SELECT dimension, label, n_answers, accuracy, contrast, confidence | |
| 363 | - FROM student_segment_profile | |
| 364 | - WHERE school = $school AND student = type::string($student) | |
| 365 | - AND confidence != 'none'; | |
| 366 | - | |
| 367 | --- Bir sınavın soru etiketleri | |
| 368 | -SELECT question, bilissel_talep, dikkat_tuzagi, okuma_yuku, confidence | |
| 369 | - FROM question_segment | |
| 370 | - WHERE school = $school AND exam = type::string($exam); | |
| 371 | -``` | |
| 372 | - | |
| 373 | -Her sorguda `school` **zorunludur**: kiracı ayrımı indeks düzeyinde bu alana | |
| 374 | -dayanır ve onsuz sorgu tam tarama yapar. | |
| 376 | +## 6. Okuma yüzeyi — bu satırları kim okur | |
| 377 | + | |
| 378 | +ZEKA'nın tabloları **ZEKA'nın veritabanı değildir**: okulun kendi | |
| 379 | +veritabanındadır ve okunduğu yer de backend'dir (`/insights` yuvası). Servis | |
| 380 | +yalnız **yazar** ve koşuya devam etmek için gereken tek listeyi okur | |
| 381 | +(`insight.pending.list`). Bu yüzden burada okuma sorgusu kalıbı yoktur — | |
| 382 | +eskiden burada duran kalıplar serviste artık bulunmayan bir veritabanını | |
| 383 | +tarif ediyordu. | |
| 384 | + | |
| 385 | +Okumanın nerede olursa olsun uyması gereken kurallar: | |
| 386 | + | |
| 387 | +| Kural | Neden | | |
| 388 | +|---|---| | |
| 389 | +| `school` kolonu **yok** | Kiracı, veritabanının kendisidir. Okuma zaten o okulun veritabanına kapsanmıştır; ayrı bir okul filtresi yanlış okulun satırını getiremez, çünkü satır orada değildir | | |
| 390 | +| `audience_role = 'teacher'` satırları öğrenciye/veliye **gösterilmez** | Rol kapısı (§5, `[T§6.8]`) | | |
| 391 | +| `expires_at > now` **ve** `dismissed_at` boş | Süre dolmuş ya da kapatılmış tavsiye ekranda görünmez (§4.3) | | |
| 392 | +| `confidence = 'none'` satırlar okunmaz | n < 30 gürültüdür; depoda durur, ekranda durmaz (§5) | | |
| 393 | +| Kimlikler `uuid` | Eski metin-kimlik tuzağı (`type::string()` sarması) veritabanıyla birlikte **ortadan kalktı**: kimlik artık gerçek bir uuid ve karşılaştırma düz eşitliktir | | |
| 394 | + | |
| 395 | +Son madde, eski bir tuzak sınıfının kapandığı yerdir: eski şemada her kimlik | |
| 396 | +`user:01K42...` biçimli bir **metindi** ve veritabanı onu uçta kayda çevirirdi; | |
| 397 | +sarma unutulunca karşılaştırma sessizce **sıfır satır** dönerdi. `uuid` FK ile | |
| 398 | +bu tuzak yapısal olarak imkânsızdır. | |
| 375 | 399 | |
| 376 | 400 | --- |
| 377 | 401 | |
| @@ -379,7 +403,7 @@ dayanır ve onsuz sorgu tam tarama yapar. | ||
| 379 | 403 | |
| 380 | 404 | 1. **Madde istatistiği yoktur.** `question_stat` (p-değeri, ayırt edicilik, |
| 381 | 405 | çeldirici dağılımı) bu sürümde üretilmiyor; köprü izin listesinde sınav |
| 382 | - yolu yok. `question_segment` onun yerine geçmez — etiket taşır, istatistik | |
| 406 | + yolu yok. `zeka_question_segment` onun yerine geçmez — etiket taşır, istatistik | |
| 383 | 407 | değil. |
| 384 | 408 | 2. **`student_subject_stat` yoktur.** Konu bazlı öğrenci özeti aynı sebeple |
| 385 | 409 | üretilemiyor. |
| @@ -391,5 +415,7 @@ dayanır ve onsuz sorgu tam tarama yapar. | ||
| 391 | 415 | gerekir (`SEGMENT-CIKTI.md` §8). |
| 392 | 416 | 5. **`T3.segment_class_gap` gerçek bir sınıfta hiç ateşlemedi** — yalnız yapay |
| 393 | 417 | pozitif kontrolde. Ekranı kurulabilir, ama boş kalabileceği varsayılmalıdır. |
| 394 | -6. **WebSocket taşıması denenmedi.** Bütün doğrulama HTTP `/rpc` üzerinden | |
| 395 | - yapıldı (`docs/DEPOLAMA.md` §7). | |
| 418 | +6. **`insight.*` kapıları backend'de henüz tanımlı değil.** Servis kendi | |
| 419 | + takvimiyle çalışır ve satırlarını yazmayı bu kapılardan ister; kapılar | |
| 420 | + gelene kadar gece koşusu `partial` yazılır. Sahibi backend'deki | |
| 421 | + `InsightDoors` hattı — `docs/BACKEND-GEREKSINIMLERI.md` Madde 1. |
service/docs/DAGITIM.mdmodified+53 -52
| @@ -84,7 +84,7 @@ biri `COPY . .` yazarsa sir yine de imaja girmez. | ||
| 84 | 84 | ```bash |
| 85 | 85 | cd service |
| 86 | 86 | export AI_SHARED_TOKEN=... # backend ile AYNI sir |
| 87 | -export DEEPSEEK_API_KEY=... # segment hatti icin | |
| 87 | +export LLM_API_KEY=... # segment hatti icin | |
| 88 | 88 | podman compose up -d |
| 89 | 89 | ``` |
| 90 | 90 | |
| @@ -94,17 +94,25 @@ podman compose up -d | ||
| 94 | 94 | podman run -d --name hezarfen_zeka \ |
| 95 | 95 | --network hezarfen_backend_default \ |
| 96 | 96 | -e AI_SHARED_TOKEN=... \ |
| 97 | - -e ZEKA_PG_DSN=postgres://<kullanici>:<parola>@<host>:5432/<okul_veritabani> \ | |
| 98 | - -e DEEPSEEK_API_KEY=... \ | |
| 97 | + -e LLM_API_KEY=... \ | |
| 99 | 98 | hezarfen-zeka:dev |
| 100 | 99 | ``` |
| 101 | 100 | |
| 102 | -> `ZEKA_PG_DSN` **zorunludur ve ULASILABILIR olmalidir**: servis acilista | |
| 103 | -> `open_store()` cagirir, DSN yoksa `RuntimeError` ile **cikar** | |
| 104 | -> (`src/store_factory.py`). Kanit betigi (`scripts/ci-konteyner-kanit.sh`) bu | |
| 105 | -> yuzden gercek bir Postgres kaldirip kaba gecerli bir DSN verir; 2026-09-16 ve | |
| 106 | -> 2026-09-17 kosularinda tam bu satir eksik oldugu icin konteyner kosu kaniti | |
| 107 | -> kirmizi kaldi (`RuntimeError: Ne ZEKA_PG_DSN ne ZEKA_DB_HTTP_URL tanimli`). | |
| 101 | +> **Acilis HICBIR veritabani ACMAZ.** ZEKA'nin kendi deposu yoktur: her okuma | |
| 102 | +> ve yazma backend'e kopruden, `insight.*` yetenek cagrilariyla gider. Bu | |
| 103 | +> yuzden verilecek bir baglanti adresi, bir kullanici, bir parola YOKTUR; | |
| 104 | +> verilse de okunmaz. | |
| 105 | +> Kanit betigi (`scripts/ci-konteyner-kanit.sh`) kabi tam olarak boyle -- | |
| 106 | +> hicbir veritabani degiskeni OLMADAN -- ayaga kaldirir ve bu basli basina | |
| 107 | +> iddianin olcumudur. | |
| 108 | +> | |
| 109 | +> **Backend yokken ne olur:** servis CIKMAZ. Baglanti denemesi gunluge bir | |
| 110 | +> satir yazar ve ustel geri cekilmeyle yeniden denenir; backend geri | |
| 111 | +> geldiginde kendiliginden toparlanir. Zamanlayici turu bos okul listesiyle | |
| 112 | +> kosar (okul kutugu backend'dedir, `insight.schools.list`). Kopru kapaliyken | |
| 113 | +> yapilan bir yazma grup basina iki kez denenir; ikinci dususte grup atlanir, | |
| 114 | +> `warn` loglanir ve kosu defterine `partial` yazilir -- sessiz basari YOKTUR | |
| 115 | +> (`src/store.py`, `MODULLER.md` §2.11). | |
| 108 | 116 | |
| 109 | 117 | **Kanitlandi.** Kap `50 saniye` boyunca gozlendi; **cikmadi**, `running` |
| 110 | 118 | kaldi. Backend'e bilerek cozulemeyen bir ad verildi ve gunluklerde ustel geri |
| @@ -188,7 +196,9 @@ gercekten ulasti mi" iddiasini denetler. | ||
| 188 | 196 | | `AI_TLS_FINGERPRINT` | *(bos)* | **Bos = TOFU.** Asagiya bakin. | |
| 189 | 197 | | `AI_MAX_CONCURRENT` | `4` | Backend clamp'i: `1..=AI_MAX_CONCURRENT_PER_WORKER`. | |
| 190 | 198 | | `AI_RECONNECT_SECS` / `AI_RECONNECT_MAX_SECS` | `3` / `120` | Geri cekilme taban ve tavani. | |
| 191 | -| `ZEKA_SCHOOLS` | `ataturk-anadolu` | Backend'de okul **listeleme yolu yok**; kapsam disaridan verilir. | | |
| 199 | +| `ZEKA_SCHOOLS` | *(bos = butun okullar)* | Yalnizca **filtre**. Okul kutugu backend'dedir (`insight.schools.list`); sabit bir varsayilan okul yoktur. | | |
| 200 | +| `ZEKA_SOURCE` | `bridge` | Veri cephesi: uretimde `bridge` (`insight.*` cagrilari). | | |
| 201 | +| `ZEKA_API_TIMEOUT_SECS` / `ZEKA_BLOB_TIMEOUT_SECS` | `15` / `60` | Kopru cagrisi ve blob cagrisi zaman asimlari. | | |
| 192 | 202 | | `LOG_LEVEL` | `info` | `debug`, `info`, `warn`, `error`. | |
| 193 | 203 | |
| 194 | 204 | Tam liste `compose.yaml` icinde, her biri yorumlu. |
| @@ -330,7 +340,7 @@ kez koşmaz; PR'lar ve dal push'ları tam katmanlı süiti buradan alır. | ||
| 330 | 340 | | **2 -- birim testleri** | `python -m unittest discover -s tests -t .` **Bagimlilik kurulmaz** -- test paketi saf `unittest` kullanir. Boylece kirmizi/yesil bilgisi paket deposu kesintilerinden bagimsizdir. | |
| 331 | 341 | | **3 -- sozlesme** | Model adi <-> fiyat tablosu; `source.py` yollari <-> izin listesi. Ayrinti asagida. | |
| 332 | 342 | | **4 -- sir taramasi** | `sk-` / `sk_` desenleri, ozel anahtar govdeleri, AWS anahtarlari, yapilandirma dosyalarina gomulmus duz degerler; compose sirlarinin `${VAR:?}` bicimini korudugu. | |
| 333 | -| **5 -- konteyner** | Imaj derleniyor **ve kosuyor** mu; **zorunlu uc env ile gercekten aciliyor mu** (kanit betigi gercek bir Postgres kaldirir, `open_store()` ile depoyu acar); non-root mu; saglik kontrolu gercekten olcuyor mu; `compose config` gecerli mi ve port acilmiyor mu. | | |
| 343 | +| **5 -- konteyner** | Imaj derleniyor **ve kosuyor** mu; kap **hicbir veritabani degiskeni OLMADAN** aciliyor mu (kanit betigi kabi boyle kosturur -- eksik bir zorunlu veritabani degiskeni olsaydi surec cikardi); non-root mu; saglik kontrolu gercekten olcuyor mu; `compose config` gecerli mi, zorunlu sirlar gercekten zorunlu mu ve port acilmiyor mu. | | |
| 334 | 344 | |
| 335 | 345 | ### `.github/workflows/main.yml` -- `main` push'u, otomatik dağıtım |
| 336 | 346 | |
| @@ -363,55 +373,45 @@ Bir seferlik ön koşullar: | ||
| 363 | 373 | 2. Sunucuda `loginctl enable-linger <kullanıcı>`. |
| 364 | 374 | 3. Sunucuda `podman` + bir compose sağlayıcı. |
| 365 | 375 | 4. Operatörün `~/hezarfen_zeka/hezarfen_zeka.env` dosyası (0600; şablon |
| 366 | - `deploy/hezarfen_zeka.env.example`, zorunlu üç sır: `AI_SHARED_TOKEN`, | |
| 367 | - `ZEKA_PG_DSN`, `DEEPSEEK_API_KEY`). | |
| 376 | + `deploy/hezarfen_zeka.env.example`, zorunlu iki sır: `AI_SHARED_TOKEN`, | |
| 377 | + `LLM_API_KEY`). Veritabanı ayarı GEREKMEZ: servis hiçbir veritabanına | |
| 378 | + bağlanmaz. | |
| 368 | 379 | 5. Sunucuda `hezarfen_backend_default` ağı (backend compose'u kurar) ve |
| 369 | 380 | backend tarafında `AI_QUIC_ADDR=0.0.0.0:8090`. |
| 370 | 381 | |
| 371 | 382 | Manuel yol değişmedi: `cd service && podman compose up -d` (§3). |
| 372 | 383 | |
| 373 | -### Konteyner kosu kaniti -- yerel dogrulama (2026-09-17) | |
| 384 | +### Konteyner kosu kaniti -- kapi neyi olcer | |
| 374 | 385 | |
| 375 | -Kanit betigi (`scripts/ci-konteyner-kanit.sh`) artik **gercek bir Postgres** | |
| 376 | -kaldirir (kendi agi, IP ile DSN) ve kabi **zorunlu uc env ile** kosturur; boylece | |
| 377 | -kanit, servisin uretimdeki acilis yolunu (`open_store()`) olcer. Duzeltmeden | |
| 378 | -sonraki yerel kosu: | |
| 386 | +Kanit betigi (`scripts/ci-konteyner-kanit.sh`) kabi **hicbir veritabani | |
| 387 | +degiskeni vermeden** kosturur ve dogrulanan sey tam olarak su bes iddiadir: | |
| 379 | 388 | |
| 380 | 389 | ``` |
| 381 | - [ok] kanit Postgres'i ayakta (adres 10.89.9.2, ...) | |
| 382 | - [ok] kap 50 saniye sonra hala kosuyor (durum=running) | |
| 383 | - [ok] ZEKA_PG_DSN kabul edildi: kopru Postgres yolunu secti (acilis satiri logda) | |
| 384 | - [ok] zorunlu env ile depo GERCEKTEN aciliyor (open_store -> kapat) | |
| 385 | - [ok] ustel geri cekilme gozlendi: 2.6s -> 12.5s (6 deneme) | |
| 386 | - [ok] backend ulasilamazken CIKMIYOR, yeniden deniyor (RAG kusurunun tersi) | |
| 387 | - [ok] non-root dogrulandi (uid=10002) | |
| 388 | - [ok] saglik kontrolu kopru yasarken GECIYOR | |
| 389 | - [ok] saglik kontrolu kopru yokken BASARISIZ oluyor (yani gercekten olcuyor) | |
| 390 | - [ok] motor kabi 'healthy' isaretledi | |
| 391 | -KONTEYNER KOSU KANITI GECTI (exit 0) | |
| 390 | + 1. kap backend YOKKEN de aciliyor ve CIKMIYOR (geri cekilerek yeniden deniyor) | |
| 391 | + 2. geri cekilme gercekten USTEL: bekleme suresi buyuyor | |
| 392 | + 3. saglik kontrolu HEM geciyor (kopru yasarken) HEM kaliyor (kopru yokken) | |
| 393 | + 4. surec NON-ROOT (uid 10002) kosuyor | |
| 394 | + 5. kap sinirli bir pencere boyunca AYAKTA kaliyor | |
| 392 | 395 | ``` |
| 393 | 396 | |
| 394 | -Negatif kontroller (kanit gercekten olcuyor): | |
| 395 | - | |
| 396 | -``` | |
| 397 | -$ podman run --rm -e AI_SHARED_TOKEN=x hezarfen-zeka:ci | |
| 398 | -RuntimeError: Ne ZEKA_PG_DSN ne ZEKA_DB_HTTP_URL tanimli — ... (exit 1) | |
| 399 | -``` | |
| 397 | +**Neden bu bir "veritabani gerekmiyor" kanitidir:** eksik bir zorunlu | |
| 398 | +veritabani degiskeni olsaydi surec daha kopru dongusu baslamadan cikardi ve | |
| 399 | +yukaridaki iddialarin HEPSI bosluga dusardi. Kabin acilmasi ve ayakta kalmasi | |
| 400 | +basli basina iddianin olcumudur. | |
| 400 | 401 | |
| 401 | -Yani duzeltme oncesi kosucudaki kirmizinin TA KENDISI yerelde yeniden uretildi; | |
| 402 | -kanit betigi o imzayi artik yakaliyor (1b iddialari). | |
| 402 | +> Kosucudaki ve sunucudaki kosu durumu icin [Kanitlanmayanlar](#kanitlanmayanlar) | |
| 403 | +> 9. maddeye bakin. | |
| 403 | 404 | |
| 404 | 405 | ### `.github/workflows/istege-bagli-testler.yml` -- elle tetiklenir |
| 405 | 406 | |
| 406 | -Her degisiklikte **kosmaz**. `aioquic` kurar ya da bir veritabani kaldirir; | |
| 407 | -yavastir ve dis etkenlere aciktir. Zorunlu kapiya konulsalardi CI guvenilmez | |
| 408 | -olurdu, guvenilmez CI da yok sayilir. | |
| 407 | +Her degisiklikte **kosmaz**. `aioquic` kurar; yavastir ve dis etkenlere | |
| 408 | +aciktir. Zorunlu kapiya konulsaydi CI guvenilmez olurdu, guvenilmez CI da yok | |
| 409 | +sayilirdi. | |
| 409 | 410 | |
| 410 | 411 | - **`kopru-canli`** -- `tests/test_bridge_live.py`: gercek UDP soketi, gercek |
| 411 | 412 | TLS 1.3 el sikismasi, gercek `hab/2` cerceveleri. Karsi taraf |
| 412 | 413 | `tests/fake_bridge/` altindaki **sahte** sunucudur, gercek backend |
| 413 | 414 | degildir. Ag kapsami **yalnizca 127.0.0.1**. |
| 414 | -- **`veritabani`** -- SurrealDB entegrasyon testleri (girdi ile acilir). | |
| 415 | 415 | |
| 416 | 416 | **Gercek LLM cagrisi hicbir iste yapilmaz.** Segment testleri `MockProvider` |
| 417 | 417 | kullanir; `kopru-canli` isi ayrica bir saglayici anahtarinin ortama sizmadigini |
| @@ -572,7 +572,7 @@ Durustluk bolumu. Asagidakiler **kosturulmadi** ya da **dogrulanamadi**; | ||
| 572 | 572 | |
| 573 | 573 | 6. **`podman compose up` ile uctan uca kaldirma.** `compose config` |
| 574 | 574 | dogrulandi (iki yonlu), ama servis compose ile **kaldirilmadi**: dis ag |
| 575 | - (`hezarfen_backend_default`) ve SurrealDB bu makinede ayakta degildi. | |
| 575 | + (`hezarfen_backend_default`) bu makinede ayakta degildi. | |
| 576 | 576 | |
| 577 | 577 | ### Kanitlanmayan -- CI |
| 578 | 578 | |
| @@ -586,8 +586,10 @@ Durustluk bolumu. Asagidakiler **kosturulmadi** ya da **dogrulanamadi**; | ||
| 586 | 586 | | `35218219339` | yesil | yesil | yesil | yesil | **kirmizi** | atlandi | atlandi | |
| 587 | 587 | |
| 588 | 588 | Katman 2 kirmizisi o gun tohum bagimli uc testti (bkz. yukarisi, duzeltildi); |
| 589 | - Katman 5 kirmizisi konteyner kanit betiginin zorunlu `ZEKA_PG_DSN`'i | |
| 590 | - vermemesiydi (asagidaki 8. madde). `Build and test` ve `Deploy`'in | |
| 589 | + Katman 5 kirmizisi konteyner kanit betiginin bekledigi zorunlu veritabani | |
| 590 | + degiskenini kosuda bulamamasindan geliyordu. O beklenti tumden kaldirildi: | |
| 591 | + kanit betigi kabi artik hicbir veritabani degiskeni olmadan kosturur (9. | |
| 592 | + madde). `Build and test` ve `Deploy`'in | |
| 591 | 593 | **atlanmasi** tasarim geregidir: kapilar yesil olmadan artefakt uretilmez ve |
| 592 | 594 | sunucuya dokunulmaz. |
| 593 | 595 | |
| @@ -598,10 +600,10 @@ Durustluk bolumu. Asagidakiler **kosturulmadi** ya da **dogrulanamadi**; | ||
| 598 | 600 | etiket turu), ama gercek bir sunucuya karsi **hic kosmadi**. Ilk gercek kosu |
| 599 | 601 | bu maddeleri kapatacaktir. |
| 600 | 602 | |
| 601 | -9. **Konteyner kosu kaniti kosucuda yeniden dogrulanmadi.** Betik artik gercek | |
| 602 | - bir Postgres kaldirip zorunlu uc env ile kabin ACILDIGINI olcer ve bu yerelde | |
| 603 | - `KONTEYNER KOSU KANITI GECTI` ile dogrulandi (bkz. asagisi), ama duzeltilmis | |
| 604 | - haliyle GitHub kosucusunda **henuz kosmadi**. | |
| 603 | +9. **Konteyner kosu kaniti kosucuda yeniden dogrulanmadi.** Betik artik kabi | |
| 604 | + **hicbir veritabani degiskeni vermeden** kosturur ve "servis veritabani | |
| 605 | + gerektirmiyor" iddiasini olcer (bkz. yukarisi); ama bu duzeltilmis haliyle | |
| 606 | + GitHub kosucusunda **henuz kosmadi**. | |
| 605 | 607 | |
| 606 | 608 | 10. **`docker compose` yolu.** `ci.yml` icindeki compose adimi |
| 607 | 609 | `docker compose` cagirir; yerelde `podman compose` zaten docker-compose'a |
| @@ -613,10 +615,9 @@ Durustluk bolumu. Asagidakiler **kosturulmadi** ya da **dogrulanamadi**; | ||
| 613 | 615 | olsa da, Makefile'in kendisi **sinanmamistir**. Guvenilir yol dogrudan |
| 614 | 616 | `bash scripts/ci-yerel.sh` kullanmaktir. |
| 615 | 617 | |
| 616 | -12. **`istege-bagli-testler.yml` isleri.** Ne `kopru-canli` ne `veritabani` | |
| 617 | - isi kosturuldu. `tests/test_bridge_live.py` yerelde `aioquic` kurulu | |
| 618 | - olmadigi icin **atlandi**; canli kopru testlerinin gectigi | |
| 619 | - **gorulmedi**. | |
| 618 | +12. **`istege-bagli-testler.yml` isleri.** `kopru-canli` isi kosturulmadi. | |
| 619 | + `tests/test_bridge_live.py` yerelde `aioquic` kurulu olmadigi icin | |
| 620 | + **atlandi**; canli kopru testlerinin gectigi **gorulmedi**. | |
| 620 | 621 | |
| 621 | 622 | 13. *(Bu madde kapatildi -- negatif sinama yapildi, bkz. asagisi.)* |
| 622 | 623 |
service/docs/DEPOLAMA.mddeleted+0 -308
| @@ -1,308 +0,0 @@ | ||
| 1 | -# DEPOLAMA — ZEKA'nın kendi veritabanı | |
| 2 | - | |
| 3 | -Bu belge, ZEKA'nın **kendi** SurrealDB veritabanına yazan katmanı anlatır: | |
| 4 | -şema, yazım hacmi, saklama politikası, nasıl koşturulacağı ve **neyin | |
| 5 | -kanıtlanmadığı**. | |
| 6 | - | |
| 7 | -> **Tek ve mutlak kural:** ZEKA okul veritabanına **asla yazmaz**. Okul | |
| 8 | -> verisini yalnız `Source` arayüzü üzerinden okur. Burada anlatılan beş tablo | |
| 9 | -> ZEKA'nın kendi veritabanında yaşar ve okul şemasıyla hiçbir bağı yoktur — | |
| 10 | -> okul kimliği bir `record` değil, düz `string` slug'dır. | |
| 11 | - | |
| 12 | ---- | |
| 13 | - | |
| 14 | -## 1. Şema | |
| 15 | - | |
| 16 | -Kaynak: `service/schema/zeka.surql` — 104 DDL ifadesi, beş tablo. | |
| 17 | -Alan alan sözleşme (frontend/backend için): `docs/CIKTI-SOZLESMESI.md`. | |
| 18 | - | |
| 19 | -| Tablo | Ne tutar | Kayıt anahtarı | | |
| 20 | -|---|---|---| | |
| 21 | -| `student_summary` | Öğrenci başına gecelik özet | `{school}_{student}` | | |
| 22 | -| `recommendation` | Üretilmiş tavsiye + kanıtı | `{school}_{audience}_{product}_{rule_id}_{scope}` | | |
| 23 | -| `insight_run` | Koşu defteri | `{school}_{YYYY-MM-DD}` (TR tarihi) | | |
| 24 | -| `question_segment` | Soru başına bilişsel etiket (segmentasyon hattı) | `{school}_{question}` | | |
| 25 | -| `student_segment_profile` | Öğrenci × boyut × etiket performansı, `contrast` ile | `{school}_{student}_{dimension}_{label}` | | |
| 26 | - | |
| 27 | -Anahtarlar **kompozit** olduğu için tekillik yapısaldır: `UNIQUE` indekse gerek | |
| 28 | -yoktur ve `UPSERT` idempotenttir — aynı geceyi iki kez koşturmak satır | |
| 29 | -çoğaltmaz. | |
| 30 | - | |
| 31 | -### Şema yüklenirken yaşanan üç gerçek hata | |
| 32 | - | |
| 33 | -Bu üç şey, şema ilk kez **gerçek** bir SurrealDB 3 örneğine yüklendiğinde | |
| 34 | -ortaya çıktı. Üçü de "kod doğru görünüyordu ama hiç koşmamıştı" sınıfından. | |
| 35 | - | |
| 36 | -1. **`type::thing()` SurrealDB 3'te yoktur.** Karşılığı `type::record()`. | |
| 37 | - `store.py`'nin toplu UPSERT'i `type::thing` kullanıyordu; gerçek bir | |
| 38 | - veritabanına gönderildiğinde ayrıştırma hatası veriyor, yani **hiçbir satır | |
| 39 | - yazılmıyordu**. | |
| 40 | -2. **`FLEXIBLE`, `TYPE`'dan sonra gelmek zorunda.** `... FLEXIBLE TYPE object` | |
| 41 | - yazımı ayrıştırma hatası verir. Bu hata sessizdir: `surreal sql` ile toplu | |
| 42 | - gönderilen dosyada ifade düşer, şema "yüklendi" sanılır, ama SCHEMAFULL | |
| 43 | - tabloda tanımsız alan da sessizce düşer. Sonuç: `marks`, `attendance`, | |
| 44 | - `submission`, `study` ve `evidence` alanları **hiç var olmuyordu** — | |
| 45 | - hesap çıktısının tamamı kayboluyordu. | |
| 46 | -3. **`attention.*` tanımı `attention`'dan ÖNCE gelmeli.** `TYPE | |
| 47 | - option<array<object>>` ifadesi `.*` alt tanımını kendiliğinden (ve | |
| 48 | - `FLEXIBLE` olmadan) üretir; sonra gelen `DEFINE FIELD IF NOT EXISTS | |
| 49 | - attention.* ... FLEXIBLE` onu atlar. O halde dikkat maddelerinin iç | |
| 50 | - anahtarları (`evidence` nesnesi dahil) sessizce düşerdi. | |
| 51 | - | |
| 52 | -Ayrıca **`option<string>` `NULL` kabul etmez**: SurrealDB 3'te `option<T>` | |
| 53 | -gerçekte `none | T` demektir. Python'un `None` değeri JSON `null` olarak gider | |
| 54 | -ve `Couldn't coerce value for field 'dismiss_reason' ... Expected 'none | | |
| 55 | -string' but found 'NULL'` hatasıyla **tüm transaction'ı** reddeder — tek bir | |
| 56 | -boş `dismiss_reason`, 500 satırlık grubun tamamını düşürürdü. Doğru karşılık | |
| 57 | -alanı hiç göndermemektir; `store._drop_nulls()` üst düzey `None` alanlarını | |
| 58 | -satırdan çıkarır. FLEXIBLE nesnelerin **içindeki** `null`'lar hesap çıktısının | |
| 59 | -parçasıdır ve olduğu gibi saklanır. | |
| 60 | - | |
| 61 | -### Alan tipleri testle pinlenir | |
| 62 | - | |
| 63 | -`tests/test_store.py::TestSchemaApply::test_declared_field_types_are_what_the_schema_says` | |
| 64 | -`INFO FOR TABLE` çıktısını okuyup **her alanın** ilan edilmiş tipini tek tek | |
| 65 | -karşılaştırır. Şemadan bir alan düşerse ya da tipi saparsa test kırılır. | |
| 66 | - | |
| 67 | -Şemada kasıtlı olarak **olmayan** şeyler de testle korunur: | |
| 68 | - | |
| 69 | -* Tek bir **risk skoru** alanı yoktur; `attention` maddelerinde `score`, | |
| 70 | - `rank`, `weight`, `severity` bulunmaz. SCHEMAFULL tablo `risk_score` | |
| 71 | - taşıyan bir satırı **gürültüyle reddeder** | |
| 72 | - (`test_schemafull_rejects_an_undeclared_field`). | |
| 73 | -* `evidence` boş olamaz: kanıtsız tavsiye depolama katmanında da reddedilir. | |
| 74 | - | |
| 75 | ---- | |
| 76 | - | |
| 77 | -## 2. Yazım | |
| 78 | - | |
| 79 | -### Toplu UPSERT | |
| 80 | - | |
| 81 | -* Grup boyutu `BATCH_SIZE = 500`; her grup **tek transaction**. | |
| 82 | -* Bir grup düşerse yeniden denenir; **ikinci düşüşte** grup atlanır, `warn` | |
| 83 | - loglanır ve hat devam eder (`MAX_ATTEMPTS = 2`). Bayat veri, yanlış veriden | |
| 84 | - iyidir. | |
| 85 | -* `student_summary` ve `insight_run` **`CONTENT`** ile yazılır (satır tümüyle | |
| 86 | - yeniden üretilir). `recommendation` **`MERGE`** ile yazılır: hat `dismissed_at` | |
| 87 | - / `dismissed_by` / `dismiss_reason` alanlarını hiç üretmez ve CONTENT ile | |
| 88 | - yazsaydı her gece kullanıcının "bu tavsiye faydalı değil" kaydını silerdi. | |
| 89 | -* Sürücü bağımsızlığı korunur: `store.py` bir SurrealDB sürücüsü **import | |
| 90 | - etmez**. Gerçek istemci `SurrealHttpClient`'tır ve yalnızca standart | |
| 91 | - kütüphane kullanır (`urllib` + JSON-RPC `/rpc`). `requirements.txt` | |
| 92 | - değişmedi. | |
| 93 | - | |
| 94 | -### Neden `/rpc`, neden `surreal sql` değil | |
| 95 | - | |
| 96 | -* `surreal sql` aracı büyük girdiyi **sessizce keser** ve çok satırlı ifadeleri | |
| 97 | - satır satır ayrıştırır (bu projede tohum yüklerken acıyla öğrenildi — | |
| 98 | - `tools/load_seed.py` baş açıklaması). | |
| 99 | -* HTTP `/sql` ucu değişken (`$v`) taşıyamaz; gövde düz metindir. İç içe | |
| 100 | - sözlükleri SurrealQL metnine gömmek kaçış hatasına açık olurdu. | |
| 101 | -* `/rpc` ucu JSON-RPC'dir: `query` yöntemi `[sql, variables]` alır. Değişkenler | |
| 102 | - tip korunarak gider. | |
| 103 | - | |
| 104 | -### En önemli davranış: hata HTTP 200 ile gelir | |
| 105 | - | |
| 106 | -SurrealDB başarısız ifade için de **HTTP 200** döner; hata, sonuç dizisindeki | |
| 107 | -`status: "ERR"` alanındadır. `SurrealHttpClient.query_sync()` **her** ifadenin | |
| 108 | -durumunu tek tek denetler ve ilk `ERR`'de `SurrealError` atar. Denetlemeyen bir | |
| 109 | -istemci "yazdım" der ve hiçbir şey yazılmamış olur. | |
| 110 | - | |
| 111 | -Aynı sebeple `apply_schema()` DDL'i **ifade ifade** gönderir: bir ifade düşerse | |
| 112 | -hangisinin düştüğünü bilmek gerekir. | |
| 113 | - | |
| 114 | -### Ölçülen hacim | |
| 115 | - | |
| 116 | -İki okullu kanıt koşusundan (9 + 4 öğrenci, `fixtures` verisi): | |
| 117 | - | |
| 118 | -| Kaynak | student_summary | recommendation | insight_run | | |
| 119 | -|---|---|---|---| | |
| 120 | -| 1. gece (kadıköy, bütçe tam) | 9 | 21 | 1 | | |
| 121 | -| 1. gece (üsküdar, bütçe −1) | 0 | 0 | 1 | | |
| 122 | -| 2. gece (ikisi de) | 13 toplam | 16 toplam (bayatlar süpürüldü) | 4 toplam | | |
| 123 | - | |
| 124 | -Öğrenci başına kabaca **1 özet + 2–3 tavsiye** satırı. Entegrasyon testlerinde | |
| 125 | -`BATCH_SIZE + 123 = 623` satırlık tek yazım da koşturulur ve hepsinin indiği | |
| 126 | -sayılarak doğrulanır. | |
| 127 | - | |
| 128 | ---- | |
| 129 | - | |
| 130 | -## 3. Saklama politikası | |
| 131 | - | |
| 132 | -`store.RETENTION_DAYS` (`[T§6.7]`, `MODULLER.md` §2.11 adım 2): | |
| 133 | - | |
| 134 | -| Tablo | Gün | Gerekçe | | |
| 135 | -|---|---|---| | |
| 136 | -| `student_summary` | 400 | "dönem + 1 yıl" — türetilmiş veri, ham veriden yeniden üretilebilir | | |
| 137 | -| `recommendation` | 90 | `retain_until = min(expires_at, created_at + 90 gün)` — bayat tavsiye zararlıdır | | |
| 138 | -| `insight_run` | 90 | koşu defteri | | |
| 139 | - | |
| 140 | -Süpürme (`Store.sweep`) hattın **en sonunda**, `DELETE <tablo> WHERE | |
| 141 | -retain_until < $now` ile koşar. Ayrıca `Store.purge_departed()` artık öğrenci | |
| 142 | -olmayanların türetilmiş verisini siler: "mezunun ham verisi arşivde kalabilir; | |
| 143 | -**profili kalmamalıdır**." | |
| 144 | - | |
| 145 | -**Süpürmenin gerçekten sildiğinin kanıtı** (`python -m src.cli sweep`): | |
| 146 | - | |
| 147 | -``` | |
| 148 | -once : student_summary 19, recommendation 22, insight_run 4 | |
| 149 | -sonra : student_summary 13, recommendation 16, insight_run 4 | |
| 150 | -silinen: student_summary 6, recommendation 6, insight_run 0 | |
| 151 | -``` | |
| 152 | - | |
| 153 | -500 gün önce hesaplanmış 6 özet ve 6 tavsiye silindi; taze satırlar duruyor. | |
| 154 | - | |
| 155 | ---- | |
| 156 | - | |
| 157 | -## 4. Kiracı izolasyonu | |
| 158 | - | |
| 159 | -Üç katman: | |
| 160 | - | |
| 161 | -1. **Kayıt anahtarı okulla önekli.** Aynı öğrenci kimliği iki okulda bulunsa | |
| 162 | - bile iki ayrı satır olur — kanıt koşusunda iki okul da `student-00…` | |
| 163 | - kimliklerini kullanıyor ve toplam `9 + 4 = 13` satır çıkıyor, 9 değil. | |
| 164 | -2. **Her satır `school` alanı taşır** ve tüm sorgular `WHERE school = $s` ile | |
| 165 | - daraltılır (`student_summary_school`, `recommendation_audience` indeksleri). | |
| 166 | -3. **Zamanlayıcı okulları sırayla ve ayrı `Source` nesneleriyle işler**; bir | |
| 167 | - okulun düşmesi diğerini etkilemez. | |
| 168 | - | |
| 169 | -Testler: `test_store.py::TestTenantIsolation` (4 test) ve | |
| 170 | -`test_scheduler.py::TestFullCycleAgainstSurreal::test_tenant_isolation_end_to_end`. | |
| 171 | - | |
| 172 | ---- | |
| 173 | - | |
| 174 | -## 5. Zamanlayıcı — bütçe ve erteleme | |
| 175 | - | |
| 176 | -* Pencere **03:00–05:00 TR**, tik 15 dakika. Kaçan tik birikmez. | |
| 177 | -* Okullar **sabit alfabetik sırada**; geçen gece `partial` biten okullar öne | |
| 178 | - alınır. Sabit sıra "hep son okul bütçesiz kalır" durumunu görünür kılar. | |
| 179 | -* **Okul başına bütçe:** `Scheduler(budgets={"okul": ms})`. Sözlükte olmayan | |
| 180 | - okul varsayılan `60_000 ms` bütçesini kullanır. | |
| 181 | -* **Bütçeyi aşan okul ertelenir:** işlenmemiş öğrenciler | |
| 182 | - `insight_run.pending_students`'a yazılır ve bir sonraki koşu bu kimlikleri | |
| 183 | - listenin **başına** alır (`run_school(resume_students=...)`). | |
| 184 | -* **Yeniden başlatmaya dayanır:** bellek içi `pending` sözlüğü süreç | |
| 185 | - ölünce kaybolur; `Store.last_pending(school)` devreden listeyi | |
| 186 | - `insight_run` satırından geri okur. | |
| 187 | -* **Bir okul düşerse tur durmaz.** O okulun `_last_run_day`'i | |
| 188 | - güncellenmez, dolayısıyla aynı gece yeni bir tik onu yeniden dener. | |
| 189 | - | |
| 190 | -### Test kipi | |
| 191 | - | |
| 192 | -`Scheduler.serve(tick_seconds=..., ignore_window=True, max_ticks=N)` gece | |
| 193 | -penceresini ve 15 dakikalık tiki beklemeden tam çevrim koşturur. Bu **ayrı bir | |
| 194 | -kod yolu değildir** — aynı döngünün parametrelenmiş hali. Ayrı yol olsaydı test | |
| 195 | -edilen şey üretimde koşan şey olmazdı. | |
| 196 | - | |
| 197 | -Bütçe testlerinde `monotonic_fn` enjekte edilir (`FakeMonotonic`), böylece | |
| 198 | -"bütçe kaçıncı öğrenciden sonra dolar" makinenin hızına değil, sayıya bağlıdır. | |
| 199 | - | |
| 200 | ---- | |
| 201 | - | |
| 202 | -## 6. Nasıl koşturulur | |
| 203 | - | |
| 204 | -### Veritabanını kaldır | |
| 205 | - | |
| 206 | -```bash | |
| 207 | -podman network create hzk | |
| 208 | -podman run -d --name hzk-zeka --network hzk --memory 2g -v hzk-zeka-data:/data --user 0 \ | |
| 209 | - docker.io/surrealdb/surrealdb:v3 start --user root --pass root "surrealkv:/data/zeka.db" | |
| 210 | -``` | |
| 211 | - | |
| 212 | -> Bu makinede host'a **port yönlendirmesi çalışmıyor**; veritabanına `hzk` | |
| 213 | -> ağının içinden `hzk-zeka:8000` adıyla bağlanılır. Bu yüzden aşağıdaki | |
| 214 | -> komutların hepsi ağ içindeki bir konteynerden koşar. | |
| 215 | - | |
| 216 | -### Şemayı yükle ve doğrula | |
| 217 | - | |
| 218 | -```bash | |
| 219 | -podman run --rm --network hzk -v /path/to/hezarfen-ZEKA:/repo:ro -w /repo/service \ | |
| 220 | - docker.io/library/python:3.12-slim \ | |
| 221 | - python -m src.cli schema --apply --db-url http://hzk-zeka:8000 \ | |
| 222 | - --db-ns hezarfen --db-name zeka | |
| 223 | -``` | |
| 224 | - | |
| 225 | -Çıktı `{"ifade_toplam": 56, "uygulanan": 56, "hatalar": []}` ve ardından | |
| 226 | -`INFO FOR DB` / `INFO FOR TABLE`'dan okunan tablo ve alan listeleridir. | |
| 227 | - | |
| 228 | -### Bir okulu koştur | |
| 229 | - | |
| 230 | -```bash | |
| 231 | -python -m src.cli run --school okul-a --source file --fixtures /yol/fikstur \ | |
| 232 | - --db-url http://hzk-zeka:8000 --db-name zeka | |
| 233 | -# ya da veritabanına dokunmadan: | |
| 234 | -python -m src.cli run --school okul-a --source file --fixtures /yol/fikstur --dry-run | |
| 235 | -``` | |
| 236 | - | |
| 237 | -### Zamanlayıcıyı elle tetikle | |
| 238 | - | |
| 239 | -```bash | |
| 240 | -python -m src.cli schedule --schools kadikoy-lisesi,uskudar-lisesi \ | |
| 241 | - --fixtures /yol/fikstur --budget "uskudar-lisesi=-1" \ | |
| 242 | - --db-url http://hzk-zeka:8000 --db-name zeka | |
| 243 | -# tam serve() döngüsü, pencere beklemeden: | |
| 244 | -python -m src.cli schedule ... --ticks 2 --tick-seconds 0.01 | |
| 245 | -``` | |
| 246 | - | |
| 247 | -### Süpürme | |
| 248 | - | |
| 249 | -```bash | |
| 250 | -python -m src.cli sweep --db-url http://hzk-zeka:8000 --db-name zeka | |
| 251 | -``` | |
| 252 | - | |
| 253 | -### Testler | |
| 254 | - | |
| 255 | -```bash | |
| 256 | -# Konteyner yoksa: entegrasyon testleri skipUnless ile atlanır. | |
| 257 | -python -m unittest discover -s service -p "test_*.py" -t service | |
| 258 | - | |
| 259 | -# Gerçek veritabanına karşı (CI'da da böyle koşar): | |
| 260 | -podman run --rm --network hzk -e ZEKA_TEST_DB_URL=http://hzk-zeka:8000 \ | |
| 261 | - -v /path/to/hezarfen-ZEKA:/repo -w /repo/service \ | |
| 262 | - docker.io/library/python:3.12-slim \ | |
| 263 | - python -m unittest discover -s . -p "test_*.py" -t . | |
| 264 | -``` | |
| 265 | - | |
| 266 | -Entegrasyon testlerinin her biri **kendi boş veritabanını** açar | |
| 267 | -(`tests/zeka_db.py::fresh_schema_client`), böylece testler birbirinin satırını | |
| 268 | -görmez. | |
| 269 | - | |
| 270 | ---- | |
| 271 | - | |
| 272 | -## 7. Kanıtlanmayanlar | |
| 273 | - | |
| 274 | -Dürüstlük bölümü. Aşağıdakiler **koşmadı**, dolayısıyla "çalışıyor" denemez. | |
| 275 | - | |
| 276 | -1. **Üretim bağlantı yolu.** Testler HTTP `/rpc` ile bağlanır. | |
| 277 | - `config.py::db_url` varsayılanı `ws://hezarfen-surrealdb:8000/rpc` | |
| 278 | - (WebSocket). WebSocket taşıması **hiç denenmedi**; `SurrealHttpClient` | |
| 279 | - yalnızca HTTP konuşur. Üretimde adresin `http(s)://host:port` biçiminde | |
| 280 | - verilmesi gerekir. | |
| 281 | -2. **Kimlik doğrulama yalnızca `root:root` ile denendi.** Sınırlı yetkili bir | |
| 282 | - veritabanı kullanıcısı, namespace/database düzeyinde erişim ve | |
| 283 | - `PERMISSIONS` kuralları denenmedi. Şemadaki alanlar `PERMISSIONS FULL`. | |
| 284 | -3. **Gerçek ölçek.** En büyük koşu 623 satırlık tek toplu yazımdı ve tüm | |
| 285 | - testler 13 öğrencilik fikstürlerle koştu. Binlerce öğrencili bir okulda | |
| 286 | - 60 saniyelik bütçenin yeteceği **ölçülmedi**; `surrealkv` arka ucunun | |
| 287 | - büyük `DELETE`lerde nasıl davrandığı da ölçülmedi. | |
| 288 | -4. **Eşzamanlılık.** `Scheduler` süreç içi `asyncio.Lock` kullanır. İki ZEKA | |
| 289 | - süreci aynı anda koşarsa ne olduğu denenmedi; ikinci savunma olarak | |
| 290 | - gösterilen "`insight_run` satırının varlığı" **kod tarafından | |
| 291 | - okunmuyor** — yalnızca `pending_students` okunuyor. Yani çok süreçli tek | |
| 292 | - koşu güvencesi şu an **yoktur**. | |
| 293 | -5. **Köprü (`BridgeSource`) ile uçtan uca koşu.** Tüm entegrasyon testleri | |
| 294 | - `FileSource` fikstürleriyle koştu. Canlı köprüden gelen gerçek gövdelerle | |
| 295 | - hat hiç denenmedi. | |
| 296 | -6. **Zaman tabanlı süpürmenin gerçek takvimde koşması.** Süpürme, testlerde ve | |
| 297 | - kanıt koşusunda **enjekte edilmiş `now_ms`** ile çalıştırıldı. Gerçek gece | |
| 298 | - 03:00'te kendiliğinden koşan bir süreç izlenmedi. | |
| 299 | -7. **`discover_students`'ın sınırı duruyor.** Öğrenci listesi hâlâ | |
| 300 | - `homework_list().assigned` alanından türetiliyor; **hiç adrese özel ödev | |
| 301 | - almamış öğrenciler kaçırılır**. Bu bir depolama sorunu değil, `Source` | |
| 302 | - arayüzünün eksiği (`docs/BACKEND-GEREKSINIMLERI.md` madde 3). | |
| 303 | -8. **`recommendation.dismissed_*` alanlarını ZEKA hiç yazmaz.** İnsan | |
| 304 | - müdahalesi izini (KVKK m.11) dolduracak bir ürün yolu yok; alanlar şemada | |
| 305 | - var ama hat onları hiç üretmiyor. Bu alanların gece koşusunda | |
| 306 | - **silinmediği** kanıtlandı (`recommendation` tablosu `UPSERT ... MERGE` ile | |
| 307 | - yazılır; `test_rerun_does_not_erase_a_human_dismissal`), ama onları dolduran | |
| 308 | - tarafın davranışı denenmedi. |
service/docs/DESEN-DOGRULAMA.mdmodified+2 -2
| @@ -214,7 +214,7 @@ içinde **en zayıf** ayrım budur; abartılmamalıdır. Diğer üçü net ayrı | ||
| 214 | 214 | |
| 215 | 215 | | Denetim | Sonuç | |
| 216 | 216 | |---|---| |
| 217 | -| `seed/99_dogrula.surql` — 48 bütünlük sorgusu (SurrealDB üzerinde) | **48 geçti / 0 ihlal / 0 hata** | | |
| 217 | +| `seed/99_dogrula.surql` — 48 bütünlük sorgusu | **48 geçti / 0 ihlal / 0 hata** | | |
| 218 | 218 | | `generator/selfcheck.py` (şema, enum, referans, sayaç, kimlik, metin, sözdizimi) | **TEMİZ** | |
| 219 | 219 | | Belirlenimcilik — aynı tohum, iki koşu, `cmp` | **14/14 dosya bayt bayt aynı** | |
| 220 | 220 | | Satır hacmi | 569.808 (önce 573.027, **−%0,6**) | |
| @@ -236,7 +236,7 @@ cd generator && python main.py && python selfcheck.py ../seed | ||
| 236 | 236 | # 2) beş desen ölçümü (yalnız .surql + manifest; veritabanı gerekmez) |
| 237 | 237 | python tools/measure_pattern.py --json work/desen.json |
| 238 | 238 | |
| 239 | -# 3) bütünlük sorguları (SurrealDB gerekir) | |
| 239 | +# 3) bütünlük sorguları (yüklenmiş tohum gerekir) | |
| 240 | 240 | python tools/load_seed.py --seed-dir seed |
| 241 | 241 | python tools/check_integrity.py |
| 242 | 242 | ``` |
service/docs/HESAP-DOGRULAMA.mdmodified+1 -1
| @@ -535,7 +535,7 @@ cd service && python -m unittest tests.test_compute_attention -v | ||
| 535 | 535 | ``` |
| 536 | 536 | |
| 537 | 537 | `tools/build_student_fixtures.py` tohum `.surql` dosyalarını doğrudan |
| 538 | -ayrıştırır (SurrealDB konteyneri gerekmez) ve | |
| 538 | +ayrıştırır (yüklenmiş bir veritabanı gerekmez) ve | |
| 539 | 539 | `service/fixtures/gold_students/` altına `Source` arayüzünün tam biçiminde |
| 540 | 540 | yazar. `service/tests/test_compute_gold.py` içindeki eşikler dosyanın başında |
| 541 | 541 | `SENARYO_*` (senaryo §7'den birebir) ve `OLCULEN_*` (gerileme koruması) diye |
service/docs/KOPRU-KANITI.mdmodified+4 -3
| @@ -314,9 +314,10 @@ dogrulamaz. | ||
| 314 | 314 | sunucu testin verdigi govdeyi doner. Govde bicimleri ayri olarak |
| 315 | 315 | `tests/test_source.py` icinde fiksturlere karsi denetlenir; ikisi arasindaki |
| 316 | 316 | bag **kurulmadi**. |
| 317 | -- ZEKA'nin yetenekleri (`insight.*`) backend tarafindan **taninmiyor** | |
| 318 | - (`capabilities.py` basi). Sunucu baslatimli akis testi bu yuzden sahte bir | |
| 319 | - cagriyla yapildi; uretimde bu yol **bugun hic kullanilmaz**. | |
| 317 | +- ZEKA'nin yetenekleri (`insight.*`) icin backend'de bir **dagitim kapisi | |
| 318 | + yok** (`docs/BACKEND-GEREKSINIMLERI.md` Madde 1; sahibi `InsightDoors`). | |
| 319 | + Sunucu baslatimli akis testi bu yuzden sahte bir cagriyla yapildi; kapilar | |
| 320 | + gelene kadar bu yol uretimde **kullanilmaz**. | |
| 320 | 321 | - Coklu okul (filo paylasimi) davranisi tek bir okulla test edildi. |
| 321 | 322 | - Ayni backend'e **birden cok ZEKA ornegi** baglanmasi test edilmedi. |
| 322 | 323 |
service/docs/OKUL-DB-TABLOLARI.mddeleted+0 -231
| @@ -1,231 +0,0 @@ | ||
| 1 | -# ZEKA için okul veritabanına eklenecek tablolar | |
| 2 | - | |
| 3 | -> ## ⏸️ BU BELGE İLERİYE DÖNÜK TAŞIMA PLANIDIR — BUGÜNKÜ DURUM DEĞİLDİR | |
| 4 | -> | |
| 5 | -> **Bugün yürürlükte olan:** ZEKA kendi ayrı şemasını kullanır | |
| 6 | -> (`service/schema/zeka.surql`, `docs/DEPOLAMA.md`). Kod, testler ve çıktı | |
| 7 | -> sözleşmesi o şemaya göredir ve öyle kalacaktır. | |
| 8 | -> | |
| 9 | -> Bu belge, çıktıların ileride okulun tek ortak veritabanına taşınmasına karar | |
| 10 | -> verildiğinde uygulanacak tasarımı saklar. **Şimdilik uygulanmayacaktır.** | |
| 11 | - | |
| 12 | -> **Kime:** backend ekibi (taşıma günü geldiğinde). | |
| 13 | -> **Kapsam:** ZEKA'nın çıktısı ayrı bir veritabanında değil, **okulun kendi | |
| 14 | -> veritabanında** duracak. Bu belge eklenmesi gereken beş tabloyu, alanlarını ve | |
| 15 | -> mevcut tablolarla ilişkilerini verir. | |
| 16 | - | |
| 17 | ---- | |
| 18 | - | |
| 19 | -## 0. Tasarım kuralları (mevcut şemadan alındı) | |
| 20 | - | |
| 21 | -Bu tablolar backend'in kendi kurallarına uyar; ayrı bir dünya kurmaz. | |
| 22 | - | |
| 23 | -| Kural | Neden | | |
| 24 | -|---|---| | |
| 25 | -| **`school` alanı YOK** | Her okul zaten ayrı veritabanında (`tenant.rs`). Kiracı, veritabanının kendisidir. | | |
| 26 | -| **Kimlikler kayıt bağı** (`record<user>`, `record<exam_question>`) | Mevcut şemanın deseni (`exam_answer.user: record<user>`). Metin kimlik kullanılmaz. | | |
| 27 | -| **`SCHEMAFULL`** | 60 tablonun tamamı öyle. Tanımsız alan sessizce düşer. | | |
| 28 | -| **Zaman `int` unix-ms** | `domain/timestamp.rs`. `datetime` kullanılmaz. | | |
| 29 | -| **Ad öneki `zeka_`** | 60 mevcut tabloyla çakışmayı önler, sahipliği görünür kılar. | | |
| 30 | -| **Kompozit kimlik** | Gecelik üzerine yazım için (`{user}_{...}`), `domain/key.rs` deseni. | | |
| 31 | -| **`retain_until` + indeks** | Saklama süpürmesi bu alanı tarar. | | |
| 32 | - | |
| 33 | -**Yazan taraf yalnız ZEKA'dır.** Backend bu tablolara yazmaz, yalnız okur. | |
| 34 | -ZEKA mevcut 60 tablonun hiçbirine yazmaz. | |
| 35 | - | |
| 36 | ---- | |
| 37 | - | |
| 38 | -## 1. `zeka_student_summary` — öğrenci başına gecelik özet | |
| 39 | - | |
| 40 | -Kimlik: `{user_key}` — öğrenci başına tek satır, her gece üzerine yazılır. | |
| 41 | - | |
| 42 | -| Alan | Tip | Açıklama | | |
| 43 | -|---|---|---| | |
| 44 | -| `student` | `record<user>` | Özetin sahibi | | |
| 45 | -| `marks` | `option<object> FLEXIBLE` | Ders bazında not durumu, bant, kohort konumu | | |
| 46 | -| `attendance` | `option<object> FLEXIBLE` | Ders bazında devam oranı ve kohort karşılaştırması | | |
| 47 | -| `submission` | `option<object> FLEXIBLE` | Teslim disiplini, geç ve eksik oranları | | |
| 48 | -| `study` | `option<object> FLEXIBLE` | Çalışma düzeni, haftalık hacim | | |
| 49 | -| `attention` | `option<array<object>>` | **Dikkat listesi maddeleri — öğrenciye ve veliye gösterilmez** | | |
| 50 | -| `confidence` | `string` | `yeterli` / `dusuk` / `yok` | | |
| 51 | -| `computed_at` | `int` | Hesaplanma anı | | |
| 52 | -| `retain_until` | `int` | Silinme sınırı | | |
| 53 | - | |
| 54 | -İndeks: `student` · `retain_until` | |
| 55 | - | |
| 56 | ---- | |
| 57 | - | |
| 58 | -## 2. `zeka_recommendation` — tavsiyeler | |
| 59 | - | |
| 60 | -Kimlik: ULID (`monotonic_id::next_ulid` deseni) — öğrenci başına çok satır. | |
| 61 | - | |
| 62 | -| Alan | Tip | Açıklama | | |
| 63 | -|---|---|---| | |
| 64 | -| `audience` | `record<user>` | Kime gösterilecek | | |
| 65 | -| `audience_role` | `string` | `student` / `teacher` / `manager` | | |
| 66 | -| `about` | `option<record<user>>` | Hangi öğrenci hakkında (öğretmen tavsiyelerinde dolu) | | |
| 67 | -| `product` | `string` | `O1`, `O3`, `T3`, `T4`… | | |
| 68 | -| `rule_id` | `string` | `T4.homework` gibi kural kimliği | | |
| 69 | -| `rule_version` | `int` | Kural sürümü | | |
| 70 | -| `course` | `option<record<course>>` | İlgili ders | | |
| 71 | -| `evidence` | `object FLEXIBLE` | Gerekçe — **boşsa satır yazılmaz** | | |
| 72 | -| `confidence` | `string` | Güven | | |
| 73 | -| `created_at` | `int` | Üretim anı | | |
| 74 | -| `expires_at` | `int` | Gösterim sonu | | |
| 75 | -| `retain_until` | `int` | Silinme sınırı | | |
| 76 | -| `dismissed_at` | `option<int>` | Kullanıcı kapattıysa | | |
| 77 | -| `dismissed_by` | `option<record<user>>` | Kim kapattı | | |
| 78 | -| `dismiss_reason` | `option<string>` | Gerekçesi | | |
| 79 | - | |
| 80 | -İndeks: `audience, created_at` · `about, product` · `rule_id, created_at` · `retain_until` | |
| 81 | - | |
| 82 | -> **Dikkat:** ZEKA bu tabloya `UPSERT ... MERGE` ile yazar. `CONTENT` kullanılırsa | |
| 83 | -> kullanıcının kapatma kaydı her gece silinir. | |
| 84 | - | |
| 85 | ---- | |
| 86 | - | |
| 87 | -## 3. `zeka_run` — gece işinin defteri | |
| 88 | - | |
| 89 | -Kimlik: ULID. | |
| 90 | - | |
| 91 | -| Alan | Tip | | |
| 92 | -|---|---| | |
| 93 | -| `started_at`, `finished_at` | `int`, `option<int>` | | |
| 94 | -| `status` | `string` (`ok` / `partial` / `failed`) | | |
| 95 | -| `duration_ms` | `option<int>` | | |
| 96 | -| `students_total`, `students_ok`, `students_failed`, `students_skipped` | `int` | | |
| 97 | -| `rows_written` | `int` | | |
| 98 | -| `pending_students` | `option<array<record<user>>>` — bütçe dolduğu için ertesi geceye kalanlar | | |
| 99 | -| `failed_modules` | `option<array<string>>` | | |
| 100 | -| `budget_exceeded` | `bool` | | |
| 101 | -| `budget_ms` | `int` | | |
| 102 | -| `retain_until` | `int` | | |
| 103 | - | |
| 104 | -İndeks: `started_at` · `retain_until` | |
| 105 | - | |
| 106 | ---- | |
| 107 | - | |
| 108 | -## 4. `zeka_question_segment` — soru başına bilişsel etiket | |
| 109 | - | |
| 110 | -Kimlik: `{exam_question_key}` — soru başına tek satır. | |
| 111 | - | |
| 112 | -| Alan | Tip | Açıklama | | |
| 113 | -|---|---|---| | |
| 114 | -| `question` | `record<exam_question>` | Etiketlenen soru | | |
| 115 | -| `exam` | `option<record<exam>>` | Hangi sınav | | |
| 116 | -| `course` | `option<record<course>>` | Hangi ders | | |
| 117 | -| `subject` | `option<record<subject>>` | Hangi konu | | |
| 118 | -| `bilissel_talep` | `string` | `hatirlama` / `uygulama` / `analiz` | | |
| 119 | -| `dikkat_tuzagi` | `string` | `var` / `yok` | | |
| 120 | -| `okuma_yuku` | `string` | `dusuk` / `yuksek` | | |
| 121 | -| `adim_sayisi` | `string` | `tek_adim` / `cok_adim` — **deneysel** | | |
| 122 | -| `confidence_*` | `float` ×4 | Boyut başına güven | | |
| 123 | -| `confidence` | `string` | Genel güven | | |
| 124 | -| `downstream_dimensions` | `option<array<string>>` | Aşağı akışta kullanılan boyutlar | | |
| 125 | -| `experimental_dimensions` | `option<array<string>>` | Kullanılmayanlar ve sebebi satırdan okunur | | |
| 126 | -| `trap_choice` | `option<string>` | Tuzak şıkkın kimliği (`exam_question.choices[].id`) | | |
| 127 | -| `rationale` | `string` | Kısa gerekçe — **öğrenciye gösterilmez** | | |
| 128 | -| `model`, `prompt_version`, `variant` | `string`, `string`, `option<string>` | Üretim izi | | |
| 129 | -| `computed_at`, `retain_until` | `int` | | | |
| 130 | - | |
| 131 | -İndeks: `question` · `exam` · `subject` · `course, bilissel_talep` · `retain_until` | |
| 132 | - | |
| 133 | ---- | |
| 134 | - | |
| 135 | -## 5. `zeka_student_segment_profile` — öğrenci × boyut × etiket | |
| 136 | - | |
| 137 | -Kimlik: `{user_key}_{dimension}_{label}`. | |
| 138 | - | |
| 139 | -| Alan | Tip | Açıklama | | |
| 140 | -|---|---|---| | |
| 141 | -| `student` | `record<user>` | | | |
| 142 | -| `dimension` | `string` | `bilissel_talep` / `dikkat_tuzagi` / `okuma_yuku` | | |
| 143 | -| `label` | `string` | O boyutun etiketi | | |
| 144 | -| `n_answers`, `n_correct` | `int` | Bu segmentteki cevap ve doğru sayısı | | |
| 145 | -| `accuracy` | `float` | Segment doğruluğu — **tek başına kullanılmaz** | | |
| 146 | -| `overall_n_answers`, `overall_accuracy` | `int`, `float` | Öğrencinin genel değerleri | | |
| 147 | -| `contrast` | `float` | **`accuracy − overall_accuracy`. Asıl kullanılacak alan.** | | |
| 148 | -| `confidence` | `string` | | | |
| 149 | -| `computed_at`, `retain_until` | `int` | | | |
| 150 | - | |
| 151 | -İndeks: `student` · `dimension, label` · `retain_until` | |
| 152 | - | |
| 153 | -> **Neden `contrast`:** ham doğruluk öğrencinin genel yeteneğini yansıtır; iyi | |
| 154 | -> öğrenci her segmentte iyi görünür. Ayrım gücü yalnız öğrencinin kendi | |
| 155 | -> ortalamasından sapmasındadır. | |
| 156 | - | |
| 157 | ---- | |
| 158 | - | |
| 159 | -## 6. İlişki haritası | |
| 160 | - | |
| 161 | -```mermaid | |
| 162 | -erDiagram | |
| 163 | - user ||--o| zeka_student_summary : "student" | |
| 164 | - user ||--o{ zeka_recommendation : "audience" | |
| 165 | - user ||--o{ zeka_recommendation : "about" | |
| 166 | - user ||--o{ zeka_student_segment_profile : "student" | |
| 167 | - user ||--o{ zeka_run : "pending_students[]" | |
| 168 | - course ||--o{ zeka_recommendation : "course" | |
| 169 | - exam_question ||--o| zeka_question_segment : "question" | |
| 170 | - exam ||--o{ zeka_question_segment : "exam" | |
| 171 | - course ||--o{ zeka_question_segment : "course" | |
| 172 | - subject ||--o{ zeka_question_segment : "subject" | |
| 173 | -``` | |
| 174 | - | |
| 175 | -Mevcut tablolardan **yalnız beşine** bağlanılıyor: `user`, `course`, `exam`, | |
| 176 | -`exam_question`, `subject`. Hiçbirine yazılmıyor. | |
| 177 | - | |
| 178 | ---- | |
| 179 | - | |
| 180 | -## 7. Cascade ve yaşam döngüsü | |
| 181 | - | |
| 182 | -| Olay | Beklenen davranış | | |
| 183 | -|---|---| | |
| 184 | -| Öğrenci silinir | `zeka_student_summary`, `zeka_student_segment_profile` ve o öğrenciye ait `zeka_recommendation` satırları silinmeli | | |
| 185 | -| Soru silinir | `zeka_question_segment` satırı silinmeli | | |
| 186 | -| Ders silinir | `zeka_recommendation.course` boşaltılmalı ya da satır silinmeli | | |
| 187 | -| Dönem arşivlenir | Satırlar korunur; salt okunur | | |
| 188 | - | |
| 189 | -Mevcut şemada yabancı anahtar zorlanmıyor ve cascade uygulama | |
| 190 | -transaction'larında yapılıyor. Bu tablolar da aynı yolu izlemeli, aksi hâlde | |
| 191 | -öğrenci silindiğinde ZEKA satırları öksüz kalır. | |
| 192 | - | |
| 193 | -`retain_until` süpürmesini ZEKA kendi zamanlayıcısında koşturur; backend'in | |
| 194 | -ek bir iş yapması gerekmez. | |
| 195 | - | |
| 196 | ---- | |
| 197 | - | |
| 198 | -## 8. Yazma yetkisi | |
| 199 | - | |
| 200 | -ZEKA bu beş tabloya yazar. Önerilen: okul veritabanında **yalnız bu beş tabloya | |
| 201 | -yazma, kalan 60 tabloya salt okuma** yetkisi olan bir veritabanı kullanıcısı. | |
| 202 | -Bugün geliştirme sırasında tam yetkili kullanıcı kullanılıyor; üretimde | |
| 203 | -daraltılmalıdır. | |
| 204 | - | |
| 205 | ---- | |
| 206 | - | |
| 207 | -## 9. Hazır DDL | |
| 208 | - | |
| 209 | -`service/schema/zeka.surql` bu tabloların çalışan DDL'ini içerir. Ancak **o dosya | |
| 210 | -ayrı veritabanı varsayımıyla yazılmıştır**: her tabloda `school: string` alanı | |
| 211 | -taşır ve kayıt bağı yerine metin kimlik kullanır. Okul veritabanına taşınırken | |
| 212 | -bu belgedeki biçime uyarlanması gerekir. | |
| 213 | - | |
| 214 | -Uyarlama listesi: | |
| 215 | -1. `school` alanını ve ona dayalı indeksleri kaldır | |
| 216 | -2. `student`, `audience`, `about`, `dismissed_by` → `record<user>` | |
| 217 | -3. `question` → `record<exam_question>`, `exam` → `record<exam>`, | |
| 218 | - `course` → `record<course>`, `subject` → `record<subject>` | |
| 219 | -4. `pending_students` → `option<array<record<user>>>` | |
| 220 | -5. Tablo adlarına `zeka_` öneki ekle | |
| 221 | -6. Kompozit kimliklerden okul segmentini çıkar | |
| 222 | - | |
| 223 | ---- | |
| 224 | - | |
| 225 | -## 10. Bilinen tuzak | |
| 226 | - | |
| 227 | -SurrealDB, RPC ile gönderilen `user:01K...` biçimli **metni** uçta kayıt tipine | |
| 228 | -çevirir. `TYPE string` alan bunu reddeder ve **grubun tamamı düşer**; okuma | |
| 229 | -tarafında aynı durum **sessiz boş sonuç** verir. Kayıt bağına geçildiğinde bu | |
| 230 | -sorun kendiliğinden ortadan kalkar — bu, metin kimlik yerine `record<>` | |
| 231 | -kullanmanın ikinci gerekçesidir. |
service/docs/POSTGRES-GECIS.mddeleted+0 -162
| @@ -1,162 +0,0 @@ | ||
| 1 | -# Postgres geçişi — hazırlık durumu | |
| 2 | - | |
| 3 | -> **CANLIYA HİÇBİR ŞEY YAPILMADI.** Bu belge hazırlığın nerede olduğunu ve | |
| 4 | -> uygulama gününde ne yapılacağını anlatır. Backend deposunda tek bir dosya | |
| 5 | -> değiştirilmedi; üretilen her şey `hezarfen-ZEKA/` altındadır. | |
| 6 | - | |
| 7 | ---- | |
| 8 | - | |
| 9 | -## 0. Ne değişti | |
| 10 | - | |
| 11 | -Backend veritabanını değiştirdi: **SurrealDB 3.2 → PostgreSQL 18** (`sqlx 0.9`). | |
| 12 | -Şema artık kodun içinde gömülü değil, `migrations/control/` ve | |
| 13 | -`migrations/school/` altında dosyalar hâlinde; `Migrator` bunları açılışta | |
| 14 | -şablona ve her yeni okul veritabanına uyguluyor. | |
| 15 | - | |
| 16 | -ZEKA açısından **değişmeyenler** — bunları ayrıca doğruladım: | |
| 17 | - | |
| 18 | -| | | | |
| 19 | -|---|---| | |
| 20 | -| Köprü protokolü | `hab/2`, aynı | | |
| 21 | -| İzin listesi | 19 yol, **harfi harfine aynı** (sınav yolu yine yok) | | |
| 22 | -| Kiracılık | okul başına ayrı veritabanı, aynı | | |
| 23 | -| Zaman | `BIGINT` unix-ms UTC, aynı | | |
| 24 | -| Yetenekler | yine yalnız `chat.reply` + `rag.index` | | |
| 25 | - | |
| 26 | -Yani `service/src/` içindeki köprü, `Source` arayüzü ve hesap modülleri | |
| 27 | -**etkilenmiyor**. Etkilenen iki şey var: ZEKA'nın çıktı şeması ve tohum verisi. | |
| 28 | - | |
| 29 | ---- | |
| 30 | - | |
| 31 | -## 1. Hazır olan: ZEKA'nın Postgres şeması | |
| 32 | - | |
| 33 | -`service/schema/postgres/school/20260916000001_zeka.sql` | |
| 34 | - | |
| 35 | -Uygulama günü bu dosya backend'in `migrations/school/` klasörüne **eklenecek** | |
| 36 | -(hiçbir mevcut dosya değişmeyecek — sqlx migration'ları sağlama toplamıyla | |
| 37 | -izler, var olan bir dosyayı düzenlemek uygulanmış veritabanlarını kırar). | |
| 38 | - | |
| 39 | -Tablolar: | |
| 40 | - | |
| 41 | -| Tablo | Ne tutar | | |
| 42 | -|---|---| | |
| 43 | -| `zeka_student_summary` | öğrenci başına gecelik özet (PK: `student`) | | |
| 44 | -| `zeka_attention_item` | dikkat listesi maddeleri, tetikleyici başına satır | | |
| 45 | -| `zeka_recommendation` | tavsiyeler, kapatma izi dahil | | |
| 46 | -| `zeka_run` | gece işinin defteri (PK: `run_day`) | | |
| 47 | -| `zeka_run_pending` | bütçe dolunca kalanlar | | |
| 48 | -| `zeka_run_failed_module` | hata veren modüller | | |
| 49 | -| `zeka_question_segment` | soru başına bilişsel etiket (PK: `question`) | | |
| 50 | -| `zeka_question_segment_dimension` | üretim/deneysel boyut ayrımı | | |
| 51 | -| `zeka_student_segment_profile` | öğrenci × boyut × etiket, `contrast` dahil | | |
| 52 | - | |
| 53 | -Backend'in kendi çeviri kurallarına uyuldu: | |
| 54 | - | |
| 55 | -- `school` kolonu **yok** — kiracı veritabanın kendisi | |
| 56 | -- kayıt bağları → `uuid` FK, hepsi `ON DELETE NO ACTION` | |
| 57 | -- `{a}_{b}` metin anahtarları → doğal bileşik PK | |
| 58 | -- `option<object> FLEXIBLE` → **JSONB**, yalnız şekli servise ait alanlarda | |
| 59 | - (`exam_question.choices` ve `rag_output.payload` ile aynı çizgi) | |
| 60 | -- diziler → `ord` kolonlu **çocuk tablo**, Postgres dizisi değil (backend | |
| 61 | - elindeki her `TEXT[]`/`uuid[]`'i böyle açtı; dizi kullansaydık şemadaki tek | |
| 62 | - istisna olurduk) | |
| 63 | -- kimlikler uygulama tarafından basılan **uuid v7** | |
| 64 | - | |
| 65 | -**FK yönü tek taraflı:** `zeka_*` tabloları `app_user`, `course`, `subject`, | |
| 66 | -`exam_question`'a bakar; okul tablolarının hiçbiri `zeka_*`'a bakmaz. Doğrulama | |
| 67 | -betiği bunu ayrıca sınar — ters yönlü tek bir FK bile çıkarsa hata verir, | |
| 68 | -çünkü o, okul şemasını ZEKA'ya bağımlı hâle getirirdi. | |
| 69 | - | |
| 70 | -### Çeviride bilinçli verilen iki karar | |
| 71 | - | |
| 72 | -**`zeka_recommendation.id` eklendi.** SurrealDB'de anahtar | |
| 73 | -`{school}_{audience}_{product}_{rule_id}[_{scope}]` idi. Postgres'te `scope` | |
| 74 | -NULL olabildiği için bu doğal anahtar PK olamıyor (`NULLS NOT DISTINCT` yalnız | |
| 75 | -`UNIQUE` için geçerli). Doğal anahtar `UNIQUE NULLS NOT DISTINCT` olarak duruyor | |
| 76 | -ve UPSERT hâlâ onun üzerinden idempotent; ayrıca bir vekil `id` var. Bu zaten | |
| 77 | -işe yarıyor: kartı kapatmak tek satıra yazmaktır, istemcinin dört kolon | |
| 78 | -adlandırması gerekmesin. | |
| 79 | - | |
| 80 | -**`zeka_question_segment.course` denormalize bırakıldı.** `subject.course`'tan | |
| 81 | -türetilebilir ama öğretmenin "ders × bilişsel talep" ekranı join'siz çalışsın | |
| 82 | -diye satırda duruyor. Çıktı sözleşmesinde zaten yayınlanmış durumda, kaldırmak | |
| 83 | -frontend'i etkilerdi. | |
| 84 | - | |
| 85 | ---- | |
| 86 | - | |
| 87 | -## 2. Hazır olan: doğrulama betiği | |
| 88 | - | |
| 89 | -`tools/check_pg_schema.sh` | |
| 90 | - | |
| 91 | -Tek kullanımlık bir Postgres'e önce backend'in kendi migration'larını, sonra | |
| 92 | -ZEKA'nınkini uygular; `zeka_*` tablolarını, dışa giden FK'leri ve ters FK | |
| 93 | -olmadığını raporlar; sonunda veritabanını düşürür. Hiçbir backend dosyasına | |
| 94 | -yazmaz. | |
| 95 | - | |
| 96 | -Bunun neden var olduğu deneyle sabit: bu şemanın SurrealDB sürümü iki kez | |
| 97 | -gözden geçirildi ve yine de beş alanı sessizce düşürdü — `FLEXIBLE TYPE object` | |
| 98 | -ayrıştırma hatası veriyor, SCHEMAFULL tablo tanımsız alanı tek kelime etmeden | |
| 99 | -atıyor. Okumakla görülmüyor; yalnız koşturmakla görülüyor. | |
| 100 | - | |
| 101 | ---- | |
| 102 | - | |
| 103 | -## 3. Henüz yapılmayanlar | |
| 104 | - | |
| 105 | -**a) Depolama katmanı.** `src/store.py` (739 satır) SurrealDB'ye yazıyor: | |
| 106 | -`DbClient` protokolü, `SurrealHttpClient`, `UPSERT ... MERGE`. Postgres'te | |
| 107 | -karşılığı `INSERT ... ON CONFLICT DO UPDATE`. Yeni bir istemci ve yeni bir | |
| 108 | -`Store` uygulaması gerekiyor; arayüz (`write_summaries`, | |
| 109 | -`write_recommendations`, `write_question_segments`, `write_segment_profiles`, | |
| 110 | -`write_run`, `last_pending`, `sweep`, `purge_departed`) aynı kalabilir. | |
| 111 | - | |
| 112 | -> Burada bir tuzak var, önceden not ediyorum: nightly yazım | |
| 113 | -> `zeka_recommendation`'a **MERGE** yapmalı. `dismissed_at`, `dismissed_by` ve | |
| 114 | -> `dismiss_reason` kolonlarını ezen bir `ON CONFLICT DO UPDATE SET` yazılırsa | |
| 115 | -> kullanıcının kapatma kaydı her gece silinir. SurrealDB sürümünde aynı tuzak | |
| 116 | -> vardı ve şema yorumuna yazılmıştı; Postgres'te `DO UPDATE SET` varsayılan | |
| 117 | -> olarak *her* kolonu yazdığı için risk daha yüksek. | |
| 118 | - | |
| 119 | -**b) Tohum verisi.** 569.808 satır SurrealQL. 58/59 tablo birebir karşılık | |
| 120 | -buluyor (yalnız `migration_mark` düşüyor, o da backend tarafından kasten | |
| 121 | -atılmış). Gereken iş: | |
| 122 | - | |
| 123 | -1. ULID → UUID v7 **deterministik** eşleme (ikisi de 48 bit ms damgası taşıyor, | |
| 124 | - sıralama korunabilir). Deterministik olmak zorunda, yoksa "başka lokalde | |
| 125 | - aynı veri" hedefi bozulur. | |
| 126 | -2. Üreticiye Postgres yazıcısı (regex'le `.surql` ayrıştırmak **değil** — | |
| 127 | - bunun bedelini bir kez ödedik, `\'` kaçışını anlamayan bir regex 47 hatalı | |
| 128 | - ölçüm üretmişti). | |
| 129 | -3. 10 gömülü diziyi çocuk tablo satırlarına aç. | |
| 130 | -4. Control veritabanı: `person`, `person_school`, `school` satırları. | |
| 131 | - | |
| 132 | -Referans bütünlüğünü şimdiden kontrol ettim, Postgres'in FK'leri artık | |
| 133 | -zorlaması sorun çıkarmıyor: | |
| 134 | - | |
| 135 | -``` | |
| 136 | -from_bank referansı: 2.636 | kopuk: 0 | |
| 137 | -exam_answer (exam, question) çelişkili: 0 / 216.633 | |
| 138 | -``` | |
| 139 | - | |
| 140 | -**c) Bir semantik kayıp.** Sayaç kolonları artık `BIGINT NOT NULL DEFAULT 0`. | |
| 141 | -Tohumdaki **K2** (`lessons_attended_total` NONE, 250 satır) ve **K3** | |
| 142 | -(`high_mark_total` NONE, 250 satır) kasıtlı bozuklukları Postgres'te temsil | |
| 143 | -edilemiyor; `0` olacaklar. Anlam aynı — migration başlığı da bunu söylüyor: | |
| 144 | -*"counter columns (absent-reads-as-zero in Surreal) are BIGINT NOT NULL | |
| 145 | -DEFAULT 0"* — ama ZEKA artık "hiç sayılmadı" ile "sıfır sayıldı" ayrımını | |
| 146 | -yapamaz. Kalan 8 kasıtlı bozukluk (K1, K4–K10) aynen taşınıyor. | |
| 147 | - | |
| 148 | ---- | |
| 149 | - | |
| 150 | -## 4. Uygulama günü sırası | |
| 151 | - | |
| 152 | -1. `tools/check_pg_schema.sh` yeşil olsun | |
| 153 | -2. `20260916000001_zeka.sql` backend'in `migrations/school/`'una **eklensin** | |
| 154 | - (mevcut dosyalara dokunulmadan) | |
| 155 | -3. `scripts/prepare_db.sh` koşsun — sqlx derleme zamanı sorgu kontrolü | |
| 156 | -4. Depolama katmanı Postgres'e çevrilsin, gerçek veritabanına karşı test edilsin | |
| 157 | -5. Tohum dönüştürülsün ve yüklensin | |
| 158 | -6. Hat uçtan uca koşsun | |
| 159 | - | |
| 160 | -**1–5 arası hiçbir adım canlıyı etkilemez.** Adım 2 backend deposunda bir | |
| 161 | -dosya ekler; o da bizim değil, backend ekibinin kararı ve onların eliyle | |
| 162 | -yapılmalı. |
service/docs/RAPORLAR.mdmodified+12 -11
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | # ZEKA Raporları |
| 2 | 2 | |
| 3 | -> ZEKA sonuç üretiyor ama kimse göremiyordu: analizler kendi veritabanına | |
| 3 | +> ZEKA sonuç üretiyor ama kimse göremiyordu: analizler okulun veritabanına | |
| 4 | 4 | > yazılıyor ve orada kalıyordu. Frontend'de değişiklik yapılmayacağı için |
| 5 | 5 | > teslim biçimi **rapor**dur. Bu belge o katmanı anlatır. |
| 6 | 6 | > |
| @@ -11,8 +11,9 @@ | ||
| 11 | 11 | |
| 12 | 12 | ## 0. Beş cümlede |
| 13 | 13 | |
| 14 | -1. Rapor **yalnız ZEKA'nın kendi beş tablosunu okur**: köprüye gitmez, okul | |
| 15 | - veritabanına dokunmaz, hiçbir şeye yazmaz. | |
| 14 | +1. Rapor **hattı olduğu gibi koşturup yazılan satırları bellekten yakalar**: | |
| 15 | + ne açılan bir veritabanı, ne bir sürücü, ne bir bağlantı dizesi. Taşıma `store.py`'nin | |
| 16 | + köprü deposudur; rapor onun yerine bir yakalayıcı koyar. | |
| 16 | 17 | 2. Dört rapor vardır: `okul` (yönetim), `ogretmen`, `ogrenci` (öğrenci/veli), |
| 17 | 18 | `ham` (teknik ekip). |
| 18 | 19 | 3. Üç biçim vardır: **JSON** (makine okunabilir), **HTML** (tek dosya, gömülü |
| @@ -31,15 +32,15 @@ python -m src.cli report --school ataturk-anadolu \ | ||
| 31 | 32 | --type okul|ogretmen|ogrenci|ham \ |
| 32 | 33 | --format json|html|csv \ |
| 33 | 34 | --out DIZIN [--about ÖĞRENCİ] [--teacher ÖĞRETMEN] \ |
| 34 | - [--db-url http://hzk-zeka:8000 | --fixtures service/fixtures/demo] [--now MS] | |
| 35 | + --fixtures service/fixtures/demo [--now MS] | |
| 35 | 36 | ``` |
| 36 | 37 | |
| 37 | 38 | * `--about` öğrenci raporunda **zorunludur**, `--teacher` öğretmen raporunda. |
| 38 | -* Veri kaynağı iki türlü verilir: | |
| 39 | - * `--db-url` (ya da `ZEKA_DB_HTTP_URL`) → gerçek ZEKA veritabanı; | |
| 40 | - * `--fixtures` → veritabanı yoksa hattı fikstürden koşturur, yazılan | |
| 41 | - satırları bellekte yakalar (`report/capture.py`) ve raporu onlardan | |
| 42 | - üretir. Aynı rapor kodu koşar; yalnız taşıma değişir. | |
| 39 | +* `--fixtures` **zorunludur**: rapor, hattı fikstürden koşturup yazılan | |
| 40 | + satırları bellekte yakalar (`report/capture.py`) ve raporu onlardan üretir. | |
| 41 | + Aynı rapor kodu koşar; yalnız taşıma değişir — canlı bir dağıtımı okumak için | |
| 42 | + bir bayrak yoktur ve olmayacaktır (rapor bir teslim biçimidir, bir yönetim | |
| 43 | + konsolu değil). | |
| 43 | 44 | |
| 44 | 45 | Çıktı dosya adları öngörülebilir ve tarihlidir: |
| 45 | 46 | |
| @@ -64,7 +65,7 @@ iki nokta Windows'ta geçerli bir dosya adı karakteri değildir. | ||
| 64 | 65 | | `okul` | Yönetim | `toplu_gorunum`, `sube_ders`, `kosu_defteri`, `dikkat_listesi`, `tavsiye_dagilimi`, `uretilemeyenler` | |
| 65 | 66 | | `ogretmen` | Öğretmen | `siniflarim`, `dikkat_listesi`, `isi_haritasi`, `tavsiyeler`, `uretilemeyenler` | |
| 66 | 67 | | `ogrenci` | Öğrenci/veli | `dersler`, `calisma`, `teslim`, `yaklasan`, `segment`, `tavsiyeler` | |
| 67 | -| `ham` | Teknik ekip | `tables` (beş tablo, JSON gövde), `recommendation`, `student_segment_profile`, `uretilemeyenler` | | |
| 68 | +| `ham` | Teknik ekip | `tables` (ham satırlar, JSON gövde), `recommendation`, `student_segment_profile`, `uretilemeyenler` | | |
| 68 | 69 | |
| 69 | 70 | **Öğretmenin kapsamı** hakkında tavsiye aldığı öğrencilerden çözülür |
| 70 | 71 | (`recommendation.audience = öğretmen`, `about = öğrenci`): şube üyeliği ve |
| @@ -204,7 +205,7 @@ bölümlü "Neden?" bir tablo değildir, hücreye sıkıştırılırsa okunmaz o | ||
| 204 | 205 | |
| 205 | 206 | ### JSON |
| 206 | 207 | |
| 207 | -Zarf §2'dedir. `ham` raporunda beş tablonun satırları olduğu gibi durur, üç | |
| 208 | +Zarf §2'dedir. `ham` raporunda satırlar olduğu gibi durur, üç | |
| 208 | 209 | istisnayla: |
| 209 | 210 | |
| 210 | 211 | * `recommendation`: kapatılmış / süresi geçmiş / kanıtsız satırlar çıkarılır — |
service/requirements.txtmodified+0 -13
| @@ -32,16 +32,3 @@ service-identity==26.1.0 | ||
| 32 | 32 | # |
| 33 | 33 | # Windows notu: yukaridaki surumlerin hepsi hazir tekerlek (wheel) olarak |
| 34 | 34 | # gelir; kurulum icin derleyici GEREKMEZ. |
| 35 | - | |
| 36 | -# --- Postgres (okul veritabanina yazma) ------------------------------------- | |
| 37 | -# Backend SurrealDB'den PostgreSQL'e gecti; ZEKA'nin cikti tablolari artik | |
| 38 | -# okulun kendi Postgres veritabaninda. Tel protokolu stdlib'de yok, elle | |
| 39 | -# yazilacak bir sey de degil. | |
| 40 | -# | |
| 41 | -# `[binary]` hazir tekerlek getirir: derleyici GEREKMEZ (Windows dahil). | |
| 42 | -# Surum PINLI, yukaridakilerle ayni gerekce. | |
| 43 | -# | |
| 44 | -# YALNIZ `src/pg_client.py` import eder ve o da tembel (fonksiyon icinde). | |
| 45 | -# `src/store_pg.py` bir Postgres surucusu import ETMEZ; birim testleri ve | |
| 46 | -# `--dry-run` psycopg kurulu olmadan da kosar. | |
| 47 | -psycopg[binary]==3.2.13 |
service/schema/postgres/school/20260916000001_zeka.sqldeleted+0 -383
| @@ -1,383 +0,0 @@ | ||
| 1 | --- ZEKA's output tables, in the school database (Postgres). | |
| 2 | --- | |
| 3 | --- WHERE THIS FILE BELONGS: `migrations/school/` in the backend repo, applied | |
| 4 | --- by `Migrator::new(migrations/school)` to the template at boot and to every | |
| 5 | --- school database at create. It is APPEND-ONLY relative to the four existing | |
| 6 | --- school migrations: it creates new tables and touches none of them. | |
| 7 | --- | |
| 8 | --- SCOPE RULE, unchanged: ZEKA **never writes** to a pre-existing table. It | |
| 9 | --- reads school data through the bridge's `ApiRequest` allowlist only, and | |
| 10 | --- writes nothing but the `zeka_*` tables below. The FKs point outward, one | |
| 11 | --- direction only. | |
| 12 | --- | |
| 13 | --- NO `school` COLUMN: each school already lives in its own database, so the | |
| 14 | --- tenant IS the database. The SurrealDB version carried a `school` slug on | |
| 15 | --- every row because ZEKA then had a database of its own; that column is gone | |
| 16 | --- and every composite key drops its school segment with it. | |
| 17 | --- | |
| 18 | --- Translated from service/schema/zeka.surql, following the same rules the | |
| 19 | --- backend's own translation used: | |
| 20 | --- * record links -> uuid FKs, ALL `ON DELETE NO ACTION` (cascades stay | |
| 21 | --- explicit application transactions) | |
| 22 | --- * `{a}_{b}` text record keys -> natural composite PRIMARY KEYs | |
| 23 | --- * timestamps -> BIGINT unix-ms UTC, never `timestamptz` | |
| 24 | --- * `option<object> FLEXIBLE` -> JSONB, and only where the shape belongs to | |
| 25 | --- the service rather than to this schema (the same line | |
| 26 | --- `rag_output.payload` and `exam_question.choices` draw) | |
| 27 | --- * `option<array<...>>` -> a child table with an `ord` column, never a | |
| 28 | --- Postgres array: the backend replaced every `TEXT[]` | |
| 29 | --- and `uuid[]` it had (course_teacher, menu_dish_tag, | |
| 30 | --- blueprint_course, ...), and an array here would be the | |
| 31 | --- one exception in the schema. | |
| 32 | --- * entity ids are app-minted uuid v7 (`domain::monotonic_id::next_uuid`), | |
| 33 | --- never a DB default — the one id convention in the codebase. | |
| 34 | --- | |
| 35 | --- CHECK constraints carry only the enums ZEKA itself closes (confidence tier, | |
| 36 | --- audience role, run status, segment dimension + its labels). `product` and | |
| 37 | --- `rule_id` carry NO CHECK: rules are added and versioned far more often than | |
| 38 | --- the schema, and a DDL CHECK could not survive that — the same reasoning that | |
| 39 | --- left exam kinds and attendance statuses unconstrained. | |
| 40 | - | |
| 41 | - | |
| 42 | --- --------------------------------------------------------------------------- | |
| 43 | --- 1) zeka_student_summary — one nightly row per student | |
| 44 | --- | |
| 45 | --- PK is the student alone (the `{school}_{user}` key minus its school half), | |
| 46 | --- which makes the nightly write an idempotent UPSERT and needs no extra | |
| 47 | --- unique index. Same shape as `dietary_profile`, keyed on `app_user`. | |
| 48 | --- --------------------------------------------------------------------------- | |
| 49 | -CREATE TABLE zeka_student_summary ( | |
| 50 | - student uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | |
| 51 | - -- The compute modules' output objects. JSONB because the shape belongs to | |
| 52 | - -- the service: it changes with a rule version, and this schema should not | |
| 53 | - -- have to move every time it does. | |
| 54 | - marks JSONB NULL, | |
| 55 | - attendance JSONB NULL, | |
| 56 | - submission JSONB NULL, | |
| 57 | - study JSONB NULL, | |
| 58 | - -- 'none' | 'exploratory' | 'stable' — inherited from the weakest input. | |
| 59 | - confidence TEXT NOT NULL | |
| 60 | - CHECK (confidence IN ('none', 'exploratory', 'stable')), | |
| 61 | - computed_at BIGINT NOT NULL, | |
| 62 | - -- Swept after this instant: derived student profile, "term + 1 year". | |
| 63 | - retain_until BIGINT NOT NULL, | |
| 64 | - CONSTRAINT zeka_student_summary_student PRIMARY KEY (student) | |
| 65 | -); | |
| 66 | - | |
| 67 | -CREATE INDEX zeka_student_summary_retain ON zeka_student_summary (retain_until); | |
| 68 | - | |
| 69 | --- The attention list, one row per trigger (was an embedded array). | |
| 70 | --- | |
| 71 | --- There is deliberately NO score column and no severity: a single risk number | |
| 72 | --- would rank children, and the literature review found no validated causal | |
| 73 | --- evidence for that product. `ord` keeps the writer's order, which is | |
| 74 | --- alphabetical by trigger and NOT by severity — see `attention.order_items`. | |
| 75 | -CREATE TABLE zeka_attention_item ( | |
| 76 | - student uuid NOT NULL REFERENCES zeka_student_summary(student) ON DELETE NO ACTION, | |
| 77 | - -- Which trigger fired: 'attendance' | 'homework' | 'mark_trend'. | |
| 78 | - -- No CHECK: a fourth trigger is a rule change, not a schema change. | |
| 79 | - trigger TEXT NOT NULL, | |
| 80 | - -- The course the trigger is about, when it has one. NULL = school-wide. | |
| 81 | - -- Only the mark-trend trigger is per-course today. | |
| 82 | - course uuid NULL REFERENCES course(id) ON DELETE NO ACTION, | |
| 83 | - -- THE SENTENCE THE TEACHER READS. A statement of fact, not a judgement: | |
| 84 | - -- "4 of the last 30 days' homework went unsubmitted", never "at risk". | |
| 85 | - -- It is written here rather than rebuilt by the reader, so that what was | |
| 86 | - -- shown and what was computed can never drift apart. | |
| 87 | - fact TEXT NOT NULL, | |
| 88 | - -- The window the fact is about. Kept as columns, not inside `evidence`, | |
| 89 | - -- because "is this item about the last 30 days or the last 7" is a | |
| 90 | - -- question the reader asks of every item. | |
| 91 | - window_from BIGINT NOT NULL, | |
| 92 | - window_to BIGINT NOT NULL, | |
| 93 | - -- The numbers behind the item. Never empty: the store | |
| 94 | - -- refuses an item without evidence, because an item nobody can explain | |
| 95 | - -- cannot be shown to a teacher. | |
| 96 | - evidence JSONB NOT NULL, | |
| 97 | - ord SMALLINT NOT NULL, | |
| 98 | - CONSTRAINT zeka_attention_item_student_trigger_course | |
| 99 | - UNIQUE NULLS NOT DISTINCT (student, trigger, course) | |
| 100 | -); | |
| 101 | - | |
| 102 | -CREATE INDEX zeka_attention_item_student ON zeka_attention_item (student); | |
| 103 | -CREATE INDEX zeka_attention_item_trigger ON zeka_attention_item (trigger); | |
| 104 | - | |
| 105 | - | |
| 106 | --- --------------------------------------------------------------------------- | |
| 107 | --- 2) zeka_recommendation — generated advice | |
| 108 | --- | |
| 109 | --- Every row carries a reason. Advice that cannot be explained is not shown, | |
| 110 | --- so `evidence` is NOT NULL and the store refuses an empty object. | |
| 111 | --- | |
| 112 | --- The old record key was `{school}_{audience}_{product}_{rule_id}[_{scope}]`; | |
| 113 | --- minus the school half that is exactly the composite PK below. `scope` is | |
| 114 | --- the optional last segment (a course id, usually), and NULLS NOT DISTINCT is | |
| 115 | --- what makes "no scope" count as a taken slot rather than an unlimited one — | |
| 116 | --- the same device `bank_question_image` uses for its NULL slot. | |
| 117 | --- --------------------------------------------------------------------------- | |
| 118 | -CREATE TABLE zeka_recommendation ( | |
| 119 | - -- A surrogate id, because the natural key below has a nullable column and | |
| 120 | - -- a PRIMARY KEY cannot: `NULLS NOT DISTINCT` is a UNIQUE-only device. It | |
| 121 | - -- earns its keep anyway — dismissing a card is a write against one row, | |
| 122 | - -- and a client should not have to name four columns to do it. | |
| 123 | - id uuid PRIMARY KEY, | |
| 124 | - -- Who sees it. | |
| 125 | - audience uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | |
| 126 | - -- Which product family: 'O1' | 'O2' | 'O3' | 'O4' | 'T3' | 'T4' today. | |
| 127 | - product TEXT NOT NULL, | |
| 128 | - -- Which rule, and which version of it, produced this. A rule may not | |
| 129 | - -- change what it says without changing this number. | |
| 130 | - rule_id TEXT NOT NULL, | |
| 131 | - rule_version BIGINT NOT NULL, | |
| 132 | - -- The rule's optional scope segment; NULL when the rule has none. TEXT, | |
| 133 | - -- not uuid: a segment rule scopes itself by label ("bilissel_talep=analiz", | |
| 134 | - -- "<class>_okuma_yuku=yuksek"), not by a row it could point at. | |
| 135 | - scope TEXT NULL, | |
| 136 | - -- Who it is about. NULL on a student's own card (audience = about would | |
| 137 | - -- be noise); set on every teacher-facing row. | |
| 138 | - about uuid NULL REFERENCES app_user(id) ON DELETE NO ACTION, | |
| 139 | - -- The role gate. T4 items are 'teacher' only — never shown to the student | |
| 140 | - -- or the parent. | |
| 141 | - audience_role TEXT NOT NULL | |
| 142 | - CHECK (audience_role IN ('student', 'teacher', 'parent', 'manager')), | |
| 143 | - course uuid NULL REFERENCES course(id) ON DELETE NO ACTION, | |
| 144 | - -- Which numbers, which window. Feeds the "why?" panel. | |
| 145 | - evidence JSONB NOT NULL, | |
| 146 | - confidence TEXT NOT NULL | |
| 147 | - CHECK (confidence IN ('none', 'exploratory', 'stable')), | |
| 148 | - created_at BIGINT NOT NULL, | |
| 149 | - expires_at BIGINT NOT NULL, | |
| 150 | - -- `expires_at` or 90 days, whichever comes first. The sweep reads this. | |
| 151 | - retain_until BIGINT NOT NULL, | |
| 152 | - -- The human-override trail (KVKK art. 11): dismissed, disputed, not | |
| 153 | - -- useful. The nightly write MERGES; it must never clear these three. | |
| 154 | - dismissed_at BIGINT NULL, | |
| 155 | - dismissed_by uuid NULL REFERENCES app_user(id) ON DELETE NO ACTION, | |
| 156 | - dismiss_reason TEXT NULL, | |
| 157 | - -- The idempotency key: the same rule is never duplicated for the same | |
| 158 | - -- person, so the nightly write is an UPSERT on this. | |
| 159 | - -- | |
| 160 | - -- `about` IS PART OF THE KEY, and that is not cosmetic. A teacher-facing | |
| 161 | - -- rule fires once per student: thirty students under one teacher, one | |
| 162 | - -- rule, one course. Without `about` all thirty share a key, the UPSERT | |
| 163 | - -- keeps the last, and the teacher is shown one student while twenty-nine | |
| 164 | - -- vanish without an error anywhere. (The SurrealDB version keyed on | |
| 165 | - -- `scope or course or about` and lost exactly that way.) | |
| 166 | - CONSTRAINT zeka_recommendation_key | |
| 167 | - UNIQUE NULLS NOT DISTINCT (audience, product, rule_id, about, scope) | |
| 168 | -); | |
| 169 | - | |
| 170 | -CREATE INDEX zeka_recommendation_audience ON zeka_recommendation (audience, created_at); | |
| 171 | -CREATE INDEX zeka_recommendation_about ON zeka_recommendation (about, product); | |
| 172 | --- Rule calibration: a rule dismissed as wrong over and over IS wrong. This | |
| 173 | --- index is what makes that measurable without a full scan. | |
| 174 | -CREATE INDEX zeka_recommendation_rule ON zeka_recommendation (rule_id, created_at); | |
| 175 | -CREATE INDEX zeka_recommendation_retain ON zeka_recommendation (retain_until); | |
| 176 | - | |
| 177 | - | |
| 178 | --- --------------------------------------------------------------------------- | |
| 179 | --- 3) zeka_run — the nightly job's ledger | |
| 180 | --- | |
| 181 | --- Partial failure and budget accounting rest on this. The key was | |
| 182 | --- `{school}_{YYYY-MM-DD}`; minus the school half it is the day itself, so a | |
| 183 | --- re-run of the same night overwrites rather than duplicating. TEXT PK, the | |
| 184 | --- same choice `settings.id` makes. | |
| 185 | --- --------------------------------------------------------------------------- | |
| 186 | -CREATE TABLE zeka_run ( | |
| 187 | - run_day TEXT NOT NULL | |
| 188 | - CHECK (run_day ~ '^[0-9]{4}-[0-9]{2}-[0-9]{2}$'), | |
| 189 | - started_at BIGINT NOT NULL, | |
| 190 | - finished_at BIGINT NULL, | |
| 191 | - status TEXT NOT NULL | |
| 192 | - CHECK (status IN ('running', 'ok', 'partial', 'failed', 'skipped')), | |
| 193 | - duration_ms BIGINT NULL, | |
| 194 | - students_total BIGINT NOT NULL DEFAULT 0, | |
| 195 | - students_ok BIGINT NOT NULL DEFAULT 0, | |
| 196 | - students_failed BIGINT NOT NULL DEFAULT 0, | |
| 197 | - students_skipped BIGINT NOT NULL DEFAULT 0, | |
| 198 | - rows_written BIGINT NOT NULL DEFAULT 0, | |
| 199 | - budget_exceeded BOOLEAN NOT NULL DEFAULT false, | |
| 200 | - budget_ms BIGINT NOT NULL, | |
| 201 | - retain_until BIGINT NOT NULL, | |
| 202 | - CONSTRAINT zeka_run_day PRIMARY KEY (run_day) | |
| 203 | -); | |
| 204 | - | |
| 205 | -CREATE INDEX zeka_run_started ON zeka_run (started_at); | |
| 206 | -CREATE INDEX zeka_run_retain ON zeka_run (retain_until); | |
| 207 | - | |
| 208 | --- Students the budget ran out on, one row each (was an embedded array). The | |
| 209 | --- next run starts here, which is the only reason the list is kept. | |
| 210 | -CREATE TABLE zeka_run_pending ( | |
| 211 | - run TEXT NOT NULL REFERENCES zeka_run(run_day) ON DELETE NO ACTION, | |
| 212 | - student uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | |
| 213 | - ord INTEGER NOT NULL, | |
| 214 | - CONSTRAINT zeka_run_pending_run_student PRIMARY KEY (run, student) | |
| 215 | -); | |
| 216 | - | |
| 217 | --- Modules that failed, one row each (was an embedded array). A partial list | |
| 218 | --- is what lets the UI mark a section "missing" instead of showing a hole. | |
| 219 | -CREATE TABLE zeka_run_failed_module ( | |
| 220 | - run TEXT NOT NULL REFERENCES zeka_run(run_day) ON DELETE NO ACTION, | |
| 221 | - module TEXT NOT NULL, | |
| 222 | - ord SMALLINT NOT NULL, | |
| 223 | - CONSTRAINT zeka_run_failed_module_run_module PRIMARY KEY (run, module) | |
| 224 | -); | |
| 225 | - | |
| 226 | - | |
| 227 | --- --------------------------------------------------------------------------- | |
| 228 | --- 4) zeka_question_segment — one cognitive label set per exam question | |
| 229 | --- | |
| 230 | --- This is a question's LABEL, not its STATISTIC. p-value and discrimination | |
| 231 | --- need raw answers, and the bridge allowlist carries no exam path, so item | |
| 232 | --- analysis still cannot be built. Everything here comes from the question's | |
| 233 | --- own text. | |
| 234 | --- | |
| 235 | --- NOT PERSONAL DATA: a row is about a question and reaches no student. It | |
| 236 | --- still carries a finite `retain_until`, because a label is the output of one | |
| 237 | --- model and one prompt version and goes stale when either moves — and an | |
| 238 | --- infinite retention would need an exception in the sweep. | |
| 239 | --- | |
| 240 | --- The composite FK below is the device `exam_answer` uses: naming both the | |
| 241 | --- exam and the question means the two can never disagree about the owner. | |
| 242 | --- --------------------------------------------------------------------------- | |
| 243 | -CREATE TABLE zeka_question_segment ( | |
| 244 | - question uuid NOT NULL, | |
| 245 | - exam uuid NOT NULL, | |
| 246 | - -- Denormalized from `subject.course` so the teacher's | |
| 247 | - -- course x cognitive-demand screen needs no join. ZEKA resolves it at | |
| 248 | - -- write time; nothing else may set it. | |
| 249 | - course uuid NOT NULL REFERENCES course(id) ON DELETE NO ACTION, | |
| 250 | - subject uuid NOT NULL REFERENCES subject(id) ON DELETE NO ACTION, | |
| 251 | - | |
| 252 | - -- --- The dimensions. Label sets match src/segment/rubric.py exactly. --- | |
| 253 | - bilissel_talep TEXT NOT NULL | |
| 254 | - CHECK (bilissel_talep IN ('hatirlama', 'uygulama', 'analiz')), | |
| 255 | - dikkat_tuzagi TEXT NOT NULL | |
| 256 | - CHECK (dikkat_tuzagi IN ('var', 'yok')), | |
| 257 | - okuma_yuku TEXT NOT NULL | |
| 258 | - CHECK (okuma_yuku IN ('dusuk', 'yuksek')), | |
| 259 | - -- EXPERIMENTAL. Measured 0.607 stability on a hand-written probe; it | |
| 260 | - -- scores far higher on our own seed only because the generator writes | |
| 261 | - -- multi-step-ness into the text, which makes that an exam we set | |
| 262 | - -- ourselves. Labelled and stored, never read downstream. | |
| 263 | - adim_sayisi TEXT NOT NULL | |
| 264 | - CHECK (adim_sayisi IN ('tek_adim', 'cok_adim')), | |
| 265 | - | |
| 266 | - -- Per-dimension model confidence in [0,1]. One total is not enough: a | |
| 267 | - -- question's reading load can be obvious while its cognitive demand is | |
| 268 | - -- genuinely ambiguous. | |
| 269 | - confidence_bilissel_talep DOUBLE PRECISION NOT NULL | |
| 270 | - CHECK (confidence_bilissel_talep BETWEEN 0 AND 1), | |
| 271 | - confidence_dikkat_tuzagi DOUBLE PRECISION NOT NULL | |
| 272 | - CHECK (confidence_dikkat_tuzagi BETWEEN 0 AND 1), | |
| 273 | - confidence_okuma_yuku DOUBLE PRECISION NOT NULL | |
| 274 | - CHECK (confidence_okuma_yuku BETWEEN 0 AND 1), | |
| 275 | - confidence_adim_sayisi DOUBLE PRECISION NOT NULL | |
| 276 | - CHECK (confidence_adim_sayisi BETWEEN 0 AND 1), | |
| 277 | - -- Row-level tier, same vocabulary as every other table here. Derived from | |
| 278 | - -- the LOWEST confidence among the PRODUCTION dimensions; the experimental | |
| 279 | - -- one does not enter it. | |
| 280 | - confidence TEXT NOT NULL | |
| 281 | - CHECK (confidence IN ('none', 'exploratory', 'stable')), | |
| 282 | - | |
| 283 | - -- The distractor the trap points at (an id from `exam_question.choices`), | |
| 284 | - -- when `dikkat_tuzagi = 'var'`. No FK: choices live inside a JSONB column. | |
| 285 | - trap_choice TEXT NULL, | |
| 286 | - -- The model's own reasoning, two sentences at most. NOT SHOWN TO THE | |
| 287 | - -- STUDENT — see docs/CIKTI-SOZLESMESI.md. | |
| 288 | - rationale TEXT NOT NULL, | |
| 289 | - | |
| 290 | - -- Provenance. A silent model or prompt change is forbidden: when either | |
| 291 | - -- moves, the row moves with it. | |
| 292 | - model TEXT NOT NULL, | |
| 293 | - prompt_version TEXT NOT NULL, | |
| 294 | - variant TEXT NULL, | |
| 295 | - | |
| 296 | - computed_at BIGINT NOT NULL, | |
| 297 | - retain_until BIGINT NOT NULL, | |
| 298 | - | |
| 299 | - CONSTRAINT zeka_question_segment_question PRIMARY KEY (question), | |
| 300 | - CONSTRAINT zeka_question_segment_exam_question_fkey FOREIGN KEY (exam, question) | |
| 301 | - REFERENCES exam_question (exam, id) ON DELETE NO ACTION | |
| 302 | -); | |
| 303 | - | |
| 304 | -CREATE INDEX zeka_question_segment_exam ON zeka_question_segment (exam); | |
| 305 | -CREATE INDEX zeka_question_segment_subject ON zeka_question_segment (subject); | |
| 306 | -CREATE INDEX zeka_question_segment_talep | |
| 307 | - ON zeka_question_segment (course, bilissel_talep); | |
| 308 | -CREATE INDEX zeka_question_segment_retain ON zeka_question_segment (retain_until); | |
| 309 | - | |
| 310 | --- Which dimensions downstream actually uses, and which are experimental (was | |
| 311 | --- two embedded arrays). Kept per row on purpose: when `rubric.py` demotes a | |
| 312 | --- dimension, that a downstream product no longer reads it is legible from the | |
| 313 | --- row itself, with no document to consult. | |
| 314 | -CREATE TABLE zeka_question_segment_dimension ( | |
| 315 | - question uuid NOT NULL | |
| 316 | - REFERENCES zeka_question_segment(question) ON DELETE NO ACTION, | |
| 317 | - dimension TEXT NOT NULL | |
| 318 | - CHECK (dimension IN ('bilissel_talep', 'dikkat_tuzagi', | |
| 319 | - 'okuma_yuku', 'adim_sayisi')), | |
| 320 | - role TEXT NOT NULL CHECK (role IN ('downstream', 'experimental')), | |
| 321 | - ord SMALLINT NOT NULL, | |
| 322 | - CONSTRAINT zeka_question_segment_dimension_question_dimension | |
| 323 | - PRIMARY KEY (question, dimension) | |
| 324 | -); | |
| 325 | - | |
| 326 | - | |
| 327 | --- --------------------------------------------------------------------------- | |
| 328 | --- 5) zeka_student_segment_profile — student x dimension x label | |
| 329 | --- | |
| 330 | --- `contrast` IS WHY THIS TABLE EXISTS. | |
| 331 | --- | |
| 332 | --- Raw `accuracy` is not a discriminating measure: a student's hit rate inside | |
| 333 | --- any segment mostly reflects their GENERAL ability. A strong student scores | |
| 334 | --- high in every segment and a weak one low in every segment, so "this student | |
| 335 | --- struggles with analysis questions" DOES NOT FOLLOW from it. | |
| 336 | --- contrast = accuracy - overall_accuracy | |
| 337 | --- The general level cancels in that difference and what remains is the part | |
| 338 | --- specific to the segment. Recommendation rules fire on `contrast` ONLY, | |
| 339 | --- never on `accuracy`. | |
| 340 | --- | |
| 341 | --- PERSONAL DATA: derived student profile — "term + 1 year", and deleted on | |
| 342 | --- graduation (`Store.purge_departed`). | |
| 343 | --- --------------------------------------------------------------------------- | |
| 344 | -CREATE TABLE zeka_student_segment_profile ( | |
| 345 | - student uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION, | |
| 346 | - -- PRODUCTION dimensions only. The experimental one is labelled in | |
| 347 | - -- `zeka_question_segment` and stays there; it never reaches a student. | |
| 348 | - dimension TEXT NOT NULL | |
| 349 | - CHECK (dimension IN ('bilissel_talep', 'dikkat_tuzagi', 'okuma_yuku')), | |
| 350 | - label TEXT NOT NULL, | |
| 351 | - | |
| 352 | - n_answers BIGINT NOT NULL, | |
| 353 | - n_correct BIGINT NOT NULL, | |
| 354 | - -- The segment hit rate. NOT SHOWN ALONE and NEVER FIRES A RULE ALONE: it | |
| 355 | - -- carries general ability and has no discriminating power. | |
| 356 | - accuracy DOUBLE PRECISION NOT NULL CHECK (accuracy BETWEEN 0 AND 1), | |
| 357 | - | |
| 358 | - -- The student's hit rate across ALL labelled items — the subtrahend. | |
| 359 | - -- Stored on the row so the evidence panel can show the comparison. | |
| 360 | - overall_n_answers BIGINT NOT NULL, | |
| 361 | - overall_accuracy DOUBLE PRECISION NOT NULL | |
| 362 | - CHECK (overall_accuracy BETWEEN 0 AND 1), | |
| 363 | - -- The honest measure. Negative = behind their OWN general level here. | |
| 364 | - contrast DOUBLE PRECISION NOT NULL CHECK (contrast BETWEEN -1 AND 1), | |
| 365 | - | |
| 366 | - confidence TEXT NOT NULL | |
| 367 | - CHECK (confidence IN ('none', 'exploratory', 'stable')), | |
| 368 | - | |
| 369 | - computed_at BIGINT NOT NULL, | |
| 370 | - retain_until BIGINT NOT NULL, | |
| 371 | - | |
| 372 | - CONSTRAINT zeka_student_segment_profile_key | |
| 373 | - PRIMARY KEY (student, dimension, label), | |
| 374 | - -- n_correct can never exceed n_answers; a row that says otherwise is a | |
| 375 | - -- counting bug, and the cheapest place to catch it is here. | |
| 376 | - CONSTRAINT zeka_student_segment_profile_counts | |
| 377 | - CHECK (n_correct <= n_answers AND n_answers <= overall_n_answers) | |
| 378 | -); | |
| 379 | - | |
| 380 | -CREATE INDEX zeka_student_segment_profile_dimension | |
| 381 | - ON zeka_student_segment_profile (dimension, label); | |
| 382 | -CREATE INDEX zeka_student_segment_profile_retain | |
| 383 | - ON zeka_student_segment_profile (retain_until); |
service/schema/zeka.surqldeleted+0 -306
| @@ -1,306 +0,0 @@ | ||
| 1 | --- ============================================================================ | |
| 2 | --- ZEKA'nin KENDI veritabani semasi. | |
| 3 | --- | |
| 4 | --- KAPSAM KURALI: bu dosyadaki hicbir tablo okul veritabaninda YASAMAZ. | |
| 5 | --- ZEKA okul veritabanina **asla yazmaz**; okul verisini yalnizca `Source` | |
| 6 | --- arayuzu uzerinden OKUR. Bu dosya ZEKA'nin kendi SurrealDB veritabaninda | |
| 7 | --- (ns/db: zeka) kosulur. | |
| 8 | --- | |
| 9 | --- Kaynak: spec/MODULLER.md §4 (DDL kurallari ve alan listeleri). | |
| 10 | --- MODULLER.md §4.1 `question_stat` ve §4.2 `student_subject_stat` tablolari | |
| 11 | --- BU SURUMDE YOKTUR: ikisi de ham sinav cevabi / madde verisi gerektirir ve | |
| 12 | --- kopru izin listesinde sinav yolu bulunmuyor (bkz. service/src/compute/README.md). | |
| 13 | --- Yerlerine not duzeyinde calisan tek bir `student_summary` tablosu gecti. | |
| 14 | --- | |
| 15 | --- BU SURUMDE EKLENEN IKI TABLO (§4, §5): `question_segment` ve | |
| 16 | --- `student_segment_profile`. Ikisi de `service/src/segment/` hattinin | |
| 17 | --- ciktisidir ve kopru izin listesine DEGIL, tohum verisine / soru metnine | |
| 18 | --- dayanir. Madde ISTATISTIGI (p-degeri, ayirt edicilik) yine YOKTUR; bu iki | |
| 19 | --- tablo madde ETIKETI ve ogrencinin o etiket altindaki KONTRASTINI tasir. | |
| 20 | --- | |
| 21 | --- DDL kurallari (MODULLER.md §4, migration_sql.rs deneyimi): | |
| 22 | --- * Her ifade `DEFINE ... IF NOT EXISTS`. | |
| 23 | --- * Tablolar SCHEMAFULL; nested key'ler ayrica tanimlanir. | |
| 24 | --- * `DEFAULT []` KULLANILMAZ — PATCH'leri kirdigi deneyimle sabit. | |
| 25 | --- Diziler `option<array<...>>` olarak tanimlanir. | |
| 26 | --- * Zaman: i64 unix MILLISECONDS, UTC. `TYPE int`, asla `datetime`. | |
| 27 | --- * Okul kimligi bir `record` degil, duz `string` slug'dir: ZEKA'nin | |
| 28 | --- veritabaninda okul tablolari yoktur, baglanti kurulamaz. | |
| 29 | --- ============================================================================ | |
| 30 | - | |
| 31 | - | |
| 32 | --- --------------------------------------------------------------------------- | |
| 33 | --- 1) student_summary — ogrenci basina gecelik ozet | |
| 34 | --- | |
| 35 | --- Kayit anahtari (kompozit, uygulama tarafinda uretilir): `{school}_{user_id}` | |
| 36 | --- -> tekillik yapisaldir, UNIQUE indekse gerek yok, UPSERT idempotenttir. | |
| 37 | --- --------------------------------------------------------------------------- | |
| 38 | --- SURUM NOTU (SurrealDB 3): `FLEXIBLE` anahtar sozcugu `TYPE`'dan SONRA gelir. | |
| 39 | --- `... FLEXIBLE TYPE object` yazimi ayristirma hatasi verir ve ifade SESSIZCE | |
| 40 | --- yuklenmez; SCHEMAFULL tabloda tanimsiz alan da sessizce DUSER. Yani yanlis | |
| 41 | --- siralama, "sema yuklendi ama marks/evidence alanlari kayboldu" demekti. | |
| 42 | - | |
| 43 | -DEFINE TABLE IF NOT EXISTS student_summary SCHEMAFULL; | |
| 44 | - | |
| 45 | -DEFINE FIELD IF NOT EXISTS school ON student_summary TYPE string; | |
| 46 | -DEFINE FIELD IF NOT EXISTS student ON student_summary TYPE string; | |
| 47 | - | |
| 48 | --- Hesap modullerinin cikti objeleri. FLEXIBLE: sekil hesaplayana aittir, | |
| 49 | --- sema her kural surumunde degismek zorunda kalmaz. | |
| 50 | -DEFINE FIELD IF NOT EXISTS marks ON student_summary TYPE option<object> FLEXIBLE; | |
| 51 | -DEFINE FIELD IF NOT EXISTS attendance ON student_summary TYPE option<object> FLEXIBLE; | |
| 52 | -DEFINE FIELD IF NOT EXISTS submission ON student_summary TYPE option<object> FLEXIBLE; | |
| 53 | -DEFINE FIELD IF NOT EXISTS study ON student_summary TYPE option<object> FLEXIBLE; | |
| 54 | - | |
| 55 | --- Dikkat listesi maddeleri: her oge TEK bir tetikleyici tasir. | |
| 56 | --- Tek bir "risk skoru" alani KASITLI OLARAK YOKTUR (MODULLER.md §2.8, | |
| 57 | --- 20_tavsiye_sistemi_tasarim.md §6.6 madde 1-2). Skor alani olmadigi icin | |
| 58 | --- siralama da semadan uretilemez. | |
| 59 | --- SIRA ONEMLI: `attention.*` once tanimlanir. `TYPE option<array<object>>` | |
| 60 | --- ifadesi, `.*` alt tanimini KENDILIGINDEN (FLEXIBLE olmadan) uretir; sonra | |
| 61 | --- gelen `IF NOT EXISTS` onu atlar ve dikkat maddelerinin ic anahtarlari | |
| 62 | --- (`evidence` nesnesi dahil) SESSIZCE DUSER. Once `.*` tanimlanirsa dizi | |
| 63 | --- tanimi var olani ezmez. | |
| 64 | -DEFINE FIELD IF NOT EXISTS attention.* ON student_summary TYPE object FLEXIBLE; | |
| 65 | -DEFINE FIELD IF NOT EXISTS attention ON student_summary TYPE option<array<object>>; | |
| 66 | - | |
| 67 | --- Guven kademesi, girdilerden devralinir: 'none' | 'exploratory' | 'stable' | |
| 68 | --- (MODULLER.md §0 kural 3, [L-5] Linacre 1994 esikleri). | |
| 69 | -DEFINE FIELD IF NOT EXISTS confidence ON student_summary TYPE string; | |
| 70 | - | |
| 71 | -DEFINE FIELD IF NOT EXISTS computed_at ON student_summary TYPE int; | |
| 72 | --- Saklama suresi: bu damgadan sonra supurulur. | |
| 73 | --- MODULLER.md §2.11 adim 2 / [T§6.7]: turetilmis ogrenci profili "donem + 1 yil". | |
| 74 | -DEFINE FIELD IF NOT EXISTS retain_until ON student_summary TYPE int; | |
| 75 | - | |
| 76 | -DEFINE INDEX IF NOT EXISTS student_summary_school ON student_summary FIELDS school; | |
| 77 | -DEFINE INDEX IF NOT EXISTS student_summary_student ON student_summary FIELDS school, student; | |
| 78 | -DEFINE INDEX IF NOT EXISTS student_summary_retain ON student_summary FIELDS retain_until; | |
| 79 | - | |
| 80 | - | |
| 81 | --- --------------------------------------------------------------------------- | |
| 82 | --- 2) recommendation — uretilmis tavsiyeler | |
| 83 | --- | |
| 84 | --- Her satir bir NEDEN tasir. Aciklanamayan tavsiye gosterilmez ([T§6.3]). | |
| 85 | --- `evidence` BOS OLAMAZ: store katmani bos kanitli satiri REDDEDER | |
| 86 | --- (MODULLER.md §2.10 yapisal kural 1). | |
| 87 | --- | |
| 88 | --- Kayit anahtari: `{school}_{audience}_{product}_{rule_id}[_{scope}]` | |
| 89 | --- -> ayni kural ayni kisi icin cogaltilmaz, UPSERT idempotenttir. | |
| 90 | --- --------------------------------------------------------------------------- | |
| 91 | -DEFINE TABLE IF NOT EXISTS recommendation SCHEMAFULL; | |
| 92 | - | |
| 93 | -DEFINE FIELD IF NOT EXISTS school ON recommendation TYPE string; | |
| 94 | --- Kime gosterilecek. | |
| 95 | -DEFINE FIELD IF NOT EXISTS audience ON recommendation TYPE string; | |
| 96 | --- Kim hakkinda. Ogrenci kendi kartinda NONE. | |
| 97 | -DEFINE FIELD IF NOT EXISTS about ON recommendation TYPE option<string>; | |
| 98 | --- Kime gosterilebilir rol kapisi: 'student' | 'teacher' | 'parent' | 'manager' | |
| 99 | --- T4 maddeleri yalnizca 'teacher' tasir — ogrenciye/veliye gosterilmez ([T§6.8]). | |
| 100 | -DEFINE FIELD IF NOT EXISTS audience_role ON recommendation TYPE string; | |
| 101 | - | |
| 102 | --- Urun kodu: 'O1'|'O2'|'O3'|'O4'|'T3'|'T4' (bu surumde uretilebilenler). | |
| 103 | --- 'O2' yalnizca segment tabanli kurallardir (`O2.segment_*`); madde bazli | |
| 104 | --- tekrar listesi (`O2.retry_item`) hala uretilemiyor. 'V1' (veli ozeti) | |
| 105 | --- uretilemiyor: `parent_link` yok (bkz. recommend.unavailable_rules()). | |
| 106 | -DEFINE FIELD IF NOT EXISTS product ON recommendation TYPE string; | |
| 107 | -DEFINE FIELD IF NOT EXISTS course ON recommendation TYPE option<string>; | |
| 108 | - | |
| 109 | --- Hangi kuralin hangi surumu bunu uretti ([T§6.4] madde 3). | |
| 110 | -DEFINE FIELD IF NOT EXISTS rule_id ON recommendation TYPE string; | |
| 111 | -DEFINE FIELD IF NOT EXISTS rule_version ON recommendation TYPE int; | |
| 112 | - | |
| 113 | --- Kanit: hangi sayilar, hangi pencere. "Neden?" ekranini besler. | |
| 114 | -DEFINE FIELD IF NOT EXISTS evidence ON recommendation TYPE object FLEXIBLE; | |
| 115 | - | |
| 116 | -DEFINE FIELD IF NOT EXISTS confidence ON recommendation TYPE string; | |
| 117 | -DEFINE FIELD IF NOT EXISTS created_at ON recommendation TYPE int; | |
| 118 | -DEFINE FIELD IF NOT EXISTS expires_at ON recommendation TYPE int; | |
| 119 | --- `expires_at` veya 90 gun — hangisi once ([T§6.7]). Supurme bunu okur. | |
| 120 | -DEFINE FIELD IF NOT EXISTS retain_until ON recommendation TYPE int; | |
| 121 | - | |
| 122 | --- Insan mudahalesi izi (KVKK m.11): itiraz / kapatma / faydali-degil. | |
| 123 | -DEFINE FIELD IF NOT EXISTS dismissed_at ON recommendation TYPE option<int>; | |
| 124 | -DEFINE FIELD IF NOT EXISTS dismissed_by ON recommendation TYPE option<string>; | |
| 125 | -DEFINE FIELD IF NOT EXISTS dismiss_reason ON recommendation TYPE option<string>; | |
| 126 | - | |
| 127 | -DEFINE INDEX IF NOT EXISTS recommendation_audience ON recommendation FIELDS school, audience, created_at; | |
| 128 | -DEFINE INDEX IF NOT EXISTS recommendation_about ON recommendation FIELDS school, about, product; | |
| 129 | -DEFINE INDEX IF NOT EXISTS recommendation_retain ON recommendation FIELDS retain_until; | |
| 130 | --- Kural kalibrasyon olcumu: bir kural surekli "bu dogru degil" ile kapaniyorsa | |
| 131 | --- kural yanlistir ([T§6.4] madde 2). | |
| 132 | -DEFINE INDEX IF NOT EXISTS recommendation_rule ON recommendation FIELDS rule_id, created_at; | |
| 133 | - | |
| 134 | - | |
| 135 | --- --------------------------------------------------------------------------- | |
| 136 | --- 3) insight_run — kosu defteri | |
| 137 | --- | |
| 138 | --- Kismi basarisizlik ve butce muhasebesi buna dayanir (MODULLER.md §3.4). | |
| 139 | --- Kayit anahtari: `{school}_{YYYY-MM-DD}` (TR tarihi, 10 karakter sabit). | |
| 140 | --- --------------------------------------------------------------------------- | |
| 141 | -DEFINE TABLE IF NOT EXISTS insight_run SCHEMAFULL; | |
| 142 | - | |
| 143 | -DEFINE FIELD IF NOT EXISTS school ON insight_run TYPE string; | |
| 144 | -DEFINE FIELD IF NOT EXISTS started_at ON insight_run TYPE int; | |
| 145 | -DEFINE FIELD IF NOT EXISTS finished_at ON insight_run TYPE option<int>; | |
| 146 | --- 'running' | 'ok' | 'partial' | 'failed' | 'skipped' | |
| 147 | -DEFINE FIELD IF NOT EXISTS status ON insight_run TYPE string; | |
| 148 | -DEFINE FIELD IF NOT EXISTS duration_ms ON insight_run TYPE option<int>; | |
| 149 | - | |
| 150 | -DEFINE FIELD IF NOT EXISTS students_total ON insight_run TYPE int; | |
| 151 | -DEFINE FIELD IF NOT EXISTS students_ok ON insight_run TYPE int; | |
| 152 | -DEFINE FIELD IF NOT EXISTS students_failed ON insight_run TYPE int; | |
| 153 | -DEFINE FIELD IF NOT EXISTS students_skipped ON insight_run TYPE int; | |
| 154 | -DEFINE FIELD IF NOT EXISTS rows_written ON insight_run TYPE int; | |
| 155 | - | |
| 156 | --- Butce asildiysa: islenmemis ogrenciler. Bir sonraki kosu buradan devam eder. | |
| 157 | -DEFINE FIELD IF NOT EXISTS pending_students ON insight_run TYPE option<array<string>>; | |
| 158 | -DEFINE FIELD IF NOT EXISTS pending_students.* ON insight_run TYPE string; | |
| 159 | --- Hata veren modul adlari; kismi liste UI'da "eksik" isaretlenir (MODULLER.md §2.8). | |
| 160 | -DEFINE FIELD IF NOT EXISTS failed_modules ON insight_run TYPE option<array<string>>; | |
| 161 | -DEFINE FIELD IF NOT EXISTS failed_modules.* ON insight_run TYPE string; | |
| 162 | -DEFINE FIELD IF NOT EXISTS budget_exceeded ON insight_run TYPE bool; | |
| 163 | -DEFINE FIELD IF NOT EXISTS budget_ms ON insight_run TYPE int; | |
| 164 | - | |
| 165 | -DEFINE FIELD IF NOT EXISTS retain_until ON insight_run TYPE int; -- 90 gun ([T§6.7]) | |
| 166 | - | |
| 167 | -DEFINE INDEX IF NOT EXISTS insight_run_started ON insight_run FIELDS school, started_at; | |
| 168 | -DEFINE INDEX IF NOT EXISTS insight_run_retain ON insight_run FIELDS retain_until; | |
| 169 | - | |
| 170 | - | |
| 171 | --- --------------------------------------------------------------------------- | |
| 172 | --- 4) question_segment — soru basina bilissel segment etiketi | |
| 173 | --- | |
| 174 | --- Kaynak: `service/src/segment/` hatti (LLM tabanli etiketleme). Bu tablo | |
| 175 | --- MODULLER.md §4.1 `question_stat`in YERINE GECMEZ: o tablo madde | |
| 176 | --- ISTATISTIGIdir (p-degeri, ayirt edicilik) ve ham sinav cevabi ister; bu | |
| 177 | --- tablo madde ETIKETIdir ve yalnizca soru METNINDEN uretilir. | |
| 178 | --- | |
| 179 | --- Kayit anahtari (kompozit): `{school}_{question}` -> tekillik yapisal, | |
| 180 | --- UPSERT idempotent, UNIQUE indekse gerek yok. | |
| 181 | --- | |
| 182 | --- KISISEL VERI DEGILDIR: satir bir soru hakkindadir, hicbir ogrenciye | |
| 183 | --- baglanamaz ([T§6.7] "sinirsiz" satiri). Yine de SONLU bir `retain_until` | |
| 184 | --- tasir: etiket bir MODEL ve bir ISTEM SURUMUNUN ciktisidir, surum degisince | |
| 185 | --- bayatlar. Sonsuz saklama, supurme dongusunde bir istisna da yaratirdi. | |
| 186 | --- --------------------------------------------------------------------------- | |
| 187 | -DEFINE TABLE IF NOT EXISTS question_segment SCHEMAFULL; | |
| 188 | - | |
| 189 | -DEFINE FIELD IF NOT EXISTS school ON question_segment TYPE string; | |
| 190 | --- Kimlikler ZEKA veritabaninda `record` OLAMAZ: okul tablolari burada yoktur, | |
| 191 | --- baglanti kurulamaz (bkz. bu dosyanin bas aciklamasi). Duz metin kimlik. | |
| 192 | -DEFINE FIELD IF NOT EXISTS question ON question_segment TYPE string; | |
| 193 | -DEFINE FIELD IF NOT EXISTS exam ON question_segment TYPE option<string>; | |
| 194 | -DEFINE FIELD IF NOT EXISTS course ON question_segment TYPE option<string>; | |
| 195 | -DEFINE FIELD IF NOT EXISTS subject ON question_segment TYPE option<string>; | |
| 196 | - | |
| 197 | --- --- Boyutlar. Etiket kumeleri `src/segment/rubric.py` ile birebir. -------- | |
| 198 | --- 'hatirlama' | 'uygulama' | 'analiz' | |
| 199 | -DEFINE FIELD IF NOT EXISTS bilissel_talep ON question_segment TYPE string; | |
| 200 | --- 'var' | 'yok' | |
| 201 | -DEFINE FIELD IF NOT EXISTS dikkat_tuzagi ON question_segment TYPE string; | |
| 202 | --- 'yuksek' | 'dusuk' | |
| 203 | -DEFINE FIELD IF NOT EXISTS okuma_yuku ON question_segment TYPE string; | |
| 204 | --- 'tek_adim' | 'cok_adim' — DENEYSEL boyut (asagiya bakiniz). | |
| 205 | -DEFINE FIELD IF NOT EXISTS adim_sayisi ON question_segment TYPE string; | |
| 206 | - | |
| 207 | --- Boyut basina model guveni [0,1]. Tek bir toplam guven sayisi YETMEZ: | |
| 208 | --- bir sorunun okuma yuku kesin, bilissel talebi belirsiz olabilir. | |
| 209 | -DEFINE FIELD IF NOT EXISTS confidence_bilissel_talep ON question_segment TYPE float; | |
| 210 | -DEFINE FIELD IF NOT EXISTS confidence_dikkat_tuzagi ON question_segment TYPE float; | |
| 211 | -DEFINE FIELD IF NOT EXISTS confidence_okuma_yuku ON question_segment TYPE float; | |
| 212 | -DEFINE FIELD IF NOT EXISTS confidence_adim_sayisi ON question_segment TYPE float; | |
| 213 | --- Satir duzeyi guven kademesi (diger tablolarla ayni sozluk): | |
| 214 | --- 'none' | 'exploratory' | 'stable'. URETIM boyutlarinin EN DUSUK guveninden | |
| 215 | --- turetilir; deneysel boyut bu kademeye GIRMEZ. | |
| 216 | -DEFINE FIELD IF NOT EXISTS confidence ON question_segment TYPE string; | |
| 217 | - | |
| 218 | --- DENEYSEL / URETIM ayrimi SEMADA gorunur olsun diye iki ayri liste tutulur. | |
| 219 | --- `rubric.py` bir boyutu deneysele indirdiginde (alpha kapisinin altinda | |
| 220 | --- kalmasi gibi) bu listeler degisir ve asagi akisin o boyutu KULLANMADIGI | |
| 221 | --- dogrudan satirdan okunur — belgeye bakmaya gerek kalmaz. | |
| 222 | --- SIRA ONEMLI: once `.*`, sonra dizi (bkz. `attention` aciklamasi). | |
| 223 | -DEFINE FIELD IF NOT EXISTS experimental_dimensions.* ON question_segment TYPE string; | |
| 224 | -DEFINE FIELD IF NOT EXISTS experimental_dimensions ON question_segment TYPE option<array<string>>; | |
| 225 | -DEFINE FIELD IF NOT EXISTS downstream_dimensions.* ON question_segment TYPE string; | |
| 226 | -DEFINE FIELD IF NOT EXISTS downstream_dimensions ON question_segment TYPE option<array<string>>; | |
| 227 | - | |
| 228 | --- `dikkat_tuzagi = 'var'` ise isaret edilen sikkin kimligi; aksi halde alan | |
| 229 | --- HIC YAZILMAZ (`option<>` NULL kabul etmez). | |
| 230 | -DEFINE FIELD IF NOT EXISTS trap_choice ON question_segment TYPE option<string>; | |
| 231 | --- Modelin kendi gerekcesi, en fazla iki cumle. OGRENCIYE GOSTERILMEZ | |
| 232 | --- (bkz. `docs/CIKTI-SOZLESMESI.md` §5 dikkat listesi). | |
| 233 | -DEFINE FIELD IF NOT EXISTS rationale ON question_segment TYPE string; | |
| 234 | - | |
| 235 | --- Uretim kunyesi: hangi model, hangi istem surumu, hangi varyant. | |
| 236 | --- Sessiz degisiklik yasak ([T§6.4] madde 3): surum degisince satir da degisir. | |
| 237 | -DEFINE FIELD IF NOT EXISTS model ON question_segment TYPE string; | |
| 238 | -DEFINE FIELD IF NOT EXISTS prompt_version ON question_segment TYPE string; | |
| 239 | -DEFINE FIELD IF NOT EXISTS variant ON question_segment TYPE option<string>; | |
| 240 | - | |
| 241 | -DEFINE FIELD IF NOT EXISTS computed_at ON question_segment TYPE int; | |
| 242 | -DEFINE FIELD IF NOT EXISTS retain_until ON question_segment TYPE int; | |
| 243 | - | |
| 244 | -DEFINE INDEX IF NOT EXISTS question_segment_question ON question_segment FIELDS school, question; | |
| 245 | -DEFINE INDEX IF NOT EXISTS question_segment_exam ON question_segment FIELDS school, exam; | |
| 246 | -DEFINE INDEX IF NOT EXISTS question_segment_subject ON question_segment FIELDS school, subject; | |
| 247 | --- Ders x bilissel talep dagilimi (ogretmen ekrani) tam tarama yapmasin. | |
| 248 | -DEFINE INDEX IF NOT EXISTS question_segment_talep ON question_segment FIELDS school, course, bilissel_talep; | |
| 249 | -DEFINE INDEX IF NOT EXISTS question_segment_retain ON question_segment FIELDS retain_until; | |
| 250 | - | |
| 251 | - | |
| 252 | --- --------------------------------------------------------------------------- | |
| 253 | --- 5) student_segment_profile — ogrenci x boyut x etiket performansi | |
| 254 | --- | |
| 255 | --- Kayit anahtari (kompozit): `{school}_{student}_{dimension}_{label}` | |
| 256 | --- -> UPSERT idempotent. | |
| 257 | --- | |
| 258 | --- `contrast` ALANI BU TABLONUN VAR OLMA SEBEBIDIR. | |
| 259 | --- Ham `accuracy` bir AYRIM OLCUSU DEGILDIR: bir ogrencinin herhangi bir | |
| 260 | --- segmentteki dogruluk orani buyuk olcude GENEL yetenegini yansitir. Iyi | |
| 261 | --- ogrenci her segmentte yuksek, zayif ogrenci her segmentte dusuk cikar; | |
| 262 | --- boyle bir sayidan "bu ogrenci analiz sorularinda zorlaniyor" sonucu | |
| 263 | --- CIKARILAMAZ. | |
| 264 | --- contrast = accuracy - overall_accuracy | |
| 265 | --- yani ogrencinin bu segmentteki dogrulugu EKSI kendi genel dogrulugu. Genel | |
| 266 | --- duzey bu farkta sadelesir; geriye segmentin kendisine ozgu sapma kalir. | |
| 267 | --- Tavsiye kurallari YALNIZCA `contrast` uzerinden ates eder, `accuracy` | |
| 268 | --- uzerinden ASLA (bkz. `src/compute/recommend.py` SEG.* kurallari). | |
| 269 | --- | |
| 270 | --- Bu tablo KISISEL VERIDIR: turetilmis ogrenci profili, "donem + 1 yil" | |
| 271 | --- ([T§6.7]) ve mezuniyette silinir (`Store.purge_departed`). | |
| 272 | --- --------------------------------------------------------------------------- | |
| 273 | -DEFINE TABLE IF NOT EXISTS student_segment_profile SCHEMAFULL; | |
| 274 | - | |
| 275 | -DEFINE FIELD IF NOT EXISTS school ON student_segment_profile TYPE string; | |
| 276 | -DEFINE FIELD IF NOT EXISTS student ON student_segment_profile TYPE string; | |
| 277 | --- 'bilissel_talep' | 'dikkat_tuzagi' | 'okuma_yuku' (URETIM boyutlari). | |
| 278 | --- Deneysel boyut (`adim_sayisi`) bu tabloya GIRMEZ; `question_segment` icinde | |
| 279 | --- etiketlenir ve orada kalir. | |
| 280 | -DEFINE FIELD IF NOT EXISTS dimension ON student_segment_profile TYPE string; | |
| 281 | -DEFINE FIELD IF NOT EXISTS label ON student_segment_profile TYPE string; | |
| 282 | - | |
| 283 | -DEFINE FIELD IF NOT EXISTS n_answers ON student_segment_profile TYPE int; | |
| 284 | -DEFINE FIELD IF NOT EXISTS n_correct ON student_segment_profile TYPE int; | |
| 285 | --- Bu segmentteki dogruluk orani. TEK BASINA GOSTERILMEZ, TEK BASINA KURAL | |
| 286 | --- ATESLEMEZ: genel yetenegi tasir, ayrim gucu yoktur. | |
| 287 | -DEFINE FIELD IF NOT EXISTS accuracy ON student_segment_profile TYPE float; | |
| 288 | - | |
| 289 | --- Ogrencinin ETIKETLENMIS butun maddelerdeki genel dogrulugu — kontrastin | |
| 290 | --- cikarani. Kanit nesnesinde gosterilebilsin diye satirda tutulur. | |
| 291 | -DEFINE FIELD IF NOT EXISTS overall_n_answers ON student_segment_profile TYPE int; | |
| 292 | -DEFINE FIELD IF NOT EXISTS overall_accuracy ON student_segment_profile TYPE float; | |
| 293 | --- DURUST OLCU: accuracy - overall_accuracy. Negatif = ogrenci kendi genel | |
| 294 | --- seviyesine gore bu segmentte GERIDE. | |
| 295 | -DEFINE FIELD IF NOT EXISTS contrast ON student_segment_profile TYPE float; | |
| 296 | - | |
| 297 | --- 'none' | 'exploratory' | 'stable' — segmentteki cevap sayisindan turetilir | |
| 298 | --- ([L-5] Linacre esikleri; olculmus degerler `docs/SEGMENT-CIKTI.md` §3). | |
| 299 | -DEFINE FIELD IF NOT EXISTS confidence ON student_segment_profile TYPE string; | |
| 300 | - | |
| 301 | -DEFINE FIELD IF NOT EXISTS computed_at ON student_segment_profile TYPE int; | |
| 302 | -DEFINE FIELD IF NOT EXISTS retain_until ON student_segment_profile TYPE int; | |
| 303 | - | |
| 304 | -DEFINE INDEX IF NOT EXISTS ssp_student ON student_segment_profile FIELDS school, student; | |
| 305 | -DEFINE INDEX IF NOT EXISTS ssp_dimension ON student_segment_profile FIELDS school, dimension, label; | |
| 306 | -DEFINE INDEX IF NOT EXISTS ssp_retain ON student_segment_profile FIELDS retain_until; |
service/src/bridge.pymodified+183 -56
| @@ -50,7 +50,6 @@ from .protocol import ( | ||
| 50 | 50 | FrameStream, |
| 51 | 51 | HandshakeRejected, |
| 52 | 52 | ) |
| 53 | -from .tenants import TenantError | |
| 54 | 53 | |
| 55 | 54 | RequestHandler = Callable[[protocol.Request], Any] |
| 56 | 55 | """Backend'den gelen bir `Request`'i karsilayan kanca. |
| @@ -327,6 +326,54 @@ class BridgeProtocol(QuicConnectionProtocol): | ||
| 327 | 326 | ) |
| 328 | 327 | return response |
| 329 | 328 | |
| 329 | + async def call_capability( | |
| 330 | + self, | |
| 331 | + capability: str, | |
| 332 | + school: str, | |
| 333 | + payload: dict[str, Any] | None = None, | |
| 334 | + timeout: float | None = None, | |
| 335 | + ) -> dict[str, Any]: | |
| 336 | + """Backend'in bir operasyonunu cagir (`insight.*`) ve payload'ini don. | |
| 337 | + | |
| 338 | + ZEKA'nin veritabani erisimi YOKTUR; hesapladigi satirlari ve okudugu | |
| 339 | + listeleri bu metot tasir. `store.BridgeStore` bu metodun TEK | |
| 340 | + kullanicisidir; depo onu `BridgeCaller` protokolu uzerinden gorur. | |
| 341 | + | |
| 342 | + `api_get` ile ayni desen: taze istemci baslatimli cift yonlu akis, tek | |
| 343 | + cerceve yaz, gonderim tarafini kapat (`end=True`), tek cerceve oku, | |
| 344 | + akisi dusur. Korelasyonu AKIS yapar; `id` yalniz iz kimligidir. | |
| 345 | + | |
| 346 | + `school` BOS olabilir: deployment olcekli tek operasyon | |
| 347 | + (`insight.schools.list`) okul adlandirmaz. | |
| 348 | + | |
| 349 | + Red (`status: "err"`) `protocol.CapabilityRefused` olarak yukselir -- | |
| 350 | + `status` ONCE okunur, cunku reddi basari saymak sessiz yazma kaybidir. | |
| 351 | + """ | |
| 352 | + budget = self._settings.api_timeout_secs if timeout is None else timeout | |
| 353 | + request = protocol.build_capability_request( | |
| 354 | + protocol.new_trace_id(), capability, school, payload or {} | |
| 355 | + ) | |
| 356 | + sid = self._quic.get_next_available_stream_id() | |
| 357 | + stream = FrameStream() | |
| 358 | + self._streams[sid] = stream | |
| 359 | + answered = False | |
| 360 | + try: | |
| 361 | + self._send_frame(sid, request, end=True) | |
| 362 | + frame = await asyncio.wait_for(stream.read_frame(), timeout=budget) | |
| 363 | + answered = True | |
| 364 | + finally: | |
| 365 | + if answered: | |
| 366 | + self._streams.pop(sid, None) | |
| 367 | + else: | |
| 368 | + self._abandon(sid) | |
| 369 | + response = protocol.parse_capability_response(frame) | |
| 370 | + result = response.raise_for_status(capability) | |
| 371 | + config.log( | |
| 372 | + "debug", | |
| 373 | + f"yetenek {capability} okul={school or '(deployment)'} -> ok", | |
| 374 | + ) | |
| 375 | + return result | |
| 376 | + | |
| 330 | 377 | async def blob_get( |
| 331 | 378 | self, |
| 332 | 379 | school: str, |
| @@ -425,11 +472,12 @@ class BridgeProtocol(QuicConnectionProtocol): | ||
| 425 | 472 | self._handle(request), timeout=request.timeout_secs |
| 426 | 473 | ) |
| 427 | 474 | response = protocol.ok_response(request_id, school, result) |
| 428 | - except (CapabilityError, TenantError) as exc: | |
| 429 | - # Okul cozumlemesi redleri (`unknown_school`, `school_suspended`, | |
| 430 | - # `school_not_migrated`) backend'e AYNEN gider: hepsi beklenen | |
| 431 | - # durumlardir ve ayrimlari backend'in yeniden deneme kararini | |
| 432 | - # etkiler. `internal` yalnizca TANINMAYAN hatalar icin. | |
| 475 | + except (CapabilityError, protocol.ApiRefused) as exc: | |
| 476 | + # Disariya cikan yetenek cagrisinin redleri (`ApiRefused`, | |
| 477 | + # dolayisiyla `CapabilityRefused`) ve isleyicinin kendi redleri | |
| 478 | + # backend'e AYNEN gider: `unavailable`, `timed_out` gibi kodlar | |
| 479 | + # backend'in yeniden deneme kararini etkiler. `internal` yalnizca | |
| 480 | + # TANINMAYAN hatalar icin. | |
| 433 | 481 | response = protocol.err_response(request_id, school, exc.code, str(exc)) |
| 434 | 482 | except asyncio.TimeoutError: |
| 435 | 483 | response = protocol.err_response( |
| @@ -537,6 +585,62 @@ async def run_once( | ||
| 537 | 585 | config.log("info", "baglanti kapandi") |
| 538 | 586 | |
| 539 | 587 | |
| 588 | +async def one_shot( | |
| 589 | + settings: config.Config, work: Callable[[BridgeProtocol], Any] | |
| 590 | +) -> Any: | |
| 591 | + """Baglan, kaydol, `work(proto)` kos, baglantiyi KAPAT, sonucu don. | |
| 592 | + | |
| 593 | + Gelistirme araclari icin (`cli sweep`, `cli schedule`): uretim dongusu | |
| 594 | + `run_forever` bir daha cikmaz, ama bir CLI komutu isini bitirip donmelidir. | |
| 595 | + Bu yardimci tam olarak o farki kapatir ve AYNI istemciyi kullanir -- | |
| 596 | + ikinci bir tasima yazilmaz. | |
| 597 | + | |
| 598 | + Baglantiyi `work` icinde kapatmak yerine burada, `finally` ile kapatmak | |
| 599 | + yanlis olurdu: `work` sirasinda kopru hala canli olmalidir. | |
| 600 | + """ | |
| 601 | + box: dict[str, Any] = {} | |
| 602 | + | |
| 603 | + async def runner(proto: BridgeProtocol) -> None: | |
| 604 | + try: | |
| 605 | + box["result"] = await work(proto) | |
| 606 | + finally: | |
| 607 | + # Kayitli akisi kapatmak backend icin "duser" sinyalidir; komut | |
| 608 | + # bitti, baglanti da bitmeli. | |
| 609 | + proto.close() | |
| 610 | + | |
| 611 | + await run_once(settings, on_ready=runner) | |
| 612 | + return box.get("result") | |
| 613 | + | |
| 614 | + | |
| 615 | +class OneShotCaller: | |
| 616 | + """Her çağrı için taze bir köprü oturumu açan `BridgeCaller`. | |
| 617 | + | |
| 618 | + Geliştirme araçları için (`segment` hattının `--persist` yolu): araç | |
| 619 | + senkron çalışır ve elinde yaşayan bir bağlantı yoktur. Çağrı başına | |
| 620 | + bağlan-kaydol-kapat maliyeti bir araç için önemsizdir; ikinci bir taşıma | |
| 621 | + yazmaktan iyidir — aynı `BridgeProtocol.call_capability` kullanılır. | |
| 622 | + """ | |
| 623 | + | |
| 624 | + def __init__(self, settings: config.Config) -> None: | |
| 625 | + self._settings = settings | |
| 626 | + | |
| 627 | + async def call( | |
| 628 | + self, capability: str, school: str, payload: dict[str, Any] | |
| 629 | + ) -> dict[str, Any]: | |
| 630 | + async def work(proto: BridgeProtocol) -> dict[str, Any]: | |
| 631 | + return await proto.call_capability( | |
| 632 | + capability, | |
| 633 | + school, | |
| 634 | + payload, | |
| 635 | + timeout=self._settings.api_timeout_secs, | |
| 636 | + ) | |
| 637 | + | |
| 638 | + result = await one_shot(self._settings, work) | |
| 639 | + if result is None: # pragma: no cover - one_shot isi bitirmeden donmez | |
| 640 | + raise RuntimeError("köprü oturumu sonuç döndürmedi") | |
| 641 | + return result | |
| 642 | + | |
| 643 | + | |
| 540 | 644 | def next_backoff(current: float, settings: config.Config) -> float: |
| 541 | 645 | """Ustel geri cekilme: ikiye katla ve tavanda dur. |
| 542 | 646 | |
| @@ -607,66 +711,89 @@ async def run_forever( | ||
| 607 | 711 | async def _serve(settings: config.Config) -> int: |
| 608 | 712 | """Kopruyu ve GECE ZAMANLAYICISINI birlikte kosturur. |
| 609 | 713 | |
| 714 | + ----------------------------------------------------------------------- | |
| 715 | + ACILISTA ACILAN HICBIR SEY YOKTUR | |
| 716 | + ----------------------------------------------------------------------- | |
| 717 | + ZEKA'nin veritabani erisimi yoktur (degismez kural: bir AI servisi | |
| 718 | + uygulama veritabanina asla dogrudan erismez). Bu yuzden acilis bir | |
| 719 | + baglanti KURMAZ: ne DSN, ne havuz, ne okul dizini. Okul listesi ilk tikte | |
| 720 | + backend'den istenir (`insight.schools.list`). | |
| 721 | + | |
| 722 | + BACKEND YOKKEN DAVRANIS (uygulanan politika): | |
| 723 | + * Acilis DUSER DEGIL. `run_forever` hicbir hatada cikmaz; ustel geri | |
| 724 | + cekilmeyle yeniden dener (`bridge.run_forever`). | |
| 725 | + * Zamanlayici turu okulsuz kosar: okul listesi okunamazsa `warn` | |
| 726 | + loglanir ve tur bos doner (`scheduler._listing`). Crash-loop yok. | |
| 727 | + * SESSIZ YAZMA YOK. Kopru kapaliyken bir yazma cagrisi | |
| 728 | + `BridgeUnavailable` -> `CapabilityRefused("unavailable")` olur; grup | |
| 729 | + `MAX_ATTEMPTS` kez denenir, sonra atlanir ve `WriteReport.status` | |
| 730 | + `partial` olur -> kosu defterine `store` diye yazilir. "Basarili | |
| 731 | + gorunen ama hicbir sey yazmamis" bir kosu uretilemez. | |
| 732 | + | |
| 610 | 733 | ----------------------------------------------------------------------- |
| 611 | 734 | NEDEN IKISI BIRDEN |
| 612 | 735 | ----------------------------------------------------------------------- |
| 613 | 736 | Kopru tek basina yalnizca BAGLANTIYI ayakta tutar ve backend'den gelen |
| 614 | - `Request` cerceverini karsilar. Ama backend bugun yalnizca `chat.reply` | |
| 615 | - ve `rag.index` yeteneklerine is yolluyor (`ai/mod.rs:23-24`); ZEKA'nin | |
| 616 | - bildirdigi `insight.*` yeteneklerine HIC istek gelmiyor. | |
| 617 | - | |
| 618 | - Zamanlayici bagli olmasaydi servis baglanir, kaydolur, "calisiyor" | |
| 619 | - gorunur ve HICBIR SEY URETMEZDI -- `zeka_*` tablolari bos kalirdi. | |
| 620 | - Baglantinin kurulmus olmasi, isin yapildigi anlamina gelmiyor. | |
| 737 | + `Request` cercevesini karsilar. Ama backend bugun ZEKA'ya yalnizca | |
| 738 | + `insight.student` / `insight.refresh` isleri yolluyor; zamanlayici | |
| 739 | + bagli olmasaydi servis baglanir, kaydolur, "calisiyor" gorunur ve HICBIR | |
| 740 | + SEY URETMEZDI -- `zeka_*` tablolari bos kalirdi. | |
| 621 | 741 | |
| 622 | 742 | Ikisi ayri gorevde kosar: koprunun yeniden baglanmasi zamanlayiciyi |
| 623 | 743 | durdurmaz, zamanlayicinin bir okulda dusmesi baglantiyi koparmaz. |
| 624 | - Zamanlayici kendi okumalarini yine KOPRUDEN yapar (`BridgeSource` -> | |
| 625 | - `ApiRequest`); REST'e cikan bir yol yoktur. | |
| 744 | + Okumalar da yazmalar da KOPRUDEN gider (`BridgeSource` -> `ApiRequest`, | |
| 745 | + depo -> `CapabilityRequest`); REST'e ya da bir veritabanina cikan yol | |
| 746 | + YOKTUR. | |
| 626 | 747 | """ |
| 627 | 748 | from .scheduler import Scheduler |
| 628 | 749 | from .source import BridgeSource |
| 629 | - from .store_factory import describe | |
| 630 | - from .tenants import open_directory | |
| 631 | - | |
| 632 | - # Okul dizini ACILISTA kurulur ve isleyicilere baglanir; okul LISTESI | |
| 633 | - # acilista okunmaz (kontrol veritabaninda hic okul olmayabilir) ve okul | |
| 634 | - # VERITABANLARINA acilista baglanilmaz (biri eksikse bu bir istek | |
| 635 | - # hatasidir, acilis hatasi degil -- `tenants.py`). | |
| 636 | - directory = await open_directory(settings) | |
| 637 | - capabilities.bind_directory(directory) | |
| 638 | - try: | |
| 639 | - config.log("info", describe()) | |
| 640 | - config.log("info", directory.describe()) | |
| 641 | - if settings.refresh_interval_secs <= 0: | |
| 642 | - config.log("info", "gece zamanlayicisi KAPALI (ZEKA_REFRESH_INTERVAL_SECS=0)") | |
| 643 | - return await run_forever(settings) | |
| 644 | - kopru: dict[str, Any] = {"protocol": None} | |
| 645 | - | |
| 646 | - def hazir(proto: BridgeProtocol) -> None: | |
| 647 | - kopru["protocol"] = proto | |
| 648 | - | |
| 649 | - # Zamanlayici her okul icin bir `Source` ister. Baglanti kopmussa | |
| 650 | - # `BridgeSource` cagrisi hata verir ve zamanlayici o okulu duser -- | |
| 651 | - # dogru davranis: veri cekilemeden hesap yapilmaz. | |
| 652 | - def source_for(_school: str) -> Any: | |
| 653 | - proto = kopru["protocol"] | |
| 654 | - if proto is None: | |
| 655 | - raise RuntimeError("kopru henuz bagli degil") | |
| 656 | - return BridgeSource(proto) | |
| 657 | - | |
| 658 | - scheduler = Scheduler( | |
| 659 | - source_for, | |
| 660 | - directory, | |
| 661 | - only=settings.schools, | |
| 662 | - budget_ms=int(settings.refresh_interval_secs * 1000), | |
| 663 | - ) | |
| 664 | - await asyncio.gather( | |
| 665 | - run_forever(settings, on_ready=hazir), | |
| 666 | - scheduler.serve(tick_seconds=settings.refresh_interval_secs), | |
| 667 | - ) | |
| 668 | - finally: | |
| 669 | - await directory.close() | |
| 750 | + from .store import BridgeStore, ProtocolCaller | |
| 751 | + | |
| 752 | + #: Baglanti nesnesi. Acilista `None`: hicbir sey kurulmaz. | |
| 753 | + kopru: dict[str, Any] = {"protocol": None} | |
| 754 | + | |
| 755 | + def hazir(proto: BridgeProtocol) -> None: | |
| 756 | + kopru["protocol"] = proto | |
| 757 | + | |
| 758 | + def caller_for() -> Any: | |
| 759 | + """Su an bagli tasima; YOKSA `None` -> depo `BridgeUnavailable` der. | |
| 760 | + | |
| 761 | + `None` dondurmek dogru cevaptir: "henuz bagli degil" bir hata degil, | |
| 762 | + beklenen bir durumdur ve sessizce bos yazmaya donusmemelidir. | |
| 763 | + """ | |
| 764 | + proto = kopru["protocol"] | |
| 765 | + if proto is None: | |
| 766 | + return None | |
| 767 | + return ProtocolCaller(proto, timeout_secs=settings.api_timeout_secs) | |
| 768 | + | |
| 769 | + # Tek depo nesnesi; okul her cagrinin kimligindedir (`store_for`). | |
| 770 | + store = BridgeStore(caller_for, timeout_secs=settings.api_timeout_secs) | |
| 771 | + capabilities.bind_store(store) | |
| 772 | + config.log("info", "depo: kopru (insight.*) -- yerel veritabani yok") | |
| 773 | + 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 | + | |
| 778 | + # Zamanlayici her okul icin bir `Source` ister. Baglanti kopmussa | |
| 779 | + # `BridgeSource` cagrisi hata verir ve zamanlayici o okulu duser -- | |
| 780 | + # dogru davranis: veri cekilemeden hesap yapilmaz. | |
| 781 | + def source_for(_school: str) -> Any: | |
| 782 | + proto = kopru["protocol"] | |
| 783 | + if proto is None: | |
| 784 | + raise RuntimeError("kopru henuz bagli degil") | |
| 785 | + return BridgeSource(proto) | |
| 786 | + | |
| 787 | + scheduler = Scheduler( | |
| 788 | + source_for, | |
| 789 | + store, | |
| 790 | + only=settings.schools, | |
| 791 | + budget_ms=int(settings.refresh_interval_secs * 1000), | |
| 792 | + ) | |
| 793 | + await asyncio.gather( | |
| 794 | + run_forever(settings, on_ready=hazir), | |
| 795 | + scheduler.serve(tick_seconds=settings.refresh_interval_secs), | |
| 796 | + ) | |
| 670 | 797 | return 0 |
| 671 | 798 | |
| 672 | 799 |
service/src/capabilities.pymodified+14 -14
| @@ -135,29 +135,29 @@ Handler = Callable[[str, dict[str, Any]], dict[str, Any]] | ||
| 135 | 135 | |
| 136 | 136 | _handlers: dict[str, Handler] = {} |
| 137 | 137 | |
| 138 | -#: Servisin okul dizini (`tenants.Directory`). Isleyiciler okulun deposunu | |
| 139 | -#: BURADAN cozer: `capabilities.directory().store_for(school)`. Cercevenin | |
| 138 | +#: Servisin deposu (`store.BridgeStore`). Isleyiciler okulun deposunu | |
| 139 | +#: BURADAN cozer: `capabilities.store().store_for(school)`. Cercevenin | |
| 140 | 140 | #: `school` alani tek kimlik kaynagidir; ikinci bir yol (ortam degiskeni, |
| 141 | -#: varsayilan okul) olmamasi bilincli -- yanlis okulun veritabanindan cevap | |
| 142 | -#: veren bir okuma, bu alanin kapatmak istedigi tek arizadir. | |
| 143 | -_directory: Any = None | |
| 141 | +#: varsayilan okul) olmamasi bilincli -- yanlis okula yazan bir isleyici, | |
| 142 | +#: bu alanin kapatmak istedigi tek arizadir. | |
| 143 | +_store: Any = None | |
| 144 | 144 | |
| 145 | 145 | |
| 146 | -def bind_directory(directory: Any) -> None: | |
| 146 | +def bind_store(store: Any) -> None: | |
| 147 | 147 | """Acilista bir kez cagrilir (`bridge._serve`); testler de kullanir.""" |
| 148 | - global _directory | |
| 149 | - _directory = directory | |
| 148 | + global _store | |
| 149 | + _store = store | |
| 150 | 150 | |
| 151 | 151 | |
| 152 | -def directory() -> Any: | |
| 153 | - """Bagli okul dizini. Baglanmamisken okul cozulemez -- sessizce | |
| 154 | - varsayilana dusmek yerine acik hata.""" | |
| 155 | - if _directory is None: | |
| 152 | +def store() -> Any: | |
| 153 | + """Bagli depo. Baglanmamisken okul cozulemez -- sessizce bos bir depo | |
| 154 | + uydurmak, yazilan her seyi kaybederdi.""" | |
| 155 | + if _store is None: | |
| 156 | 156 | raise CapabilityError( |
| 157 | 157 | "unavailable", |
| 158 | - "okul dizini bagli degil; isleyici okul veritabanini cozemez", | |
| 158 | + "depo bagli degil; isleyici okul deposunu cozemez", | |
| 159 | 159 | ) |
| 160 | - return _directory | |
| 160 | + return _store | |
| 161 | 161 | |
| 162 | 162 | |
| 163 | 163 | def names() -> list[str]: |
service/src/cli.pymodified+169 -255
| @@ -1,11 +1,12 @@ | ||
| 1 | -"""Geliştirme aracı — köprü olmadan hattı koşturur. | |
| 1 | +"""Geliştirme aracı — köprüsüz hattı koşturur. | |
| 2 | 2 | |
| 3 | - python -m src.cli run --school ataturk-anadolu --source file \ | |
| 4 | - --fixtures service/fixtures --out sonuc.json | |
| 5 | - python -m src.cli run --school X --source file --fixtures ... --dry-run | |
| 6 | - python -m src.cli schema | |
| 3 | + python -m src.cli run --school X --fixtures ... --dry-run | |
| 4 | + python -m src.cli run --school X --fixtures ... --out sonuc.json | |
| 7 | 5 | python -m src.cli rules |
| 8 | - python -m src.cli report --school X --type okul --format html --out DIZIN | |
| 6 | + python -m src.cli report --school X --type okul --format html --out DIZIN \ | |
| 7 | + --fixtures ... | |
| 8 | + python -m src.cli sweep --school X | |
| 9 | + python -m src.cli schedule --fixtures ... | |
| 9 | 10 | |
| 10 | 11 | --------------------------------------------------------------------------- |
| 11 | 12 | BURADA HTTP SUNUCUSU YOKTUR VE OLMAYACAKTIR |
| @@ -14,6 +15,20 @@ BURADA HTTP SUNUCUSU YOKTUR VE OLMAYACAKTIR | ||
| 14 | 15 | risk olarak işaretlendi. Aynı hatayı tekrarlamıyoruz: bu dosya bir CLI'dır, |
| 15 | 16 | bir servis değil. `serve` alt komutu **yoktur**; gece işi `scheduler.py` |
| 16 | 17 | tarafından süreç içinden tetiklenir. |
| 18 | + | |
| 19 | +--------------------------------------------------------------------------- | |
| 20 | +VERİTABANI DA YOKTUR | |
| 21 | +--------------------------------------------------------------------------- | |
| 22 | +ZEKA'nın kendi veritabanı yoktur (değişmez kural: bir AI servisi uygulama | |
| 23 | +veritabanına asla doğrudan erişmez). Bu yüzden burada `--db-url`, DSN ya da | |
| 24 | +şema yükleme bayrağı BULUNMAZ: | |
| 25 | + | |
| 26 | +* `--dry-run` çağrıları **sayar** (`store.RecordingCaller`), hiçbir şey yazmaz. | |
| 27 | +* `sweep` ve `schedule` canlı bir köprü bağlantısı gerektirir ve onu kendileri | |
| 28 | + kurar (`bridge.one_shot` → `BridgeProtocol.call_capability`). Okul listesi | |
| 29 | + backend'den gelir (`insight.schools.list`). | |
| 30 | +* `report` yalnız fikstür yolundan üretir; canlı bir dağıtımı okumak | |
| 31 | + backend'in `/insights` uçlarının işidir, bu aracın değil. | |
| 17 | 32 | """ |
| 18 | 33 | |
| 19 | 34 | from __future__ import annotations |
| @@ -23,7 +38,6 @@ import asyncio | ||
| 23 | 38 | import dataclasses |
| 24 | 39 | import json |
| 25 | 40 | import logging |
| 26 | -import os | |
| 27 | 41 | import sys |
| 28 | 42 | import time |
| 29 | 43 | from pathlib import Path |
| @@ -31,20 +45,17 @@ from typing import Any | ||
| 31 | 45 | |
| 32 | 46 | from .compute import recommend as recommend_mod |
| 33 | 47 | from .compute.attention import unavailable_triggers |
| 48 | +from .config import Config | |
| 34 | 49 | from .pipeline import DEFAULT_BUDGET_MS, run_school |
| 35 | 50 | from .scheduler import Scheduler |
| 36 | 51 | from .store import ( |
| 37 | 52 | RETENTION_DAYS, |
| 38 | - CollectingClient, | |
| 39 | - Store, | |
| 40 | - SurrealHttpClient, | |
| 41 | - apply_schema, | |
| 42 | - schema_field_types, | |
| 43 | - schema_tables, | |
| 53 | + BridgeStore, | |
| 54 | + ProtocolCaller, | |
| 55 | + RecordingCaller, | |
| 56 | + SWEEP_TABLES, | |
| 44 | 57 | ) |
| 45 | 58 | |
| 46 | -from .store import SCHEMA_PATH # noqa: E402 (tek kaynak: store.py) | |
| 47 | - | |
| 48 | 59 | |
| 49 | 60 | def _build_source(kind: str, fixtures: str | None) -> Any: |
| 50 | 61 | """Kaynak nesnesini kurar. |
| @@ -60,281 +71,207 @@ def _build_source(kind: str, fixtures: str | None) -> Any: | ||
| 60 | 71 | ) |
| 61 | 72 | if not fixtures: |
| 62 | 73 | raise SystemExit("--fixtures zorunlu (JSON fikstür dizini)") |
| 63 | - try: | |
| 64 | - from .source import FileSource # type: ignore[attr-defined] | |
| 65 | - except Exception as exc: # noqa: BLE001 | |
| 66 | - raise SystemExit( | |
| 67 | - "FileSource bulunamadı (src/source.py). Bu dosya köprü ajanının " | |
| 68 | - f"sorumluluğundadır. Ayrıntı: {exc}" | |
| 69 | - ) from exc | |
| 74 | + from .source import FileSource # type: ignore[attr-defined] | |
| 75 | + | |
| 70 | 76 | return FileSource(Path(fixtures)) |
| 71 | 77 | |
| 72 | 78 | |
| 73 | 79 | async def _cmd_run(args: argparse.Namespace) -> int: |
| 80 | + """Hattı koştur. | |
| 81 | + | |
| 82 | + `--dry-run` verilirse çağrılar toplanır ve **hiç gönderilmez**; verilmezse | |
| 83 | + depo gerçek köprüdür ve çağrılar backend'e gider. Yazmanın gerçekten | |
| 84 | + yapıldığını bilmeden "yazdım" demek bu aracın kaçındığı şeydir. | |
| 85 | + """ | |
| 74 | 86 | source = _build_source(args.source, args.fixtures) |
| 75 | - # `--dry-run` ifadeleri toplar, `--db-url` gercekten yazar. Ikisi de | |
| 76 | - # verilmezse hicbir sey yazilmaz ve kullanici bunu bilmelidir. | |
| 77 | - client: Any | |
| 78 | - if args.dry_run: | |
| 79 | - client = CollectingClient() | |
| 80 | - else: | |
| 81 | - client = _build_client(args) | |
| 82 | - client.ensure_namespace() | |
| 83 | - store = Store(client) | |
| 84 | 87 | now_ms = args.now or int(time.time() * 1000) |
| 85 | 88 | students = args.students.split(",") if args.students else None |
| 89 | + settings = Config(require_token=False) | |
| 86 | 90 | |
| 87 | - result = await run_school( | |
| 88 | - source, | |
| 89 | - store, | |
| 90 | - args.school, | |
| 91 | - now_ms=now_ms, | |
| 92 | - student_ids=students, | |
| 93 | - term_start_ms=args.term_start, | |
| 94 | - budget_ms=args.budget_ms, | |
| 95 | - ) | |
| 91 | + if args.dry_run: | |
| 92 | + caller = RecordingCaller() | |
| 93 | + store = BridgeStore(caller) | |
| 94 | + result = await run_school( | |
| 95 | + source, | |
| 96 | + store.store_for(args.school), | |
| 97 | + args.school, | |
| 98 | + now_ms=now_ms, | |
| 99 | + student_ids=students, | |
| 100 | + term_start_ms=args.term_start, | |
| 101 | + budget_ms=args.budget_ms, | |
| 102 | + ) | |
| 103 | + payload = { | |
| 104 | + "run": dataclasses.asdict(result), | |
| 105 | + "dry_run": True, | |
| 106 | + "cagri_sayisi": len(caller.calls), | |
| 107 | + } | |
| 108 | + if args.verbose: | |
| 109 | + payload["cagrilar"] = [ | |
| 110 | + {"yetenek": capability, "okul": school, "payload": body} | |
| 111 | + for capability, school, body in caller.calls | |
| 112 | + ] | |
| 113 | + else: | |
| 114 | + async def work(proto: Any) -> dict[str, Any]: | |
| 115 | + store = BridgeStore( | |
| 116 | + ProtocolCaller(proto, timeout_secs=settings.api_timeout_secs) | |
| 117 | + ) | |
| 118 | + result = await run_school( | |
| 119 | + source, | |
| 120 | + store.store_for(args.school), | |
| 121 | + args.school, | |
| 122 | + now_ms=now_ms, | |
| 123 | + student_ids=students, | |
| 124 | + term_start_ms=args.term_start, | |
| 125 | + budget_ms=args.budget_ms, | |
| 126 | + ) | |
| 127 | + return dataclasses.asdict(result) | |
| 96 | 128 | |
| 97 | - payload = { | |
| 98 | - "run": dataclasses.asdict(result), | |
| 99 | - "written_statements": ( | |
| 100 | - len(client.statements) | |
| 101 | - if isinstance(client, CollectingClient) | |
| 102 | - else client.statement_count | |
| 103 | - ), | |
| 104 | - "unavailable_triggers": unavailable_triggers(), | |
| 105 | - "unavailable_rules": recommend_mod.unavailable_rules(), | |
| 106 | - } | |
| 107 | - if args.verbose and isinstance(client, CollectingClient): | |
| 108 | - payload["statements"] = [ | |
| 109 | - {"sql": sql, "variables": variables} | |
| 110 | - for sql, variables in client.statements | |
| 111 | - ] | |
| 129 | + from . import bridge | |
| 130 | + | |
| 131 | + run = await bridge.one_shot(settings, work) | |
| 132 | + if run is None: | |
| 133 | + raise SystemExit("köprü bağlanamadı; hiçbir şey yazılmadı") | |
| 134 | + payload = {"run": run, "dry_run": False} | |
| 135 | + | |
| 136 | + payload["unavailable_triggers"] = unavailable_triggers() | |
| 137 | + payload["unavailable_rules"] = recommend_mod.unavailable_rules() | |
| 112 | 138 | text = json.dumps(payload, ensure_ascii=False, indent=2, default=str) |
| 113 | 139 | if args.out: |
| 114 | 140 | Path(args.out).write_text(text, encoding="utf-8") |
| 115 | 141 | print(f"yazıldı: {args.out}") |
| 116 | 142 | else: |
| 117 | 143 | print(text) |
| 118 | - return 0 if result.status in ("ok", "partial") else 1 | |
| 144 | + status = payload["run"].get("status", "failed") | |
| 145 | + return 0 if status in ("ok", "partial") else 1 | |
| 119 | 146 | |
| 120 | 147 | |
| 121 | 148 | # --------------------------------------------------------------------------- |
| 122 | -# DEPOLAMA / ZAMANLAYICI KOMUTLARI | |
| 149 | +# DEPOLAMA / ZAMANLAYICI KOMUTLARI — hepsi KÖPRÜDEN | |
| 123 | 150 | # --------------------------------------------------------------------------- |
| 124 | -# Buradaki komutlar GERCEK bir SurrealDB ornegine baglanir. Baglanti kurulumu | |
| 125 | -# tek bir yerde (`_build_client`) toplanir; parola asla basilmaz. | |
| 151 | +# Bağlantı `bridge.one_shot` ile kurulur: bağlan, kaydol, işi koştur, kapat. | |
| 152 | +# Veritabanı bayrağı YOKTUR; okul backend'in kendi dizininden gelir. | |
| 126 | 153 | |
| 127 | 154 | |
| 128 | -def _add_db_flags(parser: argparse.ArgumentParser) -> None: | |
| 129 | - parser.add_argument( | |
| 130 | - "--db-url", | |
| 131 | - help="SurrealDB HTTP adresi, orn. http://hzk-zeka:8000 " | |
| 132 | - "(verilmezse ZEKA_DB_HTTP_URL ortam degiskeni)", | |
| 133 | - ) | |
| 134 | - parser.add_argument("--db-ns", default=None, help="namespace (vars: hezarfen)") | |
| 135 | - parser.add_argument("--db-name", default=None, help="veritabani (vars: zeka)") | |
| 136 | - parser.add_argument("--db-user", default=None, help="kullanici (vars: root)") | |
| 137 | - parser.add_argument("--db-pass", default=None, help="parola (vars: root)") | |
| 155 | +async def _cmd_sweep(args: argparse.Namespace) -> int: | |
| 156 | + """Saklama süresi süpürmesini koştur (backend'de, o okulun veritabanında). | |
| 138 | 157 | |
| 158 | + `--now` yalnız çıktı içindir: saati backend damgalar, iki saatli bir | |
| 159 | + süpürme "hangi gün" sorusuna iki cevap verirdi. | |
| 160 | + """ | |
| 161 | + settings = Config(require_token=True) | |
| 139 | 162 | |
| 140 | -def _build_client(args: argparse.Namespace) -> SurrealHttpClient: | |
| 141 | - """Gercek veritabani istemcisini kurar; adres yoksa anlasilir hata verir.""" | |
| 142 | - url = args.db_url or os.environ.get("ZEKA_DB_HTTP_URL", "") | |
| 143 | - if not url: | |
| 144 | - raise SystemExit( | |
| 145 | - "--db-url verilmedi (ya da ZEKA_DB_HTTP_URL bos). Ornek: " | |
| 146 | - "--db-url http://hzk-zeka:8000" | |
| 163 | + async def work(proto: Any) -> dict[str, bool]: | |
| 164 | + store = BridgeStore( | |
| 165 | + ProtocolCaller(proto, timeout_secs=settings.api_timeout_secs) | |
| 147 | 166 | ) |
| 148 | - return SurrealHttpClient( | |
| 149 | - url, | |
| 150 | - namespace=args.db_ns or os.environ.get("ZEKA_DB_NS", "hezarfen"), | |
| 151 | - database=args.db_name or os.environ.get("ZEKA_DB_NAME", "zeka"), | |
| 152 | - user=args.db_user or os.environ.get("ZEKA_DB_USER", "root"), | |
| 153 | - password=args.db_pass or os.environ.get("ZEKA_DB_PASSWORD", "root"), | |
| 154 | - ) | |
| 167 | + return await store.store_for(args.school).sweep(args.now or int(time.time() * 1000)) | |
| 155 | 168 | |
| 169 | + from . import bridge | |
| 156 | 170 | |
| 157 | -def _cmd_schema(args: argparse.Namespace) -> int: | |
| 158 | - """Semayi basar; `--apply` verilirse gercekten yukler ve DOGRULAR.""" | |
| 159 | - if not getattr(args, "apply", False): | |
| 160 | - print(SCHEMA_PATH.read_text(encoding="utf-8")) | |
| 161 | - return 0 | |
| 162 | - client = _build_client(args) | |
| 163 | - client.ensure_namespace() | |
| 164 | - report = apply_schema(client) | |
| 165 | - payload: dict[str, Any] = { | |
| 166 | - "ifade_toplam": report.total, | |
| 167 | - "uygulanan": report.applied, | |
| 168 | - "hatalar": report.errors, | |
| 169 | - } | |
| 170 | - # Yuklendi demek yetmez: alanlarin gercekten var oldugunu OKUYARAK gosteriyoruz. | |
| 171 | - if report.ok: | |
| 172 | - payload["tablolar"] = sorted(schema_tables(client)) | |
| 173 | - payload["alanlar"] = { | |
| 174 | - table: sorted(schema_field_types(client, table)) | |
| 175 | - for table in ( | |
| 176 | - "student_summary", | |
| 177 | - "recommendation", | |
| 178 | - "insight_run", | |
| 179 | - "question_segment", | |
| 180 | - "student_segment_profile", | |
| 181 | - ) | |
| 182 | - } | |
| 183 | - print(json.dumps(payload, ensure_ascii=False, indent=2)) | |
| 184 | - return 0 if report.ok else 1 | |
| 185 | - | |
| 186 | - | |
| 187 | -def _cmd_sweep(args: argparse.Namespace) -> int: | |
| 188 | - """Saklama suresi supurmesi. Once/sonra satir sayilarini basar.""" | |
| 189 | - client = _build_client(args) | |
| 190 | - now = args.now or int(time.time() * 1000) | |
| 191 | - | |
| 192 | - def counts() -> dict[str, int]: | |
| 193 | - out: dict[str, int] = {} | |
| 194 | - for table in RETENTION_DAYS: | |
| 195 | - rows = client.query_sync(f"SELECT count() FROM {table} GROUP ALL;") | |
| 196 | - result = rows[0].get("result") or [] | |
| 197 | - out[table] = int(result[0]["count"]) if result else 0 | |
| 198 | - return out | |
| 199 | - | |
| 200 | - before = counts() | |
| 201 | - store = Store(client) | |
| 202 | - results = asyncio.run(store.sweep(now)) | |
| 203 | - after = counts() | |
| 171 | + tables = await bridge.one_shot(settings, work) | |
| 172 | + if tables is None: | |
| 173 | + raise SystemExit("köprü bağlanamadı; süpürme koşmadı") | |
| 204 | 174 | print( |
| 205 | 175 | json.dumps( |
| 206 | 176 | { |
| 207 | - "now_ms": now, | |
| 208 | - "once": before, | |
| 209 | - "sonra": after, | |
| 210 | - "silinen": {t: before[t] - after[t] for t in before}, | |
| 211 | - "tablo_sonuclari": results, | |
| 177 | + "okul": args.school, | |
| 178 | + "saklama_gun": RETENTION_DAYS, | |
| 179 | + "tablolar": tables, | |
| 212 | 180 | }, |
| 213 | 181 | ensure_ascii=False, |
| 214 | 182 | indent=2, |
| 215 | 183 | ) |
| 216 | 184 | ) |
| 217 | - return 0 if all(results.values()) else 1 | |
| 185 | + return 0 if all(tables.get(table) for table in SWEEP_TABLES) else 1 | |
| 218 | 186 | |
| 219 | 187 | |
| 220 | 188 | async def _cmd_schedule(args: argparse.Namespace) -> int: |
| 221 | - """Zamanlayiciyi elle tetikler -- gece penceresini BEKLEMEDEN. | |
| 189 | + """Zamanlayıcıyı elle tetikle — gece penceresini BEKLEMEDEN. | |
| 222 | 190 | |
| 223 | - `--ticks` verilirse tam `serve()` dongusu kosar (test kipi); verilmezse | |
| 224 | - tek tur (`run_once`) kosar. Ikisi de ayni kod yolunu kullanir. | |
| 225 | - | |
| 226 | - Iki depo yolu vardir ve ikisi de URETIMDEKI ayni kodu kullanir: | |
| 227 | - | |
| 228 | - * `--pg-dsn` (ya da `ZEKA_PG_DSN`) verilirse KONTROL veritabanidir; | |
| 229 | - okullar oradan cozulur (`tenants.open_postgres`) ve `--schools` FILTRE | |
| 230 | - olur (verilmezse butun aktif okullar kosar). | |
| 231 | - * verilmezse eski tek veritabani modu; `--schools` ZORUNLUDUR. | |
| 191 | + Okul listesi **backend'den** gelir (`insight.schools.list`); `--schools` | |
| 192 | + yalnızca bir FİLTREDİR: daraltır, üretmez. `--ticks` verilirse tam | |
| 193 | + `serve()` döngüsü koşar (test kipi), verilmezse tek tur (`run_once`). | |
| 194 | + İkisi de üretimdeki aynı kodu kullanır. | |
| 232 | 195 | """ |
| 233 | - from .tenants import OneDatabase | |
| 234 | - | |
| 196 | + settings = Config(require_token=False) | |
| 235 | 197 | schools = [s.strip() for s in (args.schools or "").split(",") if s.strip()] |
| 236 | - dsn = (args.pg_dsn or os.environ.get("ZEKA_PG_DSN", "")).strip() | |
| 237 | - if dsn: | |
| 238 | - from .tenants import open_postgres | |
| 239 | - | |
| 240 | - directory = await open_postgres(dsn) | |
| 241 | - only = schools or None | |
| 242 | - else: | |
| 243 | - if not schools: | |
| 244 | - raise SystemExit( | |
| 245 | - "--schools zorunlu (tek veritabani modu). Postgres icin " | |
| 246 | - "--pg-dsn verin; orada okullar kontrol veritabanindan gelir." | |
| 247 | - ) | |
| 248 | - client = _build_client(args) | |
| 249 | - directory = OneDatabase(Store(client), schools, teardown=[client.close]) | |
| 250 | - only = None | |
| 251 | 198 | budgets: dict[str, int] = {} |
| 252 | 199 | for pair in (args.budget or "").split(","): |
| 253 | 200 | if "=" in pair: |
| 254 | 201 | name, value = pair.split("=", 1) |
| 255 | 202 | budgets[name.strip()] = int(value) |
| 256 | - root = Path(args.fixtures) if args.fixtures else None | |
| 257 | - if root is None: | |
| 258 | - raise SystemExit("--fixtures zorunlu (her okul icin bir alt dizin)") | |
| 259 | - from .source import FileSource # type: ignore[attr-defined] | |
| 260 | - | |
| 203 | + root = Path(args.fixtures) | |
| 261 | 204 | stamp = args.now or int(time.time() * 1000) |
| 262 | - scheduler = Scheduler( | |
| 263 | - lambda school: FileSource(root), | |
| 264 | - directory, | |
| 265 | - only=only, | |
| 266 | - budget_ms=args.budget_ms, | |
| 267 | - budgets=budgets, | |
| 268 | - term_start_ms=args.term_start, | |
| 269 | - clock_fn=lambda: stamp, | |
| 270 | - ) | |
| 271 | - try: | |
| 205 | + | |
| 206 | + async def work(proto: Any) -> dict[str, Any]: | |
| 207 | + store = BridgeStore( | |
| 208 | + ProtocolCaller(proto, timeout_secs=settings.api_timeout_secs) | |
| 209 | + ) | |
| 210 | + scheduler = Scheduler( | |
| 211 | + lambda _school: _build_source("file", str(root)), | |
| 212 | + store, | |
| 213 | + only=schools or None, | |
| 214 | + budget_ms=args.budget_ms, | |
| 215 | + budgets=budgets, | |
| 216 | + term_start_ms=args.term_start, | |
| 217 | + clock_fn=lambda: stamp, | |
| 218 | + ) | |
| 272 | 219 | if args.ticks: |
| 273 | 220 | await scheduler.serve( |
| 274 | 221 | tick_seconds=args.tick_seconds, ignore_window=True, max_ticks=args.ticks |
| 275 | 222 | ) |
| 276 | - results = [] | |
| 223 | + results: list[Any] = [] | |
| 277 | 224 | else: |
| 278 | 225 | results = await scheduler.run_once(stamp) |
| 279 | - finally: | |
| 280 | - await directory.close() | |
| 281 | - gorulen = sorted({*schools, *(r.school for r in results)}) | |
| 282 | - print( | |
| 283 | - json.dumps( | |
| 284 | - { | |
| 285 | - "kosulan_okullar": [r.school for r in results], | |
| 286 | - "sonuclar": [dataclasses.asdict(r) for r in results], | |
| 287 | - "dusen_okullar": scheduler._failures, | |
| 288 | - "bekleyen": {s: scheduler.pending_for(s) for s in gorulen}, | |
| 289 | - }, | |
| 290 | - ensure_ascii=False, | |
| 291 | - indent=2, | |
| 292 | - default=str, | |
| 293 | - ) | |
| 294 | - ) | |
| 226 | + return { | |
| 227 | + "kosulan_okullar": [r.school for r in results], | |
| 228 | + "sonuclar": [dataclasses.asdict(r) for r in results], | |
| 229 | + "dusen_okullar": scheduler.failures(), | |
| 230 | + } | |
| 231 | + | |
| 232 | + from . import bridge | |
| 233 | + | |
| 234 | + payload = await bridge.one_shot(settings, work) | |
| 235 | + if payload is None: | |
| 236 | + raise SystemExit("köprü bağlanamadı; tur koşmadı") | |
| 237 | + print(json.dumps(payload, ensure_ascii=False, indent=2, default=str)) | |
| 295 | 238 | return 0 |
| 296 | 239 | |
| 297 | 240 | |
| 298 | 241 | async def _cmd_report(args: argparse.Namespace) -> int: |
| 299 | - """Rapor üretir — ZEKA'nın **kendi** veritabanından okuyarak. | |
| 300 | - | |
| 301 | - python -m src.cli report --school X --type okul --format html --out DIZIN | |
| 242 | + """Rapor üretir — hattı fikstürden koşturup yazılan satırları yakalayarak. | |
| 302 | 243 | |
| 303 | - İki okuma yolu vardır ve ikisi de aynı rapor kodunu besler: | |
| 244 | + python -m src.cli report --school X --type okul --format html --out DIZIN --fixtures ... | |
| 304 | 245 | |
| 305 | - * `--db-url` (ya da `ZEKA_DB_HTTP_URL`): gerçek ZEKA veritabanı. | |
| 306 | - * `--fixtures`: veritabanı yoksa hattı fikstürden koşturur, yazılan | |
| 307 | - satırları bellekte yakalar (`report/capture.py`) ve raporu onlardan | |
| 308 | - üretir. Konteyner ayakta olmayan makinede de uçtan uca çalışır. | |
| 246 | + Canlı bir dağıtımın satırlarını okumak bu aracın işi DEĞİLDİR: ZEKA | |
| 247 | + veritabanı okumaz, o satırlar backend'in `/insights` uçlarından okunur. | |
| 309 | 248 | """ |
| 310 | 249 | from .report import load as load_mod |
| 311 | - from .report import reader as reader_mod | |
| 312 | 250 | from .report import writer as writer_mod |
| 313 | 251 | from .report.build import build as build_report |
| 314 | - from .report.capture import CapturingClient | |
| 252 | + from .report.capture import CapturingCaller | |
| 315 | 253 | from .report.gate import REPORT_TYPES |
| 316 | 254 | |
| 317 | 255 | if args.type not in REPORT_TYPES: |
| 318 | 256 | raise SystemExit(f"bilinmeyen rapor tipi: {args.type}") |
| 257 | + if not args.fixtures: | |
| 258 | + raise SystemExit( | |
| 259 | + "--fixtures zorunlu: rapor, hattın fikstürden koşup yakaladığı " | |
| 260 | + "satırlardan üretilir (ZEKA veritabanı okumaz)." | |
| 261 | + ) | |
| 319 | 262 | |
| 320 | 263 | now_ms = args.now or int(time.time() * 1000) |
| 321 | - | |
| 322 | - reader: Any | |
| 323 | - if args.fixtures: | |
| 324 | - # Fikstür yolu: hattı koştur, yazılan satırları yakala. | |
| 325 | - source = _build_source(args.source, args.fixtures) | |
| 326 | - client = CapturingClient() | |
| 327 | - await run_school( | |
| 328 | - source, | |
| 329 | - Store(client), | |
| 330 | - args.school, | |
| 331 | - now_ms=now_ms, | |
| 332 | - term_start_ms=args.term_start, | |
| 333 | - budget_ms=args.budget_ms, | |
| 334 | - ) | |
| 335 | - reader = client.as_reader() | |
| 336 | - else: | |
| 337 | - reader = reader_mod.DbReader(_build_client(args)) | |
| 264 | + source = _build_source(args.source, args.fixtures) | |
| 265 | + caller = CapturingCaller() | |
| 266 | + await run_school( | |
| 267 | + source, | |
| 268 | + BridgeStore(caller).store_for(args.school), | |
| 269 | + args.school, | |
| 270 | + now_ms=now_ms, | |
| 271 | + term_start_ms=args.term_start, | |
| 272 | + budget_ms=args.budget_ms, | |
| 273 | + ) | |
| 274 | + reader = caller.as_reader() | |
| 338 | 275 | |
| 339 | 276 | try: |
| 340 | 277 | bundle = await load_mod.load_bundle( |
| @@ -381,7 +318,7 @@ def _cmd_rules(_args: argparse.Namespace) -> int: | ||
| 381 | 318 | def build_parser() -> argparse.ArgumentParser: |
| 382 | 319 | parser = argparse.ArgumentParser( |
| 383 | 320 | prog="python -m src.cli", |
| 384 | - description="ZEKA geliştirme aracı — köprüsüz hat koşturucu.", | |
| 321 | + description="ZEKA geliştirme aracı — köprü/veritabanı bağlamadan hat koşturucu.", | |
| 385 | 322 | ) |
| 386 | 323 | parser.add_argument("-v", "--verbose", action="store_true") |
| 387 | 324 | sub = parser.add_subparsers(dest="command", required=True) |
| @@ -400,39 +337,22 @@ def build_parser() -> argparse.ArgumentParser: | ||
| 400 | 337 | run.add_argument( |
| 401 | 338 | "--dry-run", |
| 402 | 339 | action="store_true", |
| 403 | - help="veritabanına yazma; ifadeleri say ve sonucu bas", | |
| 340 | + help="köprüye hiçbir şey gönderme; çağrıları say ve sonucu bas", | |
| 404 | 341 | ) |
| 405 | 342 | run.set_defaults(func=_cmd_run, is_async=True) |
| 406 | 343 | |
| 407 | - _add_db_flags(run) | |
| 408 | - | |
| 409 | - schema = sub.add_parser("schema", help="ZEKA şema DDL'ini bas ya da yükle") | |
| 410 | - schema.add_argument( | |
| 411 | - "--apply", | |
| 412 | - action="store_true", | |
| 413 | - help="DDL'i gerçekten veritabanına yükle ve INFO ile doğrula", | |
| 414 | - ) | |
| 415 | - _add_db_flags(schema) | |
| 416 | - schema.set_defaults(func=_cmd_schema, is_async=False) | |
| 417 | - | |
| 418 | - sweep = sub.add_parser("sweep", help="saklama süresi süpürmesini koştur") | |
| 419 | - sweep.add_argument("--now", type=int, help="unix ms; varsayılan şimdi") | |
| 420 | - _add_db_flags(sweep) | |
| 421 | - sweep.set_defaults(func=_cmd_sweep, is_async=False) | |
| 344 | + sweep = sub.add_parser("sweep", help="saklama süresi süpürmesini koştur (köprüden)") | |
| 345 | + sweep.add_argument("--school", required=True, help="okul slug'ı") | |
| 346 | + sweep.add_argument("--now", type=int, help="unix ms; yalnız çıktı içindir") | |
| 347 | + sweep.set_defaults(func=_cmd_sweep, is_async=True) | |
| 422 | 348 | |
| 423 | 349 | schedule = sub.add_parser( |
| 424 | 350 | "schedule", help="zamanlayıcıyı elle tetikle (gece penceresini beklemeden)" |
| 425 | 351 | ) |
| 426 | 352 | schedule.add_argument( |
| 427 | 353 | "--schools", |
| 428 | - help="virgülle ayrılmış slug listesi. Postgres modunda (--pg-dsn) " | |
| 429 | - "FİLTREDİR: verilmezse bütün aktif okullar koşar; eski tek veritabanı " | |
| 430 | - "modunda zorunludur", | |
| 431 | - ) | |
| 432 | - schedule.add_argument( | |
| 433 | - "--pg-dsn", | |
| 434 | - help="KONTROL veritabanı DSN'i (verilmezse ZEKA_PG_DSN). Verilirse " | |
| 435 | - "okullar kontrol veritabanındaki `school` tablosundan çözülür", | |
| 354 | + help="virgülle ayrılmış slug listesi — backend'in verdiği listenin " | |
| 355 | + "FİLTRESİ. Verilmezse bütün aktif okullar koşar.", | |
| 436 | 356 | ) |
| 437 | 357 | schedule.add_argument("--fixtures", required=True) |
| 438 | 358 | schedule.add_argument("--now", type=int) |
| @@ -443,7 +363,6 @@ def build_parser() -> argparse.ArgumentParser: | ||
| 443 | 363 | ) |
| 444 | 364 | schedule.add_argument("--ticks", type=int, help="test kipi: kaç tik atılsın") |
| 445 | 365 | schedule.add_argument("--tick-seconds", type=float, default=0.01) |
| 446 | - _add_db_flags(schedule) | |
| 447 | 366 | schedule.set_defaults(func=_cmd_schedule, is_async=True) |
| 448 | 367 | |
| 449 | 368 | report = sub.add_parser( |
| @@ -459,13 +378,11 @@ def build_parser() -> argparse.ArgumentParser: | ||
| 459 | 378 | report.add_argument("--teacher", help="öğretmen kimliği (öğretmen raporu için)") |
| 460 | 379 | report.add_argument("--now", type=int, help="unix ms; varsayılan şimdi") |
| 461 | 380 | report.add_argument( |
| 462 | - "--fixtures", | |
| 463 | - help="veritabanı yerine fikstürden koş (JSON fikstür dizini)", | |
| 381 | + "--fixtures", required=True, help="JSON fikstür dizini (rapor bu yoldan üretilir)" | |
| 464 | 382 | ) |
| 465 | 383 | report.add_argument("--source", default="file", choices=["file"]) |
| 466 | 384 | report.add_argument("--term-start", type=int) |
| 467 | 385 | report.add_argument("--budget-ms", type=int, default=DEFAULT_BUDGET_MS) |
| 468 | - _add_db_flags(report) | |
| 469 | 386 | report.set_defaults(func=_cmd_report, is_async=True) |
| 470 | 387 | |
| 471 | 388 | rules = sub.add_parser("rules", help="kural kataloğunu bas") |
| @@ -475,10 +392,7 @@ def build_parser() -> argparse.ArgumentParser: | ||
| 475 | 392 | |
| 476 | 393 | def main(argv: list[str] | None = None) -> int: |
| 477 | 394 | args = build_parser().parse_args(argv) |
| 478 | - logging.basicConfig( | |
| 479 | - level=logging.DEBUG if args.verbose else logging.INFO, | |
| 480 | - format="%(levelname)s %(name)s: %(message)s", | |
| 481 | - ) | |
| 395 | + logging.basicConfig(level=logging.DEBUG if args.verbose else logging.INFO) | |
| 482 | 396 | if getattr(args, "is_async", False): |
| 483 | 397 | return asyncio.run(args.func(args)) |
| 484 | 398 | return args.func(args) |
service/src/compute/model.pymodified+2 -2
| @@ -148,7 +148,7 @@ class Recommendation: | ||
| 148 | 148 | ) |
| 149 | 149 | |
| 150 | 150 | def record_key(self) -> str: |
| 151 | - """Kompozit kayıt anahtarı → UPSERT idempotenttir, çoğaltma olmaz. | |
| 151 | + """Kompozit kayıt anahtarı → yazma idempotenttir, çoğaltma olmaz. | |
| 152 | 152 | |
| 153 | 153 | `MODULLER.md` §2.11 adım 1: kompozit anahtar tekilliği yapısal kılar. |
| 154 | 154 | |
| @@ -156,7 +156,7 @@ class Recommendation: | ||
| 156 | 156 | Öğretmene giden kurallar (T3, T4) öğrenci başına bir kez ateşler: |
| 157 | 157 | bir öğretmen, bir kural, bir ders altında otuz öğrenci. Anahtar |
| 158 | 158 | `scope or course or about` biçiminde tek bir yuvaya sıkıştırıldığında |
| 159 | - otuzu da aynı anahtarı üretiyordu; UPSERT sonuncuyu tutuyor, öğretmen | |
| 159 | + otuzu da aynı anahtarı üretiyordu; son yazılan tutuluyor, öğretmen | |
| 160 | 160 | **tek öğrenci** görüyor ve yirmi dokuzu hiçbir yerde hata vermeden |
| 161 | 161 | kayboluyordu. Ölçüldü: beş öğrenci → bir anahtar. |
| 162 | 162 |
service/src/config.pymodified+9 -64
| @@ -170,29 +170,15 @@ class Config: | ||
| 170 | 170 | # Her frame kendi okulunu adlandirir (`ai/protocol.rs:36-47`); `Hello` |
| 171 | 171 | # okul tasimaz. Filo paylasimlidir: ZEKA butun okullara hizmet eder. |
| 172 | 172 | # |
| 173 | - # Okul KUTUGU kontrol veritabanindadir (`tenants.py`); burasi yalnizca | |
| 173 | + # Okul KUTUGU backend'dedir (`insight.schools.list`); burasi yalnizca | |
| 174 | 174 | # bir FILTREDIR. Bos liste = butun aktif okullar. Sabit bir varsayilan |
| 175 | 175 | # okul yoktur: "hangi okullar var" sorusunun cevabi yapilandirma |
| 176 | - # degil, kontrol veritabani olmalidir. | |
| 176 | + # degil, backend'dir. | |
| 177 | 177 | self.schools = env_list("ZEKA_SCHOOLS", ()) |
| 178 | 178 | self.student_source = env_choice("ZEKA_STUDENT_SOURCE", "config", STUDENT_SOURCES) |
| 179 | 179 | self.students = env_list("ZEKA_STUDENTS", ()) |
| 180 | 180 | self.student_file = _absolute(env_str("ZEKA_STUDENT_FILE", "")) |
| 181 | 181 | |
| 182 | - # --- okul havuzlari --------------------------------------------------- | |
| 183 | - # Okul sayisi sinirsiz; acik baglanti sayisi sinirli olmali. Havuz | |
| 184 | - # tavani ve TTL'i `tenants.TenantStores` uygular. | |
| 185 | - self.max_school_pools = env_int("ZEKA_MAX_SCHOOL_POOLS", 8, 1, 256) | |
| 186 | - self.school_pool_ttl_secs = env_float( | |
| 187 | - "ZEKA_SCHOOL_POOL_TTL_SECS", 900.0, 0.0, 86400.0 | |
| 188 | - ) | |
| 189 | - self.school_registry_ttl_secs = env_float( | |
| 190 | - "ZEKA_SCHOOL_REGISTRY_TTL_SECS", 30.0, 0.0, 3600.0 | |
| 191 | - ) | |
| 192 | - self.school_connect_timeout_secs = env_float( | |
| 193 | - "ZEKA_SCHOOL_CONNECT_TIMEOUT_SECS", 10.0, 1.0, 120.0 | |
| 194 | - ) | |
| 195 | - | |
| 196 | 182 | # --- veri cephesi ------------------------------------------------------ |
| 197 | 183 | self.source_mode = env_choice("ZEKA_SOURCE", "bridge", SOURCE_MODES) |
| 198 | 184 | self.fixture_root = _absolute(env_str("ZEKA_FIXTURE_ROOT", "/data/zeka/fixtures")) |
| @@ -208,16 +194,11 @@ class Config: | ||
| 208 | 194 | self.refresh_jitter_secs = env_float("ZEKA_REFRESH_JITTER_SECS", 60.0, 0.0, 3600.0) |
| 209 | 195 | self.refresh_batch = env_int("ZEKA_REFRESH_BATCH", 25, 1, 5000) |
| 210 | 196 | |
| 211 | - # --- ZEKA'nin kendi veritabani ------------------------------------------ | |
| 212 | - # Hesap ciktilari burada durur. Okulun veritabanina ZEKA yazmaz; kopru | |
| 213 | - # zaten salt-okumadir (`ai/server.rs:719-726` -> `method_not_allowed`). | |
| 214 | - self.db_url = env_str("ZEKA_DB_URL", "ws://hezarfen-surrealdb:8000/rpc") | |
| 215 | - self.db_namespace = env_str("ZEKA_DB_NS", "hezarfen") | |
| 216 | - self.db_database = env_str("ZEKA_DB_NAME", "zeka") | |
| 217 | - self.db_user = env_str("ZEKA_DB_USER", "") | |
| 218 | - self.db_password = env_str("ZEKA_DB_PASSWORD", "") | |
| 219 | - self.has_db_password = bool(self.db_password) | |
| 220 | - | |
| 197 | + # --- yazma hedefi ------------------------------------------------------- | |
| 198 | + # YOK. ZEKA'nin kendi veritabani YOKTUR: degismez kural geregi bir AI | |
| 199 | + # servisi uygulama veritabanina asla dogrudan erismez. Cikti satirlari | |
| 200 | + # backend'e kopruden yazilir (`insight.*` yetenek cagrilari); burada | |
| 201 | + # ne DSN, ne adres, ne parola okunur. | |
| 221 | 202 | if require_token and not self.has_token: |
| 222 | 203 | raise ConfigError( |
| 223 | 204 | "AI_SHARED_TOKEN tanimli degil; backend ile ayni sir olmadan kayit yapilamaz" |
| @@ -241,52 +222,16 @@ class Config: | ||
| 241 | 222 | f"token={'tanimli' if self.has_token else 'TANIMSIZ'} " |
| 242 | 223 | f"max_es_zamanli={self.max_concurrent} " |
| 243 | 224 | f"yeniden_baglanma={self.reconnect_secs}s..{self.reconnect_max_secs}s " |
| 244 | - f"okullar={','.join(self.schools) if self.schools else 'hepsi(kontrol)'} " | |
| 245 | - f"okul_havuzu=en fazla {self.max_school_pools} TTL {self.school_pool_ttl_secs:g}s " | |
| 225 | + f"okullar={','.join(self.schools) if self.schools else 'hepsi(backend)'} " | |
| 246 | 226 | f"ogrenci_kaynagi={self.student_source} ogrenci_sayisi={students} " |
| 247 | 227 | f"veri_cephesi={self.source_mode} fikstur_kok={self.fixture_root} " |
| 248 | 228 | f"api_zaman_asimi={self.api_timeout_secs}s " |
| 249 | 229 | f"tazeleme={tazeleme} parti={self.refresh_batch} " |
| 250 | - f"{self._depo_ozeti()} " | |
| 230 | + f"depo=kopru(insight.*) " | |
| 251 | 231 | f"log={self.log_level}" |
| 252 | 232 | ) |
| 253 | 233 | |
| 254 | 234 | |
| 255 | -def _depo_ozeti_impl(self) -> str: | |
| 256 | - """Yazma hedefini ozetler — DSN ASLA loglanmaz. | |
| 257 | - | |
| 258 | - Eskiden bu satir kosulsuz SurrealDB adresini basiyordu ve Postgres'e | |
| 259 | - yazilirken bile "db=ws://hezarfen-surrealdb:8000/rpc" diyordu. Acilis | |
| 260 | - logunun yanlis depoyu gostermesi, bir arizayi tesbit ederken insani | |
| 261 | - saatlerce yanlis yere baktirir. | |
| 262 | - | |
| 263 | - `ZEKA_PG_DSN` artik KONTROL veritabanidir; okul verileri okul basina | |
| 264 | - ayri veritabanlarindadir (`tenants.py`). Satir bunu soyler, yoksa "depo= | |
| 265 | - postgres /hezarfen_control" okuyan operator okul verisinin oraya | |
| 266 | - yazildigini sanirdi. | |
| 267 | - """ | |
| 268 | - import os | |
| 269 | - | |
| 270 | - dsn = os.environ.get("ZEKA_PG_DSN", "").strip() | |
| 271 | - if dsn: | |
| 272 | - try: | |
| 273 | - import urllib.parse | |
| 274 | - | |
| 275 | - parsed = urllib.parse.urlsplit(dsn) | |
| 276 | - yer = f"{parsed.hostname or '?'}{parsed.path}" | |
| 277 | - except Exception: # noqa: BLE001 | |
| 278 | - yer = "<cozumlenemedi>" | |
| 279 | - return f"depo=postgres kontrol {yer} (okullar kendi veritabanlarinda)" | |
| 280 | - return ( | |
| 281 | - f"depo=surrealdb(eski) {self.db_url} ns={self.db_namespace} " | |
| 282 | - f"db_ad={self.db_database} " | |
| 283 | - f"db_parola={'tanimli' if self.has_db_password else 'TANIMSIZ'}" | |
| 284 | - ) | |
| 285 | - | |
| 286 | - | |
| 287 | -Config._depo_ozeti = _depo_ozeti_impl | |
| 288 | - | |
| 289 | - | |
| 290 | 235 | def load(require_token: bool = True) -> Config: |
| 291 | 236 | """Yapilandirmayi oku; hataliysa tek satir basip `exit 2`.""" |
| 292 | 237 | try: |
service/src/pg_client.pydeleted+0 -152
| @@ -1,152 +0,0 @@ | ||
| 1 | -"""`PgClient` protokolunun psycopg 3 uzerindeki uygulamasi. | |
| 2 | - | |
| 3 | -`store_pg.py` bu modulu **import etmez**; hatti kuran taraf istemciyi disaridan | |
| 4 | -verir. Boylece birim testleri ve `--dry-run` psycopg kurulu olmadan da kosar — | |
| 5 | -`store.py`'nin surucu bagimsizligiyla ayni gerekce. | |
| 6 | - | |
| 7 | ---------------------------------------------------------------------------- | |
| 8 | -Neden psycopg, ve neden yeni bir bagimlilik | |
| 9 | ---------------------------------------------------------------------------- | |
| 10 | -Servisin bugune kadar tek calisma zamani bagimliligi `aioquic` idi; cerceveleme | |
| 11 | -`struct`, sertifika `urllib`, ozet `hashlib` ile yapiliyordu. Postgres'te bu | |
| 12 | -mumkun degil: tel protokolu stdlib'de yok ve elle yazilmasi gereken bir sey de | |
| 13 | -degil. `psycopg[binary]` hazir tekerlekle gelir, derleyici istemez. | |
| 14 | - | |
| 15 | -Surum PINLI. Gerekce `requirements.txt`'in basindaki ile ayni: acik araliklar | |
| 16 | -ayni Containerfile'in bugun ve yarin farkli davranmasina yol acar. | |
| 17 | - | |
| 18 | ---------------------------------------------------------------------------- | |
| 19 | -Baglanti bilgisi | |
| 20 | ---------------------------------------------------------------------------- | |
| 21 | -`ZEKA_PG_DSN` ortam degiskeninden gelir. Bu bir **sirdir**: hicbir kosulda | |
| 22 | -loglanmaz. `PgPool.describe()` yalnizca host/port/veritabani doner, kullanici | |
| 23 | -adi ve parola asla. | |
| 24 | - | |
| 25 | -DSN artik **kontrol** veritabanini adlandirir (`tenants.py`); okul | |
| 26 | -veritabanlarina ayni sunucuda, `dbname` degistirilmis DSN'lerle baglanilir. | |
| 27 | -Bu modul ikisini de bilmez: eline verilen DSN'e baglanir. | |
| 28 | -""" | |
| 29 | - | |
| 30 | -from __future__ import annotations | |
| 31 | - | |
| 32 | -import logging | |
| 33 | -import os | |
| 34 | -from typing import Any, Sequence | |
| 35 | - | |
| 36 | -log = logging.getLogger(__name__) | |
| 37 | - | |
| 38 | -#: Havuzun acik tutacagi baglanti sayisi. Gece kosusu tek is parcacigidir; | |
| 39 | -#: havuz derinligi yeniden baglanma icin var, esazamanlilik icin degil. | |
| 40 | -DEFAULT_POOL_MIN = 1 | |
| 41 | -DEFAULT_POOL_MAX = 4 | |
| 42 | - | |
| 43 | - | |
| 44 | -class PgError(RuntimeError): | |
| 45 | - """Yazma/okuma sirasinda alinan hata; ifade metni ekli.""" | |
| 46 | - | |
| 47 | - def __init__(self, message: str, *, statement: str = "") -> None: | |
| 48 | - super().__init__(message) | |
| 49 | - self.statement = statement | |
| 50 | - | |
| 51 | - | |
| 52 | -class PsycopgClient: | |
| 53 | - """`PgClient` protokolunun tek baglanti uzerindeki uygulamasi. | |
| 54 | - | |
| 55 | - `transaction()` psycopg'nin kendi transaction baglamini dondurur; ic ice | |
| 56 | - cagrilarda psycopg otomatik olarak SAVEPOINT kullanir, yani `PgStore`'un | |
| 57 | - grup transaction'lari guvenle ic ice gecebilir. | |
| 58 | - """ | |
| 59 | - | |
| 60 | - def __init__(self, conn: Any) -> None: | |
| 61 | - self._conn = conn | |
| 62 | - | |
| 63 | - @classmethod | |
| 64 | - async def connect( | |
| 65 | - cls, dsn: str | None = None, *, connect_timeout: float | None = None | |
| 66 | - ) -> "PsycopgClient": | |
| 67 | - """`ZEKA_PG_DSN` ile baglanir. DSN loglanmaz. | |
| 68 | - | |
| 69 | - `connect_timeout` saniyedir ve libpq'ye gecer: okul havuzlari istek | |
| 70 | - aninda acildigi icin, ulasilamayan bir veritabani sonsuza kadar | |
| 71 | - beklenmez (bkz. `tenants.py`). | |
| 72 | - """ | |
| 73 | - import psycopg | |
| 74 | - | |
| 75 | - target = dsn or os.environ.get("ZEKA_PG_DSN", "") | |
| 76 | - if not target: | |
| 77 | - raise PgError( | |
| 78 | - "ZEKA_PG_DSN tanimli degil; okul veritabanina baglanilamaz" | |
| 79 | - ) | |
| 80 | - # autocommit: transaction sinirlarini PgStore belirler, surucu degil. | |
| 81 | - kwargs: dict[str, Any] = {"autocommit": True} | |
| 82 | - if connect_timeout is not None: | |
| 83 | - kwargs["connect_timeout"] = max(1, int(connect_timeout)) | |
| 84 | - conn = await psycopg.AsyncConnection.connect(target, **kwargs) | |
| 85 | - log.info("veritabanina baglanildi (%s)", _describe(target)) | |
| 86 | - return cls(conn) | |
| 87 | - | |
| 88 | - async def execute(self, sql: str, params: Sequence[Any] = ()) -> None: | |
| 89 | - try: | |
| 90 | - async with self._conn.cursor() as cur: | |
| 91 | - await cur.execute(sql, tuple(params)) | |
| 92 | - except Exception as exc: | |
| 93 | - raise PgError(str(exc), statement=_head(sql)) from exc | |
| 94 | - | |
| 95 | - async def executemany( | |
| 96 | - self, sql: str, rows: Sequence[Sequence[Any]] | |
| 97 | - ) -> None: | |
| 98 | - if not rows: | |
| 99 | - return | |
| 100 | - try: | |
| 101 | - async with self._conn.cursor() as cur: | |
| 102 | - await cur.executemany(sql, [tuple(r) for r in rows]) | |
| 103 | - except Exception as exc: | |
| 104 | - raise PgError(str(exc), statement=_head(sql)) from exc | |
| 105 | - | |
| 106 | - async def fetch( | |
| 107 | - self, sql: str, params: Sequence[Any] = () | |
| 108 | - ) -> list[tuple[Any, ...]]: | |
| 109 | - try: | |
| 110 | - async with self._conn.cursor() as cur: | |
| 111 | - await cur.execute(sql, tuple(params)) | |
| 112 | - return list(await cur.fetchall()) | |
| 113 | - except Exception as exc: | |
| 114 | - raise PgError(str(exc), statement=_head(sql)) from exc | |
| 115 | - | |
| 116 | - def transaction(self) -> Any: | |
| 117 | - return self._conn.transaction() | |
| 118 | - | |
| 119 | - async def close(self) -> None: | |
| 120 | - await self._conn.close() | |
| 121 | - | |
| 122 | - | |
| 123 | -def _head(sql: str) -> str: | |
| 124 | - """Ifadenin ilk satiri — hata mesajina konacak kadari. | |
| 125 | - | |
| 126 | - Tam ifade YAZILMAZ: toplu yazimda binlerce satirlik parametre tasiyabilir | |
| 127 | - ve o parametreler ogrenci verisidir. | |
| 128 | - """ | |
| 129 | - for line in sql.strip().splitlines(): | |
| 130 | - stripped = line.strip() | |
| 131 | - if stripped: | |
| 132 | - return stripped[:120] | |
| 133 | - return "" | |
| 134 | - | |
| 135 | - | |
| 136 | -def _describe(dsn: str) -> str: | |
| 137 | - """DSN'in loglanabilir kismi: host/port/veritabani. | |
| 138 | - | |
| 139 | - Kullanici adi ve parola **hicbir kosulda** donmez. Bir baglanti hatasinin | |
| 140 | - log satirinda parola gormek, bu servisin sir tarama testinin (`ci-sir-tara.py`) | |
| 141 | - tam olarak aradigi sey. | |
| 142 | - """ | |
| 143 | - try: | |
| 144 | - import urllib.parse | |
| 145 | - | |
| 146 | - parsed = urllib.parse.urlsplit(dsn) | |
| 147 | - if parsed.hostname: | |
| 148 | - port = f":{parsed.port}" if parsed.port else "" | |
| 149 | - return f"{parsed.hostname}{port}{parsed.path}" | |
| 150 | - except Exception: # noqa: BLE001 | |
| 151 | - pass | |
| 152 | - return "<cozumlenemedi>" |
service/src/pipeline.pymodified+23 -2
| @@ -43,7 +43,7 @@ from .compute import recommend as recommend_mod | ||
| 43 | 43 | from .compute import study as study_mod |
| 44 | 44 | from .compute import submission as submission_mod |
| 45 | 45 | from .compute.model import Confidence, Recommendation, StudentSummary |
| 46 | -from .store import Store | |
| 46 | +from .store import SchoolStore | |
| 47 | 47 | |
| 48 | 48 | log = logging.getLogger(__name__) |
| 49 | 49 | |
| @@ -74,6 +74,21 @@ class RunResult: | ||
| 74 | 74 | """`{school}_{YYYY-MM-DD}` — TR tarihi (`MODULLER.md` §4.4).""" |
| 75 | 75 | return f"{self.school}_{clock.tr_date_key(self.started_at)}" |
| 76 | 76 | |
| 77 | + @property | |
| 78 | + def write_failed(self) -> bool: | |
| 79 | + """Depo yazması düştü mü? | |
| 80 | + | |
| 81 | + `pipeline.run_school` bir grup yazmayı atladığında `store` işaretini | |
| 82 | + `failed_modules`'a koyar (bkz. aşağıda, yazma bölümü). Zamanlayıcı bu | |
| 83 | + işarete bakarak o okulun GÜNÜNÜ KAPATMAZ: aksi halde köprü arızası, | |
| 84 | + yazılmamış bir geceyi kalıcı bir boşluğa çevirirdi. | |
| 85 | + | |
| 86 | + Kalıcı kayıt bu işaretin kendisidir: `failed_modules` koşu defteri | |
| 87 | + satırıyla birlikte backend'e yazılır (`insight.run.upsert`) ve bir | |
| 88 | + sonraki tur/operatör oradan okur. | |
| 89 | + """ | |
| 90 | + return "store" in self.failed_modules | |
| 91 | + | |
| 77 | 92 | def as_row(self) -> dict[str, Any]: |
| 78 | 93 | row = dataclasses.asdict(self) |
| 79 | 94 | row.pop("school", None) |
| @@ -168,7 +183,7 @@ def _summary_confidence(marks_profile: dict[str, Any]) -> Confidence: | ||
| 168 | 183 | |
| 169 | 184 | async def run_school( |
| 170 | 185 | source: Any, |
| 171 | - store: Store, | |
| 186 | + store: SchoolStore, | |
| 172 | 187 | school: str, |
| 173 | 188 | *, |
| 174 | 189 | now_ms: int, |
| @@ -360,6 +375,12 @@ async def run_school( | ||
| 360 | 375 | result.status = "failed" |
| 361 | 376 | else: |
| 362 | 377 | result.status = "ok" |
| 378 | + # Yazma düştüyse koşu "ok" DEĞİLDİR: hesaplanan satırların bir kısmı | |
| 379 | + # yazılamadı ve bu, deftere bakan birinin görebilmesi gereken bir eksik. | |
| 380 | + # Durum `partial`'a iner; asıl kalıcı işaret `failed_modules`'tadır ve | |
| 381 | + # zamanlayıcı onu görünce o okulun GÜNÜNÜ KAPATMAZ (`write_failed`). | |
| 382 | + if result.write_failed and result.status == "ok": | |
| 383 | + result.status = "partial" | |
| 363 | 384 | |
| 364 | 385 | await store.write_run(result.as_row(), result.run_key()) |
| 365 | 386 | return result |
service/src/protocol.pymodified+143 -2
| @@ -20,8 +20,11 @@ Akis disiplini (`protocol.rs:9-34`): | ||
| 20 | 20 | cerceve DEGILDIR, dolayisiyla cerceve boyut kapagina tabi degildir |
| 21 | 21 | (`protocol.rs:26-31`). |
| 22 | 22 | |
| 23 | -Iki istemci baslatimli sekil, zorunlu alaniyla ayirt edilir: `ApiRequest`'te | |
| 24 | -`path`, `BlobRequest`'te `file` vardir (`protocol.rs:34`, `server.rs:481-497`). | |
| 23 | +Uc istemci baslatimli sekil, zorunlu alaniyla ayirt edilir: `ApiRequest`'te | |
| 24 | +`path`, `BlobRequest`'te `file`, `CapabilityRequest`'te `capability` vardir | |
| 25 | +(`protocol.rs:34`, `server.rs:481-497`). Ilk ikisi okulun KENDI API'sini | |
| 26 | +okur; ucuncusu backend'in bir operasyonunu kosturur -- ZEKA'nin veritabani | |
| 27 | +erisimi olmadigi icin yazma yolu YALNIZCA budur. | |
| 25 | 28 | |
| 26 | 29 | Okul kapsami (`protocol.rs:36-47`): her istek cercevesi okulunu slug ile |
| 27 | 30 | adlandirir, her cevap onu yankilar. `Hello` KASITLI olarak okul tasimaz -- |
| @@ -237,6 +240,21 @@ class BlobRefused(ApiRefused): | ||
| 237 | 240 | """`BlobResponse{status:"err"}`.""" |
| 238 | 241 | |
| 239 | 242 | |
| 243 | +#: Yeniden denenmeye deger yetenek redleri. `timed_out` BURADA: yazinin | |
| 244 | +#: dusup dusmedigi BILINMIYOR, o yuzden ayni cerceve taze kimlikle yeniden | |
| 245 | +#: gonderilir -- `insight.*` yazmalari idempotenttir: ayni satir ayni | |
| 246 | +#: degerlerle yeniden yazilir. | |
| 247 | +RETRYABLE_CAPABILITY_CODES = ("unavailable", "school_suspended", "timed_out") | |
| 248 | + | |
| 249 | + | |
| 250 | +class CapabilityRefused(ApiRefused): | |
| 251 | + """`CapabilityResponse{status:"err"}` — servisin actigi yetenek cagrisi.""" | |
| 252 | + | |
| 253 | + @property | |
| 254 | + def retryable(self) -> bool: | |
| 255 | + return self.code in RETRYABLE_CAPABILITY_CODES | |
| 256 | + | |
| 257 | + | |
| 240 | 258 | class CapabilityError(Exception): |
| 241 | 259 | """Yetenek isleyicisinin ele alinmis hatasi; `Response{status:"err"}` olur.""" |
| 242 | 260 | |
| @@ -642,6 +660,129 @@ def parse_api_response(raw: Any) -> ApiResponse: | ||
| 642 | 660 | return ApiResponse.from_wire(raw) |
| 643 | 661 | |
| 644 | 662 | |
| 663 | +# =========================================================================== | |
| 664 | +# Yetenek cagrisi -- servis backend'in bir operasyonunu BOYLE cagirir | |
| 665 | +# =========================================================================== | |
| 666 | +# | |
| 667 | +# ZEKA'nin veritabani erisimi YOKTUR; hesapladigi satirlar backend'e bu | |
| 668 | +# cerceveyle yazilir. `ApiRequest`'ten ayrimi `capability` alanidir ve YONU | |
| 669 | +# terstir: `ApiRequest` okulun KENDI API'sini okur, bu cerceve backend'in | |
| 670 | +# bir operasyonunu kosturur (yazma dahil). | |
| 671 | +# | |
| 672 | +# KIMLIK: `id` ULID'dir ve cevapta AYNEN doner; eslesme akis kimligiyle | |
| 673 | +# kurulur, `id` yalniz loglarin yan yana okunmasi icindir (`protocol.rs:136`). | |
| 674 | + | |
| 675 | + | |
| 676 | +@dataclass(frozen=True) | |
| 677 | +class CapabilityRequest: | |
| 678 | + """Servisin actigi akista yazdigi tek yetenek cagrisi.""" | |
| 679 | + | |
| 680 | + id: str | |
| 681 | + capability: str | |
| 682 | + school: str | |
| 683 | + payload: dict[str, Any] | |
| 684 | + | |
| 685 | + def to_wire(self) -> dict[str, Any]: | |
| 686 | + return { | |
| 687 | + "id": self.id, | |
| 688 | + "capability": self.capability, | |
| 689 | + "school": self.school, | |
| 690 | + "payload": self.payload, | |
| 691 | + } | |
| 692 | + | |
| 693 | + | |
| 694 | +def build_capability_request( | |
| 695 | + request_id: str, | |
| 696 | + capability: str, | |
| 697 | + school: str, | |
| 698 | + payload: dict[str, Any] | None = None, | |
| 699 | +) -> dict[str, Any]: | |
| 700 | + """`CapabilityRequest` cercevesi kur; kablonun kendi kurallarini uygula. | |
| 701 | + | |
| 702 | + - `capability` zorunludur ve bos olamaz: adsiz bir cagri backend'de | |
| 703 | + `malformed` olur, burada ise tele hic cikmaz. | |
| 704 | + - `payload` bir NESNE olmali (dizi ya da null degil): her operasyonun | |
| 705 | + sozlesmesi bir sozluktur. | |
| 706 | + - `school` zorunludur ama BOS olabilir: deployment olcekli tek operasyon | |
| 707 | + (`insight.schools.list`) okul adlandirmaz ve backend onu cozmez. | |
| 708 | + """ | |
| 709 | + if not isinstance(capability, str) or not capability.strip(): | |
| 710 | + raise ApiRefused(ApiErrorCode.MALFORMED, "yetenek adi zorunlu") | |
| 711 | + if payload is None: | |
| 712 | + payload = {} | |
| 713 | + if not isinstance(payload, dict): | |
| 714 | + raise ApiRefused( | |
| 715 | + ApiErrorCode.MALFORMED, | |
| 716 | + f"payload bir nesne olmali, alinan: {type(payload).__name__}", | |
| 717 | + ) | |
| 718 | + if not isinstance(school, str): | |
| 719 | + raise ApiRefused(ApiErrorCode.MALFORMED, "okul alani metin olmali") | |
| 720 | + return CapabilityRequest(request_id, capability.strip(), school, payload).to_wire() | |
| 721 | + | |
| 722 | + | |
| 723 | +@dataclass(frozen=True) | |
| 724 | +class CapabilityResponse: | |
| 725 | + """Backend'in yetenek cagrisina verdigi TEK cevap cercevesi. | |
| 726 | + | |
| 727 | + Etiket alani `status` -- `ApiResponse`'un `outcome`'undan farkli, cunku | |
| 728 | + backend'in sunucu->istemci `Response` cercevesi de `status` kullanir; | |
| 729 | + ayni adi tasimak iki yonu yan yana okunur kilar. | |
| 730 | + """ | |
| 731 | + | |
| 732 | + status: str | |
| 733 | + id: str | |
| 734 | + school: str | |
| 735 | + payload: dict[str, Any] = field(default_factory=dict) | |
| 736 | + code: str = "" | |
| 737 | + message: str = "" | |
| 738 | + | |
| 739 | + @property | |
| 740 | + def ok(self) -> bool: | |
| 741 | + return self.status == "ok" | |
| 742 | + | |
| 743 | + @staticmethod | |
| 744 | + def from_wire(raw: Any) -> "CapabilityResponse": | |
| 745 | + if not isinstance(raw, dict): | |
| 746 | + raise FrameMalformed(f"yetenek cevabi nesne degil: {type(raw).__name__}") | |
| 747 | + status = _require_str(raw, "status") | |
| 748 | + if status not in ("ok", "err"): | |
| 749 | + raise FrameMalformed(f"bilinmeyen yetenek cevabi durumu: {status!r}") | |
| 750 | + payload = raw.get("payload") | |
| 751 | + if payload is None: | |
| 752 | + payload = {} | |
| 753 | + if not isinstance(payload, dict): | |
| 754 | + raise FrameMalformed("yetenek cevabinin payload'i nesne degil") | |
| 755 | + code = raw.get("code") | |
| 756 | + message = raw.get("message") | |
| 757 | + return CapabilityResponse( | |
| 758 | + status=status, | |
| 759 | + id=str(raw.get("id") or ""), | |
| 760 | + school=raw.get("school") if isinstance(raw.get("school"), str) else "", | |
| 761 | + payload=payload, | |
| 762 | + code=code if isinstance(code, str) else "", | |
| 763 | + message=message if isinstance(message, str) else "", | |
| 764 | + ) | |
| 765 | + | |
| 766 | + def raise_for_status(self, capability: str) -> dict[str, Any]: | |
| 767 | + """`ok` ise payload'i dondur; `err` ise `CapabilityRefused` firlat. | |
| 768 | + | |
| 769 | + `status` ONCE okunur: reddi basari sayan bir yol, sessiz yazma | |
| 770 | + kaybinin ta kendisidir. | |
| 771 | + """ | |
| 772 | + if self.ok: | |
| 773 | + return self.payload | |
| 774 | + raise CapabilityRefused( | |
| 775 | + self.code or "internal", | |
| 776 | + self.message or "backend yetenek cagrisini reddetti", | |
| 777 | + self.school, | |
| 778 | + self.id, | |
| 779 | + ) | |
| 780 | + | |
| 781 | + | |
| 782 | +def parse_capability_response(raw: Any) -> CapabilityResponse: | |
| 783 | + return CapabilityResponse.from_wire(raw) | |
| 784 | + | |
| 785 | + | |
| 645 | 786 | def _coerce_status(value: Any) -> int: |
| 646 | 787 | if isinstance(value, bool): |
| 647 | 788 | return int(value) |
service/src/report/__init__.pymodified+6 -6
| @@ -1,8 +1,9 @@ | ||
| 1 | 1 | """Rapor katmanı — ZEKA'nın ürettiği satırları **okunabilir** hale getirir. |
| 2 | 2 | |
| 3 | 3 | ZEKA sonuç üretiyor ama frontend değişmeyeceği için teslim biçimi rapordur. |
| 4 | -Bu paket yalnız ZEKA'nın kendi beş tablosunu **okur**; köprüye gitmez, okul | |
| 5 | -veritabanına dokunmaz, hiçbir şeye yazmaz. | |
| 4 | +Bu paket ZEKA'nın ürettiği satırları okur; köprüye ve veritabanına | |
| 5 | +gitmez, hiçbir şeye yazmaz. Canlı bir dağıtımın satırlarını okumak | |
| 6 | +backend'in `/insights` uçlarının işidir. | |
| 6 | 7 | |
| 7 | 8 | Dört rapor: `okul` (yönetim), `ogretmen`, `ogrenci` (öğrenci/veli), `ham` |
| 8 | 9 | (teknik ekip). Üç biçim: JSON, HTML (tek dosya, basılabilir), CSV. |
| @@ -12,7 +13,7 @@ Belge: `docs/RAPORLAR.md`. Sözleşme: `docs/CIKTI-SOZLESMESI.md`. | ||
| 12 | 13 | |
| 13 | 14 | from .build import BUILDERS |
| 14 | 15 | from .build import build as build_report |
| 15 | -from .capture import CapturingClient | |
| 16 | +from .capture import CapturingCaller | |
| 16 | 17 | from .document import Report |
| 17 | 18 | from .gate import ( |
| 18 | 19 | REPORT_TYPES, |
| @@ -23,13 +24,12 @@ from .gate import ( | ||
| 23 | 24 | StudentFacingBundle, |
| 24 | 25 | ) |
| 25 | 26 | from .load import load_bundle |
| 26 | -from .reader import DbReader, MemoryReader | |
| 27 | +from .reader import MemoryReader | |
| 27 | 28 | from .writer import write |
| 28 | 29 | |
| 29 | 30 | __all__ = [ |
| 30 | 31 | "BUILDERS", |
| 31 | - "CapturingClient", | |
| 32 | - "DbReader", | |
| 32 | + "CapturingCaller", | |
| 33 | 33 | "MemoryReader", |
| 34 | 34 | "REPORT_TYPES", |
| 35 | 35 | "Report", |
service/src/report/build.pymodified+1 -1
| @@ -18,7 +18,7 @@ Kurucuların uyduğu değişmezler (hepsi `docs/CIKTI-SOZLESMESI.md`'den): | ||
| 18 | 18 | olgusu da ibareye döner). |
| 19 | 19 | 5. **Kapatılmış** ve **süresi geçmiş** satırlar hiç görünmez. |
| 20 | 20 | 6. **Segment karşıtlık olarak anlatılır**; ham doğruluk okunmaz bile |
| 21 | - (`reader.py` SELECT'inde `accuracy` yoktur). | |
| 21 | + (`reader.py` izdüşümünde `accuracy` yoktur). | |
| 22 | 22 | 7. **Öğrenci raporunda akran sıralaması yoktur**: karşılaştırma öğrencinin |
| 23 | 23 | kendi geçmişi ve **anonim** şube dağılımıdır (tek sayı: şube ortalaması). |
| 24 | 24 | """ |
service/src/report/capture.pymodified+85 -29
| @@ -2,49 +2,105 @@ | ||
| 2 | 2 | |
| 3 | 3 | Konteyner her yerde ayakta değildir (CI'ın bir kısmında, geliştiricinin |
| 4 | 4 | makinesinde, bu testlerin koştuğu ortamda). Raporun "veri yoksa çöker mi, |
| 5 | -fikstürle çalışır mı" sorusu ayakta bir SurrealDB'ye bağlı olmamalıdır. | |
| 5 | +fikstürle çalışır mı" sorusu bir veritabanına bağlı olmamalıdır — zaten | |
| 6 | +ZEKA'nın veritabanı YOKTUR. | |
| 6 | 7 | |
| 7 | -`CapturingClient`, `store.Store`'un ürettiği **gerçek** UPSERT ifadelerini | |
| 8 | -yakalar ve satırları bellekte tutar. Yani hat baştan sona koşar (`pipeline` | |
| 9 | -→ `store`), yalnız taşıma değişir. Böylece rapor, gerçek koşunun yazdığı | |
| 10 | -satırlarla sınanır — elle kurulmuş sahte satırlarla değil. | |
| 8 | +`CapturingCaller`, `BridgeStore`'un gönderdiği **gerçek** `insight.*` | |
| 9 | +çağrılarını yakalar ve satırları bellekte tutar. Yani hat baştan sona koşar | |
| 10 | +(`pipeline` → `store`), yalnız taşıma değişir: köprüye bir tek bayt gitmez. | |
| 11 | +Böylece rapor, gerçek koşunun ürettiği satırlarla sınanır — elle kurulmuş | |
| 12 | +sahte satırlarla değil. | |
| 11 | 13 | |
| 12 | -Sınır: bu istemci bir veritabanı **değildir**. Sorguları (SELECT) boş | |
| 13 | -döndürür; süpürme ve mezuniyet temizliği (DELETE) yok sayılır. Raporun | |
| 14 | -okuma yolu bu satırlar üzerinde `MemoryReader` ile koşar. | |
| 14 | +Sınır: bu bir köprü **değildir**. Süpürme ve mezuniyet temizliği başarılı | |
| 15 | +sayılır (silmeleri yok sayılır), okuma yolu bu satırlar üzerinde | |
| 16 | +`MemoryReader` ile koşar. | |
| 15 | 17 | """ |
| 16 | 18 | |
| 17 | 19 | from __future__ import annotations |
| 18 | 20 | |
| 19 | -import re | |
| 20 | 21 | from typing import Any |
| 21 | 22 | |
| 23 | +from ..store import ( | |
| 24 | + CAP_PROFILE, | |
| 25 | + CAP_PURGE, | |
| 26 | + CAP_RECOMMENDATION, | |
| 27 | + CAP_RUN, | |
| 28 | + CAP_SEGMENT, | |
| 29 | + CAP_SCHOOLS, | |
| 30 | + CAP_SUMMARY, | |
| 31 | + CAP_SWEEP, | |
| 32 | + PURGE_TABLES, | |
| 33 | + SWEEP_TABLES, | |
| 34 | +) | |
| 22 | 35 | from .reader import MemoryReader |
| 23 | 36 | |
| 24 | -_UPSERT = re.compile(r"UPSERT type::record\('([A-Za-z_][A-Za-z0-9_]*)', \$k(\d+)\)") | |
| 25 | 37 | |
| 26 | - | |
| 27 | -class CapturingClient: | |
| 28 | - """`store.DbClient` protokolünü karşılayan bellek içi yazma hedefi.""" | |
| 38 | +class CapturingCaller: | |
| 39 | + """`BridgeCaller` şeklini karşılayan bellek içi yazma hedefi.""" | |
| 29 | 40 | |
| 30 | 41 | def __init__(self) -> None: |
| 31 | - #: tablo → kayıt anahtarı → satır | |
| 42 | + #: tablo → kayıt anahtarı → satır (okuyucunun beklediği adlarla; | |
| 43 | + #: köprünün `zeka_*` tablo adları DEĞİL, raporun gördüğü adlar). | |
| 32 | 44 | self.tables: dict[str, dict[str, dict[str, Any]]] = {} |
| 33 | - self.statement_count = 0 | |
| 34 | - | |
| 35 | - async def query(self, sql: str, variables: dict[str, Any]) -> Any: | |
| 36 | - self.statement_count += 1 | |
| 37 | - for table, index in _UPSERT.findall(sql): | |
| 38 | - key = str(variables.get(f"k{index}")) | |
| 39 | - row = variables.get(f"v{index}") | |
| 40 | - if not isinstance(row, dict): | |
| 41 | - continue | |
| 42 | - bucket = self.tables.setdefault(table, {}) | |
| 43 | - # MERGE ve CONTENT ayrımı burada önemsizdir: tek koşuda aynı | |
| 44 | - # anahtar bir kez yazılır. Yine de birleştirme yapılır ki iki | |
| 45 | - # koşuluk bir senaryo satırı sıfırlamasın. | |
| 46 | - bucket.setdefault(key, {}).update(row) | |
| 47 | - return [] | |
| 45 | + #: Gönderilen her çağrı: (yetenek, okul, payload). | |
| 46 | + self.calls: list[tuple[str, str, dict[str, Any]]] = [] | |
| 47 | + | |
| 48 | + def _put(self, table: str, key: str, row: dict[str, Any]) -> None: | |
| 49 | + self.tables.setdefault(table, {})[key] = row | |
| 50 | + | |
| 51 | + async def call( | |
| 52 | + self, capability: str, school: str, payload: dict[str, Any] | |
| 53 | + ) -> dict[str, Any]: | |
| 54 | + self.calls.append((capability, school, payload)) | |
| 55 | + | |
| 56 | + if capability == CAP_SCHOOLS: | |
| 57 | + return {"schools": [school] if school else []} | |
| 58 | + if capability == CAP_SWEEP: | |
| 59 | + return {"tables": {table: True for table in SWEEP_TABLES}} | |
| 60 | + if capability == CAP_PURGE: | |
| 61 | + return {"tables": {table: True for table in PURGE_TABLES}} | |
| 62 | + | |
| 63 | + rows = payload.get("rows") or [] | |
| 64 | + if capability == CAP_SUMMARY: | |
| 65 | + for row in rows: | |
| 66 | + student = str(row.get("student")) | |
| 67 | + self._put("student_summary", student, {**row, "school": school}) | |
| 68 | + for index, item in enumerate(row.get("attention") or []): | |
| 69 | + self._put( | |
| 70 | + "attention_item", | |
| 71 | + f"{student}_{index}", | |
| 72 | + {**item, "student": student, "school": school, "ord": index}, | |
| 73 | + ) | |
| 74 | + return {"written": len(rows)} | |
| 75 | + if capability == CAP_RECOMMENDATION: | |
| 76 | + for row in rows: | |
| 77 | + key = "_".join( | |
| 78 | + str(row.get(name)) | |
| 79 | + for name in ("audience", "product", "rule_id", "about", "scope") | |
| 80 | + ) | |
| 81 | + self._put("recommendation", key, {**row, "school": school}) | |
| 82 | + return {"written": len(rows), "rejected": 0} | |
| 83 | + if capability == CAP_SEGMENT: | |
| 84 | + for row in rows: | |
| 85 | + self._put( | |
| 86 | + "question_segment", | |
| 87 | + str(row.get("question")), | |
| 88 | + {**row, "school": school}, | |
| 89 | + ) | |
| 90 | + return {"written": len(rows)} | |
| 91 | + if capability == CAP_PROFILE: | |
| 92 | + for row in rows: | |
| 93 | + key = "_".join( | |
| 94 | + str(row.get(name)) for name in ("student", "dimension", "label") | |
| 95 | + ) | |
| 96 | + self._put("student_segment_profile", key, {**row, "school": school}) | |
| 97 | + return {"written": len(rows)} | |
| 98 | + if capability == CAP_RUN: | |
| 99 | + run = payload.get("run") or {} | |
| 100 | + self._put("insight_run", str(run.get("run_day")), {**run, "school": school}) | |
| 101 | + return {"written": 1} | |
| 102 | + # `insight.pending.list` (ve tanınmayan bir yetenek). | |
| 103 | + return {"students": []} | |
| 48 | 104 | |
| 49 | 105 | def as_tables(self) -> dict[str, list[dict[str, Any]]]: |
| 50 | 106 | return {name: list(rows.values()) for name, rows in self.tables.items()} |
service/src/report/gate.pymodified+1 -1
| @@ -19,7 +19,7 @@ Burada kapı **tip düzeyindedir**: | ||
| 19 | 19 | 2. `StudentFacingSummary` ile `StaffSummary` arasında **kalıtım yoktur**. |
| 20 | 20 | Kalıtım olsaydı `isinstance(staff, StudentFacing)` doğru dönerdi ve kapı |
| 21 | 21 | kağıt üstünde kalırdı. İki bağımsız tip, tek yönlü dönüşüm. |
| 22 | -3. Veri **okunurken** de kapı uygulanır: öğrenci raporu için üretilen SELECT | |
| 22 | +3. Veri **okunurken** de kapı uygulanır: öğrenci raporu için üretilen satır izdüşümü | |
| 23 | 23 | ifadesinde `attention` sütunu **hiç geçmez** (`SUMMARY_COLUMNS_STUDENT`). |
| 24 | 24 | Yani satır veritabanından bile çıkmaz. |
| 25 | 25 | 4. `build_student_report` yalnız `StudentFacingBundle` kabul eder; personel |
service/src/report/reader.pymodified+10 -119
| @@ -1,19 +1,16 @@ | ||
| 1 | -"""Rapor katmanının **okuma** yüzeyi — ZEKA'nın kendi beş tablosu. | |
| 1 | +"""Rapor katmanının **okuma** yüzeyi. | |
| 2 | 2 | |
| 3 | -Köprüye gidilmez, okul veritabanına dokunulmaz: rapor yalnız gece koşusunun | |
| 4 | -ZEKA veritabanına yazdığı satırları okur (`docs/CIKTI-SOZLESMESI.md` §0). | |
| 3 | +Köprü okumaları ve zeka veritabanı BURADA YOKTUR: ZEKA'nın kendi veritabanı | |
| 4 | +yok (değişmez kural: bir AI servisi uygulama veritabanına asla doğrudan | |
| 5 | +erişmez), o yüzden rapor katmanı yalnız bir `Reader` protokolü tanımlar ve | |
| 6 | +bellek içi bir uygulama verir: | |
| 5 | 7 | |
| 6 | -Sorgu kalıpları sözleşmenin §6'sındandır. Oradaki **en önemli tuzak** burada | |
| 7 | -da geçerlidir: iki nokta taşıyan her kimlik karşılaştırması `type::string()` | |
| 8 | -ile sarılır, yoksa SurrealDB 3 metni uçta `record`'a çevirir ve sorgu | |
| 9 | -**sessizce sıfır satır** döndürür. | |
| 8 | +* `MemoryReader` — sözlükten okuyan uygulama; fikstür yolu ve testler bunu | |
| 9 | + kullanır. Sütun izdüşümünü (`columns`) **gerçekten uygular**; böylece | |
| 10 | + dikkat listesi kapısı testte de veri düzeyinde sınanır. | |
| 10 | 11 | |
| 11 | -İki uygulama vardır: | |
| 12 | - | |
| 13 | -* `DbReader` — gerçek SurrealDB (`store.SurrealHttpClient` ya da `DbClient`). | |
| 14 | -* `MemoryReader` — sözlükten okuyan sahte; testler ve fikstür yolu için. | |
| 15 | - Sütun izdüşümünü (`columns`) **gerçekten uygular**; böylece dikkat listesi | |
| 16 | - kapısı testte de veri düzeyinde sınanır. | |
| 12 | +Canlı bir dağıtımın satırlarını okumak backend'in `/insights` uçlarının | |
| 13 | +işidir; buradan geçen bir okuma yolu yoktur ve olmayacaktır. | |
| 17 | 14 | """ |
| 18 | 15 | |
| 19 | 16 | from __future__ import annotations |
| @@ -52,112 +49,6 @@ class Reader(Protocol): | ||
| 52 | 49 | async def question_segments(self, school: str) -> list[dict[str, Any]]: ... |
| 53 | 50 | |
| 54 | 51 | |
| 55 | -def _rows(result: Any) -> list[dict[str, Any]]: | |
| 56 | - """SurrealDB `/rpc` cevabından satır listesini çıkarır. | |
| 57 | - | |
| 58 | - Cevap iki katmanlıdır: ifade listesi → `result` listesi → satır. | |
| 59 | - Sahte istemciler düz liste döndürebilir; o da kabul edilir. | |
| 60 | - """ | |
| 61 | - if not isinstance(result, list): | |
| 62 | - return [] | |
| 63 | - out: list[dict[str, Any]] = [] | |
| 64 | - for item in result: | |
| 65 | - if isinstance(item, dict) and "result" in item: | |
| 66 | - inner = item.get("result") | |
| 67 | - if isinstance(inner, list): | |
| 68 | - out.extend(r for r in inner if isinstance(r, dict)) | |
| 69 | - elif isinstance(item, dict): | |
| 70 | - out.append(item) | |
| 71 | - return out | |
| 72 | - | |
| 73 | - | |
| 74 | -class DbReader: | |
| 75 | - """Gerçek ZEKA veritabanından okur. Yazma yolu **yoktur**.""" | |
| 76 | - | |
| 77 | - def __init__(self, client: Any) -> None: | |
| 78 | - self._client = client | |
| 79 | - #: Çalıştırılan SurrealQL ifadeleri — kapı testinin kanıtı. | |
| 80 | - self.statements: list[str] = [] | |
| 81 | - | |
| 82 | - async def _query(self, sql: str, variables: dict[str, Any]) -> list[dict[str, Any]]: | |
| 83 | - self.statements.append(sql) | |
| 84 | - return _rows(await self._client.query(sql, variables)) | |
| 85 | - | |
| 86 | - async def summaries( | |
| 87 | - self, school: str, *, columns: tuple[str, ...], student: str | None = None | |
| 88 | - ) -> list[dict[str, Any]]: | |
| 89 | - """`student_summary` — **sütun listesi çağırandan gelir**. | |
| 90 | - | |
| 91 | - Öğrenci raporunda `attention` bu listede yoktur; satır veritabanından | |
| 92 | - dikkat listesi taşımadan çıkar (`gate.py` başı). | |
| 93 | - """ | |
| 94 | - select = ", ".join(columns) | |
| 95 | - sql = f"SELECT {select} FROM student_summary WHERE school = $school" | |
| 96 | - variables: dict[str, Any] = {"school": school} | |
| 97 | - if student is not None: | |
| 98 | - sql += " AND student = type::string($student)" | |
| 99 | - variables["student"] = student | |
| 100 | - return await self._query(sql + ";", variables) | |
| 101 | - | |
| 102 | - async def recommendations( | |
| 103 | - self, | |
| 104 | - school: str, | |
| 105 | - *, | |
| 106 | - audience: str | None = None, | |
| 107 | - audience_role: str | None = None, | |
| 108 | - ) -> list[dict[str, Any]]: | |
| 109 | - sql = "SELECT * FROM recommendation WHERE school = $school" | |
| 110 | - variables: dict[str, Any] = {"school": school} | |
| 111 | - if audience is not None: | |
| 112 | - sql += " AND audience = type::string($audience)" | |
| 113 | - variables["audience"] = audience | |
| 114 | - if audience_role is not None: | |
| 115 | - sql += " AND audience_role = $role" | |
| 116 | - variables["role"] = audience_role | |
| 117 | - return await self._query(sql + ";", variables) | |
| 118 | - | |
| 119 | - async def segment_profiles( | |
| 120 | - self, school: str, *, student: str | None = None | |
| 121 | - ) -> list[dict[str, Any]]: | |
| 122 | - sql = ( | |
| 123 | - "SELECT school, student, dimension, label, n_answers, contrast, " | |
| 124 | - "confidence, computed_at FROM student_segment_profile " | |
| 125 | - "WHERE school = $school" | |
| 126 | - ) | |
| 127 | - variables: dict[str, Any] = {"school": school} | |
| 128 | - if student is not None: | |
| 129 | - sql += " AND student = type::string($student)" | |
| 130 | - variables["student"] = student | |
| 131 | - return await self._query(sql + ";", variables) | |
| 132 | - | |
| 133 | - async def runs(self, school: str, *, limit: int = 5) -> list[dict[str, Any]]: | |
| 134 | - sql = ( | |
| 135 | - "SELECT * FROM insight_run WHERE school = $school " | |
| 136 | - f"ORDER BY started_at DESC LIMIT {int(limit)};" | |
| 137 | - ) | |
| 138 | - return await self._query(sql, {"school": school}) | |
| 139 | - | |
| 140 | - async def question_segments(self, school: str) -> list[dict[str, Any]]: | |
| 141 | - select = ", ".join( | |
| 142 | - ( | |
| 143 | - "question", | |
| 144 | - "exam", | |
| 145 | - "course", | |
| 146 | - "subject", | |
| 147 | - "bilissel_talep", | |
| 148 | - "dikkat_tuzagi", | |
| 149 | - "okuma_yuku", | |
| 150 | - "adim_sayisi", | |
| 151 | - "confidence", | |
| 152 | - "downstream_dimensions", | |
| 153 | - "experimental_dimensions", | |
| 154 | - "computed_at", | |
| 155 | - ) | |
| 156 | - ) | |
| 157 | - sql = f"SELECT {select} FROM question_segment WHERE school = $school;" | |
| 158 | - return await self._query(sql, {"school": school}) | |
| 159 | - | |
| 160 | - | |
| 161 | 52 | class MemoryReader: |
| 162 | 53 | """Sözlükten okuyan `Reader` — testler ve fikstür yolu. |
| 163 | 54 |
service/src/scheduler.pymodified+28 -3
| @@ -35,7 +35,12 @@ Tasarım kararları (`MODULLER.md` §2.12) | ||
| 35 | 35 | Tek bir `store` nesnesi paylaşılmaz — paylaşılsaydı bütün okulların satırı |
| 36 | 36 | ilk okulun veritabanına düşerdi. |
| 37 | 37 | * **Günde bir kez.** Bir okul için o TR gününde koşu yapıldıysa tekrar |
| 38 | - yapılmaz. | |
| 38 | + yapılmaz. **Tek istisna yazma arızasıdır** (`result.write_failed`): depo | |
| 39 | + çağrıları düşen bir koşu günü KAPATMAZ, sonraki tik aynı okulu yeniden | |
| 40 | + dener. Aksi halde bir köprü arızası, o gecenin verisini bir sonraki tura | |
| 41 | + (yarına) kadar kalıcı bir boşluğa çevirirdi. Bütçe yüzünden `partial` biten | |
| 42 | + koşu günü kapatır: kalan öğrenciler `pending_students` ile deftere yazılır | |
| 43 | + ve ertesi gece listenin BAŞINDAN devam edilir. | |
| 39 | 44 | * **Tek koşu güvencesi.** Süreç içi `asyncio.Lock`; tek süreç olduğu için |
| 40 | 45 | yeterli. İkinci savunma `insight_run` satırının varlığıdır. |
| 41 | 46 | * **Bir okul düşerse diğerleri etkilenmez** — `catch` + `warn` + sonraki okul. |
| @@ -127,6 +132,10 @@ class Scheduler: | ||
| 127 | 132 | """Bu okulda bir sonraki koşuya devredilen öğrenciler.""" |
| 128 | 133 | return list(self._pending.get(school, [])) |
| 129 | 134 | |
| 135 | + def failures(self) -> list[str]: | |
| 136 | + """Son turda düşen okullar — izolasyonun kanıtı buradan okunur.""" | |
| 137 | + return list(self._failures) | |
| 138 | + | |
| 130 | 139 | async def _listing(self) -> list[str]: |
| 131 | 140 | """Bu turun okul listesi: dizindeki aktif okullar ∩ filtre. |
| 132 | 141 | |
| @@ -180,7 +189,9 @@ class Scheduler: | ||
| 180 | 189 | # acilamayan okul dusen okuldur -- tur devam eder, `internal` |
| 181 | 190 | # diye bir seye donusmez. |
| 182 | 191 | try: |
| 183 | - store = await self._stores.store_for(school) | |
| 192 | + # `store_for` SENKRON: nesne kurmak bir kopru cagrisi | |
| 193 | + # degildir, ag beklemez. Okul nesnenin kimligidir. | |
| 194 | + store = self._stores.store_for(school) | |
| 184 | 195 | # Süreç yeniden başladıysa bellek içi `pending` boştur; |
| 185 | 196 | # devreden liste `insight_run` satırından okunur. |
| 186 | 197 | if school not in self._pending: |
| @@ -210,7 +221,21 @@ class Scheduler: | ||
| 210 | 221 | log.warning("okul düştü, tur devam ediyor (%s): %s", school, exc) |
| 211 | 222 | self._failures.append(school) |
| 212 | 223 | continue |
| 213 | - self._last_run_day[school] = day | |
| 224 | + # YAZILAMAYAN TUR GÜNÜ KAPATMAZ. Bir köprü arızası o gecenin | |
| 225 | + # verisini kalıcı olarak düşürmemelidir: damga konmazsa aynı | |
| 226 | + # gece penceresindeki sonraki tik (15 dk sonra) okulu yeniden | |
| 227 | + # dener ve köprü döndüyse satırlar yazılır. Kalıcı kayıt koşu | |
| 228 | + # defteridir: `failed_modules` içindeki `store`, ilk başarılı | |
| 229 | + # `insight.run.upsert` ile backend'e gider ve oradan okunur. | |
| 230 | + if result.write_failed: | |
| 231 | + log.warning( | |
| 232 | + "okul yazılamadı (durum=%s); gün KAPATILMADI, sonraki tik " | |
| 233 | + "yeniden denenecek: %s", | |
| 234 | + result.status, | |
| 235 | + school, | |
| 236 | + ) | |
| 237 | + else: | |
| 238 | + self._last_run_day[school] = day | |
| 214 | 239 | results.append(result) |
| 215 | 240 | # Bütçe aşan okul ertelenir: kalan öğrenciler saklanır. |
| 216 | 241 | if result.pending_students: |
service/src/segment/cli.pymodified+22 -28
| @@ -81,32 +81,32 @@ def cmd_stability(args) -> int: | ||
| 81 | 81 | |
| 82 | 82 | |
| 83 | 83 | def _store_for(args): |
| 84 | - """`--persist` icin depo nesnesi. | |
| 84 | + """`--persist` için KÖPRÜ deposu. | |
| 85 | 85 | |
| 86 | - `--db-url` verilmediyse `None` doner: donusum yapilir, satirlar SAYILIR, | |
| 87 | - ama hicbir sey yazilmaz. "Yazdim" demeden once gercekten yazabildigini | |
| 88 | - bilmek gerekir; sessizce bos bir istemciye yazmak bunun tersidir. | |
| 86 | + ZEKA'nın kendi veritabanı YOKTUR (değişmez kural: bir AI servisi | |
| 87 | + uygulama veritabanına asla doğrudan erişmez): etiketler ve profiller | |
| 88 | + `insight.*` yetenek çağrılarıyla backend'e yazılır. Bu yüzden burada | |
| 89 | + bir DSN bayrağı yoktur; köprü ayarları ortamdan gelir. | |
| 90 | + | |
| 91 | + `--persist` verilmezse `None` döner: dönüşüm yapılır, satırlar SAYILIR, | |
| 92 | + ama hiçbir şey yazılmaz. "Yazdım" demeden önce gerçekten yazabildiğini | |
| 93 | + bilmek gerekir; sessizce boş bir depoya yazmak bunun tersidir. | |
| 89 | 94 | """ |
| 90 | 95 | if not args.persist: |
| 91 | 96 | return None |
| 92 | - import os | |
| 93 | - | |
| 94 | - from ..store import Store | |
| 95 | - from .persist import build_client | |
| 97 | + if not args.school: | |
| 98 | + raise SystemExit("--persist için --school zorunlu (satırların yazılacağı okul)") | |
| 99 | + from .. import bridge | |
| 100 | + from ..config import Config, ConfigError | |
| 101 | + from ..store import BridgeStore | |
| 96 | 102 | |
| 97 | - url = args.db_url or os.environ.get("ZEKA_DB_HTTP_URL", "") | |
| 98 | - if not url: | |
| 99 | - print("[segment] --persist verildi ama --db-url yok: KURU KOSU " | |
| 100 | - "(hicbir sey yazilmayacak)", file=sys.stderr) | |
| 101 | - return None | |
| 102 | - client = build_client( | |
| 103 | - url, | |
| 104 | - namespace=args.db_ns or os.environ.get("ZEKA_DB_NS", "hezarfen"), | |
| 105 | - database=args.db_name or os.environ.get("ZEKA_DB_NAME", "zeka"), | |
| 106 | - user=args.db_user or os.environ.get("ZEKA_DB_USER", "root"), | |
| 107 | - password=args.db_pass or os.environ.get("ZEKA_DB_PASSWORD", "root"), | |
| 103 | + try: | |
| 104 | + settings = Config(require_token=True) | |
| 105 | + except ConfigError as exc: | |
| 106 | + raise SystemExit(f"--persist için köprü ayarı eksik: {exc}") from exc | |
| 107 | + return BridgeStore( | |
| 108 | + bridge.OneShotCaller(settings), timeout_secs=settings.api_timeout_secs | |
| 108 | 109 | ) |
| 109 | - return Store(client) | |
| 110 | 110 | |
| 111 | 111 | |
| 112 | 112 | def cmd_run(args) -> int: |
| @@ -179,16 +179,10 @@ def build_parser() -> argparse.ArgumentParser: | ||
| 179 | 179 | s.add_argument("--max-answers", type=int, default=None) |
| 180 | 180 | # --- Asama 5: depoya yazim. VARSAYILAN KAPALI. -------------------------- |
| 181 | 181 | s.add_argument("--persist", action="store_true", |
| 182 | - help="etiketleri ve ogrenci profillerini ZEKA deposuna yaz " | |
| 183 | - "(--db-url yoksa kuru kosu)") | |
| 182 | + help="etiketleri ve ogrenci profillerini KOPRUDEN yaz: " | |
| 183 | + "--school ve AI_SHARED_TOKEN yoksa kuru kosu") | |
| 184 | 184 | s.add_argument("--school", default=None, |
| 185 | 185 | help="okul slug'i; verilmezse tohum manifestosundan okunur") |
| 186 | - s.add_argument("--db-url", default=None, | |
| 187 | - help="SurrealDB HTTP adresi, orn. http://hzk-zeka:8000") | |
| 188 | - s.add_argument("--db-ns", default=None, help="namespace (vars: hezarfen)") | |
| 189 | - s.add_argument("--db-name", default=None, help="veritabani (vars: zeka)") | |
| 190 | - s.add_argument("--db-user", default=None, help="kullanici (vars: root)") | |
| 191 | - s.add_argument("--db-pass", default=None, help="parola (vars: root)") | |
| 192 | 186 | s.set_defaults(func=cmd_run) |
| 193 | 187 | |
| 194 | 188 | s = sub.add_parser("cache", help="onbellek durumu / temizleme") |
service/src/segment/persist.pymodified+5 -16
| @@ -13,7 +13,7 @@ Köprünün yaptığı dört şey: | ||
| 13 | 13 | 1. `LabelBatch` → `QuestionSegment` (soru başına etiket satırı), |
| 14 | 14 | 2. etiket + ham cevap → `StudentSegmentProfile` (öğrenci × boyut × etiket), |
| 15 | 15 | 3. profil + kohort referansı → segment tabanlı `Recommendation` satırları, |
| 16 | - 4. üçünü de `Store` üzerinden UPSERT. | |
| 16 | + 4. üçünü de köprüden (`insight.*`) idempotent yaz. | |
| 17 | 17 | |
| 18 | 18 | Kural motorunun burada çağrılmasının sebebi ölçüsel: segment kuralları kohort |
| 19 | 19 | ortalamasına göre ateşler ve o ortalama ancak BÜTÜN öğrenciler hesaplandıktan |
| @@ -22,8 +22,8 @@ sonra bilinir. Tek öğrenci işleyen gece koşusu (`pipeline.run_school`) bu sa | ||
| 22 | 22 | referansı hazır elde olan taraf burasıdır. |
| 23 | 23 | |
| 24 | 24 | Yazım **isteğe bağlıdır**: `runner.run(..., persist=True)` ya da CLI'da |
| 25 | -`--persist`. Varsayılan davranış değişmez; bayrak verilmezse tek bir SurrealQL | |
| 26 | -ifadesi bile çalışmaz. | |
| 25 | +`--persist`. Varsayılan davranış değişmez; bayrak verilmezse tek bir köprü çağrısı | |
| 26 | +bile yapılmaz. | |
| 27 | 27 | """ |
| 28 | 28 | |
| 29 | 29 | from __future__ import annotations |
| @@ -46,7 +46,7 @@ from ..compute.segments import ( | ||
| 46 | 46 | reference_contrasts, |
| 47 | 47 | student_profiles, |
| 48 | 48 | ) |
| 49 | -from ..store import Store, SurrealHttpClient | |
| 49 | +from ..store import SchoolStore | |
| 50 | 50 | from .config import SegmentConfig, log |
| 51 | 51 | from .labelers import LabelBatch |
| 52 | 52 | from .rubric import DIMENSION_ORDER, EXPERIMENTAL_DIMENSIONS |
| @@ -233,17 +233,6 @@ def school_slug(cfg: SegmentConfig, override: str | None = None) -> str: | ||
| 233 | 233 | return "bilinmeyen" |
| 234 | 234 | |
| 235 | 235 | |
| 236 | -def build_client( | |
| 237 | - url: str, *, namespace: str, database: str, user: str, password: str | |
| 238 | -) -> SurrealHttpClient: | |
| 239 | - """Depo istemcisi. `store.py` ile aynı istemci — ikinci bir yol yok.""" | |
| 240 | - client = SurrealHttpClient( | |
| 241 | - url, namespace=namespace, database=database, user=user, password=password | |
| 242 | - ) | |
| 243 | - client.ensure_namespace() | |
| 244 | - return client | |
| 245 | - | |
| 246 | - | |
| 247 | 236 | async def persist( |
| 248 | 237 | batch: LabelBatch, |
| 249 | 238 | items: Sequence[dict], |
| @@ -251,7 +240,7 @@ async def persist( | ||
| 251 | 240 | *, |
| 252 | 241 | school: str, |
| 253 | 242 | now_ms: int, |
| 254 | - store: Store | None, | |
| 243 | + store: SchoolStore | None, | |
| 255 | 244 | ) -> PersistReport: |
| 256 | 245 | """Dönüştür ve yaz. `store=None` ise yalnız sayar (kuru koşu).""" |
| 257 | 246 | report = PersistReport(school=school, dry_run=store is None) |
service/src/store.pymodified+579 -600
| @@ -1,41 +1,66 @@ | ||
| 1 | -"""ZEKA'nın **kendi** SurrealDB veritabanına yazma katmanı. | |
| 1 | +"""ZEKA'nın yazma **ve** okuma katmanı — hepsi köprüden. | |
| 2 | 2 | |
| 3 | -Kaynak: `spec/MODULLER.md` §2.11 `insight::store`, §4 depolama şeması. | |
| 4 | -Şema DDL'i: `service/schema/zeka.surql`. | |
| 3 | +--------------------------------------------------------------------------- | |
| 4 | +DEĞİŞMEZ KURAL (2026-09-17, kullanıcı) | |
| 5 | +--------------------------------------------------------------------------- | |
| 6 | +**Bir AI servisi uygulama veritabanına asla doğrudan erişmez. Şimdi değil, | |
| 7 | +gelecekte de.** Bu bir parti kararı değil, sürekli bir kuraldır. | |
| 8 | + | |
| 9 | +ZEKA'nın **kendi** deposu yoktur. Hesapladığı her satır, okuduğu her liste | |
| 10 | +backend'in QUIC köprüsü üzerinden gider ve gelir: `insight.*` yetenek | |
| 11 | +çağrıları. Bu modülde tek bir bağlantı açılmaz, tek bir SQL/SurrealQL dizesi | |
| 12 | +yoktur, hiçbir veritabanı sürücüsü **import edilmez**. Silinen yol budur — | |
| 13 | +`pg_client.py`, `store_pg.py`, `tenants.py`, `store_factory.py` ve | |
| 14 | +`schema/` artık yok; geri gelmeleri de yasaktır. | |
| 15 | + | |
| 16 | +`zeka_*` tabloları OKULUN veritabanında durur ve DDL'i backend deposundadır | |
| 17 | +(`hezarfen_backend/migrations/school/20260917000002_zeka.sql`). Sahibi | |
| 18 | +backend'dir; ZEKA yalnız "şu satırları yaz" der. | |
| 5 | 19 | |
| 6 | 20 | --------------------------------------------------------------------------- |
| 7 | -TEK VE MUTLAK KURAL | |
| 21 | +TEL (kablo) SÖZLEŞMESİ | |
| 8 | 22 | --------------------------------------------------------------------------- |
| 9 | -**Okul veritabanına asla yazılmaz.** ZEKA okul verisini yalnız `Source` | |
| 10 | -arayüzü üzerinden **okur**; yazma yolu diye bir şey yoktur. Bu modülün | |
| 11 | -dokunduğu tek yer ZEKA'nın kendi veritabanıdır ve orada yalnız beş tablo | |
| 12 | -vardır: `student_summary`, `recommendation`, `insight_run`, | |
| 13 | -`question_segment`, `student_segment_profile`. | |
| 23 | +Çağrı, `BridgeProtocol.call_capability()` ile, servisin AÇTIĞI taze bir | |
| 24 | +istemci-başlatımlı akışta gider (tıpkı `ApiRequest` gibi): | |
| 25 | + | |
| 26 | + { "id": "<ulid>", "capability": "insight.<noun>[.<verb>]", | |
| 27 | + "school": "<slug>", "payload": { ... } } | |
| 14 | 28 | |
| 15 | -`MODULLER.md` §2.10 yapısal kural 3 ("otomatik eylem yok") bu sayede şema | |
| 16 | -düzeyinde garantidir: bu tablolar yalnız gösterilecek metni ve kanıtı tutar, | |
| 17 | -hiçbir yazma yolu buradan okuyup başka bir tabloyu güncellemez. | |
| 29 | + { "status": "ok", "id": ..., "school": ..., "payload": { ... } } | |
| 30 | + { "status": "err", "id": ..., "school": ..., "code": ..., "message": ... } | |
| 31 | + | |
| 32 | +`status` ÖNCE okunur; `err` asla başarı sayılmaz. Reddin kodu tiplidir | |
| 33 | +(`malformed`, `unknown_capability`, `unknown_school`, `school_suspended`, | |
| 34 | +`not_permitted`, `invalid_payload`, `unavailable`, `timed_out`, `internal`, | |
| 35 | +`too_many_rows`) ve `CapabilityRefused` olarak yükselir. | |
| 36 | + | |
| 37 | +Okul **çerçevededir**, payload'da değil: backend slug'ı çözer ve her ifadeyi | |
| 38 | +o okulun kendi veritabanında koşturur. Tek istisna `insight.schools.list` | |
| 39 | +(deployment ölçekli): çerçevede `school: ""` gider. | |
| 18 | 40 | |
| 19 | 41 | --------------------------------------------------------------------------- |
| 20 | -Sürücü bağımsızlığı | |
| 42 | +HATA DAVRANIŞI (`MODULLER.md` §2.11) | |
| 21 | 43 | --------------------------------------------------------------------------- |
| 22 | -Bu modül bir SurrealDB sürücüsü **import etmez**. `DbClient` protokolünü | |
| 23 | -uygular; gerçek istemciyi hattı kuran taraf verir. Böylece testler ve | |
| 24 | -`cli.py --dry-run` gerçek bir veritabanı olmadan çalışır. | |
| 44 | +* Yazma: grup (500 satır) `MAX_ATTEMPTS` kez denenir; **ikinci düşüşte** | |
| 45 | + grup atlanır, `warn` loglanır ve hat devam eder — `WriteReport.status` | |
| 46 | + `partial` olur, `pipeline` bunu koşu defterine `store` olarak yazar. | |
| 47 | + Sessiz başarı YOKTUR: yazılamayan satır sayısı rapordadır. | |
| 48 | +* Okuma (`pending`): okunamazsa boş liste. Devretmemek, yanlış listeyle | |
| 49 | + koşmaktan iyidir. | |
| 50 | +* Süpürme/mezuniyet: tablo başına `False` / `False` döner; hata yutulmaz, | |
| 51 | + raporlanır. | |
| 52 | +* Köprü kapalıyken (`caller` yok) OKUMA çağrıları `BridgeUnavailable` | |
| 53 | + yükseltir; YAZMA ise sessizce yutulmaz ama yükseltmez de: grup | |
| 54 | + `MAX_ATTEMPTS` kez denenir, atlanır ve raporda `partial` olarak görünür. | |
| 55 | + İkisi de sessiz başarı DEĞİLDİR. Açılış bunları yakalamaz, çünkü açılışta | |
| 56 | + hiçbir şey açılmaz. | |
| 25 | 57 | """ |
| 26 | 58 | |
| 27 | 59 | from __future__ import annotations |
| 28 | 60 | |
| 29 | -import asyncio | |
| 30 | -import base64 | |
| 31 | -import dataclasses | |
| 32 | -import json | |
| 33 | 61 | import logging |
| 34 | -import re | |
| 35 | -import urllib.error | |
| 36 | -import urllib.request | |
| 37 | -from pathlib import Path | |
| 38 | -from typing import Any, Protocol, runtime_checkable | |
| 62 | +from dataclasses import dataclass, field | |
| 63 | +from typing import Any, Callable, Protocol, runtime_checkable | |
| 39 | 64 | |
| 40 | 65 | from .compute import clock |
| 41 | 66 | from .compute.model import ( |
| @@ -47,22 +72,39 @@ from .compute.model import ( | ||
| 47 | 72 | |
| 48 | 73 | log = logging.getLogger(__name__) |
| 49 | 74 | |
| 50 | -#: `schema/zeka.surql` — ZEKA veritabaninin DDL kaynagi. | |
| 51 | -SCHEMA_PATH = Path(__file__).resolve().parent.parent / "schema" / "zeka.surql" | |
| 52 | - | |
| 53 | -# `MODULLER.md` §2.11 adım 1: 500 satırlık gruplar halinde toplu UPSERT. | |
| 75 | +# `MODULLER.md` §2.11 adım 1: 500 satırlık gruplar. Backend'in tavanı da | |
| 76 | +# `MAX_INSIGHT_BATCH_ROWS = 500`; ikisi aynı sayıdır, biri değişirse diğeri | |
| 77 | +# `too_many_rows` reddiyle söyler. | |
| 54 | 78 | BATCH_SIZE = 500 |
| 55 | 79 | |
| 56 | -# `MODULLER.md` §2.11 hata davranışı: bir grup düşerse yeniden denenir; | |
| 57 | -# **ikinci düşüşte** grup atlanır, `warn` loglanır, hat devam eder. | |
| 80 | +# Bir grup düşerse yeniden denenir; **ikinci düşüşte** atlanır. | |
| 58 | 81 | MAX_ATTEMPTS = 2 |
| 59 | 82 | |
| 60 | -# --- Saklama süreleri (`[T§6.7]` tablosu, `MODULLER.md` §2.11 adım 2) -------- | |
| 83 | +# --- yetenek adları --------------------------------------------------------- | |
| 84 | +# Ad alanı backend'in ilan ettiği operasyon listesidir; burada TEK bir yerde | |
| 85 | +# yazılır ki bir yeniden adlandırma tek satırda kalsın. | |
| 86 | + | |
| 87 | +CAP_SUMMARY = "insight.summary.upsert" | |
| 88 | +CAP_RECOMMENDATION = "insight.recommendation.upsert" | |
| 89 | +CAP_SEGMENT = "insight.segment.upsert" | |
| 90 | +CAP_PROFILE = "insight.profile.upsert" | |
| 91 | +CAP_RUN = "insight.run.upsert" | |
| 92 | +CAP_PENDING = "insight.pending.list" | |
| 93 | +CAP_SWEEP = "insight.retention.sweep" | |
| 94 | +CAP_PURGE = "insight.departed.purge" | |
| 95 | +CAP_SCHOOLS = "insight.schools.list" | |
| 96 | + | |
| 97 | +#: Deployment ölçekli tek çağrı: okul çerçevede BOŞ gider. | |
| 98 | +DEPLOYMENT_SCOPED = (CAP_SCHOOLS,) | |
| 99 | + | |
| 100 | +#: Sunucu tavanları (istemci tarafında da bilinir: boşuna tur atmayalım). | |
| 101 | +#: Aşılırsa sunucu `too_many_rows` döner; istemci listeyi kırpmaz, bekler. | |
| 102 | +MAX_LIST_ROWS = 20000 | |
| 103 | + | |
| 104 | +# --- saklama süreleri ([T§6.7], MODULLER.md §2.11 adım 2) ------------------- | |
| 61 | 105 | # |
| 62 | -# `question_stat` bu sürümde üretilmiyor. Üretilen beş tablodan dördü kişisel | |
| 63 | -# veriye bağlanabilir; `question_segment` bağlanamaz ama o da sonlu süre alır | |
| 64 | -# (gerekçesi aşağıda). Süresi olmayan tablo YOKTUR: süpürme bu sözlüğü gezer, | |
| 65 | -# listede olmayan tablo hiç süpürülmez ve sessizce sonsuza kadar kalırdı. | |
| 106 | +# Süpürme artık backend'de koşar; süreler yine burada hesaplanır çünkü satırı | |
| 107 | +# yazan taraf `retain_until` alanını üretir. Süresi olmayan tablo YOKTUR. | |
| 66 | 108 | RETENTION_DAYS = { |
| 67 | 109 | # "Dönem + 1 yıl" — türetilmiş veri, ham veriden yeniden üretilebilir. |
| 68 | 110 | "student_summary": 400, |
| @@ -71,669 +113,606 @@ RETENTION_DAYS = { | ||
| 71 | 113 | # Koşu defteri. |
| 72 | 114 | "insight_run": 90, |
| 73 | 115 | # Soru hakkında, kişiye bağlanamaz → `[T§6.7]` "süresiz" satırı. Yine de |
| 74 | - # SONLU: etiket bir model ve bir istem sürümünün çıktısıdır, sürüm | |
| 75 | - # değişince bayatlar. 3 yıl = ~üç müfredat döngüsü. | |
| 116 | + # SONLU: etiket bir model ve bir istem sürümünün çıktısıdır. | |
| 76 | 117 | "question_segment": 1095, |
| 77 | 118 | # Türetilmiş öğrenci profili — `student_summary` ile aynı süre. |
| 78 | 119 | "student_segment_profile": 400, |
| 79 | 120 | } |
| 80 | 121 | |
| 122 | +#: Süpürmenin dokunduğu dokuz tablo, backend'in cevap anahtarlarıyla aynı | |
| 123 | +#: sırada: önce çocuk, sonra ebeveyn (FK'ler `NO ACTION`). | |
| 124 | +SWEEP_TABLES = ( | |
| 125 | + "zeka_attention_item", | |
| 126 | + "zeka_run_pending", | |
| 127 | + "zeka_run_failed_module", | |
| 128 | + "zeka_question_segment_dimension", | |
| 129 | + "zeka_student_summary", | |
| 130 | + "zeka_recommendation", | |
| 131 | + "zeka_run", | |
| 132 | + "zeka_question_segment", | |
| 133 | + "zeka_student_segment_profile", | |
| 134 | +) | |
| 81 | 135 | |
| 82 | -@runtime_checkable | |
| 83 | -class DbClient(Protocol): | |
| 84 | - """ZEKA veritabanı istemcisinin ihtiyaç duyulan tek yüzeyi.""" | |
| 85 | - | |
| 86 | - async def query(self, sql: str, variables: dict[str, Any]) -> Any: ... | |
| 87 | - | |
| 88 | - | |
| 89 | -class CollectingClient: | |
| 90 | - """Gerçek veritabanı yerine ifadeleri toplayan istemci. | |
| 91 | - | |
| 92 | - `cli.py --dry-run` ve testler için. Üretimde kullanılmaz. | |
| 93 | - """ | |
| 136 | +#: Mezuniyet temizliğinin dokunduğu beş tablo. | |
| 137 | +PURGE_TABLES = ( | |
| 138 | + "zeka_attention_item", | |
| 139 | + "zeka_student_summary", | |
| 140 | + "zeka_student_segment_profile", | |
| 141 | + "zeka_recommendation", | |
| 142 | + "zeka_run_pending", | |
| 143 | +) | |
| 94 | 144 | |
| 95 | - def __init__(self) -> None: | |
| 96 | - self.statements: list[tuple[str, dict[str, Any]]] = [] | |
| 97 | - self.fail_times = 0 | |
| 98 | 145 | |
| 99 | - async def query(self, sql: str, variables: dict[str, Any]) -> Any: | |
| 100 | - if self.fail_times > 0: | |
| 101 | - self.fail_times -= 1 | |
| 102 | - raise RuntimeError("sahte yazma hatası") | |
| 103 | - self.statements.append((sql, variables)) | |
| 104 | - return [] | |
| 146 | +class BridgeUnavailable(RuntimeError): | |
| 147 | + """Köprü henüz bağlı değil; çağrı yapılabilecek bir taşıma yok.""" | |
| 105 | 148 | |
| 106 | 149 | |
| 107 | -# =========================================================================== | |
| 108 | -# GERCEK SurrealDB istemcisi -- yalnizca standart kutuphane | |
| 109 | -# =========================================================================== | |
| 110 | -# | |
| 111 | -# NEDEN HTTP `/rpc`, NEDEN `surreal sql` DEGIL: | |
| 112 | -# * `surreal sql` araci standart girdiden gelen buyuk govdeyi **sessizce | |
| 113 | -# keser** ve cok satirli ifadeleri satir satir ayristirir; tohum yukleme | |
| 114 | -# deneyiminde yarim yuklenen dosyalar buradan cikti (bkz. | |
| 115 | -# `tools/load_seed.py` bas aciklamasi). | |
| 116 | -# * HTTP `/sql` ucu degisken (`$v`) tasiyamaz -- govde duz metindir. Toplu | |
| 117 | -# UPSERT'in icerigi ic ice sozluklerdir; bunlari SurrealQL metnine gomulu | |
| 118 | -# yazmak kacis hatasina acik olurdu. | |
| 119 | -# * `/rpc` ucu JSON-RPC'dir: `query` yontemi `[sql, variables]` alir. | |
| 120 | -# Degiskenler tip korunarak gider, kacis sorunu **yapisal olarak** yoktur. | |
| 121 | -# | |
| 122 | -# EN ONEMLI DAVRANIS: SurrealDB basarisiz ifade icin de **HTTP 200** doner; | |
| 123 | -# hata, sonuc dizisindeki `status: "ERR"` alanindadir. Bu yuzden asagidaki | |
| 124 | -# istemci her ifadenin durumunu tek tek denetler ve ilk `ERR`'de patlar. | |
| 125 | -# Denetlemeyen bir istemci "yazdim" der ve hicbir sey yazilmamis olur. | |
| 126 | -# | |
| 127 | -# SURUM NOTU: `type::thing()` SurrealDB 3'te **YOKTUR**, karsiligi | |
| 128 | -# `type::record()`. Bu modulun onceki hali `type::thing` kullaniyordu ve hicbir | |
| 129 | -# zaman gercek bir veritabanina karsi kosmadigi icin fark edilmemisti. | |
| 150 | +class CapabilityRefused(Exception): | |
| 151 | + """Sunucu `status: "err"` döndü. Kod makine okunabilir, kararlıdır.""" | |
| 130 | 152 | |
| 131 | -SURREAL_TIMEOUT_SECS = 60.0 | |
| 153 | + def __init__(self, code: str, message: str, *, capability: str, school: str) -> None: | |
| 154 | + super().__init__(f"{capability} reddedildi ({code}): {message}") | |
| 155 | + self.code = code | |
| 156 | + self.message = message | |
| 157 | + self.capability = capability | |
| 158 | + self.school = school | |
| 132 | 159 | |
| 133 | 160 | |
| 134 | -class SurrealError(RuntimeError): | |
| 135 | - """Bir SurrealQL ifadesi `status: ERR` dondurdu ya da tasima dustu.""" | |
| 161 | +@runtime_checkable | |
| 162 | +class BridgeCaller(Protocol): | |
| 163 | + """Deponun ihtiyaç duyduğu TEK taşıma yüzeyi.""" | |
| 136 | 164 | |
| 137 | - def __init__(self, message: str, *, statement: str = "") -> None: | |
| 138 | - super().__init__(message) | |
| 139 | - self.statement = statement | |
| 165 | + async def call( | |
| 166 | + self, capability: str, school: str, payload: dict[str, Any] | |
| 167 | + ) -> dict[str, Any]: ... | |
| 140 | 168 | |
| 141 | 169 | |
| 142 | -class SurrealHttpClient: | |
| 143 | - """`DbClient` protokolunun gercek uygulamasi -- stdlib `urllib` + `/rpc`. | |
| 170 | +class ProtocolCaller: | |
| 171 | + """`BridgeProtocol`'u deponun gördüğü yüzeye çeviren ince adaptör. | |
| 144 | 172 | |
| 145 | - Ek bagimlilik **yoktur**: ne `requests`, ne `surrealdb` surucusu. Senkron | |
| 146 | - `urllib` cagrisi `asyncio.to_thread` ile olay dongusunden cikarilir. | |
| 173 | + Taşıma TEKTİR (`BridgeProtocol.call_capability`); depo ise yalnız | |
| 174 | + `call(capability, school, payload)` bilir. İkisini birbirine bağlayan | |
| 175 | + yer burasıdır — ikinci bir taşıma yazılmaz. | |
| 147 | 176 | """ |
| 148 | 177 | |
| 149 | - def __init__( | |
| 150 | - self, | |
| 151 | - endpoint: str, | |
| 152 | - *, | |
| 153 | - namespace: str, | |
| 154 | - database: str, | |
| 155 | - user: str = "root", | |
| 156 | - password: str = "root", | |
| 157 | - timeout: float = SURREAL_TIMEOUT_SECS, | |
| 158 | - ) -> None: | |
| 159 | - self.endpoint = endpoint.rstrip("/") | |
| 160 | - self.namespace = namespace | |
| 161 | - self.database = database | |
| 162 | - self._timeout = timeout | |
| 163 | - token = base64.b64encode(f"{user}:{password}".encode()).decode() | |
| 164 | - self._auth = "Basic " + token | |
| 165 | - #: Kac SurrealQL ifadesi calisti -- kanit sayaci. | |
| 166 | - self.statement_count = 0 | |
| 167 | - | |
| 168 | - # -- tasima ------------------------------------------------------------- | |
| 169 | - | |
| 170 | - def _post(self, payload: dict[str, Any]) -> dict[str, Any]: | |
| 171 | - body = json.dumps(payload, ensure_ascii=False, default=str).encode("utf-8") | |
| 172 | - request = urllib.request.Request(self.endpoint + "/rpc", data=body) | |
| 173 | - request.add_header("Accept", "application/json") | |
| 174 | - request.add_header("Content-Type", "application/json") | |
| 175 | - request.add_header("surreal-ns", self.namespace) | |
| 176 | - request.add_header("surreal-db", self.database) | |
| 177 | - request.add_header("Authorization", self._auth) | |
| 178 | - try: | |
| 179 | - with urllib.request.urlopen(request, timeout=self._timeout) as response: | |
| 180 | - return json.loads(response.read().decode("utf-8")) | |
| 181 | - except urllib.error.HTTPError as exc: # 4xx / 5xx | |
| 182 | - detail = exc.read().decode("utf-8", "replace")[:400] | |
| 183 | - raise SurrealError(f"HTTP {exc.code}: {detail}") from exc | |
| 184 | - | |
| 185 | - def query_sync(self, sql: str, variables: dict[str, Any] | None = None) -> list: | |
| 186 | - """Tek istek; **her** ifadenin `status` alani denetlenir.""" | |
| 187 | - envelope = self._post( | |
| 188 | - {"id": 1, "method": "query", "params": [sql, variables or {}]} | |
| 189 | - ) | |
| 190 | - if envelope.get("error"): | |
| 191 | - message = envelope["error"].get("message", str(envelope["error"])) | |
| 192 | - raise SurrealError(f"ayristirma/RPC hatasi: {message}", statement=sql) | |
| 193 | - results = envelope.get("result") or [] | |
| 194 | - for item in results: | |
| 195 | - if isinstance(item, dict) and item.get("status") not in (None, "OK"): | |
| 196 | - raise SurrealError( | |
| 197 | - f"ifade reddedildi: {str(item.get('result'))[:400]}", | |
| 198 | - statement=sql, | |
| 199 | - ) | |
| 200 | - self.statement_count += len(results) | |
| 201 | - return results | |
| 202 | - | |
| 203 | - async def query(self, sql: str, variables: dict[str, Any]) -> Any: | |
| 204 | - return await asyncio.to_thread(self.query_sync, sql, variables) | |
| 178 | + def __init__(self, protocol: Any, *, timeout_secs: float | None = None) -> None: | |
| 179 | + self._protocol = protocol | |
| 180 | + self._timeout = timeout_secs | |
| 205 | 181 | |
| 206 | - # -- kurulum ------------------------------------------------------------ | |
| 207 | - | |
| 208 | - def ensure_namespace(self) -> None: | |
| 209 | - """ns/db yoksa yaratir. Tekrar edilebilir, zararsiz. | |
| 210 | - | |
| 211 | - Ilk `DEFINE NAMESPACE` istegi, namespace henuz yokken `NotFound` | |
| 212 | - dondurebilir (baglanti basligi var olmayan ns'i isaret ediyor); bu | |
| 213 | - yuzden sonucu denetlenmeden gonderilir. Ikinci istek gercek denetimi | |
| 214 | - yapar. | |
| 215 | - """ | |
| 216 | - self._post( | |
| 217 | - { | |
| 218 | - "id": 1, | |
| 219 | - "method": "query", | |
| 220 | - "params": [f"DEFINE NAMESPACE IF NOT EXISTS {self.namespace};", {}], | |
| 221 | - } | |
| 182 | + async def call( | |
| 183 | + self, capability: str, school: str, payload: dict[str, Any] | |
| 184 | + ) -> dict[str, Any]: | |
| 185 | + return await self._protocol.call_capability( | |
| 186 | + capability, school, payload, timeout=self._timeout | |
| 222 | 187 | ) |
| 223 | - self.query_sync(f"DEFINE DATABASE IF NOT EXISTS {self.database};") | |
| 224 | 188 | |
| 225 | - def close(self) -> None: # simetri icin; urllib kalici baglanti tutmaz | |
| 226 | - return None | |
| 227 | 189 | |
| 190 | +@dataclass(slots=True) | |
| 191 | +class WriteReport: | |
| 192 | + """Yazma muhasebesi; `insight_run` satırını besler ve hata görünür kalır.""" | |
| 228 | 193 | |
| 229 | -# --- DDL yukleyici --------------------------------------------------------- | |
| 194 | + table: str = "" | |
| 195 | + written: int = 0 | |
| 196 | + rejected: int = 0 | |
| 197 | + skipped_batches: int = 0 | |
| 230 | 198 | |
| 199 | + @property | |
| 200 | + def status(self) -> str: | |
| 201 | + return "partial" if self.skipped_batches else "ok" | |
| 231 | 202 | |
| 232 | -def split_statements(text: str) -> list[str]: | |
| 233 | - """SurrealQL metnini ifadelere boler. | |
| 234 | 203 | |
| 235 | - Dize farkindadir: tirnak icindeki `;` ifade sonu **sayilmaz**. `--` yorum | |
| 236 | - satirlari atilir. Desen `tools/load_seed.py` ile aynidir; oradaki aci | |
| 237 | - `surreal sql`'in cok satirli ifadeyi satir satir ayristirmasiydi. | |
| 238 | - """ | |
| 239 | - out: list[str] = [] | |
| 240 | - buf: list[str] = [] | |
| 241 | - quote: str | None = None | |
| 242 | - index = 0 | |
| 243 | - size = len(text) | |
| 244 | - while index < size: | |
| 245 | - ch = text[index] | |
| 246 | - if quote: | |
| 247 | - buf.append(ch) | |
| 248 | - if ch == quote: | |
| 249 | - quote = None | |
| 250 | - elif ch == "'" or ch == '"': | |
| 251 | - quote = ch | |
| 252 | - buf.append(ch) | |
| 253 | - elif ch == "-" and text.startswith("--", index): | |
| 254 | - end = text.find("\n", index) | |
| 255 | - index = size if end < 0 else end | |
| 256 | - continue | |
| 257 | - elif ch == ";": | |
| 258 | - statement = ("".join(buf) + ";").strip() | |
| 259 | - if statement and statement != ";": | |
| 260 | - out.append(statement) | |
| 261 | - buf = [] | |
| 262 | - else: | |
| 263 | - buf.append(ch) | |
| 264 | - index += 1 | |
| 265 | - tail = "".join(buf).strip() | |
| 266 | - if tail: | |
| 267 | - out.append(tail) | |
| 268 | - return out | |
| 204 | +@dataclass(slots=True) | |
| 205 | +class RecordingCaller: | |
| 206 | + """Gerçek köprü yerine çağrıları toplayan istemci (`--dry-run`, testler). | |
| 269 | 207 | |
| 208 | + Üretimde kullanılmaz. Cevap şekilleri sunucununkinin aynısıdır; böylece | |
| 209 | + hat (`pipeline` → `store`) baştan sona koşar, yalnız taşıma değişir. | |
| 210 | + """ | |
| 270 | 211 | |
| 271 | -@dataclasses.dataclass(slots=True) | |
| 272 | -class SchemaReport: | |
| 273 | - """`apply_schema` muhasebesi -- kac ifade gonderildi, kaci gecti.""" | |
| 212 | + calls: list[tuple[str, str, dict[str, Any]]] = field(default_factory=list) | |
| 213 | + fail_times: int = 0 | |
| 214 | + fail_capabilities: set[str] = field(default_factory=set) | |
| 215 | + | |
| 216 | + async def call( | |
| 217 | + self, capability: str, school: str, payload: dict[str, Any] | |
| 218 | + ) -> dict[str, Any]: | |
| 219 | + if self.fail_times > 0 or capability in self.fail_capabilities: | |
| 220 | + if self.fail_times > 0: | |
| 221 | + self.fail_times -= 1 | |
| 222 | + raise CapabilityRefused( | |
| 223 | + "internal", "sahte köprü hatası", capability=capability, school=school | |
| 224 | + ) | |
| 225 | + self.calls.append((capability, school, payload)) | |
| 226 | + if capability == CAP_SCHOOLS: | |
| 227 | + return {"schools": []} | |
| 228 | + if capability == CAP_PENDING: | |
| 229 | + return {"students": []} | |
| 230 | + if capability == CAP_SWEEP: | |
| 231 | + return {"tables": {table: True for table in SWEEP_TABLES}} | |
| 232 | + if capability == CAP_PURGE: | |
| 233 | + return {"tables": {table: True for table in PURGE_TABLES}} | |
| 234 | + rows = payload.get("rows") | |
| 235 | + if isinstance(rows, list): | |
| 236 | + written = len(rows) | |
| 237 | + else: | |
| 238 | + written = 1 | |
| 239 | + reply: dict[str, Any] = {"written": written} | |
| 240 | + if capability == CAP_RECOMMENDATION: | |
| 241 | + reply["rejected"] = 0 | |
| 242 | + return reply | |
| 274 | 243 | |
| 275 | - total: int = 0 | |
| 276 | - applied: int = 0 | |
| 277 | - errors: list[str] = dataclasses.field(default_factory=list) | |
| 278 | 244 | |
| 279 | - @property | |
| 280 | - def ok(self) -> bool: | |
| 281 | - return not self.errors and self.total == self.applied | |
| 245 | +# =========================================================================== | |
| 246 | +# Payload kurucuları — hesap tipleri → kablo sözlükleri | |
| 247 | +# =========================================================================== | |
| 248 | +# | |
| 249 | +# Alan adları backend'in `zeka_*` kolon adlarıyla aynıdır; iki taraf tek | |
| 250 | +# sözlüğü konuşur. `school` GÖNDERİLMEZ: okul çerçevededir ve satırda ikinci | |
| 251 | +# bir kopya, çelişebilecek ikinci bir yer olurdu. | |
| 282 | 252 | |
| 283 | 253 | |
| 284 | -def load_schema_text(path: Any = None) -> str: | |
| 285 | - """`schema/zeka.surql` metnini okur.""" | |
| 286 | - target = Path(path) if path else SCHEMA_PATH | |
| 287 | - return target.read_text(encoding="utf-8") | |
| 254 | +def _retain_until(table: str, base_ms: int) -> int: | |
| 255 | + return base_ms + RETENTION_DAYS[table] * clock.DAY_MS | |
| 288 | 256 | |
| 289 | 257 | |
| 290 | -def apply_schema( | |
| 291 | - client: SurrealHttpClient, ddl_text: str | None = None | |
| 292 | -) -> SchemaReport: | |
| 293 | - """Semayi **ifade ifade** yukler ve her birinin sonucunu dogrular. | |
| 258 | +def attention_items(summary: StudentSummary) -> list[dict[str, Any]]: | |
| 259 | + """Dikkat maddeleri. Sıra **yazanın sırasıdır**, şiddete göre değil. | |
| 294 | 260 | |
| 295 | - Toplu gonderim KASITLI OLARAK yapilmaz: bir ifade duserse hangisinin | |
| 296 | - dustugunu bilmek gerekir. Tek parca gondermek, tam da bu projede yasanan | |
| 297 | - "yari yuklenmis sema" durumunu ureten desendi. | |
| 298 | - """ | |
| 299 | - report = SchemaReport() | |
| 300 | - for statement in split_statements(ddl_text or load_schema_text()): | |
| 301 | - report.total += 1 | |
| 302 | - try: | |
| 303 | - client.query_sync(statement) | |
| 304 | - report.applied += 1 | |
| 305 | - except SurrealError as exc: | |
| 306 | - report.errors.append(f"{statement.splitlines()[0][:90]} -> {exc}") | |
| 307 | - return report | |
| 308 | - | |
| 309 | - | |
| 310 | -def schema_field_types(client: SurrealHttpClient, table: str) -> dict[str, str]: | |
| 311 | - """`INFO FOR TABLE` ciktisindan alan -> DDL metni sozlugu uretir.""" | |
| 312 | - rows = client.query_sync(f"INFO FOR TABLE {table};") | |
| 313 | - info = rows[0].get("result") if rows else None | |
| 314 | - if not isinstance(info, dict): | |
| 315 | - raise SurrealError(f"INFO FOR TABLE {table} beklenen bicimde degil") | |
| 316 | - return dict(info.get("fields") or {}) | |
| 317 | - | |
| 318 | - | |
| 319 | -def schema_tables(client: SurrealHttpClient) -> dict[str, str]: | |
| 320 | - """`INFO FOR DB` ciktisindan tablo -> DDL metni sozlugu uretir.""" | |
| 321 | - rows = client.query_sync("INFO FOR DB;") | |
| 322 | - info = rows[0].get("result") if rows else None | |
| 323 | - if not isinstance(info, dict): | |
| 324 | - raise SurrealError("INFO FOR DB beklenen bicimde degil") | |
| 325 | - return dict(info.get("tables") or {}) | |
| 326 | - | |
| 327 | - | |
| 328 | -def _drop_nulls(row: dict[str, Any]) -> dict[str, Any]: | |
| 329 | - """Ust duzey `None` alanlarini satirdan cikarir. | |
| 330 | - | |
| 331 | - SurrealDB 3'te `option<string>` gercekte `none | string` demektir ve | |
| 332 | - **`NULL` kabul etmez**: Python'un `None` degeri JSON `null` olarak gider, | |
| 333 | - veritabani da `Couldn't coerce value ... Expected none | string but found | |
| 334 | - NULL` diyerek TUM transaction'i reddeder. Yani tek bir bos `dismiss_reason` | |
| 335 | - alani, 500 satirlik grubun tamamini dusururdu. | |
| 336 | - | |
| 337 | - Alani hic gondermemek dogru karsiliktir: SCHEMAFULL tabloda tanimli ama | |
| 338 | - verilmemis `option<...>` alani `NONE` olur. | |
| 339 | - | |
| 340 | - Yalnizca UST DUZEY anahtarlar temizlenir; FLEXIBLE nesnelerin (`marks`, | |
| 341 | - `evidence`, dikkat maddeleri) icindeki `null` degerler hesap ciktisinin | |
| 342 | - parcasidir ve oldugu gibi saklanir. | |
| 261 | + Kanıtsız madde **yazılmaz**: `Recommendation` için geçerli olan kural | |
| 262 | + dikkat maddesi için de geçerlidir — açıklanamayan şey gösterilmez. | |
| 263 | + (Sunucu da aynı kuralı uygular; buradaki kontrol turu boşa çevirir.) | |
| 343 | 264 | """ |
| 344 | - return {key: value for key, value in row.items() if value is not None} | |
| 265 | + out: list[dict[str, Any]] = [] | |
| 266 | + for item in summary.attention or []: | |
| 267 | + evidence = item.get("evidence") if isinstance(item, dict) else None | |
| 268 | + if not evidence: | |
| 269 | + log.warning( | |
| 270 | + "kanıtsız dikkat maddesi atlandı (öğrenci=%s, tetik=%s)", | |
| 271 | + summary.student, | |
| 272 | + item.get("trigger") if isinstance(item, dict) else "?", | |
| 273 | + ) | |
| 274 | + continue | |
| 275 | + out.append( | |
| 276 | + { | |
| 277 | + "trigger": str(item.get("trigger")), | |
| 278 | + # Ders yalnız not-eğilimi maddesinde vardır ve kanıtın | |
| 279 | + # içindedir; üst düzeyde ayrı bir alan YOK. | |
| 280 | + "course": evidence.get("course"), | |
| 281 | + "fact": str(item.get("fact") or ""), | |
| 282 | + "window_from": int(item.get("window_from") or 0), | |
| 283 | + "window_to": int(item.get("window_to") or 0), | |
| 284 | + "evidence": evidence, | |
| 285 | + } | |
| 286 | + ) | |
| 287 | + return out | |
| 345 | 288 | |
| 346 | 289 | |
| 347 | -# --- Kimlik biçimli metinler: SurrealDB'nin sessiz `record` dönüşümü --------- | |
| 348 | -# | |
| 349 | -# ÖLÇÜLDÜ (SurrealDB 3, HTTP `/rpc`, 2026-09-15): değişken olarak gönderilen | |
| 350 | -# `"user:01K..."` biçimli bir JSON **metni**, uçta `record` değerine çevrilir. | |
| 351 | -# `TYPE string` bir alana yazılmak istendiğinde de: | |
| 352 | -# | |
| 353 | -# Couldn't coerce value for field `exam`: Expected `none | string` | |
| 354 | -# but found `exam:E1` | |
| 355 | -# | |
| 356 | -# diyerek **bütün transaction** reddedilir. Yani tek bir gerçek öğrenci | |
| 357 | -# kimliği (`user:<ULID>`) 500 satırlık grubun tamamını düşürürdü. Bu, fikstür | |
| 358 | -# kimlikleri (`student-00`) iki nokta taşımadığı için testlerde hiç görünmeyen | |
| 359 | -# bir tuzaktı. | |
| 360 | -# | |
| 361 | -# Çözüm: satır bir `$v` değişkeni olarak **bütün hâlde** gönderilmez; SurrealQL | |
| 362 | -# tarafında alan alan bir nesne kurulur ve kimlik biçimli değerler | |
| 363 | -# `type::string()` ile metne geri çevrilir. Diziler için karşılığı | |
| 364 | -# `array::map(..., |$x| type::string($x))`. İkisi de uca karşı doğrulandı. | |
| 365 | -# | |
| 366 | -# FLEXIBLE nesnelerin (`marks`, `evidence`, dikkat maddeleri) içindeki kimlikler | |
| 367 | -# dokunulmadan geçer: o alanlar tip denetimine girmez ve okurken yine metin | |
| 368 | -# olarak dönerler. | |
| 369 | -_RECORD_LIKE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*:\S+$") | |
| 370 | -#: Alan adı güvenliği — satır anahtarları koda aittir, yine de SurrealQL metnine | |
| 371 | -#: gömülmeden önce denetlenir. | |
| 372 | -_SAFE_FIELD = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$") | |
| 290 | +def summary_rows(summaries: list[StudentSummary]) -> list[dict[str, Any]]: | |
| 291 | + """`insight.summary.upsert` satırları — özet + dikkat maddeleri.""" | |
| 292 | + return [ | |
| 293 | + { | |
| 294 | + "student": s.student, | |
| 295 | + "marks": s.marks, | |
| 296 | + "attendance": s.attendance, | |
| 297 | + "submission": s.submission, | |
| 298 | + "study": s.study, | |
| 299 | + "confidence": str(s.confidence), | |
| 300 | + "computed_at": s.computed_at, | |
| 301 | + "retain_until": _retain_until("student_summary", s.computed_at), | |
| 302 | + "attention": attention_items(s), | |
| 303 | + } | |
| 304 | + for s in summaries | |
| 305 | + ] | |
| 306 | + | |
| 307 | + | |
| 308 | +def recommendation_rows(recs: list[Recommendation]) -> tuple[list[dict[str, Any]], int]: | |
| 309 | + """`insight.recommendation.upsert` satırları + reddedilen sayısı. | |
| 310 | + | |
| 311 | + **Kanıtsız satır reddedilir** (`MODULLER.md` §2.10 yapısal kural 1): | |
| 312 | + `limitation` dışında hiç kanıt yoksa satır yazılmaz. | |
| 313 | + | |
| 314 | + Kimlik GÖNDERİLMEZ: uuid7'yi yazan taraf —backend— üretir (depo kuralı: | |
| 315 | + kimliği yazan üretir). `limitation` de `evidence`'a BURADA katılmaz; | |
| 316 | + sunucu ekler. | |
| 317 | + """ | |
| 318 | + rows: list[dict[str, Any]] = [] | |
| 319 | + rejected = 0 | |
| 320 | + for rec in recs: | |
| 321 | + if not {k: v for k, v in rec.evidence.items() if k != "limitation"}: | |
| 322 | + log.warning("kanıtsız tavsiye reddedildi: %s", rec.rule_id) | |
| 323 | + rejected += 1 | |
| 324 | + continue | |
| 325 | + ninety = _retain_until("recommendation", rec.computed_at) | |
| 326 | + rows.append( | |
| 327 | + { | |
| 328 | + "audience": rec.audience, | |
| 329 | + "product": rec.product, | |
| 330 | + "rule_id": rec.rule_id, | |
| 331 | + "rule_version": rec.rule_version, | |
| 332 | + # Kapsam: kuralın kendi ayrımı (segment etiketi gibi) ya da | |
| 333 | + # ders. `about` BURAYA KONMAZ; kendi alanı vardır. | |
| 334 | + "scope": rec.scope or rec.course, | |
| 335 | + "about": rec.about, | |
| 336 | + "audience_role": str(rec.audience_role), | |
| 337 | + "course": rec.course, | |
| 338 | + "evidence": rec.evidence, | |
| 339 | + "limitation": rec.limitation, | |
| 340 | + "confidence": str(rec.confidence), | |
| 341 | + "computed_at": rec.computed_at, | |
| 342 | + "expires_at": rec.expires_at, | |
| 343 | + "retain_until": min(rec.expires_at, ninety), | |
| 344 | + } | |
| 345 | + ) | |
| 346 | + return rows, rejected | |
| 373 | 347 | |
| 374 | 348 | |
| 375 | -def _is_record_like(value: Any) -> bool: | |
| 376 | - return isinstance(value, str) and bool(_RECORD_LIKE.match(value)) | |
| 349 | +def segment_rows(segments: list[QuestionSegment]) -> list[dict[str, Any]]: | |
| 350 | + """`insight.segment.upsert` satırları — etiketler iç içe gider.""" | |
| 351 | + rows: list[dict[str, Any]] = [] | |
| 352 | + for seg in segments: | |
| 353 | + rows.append( | |
| 354 | + { | |
| 355 | + "question": seg.question, | |
| 356 | + "exam": seg.exam, | |
| 357 | + "course": seg.course, | |
| 358 | + "subject": seg.subject, | |
| 359 | + "labels": {str(k): str(v) for k, v in seg.labels.items()}, | |
| 360 | + "confidences": {str(k): float(v) for k, v in seg.confidences.items()}, | |
| 361 | + "confidence": str(seg.confidence), | |
| 362 | + "trap_choice": seg.trap_choice, | |
| 363 | + "rationale": seg.rationale, | |
| 364 | + "model": seg.model, | |
| 365 | + "prompt_version": seg.prompt_version, | |
| 366 | + "variant": seg.variant, | |
| 367 | + "computed_at": seg.computed_at, | |
| 368 | + "retain_until": _retain_until("question_segment", seg.computed_at), | |
| 369 | + "downstream_dimensions": list(seg.downstream_dimensions), | |
| 370 | + "experimental_dimensions": list(seg.experimental_dimensions), | |
| 371 | + } | |
| 372 | + ) | |
| 373 | + return rows | |
| 377 | 374 | |
| 378 | 375 | |
| 379 | -def _merge_object(var: str, row: dict[str, Any]) -> str: | |
| 380 | - """Satırı SurrealQL nesne sözdizimine çevirir (değerler değişkenden gelir). | |
| 376 | +def profile_rows(profiles: list[StudentSegmentProfile]) -> list[dict[str, Any]]: | |
| 377 | + """`insight.profile.upsert` satırları. | |
| 381 | 378 | |
| 382 | - Değerlerin kendisi **metne gömülmez**: her alan `$vN.alan` olarak | |
| 383 | - başvurulur, yalnız kaçış sorunu olmayan alan adları metne girer. | |
| 379 | + Güven kapısının **altındaki** satırlar da yazılır: depo ham olguyu tutar, | |
| 380 | + gösterme kararını `recommend.py` verir. | |
| 384 | 381 | """ |
| 385 | - parts: list[str] = [] | |
| 386 | - for key, value in row.items(): | |
| 387 | - if not _SAFE_FIELD.match(key): | |
| 388 | - raise ValueError(f"güvensiz alan adı: {key!r}") | |
| 389 | - ref = f"${var}.{key}" | |
| 390 | - if _is_record_like(value): | |
| 391 | - expr = f"type::string({ref})" | |
| 392 | - elif isinstance(value, list) and any(_is_record_like(v) for v in value): | |
| 393 | - expr = f"array::map({ref}, |$x| type::string($x))" | |
| 394 | - else: | |
| 395 | - expr = ref | |
| 396 | - parts.append(f"{key}: {expr}") | |
| 397 | - return "{ " + ", ".join(parts) + " }" | |
| 398 | - | |
| 399 | - | |
| 400 | -def _retain_until(table: str, base_ms: int) -> int: | |
| 401 | - return base_ms + RETENTION_DAYS[table] * clock.DAY_MS | |
| 402 | - | |
| 403 | - | |
| 404 | -def summary_row(summary: StudentSummary) -> dict[str, Any]: | |
| 405 | - """`student_summary` satırı — `schema/zeka.surql` §1 ile birebir.""" | |
| 406 | - return { | |
| 407 | - "school": summary.school, | |
| 408 | - "student": summary.student, | |
| 409 | - "marks": summary.marks, | |
| 410 | - "attendance": summary.attendance, | |
| 411 | - "submission": summary.submission, | |
| 412 | - "study": summary.study, | |
| 413 | - # Dikkat maddeleri: her öğe tek tetikleyici. Skor/sıra alanı YOK. | |
| 414 | - "attention": summary.attention, | |
| 415 | - "confidence": str(summary.confidence), | |
| 416 | - "computed_at": summary.computed_at, | |
| 417 | - "retain_until": _retain_until("student_summary", summary.computed_at), | |
| 418 | - } | |
| 382 | + return [ | |
| 383 | + { | |
| 384 | + "student": p.student, | |
| 385 | + "dimension": p.dimension, | |
| 386 | + "label": p.label, | |
| 387 | + "n_answers": p.n_answers, | |
| 388 | + "n_correct": p.n_correct, | |
| 389 | + "accuracy": round(p.accuracy, 6), | |
| 390 | + "overall_n_answers": p.overall_n_answers, | |
| 391 | + "overall_accuracy": round(p.overall_accuracy, 6), | |
| 392 | + "contrast": round(p.contrast, 6), | |
| 393 | + "confidence": str(p.confidence), | |
| 394 | + "computed_at": p.computed_at, | |
| 395 | + "retain_until": _retain_until("student_segment_profile", p.computed_at), | |
| 396 | + } | |
| 397 | + for p in profiles | |
| 398 | + ] | |
| 399 | + | |
| 400 | + | |
| 401 | +#: `insight.run.upsert` payload'ının kabul ettiği alanlar. Fazlası | |
| 402 | +#: gönderilmez: sözleşmede olmayan bir alan `invalid_payload` üretirdi. | |
| 403 | +RUN_FIELDS = ( | |
| 404 | + "run_day", | |
| 405 | + "started_at", | |
| 406 | + "finished_at", | |
| 407 | + "status", | |
| 408 | + "duration_ms", | |
| 409 | + "students_total", | |
| 410 | + "students_ok", | |
| 411 | + "students_failed", | |
| 412 | + "students_skipped", | |
| 413 | + "rows_written", | |
| 414 | + "budget_exceeded", | |
| 415 | + "budget_ms", | |
| 416 | + "retain_until", | |
| 417 | + "pending_students", | |
| 418 | + "failed_modules", | |
| 419 | +) | |
| 419 | 420 | |
| 420 | 421 | |
| 421 | -def recommendation_row(rec: Recommendation) -> dict[str, Any]: | |
| 422 | - """`recommendation` satırı — `schema/zeka.surql` §2 ile birebir. | |
| 422 | +def run_row(run_row: dict[str, Any], key: str) -> dict[str, Any]: | |
| 423 | + """Koşu defteri satırı + `run_day` + varsayılan `retain_until`. | |
| 423 | 424 | |
| 424 | - `retain_until = min(expires_at, created_at + 90 gün)` (`[T§6.7]`). | |
| 425 | - """ | |
| 426 | - ninety = _retain_until("recommendation", rec.computed_at) | |
| 427 | - return { | |
| 428 | - "school": rec.school, | |
| 429 | - "audience": rec.audience, | |
| 430 | - "about": rec.about, | |
| 431 | - "audience_role": str(rec.audience_role), | |
| 432 | - "product": rec.product, | |
| 433 | - "course": rec.course, | |
| 434 | - "rule_id": rec.rule_id, | |
| 435 | - "rule_version": rec.rule_version, | |
| 436 | - "evidence": {**rec.evidence, "limitation": rec.limitation}, | |
| 437 | - "confidence": str(rec.confidence), | |
| 438 | - "created_at": rec.computed_at, | |
| 439 | - "expires_at": rec.expires_at, | |
| 440 | - "retain_until": min(rec.expires_at, ninety), | |
| 441 | - "dismissed_at": None, | |
| 442 | - "dismissed_by": None, | |
| 443 | - "dismiss_reason": None, | |
| 444 | - } | |
| 445 | - | |
| 446 | - | |
| 447 | -def question_segment_row(seg: QuestionSegment) -> dict[str, Any]: | |
| 448 | - """`question_segment` satırı — `schema/zeka.surql` §4 ile birebir. | |
| 449 | - | |
| 450 | - Boyut adları **doğrudan alan adı** olur (`labels` sözlüğü yayılır). Bu | |
| 451 | - bilinçli: `rubric.py` yeni bir boyut eklerse SCHEMAFULL tablo satırı | |
| 452 | - reddeder ve hata **gürültülü** olur. Sessizce düşen bir boyut, "etiketledik" | |
| 453 | - denip hiçbir yere yazılmamasının ta kendisi olurdu. | |
| 425 | + Gün backend'de YENİDEN TÜRETİLMEZ: TR gününü bilen taraf bu taraf, o | |
| 426 | + yüzden `key`'in son on karakteri (`YYYY-MM-DD`) açıkça gönderilir. | |
| 454 | 427 | """ |
| 455 | - return { | |
| 456 | - "school": seg.school, | |
| 457 | - "question": seg.question, | |
| 458 | - "exam": seg.exam, | |
| 459 | - "course": seg.course, | |
| 460 | - "subject": seg.subject, | |
| 461 | - **{name: str(label) for name, label in seg.labels.items()}, | |
| 462 | - **{ | |
| 463 | - f"confidence_{name}": float(value) | |
| 464 | - for name, value in seg.confidences.items() | |
| 465 | - }, | |
| 466 | - "confidence": str(seg.confidence), | |
| 467 | - "downstream_dimensions": list(seg.downstream_dimensions), | |
| 468 | - "experimental_dimensions": list(seg.experimental_dimensions), | |
| 469 | - "trap_choice": seg.trap_choice, | |
| 470 | - "rationale": seg.rationale, | |
| 471 | - "model": seg.model, | |
| 472 | - "prompt_version": seg.prompt_version, | |
| 473 | - "variant": seg.variant, | |
| 474 | - "computed_at": seg.computed_at, | |
| 475 | - "retain_until": _retain_until("question_segment", seg.computed_at), | |
| 476 | - } | |
| 477 | - | |
| 478 | - | |
| 479 | -def student_segment_profile_row(profile: StudentSegmentProfile) -> dict[str, Any]: | |
| 480 | - """`student_segment_profile` satırı — `schema/zeka.surql` §5 ile birebir. | |
| 481 | - | |
| 482 | - `accuracy` ve `contrast` satıra **hesaplanmış** yazılır; okuyan tarafın | |
| 483 | - (frontend, backend) bölme yapması gerekmesin ve iki taraf farklı sonuç | |
| 484 | - bulmasın diye. `contrast` bu tablonun asıl ölçüsüdür — açıklaması | |
| 485 | - `compute/segments.py` baş yorumunda. | |
| 486 | - """ | |
| 487 | - return { | |
| 488 | - "school": profile.school, | |
| 489 | - "student": profile.student, | |
| 490 | - "dimension": profile.dimension, | |
| 491 | - "label": profile.label, | |
| 492 | - "n_answers": profile.n_answers, | |
| 493 | - "n_correct": profile.n_correct, | |
| 494 | - "accuracy": round(profile.accuracy, 6), | |
| 495 | - "overall_n_answers": profile.overall_n_answers, | |
| 496 | - "overall_accuracy": round(profile.overall_accuracy, 6), | |
| 497 | - "contrast": round(profile.contrast, 6), | |
| 498 | - "confidence": str(profile.confidence), | |
| 499 | - "computed_at": profile.computed_at, | |
| 500 | - "retain_until": _retain_until( | |
| 501 | - "student_segment_profile", profile.computed_at | |
| 502 | - ), | |
| 503 | - } | |
| 504 | - | |
| 505 | - | |
| 506 | -@dataclasses.dataclass(slots=True) | |
| 507 | -class WriteReport: | |
| 508 | - """Yazma muhasebesi; `insight_run` satırını besler.""" | |
| 428 | + row = {name: run_row.get(name) for name in RUN_FIELDS if name in run_row} | |
| 429 | + row.setdefault("run_day", key[-10:]) | |
| 430 | + started = int(run_row.get("started_at") or 0) | |
| 431 | + if row.get("retain_until") is None: | |
| 432 | + row["retain_until"] = _retain_until("insight_run", started) | |
| 433 | + row.setdefault("pending_students", []) | |
| 434 | + row.setdefault("failed_modules", []) | |
| 435 | + return row | |
| 509 | 436 | |
| 510 | - written: int = 0 | |
| 511 | - rejected: int = 0 | |
| 512 | - skipped_batches: int = 0 | |
| 513 | 437 | |
| 438 | +# =========================================================================== | |
| 439 | +# Depo | |
| 440 | +# =========================================================================== | |
| 514 | 441 | |
| 515 | -class Store: | |
| 516 | - """Toplu UPSERT + süpürme.""" | |
| 517 | 442 | |
| 518 | - def __init__(self, client: DbClient, *, batch_size: int = BATCH_SIZE) -> None: | |
| 519 | - self._client = client | |
| 520 | - self._batch_size = batch_size | |
| 443 | +class BridgeStore: | |
| 444 | + """Okul dizini + okul başına depo — hepsi köprüden. | |
| 521 | 445 | |
| 522 | - # -- yazma -------------------------------------------------------------- | |
| 446 | + Zamanlayıcı `store_for(school)` ile o okulun deposunu ister; dönen nesne | |
| 447 | + `pipeline`'ın beklediği sekiz metodu taşır. Paylaşılan bir depo YOKTUR ve | |
| 448 | + olmamalıdır: yanlış okula yazmanın en kolay yolu paylaşılan bir | |
| 449 | + nesnenin okul alanını unutmaktır; burada okul nesnenin kimliğindedir. | |
| 450 | + """ | |
| 523 | 451 | |
| 524 | - async def _upsert_batch( | |
| 452 | + def __init__( | |
| 525 | 453 | self, |
| 526 | - table: str, | |
| 527 | - rows: list[tuple[str, dict[str, Any]]], | |
| 454 | + caller: BridgeCaller | Callable[[], BridgeCaller | None], | |
| 528 | 455 | *, |
| 529 | - mode: str = "CONTENT", | |
| 530 | - ) -> bool: | |
| 531 | - """Tek transaction içinde bir grup UPSERT. Başarıyı döndürür. | |
| 532 | - | |
| 533 | - `mode="CONTENT"` satırı tümüyle değiştirir; `mode="MERGE"` yalnız | |
| 534 | - verilen alanları günceller ve dokunulmayanları korur. `recommendation` | |
| 535 | - MERGE kullanır: `dismissed_at` / `dismissed_by` / `dismiss_reason` | |
| 536 | - alanları **insan müdahalesi izidir** (KVKK m.11) ve hesap hattı onları | |
| 537 | - hiç üretmez. CONTENT ile yazılsaydı, her gece koşusu kullanıcının | |
| 538 | - "bu tavsiye faydalı değil" kaydını sessizce silerdi. | |
| 539 | - | |
| 540 | - Kayıt anahtarları kompozit → tekillik yapısaldır, UNIQUE indekse gerek | |
| 541 | - yok ve tekrar çalıştırma zararsızdır (`MODULLER.md` §2.11 adım 1). | |
| 542 | - """ | |
| 543 | - parts = ["BEGIN TRANSACTION;"] | |
| 544 | - variables: dict[str, Any] = {} | |
| 545 | - for i, (key, row) in enumerate(rows): | |
| 546 | - clean = _drop_nulls(row) | |
| 547 | - parts.append( | |
| 548 | - f"UPSERT type::record('{table}', $k{i}) {mode} " | |
| 549 | - f"{_merge_object(f'v{i}', clean)};" | |
| 456 | + batch_size: int = BATCH_SIZE, | |
| 457 | + attempts: int = MAX_ATTEMPTS, | |
| 458 | + timeout_secs: float | None = None, | |
| 459 | + ) -> None: | |
| 460 | + self._caller = caller | |
| 461 | + self._batch_size = batch_size | |
| 462 | + self._attempts = attempts | |
| 463 | + #: Okuma çağrıları için zaman aşımı (yazma grupları için de aynısı). | |
| 464 | + self._timeout = timeout_secs | |
| 465 | + | |
| 466 | + # -- taşıma ------------------------------------------------------------- | |
| 467 | + | |
| 468 | + def caller(self) -> BridgeCaller: | |
| 469 | + """Şu an bağlı taşıma. Yoksa `BridgeUnavailable` — sessizce yutulmaz.""" | |
| 470 | + target = self._caller() if callable(self._caller) else self._caller | |
| 471 | + if target is None: | |
| 472 | + raise BridgeUnavailable( | |
| 473 | + "köprü henüz bağlı değil; insight.* çağrısı yapılamaz" | |
| 550 | 474 | ) |
| 551 | - variables[f"k{i}"] = key | |
| 552 | - variables[f"v{i}"] = clean | |
| 553 | - parts.append("COMMIT TRANSACTION;") | |
| 554 | - sql = "\n".join(parts) | |
| 475 | + return target | |
| 555 | 476 | |
| 556 | - for attempt in range(1, MAX_ATTEMPTS + 1): | |
| 477 | + async def _call(self, capability: str, school: str, payload: dict[str, Any]) -> dict[str, Any]: | |
| 478 | + target = self.caller() | |
| 479 | + if capability in DEPLOYMENT_SCOPED: | |
| 480 | + school = "" | |
| 481 | + call = target.call | |
| 482 | + try: | |
| 483 | + reply = call(capability, school, payload) | |
| 484 | + if self._timeout is None: | |
| 485 | + return await reply | |
| 486 | + import asyncio | |
| 487 | + | |
| 488 | + return await asyncio.wait_for(reply, timeout=self._timeout) | |
| 489 | + except CapabilityRefused: | |
| 490 | + raise | |
| 491 | + except Exception as exc: # noqa: BLE001 — taşıma hatası aynı sözleşmeye bağlanır | |
| 492 | + raise CapabilityRefused( | |
| 493 | + "unavailable", str(exc), capability=capability, school=school | |
| 494 | + ) from exc | |
| 495 | + | |
| 496 | + async def _attempt( | |
| 497 | + self, | |
| 498 | + capability: str, | |
| 499 | + payload: dict[str, Any], | |
| 500 | + *, | |
| 501 | + school: str, | |
| 502 | + table: str, | |
| 503 | + count: int, | |
| 504 | + ) -> dict[str, Any] | None: | |
| 505 | + """Bir grubu `MAX_ATTEMPTS` kez dener; ikinci düşüşte `None` döner.""" | |
| 506 | + for attempt in range(1, self._attempts + 1): | |
| 557 | 507 | try: |
| 558 | - await self._client.query(sql, variables) | |
| 559 | - return True | |
| 508 | + return await self._call(capability, school, payload) | |
| 560 | 509 | except Exception as exc: # noqa: BLE001 — hat devam etmeli |
| 561 | 510 | log.warning( |
| 562 | - "toplu yazma düştü (tablo=%s, deneme=%d/%d): %s", | |
| 511 | + "köprü yazması düştü (tablo=%s, deneme=%d/%d): %s", | |
| 563 | 512 | table, |
| 564 | 513 | attempt, |
| 565 | - MAX_ATTEMPTS, | |
| 514 | + self._attempts, | |
| 566 | 515 | exc, |
| 567 | 516 | ) |
| 568 | - log.warning("grup atlandı (tablo=%s, satır=%d)", table, len(rows)) | |
| 569 | - return False | |
| 517 | + log.warning("grup atlandı (tablo=%s, satır=%d)", table, count) | |
| 518 | + return None | |
| 570 | 519 | |
| 571 | - async def _write_rows( | |
| 572 | - self, | |
| 573 | - table: str, | |
| 574 | - rows: list[tuple[str, dict[str, Any]]], | |
| 575 | - *, | |
| 576 | - mode: str = "CONTENT", | |
| 577 | - ) -> WriteReport: | |
| 578 | - report = WriteReport() | |
| 579 | - for start in range(0, len(rows), self._batch_size): | |
| 580 | - chunk = rows[start : start + self._batch_size] | |
| 581 | - if await self._upsert_batch(table, chunk, mode=mode): | |
| 582 | - report.written += len(chunk) | |
| 583 | - else: | |
| 520 | + # -- okuma -------------------------------------------------------------- | |
| 521 | + | |
| 522 | + async def active_schools(self) -> list[str]: | |
| 523 | + """Bu dağıtımdaki **aktif** okullar (`insight.schools.list`). | |
| 524 | + | |
| 525 | + Okul listesi artık yapılandırmadan DEĞİL backend'den gelir. Okunamazsa | |
| 526 | + hata yükselir; zamanlayıcı bunu yakalar ve turu okulsuz koşar | |
| 527 | + (`scheduler._listing`), yani açılış da bir tik de düşmez. | |
| 528 | + """ | |
| 529 | + reply = await self._call(CAP_SCHOOLS, "", {}) | |
| 530 | + schools = reply.get("schools") | |
| 531 | + if not isinstance(schools, list): | |
| 532 | + raise CapabilityRefused( | |
| 533 | + "invalid_payload", | |
| 534 | + f"okul listesi beklenen biçimde değil: {reply!r}", | |
| 535 | + capability=CAP_SCHOOLS, | |
| 536 | + school="", | |
| 537 | + ) | |
| 538 | + return sorted({str(s) for s in schools if str(s).strip()}) | |
| 539 | + | |
| 540 | + def store_for(self, school: str) -> "SchoolStore": | |
| 541 | + """Okula bağlı depo. Ağ beklemez: nesne kurmak bir çağrı değildir.""" | |
| 542 | + return SchoolStore(self, school) | |
| 543 | + | |
| 544 | + async def close(self) -> None: | |
| 545 | + """Simetri için: kapatılacak bağlantı YOKTUR.""" | |
| 546 | + return None | |
| 547 | + | |
| 548 | + | |
| 549 | +class SchoolStore: | |
| 550 | + """Tek okulun deposu. Okul nesnenin kimliğidir, çağrının argümanı değil.""" | |
| 551 | + | |
| 552 | + def __init__(self, parent: BridgeStore, school: str) -> None: | |
| 553 | + self._parent = parent | |
| 554 | + self._school = school | |
| 555 | + | |
| 556 | + @property | |
| 557 | + def school(self) -> str: | |
| 558 | + return self._school | |
| 559 | + | |
| 560 | + async def _send(self, capability: str, payload: dict[str, Any]) -> dict[str, Any]: | |
| 561 | + return await self._parent._call(capability, self._school, payload) | |
| 562 | + | |
| 563 | + # -- yazma -------------------------------------------------------------- | |
| 564 | + | |
| 565 | + async def _chunked(self, capability: str, rows: list[dict[str, Any]], *, table: str) -> WriteReport: | |
| 566 | + """Grup grup yaz. Düşen grup raporda GÖRÜNÜR kalır.""" | |
| 567 | + report = WriteReport(table=table) | |
| 568 | + for start in range(0, len(rows), self._parent._batch_size): | |
| 569 | + chunk = rows[start : start + self._parent._batch_size] | |
| 570 | + reply = await self._parent._attempt( | |
| 571 | + capability, | |
| 572 | + {"rows": chunk}, | |
| 573 | + school=self._school, | |
| 574 | + table=table, | |
| 575 | + count=len(chunk), | |
| 576 | + ) | |
| 577 | + if reply is None: | |
| 584 | 578 | report.skipped_batches += 1 |
| 579 | + continue | |
| 580 | + report.written += int(reply.get("written", len(chunk))) | |
| 581 | + if reply.get("rejected"): | |
| 582 | + report.rejected += int(reply["rejected"]) | |
| 585 | 583 | return report |
| 586 | 584 | |
| 587 | 585 | async def write_summaries(self, summaries: list[StudentSummary]) -> WriteReport: |
| 588 | - rows = [(s.record_key(), summary_row(s)) for s in summaries] | |
| 589 | - return await self._write_rows("student_summary", rows) | |
| 586 | + """Özetleri ve dikkat maddelerini yazar (dikkat: sil-ve-yaz, sunucuda).""" | |
| 587 | + return await self._chunked(CAP_SUMMARY, summary_rows(summaries), table="zeka_student_summary") | |
| 588 | + | |
| 589 | + async def write_recommendations(self, recs: list[Recommendation]) -> WriteReport: | |
| 590 | + """Tavsiyeleri yazar. **Kanıtsız satır reddedilir.**""" | |
| 591 | + rows, rejected = recommendation_rows(recs) | |
| 592 | + report = await self._chunked(CAP_RECOMMENDATION, rows, table="zeka_recommendation") | |
| 593 | + report.rejected += rejected | |
| 594 | + return report | |
| 590 | 595 | |
| 591 | - async def write_recommendations( | |
| 592 | - self, recs: list[Recommendation] | |
| 593 | - ) -> WriteReport: | |
| 594 | - """Tavsiyeleri yazar. **Kanıtsız satır reddedilir.** | |
| 596 | + async def write_question_segments(self, segments: list[QuestionSegment]) -> WriteReport: | |
| 597 | + """Soru segment etiketlerini ve boyut ayrımını yazar.""" | |
| 598 | + return await self._chunked(CAP_SEGMENT, segment_rows(segments), table="zeka_question_segment") | |
| 595 | 599 | |
| 596 | - `Recommendation` zaten boş kanıtla kurulamaz; buradaki ikinci kontrol, | |
| 597 | - sözlükten yeniden kurulan (örn. yeniden oynatılan) satırlar içindir — | |
| 598 | - `MODULLER.md` §2.10 yapısal kural 1 depolama katmanında da geçerlidir. | |
| 599 | - """ | |
| 600 | - rows: list[tuple[str, dict[str, Any]]] = [] | |
| 601 | - rejected = 0 | |
| 602 | - for rec in recs: | |
| 603 | - row = recommendation_row(rec) | |
| 604 | - evidence = row.get("evidence") or {} | |
| 605 | - # `limitation` dışında hiç kanıt yoksa satır kanıtsızdır. | |
| 606 | - if not {k: v for k, v in evidence.items() if k != "limitation"}: | |
| 607 | - log.warning("kanıtsız tavsiye reddedildi: %s", rec.rule_id) | |
| 608 | - rejected += 1 | |
| 609 | - continue | |
| 610 | - rows.append((rec.record_key(), row)) | |
| 611 | - # MERGE: insan müdahalesi izi (`dismissed_*`) korunur. | |
| 612 | - report = await self._write_rows("recommendation", rows, mode="MERGE") | |
| 613 | - report.rejected = rejected | |
| 614 | - return report | |
| 600 | + async def write_segment_profiles(self, profiles: list[StudentSegmentProfile]) -> WriteReport: | |
| 601 | + """Öğrenci segment profillerini yazar.""" | |
| 602 | + return await self._chunked(CAP_PROFILE, profile_rows(profiles), table="zeka_student_segment_profile") | |
| 615 | 603 | |
| 616 | - async def write_question_segments( | |
| 617 | - self, segments: list[QuestionSegment] | |
| 618 | - ) -> WriteReport: | |
| 619 | - """Soru segment etiketlerini yazar. | |
| 604 | + async def write_run(self, row: dict[str, Any], key: str) -> bool: | |
| 605 | + """Koşu defteri satırını yazar (koşu başında ve sonunda birer kez). | |
| 620 | 606 | |
| 621 | - **MERGE**, CONTENT değil: aynı soruya ileride başka bir kaynaktan alan | |
| 622 | - eklenebilir (örn. insan doğrulaması) ve gece koşusu onu silmemelidir — | |
| 623 | - `recommendation` tablosundaki `dismissed_*` ile aynı gerekçe. | |
| 624 | - """ | |
| 625 | - rows = [(s.record_key(), question_segment_row(s)) for s in segments] | |
| 626 | - return await self._write_rows("question_segment", rows, mode="MERGE") | |
| 627 | - | |
| 628 | - async def write_segment_profiles( | |
| 629 | - self, profiles: list[StudentSegmentProfile] | |
| 630 | - ) -> WriteReport: | |
| 631 | - """Öğrenci segment profillerini yazar. | |
| 632 | - | |
| 633 | - Güven kapısının **altındaki** satırlar da yazılır: depo ham olguyu | |
| 634 | - tutar, gösterme/tavsiye kararını `recommend.py` verir. Kapının depoda | |
| 635 | - değil kuralda olmasının sebebi, eşiğin ölçümle değişebilmesidir — | |
| 636 | - eşik değişince veriyi yeniden üretmek gerekmesin. | |
| 607 | + Gün `key`'den burada çözülür (TR günü), `retain_until` burada | |
| 608 | + varsayılanlanır. `False` = yazılamadı; çağıran bunu başarı saymaz. | |
| 637 | 609 | """ |
| 638 | - rows = [ | |
| 639 | - (p.record_key(), student_segment_profile_row(p)) for p in profiles | |
| 640 | - ] | |
| 641 | - return await self._write_rows("student_segment_profile", rows, mode="MERGE") | |
| 642 | - | |
| 643 | - async def write_run(self, run_row: dict[str, Any], key: str) -> bool: | |
| 644 | - """`insight_run` satırını yazar (koşu başında ve sonunda birer kez).""" | |
| 645 | - row = dict(run_row) | |
| 646 | - row.setdefault( | |
| 647 | - "retain_until", _retain_until("insight_run", int(row["started_at"])) | |
| 610 | + payload = {"run": run_row(row, key)} | |
| 611 | + reply = await self._parent._attempt( | |
| 612 | + CAP_RUN, payload, school=self._school, table="zeka_run", count=1 | |
| 648 | 613 | ) |
| 649 | - return await self._upsert_batch("insight_run", [(key, row)]) | |
| 614 | + return reply is not None | |
| 650 | 615 | |
| 651 | 616 | # -- okuma -------------------------------------------------------------- |
| 652 | 617 | |
| 653 | - async def last_pending(self, school: str) -> list[str]: | |
| 618 | + async def last_pending(self, school: str = "") -> list[str]: | |
| 654 | 619 | """Bu okulun son koşusundan devreden öğrenci kimlikleri. |
| 655 | 620 | |
| 656 | - Zamanlayıcının bellek içi `pending` sözlüğü süreç yeniden başlayınca | |
| 657 | - kaybolur; "bir sonraki koşu kaldığı yerden devam eder" cümlesinin | |
| 658 | - yeniden başlatmaya da dayanması için kaynak **`insight_run` satırıdır**. | |
| 621 | + `school` KULLANILMIYOR: okul çerçevededir, nesnenin kimliğindedir. | |
| 622 | + Parametre, çağrı yerlerini değiştirmemek için duruyor. | |
| 659 | 623 | |
| 660 | 624 | Okunamazsa boş liste döner: devretmemek, yanlış listeyle koşmaktan |
| 661 | - iyidir (`MODULLER.md` §3.4 "bayat veri, yanlış veriden iyidir"in | |
| 662 | - tersi yönü: burada eksik bilgi zarar vermez, yanlış bilgi verir). | |
| 625 | + iyidir. | |
| 663 | 626 | """ |
| 664 | - sql = ( | |
| 665 | - "SELECT pending_students FROM insight_run WHERE school = $school " | |
| 666 | - "ORDER BY started_at DESC LIMIT 1;" | |
| 667 | - ) | |
| 668 | 627 | try: |
| 669 | - rows = await self._client.query(sql, {"school": school}) | |
| 628 | + reply = await self._send(CAP_PENDING, {}) | |
| 670 | 629 | except Exception as exc: # noqa: BLE001 |
| 671 | - log.warning("bekleyen liste okunamadı (okul=%s): %s", school, exc) | |
| 630 | + log.warning("bekleyen liste okunamadı (okul=%s): %s", self._school, exc) | |
| 631 | + return [] | |
| 632 | + students = reply.get("students") | |
| 633 | + if not isinstance(students, list): | |
| 634 | + log.warning("bekleyen liste beklenen biçimde değil (okul=%s)", self._school) | |
| 672 | 635 | return [] |
| 673 | - return _first_pending(rows) | |
| 636 | + return [str(s) for s in students] | |
| 674 | 637 | |
| 675 | 638 | # -- süpürme ------------------------------------------------------------ |
| 676 | 639 | |
| 677 | 640 | async def sweep(self, now_ms: int) -> dict[str, bool]: |
| 678 | - """Saklama süresi dolmuş satırları siler. | |
| 641 | + """Saklama süresi dolmuş satırları sildirir. | |
| 679 | 642 | |
| 680 | - `MODULLER.md` §2.11 adım 2. Süpürme hattın **en sonunda**, okul bazında | |
| 681 | - ve sıralı koşar; büyük silmeyi gündüze taşımamak için gece yapılır. | |
| 643 | + `now_ms` GÖNDERİLMEZ: saati backend kendi damgalar — iki saatli bir | |
| 644 | + süpürme, "hangi gün" sorusuna iki cevap verirdi. Parametre çağrı | |
| 645 | + yerlerini değiştirmemek için duruyor. | |
| 646 | + | |
| 647 | + Dönen sözlük tablo başına karardır; düşen tablo `False` olur ve CLI | |
| 648 | + sıfırdan farklı çıkar. | |
| 682 | 649 | """ |
| 683 | - results: dict[str, bool] = {} | |
| 684 | - for table in RETENTION_DAYS: | |
| 685 | - sql = f"DELETE {table} WHERE retain_until < $now;" | |
| 686 | - try: | |
| 687 | - await self._client.query(sql, {"now": now_ms}) | |
| 688 | - results[table] = True | |
| 689 | - except Exception as exc: # noqa: BLE001 | |
| 690 | - log.warning("süpürme düştü (tablo=%s): %s", table, exc) | |
| 691 | - results[table] = False | |
| 692 | - return results | |
| 650 | + try: | |
| 651 | + reply = await self._send(CAP_SWEEP, {}) | |
| 652 | + except Exception as exc: # noqa: BLE001 | |
| 653 | + log.warning("süpürme düştü (okul=%s): %s", self._school, exc) | |
| 654 | + return {table: False for table in SWEEP_TABLES} | |
| 655 | + tables = reply.get("tables") | |
| 656 | + if not isinstance(tables, dict): | |
| 657 | + log.warning("süpürme cevabı beklenen biçimde değil (okul=%s)", self._school) | |
| 658 | + return {table: False for table in SWEEP_TABLES} | |
| 659 | + return {table: bool(tables.get(table)) for table in SWEEP_TABLES} | |
| 693 | 660 | |
| 694 | 661 | async def purge_departed(self, school: str, active_students: list[str]) -> bool: |
| 695 | - """Artık öğrenci olmayanların türetilmiş verisini siler. | |
| 662 | + """Artık öğrenci olmayanların türetilmiş verisini sildirir. | |
| 696 | 663 | |
| 697 | - `MODULLER.md` §2.11 adım 3 / `[T§6.7]` mezuniyet adımı 2: "mezunun ham | |
| 698 | - verisi arşivde kalabilir; **profili kalmamalıdır**." | |
| 664 | + `MODULLER.md` §2.11 adım 3: "mezunun ham verisi arşivde kalabilir; | |
| 665 | + **profili kalmamalıdır**." `question_segment` buraya girmez: o satır | |
| 666 | + bir soru hakkındadır, kişiye bağlanamaz. | |
| 699 | 667 | |
| 700 | - `question_segment` buraya **girmez**: o satır bir soru hakkındadır, | |
| 701 | - hiçbir öğrenciye bağlanamaz — mezuniyetle silinecek bir kişisel veri | |
| 702 | - değildir. `student_segment_profile` ise kişiseldir ve silinir. | |
| 668 | + **Boş liste çağrı YAPMAZ**: boş liste "okulda kimse yok" değil, | |
| 669 | + "liste çekilemedi" demektir ve herkesin verisini silerdi. Sunucu da | |
| 670 | + boş listeyi `invalid_payload` ile reddeder; buradaki kapı ondan önce | |
| 671 | + durur. | |
| 703 | 672 | """ |
| 704 | - sql = ( | |
| 705 | - "DELETE student_summary WHERE school = $school " | |
| 706 | - "AND student NOT IN $active;\n" | |
| 707 | - "DELETE student_segment_profile WHERE school = $school " | |
| 708 | - "AND student NOT IN $active;\n" | |
| 709 | - "DELETE recommendation WHERE school = $school " | |
| 710 | - "AND about != NONE AND about NOT IN $active;" | |
| 711 | - ) | |
| 673 | + if not active_students: | |
| 674 | + log.warning("mezuniyet temizliği atlandı (okul=%s): aktif liste boş", self._school) | |
| 675 | + return False | |
| 712 | 676 | try: |
| 713 | - await self._client.query( | |
| 714 | - sql, {"school": school, "active": active_students} | |
| 715 | - ) | |
| 716 | - return True | |
| 677 | + reply = await self._send(CAP_PURGE, {"students": [str(s) for s in active_students]}) | |
| 717 | 678 | except Exception as exc: # noqa: BLE001 |
| 718 | - log.warning("mezuniyet temizliği düştü (okul=%s): %s", school, exc) | |
| 679 | + log.warning("mezuniyet temizliği düştü (okul=%s): %s", self._school, exc) | |
| 719 | 680 | return False |
| 720 | - | |
| 721 | - | |
| 722 | -def _first_pending(rows: Any) -> list[str]: | |
| 723 | - """SurrealDB `/rpc` cevabından `pending_students` listesini çıkarır. | |
| 724 | - | |
| 725 | - Cevap iki katmanlı: ifade listesi → `result` listesi → satır. Sahte | |
| 726 | - istemciler boş liste döndürür; o da geçerli bir cevaptır. | |
| 727 | - """ | |
| 728 | - if not isinstance(rows, list): | |
| 729 | - return [] | |
| 730 | - for statement in rows: | |
| 731 | - result = statement.get("result") if isinstance(statement, dict) else statement | |
| 732 | - if not isinstance(result, list): | |
| 733 | - continue | |
| 734 | - for row in result: | |
| 735 | - if isinstance(row, dict): | |
| 736 | - values = row.get("pending_students") or [] | |
| 737 | - if isinstance(values, list): | |
| 738 | - return [str(v) for v in values] | |
| 739 | - return [] | |
| 681 | + tables = reply.get("tables") | |
| 682 | + if not isinstance(tables, dict): | |
| 683 | + return False | |
| 684 | + return all(bool(tables.get(table)) for table in PURGE_TABLES) | |
| 685 | + | |
| 686 | + | |
| 687 | +__all__ = [ | |
| 688 | + "BATCH_SIZE", | |
| 689 | + "MAX_ATTEMPTS", | |
| 690 | + "CAP_SUMMARY", | |
| 691 | + "CAP_RECOMMENDATION", | |
| 692 | + "CAP_SEGMENT", | |
| 693 | + "CAP_PROFILE", | |
| 694 | + "CAP_RUN", | |
| 695 | + "CAP_PENDING", | |
| 696 | + "CAP_SWEEP", | |
| 697 | + "CAP_PURGE", | |
| 698 | + "CAP_SCHOOLS", | |
| 699 | + "BridgeStore", | |
| 700 | + "SchoolStore", | |
| 701 | + "BridgeCaller", | |
| 702 | + "ProtocolCaller", | |
| 703 | + "BridgeUnavailable", | |
| 704 | + "CapabilityRefused", | |
| 705 | + "RecordingCaller", | |
| 706 | + "WriteReport", | |
| 707 | + "RETENTION_DAYS", | |
| 708 | + "SWEEP_TABLES", | |
| 709 | + "PURGE_TABLES", | |
| 710 | + "MAX_LIST_ROWS", | |
| 711 | + "attention_items", | |
| 712 | + "summary_rows", | |
| 713 | + "recommendation_rows", | |
| 714 | + "segment_rows", | |
| 715 | + "profile_rows", | |
| 716 | + "run_row", | |
| 717 | + "rows_or_err", | |
| 718 | +] |
service/src/store_factory.pydeleted+0 -91
| @@ -1,91 +0,0 @@ | ||
| 1 | -"""Depolama katmanini SECEN tek yer. | |
| 2 | - | |
| 3 | -ZEKA iki depoya yazabilir: | |
| 4 | - | |
| 5 | -* **PostgreSQL** (`store_pg.PgStore`) — okulun kendi veritabani. Backend | |
| 6 | - SurrealDB'den Postgres'e gectiginden beri dogru olan bu. | |
| 7 | -* **SurrealDB** (`store.Store`) — eski kurulum. Hala calisiyor ve testleri | |
| 8 | - geciyor; gecis tamamlanana kadar duruyor. | |
| 9 | - | |
| 10 | -Secim TEK bir degiskene bakar: `ZEKA_PG_DSN` doluysa Postgres, bossa SurrealDB. | |
| 11 | -Iki ayri "mod" bayragi yok, cunku bayrakla DSN birbirine ters dustugunde hangi | |
| 12 | -tarafin kazandigi tahmin isine doner. | |
| 13 | - | |
| 14 | ---------------------------------------------------------------------------- | |
| 15 | -Neden ayni arayuz | |
| 16 | ---------------------------------------------------------------------------- | |
| 17 | -`pipeline.py` ve `scheduler.py` hangi depoya yazdiklarini BILMEZ. Ikisi de | |
| 18 | -ayni sekiz yontemi cagirir (`write_summaries`, `write_recommendations`, | |
| 19 | -`write_question_segments`, `write_segment_profiles`, `write_run`, | |
| 20 | -`last_pending`, `sweep`, `purge_departed`). Gecisin hattaki maliyeti bu yuzden | |
| 21 | -sifir: depo degisti, hesap kodu degismedi. | |
| 22 | -""" | |
| 23 | - | |
| 24 | -from __future__ import annotations | |
| 25 | - | |
| 26 | -import logging | |
| 27 | -import os | |
| 28 | -from typing import Any | |
| 29 | - | |
| 30 | -log = logging.getLogger(__name__) | |
| 31 | - | |
| 32 | - | |
| 33 | -def is_postgres() -> bool: | |
| 34 | - """Postgres'e mi yazilacak? Tek olcut `ZEKA_PG_DSN`.""" | |
| 35 | - return bool(os.environ.get("ZEKA_PG_DSN", "").strip()) | |
| 36 | - | |
| 37 | - | |
| 38 | -async def open_store(dsn: str | None = None) -> tuple[Any, Any]: | |
| 39 | - """TEK veritabanina baglanir (eski mod / araclar). | |
| 40 | - | |
| 41 | - Coklu okul uretim yolu bu fonksiyon DEGILDIR: `tenants.open_directory` | |
| 42 | - kontrol veritabanindan okul dizinini kurar ve her okul icin ayri havuz | |
| 43 | - acar. Burada DSN neyi adlandiriyorsa ona baglanilir -- okul veritabani da | |
| 44 | - olabilir, kontrol veritabani da; karar cagiranindir. | |
| 45 | - | |
| 46 | - `(store, client)` doner; cagiran taraf isi bitince `client.close()` | |
| 47 | - cagirmalidir. | |
| 48 | - """ | |
| 49 | - target = (dsn or os.environ.get("ZEKA_PG_DSN", "")).strip() | |
| 50 | - if target: | |
| 51 | - from .pg_client import PsycopgClient | |
| 52 | - from .store_pg import PgStore | |
| 53 | - | |
| 54 | - client = await PsycopgClient.connect(target) | |
| 55 | - return PgStore(client), client | |
| 56 | - | |
| 57 | - from .store import Store, SurrealHttpClient | |
| 58 | - | |
| 59 | - url = os.environ.get("ZEKA_DB_HTTP_URL", "").strip() | |
| 60 | - if not url: | |
| 61 | - raise RuntimeError( | |
| 62 | - "Ne ZEKA_PG_DSN ne ZEKA_DB_HTTP_URL tanimli — nereye yazilacagi " | |
| 63 | - "belli degil. Postgres icin ZEKA_PG_DSN verin." | |
| 64 | - ) | |
| 65 | - log.warning( | |
| 66 | - "SurrealDB deposu kullaniliyor (ZEKA_PG_DSN bos). Backend Postgres'e " | |
| 67 | - "gecti; uretimde ZEKA_PG_DSN verilmelidir." | |
| 68 | - ) | |
| 69 | - client = SurrealHttpClient( | |
| 70 | - url, | |
| 71 | - namespace=os.environ.get("ZEKA_DB_NS", "hezarfen"), | |
| 72 | - database=os.environ.get("ZEKA_DB_NAME", "zeka"), | |
| 73 | - user=os.environ.get("ZEKA_DB_USER", "root"), | |
| 74 | - password=os.environ.get("ZEKA_DB_PASSWORD", "root"), | |
| 75 | - ) | |
| 76 | - return Store(client), client | |
| 77 | - | |
| 78 | - | |
| 79 | -def describe() -> str: | |
| 80 | - """Acilista loglanacak tek satir. DSN'in kendisi ASLA loglanmaz. | |
| 81 | - | |
| 82 | - Doluysa DSN KONTROL veritabanidir; okul ciktilari okul basina ayri | |
| 83 | - veritabanlarina yazilir (`tenants.py`). Satir bunu soyler. | |
| 84 | - """ | |
| 85 | - if not is_postgres(): | |
| 86 | - return "depo: SurrealDB (eski kurulum)" | |
| 87 | - from .pg_client import _describe | |
| 88 | - | |
| 89 | - return "depo: PostgreSQL kontrol (%s) — okullar kendi veritabanlarinda" % _describe( | |
| 90 | - os.environ["ZEKA_PG_DSN"] | |
| 91 | - ) |
service/src/store_pg.pydeleted+0 -748
| @@ -1,748 +0,0 @@ | ||
| 1 | -"""ZEKA'nın okul veritabanına (PostgreSQL) yazma katmanı. | |
| 2 | - | |
| 3 | -`src/store.py`'nin SurrealDB karşılığı. İkisi **yan yana** durur: mevcut | |
| 4 | -SurrealDB kurulumu çalışmaya devam ederken Postgres tarafı ayrı ayrı | |
| 5 | -sınanabilsin diye. Hattın gördüğü yüzey aynı olduğu için `pipeline.py` ve | |
| 6 | -`scheduler.py` değişmez. | |
| 7 | - | |
| 8 | -Şema: `schema/postgres/school/20260916000001_zeka.sql`. | |
| 9 | - | |
| 10 | ---------------------------------------------------------------------------- | |
| 11 | -TEK VE MUTLAK KURAL — değişmedi | |
| 12 | ---------------------------------------------------------------------------- | |
| 13 | -**Okul tablolarına asla yazılmaz.** Bu modülün dokunduğu her tablo `zeka_` | |
| 14 | -önekini taşır. Okul verisi yalnız `Source` arayüzü üzerinden, köprüden okunur. | |
| 15 | -`TABLES` listesi bu kuralın makine tarafından okunabilir hâlidir ve | |
| 16 | -`test_guard.py` her ifadenin hedefinin o listede olduğunu tarar. | |
| 17 | - | |
| 18 | ---------------------------------------------------------------------------- | |
| 19 | -SurrealDB sürümünden üç yapısal fark | |
| 20 | ---------------------------------------------------------------------------- | |
| 21 | -1. **`school` alanı yok.** Her okul kendi veritabanında; kiracı veritabanının | |
| 22 | - kendisidir. `school` parametresi imzalarda duruyor ama kullanılmıyor — | |
| 23 | - çağıran taraf değişmesin diye. | |
| 24 | - | |
| 25 | -2. **Diziler çocuk tabloda.** `attention`, `pending_students`, | |
| 26 | - `failed_modules`, `downstream/experimental_dimensions` artık ayrı | |
| 27 | - satırlardır. Bu yüzden yazma "üzerine yaz" değil, **sil-ve-yaz**: önce o | |
| 28 | - sahibin çocuk satırları silinir, sonra yenileri yazılır. Yalnız eklemek, | |
| 29 | - artık üretilmeyen bir dikkat maddesinin ekranda sonsuza kadar kalması | |
| 30 | - demek olurdu. | |
| 31 | - | |
| 32 | -3. **Yabancı anahtarlar gerçekten zorlanıyor.** Hepsi `ON DELETE NO ACTION`, | |
| 33 | - yani bir üst satır çocukları dururken silinemez. Süpürme ve mezuniyet | |
| 34 | - temizliği bu yüzden **önce çocuğu** siler. Ters sıra sessiz değil gürültülü | |
| 35 | - düşerdi, ama yine de düşerdi. | |
| 36 | -""" | |
| 37 | - | |
| 38 | -from __future__ import annotations | |
| 39 | - | |
| 40 | -import dataclasses | |
| 41 | -import logging | |
| 42 | -from typing import Any, Protocol, Sequence, runtime_checkable | |
| 43 | - | |
| 44 | -from .compute.model import ( | |
| 45 | - QuestionSegment, | |
| 46 | - Recommendation, | |
| 47 | - StudentSegmentProfile, | |
| 48 | - StudentSummary, | |
| 49 | -) | |
| 50 | -from .ids import uuid7 | |
| 51 | -from .store import ( | |
| 52 | - BATCH_SIZE, | |
| 53 | - MAX_ATTEMPTS, | |
| 54 | - RETENTION_DAYS, | |
| 55 | - WriteReport, | |
| 56 | - _retain_until, | |
| 57 | -) | |
| 58 | - | |
| 59 | -log = logging.getLogger(__name__) | |
| 60 | - | |
| 61 | -#: Bu modulun yazabilecegi TEK tablo kumesi. `test_guard.py` bunu okur. | |
| 62 | -TABLES = ( | |
| 63 | - "zeka_student_summary", | |
| 64 | - "zeka_attention_item", | |
| 65 | - "zeka_recommendation", | |
| 66 | - "zeka_run", | |
| 67 | - "zeka_run_pending", | |
| 68 | - "zeka_run_failed_module", | |
| 69 | - "zeka_question_segment", | |
| 70 | - "zeka_question_segment_dimension", | |
| 71 | - "zeka_student_segment_profile", | |
| 72 | -) | |
| 73 | - | |
| 74 | -#: Supurme sirasi: once cocuk, sonra ebeveyn. FK'ler NO ACTION oldugu icin | |
| 75 | -#: ters sira FK ihlaliyle duser. | |
| 76 | -SWEEP_ORDER = ( | |
| 77 | - ("zeka_attention_item", "zeka_student_summary", "student"), | |
| 78 | - ("zeka_question_segment_dimension", "zeka_question_segment", "question"), | |
| 79 | - ("zeka_run_pending", "zeka_run", "run"), | |
| 80 | - ("zeka_run_failed_module", "zeka_run", "run"), | |
| 81 | -) | |
| 82 | - | |
| 83 | - | |
| 84 | -@runtime_checkable | |
| 85 | -class PgClient(Protocol): | |
| 86 | - """Postgres istemcisinin ihtiyac duyulan tek yuzeyi. | |
| 87 | - | |
| 88 | - Surucu bagimsizligi `store.py` ile ayni gerekcede: bu modul bir Postgres | |
| 89 | - surucusu import etmez, testler ve `--dry-run` gercek veritabani olmadan | |
| 90 | - kosar. | |
| 91 | - """ | |
| 92 | - | |
| 93 | - async def execute(self, sql: str, params: Sequence[Any] = ()) -> None: ... | |
| 94 | - | |
| 95 | - async def executemany( | |
| 96 | - self, sql: str, rows: Sequence[Sequence[Any]] | |
| 97 | - ) -> None: ... | |
| 98 | - | |
| 99 | - async def fetch( | |
| 100 | - self, sql: str, params: Sequence[Any] = () | |
| 101 | - ) -> list[tuple[Any, ...]]: ... | |
| 102 | - | |
| 103 | - def transaction(self) -> Any: ... | |
| 104 | - | |
| 105 | - | |
| 106 | -class CollectingPgClient: | |
| 107 | - """Gercek veritabani yerine ifadeleri toplayan istemci (`--dry-run`).""" | |
| 108 | - | |
| 109 | - def __init__(self) -> None: | |
| 110 | - self.statements: list[tuple[str, Any]] = [] | |
| 111 | - | |
| 112 | - async def execute(self, sql: str, params: Sequence[Any] = ()) -> None: | |
| 113 | - self.statements.append((sql, list(params))) | |
| 114 | - | |
| 115 | - async def executemany( | |
| 116 | - self, sql: str, rows: Sequence[Sequence[Any]] | |
| 117 | - ) -> None: | |
| 118 | - self.statements.append((sql, [list(r) for r in rows])) | |
| 119 | - | |
| 120 | - async def fetch( | |
| 121 | - self, sql: str, params: Sequence[Any] = () | |
| 122 | - ) -> list[tuple[Any, ...]]: | |
| 123 | - self.statements.append((sql, list(params))) | |
| 124 | - return [] | |
| 125 | - | |
| 126 | - def transaction(self) -> Any: | |
| 127 | - return _NullTransaction() | |
| 128 | - | |
| 129 | - | |
| 130 | -class _NullTransaction: | |
| 131 | - async def __aenter__(self) -> None: | |
| 132 | - return None | |
| 133 | - | |
| 134 | - async def __aexit__(self, *exc: Any) -> bool: | |
| 135 | - return False | |
| 136 | - | |
| 137 | - | |
| 138 | -# --- satir donusturuculer --------------------------------------------------- | |
| 139 | -# | |
| 140 | -# `store.py`'deki `*_row` fonksiyonlari SurrealDB sekli uretir: `school` tasir, | |
| 141 | -# diziler gomuludur ve kimlikler metindir. Asagidakiler Postgres kolon | |
| 142 | -# sirasina gore DUZ demetler uretir; sozluk degil demet, cunku `executemany` | |
| 143 | -# pozisyonel parametre alir ve kolon sirasi tek bir yerde — INSERT ifadesinde — | |
| 144 | -# yazili olsun istiyoruz. | |
| 145 | - | |
| 146 | - | |
| 147 | -def summary_tuple(s: StudentSummary) -> tuple[Any, ...]: | |
| 148 | - return ( | |
| 149 | - s.student, | |
| 150 | - _json(s.marks), | |
| 151 | - _json(s.attendance), | |
| 152 | - _json(s.submission), | |
| 153 | - _json(s.study), | |
| 154 | - str(s.confidence), | |
| 155 | - s.computed_at, | |
| 156 | - _retain_until("student_summary", s.computed_at), | |
| 157 | - ) | |
| 158 | - | |
| 159 | - | |
| 160 | -def attention_tuples(s: StudentSummary) -> list[tuple[Any, ...]]: | |
| 161 | - """Dikkat maddeleri. Sira **alfabetiktir, siddete gore degil**. | |
| 162 | - | |
| 163 | - `ord` yazanin sirasini korur; okuyan taraf yeniden siralamasin diye var, | |
| 164 | - bir onem derecesi tasidigi icin degil. | |
| 165 | - """ | |
| 166 | - out: list[tuple[Any, ...]] = [] | |
| 167 | - for index, item in enumerate(s.attention or []): | |
| 168 | - evidence = item.get("evidence") if isinstance(item, dict) else None | |
| 169 | - if not evidence: | |
| 170 | - # Kanitsiz madde yazilmaz. `Recommendation` icin gecerli olan kural | |
| 171 | - # dikkat maddesi icin de gecerli: aciklanamayan sey gosterilmez. | |
| 172 | - log.warning( | |
| 173 | - "kanitsiz dikkat maddesi atlandi (ogrenci=%s, tetik=%s)", | |
| 174 | - s.student, | |
| 175 | - item.get("trigger") if isinstance(item, dict) else "?", | |
| 176 | - ) | |
| 177 | - continue | |
| 178 | - out.append( | |
| 179 | - ( | |
| 180 | - s.student, | |
| 181 | - str(item.get("trigger")), | |
| 182 | - # Ders yalnizca not-egilimi maddesinde var ve kanitin icinde | |
| 183 | - # tasiniyor; ust duzeyde bir `course` alani yok. | |
| 184 | - evidence.get("course"), | |
| 185 | - str(item.get("fact") or ""), | |
| 186 | - int(item.get("window_from") or 0), | |
| 187 | - int(item.get("window_to") or 0), | |
| 188 | - _json(evidence), | |
| 189 | - index, | |
| 190 | - ) | |
| 191 | - ) | |
| 192 | - return out | |
| 193 | - | |
| 194 | - | |
| 195 | -def recommendation_tuple(rec: Recommendation) -> tuple[Any, ...]: | |
| 196 | - """`retain_until = min(expires_at, created_at + 90 gun)`.""" | |
| 197 | - ninety = _retain_until("recommendation", rec.computed_at) | |
| 198 | - return ( | |
| 199 | - str(uuid7(rec.computed_at)), | |
| 200 | - rec.audience, | |
| 201 | - rec.product, | |
| 202 | - rec.rule_id, | |
| 203 | - rec.rule_version, | |
| 204 | - # Kapsam: kuralin kendi ayrimi (segment etiketi gibi) ya da ders. | |
| 205 | - # `about` BURAYA KONMAZ; dogal anahtarda KENDI kolonu var. Ayni | |
| 206 | - # kuralin otuz ogrenci icin urettigi otuz madde birbirinden `about` | |
| 207 | - # ile ayrilir — kapsamdan degil. | |
| 208 | - rec.scope or rec.course, | |
| 209 | - rec.about, | |
| 210 | - str(rec.audience_role), | |
| 211 | - rec.course, | |
| 212 | - _json({**rec.evidence, "limitation": rec.limitation}), | |
| 213 | - str(rec.confidence), | |
| 214 | - rec.computed_at, | |
| 215 | - rec.expires_at, | |
| 216 | - min(rec.expires_at, ninety), | |
| 217 | - ) | |
| 218 | - | |
| 219 | - | |
| 220 | -def question_segment_tuple(seg: QuestionSegment) -> tuple[Any, ...]: | |
| 221 | - labels = {name: str(label) for name, label in seg.labels.items()} | |
| 222 | - conf = {name: float(v) for name, v in seg.confidences.items()} | |
| 223 | - return ( | |
| 224 | - seg.question, | |
| 225 | - seg.exam, | |
| 226 | - seg.course, | |
| 227 | - seg.subject, | |
| 228 | - labels.get("bilissel_talep"), | |
| 229 | - labels.get("dikkat_tuzagi"), | |
| 230 | - labels.get("okuma_yuku"), | |
| 231 | - labels.get("adim_sayisi"), | |
| 232 | - conf.get("bilissel_talep"), | |
| 233 | - conf.get("dikkat_tuzagi"), | |
| 234 | - conf.get("okuma_yuku"), | |
| 235 | - conf.get("adim_sayisi"), | |
| 236 | - str(seg.confidence), | |
| 237 | - seg.trap_choice, | |
| 238 | - seg.rationale, | |
| 239 | - seg.model, | |
| 240 | - seg.prompt_version, | |
| 241 | - seg.variant, | |
| 242 | - seg.computed_at, | |
| 243 | - _retain_until("question_segment", seg.computed_at), | |
| 244 | - ) | |
| 245 | - | |
| 246 | - | |
| 247 | -def segment_dimension_tuples(seg: QuestionSegment) -> list[tuple[Any, ...]]: | |
| 248 | - """Hangi boyut asagi akista kullaniliyor, hangisi deneysel. | |
| 249 | - | |
| 250 | - Satir basina tutulur: `rubric.py` bir boyutu deneysele indirdiginde bunun | |
| 251 | - satirdan okunabilmesi icin. Belgeye bakmak gerekmesin. | |
| 252 | - """ | |
| 253 | - out: list[tuple[Any, ...]] = [] | |
| 254 | - order = 0 | |
| 255 | - for role, names in ( | |
| 256 | - ("downstream", seg.downstream_dimensions), | |
| 257 | - ("experimental", seg.experimental_dimensions), | |
| 258 | - ): | |
| 259 | - for name in names: | |
| 260 | - out.append((seg.question, str(name), role, order)) | |
| 261 | - order += 1 | |
| 262 | - return out | |
| 263 | - | |
| 264 | - | |
| 265 | -def segment_profile_tuple(p: StudentSegmentProfile) -> tuple[Any, ...]: | |
| 266 | - return ( | |
| 267 | - p.student, | |
| 268 | - p.dimension, | |
| 269 | - p.label, | |
| 270 | - p.n_answers, | |
| 271 | - p.n_correct, | |
| 272 | - round(p.accuracy, 6), | |
| 273 | - p.overall_n_answers, | |
| 274 | - round(p.overall_accuracy, 6), | |
| 275 | - round(p.contrast, 6), | |
| 276 | - str(p.confidence), | |
| 277 | - p.computed_at, | |
| 278 | - _retain_until("student_segment_profile", p.computed_at), | |
| 279 | - ) | |
| 280 | - | |
| 281 | - | |
| 282 | -def _json(value: Any) -> str | None: | |
| 283 | - """JSONB kolonuna gidecek degeri metne cevirir; None ise NULL birakir.""" | |
| 284 | - if value is None: | |
| 285 | - return None | |
| 286 | - import json | |
| 287 | - | |
| 288 | - return json.dumps(value, ensure_ascii=False, separators=(",", ":")) | |
| 289 | - | |
| 290 | - | |
| 291 | -# --- SQL -------------------------------------------------------------------- | |
| 292 | -# | |
| 293 | -# Her UPSERT'in `DO UPDATE SET` listesi ACIKCA yazilir. `EXCLUDED.*` diye bir | |
| 294 | -# toplu yazim yok ve olmayacak: `zeka_recommendation`da uc kolon (`dismissed_at`, | |
| 295 | -# `dismissed_by`, `dismiss_reason`) insan mudahalesi izidir (KVKK m.11) ve | |
| 296 | -# hesap hatti onlari hic uretmez. Toplu bir SET, her gece kosusunun | |
| 297 | -# kullanicinin "bu tavsiye faydali degil" kaydini sessizce silmesi demekti. | |
| 298 | - | |
| 299 | -SQL_SUMMARY = """ | |
| 300 | -INSERT INTO zeka_student_summary | |
| 301 | - (student, marks, attendance, submission, study, confidence, | |
| 302 | - computed_at, retain_until) | |
| 303 | -VALUES (%s, %s, %s, %s, %s, %s, %s, %s) | |
| 304 | -ON CONFLICT (student) DO UPDATE SET | |
| 305 | - marks = EXCLUDED.marks, | |
| 306 | - attendance = EXCLUDED.attendance, | |
| 307 | - submission = EXCLUDED.submission, | |
| 308 | - study = EXCLUDED.study, | |
| 309 | - confidence = EXCLUDED.confidence, | |
| 310 | - computed_at = EXCLUDED.computed_at, | |
| 311 | - retain_until = EXCLUDED.retain_until | |
| 312 | -""" | |
| 313 | - | |
| 314 | -SQL_ATTENTION = """ | |
| 315 | -INSERT INTO zeka_attention_item | |
| 316 | - (student, trigger, course, fact, window_from, window_to, evidence, ord) | |
| 317 | -VALUES (%s, %s, %s, %s, %s, %s, %s, %s) | |
| 318 | -""" | |
| 319 | - | |
| 320 | -SQL_RECOMMENDATION = """ | |
| 321 | -INSERT INTO zeka_recommendation | |
| 322 | - (id, audience, product, rule_id, rule_version, scope, about, audience_role, | |
| 323 | - course, evidence, confidence, created_at, expires_at, retain_until) | |
| 324 | -VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) | |
| 325 | -ON CONFLICT (audience, product, rule_id, about, scope) DO UPDATE SET | |
| 326 | - rule_version = EXCLUDED.rule_version, | |
| 327 | - audience_role = EXCLUDED.audience_role, | |
| 328 | - course = EXCLUDED.course, | |
| 329 | - evidence = EXCLUDED.evidence, | |
| 330 | - confidence = EXCLUDED.confidence, | |
| 331 | - created_at = EXCLUDED.created_at, | |
| 332 | - expires_at = EXCLUDED.expires_at, | |
| 333 | - retain_until = EXCLUDED.retain_until | |
| 334 | -""" | |
| 335 | - | |
| 336 | -SQL_QUESTION_SEGMENT = """ | |
| 337 | -INSERT INTO zeka_question_segment | |
| 338 | - (question, exam, course, subject, bilissel_talep, dikkat_tuzagi, okuma_yuku, | |
| 339 | - adim_sayisi, confidence_bilissel_talep, confidence_dikkat_tuzagi, | |
| 340 | - confidence_okuma_yuku, confidence_adim_sayisi, confidence, trap_choice, | |
| 341 | - rationale, model, prompt_version, variant, computed_at, retain_until) | |
| 342 | -VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, | |
| 343 | - %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) | |
| 344 | -ON CONFLICT (question) DO UPDATE SET | |
| 345 | - exam = EXCLUDED.exam, course = EXCLUDED.course, subject = EXCLUDED.subject, | |
| 346 | - bilissel_talep = EXCLUDED.bilissel_talep, | |
| 347 | - dikkat_tuzagi = EXCLUDED.dikkat_tuzagi, | |
| 348 | - okuma_yuku = EXCLUDED.okuma_yuku, | |
| 349 | - adim_sayisi = EXCLUDED.adim_sayisi, | |
| 350 | - confidence_bilissel_talep = EXCLUDED.confidence_bilissel_talep, | |
| 351 | - confidence_dikkat_tuzagi = EXCLUDED.confidence_dikkat_tuzagi, | |
| 352 | - confidence_okuma_yuku = EXCLUDED.confidence_okuma_yuku, | |
| 353 | - confidence_adim_sayisi = EXCLUDED.confidence_adim_sayisi, | |
| 354 | - confidence = EXCLUDED.confidence, trap_choice = EXCLUDED.trap_choice, | |
| 355 | - rationale = EXCLUDED.rationale, model = EXCLUDED.model, | |
| 356 | - prompt_version = EXCLUDED.prompt_version, variant = EXCLUDED.variant, | |
| 357 | - computed_at = EXCLUDED.computed_at, retain_until = EXCLUDED.retain_until | |
| 358 | -""" | |
| 359 | - | |
| 360 | -SQL_SEGMENT_DIMENSION = """ | |
| 361 | -INSERT INTO zeka_question_segment_dimension (question, dimension, role, ord) | |
| 362 | -VALUES (%s, %s, %s, %s) | |
| 363 | -ON CONFLICT (question, dimension) DO UPDATE SET | |
| 364 | - role = EXCLUDED.role, ord = EXCLUDED.ord | |
| 365 | -""" | |
| 366 | - | |
| 367 | -SQL_SEGMENT_PROFILE = """ | |
| 368 | -INSERT INTO zeka_student_segment_profile | |
| 369 | - (student, dimension, label, n_answers, n_correct, accuracy, | |
| 370 | - overall_n_answers, overall_accuracy, contrast, confidence, | |
| 371 | - computed_at, retain_until) | |
| 372 | -VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) | |
| 373 | -ON CONFLICT (student, dimension, label) DO UPDATE SET | |
| 374 | - n_answers = EXCLUDED.n_answers, n_correct = EXCLUDED.n_correct, | |
| 375 | - accuracy = EXCLUDED.accuracy, | |
| 376 | - overall_n_answers = EXCLUDED.overall_n_answers, | |
| 377 | - overall_accuracy = EXCLUDED.overall_accuracy, | |
| 378 | - contrast = EXCLUDED.contrast, confidence = EXCLUDED.confidence, | |
| 379 | - computed_at = EXCLUDED.computed_at, retain_until = EXCLUDED.retain_until | |
| 380 | -""" | |
| 381 | - | |
| 382 | -SQL_RUN = """ | |
| 383 | -INSERT INTO zeka_run | |
| 384 | - (run_day, started_at, finished_at, status, duration_ms, students_total, | |
| 385 | - students_ok, students_failed, students_skipped, rows_written, | |
| 386 | - budget_exceeded, budget_ms, retain_until) | |
| 387 | -VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) | |
| 388 | -ON CONFLICT (run_day) DO UPDATE SET | |
| 389 | - started_at = EXCLUDED.started_at, finished_at = EXCLUDED.finished_at, | |
| 390 | - status = EXCLUDED.status, duration_ms = EXCLUDED.duration_ms, | |
| 391 | - students_total = EXCLUDED.students_total, students_ok = EXCLUDED.students_ok, | |
| 392 | - students_failed = EXCLUDED.students_failed, | |
| 393 | - students_skipped = EXCLUDED.students_skipped, | |
| 394 | - rows_written = EXCLUDED.rows_written, | |
| 395 | - budget_exceeded = EXCLUDED.budget_exceeded, budget_ms = EXCLUDED.budget_ms, | |
| 396 | - retain_until = EXCLUDED.retain_until | |
| 397 | -""" | |
| 398 | - | |
| 399 | - | |
| 400 | -class PgStore: | |
| 401 | - """Toplu UPSERT + supurme, Postgres uzerinde.""" | |
| 402 | - | |
| 403 | - def __init__(self, client: PgClient, *, batch_size: int = BATCH_SIZE) -> None: | |
| 404 | - self._client = client | |
| 405 | - self._batch_size = batch_size | |
| 406 | - | |
| 407 | - # -- yardimci ----------------------------------------------------------- | |
| 408 | - | |
| 409 | - async def _attempt(self, work: Any, *, table: str, rows: int) -> bool: | |
| 410 | - """Bir grubu `MAX_ATTEMPTS` kez dener; ikinci dususte atlar. | |
| 411 | - | |
| 412 | - `store.py` ile ayni hata davranisi: bir grup dusse de hat devam eder, | |
| 413 | - cunku bir okulun bir gecesi ugruna butun kosuyu kaybetmek daha kotu. | |
| 414 | - Atlanan grup `warn` loglanir ve `WriteReport.skipped_batches` uzerinden | |
| 415 | - kosu defterine yansir — sessizce kaybolmaz. | |
| 416 | - """ | |
| 417 | - for attempt in range(1, MAX_ATTEMPTS + 1): | |
| 418 | - try: | |
| 419 | - await work() | |
| 420 | - return True | |
| 421 | - except Exception as exc: # noqa: BLE001 — hat devam etmeli | |
| 422 | - log.warning( | |
| 423 | - "toplu yazma dustu (tablo=%s, deneme=%d/%d): %s", | |
| 424 | - table, | |
| 425 | - attempt, | |
| 426 | - MAX_ATTEMPTS, | |
| 427 | - exc, | |
| 428 | - ) | |
| 429 | - log.warning("grup atlandi (tablo=%s, satir=%d)", table, rows) | |
| 430 | - return False | |
| 431 | - | |
| 432 | - def _chunks(self, rows: list[Any]) -> list[list[Any]]: | |
| 433 | - return [ | |
| 434 | - rows[i : i + self._batch_size] | |
| 435 | - for i in range(0, len(rows), self._batch_size) | |
| 436 | - ] | |
| 437 | - | |
| 438 | - # -- yazma -------------------------------------------------------------- | |
| 439 | - | |
| 440 | - async def write_summaries(self, summaries: list[StudentSummary]) -> WriteReport: | |
| 441 | - """Ozetleri ve dikkat maddelerini yazar. | |
| 442 | - | |
| 443 | - Dikkat maddeleri **sil-ve-yaz**: bir ogrencinin onceki maddeleri | |
| 444 | - silinmeden yenileri yazilsaydi, artik uretilmeyen bir madde ekranda | |
| 445 | - kalirdi. Ozet ve maddeleri ayni transaction'da gider; yarim bir durum | |
| 446 | - (ozet yeni, maddeler eski) ekranda celiskiye donusurdu. | |
| 447 | - """ | |
| 448 | - report = WriteReport() | |
| 449 | - for chunk in self._chunks(summaries): | |
| 450 | - students = [s.student for s in chunk] | |
| 451 | - rows = [summary_tuple(s) for s in chunk] | |
| 452 | - items: list[tuple[Any, ...]] = [] | |
| 453 | - for s in chunk: | |
| 454 | - items.extend(attention_tuples(s)) | |
| 455 | - | |
| 456 | - async def work( | |
| 457 | - rows: list = rows, students: list = students, items: list = items | |
| 458 | - ) -> None: | |
| 459 | - async with self._client.transaction(): | |
| 460 | - await self._client.executemany(SQL_SUMMARY, rows) | |
| 461 | - await self._client.execute( | |
| 462 | - "DELETE FROM zeka_attention_item " | |
| 463 | - "WHERE student = ANY(%s)", | |
| 464 | - (students,), | |
| 465 | - ) | |
| 466 | - if items: | |
| 467 | - await self._client.executemany(SQL_ATTENTION, items) | |
| 468 | - | |
| 469 | - if await self._attempt( | |
| 470 | - work, table="zeka_student_summary", rows=len(chunk) | |
| 471 | - ): | |
| 472 | - report.written += len(chunk) | |
| 473 | - else: | |
| 474 | - report.skipped_batches += 1 | |
| 475 | - return report | |
| 476 | - | |
| 477 | - async def write_recommendations( | |
| 478 | - self, recs: list[Recommendation] | |
| 479 | - ) -> WriteReport: | |
| 480 | - """Tavsiyeleri yazar. **Kanitsiz satir reddedilir.**""" | |
| 481 | - rows: list[tuple[Any, ...]] = [] | |
| 482 | - rejected = 0 | |
| 483 | - for rec in recs: | |
| 484 | - evidence = {**rec.evidence, "limitation": rec.limitation} | |
| 485 | - if not {k: v for k, v in evidence.items() if k != "limitation"}: | |
| 486 | - log.warning("kanitsiz tavsiye reddedildi: %s", rec.rule_id) | |
| 487 | - rejected += 1 | |
| 488 | - continue | |
| 489 | - rows.append(recommendation_tuple(rec)) | |
| 490 | - | |
| 491 | - report = WriteReport() | |
| 492 | - for chunk in self._chunks(rows): | |
| 493 | - | |
| 494 | - async def work(chunk: list = chunk) -> None: | |
| 495 | - async with self._client.transaction(): | |
| 496 | - await self._client.executemany(SQL_RECOMMENDATION, chunk) | |
| 497 | - | |
| 498 | - if await self._attempt( | |
| 499 | - work, table="zeka_recommendation", rows=len(chunk) | |
| 500 | - ): | |
| 501 | - report.written += len(chunk) | |
| 502 | - else: | |
| 503 | - report.skipped_batches += 1 | |
| 504 | - report.rejected = rejected | |
| 505 | - return report | |
| 506 | - | |
| 507 | - async def write_question_segments( | |
| 508 | - self, segments: list[QuestionSegment] | |
| 509 | - ) -> WriteReport: | |
| 510 | - """Soru segment etiketlerini ve boyut ayrimini yazar.""" | |
| 511 | - report = WriteReport() | |
| 512 | - for chunk in self._chunks(segments): | |
| 513 | - rows = [question_segment_tuple(s) for s in chunk] | |
| 514 | - dims: list[tuple[Any, ...]] = [] | |
| 515 | - for s in chunk: | |
| 516 | - dims.extend(segment_dimension_tuples(s)) | |
| 517 | - questions = [s.question for s in chunk] | |
| 518 | - | |
| 519 | - async def work( | |
| 520 | - rows: list = rows, dims: list = dims, questions: list = questions | |
| 521 | - ) -> None: | |
| 522 | - async with self._client.transaction(): | |
| 523 | - await self._client.executemany(SQL_QUESTION_SEGMENT, rows) | |
| 524 | - # Bir boyut deneyselden uretime (ya da tersine) gecerse | |
| 525 | - # eski satir kalmamali; rubrik surumu degistiginde liste | |
| 526 | - # kisalabilir de. | |
| 527 | - await self._client.execute( | |
| 528 | - "DELETE FROM zeka_question_segment_dimension " | |
| 529 | - "WHERE question = ANY(%s)", | |
| 530 | - (questions,), | |
| 531 | - ) | |
| 532 | - if dims: | |
| 533 | - await self._client.executemany( | |
| 534 | - SQL_SEGMENT_DIMENSION, dims | |
| 535 | - ) | |
| 536 | - | |
| 537 | - if await self._attempt( | |
| 538 | - work, table="zeka_question_segment", rows=len(chunk) | |
| 539 | - ): | |
| 540 | - report.written += len(chunk) | |
| 541 | - else: | |
| 542 | - report.skipped_batches += 1 | |
| 543 | - return report | |
| 544 | - | |
| 545 | - async def write_segment_profiles( | |
| 546 | - self, profiles: list[StudentSegmentProfile] | |
| 547 | - ) -> WriteReport: | |
| 548 | - """Ogrenci segment profillerini yazar. | |
| 549 | - | |
| 550 | - Guven kapisinin **altindaki** satirlar da yazilir: depo ham olguyu | |
| 551 | - tutar, gosterme karari kuralindir. Esik olcumle degisebildigi icin | |
| 552 | - kapinin depoda olmasi, esik her degistiginde veriyi yeniden uretmek | |
| 553 | - demek olurdu. | |
| 554 | - """ | |
| 555 | - report = WriteReport() | |
| 556 | - rows = [segment_profile_tuple(p) for p in profiles] | |
| 557 | - for chunk in self._chunks(rows): | |
| 558 | - | |
| 559 | - async def work(chunk: list = chunk) -> None: | |
| 560 | - async with self._client.transaction(): | |
| 561 | - await self._client.executemany(SQL_SEGMENT_PROFILE, chunk) | |
| 562 | - | |
| 563 | - if await self._attempt( | |
| 564 | - work, table="zeka_student_segment_profile", rows=len(chunk) | |
| 565 | - ): | |
| 566 | - report.written += len(chunk) | |
| 567 | - else: | |
| 568 | - report.skipped_batches += 1 | |
| 569 | - return report | |
| 570 | - | |
| 571 | - async def write_run(self, run_row: dict[str, Any], key: str) -> bool: | |
| 572 | - """Kosu defteri satirini yazar. `key` = `YYYY-MM-DD`. | |
| 573 | - | |
| 574 | - SurrealDB surumunde anahtar `{school}_{gun}` idi; okul yarisi dustu. | |
| 575 | - Cagiran taraf hala okul onekli bir anahtar gonderiyorsa son 10 karakter | |
| 576 | - alinir — sessizce yanlis gune yazmaktansa bicimi burada normalize etmek | |
| 577 | - daha guvenli. | |
| 578 | - """ | |
| 579 | - day = key[-10:] | |
| 580 | - started = int(run_row["started_at"]) | |
| 581 | - row = ( | |
| 582 | - day, | |
| 583 | - started, | |
| 584 | - run_row.get("finished_at"), | |
| 585 | - run_row.get("status", "running"), | |
| 586 | - run_row.get("duration_ms"), | |
| 587 | - int(run_row.get("students_total", 0)), | |
| 588 | - int(run_row.get("students_ok", 0)), | |
| 589 | - int(run_row.get("students_failed", 0)), | |
| 590 | - int(run_row.get("students_skipped", 0)), | |
| 591 | - int(run_row.get("rows_written", 0)), | |
| 592 | - bool(run_row.get("budget_exceeded", False)), | |
| 593 | - int(run_row.get("budget_ms", 0)), | |
| 594 | - int(run_row.get("retain_until") or _retain_until("insight_run", started)), | |
| 595 | - ) | |
| 596 | - pending = [ | |
| 597 | - (day, str(s), i) | |
| 598 | - for i, s in enumerate(run_row.get("pending_students") or []) | |
| 599 | - ] | |
| 600 | - failed = [ | |
| 601 | - (day, str(m), i) | |
| 602 | - for i, m in enumerate(run_row.get("failed_modules") or []) | |
| 603 | - ] | |
| 604 | - | |
| 605 | - async def work() -> None: | |
| 606 | - async with self._client.transaction(): | |
| 607 | - await self._client.execute(SQL_RUN, row) | |
| 608 | - await self._client.execute( | |
| 609 | - "DELETE FROM zeka_run_pending WHERE run = %s", (day,) | |
| 610 | - ) | |
| 611 | - await self._client.execute( | |
| 612 | - "DELETE FROM zeka_run_failed_module WHERE run = %s", (day,) | |
| 613 | - ) | |
| 614 | - if pending: | |
| 615 | - await self._client.executemany( | |
| 616 | - "INSERT INTO zeka_run_pending (run, student, ord) " | |
| 617 | - "VALUES (%s, %s, %s)", | |
| 618 | - pending, | |
| 619 | - ) | |
| 620 | - if failed: | |
| 621 | - await self._client.executemany( | |
| 622 | - "INSERT INTO zeka_run_failed_module (run, module, ord) " | |
| 623 | - "VALUES (%s, %s, %s)", | |
| 624 | - failed, | |
| 625 | - ) | |
| 626 | - | |
| 627 | - return await self._attempt(work, table="zeka_run", rows=1) | |
| 628 | - | |
| 629 | - # -- okuma -------------------------------------------------------------- | |
| 630 | - | |
| 631 | - async def last_pending(self, school: str = "") -> list[str]: | |
| 632 | - """Son kosudan devreden ogrenci kimlikleri. | |
| 633 | - | |
| 634 | - `school` KULLANILMIYOR: veritabaninin kendisi zaten o okul. Parametre | |
| 635 | - cagiran tarafi degistirmemek icin duruyor. | |
| 636 | - | |
| 637 | - Okunamazsa bos liste doner: devretmemek, yanlis listeyle kosmaktan | |
| 638 | - iyidir. | |
| 639 | - """ | |
| 640 | - sql = ( | |
| 641 | - "SELECT p.student FROM zeka_run_pending p " | |
| 642 | - "JOIN zeka_run r ON r.run_day = p.run " | |
| 643 | - "WHERE r.run_day = (SELECT run_day FROM zeka_run " | |
| 644 | - " ORDER BY started_at DESC LIMIT 1) " | |
| 645 | - "ORDER BY p.ord" | |
| 646 | - ) | |
| 647 | - try: | |
| 648 | - rows = await self._client.fetch(sql) | |
| 649 | - except Exception as exc: # noqa: BLE001 | |
| 650 | - log.warning("bekleyen liste okunamadi: %s", exc) | |
| 651 | - return [] | |
| 652 | - return [str(r[0]) for r in rows] | |
| 653 | - | |
| 654 | - # -- supurme ------------------------------------------------------------ | |
| 655 | - | |
| 656 | - async def sweep(self, now_ms: int) -> dict[str, bool]: | |
| 657 | - """Saklama suresi dolmus satirlari siler. | |
| 658 | - | |
| 659 | - **Once cocuk, sonra ebeveyn.** FK'ler `ON DELETE NO ACTION`, yani | |
| 660 | - cocugu duran bir ebeveyn silinemez. Cocuk satirin kendi `retain_until` | |
| 661 | - alani yok; omru ebeveyninkine bagli, o yuzden silme kosulu ebeveyn | |
| 662 | - uzerinden okunur. | |
| 663 | - """ | |
| 664 | - results: dict[str, bool] = {} | |
| 665 | - for child, parent, key in SWEEP_ORDER: | |
| 666 | - sql = ( | |
| 667 | - f"DELETE FROM {child} WHERE {key} IN " | |
| 668 | - f"(SELECT {'run_day' if parent == 'zeka_run' else key} " | |
| 669 | - f"FROM {parent} WHERE retain_until < %s)" | |
| 670 | - ) | |
| 671 | - results[child] = await self._run_sweep(child, sql, now_ms) | |
| 672 | - | |
| 673 | - for table in ( | |
| 674 | - "zeka_student_summary", | |
| 675 | - "zeka_recommendation", | |
| 676 | - "zeka_run", | |
| 677 | - "zeka_question_segment", | |
| 678 | - "zeka_student_segment_profile", | |
| 679 | - ): | |
| 680 | - sql = f"DELETE FROM {table} WHERE retain_until < %s" | |
| 681 | - results[table] = await self._run_sweep(table, sql, now_ms) | |
| 682 | - return results | |
| 683 | - | |
| 684 | - async def _run_sweep(self, table: str, sql: str, now_ms: int) -> bool: | |
| 685 | - try: | |
| 686 | - await self._client.execute(sql, (now_ms,)) | |
| 687 | - return True | |
| 688 | - except Exception as exc: # noqa: BLE001 | |
| 689 | - log.warning("supurme dustu (tablo=%s): %s", table, exc) | |
| 690 | - return False | |
| 691 | - | |
| 692 | - async def purge_departed( | |
| 693 | - self, school: str, active_students: list[str] | |
| 694 | - ) -> bool: | |
| 695 | - """Artik ogrenci olmayanlarin turetilmis verisini siler. | |
| 696 | - | |
| 697 | - "Mezunun ham verisi arsivde kalabilir; **profili kalmamalidir**." | |
| 698 | - | |
| 699 | - `zeka_question_segment` buraya GIRMEZ: o satir bir soru hakkindadir, | |
| 700 | - hicbir ogrenciye baglanamaz. | |
| 701 | - | |
| 702 | - `school` KULLANILMIYOR — veritabani zaten o okul. | |
| 703 | - | |
| 704 | - Bos `active_students` ile **hicbir sey silinmez**. Bos liste "okulda | |
| 705 | - ogrenci kalmadi" degil, neredeyse her zaman "listeyi cekemedik" | |
| 706 | - demektir; o hali silme emrine cevirmek butun ogrenci profillerini | |
| 707 | - silerdi. | |
| 708 | - """ | |
| 709 | - if not active_students: | |
| 710 | - log.warning("aktif ogrenci listesi bos — mezuniyet temizligi atlandi") | |
| 711 | - return False | |
| 712 | - | |
| 713 | - async def work() -> None: | |
| 714 | - async with self._client.transaction(): | |
| 715 | - await self._client.execute( | |
| 716 | - "DELETE FROM zeka_attention_item WHERE student <> ALL(%s)", | |
| 717 | - (active_students,), | |
| 718 | - ) | |
| 719 | - await self._client.execute( | |
| 720 | - "DELETE FROM zeka_student_summary WHERE student <> ALL(%s)", | |
| 721 | - (active_students,), | |
| 722 | - ) | |
| 723 | - await self._client.execute( | |
| 724 | - "DELETE FROM zeka_student_segment_profile " | |
| 725 | - "WHERE student <> ALL(%s)", | |
| 726 | - (active_students,), | |
| 727 | - ) | |
| 728 | - await self._client.execute( | |
| 729 | - "DELETE FROM zeka_recommendation " | |
| 730 | - "WHERE about IS NOT NULL AND about <> ALL(%s)", | |
| 731 | - (active_students,), | |
| 732 | - ) | |
| 733 | - await self._client.execute( | |
| 734 | - "DELETE FROM zeka_run_pending WHERE student <> ALL(%s)", | |
| 735 | - (active_students,), | |
| 736 | - ) | |
| 737 | - | |
| 738 | - return await self._attempt(work, table="mezuniyet", rows=0) | |
| 739 | - | |
| 740 | - | |
| 741 | -__all__ = [ | |
| 742 | - "PgClient", | |
| 743 | - "CollectingPgClient", | |
| 744 | - "PgStore", | |
| 745 | - "WriteReport", | |
| 746 | - "TABLES", | |
| 747 | - "RETENTION_DAYS", | |
| 748 | -] |
service/src/tenants.pydeleted+0 -557
| @@ -1,557 +0,0 @@ | ||
| 1 | -"""Okul cozumlemesi: slug'dan o okulun veritabanina, ve okul basina havuz. | |
| 2 | - | |
| 3 | ---------------------------------------------------------------------------- | |
| 4 | -NEDEN VAR | |
| 5 | ---------------------------------------------------------------------------- | |
| 6 | -`ZEKA_PG_DSN` artik **KONTROL** veritabanini adlandirir. Okulun verisi her | |
| 7 | -okulun KENDI veritabanindadir ve adi backend'in kendi kuralindan turer | |
| 8 | -(`hezarfen_backend/src/tenant.rs:111-112`): | |
| 9 | - | |
| 10 | - {kontrol_db}_school_{okul_uuid, tiresiz} | |
| 11 | - | |
| 12 | -Ad **desenden tahmin edilmez**; slug'i uuid'ye yalnizca kontrol | |
| 13 | -veritabanindaki `school` satiri cevirir. Satir yoksa istek reddedilir | |
| 14 | -(`unknown_school`), desene uyan bir veritabani var olsa bile: kutukte olmayan | |
| 15 | -bir veritabanina yazmak, "hangi okulun verisi bu" sorusunu cevapsiz birakirdi | |
| 16 | -(`paket/apply_zeka_tables.sh` de tam bu yuzden okullari control'den cozer). | |
| 17 | - | |
| 18 | ---------------------------------------------------------------------------- | |
| 19 | -SINIR NEDEN VAR | |
| 20 | ---------------------------------------------------------------------------- | |
| 21 | -Okul sayisi sinirsiz buyur; her okul icin bir baglanti acik tutmak, okul | |
| 22 | -sayisiyla birlikte Postgres'in baglanti tavanini yakardı. Bu yuzden okul | |
| 23 | -havuzlari **sinirli** bir onbellekte tutulur: en fazla `max_pools` havuz | |
| 24 | -(varsayilan 8), her havuz en son kullanimdan `ttl_secs` sonra kapatilir. | |
| 25 | -Sinir asilinca **en eski kullanilan** havuz kapatilir (LRU). Tavan ve TTL | |
| 26 | -`ZEKA_MAX_SCHOOL_POOLS` / `ZEKA_SCHOOL_POOL_TTL_SECS` ile ayarlanir. | |
| 27 | - | |
| 28 | ---------------------------------------------------------------------------- | |
| 29 | -HATA SINIFLARI AYRIDIR | |
| 30 | ---------------------------------------------------------------------------- | |
| 31 | -`unknown_school` (kutukte yok) ile `school_suspended` (kapatilmis) ve | |
| 32 | -`school_not_migrated` (veritabani var, `zeka_*` tablolari yok) uc ayri | |
| 33 | -durumdur ve ayri kodlarla doner: birincisinde yeniden denemek anlamsizdir, | |
| 34 | -ikincisinde sabretmek gerekir, ucuncusunde operatorun bir sey yapmasi | |
| 35 | -gerekir. Hicbiri `internal` degildir -- hepsi beklenen redlerdir. | |
| 36 | - | |
| 37 | -Kontrol veritabani okunamazsa (ulasilamaz ya da `school` tablosu yok) bu | |
| 38 | -`TenantError` olarak yukari cikar ve ZAMANLAYICI onu o tik icin "okul yok" | |
| 39 | -sayar: acilis cokmez, sonraki tik yeniden dener. | |
| 40 | -""" | |
| 41 | - | |
| 42 | -from __future__ import annotations | |
| 43 | - | |
| 44 | -import asyncio | |
| 45 | -import logging | |
| 46 | -import time | |
| 47 | -import uuid as uuid_mod | |
| 48 | -from collections.abc import Awaitable, Callable, Sequence | |
| 49 | -from dataclasses import dataclass | |
| 50 | -from typing import Any, NamedTuple, Protocol | |
| 51 | - | |
| 52 | -log = logging.getLogger(__name__) | |
| 53 | - | |
| 54 | -#: Okul veritabaninda bulunmasi ZORUNLU tablolar. Tek kaynak: | |
| 55 | -#: `service/schema/postgres/school/20260916000001_zeka.sql` (backend'de | |
| 56 | -#: `migrations/school/20260917000002_zeka.sql`). `tests/test_tenants.py` bu | |
| 57 | -#: listeyi DDL dosyasiyla KARSILASTIRIR; biri digerinden kopamaz. | |
| 58 | -REQUIRED_TABLES: tuple[str, ...] = ( | |
| 59 | - "zeka_student_summary", | |
| 60 | - "zeka_attention_item", | |
| 61 | - "zeka_recommendation", | |
| 62 | - "zeka_run", | |
| 63 | - "zeka_run_pending", | |
| 64 | - "zeka_run_failed_module", | |
| 65 | - "zeka_question_segment", | |
| 66 | - "zeka_question_segment_dimension", | |
| 67 | - "zeka_student_segment_profile", | |
| 68 | -) | |
| 69 | - | |
| 70 | -#: Kontrol okuma: butun kutuk tek sorguda. Okul sayisi binler olsa bile bu | |
| 71 | -#: tablo kucuktur; `resolve` icin okul basina sorgu atmak N+1 olurdu. | |
| 72 | -CONTROL_SQL = "SELECT slug, id::text, status FROM school ORDER BY created_at" | |
| 73 | - | |
| 74 | -#: Okul veritabaninda hangi zeka tablolari var? `pg_class` uzerinden, cunku | |
| 75 | -#: SQLSTATE ile "tablo yok" ayrimi tek tabloda kalirdi: 9 tablodan 3'u olan | |
| 76 | -#: yarim uygulanmis bir veritabani da "migrate edilmemis" sayilmalidir. | |
| 77 | -SCHOOL_TABLES_SQL = """ | |
| 78 | -SELECT c.relname | |
| 79 | - FROM pg_class c | |
| 80 | - JOIN pg_namespace n ON n.oid = c.relnamespace | |
| 81 | - WHERE n.nspname = 'public' AND c.relkind = 'r' AND c.relname = ANY(%s) | |
| 82 | -""" | |
| 83 | - | |
| 84 | - | |
| 85 | -class TenantError(Exception): | |
| 86 | - """Okul cozumlemesi reddi. | |
| 87 | - | |
| 88 | - `code` alanlari backend'in `ApiErrorCode` sozluguyle ayni adlari kullanir | |
| 89 | - (`ai/server.rs:75-99`); `school` cerceveden gelen slug'dir. | |
| 90 | - """ | |
| 91 | - | |
| 92 | - code = "unavailable" | |
| 93 | - | |
| 94 | - def __init__(self, message: str, *, school: str = "") -> None: | |
| 95 | - super().__init__(message) | |
| 96 | - self.school = school | |
| 97 | - | |
| 98 | - | |
| 99 | -class UnknownSchool(TenantError): | |
| 100 | - """Kutukte boyle bir okul yok. Kapali kume: yeniden denemek ogretmez.""" | |
| 101 | - | |
| 102 | - code = "unknown_school" | |
| 103 | - | |
| 104 | - | |
| 105 | -class SchoolSuspended(TenantError): | |
| 106 | - """Okul var ama kapatilmis. Sonradan acilabilir; yeniden denenebilir.""" | |
| 107 | - | |
| 108 | - code = "school_suspended" | |
| 109 | - | |
| 110 | - | |
| 111 | -class SchoolDatabaseGone(TenantError): | |
| 112 | - """Okul kutukte var, veritabani yok ya da baglanilamiyor.""" | |
| 113 | - | |
| 114 | - code = "unavailable" | |
| 115 | - | |
| 116 | - | |
| 117 | -class SchoolNotMigrated(TenantError): | |
| 118 | - """Okul veritabani var ama `zeka_*` tablolarini tasimiyor.""" | |
| 119 | - | |
| 120 | - code = "school_not_migrated" | |
| 121 | - | |
| 122 | - | |
| 123 | -@dataclass(frozen=True) | |
| 124 | -class SchoolRef: | |
| 125 | - """Kontrol satirinin cozulmus hali: slug, uuid ve durum.""" | |
| 126 | - | |
| 127 | - slug: str | |
| 128 | - id: uuid_mod.UUID | |
| 129 | - status: str | |
| 130 | - | |
| 131 | - | |
| 132 | -def database_name(control_db: str, school: uuid_mod.UUID | str) -> str: | |
| 133 | - """`{kontrol}_school_{uuid tiresiz}` -- backend `tenant.rs:111-112`. | |
| 134 | - | |
| 135 | - `uuid.simple()` ile ayni bicim: 32 karakter kucuk hex, tiresiz. Gecersiz | |
| 136 | - bir metin `ValueError` verir; ad UYDURULMAZ. | |
| 137 | - """ | |
| 138 | - uid = school if isinstance(school, uuid_mod.UUID) else uuid_mod.UUID(str(school)) | |
| 139 | - return f"{control_db}_school_{uid.hex}" | |
| 140 | - | |
| 141 | - | |
| 142 | -class SchoolRegistry: | |
| 143 | - """slug -> [`SchoolRef`]. Kontrol veritabanindan, TTL'li tek sorgu. | |
| 144 | - | |
| 145 | - TTL `0` ise her cagri taze okur (testler bunu kullanir); `30s` varsayilan, | |
| 146 | - cunku yeni okul acmak seyrek bir olaydir ama bayat bir kutukle bir okulu | |
| 147 | - hic gormemek daha pahalidir. | |
| 148 | - """ | |
| 149 | - | |
| 150 | - def __init__( | |
| 151 | - self, | |
| 152 | - client: Any, | |
| 153 | - *, | |
| 154 | - ttl_secs: float = 30.0, | |
| 155 | - clock_fn: Callable[[], float] = time.monotonic, | |
| 156 | - ) -> None: | |
| 157 | - self._client = client | |
| 158 | - self._ttl = float(ttl_secs) | |
| 159 | - self._clock = clock_fn | |
| 160 | - self._by_slug: dict[str, SchoolRef] = {} | |
| 161 | - self._loaded_at: float | None = None | |
| 162 | - self._queries = 0 | |
| 163 | - | |
| 164 | - @property | |
| 165 | - def queries(self) -> int: | |
| 166 | - """Kaca kere kontrol veritabani okundu (onbellek kaniti).""" | |
| 167 | - return self._queries | |
| 168 | - | |
| 169 | - def _stale(self) -> bool: | |
| 170 | - if self._loaded_at is None or self._ttl <= 0: | |
| 171 | - return True | |
| 172 | - return (self._clock() - self._loaded_at) > self._ttl | |
| 173 | - | |
| 174 | - async def _load(self) -> None: | |
| 175 | - try: | |
| 176 | - rows = await self._client.fetch(CONTROL_SQL) | |
| 177 | - except Exception as exc: # noqa: BLE001 -- yukariya tek tip hata | |
| 178 | - raise TenantError( | |
| 179 | - "kontrol veritabani okunamadi (school tablosu var mi?): %s" % exc | |
| 180 | - ) from exc | |
| 181 | - table: dict[str, SchoolRef] = {} | |
| 182 | - for slug, ident, status in rows: | |
| 183 | - try: | |
| 184 | - uid = uuid_mod.UUID(str(ident)) | |
| 185 | - except ValueError: | |
| 186 | - # Bozuk bir satir butun kutugu dusurmez; ama sessiz de kalmaz. | |
| 187 | - log.warning("okul satirinin uuid'si cozulemedi, atlandi: %r", slug) | |
| 188 | - continue | |
| 189 | - table[str(slug)] = SchoolRef(str(slug), uid, str(status)) | |
| 190 | - self._by_slug = table | |
| 191 | - self._loaded_at = self._clock() | |
| 192 | - self._queries += 1 | |
| 193 | - | |
| 194 | - async def _fresh_table(self) -> dict[str, SchoolRef]: | |
| 195 | - if self._stale(): | |
| 196 | - await self._load() | |
| 197 | - return self._by_slug | |
| 198 | - | |
| 199 | - async def all_schools(self) -> dict[str, SchoolRef]: | |
| 200 | - return dict(await self._fresh_table()) | |
| 201 | - | |
| 202 | - async def active_schools(self) -> list[str]: | |
| 203 | - """Islenmeye hazir okullar: durumu `active`, slug sirali.""" | |
| 204 | - table = await self._fresh_table() | |
| 205 | - return sorted(slug for slug, ref in table.items() if ref.status == "active") | |
| 206 | - | |
| 207 | - async def resolve(self, slug: str) -> SchoolRef: | |
| 208 | - """Slug'i okula cevir; yoksa/kapatilmissa reddet.""" | |
| 209 | - table = await self._fresh_table() | |
| 210 | - ref = table.get(slug) | |
| 211 | - if ref is None: | |
| 212 | - raise UnknownSchool( | |
| 213 | - "bu dagitimda '%s' okulu yok" % slug, school=slug | |
| 214 | - ) | |
| 215 | - if ref.status != "active": | |
| 216 | - raise SchoolSuspended( | |
| 217 | - "'%s' okulu kapatilmis (durum: %s)" % (slug, ref.status), school=slug | |
| 218 | - ) | |
| 219 | - return ref | |
| 220 | - | |
| 221 | - | |
| 222 | -class OpenedSchool(NamedTuple): | |
| 223 | - """Bir okul havuzunun acilmis hali: depo + onu kapatan kanca.""" | |
| 224 | - | |
| 225 | - store: Any | |
| 226 | - close: Callable[[], Awaitable[None]] | |
| 227 | - | |
| 228 | - | |
| 229 | -#: Okul -> acilmis havuz. `TenantStores` bunu enjekte edilebilir tutar: | |
| 230 | -#: birim testleri gercek Postgres olmadan tavan/TTL davranisini kosturur. | |
| 231 | -Opener = Callable[[SchoolRef], Awaitable[OpenedSchool]] | |
| 232 | - | |
| 233 | - | |
| 234 | -class _Held: | |
| 235 | - """Onbellekteki tek kayit: depo, kapaticisi ve son kullanim damgasi.""" | |
| 236 | - | |
| 237 | - __slots__ = ("store", "close", "last_used") | |
| 238 | - | |
| 239 | - def __init__(self, store: Any, close: Callable[[], Awaitable[None]], at: float) -> None: | |
| 240 | - self.store = store | |
| 241 | - self.close = close | |
| 242 | - self.last_used = at | |
| 243 | - | |
| 244 | - | |
| 245 | -class Directory(Protocol): | |
| 246 | - """Servisin okul dizini: hangi okullar var, her birinin deposu hangisi.""" | |
| 247 | - | |
| 248 | - async def active_schools(self) -> list[str]: ... | |
| 249 | - | |
| 250 | - async def store_for(self, slug: str) -> Any: ... | |
| 251 | - | |
| 252 | - async def close(self) -> None: ... | |
| 253 | - | |
| 254 | - def describe(self) -> str: ... | |
| 255 | - | |
| 256 | - | |
| 257 | -class TenantStores: | |
| 258 | - """Sinirli, TTL'li okul havuzu onbellegi. | |
| 259 | - | |
| 260 | - `store_for` TEK yol: her okul istegi buradan kendi veritabanini alir. Geri | |
| 261 | - dusme yoktur -- kontrol veritabaninin kendisi ya da baska bir okul asla | |
| 262 | - cevap vermez (`unknown_school` doner). | |
| 263 | - """ | |
| 264 | - | |
| 265 | - def __init__( | |
| 266 | - self, | |
| 267 | - registry: SchoolRegistry, | |
| 268 | - opener: Opener, | |
| 269 | - *, | |
| 270 | - max_pools: int = 8, | |
| 271 | - ttl_secs: float = 900.0, | |
| 272 | - clock_fn: Callable[[], float] = time.monotonic, | |
| 273 | - teardown: Sequence[Callable[[], Awaitable[None]]] = (), | |
| 274 | - ) -> None: | |
| 275 | - self._registry = registry | |
| 276 | - self._opener = opener | |
| 277 | - self._max_pools = max(1, int(max_pools)) | |
| 278 | - self._ttl = float(ttl_secs) | |
| 279 | - self._clock = clock_fn | |
| 280 | - self._teardown = list(teardown) | |
| 281 | - self._entries: dict[str, _Held] = {} | |
| 282 | - self._lock = asyncio.Lock() | |
| 283 | - self._opened = 0 | |
| 284 | - self._evicted = 0 | |
| 285 | - self._refused = 0 | |
| 286 | - | |
| 287 | - def describe(self) -> str: | |
| 288 | - return ( | |
| 289 | - "okul dizini: kontrol veritabani (ZEKA_PG_DSN), adlar " | |
| 290 | - "{kontrol}_school_{uuid}; havuz tavani=%d, havuz TTL=%.0fs, " | |
| 291 | - "kayit TTL=%.0fs" % (self._max_pools, self._ttl, self._registry._ttl) | |
| 292 | - ) | |
| 293 | - | |
| 294 | - def stats(self) -> dict[str, int]: | |
| 295 | - """Sayaclar. `atilan`, tavani ve TTL'i asan havuzlarin sayisidir.""" | |
| 296 | - return { | |
| 297 | - "acik": len(self._entries), | |
| 298 | - "tavan": self._max_pools, | |
| 299 | - "acilan": self._opened, | |
| 300 | - "atilan": self._evicted, | |
| 301 | - "reddedilen": self._refused, | |
| 302 | - } | |
| 303 | - | |
| 304 | - async def active_schools(self) -> list[str]: | |
| 305 | - return await self._registry.active_schools() | |
| 306 | - | |
| 307 | - def _expired(self, held: _Held) -> bool: | |
| 308 | - return self._ttl > 0 and (self._clock() - held.last_used) > self._ttl | |
| 309 | - | |
| 310 | - async def _drop(self, slug: str, reason: str) -> None: | |
| 311 | - held = self._entries.pop(slug, None) | |
| 312 | - if held is None: | |
| 313 | - return | |
| 314 | - self._evicted += 1 | |
| 315 | - log.info("okul havuzu kapatildi (okul=%s, sebep=%s)", slug, reason) | |
| 316 | - try: | |
| 317 | - await held.close() | |
| 318 | - except Exception as exc: # noqa: BLE001 -- kapatma hatasi turu durdurmaz | |
| 319 | - log.warning("okul havuzu kapatilamadi (okul=%s): %s", slug, exc) | |
| 320 | - | |
| 321 | - async def _make_room(self) -> None: | |
| 322 | - while len(self._entries) >= self._max_pools: | |
| 323 | - oldest = min(self._entries.items(), key=lambda item: item[1].last_used) | |
| 324 | - await self._drop(oldest[0], "tavan") | |
| 325 | - | |
| 326 | - async def _open(self, ref: SchoolRef) -> _Held: | |
| 327 | - try: | |
| 328 | - opened = await self._opener(ref) | |
| 329 | - except TenantError: | |
| 330 | - self._refused += 1 | |
| 331 | - raise | |
| 332 | - except Exception as exc: # noqa: BLE001 -- surucu hatasi tek tipe baglanir | |
| 333 | - self._refused += 1 | |
| 334 | - raise SchoolDatabaseGone( | |
| 335 | - "'%s' okulunun veritabani acilamadi: %s" % (ref.slug, exc), | |
| 336 | - school=ref.slug, | |
| 337 | - ) from exc | |
| 338 | - self._opened += 1 | |
| 339 | - log.info("okul havuzu acildi (okul=%s)", ref.slug) | |
| 340 | - return _Held(opened.store, opened.close, self._clock()) | |
| 341 | - | |
| 342 | - async def store_for(self, slug: str) -> Any: | |
| 343 | - """Okulun deposu. Kapanmis/taze degilse yeniden acilir. | |
| 344 | - | |
| 345 | - Bilinmeyen ya da kapatilmis okul burada reddedilir; acilista degil, | |
| 346 | - cunku acilisin okul satirina ihtiyaci YOKTUR (kutuk bos olabilir). | |
| 347 | - """ | |
| 348 | - held = self._entries.get(slug) | |
| 349 | - if held is not None: | |
| 350 | - if not self._expired(held): | |
| 351 | - held.last_used = self._clock() | |
| 352 | - return held.store | |
| 353 | - await self._drop(slug, "ttl") | |
| 354 | - | |
| 355 | - try: | |
| 356 | - ref = await self._registry.resolve(slug) | |
| 357 | - except TenantError: | |
| 358 | - # Bilinmeyen/kapatilmis okul da bir reddir; sayaci burada artir. | |
| 359 | - self._refused += 1 | |
| 360 | - raise | |
| 361 | - | |
| 362 | - async with self._lock: | |
| 363 | - # Kilidi beklerken baska bir gorev ayni okulu acmis olabilir. | |
| 364 | - held = self._entries.get(slug) | |
| 365 | - if held is not None: | |
| 366 | - held.last_used = self._clock() | |
| 367 | - return held.store | |
| 368 | - await self._make_room() | |
| 369 | - self._entries[slug] = await self._open(ref) | |
| 370 | - return self._entries[slug].store | |
| 371 | - | |
| 372 | - async def close(self) -> None: | |
| 373 | - """Butun havuzlari ve bu nesnenin sahibi oldugu kaynaklari kapatir.""" | |
| 374 | - for slug in list(self._entries): | |
| 375 | - await self._drop(slug, "kapanis") | |
| 376 | - for closer in self._teardown: | |
| 377 | - try: | |
| 378 | - await closer() | |
| 379 | - except Exception as exc: # noqa: BLE001 | |
| 380 | - log.warning("dizin kaynagi kapatilamadi: %s", exc) | |
| 381 | - | |
| 382 | - | |
| 383 | -class OneDatabase: | |
| 384 | - """Eski tek veritabani modu (SurrealDB): butun okullar ayni depoyu paylasir. | |
| 385 | - | |
| 386 | - Cozumleme yine kapali kumedir: listede olmayan slug reddedilir -- eski | |
| 387 | - modda da "bilinmeyen okul" diye bir sey vardir, yalnizca kaynagi kontrol | |
| 388 | - veritabani degil, yapilandirmadir (`ZEKA_SCHOOLS`). | |
| 389 | - """ | |
| 390 | - | |
| 391 | - def __init__( | |
| 392 | - self, | |
| 393 | - store: Any, | |
| 394 | - schools: Sequence[str], | |
| 395 | - *, | |
| 396 | - teardown: Sequence[Callable[[], Awaitable[None]]] = (), | |
| 397 | - ) -> None: | |
| 398 | - self._store = store | |
| 399 | - self._schools = sorted({str(s) for s in schools if str(s).strip()}) | |
| 400 | - self._teardown = list(teardown) | |
| 401 | - | |
| 402 | - def describe(self) -> str: | |
| 403 | - return ( | |
| 404 | - "okul dizini: tek veritabani (eski SurrealDB modu), okullar " | |
| 405 | - "ZEKA_SCHOOLS'ten (%d)" % len(self._schools) | |
| 406 | - ) | |
| 407 | - | |
| 408 | - async def active_schools(self) -> list[str]: | |
| 409 | - return list(self._schools) | |
| 410 | - | |
| 411 | - async def store_for(self, slug: str) -> Any: | |
| 412 | - if slug not in self._schools: | |
| 413 | - raise UnknownSchool( | |
| 414 | - "bu servis '%s' okulunu islemiyor (ZEKA_SCHOOLS)" % slug, school=slug | |
| 415 | - ) | |
| 416 | - return self._store | |
| 417 | - | |
| 418 | - async def close(self) -> None: | |
| 419 | - for closer in self._teardown: | |
| 420 | - try: | |
| 421 | - await closer() | |
| 422 | - except Exception as exc: # noqa: BLE001 | |
| 423 | - log.warning("dizin kaynagi kapatilamadi: %s", exc) | |
| 424 | - | |
| 425 | - | |
| 426 | -# --- Postgres tarafi ------------------------------------------------------- | |
| 427 | - | |
| 428 | - | |
| 429 | -def school_dsn(control_dsn: str, database: str) -> str: | |
| 430 | - """Kontrol DSN'inin AYNI sunucusunda, veritabani adi degistirilmis DSN. | |
| 431 | - | |
| 432 | - Backend de boyle yapar (`database.rs:130` `school_pool`): kontrol ile okul | |
| 433 | - veritabanlari ayni Postgres sunucusundadir, degisen tek sey `dbname`dir. | |
| 434 | - Kullanici/parola kontrol DSN'inden gelir; okul basina sir TUTULMAZ. | |
| 435 | - """ | |
| 436 | - import psycopg.conninfo | |
| 437 | - | |
| 438 | - parts = psycopg.conninfo.conninfo_to_dict(control_dsn) | |
| 439 | - parts["dbname"] = database | |
| 440 | - return psycopg.conninfo.make_conninfo(**parts) | |
| 441 | - | |
| 442 | - | |
| 443 | -async def control_database(client: Any) -> str: | |
| 444 | - """Kontrol veritabaninin GERCEK adi. | |
| 445 | - | |
| 446 | - DSN'i elle ayristirmak yerine sunucuya sorulur: URL bicimi de anahtar=deger | |
| 447 | - bicimi de ayni cevabi verir, `dbname` yazilmamissa da dogru kalir. | |
| 448 | - """ | |
| 449 | - rows = await client.fetch("SELECT current_database()") | |
| 450 | - if not rows: | |
| 451 | - raise TenantError("kontrol veritabaninin adi ogrenilemedi") | |
| 452 | - return str(rows[0][0]) | |
| 453 | - | |
| 454 | - | |
| 455 | -async def verify_school_schema(client: Any, ref: SchoolRef) -> None: | |
| 456 | - """Okul veritabani `zeka_*` tablolarini tasiyor mu? | |
| 457 | - | |
| 458 | - Ayri bir hata tipiyle reddedilir (`school_not_migrated`): veritabani | |
| 459 | - vardir, baglanti kurulmustur, eksik olan YALNIZCA semadir. Eksikler | |
| 460 | - adiyla soylenir; hangi DDL'in uygulanacagi da mesajdadir. | |
| 461 | - """ | |
| 462 | - rows = await client.fetch(SCHOOL_TABLES_SQL, [list(REQUIRED_TABLES)]) | |
| 463 | - found = {str(row[0]) for row in rows} | |
| 464 | - missing = [name for name in REQUIRED_TABLES if name not in found] | |
| 465 | - if missing: | |
| 466 | - raise SchoolNotMigrated( | |
| 467 | - "'%s' okulunun veritabani zeka tablolarini tasimiyor: %d/%d eksik " | |
| 468 | - "(%s). Veritabanina " | |
| 469 | - "service/schema/postgres/school/20260916000001_zeka.sql " | |
| 470 | - "uygulanmalidir." % (ref.slug, len(missing), len(REQUIRED_TABLES), ", ".join(missing)), | |
| 471 | - school=ref.slug, | |
| 472 | - ) | |
| 473 | - | |
| 474 | - | |
| 475 | -def postgres_opener( | |
| 476 | - control_dsn: str, | |
| 477 | - control_db: str, | |
| 478 | - *, | |
| 479 | - connect_timeout_secs: float = 10.0, | |
| 480 | -) -> Opener: | |
| 481 | - """Okul havuzlarini acan kanca: DSN turetir, semayi dogrular.""" | |
| 482 | - | |
| 483 | - async def open_school(ref: SchoolRef) -> OpenedSchool: | |
| 484 | - from .pg_client import PsycopgClient | |
| 485 | - from .store_pg import PgStore | |
| 486 | - | |
| 487 | - dsn = school_dsn(control_dsn, database_name(control_db, ref.id)) | |
| 488 | - client = await PsycopgClient.connect(dsn, connect_timeout=connect_timeout_secs) | |
| 489 | - try: | |
| 490 | - await verify_school_schema(client, ref) | |
| 491 | - except Exception: | |
| 492 | - await client.close() | |
| 493 | - raise | |
| 494 | - log.info( | |
| 495 | - "okul veritabanina baglanildi (okul=%s, veritabani=%s)", | |
| 496 | - ref.slug, | |
| 497 | - database_name(control_db, ref.id), | |
| 498 | - ) | |
| 499 | - return OpenedSchool(PgStore(client), client.close) | |
| 500 | - | |
| 501 | - return open_school | |
| 502 | - | |
| 503 | - | |
| 504 | -async def open_postgres( | |
| 505 | - dsn: str, | |
| 506 | - *, | |
| 507 | - max_pools: int = 8, | |
| 508 | - pool_ttl_secs: float = 900.0, | |
| 509 | - registry_ttl_secs: float = 30.0, | |
| 510 | - connect_timeout_secs: float = 10.0, | |
| 511 | - clock_fn: Callable[[], float] = time.monotonic, | |
| 512 | -) -> TenantStores: | |
| 513 | - """Kontrol veritabanina baglan ve sinirli okul dizinini kur. | |
| 514 | - | |
| 515 | - Acilista kutuk OKUNMAZ: kontrol baglantisi kurulur, veritabaninin kendi | |
| 516 | - adi ogrenilir ve biter. Okul satiri olmayan bir kurulum bu yuzden SORUNSUZ | |
| 517 | - acilir; eksik okul veritabani da acilisi degil, o okulun istegini dusurur. | |
| 518 | - """ | |
| 519 | - from .pg_client import PsycopgClient | |
| 520 | - | |
| 521 | - client = await PsycopgClient.connect(dsn, connect_timeout=connect_timeout_secs) | |
| 522 | - try: | |
| 523 | - control_db = await control_database(client) | |
| 524 | - except Exception: | |
| 525 | - await client.close() | |
| 526 | - raise | |
| 527 | - registry = SchoolRegistry(client, ttl_secs=registry_ttl_secs, clock_fn=clock_fn) | |
| 528 | - return TenantStores( | |
| 529 | - registry, | |
| 530 | - postgres_opener(dsn, control_db, connect_timeout_secs=connect_timeout_secs), | |
| 531 | - max_pools=max_pools, | |
| 532 | - ttl_secs=pool_ttl_secs, | |
| 533 | - clock_fn=clock_fn, | |
| 534 | - teardown=[client.close], | |
| 535 | - ) | |
| 536 | - | |
| 537 | - | |
| 538 | -async def open_directory(settings: Any) -> Directory: | |
| 539 | - """Acilista servisin okul dizinini kurar. | |
| 540 | - | |
| 541 | - `ZEKA_PG_DSN` doluysa kontrol tabanli sinirli havuzlar; bos ise eski tek | |
| 542 | - veritabani modu (okul listesi `ZEKA_SCHOOLS`). | |
| 543 | - """ | |
| 544 | - from . import store_factory | |
| 545 | - | |
| 546 | - if store_factory.is_postgres(): | |
| 547 | - import os | |
| 548 | - | |
| 549 | - return await open_postgres( | |
| 550 | - os.environ.get("ZEKA_PG_DSN", "").strip(), | |
| 551 | - max_pools=settings.max_school_pools, | |
| 552 | - pool_ttl_secs=settings.school_pool_ttl_secs, | |
| 553 | - registry_ttl_secs=settings.school_registry_ttl_secs, | |
| 554 | - connect_timeout_secs=settings.school_connect_timeout_secs, | |
| 555 | - ) | |
| 556 | - store, client = await store_factory.open_store() | |
| 557 | - return OneDatabase(store, settings.schools, teardown=[client.close]) |
service/tests/fakes.pymodified+149 -1
| @@ -1,13 +1,20 @@ | ||
| 1 | -"""Testler için sahte kaynak ve fikstür üreticileri. | |
| 1 | +"""Testler için sahte kaynak, sahte köprü ve fikstür üreticileri. | |
| 2 | 2 | |
| 3 | 3 | `FakeSource` imzaları `Source` protokolüyle **birebir aynıdır**; böylece |
| 4 | 4 | köprü ajanının yazdığı `FileSource` geldiğinde testler değişmeden çalışır. |
| 5 | +`ReplyingCaller` ise `src.store.BridgeCaller` protokolünü uygular: depo | |
| 6 | +çağrıları gerçek hat üzerinden koşar, yalnız taşıma sahtedir. | |
| 5 | 7 | """ |
| 6 | 8 | |
| 7 | 9 | from __future__ import annotations |
| 8 | 10 | |
| 11 | +import json | |
| 12 | +from pathlib import Path | |
| 9 | 13 | from typing import Any |
| 10 | 14 | |
| 15 | +from src.compute import clock | |
| 16 | +from src.store import CAP_SCHOOLS, RecordingCaller | |
| 17 | + | |
| 11 | 18 | _CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ" |
| 12 | 19 | |
| 13 | 20 | |
| @@ -225,3 +232,144 @@ class FakeSource: | ||
| 225 | 232 | ) -> list[dict]: |
| 226 | 233 | self.calls.append("course_notes") |
| 227 | 234 | return [] |
| 235 | + | |
| 236 | + | |
| 237 | +# --------------------------------------------------------------------------- | |
| 238 | +# Fikstür üretimi -- `FileSource`'un okuduğu dizin düzeni | |
| 239 | +# --------------------------------------------------------------------------- | |
| 240 | +# | |
| 241 | +# Bu üreticiler eskiden `tests/zeka_db.py` içindeydi; o dosya gerçek | |
| 242 | +# SurrealDB'ye bağlanan entegrasyon testleriyle birlikte silindi. Disk | |
| 243 | +# fikstürü YAZMAK veritabanı gerektirmez, o yüzden burada yaşıyor. | |
| 244 | + | |
| 245 | +NOW = 1_699_963_200_000 # 2023-11-14 12:00 UTC | |
| 246 | +DAY = 86_400_000 | |
| 247 | +HOUR = 3_600_000 | |
| 248 | +TERM_START = NOW - 150 * DAY | |
| 249 | + | |
| 250 | + | |
| 251 | +def student_payload( | |
| 252 | + uid: str, | |
| 253 | + class_id: str, | |
| 254 | + marks_list: list[int], | |
| 255 | + present: int, | |
| 256 | + absent: int, | |
| 257 | + *, | |
| 258 | + now_ms: int = NOW, | |
| 259 | +) -> dict[str, Any]: | |
| 260 | + """Tek öğrencinin bütün kaynak verisi (`FakeSource` ile aynı şekil).""" | |
| 261 | + base = now_ms - 100 * DAY | |
| 262 | + return { | |
| 263 | + "profile": profile(uid, [class_id], ["course-1"]), | |
| 264 | + "marks": [course_marks("course-1", marks_list, base, teachers=["teacher-1"])], | |
| 265 | + "attendance": [course_attendance("course-1", present=present, absent=absent)], | |
| 266 | + "pomodoro": [ | |
| 267 | + pomodoro( | |
| 268 | + (clock.tr_day(now_ms) - d) * DAY + 10 * HOUR - clock.TR_OFFSET_MS | |
| 269 | + ) | |
| 270 | + for d in range(1, 7) | |
| 271 | + ], | |
| 272 | + "homework_report": [ | |
| 273 | + report_entry( | |
| 274 | + f"hw-{uid}-{i}", "course-1", now_ms - (i + 1) * DAY, submitted=True | |
| 275 | + ) | |
| 276 | + for i in range(6) | |
| 277 | + ], | |
| 278 | + "homework_list": [homework("upcoming", "course-1", now_ms + 6 * HOUR, [uid])], | |
| 279 | + } | |
| 280 | + | |
| 281 | + | |
| 282 | +def dataset(count: int = 12, *, now_ms: int = NOW) -> dict[str, dict]: | |
| 283 | + """Bir şube, bir ders, `count` öğrenci; ilki belirgin biçimde düşük.""" | |
| 284 | + data: dict[str, dict] = {} | |
| 285 | + for i in range(count): | |
| 286 | + uid = f"student-{i:02d}" | |
| 287 | + if i == 0: | |
| 288 | + data[uid] = student_payload( | |
| 289 | + uid, "class-A", [40, 41, 39, 42, 40, 38], 60, 40, now_ms=now_ms | |
| 290 | + ) | |
| 291 | + else: | |
| 292 | + data[uid] = student_payload( | |
| 293 | + uid, "class-A", [70, 72, 71, 69, 70, 71], 95, 5, now_ms=now_ms | |
| 294 | + ) | |
| 295 | + data["_school"] = { | |
| 296 | + "homework_list": [ | |
| 297 | + homework("hw-school", "course-1", now_ms + DAY, list(data.keys())) | |
| 298 | + ] | |
| 299 | + } | |
| 300 | + return data | |
| 301 | + | |
| 302 | + | |
| 303 | +def write_fixtures(root: Path, school: str, data: dict[str, dict]) -> list[str]: | |
| 304 | + """`data` sözlüğünü `FileSource`'un beklediği dizin düzenine yazar. | |
| 305 | + | |
| 306 | + Dönen değer: okul genelinde işlenecek öğrenci kimlikleri. | |
| 307 | + """ | |
| 308 | + base = root / school | |
| 309 | + #: yöntem -> (alt dizin, zarf anahtarı veya None) | |
| 310 | + layout = { | |
| 311 | + "profile": ("profile", None), | |
| 312 | + "marks": ("marks", "courses"), | |
| 313 | + "attendance": ("attendance", "courses"), | |
| 314 | + "pomodoro": ("pomodoro", "items"), | |
| 315 | + "homework_report": ("homework_report", "items"), | |
| 316 | + "homework_list": ("homework", "items"), | |
| 317 | + } | |
| 318 | + for directory, _ in layout.values(): | |
| 319 | + (base / directory).mkdir(parents=True, exist_ok=True) | |
| 320 | + | |
| 321 | + students: list[str] = [] | |
| 322 | + for key, payload in data.items(): | |
| 323 | + name = "_service" if key == "_school" else key | |
| 324 | + if key != "_school": | |
| 325 | + students.append(key) | |
| 326 | + for method, (directory, envelope) in layout.items(): | |
| 327 | + if method not in payload: | |
| 328 | + continue | |
| 329 | + body = payload[method] | |
| 330 | + if envelope is None: | |
| 331 | + out: Any = body | |
| 332 | + elif method == "homework_report": | |
| 333 | + out = {"items": body, "total": len(body), "limit": None, "offset": 0} | |
| 334 | + else: | |
| 335 | + out = {envelope: body} | |
| 336 | + (base / directory / f"{name}.json").write_text( | |
| 337 | + json.dumps(out, ensure_ascii=False), encoding="utf-8" | |
| 338 | + ) | |
| 339 | + return students | |
| 340 | + | |
| 341 | + | |
| 342 | +# --------------------------------------------------------------------------- | |
| 343 | +# Sahte köprü -- depo çağrılarını toplayan ve cevap veren istemci | |
| 344 | +# --------------------------------------------------------------------------- | |
| 345 | + | |
| 346 | + | |
| 347 | +class ReplyingCaller(RecordingCaller): | |
| 348 | + """`RecordingCaller` + yetenek başına hazır cevap. | |
| 349 | + | |
| 350 | + `RecordingCaller` okuma çağrılarına boş listeler döner; okul listesi, | |
| 351 | + devreden öğrenciler gibi gerçek içerik gereken yerlerde bu sınıf | |
| 352 | + kullanılır. Kayıt ve hata davranışı aynen devralınır. | |
| 353 | + """ | |
| 354 | + | |
| 355 | + def __init__(self, replies: dict[str, dict[str, Any]], **kw: Any) -> None: | |
| 356 | + super().__init__(**kw) | |
| 357 | + self.replies = dict(replies) | |
| 358 | + | |
| 359 | + async def call( | |
| 360 | + self, capability: str, school: str, payload: dict[str, Any] | |
| 361 | + ) -> dict[str, Any]: | |
| 362 | + if ( | |
| 363 | + capability in self.replies | |
| 364 | + and self.fail_times <= 0 | |
| 365 | + and capability not in self.fail_capabilities | |
| 366 | + ): | |
| 367 | + self.calls.append((capability, school, payload)) | |
| 368 | + return dict(self.replies[capability]) | |
| 369 | + return await super().call(capability, school, payload) | |
| 370 | + | |
| 371 | + | |
| 372 | +def schools_caller(schools: list[str], **kw: Any) -> ReplyingCaller: | |
| 373 | + """Okul listesini `insight.schools.list`'ten veren sahte köprü.""" | |
| 374 | + return ReplyingCaller({CAP_SCHOOLS: {"schools": list(schools)}}, **kw) | |
| 375 | + |
service/tests/test_config.pymodified+3 -19
| @@ -24,11 +24,6 @@ _CLEARED = { | ||
| 24 | 24 | "ZEKA_STUDENT_SOURCE", |
| 25 | 25 | "ZEKA_STUDENT_FILE", |
| 26 | 26 | "ZEKA_SOURCE", |
| 27 | - "ZEKA_DB_PASSWORD", | |
| 28 | - "ZEKA_MAX_SCHOOL_POOLS", | |
| 29 | - "ZEKA_SCHOOL_POOL_TTL_SECS", | |
| 30 | - "ZEKA_SCHOOL_REGISTRY_TTL_SECS", | |
| 31 | - "ZEKA_SCHOOL_CONNECT_TIMEOUT_SECS", | |
| 32 | 27 | ) |
| 33 | 28 | } |
| 34 | 29 | |
| @@ -51,12 +46,12 @@ class TokenTests(unittest.TestCase): | ||
| 51 | 46 | self.assertFalse(config.Config(require_token=False).has_token) |
| 52 | 47 | |
| 53 | 48 | def test_secrets_never_reach_the_summary(self): |
| 54 | - with _env(AI_SHARED_TOKEN="cok-gizli-sir", ZEKA_DB_PASSWORD="parola123"): | |
| 49 | + with _env(AI_SHARED_TOKEN="cok-gizli-sir"): | |
| 55 | 50 | summary = config.Config().summary() |
| 56 | 51 | self.assertNotIn("cok-gizli-sir", summary) |
| 57 | - self.assertNotIn("parola123", summary) | |
| 58 | 52 | self.assertIn("token=tanimli", summary) |
| 59 | - self.assertIn("db_parola=tanimli", summary) | |
| 53 | + # Veritabani ozeti YOK: ZEKA'nin deposu yok, `depo=kopru(insight.*)`. | |
| 54 | + self.assertIn("depo=kopru(insight.*)", summary) | |
| 60 | 55 | |
| 61 | 56 | |
| 62 | 57 | class FingerprintTests(unittest.TestCase): |
| @@ -105,17 +100,6 @@ class ParsingTests(unittest.TestCase): | ||
| 105 | 100 | with _env(AI_SHARED_TOKEN="t", ZEKA_SCHOOLS=""): |
| 106 | 101 | self.assertEqual(config.Config().schools, ()) |
| 107 | 102 | |
| 108 | - def test_school_pool_knobs_are_parsed_and_bounded(self): | |
| 109 | - with _env(AI_SHARED_TOKEN="t", ZEKA_MAX_SCHOOL_POOLS="3", ZEKA_SCHOOL_POOL_TTL_SECS="60"): | |
| 110 | - settings = config.Config() | |
| 111 | - self.assertEqual(settings.max_school_pools, 3) | |
| 112 | - self.assertEqual(settings.school_pool_ttl_secs, 60.0) | |
| 113 | - self.assertEqual(settings.school_registry_ttl_secs, 30.0) | |
| 114 | - self.assertEqual(settings.school_connect_timeout_secs, 10.0) | |
| 115 | - with _env(ZEKA_MAX_SCHOOL_POOLS="0"): | |
| 116 | - with self.assertRaises(config.ConfigError): | |
| 117 | - config.Config(require_token=False) | |
| 118 | - | |
| 119 | 103 | def test_defaults_are_the_documented_ones(self): |
| 120 | 104 | with _env(AI_SHARED_TOKEN="t"): |
| 121 | 105 | settings = config.Config() |
service/tests/test_no_db.pyadded+168 -0
| @@ -0,0 +1,168 @@ | ||
| 1 | +"""ZEKA'nın veritabanına doğrudan erişmediğinin yapısal kanıtı. | |
| 2 | + | |
| 3 | +DEĞİŞMEZ KURAL (2026-09-17, kullanıcı): **bir AI servisi uygulama | |
| 4 | +veritabanına asla doğrudan erişmez.** ZEKA'nın kendi deposu yoktur: yazdığı | |
| 5 | +her satır `hezarfen_backend`'e bir `insight.*` yetenek çağrısıyla gider. | |
| 6 | +`pg_client.py`, `store_pg.py`, `tenants.py`, `store_factory.py` ve `schema/` | |
| 7 | +silindi ve geri gelmeleri yasaktır. | |
| 8 | + | |
| 9 | +Bu dosya kuralı davranışta değil **metinde** arar; çünkü asıl tehlike sessizce | |
| 10 | +geri sızan bir erişim yoludur ve o yol tek bir import'la başlar. | |
| 11 | + | |
| 12 | +Sınır: yalnız **yürütülebilir kod** taranır. Docstring ve yorum taranmaz — | |
| 13 | +kuralı ANLATAN cümle yasağın kendisi değildir. Taranan şey `ast` ile | |
| 14 | +çıkarılan import adları, adlar ve docstring olmayan metin sabitleridir. | |
| 15 | + | |
| 16 | +İkinci sınır: aranan dizeler burada PARÇALARDAN kurulur. Depoda düz metin | |
| 17 | +olarak duran bir yasaklı dize, `scripts/ci-sir-tara.py` gibi bir taramayı | |
| 18 | +gereksiz yere kırmızıya çevirirdi; yasağı arayan test de yasağa benzemek | |
| 19 | +zorunda değil. | |
| 20 | +""" | |
| 21 | + | |
| 22 | +from __future__ import annotations | |
| 23 | + | |
| 24 | +import ast | |
| 25 | +import importlib.util | |
| 26 | +import unittest | |
| 27 | +from pathlib import Path | |
| 28 | + | |
| 29 | +SERVICE = Path(__file__).resolve().parent.parent | |
| 30 | +SRC = SERVICE / "src" | |
| 31 | + | |
| 32 | +#: Sürücü adı: `import <sürücü>` biçiminde geçen şey erişim yolunun ta | |
| 33 | +#: kendisidir. | |
| 34 | +DRIVER = "psyco" + "pg" | |
| 35 | + | |
| 36 | +#: Bağlantı dizesi şemaları ve servisin artık kullanmadığı ayar adları. | |
| 37 | +SCHEMES = ("post" + "gres://", "post" + "gresql://") | |
| 38 | +DSN_KEYS = ("ZEKA_PG" + "_DSN", "ZEKA_DB" + "_") | |
| 39 | + | |
| 40 | +FORBIDDEN_TEXT = (DRIVER, *SCHEMES, *DSN_KEYS) | |
| 41 | + | |
| 42 | +#: SQL deyim başlangıçları. Bu kod tabanında SQL büyük harfle yazılır; tek | |
| 43 | +#: bir tanesi bile kendi sorgumuzu yazdığımız anlamına gelir. | |
| 44 | +FORBIDDEN_SQL = ( | |
| 45 | + "SELECT ", | |
| 46 | + "INSERT ", | |
| 47 | + "UPDATE ", | |
| 48 | + "DELETE FROM", | |
| 49 | + "UPSERT ", | |
| 50 | + "CREATE TABLE", | |
| 51 | +) | |
| 52 | + | |
| 53 | +#: Silinen modüller: dosyaları da import edilebilirlikleri de yasak. | |
| 54 | +REMOVED_MODULES = ("pg_client", "store_pg", "tenants", "store_factory") | |
| 55 | + | |
| 56 | + | |
| 57 | +def _docstring_nodes(tree: ast.AST) -> set[int]: | |
| 58 | + """Modül/sınıf/fonksiyon docstring'i olan `Constant` düğümlerinin kimliği.""" | |
| 59 | + found: set[int] = set() | |
| 60 | + holders = (ast.Module, ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef) | |
| 61 | + for node in ast.walk(tree): | |
| 62 | + if not isinstance(node, holders) or not node.body: | |
| 63 | + continue | |
| 64 | + first = node.body[0] | |
| 65 | + if ( | |
| 66 | + isinstance(first, ast.Expr) | |
| 67 | + and isinstance(first.value, ast.Constant) | |
| 68 | + and isinstance(first.value.value, str) | |
| 69 | + ): | |
| 70 | + found.add(id(first.value)) | |
| 71 | + return found | |
| 72 | + | |
| 73 | + | |
| 74 | +def _code_texts(tree: ast.AST) -> list[tuple[int, str]]: | |
| 75 | + """Kod metinleri: docstring olmayan metin sabitleri + tanımlayıcı adlar. | |
| 76 | + | |
| 77 | + Dönen çiftler `(satır, metin)`; bağlantı dizeleri ve SQL metin sabitinde, | |
| 78 | + sürücü adı hem import adı hem metin olarak yakalanır. | |
| 79 | + """ | |
| 80 | + docstrings = _docstring_nodes(tree) | |
| 81 | + found: list[tuple[int, str]] = [] | |
| 82 | + for node in ast.walk(tree): | |
| 83 | + if isinstance(node, ast.Constant) and isinstance(node.value, str): | |
| 84 | + if id(node) not in docstrings: | |
| 85 | + found.append((node.lineno, node.value)) | |
| 86 | + elif isinstance(node, (ast.Import, ast.ImportFrom)): | |
| 87 | + names = (alias.name for alias in node.names) | |
| 88 | + module = getattr(node, "module", None) | |
| 89 | + if module: | |
| 90 | + found.append((node.lineno, module)) | |
| 91 | + found.extend((node.lineno, name) for name in names) | |
| 92 | + return found | |
| 93 | + | |
| 94 | + | |
| 95 | +def _hits(texts: list[tuple[int, str]]) -> list[str]: | |
| 96 | + """Verilen kod metinlerinde yasağın geçtiği yerler.""" | |
| 97 | + found: list[str] = [] | |
| 98 | + for line, text in texts: | |
| 99 | + lowered = text.lower() | |
| 100 | + for token in FORBIDDEN_TEXT: | |
| 101 | + if token.lower() in lowered: | |
| 102 | + found.append(f"{line}: {token!r} geçiyor: {text[:60]!r}") | |
| 103 | + for token in FORBIDDEN_SQL: | |
| 104 | + if token in text: | |
| 105 | + found.append(f"{line}: SQL deyimi {token!r}: {text[:60]!r}") | |
| 106 | + return found | |
| 107 | + | |
| 108 | + | |
| 109 | +def _scan(path: Path) -> list[str]: | |
| 110 | + """Bir dosyada yasağın geçtiği yerler; boş liste = temiz.""" | |
| 111 | + tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path)) | |
| 112 | + return [f"{path}:{hit}" for hit in _hits(_code_texts(tree))] | |
| 113 | + | |
| 114 | + | |
| 115 | +class SourceScanTests(unittest.TestCase): | |
| 116 | + def test_source_tree_has_no_database_access(self) -> None: | |
| 117 | + self.assertTrue(SRC.is_dir(), f"kaynak ağacı yok: {SRC}") | |
| 118 | + files = sorted(SRC.rglob("*.py")) | |
| 119 | + self.assertGreater(len(files), 10, "kaynak ağacı beklenenden küçük") | |
| 120 | + hits: list[str] = [] | |
| 121 | + for path in files: | |
| 122 | + hits.extend(_scan(path)) | |
| 123 | + self.assertEqual(hits, [], "\n".join(hits)) | |
| 124 | + | |
| 125 | + def test_the_scan_would_catch_a_real_offence(self) -> None: | |
| 126 | + """Tarama gerçekten bakıyor mu: gömülü bir suç yakalanmalı.""" | |
| 127 | + offence = "\n".join( | |
| 128 | + ( | |
| 129 | + f"import {DRIVER}", | |
| 130 | + f"DSN = {SCHEMES[1]!r}", | |
| 131 | + f"KEY = {DSN_KEYS[0]!r}", | |
| 132 | + "Q = 'SELECT 1'", | |
| 133 | + ) | |
| 134 | + ) | |
| 135 | + tree = ast.parse(offence) | |
| 136 | + hits = _hits(_code_texts(tree)) | |
| 137 | + self.assertEqual(len(hits), 4, hits) | |
| 138 | + # Ve docstring'deki anlatım suç sayılmaz. | |
| 139 | + polite = f'def f():\n """{DRIVER} import edilmez; UPSERT yok."""\n' | |
| 140 | + self.assertEqual(_hits(_code_texts(ast.parse(polite))), []) | |
| 141 | + | |
| 142 | + def test_the_test_files_themselves_stay_clean(self) -> None: | |
| 143 | + """Test dosyaları da kurala uyar: yasaklı dize düz metin durmaz.""" | |
| 144 | + for path in sorted((SERVICE / "tests").rglob("*.py")): | |
| 145 | + with self.subTest(path=path.name): | |
| 146 | + raw = path.read_text(encoding="utf-8") | |
| 147 | + for token in FORBIDDEN_TEXT: | |
| 148 | + self.assertNotIn(token, raw, f"{path}: {token!r}") | |
| 149 | + | |
| 150 | + | |
| 151 | +class RemovedModuleTests(unittest.TestCase): | |
| 152 | + def test_removed_modules_are_not_importable(self) -> None: | |
| 153 | + for name in REMOVED_MODULES: | |
| 154 | + with self.subTest(module=name): | |
| 155 | + self.assertIsNone(importlib.util.find_spec(f"src.{name}")) | |
| 156 | + | |
| 157 | + def test_removed_module_files_do_not_exist(self) -> None: | |
| 158 | + for name in REMOVED_MODULES: | |
| 159 | + with self.subTest(module=name): | |
| 160 | + self.assertEqual(list(SERVICE.rglob(f"{name}.py")), []) | |
| 161 | + | |
| 162 | + def test_no_surql_schema_or_sql_bundle_remains(self) -> None: | |
| 163 | + self.assertEqual(list(SERVICE.rglob("*.surql")), []) | |
| 164 | + self.assertEqual(list(SERVICE.rglob("*.sql")), []) | |
| 165 | + | |
| 166 | + | |
| 167 | +if __name__ == "__main__": | |
| 168 | + unittest.main() |
service/tests/test_pipeline.pymodified+148 -172
| @@ -1,7 +1,11 @@ | ||
| 1 | -"""Uçtan uca hat testleri: `FakeSource` → hesap → tavsiye → `Store`. | |
| 1 | +"""Uçtan uca hat testleri: `FakeSource` → hesap → tavsiye → `BridgeStore`. | |
| 2 | 2 | |
| 3 | 3 | `FakeSource` imzaları `Source` protokolüyle birebir aynıdır; köprü ajanının |
| 4 | 4 | `FileSource`'u geldiğinde bu testler değişmeden çalışmalıdır. |
| 5 | + | |
| 6 | +Yazma yolu artık **köprüden** geçer: satırları `RecordingCaller` toplar | |
| 7 | +(`capture` testlerinde `CapturingCaller` tablolara da yazar). Gerçek bir | |
| 8 | +veritabanı yoktur — ZEKA'nın veritabanı yoktur. | |
| 5 | 9 | """ |
| 6 | 10 | |
| 7 | 11 | from __future__ import annotations |
| @@ -12,62 +16,47 @@ from pathlib import Path | ||
| 12 | 16 | |
| 13 | 17 | from src.compute import clock |
| 14 | 18 | from src.pipeline import RunResult, discover_students, run_school |
| 19 | +from src.report.capture import CapturingCaller | |
| 15 | 20 | from src.source import FileSource |
| 16 | -from src.store import RETENTION_DAYS, CollectingClient, Store | |
| 17 | - | |
| 18 | -from . import zeka_db | |
| 21 | +from src.store import ( | |
| 22 | + CAP_PURGE, | |
| 23 | + CAP_RECOMMENDATION, | |
| 24 | + CAP_RUN, | |
| 25 | + CAP_SUMMARY, | |
| 26 | + CAP_SWEEP, | |
| 27 | + RETENTION_DAYS, | |
| 28 | + BridgeStore, | |
| 29 | + RecordingCaller, | |
| 30 | +) | |
| 19 | 31 | |
| 20 | 32 | from .fakes import ( |
| 21 | 33 | FakeSource, |
| 22 | - course_attendance, | |
| 23 | - course_marks, | |
| 34 | + dataset, | |
| 24 | 35 | homework, |
| 25 | - pomodoro, | |
| 26 | - profile, | |
| 27 | - report_entry, | |
| 36 | + write_fixtures, | |
| 28 | 37 | ) |
| 29 | 38 | |
| 30 | 39 | DAY = 86_400_000 |
| 31 | -HOUR = 3_600_000 | |
| 32 | 40 | NOW = 1_699_963_200_000 # 2023-11-14 12:00 UTC |
| 33 | 41 | TERM_START = NOW - 150 * DAY |
| 34 | 42 | |
| 35 | 43 | |
| 36 | -def _student(uid: str, class_id: str, marks: list[int], present: int, absent: int): | |
| 37 | - """Bir öğrencinin tüm kaynak verisi.""" | |
| 38 | - base = NOW - 100 * DAY | |
| 39 | - return { | |
| 40 | - "profile": profile(uid, [class_id], ["course-1"]), | |
| 41 | - "marks": [course_marks("course-1", marks, base, teachers=["teacher-1"])], | |
| 42 | - "attendance": [course_attendance("course-1", present=present, absent=absent)], | |
| 43 | - "pomodoro": [ | |
| 44 | - pomodoro((clock.tr_day(NOW) - d) * DAY + 10 * HOUR - clock.TR_OFFSET_MS) | |
| 45 | - for d in range(1, 7) | |
| 46 | - ], | |
| 47 | - "homework_report": [ | |
| 48 | - report_entry(f"hw-{uid}-{i}", "course-1", NOW - (i + 1) * DAY, | |
| 49 | - submitted=True) | |
| 50 | - for i in range(6) | |
| 51 | - ], | |
| 52 | - "homework_list": [homework("upcoming", "course-1", NOW + 6 * HOUR, [uid])], | |
| 53 | - } | |
| 54 | - | |
| 55 | - | |
| 56 | 44 | def _dataset(n: int = 12) -> dict[str, dict]: |
| 57 | 45 | """Bir şube, bir ders, `n` öğrenci. Biri belirgin biçimde düşük.""" |
| 58 | - data: dict[str, dict] = {} | |
| 59 | - for i in range(n): | |
| 60 | - uid = f"student-{i:02d}" | |
| 61 | - if i == 0: | |
| 62 | - data[uid] = _student(uid, "class-A", [40, 41, 39, 42, 40, 38], 60, 40) | |
| 63 | - else: | |
| 64 | - data[uid] = _student(uid, "class-A", [70, 72, 71, 69, 70, 71], 95, 5) | |
| 65 | - data["_school"] = { | |
| 66 | - "homework_list": [ | |
| 67 | - homework("hw-school", "course-1", NOW + DAY, list(data.keys())) | |
| 68 | - ] | |
| 69 | - } | |
| 70 | - return data | |
| 46 | + return dataset(n) | |
| 47 | + | |
| 48 | + | |
| 49 | +def _rows(caller: RecordingCaller, capability: str) -> list[dict]: | |
| 50 | + """Toplanan çağrılardan bir yeteneğin satırlarını düzleştir.""" | |
| 51 | + rows: list[dict] = [] | |
| 52 | + for kind, _, payload in caller.calls: | |
| 53 | + if kind == capability: | |
| 54 | + rows.extend(payload.get("rows") or []) | |
| 55 | + return rows | |
| 56 | + | |
| 57 | + | |
| 58 | +def _run_calls(caller: RecordingCaller) -> list[dict]: | |
| 59 | + return [payload["run"] for kind, _, payload in caller.calls if kind == CAP_RUN] | |
| 71 | 60 | |
| 72 | 61 | |
| 73 | 62 | class TestDiscoverStudents(unittest.TestCase): |
| @@ -86,9 +75,9 @@ class TestDiscoverStudents(unittest.TestCase): | ||
| 86 | 75 | |
| 87 | 76 | |
| 88 | 77 | class PipelineTestCase(unittest.IsolatedAsyncioTestCase): |
| 89 | - async def _run(self, data: dict, **kw) -> tuple[RunResult, CollectingClient]: | |
| 90 | - client = CollectingClient() | |
| 91 | - store = Store(client) | |
| 78 | + async def _run(self, data: dict, **kw) -> tuple[RunResult, RecordingCaller]: | |
| 79 | + caller = RecordingCaller() | |
| 80 | + store = BridgeStore(caller) | |
| 92 | 81 | fail = kw.pop("fail", set()) |
| 93 | 82 | ids = [k for k in data if not k.startswith("_")] |
| 94 | 83 | args = { |
| @@ -98,28 +87,24 @@ class PipelineTestCase(unittest.IsolatedAsyncioTestCase): | ||
| 98 | 87 | } |
| 99 | 88 | args.update(kw) |
| 100 | 89 | result = await run_school( |
| 101 | - FakeSource(data, fail=fail), store, "okul", **args | |
| 90 | + FakeSource(data, fail=fail), store.store_for("okul"), "okul", **args | |
| 102 | 91 | ) |
| 103 | - return result, client | |
| 92 | + return result, caller | |
| 104 | 93 | |
| 105 | 94 | |
| 106 | 95 | class TestEndToEnd(PipelineTestCase): |
| 107 | 96 | async def test_full_run_succeeds(self) -> None: |
| 108 | - result, client = await self._run(_dataset()) | |
| 97 | + result, caller = await self._run(_dataset()) | |
| 109 | 98 | self.assertEqual(result.status, "ok") |
| 110 | 99 | self.assertEqual(result.students_total, 12) |
| 111 | 100 | self.assertEqual(result.students_ok, 12) |
| 112 | 101 | self.assertEqual(result.students_failed, 0) |
| 113 | 102 | self.assertGreater(result.rows_written, 0) |
| 114 | - self.assertTrue(client.statements) | |
| 103 | + self.assertTrue(caller.calls) | |
| 115 | 104 | |
| 116 | 105 | async def test_insight_run_row_is_written_twice(self) -> None: |
| 117 | - _, client = await self._run(_dataset()) | |
| 118 | - runs = [ | |
| 119 | - s | |
| 120 | - for s in client.statements | |
| 121 | - if "insight_run" in s[0] and not s[0].startswith("DELETE") | |
| 122 | - ] | |
| 106 | + _, caller = await self._run(_dataset()) | |
| 107 | + runs = [run for run in _run_calls(caller)] | |
| 123 | 108 | self.assertEqual(len(runs), 2) # başlangıç ("running") + bitiş |
| 124 | 109 | |
| 125 | 110 | async def test_run_key_is_tr_date_scoped(self) -> None: |
| @@ -127,40 +112,33 @@ class TestEndToEnd(PipelineTestCase): | ||
| 127 | 112 | self.assertEqual(result.run_key(), f"okul_{clock.tr_date_key(NOW)}") |
| 128 | 113 | |
| 129 | 114 | async def test_summaries_carry_retention(self) -> None: |
| 130 | - _, client = await self._run(_dataset()) | |
| 131 | - summary = next( | |
| 132 | - variables | |
| 133 | - for sql, variables in client.statements | |
| 134 | - if "student_summary" in sql and "DELETE" not in sql | |
| 135 | - ) | |
| 136 | - row = summary["v0"] | |
| 115 | + _, caller = await self._run(_dataset()) | |
| 116 | + row = _rows(caller, CAP_SUMMARY)[0] | |
| 137 | 117 | self.assertEqual( |
| 138 | 118 | row["retain_until"], |
| 139 | 119 | NOW + RETENTION_DAYS["student_summary"] * DAY, |
| 140 | 120 | ) |
| 141 | 121 | |
| 142 | - async def test_sweep_runs_for_every_table(self) -> None: | |
| 143 | - _, client = await self._run(_dataset()) | |
| 144 | - deletes = [sql for sql, _ in client.statements if sql.startswith("DELETE")] | |
| 145 | - for table in RETENTION_DAYS: | |
| 146 | - self.assertTrue(any(table in sql for sql in deletes), table) | |
| 122 | + async def test_cleanup_calls_go_out_once(self) -> None: | |
| 123 | + """Koşu sonunda süpürme ve mezuniyet temizliği çağrılır.""" | |
| 124 | + _, caller = await self._run(_dataset()) | |
| 125 | + kinds = [capability for capability, _, _ in caller.calls] | |
| 126 | + self.assertEqual(kinds.count(CAP_SWEEP), 1) | |
| 127 | + purge = [ | |
| 128 | + payload | |
| 129 | + for capability, _, payload in caller.calls | |
| 130 | + if capability == CAP_PURGE | |
| 131 | + ] | |
| 132 | + self.assertEqual(len(purge), 1) | |
| 133 | + self.assertEqual(len(purge[0]["students"]), 12) | |
| 147 | 134 | |
| 148 | 135 | async def test_low_performer_gets_review_band_via_cohort(self) -> None: |
| 149 | 136 | """Kohort şube × ders düzeyinde kuruldu; düşük öğrenci ayrışıyor.""" |
| 150 | - _, client = await self._run(_dataset()) | |
| 151 | - rows = [ | |
| 152 | - variables | |
| 153 | - for sql, variables in client.statements | |
| 154 | - if "student_summary" in sql and "DELETE" not in sql | |
| 155 | - ] | |
| 137 | + _, caller = await self._run(_dataset()) | |
| 156 | 138 | bands: dict[str, str] = {} |
| 157 | - for batch in rows: | |
| 158 | - index = 0 | |
| 159 | - while f"v{index}" in batch: | |
| 160 | - row = batch[f"v{index}"] | |
| 161 | - placement = row["marks"]["courses"]["course-1"]["placement"] | |
| 162 | - bands[row["student"]] = str(placement["band"]) | |
| 163 | - index += 1 | |
| 139 | + for row in _rows(caller, CAP_SUMMARY): | |
| 140 | + placement = row["marks"]["courses"]["course-1"]["placement"] | |
| 141 | + bands[row["student"]] = str(placement["band"]) | |
| 164 | 142 | self.assertEqual(bands["student-00"], "review") |
| 165 | 143 | self.assertEqual(bands["student-01"], "on_track") |
| 166 | 144 | |
| @@ -176,13 +154,12 @@ class TestPartialFailure(PipelineTestCase): | ||
| 176 | 154 | self.assertGreater(result.rows_written, 0) |
| 177 | 155 | |
| 178 | 156 | async def test_write_failure_is_recorded_but_run_continues(self) -> None: |
| 179 | - client = CollectingClient() | |
| 180 | - client.fail_times = 10 # ilk gruplar düşsün | |
| 181 | - store = Store(client) | |
| 157 | + caller = RecordingCaller(fail_times=10) # ilk gruplar düşsün | |
| 158 | + store = BridgeStore(caller) | |
| 182 | 159 | data = _dataset() |
| 183 | 160 | result = await run_school( |
| 184 | 161 | FakeSource(data), |
| 185 | - store, | |
| 162 | + store.store_for("okul"), | |
| 186 | 163 | "okul", |
| 187 | 164 | now_ms=NOW, |
| 188 | 165 | student_ids=[k for k in data if not k.startswith("_")], |
| @@ -194,11 +171,14 @@ class TestPartialFailure(PipelineTestCase): | ||
| 194 | 171 | class TestBudget(PipelineTestCase): |
| 195 | 172 | async def test_zero_budget_stops_and_records_pending(self) -> None: |
| 196 | 173 | """Bütçe aşımında hat durur ve kalanlar bir sonraki koşuya yazılır.""" |
| 197 | - result, _ = await self._run(_dataset(), budget_ms=-1) | |
| 174 | + result, caller = await self._run(_dataset(), budget_ms=-1) | |
| 198 | 175 | self.assertTrue(result.budget_exceeded) |
| 199 | 176 | self.assertEqual(result.status, "partial") |
| 200 | 177 | self.assertEqual(len(result.pending_students), 12) |
| 201 | 178 | self.assertEqual(result.students_ok, 0) |
| 179 | + # Koşu defteri satırı devredenleri taşır: bir sonraki koşu buradan | |
| 180 | + # devam eder. | |
| 181 | + self.assertEqual(len(_run_calls(caller)[-1]["pending_students"]), 12) | |
| 202 | 182 | |
| 203 | 183 | async def test_generous_budget_completes(self) -> None: |
| 204 | 184 | result, _ = await self._run(_dataset(), budget_ms=60_000) |
| @@ -208,75 +188,61 @@ class TestBudget(PipelineTestCase): | ||
| 208 | 188 | |
| 209 | 189 | class TestPrivacyInPipelineOutput(PipelineTestCase): |
| 210 | 190 | async def test_attention_rows_have_no_score(self) -> None: |
| 211 | - _, client = await self._run(_dataset()) | |
| 212 | - for sql, variables in client.statements: | |
| 213 | - if "student_summary" not in sql or "DELETE" in sql: | |
| 214 | - continue | |
| 215 | - index = 0 | |
| 216 | - while f"v{index}" in variables: | |
| 217 | - for item in variables[f"v{index}"]["attention"]: | |
| 218 | - self.assertIn("trigger", item) | |
| 219 | - self.assertNotIn("score", item) | |
| 220 | - self.assertNotIn("rank", item) | |
| 221 | - index += 1 | |
| 191 | + _, caller = await self._run(_dataset()) | |
| 192 | + rows = _rows(caller, CAP_SUMMARY) | |
| 193 | + self.assertTrue(rows) | |
| 194 | + for row in rows: | |
| 195 | + for item in row["attention"]: | |
| 196 | + self.assertIn("trigger", item) | |
| 197 | + self.assertNotIn("score", item) | |
| 198 | + self.assertNotIn("rank", item) | |
| 222 | 199 | |
| 223 | 200 | async def test_t4_recommendations_never_address_the_student(self) -> None: |
| 224 | - _, client = await self._run(_dataset()) | |
| 225 | - for sql, variables in client.statements: | |
| 226 | - if "recommendation" not in sql or "DELETE" in sql: | |
| 227 | - continue | |
| 228 | - index = 0 | |
| 229 | - while f"v{index}" in variables: | |
| 230 | - row = variables[f"v{index}"] | |
| 231 | - if row["product"] == "T4": | |
| 232 | - self.assertEqual(row["audience_role"], "teacher") | |
| 233 | - self.assertNotEqual(row["audience"], row["about"]) | |
| 234 | - index += 1 | |
| 201 | + _, caller = await self._run(_dataset()) | |
| 202 | + rows = _rows(caller, CAP_RECOMMENDATION) | |
| 203 | + self.assertTrue(rows) | |
| 204 | + for row in rows: | |
| 205 | + if row["product"] == "T4": | |
| 206 | + self.assertEqual(row["audience_role"], "teacher") | |
| 207 | + self.assertNotEqual(row["audience"], row["about"]) | |
| 235 | 208 | |
| 236 | 209 | async def test_every_stored_recommendation_has_evidence(self) -> None: |
| 237 | - _, client = await self._run(_dataset()) | |
| 238 | - seen = 0 | |
| 239 | - for sql, variables in client.statements: | |
| 240 | - if "recommendation" not in sql or "DELETE" in sql: | |
| 241 | - continue | |
| 242 | - index = 0 | |
| 243 | - while f"v{index}" in variables: | |
| 244 | - row = variables[f"v{index}"] | |
| 245 | - payload = { | |
| 246 | - k: v for k, v in row["evidence"].items() if k != "limitation" | |
| 247 | - } | |
| 248 | - self.assertTrue(payload, row["rule_id"]) | |
| 249 | - seen += 1 | |
| 250 | - index += 1 | |
| 251 | - self.assertGreater(seen, 0) | |
| 210 | + _, caller = await self._run(_dataset()) | |
| 211 | + rows = _rows(caller, CAP_RECOMMENDATION) | |
| 212 | + self.assertTrue(rows) | |
| 213 | + for row in rows: | |
| 214 | + payload = {k: v for k, v in row["evidence"].items() if k != "limitation"} | |
| 215 | + self.assertTrue(payload, row["rule_id"]) | |
| 252 | 216 | |
| 253 | 217 | |
| 254 | 218 | # =========================================================================== |
| 255 | -# `FileSource` FIKSTURLERIYLE UCTAN UCA + GERCEK SurrealDB | |
| 219 | +# `FileSource` FIKSTURLERIYLE UCTAN UCA + KOPRU TABLOLARI | |
| 256 | 220 | # =========================================================================== |
| 257 | 221 | # |
| 258 | 222 | # Yukaridaki testler `FakeSource` ile kosar (hizli, bellek ici). Asagidakiler |
| 259 | -# ayni hatti **diskteki JSON fiksturlerle** ve `FileSource` ile kosturur: | |
| 260 | -# "imzalar ayni" iddiasi boylece iddia olmaktan cikip kanita donusur. | |
| 223 | +# ayni hatti **diskteki JSON fiksturlerle** ve `FileSource` ile kosturur; | |
| 224 | +# `CapturingCaller` satirlari tablolara yazar, boylece satirlari OKUYARAK | |
| 225 | +# dogrulariz. Veritabani gerekmez. | |
| 261 | 226 | |
| 262 | 227 | |
| 263 | 228 | class TestFileSourceEndToEnd(unittest.IsolatedAsyncioTestCase): |
| 264 | - """Disk fiksturu -> `FileSource` -> hat. Veritabani gerekmez.""" | |
| 229 | + """Disk fikstürü → `FileSource` → hat. Veritabanı gerekmez.""" | |
| 265 | 230 | |
| 266 | 231 | def setUp(self) -> None: |
| 267 | 232 | self._tmp = tempfile.TemporaryDirectory() |
| 268 | 233 | self.root = Path(self._tmp.name) |
| 269 | - self.data = zeka_db.dataset(6) | |
| 270 | - self.students = zeka_db.write_fixtures(self.root, "okul-a", self.data) | |
| 234 | + self.data = dataset(6) | |
| 235 | + self.students = write_fixtures(self.root, "okul-a", self.data) | |
| 236 | + self.caller = CapturingCaller() | |
| 237 | + self.store = BridgeStore(self.caller) | |
| 271 | 238 | |
| 272 | 239 | def tearDown(self) -> None: |
| 273 | 240 | self._tmp.cleanup() |
| 274 | 241 | |
| 275 | 242 | async def test_run_from_disk_fixtures(self) -> None: |
| 276 | - client = CollectingClient() | |
| 277 | 243 | result = await run_school( |
| 278 | 244 | FileSource(self.root), |
| 279 | - Store(client), | |
| 245 | + self.store.store_for("okul-a"), | |
| 280 | 246 | "okul-a", |
| 281 | 247 | now_ms=NOW, |
| 282 | 248 | term_start_ms=TERM_START, |
| @@ -294,7 +260,7 @@ class TestFileSourceEndToEnd(unittest.IsolatedAsyncioTestCase): | ||
| 294 | 260 | ) |
| 295 | 261 | result = await run_school( |
| 296 | 262 | FileSource(self.root), |
| 297 | - Store(CollectingClient()), | |
| 263 | + self.store.store_for("okul-a"), | |
| 298 | 264 | "okul-a", |
| 299 | 265 | now_ms=NOW, |
| 300 | 266 | term_start_ms=TERM_START, |
| @@ -305,35 +271,38 @@ class TestFileSourceEndToEnd(unittest.IsolatedAsyncioTestCase): | ||
| 305 | 271 | self.assertGreater(result.rows_written, 0) |
| 306 | 272 | |
| 307 | 273 | |
| 308 | -@zeka_db.requires_db | |
| 309 | -class TestPipelineAgainstSurreal(unittest.IsolatedAsyncioTestCase): | |
| 310 | - """Hat gercekten yaziyor mu: satirlari OKUYARAK dogrula.""" | |
| 274 | +class TestPipelineWritesThroughTheBridge(unittest.IsolatedAsyncioTestCase): | |
| 275 | + """Satırlar gerçekten yazıldı mı: yakalanan tabloları OKUYARAK dogrula.""" | |
| 311 | 276 | |
| 312 | 277 | async def asyncSetUp(self) -> None: |
| 313 | - self.client = zeka_db.fresh_schema_client("hat") | |
| 314 | - self.store = Store(self.client) | |
| 278 | + self.caller = CapturingCaller() | |
| 279 | + self.store = BridgeStore(self.caller) | |
| 315 | 280 | self._tmp = tempfile.TemporaryDirectory() |
| 316 | 281 | self.root = Path(self._tmp.name) |
| 317 | - self.data = zeka_db.dataset(12) | |
| 318 | - zeka_db.write_fixtures(self.root, "okul-a", self.data) | |
| 282 | + self.data = dataset(12) | |
| 283 | + write_fixtures(self.root, "okul-a", self.data) | |
| 319 | 284 | |
| 320 | 285 | async def asyncTearDown(self) -> None: |
| 321 | 286 | self._tmp.cleanup() |
| 322 | 287 | |
| 323 | - async def _run(self, **kw): | |
| 288 | + async def _run(self, **kw) -> RunResult: | |
| 324 | 289 | args = {"now_ms": NOW, "term_start_ms": TERM_START} |
| 325 | 290 | args.update(kw) |
| 326 | 291 | return await run_school( |
| 327 | - FileSource(self.root), self.store, "okul-a", **args | |
| 292 | + FileSource(self.root), self.store.store_for("okul-a"), "okul-a", **args | |
| 328 | 293 | ) |
| 329 | 294 | |
| 295 | + @property | |
| 296 | + def tables(self) -> dict[str, list[dict]]: | |
| 297 | + return self.caller.as_tables() | |
| 298 | + | |
| 330 | 299 | async def test_end_to_end_rows_land_and_match_the_report(self) -> None: |
| 331 | 300 | result = await self._run() |
| 332 | 301 | self.assertEqual(result.status, "ok") |
| 333 | 302 | self.assertEqual(result.students_ok, 12) |
| 334 | 303 | |
| 335 | - summaries = zeka_db.count_rows(self.client, "student_summary") | |
| 336 | - recs = zeka_db.count_rows(self.client, "recommendation") | |
| 304 | + summaries = len(self.tables["student_summary"]) | |
| 305 | + recs = len(self.tables["recommendation"]) | |
| 337 | 306 | self.assertEqual(summaries, 12) |
| 338 | 307 | self.assertGreater(recs, 0) |
| 339 | 308 | # `rows_written` gercekten yazilan satir sayisidir. |
| @@ -341,7 +310,7 @@ class TestPipelineAgainstSurreal(unittest.IsolatedAsyncioTestCase): | ||
| 341 | 310 | |
| 342 | 311 | async def test_insight_run_is_written_and_ends_ok(self) -> None: |
| 343 | 312 | result = await self._run() |
| 344 | - rows = zeka_db.select(self.client, "SELECT * FROM insight_run;") | |
| 313 | + rows = self.tables["insight_run"] | |
| 345 | 314 | self.assertEqual(len(rows), 1) # basta 'running', sonda 'ok' -- ayni anahtar |
| 346 | 315 | row = rows[0] |
| 347 | 316 | self.assertEqual(row["status"], "ok") |
| @@ -351,18 +320,17 @@ class TestPipelineAgainstSurreal(unittest.IsolatedAsyncioTestCase): | ||
| 351 | 320 | self.assertFalse(row["budget_exceeded"]) |
| 352 | 321 | self.assertEqual(row["pending_students"], []) |
| 353 | 322 | |
| 354 | - async def test_nested_compute_output_survives_the_round_trip(self) -> None: | |
| 355 | - """FLEXIBLE alanlar: ic ice hesap ciktisi kaybolmadan geri okunuyor.""" | |
| 323 | + async def test_nested_compute_output_survives_the_bridge(self) -> None: | |
| 324 | + """Ic ice hesap ciktisi satirda kaybolmadan duruyor.""" | |
| 356 | 325 | await self._run() |
| 357 | - row = zeka_db.select( | |
| 358 | - self.client, | |
| 359 | - "SELECT * FROM student_summary WHERE student = 'student-00';", | |
| 360 | - )[0] | |
| 326 | + row = self.tables["student_summary"][0] | |
| 361 | 327 | self.assertIn("courses", row["marks"]) |
| 362 | 328 | self.assertIn("course-1", row["marks"]["courses"]) |
| 363 | 329 | self.assertIn("placement", row["marks"]["courses"]["course-1"]) |
| 330 | + expected = {r["student"]: r for r in self.tables["student_summary"]} | |
| 364 | 331 | self.assertEqual( |
| 365 | - row["marks"]["courses"]["course-1"]["placement"]["band"], "review" | |
| 332 | + expected["student-00"]["marks"]["courses"]["course-1"]["placement"]["band"], | |
| 333 | + "review", | |
| 366 | 334 | ) |
| 367 | 335 | self.assertIsInstance(row["attendance"], dict) |
| 368 | 336 | self.assertIsInstance(row["submission"], dict) |
| @@ -370,60 +338,68 @@ class TestPipelineAgainstSurreal(unittest.IsolatedAsyncioTestCase): | ||
| 370 | 338 | |
| 371 | 339 | async def test_stored_recommendations_keep_their_evidence(self) -> None: |
| 372 | 340 | await self._run() |
| 373 | - rows = zeka_db.select(self.client, "SELECT * FROM recommendation;") | |
| 341 | + rows = self.tables["recommendation"] | |
| 374 | 342 | self.assertTrue(rows) |
| 375 | 343 | for row in rows: |
| 376 | 344 | payload = {k: v for k, v in row["evidence"].items() if k != "limitation"} |
| 377 | 345 | self.assertTrue(payload, row["rule_id"]) |
| 378 | - self.assertTrue(row["evidence"]["limitation"]) | |
| 346 | + # `limitation` satırda KENDİ alanıdır; `evidence` içine katılması | |
| 347 | + # sunucunun işidir (köprü sözleşmesi: alanı sunucu ekler). | |
| 348 | + self.assertTrue(row["limitation"]) | |
| 379 | 349 | |
| 380 | 350 | async def test_partial_failure_keeps_the_written_rows(self) -> None: |
| 381 | - """Bir ogrenci duser, digerlerinin satirlari veritabaninda KALIR.""" | |
| 351 | + """Bir ogrenci duser, digerlerinin satirlari YAZILMIS kalir.""" | |
| 382 | 352 | (self.root / "okul-a" / "attendance" / "student-05.json").write_text( |
| 383 | 353 | '{"yanlis": []}', encoding="utf-8" |
| 384 | 354 | ) |
| 385 | 355 | result = await self._run() |
| 386 | 356 | self.assertEqual(result.students_failed, 1) |
| 387 | 357 | self.assertEqual(result.students_ok, 11) |
| 388 | - self.assertEqual(zeka_db.count_rows(self.client, "student_summary"), 11) | |
| 389 | - row = zeka_db.select(self.client, "SELECT * FROM insight_run;")[0] | |
| 358 | + self.assertEqual(len(self.tables["student_summary"]), 11) | |
| 359 | + row = self.tables["insight_run"][0] | |
| 390 | 360 | self.assertEqual(row["students_failed"], 1) |
| 391 | 361 | self.assertIn("fetch", row["failed_modules"]) |
| 392 | 362 | |
| 393 | 363 | async def test_budget_exceeded_writes_pending_students(self) -> None: |
| 394 | 364 | result = await self._run(budget_ms=-1) |
| 395 | 365 | self.assertEqual(result.status, "partial") |
| 396 | - row = zeka_db.select(self.client, "SELECT * FROM insight_run;")[0] | |
| 366 | + row = self.tables["insight_run"][0] | |
| 397 | 367 | self.assertTrue(row["budget_exceeded"]) |
| 398 | 368 | self.assertEqual(len(row["pending_students"]), 12) |
| 399 | - self.assertEqual(zeka_db.count_rows(self.client, "student_summary"), 0) | |
| 369 | + self.assertNotIn("student_summary", self.tables) | |
| 400 | 370 | |
| 401 | 371 | async def test_second_run_is_idempotent(self) -> None: |
| 402 | 372 | await self._run() |
| 403 | - before = zeka_db.count_rows(self.client, "student_summary") | |
| 404 | - recs_before = zeka_db.count_rows(self.client, "recommendation") | |
| 373 | + before = len(self.tables["student_summary"]) | |
| 374 | + recs_before = len(self.tables["recommendation"]) | |
| 405 | 375 | await self._run() |
| 406 | - self.assertEqual(zeka_db.count_rows(self.client, "student_summary"), before) | |
| 407 | - self.assertEqual(zeka_db.count_rows(self.client, "recommendation"), recs_before) | |
| 376 | + self.assertEqual(len(self.tables["student_summary"]), before) | |
| 377 | + self.assertEqual(len(self.tables["recommendation"]), recs_before) | |
| 408 | 378 | |
| 409 | - async def test_departed_student_is_purged_by_the_pipeline(self) -> None: | |
| 379 | + async def test_departed_student_leaves_the_purge_roster(self) -> None: | |
| 380 | + """Ayrilan ogrenci temizlik listesinde YOKTUR: profili kalmamalidir. | |
| 381 | + | |
| 382 | + Silme backend'in isidir; burada dogrulanan sey gonderilen listenin | |
| 383 | + gercekten daralmis olmasidir. | |
| 384 | + """ | |
| 410 | 385 | await self._run() |
| 411 | - self.assertEqual(zeka_db.count_rows(self.client, "student_summary"), 12) | |
| 412 | - # Ikinci kosuda liste daraliyor: ayrilan ogrencinin profili kalmamali. | |
| 386 | + self.assertEqual(len(self.tables["student_summary"]), 12) | |
| 413 | 387 | await run_school( |
| 414 | 388 | FileSource(self.root), |
| 415 | - self.store, | |
| 389 | + self.store.store_for("okul-a"), | |
| 416 | 390 | "okul-a", |
| 417 | 391 | now_ms=NOW, |
| 418 | 392 | term_start_ms=TERM_START, |
| 419 | 393 | student_ids=[f"student-{i:02d}" for i in range(10)], |
| 420 | 394 | ) |
| 421 | - kalanlar = { | |
| 422 | - r["student"] | |
| 423 | - for r in zeka_db.select(self.client, "SELECT student FROM student_summary;") | |
| 424 | - } | |
| 425 | - self.assertEqual(len(kalanlar), 10) | |
| 426 | - self.assertNotIn("student-11", kalanlar) | |
| 395 | + purge_calls = [ | |
| 396 | + payload | |
| 397 | + for capability, _, payload in self.caller.calls | |
| 398 | + if capability == CAP_PURGE | |
| 399 | + ] | |
| 400 | + self.assertEqual(len(purge_calls), 2) | |
| 401 | + self.assertEqual(len(purge_calls[-1]["students"]), 10) | |
| 402 | + self.assertNotIn("student-11", purge_calls[-1]["students"]) | |
| 427 | 403 | |
| 428 | 404 | |
| 429 | 405 | if __name__ == "__main__": |
service/tests/test_report.pymodified+17 -74
| @@ -35,7 +35,7 @@ from src.compute.model import Audience, Confidence, Recommendation, StudentSumma | ||
| 35 | 35 | from src.pipeline import run_school |
| 36 | 36 | from src.report import build as build_mod |
| 37 | 37 | from src.report import filters, load, render, text, writer |
| 38 | -from src.report.capture import CapturingClient | |
| 38 | +from src.report.capture import CapturingCaller | |
| 39 | 39 | from src.report.gate import ( |
| 40 | 40 | SUMMARY_COLUMNS_STUDENT, |
| 41 | 41 | ReportGateError, |
| @@ -45,12 +45,10 @@ from src.report.gate import ( | ||
| 45 | 45 | StudentFacingSummary, |
| 46 | 46 | has_attention_field, |
| 47 | 47 | ) |
| 48 | -from src.report.reader import DbReader, MemoryReader | |
| 49 | -from src.store import Store | |
| 48 | +from src.report.reader import MemoryReader | |
| 49 | +from src.store import BridgeStore, RecordingCaller | |
| 50 | 50 | |
| 51 | -from . import zeka_db | |
| 52 | - | |
| 53 | -NOW = zeka_db.NOW | |
| 51 | +from .fakes import NOW | |
| 54 | 52 | DAY = clock.DAY_MS |
| 55 | 53 | SCHOOL = "demo-okul" |
| 56 | 54 | |
| @@ -398,27 +396,6 @@ class DikkatListesiKapisi(unittest.TestCase): | ||
| 398 | 396 | with self.assertRaises(ReportGateError): |
| 399 | 397 | builder(facing) |
| 400 | 398 | |
| 401 | - def test_ogrenci_sorgusunda_attention_sutunu_hic_gecmez(self): | |
| 402 | - """Satır veritabanından dikkat listesi taşımadan çıkar.""" | |
| 403 | - | |
| 404 | - class FakeClient: | |
| 405 | - def __init__(self) -> None: | |
| 406 | - self.sql: list[str] = [] | |
| 407 | - | |
| 408 | - async def query(self, sql: str, variables: dict) -> Any: | |
| 409 | - self.sql.append(sql) | |
| 410 | - return [] | |
| 411 | - | |
| 412 | - client = FakeClient() | |
| 413 | - reader = DbReader(client) | |
| 414 | - asyncio.run(load.load_student_bundle(reader, SCHOOL, "ogrenci-a", now_ms=NOW)) | |
| 415 | - joined = "\n".join(client.sql) | |
| 416 | - self.assertNotIn("attention", joined) | |
| 417 | - self.assertIn("audience_role = $role", joined) | |
| 418 | - self.assertNotIn("attention", " ".join(SUMMARY_COLUMNS_STUDENT)) | |
| 419 | - # Kimlik karşılaştırmaları type::string ile sarılır (sözleşme §6). | |
| 420 | - self.assertIn("type::string($student)", joined) | |
| 421 | - | |
| 422 | 399 | def test_bellek_okuyucusu_da_sutun_izdusumunu_uygular(self): |
| 423 | 400 | reader = full_reader() |
| 424 | 401 | rows = asyncio.run( |
| @@ -428,6 +405,9 @@ class DikkatListesiKapisi(unittest.TestCase): | ||
| 428 | 405 | ) |
| 429 | 406 | self.assertEqual(len(rows), 1) |
| 430 | 407 | self.assertNotIn("attention", rows[0]) |
| 408 | + # Okuma sütun listesi dikkat listesini HİÇ istemez: sızıntı kapısı | |
| 409 | + # yalnız rapor kurucusunda değil, okuma sözleşmesinde de duruyor. | |
| 410 | + self.assertNotIn("attention", " ".join(SUMMARY_COLUMNS_STUDENT)) | |
| 431 | 411 | |
| 432 | 412 | def test_ogrenci_raporunun_hicbir_biciminde_dikkat_maddesi_yok(self): |
| 433 | 413 | report = build_report("ogrenci", student="ogrenci-a") |
| @@ -732,21 +712,26 @@ class BosVeri(unittest.TestCase): | ||
| 732 | 712 | |
| 733 | 713 | |
| 734 | 714 | class FiksturYolu(unittest.TestCase): |
| 735 | - """`pipeline` → `store` → `CapturingClient` → rapor.""" | |
| 715 | + """`pipeline` → `store` → `CapturingCaller` → rapor.""" | |
| 736 | 716 | |
| 737 | 717 | @classmethod |
| 738 | 718 | def setUpClass(cls) -> None: |
| 739 | 719 | root = Path(__file__).resolve().parent.parent / "fixtures" / "demo" |
| 740 | 720 | from src.source import FileSource |
| 741 | 721 | |
| 742 | - client = CapturingClient() | |
| 722 | + caller = CapturingCaller() | |
| 743 | 723 | asyncio.run( |
| 744 | 724 | run_school( |
| 745 | - FileSource(root), Store(client), SCHOOL, now_ms=NOW, budget_ms=60_000 | |
| 725 | + FileSource(root), | |
| 726 | + BridgeStore(caller).store_for(SCHOOL), | |
| 727 | + SCHOOL, | |
| 728 | + now_ms=NOW, | |
| 729 | + budget_ms=60_000, | |
| 746 | 730 | ) |
| 747 | 731 | ) |
| 748 | - cls.tables = client.as_tables() | |
| 749 | - cls.reader = client.as_reader() | |
| 732 | + cls.caller = caller | |
| 733 | + cls.tables = caller.as_tables() | |
| 734 | + cls.reader = caller.as_reader() | |
| 750 | 735 | |
| 751 | 736 | def test_hat_satir_yazdi(self): |
| 752 | 737 | self.assertIn("student_summary", self.tables) |
| @@ -796,47 +781,5 @@ class FiksturYolu(unittest.TestCase): | ||
| 796 | 781 | # --------------------------------------------------------------------------- |
| 797 | 782 | |
| 798 | 783 | |
| 799 | -@zeka_db.requires_db | |
| 800 | -class GercekVeritabanindanRapor(unittest.TestCase): | |
| 801 | - def test_yazilan_satirlar_rapora_donuyor(self): | |
| 802 | - client = zeka_db.fresh_schema_client("rapor") | |
| 803 | - store = Store(client) | |
| 804 | - summary = StudentSummary( | |
| 805 | - school=SCHOOL, | |
| 806 | - student="ogrenci-a", | |
| 807 | - computed_at=NOW, | |
| 808 | - marks=summary_row()["marks"], | |
| 809 | - attendance={}, | |
| 810 | - submission={}, | |
| 811 | - study={}, | |
| 812 | - attention=summary_row()["attention"], | |
| 813 | - confidence=Confidence.STABLE, | |
| 814 | - ) | |
| 815 | - rec = Recommendation( | |
| 816 | - school=SCHOOL, | |
| 817 | - audience="ogrenci-a", | |
| 818 | - audience_role=Audience.STUDENT, | |
| 819 | - product="O1", | |
| 820 | - rule_id="O1.review_band", | |
| 821 | - evidence={"student_average": 42.5, "class_average": 68.0}, | |
| 822 | - computed_at=NOW, | |
| 823 | - expires_at=NOW + 7 * DAY, | |
| 824 | - course="course-1", | |
| 825 | - limitation="Konu kırılımı yok.", | |
| 826 | - ) | |
| 827 | - asyncio.run(store.write_summaries([summary])) | |
| 828 | - asyncio.run(store.write_recommendations([rec])) | |
| 829 | - | |
| 830 | - reader = DbReader(client) | |
| 831 | - report = build_report("ogrenci", reader=reader, student="ogrenci-a") # type: ignore[arg-type] | |
| 832 | - blob = all_text(report) | |
| 833 | - self.assertIn("O1.review_band", blob) | |
| 834 | - # Dikkat listesi veritabanında VAR ama rapora gelmedi. | |
| 835 | - self.assertNotIn(GIZLI_OLGU, blob) | |
| 836 | - | |
| 837 | - staff = build_report("okul", reader=reader) # type: ignore[arg-type] | |
| 838 | - self.assertIn(GIZLI_OLGU, all_text(staff)) | |
| 839 | - | |
| 840 | - | |
| 841 | 784 | if __name__ == "__main__": |
| 842 | 785 | unittest.main() |
service/tests/test_scheduler.pymodified+180 -194
| @@ -9,8 +9,9 @@ Kanitlanmasi istenen dort sey: | ||
| 9 | 9 | 4. Gece penceresini beklemeden tetiklenebilen bir test kipi var ve bu kip |
| 10 | 10 | uretim yolunun **ayni** kodu. |
| 11 | 11 | |
| 12 | -Birim testleri sahte bir `Store` ile kosar; entegrasyon testleri gercek | |
| 13 | -SurrealDB'ye yazar (konteyner yoksa atlanir). | |
| 12 | +Okul listesi artik yapilandirmadan degil **dizinden** gelir: her tikte | |
| 13 | +`insight.schools.list` cagrilir. Testler sahte bir kopru ile kosar; gercek | |
| 14 | +veritabani yoktur. | |
| 14 | 15 | """ |
| 15 | 16 | |
| 16 | 17 | from __future__ import annotations |
| @@ -19,26 +20,54 @@ import asyncio | ||
| 19 | 20 | import tempfile |
| 20 | 21 | import unittest |
| 21 | 22 | from pathlib import Path |
| 23 | +from typing import Any | |
| 22 | 24 | |
| 23 | 25 | from src.compute import clock |
| 26 | +from src.report.capture import CapturingCaller | |
| 24 | 27 | from src.scheduler import WINDOW_END_HOUR, WINDOW_START_HOUR, Scheduler, in_window |
| 25 | 28 | from src.source import FileSource |
| 26 | -from src.store import CollectingClient, Store | |
| 27 | -from src.tenants import OneDatabase, SchoolDatabaseGone, TenantError | |
| 28 | - | |
| 29 | -from .fakes import FakeSource | |
| 30 | -from .zeka_db import ( | |
| 31 | - NOW, | |
| 32 | - TERM_START, | |
| 33 | - count_rows, | |
| 34 | - dataset, | |
| 35 | - fresh_schema_client, | |
| 36 | - requires_db, | |
| 37 | - select, | |
| 38 | - write_fixtures, | |
| 29 | +from src.store import ( | |
| 30 | + CAP_PENDING, | |
| 31 | + CAP_RUN, | |
| 32 | + CAP_SCHOOLS, | |
| 33 | + CAP_SUMMARY, | |
| 34 | + BridgeStore, | |
| 35 | + RecordingCaller, | |
| 39 | 36 | ) |
| 40 | 37 | |
| 38 | +from .fakes import FakeSource, dataset, write_fixtures | |
| 39 | + | |
| 41 | 40 | DAY = clock.DAY_MS |
| 41 | +NOW = 1_699_963_200_000 # 2023-11-14 12:00 UTC | |
| 42 | +TERM_START = NOW - 150 * DAY | |
| 43 | + | |
| 44 | + | |
| 45 | +class LedgerCaller(RecordingCaller): | |
| 46 | + """Kosu defterini tutan sahte backend. | |
| 47 | + | |
| 48 | + `insight.run.upsert` ile yazilan `pending_students`, `insight.pending.list` | |
| 49 | + ile geri verilir: gercek backend de en taze kosunun listesini boyle okur | |
| 50 | + (`db::insight::last_pending`). Okul listesi de buradan gelir. | |
| 51 | + """ | |
| 52 | + | |
| 53 | + def __init__(self, schools: list[str], **kw: Any) -> None: | |
| 54 | + super().__init__(**kw) | |
| 55 | + self.schools = list(schools) | |
| 56 | + self.pending: dict[str, list[str]] = {} | |
| 57 | + | |
| 58 | + async def call( | |
| 59 | + self, capability: str, school: str, payload: dict[str, Any] | |
| 60 | + ) -> dict[str, Any]: | |
| 61 | + if capability == CAP_SCHOOLS and not self.fail_times: | |
| 62 | + self.calls.append((capability, school, payload)) | |
| 63 | + return {"schools": list(self.schools)} | |
| 64 | + if capability == CAP_PENDING and not self.fail_times: | |
| 65 | + self.calls.append((capability, school, payload)) | |
| 66 | + return {"students": list(self.pending.get(school, []))} | |
| 67 | + reply = await super().call(capability, school, payload) | |
| 68 | + if capability == CAP_RUN: | |
| 69 | + self.pending[school] = list(payload["run"].get("pending_students") or []) | |
| 70 | + return reply | |
| 42 | 71 | |
| 43 | 72 | |
| 44 | 73 | class FakeMonotonic: |
| @@ -59,8 +88,11 @@ class FakeMonotonic: | ||
| 59 | 88 | return current |
| 60 | 89 | |
| 61 | 90 | |
| 62 | -def make_scheduler(data_by_school: dict[str, dict], **kw) -> tuple[Scheduler, Store]: | |
| 63 | - store = Store(CollectingClient()) | |
| 91 | +def make_scheduler( | |
| 92 | + data_by_school: dict[str, dict], **kw: Any | |
| 93 | +) -> tuple[Scheduler, LedgerCaller]: | |
| 94 | + caller = LedgerCaller(list(data_by_school)) | |
| 95 | + store = BridgeStore(caller) | |
| 64 | 96 | failing = kw.pop("failing", set()) |
| 65 | 97 | |
| 66 | 98 | def factory(school: str): |
| @@ -70,18 +102,28 @@ def make_scheduler(data_by_school: dict[str, dict], **kw) -> tuple[Scheduler, St | ||
| 70 | 102 | |
| 71 | 103 | scheduler = Scheduler( |
| 72 | 104 | factory, |
| 73 | - OneDatabase(store, list(data_by_school)), | |
| 105 | + store, | |
| 74 | 106 | term_start_ms=TERM_START, |
| 75 | 107 | clock_fn=lambda: NOW, |
| 76 | 108 | **kw, |
| 77 | 109 | ) |
| 78 | - return scheduler, store | |
| 110 | + return scheduler, caller | |
| 79 | 111 | |
| 80 | 112 | |
| 81 | 113 | def ids_of(data: dict) -> list[str]: |
| 82 | 114 | return [k for k in data if not k.startswith("_")] |
| 83 | 115 | |
| 84 | 116 | |
| 117 | +def run_rows(caller: RecordingCaller, school: str | None = None) -> list[dict]: | |
| 118 | + """Kosu defterine gonderilen satirlar (istege gore tek okul).""" | |
| 119 | + rows = [ | |
| 120 | + (frame, payload["run"]) | |
| 121 | + for capability, frame, payload in caller.calls | |
| 122 | + if capability == CAP_RUN | |
| 123 | + ] | |
| 124 | + return [row for frame, row in rows if school is None or frame == school] | |
| 125 | + | |
| 126 | + | |
| 85 | 127 | # =========================================================================== |
| 86 | 128 | # BIRIM |
| 87 | 129 | # =========================================================================== |
| @@ -102,9 +144,14 @@ class TestWindow(unittest.TestCase): | ||
| 102 | 144 | class TestOrderingAndOnceADay(unittest.IsolatedAsyncioTestCase): |
| 103 | 145 | async def test_schools_run_in_fixed_alphabetical_order(self) -> None: |
| 104 | 146 | data = {"c-okul": dataset(3), "a-okul": dataset(3), "b-okul": dataset(3)} |
| 105 | - scheduler, _ = make_scheduler(data) | |
| 147 | + scheduler, caller = make_scheduler(data) | |
| 106 | 148 | results = await scheduler.run_once(NOW) |
| 107 | 149 | self.assertEqual([r.school for r in results], ["a-okul", "b-okul", "c-okul"]) |
| 150 | + # Sira dizinden gelir: okul listesi tek bir cagriyla sorulur. | |
| 151 | + self.assertEqual( | |
| 152 | + [school for capability, school, _ in caller.calls if capability == CAP_SCHOOLS], | |
| 153 | + [""], | |
| 154 | + ) | |
| 108 | 155 | |
| 109 | 156 | async def test_a_school_runs_only_once_per_tr_day(self) -> None: |
| 110 | 157 | data = {"a-okul": dataset(3)} |
| @@ -192,7 +239,7 @@ class TestSchoolIsolation(unittest.IsolatedAsyncioTestCase): | ||
| 192 | 239 | scheduler, _ = make_scheduler(data, failing={"kirik-okul"}) |
| 193 | 240 | results = await scheduler.run_once(NOW) |
| 194 | 241 | self.assertEqual([r.school for r in results], ["a-okul", "z-okul"]) |
| 195 | - self.assertEqual(scheduler._failures, ["kirik-okul"]) | |
| 242 | + self.assertEqual(scheduler.failures(), ["kirik-okul"]) | |
| 196 | 243 | for result in results: |
| 197 | 244 | self.assertEqual(result.status, "ok") |
| 198 | 245 | self.assertEqual(result.students_ok, 3) |
| @@ -202,7 +249,7 @@ class TestSchoolIsolation(unittest.IsolatedAsyncioTestCase): | ||
| 202 | 249 | data = {"kirik-okul": dataset(2)} |
| 203 | 250 | scheduler, _ = make_scheduler(data, failing={"kirik-okul"}) |
| 204 | 251 | self.assertEqual(await scheduler.run_once(NOW), []) |
| 205 | - self.assertEqual(scheduler._failures, ["kirik-okul"]) | |
| 252 | + self.assertEqual(scheduler.failures(), ["kirik-okul"]) | |
| 206 | 253 | # Kaynak duzelirse ayni gece kosar. |
| 207 | 254 | scheduler._source_factory = lambda school: FakeSource(data[school]) |
| 208 | 255 | again = await scheduler.run_once(NOW + 900_000) |
| @@ -224,10 +271,9 @@ class TestServeTestMode(unittest.IsolatedAsyncioTestCase): | ||
| 224 | 271 | """Pencere kontrolu uretim yolunda aynen duruyor.""" |
| 225 | 272 | noon = clock.tr_day(NOW) * DAY - clock.TR_OFFSET_MS + 12 * 3_600_000 |
| 226 | 273 | data = {"a-okul": dataset(2)} |
| 227 | - store = Store(CollectingClient()) | |
| 228 | 274 | scheduler = Scheduler( |
| 229 | 275 | lambda school: FakeSource(data[school]), |
| 230 | - OneDatabase(store, list(data)), | |
| 276 | + BridgeStore(LedgerCaller(list(data))), | |
| 231 | 277 | clock_fn=lambda: noon, |
| 232 | 278 | ) |
| 233 | 279 | await scheduler.serve(tick_seconds=0.001, max_ticks=2) |
| @@ -246,17 +292,82 @@ class TestServeTestMode(unittest.IsolatedAsyncioTestCase): | ||
| 246 | 292 | |
| 247 | 293 | |
| 248 | 294 | # =========================================================================== |
| 249 | -# ENTEGRASYON -- gercek SurrealDB, cok okullu tam cevrim | |
| 295 | +# DIZIN (okul listesi) ve OKUL BASINA DEPO | |
| 250 | 296 | # =========================================================================== |
| 251 | 297 | |
| 252 | 298 | |
| 253 | -@requires_db | |
| 254 | -class TestFullCycleAgainstSurreal(unittest.IsolatedAsyncioTestCase): | |
| 255 | - """Fikstur -> hesap -> tavsiye -> GERCEK yazim -> `insight_run`.""" | |
| 299 | +class DirectoryDrivenTests(unittest.IsolatedAsyncioTestCase): | |
| 300 | + """Okul listesi YAPILANDIRMADAN degil, dizinden gelir. | |
| 301 | + | |
| 302 | + Her okul KENDI deposundan yazar; deposu cozulemeyen okul dusen okuldur. | |
| 303 | + """ | |
| 304 | + | |
| 305 | + async def test_the_tick_runs_exactly_what_the_directory_reports(self) -> None: | |
| 306 | + data = {"a-okul": dataset(2), "b-okul": dataset(2)} | |
| 307 | + caller = LedgerCaller(["a-okul"]) | |
| 308 | + store = BridgeStore(caller) | |
| 309 | + scheduler = Scheduler( | |
| 310 | + lambda school: FakeSource(data[school]), | |
| 311 | + store, | |
| 312 | + term_start_ms=TERM_START, | |
| 313 | + clock_fn=lambda: NOW, | |
| 314 | + ) | |
| 315 | + self.assertEqual([r.school for r in await scheduler.run_once(NOW)], ["a-okul"]) | |
| 316 | + | |
| 317 | + # Dizin okul eklerse surec YENIDEN BASLATILMADAN onu da gorur. | |
| 318 | + caller.schools.append("b-okul") | |
| 319 | + self.assertEqual([r.school for r in await scheduler.run_once(NOW)], ["b-okul"]) | |
| 320 | + | |
| 321 | + async def test_an_unreadable_directory_leaves_the_tick_empty_not_failed( | |
| 322 | + self, | |
| 323 | + ) -> None: | |
| 324 | + def never(_school: str): | |
| 325 | + raise AssertionError("okul listesi yokken kaynak kurulmamali") | |
| 326 | + | |
| 327 | + store = BridgeStore(RecordingCaller(fail_capabilities={CAP_SCHOOLS})) | |
| 328 | + scheduler = Scheduler(never, store, clock_fn=lambda: NOW) | |
| 329 | + self.assertEqual(await scheduler.run_once(NOW), []) | |
| 330 | + self.assertEqual(scheduler.failures(), []) | |
| 331 | + | |
| 332 | + async def test_a_school_whose_store_cannot_open_fails_alone(self) -> None: | |
| 333 | + data = {"b-okul": dataset(2)} | |
| 334 | + | |
| 335 | + class Directory: | |
| 336 | + """Depo cozulemeyen okul: `TenantError`in yerini tutan sahte dizin.""" | |
| 337 | + | |
| 338 | + async def active_schools(self) -> list[str]: | |
| 339 | + return ["a-okul", "b-okul"] | |
| 340 | + | |
| 341 | + def store_for(self, slug: str): | |
| 342 | + if slug == "a-okul": | |
| 343 | + raise RuntimeError("okul veritabani acilamadi") | |
| 344 | + return BridgeStore(LedgerCaller(["b-okul"])).store_for(slug) | |
| 345 | + | |
| 346 | + async def close(self) -> None: | |
| 347 | + return None | |
| 348 | + | |
| 349 | + scheduler = Scheduler( | |
| 350 | + lambda school: FakeSource(data[school]), | |
| 351 | + Directory(), | |
| 352 | + term_start_ms=TERM_START, | |
| 353 | + clock_fn=lambda: NOW, | |
| 354 | + ) | |
| 355 | + results = await scheduler.run_once(NOW) | |
| 356 | + self.assertEqual([r.school for r in results], ["b-okul"]) | |
| 357 | + self.assertEqual(scheduler.failures(), ["a-okul"]) | |
| 358 | + | |
| 359 | + | |
| 360 | +# =========================================================================== | |
| 361 | +# KOPRU UZERINDEN COK OKULLU TAM CEVRIM | |
| 362 | +# =========================================================================== | |
| 363 | + | |
| 364 | + | |
| 365 | +class FullCycleThroughTheBridge(unittest.IsolatedAsyncioTestCase): | |
| 366 | + """Fikstur -> hesap -> tavsiye -> kopruye yazim -> kosu defteri.""" | |
| 256 | 367 | |
| 257 | 368 | async def asyncSetUp(self) -> None: |
| 258 | - self.client = fresh_schema_client("cevrim") | |
| 259 | - self.store = Store(self.client) | |
| 369 | + self.caller = LedgerCaller(["kadikoy-lisesi", "uskudar-lisesi"]) | |
| 370 | + self.store = BridgeStore(self.caller) | |
| 260 | 371 | self._tmp = tempfile.TemporaryDirectory() |
| 261 | 372 | self.root = Path(self._tmp.name) |
| 262 | 373 | self.schools = ["kadikoy-lisesi", "uskudar-lisesi"] |
| @@ -267,15 +378,23 @@ class TestFullCycleAgainstSurreal(unittest.IsolatedAsyncioTestCase): | ||
| 267 | 378 | async def asyncTearDown(self) -> None: |
| 268 | 379 | self._tmp.cleanup() |
| 269 | 380 | |
| 270 | - def _scheduler(self, **kw) -> Scheduler: | |
| 381 | + def _scheduler(self, **kw: Any) -> Scheduler: | |
| 271 | 382 | return Scheduler( |
| 272 | 383 | lambda school: FileSource(self.root), |
| 273 | - OneDatabase(self.store, self.schools), | |
| 384 | + self.store, | |
| 274 | 385 | term_start_ms=TERM_START, |
| 275 | 386 | clock_fn=lambda: NOW, |
| 276 | 387 | **kw, |
| 277 | 388 | ) |
| 278 | 389 | |
| 390 | + def summaries_of(self, school: str) -> list[dict]: | |
| 391 | + return [ | |
| 392 | + row | |
| 393 | + for capability, frame, payload in self.caller.calls | |
| 394 | + if capability == CAP_SUMMARY and frame == school | |
| 395 | + for row in payload["rows"] | |
| 396 | + ] | |
| 397 | + | |
| 279 | 398 | async def test_full_round_writes_both_schools(self) -> None: |
| 280 | 399 | results = await self._scheduler().run_once(NOW) |
| 281 | 400 | self.assertEqual(len(results), 2) |
| @@ -285,35 +404,22 @@ class TestFullCycleAgainstSurreal(unittest.IsolatedAsyncioTestCase): | ||
| 285 | 404 | self.assertGreater(result.rows_written, 0) |
| 286 | 405 | |
| 287 | 406 | for school in self.schools: |
| 288 | - self.assertEqual( | |
| 289 | - count_rows(self.client, "student_summary", f"school = '{school}'"), | |
| 290 | - self.sizes[school], | |
| 291 | - ) | |
| 292 | - self.assertEqual( | |
| 293 | - count_rows(self.client, "insight_run", f"school = '{school}'"), 1 | |
| 294 | - ) | |
| 295 | - self.assertGreater(count_rows(self.client, "recommendation"), 0) | |
| 407 | + self.assertEqual(len(self.summaries_of(school)), self.sizes[school]) | |
| 408 | + runs = run_rows(self.caller, school) | |
| 409 | + self.assertEqual(len(runs), 2) # baslangic + bitis | |
| 410 | + self.assertEqual(runs[-1]["status"], "ok") | |
| 296 | 411 | |
| 297 | - async def test_tenant_isolation_end_to_end(self) -> None: | |
| 412 | + async def test_every_write_carries_its_own_school_frame(self) -> None: | |
| 413 | + """Okul kimligi CERCEVEDEDIR: her yazim kendi okulunun slug'iyla gider.""" | |
| 298 | 414 | await self._scheduler().run_once(NOW) |
| 415 | + frames = { | |
| 416 | + frame | |
| 417 | + for capability, frame, _ in self.caller.calls | |
| 418 | + if capability == CAP_SUMMARY | |
| 419 | + } | |
| 420 | + self.assertEqual(frames, set(self.schools)) | |
| 299 | 421 | for school in self.schools: |
| 300 | - rows = select( | |
| 301 | - self.client, | |
| 302 | - "SELECT school, student FROM student_summary WHERE school = $s;", | |
| 303 | - {"s": school}, | |
| 304 | - ) | |
| 305 | - self.assertEqual(len(rows), self.sizes[school]) | |
| 306 | - self.assertTrue(all(r["school"] == school for r in rows)) | |
| 307 | - recs = select( | |
| 308 | - self.client, | |
| 309 | - "SELECT school FROM recommendation WHERE school = $s;", | |
| 310 | - {"s": school}, | |
| 311 | - ) | |
| 312 | - self.assertTrue(all(r["school"] == school for r in recs)) | |
| 313 | - # Toplam, iki okulun toplamindan fazla degil: sizan satir yok. | |
| 314 | - self.assertEqual( | |
| 315 | - count_rows(self.client, "student_summary"), sum(self.sizes.values()) | |
| 316 | - ) | |
| 422 | + self.assertEqual(len(self.summaries_of(school)), self.sizes[school]) | |
| 317 | 423 | |
| 318 | 424 | async def test_budget_exceeded_school_is_deferred_others_are_not(self) -> None: |
| 319 | 425 | scheduler = self._scheduler(budgets={"uskudar-lisesi": -1}) |
| @@ -323,17 +429,11 @@ class TestFullCycleAgainstSurreal(unittest.IsolatedAsyncioTestCase): | ||
| 323 | 429 | self.assertTrue(results["uskudar-lisesi"].budget_exceeded) |
| 324 | 430 | |
| 325 | 431 | # Butcesiz okulun satirlari var, ertelenen okulunkiler yok. |
| 326 | - self.assertEqual( | |
| 327 | - count_rows(self.client, "student_summary", "school = 'kadikoy-lisesi'"), 8 | |
| 328 | - ) | |
| 329 | - self.assertEqual( | |
| 330 | - count_rows(self.client, "student_summary", "school = 'uskudar-lisesi'"), 0 | |
| 331 | - ) | |
| 332 | - # `insight_run` ertelemeyi kagit uzerinde tasiyor. | |
| 333 | - row = select( | |
| 334 | - self.client, | |
| 335 | - "SELECT * FROM insight_run WHERE school = 'uskudar-lisesi';", | |
| 336 | - )[0] | |
| 432 | + self.assertEqual(len(self.summaries_of("kadikoy-lisesi")), 8) | |
| 433 | + self.assertEqual(self.summaries_of("uskudar-lisesi"), []) | |
| 434 | + # `insight_run` ertelemeyi kagit uzerinde tasiyor (ayni anahtara iki | |
| 435 | + # yazim: basta 'running', sonda 'partial'). | |
| 436 | + row = run_rows(self.caller, "uskudar-lisesi")[-1] | |
| 337 | 437 | self.assertEqual(row["status"], "partial") |
| 338 | 438 | self.assertTrue(row["budget_exceeded"]) |
| 339 | 439 | self.assertEqual(len(row["pending_students"]), 5) |
| @@ -342,9 +442,7 @@ class TestFullCycleAgainstSurreal(unittest.IsolatedAsyncioTestCase): | ||
| 342 | 442 | scheduler._budgets["uskudar-lisesi"] = 60_000 |
| 343 | 443 | second = {r.school: r for r in await scheduler.run_once(NOW + DAY)} |
| 344 | 444 | self.assertEqual(second["uskudar-lisesi"].status, "ok") |
| 345 | - self.assertEqual( | |
| 346 | - count_rows(self.client, "student_summary", "school = 'uskudar-lisesi'"), 5 | |
| 347 | - ) | |
| 445 | + self.assertEqual(len(self.summaries_of("uskudar-lisesi")), 5) | |
| 348 | 446 | self.assertEqual(scheduler.pending_for("uskudar-lisesi"), []) |
| 349 | 447 | |
| 350 | 448 | async def test_one_broken_school_does_not_block_the_other(self) -> None: |
| @@ -354,22 +452,16 @@ class TestFullCycleAgainstSurreal(unittest.IsolatedAsyncioTestCase): | ||
| 354 | 452 | return FileSource(self.root) |
| 355 | 453 | |
| 356 | 454 | scheduler = Scheduler( |
| 357 | - factory, | |
| 358 | - OneDatabase(self.store, self.schools), | |
| 359 | - term_start_ms=TERM_START, | |
| 360 | - clock_fn=lambda: NOW, | |
| 455 | + factory, self.store, term_start_ms=TERM_START, clock_fn=lambda: NOW | |
| 361 | 456 | ) |
| 362 | 457 | results = await scheduler.run_once(NOW) |
| 363 | 458 | self.assertEqual([r.school for r in results], ["kadikoy-lisesi"]) |
| 364 | - self.assertEqual( | |
| 365 | - count_rows(self.client, "student_summary", "school = 'kadikoy-lisesi'"), 8 | |
| 366 | - ) | |
| 367 | - self.assertEqual( | |
| 368 | - count_rows(self.client, "student_summary", "school = 'uskudar-lisesi'"), 0 | |
| 369 | - ) | |
| 459 | + self.assertEqual(len(self.summaries_of("kadikoy-lisesi")), 8) | |
| 460 | + self.assertEqual(self.summaries_of("uskudar-lisesi"), []) | |
| 461 | + self.assertEqual(scheduler.failures(), ["uskudar-lisesi"]) | |
| 370 | 462 | |
| 371 | 463 | async def test_pending_survives_a_process_restart(self) -> None: |
| 372 | - """Bellek sifirlansa bile devreden liste `insight_run`'dan geri gelir.""" | |
| 464 | + """Bellek sifirlansa bile devreden liste kosu defterinden geri gelir.""" | |
| 373 | 465 | first = self._scheduler(budgets={"uskudar-lisesi": -1}) |
| 374 | 466 | await first.run_once(NOW) |
| 375 | 467 | self.assertEqual(len(first.pending_for("uskudar-lisesi")), 5) |
| @@ -380,9 +472,8 @@ class TestFullCycleAgainstSurreal(unittest.IsolatedAsyncioTestCase): | ||
| 380 | 472 | results = {r.school: r for r in await second.run_once(NOW + DAY)} |
| 381 | 473 | self.assertEqual(results["uskudar-lisesi"].status, "ok") |
| 382 | 474 | self.assertEqual(results["uskudar-lisesi"].students_ok, 5) |
| 383 | - self.assertEqual( | |
| 384 | - count_rows(self.client, "student_summary", "school = 'uskudar-lisesi'"), 5 | |
| 385 | - ) | |
| 475 | + # Yeniden baslayan surec devreden listeyi KOPRUDEN sordu. | |
| 476 | + self.assertIn(CAP_PENDING, [capability for capability, _, _ in self.caller.calls]) | |
| 386 | 477 | |
| 387 | 478 | async def test_serve_loop_runs_the_whole_cycle(self) -> None: |
| 388 | 479 | """Test kipi: pencereyi ve 15 dakikalik tigi beklemeden tam cevrim.""" |
| @@ -391,114 +482,9 @@ class TestFullCycleAgainstSurreal(unittest.IsolatedAsyncioTestCase): | ||
| 391 | 482 | tick_seconds=0.001, ignore_window=True, max_ticks=2 |
| 392 | 483 | ) |
| 393 | 484 | self.assertEqual(ticks, 2) |
| 394 | - self.assertEqual( | |
| 395 | - count_rows(self.client, "student_summary"), sum(self.sizes.values()) | |
| 396 | - ) | |
| 397 | - self.assertEqual(count_rows(self.client, "insight_run"), 2) | |
| 398 | - | |
| 399 | - async def test_rerunning_the_same_day_does_not_duplicate_rows(self) -> None: | |
| 400 | - scheduler = self._scheduler() | |
| 401 | - await scheduler.run_once(NOW) | |
| 402 | - before = count_rows(self.client, "student_summary") | |
| 403 | - scheduler._last_run_day.clear() # gun kapisini elle ac | |
| 404 | - await scheduler.run_once(NOW) | |
| 405 | - self.assertEqual(count_rows(self.client, "student_summary"), before) | |
| 406 | - | |
| 407 | - | |
| 408 | -class DirectoryDrivenTests(unittest.IsolatedAsyncioTestCase): | |
| 409 | - """Okul listesi YAPILANDIRMADAN degil, dizinden gelir. | |
| 410 | - | |
| 411 | - Eskiden okullar kurucuya liste olarak veriliyordu ve tek bir `store` | |
| 412 | - paylasiliyordu; cok okullu sekilde okulun kimligi cerceveden/dizinden | |
| 413 | - gelir, depo da okul basina cozulur. Bu sinif o donusu pinler. | |
| 414 | - """ | |
| 415 | - | |
| 416 | - def _store(self): | |
| 417 | - return Store(CollectingClient()) | |
| 418 | - | |
| 419 | - async def test_the_tick_runs_exactly_what_the_directory_reports(self): | |
| 420 | - store = self._store() | |
| 421 | - data = {"a-okul": dataset(2), "b-okul": dataset(2)} | |
| 422 | - | |
| 423 | - class Directory: | |
| 424 | - def __init__(self, schools): | |
| 425 | - self.schools = list(schools) | |
| 426 | - | |
| 427 | - async def active_schools(self): | |
| 428 | - return list(self.schools) | |
| 429 | - | |
| 430 | - async def store_for(self, slug): | |
| 431 | - if slug not in self.schools: | |
| 432 | - raise TenantError("yok", school=slug) | |
| 433 | - return store | |
| 434 | - | |
| 435 | - async def close(self): | |
| 436 | - return None | |
| 437 | - | |
| 438 | - def describe(self): | |
| 439 | - return "test dizini" | |
| 440 | - | |
| 441 | - directory = Directory(["a-okul"]) | |
| 442 | - scheduler = Scheduler( | |
| 443 | - lambda school: FakeSource(data[school]), | |
| 444 | - directory, | |
| 445 | - term_start_ms=TERM_START, | |
| 446 | - clock_fn=lambda: NOW, | |
| 447 | - ) | |
| 448 | - self.assertEqual([r.school for r in await scheduler.run_once(NOW)], ["a-okul"]) | |
| 449 | - | |
| 450 | - # Dizin okul eklerse surec YENIDEN BASLATILMADAN onu da gorur. | |
| 451 | - directory.schools.append("b-okul") | |
| 452 | - self.assertEqual([r.school for r in await scheduler.run_once(NOW)], ["b-okul"]) | |
| 453 | - | |
| 454 | - async def test_an_unreadable_directory_leaves_the_tick_empty_not_failed(self): | |
| 455 | - class Broken: | |
| 456 | - async def active_schools(self): | |
| 457 | - raise TenantError('relation "school" does not exist') | |
| 458 | - | |
| 459 | - async def store_for(self, slug): | |
| 460 | - raise AssertionError("okul listesi yokken depo cozulmemeli") | |
| 461 | - | |
| 462 | - async def close(self): | |
| 463 | - return None | |
| 464 | - | |
| 465 | - def describe(self): | |
| 466 | - return "test dizini" | |
| 467 | - | |
| 468 | - scheduler = Scheduler( | |
| 469 | - lambda school: FakeSource({}), Broken(), clock_fn=lambda: NOW | |
| 470 | - ) | |
| 471 | - self.assertEqual(await scheduler.run_once(NOW), []) | |
| 472 | - self.assertEqual(scheduler._failures, []) | |
| 473 | - | |
| 474 | - async def test_a_school_whose_store_cannot_open_fails_alone(self): | |
| 475 | - store = self._store() | |
| 476 | - data = {"b-okul": dataset(2)} | |
| 477 | - | |
| 478 | - class Directory: | |
| 479 | - async def active_schools(self): | |
| 480 | - return ["a-okul", "b-okul"] | |
| 481 | - | |
| 482 | - async def store_for(self, slug): | |
| 483 | - if slug == "a-okul": | |
| 484 | - raise SchoolDatabaseGone("veritabani yok", school=slug) | |
| 485 | - return store | |
| 486 | - | |
| 487 | - async def close(self): | |
| 488 | - return None | |
| 489 | - | |
| 490 | - def describe(self): | |
| 491 | - return "test dizini" | |
| 492 | - | |
| 493 | - scheduler = Scheduler( | |
| 494 | - lambda school: FakeSource(data[school]), | |
| 495 | - Directory(), | |
| 496 | - term_start_ms=TERM_START, | |
| 497 | - clock_fn=lambda: NOW, | |
| 498 | - ) | |
| 499 | - results = await scheduler.run_once(NOW) | |
| 500 | - self.assertEqual([r.school for r in results], ["b-okul"]) | |
| 501 | - self.assertEqual(scheduler._failures, ["a-okul"]) | |
| 485 | + for school in self.schools: | |
| 486 | + self.assertEqual(len(self.summaries_of(school)), self.sizes[school]) | |
| 487 | + self.assertEqual(len(run_rows(self.caller, school)), 2) | |
| 502 | 488 | |
| 503 | 489 | |
| 504 | 490 | if __name__ == "__main__": |
service/tests/test_segments.pymodified+93 -77
| @@ -38,13 +38,16 @@ from src.segment.rubric import ( | ||
| 38 | 38 | ) |
| 39 | 39 | from src.segment.schema import CallUsage, DimensionResult, ItemSegmentation |
| 40 | 40 | from src.store import ( |
| 41 | + CAP_PROFILE, | |
| 42 | + CAP_PURGE, | |
| 43 | + CAP_SEGMENT, | |
| 44 | + CAP_SWEEP, | |
| 45 | + PURGE_TABLES, | |
| 41 | 46 | RETENTION_DAYS, |
| 42 | - CollectingClient, | |
| 43 | - Store, | |
| 44 | - load_schema_text, | |
| 45 | - question_segment_row, | |
| 46 | - split_statements, | |
| 47 | - student_segment_profile_row, | |
| 47 | + BridgeStore, | |
| 48 | + RecordingCaller, | |
| 49 | + segment_rows, | |
| 50 | + profile_rows, | |
| 48 | 51 | ) |
| 49 | 52 | |
| 50 | 53 | NOW = 1_699_963_200_000 |
| @@ -385,52 +388,63 @@ def question_segment(**over) -> QuestionSegment: | ||
| 385 | 388 | |
| 386 | 389 | |
| 387 | 390 | class TestSemaMetni(unittest.TestCase): |
| 388 | - def test_iki_yeni_tablo_semada_tanimli(self) -> None: | |
| 389 | - text = load_schema_text() | |
| 390 | - for table in ("question_segment", "student_segment_profile"): | |
| 391 | - self.assertIn(f"DEFINE TABLE IF NOT EXISTS {table} SCHEMAFULL;", text) | |
| 392 | - | |
| 393 | - def test_her_satir_alani_semada_var(self) -> None: | |
| 394 | - """Satir uretecinin yazdigi her alan semada TANIMLI mi?""" | |
| 395 | - statements = split_statements(load_schema_text()) | |
| 396 | - for table, row in ( | |
| 397 | - ("question_segment", question_segment_row(question_segment())), | |
| 398 | - ( | |
| 399 | - "student_segment_profile", | |
| 400 | - student_segment_profile_row(profile("analiz")), | |
| 401 | - ), | |
| 402 | - ): | |
| 403 | - declared = { | |
| 404 | - s.split("IF NOT EXISTS", 1)[1].split("ON", 1)[0].strip() | |
| 405 | - for s in statements | |
| 406 | - if s.startswith("DEFINE FIELD") and f" ON {table} " in s | |
| 407 | - } | |
| 408 | - self.assertTrue(declared, table) | |
| 409 | - self.assertEqual(set(row) - declared, set(), table) | |
| 410 | - | |
| 411 | - def test_dizi_alanlarinda_yildiz_once_tanimlanir(self) -> None: | |
| 412 | - """`.*` diziden SONRA gelirse ic anahtarlar sessizce duserdi.""" | |
| 413 | - text = load_schema_text() | |
| 414 | - for name in ("experimental_dimensions", "downstream_dimensions"): | |
| 415 | - star = text.index(f"{name}.*") | |
| 416 | - plain = text.index(f"{name}", star + len(name) + 2) | |
| 417 | - self.assertLess(star, plain, name) | |
| 391 | + """Şemanın sahibi artık backend'dir; satır üreteci sözleşmeyi taşır. | |
| 392 | + | |
| 393 | + Eski testler `schema/zeka.surql` metnini okuyordu; o dosya silindi | |
| 394 | + (DDL `hezarfen_backend`'in göçlerinde yaşar). Burada pinlenen şey satır | |
| 395 | + üretecinin alan adlarıdır: backend'in `zeka_*` kolonlarıyla aynı olmak | |
| 396 | + zorundadır. | |
| 397 | + """ | |
| 398 | + | |
| 399 | + def test_satir_alanlari_beklenen_kume(self) -> None: | |
| 400 | + segment = segment_rows([question_segment()])[0] | |
| 401 | + self.assertEqual(set(segment) - {"retain_until"}, { | |
| 402 | + "question", | |
| 403 | + "exam", | |
| 404 | + "course", | |
| 405 | + "subject", | |
| 406 | + "labels", | |
| 407 | + "confidences", | |
| 408 | + "confidence", | |
| 409 | + "trap_choice", | |
| 410 | + "rationale", | |
| 411 | + "model", | |
| 412 | + "prompt_version", | |
| 413 | + "variant", | |
| 414 | + "computed_at", | |
| 415 | + "downstream_dimensions", | |
| 416 | + "experimental_dimensions", | |
| 417 | + }) | |
| 418 | + profile_row = profile_rows([profile("analiz")])[0] | |
| 419 | + self.assertEqual(set(profile_row) - {"retain_until"}, { | |
| 420 | + "student", | |
| 421 | + "dimension", | |
| 422 | + "label", | |
| 423 | + "n_answers", | |
| 424 | + "n_correct", | |
| 425 | + "accuracy", | |
| 426 | + "overall_n_answers", | |
| 427 | + "overall_accuracy", | |
| 428 | + "contrast", | |
| 429 | + "confidence", | |
| 430 | + "computed_at", | |
| 431 | + }) | |
| 418 | 432 | |
| 419 | 433 | |
| 420 | 434 | class TestSatirBicimi(unittest.TestCase): |
| 421 | 435 | def test_question_segment_saklama_suresi(self) -> None: |
| 422 | - row = question_segment_row(question_segment()) | |
| 436 | + row = segment_rows([question_segment()])[0] | |
| 423 | 437 | self.assertEqual( |
| 424 | 438 | row["retain_until"], NOW + RETENTION_DAYS["question_segment"] * DAY |
| 425 | 439 | ) |
| 426 | 440 | |
| 427 | - def test_boyutlar_alan_adina_donusur(self) -> None: | |
| 428 | - row = question_segment_row(question_segment()) | |
| 429 | - self.assertEqual(row["bilissel_talep"], "analiz") | |
| 430 | - self.assertEqual(row["confidence_okuma_yuku"], 0.95) | |
| 441 | + def test_boyutlar_ve_guvenleri_ic_ice_tasir(self) -> None: | |
| 442 | + row = segment_rows([question_segment()])[0] | |
| 443 | + self.assertEqual(row["labels"]["bilissel_talep"], "analiz") | |
| 444 | + self.assertEqual(row["confidences"]["okuma_yuku"], 0.95) | |
| 431 | 445 | |
| 432 | 446 | def test_deneysel_boyut_satirda_isaretli(self) -> None: |
| 433 | - row = question_segment_row(question_segment()) | |
| 447 | + row = segment_rows([question_segment()])[0] | |
| 434 | 448 | self.assertEqual(row["experimental_dimensions"], ["adim_sayisi"]) |
| 435 | 449 | self.assertNotIn("adim_sayisi", row["downstream_dimensions"]) |
| 436 | 450 | |
| @@ -444,9 +458,7 @@ class TestSatirBicimi(unittest.TestCase): | ||
| 444 | 458 | question_segment(confidences={"bilissel_talep": 0.9}) |
| 445 | 459 | |
| 446 | 460 | def test_profil_satiri_kontrast_tasir(self) -> None: |
| 447 | - row = student_segment_profile_row( | |
| 448 | - profile("analiz", accuracy=0.4, overall=0.6) | |
| 449 | - ) | |
| 461 | + row = profile_rows([profile("analiz", accuracy=0.4, overall=0.6)])[0] | |
| 450 | 462 | self.assertAlmostEqual(row["contrast"], -0.2, places=4) |
| 451 | 463 | self.assertAlmostEqual(row["overall_accuracy"], 0.6, places=4) |
| 452 | 464 | self.assertEqual( |
| @@ -456,39 +468,43 @@ class TestSatirBicimi(unittest.TestCase): | ||
| 456 | 468 | |
| 457 | 469 | |
| 458 | 470 | class TestYazim(unittest.IsolatedAsyncioTestCase): |
| 459 | - async def test_merge_kullanilir(self) -> None: | |
| 460 | - """CONTENT, insan/baska kaynak alanlarini silerdi.""" | |
| 461 | - client = CollectingClient() | |
| 462 | - store = Store(client) | |
| 471 | + async def test_yazim_yetenek_cagrisiyla_gider(self) -> None: | |
| 472 | + """Satirlar `insight.segment.upsert` / `insight.profile.upsert` ile.""" | |
| 473 | + caller = RecordingCaller() | |
| 474 | + store = BridgeStore(caller).store_for("okul-a") | |
| 463 | 475 | await store.write_question_segments([question_segment()]) |
| 464 | 476 | await store.write_segment_profiles([profile("analiz")]) |
| 465 | - for sql, _ in client.statements: | |
| 466 | - self.assertIn("MERGE", sql) | |
| 467 | - self.assertIn("type::record(", sql) | |
| 477 | + self.assertEqual( | |
| 478 | + [capability for capability, _, _ in caller.calls], | |
| 479 | + [CAP_SEGMENT, CAP_PROFILE], | |
| 480 | + ) | |
| 481 | + self.assertTrue(all(school == "okul-a" for _, school, _ in caller.calls)) | |
| 468 | 482 | |
| 469 | 483 | async def test_supurme_iki_yeni_tabloyu_da_gezer(self) -> None: |
| 470 | - client = CollectingClient() | |
| 471 | - results = await Store(client).sweep(NOW) | |
| 472 | - self.assertIn("question_segment", results) | |
| 473 | - self.assertIn("student_segment_profile", results) | |
| 474 | - tables = [sql.split()[1] for sql, _ in client.statements] | |
| 475 | - self.assertIn("question_segment", tables) | |
| 476 | - self.assertIn("student_segment_profile", tables) | |
| 477 | - | |
| 478 | - async def test_mezuniyet_temizligi_profili_siler_soruyu_silmez(self) -> None: | |
| 479 | - client = CollectingClient() | |
| 480 | - await Store(client).purge_departed("okul-a", ["kalan"]) | |
| 481 | - sql = client.statements[0][0] | |
| 482 | - self.assertIn("DELETE student_segment_profile", sql) | |
| 483 | - # Soru satiri kisisel veri DEGIL: mezuniyetle silinmez. | |
| 484 | - self.assertNotIn("DELETE question_segment", sql) | |
| 485 | - | |
| 486 | - async def test_bos_liste_ifade_uretmez(self) -> None: | |
| 487 | - client = CollectingClient() | |
| 488 | - store = Store(client) | |
| 484 | + caller = RecordingCaller() | |
| 485 | + results = await BridgeStore(caller).store_for("okul-a").sweep(NOW) | |
| 486 | + self.assertEqual( | |
| 487 | + [capability for capability, _, _ in caller.calls], [CAP_SWEEP] | |
| 488 | + ) | |
| 489 | + self.assertIn("zeka_question_segment", results) | |
| 490 | + self.assertIn("zeka_student_segment_profile", results) | |
| 491 | + | |
| 492 | + async def test_mezuniyet_temizligi_yalniz_kisisel_tablolari_siler(self) -> None: | |
| 493 | + """Soru satiri kisisel veri DEGIL: mezuniyet temizliginde YOKTUR.""" | |
| 494 | + caller = RecordingCaller() | |
| 495 | + await BridgeStore(caller).store_for("okul-a").purge_departed( | |
| 496 | + "okul-a", ["kalan"] | |
| 497 | + ) | |
| 498 | + self.assertEqual([capability for capability, _, _ in caller.calls], [CAP_PURGE]) | |
| 499 | + self.assertNotIn("zeka_question_segment", PURGE_TABLES) | |
| 500 | + self.assertIn("zeka_student_segment_profile", PURGE_TABLES) | |
| 501 | + | |
| 502 | + async def test_bos_liste_cagri_uretmez(self) -> None: | |
| 503 | + caller = RecordingCaller() | |
| 504 | + store = BridgeStore(caller).store_for("okul-a") | |
| 489 | 505 | report = await store.write_question_segments([]) |
| 490 | 506 | self.assertEqual(report.written, 0) |
| 491 | - self.assertEqual(client.statements, []) | |
| 507 | + self.assertEqual(caller.calls, []) | |
| 492 | 508 | |
| 493 | 509 | |
| 494 | 510 | # =========================================================================== |
| @@ -650,11 +666,11 @@ class TestKopru(unittest.TestCase): | ||
| 650 | 666 | sapan = s == 0 and tuzakli |
| 651 | 667 | answers.append((qid, f"user:{s}", "tuzak" if sapan else "dogru")) |
| 652 | 668 | |
| 653 | - client = CollectingClient() | |
| 669 | + caller = RecordingCaller() | |
| 670 | + store = BridgeStore(caller).store_for("okul-a") | |
| 654 | 671 | report = asyncio.run( |
| 655 | 672 | persist_mod.persist( |
| 656 | - b, items, answers, school="okul-a", now_ms=NOW, | |
| 657 | - store=Store(client), | |
| 673 | + b, items, answers, school="okul-a", now_ms=NOW, store=store, | |
| 658 | 674 | ) |
| 659 | 675 | ) |
| 660 | 676 | self.assertEqual(report.recommendation_rows, 1) |
| @@ -662,12 +678,12 @@ class TestKopru(unittest.TestCase): | ||
| 662 | 678 | self.assertEqual(report.recommendation_rejected, 0) |
| 663 | 679 | |
| 664 | 680 | def test_persist_gercek_depoya_yazar(self) -> None: |
| 665 | - client = CollectingClient() | |
| 681 | + caller = RecordingCaller() | |
| 666 | 682 | answers = [("q1", "user:1", "c-dogru"), ("q2", "user:1", "c-dogru2")] |
| 667 | 683 | report = asyncio.run( |
| 668 | 684 | persist_mod.persist( |
| 669 | 685 | batch(), ITEMS, answers, school="okul-a", now_ms=NOW, |
| 670 | - store=Store(client), | |
| 686 | + store=BridgeStore(caller).store_for("okul-a"), | |
| 671 | 687 | ) |
| 672 | 688 | ) |
| 673 | 689 | self.assertFalse(report.dry_run) |
service/tests/test_store.pydeleted+0 -859
| @@ -1,859 +0,0 @@ | ||
| 1 | -"""Depolama katmani testleri. | |
| 2 | - | |
| 3 | -Iki kume: | |
| 4 | - | |
| 5 | -* **Birim** -- veritabani gerektirmez: ifade ayirici, satir bicimi, saklama | |
| 6 | - suresi hesabi, kanitsiz tavsiyenin reddi. | |
| 7 | -* **Entegrasyon** -- GERCEK SurrealDB'ye karsi kosar: sema yukleme, alan | |
| 8 | - tiplerinin dogrulanmasi, toplu yazim, okuma dogrulamasi, supurme, kiraci | |
| 9 | - izolasyonu, mezuniyet temizligi. Konteyner yoksa `skipUnless` ile atlanir | |
| 10 | - (bkz. `tests/zeka_db.py`). | |
| 11 | -""" | |
| 12 | - | |
| 13 | -from __future__ import annotations | |
| 14 | - | |
| 15 | -import asyncio | |
| 16 | -import unittest | |
| 17 | - | |
| 18 | -from src.compute.model import ( | |
| 19 | - Audience, | |
| 20 | - Confidence, | |
| 21 | - QuestionSegment, | |
| 22 | - Recommendation, | |
| 23 | - StudentSegmentProfile, | |
| 24 | - StudentSummary, | |
| 25 | -) | |
| 26 | -from src.store import ( | |
| 27 | - BATCH_SIZE, | |
| 28 | - RETENTION_DAYS, | |
| 29 | - CollectingClient, | |
| 30 | - Store, | |
| 31 | - SurrealError, | |
| 32 | - apply_schema, | |
| 33 | - load_schema_text, | |
| 34 | - recommendation_row, | |
| 35 | - schema_field_types, | |
| 36 | - schema_tables, | |
| 37 | - split_statements, | |
| 38 | - summary_row, | |
| 39 | -) | |
| 40 | - | |
| 41 | -from .zeka_db import NOW, count_rows, fresh_client, fresh_schema_client, requires_db, select | |
| 42 | - | |
| 43 | -DAY = 86_400_000 | |
| 44 | - | |
| 45 | - | |
| 46 | -def make_summary(school: str, student: str, *, now_ms: int = NOW) -> StudentSummary: | |
| 47 | - return StudentSummary( | |
| 48 | - school=school, | |
| 49 | - student=student, | |
| 50 | - computed_at=now_ms, | |
| 51 | - marks={"courses": {"course-1": {"placement": {"band": "on_track"}}}}, | |
| 52 | - attendance={"courses": {}}, | |
| 53 | - submission={"window_days": 30}, | |
| 54 | - study={"sessions": 6}, | |
| 55 | - attention=[ | |
| 56 | - { | |
| 57 | - "trigger": "homework", | |
| 58 | - "fact": "son 30 gunde 4 odev teslim edilmedi", | |
| 59 | - "evidence": {"missed": 4, "window_days": 30}, | |
| 60 | - "window_from": now_ms - 30 * DAY, | |
| 61 | - "window_to": now_ms, | |
| 62 | - } | |
| 63 | - ], | |
| 64 | - confidence=Confidence.EXPLORATORY, | |
| 65 | - ) | |
| 66 | - | |
| 67 | - | |
| 68 | -def make_recommendation( | |
| 69 | - school: str, about: str, *, rule_id: str = "O1-a", now_ms: int = NOW | |
| 70 | -) -> Recommendation: | |
| 71 | - return Recommendation( | |
| 72 | - school=school, | |
| 73 | - audience=about, | |
| 74 | - audience_role=Audience.STUDENT, | |
| 75 | - product="O1", | |
| 76 | - rule_id=rule_id, | |
| 77 | - evidence={"missed": 4, "window_days": 30}, | |
| 78 | - computed_at=now_ms, | |
| 79 | - expires_at=now_ms + 30 * DAY, | |
| 80 | - about=about, | |
| 81 | - course="course-1", | |
| 82 | - confidence=Confidence.EXPLORATORY, | |
| 83 | - limitation="Sinav verisi dahil degildir.", | |
| 84 | - ) | |
| 85 | - | |
| 86 | - | |
| 87 | -def make_question_segment( | |
| 88 | - school: str, question: str, *, now_ms: int = NOW, trap: str | None = "choice-2" | |
| 89 | -) -> QuestionSegment: | |
| 90 | - return QuestionSegment( | |
| 91 | - school=school, | |
| 92 | - question=question, | |
| 93 | - exam="exam:E1", | |
| 94 | - subject="subject:S1", | |
| 95 | - labels={ | |
| 96 | - "bilissel_talep": "analiz", | |
| 97 | - "adim_sayisi": "cok_adim", | |
| 98 | - "dikkat_tuzagi": "var" if trap else "yok", | |
| 99 | - "okuma_yuku": "yuksek", | |
| 100 | - }, | |
| 101 | - confidences={ | |
| 102 | - "bilissel_talep": 0.91, | |
| 103 | - "adim_sayisi": 0.55, | |
| 104 | - "dikkat_tuzagi": 0.87, | |
| 105 | - "okuma_yuku": 0.96, | |
| 106 | - }, | |
| 107 | - rationale="Uzun kok, iki adimli cikarim.", | |
| 108 | - model="deepseek-flash", | |
| 109 | - prompt_version="v1", | |
| 110 | - variant="baseline", | |
| 111 | - trap_choice=trap, | |
| 112 | - downstream_dimensions=("bilissel_talep", "dikkat_tuzagi", "okuma_yuku"), | |
| 113 | - experimental_dimensions=("adim_sayisi",), | |
| 114 | - computed_at=now_ms, | |
| 115 | - confidence=Confidence.STABLE, | |
| 116 | - ) | |
| 117 | - | |
| 118 | - | |
| 119 | -def make_segment_profile( | |
| 120 | - school: str, | |
| 121 | - student: str, | |
| 122 | - *, | |
| 123 | - now_ms: int = NOW, | |
| 124 | - dimension: str = "bilissel_talep", | |
| 125 | - label: str = "analiz", | |
| 126 | -) -> StudentSegmentProfile: | |
| 127 | - return StudentSegmentProfile( | |
| 128 | - school=school, | |
| 129 | - student=student, | |
| 130 | - dimension=dimension, | |
| 131 | - label=label, | |
| 132 | - n_answers=180, | |
| 133 | - n_correct=63, | |
| 134 | - overall_n_answers=900, | |
| 135 | - overall_accuracy=0.58, | |
| 136 | - computed_at=now_ms, | |
| 137 | - confidence=Confidence.STABLE, | |
| 138 | - ) | |
| 139 | - | |
| 140 | - | |
| 141 | -# =========================================================================== | |
| 142 | -# BIRIM | |
| 143 | -# =========================================================================== | |
| 144 | - | |
| 145 | - | |
| 146 | -class TestSplitStatements(unittest.TestCase): | |
| 147 | - """`surreal sql`'in satir satir ayristirma tuzagina dusmeyen ayirici.""" | |
| 148 | - | |
| 149 | - def test_schema_file_splits_into_statements(self) -> None: | |
| 150 | - statements = split_statements(load_schema_text()) | |
| 151 | - self.assertGreater(len(statements), 40) | |
| 152 | - self.assertTrue(all(s.endswith(";") for s in statements)) | |
| 153 | - self.assertTrue(all(not s.startswith("--") for s in statements)) | |
| 154 | - | |
| 155 | - def test_multiline_statement_stays_whole(self) -> None: | |
| 156 | - text = "DEFINE FIELD a\n ON t\n TYPE int;\nDEFINE FIELD b ON t TYPE int;" | |
| 157 | - self.assertEqual(len(split_statements(text)), 2) | |
| 158 | - | |
| 159 | - def test_semicolon_inside_string_is_not_a_boundary(self) -> None: | |
| 160 | - text = "UPSERT t CONTENT { note: 'a;b;c' };" | |
| 161 | - self.assertEqual(split_statements(text), ["UPSERT t CONTENT { note: 'a;b;c' };"]) | |
| 162 | - | |
| 163 | - def test_comments_are_dropped(self) -> None: | |
| 164 | - text = "-- yorum; yine yorum\nDEFINE TABLE t SCHEMAFULL;" | |
| 165 | - self.assertEqual(split_statements(text), ["DEFINE TABLE t SCHEMAFULL;"]) | |
| 166 | - | |
| 167 | - def test_generated_upsert_uses_type_record(self) -> None: | |
| 168 | - """`type::thing()` SurrealDB 3'te YOK; uretilen SQL `type::record()` olmali.""" | |
| 169 | - client = CollectingClient() | |
| 170 | - asyncio.run(Store(client).write_summaries([make_summary("okul-a", "s1")])) | |
| 171 | - sql = client.statements[0][0] | |
| 172 | - self.assertIn("type::record(", sql) | |
| 173 | - self.assertNotIn("type::thing(", sql) | |
| 174 | - | |
| 175 | - | |
| 176 | -class TestRecordLikeStrings(unittest.TestCase): | |
| 177 | - """`"user:01K..."` biciminde bir metin uca `record` olarak gidiyordu. | |
| 178 | - | |
| 179 | - Sonuc: `TYPE string` alan reddediliyor ve 500 satirlik grubun TAMAMI | |
| 180 | - dusuyordu. Fikstur kimlikleri (`student-00`) iki nokta tasimadigi icin | |
| 181 | - testlerde hic gorunmeyen bir tuzakti. | |
| 182 | - """ | |
| 183 | - | |
| 184 | - def test_kimlik_bicimli_metin_type_string_ile_sarilir(self) -> None: | |
| 185 | - client = CollectingClient() | |
| 186 | - asyncio.run( | |
| 187 | - Store(client).write_summaries([make_summary("okul-a", "user:01K6MDX")]) | |
| 188 | - ) | |
| 189 | - sql = client.statements[0][0] | |
| 190 | - self.assertIn("student: type::string($v0.student)", sql) | |
| 191 | - # Iki nokta tasimayan alan sarilmaz -- gereksiz gurultu olmasin. | |
| 192 | - self.assertIn("school: $v0.school", sql) | |
| 193 | - | |
| 194 | - def test_kimlik_dizisi_array_map_ile_sarilir(self) -> None: | |
| 195 | - client = CollectingClient() | |
| 196 | - row = { | |
| 197 | - "school": "okul-a", | |
| 198 | - "started_at": NOW, | |
| 199 | - "status": "ok", | |
| 200 | - "students_total": 1, | |
| 201 | - "students_ok": 1, | |
| 202 | - "students_failed": 0, | |
| 203 | - "students_skipped": 0, | |
| 204 | - "rows_written": 0, | |
| 205 | - "pending_students": ["user:01K6MDX", "user:01K6MDY"], | |
| 206 | - "failed_modules": [], | |
| 207 | - "budget_exceeded": False, | |
| 208 | - "budget_ms": 1000, | |
| 209 | - } | |
| 210 | - asyncio.run(Store(client).write_run(row, "okul-a_2023-11-14")) | |
| 211 | - sql = client.statements[0][0] | |
| 212 | - self.assertIn( | |
| 213 | - "pending_students: array::map($v0.pending_students, " | |
| 214 | - "|$x| type::string($x))", | |
| 215 | - sql, | |
| 216 | - ) | |
| 217 | - self.assertIn("failed_modules: $v0.failed_modules", sql) | |
| 218 | - | |
| 219 | - def test_deger_asla_sql_metnine_gomulmez(self) -> None: | |
| 220 | - """Kacis hatasi yuzeyi acilmadi: metne yalnizca ALAN ADI giriyor.""" | |
| 221 | - client = CollectingClient() | |
| 222 | - asyncio.run( | |
| 223 | - Store(client).write_summaries([make_summary("o'kul", "user:01K")]) | |
| 224 | - ) | |
| 225 | - sql, variables = client.statements[0] | |
| 226 | - self.assertNotIn("o'kul", sql) | |
| 227 | - self.assertEqual(variables["v0"]["school"], "o'kul") | |
| 228 | - | |
| 229 | - | |
| 230 | -class TestRowShapes(unittest.TestCase): | |
| 231 | - def test_summary_row_matches_schema_fields(self) -> None: | |
| 232 | - row = summary_row(make_summary("okul-a", "s1")) | |
| 233 | - self.assertEqual( | |
| 234 | - set(row), | |
| 235 | - { | |
| 236 | - "school", | |
| 237 | - "student", | |
| 238 | - "marks", | |
| 239 | - "attendance", | |
| 240 | - "submission", | |
| 241 | - "study", | |
| 242 | - "attention", | |
| 243 | - "confidence", | |
| 244 | - "computed_at", | |
| 245 | - "retain_until", | |
| 246 | - }, | |
| 247 | - ) | |
| 248 | - self.assertEqual(row["retain_until"], NOW + RETENTION_DAYS["student_summary"] * DAY) | |
| 249 | - | |
| 250 | - def test_recommendation_retention_is_the_earlier_of_two(self) -> None: | |
| 251 | - rec = make_recommendation("okul-a", "s1") | |
| 252 | - row = recommendation_row(rec) | |
| 253 | - # 30 gunluk `expires_at`, 90 gunluk tavandan once gelir. | |
| 254 | - self.assertEqual(row["retain_until"], rec.expires_at) | |
| 255 | - | |
| 256 | - def test_attention_items_have_no_score(self) -> None: | |
| 257 | - row = summary_row(make_summary("okul-a", "s1")) | |
| 258 | - for item in row["attention"]: | |
| 259 | - self.assertNotIn("score", item) | |
| 260 | - self.assertNotIn("rank", item) | |
| 261 | - | |
| 262 | - | |
| 263 | -class TestEvidenceGate(unittest.IsolatedAsyncioTestCase): | |
| 264 | - async def test_evidence_free_recommendation_is_rejected(self) -> None: | |
| 265 | - rec = make_recommendation("okul-a", "s1") | |
| 266 | - # `Recommendation` bos kanitla kurulamaz; sozlukten yeniden kurulmus | |
| 267 | - # satiri taklit etmek icin alani sonradan bosaltiyoruz. | |
| 268 | - object.__setattr__(rec, "evidence", {}) | |
| 269 | - store = Store(CollectingClient()) | |
| 270 | - report = await store.write_recommendations([rec]) | |
| 271 | - self.assertEqual(report.rejected, 1) | |
| 272 | - self.assertEqual(report.written, 0) | |
| 273 | - | |
| 274 | - async def test_second_failure_skips_the_batch_but_keeps_going(self) -> None: | |
| 275 | - client = CollectingClient() | |
| 276 | - client.fail_times = 2 # MAX_ATTEMPTS kadar | |
| 277 | - store = Store(client) | |
| 278 | - report = await store.write_summaries([make_summary("okul-a", "s1")]) | |
| 279 | - self.assertEqual(report.written, 0) | |
| 280 | - self.assertEqual(report.skipped_batches, 1) | |
| 281 | - | |
| 282 | - | |
| 283 | -# =========================================================================== | |
| 284 | -# ENTEGRASYON -- gercek SurrealDB | |
| 285 | -# =========================================================================== | |
| 286 | - | |
| 287 | - | |
| 288 | -@requires_db | |
| 289 | -class TestSchemaApply(unittest.TestCase): | |
| 290 | - def test_every_statement_applies_cleanly(self) -> None: | |
| 291 | - client = fresh_client("sema") | |
| 292 | - report = apply_schema(client) | |
| 293 | - self.assertEqual(report.errors, []) | |
| 294 | - self.assertEqual(report.total, report.applied) | |
| 295 | - self.assertGreater(report.total, 40) | |
| 296 | - | |
| 297 | - def test_applying_twice_is_idempotent(self) -> None: | |
| 298 | - client = fresh_client("sema2") | |
| 299 | - first = apply_schema(client) | |
| 300 | - second = apply_schema(client) | |
| 301 | - self.assertTrue(first.ok) | |
| 302 | - self.assertTrue(second.ok) | |
| 303 | - | |
| 304 | - def test_five_tables_and_nothing_else(self) -> None: | |
| 305 | - client = fresh_schema_client("sema3") | |
| 306 | - self.assertEqual( | |
| 307 | - sorted(schema_tables(client)), | |
| 308 | - [ | |
| 309 | - "insight_run", | |
| 310 | - "question_segment", | |
| 311 | - "recommendation", | |
| 312 | - "student_segment_profile", | |
| 313 | - "student_summary", | |
| 314 | - ], | |
| 315 | - ) | |
| 316 | - | |
| 317 | - def test_declared_field_types_are_what_the_schema_says(self) -> None: | |
| 318 | - """Her alanin tipi TEK TEK dogrulanir -- `INFO FOR TABLE` ciktisindan.""" | |
| 319 | - client = fresh_schema_client("tip") | |
| 320 | - expected = { | |
| 321 | - "student_summary": { | |
| 322 | - "school": "string", | |
| 323 | - "student": "string", | |
| 324 | - "marks": "none | object", | |
| 325 | - "attendance": "none | object", | |
| 326 | - "submission": "none | object", | |
| 327 | - "study": "none | object", | |
| 328 | - "attention": "none | array<object>", | |
| 329 | - "attention.*": "object", | |
| 330 | - "confidence": "string", | |
| 331 | - "computed_at": "int", | |
| 332 | - "retain_until": "int", | |
| 333 | - }, | |
| 334 | - "recommendation": { | |
| 335 | - "school": "string", | |
| 336 | - "audience": "string", | |
| 337 | - "about": "none | string", | |
| 338 | - "audience_role": "string", | |
| 339 | - "product": "string", | |
| 340 | - "course": "none | string", | |
| 341 | - "rule_id": "string", | |
| 342 | - "rule_version": "int", | |
| 343 | - "evidence": "object", | |
| 344 | - "confidence": "string", | |
| 345 | - "created_at": "int", | |
| 346 | - "expires_at": "int", | |
| 347 | - "retain_until": "int", | |
| 348 | - "dismissed_at": "none | int", | |
| 349 | - "dismissed_by": "none | string", | |
| 350 | - "dismiss_reason": "none | string", | |
| 351 | - }, | |
| 352 | - "insight_run": { | |
| 353 | - "school": "string", | |
| 354 | - "started_at": "int", | |
| 355 | - "finished_at": "none | int", | |
| 356 | - "status": "string", | |
| 357 | - "duration_ms": "none | int", | |
| 358 | - "students_total": "int", | |
| 359 | - "students_ok": "int", | |
| 360 | - "students_failed": "int", | |
| 361 | - "students_skipped": "int", | |
| 362 | - "rows_written": "int", | |
| 363 | - "pending_students": "none | array<string>", | |
| 364 | - "pending_students.*": "string", | |
| 365 | - "failed_modules": "none | array<string>", | |
| 366 | - "failed_modules.*": "string", | |
| 367 | - "budget_exceeded": "bool", | |
| 368 | - "budget_ms": "int", | |
| 369 | - "retain_until": "int", | |
| 370 | - }, | |
| 371 | - "question_segment": { | |
| 372 | - "school": "string", | |
| 373 | - "question": "string", | |
| 374 | - "exam": "none | string", | |
| 375 | - "course": "none | string", | |
| 376 | - "subject": "none | string", | |
| 377 | - "bilissel_talep": "string", | |
| 378 | - "dikkat_tuzagi": "string", | |
| 379 | - "okuma_yuku": "string", | |
| 380 | - "adim_sayisi": "string", | |
| 381 | - "confidence_bilissel_talep": "float", | |
| 382 | - "confidence_dikkat_tuzagi": "float", | |
| 383 | - "confidence_okuma_yuku": "float", | |
| 384 | - "confidence_adim_sayisi": "float", | |
| 385 | - "confidence": "string", | |
| 386 | - "experimental_dimensions": "none | array<string>", | |
| 387 | - "experimental_dimensions.*": "string", | |
| 388 | - "downstream_dimensions": "none | array<string>", | |
| 389 | - "downstream_dimensions.*": "string", | |
| 390 | - "trap_choice": "none | string", | |
| 391 | - "rationale": "string", | |
| 392 | - "model": "string", | |
| 393 | - "prompt_version": "string", | |
| 394 | - "variant": "none | string", | |
| 395 | - "computed_at": "int", | |
| 396 | - "retain_until": "int", | |
| 397 | - }, | |
| 398 | - "student_segment_profile": { | |
| 399 | - "school": "string", | |
| 400 | - "student": "string", | |
| 401 | - "dimension": "string", | |
| 402 | - "label": "string", | |
| 403 | - "n_answers": "int", | |
| 404 | - "n_correct": "int", | |
| 405 | - "accuracy": "float", | |
| 406 | - "overall_n_answers": "int", | |
| 407 | - "overall_accuracy": "float", | |
| 408 | - "contrast": "float", | |
| 409 | - "confidence": "string", | |
| 410 | - "computed_at": "int", | |
| 411 | - "retain_until": "int", | |
| 412 | - }, | |
| 413 | - } | |
| 414 | - for table, fields in expected.items(): | |
| 415 | - actual = schema_field_types(client, table) | |
| 416 | - self.assertEqual( | |
| 417 | - set(actual), set(fields), f"{table}: alan kumesi sapti" | |
| 418 | - ) | |
| 419 | - for name, type_text in fields.items(): | |
| 420 | - self.assertIn( | |
| 421 | - f"TYPE {type_text}", actual[name], f"{table}.{name} tipi sapti" | |
| 422 | - ) | |
| 423 | - | |
| 424 | - def test_flexible_objects_really_are_flexible(self) -> None: | |
| 425 | - """FLEXIBLE olmayan `object` alani ic anahtarlari SESSIZCE duserdi.""" | |
| 426 | - client = fresh_schema_client("esnek") | |
| 427 | - for table, field in ( | |
| 428 | - ("student_summary", "marks"), | |
| 429 | - ("student_summary", "attention.*"), | |
| 430 | - ("recommendation", "evidence"), | |
| 431 | - ): | |
| 432 | - self.assertIn("FLEXIBLE", schema_field_types(client, table)[field]) | |
| 433 | - | |
| 434 | - def test_schemafull_rejects_an_undeclared_field(self) -> None: | |
| 435 | - """Semada olmayan alan SESSIZCE dusmuyor, satir tumden reddediliyor.""" | |
| 436 | - client = fresh_schema_client("kapali") | |
| 437 | - with self.assertRaises(SurrealError) as caught: | |
| 438 | - client.query_sync( | |
| 439 | - "UPSERT type::record('student_summary', 'x') CONTENT $v;", | |
| 440 | - { | |
| 441 | - "v": { | |
| 442 | - **summary_row(make_summary("okul-a", "s1")), | |
| 443 | - # Tek bir "risk skoru" alani semada KASITLI OLARAK yok. | |
| 444 | - "risk_score": 0.9, | |
| 445 | - } | |
| 446 | - }, | |
| 447 | - ) | |
| 448 | - self.assertIn("risk_score", str(caught.exception)) | |
| 449 | - self.assertEqual(count_rows(client, "student_summary"), 0) | |
| 450 | - | |
| 451 | - def test_none_valued_optional_field_is_omitted_not_nulled(self) -> None: | |
| 452 | - """`option<string>` NULL kabul etmez; alan hic gonderilmemeli.""" | |
| 453 | - client = fresh_schema_client("bosalan") | |
| 454 | - row = recommendation_row(make_recommendation("okul-a", "s1")) | |
| 455 | - self.assertIsNone(row["dismissed_at"]) | |
| 456 | - asyncio.run(Store(client).write_recommendations([make_recommendation("okul-a", "s1")])) | |
| 457 | - stored = select(client, "SELECT * FROM recommendation;")[0] | |
| 458 | - self.assertEqual(count_rows(client, "recommendation"), 1) | |
| 459 | - self.assertIsNone(stored.get("dismissed_at")) | |
| 460 | - | |
| 461 | - def test_wrong_type_is_refused_loudly(self) -> None: | |
| 462 | - client = fresh_schema_client("tiphata") | |
| 463 | - with self.assertRaises(SurrealError): | |
| 464 | - client.query_sync( | |
| 465 | - "UPSERT type::record('student_summary', 'y') CONTENT $v;", | |
| 466 | - {"v": {**summary_row(make_summary("okul-a", "s1")), "computed_at": "yarin"}}, | |
| 467 | - ) | |
| 468 | - | |
| 469 | - | |
| 470 | -@requires_db | |
| 471 | -class TestBulkWrite(unittest.IsolatedAsyncioTestCase): | |
| 472 | - async def asyncSetUp(self) -> None: | |
| 473 | - self.client = fresh_schema_client("yazim") | |
| 474 | - self.store = Store(self.client) | |
| 475 | - | |
| 476 | - async def test_write_and_read_back_summaries(self) -> None: | |
| 477 | - summaries = [make_summary("okul-a", f"s{i:04d}") for i in range(37)] | |
| 478 | - report = await self.store.write_summaries(summaries) | |
| 479 | - self.assertEqual(report.written, 37) | |
| 480 | - self.assertEqual(count_rows(self.client, "student_summary"), 37) | |
| 481 | - rows = select( | |
| 482 | - self.client, | |
| 483 | - "SELECT * FROM student_summary WHERE student = 's0000';", | |
| 484 | - ) | |
| 485 | - self.assertEqual(len(rows), 1) | |
| 486 | - # Ic ice nesne ve dikkat maddesi aynen geri okunuyor mu? | |
| 487 | - self.assertEqual( | |
| 488 | - rows[0]["marks"]["courses"]["course-1"]["placement"]["band"], "on_track" | |
| 489 | - ) | |
| 490 | - self.assertEqual(rows[0]["attention"][0]["evidence"]["missed"], 4) | |
| 491 | - self.assertEqual(rows[0]["confidence"], "exploratory") | |
| 492 | - | |
| 493 | - async def test_batches_larger_than_batch_size_are_split_and_all_land(self) -> None: | |
| 494 | - """`BATCH_SIZE`'i asan yazim birden fazla transaction'a boluniyor.""" | |
| 495 | - total = BATCH_SIZE + 123 | |
| 496 | - summaries = [make_summary("okul-a", f"b{i:05d}") for i in range(total)] | |
| 497 | - store = Store(self.client) | |
| 498 | - report = await store.write_summaries(summaries) | |
| 499 | - self.assertEqual(report.written, total) | |
| 500 | - self.assertEqual(report.skipped_batches, 0) | |
| 501 | - self.assertEqual(count_rows(self.client, "student_summary"), total) | |
| 502 | - | |
| 503 | - async def test_upsert_is_idempotent(self) -> None: | |
| 504 | - summaries = [make_summary("okul-a", "tek")] | |
| 505 | - await self.store.write_summaries(summaries) | |
| 506 | - await self.store.write_summaries(summaries) | |
| 507 | - self.assertEqual(count_rows(self.client, "student_summary"), 1) | |
| 508 | - | |
| 509 | - async def test_recommendations_land_with_evidence(self) -> None: | |
| 510 | - recs = [ | |
| 511 | - make_recommendation("okul-a", f"s{i}", rule_id=f"O1-{i}") for i in range(10) | |
| 512 | - ] | |
| 513 | - report = await self.store.write_recommendations(recs) | |
| 514 | - self.assertEqual(report.written, 10) | |
| 515 | - self.assertEqual(count_rows(self.client, "recommendation"), 10) | |
| 516 | - rows = select(self.client, "SELECT * FROM recommendation LIMIT 1;") | |
| 517 | - payload = {k: v for k, v in rows[0]["evidence"].items() if k != "limitation"} | |
| 518 | - self.assertTrue(payload) | |
| 519 | - self.assertIn("limitation", rows[0]["evidence"]) | |
| 520 | - | |
| 521 | - async def test_rerun_does_not_erase_a_human_dismissal(self) -> None: | |
| 522 | - """Gece kosusu, kullanicinin 'faydali degil' kaydini SILMEZ.""" | |
| 523 | - rec = make_recommendation("okul-a", "s1") | |
| 524 | - await self.store.write_recommendations([rec]) | |
| 525 | - self.client.query_sync( | |
| 526 | - "UPDATE type::record('recommendation', $k) MERGE $v;", | |
| 527 | - { | |
| 528 | - "k": rec.record_key(), | |
| 529 | - "v": { | |
| 530 | - "dismissed_at": NOW + 1000, | |
| 531 | - "dismissed_by": "s1", | |
| 532 | - "dismiss_reason": "bu dogru degil", | |
| 533 | - }, | |
| 534 | - }, | |
| 535 | - ) | |
| 536 | - await self.store.write_recommendations([rec]) # ertesi gece | |
| 537 | - row = select(self.client, "SELECT * FROM recommendation;")[0] | |
| 538 | - self.assertEqual(row["dismissed_at"], NOW + 1000) | |
| 539 | - self.assertEqual(row["dismiss_reason"], "bu dogru degil") | |
| 540 | - | |
| 541 | - async def test_insight_run_row_is_written(self) -> None: | |
| 542 | - row = { | |
| 543 | - "school": "okul-a", | |
| 544 | - "started_at": NOW, | |
| 545 | - "finished_at": NOW + 1000, | |
| 546 | - "status": "ok", | |
| 547 | - "duration_ms": 1000, | |
| 548 | - "students_total": 5, | |
| 549 | - "students_ok": 5, | |
| 550 | - "students_failed": 0, | |
| 551 | - "students_skipped": 0, | |
| 552 | - "rows_written": 12, | |
| 553 | - "pending_students": [], | |
| 554 | - "failed_modules": [], | |
| 555 | - "budget_exceeded": False, | |
| 556 | - "budget_ms": 60_000, | |
| 557 | - } | |
| 558 | - self.assertTrue(await self.store.write_run(row, "okul-a_2023-11-14")) | |
| 559 | - rows = select(self.client, "SELECT * FROM insight_run;") | |
| 560 | - self.assertEqual(len(rows), 1) | |
| 561 | - self.assertEqual(rows[0]["status"], "ok") | |
| 562 | - self.assertEqual( | |
| 563 | - rows[0]["retain_until"], NOW + RETENTION_DAYS["insight_run"] * DAY | |
| 564 | - ) | |
| 565 | - | |
| 566 | - | |
| 567 | -@requires_db | |
| 568 | -class TestSegmentTables(unittest.IsolatedAsyncioTestCase): | |
| 569 | - """Iki yeni tablo GERCEKTEN yaziliyor ve geri okunuyor mu?""" | |
| 570 | - | |
| 571 | - async def asyncSetUp(self) -> None: | |
| 572 | - self.client = fresh_schema_client("segment") | |
| 573 | - self.store = Store(self.client) | |
| 574 | - | |
| 575 | - async def test_question_segment_round_trip(self) -> None: | |
| 576 | - report = await self.store.write_question_segments( | |
| 577 | - [make_question_segment("okul-a", f"exam_question:q{i}") for i in range(5)] | |
| 578 | - ) | |
| 579 | - self.assertEqual(report.written, 5) | |
| 580 | - self.assertEqual(count_rows(self.client, "question_segment"), 5) | |
| 581 | - # DIKKAT: `WHERE question = $q` CALISMAZ. Kimlik bicimli bir degisken | |
| 582 | - # ucta `record` olur ve metin alanla esitlik SESSIZCE bos doner -- | |
| 583 | - # hata degil, BOS SONUC. Okuyan taraf da `type::string()` ile | |
| 584 | - # karsilastirmak zorunda (bkz. docs/CIKTI-SOZLESMESI.md §6). | |
| 585 | - row = select( | |
| 586 | - self.client, | |
| 587 | - "SELECT * FROM question_segment WHERE question = type::string($q);", | |
| 588 | - {"q": "exam_question:q0"}, | |
| 589 | - )[0] | |
| 590 | - self.assertEqual(row["bilissel_talep"], "analiz") | |
| 591 | - self.assertEqual(row["confidence_okuma_yuku"], 0.96) | |
| 592 | - self.assertEqual(row["experimental_dimensions"], ["adim_sayisi"]) | |
| 593 | - self.assertNotIn("adim_sayisi", row["downstream_dimensions"]) | |
| 594 | - self.assertEqual(row["trap_choice"], "choice-2") | |
| 595 | - | |
| 596 | - async def test_tuzaksiz_soruda_trap_choice_alani_hic_yazilmaz(self) -> None: | |
| 597 | - """`option<string>` NULL kabul etmez; alan gonderilmemeli.""" | |
| 598 | - await self.store.write_question_segments( | |
| 599 | - [make_question_segment("okul-a", "exam_question:temiz", trap=None)] | |
| 600 | - ) | |
| 601 | - row = select(self.client, "SELECT * FROM question_segment;")[0] | |
| 602 | - self.assertIsNone(row.get("trap_choice")) | |
| 603 | - self.assertEqual(row["dikkat_tuzagi"], "yok") | |
| 604 | - | |
| 605 | - async def test_profil_satiri_kontrastla_birlikte_geri_okunur(self) -> None: | |
| 606 | - await self.store.write_segment_profiles( | |
| 607 | - [make_segment_profile("okul-a", "s1")] | |
| 608 | - ) | |
| 609 | - row = select(self.client, "SELECT * FROM student_segment_profile;")[0] | |
| 610 | - self.assertEqual(row["n_answers"], 180) | |
| 611 | - self.assertAlmostEqual(row["accuracy"], 63 / 180, places=5) | |
| 612 | - self.assertAlmostEqual(row["contrast"], 63 / 180 - 0.58, places=5) | |
| 613 | - self.assertEqual(row["confidence"], "stable") | |
| 614 | - | |
| 615 | - async def test_upsert_idempotent(self) -> None: | |
| 616 | - rows = [make_segment_profile("okul-a", "s1")] | |
| 617 | - await self.store.write_segment_profiles(rows) | |
| 618 | - await self.store.write_segment_profiles(rows) | |
| 619 | - self.assertEqual(count_rows(self.client, "student_segment_profile"), 1) | |
| 620 | - | |
| 621 | - async def test_ayni_ogrencinin_iki_segmenti_iki_satir(self) -> None: | |
| 622 | - await self.store.write_segment_profiles( | |
| 623 | - [ | |
| 624 | - make_segment_profile("okul-a", "s1"), | |
| 625 | - make_segment_profile( | |
| 626 | - "okul-a", "s1", dimension="okuma_yuku", label="yuksek" | |
| 627 | - ), | |
| 628 | - ] | |
| 629 | - ) | |
| 630 | - self.assertEqual(count_rows(self.client, "student_segment_profile"), 2) | |
| 631 | - | |
| 632 | - async def test_semada_olmayan_alan_satiri_dusurur(self) -> None: | |
| 633 | - """Tek bir "risk skoru" alani buraya da SIZAMAZ.""" | |
| 634 | - from src.store import student_segment_profile_row | |
| 635 | - | |
| 636 | - with self.assertRaises(SurrealError): | |
| 637 | - self.client.query_sync( | |
| 638 | - "UPSERT type::record('student_segment_profile', 'x') CONTENT $v;", | |
| 639 | - { | |
| 640 | - "v": { | |
| 641 | - **student_segment_profile_row( | |
| 642 | - make_segment_profile("okul-a", "s1") | |
| 643 | - ), | |
| 644 | - "risk_score": 0.9, | |
| 645 | - } | |
| 646 | - }, | |
| 647 | - ) | |
| 648 | - | |
| 649 | - async def test_gercek_kimlikler_metin_olarak_geri_okunur(self) -> None: | |
| 650 | - """`user:<ULID>` / `exam_question:<ULID>` yazilabiliyor mu? | |
| 651 | - | |
| 652 | - Bu tam olarak uretimdeki kimlik bicimi. `type::string()` sarmasi | |
| 653 | - olmadan bu test "Expected string but found user:..." ile duserdi. | |
| 654 | - """ | |
| 655 | - await self.store.write_question_segments( | |
| 656 | - [make_question_segment("okul-a", "exam_question:01K6MDXNC0A8XV7W34QBS0")] | |
| 657 | - ) | |
| 658 | - await self.store.write_segment_profiles( | |
| 659 | - [make_segment_profile("okul-a", "user:01K4216NC0H6T9EB460A6P3RNZ")] | |
| 660 | - ) | |
| 661 | - soru = select(self.client, "SELECT * FROM question_segment;")[0] | |
| 662 | - self.assertEqual(soru["question"], "exam_question:01K6MDXNC0A8XV7W34QBS0") | |
| 663 | - self.assertEqual(soru["exam"], "exam:E1") | |
| 664 | - profil = select(self.client, "SELECT * FROM student_segment_profile;")[0] | |
| 665 | - self.assertEqual(profil["student"], "user:01K4216NC0H6T9EB460A6P3RNZ") | |
| 666 | - | |
| 667 | - async def test_kimlikle_sorgulama_type_string_ister(self) -> None: | |
| 668 | - """Okuma tarafindaki ayni tuzak: cast olmadan sonuc BOS doner. | |
| 669 | - | |
| 670 | - Bu bir hata degil, sessiz bos sonuctur -- yani en kotu tur. Sozlesme | |
| 671 | - belgesi (`docs/CIKTI-SOZLESMESI.md` §6) bu yuzden her kimlik | |
| 672 | - karsilastirmasini `type::string()` ile yazar. | |
| 673 | - """ | |
| 674 | - uid = "user:01K4216NC0H6T9EB460A6P3RNZ" | |
| 675 | - await self.store.write_segment_profiles( | |
| 676 | - [make_segment_profile("okul-a", uid)] | |
| 677 | - ) | |
| 678 | - castsiz = select( | |
| 679 | - self.client, | |
| 680 | - "SELECT * FROM student_segment_profile WHERE student = $s;", | |
| 681 | - {"s": uid}, | |
| 682 | - ) | |
| 683 | - castli = select( | |
| 684 | - self.client, | |
| 685 | - "SELECT * FROM student_segment_profile " | |
| 686 | - "WHERE student = type::string($s);", | |
| 687 | - {"s": uid}, | |
| 688 | - ) | |
| 689 | - self.assertEqual(castsiz, []) | |
| 690 | - self.assertEqual(len(castli), 1) | |
| 691 | - | |
| 692 | - async def test_mezuniyet_profili_siler_soru_etiketini_birakir(self) -> None: | |
| 693 | - await self.store.write_segment_profiles( | |
| 694 | - [ | |
| 695 | - make_segment_profile("okul-a", "kalan"), | |
| 696 | - make_segment_profile("okul-a", "mezun"), | |
| 697 | - ] | |
| 698 | - ) | |
| 699 | - await self.store.write_question_segments( | |
| 700 | - [make_question_segment("okul-a", "exam_question:q1")] | |
| 701 | - ) | |
| 702 | - self.assertTrue(await self.store.purge_departed("okul-a", ["kalan"])) | |
| 703 | - kalanlar = { | |
| 704 | - r["student"] | |
| 705 | - for r in select( | |
| 706 | - self.client, "SELECT student FROM student_segment_profile;" | |
| 707 | - ) | |
| 708 | - } | |
| 709 | - self.assertEqual(kalanlar, {"kalan"}) | |
| 710 | - # Soru etiketi kisisel veri DEGIL: mezuniyetle silinmez. | |
| 711 | - self.assertEqual(count_rows(self.client, "question_segment"), 1) | |
| 712 | - | |
| 713 | - | |
| 714 | -@requires_db | |
| 715 | -class TestSweep(unittest.IsolatedAsyncioTestCase): | |
| 716 | - """Saklama suresi supurmesi GERCEKTEN siliyor mu?""" | |
| 717 | - | |
| 718 | - async def asyncSetUp(self) -> None: | |
| 719 | - self.client = fresh_schema_client("supurme") | |
| 720 | - self.store = Store(self.client) | |
| 721 | - | |
| 722 | - async def test_expired_rows_are_deleted_and_fresh_ones_survive(self) -> None: | |
| 723 | - eski = [make_summary("okul-a", f"eski-{i}", now_ms=NOW - 500 * DAY) for i in range(5)] | |
| 724 | - taze = [make_summary("okul-a", f"taze-{i}", now_ms=NOW) for i in range(7)] | |
| 725 | - await self.store.write_summaries(eski + taze) | |
| 726 | - self.assertEqual(count_rows(self.client, "student_summary"), 12) | |
| 727 | - | |
| 728 | - results = await self.store.sweep(NOW) | |
| 729 | - self.assertTrue(all(results.values())) | |
| 730 | - self.assertEqual(count_rows(self.client, "student_summary"), 7) | |
| 731 | - kalanlar = { | |
| 732 | - r["student"] for r in select(self.client, "SELECT student FROM student_summary;") | |
| 733 | - } | |
| 734 | - self.assertTrue(all(s.startswith("taze-") for s in kalanlar)) | |
| 735 | - | |
| 736 | - async def test_sweep_touches_every_table(self) -> None: | |
| 737 | - # RETENTION_DAYS'te olan her tablonun bir eski satiri yazilir; | |
| 738 | - # supurmeden sonra HICBIRI kalmamali. Yeni bir tablo eklenip | |
| 739 | - # supurmeye baglanmazsa bu test duser. | |
| 740 | - eski = NOW - 1200 * DAY | |
| 741 | - await self.store.write_question_segments( | |
| 742 | - [make_question_segment("okul-a", "q1", now_ms=eski)] | |
| 743 | - ) | |
| 744 | - await self.store.write_segment_profiles( | |
| 745 | - [make_segment_profile("okul-a", "s", now_ms=eski)] | |
| 746 | - ) | |
| 747 | - await self.store.write_summaries( | |
| 748 | - [make_summary("okul-a", "s", now_ms=NOW - 500 * DAY)] | |
| 749 | - ) | |
| 750 | - await self.store.write_recommendations( | |
| 751 | - [make_recommendation("okul-a", "s", now_ms=NOW - 500 * DAY)] | |
| 752 | - ) | |
| 753 | - await self.store.write_run( | |
| 754 | - { | |
| 755 | - "school": "okul-a", | |
| 756 | - "started_at": NOW - 500 * DAY, | |
| 757 | - "finished_at": None, | |
| 758 | - "status": "ok", | |
| 759 | - "duration_ms": None, | |
| 760 | - "students_total": 1, | |
| 761 | - "students_ok": 1, | |
| 762 | - "students_failed": 0, | |
| 763 | - "students_skipped": 0, | |
| 764 | - "rows_written": 1, | |
| 765 | - "pending_students": [], | |
| 766 | - "failed_modules": [], | |
| 767 | - "budget_exceeded": False, | |
| 768 | - "budget_ms": 60_000, | |
| 769 | - }, | |
| 770 | - "okul-a_eski", | |
| 771 | - ) | |
| 772 | - for table in RETENTION_DAYS: | |
| 773 | - self.assertEqual(count_rows(self.client, table), 1, table) | |
| 774 | - await self.store.sweep(NOW) | |
| 775 | - for table in RETENTION_DAYS: | |
| 776 | - self.assertEqual(count_rows(self.client, table), 0, table) | |
| 777 | - | |
| 778 | - async def test_recommendation_dies_at_expires_at_not_at_ninety_days(self) -> None: | |
| 779 | - """30 gunde dusen tavsiye, 90 gunu beklemez.""" | |
| 780 | - rec = make_recommendation("okul-a", "s", now_ms=NOW - 60 * DAY) | |
| 781 | - await self.store.write_recommendations([rec]) | |
| 782 | - self.assertEqual(count_rows(self.client, "recommendation"), 1) | |
| 783 | - await self.store.sweep(NOW) # olusumdan 60 gun sonra; expires 30 gundu | |
| 784 | - self.assertEqual(count_rows(self.client, "recommendation"), 0) | |
| 785 | - | |
| 786 | - | |
| 787 | -@requires_db | |
| 788 | -class TestPurgeDeparted(unittest.IsolatedAsyncioTestCase): | |
| 789 | - async def test_departed_student_profile_is_removed(self) -> None: | |
| 790 | - client = fresh_schema_client("mezun") | |
| 791 | - store = Store(client) | |
| 792 | - await store.write_summaries( | |
| 793 | - [make_summary("okul-a", "kalan"), make_summary("okul-a", "mezun")] | |
| 794 | - ) | |
| 795 | - await store.write_recommendations( | |
| 796 | - [ | |
| 797 | - make_recommendation("okul-a", "kalan", rule_id="O1-k"), | |
| 798 | - make_recommendation("okul-a", "mezun", rule_id="O1-m"), | |
| 799 | - ] | |
| 800 | - ) | |
| 801 | - self.assertTrue(await store.purge_departed("okul-a", ["kalan"])) | |
| 802 | - kalanlar = { | |
| 803 | - r["student"] for r in select(client, "SELECT student FROM student_summary;") | |
| 804 | - } | |
| 805 | - self.assertEqual(kalanlar, {"kalan"}) | |
| 806 | - hakkinda = {r["about"] for r in select(client, "SELECT about FROM recommendation;")} | |
| 807 | - self.assertEqual(hakkinda, {"kalan"}) | |
| 808 | - | |
| 809 | - | |
| 810 | -@requires_db | |
| 811 | -class TestTenantIsolation(unittest.IsolatedAsyncioTestCase): | |
| 812 | - """Iki okulun verisi birbirine karismiyor.""" | |
| 813 | - | |
| 814 | - async def asyncSetUp(self) -> None: | |
| 815 | - self.client = fresh_schema_client("kiraci") | |
| 816 | - self.store = Store(self.client) | |
| 817 | - await self.store.write_summaries( | |
| 818 | - [make_summary("okul-a", f"a{i}") for i in range(6)] | |
| 819 | - + [make_summary("okul-b", f"b{i}") for i in range(9)] | |
| 820 | - ) | |
| 821 | - await self.store.write_recommendations( | |
| 822 | - [make_recommendation("okul-a", f"a{i}", rule_id=f"O1-{i}") for i in range(4)] | |
| 823 | - + [make_recommendation("okul-b", f"b{i}", rule_id=f"O1-{i}") for i in range(5)] | |
| 824 | - ) | |
| 825 | - | |
| 826 | - async def test_row_counts_are_separate(self) -> None: | |
| 827 | - self.assertEqual(count_rows(self.client, "student_summary", "school = 'okul-a'"), 6) | |
| 828 | - self.assertEqual(count_rows(self.client, "student_summary", "school = 'okul-b'"), 9) | |
| 829 | - self.assertEqual(count_rows(self.client, "recommendation", "school = 'okul-a'"), 4) | |
| 830 | - self.assertEqual(count_rows(self.client, "recommendation", "school = 'okul-b'"), 5) | |
| 831 | - | |
| 832 | - async def test_no_row_of_one_school_carries_the_other_students(self) -> None: | |
| 833 | - for school, prefix in (("okul-a", "a"), ("okul-b", "b")): | |
| 834 | - rows = select( | |
| 835 | - self.client, | |
| 836 | - "SELECT student FROM student_summary WHERE school = $s;", | |
| 837 | - {"s": school}, | |
| 838 | - ) | |
| 839 | - self.assertTrue(rows) | |
| 840 | - for row in rows: | |
| 841 | - self.assertTrue(row["student"].startswith(prefix), row) | |
| 842 | - | |
| 843 | - async def test_record_keys_are_school_scoped(self) -> None: | |
| 844 | - """Ayni ogrenci kimligi iki okulda olsa bile satirlar ayri kalir.""" | |
| 845 | - await self.store.write_summaries( | |
| 846 | - [make_summary("okul-a", "ayni"), make_summary("okul-b", "ayni")] | |
| 847 | - ) | |
| 848 | - self.assertEqual( | |
| 849 | - count_rows(self.client, "student_summary", "student = 'ayni'"), 2 | |
| 850 | - ) | |
| 851 | - | |
| 852 | - async def test_purging_one_school_leaves_the_other_untouched(self) -> None: | |
| 853 | - await self.store.purge_departed("okul-a", ["a0"]) | |
| 854 | - self.assertEqual(count_rows(self.client, "student_summary", "school = 'okul-a'"), 1) | |
| 855 | - self.assertEqual(count_rows(self.client, "student_summary", "school = 'okul-b'"), 9) | |
| 856 | - | |
| 857 | - | |
| 858 | -if __name__ == "__main__": | |
| 859 | - unittest.main() |
service/tests/test_store_bridge.pyadded+484 -0
| @@ -0,0 +1,484 @@ | ||
| 1 | +"""Köprü deposunun sözleşme testleri: `insight.*` çağrılarının şekli. | |
| 2 | + | |
| 3 | +ZEKA'nın kendi veritabanı yoktur; yazdığı her satır `hezarfen_backend`'e bir | |
| 4 | +yetenek çağrısıyla gider. Bu dosya o sözleşmeyi sabitler: | |
| 5 | + | |
| 6 | +1. **Dokuz operasyonun her biri** doğru yetenek adıyla, doğru çerçeve okuluyla | |
| 7 | + ve beklenen payload anahtarlarıyla çağrılır. Satır değerleri GERÇEK hesap | |
| 8 | + tiplerinden (`StudentSummary`, `Recommendation`, `QuestionSegment`, | |
| 9 | + `StudentSegmentProfile`) türetilir; elle kurulmuş sözlüklerden değil. | |
| 10 | +2. **Grup bölme**: `BATCH_SIZE`'i aşan yazım 500 + kalan diye gider. | |
| 11 | +3. **Yeniden deneme sonra atlama**: iki denemesi de düşen grup `skipped_batches` | |
| 12 | + olarak görünür ve rapor `partial` olur — düşen çağrı asla başarı sayılmaz. | |
| 13 | +4. **Boş mezuniyet listesi**: çağrı YAPILMAZ ("liste çekilemedi" herkesin | |
| 14 | + verisini silerdi) ve `False` döner. | |
| 15 | +5. **Okul çerçevededir**: `insight.schools.list` dışında her çağrı okulu | |
| 16 | + taşır, `insight.schools.list` ise okulsuz (`school == ""`) gider. | |
| 17 | +""" | |
| 18 | + | |
| 19 | +from __future__ import annotations | |
| 20 | + | |
| 21 | +import unittest | |
| 22 | + | |
| 23 | +from src.compute import clock | |
| 24 | +from src.compute.model import ( | |
| 25 | + Audience, | |
| 26 | + Confidence, | |
| 27 | + QuestionSegment, | |
| 28 | + Recommendation, | |
| 29 | + StudentSegmentProfile, | |
| 30 | + StudentSummary, | |
| 31 | +) | |
| 32 | +from src.store import ( | |
| 33 | + BATCH_SIZE, | |
| 34 | + CAP_PENDING, | |
| 35 | + CAP_PROFILE, | |
| 36 | + CAP_PURGE, | |
| 37 | + CAP_RECOMMENDATION, | |
| 38 | + CAP_RUN, | |
| 39 | + CAP_SCHOOLS, | |
| 40 | + CAP_SEGMENT, | |
| 41 | + CAP_SWEEP, | |
| 42 | + CAP_SUMMARY, | |
| 43 | + PURGE_TABLES, | |
| 44 | + RETENTION_DAYS, | |
| 45 | + SWEEP_TABLES, | |
| 46 | + BridgeStore, | |
| 47 | + BridgeUnavailable, | |
| 48 | + RecordingCaller, | |
| 49 | +) | |
| 50 | + | |
| 51 | +DAY = clock.DAY_MS | |
| 52 | +NOW = 1_699_963_200_000 # 2023-11-14 12:00 UTC | |
| 53 | +SCHOOL = "okul-a" | |
| 54 | + | |
| 55 | + | |
| 56 | +def make_summary(student: str, *, now_ms: int = NOW) -> StudentSummary: | |
| 57 | + return StudentSummary( | |
| 58 | + school=SCHOOL, | |
| 59 | + student=student, | |
| 60 | + computed_at=now_ms, | |
| 61 | + marks={"courses": {"course-1": {"placement": {"band": "review"}}}}, | |
| 62 | + attendance={"courses": {"course-1": {"present": 60, "absent": 40}}}, | |
| 63 | + submission={"window_days": 30, "missed": 4}, | |
| 64 | + study={"sessions": 6}, | |
| 65 | + attention=[ | |
| 66 | + { | |
| 67 | + "trigger": "homework", | |
| 68 | + "fact": "son 30 günde 4 ödev teslim edilmedi", | |
| 69 | + "evidence": {"missed": 4, "window_days": 30}, | |
| 70 | + "window_from": now_ms - 30 * DAY, | |
| 71 | + "window_to": now_ms, | |
| 72 | + } | |
| 73 | + ], | |
| 74 | + confidence=Confidence.EXPLORATORY, | |
| 75 | + ) | |
| 76 | + | |
| 77 | + | |
| 78 | +def make_recommendation(about: str, *, now_ms: int = NOW) -> Recommendation: | |
| 79 | + return Recommendation( | |
| 80 | + school=SCHOOL, | |
| 81 | + audience=about, | |
| 82 | + audience_role=Audience.STUDENT, | |
| 83 | + product="O1", | |
| 84 | + rule_id="O1.review_band", | |
| 85 | + evidence={"student_average": 42.5, "class_average": 68.0}, | |
| 86 | + computed_at=now_ms, | |
| 87 | + expires_at=now_ms + 30 * DAY, | |
| 88 | + about=about, | |
| 89 | + course="course-1", | |
| 90 | + confidence=Confidence.EXPLORATORY, | |
| 91 | + limitation="Konu kırılımı yok.", | |
| 92 | + ) | |
| 93 | + | |
| 94 | + | |
| 95 | +def make_question_segment(question: str, *, now_ms: int = NOW) -> QuestionSegment: | |
| 96 | + return QuestionSegment( | |
| 97 | + school=SCHOOL, | |
| 98 | + question=question, | |
| 99 | + exam="exam:E1", | |
| 100 | + subject="subject:S1", | |
| 101 | + labels={"bilissel_talep": "analiz", "dikkat_tuzagi": "var"}, | |
| 102 | + confidences={"bilissel_talep": 0.91, "dikkat_tuzagi": 0.87}, | |
| 103 | + rationale="Uzun kök, iki adımlı çıkarım.", | |
| 104 | + model="deepseek-flash", | |
| 105 | + prompt_version="v1", | |
| 106 | + variant="baseline", | |
| 107 | + trap_choice="c-tuzak", | |
| 108 | + downstream_dimensions=("bilissel_talep",), | |
| 109 | + experimental_dimensions=("dikkat_tuzagi",), | |
| 110 | + computed_at=now_ms, | |
| 111 | + confidence=Confidence.STABLE, | |
| 112 | + ) | |
| 113 | + | |
| 114 | + | |
| 115 | +def make_profile(student: str, *, now_ms: int = NOW) -> StudentSegmentProfile: | |
| 116 | + return StudentSegmentProfile( | |
| 117 | + school=SCHOOL, | |
| 118 | + student=student, | |
| 119 | + dimension="bilissel_talep", | |
| 120 | + label="analiz", | |
| 121 | + n_answers=180, | |
| 122 | + n_correct=63, | |
| 123 | + overall_n_answers=900, | |
| 124 | + overall_accuracy=0.58, | |
| 125 | + computed_at=now_ms, | |
| 126 | + confidence=Confidence.STABLE, | |
| 127 | + ) | |
| 128 | + | |
| 129 | + | |
| 130 | +from .fakes import ReplyingCaller | |
| 131 | + | |
| 132 | + | |
| 133 | +class StoreFixture(unittest.IsolatedAsyncioTestCase): | |
| 134 | + """Sahte köprüyü kuran taban sınıf.""" | |
| 135 | + | |
| 136 | + async def asyncSetUp(self) -> None: | |
| 137 | + self.caller = RecordingCaller() | |
| 138 | + self.store = BridgeStore(self.caller) | |
| 139 | + | |
| 140 | + @property | |
| 141 | + def calls(self) -> list[tuple[str, str, dict]]: | |
| 142 | + return self.caller.calls | |
| 143 | + | |
| 144 | + def only_call(self) -> tuple[str, str, dict]: | |
| 145 | + self.assertEqual(len(self.calls), 1) | |
| 146 | + return self.calls[0] | |
| 147 | + | |
| 148 | + | |
| 149 | +# =========================================================================== | |
| 150 | +# Dokuz operasyon | |
| 151 | +# =========================================================================== | |
| 152 | + | |
| 153 | + | |
| 154 | +class TestActiveSchools(StoreFixture): | |
| 155 | + async def test_schools_are_listed_without_a_school_in_the_frame(self) -> None: | |
| 156 | + caller = ReplyingCaller({CAP_SCHOOLS: {"schools": ["b-okul", "a-okul", "a-okul"]}}) | |
| 157 | + store = BridgeStore(caller) | |
| 158 | + schools = await store.active_schools() | |
| 159 | + self.assertEqual(caller.calls, [(CAP_SCHOOLS, "", {})]) | |
| 160 | + # Tekilleştirilir ve sıralanır: sabit sıra zamanlayıcının kuralıdır. | |
| 161 | + self.assertEqual(schools, ["a-okul", "b-okul"]) | |
| 162 | + | |
| 163 | + | |
| 164 | +class TestSummaryWrite(StoreFixture): | |
| 165 | + async def test_capability_school_and_payload(self) -> None: | |
| 166 | + report = await self.store.store_for(SCHOOL).write_summaries( | |
| 167 | + [make_summary("s1")] | |
| 168 | + ) | |
| 169 | + capability, school, payload = self.only_call() | |
| 170 | + self.assertEqual(capability, CAP_SUMMARY) | |
| 171 | + self.assertEqual(school, SCHOOL) | |
| 172 | + self.assertEqual(set(payload), {"rows"}) | |
| 173 | + | |
| 174 | + row = payload["rows"][0] | |
| 175 | + self.assertEqual( | |
| 176 | + set(row), | |
| 177 | + { | |
| 178 | + "student", | |
| 179 | + "marks", | |
| 180 | + "attendance", | |
| 181 | + "submission", | |
| 182 | + "study", | |
| 183 | + "confidence", | |
| 184 | + "computed_at", | |
| 185 | + "retain_until", | |
| 186 | + "attention", | |
| 187 | + }, | |
| 188 | + ) | |
| 189 | + # Okul SATIRDA yoktur: çerçevede bir kez gider, çelişecek ikinci bir | |
| 190 | + # yer bırakmaz. | |
| 191 | + self.assertNotIn("school", row) | |
| 192 | + self.assertEqual(row["student"], "s1") | |
| 193 | + self.assertEqual(row["confidence"], "exploratory") | |
| 194 | + self.assertEqual(row["marks"]["courses"]["course-1"]["placement"]["band"], "review") | |
| 195 | + self.assertEqual( | |
| 196 | + row["retain_until"], | |
| 197 | + NOW + RETENTION_DAYS["student_summary"] * DAY, | |
| 198 | + ) | |
| 199 | + item = row["attention"][0] | |
| 200 | + self.assertEqual(item["trigger"], "homework") | |
| 201 | + self.assertEqual(item["evidence"], {"missed": 4, "window_days": 30}) | |
| 202 | + self.assertNotIn("score", item) | |
| 203 | + self.assertNotIn("rank", item) | |
| 204 | + self.assertEqual(report.written, 1) | |
| 205 | + self.assertEqual(report.status, "ok") | |
| 206 | + | |
| 207 | + | |
| 208 | +class TestRecommendationWrite(StoreFixture): | |
| 209 | + async def test_capability_school_and_payload(self) -> None: | |
| 210 | + await self.store.store_for(SCHOOL).write_recommendations( | |
| 211 | + [make_recommendation("s1")] | |
| 212 | + ) | |
| 213 | + capability, school, payload = self.only_call() | |
| 214 | + self.assertEqual(capability, CAP_RECOMMENDATION) | |
| 215 | + self.assertEqual(school, SCHOOL) | |
| 216 | + | |
| 217 | + row = payload["rows"][0] | |
| 218 | + self.assertEqual( | |
| 219 | + set(row), | |
| 220 | + { | |
| 221 | + "audience", | |
| 222 | + "product", | |
| 223 | + "rule_id", | |
| 224 | + "rule_version", | |
| 225 | + "scope", | |
| 226 | + "about", | |
| 227 | + "audience_role", | |
| 228 | + "course", | |
| 229 | + "evidence", | |
| 230 | + "limitation", | |
| 231 | + "confidence", | |
| 232 | + "computed_at", | |
| 233 | + "expires_at", | |
| 234 | + "retain_until", | |
| 235 | + }, | |
| 236 | + ) | |
| 237 | + # Kimliği YAZAN taraf üretir: satırda `id` yoktur. | |
| 238 | + self.assertNotIn("id", row) | |
| 239 | + self.assertEqual(row["audience"], "s1") | |
| 240 | + self.assertEqual(row["audience_role"], "student") | |
| 241 | + # `scope` boşsa ders devralır; `about` kendi alanında kalır. | |
| 242 | + self.assertEqual(row["scope"], "course-1") | |
| 243 | + self.assertEqual(row["about"], "s1") | |
| 244 | + # `expires_at` 30 gün: 90 günlük tavandan önce gelir. | |
| 245 | + self.assertEqual( | |
| 246 | + row["retain_until"], NOW + 30 * DAY | |
| 247 | + ) | |
| 248 | + | |
| 249 | + | |
| 250 | +class TestSegmentWrite(StoreFixture): | |
| 251 | + async def test_capability_school_and_payload(self) -> None: | |
| 252 | + await self.store.store_for(SCHOOL).write_question_segments( | |
| 253 | + [make_question_segment("q1")] | |
| 254 | + ) | |
| 255 | + capability, school, payload = self.only_call() | |
| 256 | + self.assertEqual(capability, CAP_SEGMENT) | |
| 257 | + self.assertEqual(school, SCHOOL) | |
| 258 | + | |
| 259 | + row = payload["rows"][0] | |
| 260 | + self.assertEqual( | |
| 261 | + set(row), | |
| 262 | + { | |
| 263 | + "question", | |
| 264 | + "exam", | |
| 265 | + "course", | |
| 266 | + "subject", | |
| 267 | + "labels", | |
| 268 | + "confidences", | |
| 269 | + "confidence", | |
| 270 | + "trap_choice", | |
| 271 | + "rationale", | |
| 272 | + "model", | |
| 273 | + "prompt_version", | |
| 274 | + "variant", | |
| 275 | + "computed_at", | |
| 276 | + "retain_until", | |
| 277 | + "downstream_dimensions", | |
| 278 | + "experimental_dimensions", | |
| 279 | + }, | |
| 280 | + ) | |
| 281 | + self.assertEqual(row["question"], "q1") | |
| 282 | + self.assertEqual(row["labels"], {"bilissel_talep": "analiz", "dikkat_tuzagi": "var"}) | |
| 283 | + self.assertEqual(row["confidences"], {"bilissel_talep": 0.91, "dikkat_tuzagi": 0.87}) | |
| 284 | + self.assertEqual(row["trap_choice"], "c-tuzak") | |
| 285 | + self.assertEqual(row["downstream_dimensions"], ["bilissel_talep"]) | |
| 286 | + self.assertEqual(row["experimental_dimensions"], ["dikkat_tuzagi"]) | |
| 287 | + self.assertEqual( | |
| 288 | + row["retain_until"], | |
| 289 | + NOW + RETENTION_DAYS["question_segment"] * DAY, | |
| 290 | + ) | |
| 291 | + | |
| 292 | + | |
| 293 | +class TestProfileWrite(StoreFixture): | |
| 294 | + async def test_capability_school_and_payload(self) -> None: | |
| 295 | + await self.store.store_for(SCHOOL).write_segment_profiles( | |
| 296 | + [make_profile("s1")] | |
| 297 | + ) | |
| 298 | + capability, school, payload = self.only_call() | |
| 299 | + self.assertEqual(capability, CAP_PROFILE) | |
| 300 | + self.assertEqual(school, SCHOOL) | |
| 301 | + | |
| 302 | + row = payload["rows"][0] | |
| 303 | + self.assertEqual( | |
| 304 | + set(row), | |
| 305 | + { | |
| 306 | + "student", | |
| 307 | + "dimension", | |
| 308 | + "label", | |
| 309 | + "n_answers", | |
| 310 | + "n_correct", | |
| 311 | + "accuracy", | |
| 312 | + "overall_n_answers", | |
| 313 | + "overall_accuracy", | |
| 314 | + "contrast", | |
| 315 | + "confidence", | |
| 316 | + "computed_at", | |
| 317 | + "retain_until", | |
| 318 | + }, | |
| 319 | + ) | |
| 320 | + self.assertEqual(row["student"], "s1") | |
| 321 | + self.assertAlmostEqual(row["accuracy"], 63 / 180, places=6) | |
| 322 | + self.assertAlmostEqual(row["contrast"], 63 / 180 - 0.58, places=6) | |
| 323 | + self.assertEqual( | |
| 324 | + row["retain_until"], | |
| 325 | + NOW + RETENTION_DAYS["student_segment_profile"] * DAY, | |
| 326 | + ) | |
| 327 | + | |
| 328 | + | |
| 329 | +class TestRunWrite(StoreFixture): | |
| 330 | + async def test_capability_school_and_payload(self) -> None: | |
| 331 | + ok = await self.store.store_for(SCHOOL).write_run( | |
| 332 | + { | |
| 333 | + "school": SCHOOL, # satıra GİRMEZ: okul çerçevededir | |
| 334 | + "started_at": NOW, | |
| 335 | + "finished_at": NOW + 1000, | |
| 336 | + "status": "ok", | |
| 337 | + "students_total": 5, | |
| 338 | + "students_ok": 5, | |
| 339 | + "rows_written": 12, | |
| 340 | + "budget_exceeded": False, | |
| 341 | + "budget_ms": 60_000, | |
| 342 | + }, | |
| 343 | + f"{SCHOOL}_2023-11-14", | |
| 344 | + ) | |
| 345 | + self.assertTrue(ok) | |
| 346 | + capability, school, payload = self.only_call() | |
| 347 | + self.assertEqual(capability, CAP_RUN) | |
| 348 | + self.assertEqual(school, SCHOOL) | |
| 349 | + self.assertEqual(set(payload), {"run"}) | |
| 350 | + | |
| 351 | + run = payload["run"] | |
| 352 | + self.assertNotIn("school", run) | |
| 353 | + self.assertEqual(run["run_day"], "2023-11-14") | |
| 354 | + self.assertEqual(run["started_at"], NOW) | |
| 355 | + # Gönderilmeyen alanlar varsayılanlanır: liste boş, `retain_until` | |
| 356 | + # koşu süresinden türetilir. | |
| 357 | + self.assertEqual(run["pending_students"], []) | |
| 358 | + self.assertEqual(run["failed_modules"], []) | |
| 359 | + self.assertEqual( | |
| 360 | + run["retain_until"], NOW + RETENTION_DAYS["insight_run"] * DAY | |
| 361 | + ) | |
| 362 | + | |
| 363 | + | |
| 364 | +class TestPendingRead(StoreFixture): | |
| 365 | + async def test_capability_school_and_payload(self) -> None: | |
| 366 | + caller = ReplyingCaller({CAP_PENDING: {"students": ["s1", "s2"]}}) | |
| 367 | + store = BridgeStore(caller) | |
| 368 | + students = await store.store_for(SCHOOL).last_pending(SCHOOL) | |
| 369 | + self.assertEqual(caller.calls, [(CAP_PENDING, SCHOOL, {})]) | |
| 370 | + self.assertEqual(students, ["s1", "s2"]) | |
| 371 | + | |
| 372 | + | |
| 373 | +class TestSweepWrite(StoreFixture): | |
| 374 | + async def test_capability_school_and_every_table(self) -> None: | |
| 375 | + # Cevap şekli backend'in `TableVerdicts`idir: kararlar `tables` | |
| 376 | + # anahtarının altında, tablo adına göre gelir. | |
| 377 | + caller = ReplyingCaller( | |
| 378 | + {CAP_SWEEP: {"tables": {table: True for table in SWEEP_TABLES}}} | |
| 379 | + ) | |
| 380 | + store = BridgeStore(caller) | |
| 381 | + result = await store.store_for(SCHOOL).sweep(NOW) | |
| 382 | + self.assertEqual(caller.calls, [(CAP_SWEEP, SCHOOL, {})]) | |
| 383 | + self.assertEqual(tuple(result), SWEEP_TABLES) | |
| 384 | + self.assertTrue(all(result.values())) | |
| 385 | + | |
| 386 | + | |
| 387 | +class TestPurgeWrite(StoreFixture): | |
| 388 | + async def test_capability_school_and_students(self) -> None: | |
| 389 | + caller = ReplyingCaller( | |
| 390 | + {CAP_PURGE: {"tables": {table: True for table in PURGE_TABLES}}} | |
| 391 | + ) | |
| 392 | + store = BridgeStore(caller) | |
| 393 | + ok = await store.store_for(SCHOOL).purge_departed(SCHOOL, ["kalan"]) | |
| 394 | + self.assertTrue(ok) | |
| 395 | + self.assertEqual(caller.calls, [(CAP_PURGE, SCHOOL, {"students": ["kalan"]})]) | |
| 396 | + | |
| 397 | + async def test_a_false_verdict_is_reported(self) -> None: | |
| 398 | + """Süpürülemeyen tablo `False` döner; hata yutulmaz.""" | |
| 399 | + caller = ReplyingCaller( | |
| 400 | + { | |
| 401 | + CAP_PURGE: { | |
| 402 | + "tables": { | |
| 403 | + table: table != PURGE_TABLES[0] for table in PURGE_TABLES | |
| 404 | + } | |
| 405 | + } | |
| 406 | + } | |
| 407 | + ) | |
| 408 | + store = BridgeStore(caller) | |
| 409 | + self.assertFalse(await store.store_for(SCHOOL).purge_departed(SCHOOL, ["kalan"])) | |
| 410 | + | |
| 411 | + | |
| 412 | +# =========================================================================== | |
| 413 | +# Grup bölme, yeniden deneme, kapılar | |
| 414 | +# =========================================================================== | |
| 415 | + | |
| 416 | + | |
| 417 | +class TestBatching(StoreFixture): | |
| 418 | + async def test_more_than_batch_size_is_split_into_two_calls(self) -> None: | |
| 419 | + total = BATCH_SIZE + 1 | |
| 420 | + report = await self.store.store_for(SCHOOL).write_summaries( | |
| 421 | + [make_summary(f"s{i:04d}") for i in range(total)] | |
| 422 | + ) | |
| 423 | + sizes = [len(payload["rows"]) for _, _, payload in self.calls] | |
| 424 | + self.assertEqual(sizes, [BATCH_SIZE, 1]) | |
| 425 | + self.assertTrue(all(capability == CAP_SUMMARY for capability, _, _ in self.calls)) | |
| 426 | + self.assertEqual(report.written, total) | |
| 427 | + self.assertEqual(report.skipped_batches, 0) | |
| 428 | + self.assertEqual(report.status, "ok") | |
| 429 | + | |
| 430 | + | |
| 431 | +class TestFailureVisibility(StoreFixture): | |
| 432 | + async def test_a_dead_batch_is_retried_then_skipped_never_successful(self) -> None: | |
| 433 | + caller = RecordingCaller(fail_times=2) # `MAX_ATTEMPTS` kadar | |
| 434 | + store = BridgeStore(caller) | |
| 435 | + report = await store.store_for(SCHOOL).write_summaries( | |
| 436 | + [make_summary("s1")] | |
| 437 | + ) | |
| 438 | + self.assertEqual(report.written, 0) | |
| 439 | + self.assertEqual(report.skipped_batches, 1) | |
| 440 | + self.assertEqual(report.status, "partial") | |
| 441 | + # Düşen çağrı kaydedilmez: başarı gibi görünen bir iz kalmaz. | |
| 442 | + self.assertEqual(caller.calls, []) | |
| 443 | + | |
| 444 | + async def test_run_write_returns_false_when_the_bridge_refuses(self) -> None: | |
| 445 | + store = BridgeStore(RecordingCaller(fail_times=2)) | |
| 446 | + ok = await store.store_for(SCHOOL).write_run({"started_at": NOW}, "okul-a_2023-11-14") | |
| 447 | + self.assertFalse(ok) | |
| 448 | + | |
| 449 | + async def test_purge_refusal_is_false_not_an_exception(self) -> None: | |
| 450 | + store = BridgeStore(RecordingCaller(fail_capabilities={CAP_PURGE})) | |
| 451 | + ok = await store.store_for(SCHOOL).purge_departed(SCHOOL, ["kalan"]) | |
| 452 | + self.assertFalse(ok) | |
| 453 | + | |
| 454 | + async def test_pending_read_failure_yields_an_empty_list(self) -> None: | |
| 455 | + """Devretmemek, yanlış listeyle koşmaktan iyidir.""" | |
| 456 | + store = BridgeStore(RecordingCaller(fail_capabilities={CAP_PENDING})) | |
| 457 | + self.assertEqual(await store.store_for(SCHOOL).last_pending(SCHOOL), []) | |
| 458 | + | |
| 459 | + | |
| 460 | +class TestEmptyDepartedGuard(StoreFixture): | |
| 461 | + async def test_empty_list_makes_no_call_and_returns_false(self) -> None: | |
| 462 | + ok = await self.store.store_for(SCHOOL).purge_departed(SCHOOL, []) | |
| 463 | + self.assertFalse(ok) | |
| 464 | + self.assertEqual(self.calls, []) | |
| 465 | + | |
| 466 | + | |
| 467 | +class TestClosedBridge(unittest.IsolatedAsyncioTestCase): | |
| 468 | + """Taşıma yokken okuma yükseltir; yazma raporda GÖRÜNÜR, sessiz kalmaz.""" | |
| 469 | + | |
| 470 | + async def test_a_read_raises_instead_of_returning_an_empty_answer(self) -> None: | |
| 471 | + store = BridgeStore(None) | |
| 472 | + with self.assertRaises(BridgeUnavailable): | |
| 473 | + await store.active_schools() | |
| 474 | + | |
| 475 | + async def test_a_write_is_not_reported_as_a_success(self) -> None: | |
| 476 | + store = BridgeStore(None) | |
| 477 | + report = await store.store_for(SCHOOL).write_summaries([make_summary("s1")]) | |
| 478 | + self.assertEqual(report.written, 0) | |
| 479 | + self.assertEqual(report.skipped_batches, 1) | |
| 480 | + self.assertEqual(report.status, "partial") | |
| 481 | + | |
| 482 | + | |
| 483 | +if __name__ == "__main__": | |
| 484 | + unittest.main() |
service/tests/test_store_pg.pydeleted+0 -460
| @@ -1,460 +0,0 @@ | ||
| 1 | -"""`store_pg.PgStore` — GERCEK PostgreSQL'e karsi. | |
| 2 | - | |
| 3 | -Bu dosya sahte istemciyle kosmaz. Sebep deneyle sabit: SurrealDB surumunde | |
| 4 | -birim testlerin tamami yesilken gercek veritabaninda `type::thing()` diye bir | |
| 5 | -fonksiyon olmadigi icin TEK SATIR yazilamiyordu, ve `FLEXIBLE TYPE object` | |
| 6 | -yanlis sirada yazildigi icin bes alan sessizce dusuyordu. Mock bir istemci bu | |
| 7 | -hatalarin hicbirini goremez; yalnizca gercek sunucu gorebilir. | |
| 8 | - | |
| 9 | -KOSMA KOSULU: `ZEKA_PG_DSN` tanimli ve adres cevap veriyor olmali. Yoksa | |
| 10 | -testler ATLANIR, birim testleri etkilenmez. | |
| 11 | - | |
| 12 | -Her test kendi semasini (`search_path`) kullanir; boylece testler birbirinin | |
| 13 | -satirini gormez ve paralel kosabilir. | |
| 14 | -""" | |
| 15 | - | |
| 16 | -from __future__ import annotations | |
| 17 | - | |
| 18 | -import asyncio | |
| 19 | -import os | |
| 20 | -import sys | |
| 21 | -import unittest | |
| 22 | -import uuid | |
| 23 | -from pathlib import Path | |
| 24 | - | |
| 25 | -from src.compute.model import ( | |
| 26 | - Audience, | |
| 27 | - Confidence, | |
| 28 | - QuestionSegment, | |
| 29 | - Recommendation, | |
| 30 | - StudentSegmentProfile, | |
| 31 | - StudentSummary, | |
| 32 | -) | |
| 33 | -from src.store_pg import PgStore | |
| 34 | - | |
| 35 | -DSN = os.environ.get("ZEKA_PG_DSN", "") | |
| 36 | -REPO = Path(__file__).resolve().parents[2] | |
| 37 | -ZEKA_DDL = REPO / "service" / "schema" / "postgres" / "school" | |
| 38 | -BACKEND_DDL = REPO.parent / "hezarfen_backend-main-yeni" / "hezarfen_backend-main" / "migrations" | |
| 39 | - | |
| 40 | - | |
| 41 | -def _available() -> bool: | |
| 42 | - if not DSN: | |
| 43 | - return False | |
| 44 | - try: | |
| 45 | - import psycopg | |
| 46 | - | |
| 47 | - with psycopg.connect(DSN, connect_timeout=3) as conn: | |
| 48 | - conn.execute("SELECT 1") | |
| 49 | - return True | |
| 50 | - except Exception: # noqa: BLE001 | |
| 51 | - return False | |
| 52 | - | |
| 53 | - | |
| 54 | -AVAILABLE = _available() | |
| 55 | - | |
| 56 | - | |
| 57 | -def uid(n: int) -> str: | |
| 58 | - """Sabit, okunabilir uuid — hangi satirin kim oldugu hata ciktisinda belli olsun.""" | |
| 59 | - return f"01920000-0000-7000-8000-{n:012d}" | |
| 60 | - | |
| 61 | - | |
| 62 | -@unittest.skipUnless(AVAILABLE, "ZEKA_PG_DSN yok/erisilemiyor; entegrasyon atlandi") | |
| 63 | -class PgStoreTest(unittest.IsolatedAsyncioTestCase): | |
| 64 | - # Windows'un varsayilan ProactorEventLoop'u psycopg'nin async tarafiyla | |
| 65 | - # calismaz ("Psycopg cannot use the 'ProactorEventLoop'"). Uretimde servis | |
| 66 | - # Linux konteynerde kosar ve orada varsayilan zaten selector'dur; bu satir | |
| 67 | - # yalnizca testin gelistirici makinesinde de kosabilmesi icin. | |
| 68 | - if sys.platform == "win32": | |
| 69 | - loop_factory = asyncio.SelectorEventLoop | |
| 70 | - | |
| 71 | - schema_name = "" | |
| 72 | - | |
| 73 | - async def asyncSetUp(self) -> None: | |
| 74 | - import psycopg | |
| 75 | - | |
| 76 | - from src.pg_client import PsycopgClient | |
| 77 | - | |
| 78 | - self.schema_name = "t" + uuid.uuid4().hex[:12] | |
| 79 | - self.conn = await psycopg.AsyncConnection.connect(DSN, autocommit=True) | |
| 80 | - await self.conn.execute(f"CREATE SCHEMA {self.schema_name}") | |
| 81 | - await self.conn.execute(f"SET search_path TO {self.schema_name}") | |
| 82 | - | |
| 83 | - # ZEKA'nin migration'i backend deposuna kopyalandi; ayni adli dosya | |
| 84 | - # orada varsa iki kez uygulanmamali ("relation already exists"). | |
| 85 | - # Adlarla tekillestiriliyor, yol ile degil. | |
| 86 | - applied: set[str] = set() | |
| 87 | - for directory in ("control", "school"): | |
| 88 | - for path in sorted((BACKEND_DDL / directory).glob("*.sql")): | |
| 89 | - await self.conn.execute(path.read_text(encoding="utf-8")) | |
| 90 | - applied.add(path.name) | |
| 91 | - for path in sorted(ZEKA_DDL.glob("*.sql")): | |
| 92 | - if path.name in applied: | |
| 93 | - continue | |
| 94 | - await self.conn.execute(path.read_text(encoding="utf-8")) | |
| 95 | - | |
| 96 | - await self._seed_school() | |
| 97 | - self.client = PsycopgClient(self.conn) | |
| 98 | - self.store = PgStore(self.client, batch_size=2) | |
| 99 | - | |
| 100 | - async def asyncTearDown(self) -> None: | |
| 101 | - await self.conn.execute(f"DROP SCHEMA {self.schema_name} CASCADE") | |
| 102 | - await self.conn.close() | |
| 103 | - | |
| 104 | - async def _seed_school(self) -> None: | |
| 105 | - """Okul tarafinda ZEKA'nin FK'lerinin bakabilecegi asgari zincir.""" | |
| 106 | - await self.conn.execute( | |
| 107 | - "INSERT INTO app_user (id, username, role, created_at) VALUES " | |
| 108 | - "(%s,'ogr1','student',1),(%s,'ogr2','student',1),(%s,'ogt','teacher',1)", | |
| 109 | - (uid(1), uid(2), uid(9)), | |
| 110 | - ) | |
| 111 | - await self.conn.execute( | |
| 112 | - "INSERT INTO course (id, creator, title, description, kind) " | |
| 113 | - "VALUES (%s,%s,'Matematik','','course')", | |
| 114 | - (uid(10), uid(9)), | |
| 115 | - ) | |
| 116 | - await self.conn.execute( | |
| 117 | - "INSERT INTO subject (id, course, name, description) " | |
| 118 | - "VALUES (%s,%s,'Turev','')", | |
| 119 | - (uid(11), uid(10)), | |
| 120 | - ) | |
| 121 | - await self.conn.execute( | |
| 122 | - "INSERT INTO exam (id, creator, course, title, description, kind) " | |
| 123 | - "VALUES (%s,%s,%s,'Deneme','','quiz')", | |
| 124 | - (uid(12), uid(9), uid(10)), | |
| 125 | - ) | |
| 126 | - await self.conn.execute( | |
| 127 | - "INSERT INTO exam_question (id, exam, text, kind, points, subject) " | |
| 128 | - "VALUES (%s,%s,'Soru','multiple_choice',5,%s)", | |
| 129 | - (uid(13), uid(12), uid(11)), | |
| 130 | - ) | |
| 131 | - | |
| 132 | - async def rows(self, sql: str, params: tuple = ()) -> list[tuple]: | |
| 133 | - async with self.conn.cursor() as cur: | |
| 134 | - await cur.execute(sql, params) | |
| 135 | - return list(await cur.fetchall()) | |
| 136 | - | |
| 137 | - # -- ozet + dikkat ------------------------------------------------------ | |
| 138 | - | |
| 139 | - def _summary(self, student: str, *, attention: list | None = None) -> StudentSummary: | |
| 140 | - return StudentSummary( | |
| 141 | - school="okul", | |
| 142 | - student=student, | |
| 143 | - computed_at=1776056400000, | |
| 144 | - marks={"courses": [{"course": uid(10), "average": 63.4}]}, | |
| 145 | - attendance={"courses": []}, | |
| 146 | - submission={"missing_rate": 0.18}, | |
| 147 | - study={"weekly_minutes": 213}, | |
| 148 | - attention=attention or [], | |
| 149 | - confidence=Confidence.STABLE, | |
| 150 | - ) | |
| 151 | - | |
| 152 | - def _item(self, trigger: str, **evidence) -> dict: | |
| 153 | - return { | |
| 154 | - "trigger": trigger, | |
| 155 | - "fact": f"{trigger} olgusu", | |
| 156 | - "evidence": evidence or {"measure": trigger}, | |
| 157 | - "window_from": 1773464400000, | |
| 158 | - "window_to": 1776056400000, | |
| 159 | - } | |
| 160 | - | |
| 161 | - async def test_ozet_ve_dikkat_yazilir(self) -> None: | |
| 162 | - summary = self._summary( | |
| 163 | - uid(1), | |
| 164 | - attention=[ | |
| 165 | - self._item("attendance"), | |
| 166 | - self._item("mark_trend", course=uid(10)), | |
| 167 | - ], | |
| 168 | - ) | |
| 169 | - report = await self.store.write_summaries([summary]) | |
| 170 | - self.assertEqual(report.written, 1) | |
| 171 | - self.assertEqual(report.skipped_batches, 0) | |
| 172 | - | |
| 173 | - got = await self.rows( | |
| 174 | - "SELECT student, confidence, marks->'courses'->0->>'average' " | |
| 175 | - "FROM zeka_student_summary" | |
| 176 | - ) | |
| 177 | - self.assertEqual(len(got), 1) | |
| 178 | - self.assertEqual(str(got[0][0]), uid(1)) | |
| 179 | - self.assertEqual(got[0][1], "stable") | |
| 180 | - self.assertEqual(got[0][2], "63.4") | |
| 181 | - | |
| 182 | - items = await self.rows( | |
| 183 | - "SELECT trigger, course, fact, window_from FROM zeka_attention_item " | |
| 184 | - "ORDER BY ord" | |
| 185 | - ) | |
| 186 | - self.assertEqual([r[0] for r in items], ["attendance", "mark_trend"]) | |
| 187 | - # Ders yalnizca not-egilimi maddesinde; kanitin icinden cikarilir. | |
| 188 | - self.assertIsNone(items[0][1]) | |
| 189 | - self.assertEqual(str(items[1][1]), uid(10)) | |
| 190 | - # Gosterilecek CUMLE kayboluyor mu? Kolonu olmasaydi kaybolurdu. | |
| 191 | - self.assertEqual(items[0][2], "attendance olgusu") | |
| 192 | - self.assertEqual(items[0][3], 1773464400000) | |
| 193 | - | |
| 194 | - async def test_dikkat_maddeleri_sil_ve_yaz(self) -> None: | |
| 195 | - """Artik uretilmeyen bir madde ekranda KALMAMALI.""" | |
| 196 | - await self.store.write_summaries( | |
| 197 | - [self._summary(uid(1), attention=[self._item("attendance"), | |
| 198 | - self._item("homework")])] | |
| 199 | - ) | |
| 200 | - self.assertEqual( | |
| 201 | - len(await self.rows("SELECT 1 FROM zeka_attention_item")), 2 | |
| 202 | - ) | |
| 203 | - # Ertesi gece yalniz biri uretildi. | |
| 204 | - await self.store.write_summaries( | |
| 205 | - [self._summary(uid(1), attention=[self._item("homework")])] | |
| 206 | - ) | |
| 207 | - left = await self.rows("SELECT trigger FROM zeka_attention_item") | |
| 208 | - self.assertEqual([r[0] for r in left], ["homework"]) | |
| 209 | - | |
| 210 | - async def test_kanitsiz_dikkat_maddesi_yazilmaz(self) -> None: | |
| 211 | - item = self._item("attendance") | |
| 212 | - item["evidence"] = {} | |
| 213 | - with self.assertLogs("src.store_pg", level="WARNING"): | |
| 214 | - await self.store.write_summaries( | |
| 215 | - [self._summary(uid(1), attention=[item])] | |
| 216 | - ) | |
| 217 | - self.assertEqual( | |
| 218 | - await self.rows("SELECT 1 FROM zeka_attention_item"), [] | |
| 219 | - ) | |
| 220 | - | |
| 221 | - # -- tavsiye ------------------------------------------------------------ | |
| 222 | - | |
| 223 | - def _rec(self, *, about: str, evidence: dict | None = None) -> Recommendation: | |
| 224 | - return Recommendation( | |
| 225 | - school="okul", | |
| 226 | - audience=uid(9), | |
| 227 | - audience_role=Audience.TEACHER, | |
| 228 | - product="T4", | |
| 229 | - rule_id="T4.homework", | |
| 230 | - evidence=evidence or {"missing_rate": 0.44}, | |
| 231 | - computed_at=1776056400000, | |
| 232 | - expires_at=1778648400000, | |
| 233 | - about=about, | |
| 234 | - course=uid(10), | |
| 235 | - confidence=Confidence.STABLE, | |
| 236 | - limitation="Kohort-goreli esik.", | |
| 237 | - ) | |
| 238 | - | |
| 239 | - async def test_ayni_kural_farkli_ogrenciler_cakismaz(self) -> None: | |
| 240 | - """Ogretmenin iki ogrenci icin ayni kurali IKI satir olmali. | |
| 241 | - | |
| 242 | - Dogal anahtarin kapsam parcasi yalnizca derse baksaydi ikisi tek satira | |
| 243 | - coker ve bir ogrenci sessizce kaybolurdu. | |
| 244 | - """ | |
| 245 | - report = await self.store.write_recommendations( | |
| 246 | - [self._rec(about=uid(1)), self._rec(about=uid(2))] | |
| 247 | - ) | |
| 248 | - self.assertEqual(report.written, 2) | |
| 249 | - got = await self.rows("SELECT about FROM zeka_recommendation ORDER BY about") | |
| 250 | - self.assertEqual([str(r[0]) for r in got], [uid(1), uid(2)]) | |
| 251 | - | |
| 252 | - async def test_kapatma_izi_gece_yaziminda_korunur(self) -> None: | |
| 253 | - """KVKK m.11 izi: gece kosusu insan mudahalesini SILMEZ.""" | |
| 254 | - await self.store.write_recommendations([self._rec(about=uid(1))]) | |
| 255 | - await self.conn.execute( | |
| 256 | - "UPDATE zeka_recommendation SET dismissed_at=%s, dismissed_by=%s, " | |
| 257 | - "dismiss_reason=%s", | |
| 258 | - (1776142800000, uid(9), "ogrenci rapor verdi"), | |
| 259 | - ) | |
| 260 | - await self.store.write_recommendations( | |
| 261 | - [self._rec(about=uid(1), evidence={"missing_rate": 0.46})] | |
| 262 | - ) | |
| 263 | - got = await self.rows( | |
| 264 | - "SELECT dismissed_at, dismiss_reason, evidence->>'missing_rate' " | |
| 265 | - "FROM zeka_recommendation" | |
| 266 | - ) | |
| 267 | - self.assertEqual(len(got), 1) | |
| 268 | - self.assertEqual(got[0][0], 1776142800000) | |
| 269 | - self.assertEqual(got[0][1], "ogrenci rapor verdi") | |
| 270 | - # ...ama kanit tazelenmis olmali. | |
| 271 | - self.assertEqual(got[0][2], "0.46") | |
| 272 | - | |
| 273 | - async def test_kanitsiz_tavsiye_reddedilir(self) -> None: | |
| 274 | - rec = self._rec(about=uid(1), evidence={"x": 1}) | |
| 275 | - object.__setattr__(rec, "evidence", {}) | |
| 276 | - with self.assertLogs("src.store_pg", level="WARNING"): | |
| 277 | - report = await self.store.write_recommendations([rec]) | |
| 278 | - self.assertEqual(report.rejected, 1) | |
| 279 | - self.assertEqual(report.written, 0) | |
| 280 | - self.assertEqual(await self.rows("SELECT 1 FROM zeka_recommendation"), []) | |
| 281 | - | |
| 282 | - # -- segment ------------------------------------------------------------ | |
| 283 | - | |
| 284 | - def _segment(self) -> QuestionSegment: | |
| 285 | - return QuestionSegment( | |
| 286 | - school="okul", | |
| 287 | - question=uid(13), | |
| 288 | - labels={ | |
| 289 | - "bilissel_talep": "uygulama", | |
| 290 | - "dikkat_tuzagi": "var", | |
| 291 | - "okuma_yuku": "dusuk", | |
| 292 | - "adim_sayisi": "tek_adim", | |
| 293 | - }, | |
| 294 | - confidences={ | |
| 295 | - "bilissel_talep": 0.91, | |
| 296 | - "dikkat_tuzagi": 0.78, | |
| 297 | - "okuma_yuku": 0.95, | |
| 298 | - "adim_sayisi": 0.61, | |
| 299 | - }, | |
| 300 | - confidence=Confidence.STABLE, | |
| 301 | - exam=uid(12), | |
| 302 | - course=uid(10), | |
| 303 | - subject=uid(11), | |
| 304 | - trap_choice="c", | |
| 305 | - rationale="Turev kurali dogrudan uygulanir.", | |
| 306 | - model="deepseek-v4-pro", | |
| 307 | - prompt_version="v3", | |
| 308 | - downstream_dimensions=("bilissel_talep", "dikkat_tuzagi", "okuma_yuku"), | |
| 309 | - experimental_dimensions=("adim_sayisi",), | |
| 310 | - computed_at=1776056400000, | |
| 311 | - ) | |
| 312 | - | |
| 313 | - async def test_segment_ve_boyut_ayrimi(self) -> None: | |
| 314 | - report = await self.store.write_question_segments([self._segment()]) | |
| 315 | - self.assertEqual(report.written, 1) | |
| 316 | - got = await self.rows( | |
| 317 | - "SELECT bilissel_talep, confidence_adim_sayisi, trap_choice " | |
| 318 | - "FROM zeka_question_segment" | |
| 319 | - ) | |
| 320 | - self.assertEqual(got[0][0], "uygulama") | |
| 321 | - self.assertAlmostEqual(got[0][1], 0.61) | |
| 322 | - self.assertEqual(got[0][2], "c") | |
| 323 | - | |
| 324 | - dims = await self.rows( | |
| 325 | - "SELECT dimension, role FROM zeka_question_segment_dimension " | |
| 326 | - "ORDER BY ord" | |
| 327 | - ) | |
| 328 | - self.assertEqual( | |
| 329 | - dims, | |
| 330 | - [ | |
| 331 | - ("bilissel_talep", "downstream"), | |
| 332 | - ("dikkat_tuzagi", "downstream"), | |
| 333 | - ("okuma_yuku", "downstream"), | |
| 334 | - ("adim_sayisi", "experimental"), | |
| 335 | - ], | |
| 336 | - ) | |
| 337 | - | |
| 338 | - async def test_profil_contrast_yazilir(self) -> None: | |
| 339 | - profile = StudentSegmentProfile( | |
| 340 | - school="okul", | |
| 341 | - student=uid(1), | |
| 342 | - dimension="bilissel_talep", | |
| 343 | - label="analiz", | |
| 344 | - n_answers=86, | |
| 345 | - n_correct=31, | |
| 346 | - overall_n_answers=412, | |
| 347 | - overall_accuracy=240 / 412, | |
| 348 | - confidence=Confidence.STABLE, | |
| 349 | - computed_at=1776056400000, | |
| 350 | - ) | |
| 351 | - report = await self.store.write_segment_profiles([profile]) | |
| 352 | - self.assertEqual(report.written, 1) | |
| 353 | - got = await self.rows( | |
| 354 | - "SELECT accuracy, overall_accuracy, contrast " | |
| 355 | - "FROM zeka_student_segment_profile" | |
| 356 | - ) | |
| 357 | - self.assertAlmostEqual(got[0][0], 0.360465, places=5) | |
| 358 | - self.assertAlmostEqual(got[0][2], got[0][0] - got[0][1], places=6) | |
| 359 | - # Kontrast negatif: ogrenci KENDI genel seviyesine gore geride. | |
| 360 | - self.assertLess(got[0][2], 0) | |
| 361 | - | |
| 362 | - # -- kosu defteri ------------------------------------------------------- | |
| 363 | - | |
| 364 | - async def test_kosu_defteri_ve_devreden_liste(self) -> None: | |
| 365 | - ok = await self.store.write_run( | |
| 366 | - { | |
| 367 | - "started_at": 1776056400000, | |
| 368 | - "status": "partial", | |
| 369 | - "students_total": 250, | |
| 370 | - "students_ok": 231, | |
| 371 | - "budget_ms": 3600000, | |
| 372 | - "budget_exceeded": True, | |
| 373 | - "pending_students": [uid(1), uid(2)], | |
| 374 | - "failed_modules": ["submission"], | |
| 375 | - }, | |
| 376 | - "okul_2026-04-13", | |
| 377 | - ) | |
| 378 | - self.assertTrue(ok) | |
| 379 | - self.assertEqual(await self.store.last_pending("okul"), [uid(1), uid(2)]) | |
| 380 | - # Ikinci yazim cocuklari COGALTMAMALI. | |
| 381 | - await self.store.write_run( | |
| 382 | - { | |
| 383 | - "started_at": 1776056400000, | |
| 384 | - "status": "ok", | |
| 385 | - "budget_ms": 3600000, | |
| 386 | - "pending_students": [uid(2)], | |
| 387 | - }, | |
| 388 | - "okul_2026-04-13", | |
| 389 | - ) | |
| 390 | - self.assertEqual(await self.store.last_pending("okul"), [uid(2)]) | |
| 391 | - runs = await self.rows("SELECT run_day, status FROM zeka_run") | |
| 392 | - self.assertEqual(runs, [("2026-04-13", "ok")]) | |
| 393 | - | |
| 394 | - # -- supurme ve mezuniyet ---------------------------------------------- | |
| 395 | - | |
| 396 | - async def test_supurme_once_cocugu_siler(self) -> None: | |
| 397 | - """FK'ler NO ACTION; ters sirada supurme FK ihlaliyle duserdi.""" | |
| 398 | - await self.store.write_summaries( | |
| 399 | - [self._summary(uid(1), attention=[self._item("attendance")])] | |
| 400 | - ) | |
| 401 | - await self.store.write_question_segments([self._segment()]) | |
| 402 | - await self.store.write_run( | |
| 403 | - {"started_at": 1, "status": "ok", "budget_ms": 1, | |
| 404 | - "pending_students": [uid(1)], "failed_modules": ["x"]}, | |
| 405 | - "2020-01-01", | |
| 406 | - ) | |
| 407 | - # Her seyin saklama suresi gecmis olsun. | |
| 408 | - for table in ("zeka_student_summary", "zeka_question_segment", | |
| 409 | - "zeka_run", "zeka_recommendation", | |
| 410 | - "zeka_student_segment_profile"): | |
| 411 | - await self.conn.execute(f"UPDATE {table} SET retain_until = 1") | |
| 412 | - | |
| 413 | - results = await self.store.sweep(now_ms=10_000) | |
| 414 | - self.assertTrue(all(results.values()), results) | |
| 415 | - for table in ("zeka_attention_item", "zeka_student_summary", | |
| 416 | - "zeka_question_segment_dimension", "zeka_question_segment", | |
| 417 | - "zeka_run_pending", "zeka_run_failed_module", "zeka_run"): | |
| 418 | - self.assertEqual( | |
| 419 | - await self.rows(f"SELECT 1 FROM {table}"), [], f"{table} bosalmadi" | |
| 420 | - ) | |
| 421 | - | |
| 422 | - async def test_mezuniyet_temizligi(self) -> None: | |
| 423 | - await self.store.write_summaries( | |
| 424 | - [self._summary(uid(1), attention=[self._item("attendance")]), | |
| 425 | - self._summary(uid(2))] | |
| 426 | - ) | |
| 427 | - await self.store.write_recommendations([self._rec(about=uid(1))]) | |
| 428 | - ok = await self.store.purge_departed("okul", [uid(2)]) | |
| 429 | - self.assertTrue(ok) | |
| 430 | - left = await self.rows("SELECT student FROM zeka_student_summary") | |
| 431 | - self.assertEqual([str(r[0]) for r in left], [uid(2)]) | |
| 432 | - self.assertEqual(await self.rows("SELECT 1 FROM zeka_attention_item"), []) | |
| 433 | - self.assertEqual(await self.rows("SELECT 1 FROM zeka_recommendation"), []) | |
| 434 | - | |
| 435 | - async def test_bos_aktif_liste_hicbir_seyi_silmez(self) -> None: | |
| 436 | - """Bos liste "okul bosaldi" degil, "listeyi cekemedik" demektir.""" | |
| 437 | - await self.store.write_summaries([self._summary(uid(1))]) | |
| 438 | - with self.assertLogs("src.store_pg", level="WARNING"): | |
| 439 | - ok = await self.store.purge_departed("okul", []) | |
| 440 | - self.assertFalse(ok) | |
| 441 | - self.assertEqual( | |
| 442 | - len(await self.rows("SELECT 1 FROM zeka_student_summary")), 1 | |
| 443 | - ) | |
| 444 | - | |
| 445 | - # -- hata davranisi ----------------------------------------------------- | |
| 446 | - | |
| 447 | - async def test_dusen_grup_hatti_durdurmaz(self) -> None: | |
| 448 | - """Olmayan ogrenci -> FK ihlali. Grup atlanir, kosu devam eder.""" | |
| 449 | - good = self._summary(uid(1)) | |
| 450 | - bad = self._summary(uid(777)) # app_user'da yok | |
| 451 | - with self.assertLogs("src.store_pg", level="WARNING"): | |
| 452 | - report = await self.store.write_summaries([bad, good]) | |
| 453 | - # batch_size=2 -> ikisi ayni grupta, grup tumuyle atlanir. | |
| 454 | - self.assertEqual(report.skipped_batches, 1) | |
| 455 | - self.assertEqual(report.written, 0) | |
| 456 | - self.assertEqual(await self.rows("SELECT 1 FROM zeka_student_summary"), []) | |
| 457 | - | |
| 458 | - | |
| 459 | -if __name__ == "__main__": | |
| 460 | - unittest.main() |
service/tests/test_tenants.pydeleted+0 -612
| @@ -1,612 +0,0 @@ | ||
| 1 | -"""Okul cozumlemesi (`tenants.py`) testleri. | |
| 2 | - | |
| 3 | -Iki katman vardir ve ikisi AYRI isler: | |
| 4 | - | |
| 5 | -1. **Birim** (bu dosyanin cogu, bagimliliksiz): ad kurali, kayit onbellegi, | |
| 6 | - havuz tavani/TTL'i, bilinmeyen okulun reddi. Sahte kontrol istemcisi ve | |
| 7 | - sahte `opener` ile kosar -- gercek veritabani gerekmez, CI'da da kosar. | |
| 8 | -2. **Entegrasyon** (`ZEKA_TEST_PG_DSN` verilirse): gercek Postgres'te iki | |
| 9 | - okul veritabani acar, satirlarin birbirine SIZMADIGINI, eksik veritabani | |
| 10 | - ve migrate edilmemis veritabani hatalarinin AYRI oldugunu olcer. Degisken | |
| 11 | - yoksa atlanir; birim testleri etkilenmez. | |
| 12 | - | |
| 13 | -`ZEKA_TEST_PG_DSN` BILEREK ayri bir degiskendir: `ZEKA_PG_DSN` uretim | |
| 14 | -kontrol veritabanini gosterebilir ve bu testler veritabani ACAR/SILER. | |
| 15 | -""" | |
| 16 | - | |
| 17 | -from __future__ import annotations | |
| 18 | - | |
| 19 | -import asyncio | |
| 20 | -import os | |
| 21 | -import sys | |
| 22 | -import unittest | |
| 23 | -import uuid | |
| 24 | -from pathlib import Path | |
| 25 | - | |
| 26 | -from src import capabilities, tenants | |
| 27 | -from src.tenants import ( | |
| 28 | - OneDatabase, | |
| 29 | - OpenedSchool, | |
| 30 | - SchoolNotMigrated, | |
| 31 | - SchoolRegistry, | |
| 32 | - SchoolSuspended, | |
| 33 | - TenantError, | |
| 34 | - TenantStores, | |
| 35 | - UnknownSchool, | |
| 36 | - database_name, | |
| 37 | -) | |
| 38 | - | |
| 39 | -REPO = Path(__file__).resolve().parents[2] | |
| 40 | -DDL = REPO / "service" / "schema" / "postgres" / "school" / "20260916000001_zeka.sql" | |
| 41 | - | |
| 42 | -#: Sabit uuid'ler: hangi okulun hangi veritabani oldugu hata ciktisinda belli | |
| 43 | -#: olsun (`backend tenant.rs:111-112` deseninin bekledigi bicim). | |
| 44 | -SCHOOL_A = "01930000-0000-7000-8000-0000000000a1" | |
| 45 | -SCHOOL_B = "01930000-0000-7000-8000-0000000000b2" | |
| 46 | -SCHOOL_C = "01930000-0000-7000-8000-0000000000c3" | |
| 47 | -STUDENT_A = "01930000-0000-7000-8000-0000000000d1" | |
| 48 | -STUDENT_B = "01930000-0000-7000-8000-0000000000d2" | |
| 49 | -CONTROL = "hezarfen_control" | |
| 50 | - | |
| 51 | - | |
| 52 | -class _Clock: | |
| 53 | - """Deterministik saat: TTL sinirlari duvar saatine bagli kalmasin.""" | |
| 54 | - | |
| 55 | - def __init__(self, value: float = 1000.0) -> None: | |
| 56 | - self.value = value | |
| 57 | - | |
| 58 | - def __call__(self) -> float: | |
| 59 | - return self.value | |
| 60 | - | |
| 61 | - def advance(self, seconds: float) -> None: | |
| 62 | - self.value += seconds | |
| 63 | - | |
| 64 | - | |
| 65 | -class _FakeControl: | |
| 66 | - """`school` tablosunun tek sorgusunu (CONTROL_SQL) taklit eder.""" | |
| 67 | - | |
| 68 | - def __init__(self, rows: list[tuple[str, str, str]] | None = None) -> None: | |
| 69 | - self.rows = list(rows or []) | |
| 70 | - self.queries = 0 | |
| 71 | - | |
| 72 | - async def fetch(self, sql: str, params: tuple = ()) -> list[tuple]: | |
| 73 | - if sql != tenants.CONTROL_SQL: | |
| 74 | - raise AssertionError("beklenmeyen sorgu: %s" % sql) | |
| 75 | - self.queries += 1 | |
| 76 | - return list(self.rows) | |
| 77 | - | |
| 78 | - | |
| 79 | -class _FakeStore: | |
| 80 | - def __init__(self, name: str) -> None: | |
| 81 | - self.name = name | |
| 82 | - | |
| 83 | - | |
| 84 | -class NamingTests(unittest.TestCase): | |
| 85 | - def test_database_name_follows_the_backend_convention(self) -> None: | |
| 86 | - # `tenant.rs:111-112` ile ayni: {kontrol}_school_{uuid tiresiz}. | |
| 87 | - self.assertEqual( | |
| 88 | - database_name(CONTROL, SCHOOL_A), | |
| 89 | - "hezarfen_control_school_019300000000700080000000000000a1", | |
| 90 | - ) | |
| 91 | - self.assertEqual( | |
| 92 | - database_name(CONTROL, uuid.UUID(SCHOOL_A)), | |
| 93 | - "hezarfen_control_school_019300000000700080000000000000a1", | |
| 94 | - ) | |
| 95 | - | |
| 96 | - def test_the_name_never_carries_dashes_or_uppercase(self) -> None: | |
| 97 | - name = database_name(CONTROL, uuid.UUID(SCHOOL_B.upper())) | |
| 98 | - self.assertNotIn("-", name) | |
| 99 | - self.assertEqual(name, name.lower()) | |
| 100 | - | |
| 101 | - def test_garbage_is_refused_not_mangled(self) -> None: | |
| 102 | - with self.assertRaises(ValueError): | |
| 103 | - database_name(CONTROL, "kadikoy-lisesi") | |
| 104 | - | |
| 105 | - | |
| 106 | -class RegistryTests(unittest.IsolatedAsyncioTestCase): | |
| 107 | - def setUp(self) -> None: | |
| 108 | - self.clock = _Clock() | |
| 109 | - | |
| 110 | - def _registry(self, rows, ttl: float = 60.0) -> SchoolRegistry: | |
| 111 | - return SchoolRegistry(_FakeControl(rows), ttl_secs=ttl, clock_fn=self.clock) | |
| 112 | - | |
| 113 | - async def test_the_control_query_is_shared_until_the_ttl_expires(self) -> None: | |
| 114 | - registry = self._registry( | |
| 115 | - [("a-okul", SCHOOL_A, "active"), ("b-okul", SCHOOL_B, "active")] | |
| 116 | - ) | |
| 117 | - client = registry._client | |
| 118 | - for _ in range(3): | |
| 119 | - await registry.resolve("a-okul") | |
| 120 | - await registry.active_schools() | |
| 121 | - self.assertEqual(client.queries, 1, "kutuk her cagride yeniden okunmamali") | |
| 122 | - | |
| 123 | - self.clock.advance(61) | |
| 124 | - await registry.resolve("a-okul") | |
| 125 | - self.assertEqual(client.queries, 2) | |
| 126 | - | |
| 127 | - async def test_only_active_schools_are_listed_and_the_order_is_stable(self) -> None: | |
| 128 | - registry = self._registry( | |
| 129 | - [ | |
| 130 | - ("kadikoy-lisesi", SCHOOL_A, "active"), | |
| 131 | - ("kapatilan-lise", SCHOOL_B, "suspended"), | |
| 132 | - ("ataturk-lisesi", SCHOOL_A, "active"), | |
| 133 | - ] | |
| 134 | - ) | |
| 135 | - self.assertEqual( | |
| 136 | - await registry.active_schools(), ["ataturk-lisesi", "kadikoy-lisesi"] | |
| 137 | - ) | |
| 138 | - | |
| 139 | - async def test_unknown_and_suspended_are_distinguishable(self) -> None: | |
| 140 | - registry = self._registry([("kapali-lise", SCHOOL_A, "suspended")]) | |
| 141 | - with self.assertRaises(UnknownSchool) as unknown: | |
| 142 | - await registry.resolve("yok-boyle-okul") | |
| 143 | - self.assertEqual(unknown.exception.code, "unknown_school") | |
| 144 | - | |
| 145 | - with self.assertRaises(SchoolSuspended) as suspended: | |
| 146 | - await registry.resolve("kapali-lise") | |
| 147 | - self.assertEqual(suspended.exception.code, "school_suspended") | |
| 148 | - | |
| 149 | - async def test_a_broken_control_row_does_not_sink_the_catalogue(self) -> None: | |
| 150 | - registry = self._registry( | |
| 151 | - [("bozuk", "uuid-degil", "active"), ("saglam", SCHOOL_A, "active")] | |
| 152 | - ) | |
| 153 | - self.assertEqual(await registry.active_schools(), ["saglam"]) | |
| 154 | - | |
| 155 | - async def test_an_unreadable_control_database_is_a_typed_error(self) -> None: | |
| 156 | - class Broken: | |
| 157 | - async def fetch(self, sql, params=()): | |
| 158 | - raise RuntimeError('relation "school" does not exist') | |
| 159 | - | |
| 160 | - registry = SchoolRegistry(Broken(), ttl_secs=0) | |
| 161 | - with self.assertRaises(TenantError) as caught: | |
| 162 | - await registry.active_schools() | |
| 163 | - self.assertEqual(caught.exception.code, "unavailable") | |
| 164 | - self.assertIn("school", str(caught.exception)) | |
| 165 | - | |
| 166 | - | |
| 167 | -class PoolTests(unittest.IsolatedAsyncioTestCase): | |
| 168 | - """Sinirli havuz onbellegi: tavani ve TTL'i sahte opener ile olculur.""" | |
| 169 | - | |
| 170 | - def setUp(self) -> None: | |
| 171 | - self.clock = _Clock() | |
| 172 | - self.rows = [ | |
| 173 | - ("a-okul", SCHOOL_A, "active"), | |
| 174 | - ("b-okul", SCHOOL_B, "active"), | |
| 175 | - ("c-okul", SCHOOL_C, "active"), | |
| 176 | - ] | |
| 177 | - self.control = _FakeControl(self.rows) | |
| 178 | - self.opened: list[str] = [] | |
| 179 | - self.closed: list[str] = [] | |
| 180 | - | |
| 181 | - def _stores(self, *, max_pools: int = 8, ttl: float = 900.0) -> TenantStores: | |
| 182 | - self.registry = SchoolRegistry(self.control, ttl_secs=60.0, clock_fn=self.clock) | |
| 183 | - | |
| 184 | - async def opener(ref): | |
| 185 | - self.opened.append(ref.slug) | |
| 186 | - | |
| 187 | - async def close() -> None: | |
| 188 | - self.closed.append(ref.slug) | |
| 189 | - | |
| 190 | - return OpenedSchool(_FakeStore(ref.slug), close) | |
| 191 | - | |
| 192 | - return TenantStores( | |
| 193 | - self.registry, | |
| 194 | - opener, | |
| 195 | - max_pools=max_pools, | |
| 196 | - ttl_secs=ttl, | |
| 197 | - clock_fn=self.clock, | |
| 198 | - ) | |
| 199 | - | |
| 200 | - async def test_each_school_gets_its_own_store(self) -> None: | |
| 201 | - stores = self._stores() | |
| 202 | - a = await stores.store_for("a-okul") | |
| 203 | - b = await stores.store_for("b-okul") | |
| 204 | - self.assertEqual((a.name, b.name), ("a-okul", "b-okul")) | |
| 205 | - self.assertIsNot(a, b) | |
| 206 | - # Ikinci cagri onbellegi kullanir: yeniden ACILMAZ. | |
| 207 | - self.assertIs(await stores.store_for("a-okul"), a) | |
| 208 | - self.assertEqual(self.opened, ["a-okul", "b-okul"]) | |
| 209 | - | |
| 210 | - async def test_an_unknown_school_is_refused_and_nothing_falls_back(self) -> None: | |
| 211 | - stores = self._stores() | |
| 212 | - with self.assertRaises(UnknownSchool) as caught: | |
| 213 | - await stores.store_for("yok-boyle-okul") | |
| 214 | - self.assertEqual(caught.exception.code, "unknown_school") | |
| 215 | - self.assertEqual(self.opened, [], "bilinmeyen okul icin havuz ACILMAMALI") | |
| 216 | - self.assertEqual(stores.stats()["reddedilen"], 1) | |
| 217 | - | |
| 218 | - async def test_the_ceiling_evicts_the_least_recently_used_pool(self) -> None: | |
| 219 | - stores = self._stores(max_pools=2) | |
| 220 | - await stores.store_for("a-okul") | |
| 221 | - self.clock.advance(1) | |
| 222 | - b_store = await stores.store_for("b-okul") | |
| 223 | - self.clock.advance(1) | |
| 224 | - await stores.store_for("a-okul") # a artik en yeni kullanilan | |
| 225 | - self.clock.advance(1) | |
| 226 | - await stores.store_for("b-okul") # b de oyle; simdi bir yer lazim | |
| 227 | - | |
| 228 | - # Ucuncu okul icin yer acilmali: en eski kullanilan kapanir. | |
| 229 | - self.clock.advance(1) | |
| 230 | - await stores.store_for("c-okul") | |
| 231 | - | |
| 232 | - self.assertEqual(stores.stats()["acik"], 2) | |
| 233 | - self.assertEqual(stores.stats()["atilan"], 1) | |
| 234 | - self.assertEqual(self.closed, ["a-okul"]) | |
| 235 | - # Kapatilan okul yeniden istendiginde yeniden ACILIR (bayat depo yok). | |
| 236 | - self.clock.advance(1) | |
| 237 | - again = await stores.store_for("a-okul") | |
| 238 | - self.assertEqual(again.name, "a-okul") | |
| 239 | - self.assertEqual(self.opened.count("a-okul"), 2) | |
| 240 | - self.assertEqual(b_store.name, "b-okul") | |
| 241 | - | |
| 242 | - async def test_a_pool_expires_after_its_ttl(self) -> None: | |
| 243 | - stores = self._stores(ttl=10.0) | |
| 244 | - first = await stores.store_for("a-okul") | |
| 245 | - self.clock.advance(11) | |
| 246 | - second = await stores.store_for("a-okul") | |
| 247 | - self.assertIsNot(first, second) | |
| 248 | - self.assertEqual(self.closed, ["a-okul"]) | |
| 249 | - self.assertEqual(stores.stats()["atilan"], 1) | |
| 250 | - | |
| 251 | - async def test_zero_schools_boot_cleanly_and_serve_nothing(self) -> None: | |
| 252 | - self.control.rows.clear() | |
| 253 | - stores = self._stores() | |
| 254 | - self.assertEqual(await stores.active_schools(), []) | |
| 255 | - with self.assertRaises(UnknownSchool): | |
| 256 | - await stores.store_for("a-okul") | |
| 257 | - self.assertEqual(stores.stats()["acik"], 0) | |
| 258 | - await stores.close() | |
| 259 | - | |
| 260 | - async def test_close_releases_every_pool(self) -> None: | |
| 261 | - stores = self._stores() | |
| 262 | - await stores.store_for("a-okul") | |
| 263 | - await stores.store_for("b-okul") | |
| 264 | - await stores.close() | |
| 265 | - self.assertEqual(sorted(self.closed), ["a-okul", "b-okul"]) | |
| 266 | - self.assertEqual(stores.stats()["acik"], 0) | |
| 267 | - | |
| 268 | - async def test_a_failing_opener_is_reported_as_an_unavailable_school(self) -> None: | |
| 269 | - registry = SchoolRegistry(self.control, ttl_secs=60.0, clock_fn=self.clock) | |
| 270 | - | |
| 271 | - async def opener(ref): | |
| 272 | - raise RuntimeError('connection failed: FATAL: database "yok" does not exist') | |
| 273 | - | |
| 274 | - stores = TenantStores(registry, opener, clock_fn=self.clock) | |
| 275 | - with self.assertRaises(TenantError) as caught: | |
| 276 | - await stores.store_for("a-okul") | |
| 277 | - self.assertEqual(caught.exception.code, "unavailable") | |
| 278 | - | |
| 279 | - | |
| 280 | -class DispatchTests(unittest.IsolatedAsyncioTestCase): | |
| 281 | - """Cercevenin `school` alani -> o okulun deposu: istek yolunun dikişi.""" | |
| 282 | - | |
| 283 | - def setUp(self) -> None: | |
| 284 | - self.clock = _Clock() | |
| 285 | - self.control = _FakeControl( | |
| 286 | - [("a-okul", SCHOOL_A, "active"), ("b-okul", SCHOOL_B, "active")] | |
| 287 | - ) | |
| 288 | - self.seen: dict[str, list[str]] = {} | |
| 289 | - | |
| 290 | - def tearDown(self) -> None: | |
| 291 | - capabilities._handlers.clear() | |
| 292 | - capabilities.bind_directory(None) | |
| 293 | - | |
| 294 | - def _stores(self) -> TenantStores: | |
| 295 | - registry = SchoolRegistry(self.control, ttl_secs=60.0, clock_fn=self.clock) | |
| 296 | - | |
| 297 | - async def opener(ref): | |
| 298 | - store = _FakeStore(ref.slug) | |
| 299 | - store.written = [] | |
| 300 | - self.seen[ref.slug] = store.written | |
| 301 | - | |
| 302 | - async def close() -> None: | |
| 303 | - return None | |
| 304 | - | |
| 305 | - return OpenedSchool(store, close) | |
| 306 | - | |
| 307 | - return TenantStores(registry, opener, clock_fn=self.clock) | |
| 308 | - | |
| 309 | - async def test_the_handler_resolves_the_frame_s_school_and_never_another(self) -> None: | |
| 310 | - capabilities.bind_directory(self._stores()) | |
| 311 | - | |
| 312 | - async def handler(school, payload): | |
| 313 | - store = await capabilities.directory().store_for(school) | |
| 314 | - store.written.append(payload["mark"]) | |
| 315 | - return {"seen": list(store.written), "store": store.name} | |
| 316 | - | |
| 317 | - capabilities.register(capabilities.INSIGHT_REFRESH, handler) | |
| 318 | - | |
| 319 | - a = await capabilities.dispatch(capabilities.INSIGHT_REFRESH, "a-okul", {"mark": "run-a"}) | |
| 320 | - b = await capabilities.dispatch(capabilities.INSIGHT_REFRESH, "b-okul", {"mark": "run-b"}) | |
| 321 | - | |
| 322 | - self.assertEqual(a, {"seen": ["run-a"], "store": "a-okul"}) | |
| 323 | - self.assertEqual(b, {"seen": ["run-b"], "store": "b-okul"}) | |
| 324 | - self.assertEqual(self.seen["a-okul"], ["run-a"]) | |
| 325 | - self.assertEqual(self.seen["b-okul"], ["run-b"]) | |
| 326 | - | |
| 327 | - async def test_an_unknown_school_refuses_with_its_own_code(self) -> None: | |
| 328 | - capabilities.bind_directory(self._stores()) | |
| 329 | - | |
| 330 | - async def handler(school, payload): | |
| 331 | - store = await capabilities.directory().store_for(school) | |
| 332 | - return {"store": store.name} | |
| 333 | - | |
| 334 | - capabilities.register(capabilities.INSIGHT_STUDENT, handler) | |
| 335 | - with self.assertRaises(UnknownSchool) as caught: | |
| 336 | - await capabilities.dispatch(capabilities.INSIGHT_STUDENT, "yok", {}) | |
| 337 | - # Kod kabloya AYNEN gider (bridge.py: CapabilityError/TenantError). | |
| 338 | - self.assertEqual(caught.exception.code, "unknown_school") | |
| 339 | - | |
| 340 | - async def test_without_a_bound_directory_the_request_is_refused(self) -> None: | |
| 341 | - with self.assertRaises(capabilities.CapabilityError) as caught: | |
| 342 | - capabilities.directory() | |
| 343 | - self.assertEqual(caught.exception.code, "unavailable") | |
| 344 | - | |
| 345 | - | |
| 346 | -class LegacyDirectoryTests(unittest.IsolatedAsyncioTestCase): | |
| 347 | - """Eski tek veritabani modu da kapali kume olmali.""" | |
| 348 | - | |
| 349 | - async def test_the_configured_schools_are_the_only_ones_served(self) -> None: | |
| 350 | - store = _FakeStore("tek") | |
| 351 | - directory = OneDatabase(store, ["a-okul", "b-okul"]) | |
| 352 | - self.assertEqual(await directory.active_schools(), ["a-okul", "b-okul"]) | |
| 353 | - self.assertIs(await directory.store_for("a-okul"), store) | |
| 354 | - with self.assertRaises(UnknownSchool): | |
| 355 | - await directory.store_for("yok") | |
| 356 | - | |
| 357 | - | |
| 358 | -class MigrationListTests(unittest.TestCase): | |
| 359 | - """`REQUIRED_TABLES` ile okul DDL'i birbirinden kopmasin.""" | |
| 360 | - | |
| 361 | - def test_required_tables_match_the_school_migration(self) -> None: | |
| 362 | - import re | |
| 363 | - | |
| 364 | - sql = DDL.read_text(encoding="utf-8") | |
| 365 | - created = set(re.findall(r"^CREATE TABLE\s+(\w+)", sql, flags=re.MULTILINE)) | |
| 366 | - self.assertEqual( | |
| 367 | - created, | |
| 368 | - set(tenants.REQUIRED_TABLES), | |
| 369 | - "zeka okul semasi degistiyse REQUIRED_TABLES'i da guncelleyin " | |
| 370 | - "(`tenants.py`)", | |
| 371 | - ) | |
| 372 | - | |
| 373 | - | |
| 374 | -# =========================================================================== | |
| 375 | -# ENTEGRASYON -- gercek Postgres, iki okul | |
| 376 | -# =========================================================================== | |
| 377 | - | |
| 378 | -ADMIN_DSN = os.environ.get("ZEKA_TEST_PG_DSN", "").strip() | |
| 379 | - | |
| 380 | -STUB_DDL = """ | |
| 381 | -CREATE TABLE app_user (id uuid PRIMARY KEY); | |
| 382 | -CREATE TABLE course (id uuid PRIMARY KEY); | |
| 383 | -CREATE TABLE subject (id uuid PRIMARY KEY); | |
| 384 | -CREATE TABLE exam_question (exam uuid NOT NULL, id uuid NOT NULL, PRIMARY KEY (exam, id)); | |
| 385 | -""" | |
| 386 | -"""ZEKA tablolarinin disari bakan FK'leri icin asgari hedefler (bkz. | |
| 387 | -`service/schema/postgres/school/20260916000001_zeka.sql` satirlari 50, 82, | |
| 388 | -250, 300). Gercek okul veritabaninda bunlar backend'in semasidir.""" | |
| 389 | - | |
| 390 | - | |
| 391 | -def _pg_available() -> bool: | |
| 392 | - if not ADMIN_DSN: | |
| 393 | - return False | |
| 394 | - try: | |
| 395 | - import psycopg | |
| 396 | - | |
| 397 | - with psycopg.connect(ADMIN_DSN, connect_timeout=3) as conn: | |
| 398 | - conn.execute("SELECT 1") | |
| 399 | - return True | |
| 400 | - except Exception: # noqa: BLE001 | |
| 401 | - return False | |
| 402 | - | |
| 403 | - | |
| 404 | -PG_AVAILABLE = _pg_available() | |
| 405 | - | |
| 406 | -CONTROL_DDL = """ | |
| 407 | -CREATE TABLE school ( | |
| 408 | - id uuid PRIMARY KEY, | |
| 409 | - slug TEXT NOT NULL, | |
| 410 | - name TEXT NOT NULL, | |
| 411 | - status TEXT NOT NULL CONSTRAINT school_status CHECK (status IN ('active', 'suspended')), | |
| 412 | - created_at BIGINT NOT NULL, | |
| 413 | - CONSTRAINT school_slug UNIQUE (slug) | |
| 414 | -) | |
| 415 | -""" | |
| 416 | -"""Kontrol semasinin YALNIZCA kayit cozumlemesinin okudugu kadari. | |
| 417 | - | |
| 418 | -Backend'in tam kontrol semasi (`migrations/control/20260912000001_control.sql`) | |
| 419 | -bir suru tablo daha kurar; zeka yalnizca `school(slug, id, status)` okur, bu | |
| 420 | -yuzden fikstur o kadardir -- testi backend deposuna baglamak, testi baska bir | |
| 421 | -deponun surumune baglamak olurdu. | |
| 422 | -""" | |
| 423 | - | |
| 424 | - | |
| 425 | -@unittest.skipUnless( | |
| 426 | - PG_AVAILABLE, "ZEKA_TEST_PG_DSN yok/erisilemiyor; Postgres entegrasyonu atlandi" | |
| 427 | -) | |
| 428 | -class PgMultiSchoolTests(unittest.IsolatedAsyncioTestCase): | |
| 429 | - """Iki okul, iki veritabani: sizinti yok, redler ayrilabiliyor.""" | |
| 430 | - | |
| 431 | - if sys.platform == "win32": | |
| 432 | - loop_factory = asyncio.SelectorEventLoop | |
| 433 | - | |
| 434 | - async def asyncSetUp(self) -> None: | |
| 435 | - import psycopg | |
| 436 | - | |
| 437 | - from src.pg_client import PsycopgClient | |
| 438 | - from src.store_pg import PgStore | |
| 439 | - | |
| 440 | - self.PsycopgClient = PsycopgClient | |
| 441 | - self.PgStore = PgStore | |
| 442 | - self.admin = await psycopg.AsyncConnection.connect(ADMIN_DSN, autocommit=True) | |
| 443 | - self.tag = uuid.uuid4().hex[:10] | |
| 444 | - self.control = "zeka_ms_%s" % self.tag | |
| 445 | - self.a_db = database_name(self.control, SCHOOL_A) | |
| 446 | - self.b_db = database_name(self.control, SCHOOL_B) | |
| 447 | - self.made: list[str] = [] | |
| 448 | - | |
| 449 | - await self._createdb(self.control) | |
| 450 | - self.control_conn = await psycopg.AsyncConnection.connect( | |
| 451 | - tenants.school_dsn(ADMIN_DSN, self.control), autocommit=True | |
| 452 | - ) | |
| 453 | - await self.control_conn.execute(CONTROL_DDL) | |
| 454 | - await self.control_conn.execute( | |
| 455 | - "INSERT INTO school (id, slug, name, status, created_at) VALUES " | |
| 456 | - "(%s, 'a-okul', 'A', 'active', 1), (%s, 'b-okul', 'B', 'active', 2), " | |
| 457 | - "(%s, 'kapali-okul', 'K', 'suspended', 3)", | |
| 458 | - (SCHOOL_A, SCHOOL_B, SCHOOL_C), | |
| 459 | - ) | |
| 460 | - self.dsn = tenants.school_dsn(ADMIN_DSN, self.control) | |
| 461 | - | |
| 462 | - async def asyncTearDown(self) -> None: | |
| 463 | - control_conn = getattr(self, "control_conn", None) | |
| 464 | - if control_conn is not None: | |
| 465 | - await control_conn.close() | |
| 466 | - for name in reversed(self.made): | |
| 467 | - await self.admin.execute('DROP DATABASE IF EXISTS "%s" WITH (FORCE)' % name) | |
| 468 | - await self.admin.close() | |
| 469 | - | |
| 470 | - async def _createdb(self, name: str) -> None: | |
| 471 | - await self.admin.execute('CREATE DATABASE "%s"' % name) | |
| 472 | - self.made.append(name) | |
| 473 | - | |
| 474 | - async def _apply_zeka_ddl(self, name: str) -> None: | |
| 475 | - import psycopg | |
| 476 | - | |
| 477 | - conn = await psycopg.AsyncConnection.connect( | |
| 478 | - tenants.school_dsn(ADMIN_DSN, name), autocommit=True | |
| 479 | - ) | |
| 480 | - try: | |
| 481 | - # ZEKA'nin tablolari DISARI bakan FK'ler tasir (app_user, course, | |
| 482 | - # subject, exam_question). Okul veritabaninda o tablolar backend'in | |
| 483 | - # kendi semasindan gelir; fikstur FK'lerin istedigi ASGARI sutunu | |
| 484 | - # kurar, boylece test backend deposuna baglanmaz. | |
| 485 | - await conn.execute(STUB_DDL) | |
| 486 | - # Ogrenci satirlari da gerekli: `zeka_run_pending.student` ile | |
| 487 | - # `zeka_student_summary.student` app_user'a FK verir. | |
| 488 | - await conn.execute( | |
| 489 | - "INSERT INTO app_user (id) VALUES (%s), (%s)", (STUDENT_A, STUDENT_B) | |
| 490 | - ) | |
| 491 | - await conn.execute(DDL.read_text(encoding="utf-8")) | |
| 492 | - finally: | |
| 493 | - await conn.close() | |
| 494 | - | |
| 495 | - async def _open(self, **kw) -> TenantStores: | |
| 496 | - return await tenants.open_postgres(self.dsn, **kw) | |
| 497 | - | |
| 498 | - async def test_boot_succeeds_with_zero_schools(self) -> None: | |
| 499 | - # Kutugu bosalt: acilis okul satiri istememeli. | |
| 500 | - await self.control_conn.execute("DELETE FROM school") | |
| 501 | - stores = await self._open() | |
| 502 | - self.assertEqual(await stores.active_schools(), []) | |
| 503 | - with self.assertRaises(UnknownSchool) as caught: | |
| 504 | - await stores.store_for("a-okul") | |
| 505 | - self.assertEqual(caught.exception.code, "unknown_school") | |
| 506 | - await stores.close() | |
| 507 | - | |
| 508 | - async def test_two_schools_never_see_each_other_s_rows(self) -> None: | |
| 509 | - for name in (self.a_db, self.b_db): | |
| 510 | - await self._createdb(name) | |
| 511 | - await self._apply_zeka_ddl(name) | |
| 512 | - | |
| 513 | - stores = await self._open() | |
| 514 | - a = await stores.store_for("a-okul") | |
| 515 | - b = await stores.store_for("b-okul") | |
| 516 | - | |
| 517 | - # Hangi veritabanina baglandigimiz ADIYLA dogrulanir: turetme yanlissa | |
| 518 | - # butun test yanlis yeri olcerdi. | |
| 519 | - self.assertEqual( | |
| 520 | - str((await a._client.fetch("SELECT current_database()"))[0][0]), self.a_db | |
| 521 | - ) | |
| 522 | - self.assertEqual( | |
| 523 | - str((await b._client.fetch("SELECT current_database()"))[0][0]), self.b_db | |
| 524 | - ) | |
| 525 | - | |
| 526 | - # `zeka_run_pending.student` bir uuid'dir (app_user'a FK): ogrenci | |
| 527 | - # kimlikleri de o turden olmali. | |
| 528 | - self.assertTrue( | |
| 529 | - await a.write_run( | |
| 530 | - {"started_at": 1, "status": "running", "pending_students": [STUDENT_A]}, | |
| 531 | - "2026-09-17", | |
| 532 | - ) | |
| 533 | - ) | |
| 534 | - self.assertTrue( | |
| 535 | - await b.write_run( | |
| 536 | - {"started_at": 2, "status": "running", "pending_students": [STUDENT_B]}, | |
| 537 | - "2026-09-17", | |
| 538 | - ) | |
| 539 | - ) | |
| 540 | - | |
| 541 | - self.assertEqual(await a.last_pending("a-okul"), [STUDENT_A]) | |
| 542 | - self.assertEqual(await b.last_pending("b-okul"), [STUDENT_B]) | |
| 543 | - self.assertEqual( | |
| 544 | - int((await a._client.fetch("SELECT count(*) FROM zeka_run"))[0][0]), 1 | |
| 545 | - ) | |
| 546 | - self.assertEqual( | |
| 547 | - int((await b._client.fetch("SELECT count(*) FROM zeka_run"))[0][0]), 1 | |
| 548 | - ) | |
| 549 | - await stores.close() | |
| 550 | - | |
| 551 | - async def test_a_school_with_no_database_is_a_per_request_error(self) -> None: | |
| 552 | - # Ne a ne b veritabani var: acilis yine de basarili olmali. | |
| 553 | - stores = await self._open() | |
| 554 | - self.assertEqual(await stores.active_schools(), ["a-okul", "b-okul"]) | |
| 555 | - with self.assertRaises(TenantError) as caught: | |
| 556 | - await stores.store_for("a-okul") | |
| 557 | - self.assertEqual(caught.exception.code, "unavailable") | |
| 558 | - self.assertNotIsInstance(caught.exception, UnknownSchool) | |
| 559 | - await stores.close() | |
| 560 | - | |
| 561 | - async def test_an_unmigrated_school_database_is_distinguishable(self) -> None: | |
| 562 | - await self._createdb(self.a_db) # var ama zeka tablolari yok | |
| 563 | - | |
| 564 | - stores = await self._open() | |
| 565 | - with self.assertRaises(SchoolNotMigrated) as caught: | |
| 566 | - await stores.store_for("a-okul") | |
| 567 | - message = str(caught.exception) | |
| 568 | - self.assertIn("zeka_run", message) | |
| 569 | - self.assertIn("20260916000001_zeka.sql", message) | |
| 570 | - self.assertEqual(caught.exception.code, "school_not_migrated") | |
| 571 | - # Diger okulun veritabani da yok; o BASKA bir hata vermeli. | |
| 572 | - with self.assertRaises(TenantError) as other: | |
| 573 | - await stores.store_for("b-okul") | |
| 574 | - self.assertEqual(other.exception.code, "unavailable") | |
| 575 | - await stores.close() | |
| 576 | - | |
| 577 | - async def test_a_suspended_school_is_refused_by_the_control_row(self) -> None: | |
| 578 | - stores = await self._open() | |
| 579 | - with self.assertRaises(SchoolSuspended) as caught: | |
| 580 | - await stores.store_for("kapali-okul") | |
| 581 | - self.assertEqual(caught.exception.code, "school_suspended") | |
| 582 | - await stores.close() | |
| 583 | - | |
| 584 | - async def test_the_pool_cache_is_bounded_and_releases_backends(self) -> None: | |
| 585 | - for name in (self.a_db, self.b_db): | |
| 586 | - await self._createdb(name) | |
| 587 | - await self._apply_zeka_ddl(name) | |
| 588 | - | |
| 589 | - stores = await self._open(max_pools=1) | |
| 590 | - await stores.store_for("a-okul") | |
| 591 | - await stores.store_for("b-okul") | |
| 592 | - | |
| 593 | - stats = stores.stats() | |
| 594 | - self.assertEqual(stats["tavan"], 1) | |
| 595 | - self.assertEqual(stats["acik"], 1) | |
| 596 | - self.assertGreaterEqual(stats["atilan"], 1) | |
| 597 | - | |
| 598 | - # Kapatilan havuzun sunucu tarafinda baglantisi KALMAMALI; acik olan | |
| 599 | - # havuzunki durmali. Sayim kontrol baglantisindan yapilir. | |
| 600 | - sessions = await self.control_conn.execute( | |
| 601 | - "SELECT datname, count(*) FROM pg_stat_activity " | |
| 602 | - "WHERE datname IN (%s, %s) GROUP BY datname", | |
| 603 | - (self.a_db, self.b_db), | |
| 604 | - ) | |
| 605 | - counts = {str(row[0]): int(row[1]) for row in await sessions.fetchall()} | |
| 606 | - self.assertEqual(counts.get(self.a_db, 0), 0, "atilan havuz kapatilmali") | |
| 607 | - self.assertEqual(counts.get(self.b_db, 0), 1, "acik havuz yasamali") | |
| 608 | - await stores.close() | |
| 609 | - | |
| 610 | - | |
| 611 | -if __name__ == "__main__": | |
| 612 | - unittest.main() |
service/tests/zeka_db.pydeleted+0 -210
| @@ -1,210 +0,0 @@ | ||
| 1 | -"""Entegrasyon testlerinin ortak altyapisi: gercek SurrealDB + fikstur uretimi. | |
| 2 | - | |
| 3 | -`tests/test_store.py`, `tests/test_scheduler.py` ve `tests/test_pipeline.py` | |
| 4 | -buradan beslenir. | |
| 5 | - | |
| 6 | ---------------------------------------------------------------------------- | |
| 7 | -KONTEYNER YOKSA ATLANIR, VARSA KOSAR | |
| 8 | ---------------------------------------------------------------------------- | |
| 9 | -Adres `ZEKA_TEST_DB_URL` ortam degiskeninden gelir (orn. | |
| 10 | -`http://hzk-zeka:8000`). Degisken yoksa ya da adres cevap vermiyorsa | |
| 11 | -entegrasyon testleri `skipUnless` ile **atlanir** -- birim testleri etkilenmez. | |
| 12 | -CI'da degisken tanimlandigi anda ayni testler kosar. | |
| 13 | - | |
| 14 | -Neden ortam degiskeni: podman'da host'a port yonlendirmesi bu makinede | |
| 15 | -calismiyor; testler `hzk` agindaki bir konteynerden kosuluyor ve veritabanina | |
| 16 | -`hzk-zeka:8000` adiyla ulasiyor. Adresi koda gommek, tek bir topolojiye | |
| 17 | -baglanmak olurdu. | |
| 18 | -""" | |
| 19 | - | |
| 20 | -from __future__ import annotations | |
| 21 | - | |
| 22 | -import json | |
| 23 | -import os | |
| 24 | -import unittest | |
| 25 | -import urllib.error | |
| 26 | -import urllib.request | |
| 27 | -import uuid | |
| 28 | -from pathlib import Path | |
| 29 | -from typing import Any | |
| 30 | - | |
| 31 | -from src.compute import clock | |
| 32 | -from src.store import SurrealHttpClient, apply_schema | |
| 33 | - | |
| 34 | -from .fakes import ( | |
| 35 | - course_attendance, | |
| 36 | - course_marks, | |
| 37 | - homework, | |
| 38 | - pomodoro, | |
| 39 | - profile, | |
| 40 | - report_entry, | |
| 41 | -) | |
| 42 | - | |
| 43 | -DAY = clock.DAY_MS | |
| 44 | -HOUR = 3_600_000 | |
| 45 | - | |
| 46 | -#: Testlerin ortak "simdi"si: 2023-11-14 12:00 UTC. | |
| 47 | -NOW = 1_699_963_200_000 | |
| 48 | -TERM_START = NOW - 150 * DAY | |
| 49 | - | |
| 50 | -DB_URL = os.environ.get("ZEKA_TEST_DB_URL", "").strip() | |
| 51 | -DB_NS = os.environ.get("ZEKA_TEST_DB_NS", "hezarfen_test") | |
| 52 | -DB_USER = os.environ.get("ZEKA_TEST_DB_USER", "root") | |
| 53 | -DB_PASSWORD = os.environ.get("ZEKA_TEST_DB_PASSWORD", "root") | |
| 54 | - | |
| 55 | - | |
| 56 | -def _probe(url: str) -> bool: | |
| 57 | - """Adres gercekten cevap veriyor mu? Tek seferlik, kisa zaman asimi.""" | |
| 58 | - try: | |
| 59 | - with urllib.request.urlopen(url.rstrip("/") + "/health", timeout=5): | |
| 60 | - return True | |
| 61 | - except urllib.error.HTTPError: | |
| 62 | - # 4xx da "sunucu ayakta" demektir. | |
| 63 | - return True | |
| 64 | - except Exception: | |
| 65 | - return False | |
| 66 | - | |
| 67 | - | |
| 68 | -DB_AVAILABLE = bool(DB_URL) and _probe(DB_URL) | |
| 69 | - | |
| 70 | -SKIP_REASON = ( | |
| 71 | - "ZEKA_TEST_DB_URL tanimsiz ya da SurrealDB ulasilamaz durumda; " | |
| 72 | - "entegrasyon testi atlandi" | |
| 73 | -) | |
| 74 | - | |
| 75 | -requires_db = unittest.skipUnless(DB_AVAILABLE, SKIP_REASON) | |
| 76 | - | |
| 77 | - | |
| 78 | -def fresh_client(prefix: str = "t") -> SurrealHttpClient: | |
| 79 | - """Her test icin **yeni ve bos** bir veritabani acar. | |
| 80 | - | |
| 81 | - Testler birbirinin satirini gormez; "tabloyu temizlemeyi unutmak" diye bir | |
| 82 | - hata sinifi olusmaz. | |
| 83 | - """ | |
| 84 | - client = SurrealHttpClient( | |
| 85 | - DB_URL, | |
| 86 | - namespace=DB_NS, | |
| 87 | - database=f"{prefix}_{uuid.uuid4().hex[:10]}", | |
| 88 | - user=DB_USER, | |
| 89 | - password=DB_PASSWORD, | |
| 90 | - ) | |
| 91 | - client.ensure_namespace() | |
| 92 | - return client | |
| 93 | - | |
| 94 | - | |
| 95 | -def fresh_schema_client(prefix: str = "t") -> SurrealHttpClient: | |
| 96 | - """`fresh_client` + semayi yukle. Yukleme duserse test **patlar**.""" | |
| 97 | - client = fresh_client(prefix) | |
| 98 | - report = apply_schema(client) | |
| 99 | - if not report.ok: | |
| 100 | - raise AssertionError(f"sema yuklenemedi: {report.errors}") | |
| 101 | - return client | |
| 102 | - | |
| 103 | - | |
| 104 | -def count_rows(client: SurrealHttpClient, table: str, where: str = "") -> int: | |
| 105 | - """`SELECT count() ... GROUP ALL` -- SurrealDB 3'te HAVING yok, bu yeter.""" | |
| 106 | - clause = f" WHERE {where}" if where else "" | |
| 107 | - rows = client.query_sync(f"SELECT count() FROM {table}{clause} GROUP ALL;") | |
| 108 | - result = rows[0].get("result") or [] | |
| 109 | - return int(result[0]["count"]) if result else 0 | |
| 110 | - | |
| 111 | - | |
| 112 | -def select(client: SurrealHttpClient, sql: str, variables: dict | None = None) -> list: | |
| 113 | - rows = client.query_sync(sql, variables or {}) | |
| 114 | - return rows[-1].get("result") or [] | |
| 115 | - | |
| 116 | - | |
| 117 | -# --------------------------------------------------------------------------- | |
| 118 | -# Fikstur uretimi -- `FileSource`'un okudugu dizin duzeni | |
| 119 | -# --------------------------------------------------------------------------- | |
| 120 | - | |
| 121 | - | |
| 122 | -def student_payload( | |
| 123 | - uid: str, | |
| 124 | - class_id: str, | |
| 125 | - marks_list: list[int], | |
| 126 | - present: int, | |
| 127 | - absent: int, | |
| 128 | - *, | |
| 129 | - now_ms: int = NOW, | |
| 130 | -) -> dict[str, Any]: | |
| 131 | - """Tek ogrencinin butun kaynak verisi (`FakeSource` ile ayni sekil).""" | |
| 132 | - base = now_ms - 100 * DAY | |
| 133 | - return { | |
| 134 | - "profile": profile(uid, [class_id], ["course-1"]), | |
| 135 | - "marks": [course_marks("course-1", marks_list, base, teachers=["teacher-1"])], | |
| 136 | - "attendance": [course_attendance("course-1", present=present, absent=absent)], | |
| 137 | - "pomodoro": [ | |
| 138 | - pomodoro( | |
| 139 | - (clock.tr_day(now_ms) - d) * DAY + 10 * HOUR - clock.TR_OFFSET_MS | |
| 140 | - ) | |
| 141 | - for d in range(1, 7) | |
| 142 | - ], | |
| 143 | - "homework_report": [ | |
| 144 | - report_entry( | |
| 145 | - f"hw-{uid}-{i}", "course-1", now_ms - (i + 1) * DAY, submitted=True | |
| 146 | - ) | |
| 147 | - for i in range(6) | |
| 148 | - ], | |
| 149 | - "homework_list": [homework("upcoming", "course-1", now_ms + 6 * HOUR, [uid])], | |
| 150 | - } | |
| 151 | - | |
| 152 | - | |
| 153 | -def dataset(count: int = 12, *, now_ms: int = NOW) -> dict[str, dict]: | |
| 154 | - """Bir sube, bir ders, `count` ogrenci; ilki belirgin bicimde dusuk.""" | |
| 155 | - data: dict[str, dict] = {} | |
| 156 | - for i in range(count): | |
| 157 | - uid = f"student-{i:02d}" | |
| 158 | - if i == 0: | |
| 159 | - data[uid] = student_payload( | |
| 160 | - uid, "class-A", [40, 41, 39, 42, 40, 38], 60, 40, now_ms=now_ms | |
| 161 | - ) | |
| 162 | - else: | |
| 163 | - data[uid] = student_payload( | |
| 164 | - uid, "class-A", [70, 72, 71, 69, 70, 71], 95, 5, now_ms=now_ms | |
| 165 | - ) | |
| 166 | - data["_school"] = { | |
| 167 | - "homework_list": [ | |
| 168 | - homework("hw-school", "course-1", now_ms + DAY, list(data.keys())) | |
| 169 | - ] | |
| 170 | - } | |
| 171 | - return data | |
| 172 | - | |
| 173 | - | |
| 174 | -def write_fixtures(root: Path, school: str, data: dict[str, dict]) -> list[str]: | |
| 175 | - """`data` sozlugunu `FileSource`'un bekledigi dizin duzenine yazar. | |
| 176 | - | |
| 177 | - Donen deger: okul-genelinde islenecek ogrenci kimlikleri. | |
| 178 | - """ | |
| 179 | - base = root / school | |
| 180 | - #: yontem -> (alt dizin, zarf anahtari veya None) | |
| 181 | - layout = { | |
| 182 | - "profile": ("profile", None), | |
| 183 | - "marks": ("marks", "courses"), | |
| 184 | - "attendance": ("attendance", "courses"), | |
| 185 | - "pomodoro": ("pomodoro", "items"), | |
| 186 | - "homework_report": ("homework_report", "items"), | |
| 187 | - "homework_list": ("homework", "items"), | |
| 188 | - } | |
| 189 | - for directory, _ in layout.values(): | |
| 190 | - (base / directory).mkdir(parents=True, exist_ok=True) | |
| 191 | - | |
| 192 | - students: list[str] = [] | |
| 193 | - for key, payload in data.items(): | |
| 194 | - name = "_service" if key == "_school" else key | |
| 195 | - if key != "_school": | |
| 196 | - students.append(key) | |
| 197 | - for method, (directory, envelope) in layout.items(): | |
| 198 | - if method not in payload: | |
| 199 | - continue | |
| 200 | - body = payload[method] | |
| 201 | - if envelope is None: | |
| 202 | - out: Any = body | |
| 203 | - elif method == "homework_report": | |
| 204 | - out = {"items": body, "total": len(body), "limit": None, "offset": 0} | |
| 205 | - else: | |
| 206 | - out = {envelope: body} | |
| 207 | - (base / directory / f"{name}.json").write_text( | |
| 208 | - json.dumps(out, ensure_ascii=False), encoding="utf-8" | |
| 209 | - ) | |
| 210 | - return students |
tools/apply_zeka_tables.shdeleted+0 -77
| @@ -1,77 +0,0 @@ | ||
| 1 | -#!/usr/bin/env bash | |
| 2 | -# ZEKA'nin dokuz tablosunu MEVCUT okul veritabanlarina ekler. | |
| 3 | -# | |
| 4 | -# NEDEN AYRI BIR BETIK GEREKIYOR | |
| 5 | -# ------------------------------ | |
| 6 | -# Migration dosyasini `migrations/school/` altina koymak yeni okullari ve | |
| 7 | -# sablonu kapsar; HALIHAZIRDA DURAN okullari kapsamaz. Backend'in kendi | |
| 8 | -# kaynagi bunu acikca soyluyor (`database.rs:126`): | |
| 9 | -# | |
| 10 | -# "The schema is the caller's business — migrate_school for a mint, | |
| 11 | -# nothing for a re-dial of an existing school." | |
| 12 | -# | |
| 13 | -# Ve `reconcile_provisioning` yalnizca `provisioning` durumundaki okullara | |
| 14 | -# bakar. Yani sunucuda zaten duran bir okul, dosya eklense bile `zeka_*` | |
| 15 | -# tablolarini ASLA kendiliginden almaz. Bu betik o bosluğu kapatir. | |
| 16 | -# | |
| 17 | -# GUVENLI: yalnizca `CREATE TABLE`/`CREATE INDEX` calistirir, hicbir mevcut | |
| 18 | -# tabloya dokunmaz, hicbir satiri degistirmez. Tablolari zaten olan bir okulu | |
| 19 | -# ATLAR, ikinci kez uygulamaya calismaz. | |
| 20 | -# | |
| 21 | -# tools/apply_zeka_tables.sh [migration-dosyasi] | |
| 22 | -# | |
| 23 | -# Ortam: HEZARFEN_PG_CONTAINER, POSTGRES_USER, POSTGRES_DB (control) | |
| 24 | -set -euo pipefail | |
| 25 | - | |
| 26 | -HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" | |
| 27 | -DDL="${1:-$HERE/service/schema/postgres/school/20260916000001_zeka.sql}" | |
| 28 | -CONTAINER="${HEZARFEN_PG_CONTAINER:-hezarfen_backend_postgres}" | |
| 29 | -PGUSER_="${POSTGRES_USER:-hezarfen}" | |
| 30 | -CONTROL_DB="${POSTGRES_DB:-hezarfen_control}" | |
| 31 | - | |
| 32 | -[ -f "$DDL" ] || { echo "!! migration dosyasi yok: $DDL"; exit 1; } | |
| 33 | - | |
| 34 | -psql() { podman exec -i "$CONTAINER" psql -U "$PGUSER_" -v ON_ERROR_STOP=1 "$@"; } | |
| 35 | - | |
| 36 | -echo "== control: $CONTROL_DB" | |
| 37 | -echo "== ddl : $(basename "$DDL")" | |
| 38 | -echo | |
| 39 | - | |
| 40 | -# Okul veritabanlarini control'deki kutukten cozuyoruz, ad deseninden DEGIL: | |
| 41 | -# ad uuid'den turuyor ve desene guvenmek, kutukte olmayan bir veritabanina | |
| 42 | -# yazmak demek olabilirdi. | |
| 43 | -okullar="$(psql -d "$CONTROL_DB" -tAc \ | |
| 44 | - "SELECT '${CONTROL_DB}_school_' || replace(id::text, '-', '') || '|' || slug | |
| 45 | - FROM school ORDER BY created_at")" | |
| 46 | - | |
| 47 | -[ -n "$okullar" ] || { echo "kutukte okul yok — yapilacak bir sey yok"; exit 0; } | |
| 48 | - | |
| 49 | -eklendi=0 | |
| 50 | -atlandi=0 | |
| 51 | -while IFS='|' read -r db slug; do | |
| 52 | - [ -n "$db" ] || continue | |
| 53 | - var="$(psql -d "$CONTROL_DB" -tAc \ | |
| 54 | - "SELECT count(*) FROM pg_database WHERE datname='$db'")" | |
| 55 | - if [ "$var" = "0" ]; then | |
| 56 | - echo " $slug: veritabani yok ($db) — atlandi" | |
| 57 | - atlandi=$((atlandi + 1)) | |
| 58 | - continue | |
| 59 | - fi | |
| 60 | - zaten="$(psql -d "$db" -tAc \ | |
| 61 | - "SELECT count(*) FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace | |
| 62 | - WHERE n.nspname='public' AND c.relkind='r' AND c.relname LIKE 'zeka\\_%'")" | |
| 63 | - if [ "$zaten" != "0" ]; then | |
| 64 | - echo " $slug: $zaten zeka_ tablosu zaten var — atlandi" | |
| 65 | - atlandi=$((atlandi + 1)) | |
| 66 | - continue | |
| 67 | - fi | |
| 68 | - psql -d "$db" -q -f - < "$DDL" | |
| 69 | - say="$(psql -d "$db" -tAc \ | |
| 70 | - "SELECT count(*) FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace | |
| 71 | - WHERE n.nspname='public' AND c.relkind='r' AND c.relname LIKE 'zeka\\_%'")" | |
| 72 | - echo " $slug: $say tablo eklendi" | |
| 73 | - eklendi=$((eklendi + 1)) | |
| 74 | -done <<< "$okullar" | |
| 75 | - | |
| 76 | -echo | |
| 77 | -echo "== $eklendi okula eklendi, $atlandi atlandi" |
tools/check_pg_rows.sqldeleted+0 -439
| @@ -1,439 +0,0 @@ | ||
| 1 | --- ZEKA tablolarinin DAVRANIS sinavi: DDL'in yuklenmesi degil, CALISMASI. | |
| 2 | --- | |
| 3 | --- Bu dosya `tools/check_pg_schema.sh` tarafindan, backend'in ve ZEKA'nin | |
| 4 | --- migration'lari uygulandiktan SONRA kosturulur. Her blok ya yazar ya da | |
| 5 | --- yazamamasi GEREKTIGINI kanitlar; sonuncular `sonuc` tablosuna 'RED BEKLENDI' | |
| 6 | --- yazar ve kisit atesLEMEZSE test duser. | |
| 7 | --- | |
| 8 | --- Neden var: SurrealDB surumunde sema "yuklendi" ve yine de bes alani sessizce | |
| 9 | --- dusurdu. Yuklenmeyi gormek yetmiyor; satirin girip girmedigini gormek gerek. | |
| 10 | - | |
| 11 | -\set ON_ERROR_STOP on | |
| 12 | - | |
| 13 | --- SAVEPOINT yalnizca transaction icinde gecerli; ayrica sinav satirlarinin | |
| 14 | --- veritabaninda kalmasina gerek yok. | |
| 15 | -BEGIN; | |
| 16 | - | |
| 17 | -CREATE TEMP TABLE sonuc (sira int GENERATED ALWAYS AS IDENTITY, ad text, durum text); | |
| 18 | - | |
| 19 | --- --------------------------------------------------------------------------- | |
| 20 | --- Okul tarafinda en az bir gercek satir zinciri: app_user -> course -> subject | |
| 21 | --- -> exam -> exam_question. ZEKA'nin FK'leri bunlara bakiyor. | |
| 22 | --- --------------------------------------------------------------------------- | |
| 23 | -INSERT INTO app_user (id, username, role, created_at) VALUES | |
| 24 | - ('01920000-0000-7000-8000-000000000001', 'ogrenci1', 'student', 1776056400000), | |
| 25 | - ('01920000-0000-7000-8000-000000000002', 'ogretmen1', 'teacher', 1776056400000); | |
| 26 | - | |
| 27 | -INSERT INTO course (id, creator, title, description, kind) | |
| 28 | -VALUES ('01920000-0000-7000-8000-00000000000a', | |
| 29 | - '01920000-0000-7000-8000-000000000002', 'Matematik', '', 'course'); | |
| 30 | - | |
| 31 | -INSERT INTO subject (id, course, name, description) | |
| 32 | -VALUES ('01920000-0000-7000-8000-00000000000b', | |
| 33 | - '01920000-0000-7000-8000-00000000000a', 'Turev', ''); | |
| 34 | - | |
| 35 | -INSERT INTO exam (id, creator, course, title, description, kind) | |
| 36 | -VALUES ('01920000-0000-7000-8000-00000000000c', | |
| 37 | - '01920000-0000-7000-8000-000000000002', | |
| 38 | - '01920000-0000-7000-8000-00000000000a', 'Deneme 1', '', 'quiz'); | |
| 39 | - | |
| 40 | -INSERT INTO exam_question (id, exam, text, kind, points, subject, choices) | |
| 41 | -VALUES ('01920000-0000-7000-8000-00000000000d', | |
| 42 | - '01920000-0000-7000-8000-00000000000c', | |
| 43 | - 'f(x)=x^2 icin f''(2) kactir?', 'multiple_choice', 5, | |
| 44 | - '01920000-0000-7000-8000-00000000000b', | |
| 45 | - '[{"id":"a","text":"2"},{"id":"b","text":"4"},{"id":"c","text":"8"}]'::jsonb); | |
| 46 | - | |
| 47 | - | |
| 48 | --- --------------------------------------------------------------------------- | |
| 49 | --- 1) student_summary + attention: gercek sekilli JSONB girsin | |
| 50 | --- --------------------------------------------------------------------------- | |
| 51 | -INSERT INTO zeka_student_summary | |
| 52 | - (student, marks, attendance, submission, study, confidence, computed_at, retain_until) | |
| 53 | -VALUES ('01920000-0000-7000-8000-000000000001', | |
| 54 | - '{"courses":[{"course":"01920000-0000-7000-8000-00000000000a","average":63.4,"band":"Orta","cohort_percentile":41}]}'::jsonb, | |
| 55 | - '{"courses":[{"course":"01920000-0000-7000-8000-00000000000a","present_rate":0.91,"cohort_median":0.93}]}'::jsonb, | |
| 56 | - '{"missing_rate":0.18,"late_rate":0.23,"n":41}'::jsonb, | |
| 57 | - '{"weekly_minutes":213,"night_share":0.07}'::jsonb, | |
| 58 | - 'stable', 1776056400000, 1807592400000); | |
| 59 | -INSERT INTO sonuc (ad, durum) VALUES ('student_summary yazildi', 'OK'); | |
| 60 | - | |
| 61 | -INSERT INTO zeka_attention_item | |
| 62 | - (student, trigger, course, fact, window_from, window_to, evidence, ord) VALUES | |
| 63 | - ('01920000-0000-7000-8000-000000000001', 'attendance', | |
| 64 | - '01920000-0000-7000-8000-00000000000a', | |
| 65 | - 'Son 28 gunde derse katilim %78; sube ortancasi %93.', | |
| 66 | - 1773464400000, 1776056400000, | |
| 67 | - '{"measure":"level_vs_cohort_median","value":0.78,"cohort_median":0.93,"window_days":28}'::jsonb, 0), | |
| 68 | - -- Ders bagimsiz madde: course NULL. NULLS NOT DISTINCT bunu DOLU bir yuva | |
| 69 | - -- sayar, yani ayni ogrenciye ikinci bir ders-bagimsiz 'homework' giremez. | |
| 70 | - ('01920000-0000-7000-8000-000000000001', 'homework', NULL, | |
| 71 | - 'Son 30 gunde verilen odevlerin %44 kadari teslim edilmedi; sube ortancasi %18.', | |
| 72 | - 1773464400000, 1776056400000, | |
| 73 | - '{"measure":"missing_rate_vs_cohort_median","missing_rate":0.44,"cohort_missing_rate_median":0.18}'::jsonb, 1); | |
| 74 | -INSERT INTO sonuc (ad, durum) VALUES ('attention_item 2 satir (biri course NULL)', 'OK'); | |
| 75 | - | |
| 76 | - | |
| 77 | --- --------------------------------------------------------------------------- | |
| 78 | --- 2) recommendation: UPSERT idempotan mi, ve kapatma izi KORUNUYOR mu? | |
| 79 | --- Bu ikincisi belgelenmis tuzak: duz bir DO UPDATE SET her kolonu yazar ve | |
| 80 | --- kullanicinin kapatma kaydini her gece siler. | |
| 81 | --- --------------------------------------------------------------------------- | |
| 82 | -INSERT INTO zeka_recommendation | |
| 83 | - (id, audience, product, rule_id, rule_version, scope, about, audience_role, | |
| 84 | - course, evidence, confidence, created_at, expires_at, retain_until) | |
| 85 | -VALUES ('01920000-0000-7000-8000-000000000101', | |
| 86 | - '01920000-0000-7000-8000-000000000002', 'T4', 'T4.homework', 3, | |
| 87 | - '01920000-0000-7000-8000-00000000000a', | |
| 88 | - '01920000-0000-7000-8000-000000000001', 'teacher', | |
| 89 | - '01920000-0000-7000-8000-00000000000a', | |
| 90 | - '{"missing_rate":0.44,"cohort_median":0.18,"n":41}'::jsonb, | |
| 91 | - 'stable', 1776056400000, 1778648400000, 1783832400000); | |
| 92 | - | |
| 93 | --- Ogretmen kapatti. | |
| 94 | -UPDATE zeka_recommendation | |
| 95 | - SET dismissed_at = 1776142800000, | |
| 96 | - dismissed_by = '01920000-0000-7000-8000-000000000002', | |
| 97 | - dismiss_reason = 'ogrenci rapor verdi' | |
| 98 | - WHERE id = '01920000-0000-7000-8000-000000000101'; | |
| 99 | - | |
| 100 | --- Ertesi gece ayni kural yeniden uretildi. DOGRU yazim: catisma dogal anahtar | |
| 101 | --- uzerinde, ve SET listesi dismiss_* kolonlarini ICERMEZ. | |
| 102 | -INSERT INTO zeka_recommendation | |
| 103 | - (id, audience, product, rule_id, rule_version, scope, about, audience_role, | |
| 104 | - course, evidence, confidence, created_at, expires_at, retain_until) | |
| 105 | -VALUES ('01920000-0000-7000-8000-000000000102', | |
| 106 | - '01920000-0000-7000-8000-000000000002', 'T4', 'T4.homework', 3, | |
| 107 | - '01920000-0000-7000-8000-00000000000a', | |
| 108 | - '01920000-0000-7000-8000-000000000001', 'teacher', | |
| 109 | - '01920000-0000-7000-8000-00000000000a', | |
| 110 | - '{"missing_rate":0.46,"cohort_median":0.18,"n":43}'::jsonb, | |
| 111 | - 'stable', 1776142800000, 1778734800000, 1783918800000) | |
| 112 | -ON CONFLICT (audience, product, rule_id, about, scope) DO UPDATE SET | |
| 113 | - rule_version = EXCLUDED.rule_version, | |
| 114 | - evidence = EXCLUDED.evidence, | |
| 115 | - confidence = EXCLUDED.confidence, | |
| 116 | - created_at = EXCLUDED.created_at, | |
| 117 | - expires_at = EXCLUDED.expires_at, | |
| 118 | - retain_until = EXCLUDED.retain_until; | |
| 119 | - | |
| 120 | -INSERT INTO sonuc (ad, durum) | |
| 121 | -SELECT 'recommendation UPSERT tek satir birakti', | |
| 122 | - CASE WHEN count(*) = 1 THEN 'OK' ELSE 'DUSTU: ' || count(*) END | |
| 123 | - FROM zeka_recommendation; | |
| 124 | - | |
| 125 | -INSERT INTO sonuc (ad, durum) | |
| 126 | -SELECT 'kapatma izi gece yaziminda KORUNDU', | |
| 127 | - CASE WHEN dismissed_at = 1776142800000 | |
| 128 | - AND dismiss_reason = 'ogrenci rapor verdi' | |
| 129 | - THEN 'OK' ELSE 'DUSTU' END | |
| 130 | - FROM zeka_recommendation; | |
| 131 | - | |
| 132 | -INSERT INTO sonuc (ad, durum) | |
| 133 | -SELECT 'gece yazimi kaniti tazeledi', | |
| 134 | - CASE WHEN evidence->>'n' = '43' THEN 'OK' ELSE 'DUSTU' END | |
| 135 | - FROM zeka_recommendation; | |
| 136 | - | |
| 137 | - | |
| 138 | --- --------------------------------------------------------------------------- | |
| 139 | --- 3) run defteri + cocuk tablolari | |
| 140 | --- --------------------------------------------------------------------------- | |
| 141 | -INSERT INTO zeka_run (run_day, started_at, status, students_total, students_ok, | |
| 142 | - budget_ms, retain_until) | |
| 143 | -VALUES ('2026-04-13', 1776056400000, 'partial', 250, 231, 3600000, 1783832400000); | |
| 144 | - | |
| 145 | -INSERT INTO zeka_run_pending (run, student, ord) | |
| 146 | -VALUES ('2026-04-13', '01920000-0000-7000-8000-000000000001', 0); | |
| 147 | - | |
| 148 | -INSERT INTO zeka_run_failed_module (run, module, ord) | |
| 149 | -VALUES ('2026-04-13', 'submission', 0); | |
| 150 | -INSERT INTO sonuc (ad, durum) VALUES ('run + pending + failed_module', 'OK'); | |
| 151 | - | |
| 152 | - | |
| 153 | --- --------------------------------------------------------------------------- | |
| 154 | --- 4) question_segment: bilesik FK gercekten (exam, question) uyumunu zorluyor | |
| 155 | --- --------------------------------------------------------------------------- | |
| 156 | -INSERT INTO zeka_question_segment | |
| 157 | - (question, exam, course, subject, bilissel_talep, dikkat_tuzagi, okuma_yuku, | |
| 158 | - adim_sayisi, confidence_bilissel_talep, confidence_dikkat_tuzagi, | |
| 159 | - confidence_okuma_yuku, confidence_adim_sayisi, confidence, trap_choice, | |
| 160 | - rationale, model, prompt_version, variant, computed_at, retain_until) | |
| 161 | -VALUES ('01920000-0000-7000-8000-00000000000d', | |
| 162 | - '01920000-0000-7000-8000-00000000000c', | |
| 163 | - '01920000-0000-7000-8000-00000000000a', | |
| 164 | - '01920000-0000-7000-8000-00000000000b', | |
| 165 | - 'uygulama', 'var', 'dusuk', 'tek_adim', | |
| 166 | - 0.91, 0.78, 0.95, 0.61, 'stable', 'c', | |
| 167 | - 'Turev kurali dogrudan uygulanir; c sikki ussu carpan sanan ogrenciyi ceker.', | |
| 168 | - 'deepseek-v4-pro', 'v3', NULL, 1776056400000, 1783832400000); | |
| 169 | - | |
| 170 | -INSERT INTO zeka_question_segment_dimension (question, dimension, role, ord) VALUES | |
| 171 | - ('01920000-0000-7000-8000-00000000000d', 'bilissel_talep', 'downstream', 0), | |
| 172 | - ('01920000-0000-7000-8000-00000000000d', 'dikkat_tuzagi', 'downstream', 1), | |
| 173 | - ('01920000-0000-7000-8000-00000000000d', 'okuma_yuku', 'downstream', 2), | |
| 174 | - ('01920000-0000-7000-8000-00000000000d', 'adim_sayisi', 'experimental', 3); | |
| 175 | -INSERT INTO sonuc (ad, durum) VALUES ('question_segment + boyut ayrimi', 'OK'); | |
| 176 | - | |
| 177 | - | |
| 178 | --- --------------------------------------------------------------------------- | |
| 179 | --- 5) student_segment_profile: contrast ve sayac kisiti | |
| 180 | --- --------------------------------------------------------------------------- | |
| 181 | -INSERT INTO zeka_student_segment_profile | |
| 182 | - (student, dimension, label, n_answers, n_correct, accuracy, | |
| 183 | - overall_n_answers, overall_accuracy, contrast, confidence, | |
| 184 | - computed_at, retain_until) | |
| 185 | -VALUES ('01920000-0000-7000-8000-000000000001', 'bilissel_talep', 'analiz', | |
| 186 | - 86, 31, 0.3605, 412, 0.5825, -0.2220, 'stable', | |
| 187 | - 1776056400000, 1807592400000); | |
| 188 | -INSERT INTO sonuc (ad, durum) VALUES ('segment_profile (contrast -0.222)', 'OK'); | |
| 189 | - | |
| 190 | - | |
| 191 | --- =========================================================================== | |
| 192 | --- REDDEDILMESI GEREKENLER. | |
| 193 | --- | |
| 194 | --- Her sinav PL/pgSQL'in KENDI ic blogunu kullanir: `BEGIN ... EXCEPTION` zaten | |
| 195 | --- ortuk bir savepoint acar ve hata halinde YALNIZ o blogu geri alir. Acik | |
| 196 | --- SAVEPOINT/ROLLBACK kullanilmiyor: `ROLLBACK TO SAVEPOINT` sonucu yazan | |
| 197 | --- satiri da geri aliyordu ve yedi sinav rapora HIC ulasmiyordu. Rapor sekiz | |
| 198 | --- test gosterip "tamami gecti" diyordu -- yani testin kendisi sessizce | |
| 199 | --- kayboluyordu, tam da bu dosyanin yakalamak icin yazildigi hata sinifi. | |
| 200 | --- | |
| 201 | --- `kabul` degiskeni PL/pgSQL bellegindedir; geri alma onu etkilemez, sonuc | |
| 202 | --- satiri ic blok bittikten SONRA yazilir. | |
| 203 | --- | |
| 204 | --- Beklenen hata turu tek tek yazilir (`check_violation` gibi). Baska bir hata | |
| 205 | --- gelirse yakalanmaz, yukari firlar ve betigi durdurur -- yani "dogru sebeple | |
| 206 | --- mi reddedildi" sorusu da sinaniyor. | |
| 207 | --- =========================================================================== | |
| 208 | - | |
| 209 | --- (a) Bilinmeyen guven kademesi | |
| 210 | -DO $$ | |
| 211 | -DECLARE kabul boolean := false; | |
| 212 | -BEGIN | |
| 213 | - BEGIN | |
| 214 | - INSERT INTO zeka_student_summary (student, confidence, computed_at, retain_until) | |
| 215 | - VALUES ('01920000-0000-7000-8000-000000000002', 'cok_iyi', 1, 2); | |
| 216 | - kabul := true; | |
| 217 | - EXCEPTION WHEN check_violation THEN kabul := false; | |
| 218 | - END; | |
| 219 | - INSERT INTO sonuc (ad, durum) VALUES ('gecersiz confidence reddedildi', | |
| 220 | - CASE WHEN kabul THEN 'DUSTU: kabul etti' ELSE 'OK' END); | |
| 221 | -END $$; | |
| 222 | - | |
| 223 | --- (b) Bilinmeyen bilissel etiket | |
| 224 | -DO $$ | |
| 225 | -DECLARE kabul boolean := false; | |
| 226 | -BEGIN | |
| 227 | - BEGIN | |
| 228 | - INSERT INTO zeka_question_segment | |
| 229 | - (question, exam, course, subject, bilissel_talep, dikkat_tuzagi, okuma_yuku, | |
| 230 | - adim_sayisi, confidence_bilissel_talep, confidence_dikkat_tuzagi, | |
| 231 | - confidence_okuma_yuku, confidence_adim_sayisi, confidence, rationale, | |
| 232 | - model, prompt_version, computed_at, retain_until) | |
| 233 | - VALUES ('01920000-0000-7000-8000-00000000000d','01920000-0000-7000-8000-00000000000c', | |
| 234 | - '01920000-0000-7000-8000-00000000000a','01920000-0000-7000-8000-00000000000b', | |
| 235 | - 'sentez','var','dusuk','tek_adim',1,1,1,1,'stable','x','m','v',1,2); | |
| 236 | - kabul := true; | |
| 237 | - EXCEPTION WHEN check_violation THEN kabul := false; | |
| 238 | - END; | |
| 239 | - INSERT INTO sonuc (ad, durum) VALUES ('gecersiz bilissel_talep reddedildi', | |
| 240 | - CASE WHEN kabul THEN 'DUSTU: kabul etti' ELSE 'OK' END); | |
| 241 | -END $$; | |
| 242 | - | |
| 243 | --- (c) Soru DENEME 1'e ait, segment satiri DENEME 2 diyor. Bilesik FK | |
| 244 | --- (exam, question) -> exam_question (exam, id) bunu yakalamali. | |
| 245 | --- Henuz segmentlenmemis IKINCI bir soru kullanilir: ilki kullanilsaydi | |
| 246 | --- tekil anahtar once atesler, bilesik FK hic sinanmamis olurdu. | |
| 247 | -DO $$ | |
| 248 | -DECLARE | |
| 249 | - kabul boolean := false; | |
| 250 | - baska_sinav uuid := '01920000-0000-7000-8000-0000000000ff'; | |
| 251 | - ikinci_soru uuid := '01920000-0000-7000-8000-00000000000e'; | |
| 252 | -BEGIN | |
| 253 | - BEGIN | |
| 254 | - INSERT INTO exam (id, creator, course, title, description, kind) | |
| 255 | - VALUES (baska_sinav, '01920000-0000-7000-8000-000000000002', | |
| 256 | - '01920000-0000-7000-8000-00000000000a', 'Deneme 2', '', 'quiz'); | |
| 257 | - INSERT INTO exam_question (id, exam, text, kind, points, subject) | |
| 258 | - VALUES (ikinci_soru, '01920000-0000-7000-8000-00000000000c', | |
| 259 | - 'Ikinci soru', 'multiple_choice', 5, | |
| 260 | - '01920000-0000-7000-8000-00000000000b'); | |
| 261 | - INSERT INTO zeka_question_segment | |
| 262 | - (question, exam, course, subject, bilissel_talep, dikkat_tuzagi, okuma_yuku, | |
| 263 | - adim_sayisi, confidence_bilissel_talep, confidence_dikkat_tuzagi, | |
| 264 | - confidence_okuma_yuku, confidence_adim_sayisi, confidence, rationale, | |
| 265 | - model, prompt_version, computed_at, retain_until) | |
| 266 | - VALUES (ikinci_soru, baska_sinav, | |
| 267 | - '01920000-0000-7000-8000-00000000000a','01920000-0000-7000-8000-00000000000b', | |
| 268 | - 'analiz','yok','dusuk','tek_adim',1,1,1,1,'stable','x','m','v',1,2); | |
| 269 | - kabul := true; | |
| 270 | - EXCEPTION WHEN foreign_key_violation THEN kabul := false; | |
| 271 | - END; | |
| 272 | - INSERT INTO sonuc (ad, durum) VALUES ('(exam,question) uyumsuzlugu reddedildi', | |
| 273 | - CASE WHEN kabul THEN 'DUSTU: kabul etti' ELSE 'OK' END); | |
| 274 | -END $$; | |
| 275 | - | |
| 276 | --- (d) n_correct > n_answers: sayma hatasi | |
| 277 | -DO $$ | |
| 278 | -DECLARE kabul boolean := false; | |
| 279 | -BEGIN | |
| 280 | - BEGIN | |
| 281 | - INSERT INTO zeka_student_segment_profile | |
| 282 | - (student, dimension, label, n_answers, n_correct, accuracy, | |
| 283 | - overall_n_answers, overall_accuracy, contrast, confidence, computed_at, retain_until) | |
| 284 | - VALUES ('01920000-0000-7000-8000-000000000001','okuma_yuku','yuksek', | |
| 285 | - 10, 11, 1.0, 412, 0.58, 0.42, 'stable', 1, 2); | |
| 286 | - kabul := true; | |
| 287 | - EXCEPTION WHEN check_violation THEN kabul := false; | |
| 288 | - END; | |
| 289 | - INSERT INTO sonuc (ad, durum) VALUES ('n_correct > n_answers reddedildi', | |
| 290 | - CASE WHEN kabul THEN 'DUSTU: kabul etti' ELSE 'OK' END); | |
| 291 | -END $$; | |
| 292 | - | |
| 293 | --- (e) Ayni ogrenciye IKINCI bir ders-bagimsiz 'homework' maddesi. | |
| 294 | --- Iki NULL normalde birbirinden farkli sayilir; NULLS NOT DISTINCT | |
| 295 | --- olmasaydi bu GECERDI ve dikkat listesi cogalirdi. | |
| 296 | -DO $$ | |
| 297 | -DECLARE kabul boolean := false; | |
| 298 | -BEGIN | |
| 299 | - BEGIN | |
| 300 | - INSERT INTO zeka_attention_item | |
| 301 | - (student, trigger, course, fact, window_from, window_to, evidence, ord) | |
| 302 | - VALUES ('01920000-0000-7000-8000-000000000001', 'homework', NULL, | |
| 303 | - 'ikinci madde', 1, 2, '{"x":1}'::jsonb, 2); | |
| 304 | - kabul := true; | |
| 305 | - EXCEPTION WHEN unique_violation THEN kabul := false; | |
| 306 | - END; | |
| 307 | - INSERT INTO sonuc (ad, durum) VALUES ('mukerrer (course NULL) madde reddedildi', | |
| 308 | - CASE WHEN kabul THEN 'DUSTU: kabul etti' ELSE 'OK' END); | |
| 309 | -END $$; | |
| 310 | - | |
| 311 | --- (f) Olmayan ogrenci | |
| 312 | -DO $$ | |
| 313 | -DECLARE kabul boolean := false; | |
| 314 | -BEGIN | |
| 315 | - BEGIN | |
| 316 | - INSERT INTO zeka_student_summary (student, confidence, computed_at, retain_until) | |
| 317 | - VALUES ('01920000-0000-7000-8000-0000000000ee', 'stable', 1, 2); | |
| 318 | - kabul := true; | |
| 319 | - EXCEPTION WHEN foreign_key_violation THEN kabul := false; | |
| 320 | - END; | |
| 321 | - INSERT INTO sonuc (ad, durum) VALUES ('olmayan ogrenci reddedildi', | |
| 322 | - CASE WHEN kabul THEN 'DUSTU: kabul etti' ELSE 'OK' END); | |
| 323 | -END $$; | |
| 324 | - | |
| 325 | --- (g) Gecersiz gun bicimi | |
| 326 | -DO $$ | |
| 327 | -DECLARE kabul boolean := false; | |
| 328 | -BEGIN | |
| 329 | - BEGIN | |
| 330 | - INSERT INTO zeka_run (run_day, started_at, status, budget_ms, retain_until) | |
| 331 | - VALUES ('13.04.2026', 1, 'ok', 1, 2); | |
| 332 | - kabul := true; | |
| 333 | - EXCEPTION WHEN check_violation THEN kabul := false; | |
| 334 | - END; | |
| 335 | - INSERT INTO sonuc (ad, durum) VALUES ('gecersiz run_day reddedildi', | |
| 336 | - CASE WHEN kabul THEN 'DUSTU: kabul etti' ELSE 'OK' END); | |
| 337 | -END $$; | |
| 338 | - | |
| 339 | --- (h) Kanitsiz tavsiye. "Aciklanamayan tavsiye gosterilmez" kuralinin | |
| 340 | --- semadaki karsiligi: evidence NOT NULL. | |
| 341 | -DO $$ | |
| 342 | -DECLARE kabul boolean := false; | |
| 343 | -BEGIN | |
| 344 | - BEGIN | |
| 345 | - INSERT INTO zeka_recommendation | |
| 346 | - (id, audience, product, rule_id, rule_version, audience_role, | |
| 347 | - evidence, confidence, created_at, expires_at, retain_until) | |
| 348 | - VALUES ('01920000-0000-7000-8000-000000000103', | |
| 349 | - '01920000-0000-7000-8000-000000000001', 'O1', 'O1.kanitsiz', 1, | |
| 350 | - 'student', NULL, 'stable', 1, 2, 3); | |
| 351 | - kabul := true; | |
| 352 | - EXCEPTION WHEN not_null_violation THEN kabul := false; | |
| 353 | - END; | |
| 354 | - INSERT INTO sonuc (ad, durum) VALUES ('kanitsiz tavsiye reddedildi', | |
| 355 | - CASE WHEN kabul THEN 'DUSTU: kabul etti' ELSE 'OK' END); | |
| 356 | -END $$; | |
| 357 | - | |
| 358 | --- (i) contrast araligi disi: accuracy - overall_accuracy en fazla 1 olabilir. | |
| 359 | -DO $$ | |
| 360 | -DECLARE kabul boolean := false; | |
| 361 | -BEGIN | |
| 362 | - BEGIN | |
| 363 | - INSERT INTO zeka_student_segment_profile | |
| 364 | - (student, dimension, label, n_answers, n_correct, accuracy, | |
| 365 | - overall_n_answers, overall_accuracy, contrast, confidence, computed_at, retain_until) | |
| 366 | - VALUES ('01920000-0000-7000-8000-000000000001','dikkat_tuzagi','var', | |
| 367 | - 10, 8, 0.8, 412, 0.58, 1.9, 'stable', 1, 2); | |
| 368 | - kabul := true; | |
| 369 | - EXCEPTION WHEN check_violation THEN kabul := false; | |
| 370 | - END; | |
| 371 | - INSERT INTO sonuc (ad, durum) VALUES ('contrast araligi disi reddedildi', | |
| 372 | - CASE WHEN kabul THEN 'DUSTU: kabul etti' ELSE 'OK' END); | |
| 373 | -END $$; | |
| 374 | - | |
| 375 | --- (j) Deneysel boyut ogrenci profiline SIZAMAZ: `adim_sayisi` yalnizca | |
| 376 | --- question_segment'te etiketlenir ve hicbir ogrenciye baglanmaz. Bu, bir | |
| 377 | --- olcum kararinin (0,607 kararlilik, uretime alinmadi) semadaki karsiligi. | |
| 378 | -DO $$ | |
| 379 | -DECLARE kabul boolean := false; | |
| 380 | -BEGIN | |
| 381 | - BEGIN | |
| 382 | - INSERT INTO zeka_student_segment_profile | |
| 383 | - (student, dimension, label, n_answers, n_correct, accuracy, | |
| 384 | - overall_n_answers, overall_accuracy, contrast, confidence, computed_at, retain_until) | |
| 385 | - VALUES ('01920000-0000-7000-8000-000000000001','adim_sayisi','cok_adim', | |
| 386 | - 10, 8, 0.8, 412, 0.58, 0.22, 'stable', 1, 2); | |
| 387 | - kabul := true; | |
| 388 | - EXCEPTION WHEN check_violation THEN kabul := false; | |
| 389 | - END; | |
| 390 | - INSERT INTO sonuc (ad, durum) VALUES ('deneysel boyut profile sizamadi', | |
| 391 | - CASE WHEN kabul THEN 'DUSTU: kabul etti' ELSE 'OK' END); | |
| 392 | -END $$; | |
| 393 | - | |
| 394 | --- (k) AYNI ogretmen, AYNI kural, FARKLI iki ogrenci -> IKI satir. | |
| 395 | --- Dogal anahtar `about` tasimasaydi ikisi tek satira coker, ogretmen bir | |
| 396 | --- ogrenci gorur, digeri hicbir hata vermeden kaybolurdu. SurrealDB surumu | |
| 397 | --- tam boyle davraniyordu: olculdu, bes ogrenci -> bir anahtar. | |
| 398 | -INSERT INTO zeka_recommendation | |
| 399 | - (id, audience, product, rule_id, rule_version, scope, about, audience_role, | |
| 400 | - course, evidence, confidence, created_at, expires_at, retain_until) | |
| 401 | -VALUES | |
| 402 | - ('01920000-0000-7000-8000-000000000201', | |
| 403 | - '01920000-0000-7000-8000-000000000002', 'T4', 'T4.attendance', 3, | |
| 404 | - '01920000-0000-7000-8000-00000000000a', | |
| 405 | - '01920000-0000-7000-8000-000000000001', 'teacher', NULL, | |
| 406 | - '{"n":1}'::jsonb, 'stable', 1, 2, 3), | |
| 407 | - ('01920000-0000-7000-8000-000000000202', | |
| 408 | - '01920000-0000-7000-8000-000000000002', 'T4', 'T4.attendance', 3, | |
| 409 | - '01920000-0000-7000-8000-00000000000a', | |
| 410 | - '01920000-0000-7000-8000-000000000002', 'teacher', NULL, | |
| 411 | - '{"n":2}'::jsonb, 'stable', 1, 2, 3); | |
| 412 | - | |
| 413 | -INSERT INTO sonuc (ad, durum) | |
| 414 | -SELECT 'ayni kural iki ogrenci icin IKI satir', | |
| 415 | - CASE WHEN count(*) = 2 THEN 'OK' ELSE 'DUSTU: ' || count(*) END | |
| 416 | - FROM zeka_recommendation WHERE rule_id = 'T4.attendance'; | |
| 417 | - | |
| 418 | - | |
| 419 | --- --------------------------------------------------------------------------- | |
| 420 | --- Rapor | |
| 421 | --- --------------------------------------------------------------------------- | |
| 422 | -\echo '' | |
| 423 | -\echo '== davranis sinavi' | |
| 424 | -\pset tuples_only on | |
| 425 | -\pset format unaligned | |
| 426 | -SELECT lpad(sira::text, 2) || '. ' || rpad(ad, 50) || ' ' || durum FROM sonuc ORDER BY sira; | |
| 427 | -\pset tuples_only off | |
| 428 | -\pset format aligned | |
| 429 | - | |
| 430 | -\echo '' | |
| 431 | -DO $$ | |
| 432 | -DECLARE d int; | |
| 433 | -BEGIN | |
| 434 | - SELECT count(*) INTO d FROM sonuc WHERE durum <> 'OK'; | |
| 435 | - IF d > 0 THEN RAISE EXCEPTION '% adet davranis testi dustu', d; END IF; | |
| 436 | - RAISE NOTICE 'davranis sinavi: % testin tamami gecti', (SELECT count(*) FROM sonuc); | |
| 437 | -END $$; | |
| 438 | - | |
| 439 | -ROLLBACK; |
tools/check_pg_schema.shdeleted+0 -103
| @@ -1,103 +0,0 @@ | ||
| 1 | -#!/usr/bin/env bash | |
| 2 | -# Applies the backend's own school+control migrations AND ZEKA's migration to a | |
| 3 | -# throwaway Postgres, then asserts the result. | |
| 4 | -# | |
| 5 | -# TOUCHES NOTHING LIVE. It creates its own database, applies files read-only, | |
| 6 | -# and drops the database at the end. No backend file is written. | |
| 7 | -# | |
| 8 | -# Why it exists: a migration that is only read looks fine. The SurrealDB | |
| 9 | -# version of this schema passed review twice and still dropped five fields | |
| 10 | -# silently, because `FLEXIBLE TYPE object` parses as garbage and SCHEMAFULL | |
| 11 | -# discards undefined fields without a word. The only defence is running it. | |
| 12 | -# | |
| 13 | -# tools/check_pg_schema.sh | |
| 14 | -# | |
| 15 | -# Env: HEZARFEN_PG_CONTAINER (default zeka_pg_test), BACKEND (path to the new | |
| 16 | -# backend checkout). | |
| 17 | -set -euo pipefail | |
| 18 | - | |
| 19 | -CONTAINER="${HEZARFEN_PG_CONTAINER:-zeka_pg_test}" | |
| 20 | -DB="${HEZARFEN_CHECK_DB:-zeka_schema_check}" | |
| 21 | -HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" | |
| 22 | -BACKEND="${BACKEND:-$HERE/../hezarfen_backend-main-yeni/hezarfen_backend-main}" | |
| 23 | - | |
| 24 | -psql() { podman exec -i "$CONTAINER" psql -U hezarfen -v ON_ERROR_STOP=1 "$@"; } | |
| 25 | - | |
| 26 | -echo "== backend: $BACKEND" | |
| 27 | -[ -d "$BACKEND/migrations/school" ] || { echo "!! migrations/school yok"; exit 1; } | |
| 28 | - | |
| 29 | -psql -d postgres -q <<SQL | |
| 30 | -DROP DATABASE IF EXISTS $DB; | |
| 31 | -CREATE DATABASE $DB; | |
| 32 | -SQL | |
| 33 | - | |
| 34 | -for file in "$BACKEND"/migrations/control/*.sql "$BACKEND"/migrations/school/*.sql; do | |
| 35 | - echo "== backend $(basename "$file")" | |
| 36 | - psql -d "$DB" -q -f - < "$file" | |
| 37 | -done | |
| 38 | - | |
| 39 | -# ZEKA'nin migration'i backend deposuna da KOPYALANDI (orasi artik gercek | |
| 40 | -# evi). Ayni dosyayi iki kez uygulamak "relation already exists" verir, o | |
| 41 | -# yuzden backend'de ayni adla bir dosya varsa burada atlanir. Bu bir susturma | |
| 42 | -# degil: backend'deki kopyanin uygulandigi zaten yukaridaki dongude yaziyor. | |
| 43 | -for file in "$HERE"/service/schema/postgres/school/*.sql; do | |
| 44 | - ad="$(basename "$file")" | |
| 45 | - if [ -f "$BACKEND/migrations/school/$ad" ]; then | |
| 46 | - echo "== ZEKA $ad (backend kopyasi uygulandi, atlandi)" | |
| 47 | - continue | |
| 48 | - fi | |
| 49 | - echo "== ZEKA $ad" | |
| 50 | - psql -d "$DB" -q -f - < "$file" | |
| 51 | -done | |
| 52 | - | |
| 53 | -echo | |
| 54 | -echo "== zeka_* tablolari" | |
| 55 | -psql -d "$DB" -tAc " | |
| 56 | -SELECT c.relname || ' (' || count(a.attname) || ' kolon)' | |
| 57 | -FROM pg_class c | |
| 58 | -JOIN pg_namespace n ON n.oid = c.relnamespace AND n.nspname = 'public' | |
| 59 | -LEFT JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum > 0 AND NOT a.attisdropped | |
| 60 | -WHERE c.relkind = 'r' AND c.relname LIKE 'zeka\\_%' | |
| 61 | -GROUP BY c.relname ORDER BY c.relname;" | |
| 62 | - | |
| 63 | -echo | |
| 64 | -echo "== disa giden yabanci anahtarlar (ZEKA -> okul)" | |
| 65 | -psql -d "$DB" -tAc " | |
| 66 | -SELECT src.relname || '.' || con.conname || ' -> ' || tgt.relname | |
| 67 | -FROM pg_constraint con | |
| 68 | -JOIN pg_class src ON src.oid = con.conrelid | |
| 69 | -JOIN pg_class tgt ON tgt.oid = con.confrelid | |
| 70 | -WHERE con.contype = 'f' AND src.relname LIKE 'zeka\\_%' | |
| 71 | - AND tgt.relname NOT LIKE 'zeka\\_%' | |
| 72 | -ORDER BY 1;" | |
| 73 | - | |
| 74 | -echo | |
| 75 | -echo "== ZEKA okul tablolarina yaziyor mu? (ters yonlu FK olmamali)" | |
| 76 | -ters=$(psql -d "$DB" -tAc " | |
| 77 | -SELECT count(*) FROM pg_constraint con | |
| 78 | -JOIN pg_class src ON src.oid = con.conrelid | |
| 79 | -JOIN pg_class tgt ON tgt.oid = con.confrelid | |
| 80 | -WHERE con.contype = 'f' AND src.relname NOT LIKE 'zeka\\_%' | |
| 81 | - AND tgt.relname LIKE 'zeka\\_%';") | |
| 82 | -if [ "$ters" != "0" ]; then echo "!! $ters adet ters FK — okul semasi ZEKA'ya bagimli olmus"; exit 1; fi | |
| 83 | -echo " yok (0) — okul semasi ZEKA'dan bagimsiz kaldi" | |
| 84 | - | |
| 85 | -echo | |
| 86 | -echo "== ad cakismasi (DISJOINTNESS)" | |
| 87 | -cak=$(psql -d "$DB" -tAc " | |
| 88 | -SELECT count(*) FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace | |
| 89 | -WHERE n.nspname='public' AND c.relkind='r' AND c.relname LIKE 'zeka\\_%' | |
| 90 | - AND c.relname IN ('app_user','course','subject','exam','exam_question');") | |
| 91 | -[ "$cak" = "0" ] && echo " yok (0)" | |
| 92 | - | |
| 93 | -echo | |
| 94 | -echo "== toplam tablo" | |
| 95 | -psql -d "$DB" -tAc "SELECT count(*) FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace WHERE n.nspname='public' AND c.relkind='r';" | |
| 96 | - | |
| 97 | -# Semanin YUKLENMESI ile CALISMASI ayri seyler. Asagisi gercek sekilli satirlar | |
| 98 | -# yazar ve reddedilmesi gerekenlerin reddedildigini kanitlar; duserse betik de | |
| 99 | -# duser (ON_ERROR_STOP). | |
| 100 | -psql -d "$DB" -f - < "$HERE"/tools/check_pg_rows.sql | |
| 101 | - | |
| 102 | -psql -d postgres -q -c "DROP DATABASE $DB;" | |
| 103 | -echo "== $DB dusuruldu. Canliya dokunulmadi." |
tools/indexes.surqldeleted+0 -83
| @@ -1,83 +0,0 @@ | ||
| 1 | -DEFINE INDEX IF NOT EXISTS user_username ON user FIELDS username UNIQUE; | |
| 2 | -DEFINE INDEX IF NOT EXISTS session_token ON session FIELDS token UNIQUE; | |
| 3 | -DEFINE INDEX IF NOT EXISTS session_expires ON session FIELDS expires_at; | |
| 4 | -DEFINE INDEX IF NOT EXISTS note_user ON note FIELDS user; | |
| 5 | -DEFINE INDEX IF NOT EXISTS message_sender ON message FIELDS sender; | |
| 6 | -DEFINE INDEX IF NOT EXISTS message_recipient ON message FIELDS recipient; | |
| 7 | -DEFINE INDEX IF NOT EXISTS board_creator ON board FIELDS creator; | |
| 8 | -DEFINE INDEX IF NOT EXISTS board_participants ON board FIELDS participants; | |
| 9 | -DEFINE INDEX IF NOT EXISTS board_stroke_board_epoch ON board_stroke FIELDS board, epoch; | |
| 10 | -DEFINE INDEX IF NOT EXISTS board_stroke_board_kind ON board_stroke FIELDS board, kind; | |
| 11 | -DEFINE INDEX IF NOT EXISTS note_file_note ON note_file FIELDS note; | |
| 12 | -DEFINE INDEX IF NOT EXISTS course_note_course ON course_note FIELDS course; | |
| 13 | -DEFINE INDEX IF NOT EXISTS course_note_file_note ON course_note_file FIELDS course_note; | |
| 14 | -DEFINE INDEX IF NOT EXISTS rag_output_note ON rag_output FIELDS course_note; | |
| 15 | -DEFINE INDEX IF NOT EXISTS rag_output_source ON rag_output FIELDS sources; | |
| 16 | -DEFINE INDEX IF NOT EXISTS chatbot_thread_user_updated ON chatbot_thread FIELDS user_id, updated_at; | |
| 17 | -DEFINE INDEX IF NOT EXISTS chatbot_message_thread_created ON chatbot_message FIELDS thread_id, created_at; | |
| 18 | -DEFINE INDEX IF NOT EXISTS chatbot_message_user ON chatbot_message FIELDS user_id; | |
| 19 | -DEFINE INDEX IF NOT EXISTS chatbot_message_status_created ON chatbot_message FIELDS status, created_at; | |
| 20 | -DEFINE INDEX IF NOT EXISTS attendance_event_user ON attendance FIELDS event, user UNIQUE; | |
| 21 | -DEFINE INDEX IF NOT EXISTS attendance_user ON attendance FIELDS user; | |
| 22 | -DEFINE INDEX IF NOT EXISTS registration_event_user ON registration FIELDS event, user UNIQUE; | |
| 23 | -DEFINE INDEX IF NOT EXISTS registration_event ON registration FIELDS event; | |
| 24 | -DEFINE INDEX IF NOT EXISTS subject_course ON subject FIELDS course; | |
| 25 | -DEFINE INDEX IF NOT EXISTS class_group_grade ON class_group FIELDS grade; | |
| 26 | -DEFINE INDEX IF NOT EXISTS class_member_class_user ON class_member FIELDS class, user UNIQUE; | |
| 27 | -DEFINE INDEX IF NOT EXISTS class_member_class ON class_member FIELDS class; | |
| 28 | -DEFINE INDEX IF NOT EXISTS class_member_user ON class_member FIELDS user; | |
| 29 | -DEFINE INDEX IF NOT EXISTS class_course_class_course ON class_course FIELDS class, course UNIQUE; | |
| 30 | -DEFINE INDEX IF NOT EXISTS class_course_class ON class_course FIELDS class; | |
| 31 | -DEFINE INDEX IF NOT EXISTS class_course_course ON class_course FIELDS course; | |
| 32 | -DEFINE INDEX IF NOT EXISTS enrollment_course_user ON enrollment FIELDS course, user UNIQUE; | |
| 33 | -DEFINE INDEX IF NOT EXISTS enrollment_user ON enrollment FIELDS user; | |
| 34 | -DEFINE INDEX IF NOT EXISTS parent_link_parent_student ON parent_link FIELDS parent, student UNIQUE; | |
| 35 | -DEFINE INDEX IF NOT EXISTS parent_link_parent ON parent_link FIELDS parent; | |
| 36 | -DEFINE INDEX IF NOT EXISTS parent_link_student ON parent_link FIELDS student; | |
| 37 | -DEFINE INDEX IF NOT EXISTS course_session_course ON course_session FIELDS course; | |
| 38 | -DEFINE INDEX IF NOT EXISTS session_attendance_session_user ON session_attendance FIELDS session, user UNIQUE; | |
| 39 | -DEFINE INDEX IF NOT EXISTS session_attendance_session ON session_attendance FIELDS session; | |
| 40 | -DEFINE INDEX IF NOT EXISTS session_attendance_user ON session_attendance FIELDS user; | |
| 41 | -DEFINE INDEX IF NOT EXISTS session_attendance_course ON session_attendance FIELDS course; | |
| 42 | -DEFINE INDEX IF NOT EXISTS work_entry_user ON work_entry FIELDS user; | |
| 43 | -DEFINE INDEX IF NOT EXISTS pomodoro_session_user ON pomodoro_session FIELDS user; | |
| 44 | -DEFINE INDEX IF NOT EXISTS exam_course ON exam FIELDS course; | |
| 45 | -DEFINE INDEX IF NOT EXISTS exam_attempt_exam_user_seq ON exam_attempt FIELDS exam, user, seq UNIQUE; | |
| 46 | -DEFINE INDEX IF NOT EXISTS exam_attempt_exam ON exam_attempt FIELDS exam; | |
| 47 | -DEFINE INDEX IF NOT EXISTS exam_question_exam ON exam_question FIELDS exam; | |
| 48 | -DEFINE INDEX IF NOT EXISTS exam_question_subject ON exam_question FIELDS subject; | |
| 49 | -DEFINE INDEX IF NOT EXISTS question_image_exam ON question_image FIELDS exam; | |
| 50 | -DEFINE INDEX IF NOT EXISTS question_image_question ON question_image FIELDS question; | |
| 51 | -DEFINE INDEX IF NOT EXISTS bank_question_owner ON bank_question FIELDS owner; | |
| 52 | -DEFINE INDEX IF NOT EXISTS bank_question_subject ON bank_question FIELDS subject; | |
| 53 | -DEFINE INDEX IF NOT EXISTS bank_question_image_question ON bank_question_image FIELDS bank_question; | |
| 54 | -DEFINE INDEX IF NOT EXISTS exam_answer_question_user_seq ON exam_answer FIELDS question, user, seq UNIQUE; | |
| 55 | -DEFINE INDEX IF NOT EXISTS exam_answer_exam_user ON exam_answer FIELDS exam, user; | |
| 56 | -DEFINE INDEX IF NOT EXISTS exam_answer_exam ON exam_answer FIELDS exam; | |
| 57 | -DEFINE INDEX IF NOT EXISTS answer_image_exam ON answer_image FIELDS exam; | |
| 58 | -DEFINE INDEX IF NOT EXISTS answer_image_user ON answer_image FIELDS user; | |
| 59 | -DEFINE INDEX IF NOT EXISTS exam_result_exam_user_seq ON exam_result FIELDS exam, user, seq UNIQUE; | |
| 60 | -DEFINE INDEX IF NOT EXISTS pool_question_status ON pool_question FIELDS status; | |
| 61 | -DEFINE INDEX IF NOT EXISTS pool_question_asker ON pool_question FIELDS asker; | |
| 62 | -DEFINE INDEX IF NOT EXISTS solution_question ON solution FIELDS question; | |
| 63 | -DEFINE INDEX IF NOT EXISTS homework_course ON homework FIELDS course; | |
| 64 | -DEFINE INDEX IF NOT EXISTS homework_submission_homework ON homework_submission FIELDS homework; | |
| 65 | -DEFINE INDEX IF NOT EXISTS homework_file_submission ON homework_file FIELDS submission; | |
| 66 | -DEFINE INDEX IF NOT EXISTS homework_result_homework ON homework_result FIELDS homework; | |
| 67 | -DEFINE INDEX IF NOT EXISTS appointment_slot_teacher_starts ON appointment_slot FIELDS teacher, starts_at; | |
| 68 | -DEFINE INDEX IF NOT EXISTS appointment_slot_series ON appointment_slot FIELDS series; | |
| 69 | -DEFINE INDEX IF NOT EXISTS appointment_slot_ref ON appointment FIELDS slot; | |
| 70 | -DEFINE INDEX IF NOT EXISTS appointment_requester ON appointment FIELDS requester; | |
| 71 | -DEFINE INDEX IF NOT EXISTS appointment_status ON appointment FIELDS status; | |
| 72 | -DEFINE INDEX IF NOT EXISTS menu_date_slot ON menu FIELDS date, slot UNIQUE; | |
| 73 | -DEFINE INDEX IF NOT EXISTS menu_dish_menu ON menu_dish FIELDS menu; | |
| 74 | -DEFINE INDEX IF NOT EXISTS dietary_profile_student ON dietary_profile FIELDS student UNIQUE; | |
| 75 | -DEFINE INDEX IF NOT EXISTS meal_booking_menu ON meal_booking FIELDS menu; | |
| 76 | -DEFINE INDEX IF NOT EXISTS meal_booking_student ON meal_booking FIELDS student; | |
| 77 | -DEFINE INDEX IF NOT EXISTS meal_attendance_menu_student ON meal_attendance FIELDS menu, student UNIQUE; | |
| 78 | -DEFINE INDEX IF NOT EXISTS meal_ledger_student ON meal_ledger FIELDS student; | |
| 79 | -DEFINE INDEX IF NOT EXISTS fee_plan_assignment_plan ON fee_plan_assignment FIELDS plan; | |
| 80 | -DEFINE INDEX IF NOT EXISTS fee_plan_assignment_student ON fee_plan_assignment FIELDS student; | |
| 81 | -DEFINE INDEX IF NOT EXISTS payment_ledger_student ON payment_ledger FIELDS student; | |
| 82 | -DEFINE INDEX IF NOT EXISTS payment_ledger_source ON payment_ledger FIELDS source; | |
| 83 | -DEFINE INDEX IF NOT EXISTS badge_award_user ON badge_award FIELDS user; |
tools/load_pg_seed.shdeleted+0 -88
| @@ -1,88 +0,0 @@ | ||
| 1 | -#!/usr/bin/env bash | |
| 2 | -# DEMO tohumunu yeni (PostgreSQL) backend'e yukler. | |
| 3 | -# | |
| 4 | -# Ne yapar: | |
| 5 | -# 1. Okul veritabanini backend'in KENDI adlandirma kuraliyla kurar | |
| 6 | -# (`tenant::school_db_name` -> "{control}_school_{uuid.simple}") | |
| 7 | -# 2. Backend'in `migrations/school` semasini + ZEKA'nin migration'ini uygular | |
| 8 | -# 3. `pg_school.sql`'i doker | |
| 9 | -# 4. Control veritabanina okul kaydini ve kisi satirlarini yazar | |
| 10 | -# | |
| 11 | -# Neden bu sira: okul veritabaninin ADI okulun uuid'sinden tureniyor, slug'dan | |
| 12 | -# degil. Yani uuid onceden bilinmek zorunda; tohum onu sabitliyor | |
| 13 | -# (`generator/pg_map.DEMO_SCHOOL_ID`). Control satiri EN SONA birakiliyor: | |
| 14 | -# backend acilir acilmaz okulu `active` gorup istek kabul etmeye baslar, o | |
| 15 | -# yuzden okul verisi hazir olmadan kaydi yazmak yarim bir okul acmak olurdu. | |
| 16 | -# | |
| 17 | -# Tohumu iki kez yuklemek: her iki dosya da tek transaction'da kosar ve | |
| 18 | -# birincil anahtarlar deterministiktir, yani ikinci yukleme catisma verir ve | |
| 19 | -# HICBIR SEY yazmaz. Yeniden yuklemek icin veritabanini dusurmek gerekir. | |
| 20 | -# | |
| 21 | -# tools/load_pg_seed.sh /yol/pgseed | |
| 22 | -# | |
| 23 | -# Ortam: | |
| 24 | -# PGC psql'i kosturan komut (varsayilan: podman exec -i <konteyner> psql) | |
| 25 | -# CONTROL_DB control veritabani adi (varsayilan hezarfen_control) | |
| 26 | -# BACKEND yeni backend checkout'u | |
| 27 | -set -euo pipefail | |
| 28 | - | |
| 29 | -SEED_DIR="${1:-}" | |
| 30 | -[ -n "$SEED_DIR" ] || { echo "kullanim: $0 <tohum-dizini>"; exit 1; } | |
| 31 | - | |
| 32 | -# Canlida konteyner adi `hezarfen_backend_postgres`, kullanici ve control | |
| 33 | -# veritabani adi `hezarfen_backend.env` icindeki POSTGRES_USER / POSTGRES_DB | |
| 34 | -# ile ayni olmali. Uctaki degerler gelistirme icindir. | |
| 35 | -CONTAINER="${HEZARFEN_PG_CONTAINER:-zeka_pg}" | |
| 36 | -PGUSER_="${POSTGRES_USER:-hezarfen}" | |
| 37 | -CONTROL_DB="${CONTROL_DB:-${POSTGRES_DB:-hezarfen_control}}" | |
| 38 | -HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" | |
| 39 | -BACKEND="${BACKEND:-$HERE/../hezarfen_backend-main-yeni/hezarfen_backend-main}" | |
| 40 | - | |
| 41 | -# Tohumun sabitledigi okul kimligi — tek kaynak `generator/pg_map.py`. | |
| 42 | -SCHOOL_ID="$(cd "$HERE/generator" && python -c "import pg_map;print(pg_map.DEMO_SCHOOL_ID)")" | |
| 43 | -SCHOOL_DB="${CONTROL_DB}_school_$(echo "$SCHOOL_ID" | tr -d '-')" | |
| 44 | - | |
| 45 | -psql() { podman exec -i "$CONTAINER" psql -U "$PGUSER_" -v ON_ERROR_STOP=1 "$@"; } | |
| 46 | - | |
| 47 | -echo "== okul : $SCHOOL_ID" | |
| 48 | -echo "== okul db: $SCHOOL_DB" | |
| 49 | -echo "== control: $CONTROL_DB" | |
| 50 | - | |
| 51 | -psql -d postgres -q <<SQL | |
| 52 | -SELECT 'control var' WHERE EXISTS (SELECT 1 FROM pg_database WHERE datname='$CONTROL_DB'); | |
| 53 | -SQL | |
| 54 | -psql -d postgres -q -c "CREATE DATABASE $CONTROL_DB" 2>/dev/null || echo " (control zaten var)" | |
| 55 | -psql -d postgres -q -c "CREATE DATABASE $SCHOOL_DB" | |
| 56 | - | |
| 57 | -echo "== control semasi" | |
| 58 | -for f in "$BACKEND"/migrations/control/*.sql; do psql -d "$CONTROL_DB" -q -f - < "$f" 2>/dev/null || true; done | |
| 59 | - | |
| 60 | -echo "== okul semasi (+ ZEKA)" | |
| 61 | -for f in "$BACKEND"/migrations/school/*.sql; do | |
| 62 | - echo " $(basename "$f")" | |
| 63 | - psql -d "$SCHOOL_DB" -q -f - < "$f" | |
| 64 | -done | |
| 65 | - | |
| 66 | -echo "== okul verisi" | |
| 67 | -podman cp "$SEED_DIR/pg_school.sql" "$CONTAINER:/tmp/pg_school.sql" | |
| 68 | -podman exec "$CONTAINER" psql -U "$PGUSER_" -d "$SCHOOL_DB" -q -v ON_ERROR_STOP=1 -f /tmp/pg_school.sql | |
| 69 | - | |
| 70 | -echo "== control verisi (okul kaydi EN SON)" | |
| 71 | -psql -d "$CONTROL_DB" -q -f - < "$SEED_DIR/pg_control.sql" | |
| 72 | - | |
| 73 | -echo "== butunluk sinavi (48 denetim)" | |
| 74 | -if [ -f "$SEED_DIR/pg_dogrula.sql" ]; then | |
| 75 | - podman cp "$SEED_DIR/pg_dogrula.sql" "$CONTAINER:/tmp/pg_dogrula.sql" | |
| 76 | - # ON_ERROR_STOP: bir denetim ihlal bulursa betik burada duser. Yuklendi | |
| 77 | - # deyip bozuk veriyle devam etmek, hic yuklememekten kotudur. | |
| 78 | - podman exec "$CONTAINER" psql -U "$PGUSER_" -d "$SCHOOL_DB" -q -v ON_ERROR_STOP=1 -f /tmp/pg_dogrula.sql | |
| 79 | -else | |
| 80 | - echo " !! pg_dogrula.sql yok — tohum --postgres ile uretilmemis" | |
| 81 | - exit 1 | |
| 82 | -fi | |
| 83 | - | |
| 84 | -echo | |
| 85 | -echo "== satir sayilari" | |
| 86 | -psql -d "$SCHOOL_DB" -tAc "SELECT 'okul: ' || sum(n_live_tup) FROM pg_stat_user_tables;" | |
| 87 | -psql -d "$CONTROL_DB" -tAc "SELECT 'control: ' || sum(n_live_tup) FROM pg_stat_user_tables;" | |
| 88 | -echo "== bitti" |
tools/verify_pg_seed.sqldeleted+0 -325
| @@ -1,325 +0,0 @@ | ||
| 1 | --- Yuklenmis tohumun butunluk sinavi (PostgreSQL). | |
| 2 | --- | |
| 3 | --- `seed/99_dogrula.surql`'deki 48 denetimin karsiligi. HARFI HARFINE CEVIRI | |
| 4 | --- DEGIL: SurrealQL'in graf gezinmesi (`question.text`), `NOTINSIDE` ve | |
| 5 | --- `type::record` deyimlerinin Postgres'te karsiligi yok; her denetim burada | |
| 6 | --- ayni SORUYU sorar, kendi dilinde. | |
| 7 | --- | |
| 8 | --- Okuma: her satir ihlal SAYISIDIR ve SIFIR olmalidir. Sonda sifirdan buyuk | |
| 9 | --- bir sayi varsa betik hata ile duser. | |
| 10 | --- | |
| 11 | ---------------------------------------------------------------------------- | |
| 12 | --- SEMANIN ZORLADIGI DENETIMLER | |
| 13 | ---------------------------------------------------------------------------- | |
| 14 | --- Bes denetim (I1, I7, I9, I13, I48) yeni semada ARTIK IHLAL EDILEMEZ: | |
| 15 | --- yabanci anahtarlar, kismi tekil indeksler ve kolonun hic var olmamasi bunu | |
| 16 | --- yapisal olarak imkansiz kiliyor. Yine de listede duruyorlar ve ne ile | |
| 17 | --- zorlandiklari yaninda yaziyor. | |
| 18 | --- | |
| 19 | --- Bunlari "gecti" diye saymak yerine ayri isaretlemek onemli: sifir donduren | |
| 20 | --- bir sorgu, bir seyi ispatladigi icin degil, sorulmasi imkansiz hale | |
| 21 | --- geldigi icin de sifir donebilir. Ikisi ayni sey degil. | |
| 22 | - | |
| 23 | -\set ON_ERROR_STOP on | |
| 24 | - | |
| 25 | -\set t_now 1776056400000 | |
| 26 | -\set t_start 1757278800000 | |
| 27 | -\set t_end 1781902740000 | |
| 28 | - | |
| 29 | -CREATE TEMP TABLE sonuc ( | |
| 30 | - sira int GENERATED ALWAYS AS IDENTITY, | |
| 31 | - kod text, | |
| 32 | - baslik text, | |
| 33 | - ihlal bigint, | |
| 34 | - not_ text DEFAULT '' | |
| 35 | -); | |
| 36 | - | |
| 37 | --- =========================================================================== | |
| 38 | --- Sinav / cevap butunlugu | |
| 39 | --- =========================================================================== | |
| 40 | - | |
| 41 | -INSERT INTO sonuc (kod, baslik, ihlal, not_) | |
| 42 | -SELECT 'I1', 'exam_answer -> exam_question kopuk', count(*), | |
| 43 | - 'FK exam_answer_exam_question_fkey zorluyor' | |
| 44 | - FROM exam_answer a | |
| 45 | - LEFT JOIN exam_question q ON q.id = a.question AND q.exam = a.exam | |
| 46 | - WHERE q.id IS NULL; | |
| 47 | - | |
| 48 | -INSERT INTO sonuc (kod, baslik, ihlal) | |
| 49 | -SELECT 'I2', 'exam_answer.seq ile eslesen exam_attempt yok', count(*) | |
| 50 | - FROM exam_answer a | |
| 51 | - LEFT JOIN exam_attempt t | |
| 52 | - ON t.exam = a.exam AND t.app_user = a.app_user AND t.seq = a.seq | |
| 53 | - WHERE t.exam IS NULL; | |
| 54 | - | |
| 55 | -INSERT INTO sonuc (kod, baslik, ihlal) | |
| 56 | -SELECT 'I3', 'selected degeri sorunun choices[].id kumesinde degil', count(*) | |
| 57 | - FROM exam_answer a JOIN exam_question q ON q.id = a.question | |
| 58 | - WHERE a.selected IS NOT NULL | |
| 59 | - AND NOT EXISTS (SELECT 1 FROM jsonb_array_elements(coalesce(q.choices,'[]'::jsonb)) c | |
| 60 | - WHERE c->>'id' = a.selected); | |
| 61 | - | |
| 62 | -INSERT INTO sonuc (kod, baslik, ihlal) | |
| 63 | -SELECT 'I4', 'kind=text soruda selected dolu', count(*) | |
| 64 | - FROM exam_answer a JOIN exam_question q ON q.id = a.question | |
| 65 | - WHERE q.kind = 'text' AND a.selected IS NOT NULL; | |
| 66 | - | |
| 67 | -INSERT INTO sonuc (kod, baslik, ihlal) | |
| 68 | -SELECT 'I5', 'kind=choice soruda text dolu', count(*) | |
| 69 | - FROM exam_answer a JOIN exam_question q ON q.id = a.question | |
| 70 | - WHERE q.kind = 'choice' AND a.text IS NOT NULL; | |
| 71 | - | |
| 72 | -INSERT INTO sonuc (kod, baslik, ihlal) | |
| 73 | -SELECT 'I6', 'kind=choice soruda correct/choices bos', count(*) | |
| 74 | - FROM exam_question | |
| 75 | - WHERE kind = 'choice' | |
| 76 | - AND (correct IS NULL OR choices IS NULL OR jsonb_array_length(choices) = 0); | |
| 77 | - | |
| 78 | -INSERT INTO sonuc (kod, baslik, ihlal, not_) | |
| 79 | -SELECT 'I7', 'seq=1 kaydin kimliginde _1 eki', 0, | |
| 80 | - 'kimlik artik uuid; metin anahtar deseni yok'; | |
| 81 | - | |
| 82 | --- =========================================================================== | |
| 83 | --- Odev / calisma | |
| 84 | --- =========================================================================== | |
| 85 | - | |
| 86 | -INSERT INTO sonuc (kod, baslik, ihlal) | |
| 87 | -SELECT 'I8', 'submitted_at > updated_at', count(*) | |
| 88 | - FROM homework_submission WHERE submitted_at > updated_at; | |
| 89 | - | |
| 90 | -INSERT INTO sonuc (kod, baslik, ihlal) | |
| 91 | -SELECT 'I9', 'homework_result var ama submission yok', count(*) | |
| 92 | - FROM homework_result r | |
| 93 | - LEFT JOIN homework_submission s | |
| 94 | - ON s.homework = r.homework AND s.app_user = r.app_user | |
| 95 | - WHERE r.status <> 'missing' AND s.id IS NULL; | |
| 96 | - | |
| 97 | -INSERT INTO sonuc (kod, baslik, ihlal) | |
| 98 | -SELECT 'I10', 'pomodoro finished_at < started_at', count(*) | |
| 99 | - FROM pomodoro_session WHERE finished_at IS NOT NULL AND finished_at < started_at; | |
| 100 | - | |
| 101 | -INSERT INTO sonuc (kod, baslik, ihlal) | |
| 102 | -SELECT 'I11', 'counted=true ama sure < 300.000 ms', count(*) | |
| 103 | - FROM pomodoro_session | |
| 104 | - WHERE counted AND (finished_at IS NULL OR finished_at - started_at < 300000); | |
| 105 | - | |
| 106 | -INSERT INTO sonuc (kod, baslik, ihlal) | |
| 107 | -SELECT 'I12', 'ayni UTC gununde counted>16 olan (ogrenci, gun)', count(*) | |
| 108 | - FROM (SELECT app_user, started_at / 86400000 AS gun | |
| 109 | - FROM pomodoro_session WHERE counted | |
| 110 | - GROUP BY app_user, started_at / 86400000 | |
| 111 | - HAVING count(*) > 16) x; | |
| 112 | - | |
| 113 | -INSERT INTO sonuc (kod, baslik, ihlal, not_) | |
| 114 | -SELECT 'I13', 'kullanici basina birden fazla ACIK pomodoro', count(*), | |
| 115 | - 'kismi tekil indeks pomodoro_session_open_stint zorluyor' | |
| 116 | - FROM (SELECT app_user FROM pomodoro_session WHERE finished_at IS NULL | |
| 117 | - GROUP BY app_user HAVING count(*) > 1) x; | |
| 118 | - | |
| 119 | --- =========================================================================== | |
| 120 | --- Sozluk / kume kisitlari | |
| 121 | --- =========================================================================== | |
| 122 | - | |
| 123 | -INSERT INTO sonuc (kod, baslik, ihlal) | |
| 124 | -SELECT 'I14', 'session_attendance.status sozluk disi', count(*) | |
| 125 | - FROM session_attendance | |
| 126 | - WHERE status NOT IN (SELECT status FROM settings_attendance_status); | |
| 127 | - | |
| 128 | -INSERT INTO sonuc (kod, baslik, ihlal) | |
| 129 | -SELECT 'I15', 'exam.kind sozluk disi', count(*) | |
| 130 | - FROM exam WHERE kind NOT IN ( | |
| 131 | - SELECT e->>'name' FROM settings s, jsonb_array_elements(s.exam_kinds) e); | |
| 132 | - | |
| 133 | -INSERT INTO sonuc (kod, baslik, ihlal) | |
| 134 | -SELECT 'I16', 'menu.slot sozluk disi', count(*) | |
| 135 | - FROM menu WHERE slot NOT IN (SELECT name FROM slot_ref); | |
| 136 | - | |
| 137 | -INSERT INTO sonuc (kod, baslik, ihlal) | |
| 138 | -SELECT 'I17', 'meal_attendance.status sozluk disi', count(*) | |
| 139 | - FROM meal_attendance WHERE status NOT IN ('served', 'missed'); | |
| 140 | - | |
| 141 | -INSERT INTO sonuc (kod, baslik, ihlal) | |
| 142 | -SELECT 'I18', 'homework_result.status sozluk disi', count(*) | |
| 143 | - FROM homework_result WHERE status NOT IN ('done', 'incomplete', 'missing'); | |
| 144 | - | |
| 145 | -INSERT INTO sonuc (kod, baslik, ihlal) | |
| 146 | -SELECT 'I19', 'board_stroke.kind sozluk disi', count(*) | |
| 147 | - FROM board_stroke WHERE kind NOT IN ('stroke', 'clear'); | |
| 148 | - | |
| 149 | -INSERT INTO sonuc (kod, baslik, ihlal) | |
| 150 | -SELECT 'I20', 'pool_question.status sozluk disi', count(*) | |
| 151 | - FROM pool_question WHERE status NOT IN ('pending', 'approved'); | |
| 152 | - | |
| 153 | --- @ROZET_KATALOGU@ | |
| 154 | - | |
| 155 | --- =========================================================================== | |
| 156 | --- Capraz tutarlilik | |
| 157 | --- =========================================================================== | |
| 158 | - | |
| 159 | -INSERT INTO sonuc (kod, baslik, ihlal) | |
| 160 | -SELECT 'I23', 'exam_question.subject.course != exam.course', count(*) | |
| 161 | - FROM exam_question q JOIN subject s ON s.id = q.subject | |
| 162 | - JOIN exam e ON e.id = q.exam | |
| 163 | - WHERE s.course <> e.course; | |
| 164 | - | |
| 165 | -INSERT INTO sonuc (kod, baslik, ihlal) | |
| 166 | -SELECT 'I24', 'homework.subject.course != homework.course', count(*) | |
| 167 | - FROM homework h JOIN subject s ON s.id = h.subject | |
| 168 | - WHERE s.course <> h.course; | |
| 169 | - | |
| 170 | -INSERT INTO sonuc (kod, baslik, ihlal) | |
| 171 | -SELECT 'I25', 'ogrenci/veliden ogrenci/veliye mesaj', count(*) | |
| 172 | - FROM message m JOIN app_user a ON a.id = m.sender | |
| 173 | - JOIN app_user b ON b.id = m.recipient | |
| 174 | - WHERE a.role IN ('student', 'parent') AND b.role IN ('student', 'parent'); | |
| 175 | - | |
| 176 | -INSERT INTO sonuc (kod, baslik, ihlal) | |
| 177 | -SELECT 'I26', 'veli randevusu ama parent_link yok', count(*) | |
| 178 | - FROM appointment ap JOIN app_user u ON u.id = ap.requester | |
| 179 | - WHERE u.role = 'parent' | |
| 180 | - AND NOT EXISTS (SELECT 1 FROM parent_link p WHERE p.parent = ap.requester); | |
| 181 | - | |
| 182 | --- =========================================================================== | |
| 183 | --- Sayac alanlari — gercek sayiyla ayni mi | |
| 184 | --- =========================================================================== | |
| 185 | - | |
| 186 | -INSERT INTO sonuc (kod, baslik, ihlal) | |
| 187 | -SELECT 'I27', 'course.enrollment_count yanlis', count(*) FROM course c | |
| 188 | - WHERE c.enrollment_count <> (SELECT count(*) FROM enrollment e WHERE e.course = c.id); | |
| 189 | - | |
| 190 | -INSERT INTO sonuc (kod, baslik, ihlal) | |
| 191 | -SELECT 'I28', 'subject.exam_question_count yanlis', count(*) FROM subject s | |
| 192 | - WHERE s.exam_question_count <> (SELECT count(*) FROM exam_question q WHERE q.subject = s.id); | |
| 193 | - | |
| 194 | -INSERT INTO sonuc (kod, baslik, ihlal) | |
| 195 | -SELECT 'I29', 'subject.homework_count yanlis', count(*) FROM subject s | |
| 196 | - WHERE s.homework_count <> (SELECT count(*) FROM homework h WHERE h.subject = s.id); | |
| 197 | - | |
| 198 | -INSERT INTO sonuc (kod, baslik, ihlal) | |
| 199 | -SELECT 'I30', 'exam.result_count yanlis', count(*) FROM exam e | |
| 200 | - WHERE e.result_count <> (SELECT count(*) FROM exam_result r WHERE r.exam = e.id); | |
| 201 | - | |
| 202 | -INSERT INTO sonuc (kod, baslik, ihlal) | |
| 203 | -SELECT 'I31', 'class_group sayaclari yanlis', count(*) FROM class_group g | |
| 204 | - WHERE g.class_member_count <> (SELECT count(*) FROM class_member m WHERE m.class = g.id) | |
| 205 | - OR g.class_course_count <> (SELECT count(*) FROM class_course c WHERE c.class = g.id); | |
| 206 | - | |
| 207 | -INSERT INTO sonuc (kod, baslik, ihlal) | |
| 208 | -SELECT 'I32', 'term sayaclari yanlis', count(*) FROM term t | |
| 209 | - WHERE t.course_count <> (SELECT count(*) FROM course c WHERE c.term = t.id) | |
| 210 | - OR t.class_count <> (SELECT count(*) FROM class_group g WHERE g.term = t.id); | |
| 211 | - | |
| 212 | -INSERT INTO sonuc (kod, baslik, ihlal) | |
| 213 | -SELECT 'I33', 'menu.seats_booked yanlis', count(*) FROM menu m | |
| 214 | - WHERE m.seats_booked <> (SELECT count(*) FROM meal_booking b | |
| 215 | - WHERE b.menu = m.id AND b.status = 'booked'); | |
| 216 | - | |
| 217 | -INSERT INTO sonuc (kod, baslik, ihlal) | |
| 218 | -SELECT 'I34', 'event.registration_count yanlis', count(*) FROM event e | |
| 219 | - WHERE e.registration_count <> (SELECT count(*) FROM registration r WHERE r.event = e.id); | |
| 220 | - | |
| 221 | -INSERT INTO sonuc (kod, baslik, ihlal) | |
| 222 | -SELECT 'I35', 'fee_plan.assignment_count yanlis', count(*) FROM fee_plan f | |
| 223 | - WHERE f.assignment_count <> (SELECT count(*) FROM fee_plan_assignment a WHERE a.plan = f.id); | |
| 224 | - | |
| 225 | -INSERT INTO sonuc (kod, baslik, ihlal) | |
| 226 | -SELECT 'I36', 'board vurus sayaclari yanlis', count(*) FROM board b | |
| 227 | - WHERE b.total_stroke_count <> (SELECT count(*) FROM board_stroke s WHERE s.board = b.id) | |
| 228 | - OR b.epoch_stroke_count <> (SELECT count(*) FROM board_stroke s | |
| 229 | - WHERE s.board = b.id AND s.epoch = b.epoch); | |
| 230 | - | |
| 231 | -INSERT INTO sonuc (kod, baslik, ihlal) | |
| 232 | -SELECT 'I37', 'app_user thread/board sayaclari yanlis', count(*) FROM app_user u | |
| 233 | - WHERE u.chatbot_thread_count <> (SELECT count(*) FROM chatbot_thread t WHERE t.user_id = u.id) | |
| 234 | - OR u.board_count <> (SELECT count(*) FROM board b WHERE b.creator = u.id); | |
| 235 | - | |
| 236 | -INSERT INTO sonuc (kod, baslik, ihlal) | |
| 237 | -SELECT 'I38', 'note / submission file_count yanlis', count(*) FROM ( | |
| 238 | - SELECT 1 FROM note n | |
| 239 | - WHERE n.file_count <> (SELECT count(*) FROM note_file f WHERE f.note = n.id) | |
| 240 | - UNION ALL | |
| 241 | - SELECT 1 FROM homework_submission s | |
| 242 | - WHERE s.file_count <> (SELECT count(*) FROM homework_file f WHERE f.submission = s.id)) x; | |
| 243 | - | |
| 244 | -INSERT INTO sonuc (kod, baslik, ihlal) | |
| 245 | -SELECT 'I39', 'gun numarasi alanina ms yazilmis', count(*) FROM app_user | |
| 246 | - WHERE coalesce(study_streak_last_day, 0) > 100000000 | |
| 247 | - OR coalesce(pomodoro_counted_day, 0) > 100000000; | |
| 248 | - | |
| 249 | --- =========================================================================== | |
| 250 | --- Zaman sinirlari | |
| 251 | --- =========================================================================== | |
| 252 | - | |
| 253 | -INSERT INTO sonuc (kod, baslik, ihlal) | |
| 254 | -SELECT 'I40', 'T_NOW sonrasi satir', count(*) FROM ( | |
| 255 | - SELECT 1 FROM course_session WHERE starts_at > :t_now | |
| 256 | - UNION ALL SELECT 1 FROM exam_answer WHERE updated_at > :t_now | |
| 257 | - UNION ALL SELECT 1 FROM pomodoro_session WHERE started_at > :t_now) x; | |
| 258 | - | |
| 259 | -INSERT INTO sonuc (kod, baslik, ihlal) | |
| 260 | -SELECT 'I41', 'donem sonundan sonraki satir', count(*) FROM ( | |
| 261 | - SELECT 1 FROM exam WHERE starts_at > :t_end | |
| 262 | - UNION ALL SELECT 1 FROM homework WHERE due_at > :t_end | |
| 263 | - UNION ALL SELECT 1 FROM event WHERE starts_at > :t_end) x; | |
| 264 | - | |
| 265 | -INSERT INTO sonuc (kod, baslik, ihlal) | |
| 266 | -SELECT 'I42', 'donem basindan onceki satir', count(*) FROM ( | |
| 267 | - SELECT 1 FROM course_session WHERE starts_at < :t_start | |
| 268 | - UNION ALL SELECT 1 FROM exam WHERE starts_at < :t_start | |
| 269 | - UNION ALL SELECT 1 FROM pomodoro_session WHERE started_at < :t_start) x; | |
| 270 | - | |
| 271 | --- =========================================================================== | |
| 272 | --- Deger araliklari | |
| 273 | --- =========================================================================== | |
| 274 | - | |
| 275 | -INSERT INTO sonuc (kod, baslik, ihlal) | |
| 276 | -SELECT 'I43', 'not degeri 0..100 disinda', count(*) FROM ( | |
| 277 | - SELECT 1 FROM exam_result WHERE mark < 0 OR mark > 100 | |
| 278 | - UNION ALL SELECT 1 FROM homework_result | |
| 279 | - WHERE mark IS NOT NULL AND (mark < 0 OR mark > 100)) x; | |
| 280 | - | |
| 281 | -INSERT INTO sonuc (kod, baslik, ihlal) | |
| 282 | -SELECT 'I44', 'exam_question.points 1..100 disinda', count(*) | |
| 283 | - FROM exam_question WHERE points < 1 OR points > 100; | |
| 284 | - | |
| 285 | -INSERT INTO sonuc (kod, baslik, ihlal) | |
| 286 | -SELECT 'I45', 'bir sinavin puan toplami != 100', count(*) | |
| 287 | - FROM (SELECT exam FROM exam_question GROUP BY exam HAVING sum(points) <> 100) x; | |
| 288 | - | |
| 289 | -INSERT INTO sonuc (kod, baslik, ihlal) | |
| 290 | -SELECT 'I46', '*_minor alani negatif veya asiri', count(*) FROM ( | |
| 291 | - SELECT 1 FROM menu_dish WHERE price_minor < 0 OR price_minor > 1000000 | |
| 292 | - UNION ALL SELECT 1 FROM meal_ledger WHERE amount_minor < 0 OR amount_minor > 10000000 | |
| 293 | - UNION ALL SELECT 1 FROM payment_ledger WHERE amount_minor < 0 OR amount_minor > 10000000) x; | |
| 294 | - | |
| 295 | -INSERT INTO sonuc (kod, baslik, ihlal) | |
| 296 | -SELECT 'I47', 'menu.date uzunlugu != 10', count(*) FROM menu WHERE length(date) <> 10; | |
| 297 | - | |
| 298 | -INSERT INTO sonuc (kod, baslik, ihlal, not_) | |
| 299 | -SELECT 'I48', 'emekli alana yazim (source_bank, audience.users)', 0, | |
| 300 | - 'kolonlar semada hic yok; DDL zorluyor'; | |
| 301 | - | |
| 302 | --- =========================================================================== | |
| 303 | --- Rapor | |
| 304 | --- =========================================================================== | |
| 305 | -\echo '' | |
| 306 | -\echo '== tohum butunluk sinavi (PostgreSQL)' | |
| 307 | -\pset tuples_only on | |
| 308 | -\pset format unaligned | |
| 309 | -SELECT lpad(sira::text, 2) || '. ' || rpad(kod, 5) || rpad(baslik, 52) || ' ' || | |
| 310 | - CASE WHEN ihlal = 0 THEN 'OK' ELSE 'IHLAL ' || ihlal END || | |
| 311 | - CASE WHEN not_ <> '' THEN ' [' || not_ || ']' ELSE '' END | |
| 312 | - FROM sonuc ORDER BY sira; | |
| 313 | -\pset tuples_only off | |
| 314 | -\pset format aligned | |
| 315 | - | |
| 316 | -\echo '' | |
| 317 | -DO $$ | |
| 318 | -DECLARE d bigint; n bigint; | |
| 319 | -BEGIN | |
| 320 | - SELECT count(*), coalesce(sum(ihlal), 0) INTO n, d FROM sonuc WHERE ihlal > 0; | |
| 321 | - IF n > 0 THEN | |
| 322 | - RAISE EXCEPTION '% denetim ihlal buldu (toplam % satir)', n, d; | |
| 323 | - END IF; | |
| 324 | - RAISE NOTICE 'butunluk sinavi: % denetimin tamami temiz', (SELECT count(*) FROM sonuc); | |
| 325 | -END $$; |