# SPDX-License-Identifier: AGPL-3.0-or-later
"""Narrow fail-closed harness tests.

The resource operations that previously leaked are monkeypatched to fail one at
a time — cgroup removal, cgroup placement, status-pipe creation, and output-file
creation — and the caller must report failure rather than return a successful
observation. The patching is deliberately narrow (one operation per test).

Unit cases for ``_teardown`` run everywhere; the run-level cases require a
provisionable sandbox profile and skip otherwise.
"""
from __future__ import annotations

import os
import shutil
import tempfile

import pytest

from orchestrator import sandbox

from test_milestone3_sandbox import PROBE_PYTHON, TOOLCHAIN_PATHS


class _FakeCgroup:
    path = "/fake/cgroup"

    def kill(self) -> None:
        pass

    def remove(self, timeout: float = 5.0) -> bool:
        return False


def _teardown_runner() -> sandbox.SandboxRunner:
    return object.__new__(sandbox.SandboxRunner)


def test_teardown_reports_an_unremoved_cgroup():
    errors = _teardown_runner()._teardown(None, _FakeCgroup(), None, None, None, None)
    assert errors == ["cgroup '/fake/cgroup' was not removed"]


def test_teardown_never_raises_on_close_failures(monkeypatch):
    def boom(_descriptor):
        raise OSError("close failed")

    monkeypatch.setattr(sandbox.os, "close", boom)
    errors = _teardown_runner()._teardown(None, _FakeCgroup(), 1, 2, None, None)
    assert errors == ["cgroup '/fake/cgroup' was not removed"]


def _require_sandbox() -> sandbox.SandboxCapabilities:
    found = sandbox.capabilities()
    if not found.profile_available:
        pytest.fail(f"no sandbox profile (fail-closed gate): {found.unavailable_reason()}")
    return found


@pytest.fixture
def sandbox_work():
    work = tempfile.mkdtemp(prefix="fail-closed-work-")
    new_root = tempfile.mkdtemp(prefix="fail-closed-root-")
    with open(os.path.join(work, "probe.py"), "w") as handle:
        handle.write("print('ok')\n")
    try:
        yield work, new_root
    finally:
        shutil.rmtree(work, ignore_errors=True)
        shutil.rmtree(new_root, ignore_errors=True)


def _plan(work: str, new_root: str) -> sandbox.SandboxPlan:
    readonly = [
        sandbox.MountSpec(host=path, guest=path, readonly=True)
        for path in TOOLCHAIN_PATHS
        if os.path.exists(path)
    ]
    return sandbox.SandboxPlan(
        new_root=new_root,
        rw_mounts=(sandbox.MountSpec(host=work, guest="/work", readonly=False),),
        ro_mounts=tuple(readonly),
        tmpfs_mounts=("/tmp",),
        workdir="/work",
        command=(PROBE_PYTHON, "/work/probe.py"),
        env={
            "PATH": "/usr/bin:/bin",
            "HOME": "/work",
            "LANG": "C.UTF-8",
            "PYTHONDONTWRITEBYTECODE": "1",
        },
        limits=sandbox.SandboxLimits(wall_seconds=30),
    )


def test_unremoved_cgroup_fails_the_run_closed(monkeypatch, sandbox_work):
    capabilities = _require_sandbox()
    if not (capabilities.cgroup_v2 and capabilities.cgroup_parent):
        pytest.fail("no delegated cgroup v2 subtree (fail-closed gate)")

    original_remove = sandbox._Cgroup.remove

    def remove_then_claim_failure(self, timeout=5.0):
        original_remove(self, timeout)
        return False

    monkeypatch.setattr(sandbox._Cgroup, "remove", remove_then_claim_failure)
    runner = sandbox.SandboxRunner(capabilities_override=capabilities)
    with pytest.raises(sandbox.SandboxSetupError) as raised:
        runner.run(_plan(*sandbox_work))
    assert "was not removed" in str(raised.value)


def test_cgroup_placement_failure_fails_the_run(monkeypatch, sandbox_work):
    capabilities = _require_sandbox()
    if not (capabilities.cgroup_v2 and capabilities.cgroup_parent):
        pytest.fail("no delegated cgroup v2 subtree (fail-closed gate)")

    def boom(_self, _pid):
        raise OSError("cgroup placement failed")

    monkeypatch.setattr(sandbox._Cgroup, "place", boom)
    runner = sandbox.SandboxRunner(capabilities_override=capabilities)
    with pytest.raises(OSError):
        runner.run(_plan(*sandbox_work))


def test_status_pipe_failure_fails_the_run(monkeypatch, sandbox_work):
    capabilities = _require_sandbox()

    def boom():
        raise OSError("status pipe failed")

    monkeypatch.setattr(sandbox.os, "pipe", boom)
    runner = sandbox.SandboxRunner(capabilities_override=capabilities)
    with pytest.raises(OSError):
        runner.run(_plan(*sandbox_work))


def test_output_file_failure_fails_the_run(monkeypatch, sandbox_work):
    capabilities = _require_sandbox()

    def boom(*_args, **_kwargs):
        raise OSError("output file failed")

    monkeypatch.setattr(sandbox.tempfile, "TemporaryFile", boom)
    runner = sandbox.SandboxRunner(capabilities_override=capabilities)
    with pytest.raises(OSError):
        runner.run(_plan(*sandbox_work))


def test_bug_failed_cgroup_limits_leave_no_orphaned_cgroup(monkeypatch, sandbox_work):
    """A failed cgroup limit write discards the reference without removing the
    directory, leaking a delegated cgroup. Also asserts the fallback evidence
    does not overstate its provenance."""
    capabilities = _require_sandbox()
    if not (capabilities.cgroup_v2 and capabilities.cgroup_parent):
        pytest.fail("no delegated cgroup v2 subtree (fail-closed gate)")

    created = []
    original_init = sandbox._Cgroup.__init__

    def record(self, parent, name, controllers):
        original_init(self, parent, name, controllers)
        created.append(self.path)

    def boom(_self, _limits):
        raise OSError("cgroup limit write failed")

    monkeypatch.setattr(sandbox._Cgroup, "__init__", record)
    monkeypatch.setattr(sandbox._Cgroup, "set_limits", boom)
    runner = sandbox.SandboxRunner(capabilities_override=capabilities)

    leaked = []
    try:
        observation = runner.run(_plan(*sandbox_work))
    finally:
        leaked = [path for path in created if os.path.exists(path)]
        for path in leaked:
            os.rmdir(path)

    assert observation.cgroup is None
    assert observation.resource_source == "RUSAGE_CHILDREN"
    assert not leaked, f"a failed cgroup setup leaked {leaked}"

