| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | import contextlib |
| 21 | import io |
| 22 | import os |
| 23 | import re |
| 24 | import unittest |
| 25 | from unittest import mock |
| 26 | |
| 27 | from src.embed import provider as embed_provider |
| 28 | from src.rerank import provider as rerank_provider |
| 29 | from src.service import preflight |
| 30 | |
| 31 | _KOK = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) |
| 32 | |
| 33 | |
| 34 | _MEM_LIMIT_MB = 3072 |
| 35 | _DISK_MIN_GB = 8 |
| 36 | |
| 37 | |
| 38 | def _oku(ad: str) -> str: |
| 39 | with open(os.path.join(_KOK, ad), encoding="utf-8") as fh: |
| 40 | return fh.read() |
| 41 | |
| 42 | |
| 43 | def _tam_api_env(**ek): |
| 44 | env = {"RAG_EMBED_API_BASE": "https://ornek/v1", |
| 45 | "RAG_EMBED_MODEL": "embed-1", |
| 46 | "RAG_EMBED_API_KEY": "e-anahtar", |
| 47 | "RAG_RERANK_API_URL": "https://ornek/rerank", |
| 48 | "RAG_RERANK_MODEL": "rerank-1", |
| 49 | "RAG_RERANK_API_KEY": "r-anahtar", |
| 50 | "RAG_ALLOW_UNCALIBRATED_ABSTAIN": "1", |
| 51 | "LLM_API_KEY": "llm-anahtar"} |
| 52 | env.update(ek) |
| 53 | return env |
| 54 | |
| 55 | |
| 56 | @contextlib.contextmanager |
| 57 | def _saglayicilar(embed: str = "api", rerank: str = "api", |
| 58 | allow_uncalibrated: bool = True): |
| 59 | |
| 60 | |
| 61 | |
| 62 | |
| 63 | |
| 64 | with mock.patch.object(embed_provider, "PROVIDER", embed), \ |
| 65 | mock.patch.object(rerank_provider, "PROVIDER", rerank), \ |
| 66 | mock.patch.object(rerank_provider, "ALLOW_UNCALIBRATED", |
| 67 | allow_uncalibrated): |
| 68 | yield |
| 69 | |
| 70 | |
| 71 | class ProviderConfigTests(unittest.TestCase): |
| 72 | def test_local_selection_needs_no_api_config(self): |
| 73 | |
| 74 | with _saglayicilar("local", "local"): |
| 75 | self.assertEqual(preflight.check_provider_config({"LLM_API_KEY": "k"}), |
| 76 | []) |
| 77 | |
| 78 | def test_api_selection_names_every_missing_key(self): |
| 79 | with _saglayicilar(): |
| 80 | eksik = preflight.check_provider_config({}) |
| 81 | metin = "\n".join(eksik) |
| 82 | for ad in ("RAG_EMBED_API_BASE", "RAG_EMBED_MODEL", "RAG_EMBED_API_KEY", |
| 83 | "RAG_RERANK_API_URL", "RAG_RERANK_MODEL", |
| 84 | "RAG_RERANK_API_KEY", "LLM_API_KEY"): |
| 85 | self.assertIn(ad, metin, f"{ad} adıyla söylenmeli") |
| 86 | |
| 87 | def test_api_complete_config_passes(self): |
| 88 | with _saglayicilar(): |
| 89 | self.assertEqual(preflight.check_provider_config(_tam_api_env()), []) |
| 90 | |
| 91 | def test_cohere_selection_needs_the_same_three_names(self): |
| 92 | |
| 93 | |
| 94 | |
| 95 | with _saglayicilar("cohere", "api"): |
| 96 | eksik = preflight.check_provider_config({}) |
| 97 | metin = "\n".join(eksik) |
| 98 | for ad in ("RAG_EMBED_API_BASE", "RAG_EMBED_MODEL", "RAG_EMBED_API_KEY"): |
| 99 | self.assertIn(ad, metin, f"{ad} adıyla söylenmeli") |
| 100 | |
| 101 | def test_cohere_complete_config_passes(self): |
| 102 | with _saglayicilar("cohere", "api"): |
| 103 | self.assertEqual(preflight.check_provider_config(_tam_api_env()), []) |
| 104 | |
| 105 | def test_voyage_selection_is_accepted_with_the_same_three_names(self): |
| 106 | |
| 107 | |
| 108 | |
| 109 | with _saglayicilar("voyage", "api"): |
| 110 | eksik = preflight.check_provider_config({}) |
| 111 | metin = "\n".join(eksik) |
| 112 | for ad in ("RAG_EMBED_API_BASE", "RAG_EMBED_MODEL", "RAG_EMBED_API_KEY"): |
| 113 | self.assertIn(ad, metin, f"{ad} adıyla söylenmeli") |
| 114 | |
| 115 | def test_voyage_complete_config_passes(self): |
| 116 | with _saglayicilar("voyage", "api"): |
| 117 | self.assertEqual(preflight.check_provider_config(_tam_api_env()), []) |
| 118 | |
| 119 | def test_cohere_key_can_come_through_env_name_indirection(self): |
| 120 | |
| 121 | ortam = _tam_api_env() |
| 122 | ortam.pop("RAG_EMBED_API_KEY") |
| 123 | with _saglayicilar("cohere", "api"): |
| 124 | with mock.patch.object(embed_provider, "API_KEY_ENV", |
| 125 | "RAG_EMBED_API_KEY"): |
| 126 | self.assertEqual( |
| 127 | preflight.check_provider_config( |
| 128 | {**ortam, "RAG_EMBED_API_KEY": "deger"}), []) |
| 129 | |
| 130 | def test_key_can_come_through_env_name_indirection(self): |
| 131 | |
| 132 | ortam = _tam_api_env() |
| 133 | ortam.pop("RAG_EMBED_API_KEY") |
| 134 | ortam["PAYLASILAN_ANAHTAR"] = "deger" |
| 135 | with _saglayicilar(): |
| 136 | with mock.patch.object(embed_provider, "API_KEY_ENV", |
| 137 | "PAYLASILAN_ANAHTAR"): |
| 138 | self.assertEqual(preflight.check_provider_config(ortam), []) |
| 139 | with mock.patch.object(embed_provider, "API_KEY_ENV", |
| 140 | "BASKA_ANAHTAR"): |
| 141 | eksik = preflight.check_provider_config(ortam) |
| 142 | self.assertIn("BASKA_ANAHTAR", "\n".join(eksik), |
| 143 | "dolaylı ad eksikse OKUNAN ad söylenmeli") |
| 144 | |
| 145 | def test_unknown_provider_spelling_is_reported(self): |
| 146 | with _saglayicilar("magic", "local"): |
| 147 | eksik = preflight.check_provider_config({"LLM_API_KEY": "k"}) |
| 148 | self.assertIn("tanınmıyor", "\n".join(eksik)) |
| 149 | |
| 150 | def test_uncalibrated_rerank_requires_explicit_flag(self): |
| 151 | |
| 152 | |
| 153 | ortam = _tam_api_env() |
| 154 | ortam.pop("RAG_ALLOW_UNCALIBRATED_ABSTAIN") |
| 155 | with _saglayicilar(), \ |
| 156 | mock.patch.object(preflight, "ABSTAIN_SCORE_DEFAULT", 0.30), \ |
| 157 | mock.patch.object(rerank_provider, "ALLOW_UNCALIBRATED", False): |
| 158 | eksik = preflight.check_provider_config(ortam) |
| 159 | self.assertIn("RAG_ALLOW_UNCALIBRATED_ABSTAIN", "\n".join(eksik)) |
| 160 | |
| 161 | def test_disabled_abstain_gate_removes_the_complaint(self): |
| 162 | ortam = _tam_api_env() |
| 163 | ortam.pop("RAG_ALLOW_UNCALIBRATED_ABSTAIN") |
| 164 | with _saglayicilar(), \ |
| 165 | mock.patch.object(preflight, "ABSTAIN_SCORE_DEFAULT", 0.0): |
| 166 | self.assertEqual(preflight.check_provider_config(ortam), []) |
| 167 | |
| 168 | def test_enforce_refuses_with_a_named_report(self): |
| 169 | err = io.StringIO() |
| 170 | with _saglayicilar(): |
| 171 | with contextlib.redirect_stderr(err), \ |
| 172 | self.assertRaises(SystemExit) as ctx: |
| 173 | preflight.enforce({}) |
| 174 | self.assertEqual(ctx.exception.code, 2) |
| 175 | self.assertIn("RAG_EMBED_API_KEY", err.getvalue()) |
| 176 | |
| 177 | def test_validate_cli_exit_codes(self): |
| 178 | with _saglayicilar(): |
| 179 | with mock.patch.object(preflight, "check_provider_config", |
| 180 | return_value=["X boş"]): |
| 181 | err = io.StringIO() |
| 182 | with contextlib.redirect_stderr(err): |
| 183 | kod = preflight.main(["--validate"]) |
| 184 | self.assertEqual(kod, 2) |
| 185 | self.assertIn("X boş", err.getvalue()) |
| 186 | with _saglayicilar(), \ |
| 187 | mock.patch.object(preflight, "check_provider_config", |
| 188 | return_value=[]): |
| 189 | self.assertEqual(preflight.main(["--validate"]), 0) |
| 190 | |
| 191 | |
| 192 | class DeploySurfaceTests(unittest.TestCase): |
| 193 | |
| 194 | |
| 195 | def test_envelope_is_the_single_source(self): |
| 196 | compose = _oku("compose.yaml") |
| 197 | blok = re.search(r"^x-rag-envelope:\n((?:[ \t]+.*\n)+)", compose, |
| 198 | re.M) |
| 199 | self.assertIsNotNone(blok, "x-rag-envelope bloğu yok") |
| 200 | deger = dict(re.findall(r"^\s+(\w+):\s*(\d+)\s*$", blok.group(1), re.M)) |
| 201 | self.assertEqual(int(deger["mem_limit_mb"]), _MEM_LIMIT_MB) |
| 202 | self.assertEqual(int(deger["disk_min_gb"]), _DISK_MIN_GB) |
| 203 | |
| 204 | |
| 205 | servis = compose.split(" rag:\n", 1)[1].split(" # #96", 1)[0] |
| 206 | self.assertIn(f"mem_limit: {_MEM_LIMIT_MB * 1024 * 1024}", servis) |
| 207 | |
| 208 | def test_workflow_reads_the_envelope_instead_of_hardcoding(self): |
| 209 | yml = _oku(".github/workflows/main.yml") |
| 210 | self.assertIn("x-rag-envelope", yml, "CI eşiği zarfı okumalı") |
| 211 | self.assertIn('"$mem_limit_mb"', yml) |
| 212 | self.assertIn('"$disk_min_gb"', yml) |
| 213 | for eski in ("-lt 12000", "-lt 20 ", "need >= 12000", "need >= 20)"): |
| 214 | self.assertNotIn(eski, yml, f"eski eşik kalmış: {eski}") |
| 215 | |
| 216 | def test_docs_publish_the_envelope(self): |
| 217 | for ad in ("README.md", "PROJECT_STATE.md"): |
| 218 | metin = _oku(ad) |
| 219 | self.assertIn(str(_MEM_LIMIT_MB), metin, f"{ad}: RAM tavanı") |
| 220 | self.assertIn(f"{_DISK_MIN_GB} GB", metin, f"{ad}: disk eşiği") |
| 221 | |
| 222 | def test_deploy_provider_defaults_are_api_in_every_surface(self): |
| 223 | ckok = preflight.DEPLOY_DEFAULT_PROVIDERS |
| 224 | self.assertEqual(ckok, {"RAG_EMBED_PROVIDER": "api", |
| 225 | "RAG_RERANK_PROVIDER": "api"}) |
| 226 | yuzeyler = { |
| 227 | "Containerfile": _oku("Containerfile"), |
| 228 | ".env.example": _oku(".env.example"), |
| 229 | "deploy/hezarfen_rag.env.example": |
| 230 | _oku("deploy/hezarfen_rag.env.example"), |
| 231 | } |
| 232 | for ad, metin in yuzeyler.items(): |
| 233 | for anahtar, beklenen in ckok.items(): |
| 234 | |
| 235 | self.assertRegex( |
| 236 | metin, rf"(?m)^[ \t]*{anahtar}={beklenen}[ \t]*\\?[ \t]*$", |
| 237 | f"{ad}: {anahtar}={beklenen}") |
| 238 | |
| 239 | def test_local_path_stays_selectable_and_fully_documented(self): |
| 240 | |
| 241 | |
| 242 | |
| 243 | |
| 244 | from src.embed.embedder import BGEM3Embedder |
| 245 | from src.rerank.reranker import BGEReranker |
| 246 | gomme = embed_provider.build_embedder(provider="local") |
| 247 | self.assertIsInstance(gomme, BGEM3Embedder) |
| 248 | self.assertTrue(gomme.sparse_supported, "yerel yol sparse üretir") |
| 249 | rr = rerank_provider.build_reranker(provider="local") |
| 250 | self.assertIsInstance(rr, BGEReranker) |
| 251 | |
| 252 | |
| 253 | with mock.patch.object(rerank_provider, "ALLOW_UNCALIBRATED", False): |
| 254 | rerank_provider.check_abstain_compatibility(rr, abstain_score=0.30) |
| 255 | sablon = _oku("deploy/hezarfen_rag.env.example") |
| 256 | self.assertIn("RAG_EMBED_PROVIDER=local", sablon) |
| 257 | self.assertIn("RAG_RERANK_PROVIDER=local", sablon) |
| 258 | |
| 259 | def test_operator_env_example_is_systemd_safe_and_complete(self): |
| 260 | |
| 261 | |
| 262 | metin = _oku("deploy/hezarfen_rag.env.example") |
| 263 | for satir in metin.splitlines(): |
| 264 | if satir.lstrip().startswith("#") or not satir.strip(): |
| 265 | continue |
| 266 | self.assertRegex(satir, r"^[A-Za-z_][A-Za-z0-9_]*=[^\s#]*$", |
| 267 | f"düz KEY=value değil: {satir!r}") |
| 268 | zorunlu = ("RAG_EMBED_PROVIDER", "RAG_EMBED_API_BASE", "RAG_EMBED_MODEL", |
| 269 | "RAG_EMBED_API_KEY", "RAG_EMBED_API_KEY_ENV", |
| 270 | "RAG_RERANK_PROVIDER", "RAG_RERANK_API_URL", |
| 271 | "RAG_RERANK_MODEL", "RAG_RERANK_API_KEY", |
| 272 | "RAG_RERANK_API_KEY_ENV", "RAG_ALLOW_UNCALIBRATED_ABSTAIN", |
| 273 | "LLM_API_KEY", "LLM_BASE_URL", "LLM_MODEL", |
| 274 | "AI_SHARED_TOKEN", "HEZARFEN_NET", "HEZARFEN_DATA_VOLUME", |
| 275 | "BOOK_PATH", "SINIF", "DERS", "RAG_MAX_CORPORA") |
| 276 | for ad in zorunlu: |
| 277 | self.assertRegex(metin, rf"(?m)^#?{ad}=", f"şablonda {ad} yok") |
| 278 | |
| 279 | def test_operator_env_example_covers_every_refusal_the_preflight_names(self): |
| 280 | |
| 281 | |
| 282 | metin = _oku("deploy/hezarfen_rag.env.example") |
| 283 | with _saglayicilar(), \ |
| 284 | mock.patch.object(preflight, "ABSTAIN_SCORE_DEFAULT", 0.30), \ |
| 285 | mock.patch.object(rerank_provider, "ALLOW_UNCALIBRATED", False): |
| 286 | eksik = preflight.check_provider_config({}) |
| 287 | self.assertTrue(eksik) |
| 288 | for mesaj in eksik: |
| 289 | ad = re.match(r"([A-Z_][A-Z0-9_]*)", mesaj) |
| 290 | self.assertIsNotNone(ad, f"mesaj adla başlamalı: {mesaj!r}") |
| 291 | self.assertRegex(metin, rf"(?m)^#?{ad.group(1)}=", |
| 292 | f"{ad.group(1)} şablonda yok") |
| 293 | |
| 294 | |
| 295 | class LocalStackVolumeTests(unittest.TestCase): |
| 296 | |
| 297 | |
| 298 | |
| 299 | |
| 300 | |
| 301 | |
| 302 | |
| 303 | def test_local_without_any_stack_refuses_with_the_command(self): |
| 304 | with _saglayicilar("local", "local"), \ |
| 305 | mock.patch.object(preflight, "_yerel_yigin_site_packages", |
| 306 | return_value=[]), \ |
| 307 | mock.patch("importlib.util.find_spec", return_value=None): |
| 308 | eksik = preflight.check_provider_config({"LLM_API_KEY": "k"}) |
| 309 | metin = "\n".join(eksik) |
| 310 | self.assertIn("provision_local_stack.sh", metin) |
| 311 | self.assertIn(preflight.LOCAL_VENV_ENV, metin) |
| 312 | self.assertIn(preflight.LOCAL_MODELS_ENV, metin) |
| 313 | |
| 314 | def test_local_with_provisioned_volume_passes(self): |
| 315 | with _saglayicilar("local", "local"), \ |
| 316 | mock.patch.object(preflight, "_yerel_yigin_site_packages", |
| 317 | return_value=["/vol/venv/lib/python3.11/site-packages"]), \ |
| 318 | mock.patch("importlib.util.find_spec", return_value=object()): |
| 319 | self.assertEqual(preflight.check_provider_config({"LLM_API_KEY": "k"}), []) |
| 320 | |
| 321 | def test_prepare_adds_the_volume_venv_to_sys_path(self): |
| 322 | import sys |
| 323 | with mock.patch.object(preflight, "_yerel_yigin_site_packages", |
| 324 | return_value=["/vol/venv/lib/python3.11/site-packages"]): |
| 325 | preflight.yerel_yigin_hazirla({preflight.LOCAL_VENV_ENV: "/vol/venv", |
| 326 | preflight.LOCAL_MODELS_ENV: "/vol/models"}) |
| 327 | self.assertEqual(sys.path[0], "/vol/venv/lib/python3.11/site-packages") |
| 328 | hf_home = os.environ.get("HF_HOME") |
| 329 | os.environ.pop("HF_HOME", None) |
| 330 | sys.path.remove("/vol/venv/lib/python3.11/site-packages") |
| 331 | self.assertEqual(hf_home, "/vol/models", |
| 332 | "ağırlıklar volume'da kalmalı (HF_HOME)") |
| 333 | |
| 334 | def test_durum_reads_the_provisioning_marker(self): |
| 335 | import tempfile |
| 336 | import pathlib as _p |
| 337 | with tempfile.TemporaryDirectory() as d: |
| 338 | (_p.Path(d) / "PROVISIONED").write_text( |
| 339 | "PROVISIONED_IMAGE=localhost/hezarfen_rag:current\n" |
| 340 | "PROVISIONED_TAG=abc123\nPYTHON=3.11.9\nDATE=2026-09-17T00:00:00+00:00\n", |
| 341 | encoding="utf-8") |
| 342 | durum = preflight.yerel_yigin_durumu( |
| 343 | {preflight.LOCAL_VENV_ENV: os.path.join(d, "venv")}) |
| 344 | self.assertIn("tag=abc123", durum) |
| 345 | self.assertIn("python=3.11.9", durum) |
| 346 | |
| 347 | def test_missing_marker_is_reported_as_missing(self): |
| 348 | self.assertIn("yok", preflight.yerel_yigin_durumu({})) |
| 349 | |
| 350 | |
| 351 | class SmallImageContractTests(unittest.TestCase): |
| 352 | |
| 353 | |
| 354 | def test_default_build_does_not_install_the_local_stack(self): |
| 355 | c = _oku("Containerfile") |
| 356 | self.assertIn("ARG WITH_LOCAL_MODELS=0", c) |
| 357 | kapi = c.index('if [ "$WITH_LOCAL_MODELS" = "1" ]') |
| 358 | self.assertGreater(c.index("requirements-local.txt", kapi), kapi, |
| 359 | "yerel liste yalnız kapının İÇİNDE kurulmalı") |
| 360 | |
| 361 | |
| 362 | kod = "\n".join(l for l in c.splitlines() |
| 363 | if not l.lstrip().startswith("#")) |
| 364 | self.assertIn('pip install --no-cache-dir "torch>=2.6" --index-url "${TORCH_INDEX}"', |
| 365 | kod) |
| 366 | self.assertNotRegex(kod, r"(?m)^pip install[^\n]*torch", |
| 367 | "torch kurulumu koşulsuz olmamalı") |
| 368 | self.assertGreater(kod.index('"torch>=2.6"'), kod.index('if [ "$WITH_LOCAL_MODELS" = "1" ]')) |
| 369 | |
| 370 | def test_local_deps_live_only_in_the_local_list(self): |
| 371 | temel = _oku("requirements.txt") |
| 372 | yerel = _oku("requirements-local.txt") |
| 373 | for paket in ("torch", "FlagEmbedding"): |
| 374 | self.assertNotRegex(temel, rf"(?m)^{paket}", f"{paket} temel listede") |
| 375 | self.assertRegex(yerel, rf"(?m)^{paket}", f"{paket} yerel listede") |
| 376 | self.assertNotRegex(temel, r"(?m)^deepeval", |
| 377 | "deepeval eval listesine taşındı") |
| 378 | |
| 379 | def test_containerfile_copies_the_local_list_into_the_image(self): |
| 380 | |
| 381 | c = _oku("Containerfile") |
| 382 | self.assertIn("COPY requirements.txt requirements-local.txt", c, |
| 383 | "sağlama betiği imge İÇİNDE pip çalıştırır; liste imgede olmalı") |
| 384 | |
| 385 | def test_provisioner_runs_pip_inside_the_service_image(self): |
| 386 | s = _oku("deploy/provision_local_stack.sh") |
| 387 | self.assertIn("podman run --rm -v", s) |
| 388 | self.assertIn("requirements-local.txt", s) |
| 389 | self.assertIn("PROVISIONED", s) |
| 390 | |
| 391 | |
| 392 | if __name__ == "__main__": |
| 393 | unittest.main() |