File size: 11,151 Bytes
fdfe81a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
"""Unit tests for scripts.grader β€” EVAL_MAPPING projection + grading logic.

Covers:
* EVAL_MAPPING projection: synthetic findings produce expected eval categories.
* Matching logic: synthetic agent + GT pairs produce expected TP/FP/FN.
* --cached path: grader runs without invoking run_audit (mock asserts not called).
* Pass-bar: 4 covered eval categories β†’ PASS; 3 β†’ FAIL.
"""
from __future__ import annotations

from dataclasses import dataclass
from unittest.mock import AsyncMock, patch

import pytest

from scripts.grader import (
    EVAL_CATEGORIES,
    EVAL_MAPPING,
    PASS_BAR_MIN,
    GradeResult,
    grade,
    project_findings,
)


# ---------------------------------------------------------------------------
# Minimal FindingLike stub
# ---------------------------------------------------------------------------


@dataclass
class _F:
    """Minimal finding stub that satisfies FindingLike."""

    category: str


# ---------------------------------------------------------------------------
# 1. EVAL_MAPPING projection tests
# ---------------------------------------------------------------------------


class TestEvalMappingProjection:
    def test_known_category_maps_correctly(self) -> None:
        findings = [_F("confidentiality_statement")]
        assert project_findings(findings) == {"confidentiality_statement"}

    def test_slide_title_maps_to_slide_title_position(self) -> None:
        assert project_findings([_F("slide_title")]) == {"slide_title_position"}

    def test_title_slide_maps_to_slide_title_position(self) -> None:
        assert project_findings([_F("title_slide")]) == {"slide_title_position"}

    def test_bullets_maps_to_spacing_and_terminology(self) -> None:
        assert project_findings([_F("bullets")]) == {"spacing", "terminology"}

    def test_chart_content_maps_to_key_vs_legend(self) -> None:
        assert project_findings([_F("chart_content")]) == {"key_vs_legend"}

    def test_table_header_maps_to_table_labeling(self) -> None:
        assert project_findings([_F("table_header")]) == {"table_labeling"}

    def test_footnotes_maps_to_terminology(self) -> None:
        assert project_findings([_F("footnotes")]) == {"terminology"}

    def test_emphasis_annotations_maps_to_empty(self) -> None:
        assert project_findings([_F("emphasis_annotations")]) == set()

    def test_color_palette_maps_to_empty(self) -> None:
        assert project_findings([_F("color_palette")]) == set()

    def test_terminology_maps_to_terminology_and_table_labeling(self) -> None:
        assert project_findings([_F("terminology")]) == {"terminology", "table_labeling"}

    def test_unknown_category_is_ignored(self) -> None:
        assert project_findings([_F("nonexistent_category")]) == set()

    def test_multiple_findings_union(self) -> None:
        findings = [_F("slide_title"), _F("confidentiality_statement"), _F("chart_content")]
        result = project_findings(findings)
        assert result == {
            "slide_title_position",
            "confidentiality_statement",
            "key_vs_legend",
        }

    def test_empty_findings_returns_empty(self) -> None:
        assert project_findings([]) == set()

    def test_all_eval_mapping_values_are_valid_eval_categories(self) -> None:
        valid = set(EVAL_CATEGORIES)
        for rubric_cat, eval_cats in EVAL_MAPPING.items():
            for ec in eval_cats:
                assert ec in valid, (
                    f"EVAL_MAPPING['{rubric_cat}'] contains '{ec}' which is not "
                    f"in EVAL_CATEGORIES"
                )


# ---------------------------------------------------------------------------
# 2. Grading logic tests
# ---------------------------------------------------------------------------


class TestGradingLogic:
    def test_perfect_match_single_slide(self) -> None:
        agent = {1: [_F("confidentiality_statement")]}
        gt = {1: {"confidentiality_statement"}}
        result = grade(agent, gt, total_slides=1)
        assert result.per_category["confidentiality_statement"].tp_count == 1
        assert result.per_category["confidentiality_statement"].fp_count == 0
        assert result.per_category["confidentiality_statement"].fn_count == 0
        assert result.per_slide[0].hit is True

    def test_false_negative_no_agent_findings(self) -> None:
        agent: dict = {}
        gt = {1: {"spacing"}}
        result = grade(agent, gt, total_slides=1)
        stats = result.per_category["spacing"]
        assert stats.tp_count == 0
        assert stats.fn_count == 1
        assert result.per_slide[0].hit is False

    def test_false_positive_agent_fires_no_gt(self) -> None:
        agent = {1: [_F("chart_content")]}  # β†’ key_vs_legend
        gt: dict = {}
        result = grade(agent, gt, total_slides=1)
        stats = result.per_category["key_vs_legend"]
        assert stats.fp_count == 1
        assert stats.tp_count == 0
        assert result.per_slide[0].hit is False

    def test_partial_overlap_counts_as_hit(self) -> None:
        # GT has table_labeling + spacing; agent covers only table_labeling.
        agent = {1: [_F("table_header")]}  # β†’ table_labeling
        gt = {1: {"table_labeling", "spacing"}}
        result = grade(agent, gt, total_slides=1)
        # Slide-level hit is True because there is overlap.
        assert result.per_slide[0].hit is True
        # table_labeling: TP=1, spacing: FN=1
        assert result.per_category["table_labeling"].tp_count == 1
        assert result.per_category["spacing"].fn_count == 1

    def test_multi_slide_deck(self) -> None:
        agent = {
            1: [_F("confidentiality_statement")],
            2: [_F("slide_title")],
            3: [],
        }
        gt = {
            1: {"confidentiality_statement"},
            2: {"slide_title_position"},
            3: {"key_vs_legend"},
        }
        result = grade(agent, gt, total_slides=3)
        assert result.per_slide[0].hit is True
        assert result.per_slide[1].hit is True
        assert result.per_slide[2].hit is False
        assert result.per_category["key_vs_legend"].fn_count == 1

    def test_deck_recall_computation(self) -> None:
        agent = {1: [_F("confidentiality_statement")]}
        gt = {1: {"confidentiality_statement"}, 2: {"spacing"}}
        result = grade(agent, gt, total_slides=2)
        # 1 of 2 GT slides hit β†’ recall = 0.5
        assert result.deck_recall == pytest.approx(0.5)

    def test_deck_precision_computation(self) -> None:
        agent = {1: [_F("confidentiality_statement")], 2: [_F("chart_content")]}
        gt = {1: {"confidentiality_statement"}}
        result = grade(agent, gt, total_slides=2)
        # 1 of 2 agent-active slides hit β†’ precision = 0.5
        assert result.deck_precision == pytest.approx(0.5)

    def test_total_slides_respected(self) -> None:
        result = grade({}, {}, total_slides=10)
        assert result.total_slides == 10
        assert len(result.per_slide) == 10


# ---------------------------------------------------------------------------
# 3. Pass-bar tests
# ---------------------------------------------------------------------------


class TestPassBar:
    def _make_agent_for_cats(self, eval_cats: list[str]) -> dict[int, list[_F]]:
        """Build a single-slide agent dict that covers the given eval categories
        by choosing appropriate rubric categories."""
        cat_to_rubric = {
            "confidentiality_statement": "confidentiality_statement",
            "slide_title_position": "slide_title",
            "table_labeling": "table_header",
            "key_vs_legend": "chart_content",
            "spacing": "chart_title",
            "terminology": "footnotes",
        }
        findings = [_F(cat_to_rubric[ec]) for ec in eval_cats if ec in cat_to_rubric]
        return {1: findings}

    def _make_gt_for_cats(self, eval_cats: list[str]) -> dict[int, set[str]]:
        return {1: set(eval_cats)}

    def test_four_categories_is_pass(self) -> None:
        cats = ["confidentiality_statement", "slide_title_position", "table_labeling", "key_vs_legend"]
        agent = self._make_agent_for_cats(cats)
        gt = self._make_gt_for_cats(cats)
        result = grade(agent, gt, total_slides=1)
        assert result.pass_bar is True
        assert result.categories_with_tp >= PASS_BAR_MIN

    def test_three_categories_is_fail(self) -> None:
        cats = ["confidentiality_statement", "slide_title_position", "table_labeling"]
        agent = self._make_agent_for_cats(cats)
        gt = self._make_gt_for_cats(cats)
        result = grade(agent, gt, total_slides=1)
        assert result.pass_bar is False
        assert result.categories_with_tp < PASS_BAR_MIN

    def test_all_six_categories_is_pass(self) -> None:
        cats = EVAL_CATEGORIES[:]
        agent = self._make_agent_for_cats(cats)
        gt = self._make_gt_for_cats(cats)
        result = grade(agent, gt, total_slides=1)
        assert result.pass_bar is True
        assert result.categories_with_tp == 6

    def test_zero_categories_is_fail(self) -> None:
        result = grade({}, {}, total_slides=1)
        assert result.pass_bar is False
        assert result.categories_with_tp == 0

    def test_pass_bar_min_constant_is_four(self) -> None:
        assert PASS_BAR_MIN == 4


# ---------------------------------------------------------------------------
# 4. --cached path: grader runs without invoking run_audit
# ---------------------------------------------------------------------------


class TestCachedPath:
    """Verify that --cached skips run_audit entirely."""

    def test_cached_does_not_call_run_audit(self, tmp_path: Path) -> None:
        """Simulate the --cached flow: load final.json, grade, assert no run_audit call."""
        import json
        from pathlib import Path as _Path

        from agents.output_schemas import FinalAuditResult

        # Write a minimal final.json to a synthetic run dir.
        run_dir = tmp_path / "calibration_runs" / "synthetic"
        run_dir.mkdir(parents=True)
        payload = {
            "job_id": "calib_test",
            "file_name": "test.pptx",
            "slide_count": 1,
            "summary": {"high": 0, "medium": 0, "low": 0},
            "slides": [],
            "errors": [],
        }
        (run_dir / "final.json").write_text(json.dumps(payload), encoding="utf-8")

        loaded = FinalAuditResult.model_validate(payload)

        mock_run_audit = AsyncMock()

        with patch("agents.runner.run_audit", mock_run_audit):
            # When --cached is used we load from disk; run_audit must NOT be called.
            from scripts.calibrate import _build_agent_findings

            agent_findings = _build_agent_findings(loaded)
            gt: dict = {}
            result = grade(agent_findings, gt, total_slides=loaded.slide_count)

        # The critical assertion: run_audit was never invoked.
        mock_run_audit.assert_not_called()

        # Grader still produces a valid GradeResult.
        assert isinstance(result, GradeResult)
        assert result.total_slides == 1