# SPDX-License-Identifier: AGPL-3.0-or-later
"""R14: recovery reconciles controller-owned derived consequences that a crash
may have interrupted between an originating event and its consequence.
"""
from __future__ import annotations

import pytest

from helpers import build_run_config

from orchestrator import sandbox
from orchestrator.controller import Controller
from orchestrator.executor import ScriptedExecutor
from orchestrator.store import CrashInjected, EventStore


def _controller(path, run_id, executor=None):
    store = EventStore(path)
    controller = Controller(store, executor or ScriptedExecutor({}))
    root = controller.submit_run(build_run_config(run_id, budgets={"MODEL_COST": 10.0}))
    return store, controller, root


def _crash_on(store, event_type):
    def boom(event):
        if event.event_type == event_type:
            raise CrashInjected(f"crash before {event_type}")

    store.crash_before_commit = boom


def test_recovery_rejects_an_artefact_left_by_an_interrupted_violation(tmp_path):
    """A crash between SANDBOX_VIOLATION_RECORDED and its derived
    ARTEFACT_REJECTED must not leave the artefact admitted."""
    db = str(tmp_path / "violation.db")
    store, controller, root = _controller(db, "RUN-R14-V")
    attempt = controller.plan_attempt("RUN-R14-V", root, 5.0)
    controller._emit(
        "RUN-R14-V",
        "ARTEFACT_ADMITTED",
        {
            "artefact_id": "art-v",
            "type": "GIT_CANDIDATE",
            "hash": "sha256:v",
            "attempt_id": attempt,
        },
        f"artefact-{attempt}",
    )
    assert "art-v" in store.state("RUN-R14-V").artefacts
    _crash_on(store, "ARTEFACT_REJECTED")
    with pytest.raises(CrashInjected):
        controller._emit(
            "RUN-R14-V",
            "SANDBOX_VIOLATION_RECORDED",
            {"attempt_id": attempt, "evidence": {"rule": "RLIMIT_AS"}},
            f"violation-{attempt}",
            source="sandbox",
        )
    store.crash_before_commit = None
    # The originating violation is durable; its consequence is not.
    assert store.state("RUN-R14-V").artefacts["art-v"].state == "CANDIDATE"
    store.close()

    restarted = EventStore(db)
    try:
        controller = Controller(restarted, ScriptedExecutor({}))
        controller.recover("RUN-R14-V")
        assert restarted.state("RUN-R14-V").artefacts["art-v"].state == "REJECTED"
    finally:
        restarted.close()


def test_recovery_reconciles_the_derived_cancellation_of_a_budget_exhausted_run(tmp_path):
    """A crash between BUDGET_EXHAUSTION_RECORDED and its derived cancellation
    leaves the attempt terminal after recovery, with no redispatch."""
    db = str(tmp_path / "exhaustion.db")

    class _CountingExecutor(ScriptedExecutor):
        def __init__(self):
            super().__init__({})
            self.dispatches = 0

        def dispatch(self, request):
            self.dispatches += 1
            return super().dispatch(request)

    executor = _CountingExecutor()
    store, controller, root = _controller(db, "RUN-R14-B", executor)
    attempt = controller.plan_attempt("RUN-R14-B", root, 5.0)
    _crash_on(store, "CANCELLATION_CONFIRMED")
    with pytest.raises(CrashInjected):
        controller._emit(
            "RUN-R14-B",
            "BUDGET_EXHAUSTION_RECORDED",
            {"node_id": root},
            f"budget-exhaustion-{root}",
        )
    store.crash_before_commit = None
    dispatches_before = executor.dispatches
    store.close()

    restarted = EventStore(db)
    try:
        restarted_executor = _CountingExecutor()
        controller = Controller(restarted, restarted_executor)
        controller.recover("RUN-R14-B")
        attempt_state = restarted.state("RUN-R14-B").attempts[attempt].state
        assert attempt_state in ("CANCELLED", "FAILED", "TIMED_OUT")
        # Recovery reconciles the recorded consequence; it never redispatches
        # paid work.
        assert restarted_executor.dispatches == 0
        assert dispatches_before == 0
    finally:
        restarted.close()


def test_terminal_run_with_an_interrupted_decomposition_has_no_orphan_budget(tmp_path):
    """F3: recovery must not resurrect a child for a run that already reached an
    outcome, and must leave no orphan child budget behind."""
    from invariants import orphan_child_budget_violations

    db = str(tmp_path / "terminal.db")
    store = EventStore(db)
    run_id = "RUN-R14-T"
    controller = Controller(store, ScriptedExecutor({}))
    config = build_run_config(run_id, budgets={"MODEL_COST": 10.0})
    config["root_contract"] = {
        **config["root_contract"],
        "acceptance_criteria": [{"id": "AC-001", "mandatory": True}],
    }
    root = controller.submit_run(config)
    child_id = f"{run_id}-child"
    try:

        def boom(event):
            if event.event_type == "NODE_PROPOSED" and event.payload.get("node_id") == child_id:
                raise CrashInjected("crash after decomposition admission")

        store.crash_before_commit = boom
        with pytest.raises(CrashInjected):
            controller.admit_derived_decomposition(
                run_id,
                root,
                "decomp-t",
                [
                    {
                        "node_id": child_id,
                        "mandatory": True,
                        "criterion_ids": ["AC-001"],
                        "budget_allocation": {"MODEL_COST": 5.0},
                        "contract": {
                            "description": "child",
                            "owned_scope": ["src/child/**"],
                            "acceptance_criteria": [{"id": "AC-001", "mandatory": True}],
                            "budget_id": f"{child_id}-budget",
                        },
                    }
                ],
                [{"criterion_id": "AC-001", "child_id": child_id, "mandatory_cover": True}],
            )
        store.crash_before_commit = None
        # The run reaches a terminal outcome before recovery runs.
        controller._emit(run_id, "NODE_CANCELLED", {"node_id": root}, f"cancel-{root}")
        assert store.state(run_id).outcome is not None
    finally:
        store.close()

    restarted = EventStore(db)
    try:
        controller = Controller(restarted, ScriptedExecutor({}))
        controller.recover(run_id)
        state = restarted.state(run_id)
        # No child is resurrected for the terminal run, and no allocation is
        # left without a node behind it.
        assert child_id not in state.nodes
        assert orphan_child_budget_violations(state) == []
    finally:
        restarted.close()
