# SPDX-License-Identifier: AGPL-3.0-or-later
"""Dispatch-failure split: pre-ack DISPATCH_FAILED vs post-ack EXECUTOR_FAILED.

``Controller.dispatch_attempt`` classifies a model provider failure by the
attempt's state when the classifier reads it
(src/orchestrator/controller.py:1393): an attempt still DISPATCHED — no
DISPATCH_ACKNOWLEDGED admitted yet — records DISPATCH_FAILED, while an
attempt already RUNNING records EXECUTOR_FAILED. Each case forces its
ordering at the named window (no sleeps as synchronisation), asserts the
forced event is durable before asserting on it, and proves replay from the
log alone reproduces the terminal and accounting states. No new fixture
classes: the raising provider is an instance-attribute monkeypatch of the
production ModelAdapter, and the post-ack failure rides the
validate_response window the controller already names.
"""
from __future__ import annotations

import pytest

from helpers import build_run_config
from orchestrator import executor_protocol, model_adapter
from orchestrator.controller import Controller, ExecutorFailed
from orchestrator.executor import ScriptedExecutor
from orchestrator.model_adapter import ModelAdapter
from orchestrator.store import EventStore

_COMMITMENT = 5.0
_MODEL_LIMITS = {
    "root_model_input_tokens": 32768,
    "root_model_output_tokens": 8192,
}


def _completion():
    return model_adapter.ModelCompletion(
        outputs=(
            model_adapter.ModelOutput(
                "SEMANTIC_EVALUATION",
                {"subject_reference": "x", "verdict": "PASS", "rationale": "ok"},
            ),
        ),
        cost=0.01,
        units="COST_UNITS",
        model_id="model-x",
        model_version="1",
        input_tokens=10,
        output_tokens=5,
    )


def _setup(tmp_path, run_id):
    store = EventStore(str(tmp_path / f"{run_id}-events.db"))
    node_id = f"{run_id}-root"
    client = model_adapter.ScriptedModelClient({node_id: _completion()})
    adapter = ModelAdapter(client, model_id="model-x", model_version="1")
    controller = Controller(
        store,
        ScriptedExecutor({}),
        model_executor=adapter,
        executor_environment={"base_commit": "HEAD", "timeout_seconds": 30.0},
    )
    root = controller.submit_run(build_run_config(run_id, limits=_MODEL_LIMITS))
    return store, controller, adapter, root


def _index(history, event_type, attempt_id):
    """The log position (ascending sequence order) of an attempt's event."""
    for position, event in enumerate(history):
        if event.event_type == event_type and event.payload.get("attempt_id") == attempt_id:
            return position
    return None


def _events(history, event_type, attempt_id):
    return [
        event
        for event in history
        if event.event_type == event_type and event.payload.get("attempt_id") == attempt_id
    ]


def _assert_conservatively_settled(store, run_id, attempt_id):
    """The failure settled conservatively and replay reproduces it from the log."""
    history = store.history(run_id)
    assert len(_events(history, "ATTEMPT_COST_SETTLED_CONSERVATIVELY", attempt_id)) == 1
    state = store.state(run_id)
    attempt = state.attempts[attempt_id]
    assert attempt.state == "FAILED"
    assert attempt.accounting_state == "FINALLY_SETTLED"
    assert attempt.actual_cost == pytest.approx(_COMMITMENT)
    assert state.ledger.charged.get(attempt_id, 0.0) == pytest.approx(_COMMITMENT)
    assert state.ledger.total_charged == pytest.approx(_COMMITMENT)
    replayed = store.replay_fresh(run_id)
    replayed_attempt = replayed.attempts[attempt_id]
    assert replayed_attempt.state == "FAILED"
    assert replayed_attempt.accounting_state == "FINALLY_SETTLED"
    assert (replayed_attempt.actual_cost or 0.0) == pytest.approx(_COMMITMENT)
    assert replayed.ledger.charged.get(attempt_id, 0.0) == pytest.approx(_COMMITMENT)
    assert replayed.ledger.total_charged == pytest.approx(state.ledger.total_charged)


# ---------------------------------------------------------------------------
# Shape 1: forced pre-ack branch. The provider raises inside the executor
# call the controller awaits (:1308), so no DISPATCH_ACKNOWLEDGED exists and
# the attempt is still DISPATCHED when the classifier reads it (:1393).
# ---------------------------------------------------------------------------


@pytest.mark.timeout(60)
def test_pre_ack_provider_failure_records_dispatch_failed(tmp_path):
    run_id = "DFS1"
    store, controller, adapter, root = _setup(tmp_path, run_id)
    try:
        fired = []

        def boom(request):
            fired.append(request["attempt_id"])
            raise RuntimeError("provider HTTP 500")

        adapter.dispatch = boom
        with pytest.raises(ExecutorFailed) as excinfo:
            controller.run_model_review(run_id, root, _COMMITMENT)
        # Anti-vacuity: the failure was raised inside the awaited executor
        # call, for exactly one attempt, and it is the attempt under test.
        assert len(fired) == 1
        attempt_id = fired[0]
        assert excinfo.value.attempt_id == attempt_id

        history = store.history(run_id)
        dispatch_at = _index(history, "ACTION_DISPATCHED", attempt_id)
        failed_at = _index(history, "DISPATCH_FAILED", attempt_id)
        assert dispatch_at is not None and failed_at is not None
        assert dispatch_at < failed_at, "the forced ordering must hold"
        assert _index(history, "DISPATCH_ACKNOWLEDGED", attempt_id) is None, (
            "no acknowledgement may exist on the pre-ack branch"
        )
        assert not _events(history, "EXECUTOR_FAILED", attempt_id)

        _assert_conservatively_settled(store, run_id, attempt_id)
    finally:
        store.close()


# ---------------------------------------------------------------------------
# Shape 2: forced post-ack branch. The provider returns a response, the
# acknowledgement is admitted (:1411-1418, the attempt is RUNNING), and the
# failure is raised once the ack is durable by the validation window
# (:1468-1491) — so the ordering is chosen, not raced.
# ---------------------------------------------------------------------------


@pytest.mark.timeout(60)
def test_post_ack_validation_failure_records_executor_failed(tmp_path, monkeypatch):
    run_id = "DFS2"
    store, controller, adapter, root = _setup(tmp_path, run_id)
    try:
        fired = []

        def fail_once(request, response, **kwargs):
            fired.append(request["attempt_id"])
            assert _index(
                store.history(run_id), "DISPATCH_ACKNOWLEDGED", request["attempt_id"]
            ) is not None, (
                "anti-vacuity: the ack must be durable before the post-ack failure"
            )
            raise executor_protocol.ProtocolViolation(
                "forced post-ack validation failure"
            )

        monkeypatch.setattr(executor_protocol, "validate_response", fail_once)
        with pytest.raises(executor_protocol.ProtocolViolation):
            controller.run_model_review(run_id, root, _COMMITMENT)
        # Anti-vacuity: the validation window fired exactly once, for the
        # attempt under test.
        assert len(fired) == 1
        attempt_id = fired[0]

        history = store.history(run_id)
        ack_at = _index(history, "DISPATCH_ACKNOWLEDGED", attempt_id)
        failed_at = _index(history, "EXECUTOR_FAILED", attempt_id)
        assert ack_at is not None and failed_at is not None
        assert ack_at < failed_at, "the forced ordering must hold"
        assert not _events(history, "DISPATCH_FAILED", attempt_id)

        _assert_conservatively_settled(store, run_id, attempt_id)
    finally:
        store.close()
