From 129430bffd69f9f7b597a0edffecb4c2caa42142 Mon Sep 17 00:00:00 2001 From: Hermenix Date: Fri, 2 Oct 2026 19:47:33 +0000 Subject: [PATCH] wire the broker to the compositor, containers and pointer MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 Claude-Session: https://claude.ai/code/session_017mUq7QvQ9EZb2Wi35xj4cs --- src/hhstreamd/container_host.py | 395 ++++++ src/hhstreamd/containers.py | 54 +- src/hhstreamd/driver.py | 210 +++ src/hhstreamd/launcher.py | 41 +- src/hhstreamd/manager.py | 1127 ++++++++++++++++- src/hhstreamd/protocol.py | 114 ++ src/hhstreamd/registry.py | 125 +- src/hhstreamd/server.py | 112 +- tests/containers/test_plan.py | 37 +- tests/sessions/conftest.py | 3 + tests/sessions/fakes.py | 432 +++++++ tests/sessions/integration/test_containers.py | 600 +++++++++ tests/sessions/integration/test_lifecycle.py | 18 +- tests/sessions/unit/test_broker_protocol.py | 86 ++ tests/sessions/unit/test_container_host.py | 288 +++++ .../sessions/unit/test_container_reconcile.py | 296 +++++ tests/sessions/unit/test_driver_client.py | 222 ++++ tests/sessions/unit/test_exit_codes.py | 37 +- tests/sessions/unit/test_pointer_verbs.py | 592 +++++++++ tests/sessions/unit/test_registry.py | 105 +- 20 files changed, 4805 insertions(+), 89 deletions(-) create mode 100644 src/hhstreamd/container_host.py create mode 100644 src/hhstreamd/driver.py create mode 100644 tests/sessions/fakes.py create mode 100644 tests/sessions/integration/test_containers.py create mode 100644 tests/sessions/unit/test_container_host.py create mode 100644 tests/sessions/unit/test_container_reconcile.py create mode 100644 tests/sessions/unit/test_driver_client.py create mode 100644 tests/sessions/unit/test_pointer_verbs.py diff --git a/src/hhstreamd/container_host.py b/src/hhstreamd/container_host.py new file mode 100644 index 0000000..db2c123 --- /dev/null +++ b/src/hhstreamd/container_host.py @@ -0,0 +1,395 @@ +"""The impure half of containers: running the plans and reading the result back. + +:mod:`hhstreamd.containers` decides *what* a container is — argv lists, a +workspace slot, an output name — and deliberately cannot run any of it. This +module is the other side of that line: it owns the compositor connection, turns +a :class:`~hhstreamd.containers.ContainerPlan` into real outputs and rules, and +then asks the compositor what actually happened. Keeping the two apart is what +lets every placement decision be unit-tested without a compositor, and confines +everything that *needs* one to a single file. + +Three decisions worth finding here. + +**Commands go over the request socket, not through ``hyprctl``.** The plans are +``["hyprctl", "keyword", ...]`` argv lists, and running them literally would +mean a subprocess per command, ``hyprctl`` on the broker's ``PATH``, and +``HYPRLAND_INSTANCE_SIGNATURE``/``XDG_RUNTIME_DIR`` set correctly in its +environment — three ways to fail that have nothing to do with the compositor. +``hyprctl`` itself does exactly one thing with those arguments: it joins them +with spaces and writes them to ``/hypr//.socket.sock``, which is +the socket this broker already holds open for queries. So :meth:`dispatch` +sends the argv's *content* down the socket ``hyprctl`` would have used. The +plan is still the authority on what runs and in what order; only the transport +is ours. + +**Read back, never assume.** Every mutation is followed by a query (PLAN §4.2). +``create`` returns what the compositor says the window's workspace and output +are, not what the rule asked for — a rule that did not bind is the failure mode +this exists to catch, and a record that repeated our intention back to us would +hide it. + +**Degrade, never guess.** No compositor means :meth:`available` is false and +every lifecycle verb carries on without one: a container of ``state: +"degraded"``, with every field it could not verify left ``None``. Nothing here +ever invents an output name, a workspace number or a window. +""" + +from __future__ import annotations + +import logging +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +from . import containers +from .ipc import Client, CompositorUnavailable, HyprlandIPC + +log = logging.getLogger("hhstreamd.container_host") + +#: Where a window that matched no container lands (PLAN §5.2). A special +#: workspace, so it is hidden rather than shown on whatever output is in front. +DEFAULT_QUARANTINE_WORKSPACE = "special:quarantine" + +#: The container's size (CONTRACT-sessions.md §5). +DEFAULT_MODE = (1280, 720) + +#: Hyprland answers a successful ``keyword``/``output`` with this, and anything +#: else with prose. Matched case-insensitively and with whitespace stripped. +OK_REPLY = "ok" + + +@dataclass(frozen=True) +class ContainerFacts: + """What the compositor says about a session's window, after the fact. + + Every field is ``None`` when the compositor did not say: there is no window + yet, or no workspace carries a monitor name. ``output`` is the monitor the + *window* is on, which is not necessarily the output we created — and when + the two differ, the rule did not bind and the caller must say so. + """ + + workspace: int | None + output: str | None + window: dict[str, Any] | None + foreground: bool | None + + +class ContainerHost: + """One compositor instance, and the containers this broker owns in it.""" + + def __init__( + self, + runtime_dir: Path | str | None, + *, + allocator: containers.WorkspaceAllocator, + signature: str | None = None, + mode: tuple[int, int] = DEFAULT_MODE, + quarantine_workspace: str = DEFAULT_QUARANTINE_WORKSPACE, + ipc: HyprlandIPC | None = None, + ) -> None: + self.runtime_dir = None if runtime_dir is None else Path(runtime_dir) + self.allocator = allocator + self.mode = mode + self.quarantine_workspace = quarantine_workspace + self._wanted_signature = signature + self._ipc = ipc + self._signature: str | None = signature + self._last_error: str | None = None + if ipc is not None: + self._signature = signature or _signature_of(ipc) + + # -- the connection --------------------------------------------------- + + def ipc(self) -> HyprlandIPC: + """The client for this instance, discovering it if we have none. + + Rediscovery is a ``stat`` and is attempted on every call that needs the + compositor, so a compositor that comes back is picked up without a + broker restart. The signature, once known, is reused: a second + instance appearing must not silently move the broker's containers to a + different desktop. + """ + + if self._ipc is not None: + return self._ipc + if self.runtime_dir is None: + raise CompositorUnavailable( + "no compositor runtime directory is configured; containers are disabled" + ) + client = HyprlandIPC.discover(self.runtime_dir, self._wanted_signature or self._signature) + self._ipc = client + self._signature = _signature_of(client) + self._last_error = None + log.info("compositor instance %s at %s", self._signature, client.request_socket) + return client + + @property + def signature(self) -> str | None: + """The instance signature, or ``None`` if we never reached one.""" + + return self._signature + + @property + def last_error(self) -> str | None: + return self._last_error + + def available(self) -> bool: + """True if the compositor answered just now. Never cached as true. + + ``version`` is the cheapest round trip that proves the socket is a live + compositor and not a leftover inode. + """ + + try: + self.ipc().version() + except CompositorUnavailable as exc: + self._degrade(exc) + return False + return True + + def _degrade(self, exc: CompositorUnavailable) -> None: + self._last_error = str(exc) + # Drop the client: its socket path may be stale, and the next call + # should rediscover rather than keep failing against a dead instance. + self._ipc = None + + # -- running plans ---------------------------------------------------- + + def dispatch(self, argv: list[str]) -> str: + """Run one ``["hyprctl", ...]`` argv over the request socket. + + The reply is checked: Hyprland answers ``ok`` to a command it carried + out and prose to one it refused, and an unchecked dispatch is how a + container ends up recorded as created when the compositor declined. + """ + + if not argv or argv[0] != "hyprctl": + raise ValueError(f"not a hyprctl plan entry: {argv!r}") + command = " ".join(argv[1:]) + reply = self.ipc().query(command).strip() + if reply.lower() != OK_REPLY and reply != "": + raise CompositorUnavailable(f"compositor refused {command!r}: {reply[:200]!r}") + return reply + + def run_plan(self, plan: list[list[str]]) -> None: + """Run argv lists in the order given. Stops at the first refusal.""" + + for argv in plan: + self.dispatch(argv) + + def install_quarantine(self) -> bool: + """Install the catch-all backstop. Returns False when it is disabled. + + **Called once at broker start-up, before any session's container + exists.** Hyprland applies window rules in the order they were + declared and this one matches every class, so installing it after a + per-session rule would override that rule and sweep the session's own + window into the special workspace. The ordering cannot live in + :mod:`hhstreamd.containers`, which runs nothing; it lives here, in the + one caller that could get it wrong. + """ + + argv = containers.quarantine_argv(self.quarantine_workspace) + if argv is None: + log.info("the quarantine backstop is disabled; unmatched windows stay where they land") + return False + self.run_plan(argv) + return True + + # -- containers ------------------------------------------------------- + + def create(self, session_id: str, app_id: str) -> containers.ContainerPlan: + """Allocate a slot and build the session's container. + + The slot is released again if the compositor refuses part way through, + because a half-built container must not also leak a workspace number. + Whatever *was* created is left for :meth:`remove` and for the start-up + scan: deleting an output while the compositor is misbehaving is how one + failure becomes two. + """ + + workspace = self.allocator.allocate() + plan = containers.container_plan( + session_id, workspace, self.mode[0], self.mode[1], app_id + ) + try: + self.run_plan(plan.create) + except (CompositorUnavailable, ValueError): + self.allocator.release(workspace) + raise + return plan + + def remove(self, output: str) -> None: + """Remove one output of ours. Refuses a name we could not have made.""" + + if not containers.contains_output(output): + raise ValueError( + f"refusing to remove output {output!r}: not one this broker creates" + ) + self.dispatch(["hyprctl", "output", "remove", output]) + + def release(self, workspace: int | None) -> None: + """Give a workspace slot back, tolerating one we never held. + + Unlike the allocator's own ``release``, this is called from teardown + paths that also run for sessions started before the broker restarted, + or in degraded mode, where there is no slot to return. Losing a slot + is a leak; raising here would abort a teardown that has already killed + the application. + """ + + if workspace is None: + return + try: + self.allocator.release(workspace) + except KeyError: + log.debug("workspace %s was not held by this allocator", workspace) + + def reserve(self, workspaces: list[int]) -> list[int]: + """Re-take slots a previous broker handed out. Returns what was taken. + + The allocator's frozen interface (CONTRACT-sessions.md §3.2) has + ``allocate``, ``release`` and ``in_use`` and no way to say "this one is + already mine", which adoption needs: the records restored at start-up + name workspaces that must not be handed to a new session. Allocating + from the bottom until each wanted slot has come up, then giving back + the ones we did not want, reserves them through the interface that + exists. The band is a few entries wide, so the cost is nothing; the + alternative is a second free list beside the allocator's, which is the + drift the allocator exists to prevent. + """ + + wanted = {w for w in workspaces if isinstance(w, int) and not isinstance(w, bool)} + if not wanted: + return [] + # Slots this allocator already holds are already reserved. Without + # this, a second reconcile walks the band looking for a number it has + # itself taken, exhausts it, and reports the band full. + taken: list[int] = sorted(wanted & set(self.allocator.in_use())) + wanted -= set(taken) + if not wanted: + return taken + spare: list[int] = [] + while wanted - set(taken): + try: + slot = self.allocator.allocate() + except containers.NoSlots: + missing = sorted(wanted - set(taken)) + log.error( + "cannot reserve adopted workspaces %s: the band is full; a new " + "session could be given one of them", + missing, + ) + break + (taken if slot in wanted else spare).append(slot) + for slot in spare: + self.allocator.release(slot) + return sorted(taken) + + # -- reading back ----------------------------------------------------- + + def read_back(self, app_id: str, pid: int | None = None) -> ContainerFacts | None: + """What the compositor says about this session's window, or ``None``. + + ``None`` means no window has appeared yet, which is not a failure: an + application takes time to map one, and the caller polls. A window is + matched by its ``initial_class`` — the stamp the rule also matches — + and failing that by pid, so a session whose toolkit ignored the stamp + is still *observed*, even though its rule will not have bound. + """ + + client = self._find(app_id, pid) + if client is None: + return None + workspace_monitor = {w.id: w.monitor for w in self.ipc().workspaces()} + output = workspace_monitor.get(client.workspace_id) if client.workspace_id else None + foreground: bool | None = None + if output is not None: + for monitor in self.ipc().monitors(): + if monitor.name == output: + # "Foreground" is the monitor-active-workspace join, not + # the client's own `visible` flag: it answers "is anything + # — a human, the frame server — actually looking at this", + # which a mapped window on a hidden workspace is not. + foreground = monitor.active_workspace_id == client.workspace_id + break + return ContainerFacts( + workspace=client.workspace_id, + output=output, + window={ + "stable_id": client.stable_id, + "address": client.address, + "class": client.class_, + "initial_class": client.initial_class, + "title": client.title, + "pid": client.pid, + }, + foreground=foreground, + ) + + def _find(self, app_id: str, pid: int | None) -> Client | None: + by_pid: Client | None = None + for client in self.ipc().clients(): + if client.initial_class == app_id: + return client + if pid is not None and pid > 0 and client.pid == pid: + by_pid = client + return by_pid + + def survivors(self, app_id: str, output: str | None) -> list[dict[str, Any]]: + """Windows of ours the compositor still has after a teardown. + + Either identity counts: a window still carrying the session's class, or + any window still sitting on the output we were about to remove. Both + mean the teardown did not finish, and the caller reports them instead + of claiming success (PLAN §4.5). + """ + + on_output: set[int] = set() + if output is not None: + on_output = { + workspace.id + for workspace in self.ipc().workspaces() + if workspace.monitor == output + } + found = [] + for client in self.ipc().clients(): + if client.initial_class == app_id or ( + client.workspace_id is not None and client.workspace_id in on_output + ): + found.append( + { + "address": client.address, + "pid": client.pid, + "class": client.class_, + "initial_class": client.initial_class, + "workspace": client.workspace_id, + } + ) + return found + + def our_outputs(self) -> list[str]: + """Live outputs whose names this broker could have created. + + :func:`hhstreamd.containers.contains_output` is the whole filter, and + it is the only thing standing between the start-up scan and somebody + else's monitor. A name it rejects is never returned, so it can never + be removed. + """ + + return sorted(m.name for m in self.ipc().monitors() if containers.contains_output(m.name)) + + +def _signature_of(client: HyprlandIPC) -> str | None: + """The instance signature, read back off the socket path we connected to. + + ``HyprlandIPC.discover`` resolves the signature (from the argument, the + environment, or the single instance directory) but does not report which + one it chose, and the record has to carry it so a restarted broker + re-attaches to the same instance. The socket lives at + ``/hypr//.socket.sock``, so its parent directory is the + answer. + """ + + parent = client.request_socket.parent + return parent.name or None diff --git a/src/hhstreamd/containers.py b/src/hhstreamd/containers.py index d4f07da..5381d15 100644 --- a/src/hhstreamd/containers.py +++ b/src/hhstreamd/containers.py @@ -173,44 +173,44 @@ def container_plan( ) -def quarantine_plan(quarantine_workspace: str) -> ContainerPlan | None: +def quarantine_argv(quarantine_workspace: str) -> list[list[str]] | None: """The backstop rule: a window that matched no container goes here. Without it, a window with an unexpected class — a dialog spawned by a helper process, a toolkit that rewrites its class — lands on whatever - workspace is in front, which is the leak containers exist to prevent. The - rule matches every class and is therefore emitted *before* the per-session - rules, which are anchored and more specific. + workspace is in front, which is the leak containers exist to prevent. - ``quarantine_workspace`` is a workspace *name* (``special:quarantine``), not - a slot out of the allocator's band, so the returned plan carries no output - and no mode: it is a rule, not a container. An empty or blank name means - the operator turned the backstop off, and the answer is ``None`` rather than - a plan with an empty command list — a caller that gets a plan should always - have something to run. + **Install it before any per-session rule.** Hyprland evaluates window + rules in the order the keywords were issued and this one matches every + class, so a quarantine rule issued *after* a session's anchored rule + overrides it and every window in the system ends up in the special + workspace — containers included. The ordering cannot be enforced from + here, because this module never runs anything; the broker installs it once + at start-up, before the first ``container_plan`` is executed, and + :mod:`hhstreamd.container_host` says so at the call site. + + ``quarantine_workspace`` is a workspace *name* (``special:quarantine``), + not a slot out of the allocator's band — which is why this returns bare + argv and not a :class:`ContainerPlan` (CONTRACT-sessions.md v2 §3.2): a + quarantine rule has no output, no numbered workspace and no mode, and + ``container_plan`` refuses the zero size one would have to invent. An + empty or blank name is how "disabled" is spelled, and the answer is + ``None`` rather than an empty list — a caller that gets commands should + always have something to run. """ target = quarantine_workspace.strip() if not target: return None _checked_rule_value(target, "quarantine_workspace") - return ContainerPlan( - output="", - workspace=0, - mode=(0, 0), - create=[ - [ - "hyprctl", - "keyword", - "windowrule", - f"match:initial_class .*, workspace {target}", - ] - ], - # A keyword rule cannot be unset one at a time, and this one is not - # per-session anyway: it is installed once at start-up and goes away - # with the compositor. - teardown=[], - ) + return [ + [ + "hyprctl", + "keyword", + "windowrule", + f"match:initial_class .*, workspace {target}", + ] + ] class WorkspaceAllocator: diff --git a/src/hhstreamd/driver.py b/src/hhstreamd/driver.py new file mode 100644 index 0000000..d478af0 --- /dev/null +++ b/src/hhstreamd/driver.py @@ -0,0 +1,210 @@ +"""The broker's end of the private driver socket (CONTRACT-sessions.md §3.4). + +The pointer driver is a separate process because a Wayland client needs its own +connection; this module is the five-verb client that talks to it. It is the +only place in the broker that knows the driver's wire format, so the driver and +the broker can be read against each other in two files. + +**It holds no lease state and asks for none.** The driver is an executor: it +will warp anywhere it is told, and the only thing that stops two sessions +fighting over the one cursor is the lease in :mod:`hhstreamd.manager`. Putting +even a session id in a request here would suggest otherwise, so none of these +methods takes one. + +**Blocking, with a short timeout, and deliberately synchronous.** The driver +is local, the requests are one small line each, and the broker is the only +peer. An async client would buy nothing but a way to interleave two warps. +The caller runs it off the event loop (``asyncio.to_thread``) so a wedged +driver cannot stall session lifecycle — which is the whole reason the driver is +a separate process — and the lock below makes that safe: one request on the +wire at a time, whatever thread asks. + +**One connection, checked before every use, never retried after one.** The +driver's server handles one connection at a time and reads lines from it until +EOF, so a connection per request would work but would churn the accept loop. +A held connection can die under us when the driver restarts, so it is tested +for EOF before each write and silently replaced — but a request that *was* +written and then went unanswered is never sent again, because a repeated +``button down`` is a click the agent did not ask for. Every failure is +:class:`DriverUnavailable` — never a guess, and never a silent no-op, because a +dropped ``release_all`` leaves a mouse button down. +""" + +from __future__ import annotations + +import json +import logging +import select +import socket +import threading +from pathlib import Path +from typing import Any + +log = logging.getLogger("hhstreamd.driver") + +#: The driver answers from memory; it does not render, wait for a frame +#: callback or ask the compositor anything. This only bounds a driver that has +#: stopped answering at all. +DEFAULT_TIMEOUT_S = 2.0 + +#: Matches the driver's own ceiling (``hhstream_pointer.server``). +MAX_LINE_BYTES = 1 << 20 + + +class DriverUnavailable(Exception): + """The driver could not be reached, or did not answer intelligibly. + + Distinct from :class:`DriverRejected`: this one means the cursor's state is + now unknown, so the broker drops the lease rather than carrying on. + """ + + +class DriverRejected(Exception): + """The driver understood the request and refused it (``ok: false``).""" + + +class PointerDriver: + """A client for one driver socket. Thread-safe; one request at a time.""" + + def __init__(self, socket_path: Path | str, *, timeout_s: float = DEFAULT_TIMEOUT_S) -> None: + self.socket_path = Path(socket_path) + self.timeout_s = float(timeout_s) + self._lock = threading.Lock() + self._sock: socket.socket | None = None + self._stream = None + + # -- the five verbs --------------------------------------------------- + + def warp(self, output: str, x: float, y: float) -> None: + """Aim at ``x``/``y``, each 0..1 in ``output``'s own frame.""" + + self.request({"op": "warp", "output": output, "x": float(x), "y": float(y)}) + + def button(self, button: str, state: str) -> None: + self.request({"op": "button", "button": button, "state": state}) + + def frame(self) -> None: + """Commit what was queued. Nothing the driver was sent is delivered + to the compositor until this, so every gesture ends with one.""" + + self.request({"op": "frame"}) + + def pressed(self) -> list[str]: + """What the *driver* believes is down. + + The lease keeps its own set, and this is the one that matters when the + two disagree: the driver's is the one the compositor saw. + """ + + reply = self.request({"op": "pressed"}) + return _string_list(reply.get("buttons"), "pressed") + + def release_all(self) -> list[str]: + """Lift everything, returning what came up. Called on expiry.""" + + reply = self.request({"op": "release_all"}) + return _string_list(reply.get("lifted"), "release_all") + + # -- plumbing --------------------------------------------------------- + + def request(self, message: dict[str, Any]) -> dict[str, Any]: + """One request, one reply. Raises rather than returning a guess.""" + + with self._lock: + try: + return self._exchange(message) + except (OSError, ValueError) as exc: + # The connection is now of unknown state — a half-written + # request, a partial reply — so it is dropped rather than + # reused for the next verb. + self._disconnect() + raise DriverUnavailable( + f"pointer driver {self.socket_path}: {exc}" + ) from exc + + def close(self) -> None: + with self._lock: + self._disconnect() + + def _exchange(self, message: dict[str, Any]) -> dict[str, Any]: + stream = self._connect() + line = json.dumps(message, separators=(",", ":")).encode("ascii") + b"\n" + stream.write(line) + stream.flush() + reply_line = stream.readline(MAX_LINE_BYTES + 1) + if not reply_line: + # The driver went away between the write and the reply, so whether + # it carried the request out is unknowable. **Not retried**: a + # repeated ``button down`` is a second press the agent never asked + # for, and the broker's answer to an unknown cursor is to drop the + # lease, not to guess again. + raise OSError("the driver closed the connection without answering") + if len(reply_line) > MAX_LINE_BYTES: + raise ValueError("reply exceeds the frame limit") + reply = json.loads(reply_line) + if not isinstance(reply, dict): + raise ValueError(f"reply is not an object: {type(reply).__name__}") + if not reply.get("ok"): + raise DriverRejected(str(reply.get("error") or "the driver refused the request")) + return reply + + def _connect(self): + if self._stream is not None and not self._stale(): + return self._stream + self._disconnect() + sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + try: + sock.settimeout(self.timeout_s) + sock.connect(str(self.socket_path)) + except OSError: + sock.close() + raise + self._sock = sock + self._stream = sock.makefile("rwb") + log.debug("connected to the pointer driver at %s", self.socket_path) + return self._stream + + def _stale(self) -> bool: + """True if the held connection has died since the last verb. + + The driver never speaks unsolicited, so a readable socket can only be + at EOF — the driver restarted, or was stopped. Checking costs one + non-blocking ``select`` and is what makes reconnecting safe: the + request is written only to a connection that was alive when it was + written, so there is never a question of whether a retry would repeat + a click. + """ + + sock = self._sock + if sock is None: + return True + try: + readable, _, _ = select.select([sock], [], [], 0) + except (OSError, ValueError): + return True + return bool(readable) + + def _disconnect(self) -> None: + stream, self._stream = self._stream, None + sock, self._sock = self._sock, None + for closeable in (stream, sock): + if closeable is None: + continue + try: + closeable.close() + except OSError: + pass + + +def _string_list(value: Any, what: str) -> list[str]: + """A list of button names, or a malformed reply — never a silent ``[]``. + + An empty list is a real answer ("nothing was down"); anything that is not a + list of strings means the broker and the driver disagree about the + protocol, and treating that as "nothing was down" is how a button stays + pressed forever. + """ + + if not isinstance(value, list) or not all(isinstance(item, str) for item in value): + raise DriverUnavailable(f"{what}: expected a list of button names, got {value!r}") + return list(value) diff --git a/src/hhstreamd/launcher.py b/src/hhstreamd/launcher.py index 220ef89..60fcdc5 100644 --- a/src/hhstreamd/launcher.py +++ b/src/hhstreamd/launcher.py @@ -32,6 +32,18 @@ environment at spawn. Without that option the old inherited-environment behaviour stands, and the daemon warns at startup that applications may not reach a compositor. +**The container stamp.** A session's window rule matches ``initial_class +^hh-$``, so the application has to report that class or the rule binds to +nothing and the window lands outside its container. The only lever this module +has is the environment (:data:`APP_ID_ENV`), because the alternative — a +per-app ``--app-id``/``--class`` flag — would have to come from the allowlist, +and the allowlist is not this slice's file. The variables below are the ones +that are actually read by something: SDL's two, X11's ``RESOURCE_NAME`` (which +XWayland clients surface as ``WM_CLASS``), and ``HHSTREAM_APP_ID`` for a +wrapper script that knows what to do with it. **A GTK or Qt application +ignores all of them**, which is a real limit and is reported as one: the +read-back after launch is what tells the broker the rule did not bind. + The app runs as **the same unprivileged user as the daemon** and inherits the real home directory. M0 invents no service account and forces no throwaway ``HOME``; ``--home`` pins a different one and ``--ephemeral-home`` opts in to a @@ -52,6 +64,19 @@ from .registry import Session log = logging.getLogger("hhstreamd.launcher") +#: The variables that carry the container stamp, each read by something real: +#: SDL sets the surface's app id from its two, Xlib's ``XSetClassHint`` falls +#: back to ``RESOURCE_NAME`` for an XWayland client's ``WM_CLASS``, and +#: ``HHSTREAM_APP_ID`` is the broker's own name for it. A toolkit that reads +#: none of them (GTK, Qt) keeps its own class and its window rule will not +#: bind; that is visible in the read-back, not papered over here. +APP_ID_ENV = ( + "HHSTREAM_APP_ID", + "SDL_VIDEO_WAYLAND_WMCLASS", + "SDL_VIDEO_X11_WMCLASS", + "RESOURCE_NAME", +) + #: Environment variables the daemon's own plumbing must not leak into an app. _STRIPPED = ( "HHSTREAM_SOCKET", @@ -104,7 +129,7 @@ class Launcher: # ---- environment ------------------------------------------------- - def build_env(self, session_id: str, home: Path) -> dict[str, str]: + def build_env(self, session_id: str, home: Path, app_id: str | None = None) -> dict[str, str]: """The app's environment. It inherits the daemon's, minus the daemon's own configuration, plus a @@ -133,6 +158,9 @@ class Launcher: env["HHSTREAM_SESSION_ID"] = session_id if self.compositor is not None: env.update(self.compositor.env()) + if app_id: + for name in APP_ID_ENV: + env[name] = app_id return env def resolve_home(self, session_id: str, home: str | None, ephemeral: bool) -> tuple[Path, bool]: @@ -184,8 +212,15 @@ class Launcher: *, home: str | None = None, ephemeral_home: bool = False, + app_id: str | None = None, ) -> Spawned: - """Start the application. Raises ``OSError`` if it cannot be executed.""" + """Start the application. Raises ``OSError`` if it cannot be executed. + + ``app_id`` is the container stamp: the class the session's window rule + matches on. It reaches the application through the environment only + (see :data:`APP_ID_ENV` and the module docstring), so passing it is a + request, not a guarantee. + """ if not argv: raise ValueError("argv is empty") @@ -196,7 +231,7 @@ class Launcher: raise ValueError(f"argv[0] must be an absolute path, got {argv[0]!r}") home_path, is_ephemeral = self.resolve_home(session_id, home, ephemeral_home) - env = self.build_env(session_id, home_path) + env = self.build_env(session_id, home_path, app_id) log_file = self.log_path(session_id) log_file.parent.mkdir(parents=True, exist_ok=True, mode=0o750) diff --git a/src/hhstreamd/manager.py b/src/hhstreamd/manager.py index 1822e49..2059aaf 100644 --- a/src/hhstreamd/manager.py +++ b/src/hhstreamd/manager.py @@ -9,12 +9,28 @@ Two things are worth finding quickly: grace, ``killpg(SIGKILL)``, then the ``/proc`` session-id sweep (DESIGN.md §3.3). ``kill`` and the reaper both call it with a different ``reason``, so there is one kill path and not two. -* :meth:`SessionManager.touch` is the **only** mark of activity in M0. There is - no input verb and no session-scoped frame verb, so an agent observing a - long-running app has no other way to say "still working". ``list``, - ``status``, ``logs`` and ``gc`` deliberately do not stamp it: if monitoring - refreshed the clock, a supervisor polling every 60 s would keep every - abandoned session alive forever and the reaper would never fire. +* :meth:`SessionManager.touch` is the **only** mark of activity. ``list``, + ``status``, ``logs``, ``gc`` and **every ``pointer.*`` verb** deliberately do + not stamp it: if monitoring refreshed the clock, a supervisor polling every + 60 s would keep every abandoned session alive forever and the reaper would + never fire — and a session being clicked in is still a session nobody has + claimed to want (PLAN §8.3). + +Two things arrived with the container work and are worth stating once. + +**The compositor is never load-bearing for lifecycle.** ``start``, ``kill``, +the reaper and ``gc`` all work with no IPC at all: the session is a process +group, it is tracked by process identity, and its container is recorded as +``degraded`` (PLAN §4.4). Every call into :mod:`hhstreamd.container_host` from +a lifecycle path is wrapped so that losing the compositor downgrades the +*record* and never the verb. + +**The broker owns the pointer lease; the driver owns nothing.** The lease +lives here because there is one cursor for the whole compositor, so the +decision cannot be per-session and cannot be in a process that might be +restarted under us. :mod:`hhstreamd.driver` executes; this module decides, and +it is this module's job to lift a button the lease timed out underneath (the +lease cannot — see :meth:`SessionManager._expire_pointer`). """ from __future__ import annotations @@ -30,18 +46,25 @@ from dataclasses import dataclass from pathlib import Path from typing import Any -from . import procmon +from . import containers, procmon from .audit import AuditLog from .clock import Clock, iso from .compositor import CompositorTarget +from .container_host import DEFAULT_MODE, DEFAULT_QUARANTINE_WORKSPACE, ContainerHost +from .driver import DriverRejected, DriverUnavailable, PointerDriver +from .ipc import CompositorUnavailable from .launcher import Launcher +from .pointer import Bookmark, LeaseBusy, LeaseInvalid, PointerLease from .policy import Policy, PolicyError, check_app_name from .reaper import Reaper from .registry import ( TERMINAL_ERROR, + ContainerState, Registry, Session, State, + container_record, + pointer_record, ) from .textio import tail_lines @@ -65,6 +88,34 @@ SURVIVOR_GRACE_S = 0.5 #: exceed the protocol's frame limit however much the app has written. MAX_LOG_CHUNK_BYTES = 256 * 1024 +#: How long ``start`` waits for the application's window to appear in +#: ``clients -j`` before recording "no window yet". Short on purpose: it is +#: added to every start that has a compositor, and a window that has not +#: mapped in this long is better reported as absent and reconciled later than +#: waited for while the caller holds a connection open. +DEFAULT_READBACK_S = 2.0 + +#: Poll interval for the read-back. A window maps in milliseconds or not at +#: all; this is tight enough not to dominate ``start``. +READBACK_INTERVAL_S = 0.05 + +#: How often the broker checks whether the pointer lease has expired. The +#: lease does not expire itself (nothing calls it), and an expiry that is +#: noticed only when the next verb arrives would leave a mouse button down for +#: as long as nobody asks. +POINTER_SWEEP_S = 1.0 + +#: The workspace band (CONTRACT-sessions.md §5) and how many slots of it this +#: broker will hand out. The real ceiling is a CPU question the plan defers to +#: a measurement (PLAN §5.5); the band is the part that can be enforced here, +#: and exhausting it refuses the session rather than quietly sharing a screen. +DEFAULT_CONTAINER_BASE = 1000 +DEFAULT_CONTAINER_SLOTS = 4 + +#: Clicks per ``pointer.click``. Bounded because a count comes off the wire +#: and "click 10000 times" is not a gesture. +MAX_CLICK_COUNT = 3 + SIGNALS_BY_NAME = { "TERM": signal.SIGTERM, "SIGTERM": signal.SIGTERM, @@ -99,6 +150,35 @@ class ManagerConfig: #: The compositor launched applications attach to, or ``None`` for the #: inherited environment (``--compositor-runtime-dir`` unset). compositor: CompositorTarget | None = None + #: Where ``hypr//`` lives. Defaults to the compositor target's + #: own directory, which is the same place (CONTRACT-sessions.md §5), so + #: configuring a compositor is all it takes to get containers; it is a + #: separate field only so a test can point IPC at a fake instance without + #: also standing up a Wayland socket. + compositor_runtime_dir: Path | None = None + #: Pinned instance signature. ``None`` means "discover it", which is right + #: for a first start; a restart passes what the records remember. + signature: str | None = None + container_base: int = DEFAULT_CONTAINER_BASE + container_slots: int = DEFAULT_CONTAINER_SLOTS + container_mode: tuple[int, int] = DEFAULT_MODE + quarantine_workspace: str = DEFAULT_QUARANTINE_WORKSPACE + readback_s: float = DEFAULT_READBACK_S + #: The broker↔driver socket. ``None`` leaves pointer verbs answering + #: ``driver_unavailable`` (exit 10) rather than pretending. + pointer_socket: Path | None = None + pointer_ttl_s: float = 30.0 + pointer_max_s: float = 300.0 + pointer_sweep_s: float = POINTER_SWEEP_S + + def __post_init__(self) -> None: + if self.pointer_socket is None: + # `/pointer.sock` is the frozen path + # (CONTRACT-sessions.md §5: /run/hhstream/pointer.sock), and + # deriving it means the daemon needs no flag for a value that is + # not allowed to vary. A driver that is not running is then an + # unreachable socket, which is the same answer by a shorter route. + self.pointer_socket = Path(self.runtime_dir) / "pointer.sock" class SessionManager: @@ -110,6 +190,8 @@ class SessionManager: registry: Registry | None = None, launcher: Launcher | None = None, audit: AuditLog | None = None, + host: ContainerHost | None = None, + driver: PointerDriver | None = None, ) -> None: self.config = config self.clock = clock or Clock() @@ -123,10 +205,36 @@ class SessionManager: sessions=self.registry.live, on_expire=self._reap, ) + self.host = host or ContainerHost( + _compositor_runtime_dir(config), + allocator=containers.WorkspaceAllocator( + config.container_base, config.container_slots + ), + signature=config.signature, + mode=config.container_mode, + quarantine_workspace=config.quarantine_workspace, + ) + # The lease runs on CLOCK_BOOTTIME like every other deadline here, so a + # host suspended mid-gesture does not come back believing the lease is + # still fresh, and ManualClock drives it in tests without sleeping. + self.pointer = PointerLease( + ttl_s=config.pointer_ttl_s, max_s=config.pointer_max_s, clock=self.clock.boottime + ) + self.driver = driver # Per-session asyncio plumbing, never persisted. self._exited: dict[str, asyncio.Event] = {} self._watchers: dict[str, asyncio.Task] = {} self._busy: set[str] = set() + #: Fire-and-forget work started from a callback that cannot await. + #: Held so the loop does not collect a task mid-flight. + self._background: set[asyncio.Task] = set() + self._pointer_sweeper: asyncio.Task | None = None + #: Set while a lease is held with a caller-supplied TTL, so the default + #: comes back when the lease ends (the frozen ``acquire`` takes no TTL). + self._pointer_ttl_override = False + #: True once the compositor has been reached at least once; reported by + #: ``status`` so "degraded" is distinguishable from "never tried". + self.containers_available = False # ------------------------------------------------------------------ # startup / shutdown @@ -193,12 +301,256 @@ class SessionManager: summary["adopted"] += 1 self.audit.emit("adopted", session=record.id, app=record.app, pid=record.pid) summary["pruned"] = self._prune_tombstones() + summary["containers"] = self.reconcile_containers() self.audit.emit("daemon_started", pid=os.getpid(), **summary) # Expired deadlines are reaped on the reaper's first pass, which runs # before its first sleep. self.reaper.start() + self._pointer_sweeper = asyncio.create_task( + self._sweep_pointer(), name="hhstreamd.pointer-sweep" + ) return summary + # ------------------------------------------------------------------ + # containers + # ------------------------------------------------------------------ + + def reconcile_containers(self) -> dict[str, Any]: + """Make the compositor's outputs and the registry agree (PLAN §5.3). + + Run at start-up, and by ``container.reconcile``. Three things happen, + in this order and for this reason: + + 1. **The quarantine backstop goes in first.** It matches every class, + and Hyprland applies rules in declaration order, so a per-session + rule installed before it would be overridden and that session's own + window would be swept into the special workspace. + 2. **Adopted containers re-take their workspace slots**, so a new + session cannot be handed a number an adopted one is already using. + Only records from *this* compositor instance count: a record whose + signature is someone else's describes a container that died with + its compositor. + 3. **Every ``hh-*`` output with no live session is removed.** A + container must never be left unattended — it is a render target + costing CPU and a place windows can land — and the recovery path + for a broker that lost its registry is exactly this scan. + :func:`hhstreamd.containers.contains_output` is the whole filter, + so an output it rejects is never even a candidate. + """ + + summary: dict[str, Any] = { + "available": False, + "signature": None, + "quarantine": None, + "adopted": [], + "removed": [], + "orphaned": [], + "failed": [], + } + if not self.host.available(): + self.containers_available = False + reason = self.host.last_error or "no compositor runtime directory is configured" + summary["error"] = reason + log.warning("no compositor IPC (%s); sessions run with container: degraded", reason) + self.audit.emit("compositor_unavailable", why=reason) + return summary + self.containers_available = True + signature = self.host.signature + summary["available"] = True + summary["signature"] = signature + + try: + summary["quarantine"] = self.host.install_quarantine() + except (CompositorUnavailable, ValueError) as exc: + summary["failed"].append({"what": "quarantine", "why": str(exc)}) + log.error("could not install the quarantine backstop: %s", exc) + + claimed: dict[str, Session] = {} + for session in self.registry.live(): + container = session.container + output = (container or {}).get("output") + if not output: + continue + if session.signature and signature and session.signature != signature: + # A different compositor instance: the output named here is not + # in this one, and the slot is not ours to reserve. + self._set_container_state(session, ContainerState.ORPHAN) + summary["orphaned"].append({"id": session.id, "why": "signature_changed"}) + continue + claimed[output] = session + + try: + present = self.host.our_outputs() + except CompositorUnavailable as exc: + summary["failed"].append({"what": "scan", "why": str(exc)}) + return summary + + reserved = self.host.reserve( + [(s.container or {}).get("workspace") for s in claimed.values()] + ) + summary["reserved"] = reserved + + for output, session in sorted(claimed.items()): + if output in present: + self._set_container_state(session, ContainerState.OWNED) + summary["adopted"].append({"id": session.id, "output": output}) + else: + # The record names an output the compositor does not have. The + # session's application may still be running, so nothing is + # killed; the container is simply no longer there. + self._set_container_state(session, ContainerState.ORPHAN) + summary["orphaned"].append({"id": session.id, "output": output}) + + for output in present: + if output in claimed: + continue + try: + self.host.remove(output) + except (CompositorUnavailable, ValueError) as exc: + summary["failed"].append({"what": "remove", "output": output, "why": str(exc)}) + log.error("could not remove unattended output %s: %s", output, exc) + continue + summary["removed"].append(output) + log.warning("removed unattended container output %s (no live session)", output) + self.audit.emit("container_orphan_removed", output=output) + return summary + + def _set_container_state(self, session: Session, state: str) -> None: + if session.container is None: + return + if session.container.get("state") == state: + return + session.container = {**session.container, "state": state} + self.registry.persist(session, force=True) + + def _create_container(self, session_id: str, app_id: str) -> containers.ContainerPlan | None: + """Build the session's container, or record why there is none. + + Returns the plan when the compositor built it, ``None`` when it could + not be reached. The caller writes the record either way: a failure + here is a *degraded* session, never a refused one (PLAN §4.4). + """ + + if not self.containers_available: + return None + try: + return self.host.create(session_id, app_id) + except containers.NoSlots as exc: + raise ManagerError( + "container_budget", + str(exc), + hint="kill or gc a session; the workspace band bounds how many " + "containers exist at once", + ) from exc + except (CompositorUnavailable, ValueError) as exc: + # The session still starts. It simply has nowhere of its own, and + # the record says so instead of naming an output that is not there. + log.error("could not build a container for %s: %s", session_id, exc) + self.audit.emit("container_create_failed", session=session_id, why=str(exc)) + self.containers_available = False + return None + + def _destroy_container(self, session: Session) -> dict[str, Any]: + """Remove the session's output and give its slot back. + + Returns what is left: ``survivors`` are windows the compositor still + shows for this session after the output went away. They are + *reported*, never assumed absent — two independent sources (``/proc`` + and the compositor) have to agree before a teardown is a success + (PLAN §4.5). + """ + + result: dict[str, Any] = {"container_removed": False, "container_survivors": []} + container = session.container + if container is None: + return result + if container.get("state") == ContainerState.REMOVED: + # Already taken down — by the exit watcher, or by an earlier verb. + # Asking the compositor to remove it again would answer "no such + # output", which is not a failure and must not read as one. + return {"container_removed": True, "container_survivors": []} + output = container.get("output") + workspace = container.get("workspace") + app_id = containers.app_id_for(session.id) + if output and self.containers_available: + try: + self.host.remove(output) + result["container_removed"] = True + except (CompositorUnavailable, ValueError) as exc: + result["container_error"] = str(exc) + log.error("could not remove output %s for %s: %s", output, session.id, exc) + try: + result["container_survivors"] = self.host.survivors(app_id, output) + except CompositorUnavailable as exc: + # "I could not check" is not "nothing survived". + result["container_error"] = str(exc) + result["container_survivors"] = None + self.host.release(workspace) + if output: + session.container = {**container, "state": ContainerState.REMOVED} + # A degraded container stays degraded: there was never anything to + # remove, and "removed" would claim a teardown that did not happen. + if result["container_survivors"]: + log.error( + "%s: the compositor still shows %d window(s) after teardown: %s", + session.id, + len(result["container_survivors"]), + result["container_survivors"], + ) + return result + + async def _read_back(self, session: Session, app_id: str) -> None: + """Fill ``workspace``/``window``/``foreground`` from the compositor. + + The compositor is the authority here, not the plan: the rule may not + have bound (an application that ignored the class stamp keeps its own), + and a record that echoed our intention back would hide exactly that. + When the window turns up on an output that is not ours, the container + is marked ``degraded`` — it exists, but it is not holding the window it + was made for. + """ + + if not self.containers_available or session.container is None: + return + deadline = time.monotonic() + self.config.readback_s + facts = None + while True: + try: + facts = self.host.read_back(app_id, session.pid) + except CompositorUnavailable as exc: + log.error("read-back for %s failed: %s", session.id, exc) + self.containers_available = False + return + if facts is not None or time.monotonic() >= deadline or not session.live: + break + await asyncio.sleep(READBACK_INTERVAL_S) + if facts is None: + # No window yet. Not a failure: an application takes its time, and + # `container.reconcile` picks it up later. Nothing is invented. + log.info("%s: no window in clients -j yet; workspace and window stay null", session.id) + return + session.workspace = facts.workspace + session.window = facts.window + session.foreground = facts.foreground + expected = session.container.get("output") + if facts.output is not None and expected is not None and facts.output != expected: + log.error( + "%s: the window mapped on %s, not on its own output %s — the window " + "rule did not bind (the application kept its own class)", + session.id, + facts.output, + expected, + ) + session.container = {**session.container, "state": ContainerState.DEGRADED} + session.last_error = "window_outside_container" + self.audit.emit( + "container_rule_unbound", + session=session.id, + expected=expected, + observed=facts.output, + ) + self.registry.persist(session, force=True) + async def shutdown(self) -> None: """Stop watching, flush the mirror. **Sessions are left running.** @@ -208,6 +560,24 @@ class SessionManager: """ await self.reaper.stop() + if self._pointer_sweeper is not None: + self._pointer_sweeper.cancel() + with contextlib.suppress(asyncio.CancelledError, Exception): + await self._pointer_sweeper + self._pointer_sweeper = None + for task in list(self._background): + task.cancel() + for task in list(self._background): + with contextlib.suppress(asyncio.CancelledError, Exception): + await task + self._background.clear() + if self.driver is not None: + # The lease is dropped with the broker (a lease is stale by + # definition across a restart), but a button must not be: anything + # still down is lifted while there is still a driver to ask. + with contextlib.suppress(Exception): + await self._release_all_buttons() + self.driver.close() for task in list(self._watchers.values()): task.cancel() for task in list(self._watchers.values()): @@ -378,6 +748,22 @@ class SessionManager: self.registry.terminate( session, State.EXITED, exit_code=exit_code, exit_detected_by=detected_by ) + # An application that exits on its own is not a `kill`, a reap or a + # `gc` — and its container would otherwise be left standing with + # nobody to own it, which is exactly the thing the start-up scan has + # to clean up after. So the one honest place to take it down is here, + # where every exit arrives. Unless a teardown is already running: the + # process exiting inside its grace period lands here, and the teardown + # that asked for it is the one that reports what happened. + result = {"container_removed": False, "container_survivors": []} + if session.id not in self._busy: + result = self._destroy_container(session) + self.registry.persist(session, force=True) + if session.id not in self._busy and self.pointer.state()["holder"] == session.id: + # The holder is gone, so the cursor comes back — and anything it + # left pressed has to come up. Lifting is a driver call, which + # cannot be awaited from this callback, so it is scheduled. + self._spawn(self._drop_lease_for(session, "crash")) self.audit.emit( "session_exited", session=session.id, @@ -385,9 +771,28 @@ class SessionManager: pid=session.pid, exit_code=exit_code, detected_by=detected_by, + container_removed=result["container_removed"], + container_survivors=result["container_survivors"], ) self.reaper.wake() + def _spawn(self, coro) -> None: + """Run a coroutine from a callback that cannot await it. + + The task is held until it finishes: a bare ``create_task`` can be + collected mid-flight, and the work scheduled here is "lift the button + the dead session left down", which must not be. + """ + + try: + task = asyncio.get_running_loop().create_task(coro) + except RuntimeError: # pragma: no cover - only outside a loop + coro.close() + log.error("no event loop to finish post-exit cleanup on") + return + self._background.add(task) + task.add_done_callback(self._background.discard) + # ------------------------------------------------------------------ # verbs # ------------------------------------------------------------------ @@ -411,11 +816,22 @@ class SessionManager: wait_ready = policy.wait_ready_s if wait_ready_s is None else float(wait_ready_s) session_id = self.registry.new_id(app) + app_id = containers.app_id_for(session_id) + plan = self._create_container(session_id, app_id) try: spawned = self.launcher.spawn( - session_id, full_argv, home=home, ephemeral_home=ephemeral_home + session_id, + full_argv, + home=home, + ephemeral_home=ephemeral_home, + # The stamp the container's window rule matches on. Whether + # the application honours it is read back below, not assumed. + app_id=app_id, ) except (OSError, ValueError) as exc: + # Nothing was launched, so the container has no occupant and must + # not be left behind for the start-up scan to find. + self._discard_unused_container(plan) self.audit.emit("start_failed", app=app, argv=full_argv, reason=str(exc)) raise ManagerError( "refused", f"could not execute {full_argv[0]!r}: {exc}" @@ -443,6 +859,28 @@ class SessionManager: state=State.STARTING, ephemeral_home=ephemeral_home, command_count=1, + container=( + container_record( + output=plan.output, + workspace=plan.workspace, + mode=plan.mode, + created_by="broker", + state=ContainerState.OWNED, + ) + if plan is not None + else container_record( + # Degraded: there is no output, no workspace and no mode, + # and saying so is the point. `null` would mean "this + # session has no container", which is a different claim + # from "the compositor could not be asked". + output=None, + workspace=None, + mode=None, + created_by="broker", + state=ContainerState.DEGRADED, + ) + ), + signature=self.host.signature if plan is not None else None, ) self.registry.add(session) self._exited.pop(session_id, None) @@ -459,6 +897,8 @@ class SessionManager: ) ready = await self._settle(session, wait_ready) + if session.live: + await self._read_back(session, app_id) self.reaper.wake() record = session.public(self.now()) if session.state == State.EXITED: @@ -524,16 +964,18 @@ class SessionManager: record = session.public(self.now()) record["events"] = self.audit.tail(events, session=session.id) record["compositor"] = { - # Enrichment the design calls optional, absent by construction in - # M0: the daemon never speaks the Wayland protocol and never talks - # to Hyprland's IPC. Locating the compositor's socket so a child - # can attach to it (see hhstreamd.compositor) tells us nothing - # about windows, so none of this becomes knowable. - "ipc": "absent", - "window": None, - "workspace": None, - "foreground": None, - "note": "M0 does not talk to the compositor; these are never guessed", + # What the broker knows *now*, not what it knew at launch. The + # three spatial fields are repeated here from the record so a + # caller reading `status` has the compositor's answer and the + # evidence for it in one place; every one of them is `None` when + # the compositor could not be asked, and none is ever guessed. + "ipc": "ok" if self.containers_available else "absent", + "signature": self.host.signature, + "error": None if self.containers_available else self.host.last_error, + "window": session.window, + "workspace": session.workspace, + "foreground": session.foreground, + "container": session.container, } return record @@ -607,15 +1049,16 @@ class SessionManager: if session is None or not session.live: return result = await self.teardown(session, reason="reaped", grace_s=self.config.policy.grace_s) - if result["refused"] or result["survivors"]: + if result["refused"] or result["survivors"] or result["container_survivors"]: # There is no caller to raise at here, so the loudness has to be in # the log and the audit trail. The session is tombstoned either # way, which is what keeps the reaper from spinning on it. log.error( - "reaping %s did not complete: refused=%s survivors=%s", + "reaping %s did not complete: refused=%s survivors=%s container_survivors=%s", session_id, result["refused"], result["survivors"], + result["container_survivors"], ) async def teardown( @@ -711,6 +1154,17 @@ class SessionManager: # a survivor: `refused` is the thing the caller has to hear. survivors = [] if refused else await self._survivors(session) + # The container goes whether or not the process could be signalled: + # an output with nothing in it is still a render target, and + # leaving it behind is exactly what the start-up scan has to clean + # up after a crash. The pointer lease goes too — a dead session + # cannot hold the one cursor. + # "kill" and not the verb's own word: the record's `released_by` + # has four values (lease|timeout|crash|kill), and a reap is the + # broker killing the session. + await self._drop_lease_for(session, reason="kill") + container_result = self._destroy_container(session) + if refused is None: state_now = state else: @@ -738,6 +1192,8 @@ class SessionManager: pgid=session.pgid, refused=refused, survivors=survivors, + container_removed=container_result["container_removed"], + container_survivors=container_result["container_survivors"], identity=verdict.reason or "verified", cmdline_drifted=verdict.cmdline_drifted, idle_s=None if idle_s is None else round(idle_s, 3), @@ -751,6 +1207,7 @@ class SessionManager: ) self.reaper.wake() return { + **container_result, "reason": reason, "signalled": verdict.ok, #: The signal actually delivered, or ``None`` if none was. @@ -850,11 +1307,16 @@ class SessionManager: self.reaper.wake() return session.public(self.now()) - def gc(self) -> dict[str, Any]: + async def gc(self) -> dict[str, Any]: """Prune tombstones and reconcile the table with ``/proc``. Read-only with respect to the idle clock: **``gc`` does not count as activity.** + + Asynchronous because it tombstones sessions, and tombstoning one means + taking its container down and giving the cursor back — and giving the + cursor back means lifting whatever it left pressed, on the driver, + which is a call off the event loop. """ now = self.now() @@ -877,7 +1339,12 @@ class SessionManager: exit_detected_by="gc_proc_scan", last_error=None if why == procmon.GONE else why, ) - entry = {"id": session.id, "why": why} + # `gc` tombstones a session whose process vanished without the + # daemon noticing, so it is also the last chance to take that + # session's container down: nothing else will come back for it. + await self._drop_lease_for(session, reason="kill") + entry = {"id": session.id, "why": why, **self._destroy_container(session)} + self.registry.persist(session, force=True) if verdict.unresolved: entry["mismatched"] = list(verdict.mismatched) unresolved.append(entry) @@ -930,6 +1397,564 @@ class SessionManager: pruned += 1 return pruned + # ------------------------------------------------------------------ + # container verbs + # ------------------------------------------------------------------ + + def container_list(self) -> dict[str, Any]: + """Every container this broker believes in, and every one it does not. + + Read-only, and **does not** count as activity. ``orphans`` are + ``hh-*`` outputs the compositor has that no live session claims: the + thing the start-up scan removes, listed rather than acted on, because + a verb that deleted outputs as a side effect of being asked for a list + would be a trap. + """ + + claimed: dict[str, str] = {} + rows: list[dict[str, Any]] = [] + for session in self.registry.live(): + container = session.container + if container is None: + continue + output = container.get("output") + if output: + claimed[output] = session.id + rows.append( + { + "id": session.id, + "app": session.app, + **container, + "window": session.window, + "foreground": session.foreground, + } + ) + orphans: list[str] | None = [] + error: str | None = None + if self.containers_available: + try: + orphans = [name for name in self.host.our_outputs() if name not in claimed] + except CompositorUnavailable as exc: + # `[]` here would read as "no orphans", which is a claim we + # cannot make without having looked. + orphans = None + error = str(exc) + else: + orphans = None + error = self.host.last_error or "no compositor IPC" + return { + "containers": rows, + "orphans": orphans, + "compositor": "ok" if self.containers_available else "absent", + "error": error, + "workspaces_in_use": self.host.allocator.in_use(), + } + + async def container_reconcile(self, session_id: str | None = None) -> dict[str, Any]: + """Re-read one session's container from the compositor, or all of them. + + Returns the container as it now stands and a ``diff``: every field + whose recorded value disagreed with what the compositor reports, with + both values. The record is updated to the compositor's answer, which + is the only direction this can go — the compositor is the authority on + where a window is, and the record is a cache of it. + """ + + if session_id is None: + summary = self.reconcile_containers() + diffs = [] + for session in self.registry.live(): + diffs.extend(await self._reconcile_one(session)) + return {"container": None, "diff": diffs, "scan": summary} + session = self._require(session_id) + diff = await self._reconcile_one(session) + return {"id": session.id, "container": session.container, "diff": diff} + + async def _reconcile_one(self, session: Session) -> list[dict[str, Any]]: + if session.container is None or not self.containers_available: + return [] + app_id = containers.app_id_for(session.id) + try: + facts = self.host.read_back(app_id, session.pid) + except CompositorUnavailable as exc: + self.containers_available = False + return [{"id": session.id, "field": "compositor", "error": str(exc)}] + observed = { + "workspace": None if facts is None else facts.workspace, + "window": None if facts is None else facts.window, + "foreground": None if facts is None else facts.foreground, + } + diff = [ + {"id": session.id, "field": field, "recorded": getattr(session, field), "observed": value} + for field, value in observed.items() + if getattr(session, field) != value + ] + session.workspace = observed["workspace"] + session.window = observed["window"] + session.foreground = observed["foreground"] + self.registry.persist(session, force=True) + return diff + + def _discard_unused_container(self, plan: containers.ContainerPlan | None) -> None: + """Undo a container whose application never started.""" + + if plan is None: + return + self.host.release(plan.workspace) + try: + self.host.remove(plan.output) + except (CompositorUnavailable, ValueError) as exc: # pragma: no cover - rare + log.error("could not remove the unused output %s: %s", plan.output, exc) + + # ------------------------------------------------------------------ + # the pointer lease + # ------------------------------------------------------------------ + + async def pointer_acquire( + self, session_id: str, *, ttl_s: float | None = None, restore: bool = True + ) -> dict[str, Any]: + """Take the one cursor for this session and aim it into its container. + + **Does not** count as activity (PLAN §8.3): a session being driven is + still a session nobody has said they want kept. + + ``restore`` warps to the bookmark the session was left at, which is + what makes a gesture resumable across two leases; with no bookmark — + or one belonging to an output this session no longer has — the cursor + goes to the container's centre, which is the only other defensible + place. + """ + + session = self._require_live(session_id) + await self._expire_pointer() + output = self._pointer_output(session) + ttl = self._checked_ttl(ttl_s) + if ttl is not None: + # Before `acquire`, which is where the deadline is computed: the + # frozen `acquire(session_id)` takes no TTL, so a caller's ttl_s + # can only be applied to the lease object, for the life of this + # lease, and taken back when it ends. Reported as a contract gap. + self.pointer.ttl_s = ttl + self._pointer_ttl_override = True + try: + lease_id = self.pointer.acquire(session.id) + except LeaseBusy as exc: + self._restore_default_ttl() + raise ManagerError( + "pointer_busy", + f"the pointer is held by {exc.holder}", + hint="wait for the holder to release it, or let its lease time out", + **self.pointer.state(), + ) from exc + bookmark = self._restore_point(session, output) if restore else None + x, y = (bookmark["x"], bookmark["y"]) if bookmark else (0.5, 0.5) + try: + await self._warp(output, x, y) + except ManagerError: + # Never hold a lease we could not aim: the next verb would move a + # cursor that is somewhere else entirely. + self._force_release(session, "driver_lost") + raise + mark = self._mark(session, lease_id, output, x, y) + self.audit.emit( + "pointer_acquired", + session=session.id, + lease_id=lease_id, + output=output, + restored=bool(bookmark), + ttl_s=self.pointer.ttl_s, + ) + return { + "id": session.id, + "lease_id": lease_id, + "bookmark": mark, + "expires_in_s": self.pointer.ttl_s, + } + + async def pointer_move( + self, + session_id: str, + lease_id: str, + *, + x: Any = None, + y: Any = None, + dx: Any = None, + dy: Any = None, + ) -> dict[str, Any]: + """Warp within the session's own output. + + Coordinates are **normalised 0..1, output-local** (PLAN §6.3) — the + frame ``motion_absolute`` already speaks, so nothing is converted on + the way in and the value survives the output being resized. ``x``/``y`` + are absolute and refused outside the range, because a caller that + computed 1.4 has a bug and clamping would hide it; ``dx``/``dy`` are + relative and *are* clamped, because running into the edge of the + screen is what a mouse does. + """ + + session, output = await self._refresh(session_id, lease_id) + if x is not None or y is not None: + if dx is not None or dy is not None: + raise ManagerError("invalid_argument", "pass either x/y or dx/dy, not both") + target = (_unit(x, "x"), _unit(y, "y")) + elif dx is not None or dy is not None: + base = self._restore_point(session, output) or {"x": 0.5, "y": 0.5} + target = ( + _clamp(base["x"] + _number(dx or 0.0, "dx")), + _clamp(base["y"] + _number(dy or 0.0, "dy")), + ) + else: + raise ManagerError("invalid_argument", "pointer.move needs x/y or dx/dy") + await self._warp(output, *target) + # The bookmark is written on *every* move, so a broker that dies + # mid-gesture still leaves the last real position behind (PLAN §6.2). + mark = self._mark(session, lease_id, output, *target) + return {"id": session.id, "bookmark": mark} + + async def pointer_button( + self, session_id: str, lease_id: str, button: Any, state: Any + ) -> dict[str, Any]: + session, output = await self._refresh(session_id, lease_id) + name = _button_name(button) + if state not in ("down", "up"): + raise ManagerError("invalid_argument", f"button state must be 'down' or 'up', got {state!r}") + # The driver first, then the lease's mirror of it: if the driver + # refuses, the lease must not claim a button went down that did not. + # The reverse mistake is harmless — `release_all` lifts what the + # *driver* recorded, and that is the set the compositor saw. + await self._drive("button", name, state) + await self._drive("frame") + if state == "down": + self.pointer.press(session.id, name) + else: + self.pointer.unpress(session.id, name) + self.audit.emit("pointer_button", session=session.id, button=name, state=state) + return {"id": session.id, "buttons": self.pointer.pressed()} + + async def pointer_click( + self, session_id: str, lease_id: str, button: Any = "left", count: Any = 1 + ) -> dict[str, Any]: + session, output = await self._refresh(session_id, lease_id) + name = _button_name(button if button is not None else "left") + times = _checked_count(count) + for _ in range(times): + await self._drive("button", name, "down") + await self._drive("frame") + self.pointer.press(session.id, name) + await self._drive("button", name, "up") + await self._drive("frame") + self.pointer.unpress(session.id, name) + self.audit.emit("pointer_click", session=session.id, button=name, count=times) + return { + "id": session.id, + "button": name, + "count": times, + "bookmark": self._restore_point(session, output), + } + + async def pointer_release(self, session_id: str, lease_id: str) -> dict[str, Any]: + """Give the cursor back, leaving nothing pressed and a bookmark behind.""" + + session = self._require(session_id) + # Checked *before* anything reaches the driver: otherwise a release + # quoting someone else's lease would lift the holder's buttons on the + # way to being refused. + state = self.pointer.state() + if state["holder"] != session.id or state["lease_id"] != lease_id: + raise ManagerError( + "no_lease", + f"{session.id} does not hold the pointer", + hint="pointer.state names the holder", + **state, + ) + output = self._pointer_output(session, required=False) + here = self._restore_point(session, output) + if here is not None and output is not None: + # Marked before release, so `LeaseOutcome.bookmark` carries the + # position even for a lease that never moved (PLAN §6.2). + mark = _bookmark(output, here["x"], here["y"], here["at"]) + with contextlib.suppress(LeaseInvalid): + self.pointer.mark(session.id, lease_id, mark) + try: + lifted = await self._release_all_buttons() + except ManagerError: + # The driver is gone, so the cursor's state is unknown — and + # holding a lease over an unknown cursor helps nobody. Drop it + # and let the caller hear why. + self._force_release(session, "crash") + raise + try: + outcome = self.pointer.release(session.id, lease_id, "lease") + except LeaseInvalid as exc: + raise ManagerError("no_lease", str(exc), **self.pointer.state()) from exc + self._restore_default_ttl() + released_at = self._stamp_release(session, "lease") + self.audit.emit( + "pointer_released", + session=session.id, + reason=outcome.reason, + buttons_lifted=lifted, + ) + return { + "id": session.id, + "bookmark": (session.pointer or {}).get("bookmark"), + "released_by": "lease", + "released_at": released_at, + "buttons_lifted": lifted, + } + + def pointer_state(self) -> dict[str, Any]: + """Who holds the cursor. Read-only; **does not** count as activity.""" + + state = self.pointer.state() + holder = state["holder"] + session = self.registry.get(holder) if holder else None + return { + **state, + "buttons": self.pointer.pressed(), + "bookmark": None if session is None else (session.pointer or {}).get("bookmark"), + "driver": None if self.config.pointer_socket is None else str(self.config.pointer_socket), + } + + # -- lease internals -------------------------------------------------- + + async def _sweep_pointer(self) -> None: + """Expire a stale lease even when nobody asks. + + Without this the lease would only ever be checked by the next pointer + verb, so an agent that acquired, pressed a button and died would hold + the cursor — with the button down — until someone else happened to + try. The sweep is what makes the TTL a promise. + """ + + while True: + await asyncio.sleep(self.config.pointer_sweep_s) + try: + await self._expire_pointer() + except Exception: # pragma: no cover - a sweep must never die + log.exception("the pointer expiry sweep failed") + + async def _expire_pointer(self) -> dict[str, Any] | None: + """Force-release a lease past its TTL or hard cap, lifting its buttons. + + The order is the contract's (§3.3) and it is not interchangeable: + ``pressed()`` is read **before** ``expire()``, because ``expire()`` + drops the lease and its button set with it, and ``release_all`` on the + driver is what actually ungrabs the mouse — the lease cannot lift + anything itself. + """ + + state = self.pointer.state() + holder = state["holder"] + if holder is None: + return None + pressed = self.pointer.pressed() + info = self.pointer.expire() + if info is None: + return None + self._restore_default_ttl() + hard = self.clock.boottime() >= info.hard_deadline + lifted: list[str] = [] + try: + lifted = await self._release_all_buttons() + except ManagerError as exc: + # Loud: a button is down and we could not lift it. There is no + # caller to raise at, so the log and the audit trail are the alarm. + log.error( + "pointer lease for %s expired with %s pressed and the driver " + "unreachable (%s): a button may still be down", + holder, + pressed or "nothing", + exc.reason, + ) + session = self.registry.get(holder) + if session is not None: + self._stamp_release(session, "timeout") + self.audit.emit( + "pointer_lease_timeout", + session=holder, + lease_id=info.lease_id, + hard_cap=hard, + pressed=pressed, + buttons_lifted=lifted, + ) + log.warning( + "pointer lease for %s expired (%s); lifted %s", + holder, + "hard cap" if hard else "idle ttl", + lifted or "nothing", + ) + return {"session": holder, "lease_id": info.lease_id, "buttons_lifted": lifted} + + async def _refresh(self, session_id: Any, lease_id: Any) -> tuple[Session, str]: + """The gate every gesture verb goes through: live, holder, not expired.""" + + session = self._require_live(session_id) + await self._expire_pointer() + if not isinstance(lease_id, str) or not lease_id: + raise ManagerError("invalid_argument", "a lease_id is required") + try: + self.pointer.refresh(session.id, lease_id) + except LeaseInvalid as exc: + raise ManagerError( + "no_lease", + f"{session.id} does not hold the pointer: {exc}", + hint="acquire the lease first with pointer.acquire", + **self.pointer.state(), + ) from exc + return session, self._pointer_output(session) + + def _pointer_output(self, session: Session, *, required: bool = True) -> str | None: + """The output a pointer verb aims at: the session's own container. + + Refused rather than defaulted: aiming at "wherever the cursor is" is + how a click lands in another session's window, which is the whole + thing containers and the lease exist to prevent. + """ + + output = (session.container or {}).get("output") + if output: + return output + if not required: + return None + raise ManagerError( + "no_container", + f"session {session.id} has no container output to aim at", + hint="the compositor was unreachable when this session started; " + "`container.reconcile` once it is back", + id=session.id, + container=session.container, + ) + + def _restore_point(self, session: Session, output: str | None) -> dict[str, Any] | None: + """This session's bookmark, if it belongs to the output we are aiming at.""" + + bookmark = (session.pointer or {}).get("bookmark") + if not isinstance(bookmark, dict): + return None + if output is not None and bookmark.get("output") != output: + # A bookmark from a container this session no longer has is not a + # position in the one it does have. + return None + return bookmark + + def _mark( + self, session: Session, lease_id: str, output: str, x: float, y: float + ) -> dict[str, Any]: + """Record where the cursor now is, in the lease *and* in the record. + + Both, because they answer different questions: the lease's copy is + what ``release`` reports, and the record's is what survives the broker + restarting and is what ``pointer.acquire --restore`` reads. + """ + + at = iso(self.clock.wall()) + with contextlib.suppress(LeaseInvalid): + self.pointer.mark(session.id, lease_id, _bookmark(output, x, y, at)) + mark = {"x": x, "y": y, "output": output, "at": at} + previous = session.pointer or {} + session.pointer = pointer_record( + bookmark=mark, + last_released_at=previous.get("last_released_at"), + released_by=previous.get("released_by"), + ) + self.registry.persist(session, force=True) + return mark + + def _stamp_release(self, session: Session, released_by: str) -> str: + at = iso(self.clock.wall()) + previous = session.pointer or {} + session.pointer = pointer_record( + bookmark=previous.get("bookmark"), + last_released_at=at, + released_by=released_by, + ) + self.registry.persist(session, force=True) + return at + + def _force_release(self, session: Session, released_by: str) -> None: + """Drop the lease without talking to the driver. Used when it is gone.""" + + state = self.pointer.state() + if state["holder"] != session.id: + return + with contextlib.suppress(LeaseInvalid): + self.pointer.release(session.id, state["lease_id"], released_by) + self._restore_default_ttl() + self._stamp_release(session, released_by) + + async def _drop_lease_for(self, session: Session, reason: str) -> None: + """Release the lease a dying session holds, lifting anything down.""" + + if self.pointer.state()["holder"] != session.id: + return + with contextlib.suppress(ManagerError): + await self._release_all_buttons() + self._force_release(session, reason) + + def _checked_ttl(self, ttl_s: Any) -> float | None: + if ttl_s is None: + return None + value = _number(ttl_s, "ttl_s") + if value <= 0: + raise ManagerError("invalid_argument", "ttl_s must be positive") + if value > self.config.pointer_max_s: + raise ManagerError( + "invalid_argument", + f"ttl_s {value:g}s exceeds the lease's hard cap of " + f"{self.config.pointer_max_s:g}s", + ) + return value + + def _restore_default_ttl(self) -> None: + if self._pointer_ttl_override: + self.pointer.ttl_s = self.config.pointer_ttl_s + self._pointer_ttl_override = False + + # -- the driver ------------------------------------------------------- + + def _pointer_driver(self) -> PointerDriver: + if self.driver is None: + if self.config.pointer_socket is None: + raise ManagerError( + "driver_unavailable", + "no pointer driver socket is configured", + hint="start hhstream-pointer and point the broker at its socket", + ) + self.driver = PointerDriver(self.config.pointer_socket) + return self.driver + + async def _drive(self, verb: str, *args: Any) -> Any: + """One driver call, off the event loop. + + ``asyncio.to_thread`` because the driver is a separate process + precisely so that a blocked one does not stall session lifecycle + (PLAN §6.5); calling it inline would give that back. The driver + client holds its own lock, so one request is on the wire at a time + however many verbs are in flight. + """ + + driver = self._pointer_driver() + try: + return await asyncio.to_thread(getattr(driver, verb), *args) + except DriverRejected as exc: + raise ManagerError("driver_refused", f"the pointer driver refused {verb}: {exc}") from exc + except DriverUnavailable as exc: + raise ManagerError( + "driver_unavailable", f"the pointer driver is unreachable: {exc}" + ) from exc + + async def _warp(self, output: str, x: float, y: float) -> None: + await self._drive("warp", output, x, y) + # Nothing the driver was sent reaches the compositor until a frame. + await self._drive("frame") + + async def _release_all_buttons(self) -> list[str]: + """Lift everything on the driver. The driver's set is the real one.""" + + lifted = await self._drive("release_all") + return list(lifted) + def logs(self, session_id: str, *, lines: int = 100, offset: int | None = None) -> dict[str, Any]: """The daemon's capture of the app's stdout/stderr. @@ -998,3 +2023,61 @@ def _signal_number(sig: str | int) -> int: f"unknown signal: {sig!r}", hint=f"one of {', '.join(sorted(set(SIGNALS_BY_NAME)))}", ) + + +def _compositor_runtime_dir(config: ManagerConfig) -> Path | None: + """Where ``hypr//`` lives, from the configuration we already have. + + ``--compositor-runtime-dir`` names the compositor's runtime directory, and + that is the same directory the instance sockets live under + (CONTRACT-sessions.md §5), so a daemon configured to launch applications + into a compositor needs no second flag to talk to it. + """ + + if config.compositor_runtime_dir is not None: + return Path(config.compositor_runtime_dir) + if config.compositor is not None: + return Path(config.compositor.session.runtime_dir) + return None + + +def _bookmark(output: str, x: float, y: float, at: str) -> Bookmark: + return Bookmark(x=float(x), y=float(y), output=output, at=at) + + +def _number(value: Any, label: str) -> float: + # bool is an int in Python, and `True` would silently become 1.0. + if isinstance(value, bool) or not isinstance(value, (int, float)): + raise ManagerError("invalid_argument", f"{label} must be a number, got {value!r}") + return float(value) + + +def _unit(value: Any, label: str) -> float: + number = _number(value, label) + if not 0.0 <= number <= 1.0: + raise ManagerError( + "invalid_argument", + f"{label} is {number:g}, outside 0..1 — pointer coordinates are " + "normalised and output-local", + ) + return number + + +def _clamp(value: float) -> float: + return min(1.0, max(0.0, value)) + + +def _button_name(value: Any) -> str: + if not isinstance(value, str) or not value: + raise ManagerError("invalid_argument", f"button must be a name, got {value!r}") + return value + + +def _checked_count(value: Any) -> int: + if isinstance(value, bool) or not isinstance(value, int): + raise ManagerError("invalid_argument", f"count must be an integer, got {value!r}") + if not 1 <= value <= MAX_CLICK_COUNT: + raise ManagerError( + "invalid_argument", f"count must be between 1 and {MAX_CLICK_COUNT}, got {value}" + ) + return value diff --git a/src/hhstreamd/protocol.py b/src/hhstreamd/protocol.py index f6ba66a..9f0f05f 100644 --- a/src/hhstreamd/protocol.py +++ b/src/hhstreamd/protocol.py @@ -9,6 +9,7 @@ rest of ``hhstreamd``. from __future__ import annotations +import collections import enum import json from typing import Any @@ -48,6 +49,14 @@ class ExitCode(enum.IntEnum): POLICY = 6 TIMEOUT = 7 BUSY = 8 + #: The verb needs the pointer lease and this session does not hold it. + #: Distinct from BUSY, which is "someone else holds it": an agent that + #: sees 9 must acquire, one that sees 8 must wait. + NO_LEASE = 9 + #: An IPC or output operation failed. **The session is not lost** — it + #: keeps running in degraded mode — so this must never be confused with a + #: session failure, which is what a shared code would do. + COMPOSITOR = 10 #: Machine-readable error names, grouped by the exit code they map to. Every @@ -80,6 +89,9 @@ EXIT_CODE_FOR_ERROR: dict[str, ExitCode] = { "not_allowlisted": ExitCode.POLICY, "argument_refused": ExitCode.POLICY, "session_cap_reached": ExitCode.POLICY, + # The workspace band is full. A policy refusal and not a compositor + # failure: the compositor is fine, the broker is at its budget. + "container_budget": ExitCode.POLICY, "refused": ExitCode.POLICY, # 7 — timed out "timeout": ExitCode.TIMEOUT, @@ -87,6 +99,15 @@ EXIT_CODE_FOR_ERROR: dict[str, ExitCode] = { # 8 — busy "busy": ExitCode.BUSY, "already_managed": ExitCode.BUSY, + "pointer_busy": ExitCode.BUSY, + # 9 — the lease is required and not held + "no_lease": ExitCode.NO_LEASE, + # 10 — the compositor side failed; the session itself is fine + "compositor": ExitCode.COMPOSITOR, + "compositor_unavailable": ExitCode.COMPOSITOR, + "no_container": ExitCode.COMPOSITOR, + "driver_unavailable": ExitCode.COMPOSITOR, + "driver_refused": ExitCode.COMPOSITOR, } @@ -103,6 +124,99 @@ def exit_code_for(error: str | None) -> ExitCode: return EXIT_CODE_FOR_ERROR.get(error, ExitCode.BAD_STATE) +# -------------------------------------------------------------------------- +# Verbs and `request_id` idempotency (PLAN §8) +# -------------------------------------------------------------------------- + +#: Every verb the daemon answers. The container and pointer verbs are dotted +#: and the original eight are not, because the original eight are frozen +#: (CONTRACT-sessions.md §4: "existing verbs are unchanged") and renaming them +#: would break every agent for a cosmetic gain. +VERBS = ( + "ping", + "start", + "list", + "status", + "touch", + "kill", + "gc", + "adopt", + "logs", + "container.list", + "container.reconcile", + "pointer.acquire", + "pointer.move", + "pointer.button", + "pointer.click", + "pointer.release", + "pointer.state", +) + +#: Verbs whose reply is remembered by ``request_id``, so a caller that died +#: before reading the reply can retry without the mutation happening twice. +#: +#: The read verbs are absent deliberately: they are idempotent already, so a +#: retry costs nothing, and a cached ``list`` would be a stale one. Every +#: ``pointer.*`` verb that moves something is here, because a retried click is +#: a second click — the one failure an agent cannot undo. +MUTATING_VERBS = frozenset( + { + "start", + "touch", + "kill", + "adopt", + "gc", + "container.reconcile", + "pointer.acquire", + "pointer.move", + "pointer.button", + "pointer.click", + "pointer.release", + } +) + +#: How many completed replies are kept. Bounded because a client chooses the +#: ids: an unbounded cache is memory a peer controls. +DEDUP_ENTRIES = 64 + + +class IdempotencyCache: + """The last N mutating replies, by ``request_id``. + + A retry returns *the recorded answer*, including a recorded failure: an + agent that retries a ``start`` which was refused by policy must see the + refusal again, not a second attempt that might succeed and leave it with + an application it has no id for. Replies are returned with + ``deduplicated: true`` so the caller can tell a replay from a fresh answer + rather than having to infer it. + """ + + def __init__(self, capacity: int = DEDUP_ENTRIES) -> None: + self.capacity = capacity + self._entries: collections.OrderedDict[str, dict[str, Any]] = collections.OrderedDict() + + def lookup(self, op: str, request_id: Any) -> dict[str, Any] | None: + """The recorded reply for this id, or ``None`` to go ahead and do it.""" + + if not isinstance(request_id, str) or op not in MUTATING_VERBS: + return None + recorded = self._entries.get(request_id) + if recorded is None: + return None + return {**recorded, "deduplicated": True} + + def remember(self, op: str, request_id: Any, response: dict[str, Any]) -> None: + if not isinstance(request_id, str) or op not in MUTATING_VERBS: + return + self._entries[request_id] = dict(response) + self._entries.move_to_end(request_id) + while len(self._entries) > self.capacity: + self._entries.popitem(last=False) + + def __len__(self) -> int: + return len(self._entries) + + # -------------------------------------------------------------------------- # Message construction # -------------------------------------------------------------------------- diff --git a/src/hhstreamd/registry.py b/src/hhstreamd/registry.py index 92198a0..41770b4 100644 --- a/src/hhstreamd/registry.py +++ b/src/hhstreamd/registry.py @@ -22,7 +22,12 @@ from .clock import Clock, iso log = logging.getLogger("hhstreamd.registry") -SCHEMA = 2 +#: 3 adds the container, the pointer bookmark and the compositor signature +#: (PLAN §7). The number is read, never written by anyone but this module: a +#: record carrying an older one is **migrated on load** (:func:`migrate`), not +#: refused, because the processes it describes are still running and refusing +#: the record would strand them. +SCHEMA = 3 #: Tombstones survive this long so a ``status`` after an unexplained failure #: still answers the question. ``gc`` prunes them. @@ -34,6 +39,28 @@ DEFAULT_TOMBSTONE_TTL_S = 3600.0 ACTIVITY_FLUSH_INTERVAL_S = 15.0 +class ContainerState: + """What the broker knows about a session's spatial container. + + These are the only four answers. ``container: null`` is a fifth and + different thing — "this session has no container at all" — and nothing here + means "probably something": a field the compositor did not confirm stays + ``None`` (PLAN §7). + """ + + #: Created by us, and the compositor still shows the output. + OWNED = "owned" + #: No IPC, so nothing was created and nothing can be verified. The session + #: still starts, stops and is reaped by process identity (PLAN §4.4). + DEGRADED = "degraded" + #: Torn down on purpose: the output was removed and the slot released. + REMOVED = "removed" + #: The record and the compositor disagree — the output we recorded is not + #: there, or an output of ours has no live session. Never deleted on a + #: guess; reconciliation decides. + ORPHAN = "orphan" + + class State: STARTING = "starting" READY = "ready" @@ -102,6 +129,19 @@ class Session: workspace: int | None = None window: Any = None foreground: bool | None = None + #: ``{output, workspace, mode, created_by, state}`` or ``None`` for "no + #: container". A dict rather than a nested dataclass because + #: :meth:`to_dict` is ``asdict`` and :meth:`from_dict` is ``cls(**data)``: + #: a dataclass would serialise and come back as a dict anyway, and the + #: asymmetry is where a half-migrated record would hide. + container: dict[str, Any] | None = None + #: ``{bookmark, last_released_at, released_by}``. Absent (``None``) means + #: the pointer was never aimed here — not that its position is unknown. + pointer: dict[str, Any] | None = None + #: ``HYPRLAND_INSTANCE_SIGNATURE`` of the compositor this session's + #: container lives in, so a restarted broker re-attaches to the same + #: instance instead of picking whichever one is there now. + signature: str | None = None command_count: int = 0 exit_code: int | None = None exit_detected_by: str | None = None @@ -147,6 +187,7 @@ class Session: @classmethod def from_dict(cls, data: dict[str, Any]) -> "Session": + data = migrate(data) known = {f for f in cls.__dataclass_fields__} unknown = set(data) - known if unknown: @@ -168,6 +209,88 @@ class Session: return data +def container_record( + *, + output: str | None, + workspace: int | None, + mode: tuple[int, int] | None, + created_by: str, + state: str, +) -> dict[str, Any]: + """One ``container`` sub-record (PLAN §7). + + Every argument is explicit and may be ``None`` because the degraded case is + the common one: there is a container *state* to report long before there is + an output to name, and the alternative — leaving the key out — would read + as "no container" when what we mean is "a container we could not verify". + """ + + return { + "output": output, + "workspace": workspace, + "mode": None if mode is None else {"width": mode[0], "height": mode[1]}, + "created_by": created_by, + "state": state, + } + + +def pointer_record( + *, + bookmark: dict[str, Any] | None, + last_released_at: str | None, + released_by: str | None, +) -> dict[str, Any]: + """One ``pointer`` sub-record: where the cursor was left, and by what. + + Written on every move and on release. A session that has one has been + aimed at; a session that has none never was. + """ + + return { + "bookmark": bookmark, + "last_released_at": last_released_at, + "released_by": released_by, + } + + +def migrate(data: dict[str, Any]) -> dict[str, Any]: + """Bring a record read from disk up to :data:`SCHEMA`. + + A schema-2 record is **adopted, not rejected**: its application is very + likely still running, and the daemon that wrote it knew nothing of + containers, so the honest value for every field schema 3 added is ``None`` + — "no container", "the pointer was never used here", "we do not know which + compositor instance this was". Each of those is a defined value, which is + the whole reason the migration can be this short. + + A record from a *newer* schema is left alone and loudly logged: the fields + this daemon does not know are dropped by :meth:`Session.from_dict`, and + guessing at what a future version meant would be worse than running with + the subset we understand. + """ + + schema = data.get("schema") + if schema == SCHEMA: + return data + if isinstance(schema, int) and schema > SCHEMA: + log.error( + "record %s is schema %s, newer than this daemon's %s; reading the fields " + "this version knows and leaving the rest", + data.get("id"), + schema, + SCHEMA, + ) + return data + upgraded = dict(data) + # Only ever *adds* keys. A v2 record that somehow carries a container must + # keep it: the field is new to the schema, not new to the session. + for key in ("container", "pointer", "signature"): + upgraded.setdefault(key, None) + upgraded["schema"] = SCHEMA + log.info("migrated record %s from schema %s to %s", data.get("id"), schema, SCHEMA) + return upgraded + + def mint_id(app: str, taken: set[str], *, rng: Any = secrets) -> str: """``-<6 base32 chars>`` (DESIGN.md §2.2). diff --git a/src/hhstreamd/server.py b/src/hhstreamd/server.py index acaf348..755c583 100644 --- a/src/hhstreamd/server.py +++ b/src/hhstreamd/server.py @@ -13,7 +13,6 @@ This module is framing and dispatch only. Every decision lives in from __future__ import annotations import asyncio -import collections import contextlib import logging import os @@ -35,14 +34,9 @@ DEFAULT_REQUEST_TIMEOUT_S = 5.0 #: A `kill` may legitimately take `grace` seconds, so it gets its own budget. KILL_TIMEOUT_MARGIN_S = 5.0 -#: Replies to mutating verbs are remembered so a CLI that died before reading -#: the reply can retry without launching a second application. -DEDUP_ENTRIES = 64 - -#: Verbs whose replies are cached by `request_id`. The read verbs are absent -#: deliberately: they are idempotent, so a retry costs nothing and a cached -#: `list` would be a stale one. -MUTATING_VERBS = frozenset({"start", "touch", "kill", "adopt", "gc"}) +#: `request_id` idempotency lives in `protocol` (which verbs mutate, how many +#: replies are kept, what a replay looks like) because the CLI has to agree +#: with it and the CLI imports that module and not this one. class ControlServer: @@ -59,7 +53,7 @@ class ControlServer: self.request_timeout_s = request_timeout_s self.socket_mode = socket_mode self._server: asyncio.AbstractServer | None = None - self._dedup: collections.OrderedDict[str, dict[str, Any]] = collections.OrderedDict() + self._dedup = protocol.IdempotencyCache() self._ops: dict[str, Callable[[dict[str, Any], dict[str, Any]], Awaitable[dict[str, Any]]]] = { "ping": self._op_ping, "start": self._op_start, @@ -70,6 +64,14 @@ class ControlServer: "gc": self._op_gc, "adopt": self._op_adopt, "logs": self._op_logs, + "container.list": self._op_container_list, + "container.reconcile": self._op_container_reconcile, + "pointer.acquire": self._op_pointer_acquire, + "pointer.move": self._op_pointer_move, + "pointer.button": self._op_pointer_button, + "pointer.click": self._op_pointer_click, + "pointer.release": self._op_pointer_release, + "pointer.state": self._op_pointer_state, } # ------------------------------------------------------------------ @@ -188,9 +190,8 @@ class ControlServer: "unknown_op", f"unknown op {op!r}", hint=f"known: {', '.join(sorted(self._ops))}" ) - if isinstance(request_id, str) and op in MUTATING_VERBS and request_id in self._dedup: - cached = dict(self._dedup[request_id]) - cached["deduplicated"] = True + cached = self._dedup.lookup(op, request_id) + if cached is not None: return cached timeout = self.request_timeout_s @@ -224,8 +225,7 @@ class ControlServer: response.setdefault("elapsed_ms", elapsed_ms) if isinstance(request_id, str): response["request_id"] = request_id - if op in MUTATING_VERBS: - self._remember(request_id, response) + self._dedup.remember(op, request_id, response) self.manager.audit.emit( "request", @@ -239,12 +239,6 @@ class ControlServer: ) return response - def _remember(self, request_id: str, response: dict[str, Any]) -> None: - self._dedup[request_id] = dict(response) - self._dedup.move_to_end(request_id) - while len(self._dedup) > DEDUP_ENTRIES: - self._dedup.popitem(last=False) - # ------------------------------------------------------------------ # ops # ------------------------------------------------------------------ @@ -290,7 +284,7 @@ class ControlServer: return protocol.ok(id=record["id"], state=record["state"], session=record) async def _op_gc(self, request: dict[str, Any], caller: dict[str, Any]) -> dict[str, Any]: - return protocol.ok(**self.manager.gc()) + return protocol.ok(**await self.manager.gc()) async def _op_adopt(self, request: dict[str, Any], caller: dict[str, Any]) -> dict[str, Any]: record = await self.manager.adopt( @@ -300,6 +294,80 @@ class ControlServer: ) return protocol.ok(id=record["id"], state=record["state"], session=record) + async def _op_container_list( + self, request: dict[str, Any], caller: dict[str, Any] + ) -> dict[str, Any]: + return protocol.ok(**self.manager.container_list()) + + async def _op_container_reconcile( + self, request: dict[str, Any], caller: dict[str, Any] + ) -> dict[str, Any]: + return protocol.ok(**await self.manager.container_reconcile(request.get("id"))) + + async def _op_pointer_acquire( + self, request: dict[str, Any], caller: dict[str, Any] + ) -> dict[str, Any]: + return protocol.ok( + **await self.manager.pointer_acquire( + request.get("id"), + ttl_s=request.get("ttl_s"), + # Restoring is the default: the bookmark exists so a gesture + # can be picked up where it was left, and a caller that wants + # the centre of the output says so. + restore=bool(request.get("restore", True)), + ) + ) + + async def _op_pointer_move( + self, request: dict[str, Any], caller: dict[str, Any] + ) -> dict[str, Any]: + return protocol.ok( + **await self.manager.pointer_move( + request.get("id"), + request.get("lease_id"), + x=request.get("x"), + y=request.get("y"), + dx=request.get("dx"), + dy=request.get("dy"), + ) + ) + + async def _op_pointer_button( + self, request: dict[str, Any], caller: dict[str, Any] + ) -> dict[str, Any]: + return protocol.ok( + **await self.manager.pointer_button( + request.get("id"), + request.get("lease_id"), + request.get("button"), + request.get("state"), + ) + ) + + async def _op_pointer_click( + self, request: dict[str, Any], caller: dict[str, Any] + ) -> dict[str, Any]: + return protocol.ok( + **await self.manager.pointer_click( + request.get("id"), + request.get("lease_id"), + request.get("button", "left"), + request.get("count", 1), + ) + ) + + async def _op_pointer_release( + self, request: dict[str, Any], caller: dict[str, Any] + ) -> dict[str, Any]: + return protocol.ok( + **await self.manager.pointer_release(request.get("id"), request.get("lease_id")) + ) + + async def _op_pointer_state( + self, request: dict[str, Any], caller: dict[str, Any] + ) -> dict[str, Any]: + return protocol.ok(**self.manager.pointer_state()) + async def _op_logs(self, request: dict[str, Any], caller: dict[str, Any]) -> dict[str, Any]: return protocol.ok( **self.manager.logs( diff --git a/tests/containers/test_plan.py b/tests/containers/test_plan.py index 0a77c0e..d13c4b8 100644 --- a/tests/containers/test_plan.py +++ b/tests/containers/test_plan.py @@ -16,7 +16,7 @@ from hhstreamd.containers import ( contains_output, container_plan, output_name, - quarantine_plan, + quarantine_argv, ) @@ -193,11 +193,12 @@ def test_an_app_id_that_could_forge_a_rule_field_is_refused(bad: str) -> None: assert "[A-Za-z0-9._+-]" in str(exc.value) -def test_quarantine_plan_is_the_catch_all_keyword() -> None: - plan = quarantine_plan("special:quarantine") +def test_quarantine_argv_is_the_catch_all_keyword() -> None: + argv = quarantine_argv("special:quarantine") - assert plan is not None - assert plan.create == [ + # Bare argv lists, not a ContainerPlan: a quarantine rule has no output, + # no numbered workspace and no mode to put in one (CONTRACT v2 §3.2). + assert argv == [ [ "hyprctl", "keyword", @@ -205,19 +206,33 @@ def test_quarantine_plan_is_the_catch_all_keyword() -> None: "match:initial_class .*, workspace special:quarantine", ] ] - # A rule, not a container: nothing to remove, no output, no mode. - assert plan.teardown == [] - assert (plan.output, plan.workspace, plan.mode) == ("", 0, (0, 0)) + + +def test_the_quarantine_rule_matches_what_a_container_rule_does_not() -> None: + """The backstop and a container rule must not be able to collide. + + The catch-all is what every unplaced window hits, so it has to be the same + shape as a per-session rule with a wider match — otherwise the two are + evaluated differently and the ordering the caller gets right stops + mattering. + """ + + (backstop,) = quarantine_argv("special:quarantine") + container = container_plan("x1", 1000, 1280, 720, "hh-x1").create[2] + + assert backstop[:3] == container[:3] == ["hyprctl", "keyword", "windowrule"] + assert backstop[3].startswith("match:initial_class .*,") + assert container[3].startswith("match:initial_class ^hh-x1$,") @pytest.mark.parametrize("disabled", ["", " ", "\n"]) -def test_quarantine_plan_is_none_when_disabled(disabled: str) -> None: - assert quarantine_plan(disabled) is None +def test_quarantine_argv_is_none_when_disabled(disabled: str) -> None: + assert quarantine_argv(disabled) is None @pytest.mark.parametrize("bad", ["special:quarantine, monitor eDP-1", "a b", "q\n1", "q'"]) def test_a_quarantine_workspace_that_could_forge_a_field_is_refused(bad: str) -> None: with pytest.raises(ValueError) as exc: - quarantine_plan(bad) + quarantine_argv(bad) assert "quarantine_workspace" in str(exc.value) assert repr(bad.strip()) in str(exc.value) diff --git a/tests/sessions/conftest.py b/tests/sessions/conftest.py index 8bc02e0..4cde7fb 100644 --- a/tests/sessions/conftest.py +++ b/tests/sessions/conftest.py @@ -23,7 +23,10 @@ from pathlib import Path import pytest +# `tests/` for the shared helpers, and this directory for `fakes`, which the +# unit tests and the integration tests both import. sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +sys.path.insert(0, str(Path(__file__).resolve().parent)) #: Linux's sun_path is 108 bytes including the NUL. SUN_PATH_MAX = 107 diff --git a/tests/sessions/fakes.py b/tests/sessions/fakes.py new file mode 100644 index 0000000..04f21ae --- /dev/null +++ b/tests/sessions/fakes.py @@ -0,0 +1,432 @@ +"""A compositor and a pointer driver that are real sockets and nothing else. + +Both fakes bind an actual ``AF_UNIX`` listener and speak the real wire format. +Nothing here patches :mod:`socket`, :mod:`subprocess` or any method on the code +under test: a mock would pass while the things that actually break — a half- +closed request, a reply that is prose where JSON was promised, a driver that +went away mid-gesture — went untested. This is the same choice ``tests/ipc`` +made, for the same reason. + +What they prove and what they do not: + +* :class:`FakeCompositor` proves the **wiring** — that the broker sends the + plan's commands in the plan's order, parses what comes back and writes the + compositor's answer rather than its own intention into the record. It does + not prove that Hyprland agrees: it answers ``ok`` because it was asked + politely, and the real compositor's behaviour for ``output create headless`` + is marked unverified in the plan. Every test here is a test of this broker. +* :class:`FakeDriver` runs the **real dispatcher** from + :mod:`hhstream_pointer.ops`, behind the **real handler wrapper** from + :mod:`hhstream_pointer.__main__` and the **real server** from + :mod:`hhstream_pointer.server`, with only the Wayland sink replaced by a + recorder. So the protocol, the framing, the driver's own button bookkeeping + and — importantly — which backend failures become ``ok: false`` and which + kill the connection are the shipped ones; only the compositor is absent. +""" + +from __future__ import annotations + +import json +import socket +import threading +from pathlib import Path +from typing import Any + +import pytest + +from hhstream_pointer.__main__ import _handler +from hhstream_pointer.ops import Dispatcher +from hhstream_pointer.server import PointerServer + +#: Linux's sun_path is 108 bytes including the NUL. +SUN_PATH_MAX = 107 + +#: The pid the fake gives a window it conjures for a window rule. Fixed, and +#: not the session's: the compositor is the authority on what is on screen, and +#: a fake that echoed the broker's own pid back could not catch a broker that +#: wrote its intention into the record instead of the read-back. +WINDOW_PID = 424242 + + +def check_path(path: Path) -> None: + if len(str(path).encode()) > SUN_PATH_MAX: + pytest.skip(f"socket path too long for AF_UNIX ({len(str(path))} bytes): {path}") + + +class FakeCompositor: + """A Hyprland request socket with state: outputs, workspaces and windows. + + Laid out the way Hyprland lays one out — ``/hypr// + .socket.sock`` — so the broker's own discovery finds it, and answering + ``j/monitors``, ``j/workspaces``, ``j/clients`` with JSON of the shape + ``-j`` produces. + + It is stateful because the interesting assertions are about state: an + ``output create`` has to show up in the next ``monitors``, an ``output + remove`` has to make it and its windows disappear, and an orphan scan is + only meaningful against a compositor that still has the orphan. + """ + + def __init__(self, runtime_dir: Path, signature: str = "fake_1700000000") -> None: + self.runtime_dir = Path(runtime_dir) + self.signature = signature + self.directory = self.runtime_dir / "hypr" / signature + self.directory.mkdir(parents=True, exist_ok=True) + self.socket_path = self.directory / ".socket.sock" + check_path(self.socket_path) + + #: Commands received, in order, exactly as they arrived on the wire. + self.commands: list[str] = [] + #: ``initial_class`` -> ``(workspace, monitor)`` from the window rules. + self.rules: dict[str, tuple[int, str]] = {} + #: Commands to answer with prose instead of ``ok`` (a refusal). + self.refuse: set[str] = set() + #: When true, installing an anchored window rule also conjures the + #: window it describes — which is what a compositor with a cooperating + #: application does, and what the read-back path needs to have happen. + self.auto_window = True + + self._lock = threading.Lock() + self._monitors: list[dict[str, Any]] = [ + { + "id": 0, + "name": "HEADLESS-1", + "x": 0, + "y": 0, + "width": 1920, + "height": 1080, + "scale": 1.0, + "activeWorkspace": {"id": 1, "name": "1"}, + } + ] + self._workspaces: list[dict[str, Any]] = [ + {"id": 1, "name": "1", "monitor": "HEADLESS-1", "windows": 0} + ] + self._clients: list[dict[str, Any]] = [] + self._next_address = 0x1000 + + self._stop = threading.Event() + self._sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + self._sock.bind(str(self.socket_path)) + self._sock.listen(8) + self._sock.settimeout(0.05) + self._thread = threading.Thread(target=self._serve, daemon=True) + self._thread.start() + + # -- inspection, for the tests --------------------------------------- + + def outputs(self) -> list[str]: + with self._lock: + return [m["name"] for m in self._monitors] + + def workspaces_on(self, output: str) -> list[int]: + with self._lock: + return [w["id"] for w in self._workspaces if w["monitor"] == output] + + def windows(self) -> list[str]: + with self._lock: + return [c["initialClass"] for c in self._clients] + + def add_output(self, name: str) -> None: + """Create an output behind the broker's back — an orphan from a crash.""" + + with self._lock: + self._create_output(name) + + def add_window( + self, initial_class: str, workspace: int, monitor: str, *, pid: int = WINDOW_PID + ) -> str: + with self._lock: + return self._create_window(initial_class, workspace, monitor, pid) + + def focus(self, output: str, workspace: int) -> None: + """Make ``workspace`` the active one on ``output`` (the foreground join).""" + + with self._lock: + for monitor in self._monitors: + if monitor["name"] == output: + monitor["activeWorkspace"] = {"id": workspace, "name": str(workspace)} + + def stop(self) -> None: + self._stop.set() + self._sock.close() + self._thread.join(timeout=5.0) + + # -- the socket ------------------------------------------------------- + + def _serve(self) -> None: + while not self._stop.is_set(): + try: + conn, _ = self._sock.accept() + except (TimeoutError, socket.timeout): + continue + except OSError: + return + try: + self._handle(conn) + finally: + conn.close() + + def _handle(self, conn: socket.socket) -> None: + # The client half-closes after writing, so the request ends at EOF. + conn.settimeout(5.0) + received = b"" + while True: + try: + chunk = conn.recv(4096) + except OSError: + return + if not chunk: + break + received += chunk + text = received.decode("utf-8", errors="replace") + flags, separator, command = text.partition("/") + if not separator: + flags, command = "", text + command = command.strip() + with self._lock: + self.commands.append(command) + reply = self._reply(command) + try: + conn.sendall(reply.encode()) + except OSError: + pass + + # -- the command set -------------------------------------------------- + + def _reply(self, command: str) -> str: + if command in self.refuse: + return "Invalid command" + if command == "version": + return "Hyprland 0.56.2 built from branch at commit 0000000\nTag: v0.56.2\n" + if command == "monitors": + return json.dumps(self._monitors) + if command == "workspaces": + return json.dumps(self._workspaces) + if command == "clients": + return json.dumps(self._clients) + if command == "cursorpos": + return json.dumps({"x": 0, "y": 0}) + words = command.split() + if words[:3] == ["output", "create", "headless"] and len(words) == 4: + self._create_output(words[3]) + return "ok" + if words[:2] == ["output", "remove"] and len(words) == 3: + return "ok" if self._remove_output(words[2]) else f"no such output {words[2]}" + if words[:1] == ["keyword"]: + return self._keyword(command[len("keyword") :].strip()) + return f"unknown request {command!r}" + + def _keyword(self, rest: str) -> str: + name, _, body = rest.partition(" ") + if name == "workspace": + return self._keyword_workspace(body) + if name == "windowrule": + return self._keyword_windowrule(body) + if name == "monitor": + return self._keyword_monitor(body) + return f"unknown keyword {name!r}" + + def _keyword_workspace(self, body: str) -> str: + # `, monitor:, default:true, persistent:true` + parts = [p.strip() for p in body.split(",")] + slot = int(parts[0]) + monitor = next((p.split(":", 1)[1] for p in parts if p.startswith("monitor:")), None) + if monitor is None: + return "workspace rule has no monitor" + if not any(w["id"] == slot for w in self._workspaces): + self._workspaces.append( + {"id": slot, "name": str(slot), "monitor": monitor, "windows": 0} + ) + return "ok" + + def _keyword_windowrule(self, body: str) -> str: + # `match:initial_class ^hh-x$, workspace 1000, monitor hh-x` + parts = [p.strip() for p in body.split(",")] + match = parts[0] + if not match.startswith("match:initial_class "): + return "unsupported rule" + pattern = match[len("match:initial_class ") :] + workspace = next((p[len("workspace ") :] for p in parts if p.startswith("workspace ")), None) + monitor = next((p[len("monitor ") :] for p in parts if p.startswith("monitor ")), None) + if pattern == ".*" or monitor is None or workspace is None: + # The quarantine backstop: recorded so a test can assert it was + # installed, and first, but it conjures nothing. + self.rules[pattern] = (0, workspace or "") + return "ok" + initial_class = pattern.strip("^$") + self.rules[initial_class] = (int(workspace), monitor) + if self.auto_window: + self._create_window(initial_class, int(workspace), monitor, WINDOW_PID) + return "ok" + + def _keyword_monitor(self, body: str) -> str: + # `,x,auto,1` + parts = body.split(",") + name = parts[0] + width, _, height = parts[1].partition("x") + for monitor in self._monitors: + if monitor["name"] == name: + monitor["width"] = int(width) + monitor["height"] = int(height) + return "ok" + return f"no such monitor {name}" + + # -- state ------------------------------------------------------------ + + def _create_output(self, name: str) -> None: + if any(m["name"] == name for m in self._monitors): + return + self._monitors.append( + { + "id": len(self._monitors), + "name": name, + "x": 1920 * len(self._monitors), + "y": 0, + "width": 1280, + "height": 720, + "scale": 1.0, + "activeWorkspace": None, + } + ) + + def _remove_output(self, name: str) -> bool: + before = len(self._monitors) + self._monitors = [m for m in self._monitors if m["name"] != name] + if len(self._monitors) == before: + return False + gone = {w["id"] for w in self._workspaces if w["monitor"] == name} + self._workspaces = [w for w in self._workspaces if w["monitor"] != name] + # Hyprland destroys a window with its surface; the fake destroys the + # ones that were on the output's workspaces, which is the behaviour the + # teardown cross-check is written against. + self._clients = [c for c in self._clients if c["workspace"]["id"] not in gone] + return True + + def _create_window(self, initial_class: str, workspace: int, monitor: str, pid: int) -> str: + self._next_address += 0x10 + address = hex(self._next_address) + self._clients.append( + { + "address": address, + "mapped": True, + "hidden": False, + "at": [0, 0], + "size": [1280, 720], + "workspace": {"id": workspace, "name": str(workspace)}, + "monitor": next( + (m["id"] for m in self._monitors if m["name"] == monitor), 0 + ), + "class": initial_class, + "initialClass": initial_class, + "title": "a window, with a comma in its title", + "pid": pid, + } + ) + for entry in self._workspaces: + if entry["id"] == workspace: + entry["windows"] += 1 + # A window that maps makes its workspace the active one on its output, + # which is what the `foreground` join reads. + for entry in self._monitors: + if entry["name"] == monitor: + entry["activeWorkspace"] = {"id": workspace, "name": str(workspace)} + return address + + +class RecordingSink: + """A :class:`hhstream_pointer.ops.PointerSink` that writes nothing anywhere.""" + + def __init__(self) -> None: + self.calls: list[tuple] = [] + #: An exception to raise from the next call. The shipped driver + #: answers an ``OutputUnknown`` on the wire and lets anything else + #: take the connection down, so which one is raised here decides which + #: of the broker's two failure paths is being tested. + self.fail: Exception | None = None + + def motion_absolute(self, output: str, x: float, y: float) -> None: + self._check() + self.calls.append(("warp", output, round(x, 6), round(y, 6))) + + def button(self, output: str, code: int, state: int) -> None: + self._check() + self.calls.append(("button", output, code, state)) + + def frame(self, output: str) -> None: + self._check() + self.calls.append(("frame", output)) + + def _check(self) -> None: + if self.fail is not None: + raise self.fail + + def of(self, kind: str) -> list[tuple]: + return [c for c in self.calls if c[0] == kind] + + +class FakeDriver: + """The shipped driver with its Wayland sink replaced by a recorder. + + The dispatcher, the handler wrapper and the per-connection protocol loop + are the shipped ones. The **accept loop** is not: ``serve_forever`` blocks + in ``accept()`` for ever by design, and closing a listening socket does not + reliably wake a thread already inside it, so a fake that used it would cost + every test the stop timeout. Four lines with a poll interval replace it; + everything a test is actually asserting about still runs the real code. + """ + + def __init__(self, socket_path: Path) -> None: + check_path(Path(socket_path)) + self.socket_path = Path(socket_path) + self.sink = RecordingSink() + self.dispatcher = Dispatcher(self.sink) + self.server = PointerServer(self.socket_path, _handler(self.dispatcher)) + self.server.listen() + self.connections: list[socket.socket] = [] + self._stop = threading.Event() + self._listener = self.server._sock + self._listener.settimeout(0.05) + self._thread = threading.Thread(target=self._serve, daemon=True) + self._thread.start() + + def _serve(self) -> None: + while not self._stop.is_set(): + try: + conn, _ = self._listener.accept() + except (TimeoutError, socket.timeout): + continue + except OSError: + return + conn.settimeout(None) + self.connections.append(conn) + try: + self.server._serve_connection(conn) + except Exception: + # The shipped `main` lets a backend failure out of the serve + # loop and exits with code 10 — a driver talking to a dead + # display has nothing useful left to say. The fake ends its + # thread for the same reason, so the broker sees the same + # thing: a connection that closed without answering. + return + finally: + conn.close() + + def stop(self) -> None: + """Stop the way a killed process stops: listener *and* connections. + + The shipped driver never has to do this — the kernel closes its fds + when it exits — but a fake that left the broker's held connection open + would not look like a driver that restarted, which is one of the + things the client has to get right. + """ + + self._stop.set() + for conn in self.connections: + try: + conn.shutdown(socket.SHUT_RDWR) + except OSError: + pass + conn.close() + self._thread.join(timeout=5.0) + self.server.close() diff --git a/tests/sessions/integration/test_containers.py b/tests/sessions/integration/test_containers.py new file mode 100644 index 0000000..733f436 --- /dev/null +++ b/tests/sessions/integration/test_containers.py @@ -0,0 +1,600 @@ +"""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//` 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"] diff --git a/tests/sessions/integration/test_lifecycle.py b/tests/sessions/integration/test_lifecycle.py index 952b522..8b05954 100644 --- a/tests/sessions/integration/test_lifecycle.py +++ b/tests/sessions/integration/test_lifecycle.py @@ -118,6 +118,17 @@ ENV_DUMP = ( "time.sleep(600)" ) +# The container stamp as the application actually receives it. A separate app +# from `envdump` because that one asserts on an exact three-key dict, and the +# question here is a different one: did the class the window rule matches +# reach the process. +APP_ID_DUMP = ( + "import json, os, time; " + "print(json.dumps({k: os.environ.get(k) for k in " + "('HHSTREAM_APP_ID', 'SDL_VIDEO_WAYLAND_WMCLASS', 'RESOURCE_NAME')}), flush=True); " + "time.sleep(600)" +) + #: How the daemon may report having noticed an exit: a pidfd, or the documented #: /proc fallback where pidfd is unavailable. EXIT_MECHANISMS = {"pidfd", "proc_poll", "proc_check"} @@ -146,6 +157,7 @@ def config_text(wrapper: Path | None = None) -> str: + app("echoer", "import time; print('hello', flush=True); time.sleep(600)") + app("chatty", "import time\nfor i in range(3):\n print(f'line {i}', flush=True)\n time.sleep(0.2)") + app("envdump", ENV_DUMP) + + app("idump", APP_ID_DUMP) ) @@ -154,6 +166,10 @@ class Daemon: def __init__(self, root: Path, *extra_args: str): self.extra_args = list(extra_args) + #: Extra environment for the daemon process, laid over the inherited + #: one. The container tests use it to pin the compositor instance + #: signature the way a real deployment's unit does. + self.env: dict[str, str] = {} self.root = root self.socket = socket_path(root) self.state_dir = root / "state" @@ -194,7 +210,7 @@ class Daemon: stdout=open(self.log, "ab"), stderr=subprocess.STDOUT, cwd=str(REPO_ROOT), - env={**os.environ, "PYTHONPATH": IMPORT_PATH}, + env={**os.environ, "PYTHONPATH": IMPORT_PATH, **self.env}, ) wait_until( lambda: socket_is_live(self.socket) or self.process.poll() is not None, diff --git a/tests/sessions/unit/test_broker_protocol.py b/tests/sessions/unit/test_broker_protocol.py index ff2af78..85065ec 100644 --- a/tests/sessions/unit/test_broker_protocol.py +++ b/tests/sessions/unit/test_broker_protocol.py @@ -108,3 +108,89 @@ def test_error_replies_carry_both_a_machine_field_and_a_human_field(): def test_ok_replies_are_flagged(): assert protocol.ok(id="a")["ok"] is True + + +# --------------------------------------------------------------------------- +# `request_id` idempotency (PLAN §8) +# --------------------------------------------------------------------------- + + +def test_a_repeated_mutating_request_returns_the_recorded_answer(): + cache = protocol.IdempotencyCache() + cache.remember("start", "r1", {"ok": True, "id": "foot-aaaaaa"}) + + replay = cache.lookup("start", "r1") + + assert replay == {"ok": True, "id": "foot-aaaaaa", "deduplicated": True} + + +def test_a_recorded_failure_is_replayed_as_the_failure_it_was(): + """A retried `start` that policy refused must not get a second attempt.""" + + cache = protocol.IdempotencyCache() + cache.remember("start", "r1", {"ok": False, "error": "not_allowlisted"}) + + assert cache.lookup("start", "r1")["error"] == "not_allowlisted" + + +def test_read_verbs_are_never_cached_because_a_stale_list_is_worse(): + cache = protocol.IdempotencyCache() + cache.remember("list", "r1", {"ok": True, "sessions": []}) + + assert cache.lookup("list", "r1") is None + + +def test_a_request_with_no_id_is_never_matched_against_another(): + cache = protocol.IdempotencyCache() + cache.remember("start", None, {"ok": True}) + + assert len(cache) == 0 + assert cache.lookup("start", None) is None + + +def test_the_cache_is_bounded_because_the_peer_chooses_the_keys(): + cache = protocol.IdempotencyCache(capacity=4) + for n in range(10): + cache.remember("touch", f"r{n}", {"ok": True, "n": n}) + + assert len(cache) == 4 + assert cache.lookup("touch", "r0") is None + assert cache.lookup("touch", "r9")["n"] == 9 + + +def test_every_pointer_verb_that_moves_something_is_cached(): + """A retried click is a second click — the one mutation an agent cannot undo.""" + + assert { + "pointer.acquire", + "pointer.move", + "pointer.button", + "pointer.click", + "pointer.release", + } <= protocol.MUTATING_VERBS + assert "pointer.state" not in protocol.MUTATING_VERBS + assert "container.list" not in protocol.MUTATING_VERBS + + +def test_every_verb_the_protocol_names_is_one_the_daemon_answers(): + """One list, so a verb cannot be added to the dispatcher alone. + + The CLI imports `protocol`, not `server`; a verb in one and not the other + is a client that asks for something nothing answers. + """ + + from pathlib import Path + + from hhstreamd.clock import ManualClock + from hhstreamd.manager import ManagerConfig, SessionManager + from hhstreamd.policy import Policy + from hhstreamd.server import ControlServer + + manager = SessionManager( + ManagerConfig(state_dir=Path("/nonexistent"), runtime_dir=Path("/nonexistent"), policy=Policy()), + clock=ManualClock(), + ) + server = ControlServer(manager, "/nonexistent/control.sock") + + assert set(server._ops) == set(protocol.VERBS) + assert protocol.MUTATING_VERBS <= set(protocol.VERBS) diff --git a/tests/sessions/unit/test_container_host.py b/tests/sessions/unit/test_container_host.py new file mode 100644 index 0000000..4e680ec --- /dev/null +++ b/tests/sessions/unit/test_container_host.py @@ -0,0 +1,288 @@ +"""Running container plans against a compositor-shaped socket. + +The compositor here is a real ``AF_UNIX`` listener laid out the way Hyprland +lays one out, answering the commands Hyprland answers. That proves the wiring +— the right commands, in the right order, and a record built from the reply +rather than from the request. It does **not** prove Hyprland agrees: see the +slice report for what is unverified. +""" + +from __future__ import annotations + +from pathlib import Path + +import pytest +from fakes import WINDOW_PID, FakeCompositor + +from hhstreamd import containers +from hhstreamd.container_host import ContainerHost +from hhstreamd.ipc import CompositorUnavailable + + +@pytest.fixture +def compositor(short_tmpdir: Path): + fake = FakeCompositor(short_tmpdir) + try: + yield fake + finally: + fake.stop() + + +def make_host(fake: FakeCompositor, *, slots: int = 4) -> ContainerHost: + return ContainerHost( + fake.runtime_dir, + allocator=containers.WorkspaceAllocator(1000, slots), + signature=fake.signature, + ) + + +def test_a_live_compositor_is_available_and_names_its_instance(compositor): + host = make_host(compositor) + + assert host.available() is True + # The signature goes in the record so a restarted broker re-attaches to + # this instance rather than whichever one is there later. + assert host.signature == compositor.signature + + +def test_no_compositor_is_unavailable_and_says_why(short_tmpdir: Path): + host = ContainerHost( + short_tmpdir / "nothing-here", + allocator=containers.WorkspaceAllocator(1000, 2), + ) + + assert host.available() is False + assert host.last_error and "nothing-here" in host.last_error + + +def test_no_runtime_directory_at_all_is_unavailable_rather_than_an_error(short_tmpdir): + """A broker with no `--compositor-runtime-dir` still has to start.""" + + host = ContainerHost(None, allocator=containers.WorkspaceAllocator(1000, 2)) + + assert host.available() is False + assert "no compositor runtime directory" in (host.last_error or "") + + +def test_create_runs_the_plan_in_order_and_the_output_appears(compositor): + host = make_host(compositor) + host.available() + + plan = host.create("foot-aaaaaa", "hh-foot-aaaaaa") + + assert plan.output == "hh-foot-aaaaaa" + assert plan.workspace == 1000 + # The plan's own order, which is load-bearing: the output has to exist + # before a rule can name it, and the mode is set on an output that is + # already there. + queries = ("version", "clients", "monitors", "workspaces") + assert [c for c in compositor.commands if not c.startswith(queries)] == [ + "output create headless hh-foot-aaaaaa", + "keyword workspace 1000, monitor:hh-foot-aaaaaa, default:true, persistent:true", + "keyword windowrule match:initial_class ^hh-foot-aaaaaa$, workspace 1000, " + "monitor hh-foot-aaaaaa", + "keyword monitor hh-foot-aaaaaa,1280x720,auto,1", + ] + assert "hh-foot-aaaaaa" in compositor.outputs() + assert compositor.workspaces_on("hh-foot-aaaaaa") == [1000] + + +def test_the_quarantine_backstop_goes_in_before_any_container_rule(compositor): + """Rules are applied in declaration order, so the catch-all must be first. + + Installed after a session's anchored rule, the catch-all would override it + and sweep that session's own window into the special workspace — the exact + leak containers exist to prevent. + """ + + host = make_host(compositor) + host.available() + + assert host.install_quarantine() is True + host.create("foot-aaaaaa", "hh-foot-aaaaaa") + + rules = [c for c in compositor.commands if c.startswith("keyword windowrule")] + assert rules[0] == "keyword windowrule match:initial_class .*, workspace special:quarantine" + assert rules[1].startswith("keyword windowrule match:initial_class ^hh-foot-aaaaaa$") + + +def test_a_blank_quarantine_workspace_installs_nothing(compositor): + host = ContainerHost( + compositor.runtime_dir, + allocator=containers.WorkspaceAllocator(1000, 2), + quarantine_workspace=" ", + ) + host.available() + + assert host.install_quarantine() is False + assert not [c for c in compositor.commands if c.startswith("keyword")] + + +def test_a_refused_command_is_reported_and_the_slot_is_given_back(compositor): + """A half-built container must not also leak a workspace number.""" + + host = make_host(compositor) + host.available() + compositor.refuse.add("keyword monitor hh-foot-aaaaaa,1280x720,auto,1") + + with pytest.raises(CompositorUnavailable) as exc: + host.create("foot-aaaaaa", "hh-foot-aaaaaa") + assert "refused" in str(exc.value) + assert host.allocator.in_use() == [] + + +def test_read_back_reports_the_compositor_s_answer_not_ours(compositor): + host = make_host(compositor) + host.available() + host.create("foot-aaaaaa", "hh-foot-aaaaaa") + + facts = host.read_back("hh-foot-aaaaaa") + + assert facts is not None + assert facts.workspace == 1000 + # The output is joined through the *workspace's* monitor name, because a + # client reports its monitor as a numeric index and `ipc.Monitor` carries + # no id to join that against (see the slice report). + assert facts.output == "hh-foot-aaaaaa" + assert facts.window["initial_class"] == "hh-foot-aaaaaa" + assert facts.window["stable_id"] == f"hh-foot-aaaaaa:{WINDOW_PID}" + # Titles contain commas; the client must not have lost the end of one. + assert facts.window["title"] == "a window, with a comma in its title" + + +def test_foreground_is_the_monitor_active_workspace_join(compositor): + """Not the client's `visible` flag: "is anyone actually looking at this".""" + + host = make_host(compositor) + host.available() + host.create("foot-aaaaaa", "hh-foot-aaaaaa") + assert host.read_back("hh-foot-aaaaaa").foreground is True + + compositor.focus("hh-foot-aaaaaa", 9999) + assert host.read_back("hh-foot-aaaaaa").foreground is False + + +def test_no_window_yet_is_none_and_not_an_invented_one(compositor): + host = make_host(compositor) + host.available() + compositor.auto_window = False + host.create("foot-aaaaaa", "hh-foot-aaaaaa") + + assert host.read_back("hh-foot-aaaaaa") is None + + +def test_a_window_that_kept_its_own_class_is_still_found_by_pid(compositor): + """An application that ignored the stamp is observed, not pretended away.""" + + host = make_host(compositor) + host.available() + compositor.auto_window = False + host.create("foot-aaaaaa", "hh-foot-aaaaaa") + compositor.add_window("firefox", 1, "HEADLESS-1", pid=777) + + facts = host.read_back("hh-foot-aaaaaa", pid=777) + + assert facts is not None + assert facts.window["initial_class"] == "firefox" + # On the shared output, not the container's: the rule did not bind, and + # the caller is the one that has to say so. + assert facts.output == "HEADLESS-1" + + +def test_remove_takes_the_output_and_its_windows_with_it(compositor): + host = make_host(compositor) + host.available() + plan = host.create("foot-aaaaaa", "hh-foot-aaaaaa") + + host.remove(plan.output) + + assert "hh-foot-aaaaaa" not in compositor.outputs() + assert compositor.windows() == [] + assert host.survivors("hh-foot-aaaaaa", plan.output) == [] + + +def test_a_window_that_outlives_the_output_is_reported_as_a_survivor(compositor): + """Teardown reports what is left rather than declaring success.""" + + host = make_host(compositor) + host.available() + host.create("foot-aaaaaa", "hh-foot-aaaaaa") + # A second window of ours that landed somewhere else entirely. + compositor.add_window("hh-foot-aaaaaa", 1, "HEADLESS-1", pid=999) + host.remove("hh-foot-aaaaaa") + + survivors = host.survivors("hh-foot-aaaaaa", "hh-foot-aaaaaa") + + assert [s["pid"] for s in survivors] == [999] + + +@pytest.mark.parametrize("name", ["HEADLESS-1", "hh-", "HH-x", "eDP-1", "hh-Foo"]) +def test_remove_refuses_any_name_the_filter_rejects(compositor, name): + """`contains_output` is the only thing between the scan and someone + else's monitor, so the removal path asks it too.""" + + host = make_host(compositor) + host.available() + + with pytest.raises(ValueError) as exc: + host.remove(name) + assert "not one this broker creates" in str(exc.value) + + +def test_our_outputs_lists_only_names_this_broker_could_have_made(compositor): + host = make_host(compositor) + host.available() + host.create("foot-aaaaaa", "hh-foot-aaaaaa") + compositor.add_output("DP-1") + compositor.add_output("hh-orphan-zzzzzz") + + assert host.our_outputs() == ["hh-foot-aaaaaa", "hh-orphan-zzzzzz"] + + +def test_reserve_re_takes_an_adopted_slot_so_it_is_not_handed_out_twice(compositor): + """After a restart the records name workspaces that are still in use.""" + + host = make_host(compositor) + + assert host.reserve([1002]) == [1002] + assert host.allocator.in_use() == [1002] + # The slots walked past on the way there were given back, so the next + # session still gets the lowest free one. + assert host.allocator.allocate() == 1000 + + +def test_reserving_a_slot_this_allocator_already_holds_is_not_a_second_hunt(compositor): + """Reconcile runs more than once; the second pass must be a no-op.""" + + host = make_host(compositor, slots=2) + + assert host.reserve([1001]) == [1001] + assert host.reserve([1001]) == [1001] + assert host.allocator.in_use() == [1001] + assert host.allocator.allocate() == 1000 + + +def test_reserve_is_a_no_op_for_a_session_that_never_had_a_slot(compositor): + host = make_host(compositor) + + assert host.reserve([None, None]) == [] + assert host.allocator.in_use() == [] + + +def test_release_tolerates_a_slot_this_allocator_never_held(compositor): + """Teardown runs for sessions started before the broker restarted too.""" + + host = make_host(compositor) + + host.release(1003) # must not raise: the application is already dead + host.release(None) + assert host.allocator.in_use() == [] + + +def test_a_plan_entry_that_is_not_hyprctl_is_a_bug_and_says_so(compositor): + host = make_host(compositor) + host.available() + + with pytest.raises(ValueError) as exc: + host.dispatch(["sh", "-c", "rm -rf /"]) + assert "not a hyprctl plan entry" in str(exc.value) diff --git a/tests/sessions/unit/test_container_reconcile.py b/tests/sessions/unit/test_container_reconcile.py new file mode 100644 index 0000000..dfdc62a --- /dev/null +++ b/tests/sessions/unit/test_container_reconcile.py @@ -0,0 +1,296 @@ +"""Start-up reconciliation: adopt what is ours, remove what is unattended. + +A container is a render target that costs CPU and a place windows can land, so +one with no live session must never be left behind — and a broker that lost its +registry recovers by exactly this scan. The danger is the other direction: the +scan deletes outputs, so everything here is also a test that it deletes only +what :func:`hhstreamd.containers.contains_output` claims. +""" + +from __future__ import annotations + +import asyncio +import os +from pathlib import Path + +import pytest +from fakes import FakeCompositor + +from hhstreamd import procmon +from hhstreamd.clock import ManualClock +from hhstreamd.manager import ManagerConfig, SessionManager +from hhstreamd.policy import Policy +from hhstreamd.registry import ContainerState, Session, State, container_record + + +def make_session(session_id: str, *, output: str | None, workspace: int | None, **kwargs) -> Session: + return Session( + id=session_id, + app="foot", + argv=["/usr/bin/foot"], + pid=4242, + pgid=4242, + sid=4242, + pid_starttime=1, + cmdline_sha256="9f2c", + home="/home/someone", + runtime_dir=f"/run/hhstream/sessions/{session_id}", + created_at="2026-10-01T09:14:02Z", + created_boottime=1000.0, + last_activity_at="2026-10-01T09:14:02Z", + last_activity_boottime=1000.0, + idle_timeout_s=10800.0, + state=State.READY, + container=container_record( + output=output, + workspace=workspace, + mode=(1280, 720), + created_by="broker", + state=ContainerState.OWNED, + ), + **kwargs, + ) + + +@pytest.fixture +def compositor(short_tmpdir: Path): + fake = FakeCompositor(short_tmpdir) + try: + yield fake + finally: + fake.stop() + + +@pytest.fixture +def manager(short_tmpdir: Path, compositor: FakeCompositor) -> SessionManager: + return SessionManager( + ManagerConfig( + state_dir=short_tmpdir / "state", + runtime_dir=short_tmpdir / "run", + policy=Policy(), + compositor_runtime_dir=compositor.runtime_dir, + signature=compositor.signature, + ), + clock=ManualClock(boottime=1000.0), + ) + + +def test_an_unattended_output_is_removed_at_start_up(manager, compositor): + compositor.add_output("hh-ghost-aaaaaa") + + summary = manager.reconcile_containers() + + assert summary["removed"] == ["hh-ghost-aaaaaa"] + assert "hh-ghost-aaaaaa" not in compositor.outputs() + + +@pytest.mark.parametrize("name", ["HEADLESS-1", "DP-1", "hh-", "hh-Upper", "hhother"]) +def test_an_output_the_filter_rejects_is_never_touched(manager, compositor, name): + """The one thing between this scan and somebody else's monitor.""" + + compositor.add_output(name) + + summary = manager.reconcile_containers() + + assert summary["removed"] == [] + assert name in compositor.outputs() + + +def test_a_container_with_a_live_session_is_adopted_not_removed(manager, compositor): + compositor.add_output("hh-foot-aaaaaa") + manager.registry.add( + make_session("foot-aaaaaa", output="hh-foot-aaaaaa", workspace=1002, + signature=compositor.signature) + ) + + summary = manager.reconcile_containers() + + assert summary["adopted"] == [{"id": "foot-aaaaaa", "output": "hh-foot-aaaaaa"}] + assert summary["removed"] == [] + assert "hh-foot-aaaaaa" in compositor.outputs() + + +def test_an_adopted_workspace_is_not_handed_to_the_next_session(manager, compositor): + """After a restart the records name slots that are still in use.""" + + compositor.add_output("hh-foot-aaaaaa") + manager.registry.add( + make_session("foot-aaaaaa", output="hh-foot-aaaaaa", workspace=1000, + signature=compositor.signature) + ) + + manager.reconcile_containers() + + assert manager.host.allocator.in_use() == [1000] + assert manager.host.create("foot-bbbbbb", "hh-foot-bbbbbb").workspace == 1001 + + +def test_a_record_naming_an_output_that_is_gone_is_marked_orphan(manager, compositor): + """The application may still be running, so nothing is killed for this.""" + + session = manager.registry.add( + make_session("foot-aaaaaa", output="hh-foot-aaaaaa", workspace=1000, + signature=compositor.signature) + ) + + summary = manager.reconcile_containers() + + assert session.container["state"] == ContainerState.ORPHAN + assert summary["orphaned"] == [{"id": "foot-aaaaaa", "output": "hh-foot-aaaaaa"}] + assert session.live, "losing a container is not losing the session" + + +def test_a_container_from_a_previous_compositor_instance_is_not_claimed(manager, compositor): + """This is what the recorded signature is for. + + The output name would match, and adopting it would hand this broker a + container that died with its compositor — and reserve a workspace slot in + an instance that never allocated one. + """ + + compositor.add_output("hh-foot-aaaaaa") + session = manager.registry.add( + make_session("foot-aaaaaa", output="hh-foot-aaaaaa", workspace=1000, + signature="an-older-instance") + ) + + summary = manager.reconcile_containers() + + assert session.container["state"] == ContainerState.ORPHAN + assert summary["orphaned"] == [{"id": "foot-aaaaaa", "why": "signature_changed"}] + # Unclaimed, so the scan takes it down like any other unattended output. + assert summary["removed"] == ["hh-foot-aaaaaa"] + assert manager.host.allocator.in_use() == [] + + +def test_the_quarantine_backstop_is_installed_before_anything_else(manager, compositor): + manager.reconcile_containers() + + keywords = [c for c in compositor.commands if c.startswith("keyword")] + assert keywords[0].startswith("keyword windowrule match:initial_class .*,") + + +def test_no_compositor_leaves_the_broker_degraded_rather_than_refusing(short_tmpdir: Path): + manager = SessionManager( + ManagerConfig( + state_dir=short_tmpdir / "state", + runtime_dir=short_tmpdir / "run", + policy=Policy(), + compositor_runtime_dir=short_tmpdir / "no-compositor", + ), + clock=ManualClock(boottime=1000.0), + ) + + summary = manager.reconcile_containers() + + assert summary["available"] is False + assert summary["removed"] == [] + assert manager.containers_available is False + assert "no-compositor" in summary["error"] + + +def test_container_list_will_not_claim_there_are_no_orphans_without_looking(short_tmpdir): + """`[]` would read as "nothing is out there", which we cannot know.""" + + manager = SessionManager( + ManagerConfig( + state_dir=short_tmpdir / "state", + runtime_dir=short_tmpdir / "run", + policy=Policy(), + compositor_runtime_dir=short_tmpdir / "no-compositor", + ), + clock=ManualClock(boottime=1000.0), + ) + manager.reconcile_containers() + + listing = manager.container_list() + + assert listing["orphans"] is None + assert listing["compositor"] == "absent" + + +def test_container_list_names_the_orphans_it_can_see(manager, compositor): + compositor.add_output("hh-ghost-aaaaaa") + manager.containers_available = True + manager.registry.add( + make_session("foot-aaaaaa", output="hh-foot-aaaaaa", workspace=1000, + signature=compositor.signature) + ) + compositor.add_output("hh-foot-aaaaaa") + + listing = manager.container_list() + + assert listing["orphans"] == ["hh-ghost-aaaaaa"] + assert [row["id"] for row in listing["containers"]] == ["foot-aaaaaa"] + # Listing is not acting: the orphan is still there afterwards. + assert "hh-ghost-aaaaaa" in compositor.outputs() + + +def test_gc_takes_down_the_container_of_a_session_it_tombstones(manager, compositor): + """`gc` is the last thing that will ever look at that session. + + It tombstones a record whose process vanished without the watcher + noticing; if it did not also take the output down, nothing else would, + until the next broker start-up found it unattended. + """ + + compositor.add_output("hh-foot-aaaaaa") + session = manager.registry.add( + make_session("foot-aaaaaa", output="hh-foot-aaaaaa", workspace=1000, + signature=compositor.signature) + ) + manager.reconcile_containers() # adopts it, and reserves its slot + # A pid that is not a process: what `gc` is for. + session.pid = session.pgid = session.sid = 4_194_303 + + result = asyncio.run(manager.gc()) + + entry = {row["id"]: row for row in result["reconciled"]}["foot-aaaaaa"] + assert entry["container_removed"] is True + assert entry["container_survivors"] == [] + assert "hh-foot-aaaaaa" not in compositor.outputs() + assert session.container["state"] == ContainerState.REMOVED + assert manager.host.allocator.in_use() == [], "the slot came back" + + +def test_gc_leaves_a_healthy_session_s_container_alone(manager, compositor): + compositor.add_output("hh-foot-aaaaaa") + session = manager.registry.add( + make_session("foot-aaaaaa", output="hh-foot-aaaaaa", workspace=1000, + signature=compositor.signature) + ) + manager.reconcile_containers() + # This process: alive, and its own identity. + identity = procmon.identity(os.getpid()) + session.pid, session.pgid, session.sid = os.getpid(), identity.pgid, identity.sid + session.pid_starttime = identity.starttime + session.cmdline_sha256 = identity.cmdline_sha256 + + asyncio.run(manager.gc()) + + assert "hh-foot-aaaaaa" in compositor.outputs() + assert session.container["state"] == ContainerState.OWNED + + +def test_reconciling_everything_rescans_the_outputs_and_every_session(manager, compositor): + """`container.reconcile` with no id is the start-up scan, on demand.""" + + compositor.add_output("hh-foot-aaaaaa") + session = manager.registry.add( + make_session("foot-aaaaaa", output="hh-foot-aaaaaa", workspace=1000, + signature=compositor.signature) + ) + manager.reconcile_containers() + compositor.add_output("hh-ghost-aaaaaa") + compositor.add_window("hh-foot-aaaaaa", 1000, "hh-foot-aaaaaa") + + result = asyncio.run(manager.container_reconcile(None)) + + assert result["scan"]["removed"] == ["hh-ghost-aaaaaa"] + assert result["scan"]["adopted"] == [{"id": "foot-aaaaaa", "output": "hh-foot-aaaaaa"}] + # The window that appeared while nobody was looking is now in the record. + assert session.window["initial_class"] == "hh-foot-aaaaaa" + assert {d["field"] for d in result["diff"]} == {"workspace", "window"} + # The slot stays reserved across a second scan rather than being hunted + # for again in a band it is itself occupying. + assert manager.host.allocator.in_use() == [1000] diff --git a/tests/sessions/unit/test_driver_client.py b/tests/sessions/unit/test_driver_client.py new file mode 100644 index 0000000..314a6e2 --- /dev/null +++ b/tests/sessions/unit/test_driver_client.py @@ -0,0 +1,222 @@ +"""The broker's end of the driver socket, against a real driver socket. + +Every test here goes over an actual ``AF_UNIX`` connection to the shipped +:class:`hhstream_pointer.server.PointerServer` running the shipped +:class:`hhstream_pointer.ops.Dispatcher`. Only the Wayland sink is a +recorder. Mocking the socket would have tested that this module can call +``json.dumps``; what it has to be right about is the half of the protocol it +does not own. +""" + +from __future__ import annotations + +import socket +import threading +from pathlib import Path + +import pytest +from fakes import FakeDriver + +from hhstream_pointer.backend import CompositorUnavailable as DriverDied +from hhstream_pointer.backend import OutputUnknown + +from hhstreamd.driver import DriverRejected, DriverUnavailable, PointerDriver + + +@pytest.fixture +def driver(short_tmpdir: Path): + fake = FakeDriver(short_tmpdir / "p.sock") + client = PointerDriver(fake.socket_path, timeout_s=5.0) + try: + yield client, fake + finally: + client.close() + fake.stop() + + +def test_a_warp_reaches_the_sink_as_output_local_coordinates(driver): + client, fake = driver + client.warp("hh-a", 0.25, 0.75) + + assert fake.sink.calls == [("warp", "hh-a", 0.25, 0.75)] + + +def test_a_gesture_arrives_in_order_and_is_committed_by_a_frame(driver): + """Nothing the driver is sent reaches the compositor until a frame.""" + + client, fake = driver + client.warp("hh-a", 0.5, 0.5) + client.button("left", "down") + client.button("left", "up") + client.frame() + + assert fake.sink.calls == [ + ("warp", "hh-a", 0.5, 0.5), + ("button", "hh-a", 0x110, 1), + ("button", "hh-a", 0x110, 0), + ("frame", "hh-a"), + ] + + +def test_pressed_reports_what_the_driver_believes_is_down(driver): + client, _ = driver + client.warp("hh-a", 0.5, 0.5) + assert client.pressed() == [] + + client.button("right", "down") + client.button("middle", "down") + assert client.pressed() == ["right", "middle"] + + client.button("right", "up") + assert client.pressed() == ["middle"] + + +def test_release_all_lifts_everything_and_says_what_it_lifted(driver): + client, fake = driver + client.warp("hh-a", 0.5, 0.5) + client.button("left", "down") + client.button("right", "down") + + assert client.release_all() == ["left", "right"] + assert client.pressed() == [] + # Lifted through the pointer each went down on, then one frame for it. + assert fake.sink.calls[-3:] == [ + ("button", "hh-a", 0x110, 0), + ("button", "hh-a", 0x111, 0), + ("frame", "hh-a"), + ] + + +def test_release_all_on_an_idle_driver_is_an_empty_list_not_an_error(driver): + """The expiry path calls this unconditionally; it must be safe.""" + + client, _ = driver + assert client.release_all() == [] + + +def test_a_refusal_is_carried_back_and_is_not_a_lost_connection(driver): + """``ok: false`` is the driver working, so the client must stay usable.""" + + client, fake = driver + with pytest.raises(DriverRejected) as exc: + client.warp("hh-a", 1.5, 0.5) + assert "0..1" in str(exc.value) + + client.warp("hh-a", 0.5, 0.5) + assert fake.sink.calls == [("warp", "hh-a", 0.5, 0.5)] + + +def test_a_button_before_any_warp_is_refused_rather_than_aimed_at_nothing(driver): + client, _ = driver + with pytest.raises(DriverRejected) as exc: + client.button("left", "down") + assert "warp" in str(exc.value) + + +def test_an_unknown_output_is_a_refusal_and_leaves_the_driver_usable(driver): + """Routine: the broker can be racing a container it just tore down.""" + + client, fake = driver + fake.sink.fail = OutputUnknown("no output hh-gone") + with pytest.raises(DriverRejected) as exc: + client.warp("hh-gone", 0.5, 0.5) + assert "hh-gone" in str(exc.value) + + fake.sink.fail = None + client.warp("hh-a", 0.5, 0.5) + assert fake.sink.of("warp") == [("warp", "hh-a", 0.5, 0.5)] + + +def test_a_driver_that_dies_mid_gesture_is_unavailable_not_a_refusal(driver): + """A lost compositor takes the driver's connection with it (by design). + + The broker has to be able to tell this from a refusal, because the cursor + is now in an unknown state and the lease has to go rather than carry on. + """ + + client, fake = driver + fake.sink.fail = DriverDied("the compositor hung up") + + with pytest.raises(DriverUnavailable): + client.warp("hh-a", 0.5, 0.5) + + +def test_no_driver_at_all_is_unavailable_and_never_a_silent_no_op(short_tmpdir: Path): + client = PointerDriver(short_tmpdir / "absent.sock", timeout_s=0.5) + with pytest.raises(DriverUnavailable) as exc: + client.release_all() + assert "absent.sock" in str(exc.value) + + +def test_a_driver_that_restarts_is_reconnected_to_rather_than_lost(short_tmpdir: Path): + """The held connection dies with the driver; the next verb must not.""" + + path = short_tmpdir / "p.sock" + first = FakeDriver(path) + client = PointerDriver(path, timeout_s=5.0) + client.warp("hh-a", 0.1, 0.1) + first.stop() + + second = FakeDriver(path) + try: + client.warp("hh-a", 0.2, 0.2) + assert second.sink.calls == [("warp", "hh-a", 0.2, 0.2)] + finally: + client.close() + second.stop() + + +def test_a_driver_that_answers_nothing_is_unavailable_within_the_timeout(short_tmpdir: Path): + """A wedged driver must time out, not hang the verb that called it.""" + + path = short_tmpdir / "mute.sock" + listener = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + listener.bind(str(path)) + listener.listen(1) + accepted: list[socket.socket] = [] + + def accept_and_say_nothing() -> None: + conn, _ = listener.accept() + accepted.append(conn) + + thread = threading.Thread(target=accept_and_say_nothing, daemon=True) + thread.start() + client = PointerDriver(path, timeout_s=0.3) + try: + with pytest.raises(DriverUnavailable): + client.pressed() + finally: + client.close() + thread.join(timeout=5.0) + for conn in accepted: + conn.close() + listener.close() + + +def test_a_reply_that_is_not_the_protocol_is_unavailable_not_an_empty_answer( + short_tmpdir: Path, +): + """"I could not read the answer" must never render as "nothing was down".""" + + path = short_tmpdir / "liar.sock" + listener = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + listener.bind(str(path)) + listener.listen(1) + + def answer_nonsense() -> None: + conn, _ = listener.accept() + with conn: + conn.recv(4096) + conn.sendall(b'{"ok":true,"buttons":"left"}\n') + + thread = threading.Thread(target=answer_nonsense, daemon=True) + thread.start() + client = PointerDriver(path, timeout_s=2.0) + try: + with pytest.raises(DriverUnavailable) as exc: + client.pressed() + assert "list of button names" in str(exc.value) + finally: + client.close() + thread.join(timeout=5.0) + listener.close() diff --git a/tests/sessions/unit/test_exit_codes.py b/tests/sessions/unit/test_exit_codes.py index 13fd676..fd576f7 100644 --- a/tests/sessions/unit/test_exit_codes.py +++ b/tests/sessions/unit/test_exit_codes.py @@ -21,6 +21,8 @@ def test_the_frozen_numbers(): assert ExitCode.POLICY == 6 assert ExitCode.TIMEOUT == 7 assert ExitCode.BUSY == 8 + assert ExitCode.NO_LEASE == 9 + assert ExitCode.COMPOSITOR == 10 # 1 is deliberately absent: it is the shell's "something went wrong", and # reusing it would make an unhandled crash indistinguishable from a # documented outcome. @@ -61,6 +63,17 @@ def test_the_frozen_numbers(): # 8 — busy ("busy", 8), ("already_managed", 8), + ("pointer_busy", 8), + # 9 — the verb needs the lease and this session does not hold it + ("no_lease", 9), + # 10 — the compositor side failed; the session itself survives + ("compositor", 10), + ("compositor_unavailable", 10), + ("no_container", 10), + ("driver_unavailable", 10), + ("driver_refused", 10), + # 6 — the container band is full: a budget, not a compositor failure + ("container_budget", 6), ], ) def test_every_error_name_maps_to_its_documented_code(error, code): @@ -77,7 +90,9 @@ def test_the_table_has_no_entries_this_test_does_not_know_about(): "bad_state", "pid_reuse_detected", "identity_unknown", "daemon_unreachable", "not_allowlisted", "argument_refused", "session_cap_reached", "refused", "timeout", - "readiness_timeout", "busy", "already_managed", + "readiness_timeout", "busy", "already_managed", "pointer_busy", + "container_budget", "no_lease", "compositor", "compositor_unavailable", + "no_container", "driver_unavailable", "driver_refused", } assert set(EXIT_CODE_FOR_ERROR) == documented @@ -87,6 +102,26 @@ def test_success_is_zero(): assert exit_code_for("") == 0 +def test_losing_the_compositor_is_not_the_same_as_losing_the_session(): + """Code 10 exists precisely so these two cannot be confused (PLAN §8.2). + + A session whose container could not be built is still running; one that + exited is not. An agent that saw the same code for both would kill a + healthy application to recover from a compositor hiccup. + """ + + assert exit_code_for("compositor") == ExitCode.COMPOSITOR + assert exit_code_for("session_exited") == ExitCode.BAD_STATE + assert ExitCode.COMPOSITOR != ExitCode.BAD_STATE + + +def test_a_missing_lease_and_a_held_one_are_different_codes(): + """8 means "wait", 9 means "acquire". One code could not say both.""" + + assert exit_code_for("pointer_busy") == ExitCode.BUSY + assert exit_code_for("no_lease") == ExitCode.NO_LEASE + + def test_an_unknown_error_degrades_to_not_usable_rather_than_to_success(): """A caller that does not recognise the failure must still not see a 0.""" diff --git a/tests/sessions/unit/test_pointer_verbs.py b/tests/sessions/unit/test_pointer_verbs.py new file mode 100644 index 0000000..e834e8d --- /dev/null +++ b/tests/sessions/unit/test_pointer_verbs.py @@ -0,0 +1,592 @@ +"""The pointer verbs: the lease, the bookmark, and never leaving a button down. + +The broker end is real (the manager, the lease, the driver client) and so is +the driver end (the shipped dispatcher and server over a real ``AF_UNIX`` +socket). Only the Wayland sink and the clock are substituted — the clock +because expiry has to be testable without sleeping for thirty seconds, and the +sink because this machine has no compositor. +""" + +from __future__ import annotations + +import asyncio +from pathlib import Path + +import pytest +from fakes import FakeDriver + +from hhstreamd.clock import ManualClock +from hhstreamd.manager import ManagerConfig, ManagerError, SessionManager +from hhstreamd.policy import Policy +from hhstreamd.protocol import ExitCode, exit_code_for +from hhstreamd.registry import ContainerState, Session, State, container_record + +LEFT = 0x110 +DOWN, UP = 1, 0 + + +def make_session(session_id: str = "foot-aaaaaa", *, container: bool = True) -> Session: + return Session( + id=session_id, + app="foot", + argv=["/usr/bin/foot"], + pid=4242, + pgid=4242, + sid=4242, + pid_starttime=918342, + cmdline_sha256="9f2c", + home="/home/someone", + runtime_dir=f"/run/hhstream/sessions/{session_id}", + created_at="2026-10-01T09:14:02Z", + created_boottime=1000.0, + last_activity_at="2026-10-01T09:14:02Z", + last_activity_boottime=1000.0, + idle_timeout_s=10800.0, + state=State.READY, + container=( + container_record( + output=f"hh-{session_id}", + workspace=1000, + mode=(1280, 720), + created_by="broker", + state=ContainerState.OWNED, + ) + if container + else None + ), + ) + + +class Harness: + def __init__(self, manager: SessionManager, fake: FakeDriver, clock: ManualClock) -> None: + self.manager = manager + self.fake = fake + self.clock = clock + + def add(self, session_id: str = "foot-aaaaaa", **kwargs) -> Session: + return self.manager.registry.add(make_session(session_id, **kwargs)) + + def run(self, coro): + return asyncio.run(coro) + + +@pytest.fixture +def harness(short_tmpdir: Path): + fake = FakeDriver(short_tmpdir / "p.sock") + clock = ManualClock(boottime=1000.0) + manager = SessionManager( + ManagerConfig( + state_dir=short_tmpdir / "state", + runtime_dir=short_tmpdir / "run", + policy=Policy(), + pointer_socket=fake.socket_path, + pointer_ttl_s=30.0, + pointer_max_s=300.0, + ), + clock=clock, + ) + try: + yield Harness(manager, fake, clock) + finally: + if manager.driver is not None: + manager.driver.close() + fake.stop() + + +# --------------------------------------------------------------------------- +# acquiring +# --------------------------------------------------------------------------- + + +def test_acquire_with_no_bookmark_aims_at_the_centre_of_the_container(harness): + harness.add() + + reply = harness.run(harness.manager.pointer_acquire("foot-aaaaaa")) + + assert reply["lease_id"] + assert reply["bookmark"] == { + "x": 0.5, + "y": 0.5, + "output": "hh-foot-aaaaaa", + "at": reply["bookmark"]["at"], + } + assert harness.fake.sink.calls == [ + ("warp", "hh-foot-aaaaaa", 0.5, 0.5), + ("frame", "hh-foot-aaaaaa"), + ] + + +def test_acquire_restores_the_position_the_session_was_left_at(harness): + session = harness.add() + lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"] + harness.run(harness.manager.pointer_move("foot-aaaaaa", lease, x=0.25, y=0.75)) + harness.run(harness.manager.pointer_release("foot-aaaaaa", lease)) + harness.fake.sink.calls.clear() + + reply = harness.run(harness.manager.pointer_acquire("foot-aaaaaa")) + + assert (reply["bookmark"]["x"], reply["bookmark"]["y"]) == (0.25, 0.75) + assert harness.fake.sink.of("warp") == [("warp", "hh-foot-aaaaaa", 0.25, 0.75)] + assert session.pointer["bookmark"]["x"] == 0.25 + + +def test_restore_false_goes_to_the_centre_even_with_a_bookmark(harness): + harness.add() + lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"] + harness.run(harness.manager.pointer_move("foot-aaaaaa", lease, x=0.1, y=0.1)) + harness.run(harness.manager.pointer_release("foot-aaaaaa", lease)) + harness.fake.sink.calls.clear() + + reply = harness.run(harness.manager.pointer_acquire("foot-aaaaaa", restore=False)) + + assert (reply["bookmark"]["x"], reply["bookmark"]["y"]) == (0.5, 0.5) + + +def test_a_bookmark_from_another_output_is_not_a_position_in_this_one(harness): + """A container is rebuilt with a new name; the old fraction is not a place.""" + + session = harness.add() + session.pointer = { + "bookmark": {"x": 0.9, "y": 0.9, "output": "hh-gone", "at": "2026-01-01T00:00:00Z"}, + "last_released_at": None, + "released_by": None, + } + + reply = harness.run(harness.manager.pointer_acquire("foot-aaaaaa")) + + assert (reply["bookmark"]["x"], reply["bookmark"]["y"]) == (0.5, 0.5) + + +def test_a_second_session_is_told_who_holds_the_cursor(harness): + """There is one cursor, so the answer is "wait", with a name attached.""" + + harness.add("foot-aaaaaa") + harness.add("foot-bbbbbb") + harness.run(harness.manager.pointer_acquire("foot-aaaaaa")) + + with pytest.raises(ManagerError) as exc: + harness.run(harness.manager.pointer_acquire("foot-bbbbbb")) + + assert exc.value.error == "pointer_busy" + assert exit_code_for(exc.value.error) == ExitCode.BUSY + assert exc.value.fields["holder"] == "foot-aaaaaa" + + +def test_a_session_with_no_container_has_nowhere_to_aim(harness): + """Aiming at "wherever the cursor is" is how a click lands next door.""" + + harness.add("foot-aaaaaa", container=False) + + with pytest.raises(ManagerError) as exc: + harness.run(harness.manager.pointer_acquire("foot-aaaaaa")) + + assert exc.value.error == "no_container" + assert exit_code_for(exc.value.error) == ExitCode.COMPOSITOR + + +def test_a_lease_that_could_not_be_aimed_is_not_left_held(harness): + harness.add() + harness.fake.stop() + + with pytest.raises(ManagerError) as exc: + harness.run(harness.manager.pointer_acquire("foot-aaaaaa")) + + assert exc.value.error == "driver_unavailable" + assert exit_code_for(exc.value.error) == ExitCode.COMPOSITOR + assert harness.manager.pointer.state()["holder"] is None + + +# --------------------------------------------------------------------------- +# moving +# --------------------------------------------------------------------------- + + +def test_every_move_writes_the_bookmark_to_the_record(harness): + """So a broker that dies mid-gesture still leaves the last real position.""" + + session = harness.add() + lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"] + + for x in (0.1, 0.2, 0.3): + reply = harness.run(harness.manager.pointer_move("foot-aaaaaa", lease, x=x, y=0.5)) + assert reply["bookmark"]["x"] == x + assert session.pointer["bookmark"]["x"] == x + + # And in the lease, which is what `release` reports. + outcome = harness.manager.pointer.release("foot-aaaaaa", lease, "test") + assert outcome.bookmark.x == 0.3 + + +def test_a_relative_move_is_applied_to_the_bookmark_and_clamped(harness): + harness.add() + lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"] + + reply = harness.run(harness.manager.pointer_move("foot-aaaaaa", lease, dx=0.25, dy=-0.25)) + assert (reply["bookmark"]["x"], reply["bookmark"]["y"]) == (0.75, 0.25) + + # Running into the edge of the screen is what a mouse does. + reply = harness.run(harness.manager.pointer_move("foot-aaaaaa", lease, dx=5.0, dy=-5.0)) + assert (reply["bookmark"]["x"], reply["bookmark"]["y"]) == (1.0, 0.0) + + +@pytest.mark.parametrize("bad", [1.4, -0.1, "0.5", True, None]) +def test_an_absolute_coordinate_outside_the_frame_is_a_usage_error(harness, bad): + """A caller that computed 1.4 has a bug; clamping it would hide it.""" + + harness.add() + lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"] + + with pytest.raises(ManagerError) as exc: + harness.run(harness.manager.pointer_move("foot-aaaaaa", lease, x=bad, y=0.5)) + assert exc.value.error == "invalid_argument" + + +def test_moving_without_the_lease_is_nine_and_not_eight(harness): + harness.add("foot-aaaaaa") + harness.add("foot-bbbbbb") + lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"] + + with pytest.raises(ManagerError) as exc: + harness.run(harness.manager.pointer_move("foot-bbbbbb", lease, x=0.5, y=0.5)) + + assert exc.value.error == "no_lease" + assert exit_code_for(exc.value.error) == ExitCode.NO_LEASE + + +def test_a_stale_lease_id_is_refused_even_for_the_holder(harness): + harness.add() + harness.run(harness.manager.pointer_acquire("foot-aaaaaa")) + + with pytest.raises(ManagerError) as exc: + harness.run(harness.manager.pointer_move("foot-aaaaaa", "not-the-lease", x=0.5, y=0.5)) + assert exc.value.error == "no_lease" + + +# --------------------------------------------------------------------------- +# buttons +# --------------------------------------------------------------------------- + + +def test_a_button_goes_down_and_up_through_the_driver(harness): + harness.add() + lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"] + harness.fake.sink.calls.clear() + + assert harness.run( + harness.manager.pointer_button("foot-aaaaaa", lease, "left", "down") + )["buttons"] == ["left"] + assert harness.run( + harness.manager.pointer_button("foot-aaaaaa", lease, "left", "up") + )["buttons"] == [] + + assert harness.fake.sink.calls == [ + ("button", "hh-foot-aaaaaa", LEFT, DOWN), + ("frame", "hh-foot-aaaaaa"), + ("button", "hh-foot-aaaaaa", LEFT, UP), + ("frame", "hh-foot-aaaaaa"), + ] + + +def test_a_click_is_a_press_and_a_release_each_committed(harness): + harness.add() + lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"] + harness.fake.sink.calls.clear() + + reply = harness.run(harness.manager.pointer_click("foot-aaaaaa", lease, "left", 2)) + + assert reply["count"] == 2 + assert harness.fake.sink.calls == [ + ("button", "hh-foot-aaaaaa", LEFT, DOWN), + ("frame", "hh-foot-aaaaaa"), + ("button", "hh-foot-aaaaaa", LEFT, UP), + ("frame", "hh-foot-aaaaaa"), + ] * 2 + assert harness.manager.pointer.pressed() == [] + + +@pytest.mark.parametrize("bad", [0, 99, "two", True, 1.5]) +def test_a_click_count_off_the_wire_is_bounded(harness, bad): + harness.add() + lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"] + + with pytest.raises(ManagerError) as exc: + harness.run(harness.manager.pointer_click("foot-aaaaaa", lease, "left", bad)) + assert exc.value.error == "invalid_argument" + + +def test_an_unknown_button_is_refused_by_the_driver_not_invented(harness): + harness.add() + lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"] + + with pytest.raises(ManagerError) as exc: + harness.run(harness.manager.pointer_button("foot-aaaaaa", lease, "pinky", "down")) + + assert exc.value.error == "driver_refused" + assert harness.manager.pointer.pressed() == [], "a refused press must not be mirrored" + + +# --------------------------------------------------------------------------- +# releasing and expiry +# --------------------------------------------------------------------------- + + +def test_release_lifts_what_was_down_and_stamps_the_record(harness): + session = harness.add() + lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"] + harness.run(harness.manager.pointer_move("foot-aaaaaa", lease, x=0.4, y=0.6)) + harness.run(harness.manager.pointer_button("foot-aaaaaa", lease, "left", "down")) + + reply = harness.run(harness.manager.pointer_release("foot-aaaaaa", lease)) + + assert reply["buttons_lifted"] == ["left"] + assert reply["released_by"] == "lease" + assert reply["bookmark"]["x"] == 0.4 + assert session.pointer["released_by"] == "lease" + assert session.pointer["last_released_at"] == reply["released_at"] + assert harness.manager.pointer.state()["holder"] is None + + +def test_an_idle_lease_expires_and_the_button_it_left_down_is_lifted(harness): + """The order is the contract's: `pressed()` is read before `expire()`, + because `expire()` drops the lease's button set with the lease.""" + + session = harness.add() + lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"] + harness.run(harness.manager.pointer_button("foot-aaaaaa", lease, "left", "down")) + harness.clock.advance(31.0) + + expired = harness.run(harness.manager._expire_pointer()) + + assert expired == { + "session": "foot-aaaaaa", + "lease_id": lease, + "buttons_lifted": ["left"], + } + assert harness.manager.pointer.state()["holder"] is None + assert harness.fake.sink.calls[-2:] == [ + ("button", "hh-foot-aaaaaa", LEFT, UP), + ("frame", "hh-foot-aaaaaa"), + ] + assert session.pointer["released_by"] == "timeout" + + +def test_an_expired_lease_is_noticed_by_the_next_verb_as_well(harness): + """So the cursor is free for someone else even with no sweep in between.""" + + harness.add("foot-aaaaaa") + harness.add("foot-bbbbbb") + harness.run(harness.manager.pointer_acquire("foot-aaaaaa")) + harness.clock.advance(31.0) + + reply = harness.run(harness.manager.pointer_acquire("foot-bbbbbb")) + + assert reply["id"] == "foot-bbbbbb" + assert harness.manager.pointer.state()["holder"] == "foot-bbbbbb" + + +def test_a_refresh_loop_still_loses_the_cursor_at_the_hard_cap(harness): + """A stuck agent must not be able to hold the mouse forever.""" + + harness.add() + lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"] + for _ in range(12): + harness.clock.advance(25.0) + try: + harness.run(harness.manager.pointer_move("foot-aaaaaa", lease, x=0.5, y=0.5)) + except ManagerError as exc: + assert exc.error == "no_lease" + break + else: # pragma: no cover - the cap did not fire + pytest.fail("the hard cap never expired the lease") + + assert harness.manager.pointer.state()["holder"] is None + + +def test_a_caller_supplied_ttl_applies_to_this_lease_and_then_goes_away(harness): + harness.add("foot-aaaaaa") + harness.add("foot-bbbbbb") + harness.run(harness.manager.pointer_acquire("foot-aaaaaa", ttl_s=5.0)) + harness.clock.advance(6.0) + + assert harness.run(harness.manager._expire_pointer()) is not None + assert harness.manager.pointer.ttl_s == 30.0, "the default must come back" + + harness.run(harness.manager.pointer_acquire("foot-bbbbbb")) + harness.clock.advance(6.0) + assert harness.run(harness.manager._expire_pointer()) is None + + +def test_a_ttl_beyond_the_hard_cap_is_refused(harness): + harness.add() + + with pytest.raises(ManagerError) as exc: + harness.run(harness.manager.pointer_acquire("foot-aaaaaa", ttl_s=10_000)) + assert exc.value.error == "invalid_argument" + assert harness.manager.pointer.state()["holder"] is None + + +def test_expiry_with_no_driver_is_loud_rather_than_silent(harness, caplog): + """A button we could not lift is the one thing that must never be quiet.""" + + harness.add() + lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"] + harness.run(harness.manager.pointer_button("foot-aaaaaa", lease, "left", "down")) + harness.fake.stop() + harness.clock.advance(31.0) + + with caplog.at_level("ERROR"): + harness.run(harness.manager._expire_pointer()) + + assert "a button may still be down" in caplog.text + assert harness.manager.pointer.state()["holder"] is None + + +# --------------------------------------------------------------------------- +# the rest of the contract +# --------------------------------------------------------------------------- + + +def test_no_pointer_verb_counts_as_activity(harness): + """A session being clicked in is still one nobody has asked to keep.""" + + session = harness.add() + before = (session.last_activity_boottime, session.command_count) + harness.clock.advance(100.0) + + lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"] + harness.run(harness.manager.pointer_move("foot-aaaaaa", lease, x=0.5, y=0.5)) + harness.run(harness.manager.pointer_click("foot-aaaaaa", lease)) + harness.manager.pointer_state() + harness.run(harness.manager.pointer_release("foot-aaaaaa", lease)) + + assert (session.last_activity_boottime, session.command_count) == before + + +def test_pointer_state_names_the_holder_and_what_is_down(harness): + harness.add() + assert harness.manager.pointer_state()["holder"] is None + + lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"] + harness.run(harness.manager.pointer_button("foot-aaaaaa", lease, "right", "down")) + + state = harness.manager.pointer_state() + assert state["holder"] == "foot-aaaaaa" + assert state["lease_id"] == lease + assert state["buttons"] == ["right"] + assert state["bookmark"]["output"] == "hh-foot-aaaaaa" + + +def test_a_dead_session_cannot_be_aimed_at(harness): + session = harness.add() + harness.manager.registry.terminate(session, State.EXITED) + + with pytest.raises(ManagerError) as exc: + harness.run(harness.manager.pointer_acquire("foot-aaaaaa")) + assert exc.value.error == "session_exited" + + +def test_an_unknown_session_is_three_not_a_lease_error(harness): + with pytest.raises(ManagerError) as exc: + harness.run(harness.manager.pointer_acquire("nope-zzzzzz")) + assert exit_code_for(exc.value.error) == ExitCode.NO_SUCH_SESSION + + +def test_no_driver_configured_at_all_is_reported_as_unavailable(short_tmpdir: Path): + manager = SessionManager( + ManagerConfig( + state_dir=short_tmpdir / "state", + runtime_dir=short_tmpdir / "run", + policy=Policy(), + # Explicitly nothing, rather than the derived default. + pointer_socket=short_tmpdir / "no-driver-here.sock", + ), + clock=ManualClock(boottime=1000.0), + ) + manager.registry.add(make_session()) + + with pytest.raises(ManagerError) as exc: + asyncio.run(manager.pointer_acquire("foot-aaaaaa")) + assert exc.value.error == "driver_unavailable" + + +def test_releasing_with_someone_elses_lease_lifts_nothing(harness): + """The refusal has to come before anything reaches the driver. + + Otherwise ``pointer.release`` is a way for any session to drop the + holder's buttons mid-drag on its way to being told no. + """ + + harness.add("foot-aaaaaa") + harness.add("foot-bbbbbb") + lease = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"] + harness.run(harness.manager.pointer_button("foot-aaaaaa", lease, "left", "down")) + harness.fake.sink.calls.clear() + + with pytest.raises(ManagerError) as exc: + harness.run(harness.manager.pointer_release("foot-bbbbbb", lease)) + + assert exc.value.error == "no_lease" + assert harness.fake.sink.calls == [] + assert harness.manager.pointer.pressed() == ["left"] + assert harness.manager.pointer.state()["holder"] == "foot-aaaaaa" + + +def test_a_stale_lease_id_cannot_release_the_current_one(harness): + harness.add() + first = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"] + harness.run(harness.manager.pointer_release("foot-aaaaaa", first)) + second = harness.run(harness.manager.pointer_acquire("foot-aaaaaa"))["lease_id"] + + with pytest.raises(ManagerError) as exc: + harness.run(harness.manager.pointer_release("foot-aaaaaa", first)) + + assert exc.value.error == "no_lease" + assert harness.manager.pointer.state()["lease_id"] == second + + +def test_the_sweeper_expires_a_lease_nobody_came_back_for(short_tmpdir: Path): + """The TTL is only a promise if something checks it unprompted. + + An agent that acquired, pressed a button and died would otherwise hold the + cursor — with the button down — until some other session happened to try. + """ + + fake = FakeDriver(short_tmpdir / "p.sock") + clock = ManualClock(boottime=1000.0) + manager = SessionManager( + ManagerConfig( + state_dir=short_tmpdir / "state", + runtime_dir=short_tmpdir / "run", + policy=Policy(), + pointer_socket=fake.socket_path, + pointer_ttl_s=30.0, + # Short, so the test waits on the sweep and not on the TTL; the + # TTL itself is the injected clock's business. + pointer_sweep_s=0.01, + ), + clock=clock, + ) + session = manager.registry.add(make_session()) + + async def scenario(): + lease = (await manager.pointer_acquire("foot-aaaaaa"))["lease_id"] + await manager.pointer_button("foot-aaaaaa", lease, "left", "down") + sweeper = asyncio.create_task(manager._sweep_pointer()) + clock.advance(31.0) + for _ in range(500): + await asyncio.sleep(0.01) + if manager.pointer.state()["holder"] is None: + break + sweeper.cancel() + with pytest.raises(asyncio.CancelledError): + await sweeper + + try: + asyncio.run(scenario()) + assert manager.pointer.state()["holder"] is None + assert fake.dispatcher._pressed == {}, "the sweep lifted it on the driver" + assert session.pointer["released_by"] == "timeout" + finally: + if manager.driver is not None: + manager.driver.close() + fake.stop() diff --git a/tests/sessions/unit/test_registry.py b/tests/sessions/unit/test_registry.py index 27a2adb..0faa63d 100644 --- a/tests/sessions/unit/test_registry.py +++ b/tests/sessions/unit/test_registry.py @@ -11,11 +11,15 @@ import pytest from hhstreamd.clock import ManualClock from hhstreamd.registry import ( + ContainerState, Registry, Session, State, atomic_write_json, + container_record, + migrate, mint_id, + pointer_record, ) @@ -267,4 +271,103 @@ def test_derived_fields_reported_to_callers(registry: Registry): assert public["idle_s"] == 600.0 assert public["expires_in_s"] == 10800.0 - 600.0 assert public["live"] is True - assert public["schema"] == 2 + assert public["schema"] == 3 + + +# --------------------------------------------------------------------------- +# schema 3: the container, the pointer and the instance signature (PLAN §7) +# --------------------------------------------------------------------------- + + +def test_a_record_with_no_container_says_so_and_does_not_hint(registry: Registry): + """`null` is "no spatial container", never "unknown but probably something".""" + + session = registry.add(make_session()) + public = session.public(now=1000.0) + + assert public["container"] is None + assert public["pointer"] is None, "absent means the pointer was never used here" + assert public["signature"] is None + + +def test_the_container_sub_record_keeps_every_unverified_field_null(): + """Degraded has a *state* long before it has an output to name.""" + + degraded = container_record( + output=None, workspace=None, mode=None, created_by="broker", state=ContainerState.DEGRADED + ) + + assert degraded == { + "output": None, + "workspace": None, + "mode": None, + "created_by": "broker", + "state": "degraded", + } + + +def test_a_container_record_round_trips_through_the_mirror(tmp_path: Path): + registry = Registry(tmp_path, ManualClock(boottime=1000.0)) + registry.ensure_dirs() + session = make_session( + container=container_record( + output="hh-foot-aaaaaa", + workspace=1003, + mode=(1280, 720), + created_by="broker", + state=ContainerState.OWNED, + ), + pointer=pointer_record( + bookmark={"x": 0.42, "y": 0.61, "output": "hh-foot-aaaaaa", "at": "2026-10-01T09:14:02Z"}, + last_released_at="2026-10-01T09:20:00Z", + released_by="lease", + ), + signature="efb5deadbeef", + ) + registry.add(session) + + (restored,), quarantined = Registry(tmp_path, ManualClock()).load_records() + + assert quarantined == [] + assert restored.container["output"] == "hh-foot-aaaaaa" + assert restored.container["mode"] == {"width": 1280, "height": 720} + assert restored.pointer["bookmark"]["x"] == 0.42 + assert restored.signature == "efb5deadbeef" + + +def test_a_schema_two_record_is_adopted_and_not_rejected(tmp_path: Path): + """Its application is still running; refusing the record would strand it.""" + + registry = Registry(tmp_path, ManualClock(boottime=1000.0)) + registry.ensure_dirs() + old = make_session().to_dict() + for gone in ("container", "pointer", "signature"): + del old[gone] + old["schema"] = 2 + atomic_write_json(registry.record_path("foot-aaaaaa"), old) + + (restored,), quarantined = registry.load_records() + + assert quarantined == [] + assert restored.id == "foot-aaaaaa" + assert restored.schema == 3 + # The honest value for everything schema 3 added: the daemon that wrote + # this record knew nothing of containers, so there is nothing to claim. + assert (restored.container, restored.pointer, restored.signature) == (None, None, None) + + +def test_migrating_never_overwrites_a_field_that_was_already_there(): + """Only ever additive: the field is new to the schema, not to the session.""" + + migrated = migrate({"schema": 2, "id": "a", "container": {"state": "owned"}}) + + assert migrated["container"] == {"state": "owned"} + assert migrated["schema"] == 3 + + +def test_a_record_from_a_newer_schema_is_read_not_guessed_at(caplog): + with caplog.at_level("ERROR"): + migrated = migrate({"schema": 99, "id": "a"}) + + assert migrated["schema"] == 99, "its number is not ours to rewrite" + assert "newer than this daemon" in caplog.text