# SPDX-License-Identifier: AGPL-3.0-or-later
"""A5 single-flight concurrency harness.

Two callers rendezvous on a barrier and dispatch the same ``(attempt_id,
token)`` concurrently. Exactly one priced client invocation may occur, and both
callers must observe the same outcome — including when the completion fails
post-call validation (a malformed cost or a token-shaped unit), because a
failure must be cached as well as a success.

Anti-vacuity: every case asserts the barrier was reached by both parties and
that the client was invoked at least once. Each case is time-bounded so a
deadlock fails instead of hanging.
"""

from __future__ import annotations

import json
import threading

import pytest

from orchestrator import model_adapter
from orchestrator.model_adapter import ModelAdapter, ModelBudgetRefused, ModelCompletion

REQUEST = {
    "run_id": "R",
    "action_id": "A",
    "attempt_id": "a1",
    "node_id": "n1",
    "action_type": "REVIEW",
    "resolved_inputs": [],
    "budget_commitment": {"dimension": "MODEL_COST", "hard_limit": 5},
    "policy_version": 1,
    "prompt_hash": "sha256:p",
}


class _ScriptedCompletionClient(model_adapter.ModelClient):
    """Counts calls and returns the queued completions in order."""

    def __init__(self, completions):
        self.completions = list(completions)
        self.calls = 0

    def max_cost(self, request):
        return 1.0

    def complete(self, request):
        self.calls += 1
        if self.completions:
            return self.completions.pop(0)
        raise AssertionError("client invoked more times than completions were queued")


def _completion(cost=1.0, units="USD"):
    return ModelCompletion(
        outputs=(),
        cost=cost,
        units=units,
        model_id="model-x",
        model_version="1",
        input_tokens=1,
        output_tokens=1,
    )


def _dispatch_twice(client):
    adapter = ModelAdapter(client, model_id="model-x", model_version="1")
    request = dict(REQUEST, attempt_token=adapter.issue_token("a1"))
    barrier = threading.Barrier(2)
    arrived = []
    outcomes = []

    def worker():
        arrived.append(1)
        barrier.wait(timeout=10)
        try:
            result = adapter.dispatch(request)
            outcomes.append(("ok", json.dumps(result, sort_keys=True, default=str)))
        except ModelBudgetRefused as error:
            outcomes.append(("refused", type(error).__name__))

    threads = [threading.Thread(target=worker) for _ in range(2)]
    for thread in threads:
        thread.start()
    for thread in threads:
        thread.join(timeout=30)
    assert not any(thread.is_alive() for thread in threads), "dispatch deadlocked"
    return arrived, outcomes


def _assert_single_flight(client, expected_kind):
    arrived, outcomes = _dispatch_twice(client)
    assert arrived == [1, 1], "anti-vacuity: both callers must reach the barrier"
    assert client.calls >= 1, "anti-vacuity: the client must be reached"
    assert client.calls == 1, f"the priced client was invoked {client.calls} times"
    assert len(set(outcomes)) == 1, f"callers observed different outcomes: {outcomes}"
    assert outcomes[0][0] == expected_kind


@pytest.mark.timeout(30)
def test_single_flight_holds_for_a_valid_completion():
    client = _ScriptedCompletionClient([_completion(), _completion()])
    _assert_single_flight(client, "ok")


@pytest.mark.timeout(30)
def test_single_flight_holds_when_cost_fails_validation():
    client = _ScriptedCompletionClient([_completion(cost=float("nan")), _completion()])
    _assert_single_flight(client, "refused")


@pytest.mark.timeout(30)
def test_single_flight_holds_when_units_fail_validation():
    client = _ScriptedCompletionClient([_completion(units="MODEL_TOKENS"), _completion()])
    _assert_single_flight(client, "refused")


class _RaisingThenValidClient(model_adapter.ModelClient):
    """First completion raises at the transport boundary; a second would return."""

    def __init__(self):
        self.calls = 0

    def max_cost(self, request):
        return 1.0

    def complete(self, request):
        self.calls += 1
        if self.calls == 1:
            raise RuntimeError("transport error")
        return _completion()


@pytest.mark.timeout(30)
def test_single_flight_holds_when_the_completion_raises():
    """SPEND re-verification N1: a completion that raises at the transport layer
    is cached as a failure, so one attempt/token is invoked once."""
    client = _RaisingThenValidClient()
    adapter = ModelAdapter(client, model_id="model-x", model_version="1")
    request = dict(REQUEST, attempt_token=adapter.issue_token("a1"))
    barrier = threading.Barrier(2)
    outcomes = []

    def worker():
        barrier.wait(timeout=10)
        try:
            adapter.dispatch(request)
            outcomes.append("ok")
        except Exception as error:  # noqa: BLE001 - outcome recorded for the assertion
            outcomes.append(type(error).__name__)

    threads = [threading.Thread(target=worker) for _ in range(2)]
    for thread in threads:
        thread.start()
    for thread in threads:
        thread.join(timeout=30)
    assert not any(thread.is_alive() for thread in threads), "dispatch deadlocked"
    assert client.calls == 1, f"the priced client was invoked {client.calls} times"
    assert outcomes == ["RuntimeError", "RuntimeError"], outcomes
