# SPDX-License-Identifier: AGPL-3.0-or-later
"""Review probes for the phase 6 supervisor.

Filed by the review at `docs/research/phase6-supervisor-review-brief.md`.
Two shapes the delivered module does not build, both green at
`90b54a15692f34faa49fb5802af1f3d74f32c8ad`:

1. ``test_the_group_kill_reaches_the_grandchild_before_the_supervisor_exits``
   — the grandchild's liveness is measured at a fixed time after the
   deadline, not after the supervisor's exit. The delivered tree pin waits
   for the supervisor to exit first, and a grandchild that survived the
   kill holds the output pipes open, delaying that exit past the
   grandchild's own sleep; the pin therefore cannot tell a group kill from
   a lone child kill. This probe measures the guarantee itself.
2. ``test_the_child_head_receives_the_whole_environment_and_runs_once`` —
   the fixture records the ``--json`` head's own launches (count, argv,
   and the whole ``ORCHESTRATOR_*`` environment). The delivered module
   records only the ``--resume`` head, so the child head's environment
   pass-through and its "exactly one child" launch are unobserved.
"""

from __future__ import annotations

import contextlib
import json
import os
import subprocess
import sys
import time
from pathlib import Path

import supervise_run

REPO_ROOT = Path(__file__).resolve().parents[1]
SUPERVISOR = Path(supervise_run.__file__).resolve()
SECRET = "phase6-review-probe-secret"

# The review probe's own fixture child. It records both heads: the
# ``--json`` launch (argv, the whole environment, and a launch count) and
# the ``--resume`` invocation. In the tree scenario it spawns a grandchild
# sleep whose lifetime is far longer than the supervisor's budget, and
# records the grandchild's pid.
FIXTURE = '''\
import json
import os
import subprocess
import sys
import time

out = os.environ.get("REVIEW_MARKER_DIR", "")


def record(name, payload):
    if out:
        with open(os.path.join(out, name), "a") as handle:
            handle.write(json.dumps(payload) + "\\n")


if "--resume" in sys.argv:
    record("resume.jsonl", {"argv": sys.argv[1:]})
    sys.exit(0)

record("child-launches.jsonl", {
    "argv": sys.argv[1:],
    "env": {k: v for k, v in os.environ.items() if k.startswith("ORCHESTRATOR_")},
})

if os.environ.get("REVIEW_SCENARIO") == "tree":
    grandchild = subprocess.Popen(
        [sys.executable, "-c", "import time; time.sleep(60)"]
    )
    record("grandchild.json", {"pid": grandchild.pid})
    time.sleep(60)

if os.environ.get("REVIEW_SCENARIO") == "lost":
    sys.stderr.write("review fixture: lost\\n")
    sys.exit(3)

sys.stdout.write(json.dumps({"code": 0}) + "\\n")
sys.exit(0)
'''


def _fixture_root(root: Path) -> Path:
    scripts = root / "scripts"
    scripts.mkdir(parents=True, exist_ok=True)
    (scripts / "smoke_run.py").write_text(FIXTURE)
    return root


def _env(root: Path, scenario: str = "clean") -> dict:
    env = {
        key: value
        for key, value in os.environ.items()
        if not key.startswith("ORCHESTRATOR_")
    }
    env.update({
        "ORCHESTRATOR_WORKDIR": str(root / "workdir"),
        "ORCHESTRATOR_OWNER": "phase6-review",
        "ORCHESTRATOR_CAP": "500",
        "ORCHESTRATOR_AUTHORIZED_AT": "2026-01-01T00:00:00Z",
        "ORCHESTRATOR_AUTH_METHOD": "phase6-review-probe",
        "ORCHESTRATOR_PROVIDER_API_KEY": SECRET,
        "REVIEW_SCENARIO": scenario,
        "REVIEW_MARKER_DIR": str(root),
    })
    return env


def _alive(pid: int) -> bool:
    """A pid is alive only while it is a live (non-zombie) process."""
    try:
        os.kill(pid, 0)
    except ProcessLookupError:
        return False
    except PermissionError:
        return True
    try:
        with open(f"/proc/{pid}/stat") as handle:
            state = handle.read().rsplit(")", 1)[1].split()[0]
    except OSError:
        return False
    return state not in ("Z", "X", "x")


def _kill(pid: int) -> None:
    with contextlib.suppress(ProcessLookupError, PermissionError):
        os.kill(pid, 9)


def _wait_for(path: Path, timeout: float = 30.0) -> None:
    deadline = time.monotonic() + timeout
    while not path.exists():
        assert time.monotonic() < deadline, f"the fixture never wrote {path.name}"
        time.sleep(0.02)


def test_the_group_kill_reaches_the_grandchild_before_the_supervisor_exits(tmp_path):
    """The grandchild must be dead a fixed time after the deadline, not
    merely dead once the supervisor has exited (a surviving grandchild
    holds the output pipes open and delays that exit past its own
    sleep, so "dead after the supervisor exits" does not measure the
    kill)."""
    root = _fixture_root(tmp_path)
    started = time.monotonic()
    supervisor = subprocess.Popen(
        [sys.executable, str(SUPERVISOR), "--budget", "2"],
        cwd=str(root),
        env=_env(root, "tree"),
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        text=True,
    )
    grandchild_pid = None
    try:
        _wait_for(tmp_path / "grandchild.json")
        grandchild_pid = json.loads(
            (tmp_path / "grandchild.json").read_text().strip()
        )["pid"]
        # A fixed observation point: the 2s deadline plus slack. The
        # grandchild sleeps 60s, so it is alive here unless the group
        # kill reached it.
        while time.monotonic() - started < 6.5:
            time.sleep(0.05)
        assert not _alive(grandchild_pid), (
            f"grandchild {grandchild_pid} survives the deadline kill: the "
            "expiry kill does not reach the whole process group"
        )
        lines = [
            line for line in supervisor.stdout.read().splitlines() if line.strip()
        ] if supervisor.poll() is not None else []
        assert lines == [] or len(lines) == 1, lines
    finally:
        if supervisor.poll() is None:
            supervisor.kill()
        if grandchild_pid is not None:
            _kill(grandchild_pid)
        try:
            supervisor.communicate(timeout=30)
        except subprocess.TimeoutExpired:
            supervisor.kill()
            supervisor.communicate(timeout=30)


def test_the_child_head_receives_the_whole_environment_and_runs_once(tmp_path):
    """The ``--json`` head runs exactly once and receives every
    ``ORCHESTRATOR_*`` variable unchanged — the supervisor adds none and
    redacts none, the provider credential included — on the clean face
    and on the controller-death face alike."""
    for scenario, expected_exit in (("clean", 0), ("lost", 3)):
        root = _fixture_root(tmp_path / scenario)
        completed = subprocess.run(
            [sys.executable, str(SUPERVISOR), "--budget", "60"],
            cwd=str(root),
            env=_env(root, "clean" if scenario == "clean" else "lost"),
            capture_output=True,
            text=True,
            timeout=120,
        )
        assert completed.returncode == expected_exit, (
            scenario, completed.returncode, completed.stderr
        )
        launches = [
            json.loads(line)
            for line in (root / "child-launches.jsonl").read_text().splitlines()
            if line.strip()
        ]
        assert len(launches) == 1, (scenario, launches)  # exactly one child
        assert launches[0]["argv"] == ["--json"], launches[0]["argv"]
        expected = {
            key: value
            for key, value in _env(root, "clean" if scenario == "clean" else "lost").items()
            if key.startswith("ORCHESTRATOR_")
        }
        assert launches[0]["env"] == expected, (
            f"the child's environment is not the supervisor's on the {scenario} "
            "face: the run's ORCHESTRATOR_* set must reach the child unchanged"
        )
        assert SECRET not in completed.stdout, scenario
        assert SECRET not in completed.stderr, scenario
        document = json.loads(
            [ln for ln in completed.stdout.splitlines() if ln.strip()][0]
        )
        if scenario == "clean":
            assert document["recovered"] is False, document
            assert not (root / "resume.jsonl").exists()
        else:
            assert document["recovered"] is True, document
            resumes = [
                json.loads(line)
                for line in (root / "resume.jsonl").read_text().splitlines()
                if line.strip()
            ]
            assert [r["argv"] for r in resumes] == [["--resume"]], resumes
