| 1 | |
| 2 | |
| 3 | import json |
| 4 | import re |
| 5 | import tempfile |
| 6 | import unittest |
| 7 | from collections import Counter, defaultdict |
| 8 | from pathlib import Path |
| 9 | from unittest.mock import patch |
| 10 | |
| 11 | from src.catalog import INTENTS, ROLE_HIERARCHY |
| 12 | from src.role_spaces import get_role_space |
| 13 | from stress_benchmark import ( |
| 14 | DEFAULT_IN_SCOPE_COUNT, |
| 15 | DEFAULT_OOS_COUNT, |
| 16 | DEFAULT_TOTAL_COUNT, |
| 17 | GENERATOR_VERSION, |
| 18 | MUTATION_FAMILIES, |
| 19 | SOCIAL_INTENTS, |
| 20 | STATE_ERROR_ELIGIBLE, |
| 21 | collect_results, |
| 22 | generate_stress_records, |
| 23 | load_source_seeds, |
| 24 | main, |
| 25 | normalise_question_key, |
| 26 | privacy_findings, |
| 27 | render_markdown, |
| 28 | render_markdown_part, |
| 29 | write_jsonl, |
| 30 | write_report, |
| 31 | ) |
| 32 | |
| 33 | |
| 34 | def _response( |
| 35 | *, |
| 36 | intent: str | None, |
| 37 | response_id: str, |
| 38 | outcome: str, |
| 39 | reason_code: str, |
| 40 | fallback: bool = False, |
| 41 | auth_action: str | None = None, |
| 42 | route: str | None = None, |
| 43 | route_key: str | None = None, |
| 44 | text: str = "Kullanıcıya görünen sahte cevap", |
| 45 | ) -> dict: |
| 46 | return { |
| 47 | "trace_id": "fake", |
| 48 | "intent": intent, |
| 49 | "response_id": response_id, |
| 50 | "text": text, |
| 51 | "fallback": fallback, |
| 52 | "auth_action": auth_action, |
| 53 | "navigation": ( |
| 54 | {"route": route, "label": "Sahte", "available": True} |
| 55 | if route else None |
| 56 | ), |
| 57 | "assistant_meta": { |
| 58 | "outcome": outcome, |
| 59 | "action_id": intent, |
| 60 | "reason_code": reason_code, |
| 61 | "navigation": {"route_key": route_key} if route_key else None, |
| 62 | }, |
| 63 | "nested": {"machine_only": [1, 2, 3]}, |
| 64 | } |
| 65 | |
| 66 | |
| 67 | class _FakeEngine: |
| 68 | def handle(self, payload: dict) -> dict: |
| 69 | if payload["query"] == "good": |
| 70 | result = _response( |
| 71 | intent="profile_view", |
| 72 | response_id="profile_view_response", |
| 73 | outcome="allow", |
| 74 | reason_code="allowed", |
| 75 | route="/profile/me", |
| 76 | route_key="profile", |
| 77 | ) |
| 78 | elif payload["query"] == "scope": |
| 79 | result = _response( |
| 80 | intent=None, |
| 81 | response_id="out_of_scope_action", |
| 82 | outcome="deny", |
| 83 | reason_code="scope_boundary_action", |
| 84 | ) |
| 85 | elif payload["query"] in {"clarify", "clarify-boundary"}: |
| 86 | result = _response( |
| 87 | intent=None, |
| 88 | response_id="clarification_prompt", |
| 89 | outcome="clarify", |
| 90 | reason_code="ambiguous_query", |
| 91 | ) |
| 92 | else: |
| 93 | result = _response( |
| 94 | intent="wrong_intent", |
| 95 | response_id="wrong_response", |
| 96 | outcome="allow", |
| 97 | reason_code="allowed", |
| 98 | route="/wrong", |
| 99 | route_key="wrong", |
| 100 | ) |
| 101 | result["trace_id"] = payload["trace_id"] |
| 102 | return result |
| 103 | |
| 104 | |
| 105 | def _fake_record( |
| 106 | question: str, |
| 107 | *, |
| 108 | record_id: str, |
| 109 | expected: dict, |
| 110 | family: str = "semantic_paraphrase", |
| 111 | scope: str = "in_scope", |
| 112 | scope_boundary_type: str | None = None, |
| 113 | ) -> dict: |
| 114 | expected_intent = expected["intent"] or "oos" |
| 115 | return { |
| 116 | "id": record_id, |
| 117 | "question": question, |
| 118 | "expected_intent": expected_intent, |
| 119 | "expected": expected, |
| 120 | "role": "ogrenci", |
| 121 | "scope": scope, |
| 122 | "scope_boundary_type": scope_boundary_type, |
| 123 | "family": family, |
| 124 | "transformations": [family], |
| 125 | "mutation": {"fixture": True, "variant_hash": "0000000000000001"}, |
| 126 | "policy": { |
| 127 | "outcome": expected["outcome"], |
| 128 | "action_id": expected["intent"], |
| 129 | "scope": None, |
| 130 | "reason_code": expected.get("reason_code"), |
| 131 | "route_key": expected.get("meta_route_key"), |
| 132 | }, |
| 133 | "source": { |
| 134 | "dataset": "fixture", |
| 135 | "index": 1, |
| 136 | "question": "seed", |
| 137 | "role": "ogrenci", |
| 138 | }, |
| 139 | "synthetic": True, |
| 140 | "is_gold": False, |
| 141 | "generator_version": GENERATOR_VERSION, |
| 142 | "generation_round": 0, |
| 143 | "privacy_scan": {"passed": True, "findings": []}, |
| 144 | } |
| 145 | |
| 146 | |
| 147 | ALLOW_EXPECTED = { |
| 148 | "intent": "profile_view", |
| 149 | "outcome": "allow", |
| 150 | "meta_outcome": "allow", |
| 151 | "meta_action_id": "profile_view", |
| 152 | "response_ids": ["profile_view_response"], |
| 153 | "auth_action": None, |
| 154 | "fallback": False, |
| 155 | "navigation_route": "/profile/me", |
| 156 | "meta_route_key": "profile", |
| 157 | "reason_code": "allowed", |
| 158 | } |
| 159 | |
| 160 | FALLBACK_EXPECTED = { |
| 161 | "intent": None, |
| 162 | "outcome": "fallback", |
| 163 | "meta_outcome": "fallback", |
| 164 | "meta_action_id": None, |
| 165 | "response_ids": ["fallback_message"], |
| 166 | "auth_action": None, |
| 167 | "fallback": True, |
| 168 | "navigation_route": None, |
| 169 | "meta_route_key": None, |
| 170 | "reason_code": "out_of_scope", |
| 171 | } |
| 172 | |
| 173 | SCOPE_EXPECTED = { |
| 174 | "intent": None, |
| 175 | "outcome": "deny", |
| 176 | "meta_outcome": "deny", |
| 177 | "meta_action_id": None, |
| 178 | "response_ids": ["out_of_scope_action"], |
| 179 | "auth_action": None, |
| 180 | "fallback": False, |
| 181 | "navigation_route": None, |
| 182 | "meta_route_key": None, |
| 183 | "reason_code": "scope_boundary_action", |
| 184 | } |
| 185 | |
| 186 | DATA_SCOPE_EXPECTED = { |
| 187 | **SCOPE_EXPECTED, |
| 188 | "reason_code": "scope_boundary_data", |
| 189 | } |
| 190 | |
| 191 | |
| 192 | class StressGenerationTests(unittest.TestCase): |
| 193 | @classmethod |
| 194 | def setUpClass(cls) -> None: |
| 195 | cls.records = generate_stress_records() |
| 196 | |
| 197 | def test_exactly_ten_thousand_with_ninety_ten_split(self) -> None: |
| 198 | self.assertEqual(len(self.records), DEFAULT_TOTAL_COUNT) |
| 199 | counts = Counter(record["scope"] for record in self.records) |
| 200 | self.assertEqual(counts, { |
| 201 | "in_scope": DEFAULT_IN_SCOPE_COUNT, |
| 202 | "oos": DEFAULT_OOS_COUNT, |
| 203 | }) |
| 204 | |
| 205 | def test_in_scope_is_intent_balanced_and_covers_catalog(self) -> None: |
| 206 | counts = Counter( |
| 207 | record["expected_intent"] |
| 208 | for record in self.records |
| 209 | if record["scope"] == "in_scope" |
| 210 | ) |
| 211 | self.assertEqual(set(counts), {item["intent"] for item in INTENTS}) |
| 212 | self.assertLessEqual(max(counts.values()) - min(counts.values()), 1) |
| 213 | |
| 214 | def test_only_human_labeled_sources_are_used_and_catalog_is_never_a_seed(self) -> None: |
| 215 | sources = {record["source"]["dataset"] for record in self.records} |
| 216 | self.assertEqual(sources, {"benchmark", "near_oos"}) |
| 217 | self.assertTrue(all( |
| 218 | record["source"]["dataset"] == "benchmark" |
| 219 | for record in self.records |
| 220 | if record["scope"] == "in_scope" |
| 221 | )) |
| 222 | |
| 223 | def test_all_normalized_questions_and_stable_ids_are_unique(self) -> None: |
| 224 | keys = [normalise_question_key(record["question"]) for record in self.records] |
| 225 | ids = [record["id"] for record in self.records] |
| 226 | self.assertEqual(len(set(keys)), DEFAULT_TOTAL_COUNT) |
| 227 | self.assertEqual(len(set(ids)), DEFAULT_TOTAL_COUNT) |
| 228 | self.assertTrue(all(re.fullmatch(r"stress-[0-9a-f]{20}", value) for value in ids)) |
| 229 | |
| 230 | def test_smaller_generation_is_deterministic_including_hash_ids(self) -> None: |
| 231 | kwargs = {"in_scope_count": 176, "oos_count": 64} |
| 232 | self.assertEqual(generate_stress_records(**kwargs), generate_stress_records(**kwargs)) |
| 233 | |
| 234 | def test_every_record_has_version_privacy_and_full_expected_contract(self) -> None: |
| 235 | required = { |
| 236 | "intent", "outcome", "meta_outcome", "meta_action_id", "response_ids", "auth_action", |
| 237 | "fallback", "navigation_route", "meta_route_key", "reason_code", |
| 238 | } |
| 239 | for record in self.records: |
| 240 | self.assertEqual(record["generator_version"], GENERATOR_VERSION) |
| 241 | self.assertEqual(record["privacy_scan"], {"passed": True, "findings": []}) |
| 242 | self.assertEqual(set(record["expected"]), required) |
| 243 | self.assertTrue(record["expected"]["response_ids"]) |
| 244 | |
| 245 | def test_named_other_person_data_uses_safety_precedence_contract(self) -> None: |
| 246 | safety_rows = [ |
| 247 | row for row in self.records |
| 248 | if row["expected_intent"] == "exam_grade_student" |
| 249 | and row["expected"]["response_ids"] == ["safety_other_person_data"] |
| 250 | ] |
| 251 | self.assertTrue(safety_rows) |
| 252 | for row in safety_rows: |
| 253 | self.assertIn(row["role"], {"ziyaretci", "veli", "ogrenci"}) |
| 254 | self.assertIsNone(row["expected"]["intent"]) |
| 255 | self.assertEqual(row["expected"]["outcome"], "deny") |
| 256 | self.assertEqual(row["expected"]["reason_code"], "safety_other_person_data") |
| 257 | |
| 258 | def test_policy_metadata_comes_from_real_role_space_matrix(self) -> None: |
| 259 | generated_outcomes: dict[str, set[str]] = defaultdict(set) |
| 260 | for record in self.records: |
| 261 | if record["scope"] != "in_scope": |
| 262 | continue |
| 263 | intent = record["expected_intent"] |
| 264 | view = get_role_space(record["role"]).view_for(intent) |
| 265 | self.assertIsNotNone(view) |
| 266 | if record["expected"]["response_ids"] == ["safety_other_person_data"]: |
| 267 | |
| 268 | generated_outcomes[intent].add(view.outcome.value) |
| 269 | continue |
| 270 | redirect_targets = { |
| 271 | "report_card_view": "student_marks_lookup", |
| 272 | "attendance_view": "student_attendance_lookup", |
| 273 | "exam_finish_result": "student_marks_lookup", |
| 274 | } |
| 275 | if record["role"] in {"ogretmen", "yonetici", "admin"} and intent in redirect_targets: |
| 276 | view = get_role_space(record["role"]).view_for(redirect_targets[intent]) |
| 277 | self.assertEqual(record["policy"]["outcome"], view.outcome.value) |
| 278 | self.assertEqual(record["policy"]["action_id"], view.action_id) |
| 279 | self.assertEqual(record["policy"]["route_key"], view.route_key) |
| 280 | generated_outcomes[intent].add(view.outcome.value) |
| 281 | |
| 282 | for item in INTENTS: |
| 283 | intent = item["intent"] |
| 284 | matrix_outcomes = { |
| 285 | get_role_space(role).view_for(intent).outcome.value |
| 286 | for role in ROLE_HIERARCHY |
| 287 | } |
| 288 | self.assertTrue(matrix_outcomes.issubset(generated_outcomes[intent])) |
| 289 | |
| 290 | def test_denied_cases_expect_correct_auth_action_and_no_routes(self) -> None: |
| 291 | denied = [ |
| 292 | record for record in self.records |
| 293 | if record["scope"] == "in_scope" |
| 294 | and record["policy"]["outcome"] == "deny" |
| 295 | and record["expected"]["outcome"] == "deny" |
| 296 | ] |
| 297 | self.assertTrue(denied) |
| 298 | for record in denied: |
| 299 | if record["expected"]["response_ids"] == ["safety_other_person_data"]: |
| 300 | self.assertIsNone(record["expected"]["auth_action"]) |
| 301 | self.assertIsNone(record["expected"]["navigation_route"]) |
| 302 | self.assertIsNone(record["expected"]["meta_route_key"]) |
| 303 | continue |
| 304 | expected_auth = ( |
| 305 | "login_required" if record["role"] == "ziyaretci" |
| 306 | else "role_insufficient" |
| 307 | ) |
| 308 | self.assertEqual(record["expected"]["auth_action"], expected_auth) |
| 309 | self.assertIsNone(record["expected"]["navigation_route"]) |
| 310 | self.assertIsNone(record["expected"]["meta_route_key"]) |
| 311 | |
| 312 | def test_rich_families_exist_and_invalid_error_frames_do_not(self) -> None: |
| 313 | self.assertEqual( |
| 314 | {record["family"] for record in self.records}, |
| 315 | set(MUTATION_FAMILIES), |
| 316 | ) |
| 317 | for record in self.records: |
| 318 | if record["expected_intent"] not in STATE_ERROR_ELIGIBLE: |
| 319 | self.assertNotIn("state_error", record["transformations"]) |
| 320 | if record["scope"] == "oos": |
| 321 | self.assertNotIn("state_error", record["transformations"]) |
| 322 | |
| 323 | def test_punctuation_and_case_do_not_fake_question_uniqueness(self) -> None: |
| 324 | self.assertEqual( |
| 325 | normalise_question_key(" Sınava nasıl girerim?! "), |
| 326 | normalise_question_key("sınava NASIL girerim..."), |
| 327 | ) |
| 328 | |
| 329 | def test_nav_overview_accepts_dynamic_section_response(self) -> None: |
| 330 | nav_rows = [ |
| 331 | row for row in self.records |
| 332 | if row["scope"] == "in_scope" and row["expected_intent"] == "nav_overview" |
| 333 | ] |
| 334 | self.assertTrue(nav_rows) |
| 335 | self.assertTrue(all( |
| 336 | "section_overview" in row["expected"]["response_ids"] |
| 337 | for row in nav_rows |
| 338 | )) |
| 339 | |
| 340 | def test_upper_role_report_redirect_uses_served_target_contract(self) -> None: |
| 341 | rows = [ |
| 342 | row for row in self.records |
| 343 | if row["expected_intent"] == "exam_finish_result" |
| 344 | and row["role"] in {"ogretmen", "yonetici", "admin"} |
| 345 | ] |
| 346 | self.assertTrue(rows) |
| 347 | for row in rows: |
| 348 | self.assertEqual(row["expected"]["outcome"], "allow") |
| 349 | self.assertEqual(row["expected"]["response_ids"], ["student_report_redirect"]) |
| 350 | self.assertEqual(row["expected"]["meta_action_id"], "student_marks_lookup") |
| 351 | self.assertEqual(row["expected"]["meta_route_key"], "student_marks") |
| 352 | self.assertEqual(row["expected"]["reason_code"], "allowed") |
| 353 | self.assertEqual(row["policy"]["outcome"], "allow") |
| 354 | |
| 355 | def test_ascii_typo_semantic_ui_and_hash_variant_contracts(self) -> None: |
| 356 | ascii_rows = [r for r in self.records if r["family"] == "turkish_ascii"] |
| 357 | typo_rows = [r for r in self.records if r["family"] == "single_typo"] |
| 358 | semantic_rows = [r for r in self.records if r["family"] == "semantic_paraphrase"] |
| 359 | ui_rows = [r for r in self.records if r["family"] == "ui_label_tr_en"] |
| 360 | self.assertTrue(all(row["question"].isascii() for row in ascii_rows)) |
| 361 | self.assertTrue(all(row["mutation"]["typo_count"] == 1 for row in typo_rows)) |
| 362 | self.assertTrue(all( |
| 363 | row["mutation"]["strategy"] in { |
| 364 | "lexical_replacement", "meaning_preserving_frame", |
| 365 | } |
| 366 | for row in semantic_rows if row["scope"] == "in_scope" |
| 367 | )) |
| 368 | self.assertTrue(all( |
| 369 | row["mutation"]["strategy"] == "neutral_scope_frame" |
| 370 | for row in semantic_rows if row["scope"] == "oos" |
| 371 | )) |
| 372 | self.assertTrue(ui_rows) |
| 373 | self.assertTrue(all(row["mutation"]["strategy"] in { |
| 374 | "inline_label", "screen_context", |
| 375 | } for row in ui_rows)) |
| 376 | self.assertGreater( |
| 377 | len({row["mutation"]["variant_hash"] for row in self.records}), |
| 378 | len(self.records) // 2, |
| 379 | ) |
| 380 | |
| 381 | def test_mutations_preserve_natural_language_and_intent_semantics(self) -> None: |
| 382 | lowered = [row["question"].casefold() for row in self.records] |
| 383 | invalid_fragments = ( |
| 384 | "eklemek yapmam gerekiyor", "değiştirmek yapmam gerekiyor", |
| 385 | "silmek yapmam gerekiyor", "yeni kayıt girmek", |
| 386 | "yeni kayıt açmak", "üyeliğini sonlandırmak", |
| 387 | ) |
| 388 | for fragment in invalid_fragments: |
| 389 | self.assertFalse(any(fragment in question for question in lowered), fragment) |
| 390 | |
| 391 | social_semantic = [ |
| 392 | row["question"].casefold() for row in self.records |
| 393 | if row["scope"] == "in_scope" |
| 394 | and row["expected_intent"] in SOCIAL_INTENTS |
| 395 | and row["family"] == "semantic_paraphrase" |
| 396 | ] |
| 397 | self.assertTrue(social_semantic) |
| 398 | self.assertTrue(all("işlem yolunu" not in question for question in social_semantic)) |
| 399 | |
| 400 | board_view_states = [ |
| 401 | row["question"].casefold() for row in self.records |
| 402 | if row["expected_intent"] == "board_view" and row["family"] == "state_error" |
| 403 | ] |
| 404 | self.assertTrue(board_view_states) |
| 405 | self.assertTrue(all("yeniden açamıyorum" not in question for question in board_view_states)) |
| 406 | |
| 407 | def test_oos_mutations_use_neutral_language_and_keep_boundary_semantics(self) -> None: |
| 408 | oos = [record for record in self.records if record["scope"] == "oos"] |
| 409 | self.assertTrue(oos) |
| 410 | product_frame_fragments = ( |
| 411 | "hezarfen'de", "hezarfende", "uygulamada", "hangi ekran", |
| 412 | "hangi ekrandan", "hangi ekranda", "hangi adım", "hangi adim", |
| 413 | "işlem akışı", "islem akisi", "doğru ekran", "dogru ekran", |
| 414 | "nereden başlamalı", "nereden baslamali", "panelinden", |
| 415 | "hesabımla", "hesabimla", "hangi sayfaya", |
| 416 | ) |
| 417 | for row in oos: |
| 418 | folded = row["question"].casefold() |
| 419 | self.assertFalse( |
| 420 | any(fragment in folded for fragment in product_frame_fragments), |
| 421 | msg=f"ürün-içi OOS çerçevesi: {row['question']}", |
| 422 | ) |
| 423 | expected_semantics = row["scope_boundary_type"] or "fallback" |
| 424 | self.assertEqual(row["mutation"]["scope_framing"], "neutral_oos") |
| 425 | self.assertEqual(row["mutation"]["boundary_semantics"], expected_semantics) |
| 426 | |
| 427 | action_rows = [row for row in oos if row["scope_boundary_type"] == "action"] |
| 428 | self.assertTrue(action_rows) |
| 429 | self.assertTrue(all(row["expected"]["outcome"] == "deny" for row in action_rows)) |
| 430 | |
| 431 | def test_oos_fallback_and_scope_boundary_metadata_are_separate(self) -> None: |
| 432 | oos = [record for record in self.records if record["scope"] == "oos"] |
| 433 | boundary = [record for record in oos if record["scope_boundary_type"]] |
| 434 | fallback = [record for record in oos if not record["scope_boundary_type"]] |
| 435 | self.assertTrue(boundary) |
| 436 | self.assertTrue(fallback) |
| 437 | self.assertTrue(all( |
| 438 | row["expected"]["outcome"] == "deny" |
| 439 | and row["expected"]["fallback"] is False |
| 440 | and row["expected"]["response_ids"] == ["out_of_scope_action"] |
| 441 | for row in boundary |
| 442 | )) |
| 443 | self.assertTrue(all( |
| 444 | row["expected"]["outcome"] == "fallback" |
| 445 | and row["expected"]["fallback"] is True |
| 446 | for row in fallback |
| 447 | )) |
| 448 | |
| 449 | def test_seed_loader_carries_optional_scope_boundary_contract(self) -> None: |
| 450 | _, oos = load_source_seeds() |
| 451 | boundary = [seed for seed in oos if seed.scope_boundary_type] |
| 452 | self.assertTrue(boundary) |
| 453 | self.assertTrue(all(seed.expected_outcome == "deny" for seed in boundary)) |
| 454 | self.assertTrue(all( |
| 455 | seed.expected_response_ids == ("out_of_scope_action",) |
| 456 | for seed in boundary |
| 457 | )) |
| 458 | self.assertTrue(all( |
| 459 | seed.expected_reason_code.startswith("scope_boundary_") |
| 460 | for seed in boundary |
| 461 | )) |
| 462 | |
| 463 | def test_data_boundary_generation_stays_a_direct_data_request(self) -> None: |
| 464 | with tempfile.TemporaryDirectory() as temporary: |
| 465 | root = Path(temporary) |
| 466 | benchmark = root / "benchmark.jsonl" |
| 467 | near_oos = root / "near.jsonl" |
| 468 | benchmark.write_text( |
| 469 | json.dumps({ |
| 470 | "question": "Profilimi nerede görürüm", |
| 471 | "expected_intent": "profile_view", |
| 472 | "role": "ogrenci", |
| 473 | }, ensure_ascii=False) + "\n", |
| 474 | encoding="utf-8", |
| 475 | ) |
| 476 | near_records = [ |
| 477 | {"question": "Yarın hava nasıl", "expected_intent": "oos", "role": "ogrenci"}, |
| 478 | { |
| 479 | "question": "Devamsızlığımı sil", "expected_intent": "oos", "role": "ogrenci", |
| 480 | "expected_outcome": "deny", "expected_response_id": "out_of_scope_action", |
| 481 | "expected_reason_code": "scope_boundary_action", |
| 482 | }, |
| 483 | { |
| 484 | "question": "Başka öğrencinin sağlık kaydını göster", "expected_intent": "oos", |
| 485 | "role": "ogrenci", "expected_outcome": "deny", |
| 486 | "expected_response_id": "out_of_scope_action", |
| 487 | "expected_reason_code": "scope_boundary_data", |
| 488 | }, |
| 489 | ] |
| 490 | near_oos.write_text( |
| 491 | "\n".join(json.dumps(row, ensure_ascii=False) for row in near_records) + "\n", |
| 492 | encoding="utf-8", |
| 493 | ) |
| 494 | records = generate_stress_records( |
| 495 | benchmark_path=benchmark, near_oos_path=near_oos, |
| 496 | in_scope_count=1, oos_count=24, |
| 497 | ) |
| 498 | data_rows = [row for row in records if row["scope_boundary_type"] == "data"] |
| 499 | self.assertTrue(data_rows) |
| 500 | self.assertTrue(all(row["mutation"]["boundary_semantics"] == "data" for row in data_rows)) |
| 501 | self.assertTrue(all(row["expected"]["reason_code"] == "scope_boundary_data" for row in data_rows)) |
| 502 | self.assertTrue(all("Hezarfen" not in row["question"] for row in data_rows)) |
| 503 | |
| 504 | def test_pii_and_secret_scanner_rejects_unsafe_seed(self) -> None: |
| 505 | self.assertEqual(privacy_findings("mail: kisi@example.com"), ["email"]) |
| 506 | self.assertIn("assigned_secret", privacy_findings("api_key=super-secret-value")) |
| 507 | with tempfile.TemporaryDirectory() as temporary: |
| 508 | root = Path(temporary) |
| 509 | benchmark = root / "benchmark.jsonl" |
| 510 | near_oos = root / "near.jsonl" |
| 511 | benchmark.write_text( |
| 512 | json.dumps({ |
| 513 | "question": "kisi@example.com profilini aç", |
| 514 | "expected_intent": "profile_view", |
| 515 | "role": "ogrenci", |
| 516 | }, ensure_ascii=False) + "\n", |
| 517 | encoding="utf-8", |
| 518 | ) |
| 519 | near_oos.write_text( |
| 520 | json.dumps({ |
| 521 | "question": "Bana hava durumunu söyle", |
| 522 | "expected_intent": "oos", |
| 523 | "role": "ogrenci", |
| 524 | }, ensure_ascii=False) + "\n", |
| 525 | encoding="utf-8", |
| 526 | ) |
| 527 | with self.assertRaisesRegex(ValueError, "PII/secret"): |
| 528 | load_source_seeds(benchmark, near_oos) |
| 529 | |
| 530 | |
| 531 | class StressContractAndReportTests(unittest.TestCase): |
| 532 | def test_collect_results_checks_entire_contract_and_clusters_reasons(self) -> None: |
| 533 | records = [ |
| 534 | _fake_record("good", record_id="fixture-good", expected=ALLOW_EXPECTED), |
| 535 | _fake_record("wrong", record_id="fixture-wrong", expected=FALLBACK_EXPECTED, |
| 536 | family="compound", scope="oos"), |
| 537 | _fake_record("scope", record_id="fixture-scope", expected=SCOPE_EXPECTED, |
| 538 | family="sentence_form", scope="oos"), |
| 539 | ] |
| 540 | rows = collect_results(records, engine=_FakeEngine()) |
| 541 | self.assertTrue(rows[0]["passed"]) |
| 542 | self.assertFalse(rows[1]["passed"]) |
| 543 | self.assertTrue(rows[2]["passed"]) |
| 544 | self.assertEqual(rows[0]["response"]["trace_id"], "stress-00001") |
| 545 | self.assertIn("intent_mismatch", rows[1]["failure_reasons"]) |
| 546 | self.assertIn("outcome_mismatch", rows[1]["failure_reasons"]) |
| 547 | self.assertIn("response_id_mismatch", rows[1]["failure_reasons"]) |
| 548 | self.assertIn("fallback_mismatch", rows[1]["failure_reasons"]) |
| 549 | self.assertIn("navigation_route_mismatch", rows[1]["failure_reasons"]) |
| 550 | self.assertIn("meta_route_key_mismatch", rows[1]["failure_reasons"]) |
| 551 | self.assertEqual(rows[1]["failure_severity"], "hard") |
| 552 | |
| 553 | def test_only_safe_oos_fallback_clarification_is_soft_and_remains_failed(self) -> None: |
| 554 | rows = collect_results([ |
| 555 | _fake_record( |
| 556 | "clarify", record_id="fixture-soft", expected=FALLBACK_EXPECTED, |
| 557 | scope="oos", |
| 558 | ), |
| 559 | _fake_record( |
| 560 | "clarify-boundary", record_id="fixture-boundary-hard", |
| 561 | expected=SCOPE_EXPECTED, scope="oos", scope_boundary_type="action", |
| 562 | ), |
| 563 | ], engine=_FakeEngine()) |
| 564 | self.assertFalse(rows[0]["passed"]) |
| 565 | self.assertEqual(rows[0]["failure_severity"], "soft") |
| 566 | self.assertIn("fallback_mismatch", rows[0]["failure_reasons"]) |
| 567 | self.assertFalse(rows[1]["passed"]) |
| 568 | self.assertEqual(rows[1]["failure_severity"], "hard") |
| 569 | |
| 570 | def test_summary_has_required_breakdowns_without_full_engine_json(self) -> None: |
| 571 | rows = collect_results([ |
| 572 | _fake_record("wrong", record_id="fixture-in-scope-fail", expected=ALLOW_EXPECTED), |
| 573 | _fake_record("wrong", record_id="fixture-wrong", expected=FALLBACK_EXPECTED, |
| 574 | family="compound", scope="oos"), |
| 575 | _fake_record("clarify", record_id="fixture-soft", expected=FALLBACK_EXPECTED, |
| 576 | scope="oos"), |
| 577 | _fake_record("wrong", record_id="fixture-action", expected=SCOPE_EXPECTED, |
| 578 | scope="oos", scope_boundary_type="action"), |
| 579 | _fake_record("wrong", record_id="fixture-data", expected=DATA_SCOPE_EXPECTED, |
| 580 | scope="oos", scope_boundary_type="data"), |
| 581 | ], engine=_FakeEngine()) |
| 582 | markdown = render_markdown(rows, part_links=["parts/part-0001.md"]) |
| 583 | self.assertIn("gold benchmark değildir", markdown) |
| 584 | self.assertIn("Kaynak bazında", markdown) |
| 585 | self.assertIn("Beklenen outcome bazında", markdown) |
| 586 | self.assertIn("Gerçek outcome bazında", markdown) |
| 587 | self.assertIn("Hata kümeleri", markdown) |
| 588 | self.assertIn("intent_mismatch", markdown) |
| 589 | self.assertIn("OOS türü ve FAIL şiddeti", markdown) |
| 590 | self.assertRegex(markdown, r"\| `fallback` \| 2 \| 0 \| 1 \| 1 \|") |
| 591 | self.assertRegex(markdown, r"\| `action-boundary` \| 1 \| 0 \| 0 \| 1 \|") |
| 592 | self.assertRegex(markdown, r"\| `data-boundary` \| 1 \| 0 \| 0 \| 1 \|") |
| 593 | self.assertIn("İlk uygulama-içi FAIL örnekleri", markdown) |
| 594 | self.assertIn("fixture-in-scope-fail", markdown) |
| 595 | self.assertIn("İlk OOS FAIL örnekleri", markdown) |
| 596 | self.assertIn("fixture-soft", markdown) |
| 597 | self.assertIn("parts/part-0001.md", markdown) |
| 598 | self.assertNotIn('"machine_only": [', markdown) |
| 599 | |
| 600 | def test_markdown_part_contains_visible_text_not_machine_payload(self) -> None: |
| 601 | rows = collect_results([ |
| 602 | _fake_record("good", record_id="fixture-good", expected=ALLOW_EXPECTED), |
| 603 | ], engine=_FakeEngine()) |
| 604 | part = render_markdown_part(rows, part_number=1, total_parts=1) |
| 605 | self.assertIn("Kullanıcıya görünen sahte cevap", part) |
| 606 | self.assertIn("### Soru", part) |
| 607 | self.assertIn("kısa inceleme metadata'sı", part) |
| 608 | self.assertNotIn("yalnız kullanıcıya görünen metin", part) |
| 609 | self.assertNotIn("machine_only", part) |
| 610 | |
| 611 | def test_oos_report_exposes_zero_coverage_boundary_classes(self) -> None: |
| 612 | rows = collect_results([ |
| 613 | _fake_record("good", record_id="fixture-good", expected=ALLOW_EXPECTED), |
| 614 | ], engine=_FakeEngine()) |
| 615 | markdown = render_markdown(rows) |
| 616 | self.assertIn("| `fallback` | 0 | 0 | 0 | 0 | 0.0% |", markdown) |
| 617 | self.assertIn("| `action-boundary` | 0 | 0 | 0 | 0 | 0.0% |", markdown) |
| 618 | self.assertIn("| `data-boundary` | 0 | 0 | 0 | 0 | 0.0% |", markdown) |
| 619 | |
| 620 | def test_report_writer_creates_250_case_parts_and_jsonl_keeps_full_response(self) -> None: |
| 621 | base_row = collect_results([ |
| 622 | _fake_record("good", record_id="fixture-good", expected=ALLOW_EXPECTED), |
| 623 | ], engine=_FakeEngine())[0] |
| 624 | rows = [] |
| 625 | for index in range(1, 502): |
| 626 | row = dict(base_row) |
| 627 | row["index"] = index |
| 628 | row["id"] = f"fixture-{index:04d}" |
| 629 | rows.append(row) |
| 630 | with tempfile.TemporaryDirectory() as temporary: |
| 631 | root = Path(temporary) |
| 632 | custom_results = root / "results-special.jsonl" |
| 633 | report = write_report( |
| 634 | rows, root / "summary.md", chunk_size=250, |
| 635 | results_path=custom_results, |
| 636 | ) |
| 637 | parts = sorted((root / "summary_parcalar").glob("part-*.md")) |
| 638 | self.assertEqual(len(parts), 3) |
| 639 | self.assertIn("part-0003.md", report.read_text(encoding="utf-8")) |
| 640 | self.assertIn("results-special.jsonl", report.read_text(encoding="utf-8")) |
| 641 | |
| 642 | part_dir = root / "summary_parcalar" |
| 643 | (part_dir / "part-9999.md").write_text("stale generated", encoding="utf-8") |
| 644 | (part_dir / "inceleme-notlari.md").write_text("koru", encoding="utf-8") |
| 645 | sibling = root / "baska_rapor_parcalar" |
| 646 | sibling.mkdir() |
| 647 | sibling_part = sibling / "part-0001.md" |
| 648 | sibling_part.write_text("koru", encoding="utf-8") |
| 649 | write_report( |
| 650 | rows[:251], root / "summary.md", chunk_size=250, |
| 651 | results_path=custom_results, |
| 652 | ) |
| 653 | remaining_parts = sorted(path.name for path in part_dir.glob("part-*.md") if path.is_file()) |
| 654 | self.assertEqual(remaining_parts, ["part-0001.md", "part-0002.md"]) |
| 655 | self.assertEqual((part_dir / "inceleme-notlari.md").read_text(encoding="utf-8"), "koru") |
| 656 | self.assertEqual(sibling_part.read_text(encoding="utf-8"), "koru") |
| 657 | |
| 658 | result_path = write_jsonl(rows, root / "results.jsonl") |
| 659 | persisted = json.loads(result_path.read_text(encoding="utf-8").splitlines()[0]) |
| 660 | self.assertEqual(persisted["response"]["nested"]["machine_only"], [1, 2, 3]) |
| 661 | |
| 662 | def test_report_chunk_size_is_limited_to_reviewable_range(self) -> None: |
| 663 | with tempfile.TemporaryDirectory() as temporary: |
| 664 | with self.assertRaisesRegex(ValueError, "250-500"): |
| 665 | write_report([], Path(temporary) / "summary.md", chunk_size=249) |
| 666 | with self.assertRaisesRegex(ValueError, "250-500"): |
| 667 | write_report([], Path(temporary) / "summary.md", chunk_size=501) |
| 668 | |
| 669 | def test_cli_is_diagnostic_by_default_and_strict_only_on_request(self) -> None: |
| 670 | failed_rows = [{"passed": False}] |
| 671 | fake_return = (Path("data.jsonl"), Path("summary.md"), failed_rows) |
| 672 | with patch("stress_benchmark.build_artifacts", return_value=fake_return): |
| 673 | self.assertEqual(main([]), 0) |
| 674 | self.assertEqual(main(["--allow-failures"]), 0) |
| 675 | self.assertEqual(main(["--strict"]), 1) |
| 676 | |
| 677 | |
| 678 | if __name__ == "__main__": |
| 679 | unittest.main() |