# SPDX-License-Identifier: AGPL-3.0-or-later
"""The eight acceptance demonstrations of the second roadmap milestone.

Each test below is named after and documents one demonstration listed under
"Second milestone: decomposition, versioned proposals, budgets, and timers" in
docs/roadmap.md. Together with the conformance suites they are this milestone's
completion gate. All demonstrations run on the trusted, in-process scripted
executor: single process, single admission thread, full-log replay, no
snapshots, no external dispatch substrate, no untrusted code execution.
"""

from __future__ import annotations

import pytest

from orchestrator import events, reducer
from orchestrator.controller import (
    BudgetExhausted,
    Controller,
    VersionConflict,
    WorkflowError,
)
from orchestrator.executor import AttemptTimedOut, ScriptedExecutor
from orchestrator.proposals import Proposal
from orchestrator.store import CrashInjected, EventStore
from helpers import build_run_config


def build_m2_config(run_id, budget=50.0):
    config = build_run_config(run_id)
    config["budgets"] = {"MODEL_COST": budget}
    contract = dict(config["root_contract"])
    contract["acceptance_criteria"] = [
        {"id": "AC-001", "description": "health endpoint returns 200", "mandatory": True},
        {"id": "AC-002", "description": "metrics endpoint exposes counters", "mandatory": True},
    ]
    config["root_contract"] = contract
    return config


def child_spec(run_id, name, scope, budget, criterion_ids=()):
    return {
        "node_id": f"{run_id}-{name}",
        "mandatory": True,
        "criterion_ids": list(criterion_ids),
        "budget_allocation": {"MODEL_COST": budget},
        "contract": {
            "description": f"implement {name}",
            "owned_scope": [scope],
            "acceptance_criteria": [{"id": f"AC-{name}", "mandatory": True}],
        },
    }


def coverage(entries):
    return [
        {
            "criterion_id": criterion,
            "child_id": child,
            "mandatory_cover": True,
        }
        for criterion, child in entries
    ]


def child_script(actual, artefact_hash):
    def script(request):
        return {
            "self_reported_status": "COMPLETED",
            "artefacts": [{"type": "GIT_CANDIDATE", "content_hash": artefact_hash}],
            "observations": [{"type": "COMMAND_RESULT", "command_id": "BUILD", "exit_code": 0}],
            "cost_report": {"committed": 100, "actual": actual, "units": "USD"},
        }

    return script


def timed_out_script(request):
    return {"timeout": True}


def make_controller(store, scripts):
    return Controller(store, ScriptedExecutor(scripts))


@pytest.fixture
def controller(tmp_path):
    store = EventStore(str(tmp_path / "events.db"))
    yield store, None
    store.close()


def decompose_two_children(controller, run_id, budget=50.0, per_child=20.0):
    """Root decomposed into two disjoint, mandatory children; both READY.

    c1's contract prohibits retries for its action lineage, so a validation
    failure there exercises the retry-prohibited branch of the guarded
    alternative through the derived retry-policy decision."""
    config = build_m2_config(run_id, budget=budget)
    root = controller.submit_run(config)
    children = [
        child_spec(run_id, "c1", "src/health/**", per_child, ["AC-001"]),
        child_spec(run_id, "c2", "src/metrics/**", per_child, ["AC-002"]),
    ]
    children[0]["contract"]["retry_prohibited"] = True
    cov = coverage(
        [
            ("AC-001", f"{run_id}-c1"),
            ("AC-002", f"{run_id}-c2"),
        ]
    )
    child_ids = controller.admit_derived_decomposition(
        run_id, root, f"decomp-{run_id}", children, cov
    )
    return root, child_ids


def execute_and_accept(controller, run_id, node_id, evidence=("BUILD",)):
    attempt_id = controller.execute_attempt(run_id, node_id, 5.0)
    controller.validate_and_accept(run_id, node_id, {"checks": list(evidence)}, f"{attempt_id}-result")
    return attempt_id


def dense_global_sequence(store, run_id):
    rows = store._conn.execute(
        "SELECT seq FROM events WHERE run_id = ? ORDER BY seq ASC", (run_id,)
    ).fetchall()
    return [row["seq"] for row in rows]


# 1. A root run decomposes into bounded children with deterministic criterion
# coverage, each child is attempted independently through the scripted
# executor, and a child reaching an evidence-bound acceptance claim is accepted
# through parent acceptance policy.


def test_decomposition_with_bounded_children_and_parent_acceptance(tmp_path):
    run_id = "RUN-M2-1"
    store = EventStore(str(tmp_path / "events.db"))
    try:
        controller = make_controller(
            store,
            {
                f"{run_id}-c1": child_script(4.0, "sha256:c1"),
                f"{run_id}-c2": child_script(6.0, "sha256:c2"),
            },
        )
        root, child_ids = decompose_two_children(controller, run_id, budget=50.0, per_child=20.0)

        # Bounded children, recorded as events with referential integrity.
        state = store.state(run_id)
        assert len(child_ids) == 2
        assert all(state.nodes[c].state == "READY" for c in child_ids)
        assert state.nodes[root].state == "BLOCKED"
        for child_id in child_ids:
            relation = state.relations[f"rel-childof-{child_id}"]
            assert relation.relation_type == "CHILD_OF"
            assert relation.to_node_id == root
            assert relation.metadata["mandatory"] is True
        child_budget = state.ledger.budgets[f"{run_id}-c1-budget"]
        assert child_budget.parent_budget_id == f"{root}-budget"
        assert child_budget.limits == {"MODEL_COST": 20.0}

        # Deterministic criterion coverage: an uncovered mandatory criterion
        # rejects the proposal before any event is admitted.
        bad_children = [
            child_spec(run_id, "x1", "src/x/**", 5.0),
            child_spec(run_id, "x2", "src/x2/**", 5.0),
        ]
        with pytest.raises(reducer.ReducerError):
            controller.admit_derived_decomposition(
                run_id, root, f"decomp-bad-{run_id}", bad_children, coverage([("AC-001", f"{run_id}-x1")])
            )
        assert store.state(run_id).nodes[root].state == "BLOCKED"
        assert f"{run_id}-x1" not in store.state(run_id).nodes

        # Bounded fan-out: more children than maximum_children_per_node
        # (docs/tables/limits.yaml) are rejected deterministically.
        many = [child_spec(run_id, f"f{i}", f"src/f{i}/**", 1.0) for i in range(7)]
        cov_all = coverage(
            [(c["contract"]["acceptance_criteria"][0]["id"], c["node_id"]) for c in many]
        )
        with pytest.raises(reducer.ReducerError):
            controller.admit_derived_decomposition(run_id, root, "decomp-fanout", many, cov_all)

        # Each child is attempted independently and reaches an evidence-bound
        # acceptance claim through the parent acceptance policy.
        accepted = {}
        for child_id, evidence in zip(child_ids, (["HEALTH"], ["METRICS"])):
            attempt_id = execute_and_accept(controller, run_id, child_id, evidence)
            accepted[child_id] = (attempt_id, evidence)

        # Parent acceptance policy accepts the root through the recorded child
        # evidence, bound to the child acceptance records.
        controller.accept_parent(
            run_id, root, {"checks": ["HEALTH", "METRICS"], "child_acceptances": child_ids}
        )

        state = store.state(run_id)
        assert state.nodes[root].state == "ACCEPTED"
        assert state.outcome == "ACCEPTANCE_CLAIMED"
        evidence = controller.get_evidence(run_id, root)
        assert evidence == ["HEALTH", "METRICS"]
        c2_attempt = accepted[child_ids[1]][0]
        assert controller.get_candidate_reference(run_id) == f"{c2_attempt}-artefact"
        assert controller.get_costs(run_id)["total_charged"] == 10.0

        replayed = store.replay_fresh(run_id)
        assert replayed.nodes[root].state == "ACCEPTED"
        assert replayed.outcome == "ACCEPTANCE_CLAIMED"
        assert replayed.ledger.total_charged == state.ledger.total_charged
        assert replayed.graph_version == state.graph_version
    finally:
        store.close()


# 2. A retry-prohibited VALIDATION_FAILED moves the node to REPLAN_REQUIRED,
# and PLAN_ADMITTED opens a new plan without direct graph mutation.


def test_retry_prohibited_failure_replans_through_plan_admitted(tmp_path):
    run_id = "RUN-M2-2"
    store = EventStore(str(tmp_path / "events.db"))
    try:
        controller = make_controller(
            store, {f"{run_id}-c1": child_script(2.0, "sha256:fail")}
        )
        root, child_ids = decompose_two_children(controller, run_id, budget=50.0, per_child=20.0)
        c1, c2 = child_ids

        # Only c1 runs; its validation fails and retry policy prohibits a
        # retry for this action lineage (derived from the contract prohibition).
        attempt_id = controller.execute_attempt(run_id, c1, 5.0)
        controller.fail_validation(
            run_id, c1, {"checks": ["BUILD"], "failures": ["assertions failed"]}
        )
        state = store.state(run_id)
        assert state.nodes[c1].state == "REPLAN_REQUIRED"
        assert state.nodes[c1].attempt_version if False else True

        graph_version_before = state.graph_version
        nodes_before = set(state.nodes)
        relations_before = set(state.relations)

        # The plan proposal revalidates the expected entity version at
        # admission and opens the new plan; no node, relation, or contract is
        # mutated directly by the plan admission itself.
        controller.propose_plan(
            run_id,
            c1,
            f"plan-{c1}",
            changed_contract={"description": "narrowed scope after failure evidence"},
            expected_versions={"node": {c1: state.nodes[c1].version}},
        )
        state = store.state(run_id)
        assert state.nodes[c1].state == "BLOCKED"
        assert set(state.nodes) == nodes_before, "PLAN_ADMITTED must not create nodes"
        assert set(state.relations) == relations_before, "PLAN_ADMITTED must not create relations"

        # The new-plan node is introduced only through NODE_PROPOSED with cause
        # REPLAN (a graph event), then proceeds through the normal lifecycle.
        new_node = controller.admit_plan_node(
            run_id,
            c1,
            f"{c1}-plan-1",
            {
                "description": "retry with narrowed scope",
                "owned_scope": ["src/health/**"],
                "acceptance_criteria": [{"id": "AC-c1-plan", "mandatory": True}],
            },
        )
        state = store.state(run_id)
        assert state.nodes[new_node].cause == "REPLAN"
        assert state.nodes[new_node].state == "BLOCKED"
        controller.prepare_child(run_id, new_node)
        assert store.state(run_id).nodes[new_node].state == "READY"

        # The graph advanced only through admitted events.
        history = store.history(run_id)
        assert state.graph_version >= graph_version_before

        replayed = store.replay_fresh(run_id)
        assert replayed.nodes[c1].state == "BLOCKED"
        assert replayed.nodes[new_node].state == "READY"
        assert replayed.outcome is None
        assert len(replayed.relations) == len(state.relations)
    finally:
        store.close()


# 3. Admission revalidates a proposal's expected entity versions:
# VERSION_CONFLICT_RECORDED is emitted only when a referenced entity changed,
# an expected-absence condition no longer holds, or an invariant is violated;
# unrelated cost, scheduling, attempt, or graph events never invalidate a
# proposal, and the global graph version advancing alone never rejects it.


def test_versioned_proposals_record_conflicts_only_on_referenced_change(tmp_path):
    run_id = "RUN-M2-3"
    store = EventStore(str(tmp_path / "events.db"))
    try:
        controller = make_controller(
            store,
            {
                f"{run_id}-c1": child_script(2.0, "sha256:fail"),
                f"{run_id}-c2": child_script(3.0, "sha256:c2"),
            },
        )
        root, child_ids = decompose_two_children(controller, run_id, budget=50.0, per_child=20.0)
        c1, c2 = child_ids

        # c2 executes independently (unrelated to c1's replan story).
        c2_attempt = controller.execute_attempt(run_id, c2, 5.0)

        # c1 fails validation retry-prohibited, so a replan proposal is the
        # natural next step for it.
        controller.execute_attempt(run_id, c1, 5.0)
        controller.fail_validation(run_id, c1, {"checks": ["BUILD"]})
        state = store.state(run_id)
        c1_version = state.nodes[c1].version

        # Build the plan proposal but do not submit it yet; instead admit
        # unrelated events: a graph relation on other nodes and a scheduling
        # timer for c2's finished attempt. None of them may invalidate the
        # proposal.
        proposal = Proposal(
            proposal_id=f"plan-proposal-{c1}",
            event_type="PLAN_ADMITTED",
            payload={
                "plan_id": f"plan-{c1}",
                "node_id": c1,
                "changed_contract": {"description": "materially changed contract"},
            },
            node_id=c1,
            expected_versions={"node": {c1: c1_version}},
        )
        controller.record_relation(
            run_id,
            f"rel-produces-{c2}",
            "PRODUCES_FOR",
            c2,
            root,
            metadata={"artefact": "candidate"},
        )
        unrelated_timer = events.make_event(
            "TIMER_SCHEDULED",
            {"timer_id": f"timer-audit-{c2}", "attempt_id": c2_attempt, "deadline": 30.0},
            idempotency_key=f"{run_id}:TIMER_SCHEDULED:audit-{c2}",
        )
        store.admit(run_id, unrelated_timer)
        assert store.state(run_id).graph_version > state.graph_version

        # Admission revalidates: every referenced entity is unchanged, so the
        # proposal is admitted even though the global graph version advanced.
        controller.propose(run_id, proposal)
        state = store.state(run_id)
        assert state.nodes[c1].state == "BLOCKED"
        assert not any(
            event.event_type == "VERSION_CONFLICT_RECORDED" for event in store.history(run_id)
        )

        # Trigger 1: a referenced entity changed. A second proposal still
        # expecting c1's old version is revalidated against the current state
        # and produces VERSION_CONFLICT_RECORDED instead of being admitted.
        stale = Proposal(
            proposal_id=f"plan-proposal-stale-{c1}",
            event_type="PLAN_ADMITTED",
            payload={
                "plan_id": f"plan-stale-{c1}",
                "node_id": c1,
                "changed_contract": {"description": "second plan"},
            },
            node_id=c1,
            expected_versions={"node": {c1: c1_version}},
        )
        with pytest.raises(VersionConflict):
            controller.propose(run_id, stale)
        recorded = [
            event
            for event in store.history(run_id)
            if event.event_type == "VERSION_CONFLICT_RECORDED"
        ]
        assert len(recorded) == 1
        entity = recorded[0].payload["entity"]
        assert entity["kind"] == "node" and entity["entity_id"] == c1
        assert entity["reason"] == "ENTITY_CHANGED"
        assert entity["expected_version"] == c1_version
        assert entity["actual_version"] > c1_version
        assert store.state(run_id).nodes[c1].state == "BLOCKED", "a conflicted proposal is not applied"

        # Trigger 2: an expected-absence condition no longer holds.
        absence_proposal = Proposal(
            proposal_id="absence-proposal",
            event_type="PLAN_ADMITTED",
            payload={
                "plan_id": "plan-absence",
                "node_id": c1,
                "changed_contract": {"description": "third plan"},
            },
            node_id=c1,
            expected_absences=[("node", f"{c1}-plan-1")],
        )
        controller._emit(
            run_id,
            "NODE_PROPOSED",
            {
                "node_id": f"{c1}-plan-1",
                "contract": {"description": "plan node"},
                "cause": "REPLAN",
            },
            f"node-proposed-{c1}-plan-1",
        )
        with pytest.raises(VersionConflict):
            controller.propose(run_id, absence_proposal)
        recorded = [
            event
            for event in store.history(run_id)
            if event.event_type == "VERSION_CONFLICT_RECORDED"
        ]
        assert len(recorded) == 2
        assert recorded[-1].payload["entity"]["reason"] == "EXPECTED_ABSENCE_VIOLATED"

        # Trigger 3: the proposed mutation now violates an invariant. A
        # decomposition proposal whose child allocations exceed the parent
        # budget's capacity is recorded as a version conflict, not admitted.
        over_budget_children = [
            child_spec(run_id, "z1", "src/z1/**", 30.0),
            child_spec(run_id, "z2", "src/z2/**", 30.0),
        ]
        with pytest.raises(VersionConflict) as excinfo:
            controller.admit_derived_decomposition(
                run_id,
                root,
                "decomp-invariant",
                over_budget_children,
                coverage(
                    [
                        ("AC-001", f"{run_id}-z1"),
                        ("AC-002", f"{run_id}-z2"),
                    ]
                ),
            )
        assert any(
            conflict["reason"] and "exceed the available capacity" in conflict["reason"]
            for conflict in excinfo.value.conflicts
        )
        recorded = [
            event
            for event in store.history(run_id)
            if event.event_type == "VERSION_CONFLICT_RECORDED"
        ]
        assert len(recorded) == 3
        assert recorded[-1].payload["entity"]["reason"].startswith("child budget allocations")

        replayed = store.replay_fresh(run_id)
        assert len(replayed.version_conflicts) == len(store.state(run_id).version_conflicts) == 3
        assert replayed.nodes[c1].state == "BLOCKED"
    finally:
        store.close()


# 4. Budget reservations, commitments, actuals, reclamation, and ancestor
# projections obey the no-overcommitment invariant, and exhaustion records
# BUDGET_EXHAUSTION_RECORDED when no permitted action can obtain a required
# commitment.


def test_budget_reservations_commitments_reclamation_and_exhaustion(tmp_path):
    run_id = "RUN-M2-4"
    store = EventStore(str(tmp_path / "events.db"))
    try:
        controller = make_controller(
            store,
            {
                f"{run_id}-c1": child_script(30.0, "sha256:c1"),
            },
        )
        config = build_m2_config(run_id, budget=100.0)
        root = controller.submit_run(config)
        # The single child deterministically covers both mandatory criteria.
        children = [child_spec(run_id, "c1", "src/health/**", 60.0, ["AC-001", "AC-002"])]
        controller.admit_derived_decomposition(
            run_id,
            root,
            f"decomp-{run_id}",
            children,
            coverage([("AC-001", f"{run_id}-c1"), ("AC-002", f"{run_id}-c1")]),
        )
        c1 = children[0]["node_id"]

        # A commitment of 60 is reserved and then committed for the attempt.
        attempt_id = controller.plan_attempt(run_id, c1, 60)
        state = store.state(run_id)
        assert state.ledger.reservations == {}, "the reservation converted to a commitment"
        assert state.ledger.commitments == {attempt_id: 60.0}
        assert state.ledger.available(f"{c1}-budget") == 0.0
        # Ancestor projection: the child commitment counts against the parent.
        assert state.ledger.available(f"{root}-budget") == 40.0

        token = controller.dispatch_attempt(run_id, attempt_id, c1)
        response = controller.executor.dispatch(
            {"run_id": run_id, "attempt_id": attempt_id, "attempt_token": token, "node_id": c1}
        )
        controller.admit_observation_and_result(run_id, attempt_id, c1, token, response)

        state = store.state(run_id)
        # The ledger records actual consumption of 30 and reclamation of 30;
        # capacity is available again (docs/budgets.md example).
        assert state.ledger.total_charged == 30.0
        assert state.ledger.commitments == {}
        assert state.ledger.available(f"{c1}-budget") == 30.0
        assert state.ledger.available(f"{root}-budget") == 70.0
        reclamation_entries = [
            entry
            for entry in state.ledger.entries.values()
            if entry.kind == "RECLAMATION" and entry.attempt_id == attempt_id
        ]
        assert [entry.amount for entry in reclamation_entries] == [30.0]

        # The no-overcommitment invariant is enforced inside the reducer: a
        # reservation exceeding the remaining authorisation is rejected and
        # nothing is persisted.
        over = events.make_event(
            "ACTION_RESERVED",
            {"attempt_id": f"{c1}-attempt-over", "commitment": 100.0},
            idempotency_key="over-reserve",
            source="scheduler",
        )
        with pytest.raises(reducer.ReducerError):
            store.admit(run_id, over)
        assert f"{c1}-attempt-over" not in store.replay_fresh(run_id).attempts

        # A commitment without an active reservation is invalid (the
        # first-milestone gap where ACTION_RESERVED opened no ledger
        # reservation is closed in both directions).
        bare = events.make_event(
            "ATTEMPT_COMMITMENT_OPENED",
            {"attempt_id": "a-bare", "commitment": 1},
            idempotency_key="bare-commitment",
        )
        planned = events.make_event(
            "ATTEMPT_PLANNED",
            {"attempt_id": "a-bare", "node_id": c1, "cause": "INITIAL"},
            idempotency_key="bare-plan",
        )
        store.admit(run_id, planned)
        with pytest.raises(reducer.ReducerError):
            store.admit(run_id, bare)

        # Exhaustion: with 30 remaining on the child budget, no permitted
        # action can obtain a required commitment of 40.
        with pytest.raises(BudgetExhausted):
            controller.plan_attempt(run_id, c1, 40.0)
        state = store.state(run_id)
        assert state.nodes[c1].state == "BUDGET_EXHAUSTED"
        assert state.outcome is None, "a non-root node's exhaustion does not terminate the run"
        assert any(
            event.event_type == "BUDGET_EXHAUSTION_RECORDED" for event in store.history(run_id)
        )

        # Ancestor accounting: spending the parent's remaining capacity leaves
        # the child budget untouched, and vice versa.
        assert state.ledger.available(f"{root}-budget") == 70.0
        assert state.ledger.available(f"{c1}-budget") == 30.0

        replayed = store.replay_fresh(run_id)
        assert replayed.ledger.total_charged == 30.0
        assert replayed.ledger.available(f"{c1}-budget") == 30.0
        assert replayed.nodes[c1].state == "BUDGET_EXHAUSTED"
        assert replayed.outcome is None
    finally:
        store.close()


# 5. A TIMER_FIRED timeout fails the attempt through the attempt machine, and
# competing terminal conditions resolve by global event order.


def test_timer_fired_timeout_resolves_by_global_event_order(tmp_path):
    run_id = "RUN-M2-5"
    store = EventStore(str(tmp_path / "events.db"))
    try:
        controller = make_controller(store, {f"{run_id}-root": timed_out_script})
        config = build_m2_config(run_id, budget=20.0)
        root = controller.submit_run(config)

        attempt_id = controller.plan_attempt(run_id, root, 10)
        with pytest.raises(AttemptTimedOut):
            controller.dispatch_attempt(run_id, attempt_id, root, ack_timeout=5.0)

        state = store.state(run_id)
        assert state.attempts[attempt_id].state == "TIMED_OUT"
        timer = state.timers[f"timer-{attempt_id}"]
        # The recorded deadline is an absolute timestamp, not a duration (R22).
        assert timer.fired is True and timer.deadline > 0
        # TIMER_FIRED is an event in the log: replay, not recomputation
        # (docs/control-plane.md#replay-and-external-inputs).
        fired_events = [
            event for event in store.history(run_id) if event.event_type == "TIMER_FIRED"
        ]
        assert len(fired_events) == 1
        payload = fired_events[0].payload
        assert payload["timer_id"] == f"timer-{attempt_id}"
        assert payload["attempt_id"] == attempt_id
        assert payload["configured_deadline"] == timer.deadline
        assert payload["observed_firing_time"] <= payload["configured_deadline"]

        # Timeout followed by late usage settles cost without admitting a
        # result (docs/experiment.md#attempt-and-accounting).
        controller._emit(
            run_id,
            "ATTEMPT_COST_RECONCILED",
            {"attempt_id": attempt_id, "actual": 3.0, "reclamation": 7.0},
            f"late-reconcile-{attempt_id}",
        )
        assert controller.get_costs(run_id)["total_charged"] == 3.0
        assert store.state(run_id).attempts[attempt_id].accounting_state == "FINALLY_SETTLED"
        result_events = [e for e in store.history(run_id) if e.event_type == "RESULT_ADMITTED"]
        assert result_events == []

        # The first terminal condition admitted for the root fixes the outcome.
        controller._emit(
            run_id, "NODE_MARKED_INFEASIBLE", {"node_id": root}, "infeasible-after-timeout"
        )
        assert controller.get_outcome(run_id) == "INFEASIBLE"

        # A competing terminal condition admitted afterwards is retained in
        # the log but leaves the already-admitted outcome unchanged.
        result = controller._emit(
            run_id, "BUDGET_EXHAUSTION_RECORDED", {"node_id": root}, "budget-late"
        )
        assert result.mutated is False
        late_fire = controller._emit(
            run_id,
            "TIMER_FIRED",
            {
                "timer_id": f"timer-{attempt_id}",
                "attempt_id": attempt_id,
                "configured_deadline": timer.deadline,
                "observed_firing_time": timer.deadline,
            },
            f"late-fire-{attempt_id}",
            source="timer",
        )
        assert late_fire.mutated is False
        assert controller.get_outcome(run_id) == "INFEASIBLE"

        replayed = store.replay_fresh(run_id)
        assert replayed.outcome == "INFEASIBLE"
        assert replayed.attempts[attempt_id].state == "TIMED_OUT"
        assert replayed.ledger.total_charged == 3.0
    finally:
        store.close()


# 6. Typed conflicts are recorded and resolved through the Policy transition
# completeness paths, using the deterministic resolution-policy registry.


def test_typed_conflicts_record_and_resolve_via_policy_paths(tmp_path):
    run_id = "RUN-M2-6"
    store = EventStore(str(tmp_path / "events.db"))
    try:
        controller = make_controller(store, {})
        root = controller.submit_run(build_m2_config(run_id, budget=50.0))

        conflict_id = controller.record_conflict(
            run_id,
            root,
            {
                "type": "WRITE_CONFLICT",
                "parties": [root],
                "severity": "BLOCKING",
                "evidence_ids": [],
            },
        )
        state = store.state(run_id)
        assert state.nodes[root].state == "CONFLICTED"
        record = state.conflicts[conflict_id]
        assert record.lifecycle_state == "OPEN"
        # Deterministic registry selection: same input, same policy.
        assert record.resolution_policy == "INTEGRATION_OWNER_ADJUDICATION"
        from orchestrator import policy

        assert (
            controller.executor  # no-op use of controller
            and policy.resolution_policy_for("WRITE_CONFLICT")
            == record.resolution_policy
        )

        # The policy-completeness path taken: READY --CONFLICT_RECORDED-->
        # CONFLICTED --CONFLICT_RESOLVED--> BLOCKED.
        controller.resolve_conflict(run_id, root, conflict_id)
        state = store.state(run_id)
        assert state.nodes[root].state == "BLOCKED"
        assert state.conflicts[conflict_id].lifecycle_state == "RESOLVED"

        # Readiness is re-established after resolution, and the run continues.
        controller._emit(
            run_id,
            "READINESS_ESTABLISHED",
            {"node_id": root, "action": "EXECUTE"},
            f"node-ready-again-{root}",
            source="scheduler",
        )
        assert store.state(run_id).nodes[root].state == "READY"

        replayed = store.replay_fresh(run_id)
        assert replayed.nodes[root].state == "READY"
        assert replayed.conflicts[conflict_id].lifecycle_state == "RESOLVED"
        assert replayed.outcome is None
    finally:
        store.close()


# 7. Independent attempts for deterministically disjoint write scopes run
# concurrently while mutation admission stays serialised; concurrent scheduling
# admits per-attempt events in one global sequence; duplicate events do not
# duplicate state changes or charges.


def test_concurrent_disjoint_attempts_serialised_admission_and_idempotency(tmp_path):
    run_id = "RUN-M2-7"
    store = EventStore(str(tmp_path / "events.db"))
    try:
        controller = make_controller(
            store,
            {
                f"{run_id}-c1": child_script(4.0, "sha256:c1"),
                f"{run_id}-c2": child_script(4.0, "sha256:c2"),
                f"{run_id}-s1": child_script(2.0, "sha256:s1"),
                f"{run_id}-s2": child_script(2.0, "sha256:s2"),
                "RUN-M2-7-serial-s1": child_script(2.0, "sha256:s1"),
                "RUN-M2-7-serial-s2": child_script(2.0, "sha256:s2"),
            },
        )
        root, child_ids = decompose_two_children(controller, run_id, budget=50.0, per_child=20.0)

        attempt_ids = controller.schedule_child_attempts(run_id, child_ids, 5.0)
        assert len(attempt_ids) == 2
        state = store.state(run_id)
        assert all(state.attempts[a].state == "RESULT_PRODUCED" for a in attempt_ids)

        # One global sequence with no gaps: every per-attempt event was
        # admitted through the single serialised admission path.
        assert dense_global_sequence(store, run_id) == list(range(1, len(store.history(run_id)) + 1))
        history = controller.get_event_history(run_id)
        for attempt_id in attempt_ids:
            planned = [
                e
                for e in history
                if e["event_type"] == "ATTEMPT_PLANNED" and e["payload"]["attempt_id"] == attempt_id
            ]
            assert len(planned) == 1

        # Duplicate events do not duplicate state changes or charges.
        charged_before = controller.get_costs(run_id)["total_charged"]
        duplicate = events.make_event(
            "ATTEMPT_COST_RECONCILED",
            {"attempt_id": attempt_ids[0], "actual": 4.0, "reclamation": 1.0},
            idempotency_key=f"{run_id}:ATTEMPT_COST_RECONCILED:reconcile-{attempt_ids[0]}",
        )
        assert store.admit(run_id, duplicate).duplicate is True
        assert controller.get_costs(run_id)["total_charged"] == charged_before

        # Nodes with overlapping write scopes are serialised in deterministic
        # (sorted) order instead of running concurrently.
        run_id2 = "RUN-M2-7-serial"
        config2 = build_m2_config(run_id2, budget=50.0)
        root2 = controller.submit_run(config2)
        children = [
            child_spec(run_id2, "s2", "src/shared/**", 10.0),
            child_spec(run_id2, "s1", "src/shared/**", 10.0),
        ]
        child_ids2 = controller.admit_derived_decomposition(
            run_id2,
            root2,
            f"decomp-{run_id2}",
            children,
            coverage([("AC-001", f"{run_id2}-s1"), ("AC-002", f"{run_id2}-s2")]),
        )
        controller.schedule_child_attempts(run_id2, child_ids2, 2.0)
        planned_order = [
            e["payload"]["node_id"]
            for e in controller.get_event_history(run_id2)
            if e["event_type"] == "ATTEMPT_PLANNED"
        ]
        assert planned_order == sorted([f"{run_id2}-s1", f"{run_id2}-s2"])

        replayed = store.replay_fresh(run_id)
        assert replayed.ledger.total_charged == state.ledger.total_charged
        assert replayed.attempts[attempt_ids[0]].state == "RESULT_PRODUCED"
        assert replayed.attempts[attempt_ids[1]].state == "RESULT_PRODUCED"
        assert replayed.graph_version == state.graph_version
    finally:
        store.close()


# 8. Replay reproduces state, ledger, and outcome without dispatching work, and
# crash injection at persistence and dispatch boundaries recovers as declared.


def test_replay_and_crash_boundaries_recover_as_declared(tmp_path):
    run_id = "RUN-M2-8"
    db_path = str(tmp_path / "events.db")
    store = EventStore(db_path)
    scripts = {
        f"{run_id}-c1": child_script(4.0, "sha256:c1"),
        f"{run_id}-c2": child_script(4.0, "sha256:c2"),
    }
    try:
        controller = make_controller(store, scripts)
        root, child_ids = decompose_two_children(controller, run_id, budget=50.0, per_child=20.0)
        c1, c2 = child_ids

        # Persistence boundary: a crash before commit leaves no partial event.
        def boom(event):
            raise CrashInjected("simulated crash before commit")

        store.crash_before_commit = boom
        with pytest.raises(CrashInjected):
            controller.plan_attempt(run_id, c1, 5.0)
        store.crash_before_commit = None
        assert store.replay_fresh(run_id).attempts == {}

        # Retry with the same semantic flow succeeds cleanly.
        execute_and_accept(controller, run_id, c1)

        # Dispatch boundary: ACTION_DISPATCHED is durable, then the process
        # "crashes" before the executor receives the request.
        attempt2 = controller.plan_attempt(run_id, c2, 5.0)
        controller.executor.issue_token(attempt2)
        controller._emit(
            run_id,
            "ACTION_DISPATCHED",
            {"attempt_id": attempt2, "executor": "scripted-in-process"},
            f"dispatch-{attempt2}",
        )
        assert store.state(run_id).attempts[attempt2].state == "DISPATCHED"
    finally:
        store.close()

    # Restart from the durable log only, then run recovery.
    restarted_store = EventStore(db_path)
    try:
        restarted_controller = make_controller(restarted_store, scripts)
        recovered = restarted_controller.recover(run_id)
        assert recovered == [attempt2]
        state = restarted_store.state(run_id)
        assert state.attempts[attempt2].state == "FAILED"
        assert state.attempts[attempt2].accounting_state == "FINALLY_SETTLED"
        # Conservative settlement charged the full outstanding commitment
        # (on top of c1's reconciled actual of 4.0).
        assert restarted_controller.get_costs(run_id)["total_charged"] == 9.0

        # The run continues: the retried attempt for c2 completes and the
        # parent acceptance policy accepts the root.
        execute_and_accept(restarted_controller, run_id, c2)
        restarted_controller.accept_parent(
            run_id, root, {"checks": ["HEALTH", "METRICS"], "child_acceptances": child_ids}
        )
        assert restarted_store.state(run_id).outcome == "ACCEPTANCE_CLAIMED"

        # Replay reproduces state, ledger, and outcome without dispatching
        # work: replaying leaves the executor's response cache untouched.
        live = restarted_store.state(run_id)
        dispatch_count_before = len(restarted_controller.executor._responses)
        replayed = restarted_store.replay_fresh(run_id)
        assert replayed.nodes[root].state == live.nodes[root].state == "ACCEPTED"
        assert replayed.outcome == live.outcome == "ACCEPTANCE_CLAIMED"
        # c1 actual (4.0) + conservative settlement of the crashed attempt
        # (5.0) + the retried c2 attempt actual (4.0).
        assert replayed.ledger.total_charged == live.ledger.total_charged == 13.0
        assert replayed.graph_version == live.graph_version
        assert len(restarted_controller.executor._responses) == dispatch_count_before
    finally:
        restarted_store.close()


# Regression (docs/work-graph.md#hierarchy-and-dependency-are-separate): a
# DEPENDS_ON relation is recorded from the dependent to its required
# predecessor. The dependent stays BLOCKED, prepare_child refuses while a
# predecessor is unaccepted and succeeds once it is ACCEPTED, and a
# predecessor is never blocked by its own dependent.


def test_prepare_child_refuses_until_every_predecessor_is_accepted(tmp_path):
    run_id = "RUN-M2-DEPS"
    store = EventStore(str(tmp_path / "events.db"))
    try:
        controller = make_controller(
            store,
            {
                f"{run_id}-c1": child_script(4.0, "sha256:c1"),
                f"{run_id}-c2": child_script(6.0, "sha256:c2"),
            },
        )
        root, child_ids = decompose_two_children(controller, run_id)
        c1, c2 = child_ids
        # Both children are schedulable here (no dependency edge yet); record
        # c2's dependency on c1 through the same relation the controller's
        # decomposition admission emits.
        controller.propose(run_id, Proposal(
            proposal_id=f"dep-{c2}",
            event_type="RELATION_RECORDED",
            payload={
                "relation_id": f"rel-depends-{c2}-{c1}",
                "relation_type": "DEPENDS_ON",
                "from_node_id": c2,
                "to_node_id": c1,
            },
            node_id=root,
            expected_absences=[("relation", f"rel-depends-{c2}-{c1}")],
        ))
        state = store.state(run_id)
        assert state.nodes[c1].state == "READY"
        assert state.nodes[c2].state == "READY"

        # A dependent whose predecessor is only READY is refused...
        with pytest.raises(WorkflowError):
            controller.prepare_child(run_id, c2)
        # ...and a predecessor is never blocked by its own dependent.
        assert state.dependencies_of(c1) == []
        controller.prepare_child(run_id, c1)
        assert store.state(run_id).nodes[c1].state == "READY"
    finally:
        store.close()


def test_prepare_child_grants_readiness_once_predecessor_is_accepted(tmp_path):
    run_id = "RUN-M2-DEPS-2"
    store = EventStore(str(tmp_path / "events.db"))
    try:
        controller = make_controller(
            store,
            {
                f"{run_id}-c1": child_script(4.0, "sha256:c1"),
                f"{run_id}-c2": child_script(6.0, "sha256:c2"),
            },
        )
        root, child_ids = decompose_two_children(controller, run_id)
        c1, c2 = child_ids
        controller._emit(
            run_id,
            "RELATION_RECORDED",
            {
                "relation_id": f"rel-depends-{c2}-{c1}",
                "relation_type": "DEPENDS_ON",
                "from_node_id": c2,
                "to_node_id": c1,
            },
            f"relation-dep-{c2}-{c1}",
        )
        execute_and_accept(controller, run_id, c1)
        state = store.state(run_id)
        assert state.nodes[c1].state == "ACCEPTED"
        controller.prepare_child(run_id, c2)
        assert store.state(run_id).nodes[c2].state == "READY"
        # Replay reproduces the refused-then-granted readiness from the log.
        replayed = store.replay_fresh(run_id)
        assert replayed.nodes[c1].state == "ACCEPTED"
        assert replayed.nodes[c2].state == "READY"
        assert len(replayed.relations) == len(state.relations)
    finally:
        store.close()


def test_admitted_decomposition_blocks_dependents_only(tmp_path):
    run_id = "RUN-M2-DEPS-2"
    store = EventStore(str(tmp_path / "events.db"))
    try:
        controller = make_controller(
            store,
            {
                f"{run_id}-c1": child_script(4.0, "sha256:c1"),
                f"{run_id}-c2": child_script(6.0, "sha256:c2"),
            },
        )
        config = build_m2_config(run_id)
        root = controller.submit_run(config)
        children = [
            child_spec(run_id, "c1", "src/health/**", 20.0, ["AC-001"]),
            child_spec(run_id, "c2", "src/metrics/**", 20.0, ["AC-002"]),
        ]
        cov = coverage([("AC-001", f"{run_id}-c1"), ("AC-002", f"{run_id}-c2")])
        child_ids = controller.admit_derived_decomposition(
            run_id, root, f"decomp-{run_id}", children, cov,
            dependencies=[{"from_node_id": f"{run_id}-c2", "to_node_id": f"{run_id}-c1"}],
        )
        state = store.state(run_id)
        # The dependent starts BLOCKED; the predecessor is schedulable.
        assert state.nodes[child_ids[1]].state == "BLOCKED"
        assert state.nodes[child_ids[0]].state == "READY"
        relation = state.relations[f"rel-depends-{child_ids[1]}-{child_ids[0]}"]
        assert relation.relation_type == "DEPENDS_ON"
        assert relation.from_node_id == child_ids[1]
        assert relation.to_node_id == child_ids[0]
    finally:
        store.close()
