# SPDX-License-Identifier: AGPL-3.0-or-later
"""A6 multi-writer durable ledger (slow tier).

Two processes reserve against one workdir and one ceiling smaller than their
sum. Exactly one reservation may be represented, it must equal the ceiling
remainder, and the ledger file must be present, parseable, and free of the
shared temporary file after the run. The writers use a spawn context with a
module-level worker to avoid fork-in-threads hazards.

Anti-vacuity: the ledger file must exist and parse, and the accepted
reservation is compared to the exact ceiling remainder.
"""
from __future__ import annotations

import json
import multiprocessing

import pytest

from orchestrator import spend

from test_milestone8_readiness import _authorization, _concurrent_reserve_worker

CEILING = 10.0
RESERVATION = 8.0


@pytest.mark.slow
def test_concurrent_writers_preserve_one_reservation(tmp_path):
    workdir = str(tmp_path / "experiment")
    context = multiprocessing.get_context("spawn")
    barrier = context.Barrier(2)
    results = context.Queue()

    processes = [
        context.Process(
            target=_concurrent_reserve_worker,
            args=(workdir, f"t{index}", barrier, results),
        )
        for index in range(2)
    ]
    for process in processes:
        process.start()
    for process in processes:
        process.join(timeout=30)
        assert process.exitcode == 0, "a writer process crashed"

    outcomes = [results.get(timeout=5) for _ in range(2)]
    accepted = [trial for trial, status in outcomes if status == "reserved"]
    assert len(accepted) == 1, f"expected exactly one accepted reservation: {outcomes}"

    # Durability: the file exists, parses, and holds exactly the accepted amount.
    ledger_path = tmp_path / "experiment" / "experiment-spend.json"
    assert ledger_path.exists(), "anti-vacuity: the ledger file must be written"
    payload = json.loads(ledger_path.read_text())
    assert isinstance(payload, dict)

    reopened = spend.open_spend_ledger(workdir, _authorization(limit=CEILING))
    assert reopened.reserved() == RESERVATION
    assert reopened.authorization.limit - reopened.reserved() == CEILING - RESERVATION
    assert not (tmp_path / "experiment" / "experiment-spend.json.tmp").exists()
