Files
hyprland-headless-stream-pl…/tests/sessions/unit/test_compositor.py
Hermenix 30f456c07e integrate the session broker: one CLI, a module unit, and a VM check
M0 of the sessions design, wired into the flake and gated by a real check.

What is here now:

- `src/hhstreamd/` — the broker: session registry, lifecycle verbs, process-group
  teardown, app allowlist, audit log, idle reaper on CLOCK_BOOTTIME.
- `src/hhstream_session/` — the CLI handlers, registered into the one front door.
- `src/hhstream/cli.py` — `hhstream status|shot|run|record|session …`, so the
  frame verbs and the session namespace are one binary.
- `nix/module.nix` — `sessions.*` options and the `hhstream-sessions.service`
  unit: the operator's own account (never a service account, because launched
  applications should see that account's home), the compositor's group as a
  supplementary group (without it a launched GUI client cannot open the Wayland
  socket), the generated app allowlist, and `--compositor-runtime-dir` so
  applications are handed the compositor's session rather than the broker's.
- `checks/vm-sessions.nix` — 18 subtests on a real compositor in a VM.

Two bugs found by driving it, both fixed:

- BUG-01: launched applications could not reach the compositor at all — the
  broker spawned them with its own inherited environment, which names the login
  session. `hhstreamd/compositor.py` discovers the socket and builds the child
  environment; a directory with no usable socket is a startup refusal, not a
  warning.
- BUG-02: `kill` refused to signal a live application and said nothing was
  wrong. The identity gate hashed `/proc/<pid>/cmdline`, which every `execve`
  replaces — and on NixOS applications are reached through wrapper scripts that
  do exactly that. The gate now rests on `starttime` (+ boot id, + session id
  where it is immutable) and records command-line drift as evidence of nothing.

KillMode=process is set on the unit on purpose: the default control-group kill
would take the applications down with the broker, which would make adoption and
a broker restart pointless.
2026-10-01 12:23:16 +00:00

415 lines
15 KiB
Python

"""BUG-01: a launched application must be able to reach the compositor.
Every test here fails against the pre-fix daemon, which spawned children with
its own inherited environment — on the target machine the *login* session, with
no compositor listening in it — so every GUI application died within a second of
``start`` and the only symptom was ``state exited`` one command later.
A note on the fixtures: a Wayland socket that is **bound but not listening**
gives ``ECONNREFUSED`` on connect, which is exactly what a socket left behind by
a crashed compositor looks like. A bound *and listening* socket is what a live
one looks like. That is the whole difference between the two helpers below, and
it is why the tests need no compositor.
"""
from __future__ import annotations
import json
import logging
import os
import socket
import stat
import sys
from pathlib import Path
import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from conftest import SUN_PATH_MAX
from hhstreamd import compositor
from hhstreamd.__main__ import (
ENV_COMPOSITOR_RUNTIME_DIR,
build_parser,
main,
resolve_compositor,
)
from hhstreamd.compositor import CompositorError, CompositorSession, CompositorTarget, discover
from hhstreamd.launcher import Launcher
def _bind(directory: Path, name: str, *, listening: bool) -> socket.socket:
path = directory / name
if len(str(path).encode()) > SUN_PATH_MAX:
pytest.skip(f"socket path too long for AF_UNIX: {path}")
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.bind(str(path))
if listening:
sock.listen(4)
return sock
@pytest.fixture
def sockets():
"""Open sockets closed at teardown, so no test leaks a listener."""
opened: list[socket.socket] = []
def make(directory: Path, name: str, *, listening: bool = True) -> Path:
sock = _bind(directory, name, listening=listening)
opened.append(sock)
return directory / name
try:
yield make
finally:
for sock in opened:
sock.close()
# ---------------------------------------------------------------------------
# discovery: the socket's name is found, never assumed
# ---------------------------------------------------------------------------
def test_discovers_wayland_1_not_wayland_0(short_tmpdir, sockets):
"""The target machine's compositor is on ``wayland-1``. Nothing may assume ``-0``."""
sockets(short_tmpdir, "wayland-1")
session = discover(short_tmpdir)
assert session.wayland_display == "wayland-1"
assert session.runtime_dir == short_tmpdir.resolve()
assert session.socket_path == short_tmpdir.resolve() / "wayland-1"
def test_ignores_lock_files_and_other_non_sockets(short_tmpdir, sockets):
"""``wayland-1.lock`` is a regular file libwayland writes beside the socket."""
(short_tmpdir / "wayland-1.lock").write_text("")
(short_tmpdir / "wayland-0").write_text("not a socket") # a leftover regular file
(short_tmpdir / "wayland-9").mkdir() # and a directory named like one
sockets(short_tmpdir, "wayland-1")
assert discover(short_tmpdir).wayland_display == "wayland-1"
def test_candidates_lists_only_sockets(short_tmpdir, sockets):
sockets(short_tmpdir, "wayland-0")
(short_tmpdir / "wayland-0.lock").write_text("")
(short_tmpdir / "bus").write_text("")
assert compositor.candidates(short_tmpdir.resolve()) == ["wayland-0"]
def test_a_live_socket_beats_a_crashed_compositors_leftover(short_tmpdir, sockets):
"""Both are sockets; only one has anything behind it."""
sockets(short_tmpdir, "wayland-1", listening=False) # refuses connections
sockets(short_tmpdir, "wayland-0", listening=True)
assert discover(short_tmpdir).wayland_display == "wayland-0"
def test_among_live_sockets_the_later_name_wins(short_tmpdir, sockets):
"""A compositor takes the first free name, so the survivor of a restart is later."""
sockets(short_tmpdir, "wayland-0")
sockets(short_tmpdir, "wayland-1")
assert discover(short_tmpdir).wayland_display == "wayland-1"
def test_non_numeric_suffix_is_usable_but_ranks_last(short_tmpdir, sockets):
sockets(short_tmpdir, "wayland-hyprland")
assert discover(short_tmpdir).wayland_display == "wayland-hyprland"
# ---------------------------------------------------------------------------
# fail loudly, early, and correctly
# ---------------------------------------------------------------------------
def test_empty_runtime_dir_is_refused_and_named(short_tmpdir):
with pytest.raises(CompositorError) as exc:
discover(short_tmpdir)
message = str(exc.value)
assert str(short_tmpdir.resolve()) in message
assert "no Wayland socket" in message
# It must not be mistaken for the daemon's own --runtime-dir.
assert "--runtime-dir" in message
def test_missing_runtime_dir_is_refused_and_named(short_tmpdir):
missing = short_tmpdir / "nope"
with pytest.raises(CompositorError) as exc:
discover(missing)
assert str(missing) in str(exc.value)
def test_a_file_in_place_of_the_runtime_dir_is_refused(short_tmpdir):
path = short_tmpdir / "file"
path.write_text("")
with pytest.raises(CompositorError) as exc:
discover(path)
assert str(path) in str(exc.value)
def test_only_stale_sockets_is_refused(short_tmpdir, sockets):
"""Accepting work here would kill every application that arrived."""
sockets(short_tmpdir, "wayland-0", listening=False)
sockets(short_tmpdir, "wayland-1", listening=False)
with pytest.raises(CompositorError) as exc:
discover(short_tmpdir)
message = str(exc.value)
assert str(short_tmpdir.resolve()) in message
assert "no usable Wayland socket" in message
assert "wayland-0" in message and "wayland-1" in message
def test_an_unconnectable_but_not_refused_socket_is_used_with_a_warning(
short_tmpdir, sockets, caplog, monkeypatch
):
"""An ambiguous probe (EACCES, a timeout) is a warning, not an outage."""
sockets(short_tmpdir, "wayland-1", listening=False)
def refuse_with_eacces(path):
return compositor._Candidate(Path(path).name, False, False, "PermissionError: denied")
monkeypatch.setattr(compositor, "_probe", refuse_with_eacces)
with caplog.at_level(logging.WARNING, logger="hhstreamd.compositor"):
assert discover(short_tmpdir).wayland_display == "wayland-1"
assert "did not accept a probe connection" in caplog.text
# ---------------------------------------------------------------------------
# the environment a child is given
# ---------------------------------------------------------------------------
def test_session_env_is_the_three_variables():
session = CompositorSession(runtime_dir=Path("/run/user/1001"), wayland_display="wayland-1")
assert session.env() == {
"XDG_RUNTIME_DIR": "/run/user/1001",
"WAYLAND_DISPLAY": "wayland-1",
"XDG_SESSION_TYPE": "wayland",
}
def test_child_env_is_built_from_the_compositor_runtime_dir(short_tmpdir, sockets, tmp_path):
sockets(short_tmpdir, "wayland-1")
launcher = Launcher(
tmp_path / "runtime",
tmp_path / "state",
compositor=CompositorTarget.from_runtime_dir(short_tmpdir),
)
env = launcher.build_env("chromium-uynn6w", tmp_path / "home")
assert env["XDG_RUNTIME_DIR"] == str(short_tmpdir.resolve())
assert env["WAYLAND_DISPLAY"] == "wayland-1"
assert env["XDG_SESSION_TYPE"] == "wayland"
# Not the daemon's own runtime dir, and not the session's private one.
assert env["XDG_RUNTIME_DIR"] != str(launcher.session_runtime_dir("chromium-uynn6w"))
# The private directory is still created: the daemon owns and cleans it up.
assert launcher.session_runtime_dir("chromium-uynn6w").is_dir()
def test_child_env_keeps_the_inherited_environment_underneath(
short_tmpdir, sockets, tmp_path, monkeypatch
):
sockets(short_tmpdir, "wayland-1")
monkeypatch.setenv("PATH", "/usr/bin")
monkeypatch.setenv("DBUS_SESSION_BUS_ADDRESS", "unix:path=/run/user/1000/bus")
launcher = Launcher(
tmp_path / "runtime",
tmp_path / "state",
compositor=CompositorTarget.from_runtime_dir(short_tmpdir),
)
env = launcher.build_env("s", tmp_path / "home")
assert env["PATH"] == "/usr/bin"
assert env["DBUS_SESSION_BUS_ADDRESS"] == "unix:path=/run/user/1000/bus"
assert env["HOME"] == str(tmp_path / "home")
assert env["HHSTREAM_SESSION_ID"] == "s"
def test_the_daemons_own_configuration_never_leaks_to_a_child(tmp_path, monkeypatch):
monkeypatch.setenv(ENV_COMPOSITOR_RUNTIME_DIR, "/run/user/1001")
env = Launcher(tmp_path / "runtime", tmp_path / "state").build_env("s", tmp_path)
assert ENV_COMPOSITOR_RUNTIME_DIR not in env
def test_without_a_compositor_the_inherited_environment_still_stands(tmp_path, monkeypatch):
"""Point 4 of the brief: the old behaviour is kept, not broken."""
monkeypatch.setenv("WAYLAND_DISPLAY", "wayland-7")
monkeypatch.delenv("XDG_SESSION_TYPE", raising=False)
launcher = Launcher(tmp_path / "runtime", tmp_path / "state")
env = launcher.build_env("s", tmp_path / "home")
assert env["XDG_RUNTIME_DIR"] == str(launcher.session_runtime_dir("s"))
assert env["WAYLAND_DISPLAY"] == "wayland-7" # passed through, not invented
assert "XDG_SESSION_TYPE" not in env
def test_the_recorded_runtime_dir_stays_the_one_the_daemon_may_delete(
short_tmpdir, sockets, tmp_path
):
"""``discard_runtime_dir`` must never be pointed at another user's directory."""
sockets(short_tmpdir, "wayland-1")
launcher = Launcher(
tmp_path / "runtime",
tmp_path / "state",
compositor=CompositorTarget.from_runtime_dir(short_tmpdir),
)
spawned = launcher.spawn("s", [sys.executable, "-c", "pass"])
spawned.process.wait(timeout=10)
assert spawned.runtime_dir == str(launcher.session_runtime_dir("s"))
assert spawned.runtime_dir != str(short_tmpdir.resolve())
def test_a_real_child_sees_the_compositor_environment(short_tmpdir, sockets, tmp_path):
"""The end of the chain: what the process actually gets after exec."""
sockets(short_tmpdir, "wayland-1")
launcher = Launcher(
tmp_path / "runtime",
tmp_path / "state",
compositor=CompositorTarget.from_runtime_dir(short_tmpdir),
)
code = (
"import json, os, sys; "
"sys.stdout.write(json.dumps({k: os.environ.get(k) for k in "
"('XDG_RUNTIME_DIR', 'WAYLAND_DISPLAY', 'XDG_SESSION_TYPE')}))"
)
spawned = launcher.spawn("s", [sys.executable, "-c", code])
assert spawned.process.wait(timeout=30) == 0
seen = json.loads(Path(spawned.log_path).read_text())
assert seen == {
"XDG_RUNTIME_DIR": str(short_tmpdir.resolve()),
"WAYLAND_DISPLAY": "wayland-1",
"XDG_SESSION_TYPE": "wayland",
}
# And the socket it was pointed at is really there.
assert stat.S_ISSOCK(os.stat(short_tmpdir / seen["WAYLAND_DISPLAY"]).st_mode)
# ---------------------------------------------------------------------------
# re-resolution: the compositor can restart under a running daemon
# ---------------------------------------------------------------------------
def test_target_follows_a_compositor_that_came_back_on_another_socket(short_tmpdir, sockets):
first = sockets(short_tmpdir, "wayland-0")
target = CompositorTarget.from_runtime_dir(short_tmpdir)
assert target.session.wayland_display == "wayland-0"
sockets(short_tmpdir, "wayland-1") # restarted compositor, new name
first.unlink() # the old socket file went with the old compositor
assert target.env()["WAYLAND_DISPLAY"] == "wayland-1"
assert target.session.wayland_display == "wayland-1"
def test_target_keeps_the_last_known_good_when_re_resolution_fails(short_tmpdir, sockets, caplog):
sockets(short_tmpdir, "wayland-1")
target = CompositorTarget.from_runtime_dir(short_tmpdir)
(short_tmpdir / "wayland-1").unlink() # compositor gone, mid-flight
with caplog.at_level(logging.WARNING, logger="hhstreamd.compositor"):
env = target.env()
assert env["WAYLAND_DISPLAY"] == "wayland-1"
assert "re-resolving the compositor socket failed" in caplog.text
# ---------------------------------------------------------------------------
# the daemon's startup contract
# ---------------------------------------------------------------------------
def _args(argv: list[str]):
return build_parser().parse_args(argv)
def test_the_option_and_the_environment_variable_are_both_accepted(monkeypatch):
monkeypatch.setenv(ENV_COMPOSITOR_RUNTIME_DIR, "/from/env")
assert _args([]).compositor_runtime_dir == "/from/env"
assert _args(["--compositor-runtime-dir", "/from/flag"]).compositor_runtime_dir == "/from/flag"
def test_no_option_means_no_compositor_and_a_startup_warning(monkeypatch, caplog):
monkeypatch.delenv(ENV_COMPOSITOR_RUNTIME_DIR, raising=False)
with caplog.at_level(logging.WARNING, logger="hhstreamd"):
assert resolve_compositor(_args([])) is None
assert "may not be able to reach a compositor" in caplog.text
assert "--compositor-runtime-dir" in caplog.text
def test_resolve_compositor_returns_a_target_when_the_socket_is_there(short_tmpdir, sockets):
sockets(short_tmpdir, "wayland-1")
target = resolve_compositor(_args(["--compositor-runtime-dir", str(short_tmpdir)]))
assert target is not None
assert target.session.wayland_display == "wayland-1"
def test_daemon_refuses_to_start_on_an_unusable_compositor_dir(short_tmpdir, capsys, monkeypatch):
"""Exit before listening, with the directory in the message."""
monkeypatch.delenv(ENV_COMPOSITOR_RUNTIME_DIR, raising=False)
code = main(
[
"--check",
"--socket",
str(short_tmpdir / "c.sock"),
"--state-dir",
str(short_tmpdir / "state"),
"--runtime-dir",
str(short_tmpdir / "runtime"),
"--config",
str(short_tmpdir / "missing.toml"),
"--compositor-runtime-dir",
str(short_tmpdir),
]
)
assert code == 2
err = capsys.readouterr().err
assert str(short_tmpdir.resolve()) in err
assert "no Wayland socket" in err
def test_check_reports_the_discovered_compositor(short_tmpdir, sockets, capsys, monkeypatch):
monkeypatch.delenv(ENV_COMPOSITOR_RUNTIME_DIR, raising=False)
runtime = short_tmpdir / "comp"
runtime.mkdir()
sockets(runtime, "wayland-1")
code = main(
[
"--check",
"--state-dir",
str(short_tmpdir / "state"),
"--runtime-dir",
str(short_tmpdir / "runtime"),
"--config",
str(short_tmpdir / "missing.toml"),
"--compositor-runtime-dir",
str(runtime),
]
)
assert code == 0
out = capsys.readouterr().out
assert f"compositor: {runtime.resolve()}" in out
assert "WAYLAND_DISPLAY=wayland-1" in out
def test_check_says_so_when_no_compositor_is_configured(short_tmpdir, capsys, monkeypatch):
monkeypatch.delenv(ENV_COMPOSITOR_RUNTIME_DIR, raising=False)
code = main(
[
"--check",
"--state-dir",
str(short_tmpdir / "state"),
"--runtime-dir",
str(short_tmpdir / "runtime"),
"--config",
str(short_tmpdir / "missing.toml"),
]
)
assert code == 0
assert "compositor: none configured" in capsys.readouterr().out