"""An interrupted critic is not a verdict (issue #256). A critic pod that fleetd's shutdown stops (or that dies of an infra failure) reviewed nothing. The attempt must stay `review` and be re-driven on the next tick — the same shape as the no-room wait (#246) — instead of parking the run on "review advisory: the critic returned no verdict line". Only a critic that ran to completion without a `VERDICT:` line counts as "no verdict line". """ from __future__ import annotations import asyncio from datetime import datetime, timedelta from types import SimpleNamespace from unittest.mock import AsyncMock import pytest from wp2_support import make_attempt, make_config, make_reconcile, seed_model from fleet.gitea import FakeGitea from fleet.model import FailureClass, Outcome, State, Tier, Verdict from fleet.sentinel import SentinelResult @pytest.mark.parametrize("expired_retry_window", [False, True]) async def test_shutdown_marks_live_critic_and_discards_partial_approval(store, tmp_path, expired_retry_window): run, attempt = await make_attempt(store, state=State.REVIEW) await seed_model(store) loop = make_reconcile(store, make_config(tmp_path), FakeGitea(), tmp_path) if expired_retry_window: loop._review_clock_s = AsyncMock(return_value=loop.cfg.review_routing.call_wall_s + 1) sentinel = SimpleNamespace(cleanup=AsyncMock(), shutting_down=False) observed = [] async def run_attempt(*args, **kwargs): loop.begin_shutdown() observed.append(sentinel.shutting_down) # DSH can exit zero during SIGTERM with empty or partial output. return SentinelResult( attempt_id=attempt.id, outcome=Outcome.DONE, head_sha="a" * 40, summary="VERDICT: approved" ) sentinel.run_attempt = run_attempt loop.sentinel_factory = lambda: sentinel assert await loop.run_critic(run, attempt) is None assert observed == [True] assert (await store.get_attempt(attempt.id)).state is State.REVIEW assert await store.list_events(attempt.id, kind="verdict") == [] assert await store.list_events(attempt.id, kind="review.result") == [] assert attempt.id not in loop._sentinels async def test_review_lease_is_renewed_during_provisioning(store, tmp_path, monkeypatch): from fleet.lease import Lease run, attempt = await make_attempt(store, state=State.REVIEW) model = await seed_model(store) loop = make_reconcile(store, make_config(tmp_path), FakeGitea(), tmp_path) renewed = asyncio.Event() original = loop.lease.heartbeat async def heartbeat(aid): value = await original(aid) renewed.set() return value monkeypatch.setattr(Lease, "heartbeat_interval_s", property(lambda self: 0.01)) monkeypatch.setattr(loop.lease, "heartbeat", heartbeat) async def run_attempt(*args, **kwargs): # Provisioning precedes Sentinel's own heartbeat loop. await asyncio.wait_for(renewed.wait(), timeout=1) return SentinelResult(attempt_id=attempt.id, outcome=Outcome.DONE, head_sha="a" * 40) loop.sentinel_factory = lambda: SimpleNamespace(run_attempt=run_attempt, cleanup=AsyncMock()) from fleet.workflow import PodSpec await loop._run_critic_pod(run, attempt, None, PodSpec(), model, "fake", None) assert renewed.is_set() assert (await store.get_attempt(attempt.id)).lease_expires is None async def test_expired_review_lease_retries_review_not_implementation(store, tmp_path): from fleet.lease import Lease run, attempt = await make_attempt(store, state=State.REVIEW) lease = Lease(store) await lease.acquire(attempt, ttl_s=-1, state=None) retried = await lease.expire_stale() assert [a.id for a in retried] == [attempt.id] assert (await store.get_attempt(attempt.id)).state is State.REVIEW assert await store.list_events(attempt.id, kind="verdict") == [] async def test_lost_review_lease_cancels_provisioning_and_retries(store, tmp_path, monkeypatch): from fleet.lease import Lease run, attempt = await make_attempt(store, state=State.REVIEW) await seed_model(store) loop = make_reconcile(store, make_config(tmp_path), FakeGitea(), tmp_path) cancelled = asyncio.Event() monkeypatch.setattr(Lease, "heartbeat_interval_s", property(lambda self: 0.01)) monkeypatch.setattr(loop.lease, "heartbeat", AsyncMock(return_value=None)) async def run_attempt(*args, **kwargs): try: await asyncio.Event().wait() finally: cancelled.set() sentinel = SimpleNamespace(run_attempt=run_attempt, cleanup=AsyncMock()) loop.sentinel_factory = lambda: sentinel assert await asyncio.wait_for(loop.run_critic(run, attempt), timeout=2) is None assert cancelled.is_set() sentinel.cleanup.assert_awaited_once() assert attempt.id not in loop._sentinels assert (await store.get_attempt(attempt.id)).lease_expires is None assert (await store.get_attempt(attempt.id)).state is State.REVIEW assert await store.list_events(attempt.id, kind="verdict") == [] events = await store.list_events(attempt.id, kind="review.interrupted") assert events[0].payload["failure_class"] == "infra" def _script_critic(loop, attempt, result: SentinelResult) -> list: """Route every critic pod to a scripted sentinel result; return the call log.""" calls = [] async def run_attempt(*args, **kwargs): calls.append(kwargs) return result sentinel = SimpleNamespace(run_attempt=run_attempt, cleanup=AsyncMock()) loop.sentinel_factory = lambda: sentinel return calls def _stopped_result(attempt_id: str, *, outcome: Outcome, failure_class: FailureClass) -> SentinelResult: return SentinelResult( attempt_id=attempt_id, outcome=outcome, failure_class=failure_class, reason="interrupted: fleetd shutdown", interrupted=outcome is Outcome.INTERRUPTED, ) async def test_interrupted_critic_stays_in_review_not_parked(store, tmp_path): """A critic stopped by a fleetd restart is not a verdict: re-drive it next tick.""" run, attempt = await make_attempt(store, state=State.REVIEW) await seed_model(store) loop = make_reconcile(store, make_config(tmp_path), FakeGitea(), tmp_path) calls = _script_critic( loop, attempt, _stopped_result(attempt.id, outcome=Outcome.INTERRUPTED, failure_class=FailureClass.INFRA) ) assert await loop.run_critic(run, attempt) is None after = await store.get_attempt(attempt.id) assert after.state is State.REVIEW, "a fleetd-stopped critic must not park the run" assert await store.list_events(attempt.id, kind="verdict") == [] events = await store.list_events(attempt.id, kind="review.interrupted") assert [e.payload["failure_class"] for e in events] == ["infra"] # The next tick re-drives the same review instead of re-parsing the # interrupted pod's partial output. assert await loop.run_critic(run, attempt) is None assert (await store.get_attempt(attempt.id)).state is State.REVIEW assert len(calls) == 2 assert await store.list_events(attempt.id, kind="verdict") == [] async def test_critic_pod_infra_crash_stays_in_review_not_parked(store, tmp_path): """Any infra-class failure of the critic pod is a crash, not a review.""" run, attempt = await make_attempt(store, state=State.REVIEW) await seed_model(store) loop = make_reconcile(store, make_config(tmp_path), FakeGitea(), tmp_path) _script_critic(loop, attempt, _stopped_result(attempt.id, outcome=Outcome.ERROR, failure_class=FailureClass.INFRA)) assert await loop.run_critic(run, attempt) is None assert (await store.get_attempt(attempt.id)).state is State.REVIEW assert await store.list_events(attempt.id, kind="verdict") == [] events = await store.list_events(attempt.id, kind="review.interrupted") assert events and events[0].payload["failure_class"] == "infra" async def test_completed_critic_without_verdict_line_still_parks(store, tmp_path): """Only a critic that ran to completion may count as 'no verdict line'.""" run, attempt = await make_attempt(store, state=State.REVIEW) await seed_model(store) loop = make_reconcile(store, make_config(tmp_path), FakeGitea(), tmp_path) _script_critic( loop, attempt, SentinelResult( attempt_id=attempt.id, outcome=Outcome.DONE, head_sha="a" * 40, # The restart shape: the pod's summary is gone, and no verdict line # to parse. An empty summary is what makes "no verdict line" the # recorded reason rather than the tail of the model's prose. summary="", ), ) verdict = await loop.run_critic(run, attempt) assert verdict is Verdict.ADVISORY assert (await store.get_attempt(attempt.id)).state is State.PARKED verdicts = await store.list_events(attempt.id, kind="verdict") assert len(verdicts) == 1 assert verdicts[0].payload["reason"] == "the critic returned no verdict line" assert verdicts[0].payload["failure_class"] is None async def test_repeated_interruptions_out_the_deadline_park_with_failure_class(store, tmp_path, monkeypatch): """The retry is bounded: past `call_wall_s` of crashes it parks, audibly. A critic that keeps dying of infrastructure must not hold a review open forever, and the park it degrades to must say *why* the review never happened: the verdict event carries the failure class, so an operator can tell a review from a crash. """ import fleet.reconcile as reconcile_module cfg = make_config(tmp_path) deadline = cfg.review_routing.call_wall_s run, attempt = await make_attempt(store, state=State.REVIEW) await seed_model(store) loop = make_reconcile(store, cfg, FakeGitea(), tmp_path) _script_critic( loop, attempt, _stopped_result(attempt.id, outcome=Outcome.INTERRUPTED, failure_class=FailureClass.INFRA) ) assert await loop.run_critic(run, attempt) is None assert (await store.get_attempt(attempt.id)).state is State.REVIEW class AgedNow(datetime): @classmethod def now(cls, tz=None): return datetime.now(tz) + timedelta(seconds=deadline + 1) monkeypatch.setattr(reconcile_module, "datetime", AgedNow) verdict = await loop.run_critic(run, attempt) assert verdict is Verdict.ADVISORY assert (await store.get_attempt(attempt.id)).state is State.PARKED verdicts = await store.list_events(attempt.id, kind="verdict") assert len(verdicts) == 1 assert verdicts[0].payload["failure_class"] == "infra" assert "fleetd shutdown" in verdicts[0].payload["reason"] async def test_interrupted_local_critic_does_not_escalate_to_paid(store, tmp_path): """An infra crash is not 'the local reviewer could not judge': no paid call.""" cfg = make_config(tmp_path, review_routing={"paid_on_advisory": True}) run, attempt = await make_attempt(store, state=State.REVIEW) await seed_model(store) await seed_model(store, "test-review", tier=Tier.REVIEW) loop = make_reconcile(store, cfg, FakeGitea(), tmp_path) calls = _script_critic( loop, attempt, _stopped_result(attempt.id, outcome=Outcome.INTERRUPTED, failure_class=FailureClass.INFRA) ) assert await loop.run_critic(run, attempt) is None assert (await store.get_attempt(attempt.id)).state is State.REVIEW assert len(calls) == 1, "a crashed local critic must not be re-driven as a paid escalation" assert await store.paid_usage() == []