"""Per-section pipeline diagnostics. An exam shipped with 7 of its 15 sections empty — 71 questions instead of ~142 — and the exam JSON recorded only "0 questions" for each. A section that loses every question to a structural validator was indistinguishable from one that was never requested, so diagnosing it meant grepping server logs. The structural validators themselves are correct and stay strict: an إعراب question with no sentence to parse is unanswerable and should be dropped. What was missing is the record of *why*, which is what these cover. """ import asyncio import pytest from app.models.structured_schemas import SectionDiagnostics from app.services.gateway import _build_generation_insights def _section(title, questions, diagnostics=None): sec = {"title": title, "questions": questions, "quality_metrics": None} if diagnostics: sec["diagnostics"] = diagnostics return sec def _diag(**kw): base = { "type": "grammar", "requested": 10, "produced": 0, "status": "empty", "raw_returned": 10, "drop_reasons": {"grammar_needs_two_quoted_segments": 10}, "batch_attempts": 4, "batch_failures": [], "retrieval_confidence": 1.0, "source_pool_size": 12, } base.update(kw) return base def test_an_empty_section_reports_why_it_is_empty(): insights = asyncio.run(_build_generation_insights( [_section("النحو", [], _diag())], {}, [], )) reported = insights["section_diagnostics"] assert len(reported) == 1 assert reported[0]["status"] == "empty" # The distinguishing pair: the model DID return questions, and validation # rejected all of them — a different fault from "the model returned nothing". assert reported[0]["raw_returned"] == 10 assert reported[0]["drop_reasons"] == {"grammar_needs_two_quoted_segments": 10} def test_nothing_returned_is_distinguishable_from_everything_rejected(): """These need different fixes: one is a prompt/validator mismatch, the other is a failed call or missing context upstream of validation.""" rejected = _diag(raw_returned=10, drop_reasons={"rhetoric_answer_missing_effect": 10}) nothing = _diag(raw_returned=0, drop_reasons={}, batch_failures=["batch1: TimeoutError"]) insights = asyncio.run(_build_generation_insights([ _section("البلاغة", [], rejected), _section("القراءة", [], nothing), ], {}, [])) by_reason = {tuple(d["drop_reasons"]): d for d in insights["section_diagnostics"]} assert by_reason[("rhetoric_answer_missing_effect",)]["raw_returned"] == 10 assert by_reason[()]["batch_failures"] == ["batch1: TimeoutError"] def test_short_sections_are_reported_too(): insights = asyncio.run(_build_generation_insights( [_section("النحو", [{"type": "grammar", "question": "س", "answer": "ج", "difficulty": "easy", "learning_objective": "x"}], _diag(produced=1, status="short"))], {}, [], )) assert insights["section_diagnostics"][0]["status"] == "short" def test_a_complete_exam_reports_no_diagnostics(): """Stays quiet when there's nothing wrong, so a non-empty list always means something needs looking at.""" complete = _diag(type="mcq", produced=10, status="ok", drop_reasons={}) insights = asyncio.run(_build_generation_insights( [_section("الاختيار", [], complete)], {}, [], )) assert insights["section_diagnostics"] == [] def test_exams_generated_before_this_existed_still_build(): """Sections with no diagnostics key at all (older callers) must not crash.""" insights = asyncio.run(_build_generation_insights( [_section("قسم", [])], {}, [], )) assert insights["section_diagnostics"] == [] def test_schema_version_marks_the_new_shape(): insights = asyncio.run(_build_generation_insights([_section("قسم", [])], {}, [])) assert insights["schema_version"] == 3 @pytest.mark.parametrize("payload", [ {"type": "grammar", "requested": 10, "produced": 0, "status": "empty"}, {"type": "mcq", "requested": 5, "produced": 5, "status": "ok", "raw_returned": 6, "drop_reasons": {"too_few_choices": 1}}, ]) def test_diagnostics_model_accepts_the_shapes_the_generator_emits(payload): assert SectionDiagnostics(**payload).requested == payload["requested"] def test_drops_are_reported_even_when_the_section_recovered(): """A question rejected as a duplicate is refilled by the top-up loop, so the section reports `ok` and its drops used to vanish from the report entirely. That hid exactly what we most want to see: whether the generator is repeating itself. Filtering on status alone is not enough.""" recovered = _diag( type="mcq", requested=10, produced=10, status="ok", raw_returned=13, drop_reasons={"template_duplicate": 2, "exact_duplicate": 1}, ) insights = asyncio.run(_build_generation_insights( [_section("الاختيار", [], recovered)], {}, [], )) reported = insights["section_diagnostics"] assert len(reported) == 1 assert reported[0]["status"] == "ok" assert reported[0]["drop_reasons"]["template_duplicate"] == 2 def test_a_clean_full_section_still_reports_nothing(): """The quiet case must stay quiet, or a non-empty list stops meaning 'something needs looking at'.""" clean = _diag(type="mcq", requested=10, produced=10, status="ok", raw_returned=10, drop_reasons={}) insights = asyncio.run(_build_generation_insights( [_section("الاختيار", [], clean)], {}, [], )) assert insights["section_diagnostics"] == []