# SPDX-License-Identifier: AGPL-3.0-or-later
"""Review probe for the phase6 supervisor-boundary step.

Filed by the review at `docs/research/phase6-supervisor-boundary-review-brief.md`.
The shape the delivered module does not build, green at FINAL
`c2186543f356755d2102457b56f0283ffec4e6f0`:

``test_the_deadline_drive_leaves_no_container_leaf`` — a full escaped-forker
deadline drive (the resolved F11 scenario, at the delivered boundary pins'
own ``--budget 0.4``) asserts that the drive's container leaf is gone after
the supervisor exits. The delivered pins hold the kill's liveness (no
recorded PID alive) but nothing holds the cleanup half: the delivered
docstring claims the leaf "is per supervisor process and removed when the
child is done" (`scripts/supervise_run.py:106`-`:107`), and no delivered
pin asserts it. Under a ``_container_close``-leaks mutant driven on a
byte-verified FINAL scratch, both boundary pins stayed green (2 of 2
drives) while four empty leaves of the four drives stood under the
boundary parent — a regression in the removal would go unheld by the
delivered suite. At FINAL the delivered close removed the leaf on every
drive this review measured (leaves remaining: ``[]`` after each). The
clean-child corner (a child exiting 0 while an orphan outlives it) is
``_container_close``'s own documented bounded wait — its leaf is left
standing by construction and is the module docstring's one false case.

Skip discipline is the delivered pins' pattern, decided by the
supervisor's own measurement: where no cgroup v2 delegation exists (the
R08 grading sandbox) the leaf cannot exist, so the drive is skipped and
the nested gate carries no cost. Unmarked: it runs the supervisor on a
fixture child, not a trial or a sandboxed suite, exactly like the
delivered module's own pins.

This is a review probe, not a delivered pin: it rides green at FINAL (red
only under the leak defect it names) until the delivered module absorbs
the leaf-cleanup pin.
"""

from __future__ import annotations

import glob
import os
import time

import pytest

import supervise_run
import test_phase6_supervisor

LEAF_PREFIX = "orchestrator-supervisor-"


def _boundary_leaves() -> set:
    parent = supervise_run._container_boundary()
    if parent is None:
        return set()
    return {entry for entry in glob.glob(os.path.join(parent, LEAF_PREFIX + "*"))}


def test_the_deadline_drive_leaves_no_container_leaf(tmp_path):
    """The deadline drive's container leaf is removed when the child is
    done: the supervisor's own ``_container_close`` bounded wait (20
    retries, 50ms settle) completes before the exit, so a leaf that still
    stands after a fresh measurement window is a removal defect, not
    asynchronous exit noise. The leaf set is diffed before and after the
    one drive, so concurrent suites' leaves are never this assertion's."""
    if not test_phase6_supervisor._boundary_available():
        pytest.skip("no cgroup v2 delegation here: the leaf cannot exist")
    before = _boundary_leaves()
    completed = test_phase6_supervisor._run_supervisor(tmp_path, "escaped-forker", "0.4")
    assert completed.returncode != 0, completed.stdout + completed.stderr
    document = test_phase6_supervisor._single_document(completed.stdout)
    assert document["timed_out"] is True
    deadline = time.monotonic() + 5.0
    remaining: set = set()
    while time.monotonic() < deadline:
        remaining = _boundary_leaves() - before
        if not remaining:
            break
        time.sleep(0.1)
    assert not remaining, (
        f"leaf(s) left standing after the deadline drive: {sorted(remaining)} "
        "- the delivered docstring's removal claim (`scripts/supervise_run.py:106`-`:107`) "
        "is unheld"
    )
