# SPDX-License-Identifier: AGPL-3.0-or-later
"""A-class interleaving harness: cancellation racing dispatch and admission.

The laundering defect shape survived three adversarial reviews because
cancellation was only ever tested *sequentially*. This harness drives the exact
windows the controller documents — the ``_cancel_attempt`` dispatched snapshot,
the ``late``-flag read before result admission, and the artefact
admission/integration pair — under deterministic interleaves (barriers and
admission hooks), plus the store-boundary crafted-log interleave the reducer
must refuse.

Invariants under every interleave: the durable ``actual`` of a dispatched
attempt is never laundered to 0; a cancelled attempt publishes no result or
integrated artefact; every attempt ends terminal and settled; replay reproduces
the same state.

Anti-vacuity: every case asserts its interleave actually fired (the hook saw
its event, the barrier was reached) and is time-bounded so a deadlock fails
instead of hanging.
"""
from __future__ import annotations

import threading

import pytest

from helpers import build_run_config
from orchestrator import tables
from orchestrator.controller import Controller
from orchestrator.executor import 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"},
}


def _controller(tmp_path, script, name="events.db"):
    store = EventStore(str(tmp_path / name))
    controller = Controller(store, ScriptedExecutor({f"IL-root": script}))
    root = controller.submit_run(build_run_config("IL", budgets={"MODEL_COST": 100.0}))
    return store, controller, root


def _history(store, run_id, event_type):
    return [e for e in store.history(run_id) if e.event_type == event_type]


# --------------------------------------------------------------------------
# Window 1: cancellation while the executor is in flight, observation arrives
# afterwards (the R04 laundering shape, verified to stay closed)
# --------------------------------------------------------------------------


@pytest.mark.timeout(60)
def test_late_observation_after_cancellation_retains_liability(tmp_path):
    run_id = "IL"
    started = threading.Event()
    cancelled = threading.Event()

    def script(request):
        started.set()
        cancelled.wait(timeout=10)
        return dict(_RESPONSE)

    store, controller, root = _controller(tmp_path, script)
    try:
        outcome = {}

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

        thread = threading.Thread(target=driver)
        thread.start()
        assert started.wait(timeout=10), "anti-vacuity: the dispatch must start"
        controller.cancel_run(run_id, root)
        cancelled.set()
        thread.join(timeout=30)
        assert not thread.is_alive(), "the late-observation window deadlocked"

        state = store.state(run_id)
        attempt = state.attempts[next(iter(state.attempts))]
        assert attempt.state == "CANCELLED"
        assert attempt.accounting_state == "FINALLY_SETTLED"
        # A dispatched attempt's liability is retained: the conservative
        # settlement charges the commitment and a late observation never
        # launders the durable actual to 0 (R04; SPEND F2; Exec F3).
        assert (attempt.actual_cost or 0.0) > 0.0
        assert state.ledger.total_charged > 0.0
        history = store.history(run_id)
        assert not [e for e in history if e.event_type == "RESULT_ADMITTED"]
        assert not [e for e in history if e.event_type == "ARTEFACT_ADMITTED"]
        replayed = store.replay_fresh(run_id)
        assert replayed.ledger.total_charged == state.ledger.total_charged
        assert replayed.attempts[attempt.attempt_id].state == "CANCELLED"
    finally:
        store.close()


# --------------------------------------------------------------------------
# Window 2: cancellation landing between the result-admission decisions and
# the RESULT_ADMITTED emission — the late flag is read before the emission, so
# a cancel in between must degrade to an honest late-retention, not crash the
# driver with a raw machine refusal.
# --------------------------------------------------------------------------


@pytest.mark.timeout(60)
def test_cancellation_racing_the_result_emission_is_retained_not_fatal(tmp_path):
    run_id = "IL"

    def script(request):
        return dict(_RESPONSE)

    store, controller, root = _controller(tmp_path, script)
    keys_seen = []
    original = controller._emit

    def racing(run_id, event_type, payload, key, **kwargs):
        if event_type == "RESULT_ADMITTED":
            # The cancellation lands in the TOCTOU window between the `late`
            # read and the RESULT_ADMITTED admission.
            controller.cancel_run(run_id, root)
            keys_seen.append(key)
        return original(run_id, event_type, payload, key, **kwargs)

    controller._emit = racing
    try:
        controller.execute_attempt(run_id, root, 5.0)
    finally:
        controller._emit = original
    assert keys_seen, "anti-vacuity: the result emission must have been reached"
    history = store.history(run_id)
    state = store.state(run_id)
    attempt = state.attempts[next(iter(state.attempts))]
    # The late RESULT_ADMITTED emission is retained by the reducer (a terminal
    # attempt keeps no result): the attempt stays CANCELLED, no freshness record
    # is created, and the liability survives the race (R04).
    assert attempt.state == "CANCELLED", (
        "a result refused after cancellation must not produce the attempt"
    )
    assert not state.freshness, (
        "a retained late result must not create a freshness record"
    )
    assert (attempt.actual_cost or 0.0) > 0.0, "liability must survive the race"
    replayed = store.replay_fresh(run_id)
    assert replayed.attempts[attempt.attempt_id].state == "CANCELLED"
    assert not replayed.freshness


# --------------------------------------------------------------------------
# Window 3 (positive control): through the controller the attempt is already
# RESULT_PRODUCED when its artefact is admitted, so a legitimate integration
# must proceed — the store-boundary guard added for window 4 must not
# over-refuse the honest flow.
# --------------------------------------------------------------------------


class _IntegrationExecutor(ScriptedExecutor):
    performs_integration = True


@pytest.mark.timeout(60)
def test_legitimate_integration_survives_the_cancelled_attempt_guard(tmp_path):
    def script(request):
        return dict(
            _RESPONSE,
            artefacts=[{"type": "GIT_CANDIDATE", "content_hash": "sha256:c", "reference": "r1"}],
            changed_paths=["src/health/parse.py"],
        )

    store = EventStore(str(tmp_path / "events.db"))
    controller = Controller(store, _IntegrationExecutor({f"IL-root": script}))
    try:
        root = controller.submit_run(build_run_config("IL", budgets={"MODEL_COST": 100.0}))
        controller.execute_attempt(run_id="IL", node_id=root, commitment=5.0)
        history = store.history("IL")
        assert [e for e in history if e.event_type == "RESULT_ADMITTED"]
        integrated = [e for e in history if e.event_type == "ARTEFACT_INTEGRATED"]
        assert integrated, "a produced result's artefact must integrate honestly"
        assert store.replay_fresh("IL").artefacts == store.state("IL").artefacts
    finally:
        store.close()


# --------------------------------------------------------------------------
# Window 4 (store boundary): a crafted or replayed log must not integrate a
# cancelled attempt's artefact. Admission is serialized, so the reducer is the
# authority for this race.
# --------------------------------------------------------------------------


@pytest.mark.timeout(60)
def test_cancelled_attempt_artefact_cannot_integrate_at_the_store_boundary(tmp_path):
    run_id = "IL"
    store, controller, root = _controller(
        tmp_path, lambda request: dict(_RESPONSE)
    )
    try:
        attempt_id = controller.plan_attempt(run_id, root, 5.0, action_type="EXECUTE")
        controller._emit(
            run_id,
            "ACTION_DISPATCHED",
            {"attempt_id": attempt_id, "executor": "scripted-in-process"},
            f"dispatch-{attempt_id}",
        )
        artefact_id = f"{attempt_id}-artefact"
        controller._emit(
            run_id,
            "ARTEFACT_ADMITTED",
            {
                "artefact_id": artefact_id,
                "type": "GIT_CANDIDATE",
                "hash": "sha256:c",
                "attempt_id": attempt_id,
            },
            f"artefact-{attempt_id}",
        )
        assert store.state(run_id).artefacts[artefact_id].state == "CANDIDATE"
        controller._cancel_attempt(run_id, attempt_id)
        assert store.state(run_id).attempts[attempt_id].state == "CANCELLED"
        # The admission guard (already fixed by Exec F2) must also hold: an
        # artefact admission that arrives after the cancellation is retained,
        # not created.
        late_id = f"{attempt_id}-artefact-late"
        controller._emit(
            run_id,
            "ARTEFACT_ADMITTED",
            {
                "artefact_id": late_id,
                "type": "GIT_CANDIDATE",
                "hash": "sha256:c",
                "attempt_id": attempt_id,
            },
            f"artefact-{late_id}",
        )
        assert late_id not in store.state(run_id).artefacts
        controller._emit(
            run_id,
            "ARTEFACT_INTEGRATED",
            {"artefact_id": artefact_id, "merge_info": {"reference": "r1"}},
            f"integrate-{attempt_id}",
        )
        state = store.state(run_id)
        assert state.artefacts[artefact_id].state != "INTEGRATED", (
            "a cancelled attempt's artefact must not be integrated: the reducer "
            "retains it as a late observation (Exec F2)"
        )
        # The retention is durable: replay reproduces it from the log alone.
        assert store.replay_fresh(run_id).artefacts == state.artefacts
    finally:
        store.close()
