Files
hyprland-headless-stream-pl…/tests/sessions/integration/test_containers.py
T
HermenixandClaude Opus 5 129430bffd wire the broker to the compositor, containers and pointer
The four slices existed and nothing called them. Now the broker builds a
spatial container per session, reads back what the compositor actually did,
and aims the cursor into one container under a broker-wide lease.

Record schema 3 (registry.py): `container` {output, workspace, mode,
created_by, state}, `pointer` {bookmark, last_released_at, released_by} and
the compositor's `signature`. A v2 record is migrated on load, not refused —
its application is still running. Every field that could not be verified is
null; `container: null` means "no container", never "probably something".

Containers (new container_host.py, manager.py, launcher.py): `start`
allocates a slot from `WorkspaceAllocator`, runs `container_plan()`'s argv,
launches the app with the container stamp in its environment, then reads the
workspace, output and window back out of `clients -j`. Teardown removes the
output, releases the slot and reports survivors rather than claiming success
— and runs for an unprompted exit and for `gc` too, so no container is ever
left unattended. Broker start-up reconciles: adopt `hh-*` outputs a live
session claims, remove the rest, `contains_output()` being the only filter.
No IPC means `container: degraded` and lifecycle verbs unchanged.

The plans' argv are dispatched over the compositor's request socket rather
than by executing `hyprctl`, which is what hyprctl does with the same words;
the reply is checked, so a refused command is not recorded as a container.

Pointer (new driver.py, manager.py): a client for the driver's private
socket, and `pointer.acquire|move|button|click|release|state` on top of
`PointerLease`. The broker owns the lease, the driver executes. The bookmark
is marked on every move and before release and stored in the record, so it
survives a restart. On expiry `pressed()` is read before `expire()` and
`release_all` goes to the driver, because the lease cannot lift a button
itself; a sweep runs unprompted so the TTL is a promise.

containers.py to v2: `quarantine_plan()` -> `quarantine_argv()`, with the
before-any-per-session-rule ordering stated where the caller could get it
wrong. protocol.py: 9 NO_LEASE, 10 COMPOSITOR, the verb table, and the
`request_id` cache moved out of the server so the CLI agrees with it.

Tests: real AF_UNIX everywhere — a stateful fake compositor and the shipped
pointer driver behind a recording sink. No mocked sockets, no compositor, no
VM. 551 -> 693.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017mUq7QvQ9EZb2Wi35xj4cs
2026-10-02 19:47:33 +00:00

601 lines
23 KiB
Python

"""Integration: a real daemon, a real control socket, a container and a cursor.
Everything the broker talks to is a real socket in this test. The daemon is
``python -m hhstreamd`` in a subprocess; the compositor is an ``AF_UNIX``
listener laid out the way Hyprland lays one out, answering the commands
Hyprland answers; the pointer driver is the shipped driver with its Wayland
sink replaced by a recorder. No compositor, no VM, no GUI application, no
network.
**What this proves, and what it cannot.** It proves the broker's half: that
the plan's commands go out in the plan's order, that the record is built from
what came back rather than from what was asked for, that a container is taken
down with its session and an unattended one is taken down at start-up, and
that the cursor is leased, bookmarked and never left with a button down. It
proves nothing about whether Hyprland agrees — ``output create headless`` is
marked unverified in the plan, and this fake says ``ok`` because it was asked
politely. The slice report lists what still needs a real compositor.
"""
from __future__ import annotations
import json
import os
import signal
import sys
from pathlib import Path
import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from conftest import socket_path, wait_until
from fakes import WINDOW_PID, FakeCompositor, FakeDriver
from hhstreamd.protocol import ExitCode
# The lifecycle test owns the daemon harness; reusing it is what keeps the two
# files describing the *same* daemon rather than two subtly different ones.
from test_lifecycle import Daemon, compositor_dir, start
class Rig:
"""A daemon with a compositor and a driver behind it."""
def __init__(self, root: Path, *, with_compositor: bool = True, with_driver: bool = True):
self.root = root
# The daemon refuses to start without a Wayland socket to hand its
# children, so the compositor's runtime directory holds both: the
# `wayland-N` an application connects to and the `hypr/<sig>/` the
# broker queries. That is the real layout of /run/hypr-stream.
self.comp_dir, self._wayland = compositor_dir(root)
self.compositor = FakeCompositor(self.comp_dir) if with_compositor else None
runtime = root / "run"
runtime.mkdir(parents=True, exist_ok=True)
socket_path(runtime, "pointer.sock")
self.driver = FakeDriver(runtime / "pointer.sock") if with_driver else None
self.daemon = Daemon(root, "--compositor-runtime-dir", str(self.comp_dir))
if self.compositor is not None:
# As a deployment does: the instance is named, not guessed at.
self.daemon.env["HYPRLAND_INSTANCE_SIGNATURE"] = self.compositor.signature
def start(self) -> None:
self.daemon.start()
def stop(self) -> None:
self.daemon.stop()
if self.driver is not None:
self.driver.stop()
if self.compositor is not None:
self.compositor.stop()
self._wayland.close()
# -- convenience ------------------------------------------------------
def plan_commands(self) -> list[str]:
"""What the compositor was told to do, queries filtered out."""
assert self.compositor is not None
return [
c
for c in self.compositor.commands
if not c.startswith(("version", "clients", "monitors", "workspaces", "cursorpos"))
]
def make_rig(root: Path, **kwargs) -> Rig:
rig = Rig(root, **kwargs)
rig.start()
return rig
@pytest.fixture
def rig(short_tmpdir: Path):
r = make_rig(short_tmpdir)
try:
yield r
finally:
_kill_everything(r.daemon)
r.stop()
def _kill_everything(daemon: Daemon) -> None:
try:
for session in daemon.call("list", all=True).get("sessions", []):
if session.get("live"):
try:
daemon.call("kill", id=session["id"], grace_s=0)
except Exception:
pass
except Exception:
pass
# ===========================================================================
# the container, start to finish
# ===========================================================================
def test_a_started_session_gets_an_output_a_workspace_and_a_window(rig: Rig):
session_id = start(rig.daemon, "sleeper")
record = rig.daemon.session(session_id)
container = record["container"]
assert container["output"] == f"hh-{session_id}"
assert container["workspace"] == 1000
assert container["mode"] == {"width": 1280, "height": 720}
assert container["created_by"] == "broker"
assert container["state"] == "owned"
# The signature, so a restarted broker re-attaches to this instance.
assert record["signature"] == rig.compositor.signature
# And the compositor really has it.
assert f"hh-{session_id}" in rig.compositor.outputs()
assert rig.compositor.workspaces_on(f"hh-{session_id}") == [1000]
def test_the_spatial_fields_come_from_the_compositor_not_from_our_intention(rig: Rig):
"""The read-back is the point: a record that echoed the plan back would
look identical whether or not the window rule ever bound."""
session_id = start(rig.daemon, "sleeper")
record = rig.daemon.session(session_id)
assert record["workspace"] == 1000
# The fake gives every window it conjures a pid of its own, which is not
# the session's — so a record carrying it can only have come from
# `clients -j`.
assert record["window"]["stable_id"] == f"hh-{session_id}:{WINDOW_PID}"
assert record["window"]["initial_class"] == f"hh-{session_id}"
assert record["pid"] != WINDOW_PID
assert record["foreground"] is True
# And `status` says where all of that came from.
assert record["compositor"]["ipc"] == "ok"
assert record["compositor"]["signature"] == rig.compositor.signature
assert record["compositor"]["error"] is None
def test_the_plan_runs_in_order_with_the_quarantine_backstop_first(rig: Rig):
session_id = start(rig.daemon, "sleeper")
assert rig.plan_commands() == [
# Installed at start-up, before any container exists: it matches every
# class, and a catch-all declared after an anchored rule overrides it.
"keyword windowrule match:initial_class .*, workspace special:quarantine",
f"output create headless hh-{session_id}",
f"keyword workspace 1000, monitor:hh-{session_id}, default:true, persistent:true",
f"keyword windowrule match:initial_class ^hh-{session_id}$, workspace 1000, "
f"monitor hh-{session_id}",
f"keyword monitor hh-{session_id},1280x720,auto,1",
]
def test_the_application_is_launched_with_the_container_stamp(rig: Rig):
"""The class the window rule matches reaches the app in its environment.
The environment is the only lever the launcher has: a per-app
``--app-id``/``--class`` flag would have to come from the allowlist, and
the allowlist is not this slice's file. A toolkit that reads none of
these keeps its own class — which the read-back is there to catch.
"""
session_id = start(rig.daemon, "idump")
lines = wait_until(
lambda: rig.daemon.call("logs", id=session_id).get("lines"),
timeout=10.0,
what="the app to report its environment",
)
assert json.loads(lines[0]) == {
"HHSTREAM_APP_ID": f"hh-{session_id}",
"SDL_VIDEO_WAYLAND_WMCLASS": f"hh-{session_id}",
"RESOURCE_NAME": f"hh-{session_id}",
}
# And the rule the compositor was given matches exactly that class.
assert rig.compositor.rules[f"hh-{session_id}"] == (1000, f"hh-{session_id}")
def test_killing_a_session_removes_its_output_and_reports_no_survivors(rig: Rig):
session_id = start(rig.daemon, "sleeper")
assert f"hh-{session_id}" in rig.compositor.outputs()
reply = rig.daemon.call("kill", id=session_id, grace_s=0)
assert reply["ok"], reply
# Teardown facts ride with the record, where `survivors` already does and
# where the CLI reads them from.
record = reply["session"]
assert record["container_removed"] is True
assert record["container_survivors"] == []
assert record["container"]["state"] == "removed"
assert f"hh-{session_id}" not in rig.compositor.outputs()
assert f"output remove hh-{session_id}" in rig.plan_commands()
def test_a_window_that_outlives_the_teardown_is_reported_not_hidden(rig: Rig):
"""Two sources have to agree before a teardown is called a success."""
session_id = start(rig.daemon, "sleeper")
# A second window of ours that landed outside the container, so removing
# the output does not take it with it.
rig.compositor.add_window(f"hh-{session_id}", 1, "HEADLESS-1", pid=999)
reply = rig.daemon.call("kill", id=session_id, grace_s=0)
assert [s["pid"] for s in reply["session"]["container_survivors"]] == [999]
def test_the_workspace_slot_comes_back_when_the_session_does_not(rig: Rig):
first = start(rig.daemon, "sleeper")
assert rig.daemon.session(first)["container"]["workspace"] == 1000
rig.daemon.call("kill", id=first, grace_s=0)
second = start(rig.daemon, "sleeper")
assert rig.daemon.session(second)["container"]["workspace"] == 1000, "the slot was reused"
def test_two_sessions_get_different_outputs_and_different_workspaces(rig: Rig):
first = start(rig.daemon, "sleeper")
second = start(rig.daemon, "sleeper")
a = rig.daemon.session(first)["container"]
b = rig.daemon.session(second)["container"]
assert a["output"] != b["output"]
assert {a["workspace"], b["workspace"]} == {1000, 1001}
assert sorted(rig.compositor.outputs()) == sorted(
["HEADLESS-1", a["output"], b["output"]]
)
def test_container_list_reports_the_containers_and_the_orphans(rig: Rig):
session_id = start(rig.daemon, "sleeper")
rig.compositor.add_output("hh-ghost-aaaaaa")
reply = rig.daemon.call("container.list")
assert reply["ok"], reply
assert [row["id"] for row in reply["containers"]] == [session_id]
assert reply["orphans"] == ["hh-ghost-aaaaaa"]
assert reply["workspaces_in_use"] == [1000]
# Listing is not acting.
assert "hh-ghost-aaaaaa" in rig.compositor.outputs()
def test_container_reconcile_reports_the_difference_it_repaired(rig: Rig):
session_id = start(rig.daemon, "sleeper")
# The window goes away under the broker, as a crashed application's would.
rig.compositor._clients.clear()
reply = rig.daemon.call("container.reconcile", id=session_id)
assert reply["ok"], reply
fields = {d["field"]: d for d in reply["diff"]}
assert fields["window"]["observed"] is None
assert fields["window"]["recorded"]["initial_class"] == f"hh-{session_id}"
assert rig.daemon.session(session_id)["window"] is None
# ===========================================================================
# the start-up scan
# ===========================================================================
def test_an_unattended_output_is_removed_when_the_broker_starts(short_tmpdir: Path):
"""A container must never be left running with nobody to own it."""
rig = make_rig(short_tmpdir)
try:
rig.daemon.stop()
rig.compositor.add_output("hh-leftover-aaaaaa")
rig.compositor.add_output("DP-9") # not ours, and must survive
rig.daemon.start()
assert "hh-leftover-aaaaaa" not in rig.compositor.outputs()
assert "DP-9" in rig.compositor.outputs()
assert "output remove hh-leftover-aaaaaa" in rig.plan_commands()
assert "output remove DP-9" not in rig.plan_commands()
finally:
_kill_everything(rig.daemon)
rig.stop()
def test_a_session_adopted_across_a_restart_keeps_its_container(short_tmpdir: Path):
rig = make_rig(short_tmpdir)
try:
session_id = start(rig.daemon, "sleeper")
output = rig.daemon.session(session_id)["container"]["output"]
rig.daemon.stop()
rig.daemon.start()
record = rig.daemon.session(session_id)
assert record["adopted"] is True
assert record["container"]["state"] == "owned"
assert output in rig.compositor.outputs(), "an adopted container is not an orphan"
# Its slot is not handed to the next session.
assert rig.daemon.session(start(rig.daemon, "sleeper"))["container"]["workspace"] == 1001
finally:
_kill_everything(rig.daemon)
rig.stop()
# ===========================================================================
# degraded mode — PLAN §4.4
# ===========================================================================
def test_with_no_compositor_ipc_sessions_still_live_and_die_normally(short_tmpdir: Path):
"""Lifecycle verbs never depend on the compositor.
The daemon has a Wayland socket to hand its children (so it starts) and no
Hyprland instance to query, which is exactly what a compositor that is up
but not answering IPC looks like from here.
"""
rig = make_rig(short_tmpdir, with_compositor=False)
try:
session_id = start(rig.daemon, "sleeper")
record = rig.daemon.session(session_id)
assert record["state"] == "ready"
assert record["container"] == {
"output": None,
"workspace": None,
"mode": None,
"created_by": "broker",
"state": "degraded",
}
# Nothing is guessed: no workspace, no window, no instance.
assert (record["workspace"], record["window"], record["signature"]) == (None, None, None)
assert record["compositor"]["ipc"] == "absent"
rig.daemon.call("touch", id=session_id)
reply = rig.daemon.call("kill", id=session_id, grace_s=0)
assert reply["ok"], reply
assert reply["session"]["state"] == "killed"
assert reply["session"]["survivors"] == []
assert reply["session"]["container_survivors"] == []
finally:
_kill_everything(rig.daemon)
rig.stop()
def test_a_degraded_session_cannot_be_aimed_at_and_says_why(short_tmpdir: Path):
rig = make_rig(short_tmpdir, with_compositor=False)
try:
session_id = start(rig.daemon, "sleeper")
reply = rig.daemon.call("pointer.acquire", id=session_id)
assert reply["ok"] is False
assert reply["error"] == "no_container"
assert ExitCode(10) == ExitCode.COMPOSITOR
finally:
_kill_everything(rig.daemon)
rig.stop()
# ===========================================================================
# the pointer, over the real control socket
# ===========================================================================
def test_a_whole_gesture_runs_through_the_broker_and_the_driver(rig: Rig):
session_id = start(rig.daemon, "sleeper")
output = f"hh-{session_id}"
acquired = rig.daemon.call("pointer.acquire", id=session_id)
assert acquired["ok"], acquired
lease = acquired["lease_id"]
assert acquired["bookmark"] == {
"x": 0.5,
"y": 0.5,
"output": output,
"at": acquired["bookmark"]["at"],
}
moved = rig.daemon.call("pointer.move", id=session_id, lease_id=lease, x=0.25, y=0.75)
assert moved["ok"], moved
assert (moved["bookmark"]["x"], moved["bookmark"]["y"]) == (0.25, 0.75)
clicked = rig.daemon.call("pointer.click", id=session_id, lease_id=lease, button="left")
assert clicked["ok"], clicked
released = rig.daemon.call("pointer.release", id=session_id, lease_id=lease)
assert released["ok"], released
assert released["released_by"] == "lease"
assert released["buttons_lifted"] == []
assert rig.driver.sink.calls == [
("warp", output, 0.5, 0.5),
("frame", output),
("warp", output, 0.25, 0.75),
("frame", output),
("button", output, 0x110, 1),
("frame", output),
("button", output, 0x110, 0),
("frame", output),
]
# The bookmark is in the record, which is what survives a broker restart.
record = rig.daemon.session(session_id)
assert record["pointer"]["bookmark"]["x"] == 0.25
assert record["pointer"]["released_by"] == "lease"
assert record["pointer"]["last_released_at"] == released["released_at"]
def test_the_cursor_is_leased_broker_wide_and_the_holder_is_named(rig: Rig):
first = start(rig.daemon, "sleeper")
second = start(rig.daemon, "sleeper")
lease = rig.daemon.call("pointer.acquire", id=first)["lease_id"]
refused = rig.daemon.call("pointer.acquire", id=second)
assert refused["ok"] is False
assert refused["error"] == "pointer_busy"
assert refused["holder"] == first
# And the other session cannot move it with someone else's lease either.
denied = rig.daemon.call("pointer.move", id=second, lease_id=lease, x=0.1, y=0.1)
assert denied["error"] == "no_lease"
state = rig.daemon.call("pointer.state")
assert state["holder"] == first
assert state["lease_id"] == lease
def test_a_released_lease_frees_the_cursor_for_the_next_session(rig: Rig):
first = start(rig.daemon, "sleeper")
second = start(rig.daemon, "sleeper")
lease = rig.daemon.call("pointer.acquire", id=first)["lease_id"]
rig.daemon.call("pointer.release", id=first, lease_id=lease)
taken = rig.daemon.call("pointer.acquire", id=second)
assert taken["ok"], taken
assert taken["bookmark"]["output"] == f"hh-{second}"
def test_a_button_left_down_is_lifted_when_the_lease_is_released(rig: Rig):
session_id = start(rig.daemon, "sleeper")
lease = rig.daemon.call("pointer.acquire", id=session_id)["lease_id"]
down = rig.daemon.call("pointer.button", id=session_id, lease_id=lease, button="left", state="down")
assert down["buttons"] == ["left"]
released = rig.daemon.call("pointer.release", id=session_id, lease_id=lease)
assert released["buttons_lifted"] == ["left"]
assert rig.driver.dispatcher._pressed == {}, "nothing may be left down on the driver"
def test_killing_a_session_that_holds_the_cursor_gives_it_back(rig: Rig):
first = start(rig.daemon, "sleeper")
second = start(rig.daemon, "sleeper")
lease = rig.daemon.call("pointer.acquire", id=first)["lease_id"]
rig.daemon.call("pointer.button", id=first, lease_id=lease, button="right", state="down")
rig.daemon.call("kill", id=first, grace_s=0)
assert rig.driver.dispatcher._pressed == {}
assert rig.daemon.call("pointer.state")["holder"] is None
assert rig.daemon.call("pointer.acquire", id=second)["ok"]
def test_pointer_verbs_do_not_reset_the_idle_clock(rig: Rig):
"""A session being clicked in is still one nobody has asked to keep."""
session_id = start(rig.daemon, "sleeper")
before = rig.daemon.session(session_id)["command_count"]
lease = rig.daemon.call("pointer.acquire", id=session_id)["lease_id"]
rig.daemon.call("pointer.move", id=session_id, lease_id=lease, x=0.3, y=0.3)
rig.daemon.call("pointer.click", id=session_id, lease_id=lease)
rig.daemon.call("pointer.release", id=session_id, lease_id=lease)
assert rig.daemon.session(session_id)["command_count"] == before
def test_a_retried_click_with_the_same_request_id_clicks_once(rig: Rig):
"""A click is the one mutation an agent cannot undo."""
session_id = start(rig.daemon, "sleeper")
lease = rig.daemon.call("pointer.acquire", id=session_id)["lease_id"]
rig.driver.sink.calls.clear()
first = rig.daemon.call(
"pointer.click", id=session_id, lease_id=lease, request_id="retry-me"
)
second = rig.daemon.call(
"pointer.click", id=session_id, lease_id=lease, request_id="retry-me"
)
assert first["ok"] and second["ok"]
assert second.get("deduplicated") is True
assert len(rig.driver.sink.of("button")) == 2, "one press and one release, not two"
def test_a_restored_bookmark_survives_a_daemon_restart(short_tmpdir: Path):
"""That is what putting it in the record, and not only in the lease, is for."""
rig = make_rig(short_tmpdir)
try:
session_id = start(rig.daemon, "sleeper")
lease = rig.daemon.call("pointer.acquire", id=session_id)["lease_id"]
rig.daemon.call("pointer.move", id=session_id, lease_id=lease, x=0.8, y=0.2)
rig.daemon.call("pointer.release", id=session_id, lease_id=lease)
rig.daemon.stop()
rig.daemon.start()
rig.driver.sink.calls.clear()
acquired = rig.daemon.call("pointer.acquire", id=session_id)
assert (acquired["bookmark"]["x"], acquired["bookmark"]["y"]) == (0.8, 0.2)
assert rig.driver.sink.of("warp") == [("warp", f"hh-{session_id}", 0.8, 0.2)]
finally:
_kill_everything(rig.daemon)
rig.stop()
def test_with_no_driver_the_pointer_verbs_say_so_and_the_lease_is_not_held(
short_tmpdir: Path,
):
rig = make_rig(short_tmpdir, with_driver=False)
try:
session_id = start(rig.daemon, "sleeper")
reply = rig.daemon.call("pointer.acquire", id=session_id)
assert reply["ok"] is False
assert reply["error"] == "driver_unavailable"
assert rig.daemon.call("pointer.state")["holder"] is None
finally:
_kill_everything(rig.daemon)
rig.stop()
# ===========================================================================
# an exit nobody asked for
# ===========================================================================
def test_an_application_that_dies_takes_its_container_with_it(rig: Rig):
session_id = start(rig.daemon, "sleeper")
output = f"hh-{session_id}"
pid = rig.daemon.session(session_id)["pid"]
os.kill(pid, signal.SIGKILL)
wait_until(
lambda: not rig.daemon.session(session_id)["live"],
timeout=10.0,
what="the daemon to notice the exit",
)
wait_until(
lambda: output not in rig.compositor.outputs(),
timeout=10.0,
what="the container to be taken down with it",
)
assert rig.daemon.session(session_id)["container"]["state"] == "removed"
# And its slot is free again.
assert rig.daemon.session(start(rig.daemon, "sleeper"))["container"]["workspace"] == 1000
def test_a_session_that_dies_holding_the_cursor_gives_it_back(rig: Rig):
"""Never leave a button down, even when nobody asked for the teardown."""
first = start(rig.daemon, "sleeper")
second = start(rig.daemon, "sleeper")
lease = rig.daemon.call("pointer.acquire", id=first)["lease_id"]
rig.daemon.call("pointer.button", id=first, lease_id=lease, button="left", state="down")
os.kill(rig.daemon.session(first)["pid"], signal.SIGKILL)
wait_until(
lambda: rig.daemon.call("pointer.state")["holder"] is None,
timeout=10.0,
what="the lease to come back",
)
assert rig.driver.dispatcher._pressed == {}
assert rig.daemon.call("pointer.acquire", id=second)["ok"]