# SPDX-License-Identifier: AGPL-3.0-or-later
"""Ledger row A: cancel-by-dispatch classification under racing dispatch.

``Controller._cancel_attempt`` decides whether a cancelled attempt was ever
handed to an executor and settles the two branches differently: a
never-dispatched attempt's commitment is reclaimed (``ATTEMPT_COST_RECONCILED``
with ``actual`` 0), while a dispatched attempt's liability is retained
(``ATTEMPT_COST_SETTLED_CONSERVATIVELY`` charging the commitment). The
classification is read from the current state *and* the durable log under the
admission lock. Three earlier fixes (R04, SPEND F2, Exec F3) all closed a stale
``dispatched``/``late`` snapshot that laundered a dispatched charge to zero.

This harness forces each ordering at the exact window — the cancel fully
admitted before ``ACTION_DISPATCHED``, and ``ACTION_DISPATCHED`` durable with
the executor in flight before the cancel — then races the two admissions
without a forced winner. Every case asserts its interleave actually fired
(barrier released, hook reached, event durable) and is time-bounded so a
deadlock fails instead of hanging. Replay from the log alone must reproduce
every settled state.
"""
from __future__ import annotations

import threading

import pytest

from helpers import build_run_config
from orchestrator.controller import Controller
from orchestrator.executor import AttemptCancelled, ScriptedExecutor
from orchestrator.store import EventStore

_RESPONSE = {
    "self_reported_status": "COMPLETED",
    "observations": [{"type": "COMMAND_RESULT", "exit_code": 0}],
    "artefacts": [],
    "cost_report": {"committed": 5, "actual": 5, "units": "COST_UNITS"},
}
_COMMITMENT = 5.0
_RACE_ITERATIONS = 40


def _setup(tmp_path, run_id):
    store = EventStore(str(tmp_path / f"{run_id}-events.db"))
    executor = ScriptedExecutor({f"{run_id}-root": lambda request: dict(_RESPONSE)})
    controller = Controller(store, executor)
    root = controller.submit_run(build_run_config(run_id, budgets={"MODEL_COST": 100.0}))
    return store, controller, executor, 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_replay_reproduces(store, run_id, attempt_id, expected_charge):
    """replay_fresh must reproduce the settled attempt and ledger from the log."""
    state = store.state(run_id)
    attempt = state.attempts[attempt_id]
    replayed = store.replay_fresh(run_id)
    replayed_attempt = replayed.attempts[attempt_id]
    assert replayed_attempt.state == attempt.state == "CANCELLED"
    assert replayed_attempt.accounting_state == attempt.accounting_state == "FINALLY_SETTLED"
    assert (replayed_attempt.actual_cost or 0.0) == pytest.approx(expected_charge)
    assert replayed.ledger.charged.get(attempt_id, 0.0) == pytest.approx(expected_charge)
    assert replayed.ledger.total_charged == pytest.approx(state.ledger.total_charged)


# --------------------------------------------------------------------------
# Shape 1: forced undispatched branch. The cancel is fully admitted while the
# dispatch thread is held before its ACTION_DISPATCHED emission, so the
# ordering is chosen, not raced.
# --------------------------------------------------------------------------


@pytest.mark.timeout(60)
def test_cancel_admitted_before_dispatch_reclaims_and_late_dispatch_adds_no_liability(
    tmp_path,
):
    run_id = "CBD1"
    store, controller, executor, root = _setup(tmp_path, run_id)
    try:
        attempt_id = controller.plan_attempt(run_id, root, _COMMITMENT)
        at_emission = threading.Event()
        cancel_admitted = threading.Event()
        late_results = []
        original_emit = controller._emit

        def hooked(run_id_arg, event_type, payload, semantic_key, **kwargs):
            blocked = event_type == "ACTION_DISPATCHED"
            if blocked:
                at_emission.set()
                assert cancel_admitted.wait(timeout=10), (
                    "deadlock: the cancellation never completed"
                )
            result = original_emit(run_id_arg, event_type, payload, semantic_key, **kwargs)
            if blocked:
                late_results.append(result)
            return result

        controller._emit = hooked
        outcome = {}

        def driver():
            try:
                controller.dispatch_attempt(run_id, attempt_id, root)
                outcome["result"] = "returned"
            except Exception as error:  # noqa: BLE001 - recorded for the assertion
                outcome["result"] = type(error).__name__

        thread = threading.Thread(target=driver)
        thread.start()
        try:
            assert at_emission.wait(timeout=10), (
                "anti-vacuity: the dispatch must reach its emission window"
            )
            controller.cancel_run(run_id, root)
        finally:
            cancel_admitted.set()
        thread.join(timeout=30)
        assert not thread.is_alive(), "the cancel-before-dispatch window deadlocked"

        history = store.history(run_id)
        cancel_at = _index(history, "CANCELLATION_CONFIRMED", attempt_id)
        dispatch_at = _index(history, "ACTION_DISPATCHED", attempt_id)
        assert cancel_at is not None and dispatch_at is not None
        assert cancel_at < dispatch_at, "the forced ordering must hold"

        # Anti-vacuity and shape proof: the late emission was retained by the
        # reducer, so the state never entered DISPATCHED.
        assert late_results, "anti-vacuity: the late dispatch emission must return"
        assert "late_event_retained" in [effect.kind for effect in late_results[0].effects], (
            "the late ACTION_DISPATCHED must be retained, not applied"
        )

        state = store.state(run_id)
        attempt = state.attempts[attempt_id]
        assert attempt.state == "CANCELLED"
        assert all(a.state != "DISPATCHED" for a in state.attempts.values()), (
            "no attempt may be created in DISPATCHED by the late emission"
        )

        # Settlement took the reclamation branch: the reconcile-with-reclaim
        # event is present, and the conservative-retention event is absent.
        reconciles = _events(history, "ATTEMPT_COST_RECONCILED", attempt_id)
        assert len(reconciles) == 1
        assert reconciles[0].payload["actual"] == 0
        assert reconciles[0].payload["reclamation"] == pytest.approx(_COMMITMENT)
        assert not _events(history, "ATTEMPT_COST_SETTLED_CONSERVATIVELY", attempt_id)

        # The late dispatch added no liability.
        assert (attempt.actual_cost or 0.0) == 0.0
        assert state.ledger.charged.get(attempt_id, 0.0) == 0.0
        assert state.ledger.total_charged == 0.0
        assert attempt_id not in state.ledger.reservations
        _assert_replay_reproduces(store, run_id, attempt_id, expected_charge=0.0)
        assert outcome["result"] in ("AttemptCancelled", "returned")
    finally:
        store.close()


# --------------------------------------------------------------------------
# Shape 2: forced retained branch. ACTION_DISPATCHED is durable and the
# executor is in flight (blocked inside dispatch) when the cancel is admitted.
# --------------------------------------------------------------------------


@pytest.mark.timeout(60)
def test_durable_dispatch_and_in_flight_executor_before_cancel_retains_liability(tmp_path):
    run_id = "CBD2"
    store, controller, executor, root = _setup(tmp_path, run_id)
    try:
        attempt_id = controller.plan_attempt(run_id, root, _COMMITMENT)
        in_dispatch = threading.Event()
        release = threading.Event()
        original_dispatch = executor.dispatch

        def blocking_dispatch(request):
            in_dispatch.set()
            assert release.wait(timeout=10), (
                "deadlock: the cancellation never released dispatch"
            )
            return original_dispatch(request)

        executor.dispatch = blocking_dispatch
        outcome = {}

        def driver():
            try:
                controller.dispatch_attempt(run_id, attempt_id, root)
                outcome["result"] = "returned"
            except Exception as error:  # noqa: BLE001 - recorded for the assertion
                outcome["result"] = type(error).__name__

        thread = threading.Thread(target=driver)
        thread.start()
        try:
            assert in_dispatch.wait(timeout=10), (
                "anti-vacuity: the executor must be in flight"
            )
            # Both preconditions are observed before the cancel is admitted:
            # the dispatch is durable and the executor is executing it.
            state_before = store.state(run_id)
            assert state_before.attempts[attempt_id].state == "DISPATCHED"
            controller.cancel_run(run_id, root)
        finally:
            release.set()
        thread.join(timeout=30)
        assert not thread.is_alive(), "the dispatch-then-cancel window deadlocked"

        history = store.history(run_id)
        dispatch_at = _index(history, "ACTION_DISPATCHED", attempt_id)
        cancel_at = _index(history, "CANCELLATION_CONFIRMED", attempt_id)
        assert dispatch_at is not None and cancel_at is not None
        assert dispatch_at < cancel_at, "the forced ordering must hold"

        state = store.state(run_id)
        attempt = state.attempts[attempt_id]
        assert attempt.state == "CANCELLED"
        assert attempt.accounting_state == "FINALLY_SETTLED"

        # Liability is retained: the conservative settlement charged the
        # commitment and no reconciliation to zero exists.
        assert (attempt.actual_cost or 0.0) > 0.0
        assert state.ledger.charged.get(attempt_id, 0.0) > 0.0
        conservatively = _events(history, "ATTEMPT_COST_SETTLED_CONSERVATIVELY", attempt_id)
        assert len(conservatively) == 1
        assert conservatively[0].payload["commitment"] == pytest.approx(_COMMITMENT)
        assert not _events(history, "ATTEMPT_COST_RECONCILED", attempt_id), (
            "a dispatched attempt's retained actual must never be reconciled to zero"
        )
        _assert_replay_reproduces(store, run_id, attempt_id, expected_charge=_COMMITMENT)
        assert outcome["result"] in ("AttemptCancelled", "returned")
    finally:
        store.close()


# --------------------------------------------------------------------------
# Shape 3: unforced race of cancel x ACTION_DISPATCHED admission. Both threads
# rendezvous on a barrier with no forced winner; the settled accounting must
# equal an honest ordering in every iteration, and both orderings must be
# observed across the loop.
# --------------------------------------------------------------------------


def _race_once(tmp_path, iteration):
    """One unforced cancel x ACTION_DISPATCHED race; assert the honest result.

    Returns whether the durable log shows the dispatch admitted first.
    """
    run_id = f"CBD3-{iteration}"
    store, controller, executor, root = _setup(tmp_path, run_id)
    try:
        attempt_id = controller.plan_attempt(run_id, root, _COMMITMENT)
        barrier = threading.Barrier(2)
        released = []
        failures = []

        def dispatch():
            try:
                barrier.wait(timeout=10)
                released.append("dispatch")
                controller.dispatch_attempt(run_id, attempt_id, root)
            except AttemptCancelled:
                # The cancel won the race and the executor refused the late
                # delivery: an honest outcome, not a failure.
                pass
            except Exception as error:  # noqa: BLE001 - recorded for the assertion
                failures.append(("dispatch", type(error).__name__, str(error)))

        def cancel():
            try:
                barrier.wait(timeout=10)
                released.append("cancel")
                controller._cancel_attempt(run_id, attempt_id)
            except Exception as error:  # noqa: BLE001 - recorded for the assertion
                failures.append(("cancel", type(error).__name__, str(error)))

        threads = [threading.Thread(target=dispatch), threading.Thread(target=cancel)]
        # Alternate creation order so both interleavings are reachable without
        # a barrier hook choosing the winner in either.
        if iteration % 2:
            threads.reverse()
        for thread in threads:
            thread.start()
        for thread in threads:
            thread.join(timeout=30)
        assert not any(thread.is_alive() for thread in threads), "the race deadlocked"
        assert sorted(released) == ["cancel", "dispatch"], (
            "anti-vacuity: the barrier must release both racers"
        )
        assert not failures, f"unexpected race failure: {failures}"

        history = store.history(run_id)
        dispatch_at = _index(history, "ACTION_DISPATCHED", attempt_id)
        cancel_at = _index(history, "CANCELLATION_CONFIRMED", attempt_id)
        assert cancel_at is not None, "the winning cancel must be admitted"
        assert dispatch_at is not None, (
            "anti-vacuity: the dispatch must be durable in one ordering or the other"
        )
        dispatched_first = dispatch_at < cancel_at

        state = store.state(run_id)
        attempt = state.attempts[attempt_id]
        charge = state.ledger.charged.get(attempt_id, 0.0)
        assert attempt.state == "CANCELLED"
        assert attempt.accounting_state == "FINALLY_SETTLED"
        # The settled accounting equals an honest ordering: liability is
        # retained if and only if the durable log shows the dispatch was
        # admitted before the cancellation.
        if dispatched_first:
            assert charge > 0.0, "a dispatched charge was laundered to zero"
            assert (attempt.actual_cost or 0.0) > 0.0
        else:
            assert charge == 0.0, "an undispatched attempt was charged"
            assert (attempt.actual_cost or 0.0) == 0.0

        replayed = store.replay_fresh(run_id)
        assert replayed.attempts[attempt_id].state == "CANCELLED"
        assert replayed.attempts[attempt_id].accounting_state == "FINALLY_SETTLED"
        assert replayed.ledger.charged.get(attempt_id, 0.0) == pytest.approx(charge)
        assert replayed.ledger.total_charged == pytest.approx(state.ledger.total_charged)
        return dispatched_first
    finally:
        store.close()


@pytest.mark.timeout(180)
def test_unforced_cancel_dispatch_race_settles_by_the_durable_order(tmp_path):
    outcomes = [_race_once(tmp_path, iteration) for iteration in range(_RACE_ITERATIONS)]
    retained = sum(1 for dispatched_first in outcomes if dispatched_first)
    reclaimed = len(outcomes) - retained
    assert retained > 0 and reclaimed > 0, (
        "an unforced race must exhibit both cancel/dispatch orderings; "
        f"observed retained={retained} reclaimed={reclaimed}"
    )
