farient-deckcheck / tests /test_runner.py
Xander Labide
Claude Opus 4.7 (1M context)
Initial commit β€” Farient DeckCheck
fdfe81a
Raw History Blame Contribute Delete
50.6 kB
"""Non-live tests for ``agents.runner.run_audit``. These tests mock ``Runner.run`` so no network calls are made. They cover: * **Bounded concurrency** β€” at most ``MAX_CONCURRENT_SLIDES`` (5) Slide Reviewer calls are ever in flight at once. * **Must-flag guarantee** β€” when every agent returns ZERO findings, the Python orchestrator still emits ``safety_net``-tagged findings for every Jacobs marker hit (slides 1, 6, 7, 23, 24). * **Retry helper** β€” fails twice with ``RateLimitError``, succeeds on the third attempt; verifies 3 calls happened with backoff in between. * **Boundary validation** β€” drops findings with empty ``evidence`` or unknown ``category``. * **Lead Auditor must-flag firewall** β€” even with a Lead Auditor mock that returns an empty result, every Jacobs marker hit becomes a safety_net finding (proving must-flag enforcement is in ``runner.py``, NOT inside the Lead Auditor agent). * **Partial audit** β€” a slide whose final retry fails records an entry in ``FinalAuditResult.errors`` and the audit still completes. """ from __future__ import annotations import asyncio import inspect from pathlib import Path from types import SimpleNamespace from typing import Any import httpx import openai import pytest from agents.context import AuditContext from agents.output_schemas import ( DeckFindings, Finding, FindingExtended, FindingMeta, FinalAuditResult, SeverityCounts, SlideEnvelopeExtended, SlideFindings, ) from agents.runner import ( MAX_CONCURRENT_SLIDES, MAX_RETRY_ATTEMPTS, MUST_FLAG_TERMS, SlideBriefing, _build_safety_net_finding, _finalise, _is_retriable, _python_fallback_merge, _run_with_retry, run_audit, ) from rubric.loader import load_rubric from schemas.parsed import ParsedDeck, ParsedSlide, RunInfo, ShapeInfo from services.markers import Hit, find_text_markers_pure from services.parser import parse_deck from services.renderer import RenderResult _DOC_REF = Path(__file__).parents[3] / "Doc Reference" JACOBS_PATH = _DOC_REF / ( "20260429 Jacobs Assessment of Compensation Peers - DRAFT 20260327 (3).pptx" ) # =========================================================================== # Fixtures # =========================================================================== @pytest.fixture(scope="module") def rubric(): return load_rubric() @pytest.fixture(scope="module") def jacobs_deck() -> ParsedDeck: return parse_deck(JACOBS_PATH) @pytest.fixture def jacobs_ctx(jacobs_deck, rubric, tmp_path) -> AuditContext: return AuditContext( parsed_deck=jacobs_deck, render_result=RenderResult(skipped=True, reason="unit test"), rubric=rubric, out_dir=tmp_path, ) def _synthetic_deck( *, n_slides: int, text_per_slide: dict[int, str] | None = None, ) -> ParsedDeck: text_per_slide = text_per_slide or {} slides: list[ParsedSlide] = [] for i in range(1, n_slides + 1): body = text_per_slide.get(i, f"Slide {i} content") shape = ShapeInfo( shape_id=f"s{i}.shape1", shape_type="TEXT_BOX", name="Body", left=0, top=0, width=1000, height=500, text=body, runs=[], table_cells=[], ) slides.append( ParsedSlide(slide_number=i, shapes=[shape], extracted_text=body) ) return ParsedDeck( slide_count=n_slides, slide_width_emu=12192000, slide_height_emu=6858000, slides=slides, ) # =========================================================================== # Mock Runner machinery # =========================================================================== class _MockRunner: """A drop-in replacement for ``agents.Runner`` for tests. Wraps ``run`` with an in-flight counter so we can verify bounded concurrency. Records every call so we can assert call counts and inputs. """ def __init__(self, side_effect): self._side_effect = side_effect self.calls: list[dict[str, Any]] = [] self._inflight = 0 self.peak_inflight = 0 self._inflight_lock = asyncio.Lock() async def run(self, agent, *, input=None, context=None, max_turns=10, **kwargs): async with self._inflight_lock: self._inflight += 1 self.peak_inflight = max(self.peak_inflight, self._inflight) try: self.calls.append( { "agent_name": agent.name, "input": input, "max_turns": max_turns, } ) # side_effect can be sync or async; return a RunResult-shaped obj. result = self._side_effect(agent, input, context) if inspect.isawaitable(result): result = await result return result finally: async with self._inflight_lock: self._inflight -= 1 def _wrap_as_run_result(final_output: Any) -> Any: """Mimic the SDK RunResult shape that the runner extracts ``final_output`` from.""" return SimpleNamespace(final_output=final_output) # =========================================================================== # 1. Boundary validation β€” empty evidence + unknown category dropped # =========================================================================== def test_finalise_drops_empty_evidence_and_unknown_category(rubric, jacobs_deck, tmp_path): """Boundary validator must drop bad findings before they reach the result.""" ctx = AuditContext( parsed_deck=jacobs_deck, render_result=RenderResult(skipped=True), rubric=rubric, out_dir=tmp_path, ) bogus_extended = FindingExtended( category="title_slide", severity="high", confidence=0.9, title="Drop me β€” empty evidence", description="should be dropped", evidence="", # empty β†’ must be dropped suggested_fix="n/a", guideline_reference="title_slide.no_draft", finding_meta=FindingMeta(source="agent_slide", must_flag=False), ) bad_category = FindingExtended( category="totally_made_up_category", severity="medium", confidence=0.7, title="Drop me β€” unknown category", description="should be dropped", evidence="some text", suggested_fix="n/a", guideline_reference="bogus.rule", finding_meta=FindingMeta(source="agent_slide", must_flag=False), ) keeper = FindingExtended( category="title_slide", severity="medium", confidence=0.85, title="Keep me", description="legit", evidence="real evidence quote", suggested_fix="fix it", guideline_reference="title_slide.no_draft", finding_meta=FindingMeta(source="agent_slide", must_flag=False), ) envelope = SlideEnvelopeExtended( slide_number=2, image_url=None, findings=[bogus_extended, bad_category, keeper], ) lead_result = FinalAuditResult( job_id="t", file_name="x.pptx", slide_count=jacobs_deck.slide_count, summary=SeverityCounts(), slides=[envelope], errors=[], ) final = _finalise( job_id="t", file_name="x.pptx", slide_count=jacobs_deck.slide_count, lead_result=lead_result, marker_hits={n: [] for n in range(1, jacobs_deck.slide_count + 1)}, ctx=ctx, errors=[], ) s2 = final.slides[1] # slide_number=2 titles = [f.title for f in s2.findings] assert "Drop me β€” empty evidence" not in titles assert "Drop me β€” unknown category" not in titles assert "Keep me" in titles # =========================================================================== # 2. Retry helper β€” RateLimitError twice then success # =========================================================================== def _make_rate_limit_error() -> openai.RateLimitError: """Synthesise a RateLimitError without hitting the live API.""" request = httpx.Request("POST", "https://api.openai.com/v1/responses") response = httpx.Response(429, request=request, json={"error": "rate"}) return openai.RateLimitError( message="rate limited", response=response, body={"error": "rate"}, ) def _make_500_error() -> openai.APIStatusError: request = httpx.Request("POST", "https://api.openai.com/v1/responses") response = httpx.Response(503, request=request, json={"error": "boom"}) return openai.APIStatusError( message="server error", response=response, body={"error": "boom"}, ) def _make_400_error() -> openai.BadRequestError: request = httpx.Request("POST", "https://api.openai.com/v1/responses") response = httpx.Response(400, request=request, json={"error": "bad"}) return openai.BadRequestError( message="bad request", response=response, body={"error": "bad"}, ) @pytest.mark.asyncio async def test_run_with_retry_succeeds_after_two_rate_limits(): """Two RateLimitError attempts then success β€” total of 3 invocations.""" sleep_calls: list[float] = [] async def no_sleep(seconds: float): sleep_calls.append(seconds) invocations = {"count": 0} async def factory(): invocations["count"] += 1 if invocations["count"] <= 2: raise _make_rate_limit_error() return "ok" result = await _run_with_retry( factory, label="test", sleep=no_sleep, rng=lambda: 0.0, ) assert result == "ok" assert invocations["count"] == 3, "factory must have been called 3 times" # Two backoff sleeps before attempts 2 and 3 (2s and 4s base + 0 jitter). assert sleep_calls == [2.0, 4.0] @pytest.mark.asyncio async def test_run_with_retry_retries_on_5xx(): """``APIStatusError(>=500)`` is retriable.""" sleeps: list[float] = [] async def no_sleep(s: float): sleeps.append(s) n = {"count": 0} async def factory(): n["count"] += 1 if n["count"] == 1: raise _make_500_error() return "ok" res = await _run_with_retry(factory, label="t", sleep=no_sleep, rng=lambda: 0.0) assert res == "ok" assert n["count"] == 2 @pytest.mark.asyncio async def test_run_with_retry_does_not_retry_on_4xx(): """A non-429 4xx is permanent β€” must propagate without retrying.""" n = {"count": 0} async def factory(): n["count"] += 1 raise _make_400_error() with pytest.raises(openai.BadRequestError): await _run_with_retry(factory, label="t", sleep=_no_sleep, rng=lambda: 0.0) assert n["count"] == 1 @pytest.mark.asyncio async def test_run_with_retry_gives_up_after_max_attempts(): """All 4 attempts hit RateLimit β†’ propagate the last RateLimitError.""" n = {"count": 0} async def factory(): n["count"] += 1 raise _make_rate_limit_error() with pytest.raises(openai.RateLimitError): await _run_with_retry(factory, label="t", sleep=_no_sleep, rng=lambda: 0.0) assert n["count"] == MAX_RETRY_ATTEMPTS def test_is_retriable_classifies_correctly(): assert _is_retriable(_make_rate_limit_error()) is True assert _is_retriable(_make_500_error()) is True assert _is_retriable(openai.APITimeoutError(httpx.Request("GET", "/"))) is True assert _is_retriable(_make_400_error()) is False assert _is_retriable(ValueError("bare exception")) is False async def _no_sleep(_seconds: float) -> None: return None # =========================================================================== # 3. Bounded concurrency β€” semaphore caps in-flight Runner.run at 5 # =========================================================================== @pytest.mark.asyncio async def test_bounded_concurrency_caps_at_5(jacobs_ctx, monkeypatch): """A 33-slide deck with slow mocks must NEVER exceed 5 in flight.""" async def slow_side_effect(agent, input_str, context): # Yield to the event loop so other coroutines can pile up β€” this # demonstrates the semaphore actually bounds concurrency. await asyncio.sleep(0.01) if agent.name == "Slide Reviewer": # Extract slide_number from the briefing JSON. import json try: payload = json.loads(input_str) slide_n = payload["slide_number"] except Exception: # noqa: BLE001 slide_n = 1 return _wrap_as_run_result(SlideFindings(slide_number=slide_n, findings=[])) if agent.name == "Deck Consistency": return _wrap_as_run_result(DeckFindings(findings=[])) if agent.name == "Lead Auditor": return _wrap_as_run_result( FinalAuditResult( job_id="job1", file_name="jacobs.pptx", slide_count=jacobs_ctx.parsed_deck.slide_count, summary=SeverityCounts(), slides=[], errors=[], ) ) raise AssertionError(f"unexpected agent: {agent.name}") mock = _MockRunner(slow_side_effect) final = await run_audit( jacobs_ctx, job_id="job1", file_name="jacobs.pptx", runner=mock, ) assert isinstance(final, FinalAuditResult) # Slide-reviewer calls = 33; plus 1 deck consistency + 1 lead auditor. slide_calls = [c for c in mock.calls if c["agent_name"] == "Slide Reviewer"] assert len(slide_calls) == jacobs_ctx.parsed_deck.slide_count # The peak in-flight count across ALL agents must be <= 5. # (Deck Consistency and Lead Auditor run after slides β€” they shouldn't # push the peak above 5 either.) assert mock.peak_inflight <= MAX_CONCURRENT_SLIDES, ( f"peak in-flight {mock.peak_inflight} exceeded {MAX_CONCURRENT_SLIDES}" ) # =========================================================================== # 4. Must-flag guarantee β€” agents return ZERO findings; safety_net still fires # =========================================================================== @pytest.mark.asyncio async def test_must_flag_safety_net_fires_when_agents_return_nothing(jacobs_ctx): """The most important test: the Python guarantee must hold even if every LLM call returns no findings. Every marker hit on Jacobs slides 1, 6, 7, 23, 24 must end up in the final result as a safety_net finding with finding_meta.source='safety_net' and finding_meta.must_flag=True. """ async def empty_side_effect(agent, input_str, context): if agent.name == "Slide Reviewer": import json payload = json.loads(input_str) slide_n = payload["slide_number"] return _wrap_as_run_result(SlideFindings(slide_number=slide_n, findings=[])) if agent.name == "Deck Consistency": return _wrap_as_run_result(DeckFindings(findings=[])) if agent.name == "Lead Auditor": # Lead Auditor returns ZERO findings β€” proves must-flag enforcement # does NOT depend on the Lead Auditor adding them. return _wrap_as_run_result( FinalAuditResult( job_id="job1", file_name="jacobs.pptx", slide_count=jacobs_ctx.parsed_deck.slide_count, summary=SeverityCounts(), slides=[ SlideEnvelopeExtended(slide_number=n, image_url=None, findings=[]) for n in range(1, jacobs_ctx.parsed_deck.slide_count + 1) ], errors=[], ) ) raise AssertionError(f"unexpected: {agent.name}") mock = _MockRunner(empty_side_effect) final = await run_audit( jacobs_ctx, job_id="job1", file_name="jacobs.pptx", runner=mock, ) # The marker-related safety_net rule_ids in the rubric. Scope this # assertion to JUST marker findings β€” post-determinism-fix the runner # also injects safety_net findings for confidentiality / palette # violations on every slide of the Jacobs deck, but those are NOT # must_flag and have different rule_ids. marker_rule_ids = { "title_slide.no_draft", "writing_style.no_internal_comments", } expected_slides = {1, 6, 7, 23, 24} actual_slides = set() for env in final.slides: for f in env.findings: if f.finding_meta.source != "safety_net": continue if f.guideline_reference not in marker_rule_ids: continue # confidentiality / palette safety_nets β€” different contract actual_slides.add(env.slide_number) # Acceptance: every marker safety_net has must_flag=True. assert f.finding_meta.must_flag is True # Severity must be high (DRAFT/TW question/Page to be updated). assert f.severity == "high" # Evidence must be non-empty. assert f.evidence.strip() assert actual_slides == expected_slides, ( f"expected marker safety_net findings on {expected_slides}, " f"got {actual_slides}" ) @pytest.mark.asyncio async def test_safety_net_always_injected_even_when_agent_covered_hit(jacobs_ctx): """Determinism contract (post-regression-fix): the safety_net for a marker hit is ALWAYS injected, regardless of whether the LLM already produced a finding quoting the same marker. Rationale: at temperature=1, the LLM's choice to surface the marker is stochastic. The previous "suppress when agent covers" logic let counts of marker-related findings drift across repeated runs of the same deck. The fix is to pin marker findings to a Python floor β€” one safety_net per hit, deterministically. The LLM finding (if any) is kept alongside and gets its finding_meta.must_flag promoted to True so the dashboard badges it. """ async def smart_side(agent, input_str, context): if agent.name == "Slide Reviewer": import json payload = json.loads(input_str) slide_n = payload["slide_number"] findings = [] if slide_n == 1: # Agent quotes DRAFT in its evidence. Old behaviour: safety_net # would be suppressed. New behaviour: safety_net still fires. findings = [ Finding( category="title_slide", severity="high", confidence=0.95, title="DRAFT designator on title slide", description="Title slide carries DRAFT.", evidence="April 29, 2026 – DRAFT 20260327", suggested_fix="Remove DRAFT.", guideline_reference="title_slide.no_draft", ) ] return _wrap_as_run_result( SlideFindings(slide_number=slide_n, findings=findings) ) if agent.name == "Deck Consistency": return _wrap_as_run_result(DeckFindings(findings=[])) if agent.name == "Lead Auditor": # Echo the slide-1 finding into the merge result (extended shape). slides = [] for n in range(1, jacobs_ctx.parsed_deck.slide_count + 1): if n == 1: slides.append( SlideEnvelopeExtended( slide_number=1, image_url=None, findings=[ FindingExtended( category="title_slide", severity="high", confidence=0.95, title="DRAFT designator on title slide", description="Title slide carries DRAFT.", evidence="April 29, 2026 – DRAFT 20260327", suggested_fix="Remove DRAFT.", guideline_reference="title_slide.no_draft", finding_meta=FindingMeta( source="agent_slide", must_flag=False ), ) ], ) ) else: slides.append( SlideEnvelopeExtended( slide_number=n, image_url=None, findings=[] ) ) return _wrap_as_run_result( FinalAuditResult( job_id="job1", file_name="jacobs.pptx", slide_count=jacobs_ctx.parsed_deck.slide_count, summary=SeverityCounts(), slides=slides, errors=[], ) ) raise AssertionError(agent.name) mock = _MockRunner(smart_side) final = await run_audit(jacobs_ctx, job_id="job1", file_name="jacobs.pptx", runner=mock) s1 = final.slides[0] # New contract: agent finding is kept AND a safety_net finding is appended. sources = [f.finding_meta.source for f in s1.findings] assert "agent_slide" in sources, "agent finding must be retained" assert "safety_net" in sources, ( "safety_net must be injected even when agent covered the hit" ) # The agent finding's must_flag is promoted to True due to overlap. agent_findings = [f for f in s1.findings if f.finding_meta.source == "agent_slide"] assert all(f.finding_meta.must_flag is True for f in agent_findings) # The OTHER must-flag slides (6, 7, 23, 24) all still get safety_net findings. for n in (6, 7, 23, 24): env = final.slides[n - 1] sn = [f for f in env.findings if f.finding_meta.source == "safety_net"] assert len(sn) >= 1, f"slide {n} missing safety_net finding" # =========================================================================== # 5. Lead Auditor source code MUST NOT contain safety_net injection logic # =========================================================================== def test_lead_auditor_module_does_not_inject_safety_net(): """Static guard: must-flag enforcement lives in runner.py, not lead_auditor.py.""" import agents.lead_auditor as la src_path = Path(la.__file__) src = src_path.read_text(encoding="utf-8") # The string 'safety_net' must not appear as injection logic in lead_auditor. # It may appear in the prompt prose ONLY via the Markdown file β€” not here. assert "safety_net" not in src, ( "lead_auditor.py must not contain 'safety_net' β€” that logic belongs to runner.py" ) # Also: no SDK handoffs. assert "handoffs=" not in src and "Handoff(" not in src # =========================================================================== # 6. Partial audit β€” a slide whose retry budget is exhausted records an error # =========================================================================== @pytest.mark.asyncio async def test_partial_audit_when_one_slide_fails_permanently(jacobs_ctx, monkeypatch): """If slide 3's retries all fail, it ends up in errors[]; other slides succeed.""" # Patch sleep so retries don't actually wait. import agents.runner as runner_module async def no_sleep(_): return None real_with_retry = runner_module._run_with_retry async def patched_with_retry(coro_factory, *, label, **kwargs): return await real_with_retry( coro_factory, label=label, sleep=no_sleep, rng=lambda: 0.0, ) monkeypatch.setattr(runner_module, "_run_with_retry", patched_with_retry) async def side(agent, input_str, context): if agent.name == "Slide Reviewer": import json payload = json.loads(input_str) slide_n = payload["slide_number"] if slide_n == 3: # Permanent rate limit β€” exhausts retries. raise _make_rate_limit_error() return _wrap_as_run_result(SlideFindings(slide_number=slide_n, findings=[])) if agent.name == "Deck Consistency": return _wrap_as_run_result(DeckFindings(findings=[])) if agent.name == "Lead Auditor": return _wrap_as_run_result( FinalAuditResult( job_id="job1", file_name="jacobs.pptx", slide_count=jacobs_ctx.parsed_deck.slide_count, summary=SeverityCounts(), slides=[ SlideEnvelopeExtended(slide_number=n, image_url=None, findings=[]) for n in range(1, jacobs_ctx.parsed_deck.slide_count + 1) ], errors=[], ) ) raise AssertionError(agent.name) mock = _MockRunner(side) final = await run_audit(jacobs_ctx, job_id="job1", file_name="jacobs.pptx", runner=mock) # The runner MUST NOT have aborted the whole audit. assert isinstance(final, FinalAuditResult) # Slide 3's failure must be recorded. assert any("slide 3" in e for e in final.errors), ( f"expected slide 3 failure in errors, got {final.errors!r}" ) # The other 32 slides must still appear in the result. assert len(final.slides) == jacobs_ctx.parsed_deck.slide_count # =========================================================================== # 7. _build_safety_net_finding β€” schema correctness on synthetic hit # =========================================================================== def test_build_safety_net_finding_uses_rubric_metadata(rubric): hit = Hit( term="DRAFT", offset=10, context_window="Some - DRAFT 20260327", source="shape", shape_id="s1.shape1", ) f = _build_safety_net_finding( slide_n=1, hit=hit, must_flag_meta=rubric.metadata.must_flag_markers, ) assert isinstance(f, FindingExtended) assert f.category == "title_slide" assert f.severity == "high" assert f.finding_meta.source == "safety_net" assert f.finding_meta.must_flag is True assert f.guideline_reference == "title_slide.no_draft" assert "DRAFT" in f.evidence assert "slide 1" in f.title.lower() assert f.confidence == 1.0 def test_build_safety_net_finding_for_internal_comment(rubric): hit = Hit( term="TW question", offset=0, context_window="TW question - Is Accenture US?", source="shape", shape_id="s7.shape1", ) f = _build_safety_net_finding( slide_n=7, hit=hit, must_flag_meta=rubric.metadata.must_flag_markers, ) assert f.category == "writing_style" assert f.severity == "high" assert f.guideline_reference == "writing_style.no_internal_comments" assert f.finding_meta.must_flag is True # =========================================================================== # 8. Strict PRD shape β€” Finding (no finding_meta) vs FindingExtended # =========================================================================== def test_finding_strict_shape_has_no_finding_meta_field(): """The strict PRD shape MUST be Finding (no finding_meta) β€” verify the serialised JSON Schema does not contain a finding_meta property.""" schema = Finding.model_json_schema() assert "finding_meta" not in schema.get("properties", {}) expected = { "category", "severity", "confidence", "title", "description", "evidence", "suggested_fix", "guideline_reference", } assert set(schema["properties"].keys()) == expected def test_finding_extended_shape_adds_only_finding_meta(): schema = FindingExtended.model_json_schema() expected = { "category", "severity", "confidence", "title", "description", "evidence", "suggested_fix", "guideline_reference", "finding_meta", } assert set(schema["properties"].keys()) == expected def test_strict_dump_drops_finding_meta_via_exclude(): """When serialising a FindingExtended for export, exclude={'finding_meta'} must work.""" fe = FindingExtended( category="title_slide", severity="high", confidence=0.9, title="t", description="d", evidence="e", suggested_fix="s", guideline_reference="title_slide.no_draft", finding_meta=FindingMeta(source="agent_slide", must_flag=False), ) dumped = fe.model_dump(exclude={"finding_meta"}) assert "finding_meta" not in dumped assert set(dumped.keys()) == { "category", "severity", "confidence", "title", "description", "evidence", "suggested_fix", "guideline_reference", } # =========================================================================== # 9. Python fallback merge β€” produces a usable result without an LLM # =========================================================================== def test_python_fallback_merge_assembles_envelopes(): sf1 = SlideFindings( slide_number=1, findings=[ Finding( category="title_slide", severity="high", confidence=0.9, title="t", description="d", evidence="ev", suggested_fix="s", guideline_reference="title_slide.no_draft", ) ], ) sf2 = SlideFindings(slide_number=2, findings=[]) df = DeckFindings( findings=[ Finding( category="terminology", severity="medium", confidence=0.8, title="drift", description="slides 1+2", evidence="quote A vs quote B", suggested_fix="align", guideline_reference="terminology.consistent", ) ] ) final = _python_fallback_merge( job_id="j", file_name="x.pptx", slide_count=2, slide_findings_by_n={1: sf1, 2: sf2}, deck_findings=df, ) assert final.slide_count == 2 s1 = final.slides[0] assert len(s1.findings) == 2 # 1 slide + 1 deck (parked on slide 1) sources = sorted({f.finding_meta.source for f in s1.findings}) assert sources == ["agent_deck", "agent_slide"] # =========================================================================== # 10. End-to-end run_audit on synthetic deck β€” must-flag injection works # =========================================================================== @pytest.mark.asyncio async def test_run_audit_synthetic_must_flag_injection(rubric, tmp_path): """A 3-slide synthetic deck where slide 2 has 'DRAFT' in its body.""" deck = _synthetic_deck( n_slides=3, text_per_slide={ 1: "Title page", 2: "Quarterly report β€” DRAFT for review only", 3: "Conclusion", }, ) ctx = AuditContext( parsed_deck=deck, render_result=RenderResult(skipped=True), rubric=rubric, out_dir=tmp_path, ) async def empty(agent, input_str, context): if agent.name == "Slide Reviewer": import json payload = json.loads(input_str) return _wrap_as_run_result( SlideFindings(slide_number=payload["slide_number"], findings=[]) ) if agent.name == "Deck Consistency": return _wrap_as_run_result(DeckFindings(findings=[])) if agent.name == "Lead Auditor": return _wrap_as_run_result( FinalAuditResult( job_id="syn", file_name="syn.pptx", slide_count=3, summary=SeverityCounts(), slides=[ SlideEnvelopeExtended(slide_number=n, image_url=None, findings=[]) for n in (1, 2, 3) ], errors=[], ) ) raise AssertionError(agent.name) mock = _MockRunner(empty) final = await run_audit(ctx, job_id="syn", file_name="syn.pptx", runner=mock) # Slide 2 must have the safety_net DRAFT finding (writing_style category β€” # the rubric maps the 'DRAFT' marker via must_flag_markers; on a body # shape it routes to title_slide.no_draft if the term is exactly 'DRAFT'). s2 = final.slides[1] draft_sn = [ f for f in s2.findings if f.finding_meta.source == "safety_net" and f.guideline_reference == "title_slide.no_draft" ] assert len(draft_sn) == 1 assert draft_sn[0].category == "title_slide" assert draft_sn[0].severity == "high" assert draft_sn[0].finding_meta.must_flag is True # NOTE (post-determinism-fix): the runner now also injects deterministic # safety_net findings for missing/mispositioned confidentiality # statements. The synthetic deck has no confidentiality footer on any # slide, so EVERY slide gets one such finding. We assert the expected # marker finding still exists and that confidentiality safety_net # findings appear on every slide. for n in (1, 2, 3): env = final.slides[n - 1] conf = [ f for f in env.findings if f.finding_meta.source == "safety_net" and f.category == "confidentiality_statement" ] assert len(conf) == 1, ( f"slide {n}: expected exactly one confidentiality safety_net " f"finding, got {[f.title for f in env.findings]}" ) # Summary is recomputed: 1 DRAFT high + 3 confidentiality high = 4. assert final.summary.high == 4 assert final.summary.medium == 0 assert final.summary.low == 0 # =========================================================================== # 11. on_slide_done callback fires once per slide + initial tick # =========================================================================== @pytest.mark.asyncio async def test_progress_callback_fires_per_slide(rubric, tmp_path): """on_slide_done must be called: once with (0, 3) before the gather, then once per slide as each reviewer settles β€” 4 calls total ending at (3, 3). Intermediate values may arrive in any order due to concurrency. """ deck = _synthetic_deck(n_slides=3) ctx = AuditContext( parsed_deck=deck, render_result=RenderResult(skipped=True), rubric=rubric, out_dir=tmp_path, ) async def empty(agent, input_str, context): if agent.name == "Slide Reviewer": import json payload = json.loads(input_str) return _wrap_as_run_result( SlideFindings(slide_number=payload["slide_number"], findings=[]) ) if agent.name == "Deck Consistency": return _wrap_as_run_result(DeckFindings(findings=[])) if agent.name == "Lead Auditor": return _wrap_as_run_result( FinalAuditResult( job_id="t", file_name="t.pptx", slide_count=3, summary=SeverityCounts(), slides=[ SlideEnvelopeExtended(slide_number=n, image_url=None, findings=[]) for n in (1, 2, 3) ], errors=[], ) ) raise AssertionError(agent.name) ticks: list[tuple[int, int]] = [] def callback(completed: int, total: int) -> None: ticks.append((completed, total)) mock = _MockRunner(empty) await run_audit(ctx, job_id="t", runner=mock, on_slide_done=callback) # 1 initial tick + 3 per-slide ticks = 4 total assert len(ticks) == 4, f"expected 4 ticks, got {len(ticks)}: {ticks}" # First tick is always the 0/N initialisation. assert ticks[0] == (0, 3), f"first tick must be (0, 3), got {ticks[0]}" # Final tick must show all slides complete. assert ticks[-1] == (3, 3), f"last tick must be (3, 3), got {ticks[-1]}" # All totals must be 3. assert all(t == 3 for _, t in ticks), f"all totals must be 3: {ticks}" # =========================================================================== # 12. Determinism regression β€” single-shot safety_net counts are bit-stable # =========================================================================== # # These tests pin down the regression discovered when two consecutive audits # of the same Jacobs deck produced 48 vs 14 findings. Root cause: the # deterministic Python checks (text_markers, confidentiality, palette) were # being passed as advisory data into the LLM prompt at temperature=1, and # the model was stochastically choosing not to surface them. The fix in # ``runner.py::_finalise`` promotes those checks to ALWAYS-fire safety_net # findings post-LLM, independent of what the LLM emitted. @pytest.mark.asyncio async def test_single_shot_draft_safety_net_fires_with_empty_llm_output(jacobs_ctx, monkeypatch): """Determinism floor (text_markers): even when the (mocked) LLM returns EMPTY SlideFindings β€” the worst case at temp=1 β€” every Jacobs DRAFT/ TW-question/Page-to-be-updated hit must surface as a safety_net finding. This is the regression test for the 48->14 finding drop: when the LLM skipped the marker-related findings, the prior code suppressed the safety_net too because it incorrectly considered the absent finding as "covered". The fix decouples safety_net injection from LLM output entirely. """ monkeypatch.setenv("SLIDE_REVIEWER_MODE", "single_shot") async def empty(agent, input_str, context): if agent.name == "Slide Reviewer": # Single-shot input is a list[dict]; agentic input is a JSON # string. The runner accepts both shapes β€” we only need to # return an empty SlideFindings keyed to the right slide. slide_n: int if isinstance(input_str, list): # Multimodal content β€” find the input_text part. content = input_str[0].get("content", []) text_part = next( (p for p in content if p.get("type") == "input_text"), None, ) import json as _json payload = _json.loads(text_part["text"]) if text_part else {} slide_n = payload.get("slide_number", 1) else: import json as _json slide_n = _json.loads(input_str)["slide_number"] return _wrap_as_run_result( SlideFindings(slide_number=slide_n, findings=[]) ) if agent.name == "Deck Consistency": return _wrap_as_run_result(DeckFindings(findings=[])) if agent.name == "Lead Auditor": return _wrap_as_run_result( FinalAuditResult( job_id="d", file_name="jacobs.pptx", slide_count=jacobs_ctx.parsed_deck.slide_count, summary=SeverityCounts(), slides=[ SlideEnvelopeExtended(slide_number=n, image_url=None, findings=[]) for n in range(1, jacobs_ctx.parsed_deck.slide_count + 1) ], errors=[], ) ) raise AssertionError(agent.name) mock = _MockRunner(empty) final = await run_audit( jacobs_ctx, job_id="d", file_name="jacobs.pptx", runner=mock, ) # Every safety_net finding tied to an internal-marker rule must be high # severity and must_flag=True β€” regardless of LLM output. marker_rule_ids = {"title_slide.no_draft", "writing_style.no_internal_comments"} sn_marker_findings = [ f for env in final.slides for f in env.findings if f.finding_meta.source == "safety_net" and f.guideline_reference in marker_rule_ids ] assert len(sn_marker_findings) >= 5, ( "Jacobs deck has at least 5 known marker hits across slides " "1, 6, 7, 23, 24 β€” every one must produce a safety_net finding " "even when the LLM returned empty output." ) for f in sn_marker_findings: assert f.severity == "high" assert f.finding_meta.must_flag is True assert f.finding_meta.source == "safety_net" @pytest.mark.asyncio async def test_single_shot_safety_net_counts_identical_across_5_runs( jacobs_ctx, monkeypatch ): """Run the same deck 5 times with a stochastic mock LLM (different findings each time) and verify the count of safety_net-source findings is identical across all runs. This is the headline determinism contract for the fix: LLM stochasticity must NOT change the count of deterministic safety_net findings. """ monkeypatch.setenv("SLIDE_REVIEWER_MODE", "single_shot") import random as _r async def stochastic(agent, input_str, context): if agent.name == "Slide Reviewer": slide_n: int if isinstance(input_str, list): content = input_str[0].get("content", []) text_part = next( (p for p in content if p.get("type") == "input_text"), None, ) import json as _json payload = _json.loads(text_part["text"]) if text_part else {} slide_n = payload.get("slide_number", 1) else: import json as _json slide_n = _json.loads(input_str)["slide_number"] # Stochastic: sometimes emit a finding mentioning DRAFT, sometimes # not. This simulates the real bug β€” the LLM at temp=1 picking # different subsets of issues to surface across runs. findings: list[Finding] = [] if _r.random() < 0.5: findings.append( Finding( category="title_slide", severity="high", confidence=0.9, title=f"Stochastic finding on slide {slide_n}", description=f"Random emission for slide {slide_n}.", evidence=f"DRAFT marker on slide {slide_n}", suggested_fix="Remove DRAFT.", guideline_reference="title_slide.no_draft", ) ) return _wrap_as_run_result( SlideFindings(slide_number=slide_n, findings=findings) ) if agent.name == "Deck Consistency": return _wrap_as_run_result(DeckFindings(findings=[])) if agent.name == "Lead Auditor": return _wrap_as_run_result( FinalAuditResult( job_id="r", file_name="jacobs.pptx", slide_count=jacobs_ctx.parsed_deck.slide_count, summary=SeverityCounts(), slides=[ SlideEnvelopeExtended(slide_number=n, image_url=None, findings=[]) for n in range(1, jacobs_ctx.parsed_deck.slide_count + 1) ], errors=[], ) ) raise AssertionError(agent.name) safety_net_counts: list[int] = [] text_marker_counts: list[int] = [] confidentiality_counts: list[int] = [] for _ in range(5): # Re-seed each run differently to amplify stochasticity. _r.seed() mock = _MockRunner(stochastic) final = await run_audit( jacobs_ctx, job_id="r", file_name="jacobs.pptx", runner=mock, ) sn_total = 0 sn_marker = 0 sn_conf_high = 0 marker_rule_ids = { "title_slide.no_draft", "writing_style.no_internal_comments", } for env in final.slides: for f in env.findings: if f.finding_meta.source != "safety_net": continue sn_total += 1 if f.guideline_reference in marker_rule_ids: sn_marker += 1 if ( f.category == "confidentiality_statement" and f.severity == "high" ): sn_conf_high += 1 safety_net_counts.append(sn_total) text_marker_counts.append(sn_marker) confidentiality_counts.append(sn_conf_high) assert len(set(safety_net_counts)) == 1, ( f"safety_net total count drifted across runs: {safety_net_counts}" ) assert len(set(text_marker_counts)) == 1, ( f"text_marker safety_net count drifted: {text_marker_counts}" ) assert len(set(confidentiality_counts)) == 1, ( f"confidentiality_statement(high) safety_net count drifted: " f"{confidentiality_counts}" ) # =========================================================================== # 13. Confidentiality + palette deterministic injectors β€” unit coverage # =========================================================================== def test_confidentiality_violates_logic(): """``_confidentiality_violates`` must fire for absent OR mispositioned.""" from agents.runner import _confidentiality_violates from services.confidentiality import ConfidentialityCheck # Absent β†’ violates. cc_absent = ConfidentialityCheck( present=False, exact_match=False, position_hint="absent", matched_excerpt=None, matching_shape_id=None, ) assert _confidentiality_violates(cc_absent) is True # Header β†’ violates. cc_header = ConfidentialityCheck( present=True, exact_match=True, position_hint="header", matched_excerpt="Confidential", matching_shape_id="s1.shape1", ) assert _confidentiality_violates(cc_header) is True # Body β†’ violates. cc_body = ConfidentialityCheck( present=True, exact_match=True, position_hint="body", matched_excerpt="Confidential", matching_shape_id="s1.shape1", ) assert _confidentiality_violates(cc_body) is True # Footer β†’ satisfies. cc_footer = ConfidentialityCheck( present=True, exact_match=True, position_hint="footer", matched_excerpt="Confidential", matching_shape_id="s1.shape1", ) assert _confidentiality_violates(cc_footer) is False def test_offpalette_hexes_for_slide_filters_grayscale_and_allowed(rubric): """``_offpalette_hexes_for_slide`` keeps only non-grayscale, off-palette run colors β€” and de-dupes by first occurrence for stable ordering.""" from agents.runner import _offpalette_hexes_for_slide # Build a tiny synthetic deck with three runs: one allowed-palette color, # one off-palette color, one grayscale (must be filtered out), and a # repeat of the off-palette color (must be de-duped). allowed = [] for rule in rubric.rules: if rule.category == "color_palette" and rule.metadata and rule.metadata.allowed_hex: allowed = [h.lstrip("#").upper() for h in rule.metadata.allowed_hex] break assert allowed, "rubric must have a color_palette rule with allowed_hex" in_palette = allowed[0] off_palette = "112233" if "112233" not in {a.upper() for a in allowed} else "778899" runs = [ RunInfo(text="a", font_size_pt=10.0, color_rgb=in_palette), RunInfo(text="b", font_size_pt=10.0, color_rgb=off_palette), RunInfo(text="c", font_size_pt=10.0, color_rgb="888888"), # grayscale RunInfo(text="d", font_size_pt=10.0, color_rgb=off_palette), # dupe ] shape = ShapeInfo( shape_id="s1.shape1", shape_type="TEXT_BOX", name="t", left=0, top=0, width=100, height=100, text="abcd", runs=runs, table_cells=[], ) slide = ParsedSlide(slide_number=1, shapes=[shape], extracted_text="abcd") deck = ParsedDeck( slide_count=1, slide_width_emu=12192000, slide_height_emu=6858000, slides=[slide], ) out = _offpalette_hexes_for_slide(deck, 1, allowed) assert out == [off_palette], f"expected [{off_palette!r}], got {out}" def test_finalise_injects_confidentiality_and_palette_safety_nets( rubric, tmp_path ): """End-to-end on a synthetic deck with no confidentiality footer and an off-palette run color: ``_finalise`` must add a confidentiality safety_net AND a palette safety_net even when the LLM produced nothing.""" from agents.runner import _finalise # Pick an off-palette color that isn't in the rubric's allowed list. allowed = [] for rule in rubric.rules: if rule.category == "color_palette" and rule.metadata and rule.metadata.allowed_hex: allowed = [h.lstrip("#").upper() for h in rule.metadata.allowed_hex] break off_palette = "FF00FF" if "FF00FF" not in {a.upper() for a in allowed} else "00FFFF" runs = [RunInfo(text="x", font_size_pt=10.0, color_rgb=off_palette)] shape = ShapeInfo( shape_id="s1.shape1", shape_type="TEXT_BOX", name="body", left=0, top=0, width=100, height=100, text="x", runs=runs, table_cells=[], ) slide = ParsedSlide(slide_number=1, shapes=[shape], extracted_text="x") deck = ParsedDeck( slide_count=1, slide_width_emu=12192000, slide_height_emu=6858000, slides=[slide], ) ctx = AuditContext( parsed_deck=deck, render_result=RenderResult(skipped=True), rubric=rubric, out_dir=tmp_path, ) lead_result = FinalAuditResult( job_id="t", file_name="t.pptx", slide_count=1, summary=SeverityCounts(), slides=[SlideEnvelopeExtended(slide_number=1, image_url=None, findings=[])], errors=[], ) final = _finalise( job_id="t", file_name="t.pptx", slide_count=1, lead_result=lead_result, marker_hits={1: []}, ctx=ctx, errors=[], ) findings = final.slides[0].findings cats = {f.category for f in findings if f.finding_meta.source == "safety_net"} assert "confidentiality_statement" in cats, ( f"expected confidentiality safety_net, got categories: {cats}" ) assert "color_palette" in cats, ( f"expected color_palette safety_net, got categories: {cats}" )
"""Non-live tests for ``agents.runner.run_audit``.
These tests mock ``Runner.run`` so no network calls are made. They cover:
* **Bounded concurrency** β€” at most ``MAX_CONCURRENT_SLIDES`` (5) Slide
Reviewer calls are ever in flight at once.
* **Must-flag guarantee** β€” when every agent returns ZERO findings, the
Python orchestrator still emits ``safety_net``-tagged findings for every
Jacobs marker hit (slides 1, 6, 7, 23, 24).
* **Retry helper** β€” fails twice with ``RateLimitError``, succeeds on the
third attempt; verifies 3 calls happened with backoff in between.
* **Boundary validation** β€” drops findings with empty ``evidence`` or
unknown ``category``.
* **Lead Auditor must-flag firewall** β€” even with a Lead Auditor mock that
returns an empty result, every Jacobs marker hit becomes a safety_net
finding (proving must-flag enforcement is in ``runner.py``, NOT inside
the Lead Auditor agent).
* **Partial audit** β€” a slide whose final retry fails records an entry in
``FinalAuditResult.errors`` and the audit still completes.
"""
from __future__ import annotations
import asyncio
import inspect
from pathlib import Path
from types import SimpleNamespace
from typing import Any
import httpx
import openai
import pytest
from agents.context import AuditContext
from agents.output_schemas import (
DeckFindings,
Finding,
FindingExtended,
FindingMeta,
FinalAuditResult,
SeverityCounts,
SlideEnvelopeExtended,
SlideFindings,
)
from agents.runner import (
MAX_CONCURRENT_SLIDES,
MAX_RETRY_ATTEMPTS,
MUST_FLAG_TERMS,
SlideBriefing,
_build_safety_net_finding,
_finalise,
_is_retriable,
_python_fallback_merge,
_run_with_retry,
run_audit,
)
from rubric.loader import load_rubric
from schemas.parsed import ParsedDeck, ParsedSlide, RunInfo, ShapeInfo
from services.markers import Hit, find_text_markers_pure
from services.parser import parse_deck
from services.renderer import RenderResult
_DOC_REF = Path(__file__).parents[3] / "Doc Reference"
JACOBS_PATH = _DOC_REF / (
"20260429 Jacobs Assessment of Compensation Peers - DRAFT 20260327 (3).pptx"
)
# ===========================================================================
# Fixtures
# ===========================================================================
@pytest.fixture(scope="module")
def rubric():
return load_rubric()
@pytest.fixture(scope="module")
def jacobs_deck() -> ParsedDeck:
return parse_deck(JACOBS_PATH)
@pytest.fixture
def jacobs_ctx(jacobs_deck, rubric, tmp_path) -> AuditContext:
return AuditContext(
parsed_deck=jacobs_deck,
render_result=RenderResult(skipped=True, reason="unit test"),
rubric=rubric,
out_dir=tmp_path,
)
def _synthetic_deck(
*, n_slides: int, text_per_slide: dict[int, str] | None = None,
) -> ParsedDeck:
text_per_slide = text_per_slide or {}
slides: list[ParsedSlide] = []
for i in range(1, n_slides + 1):
body = text_per_slide.get(i, f"Slide {i} content")