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

Filed by the review at `docs/research/phase6-sandbox-sweep-review-brief.md`.
Its original over-match shape was absorbed by the scoping delivered under
`docs/research/phase6-probe-scope-brief.md`, and the probe was repointed here at
the scoped surface (the docstring's second named disposition).

``test_the_probe_pid_scan_does_not_count_an_unrelated_argv_carrier`` holds the
absorbed F24's live measure. The batch3 module's ``_probe_pids`` once scanned
the whole process table for any command line carrying the literal probe path, so
an unrelated process that merely carried that string in argv was counted a
survivor. Measured by hand during that review: with a literal-retaining
``bash -c`` wrapper alive, the F1 escape pin failed its survivor assertion on
the carrier's pid (``escaped workload survived teardown: [<carrier>]``), and the
same wrapper vanished when its form exec'd the command in place — the class
needs a process that retains the literal, not merely a command line that briefly
formed one. The scoping counts a pid only where its command line names the
workload's own executor invocation (the plan's ``/usr/bin/python3
/work/probe.py`` argv pair), so this probe asserts the inverse of what it once
asserted: the carrier alive, and the scoped scan empty of it. Repointed because
the first run after the scoping reddened on the old assertion (``1 failed in
0.29s``, ``assert carrier.pid in found`` firing against an empty scan over the
live carrier) — that red was the absorption signal this docstring's first
version named. The workload-survivor half of the shape rides the F1/F20 pins in
`tests/test_batch3_execution.py`, unchanged by the scoping.

The module carries ``pytestmark = pytest.mark.slow``: the module is a
whole-host-table measure, and the oracle's own floor snapshots copy the dirty
working tree into every graded candidate — an unmarked module here joins the
inner deterministic suite and breaks the seeded-determinism pin (measured
during the filing review: three red determinism re-drives, all of them this
file's own artifact: inside the R08 grading sandbox the carrier's exec fails at
the fresh root's minimal toolchain view and reads back an empty zombie
``cmdline``). The slow mark removes the module from ``-m "not slow"`` suites
everywhere, and the body below never reds on a context whose carrier cannot
survive spawn: it waits for a nonempty cmdline, retries the spawn once, and
skips if the carrier still cannot hold the literal (the guard skips anywhere
without cgroup2 visible, which is every R08-type fresh root).
"""

import contextlib
import os
import subprocess
import time

import pytest

from test_batch3_execution import _probe_pids

pytestmark = pytest.mark.slow


def test_the_probe_pid_scan_does_not_count_an_unrelated_argv_carrier():
    """F24: the workload-surface scan does not count an unrelated
    literal-retaining carrier as a survivor of a teardown that never ran."""
    if not os.path.exists("/sys/fs/cgroup/cgroup.controllers"):
        pytest.skip("no cgroup2 visible here (an R08-type fresh root): the whole-table measure is host-side only")
    carrier_cmd = "sleep 20; true # teardown sweep quoting the module's path /work/probe" + ".py"
    carrier: subprocess.Popen | None = None
    try:
        last = ""
        for _attempt in range(2):
            if carrier is not None:
                with contextlib.suppress(OSError):
                    carrier.kill()
                carrier.poll()
            carrier = subprocess.Popen(["bash", "-c", carrier_cmd], start_new_session=True)
            # A carrier can die before its exec lands (a context whose /bin
            # view is minimal leaves an exec-failed zombie at the pid); wait
            # for a nonempty cmdline before trusting the literal check.
            last = ""
            for _ in range(20):
                try:
                    with open(f"/proc/{carrier.pid}/cmdline", "rb") as handle:
                        last = handle.read().replace(b"\0", b" ").decode(errors="replace")
                except OSError:
                    last = ""
                if last:
                    break
                time.sleep(0.1)
            if "/work/probe" + ".py" in last:
                break
        assert "/work/probe" + ".py" in last, (
            f"the carrier never retained the probe path literal in this context: {last!r}"
        )
        assert carrier is not None and carrier.poll() is None, (
            "the carrier died before the scan measured it"
        )
        found = _probe_pids()
        assert carrier.pid not in found, (
            f"the scoped scan counted an unrelated argv carrier: {found}"
        )
    finally:
        if carrier is not None:
            if carrier.poll() is None:
                with contextlib.suppress(OSError):
                    carrier.kill()
            carrier.wait()
