mirror of
https://github.com/pewdiepie-archdaemon/odysseus.git
synced 2026-10-09 08:22:19 +02:00
fix(runtime): verify process identity before any teardown signal
A recorded pid is a claim, not a handle. The containment grant store, the background-job store and the Cookbook task list all outlive the process that wrote them — deliberately, so a restart keeps a job and its result — and the kernel reuses pids. Any teardown driven off one of those records can therefore land on a process we never started. ODY-86 was exactly this, and the Cookbook survivor sweep still terminated any process whose full command line matched a tracked one, which is the same mistake spelled differently. Identity is (pid, start token). The token comes from /proc/<pid>/stat on Linux, ps -o lstart= on macOS and the BSDs, and GetProcessTimes on Windows; the kernel will not hand a pid to a process that started earlier, so comparing the token recorded at launch against the token read now answers "is this still ours" without a handle or a supervisor. verify() returns owned, gone, foreign or unverifiable, and only owned permits a signal. Keeping "unverifiable" out of the other two is the point. Process inspection has broken off Linux four times here — ODY-70, -86, -94, -99 — every time because an absent mechanism read as a successful answer. Folding it into "ours" signals strangers; folding it into "gone" abandons live processes. It is a containment failure and every caller treats it as one. Wired into the three places that signal: - containment.release() gates a grant recovered from the durable store, and leaves an in-process teardown alone, where the caller holds the child and no identity question arises. The verdict lands on the record, so "why is this grant still here" is answerable afterwards. - A startup reaper. Nothing read either store before, so a crashed run left every grant permanently active and every job permanently running, and the first thing to touch such a record was a teardown aimed at a reassigned pid. The two stores get opposite treatment: an orphaned grant has no caller left and is torn down, while a detached job is documented to survive a restart and is only corrected, never killed. - The Cookbook sweep takes its ownership from the tmux pane's process tree, captured before the kill destroys the only link between a surviving model server and the session that started it. A process that merely matches the tracked command line is now reported rather than killed: the Cookbook composed that command line, so an identical one is just as likely to be a server the user started by hand. The sweep also runs on hosts with no procfs instead of silently skipping, and says so when it could not look at all.
This commit is contained in:
@@ -1,13 +1,26 @@
|
||||
"""Stopping a Cookbook server must succeed on a host with no procfs.
|
||||
"""Stopping a Cookbook server, on a host with procfs and on one without.
|
||||
|
||||
The tmux kill is what actually stops the server; the pid sweep that follows
|
||||
it only catches model servers that survive the session's SIGHUP. On macOS and
|
||||
Windows there is no ``/proc`` to sweep, and letting that raise turned a
|
||||
successful stop into a reported failure *and* skipped the state write that
|
||||
marks the session stopped for the Cookbook UI.
|
||||
The tmux kill is what actually stops the server; the pid sweep that follows it
|
||||
only catches model servers that survive the session's SIGHUP. Two invariants
|
||||
live here.
|
||||
|
||||
**The stop must not fail because the host cannot be inspected.** Letting a
|
||||
procfs scan raise on macOS turned a successful stop into a reported failure and
|
||||
skipped the state write that marks the session stopped for the Cookbook UI
|
||||
(ODY-94). Skipping the sweep silently fixed the crash and left the other half:
|
||||
the stop then claimed success without having looked at all. So the sweep now
|
||||
runs through ``ps`` where there is no procfs, and says so when it cannot look.
|
||||
|
||||
**The sweep signals only processes the session owns.** It used to kill anything
|
||||
whose full command line matched the tracked one. The Cookbook composed that
|
||||
command line, so an identical one is just as likely to be a server the user
|
||||
started by hand — killing it is indistinguishable from killing ours, which is
|
||||
the "stop only what we started" failure. Ownership now comes from the tmux
|
||||
pane's process tree, captured before the kill; a lookalike is reported instead.
|
||||
"""
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import signal
|
||||
|
||||
import pytest
|
||||
@@ -67,20 +80,34 @@ def _install_httpx_client(monkeypatch, state):
|
||||
return posts
|
||||
|
||||
|
||||
def _install_successful_tmux_kill(monkeypatch):
|
||||
"""Replace the real ``tmux kill-session`` with a process that succeeds."""
|
||||
def _install_successful_tmux_kill(monkeypatch, panes=""):
|
||||
"""Fake the two tmux calls a stop makes: list-panes, then kill-session.
|
||||
|
||||
``panes`` is the ``list-panes`` stdout, i.e. ``"<session> <pane_pid>"`` per
|
||||
line — the stop reads it to learn which processes the session owns before
|
||||
the kill destroys that link.
|
||||
"""
|
||||
calls = []
|
||||
|
||||
class FakeProc:
|
||||
returncode = 0
|
||||
|
||||
def __init__(self, stdout=b""):
|
||||
self._stdout = stdout
|
||||
|
||||
async def communicate(self):
|
||||
return b"", b""
|
||||
return self._stdout, b""
|
||||
|
||||
async def fake_exec(*argv, **kwargs):
|
||||
assert argv[:2] == ("tmux", "kill-session")
|
||||
calls.append(argv)
|
||||
assert argv[0] == "tmux"
|
||||
if argv[1] == "list-panes":
|
||||
return FakeProc(panes.encode())
|
||||
assert argv[1] == "kill-session"
|
||||
return FakeProc()
|
||||
|
||||
monkeypatch.setattr(asyncio, "create_subprocess_exec", fake_exec)
|
||||
return calls
|
||||
|
||||
|
||||
def _stopped_statuses(posts, session_id):
|
||||
@@ -92,63 +119,192 @@ def _stopped_statuses(posts, session_id):
|
||||
return out
|
||||
|
||||
|
||||
def _fake_table(monkeypatch, rows):
|
||||
"""Substitute the process table. ``rows`` is {pid: (ppid, command)}.
|
||||
|
||||
Returns the live dict, so a test can model a process actually dying by
|
||||
removing it: ``start_token`` reads from the same dict, and a pid that is no
|
||||
longer in it has no token, which :func:`process_ownership.verify` reports as
|
||||
``GONE``.
|
||||
"""
|
||||
from src import process_ownership
|
||||
|
||||
table = {
|
||||
pid: process_ownership.ProcessInfo(pid=pid, ppid=ppid, command=command)
|
||||
for pid, (ppid, command) in rows.items()
|
||||
}
|
||||
monkeypatch.setattr(process_ownership, "process_table", lambda: dict(table))
|
||||
# Identity is what authorises a signal, so every pid in the fake table has
|
||||
# one. A pid absent from the table has no token and cannot be signalled.
|
||||
monkeypatch.setattr(
|
||||
process_ownership, "start_token",
|
||||
lambda pid: f"token:{pid}" if int(pid or 0) in table else None,
|
||||
)
|
||||
return table
|
||||
|
||||
|
||||
def _install_effective_kill(monkeypatch, table):
|
||||
"""Record signals, and let SIGTERM actually remove the process.
|
||||
|
||||
Keeps the sweep off its escalation path, which would otherwise spend the
|
||||
full SIGTERM grace plus the SIGKILL confirmation window on every pid.
|
||||
"""
|
||||
signalled = []
|
||||
|
||||
def _kill(pid, sig):
|
||||
signalled.append((pid, sig))
|
||||
table.pop(int(pid), None)
|
||||
|
||||
monkeypatch.setattr(os, "kill", _kill)
|
||||
return signalled
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stop_marks_session_stopped_when_the_host_has_no_procfs(
|
||||
monkeypatch, tmp_path
|
||||
):
|
||||
"""The ODY-94 regression: no procfs must not turn a working stop into a failure."""
|
||||
state = _tracked_state()
|
||||
posts = _install_httpx_client(monkeypatch, state)
|
||||
_install_successful_tmux_kill(monkeypatch)
|
||||
_install_successful_tmux_kill(monkeypatch, panes="serve-abc123 900\n")
|
||||
monkeypatch.setattr(platform_compat, "PROC_ROOT", tmp_path / "no-procfs")
|
||||
|
||||
import os
|
||||
|
||||
def _unexpected_listdir(*args, **kwargs):
|
||||
raise AssertionError("the pid sweep must not run without procfs")
|
||||
|
||||
monkeypatch.setattr(os, "listdir", _unexpected_listdir)
|
||||
# ps is the mechanism on a procfs-less host; the sweep goes through it
|
||||
# instead of being skipped.
|
||||
_fake_table(monkeypatch, {900: (1, "bash")})
|
||||
|
||||
result = await tools.do_stop_served_model(
|
||||
json.dumps({"session_id": "serve-abc123"})
|
||||
)
|
||||
|
||||
assert result == {"output": "Stopped server serve-abc123", "exit_code": 0}
|
||||
assert result["exit_code"] == 0
|
||||
assert result["output"].startswith("Stopped server serve-abc123")
|
||||
assert _stopped_statuses(posts, "serve-abc123") == ["stopped"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stop_sweeps_surviving_pids_when_procfs_is_present(
|
||||
async def test_stop_says_so_when_the_session_cannot_be_inspected(
|
||||
monkeypatch, tmp_path
|
||||
):
|
||||
tracked_cmd = "python -m vllm.entrypoints.openai.api_server --model org/model"
|
||||
state = _tracked_state(cmd=tracked_cmd)
|
||||
"""A sweep that could not look must not read as a sweep that found nothing.
|
||||
|
||||
This is the half of ODY-94 that the procfs guard left behind: skipping the
|
||||
sweep stopped the crash and still reported plain success.
|
||||
"""
|
||||
from src import process_ownership
|
||||
|
||||
state = _tracked_state()
|
||||
posts = _install_httpx_client(monkeypatch, state)
|
||||
_install_successful_tmux_kill(monkeypatch)
|
||||
_install_successful_tmux_kill(monkeypatch, panes="serve-abc123 900\n")
|
||||
monkeypatch.setattr(platform_compat, "PROC_ROOT", tmp_path / "no-procfs")
|
||||
|
||||
proc = tmp_path / "proc"
|
||||
def _no_inspection():
|
||||
raise process_ownership.InspectionUnavailable("the process table")
|
||||
|
||||
def _write_pid(pid, cmdline):
|
||||
entry = proc / pid
|
||||
entry.mkdir(parents=True)
|
||||
(entry / "cmdline").write_bytes(cmdline.replace(" ", "\0").encode())
|
||||
|
||||
_write_pid("101", tracked_cmd)
|
||||
_write_pid("202", "python -m http.server")
|
||||
(proc / "self").mkdir()
|
||||
monkeypatch.setattr(platform_compat, "PROC_ROOT", proc)
|
||||
monkeypatch.setattr(process_ownership, "process_table", _no_inspection)
|
||||
|
||||
signalled = []
|
||||
import os
|
||||
|
||||
monkeypatch.setattr(os, "kill", lambda pid, sig: signalled.append((pid, sig)))
|
||||
|
||||
result = await tools.do_stop_served_model(
|
||||
json.dumps({"session_id": "serve-abc123"})
|
||||
)
|
||||
|
||||
assert result["exit_code"] == 0
|
||||
assert "could not identify the session's processes" in result["output"]
|
||||
assert signalled == []
|
||||
assert _stopped_statuses(posts, "serve-abc123") == ["stopped"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stop_kills_the_sessions_own_survivor(monkeypatch, tmp_path):
|
||||
"""A process under the session's pane is ours, so it gets signalled."""
|
||||
tracked_cmd = "python -m vllm.entrypoints.openai.api_server --model org/model"
|
||||
state = _tracked_state(cmd=tracked_cmd)
|
||||
posts = _install_httpx_client(monkeypatch, state)
|
||||
_install_successful_tmux_kill(monkeypatch, panes="serve-abc123 900\n")
|
||||
table = _fake_table(monkeypatch, {
|
||||
900: (1, "bash"), # the pane shell
|
||||
101: (900, tracked_cmd), # the model server it started — ours
|
||||
})
|
||||
signalled = _install_effective_kill(monkeypatch, table)
|
||||
|
||||
result = await tools.do_stop_served_model(
|
||||
json.dumps({"session_id": "serve-abc123"})
|
||||
)
|
||||
|
||||
assert result["exit_code"] == 0
|
||||
assert (101, signal.SIGTERM) in signalled
|
||||
assert "killed 2 surviving process(es)" in result["output"]
|
||||
assert _stopped_statuses(posts, "serve-abc123") == ["stopped"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stop_reports_a_command_line_lookalike_without_signalling_it(
|
||||
monkeypatch, tmp_path
|
||||
):
|
||||
"""The headline change: matching the command line is not owning the process.
|
||||
|
||||
pid 202 runs exactly the tracked command but descends from nothing this
|
||||
session started — a server the user launched by hand looks precisely like
|
||||
this. The old sweep killed it.
|
||||
"""
|
||||
tracked_cmd = "python -m vllm.entrypoints.openai.api_server --model org/model"
|
||||
state = _tracked_state(cmd=tracked_cmd)
|
||||
posts = _install_httpx_client(monkeypatch, state)
|
||||
_install_successful_tmux_kill(monkeypatch, panes="serve-abc123 900\n")
|
||||
table = _fake_table(monkeypatch, {
|
||||
900: (1, "bash"),
|
||||
202: (1, tracked_cmd), # same command, different lineage
|
||||
})
|
||||
signalled = _install_effective_kill(monkeypatch, table)
|
||||
|
||||
result = await tools.do_stop_served_model(
|
||||
json.dumps({"session_id": "serve-abc123"})
|
||||
)
|
||||
|
||||
assert result["exit_code"] == 0
|
||||
assert not any(pid == 202 for pid, _sig in signalled)
|
||||
# Reported rather than silently dropped: the old behaviour acted on this
|
||||
# information, so giving it up entirely would be a regression of its own.
|
||||
assert "202" in result["output"]
|
||||
assert "not signalled" in result["output"]
|
||||
assert _stopped_statuses(posts, "serve-abc123") == ["stopped"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stop_does_not_signal_a_pid_whose_identity_changed(
|
||||
monkeypatch, tmp_path
|
||||
):
|
||||
"""Captured before the kill, recycled before the sweep: do not signal it."""
|
||||
from src import process_ownership
|
||||
|
||||
tracked_cmd = "python -m vllm.entrypoints.openai.api_server --model org/model"
|
||||
state = _tracked_state(cmd=tracked_cmd)
|
||||
posts = _install_httpx_client(monkeypatch, state)
|
||||
_install_successful_tmux_kill(monkeypatch, panes="serve-abc123 900\n")
|
||||
table = _fake_table(monkeypatch, {900: (1, "bash"), 101: (900, tracked_cmd)})
|
||||
|
||||
# pid 101's slot reads differently every time it is asked, so whatever the
|
||||
# capture recorded, the sweep's re-check cannot match it: the pid was
|
||||
# recycled in between. Every other pid keeps a stable identity.
|
||||
drift = {"n": 0}
|
||||
|
||||
def _drifting_token(pid):
|
||||
if int(pid) == 101:
|
||||
drift["n"] += 1
|
||||
return f"token:101:{drift['n']}"
|
||||
return f"token:{pid}" if int(pid or 0) in table else None
|
||||
|
||||
monkeypatch.setattr(process_ownership, "start_token", _drifting_token)
|
||||
signalled = _install_effective_kill(monkeypatch, table)
|
||||
|
||||
result = await tools.do_stop_served_model(
|
||||
json.dumps({"session_id": "serve-abc123"})
|
||||
)
|
||||
|
||||
assert result["exit_code"] == 0
|
||||
# The pane shell is genuinely ours and is signalled; 101 never is.
|
||||
assert not any(pid == 101 for pid, _sig in signalled)
|
||||
assert _stopped_statuses(posts, "serve-abc123") == ["stopped"]
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,412 @@
|
||||
"""Teardown across a restart: the pid in a store is a claim, not a handle.
|
||||
|
||||
Three stores here outlive the process that wrote them, deliberately — a restart
|
||||
is supposed to keep a background job and its result. The consequence nobody had
|
||||
closed is that the recorded pid is reassignable, so a teardown driven off an old
|
||||
record can land on a process the kernel has since given to somebody else. That
|
||||
was ODY-86's shape.
|
||||
|
||||
Covered:
|
||||
|
||||
* :func:`src.containment.release` gating a grant it recovered from the store,
|
||||
and *not* gating one whose process the caller is holding.
|
||||
* :func:`src.containment.reap_record`, the entry point for a reaper that has a
|
||||
row and no grant object.
|
||||
* :mod:`src.process_reaper`, which gives the two stores opposite treatment —
|
||||
orphaned grants are torn down, detached jobs are only corrected.
|
||||
* :func:`src.bg_jobs.disown_unverified`.
|
||||
|
||||
The verdicts come from :mod:`src.process_ownership`, substituted here so each
|
||||
case is driven exactly; that module's own tests pin it against real processes.
|
||||
"""
|
||||
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from src import bg_jobs, containment, process_ownership, process_reaper
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def grant_store(tmp_path, monkeypatch):
|
||||
"""Redirect the containment grant store. Returns a reader for it."""
|
||||
path = tmp_path / "containment_grants.json"
|
||||
monkeypatch.setattr(containment, "_store_path", lambda: path)
|
||||
|
||||
def _read():
|
||||
return json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}
|
||||
|
||||
return _read
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def job_store(tmp_path, monkeypatch):
|
||||
"""Redirect the background-job store and its spool directory."""
|
||||
monkeypatch.setattr(bg_jobs, "_STORE", tmp_path / "bg_jobs.json")
|
||||
monkeypatch.setattr(bg_jobs, "_JOBS_DIR", tmp_path / "bg_jobs")
|
||||
(tmp_path / "bg_jobs").mkdir()
|
||||
|
||||
|
||||
def verdicts(monkeypatch, mapping, default=process_ownership.OWNED):
|
||||
"""Pin verify()'s answer per pid."""
|
||||
monkeypatch.setattr(
|
||||
process_ownership, "verify",
|
||||
lambda pid, _token: mapping.get(int(pid or 0), default),
|
||||
)
|
||||
|
||||
|
||||
def seed_grant(pid=4242, pgid=4242, token="token:4242", **extra):
|
||||
"""Write a grant record the way a previous run would have left it."""
|
||||
record = {
|
||||
"id": "grant-1", "owner": "session-7", "mechanism": "process_group",
|
||||
"mode": containment.CONTAINMENT_MODE, "workspace": "/tmp",
|
||||
"enforced": ["filesystem", "process_tree", "wall_clock"],
|
||||
"degraded": [], "unenforced_required": [],
|
||||
"required": ["filesystem", "process_tree", "wall_clock"],
|
||||
"wall_clock_s": 60, "max_memory_bytes": None, "max_processes": None,
|
||||
"network": "inherit", "external": False, "pid": pid, "pgid": pgid,
|
||||
"start_token": token, "acquired_at": 0.0, "released_at": None, "release": None,
|
||||
}
|
||||
record.update(extra)
|
||||
containment._save_records({record["id"]: record})
|
||||
return record
|
||||
|
||||
|
||||
def seed_job(pid=4242, token="token:4242", status="running", **extra):
|
||||
record = {
|
||||
"id": "job-1", "session_id": "chat-1", "command": "sleep 300",
|
||||
"status": status, "pid": pid, "start_token": token, "started_at": 0.0,
|
||||
"ended_at": None, "exit_code": None, "max_runtime_s": 3600,
|
||||
"followed_up": False, "log_path": "", "exit_path": "",
|
||||
}
|
||||
record.update(extra)
|
||||
bg_jobs._save({record["id"]: record})
|
||||
return record
|
||||
|
||||
|
||||
# ── The gate inside release() ───────────────────────────────────────────────
|
||||
def test_a_recovered_grant_naming_a_recycled_pid_is_not_signalled(
|
||||
grant_store, monkeypatch
|
||||
):
|
||||
"""The headline case. The pid is live, and it is not ours."""
|
||||
seed_grant()
|
||||
verdicts(monkeypatch, {4242: process_ownership.FOREIGN})
|
||||
|
||||
def _no_signals(*_args, **_kwargs):
|
||||
raise AssertionError("a foreign pid must never be signalled")
|
||||
|
||||
monkeypatch.setattr(containment, "_signal_tree", _no_signals)
|
||||
|
||||
outcome = containment.reap_record(grant_store()["grant-1"])
|
||||
|
||||
assert outcome.ownership == process_ownership.FOREIGN
|
||||
assert outcome.dead is False
|
||||
# Not listed as a survivor of *our* grant either: naming a stranger's pid
|
||||
# there invites the next reaper to kill it.
|
||||
assert outcome.survivors == ()
|
||||
|
||||
|
||||
def test_an_unverifiable_grant_is_not_signalled_and_stays_active(
|
||||
grant_store, monkeypatch
|
||||
):
|
||||
"""An inspection mechanism this host does not have is a containment failure.
|
||||
|
||||
Reported as an undead tree and left in the store, so the orphan stays
|
||||
visible in ``active_grants()`` rather than being written off as handled.
|
||||
"""
|
||||
seed_grant()
|
||||
verdicts(monkeypatch, {4242: process_ownership.UNVERIFIABLE})
|
||||
monkeypatch.setattr(
|
||||
containment, "_signal_tree",
|
||||
lambda *_a, **_k: pytest.fail("an unidentified pid must never be signalled"),
|
||||
)
|
||||
|
||||
outcome = containment.reap_record(grant_store()["grant-1"])
|
||||
|
||||
assert outcome.ownership == process_ownership.UNVERIFIABLE
|
||||
assert outcome.dead is False
|
||||
assert containment.active_grants(), "the orphan must remain visible"
|
||||
|
||||
|
||||
def test_a_recovered_grant_whose_process_is_gone_is_released_clean(
|
||||
grant_store, monkeypatch
|
||||
):
|
||||
seed_grant()
|
||||
verdicts(monkeypatch, {4242: process_ownership.GONE})
|
||||
monkeypatch.setattr(containment, "_group_present", lambda _pgid: False)
|
||||
|
||||
outcome = containment.reap_record(grant_store()["grant-1"])
|
||||
|
||||
assert outcome.dead is True
|
||||
assert outcome.ownership == process_ownership.GONE
|
||||
assert containment.active_grants() == []
|
||||
|
||||
|
||||
def test_a_gone_leader_with_a_live_group_is_reported_not_killed(
|
||||
grant_store, monkeypatch
|
||||
):
|
||||
"""Children outlive the leader, but with the leader gone nothing proves the
|
||||
group is still ours — and a recycled group id would mean killpg hits
|
||||
strangers. The orphan is reported instead of guessed at."""
|
||||
seed_grant()
|
||||
verdicts(monkeypatch, {4242: process_ownership.GONE})
|
||||
monkeypatch.setattr(containment, "_group_present", lambda _pgid: True)
|
||||
monkeypatch.setattr(
|
||||
containment, "_signal_tree",
|
||||
lambda *_a, **_k: pytest.fail("an unprovable group must not be signalled"),
|
||||
)
|
||||
|
||||
outcome = containment.reap_record(grant_store()["grant-1"])
|
||||
|
||||
assert outcome.dead is False
|
||||
assert outcome.survivors == (4242,)
|
||||
|
||||
|
||||
def test_a_verified_grant_is_torn_down_normally(grant_store, monkeypatch):
|
||||
seed_grant()
|
||||
verdicts(monkeypatch, {4242: process_ownership.OWNED})
|
||||
signals = []
|
||||
monkeypatch.setattr(
|
||||
containment, "_signal_tree",
|
||||
lambda pid, pgid, sig: signals.append((pid, pgid, sig)),
|
||||
)
|
||||
# Dead on the first probe, so the teardown does not wait out its grace.
|
||||
monkeypatch.setattr(containment, "_tree_gone", lambda *_a, **_k: True)
|
||||
|
||||
outcome = containment.reap_record(grant_store()["grant-1"])
|
||||
|
||||
assert outcome.dead is True
|
||||
assert outcome.ownership == ""
|
||||
|
||||
|
||||
def test_an_in_process_grant_is_not_subjected_to_the_gate(monkeypatch, tmp_path):
|
||||
"""A grant carrying its own pid belongs to the caller holding it.
|
||||
|
||||
The caller launched the child, so there is no identity question — and
|
||||
demanding a token here would refuse teardown of a perfectly ordinary tool
|
||||
call on a host with no inspection mechanism.
|
||||
"""
|
||||
monkeypatch.setattr(containment, "_store_path", lambda: tmp_path / "grants.json")
|
||||
monkeypatch.setattr(
|
||||
process_ownership, "verify",
|
||||
lambda *_a, **_k: pytest.fail("an in-process teardown must not consult ownership"),
|
||||
)
|
||||
spec = containment.ContainmentSpec(
|
||||
workspace=str(tmp_path), env={}, wall_clock_s=5,
|
||||
)
|
||||
grant = containment.ContainmentGrant(
|
||||
id="live-1", mechanism="process_group", workspace=str(tmp_path),
|
||||
enforced=containment.DEFAULT_REQUIRED, degraded=(), unenforced_required=(),
|
||||
owner="session-7", mode=containment.CONTAINMENT_MODE, spec=spec,
|
||||
pid=4242, pgid=4242,
|
||||
)
|
||||
monkeypatch.setattr(containment, "_tree_gone", lambda *_a, **_k: True)
|
||||
monkeypatch.setattr(containment, "_group_present", lambda _pgid: False)
|
||||
|
||||
outcome = containment.release(grant)
|
||||
|
||||
assert outcome.dead is True
|
||||
assert outcome.ownership == ""
|
||||
|
||||
|
||||
def test_the_release_block_names_the_ownership_verdict(grant_store, monkeypatch):
|
||||
"""The verdict reaches the record, so "why is this still here" is answerable."""
|
||||
seed_grant()
|
||||
verdicts(monkeypatch, {4242: process_ownership.FOREIGN})
|
||||
|
||||
outcome = containment.reap_record(grant_store()["grant-1"])
|
||||
|
||||
assert outcome.to_dict()["ownership"] == process_ownership.FOREIGN
|
||||
assert grant_store()["grant-1"]["release"]["ownership"] == process_ownership.FOREIGN
|
||||
|
||||
|
||||
# ── The reaper ──────────────────────────────────────────────────────────────
|
||||
def test_the_reaper_drops_a_foreign_grant_without_signalling_it(
|
||||
grant_store, job_store, monkeypatch
|
||||
):
|
||||
seed_grant()
|
||||
verdicts(monkeypatch, {4242: process_ownership.FOREIGN})
|
||||
monkeypatch.setattr(
|
||||
containment, "_signal_tree",
|
||||
lambda *_a, **_k: pytest.fail("the reaper must not signal a foreign pid"),
|
||||
)
|
||||
|
||||
report = process_reaper.reap_containment_grants()
|
||||
|
||||
assert report["foreign"] == 1
|
||||
# Dropped rather than retried: the only thing left to do with a record
|
||||
# about someone else's process is stop believing it.
|
||||
assert containment.active_grants() == []
|
||||
|
||||
|
||||
def test_the_reaper_keeps_an_unverifiable_grant_visible(
|
||||
grant_store, job_store, monkeypatch
|
||||
):
|
||||
seed_grant()
|
||||
verdicts(monkeypatch, {4242: process_ownership.UNVERIFIABLE})
|
||||
|
||||
report = process_reaper.reap_containment_grants()
|
||||
|
||||
assert report["unverifiable"] == 1
|
||||
assert len(containment.active_grants()) == 1
|
||||
|
||||
|
||||
def test_the_reaper_tears_down_a_verified_orphan(grant_store, job_store, monkeypatch):
|
||||
"""A live process under an abandoned grant has no caller left. It goes."""
|
||||
seed_grant()
|
||||
verdicts(monkeypatch, {4242: process_ownership.OWNED})
|
||||
torn_down = []
|
||||
|
||||
def _reap(record, **_kwargs):
|
||||
torn_down.append(record["id"])
|
||||
return containment.ReleaseOutcome(dead=True, escalated=True, mechanism="process_group")
|
||||
|
||||
monkeypatch.setattr(containment, "reap_record", _reap)
|
||||
|
||||
report = process_reaper.reap_containment_grants()
|
||||
|
||||
assert torn_down == ["grant-1"]
|
||||
assert report["torn_down"] == 1
|
||||
assert containment.active_grants() == []
|
||||
|
||||
|
||||
def test_the_reaper_keeps_a_grant_that_survived_its_teardown(
|
||||
grant_store, job_store, monkeypatch
|
||||
):
|
||||
seed_grant()
|
||||
verdicts(monkeypatch, {4242: process_ownership.OWNED})
|
||||
monkeypatch.setattr(
|
||||
containment, "reap_record",
|
||||
lambda record, **_k: containment.ReleaseOutcome(
|
||||
dead=False, escalated=True, survivors=(4242,), mechanism="process_group",
|
||||
),
|
||||
)
|
||||
|
||||
report = process_reaper.reap_containment_grants()
|
||||
|
||||
assert report["failed"] == 1
|
||||
assert len(containment.active_grants()) == 1
|
||||
|
||||
|
||||
def test_the_reaper_forgets_an_external_grant_without_inspecting_anything(
|
||||
grant_store, job_store, monkeypatch
|
||||
):
|
||||
"""Nothing local ever ran, so there is nothing local to reap."""
|
||||
seed_grant(external=True)
|
||||
monkeypatch.setattr(
|
||||
process_ownership, "verify",
|
||||
lambda *_a, **_k: pytest.fail("an external grant has no local pid to verify"),
|
||||
)
|
||||
|
||||
report = process_reaper.reap_containment_grants()
|
||||
|
||||
assert report["already_gone"] == 1
|
||||
assert containment.active_grants() == []
|
||||
|
||||
|
||||
def test_the_reaper_survives_an_unreadable_store(monkeypatch, job_store):
|
||||
monkeypatch.setattr(
|
||||
containment, "active_grants",
|
||||
lambda: (_ for _ in ()).throw(RuntimeError("store on fire")),
|
||||
)
|
||||
|
||||
assert process_reaper.reap_containment_grants()["seen"] == 0
|
||||
|
||||
|
||||
# ── Background jobs: corrected, never killed ────────────────────────────────
|
||||
def test_a_job_whose_pid_was_reassigned_is_retired_unsignalled(
|
||||
job_store, monkeypatch
|
||||
):
|
||||
"""Left alone, refresh() would SIGKILL this pid at max-runtime.
|
||||
|
||||
An hour after a restart, aimed at whatever now holds it.
|
||||
"""
|
||||
seed_job()
|
||||
verdicts(monkeypatch, {4242: process_ownership.FOREIGN})
|
||||
monkeypatch.setattr(
|
||||
bg_jobs, "_kill",
|
||||
lambda *_a, **_k: pytest.fail("disowning a job must not signal anything"),
|
||||
)
|
||||
|
||||
report = bg_jobs.disown_unverified()
|
||||
|
||||
assert report == {"seen": 1, "retired": 1, "kept": 0}
|
||||
record = bg_jobs._load()["job-1"]
|
||||
assert record["status"] == "failed"
|
||||
assert record["ownership_lost"] == process_ownership.FOREIGN
|
||||
# The agent asked for this job and is still owed an answer.
|
||||
assert record["followed_up"] is False
|
||||
|
||||
|
||||
def test_an_unverifiable_job_is_also_retired(job_store, monkeypatch):
|
||||
"""Fail closed. Retiring loses a result, which is visible; keeping it leaves
|
||||
a pid this server will later signal without knowing what it points at."""
|
||||
seed_job(token=None)
|
||||
verdicts(monkeypatch, {4242: process_ownership.UNVERIFIABLE})
|
||||
|
||||
assert bg_jobs.disown_unverified()["retired"] == 1
|
||||
|
||||
|
||||
def test_a_job_that_is_still_ours_keeps_running(job_store, monkeypatch):
|
||||
"""A detached job is documented to survive a restart. Killing it here would
|
||||
break the feature the store exists for."""
|
||||
seed_job()
|
||||
verdicts(monkeypatch, {4242: process_ownership.OWNED})
|
||||
|
||||
report = bg_jobs.disown_unverified()
|
||||
|
||||
assert report == {"seen": 1, "retired": 0, "kept": 1}
|
||||
assert bg_jobs._load()["job-1"]["status"] == "running"
|
||||
|
||||
|
||||
def test_a_job_whose_process_is_gone_is_left_for_refresh(job_store, monkeypatch):
|
||||
"""refresh() may still find an exit-code file the job wrote before it went,
|
||||
so retiring it here would discard a result that exists."""
|
||||
seed_job()
|
||||
verdicts(monkeypatch, {4242: process_ownership.GONE})
|
||||
|
||||
assert bg_jobs.disown_unverified()["kept"] == 1
|
||||
assert bg_jobs._load()["job-1"]["status"] == "running"
|
||||
|
||||
|
||||
def test_already_finished_jobs_are_not_reconsidered(job_store, monkeypatch):
|
||||
seed_job(status="done")
|
||||
verdicts(monkeypatch, {4242: process_ownership.FOREIGN})
|
||||
|
||||
assert bg_jobs.disown_unverified() == {"seen": 0, "retired": 0, "kept": 0}
|
||||
|
||||
|
||||
def test_a_launched_job_records_an_identity_next_to_its_pid(job_store):
|
||||
"""Without this the record is unverifiable forever and the reaper can only
|
||||
refuse — the token has to be captured at launch or not at all."""
|
||||
record = bg_jobs.launch("true", "chat-1")
|
||||
|
||||
assert "start_token" in record
|
||||
assert process_ownership.verify(record["pid"], record["start_token"]) in (
|
||||
process_ownership.OWNED, process_ownership.GONE,
|
||||
)
|
||||
|
||||
|
||||
def test_an_abandoned_job_says_so_in_its_follow_up(job_store):
|
||||
"""The agent is told the job was lost, not that it failed for its own reasons."""
|
||||
record = seed_job(status="failed", ownership_lost=process_ownership.FOREIGN)
|
||||
|
||||
text = bg_jobs.result_text(record)
|
||||
|
||||
assert "abandoned across a server restart" in text
|
||||
assert "neither waited on nor signalled" in text
|
||||
|
||||
|
||||
def test_reap_orphans_reports_both_stores_and_the_mechanism(
|
||||
grant_store, job_store, monkeypatch
|
||||
):
|
||||
seed_grant()
|
||||
seed_job()
|
||||
verdicts(monkeypatch, {4242: process_ownership.GONE})
|
||||
monkeypatch.setattr(containment, "_group_present", lambda _pgid: False)
|
||||
|
||||
report = process_reaper.reap_orphans()
|
||||
|
||||
assert report["mechanism"] == process_ownership.inspection_mechanism()
|
||||
assert report["grants"]["already_gone"] == 1
|
||||
assert report["bg_jobs"]["kept"] == 1
|
||||
@@ -0,0 +1,327 @@
|
||||
"""Process identity: the four verdicts, and that the fourth is never permissive.
|
||||
|
||||
Split in two. The verdict tests use **real processes**, because the claim under
|
||||
test is about the kernel's behaviour — a pid that has been reaped, a pid that was
|
||||
never issued, a pid whose start time differs from the one recorded — and a fake
|
||||
process table cannot be wrong about that in the same ways. The mechanism tests
|
||||
substitute the inspection layer, so both the procfs branch and the ``ps`` branch
|
||||
are exercised on whichever kind of host happens to be running them.
|
||||
|
||||
The invariant worth most here is negative: :data:`process_ownership.OWNED` is the
|
||||
only verdict that permits a signal, and nothing — a missing token, an absent
|
||||
mechanism, a probe that raised — may produce it by default. Process inspection
|
||||
has broken off Linux four times in this tree (ODY-70, -86, -94, -99), every time
|
||||
because an absent mechanism read as a successful answer.
|
||||
"""
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
|
||||
import pytest
|
||||
|
||||
from core import platform_compat
|
||||
from src import process_ownership as po
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sleeper():
|
||||
"""A real, short-lived child in its own session. Always reaped."""
|
||||
procs = []
|
||||
|
||||
def _spawn(argv=("sleep", "30")):
|
||||
proc = subprocess.Popen(list(argv), start_new_session=True)
|
||||
procs.append(proc)
|
||||
return proc
|
||||
|
||||
yield _spawn
|
||||
for proc in procs:
|
||||
try:
|
||||
proc.kill()
|
||||
proc.wait(timeout=5)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
# ── Verdicts, against real processes ────────────────────────────────────────
|
||||
def test_a_live_process_with_its_own_token_is_owned(sleeper):
|
||||
proc = sleeper()
|
||||
token = po.start_token(proc.pid)
|
||||
|
||||
assert token
|
||||
assert po.verify(proc.pid, token) == po.OWNED
|
||||
|
||||
|
||||
def test_the_same_pid_with_a_different_token_is_foreign(sleeper):
|
||||
"""The whole point: a pid is a slot, and the token says who is in it."""
|
||||
proc = sleeper()
|
||||
token = po.start_token(proc.pid)
|
||||
|
||||
assert po.verify(proc.pid, str(token) + "-not-this-one") == po.FOREIGN
|
||||
|
||||
|
||||
def test_a_reaped_process_is_gone(sleeper):
|
||||
proc = sleeper()
|
||||
token = po.start_token(proc.pid)
|
||||
proc.kill()
|
||||
proc.wait(timeout=5)
|
||||
|
||||
assert po.verify(proc.pid, token) == po.GONE
|
||||
|
||||
|
||||
def test_a_pid_that_was_never_issued_is_gone():
|
||||
# Above any plausible pid_max, so this cannot collide with a real process.
|
||||
assert po.verify(2 ** 30, "token:anything") == po.GONE
|
||||
|
||||
|
||||
def test_a_missing_token_is_unverifiable_and_never_owned(sleeper):
|
||||
"""A record that captured no identity cannot acquire one afterwards.
|
||||
|
||||
This is the pre-upgrade record, and the reason it must not be OWNED is that
|
||||
treating "we did not write it down" as "it is ours" is what makes a recycled
|
||||
pid lethal.
|
||||
"""
|
||||
proc = sleeper()
|
||||
|
||||
assert po.verify(proc.pid, None) == po.UNVERIFIABLE
|
||||
assert po.verify(proc.pid, "") == po.UNVERIFIABLE
|
||||
assert po.UNVERIFIABLE not in po.SIGNALLABLE
|
||||
|
||||
|
||||
def test_only_owned_permits_a_signal():
|
||||
assert po.SIGNALLABLE == frozenset({po.OWNED})
|
||||
|
||||
|
||||
def test_a_falsy_pid_is_gone_rather_than_unverifiable():
|
||||
"""Nothing to identify and nothing to signal; the record is just empty."""
|
||||
assert po.verify(None, "token:x") == po.GONE
|
||||
assert po.verify(0, "token:x") == po.GONE
|
||||
|
||||
|
||||
def test_capture_always_returns_both_fields(sleeper):
|
||||
proc = sleeper()
|
||||
captured = po.capture(proc.pid)
|
||||
|
||||
assert set(captured) == {"pid", "start_token"}
|
||||
assert captured["pid"] == proc.pid
|
||||
assert po.verify(captured["pid"], captured["start_token"]) == po.OWNED
|
||||
|
||||
|
||||
def test_this_process_verifies_as_itself():
|
||||
assert po.verify(os.getpid(), po.start_token(os.getpid())) == po.OWNED
|
||||
|
||||
|
||||
# ── An unavailable mechanism is a failure, not a default ────────────────────
|
||||
def test_no_inspection_mechanism_yields_unverifiable(monkeypatch, sleeper):
|
||||
proc = sleeper()
|
||||
token = po.start_token(proc.pid)
|
||||
monkeypatch.setattr(po, "inspection_mechanism", lambda: po.MECHANISM_NONE)
|
||||
|
||||
# Not GONE (which would abandon a live process) and not OWNED (which would
|
||||
# license a signal at an unidentified one).
|
||||
assert po.verify(proc.pid, token) == po.UNVERIFIABLE
|
||||
|
||||
|
||||
def test_no_mechanism_makes_start_token_raise_rather_than_return_none(monkeypatch):
|
||||
"""None means "no such process". A question we could not ask is not that."""
|
||||
monkeypatch.setattr(po, "inspection_mechanism", lambda: po.MECHANISM_NONE)
|
||||
|
||||
with pytest.raises(po.InspectionUnavailable):
|
||||
po.start_token(os.getpid())
|
||||
|
||||
|
||||
def test_a_probe_that_raises_is_unverifiable_not_owned(monkeypatch, sleeper):
|
||||
proc = sleeper()
|
||||
|
||||
def _broken(_pid):
|
||||
raise po.InspectionUnavailable("deliberately broken probe")
|
||||
|
||||
monkeypatch.setattr(po, "start_token", _broken)
|
||||
|
||||
assert po.verify(proc.pid, "token:whatever") == po.UNVERIFIABLE
|
||||
|
||||
|
||||
def test_capture_records_no_token_rather_than_failing(monkeypatch):
|
||||
"""A host that cannot identify its children must still be able to launch.
|
||||
|
||||
The record then reads UNVERIFIABLE forever, which is the honest outcome:
|
||||
the launch is allowed, and the later teardown refuses.
|
||||
"""
|
||||
monkeypatch.setattr(po, "inspection_mechanism", lambda: po.MECHANISM_NONE)
|
||||
|
||||
captured = po.capture(4242)
|
||||
|
||||
assert captured == {"pid": 4242, "start_token": None}
|
||||
assert po.verify(4242, captured["start_token"]) == po.UNVERIFIABLE
|
||||
|
||||
|
||||
def test_process_table_raises_without_any_mechanism(monkeypatch):
|
||||
monkeypatch.setattr(po, "inspection_mechanism", lambda: po.MECHANISM_NONE)
|
||||
|
||||
with pytest.raises(po.InspectionUnavailable):
|
||||
po.process_table()
|
||||
|
||||
|
||||
def test_the_procfs_table_guards_its_own_scan(monkeypatch, tmp_path):
|
||||
"""Guarded in the function that scans, not only in its caller.
|
||||
|
||||
tests/test_procfs_scan_guard.py pins this structurally; this pins the
|
||||
behaviour, so calling the branch directly on a procfs-less host raises
|
||||
instead of FileNotFoundError.
|
||||
"""
|
||||
monkeypatch.setattr(platform_compat, "PROC_ROOT", tmp_path / "absent")
|
||||
|
||||
with pytest.raises(po.InspectionUnavailable):
|
||||
po._procfs_process_table()
|
||||
|
||||
|
||||
# ── Mechanism selection ─────────────────────────────────────────────────────
|
||||
def test_procfs_is_preferred_where_it_exists(monkeypatch, tmp_path):
|
||||
procfs = tmp_path / "proc"
|
||||
procfs.mkdir()
|
||||
monkeypatch.setattr(platform_compat, "PROC_ROOT", procfs)
|
||||
monkeypatch.setattr(po, "PROC_ROOT", procfs)
|
||||
monkeypatch.setattr(po, "IS_WINDOWS", False)
|
||||
|
||||
assert po.inspection_mechanism() == po.MECHANISM_PROCFS
|
||||
|
||||
|
||||
def test_ps_covers_hosts_with_no_procfs(monkeypatch, tmp_path):
|
||||
"""macOS and the BSDs. The reason this module is not another /proc scan."""
|
||||
monkeypatch.setattr(platform_compat, "PROC_ROOT", tmp_path / "absent")
|
||||
monkeypatch.setattr(po, "IS_WINDOWS", False)
|
||||
monkeypatch.setattr(po.shutil, "which", lambda name: "/bin/ps" if name == "ps" else None)
|
||||
|
||||
assert po.inspection_mechanism() == po.MECHANISM_PS
|
||||
assert po.inspection_available()
|
||||
|
||||
|
||||
def test_a_host_with_neither_reports_none(monkeypatch, tmp_path):
|
||||
monkeypatch.setattr(platform_compat, "PROC_ROOT", tmp_path / "absent")
|
||||
monkeypatch.setattr(po, "IS_WINDOWS", False)
|
||||
monkeypatch.setattr(po.shutil, "which", lambda _name: None)
|
||||
|
||||
assert po.inspection_mechanism() == po.MECHANISM_NONE
|
||||
assert not po.inspection_available()
|
||||
|
||||
|
||||
def test_the_procfs_token_reads_a_comm_containing_spaces_and_parens(monkeypatch, tmp_path):
|
||||
"""``/proc/<pid>/stat`` field 2 is attacker-adjacent: it is the executable name.
|
||||
|
||||
A process called ``my (weird) prog`` would shift every field after it if the
|
||||
parser split on whitespace, which would silently read the wrong number as the
|
||||
start time and make every verdict wrong.
|
||||
"""
|
||||
procfs = tmp_path / "proc"
|
||||
(procfs / "77").mkdir(parents=True)
|
||||
# "77 (comm) S" are fields 1-3, so the filler starts numbering at 4 and
|
||||
# each value equals its own field number.
|
||||
fields = " ".join(str(index) for index in range(4, 54))
|
||||
(procfs / "77" / "stat").write_text(f"77 (my (weird) prog) S {fields}\n")
|
||||
monkeypatch.setattr(platform_compat, "PROC_ROOT", procfs)
|
||||
monkeypatch.setattr(po, "PROC_ROOT", procfs)
|
||||
monkeypatch.setattr(po, "IS_WINDOWS", False)
|
||||
|
||||
assert po.start_token(77) == "procfs:22"
|
||||
|
||||
|
||||
# ── The process tree ────────────────────────────────────────────────────────
|
||||
def test_descendants_walks_a_real_tree(sleeper):
|
||||
"""The grandchild case: a shell that backgrounds work and the work itself."""
|
||||
proc = sleeper(("bash", "-c", "sleep 30 & sleep 30"))
|
||||
# Wait for the shell to have actually forked, without sleeping on a clock:
|
||||
# poll the table until the children appear or the attempts run out.
|
||||
found = []
|
||||
for _attempt in range(100):
|
||||
found = po.descendants([proc.pid])
|
||||
if len(found) >= 3:
|
||||
break
|
||||
|
||||
assert proc.pid in found
|
||||
assert len(found) >= 3, f"expected the shell and its two children, got {found}"
|
||||
|
||||
|
||||
def test_descendants_includes_the_root_even_with_no_children(sleeper):
|
||||
proc = sleeper()
|
||||
|
||||
assert po.descendants([proc.pid]) == [proc.pid]
|
||||
|
||||
|
||||
def test_descendants_takes_a_single_table_snapshot(monkeypatch):
|
||||
"""One table in, one answer out — reparenting cannot hide a process.
|
||||
|
||||
Walking the tree with a fresh query per level lets a child be reparented
|
||||
between queries and drop out of the result, which for a teardown means a
|
||||
process nobody signals.
|
||||
"""
|
||||
rows = {
|
||||
10: po.ProcessInfo(pid=10, ppid=1, command="root"),
|
||||
11: po.ProcessInfo(pid=11, ppid=10, command="child"),
|
||||
12: po.ProcessInfo(pid=12, ppid=11, command="grandchild"),
|
||||
13: po.ProcessInfo(pid=13, ppid=1, command="unrelated"),
|
||||
}
|
||||
|
||||
def _explode():
|
||||
raise AssertionError("descendants must use the table it was given")
|
||||
|
||||
monkeypatch.setattr(po, "process_table", _explode)
|
||||
|
||||
assert po.descendants([10], table=rows) == [10, 11, 12]
|
||||
|
||||
|
||||
def test_descendants_terminates_on_a_parent_cycle():
|
||||
"""A table can report a cycle; the walk must not spin on it."""
|
||||
rows = {
|
||||
20: po.ProcessInfo(pid=20, ppid=21, command="a"),
|
||||
21: po.ProcessInfo(pid=21, ppid=20, command="b"),
|
||||
}
|
||||
|
||||
assert sorted(po.descendants([20], table=rows)) == [20, 21]
|
||||
|
||||
|
||||
def test_the_procfs_table_reads_the_parent_pid(monkeypatch, tmp_path):
|
||||
"""The procfs branch of the tree walk, exercised on a host without procfs.
|
||||
|
||||
macOS runs this suite and takes the ``ps`` branch, so without a substituted
|
||||
``/proc`` the Linux parse — which is what the deployed image uses — would be
|
||||
covered by nothing.
|
||||
"""
|
||||
procfs = tmp_path / "proc"
|
||||
for pid, ppid in ((10, 1), (11, 10)):
|
||||
(procfs / str(pid)).mkdir(parents=True)
|
||||
(procfs / str(pid) / "cmdline").write_bytes(f"proc-{pid}\0--flag\0".encode())
|
||||
filler = " ".join(str(index) for index in range(5, 54))
|
||||
(procfs / str(pid) / "stat").write_text(f"{pid} (proc) S {ppid} {filler}\n")
|
||||
monkeypatch.setattr(platform_compat, "PROC_ROOT", procfs)
|
||||
monkeypatch.setattr(po, "PROC_ROOT", procfs)
|
||||
monkeypatch.setattr(po, "IS_WINDOWS", False)
|
||||
|
||||
table = po.process_table()
|
||||
|
||||
assert table[11].ppid == 10
|
||||
assert table[10].command == "proc-10 --flag"
|
||||
assert po.descendants([10], table=table) == [10, 11]
|
||||
|
||||
|
||||
def test_a_procfs_row_with_an_unreadable_stat_keeps_its_command_line(
|
||||
monkeypatch, tmp_path
|
||||
):
|
||||
"""A kernel thread or a pid that exits mid-walk still matters to a
|
||||
command-line match; dropping the row entirely would hide it."""
|
||||
procfs = tmp_path / "proc"
|
||||
(procfs / "12").mkdir(parents=True)
|
||||
(procfs / "12" / "cmdline").write_bytes(b"orphan-cmd\0")
|
||||
monkeypatch.setattr(platform_compat, "PROC_ROOT", procfs)
|
||||
monkeypatch.setattr(po, "PROC_ROOT", procfs)
|
||||
monkeypatch.setattr(po, "IS_WINDOWS", False)
|
||||
|
||||
table = po.process_table()
|
||||
|
||||
assert table[12].command == "orphan-cmd"
|
||||
assert table[12].ppid == 0
|
||||
|
||||
|
||||
def test_command_lines_sees_this_process():
|
||||
table = po.command_lines()
|
||||
|
||||
assert os.getpid() in table
|
||||
assert table[os.getpid()]
|
||||
Reference in New Issue
Block a user