# SPDX-License-Identifier: AGPL-3.0-or-later
"""The B-lite input-purity property (performance plan, cheap state clone gate).

The gate is inventory-independent: after ``reduce(state, event)`` the input
state must deep-equal a pre-call ``deepcopy`` of itself, applied across a
fuzzer-shaped corpus **including calls that raise** — a ``ReducerError``
mid-application is exactly where a partial in-place mutation would hide. A
per-call check also catches cross-call aliasing: any in-place mutation targets
an object reachable from the immediate input, so the input changes at the call
where the mutation happens and the check catches it there.

The property's own ``deepcopy`` is test-only and does not affect production
clone cost.
"""

from __future__ import annotations

import copy
import random

import pytest

from helpers import build_run_config

from orchestrator.events import Event
from orchestrator.model import RunState
from orchestrator.reducer import ReducerError, reduce
from orchestrator.store import EventStore
from orchestrator.controller import Controller
from orchestrator.executor import ScriptedExecutor

def _broken_variants(event: Event):
    """Real event types with payloads crafted to fail somewhere in the handler
    (unknown references, malformed amounts, impossible transitions). Whatever
    raises and wherever it raises, the input state must be untouched."""
    payload = dict(event.payload)
    variants = []
    for key in ("node_id", "attempt_id", "output_id", "artefact_id", "budget_id"):
        if key in payload:
            broken = dict(payload)
            broken[key] = "does-not-exist"
            variants.append((event.event_type, broken))
    if "amount" in payload:
        broken = dict(payload)
        broken["amount"] = "not-an-amount"
        variants.append((event.event_type, broken))
    variants.append((event.event_type + "_NO_SUCH_TYPE", payload))
    return variants


def _script(_request):
    return {
        "self_reported_status": "COMPLETED",
        "artefacts": [{"type": "GIT_CANDIDATE", "content_hash": "sha256:purity"}],
        "observations": [{"type": "COMMAND_RESULT", "command_id": "BUILD", "exit_code": 0}],
        "cost_report": {"committed": 5, "actual": 5, "units": "USD"},
    }


def _failing_script(_request):
    return {
        "self_reported_status": "FAILED",
        "artefacts": [],
        "observations": [],
        "cost_report": {"committed": 5, "actual": 5, "units": "USD"},
    }


def _corpus_events(tmp_path) -> list:
    """An event corpus shaped like the state fuzzer's walks: attempts,
    executions, validations, cancellations, failures (the
    ``failure_fingerprints``/``failure_strategies`` appends), retries, and
    conservative settlements (the ledger's in-place entry flips)."""
    events = []
    for seed in (7, 21, 33):
        run_id = f"PURITY-{seed}"
        store = EventStore(str(tmp_path / f"{run_id}.db"))
        scripts = {f"{run_id}-root": _script if seed % 2 else _failing_script}
        controller = Controller(store, ScriptedExecutor(scripts))
        try:
            root = controller.submit_run(build_run_config(run_id))
            rng = random.Random(seed)
            for step in range(30):
                try:
                    actions = [
                        lambda: controller.plan_attempt(run_id, root, rng.choice([1.0, 5.0])),
                        lambda: controller.execute_attempt(run_id, root, rng.choice([1.0, 5.0])),
                        lambda: controller.record_failure(
                            run_id,
                            root,
                            action_type="EXECUTE",
                            diagnostic_category="EXECUTOR_FAILED",
                            evidence_digest="sha256:failed",
                        ),
                    ]
                    if step >= 6:
                        actions.append(lambda: controller.cancel_run(run_id, root))
                    rng.choice(actions)()
                except (ReducerError, Exception):
                    # Refusals are part of the corpus's real shape; their
                    # partially-applied events are exactly what the gate must
                    # catch, and the recorded history below holds them all.
                    pass
            events.extend(store.history(run_id))
        finally:
            store.close()
    return events


def test_reduce_never_mutates_its_input_state(tmp_path):
    events = _corpus_events(tmp_path)
    assert len(events) > 50, "the corpus is vacuous"

    state = RunState(run_id="PURITY")
    for index, event in enumerate(events):
        before = copy.deepcopy(state)
        try:
            new_state, _effects = reduce(state, event)
        except ReducerError:
            # The input must be untouched even when the handler raised
            # mid-application.
            assert state == before, f"input mutated by raising call on {event.event_type}"
            continue
        assert state == before, f"input mutated by reduce on {event.event_type}"
        state = new_state

        # Interleave synthetic raising calls against the grown state: every
        # failure path must leave the input untouched (a ReducerError
        # mid-application is exactly where a partial in-place mutation hides).
        if index % 20 == 19:
            for event_type, payload in _broken_variants(event):
                broken = Event(
                    event_id="purity-broken",
                    event_type=event_type,
                    payload=payload,
                    idempotency_key="purity-broken",
                    schema_version=1,
                    policy_version=1,
                )
                before = copy.deepcopy(state)
                try:
                    reduce(state, broken)
                except Exception:  # noqa: BLE001 - the property holds for any failure
                    pass
                assert state == before, f"input mutated by failing call on {event_type}"


def test_clone_shares_nothing_the_reducer_can_mutate():
    """The clone contract itself: every reducer-mutable container is unshared,
    while nested immutable values are shared (the saving)."""
    state = RunState(run_id="PURITY-CLONE")
    state.failure_fingerprints.setdefault("node", []).append("fp")
    state.failure_strategies.setdefault("node", []).append("st")
    state.version_conflicts.append({"node_id": "n", "entity": "e"})
    clone = state.clone()

    for name in (
        "nodes",
        "relations",
        "attempts",
        "artefacts",
        "freshness",
        "model_outputs",
        "evidence",
        "failure_fingerprints",
        "failure_strategies",
        "conflicts",
        "timers",
        "approvals",
        "credentials",
    ):
        assert getattr(clone, name) is not getattr(state, name), name
    assert clone.failure_fingerprints["node"] is not state.failure_fingerprints["node"]
    assert clone.failure_strategies["node"] is not state.failure_strategies["node"]
    assert clone.version_conflicts is not state.version_conflicts
    assert clone.version_conflicts[0] is not state.version_conflicts[0]

    assert clone.ledger is not state.ledger
    assert clone.ledger.budgets is not state.ledger.budgets
    assert clone.ledger.entries is not state.ledger.entries
    assert clone.ledger.reservations is not state.ledger.reservations
    assert clone.ledger.commitments is not state.ledger.commitments
    assert clone.ledger.charged is not state.ledger.charged
    assert clone.ledger.overruns is not state.ledger.overruns

    # Mutating the clone's containers leaves the input alone.
    clone.failure_fingerprints["node"].append("mutated")
    clone.version_conflicts.append({"node_id": "x", "entity": "y"})
    clone.ledger.total_charged = 99.0
    assert state.failure_fingerprints["node"] == ["fp"]
    assert len(state.version_conflicts) == 1
    assert state.ledger.total_charged == 0.0
