the surface: CLI verbs, the module's options, and three checks the compositor votes in

Everything below the CLI was merged and green against fakes; none of it was
reachable and none of it had ever met a compositor. This wires it up and then
puts the compositor in a position to disagree.

CLI (src/hhstream/cli.py, src/hhstream_session/**)

  session container [ID], session reconcile [ID], and the seven pointer verbs
  from PLAN §9. `start` still prints the bare session id and nothing else.
  `list` gains WS / OUTPUT / POINTER, with the gap marker where a value is
  genuinely unknown rather than a blank that reads as zero -- the POINTER
  column needs a second, read-only `pointer.state` call because the `list`
  reply carries no lease state.

  The lease id is cached in `hhstream_session.lease` (under
  $XDG_RUNTIME_DIR), because PLAN §9's gesture verbs take no --lease and the
  wire requires a lease_id on every one of them; --lease and $HHSTREAM_LEASE
  override it, and a `no_lease` refusal drops the stale entry.

  Exit codes are the contract's: a gesture with no lease is 9 and never
  reaches the broker, and a compositor failure is 10 with a message that says
  the session is still running. `kill` now warns about
  `session.container_survivors` -- windows the compositor still shows -- and
  distinguishes `null` ("could not ask") from `[]`.

  `shot`/`record --output NAME` capture one container through `grim -o`; the
  frame socket publishes the main output only, so it cannot do it.

Module (nix/module.nix)

  sessions.containers.{enable,max,mode,workspaceBase},
  sessions.pointer.{enable,leaseTtl,leaseMax}, rendered into the generated
  TOML with §10's key names. hhstream-pointer.service: the operator's account,
  supplementary group hhstream, After=/BindsTo= the compositor,
  Restart=on-failure, KillMode=process, and the command line §3.4 freezes.
  tmpfiles for /run/hhstream plus RuntimeDirectoryPreserve on the broker,
  without which restarting the broker deletes the driver's socket out from
  under it. The runtime-directory length assertion is untouched.

  And ExecStartPost on the compositor, opening its IPC directory to its own
  group: Hyprland creates <runtime>/hypr with S_IRWXU, so the broker -- a
  different account by design -- could not reach the request or event socket
  at all, and degraded silently exactly as it is built to.

Checks (checks/**)

  vm-ipc: both sockets at their frozen names, measured against sun_path's 108
  bytes, and a socket2 subscriber that receives an openwindow for a window the
  test creates. The subscriber is the shipped HyprlandIPC, not a second
  implementation: this check exists to prove that this client hears this
  compositor.

  vm-containers: one hh-* output per session at the container mode, the window
  on it, a second window of the same application beside it, an unmatched
  window quarantined, grim -o isolating one container, teardown removing the
  output and freeing the slot. PLAN experiment 3 is answered: `hyprctl output
  create headless` works.

  vm-pointer: a version-2 virtual pointer, a warp and a click whose
  coordinates the *application* reports, BUSY naming the holder, an expired
  lease swept with its held button lifted, and a broker restart that leaves
  the lock free, the bookmark intact and the driver reachable.

  checks/lib gains the guest the three share, their test-script helpers (no
  assertions live there), an event-socket subscriber and a Wayland client that
  says where it was clicked -- nothing in nixpkgs both honours
  $HHSTREAM_APP_ID and reports pointer events.

Reported, not worked around: the broker reads none of the container or
pointer config (policy.py takes [defaults] and [apps] only), `start` has no
no_container field so --no-container is refused rather than silently ignored,
and nix/hyprland-conf.nix sets input:follow_mouse = 0, which sends pointer
events to the focused window only -- measured, with the cursor at the aimed
pixel and no client told. README.dev.md has the evidence for each.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WQy29x9AfHWyzNd1f7XPGK
This commit is contained in:
HermenixandClaude Opus 5 committed 2026-10-03 06:58:44 +00:00
1 parent 57fdd4f636
commit de408e4b7f
19 files changed
+4304 -98

No files matched your search

+28 -5
View File
@@ -1,11 +1,22 @@
# The flake's `checks` output. One file per check; this is only the wiring.
#
# unit -- pytest over tests/unit/, against the nix/package.nix build
# vm-basic -- nixosTest with a fake capture backend: module + wire contract
# vm-hyprland -- nixosTest with the real compositor and grim
# vm-sessions -- nixosTest with the real compositor and the session broker
# unit -- pytest over tests/, against the nix/package.nix build
# vm-basic -- nixosTest with a fake capture backend: module + wire contract
# vm-hyprland -- nixosTest with the real compositor and grim
# vm-sessions -- nixosTest with the real compositor and the session broker
# vm-ipc -- the compositor's IPC sockets, and an event that arrives
# vm-containers -- one output and one workspace per session
# vm-pointer -- the lease, the driver, and a click the application saw
#
# Everything the guests need lives in checks/lib/test-tools.nix.
# What the guests need lives in checks/lib: `test-tools.nix` for the fake
# capture and the contract asserter, `session-tools.nix` for the event
# subscriber and the pointer target, `session-machine.nix` for the guest the
# three session checks share, and `session-prelude.nix` for their test-script
# helpers.
#
# Run them ONE AT A TIME. Each boots a VM with a software-rendered compositor;
# two at once on a two-core machine make the timing-sensitive assertions flake,
# and a flaky green is worth less than a slow one.
{
pkgs,
self,
@@ -15,6 +26,12 @@ let
hhstream = self.packages.${system}.hhstream;
hhsModule = self.nixosModules.default;
testTools = pkgs.callPackage ./lib/test-tools.nix { };
# The three session checks take the same five arguments; naming them once
# keeps a new check from being wired up with a different compositor or a
# different package than its neighbours.
sessionArgs = {
inherit hhstream hhsModule testTools;
};
in
{
unit = pkgs.callPackage ./unit.nix { inherit hhstream; };
@@ -30,4 +47,10 @@ in
vm-sessions = pkgs.callPackage ./vm-sessions.nix {
inherit hhstream hhsModule testTools;
};
vm-ipc = pkgs.callPackage ./vm-ipc.nix sessionArgs;
vm-containers = pkgs.callPackage ./vm-containers.nix sessionArgs;
vm-pointer = pkgs.callPackage ./vm-pointer.nix sessionArgs;
}
+112
View File
@@ -0,0 +1,112 @@
#!/usr/bin/env python3
"""Subscribe to the compositor's event socket and write what arrives.
This is ``vm-ipc``'s witness, and it runs the **shipped** client
(:class:`hhstreamd.ipc.HyprlandIPC`) rather than a second implementation of
the same parsing. That is the opposite choice from ``tests/assert_stream.py``,
which is deliberately independent of ``hhstream.client`` so a shared framing
bug still fails -- and the reason for the difference is what each check is
for. ``vm-basic`` asserts a wire format two programs must agree on; this one
asserts that *this* client, against *this* compositor, receives events at all.
That is the defect it is pointed at. The compositor's event socket is
``<runtime dir>/hypr/<signature>/.socket2.sock``, and at the old 29-character
runtime directory the path did not fit in ``sun_path``:
ERR ]: Socket2 path is too long. (2) IPC will not work.
The *request* socket kept answering ``hyprctl`` -- both ends agreed on the
same truncated path -- so everything looked healthy while no event ever
arrived. Only a subscriber that waits for a named event can tell the
difference, which is why this program exists and why it reports what it saw
rather than just its exit status.
Every line it writes is flushed, so a caller can tail the file while the
compositor is still running.
"""
from __future__ import annotations
import argparse
import sys
import threading
import time
from pathlib import Path
from hhstreamd.ipc import CompositorUnavailable, HyprlandIPC
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(
prog="hhs-ipc-watch",
description="Record Hyprland events from the real event socket.",
)
parser.add_argument(
"--runtime-dir",
type=Path,
default=Path("/run/hypr-stream"),
help="the compositor's runtime directory (default: %(default)s)",
)
parser.add_argument(
"--out", type=Path, required=True, help="append every event here, one per line"
)
parser.add_argument(
"--await-event",
action="append",
default=[],
metavar="NAME",
help="exit 0 once this event has been seen; repeatable, all must arrive",
)
parser.add_argument(
"--timeout",
type=float,
default=120.0,
help="give up after this long and exit 1 (default: %(default)ss)",
)
args = parser.parse_args(argv)
try:
ipc = HyprlandIPC.discover(args.runtime_dir)
except CompositorUnavailable as exc:
print(f"hhs-ipc-watch: {exc}", file=sys.stderr)
return 1
out = args.out.open("a", encoding="utf-8", buffering=1)
print(f"watching {args.runtime_dir} for {args.await_event or 'everything'}", file=out)
wanted = set(args.await_event)
seen: set[str] = set()
deadline = time.monotonic() + args.timeout
# `events()` blocks in `recv`, so the deadline cannot be enforced from the
# same thread. Closing the socket from a timer is what unblocks it, and it
# is also what a real caller would have to do -- the contract's `events()`
# is explicitly a blocking iterator.
timer = threading.Timer(args.timeout, ipc.close)
timer.daemon = True
timer.start()
try:
for event in ipc.events():
print(f"{event.name}\t{event.data.get('raw', '')}", file=out)
if event.name in wanted:
seen.add(event.name)
if seen >= wanted:
print(f"saw {sorted(seen)}", file=out)
return 0
if time.monotonic() > deadline:
break
except CompositorUnavailable as exc:
print(f"event stream ended: {exc}", file=out)
finally:
timer.cancel()
ipc.close()
out.flush()
missing = sorted(wanted - seen)
print(f"TIMED OUT after {args.timeout}s; never saw {missing}", file=out)
print(f"hhs-ipc-watch: never saw {missing}", file=sys.stderr)
out.close()
return 1
if __name__ == "__main__":
sys.exit(main())
+269
View File
@@ -0,0 +1,269 @@
#!/usr/bin/env python3
"""A Wayland client that says where it was clicked, in its own words.
The VM checks need two things no application in nixpkgs gives them together:
* **a window that lands in its container.** The broker stamps a session's
identity into the environment only (``$HHSTREAM_APP_ID``, see
``hhstreamd/launcher.py``), because the alternative -- a per-app
``--app-id`` flag -- would have to come out of the allowlist. ``foot`` and
``wev`` ignore the environment and keep their own class, so their windows
match no per-session rule and are swept into quarantine. This client reads
the variable and sets ``xdg_toplevel.set_app_id`` to it, which is what the
rule ``match:initial_class ^hh-<id>$`` is written against.
* **a report of pointer events from the application's side.** PLAN §14 is
explicit that "a click lands where aimed" must be verified by reading back
*the application's* state and not by comparing pixels: a pixel comparison
proves the compositor drew a cursor, not that the client was told about a
button. Every event below is printed as the client received it, with the
surface-local coordinates the compositor sent, and flushed -- the broker
captures stdout into the session log, so ``hhstream session logs`` is the
read-back.
It is deliberately minimal and deliberately loud: it prints what it bound,
what size it was configured at, and every pointer event, so a check that fails
says whether the window was never mapped, never entered, or entered somewhere
other than where the warp aimed.
"""
from __future__ import annotations
import argparse
import mmap
import os
import signal
import struct
import sys
from pywayland.client import Display
from pywayland.protocol.wayland import WlCompositor, WlPointer, WlSeat, WlShm
from pywayland.protocol.xdg_shell import XdgWmBase
#: Opaque 32-bit colour. Something has to be in the buffer for the compositor
#: to map the surface at all, and a flat fill is the least that will do.
FILL = 0xFF3050A0
#: Fallback size for a compositor that configures 0x0 (meaning "you choose").
DEFAULT_SIZE = (640, 360)
def say(line: str) -> None:
"""One line, flushed. Unbuffered because the reader is a log tail."""
print(line, flush=True)
class Target:
def __init__(self, app_id: str, title: str, windows: int) -> None:
self.app_id = app_id
self.title = title
self.windows = windows
self.display: Display | None = None
self.compositor = None
self.shm = None
self.wm_base = None
self.seat = None
self.surfaces: list[_Window] = []
#: Last position the compositor reported, per surface, so a button
#: event can be printed with the place it happened. The protocol does
#: not put coordinates on `button`; `enter` and `motion` carry them.
self.pointer = None
# -- setup ---------------------------------------------------------
def run(self) -> int:
self.display = Display()
self.display.connect()
registry = self.display.get_registry()
registry.dispatcher["global"] = self._on_global
self.display.roundtrip()
missing = [
name
for name, value in (
("wl_compositor", self.compositor),
("wl_shm", self.shm),
("xdg_wm_base", self.wm_base),
("wl_seat", self.seat),
)
if value is None
]
if missing:
say(f"target: FATAL missing globals: {', '.join(missing)}")
return 1
self.wm_base.dispatcher["ping"] = lambda base, serial: base.pong(serial)
self.seat.dispatcher["capabilities"] = self._on_capabilities
for index in range(self.windows):
self.surfaces.append(_Window(self, index))
self.display.roundtrip()
say(f"target: app_id={self.app_id} windows={self.windows} pid={os.getpid()}")
while True:
# Blocking dispatch: this process exists to report events, so there
# is nothing to do between them and nothing to poll for.
if self.display.dispatch(block=True) < 0:
say("target: display disconnected")
return 1
def _on_global(self, registry, global_id: int, interface: str, version: int) -> None:
if interface == WlCompositor.name:
self.compositor = registry.bind(global_id, WlCompositor, min(version, 4))
elif interface == WlShm.name:
self.shm = registry.bind(global_id, WlShm, 1)
elif interface == XdgWmBase.name:
self.wm_base = registry.bind(global_id, XdgWmBase, min(version, 2))
elif interface == WlSeat.name and self.seat is None:
self.seat = registry.bind(global_id, WlSeat, min(version, 5))
def _on_capabilities(self, seat, capabilities: int) -> None:
if not capabilities & WlSeat.capability.pointer.value:
# Said out loud: a seat with no pointer capability is the headless
# case where nothing has ever created a virtual pointer, and it is
# indistinguishable from "the warp did not arrive" unless reported.
say("target: seat has no pointer capability yet")
return
if self.pointer is not None:
return
self.pointer = seat.get_pointer()
self.pointer.dispatcher["enter"] = self._on_enter
self.pointer.dispatcher["leave"] = self._on_leave
self.pointer.dispatcher["motion"] = self._on_motion
self.pointer.dispatcher["button"] = self._on_button
say("target: pointer bound")
# -- pointer -------------------------------------------------------
def _window_of(self, surface) -> "_Window | None":
for window in self.surfaces:
if window.surface == surface:
return window
return None
def _on_enter(self, pointer, serial, surface, x, y) -> None:
window = self._window_of(surface)
if window is not None:
window.at = (x, y)
say(f"pointer enter window={_name(window)} x={x:.2f} y={y:.2f}")
def _on_leave(self, pointer, serial, surface) -> None:
say(f"pointer leave window={_name(self._window_of(surface))}")
def _on_motion(self, pointer, time, x, y) -> None:
for window in self.surfaces:
# Motion carries no surface; the focused one is whichever was
# entered last, and with one window per container that is the only
# one. Recording it on all of them keeps the button line honest
# without inventing a focus model this client does not need.
window.at = (x, y)
say(f"pointer motion x={x:.2f} y={y:.2f}")
def _on_button(self, pointer, serial, time, button, state) -> None:
where = self.surfaces[0].at if self.surfaces else None
position = "x=? y=?" if where is None else f"x={where[0]:.2f} y={where[1]:.2f}"
say(
f"pointer button code={button} state="
f"{'pressed' if state else 'released'} {position}"
)
def _name(window: "_Window | None") -> str:
return "?" if window is None else str(window.index)
class _Window:
"""One toplevel: a surface, its xdg wrapper, and an shm buffer."""
def __init__(self, target: Target, index: int) -> None:
self.target = target
self.index = index
self.at: tuple[float, float] | None = None
self.size = DEFAULT_SIZE
self.buffer = None
self._pool = None
self._map: mmap.mmap | None = None
self.surface = target.compositor.create_surface()
self.xdg_surface = target.wm_base.get_xdg_surface(self.surface)
self.xdg_surface.dispatcher["configure"] = self._on_configure
self.toplevel = self.xdg_surface.get_toplevel()
# The whole reason this program exists rather than `wev`.
self.toplevel.set_app_id(target.app_id)
self.toplevel.set_title(f"{target.title}-{index}")
self.toplevel.dispatcher["configure"] = self._on_toplevel_configure
self.toplevel.dispatcher["close"] = lambda *_: sys.exit(0)
self.surface.commit()
def _on_toplevel_configure(self, toplevel, width, height, states) -> None:
if width and height:
self.size = (width, height)
def _on_configure(self, xdg_surface, serial) -> None:
xdg_surface.ack_configure(serial)
self._paint()
say(f"target: window {self.index} configured {self.size[0]}x{self.size[1]}")
def _paint(self) -> None:
width, height = self.size
stride = width * 4
size = stride * height
if self._map is None or self._map.size() < size:
self._allocate(size)
# A flat fill, written once per resize: the pixels are not the subject
# of any assertion, they only make the surface mappable.
self._map.seek(0)
self._map.write(struct.pack("<I", FILL) * (size // 4))
self.buffer = self._pool.create_buffer(
0, width, height, stride, WlShm.format.xrgb8888.value
)
self.surface.attach(self.buffer, 0, 0)
self.surface.damage(0, 0, width, height)
self.surface.commit()
def _allocate(self, size: int) -> None:
fd = os.memfd_create(f"hhs-target-{self.index}", 0)
os.ftruncate(fd, size)
self._map = mmap.mmap(fd, size)
self._pool = self.target.shm.create_pool(fd, size)
os.close(fd)
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(
prog="hhs-pointer-target",
description="A Wayland window that reports the pointer events it receives.",
)
parser.add_argument(
"--app-id",
default=None,
help="xdg_toplevel app id; the default is $HHSTREAM_APP_ID, which is how "
"a session's window rule finds its container",
)
parser.add_argument("--title", default="hhs-target")
parser.add_argument(
"--windows",
type=int,
default=1,
help="how many toplevels to open, all with the same app id",
)
args = parser.parse_args(argv)
app_id = args.app_id or os.environ.get("HHSTREAM_APP_ID")
if not app_id:
print(
"hhs-pointer-target: no --app-id and no $HHSTREAM_APP_ID; refusing to "
"guess, because the app id is the whole point of this program",
file=sys.stderr,
)
return 2
# The broker kills the process group; exit on the first signal rather than
# leaving the compositor to notice a dead client.
signal.signal(signal.SIGTERM, lambda *_: sys.exit(0))
signal.signal(signal.SIGINT, lambda *_: sys.exit(0))
return Target(app_id, args.title, max(1, args.windows)).run()
if __name__ == "__main__":
sys.exit(main())
+125
View File
@@ -0,0 +1,125 @@
# The guest the three session checks share: compositor, broker, one account.
#
# A function rather than a copy in each check, because what the three differ in
# is the *assertions*, not the machine, and three drifting copies of a machine
# definition is how a check quietly stops testing what its neighbour tests.
# Everything that varies is an argument; nothing here relaxes an assertion.
#
# It is a machine, not a test. `gpu-session.nix` supplies the two pieces of
# hardware a bare NixOS test machine lacks (see that file); this adds the
# module under test, the account applications run as, and the tools the guest
# needs to interrogate the compositor.
{
hhsModule,
hhstream,
hyprland,
testTools,
sessionTools,
foot,
jq,
procps,
grim,
coreutils,
dejavu_fonts,
}:
{
# The allowlist, as `sessions.apps` takes it.
apps,
pointer ? false,
# Only read when `pointer` is true; the module's own defaults otherwise.
leaseTtl ? 30,
leaseMax ? 300,
width ? 1280,
height ? 720,
fps ? 30,
sessionUser ? "hermes",
# Long enough that nothing is reaped by surprise mid-check, short enough that
# the number is visibly the test's and not the module's 3 h default.
idleTimeout ? 600,
# The group that owns the compositor's runtime directory. The module's
# default, named here because this fragment is a plain attribute set (the
# test driver's `nodes.<name>` does not take a function) and so cannot read
# it back out of `config`.
sessionGroup ? "hhstream",
# Appended to the generated hyprland.conf. Only `vm-pointer` uses it, and
# only for one line it has to override; see that file for the measurement.
extraConfig ? "",
}:
{
imports = [
hhsModule
./gpu-session.nix
];
services.hyprland-headless-stream = {
enable = true;
package = hhstream;
hyprlandPackage = hyprland;
inherit extraConfig;
# No `name`: the wildcard rule applies to whatever connector the virtio GPU
# gives this guest (see vm-hyprland.nix for why a check must not know it).
outputs = [
{
inherit width height;
refresh = fps;
}
];
sessions = {
enable = true;
user = sessionUser;
inherit apps idleTimeout;
pointer = {
enable = pointer;
inherit leaseTtl leaseMax;
};
};
};
# The module deliberately does not create this user: launched applications
# run as it, so it is normally a real person's account. `video` and `render`
# are what any client of this session needs to reach the GPU; the broker's
# unit adds the compositor's own group on top.
users.users.${sessionUser} = {
isNormalUser = true;
extraGroups = [
"video"
"render"
# The compositor's own group, on the *account*.
#
# The broker does not need this -- its unit has the group as a
# supplementary one, which is how the applications it launches reach the
# Wayland socket. This is for the other half of the CLI: `hhstream shot
# --output hh-<id>` runs grim as whoever typed it, and the frame socket
# and runtime directory are 0750/0660 owned by this group. The operator
# account on a real machine is in it for exactly that reason -- it is
# what `hhstream`'s `sg` re-exec exists to recover when a login predates
# the membership.
sessionGroup
];
};
# foot resolves "monospace" through fontconfig and refuses to start without a
# usable font; a NixOS test machine has `fonts.enableDefaultPackages = false`.
# One font, not the default set.
fonts.packages = [ dejavu_fonts ];
environment.systemPackages = [
testTools # hhs-hyprland-diagnostics
sessionTools # hhs-ipc-watch, hhs-pointer-target
hhstream # the CLI under test
hyprland # hyprctl: the compositor is the source of truth here
foot
grim # per-container capture, which is what an output *is* for
jq # the in-guest predicates the bounded waits poll
procps
coreutils
];
virtualisation = {
memorySize = 2048;
cores = 2;
diskSize = 4096;
graphics = false;
};
}
+219
View File
@@ -0,0 +1,219 @@
# The test-script helpers the three session checks share: how to run something
# as the session account, how to call the CLI, how to ask the compositor, and
# what to dump when an assertion fails.
#
# Helpers only. There is not one assertion in this file, deliberately: a shared
# prelude that asserted things would make each check's own script an incomplete
# account of what it proves, and the whole point of these scripts is that they
# can be read top to bottom when one of them goes red.
{
hhstream,
coreutils,
sessionUser,
compositorRuntime ? "/run/hypr-stream",
controlSocket ? "/run/hhstream/control.sock",
}:
''
import json
import time
USER = "${sessionUser}"
CONTROL = "${controlSocket}"
CONTROL_DIR = "/run/hhstream"
COMPOSITOR_RUNTIME = "${compositorRuntime}"
HHSTREAM = "${hhstream}/bin/hhstream"
TRUE = "${coreutils}/bin/true"
FALSE = "${coreutils}/bin/false"
# The module pins the compositor's XDG_RUNTIME_DIR; the instance signature
# under it is the only part not known ahead of time. Root may connect to the
# IPC socket even though it belongs to `hhstream`. Same shape as
# vm-hyprland.nix, which asks this for monitors.
HYPRCTL = (
"set -eu; "
f"sig=$(ls -1 {COMPOSITOR_RUNTIME}/hypr | head -n1); "
f"XDG_RUNTIME_DIR={COMPOSITOR_RUNTIME}"
" HYPRLAND_INSTANCE_SIGNATURE=$sig hyprctl -j"
)
#: A transient `systemd-run` unit inherits systemd's own minimal PATH, not
#: the guest's. That is an artefact of how these checks invoke things, not a
#: property of the system under test: a person's login has the system profile
#: on PATH, and `hhstream shot --output` looks `grim` up there. Measured, by
#: a check that failed with the CLI's own "grim is not on PATH, and --output
#: needs it" -- which is the right message and the wrong environment.
SYSTEM_PATH = "/run/current-system/sw/bin"
def as_user(command, env=""):
"""`command` (absolute path plus argv, never a shell) run as USER.
A transient unit rather than `su`, because it gives a clean argv with no
login shell in the middle, and `--pipe --wait` propagates the command's
own exit status -- which each check proves before anything depends on it.
"""
return (
"systemd-run --quiet --collect --pipe --wait"
f" --uid={USER} --setenv=HOME=/home/{USER}"
f" --setenv=PATH={SYSTEM_PATH} {env} -- {command}"
)
def background(unit, command, env="", user=None):
"""A transient unit that keeps running after the call returns.
For the programs a check must have running *before* the thing they
witness happens: the event subscriber, and a window that is not a
session.
No `--collect`: the unit has to stay loaded after it exits, because its
exit status is part of what is asserted, and a collected unit is
unloaded the moment it stops.
`user=None` means root, which is how the driver already reaches the
compositor's IPC socket (see HYPRCTL); pass USER for something that
should be subject to the same permissions an operator has.
"""
who = "" if user is None else f" --uid={user} --setenv=HOME=/home/{user}"
return (
f"systemd-run --quiet --unit={unit}{who}"
f" --setenv=PATH={SYSTEM_PATH} {env} -- {command}"
)
def compositor_env():
"""`--setenv` flags that point a Wayland client at this session.
The socket name is discovered, never assumed: the compositor binds the
first free `wayland-N`, and a crashed one leaves `wayland-0` behind.
"""
display = machine.succeed(
f"cd {COMPOSITOR_RUNTIME} && ls -1 wayland-* | grep -v '[.]lock$' | head -n1"
).strip()
assert display, f"no wayland socket in {COMPOSITOR_RUNTIME}"
return (
f"--setenv=XDG_RUNTIME_DIR={COMPOSITOR_RUNTIME}"
f" --setenv=WAYLAND_DISPLAY={display}"
)
def cli(args):
"""`hhstream session …` as USER, against the control socket."""
return as_user(f"{HHSTREAM} session --socket {CONTROL} {args}")
def cli_json(args, timeout=120):
"""Run a `--json` verb and parse what it printed. Fails loudly if it did not."""
out = machine.succeed(cli(args), timeout=timeout)
try:
return json.loads(out)
except json.JSONDecodeError:
raise AssertionError(f"not JSON from `session {args}`: {out!r}")
def compositor(resource):
"""`hyprctl -j <resource>`, parsed. The compositor is the authority here."""
return json.loads(machine.succeed(f"{HYPRCTL} {resource}", timeout=120))
def monitor_named(name):
for entry in compositor("monitors"):
if entry.get("name") == name:
return entry
return None
def wait_for(predicate, timeout, what, interval=1.0):
"""Poll a *Python* predicate to a deadline, and return its value.
`machine.wait_until_succeeds` can only wait on a shell command, which
forces anything with structure into jq. This is for the waits whose
condition is a parsed value -- "the client has reported a third button
event" -- where a shell pipeline would be both unreadable and quietly
wrong when `grep -c` prints 0 and exits 1.
It waits for an *event that must happen*, never for an assertion to come
good: every caller below asserts after it returns, not inside it.
"""
deadline = time.monotonic() + timeout
while True:
value = predicate()
if value:
return value
if time.monotonic() > deadline:
raise AssertionError(f"timed out after {timeout}s waiting for {what}")
time.sleep(interval)
def dump(label, session_id=None):
print(f"########## diagnostics: {label} ##########")
status, out = machine.execute("hhs-hyprland-diagnostics", timeout=300)
print(out)
print(f"----- hhs-hyprland-diagnostics exit {status} -----")
commands = [
"systemctl --no-pager --full status hhstream-sessions.service",
"journalctl --no-pager --boot --lines=200 --unit hhstream-sessions.service",
"systemctl --no-pager --full status hhstream-pointer.service",
"journalctl --no-pager --boot --lines=200 --unit hhstream-pointer.service",
f"ls -la {CONTROL_DIR} /var/lib/hhstream/sessions",
"ps -eo pid,ppid,pgid,sid,user,stat,comm,args --sort=pid",
cli("list --all"),
cli("container"),
cli("pointer state"),
]
if session_id:
commands += [
cli(f"status {session_id}"),
# Every session's captured output, not just the named one: when
# a pointer event goes to the wrong window, the wrong window's
# log is the evidence and the named session's is empty.
cli("list"),
# The application's own captured output: the only place a failed
# launch, or a pointer event that never arrived, explains itself.
cli(f"logs {session_id} --lines 200"),
]
for command in commands:
status, out = machine.execute(f"{command} 2>&1", timeout=180)
print(f"----- {command} (exit {status}) -----")
print(out)
for resource in ("monitors", "workspaces", "clients", "cursorpos"):
status, out = machine.execute(f"{HYPRCTL} {resource} 2>&1", timeout=180)
print(f"----- hyprctl {resource} (exit {status}) -----")
print(out)
print("########## end diagnostics ##########")
def bring_up(label="the session stack"):
"""Compositor, then broker, then the socket each exists to serve.
`wait_for_unit` alone is not enough for the broker and that is measured,
not assumed: the unit is `Type=simple` with no readiness protocol, so
systemd calls it active the instant it has forked. A daemon that exits
two milliseconds later and is restarted every second passes it. The
honest test of "it came up" is the socket plus a restart count of zero.
"""
try:
machine.wait_for_unit("hyprland-headless.service", timeout=300)
machine.wait_for_file(f"{COMPOSITOR_RUNTIME}/hypr", timeout=120)
machine.wait_for_unit("hhstream-sessions.service", timeout=180)
machine.wait_for_file(CONTROL, timeout=120)
machine.succeed("systemctl is-active hhstream-sessions.service")
restarts = machine.succeed(
"systemctl show -p NRestarts --value hhstream-sessions.service"
).strip()
assert restarts == "0", (
f"the broker has restarted {restarts} time(s) already: it is "
"crash-looping, not running"
)
except Exception:
dump(f"{label} did not come up")
raise
''
+55
View File
@@ -0,0 +1,55 @@
# The guest programs the session checks need, packaged with the interpreters
# they actually require.
#
# Separate from `test-tools.nix` because these two need things that one does
# not: `hhs-ipc-watch` imports the shipped `hhstreamd.ipc` (so it needs the
# package on PYTHONPATH -- it is the client under test, not a reimplementation
# of it), and `hhs-pointer-target` is a Wayland client (so it needs pywayland).
#
# Both are self-tested at build time, for the same reason test-tools.nix does
# it: a broken helper otherwise surfaces as a baffling VM failure three layers
# away, long after the thing that would have explained it scrolled past.
{
runCommandLocal,
python3,
hhstream,
}:
let
# pywayland for the Wayland client; nothing else, so an import error in the
# guest is a real missing dependency and not this file being generous.
waylandPython = python3.withPackages (ps: [ ps.pywayland ]);
in
runCommandLocal "hhstream-session-tools"
{
nativeBuildInputs = [ python3 ];
meta.description = "Event-socket witness and pointer target for the hhstream session checks";
} ''
mkdir -p $out/bin
# The event-socket subscriber runs the broker's own IPC client, so it is
# pointed at what nix/package.nix installed rather than at a copy.
cat > $out/bin/hhs-ipc-watch <<EOF
#!${python3}/bin/python3
import sys
sys.path.insert(0, "${hhstream}/${python3.sitePackages}")
sys.argv[0] = "hhs-ipc-watch"
exec(compile(open("${./ipc_watch.py}").read(), "${./ipc_watch.py}", "exec"))
EOF
install -Dm755 ${./pointer_target.py} $out/bin/hhs-pointer-target
chmod +x $out/bin/hhs-ipc-watch
sed -i '1s|.*|#!${waylandPython}/bin/python3|' $out/bin/hhs-pointer-target
# Proof that both start, that `hhstreamd.ipc` is importable through the path
# above, and that pywayland's xdg_shell bindings are present -- the three
# ways these could be broken without the guest ever saying so.
$out/bin/hhs-ipc-watch --help > /dev/null
$out/bin/hhs-pointer-target --help > /dev/null
${waylandPython}/bin/python3 -c 'from pywayland.protocol.xdg_shell import XdgWmBase'
# The target refuses to guess an app id, and the checks depend on that
# refusal being exit 2 rather than a window with somebody else's class.
if $out/bin/hhs-pointer-target; then
echo "hhs-pointer-target started with no app id; it must refuse" >&2
exit 1
fi
''
+355
View File
@@ -0,0 +1,355 @@
# checks.<system>.vm-containers -- one output and one workspace per session,
# proved against the compositor that has to create them.
#
# Everything under this has so far been proved against fakes. `hyprctl output
# create headless` is marked **[UNVERIFIED -- experiment 3]** in PLAN §5.1: it
# is *implied* by Hyprland requesting the headless backend as
# AQ_BACKEND_REQUEST_MANDATORY, and nobody had run it. If it does not work,
# this is where that is found out, and the right outcome is a red check that
# quotes the compositor rather than a softer assertion.
#
# ─── THE VICTIM, AND WHY IT IS NOT `foot` ────────────────────────────────────
# A session's window rule is `match:initial_class ^hh-<id>$`, and the broker's
# only lever on an application's class is the environment (`$HHSTREAM_APP_ID`,
# see `hhstreamd/launcher.py`): a per-app `--app-id` flag would have to come
# out of the allowlist. `foot` and `wev` ignore the environment and keep their
# own class, so their windows match no per-session rule -- which makes them
# excellent *unmatched* windows and useless as matched ones.
#
# So this check uses both, for the two different jobs:
#
# * `target`, a wrapper around `hhs-pointer-target` (checks/lib), reads
# $HHSTREAM_APP_ID and calls `xdg_toplevel.set_app_id` with it. Its windows
# are the ones that must land in their container.
# * `foot`, launched *outside* any session, is the window that matches
# nothing and must end up quarantined.
#
# The launcher's own docstring says a GTK or Qt application ignores all four
# variables and its rule will not bind. That is a real limitation of the
# design, and this check is deliberately written so it is visible: the matched
# case needs a cooperating client, and nothing here pretends otherwise.
# ─────────────────────────────────────────────────────────────────────────────
{
testers,
hhstream,
hhsModule,
testTools,
hyprland,
foot,
jq,
grim,
procps,
coreutils,
dejavu_fonts,
width ? 1280,
height ? 720,
sessionUser ? "hermes",
}:
testers.runNixOSTest (
{ pkgs, ... }:
let
tools = pkgs.callPackage ./lib/session-tools.nix { inherit hhstream; };
guest = import ./lib/session-machine.nix {
inherit
hhsModule
hhstream
hyprland
testTools
foot
jq
procps
grim
coreutils
dejavu_fonts
;
sessionTools = tools;
};
prelude = import ./lib/session-prelude.nix {
inherit hhstream coreutils sessionUser;
};
# The wrapper the launcher's docstring describes: "HHSTREAM_APP_ID for a
# wrapper script that knows what to do with it". `exec`, so the session's
# pid is the client's and the broker's kill handle stays correct -- the
# cmdline change that causes is explicitly tolerated (procmon, BUG-02).
target = pkgs.writeShellScript "hhs-target-wrapper" ''
exec ${tools}/bin/hhs-pointer-target --app-id "$HHSTREAM_APP_ID" "$@"
'';
in
{
name = "hhstream-vm-containers";
globalTimeout = 1800;
nodes.machine = guest {
inherit width height sessionUser;
apps = {
target = {
exec = "${target}";
# One caller-supplied argument, so the two-window subtest can ask for
# a second toplevel without a second allowlist entry.
argsAllow = [ "--windows=*" ];
};
};
};
testScript =
prelude
+ ''
MODE = (${toString width}, ${toString height})
start_all()
bring_up("the compositor and broker")
with subtest("the as-user wrapper propagates exit status"):
machine.succeed(as_user(TRUE), timeout=120)
machine.fail(as_user(FALSE), timeout=120)
with subtest("a fresh machine has one output and no containers"):
# The baseline every assertion below is a difference from. An
# `hh-*` output here would mean the compositor kept one from a
# previous boot, which it cannot -- so this also proves the
# start-up scan found nothing to clean up.
try:
before = [m["name"] for m in compositor("monitors")]
print(f"outputs before: {before}")
assert not [n for n in before if n.startswith("hh-")], before
listing = cli_json("container --json")
assert listing["containers"] == [], listing
assert listing["orphans"] == [], listing
except Exception:
dump("the machine did not start clean")
raise
with subtest("starting a session creates one output named hh-<id>"):
# PLAN §5.1 experiment 3: does `hyprctl output create headless`
# actually work on this instance? Everything else depends on it.
try:
session_id = machine.succeed(cli("start target"), timeout=180).strip()
print(f"session: {session_id}")
expected = f"hh-{session_id}"
record = cli_json(f"status --json {session_id}")["session"]
print(json.dumps(record["container"], indent=2, sort_keys=True))
container = record["container"]
assert container["state"] == "owned", (
f"the broker did not create a container: {container}. "
"If `state` is 'degraded' the compositor refused `output "
"create headless` -- read the journal above for its words."
)
assert container["output"] == expected, container
monitor = monitor_named(expected)
assert monitor is not None, (
f"the broker recorded {expected} but the compositor has "
f"{[m['name'] for m in compositor('monitors')]}"
)
print(json.dumps(monitor, indent=2, sort_keys=True))
assert (monitor["width"], monitor["height"]) == MODE, (
f"{expected} is {monitor['width']}x{monitor['height']}, not "
f"the container mode {MODE[0]}x{MODE[1]}"
)
workspace = container["workspace"]
assert workspace >= 1000, (
f"workspace {workspace} is outside the reserved band (1000+)"
)
except Exception:
dump("no container output was created", locals().get("session_id"))
raise
with subtest("the application's window is on that output, not elsewhere"):
# The compositor is the authority: the record saying `owned` only
# means the broker asked for an output, not that the window rule
# bound and the window went there.
try:
machine.wait_until_succeeds(
f"{HYPRCTL} clients | jq -e --arg m {expected}"
" 'any(.initialClass == $m)' >/dev/null",
timeout=120,
)
ours = [
c for c in compositor("clients") if c.get("initialClass") == expected
]
print(json.dumps(ours, indent=2, sort_keys=True))
assert len(ours) == 1, f"expected one window of ours, got {len(ours)}"
client = ours[0]
assert client["workspace"]["id"] == workspace, (
f"the window is on workspace {client['workspace']} and the "
f"container is {workspace}"
)
except Exception:
dump("the window did not land in its container", session_id)
raise
with subtest("a second window of the same application lands in the same one"):
# Same session, same app id, second toplevel. The rule matches on
# `initial_class`, so this is the case the rule is written for --
# and the one that would silently break if the rule were per-window
# rather than per-class.
try:
second = machine.succeed(
cli("start target -- --windows=2"), timeout=180
).strip()
second_expected = f"hh-{second}"
second_ws = cli_json(f"status --json {second}")["session"]["container"][
"workspace"
]
print(f"second session {second} on workspace {second_ws}")
machine.wait_until_succeeds(
f"{HYPRCTL} clients | jq -e --arg m {second_expected}"
" '[.[] | select(.initialClass == $m)] | length == 2' >/dev/null",
timeout=120,
)
windows = [
c
for c in compositor("clients")
if c.get("initialClass") == second_expected
]
print(json.dumps(windows, indent=2, sort_keys=True))
assert len(windows) == 2, windows
on = {w["workspace"]["id"] for w in windows}
assert on == {second_ws}, (
f"the two windows of one application are on workspaces {on}, "
f"not both on the container's {second_ws}"
)
# And they are in a different container from the first session:
# one output per session is the other half of the claim.
assert second_ws != workspace, (second_ws, workspace)
except Exception:
dump("the second window did not join its container", locals().get("second"))
raise
with subtest("a window matching no container is quarantined"):
# `foot` is launched outside any session, so it carries its own
# class and matches no per-session rule. Without the backstop it
# would appear on whatever output happened to be focused -- which
# is one of the two sessions' containers, i.e. in someone's screen
# capture. PLAN §5.2.
try:
machine.succeed(
background(
"stray",
"${foot}/bin/foot",
env=compositor_env(),
user=USER,
),
timeout=120,
)
machine.wait_until_succeeds(
f"{HYPRCTL} clients | jq -e 'any(.initialClass == \"foot\")' >/dev/null",
timeout=120,
)
stray = [c for c in compositor("clients") if c.get("initialClass") == "foot"]
print(json.dumps(stray, indent=2, sort_keys=True))
assert len(stray) == 1, stray
landed = stray[0]["workspace"]["name"]
assert landed == "special:quarantine", (
f"an unmatched window landed on workspace {landed!r}; the "
"quarantine backstop did not catch it, so it is sitting on "
"whatever output was focused"
)
except Exception:
dump("an unmatched window was not quarantined")
raise
with subtest("grim -o captures that container and only that container"):
# The reason a container is an *output* and not just a workspace
# (PLAN §5.4). Two captures of two different containers must differ
# -- and both must differ from a capture of the main output, which
# has the stray window on it.
try:
shots = {}
for name in (expected, second_expected):
path = f"/tmp/{name}.png"
# No compositor environment passed in: the CLI discovers
# the session itself, which is the part under test. It runs
# as the operator account, through grim, like a person.
machine.succeed(
as_user(f"{HHSTREAM} shot --output {name} --out {path}"),
timeout=180,
)
# PNG IHDR: width and height are two big-endian uint32 at
# byte 16. Read with od so no interpreter is involved.
geometry = machine.succeed(
f"od -An -tu4 -j16 -N8 --endian=big {path}"
).split()
shots[name] = (
geometry,
machine.succeed(f"sha256sum {path}").split()[0],
)
print(f"{name}: {geometry} sha {shots[name][1]}")
for name, (geometry, _) in shots.items():
assert geometry == [str(MODE[0]), str(MODE[1])], (
f"{name} captured at {geometry}, not the container mode "
f"{MODE[0]}x{MODE[1]}"
)
assert shots[expected][1] != shots[second_expected][1], (
"two different containers captured byte-identical images; "
"grim -o is not selecting an output"
)
except Exception:
dump("per-container capture did not isolate the containers")
raise
with subtest("an output that does not exist is refused, not invented"):
try:
code, out = machine.execute(
as_user(f"{HHSTREAM} shot --output hh-nothing --out /tmp/no.png")
+ " 2>&1",
timeout=120,
)
print(f"exit {code}: {out}")
assert code != 0, "capturing a non-existent output succeeded"
# grim's own words, passed through rather than replaced by a
# guess at what went wrong.
assert "hh-nothing" in out, out
machine.fail("test -e /tmp/no.png")
except Exception:
dump("a bad output name did not fail")
raise
with subtest("teardown removes the output and the compositor agrees"):
try:
reply = cli_json(f"kill --json {session_id}", timeout=180)
print(json.dumps(reply["session"]["container"], indent=2, sort_keys=True))
assert reply["ok"] is True, reply
assert reply["session"]["container_removed"] is True, reply["session"]
assert reply["session"]["container_survivors"] == [], (
"the compositor still shows windows for a session whose "
f"output was removed: {reply['session']['container_survivors']}"
)
machine.wait_until_succeeds(
f"{HYPRCTL} monitors | jq -e --arg m {expected}"
" 'all(.name != $m)' >/dev/null",
timeout=60,
)
assert monitor_named(expected) is None, (
f"{expected} is still an output after teardown"
)
except Exception:
dump("the container outlived its session", session_id)
raise
with subtest("the workspace slot comes back and a new session reuses the band"):
# Releasing the slot is what stops the band leaking: without it the
# fourth session on a 4-slot band would be refused for no reason.
try:
listing = cli_json("container --json")
print(json.dumps(listing, indent=2, sort_keys=True))
assert workspace not in listing["workspaces_in_use"], listing
assert listing["orphans"] == [], (
f"teardown left an orphan output behind: {listing['orphans']}"
)
third = machine.succeed(cli("start target"), timeout=180).strip()
third_ws = cli_json(f"status --json {third}")["session"]["container"][
"workspace"
]
print(f"third session {third} took workspace {third_ws}")
assert third_ws == workspace, (
f"the freed slot {workspace} was not reused; got {third_ws}"
)
except Exception:
dump("the workspace slot was not released", locals().get("third"))
raise
'';
}
)
+241
View File
@@ -0,0 +1,241 @@
# checks.<system>.vm-ipc -- the compositor's own IPC, against the real thing.
#
# This is the check that would have caught the `sun_path` defect, and that is
# its reason for existing. Hyprland's event socket lives at
#
# <runtime dir>/hypr/<HYPRLAND_INSTANCE_SIGNATURE>/.socket2.sock
#
# and at the old 29-character runtime directory that path did not fit in the
# 108 bytes a Unix socket address has:
#
# ERR ]: Socket2 path is too long. (2) IPC will not work.
#
# The *request* socket is shorter by one character and kept working, so
# `hyprctl` answered, every reconciliation that only ever asked `clients -j`
# looked healthy, and the event stream was simply dead. Nothing short of a
# subscriber that waits for a named event can tell those two apart -- so that
# is what the last subtest is, and the subscriber is the shipped
# `hhstreamd.ipc.HyprlandIPC`, not a reimplementation of it.
#
# Both socket paths are asserted by name and measured against the 108-byte
# limit with the numbers printed, because "it fits today" is a fact about this
# instance signature and the next compositor may choose a longer one.
#
# Habits copied from vm-hyprland and vm-sessions: every wait is bounded, each
# assertion is made once, and a failure dumps the compositor's diagnostics and
# the broker's journal before it propagates.
{
testers,
hhstream,
hhsModule,
testTools,
hyprland,
foot,
jq,
grim,
procps,
coreutils,
dejavu_fonts,
width ? 1280,
height ? 720,
sessionUser ? "hermes",
}:
testers.runNixOSTest (
{ pkgs, ... }:
let
tools = pkgs.callPackage ./lib/session-tools.nix { inherit hhstream; };
guest = import ./lib/session-machine.nix {
inherit
hhsModule
hhstream
hyprland
testTools
foot
jq
procps
grim
coreutils
dejavu_fonts
;
sessionTools = tools;
};
prelude = import ./lib/session-prelude.nix {
inherit hhstream coreutils sessionUser;
};
in
{
name = "hhstream-vm-ipc";
globalTimeout = 1800;
nodes.machine = guest {
inherit width height sessionUser;
apps.foot = {
exec = "${foot}/bin/foot";
# The daemon refuses unlisted arguments and this check passes none:
# `foot` with no argv opens a window, which is all the witness needs.
argsAllow = [ ];
};
};
testScript =
prelude
+ ''
import re
EVENTS = "/tmp/hypr-events.log"
#: linux/un.h: sun_path is 108 bytes including the terminating NUL.
SUN_PATH_MAX = 107
start_all()
bring_up("the compositor and broker")
with subtest("the as-user wrapper propagates exit status"):
# Every assertion below reads machine.succeed/fail through it, so a
# wrapper that swallowed the status would make them all vacuous.
machine.succeed(as_user(TRUE), timeout=120)
machine.fail(as_user(FALSE), timeout=120)
with subtest("both IPC sockets exist, at the names the contract freezes"):
# By name, not by glob. CONTRACT-sessions.md §5 fixes
# <runtime dir>/hypr/<signature>/.socket{,2}.sock, and the defect
# this check exists for was precisely the second of those two being
# absent while the first was there.
try:
signature = machine.succeed(
f"ls -1 {COMPOSITOR_RUNTIME}/hypr | head -n1"
).strip()
assert signature, "no instance directory under the runtime dir"
print(f"instance signature: {signature!r} ({len(signature)} chars)")
base = f"{COMPOSITOR_RUNTIME}/hypr/{signature}"
for name in (".socket.sock", ".socket2.sock"):
path = f"{base}/{name}"
kind = machine.succeed(f"stat -c %F {path}").strip()
assert kind == "socket", f"{path} is a {kind}, not a socket"
print(f"{path} ({len(path)} bytes of {SUN_PATH_MAX})")
assert len(path) <= SUN_PATH_MAX, (
f"{path} is {len(path)} bytes; sun_path holds "
f"{SUN_PATH_MAX}. The compositor cannot have bound this."
)
except Exception:
dump("an IPC socket is missing or does not fit in sun_path")
raise
with subtest("hyprctl answers over the request socket"):
try:
version = machine.succeed(f"{HYPRCTL} version", timeout=120)
print(version)
assert json.loads(version).get("tag"), "version carries no tag"
monitors = compositor("monitors")
assert monitors, "hyprctl reported no monitors at all"
print(
"monitors: "
+ ", ".join(f"{m['name']} {m['width']}x{m['height']}" for m in monitors)
)
except Exception:
dump("the request socket did not answer")
raise
with subtest("the broker's own IPC client reads the same facts"):
# The client under test, not hyprctl: `container` goes through
# ContainerHost -> HyprlandIPC -> the request socket, so a reply
# here is this repository's parser against this compositor.
try:
reply = cli_json("container --json")
print(json.dumps(reply, indent=2, sort_keys=True))
assert reply["compositor"] == "ok", (
f"the broker cannot reach the compositor: {reply.get('error')!r}"
)
assert reply["orphans"] == [], (
f"a fresh machine already has orphan outputs: {reply['orphans']}"
)
except Exception:
dump("the broker's IPC client could not reach the compositor")
raise
with subtest("a socket2 subscriber receives openwindow for a window we create"):
# THE assertion. The subscriber is started first and left blocking
# on the event socket; the window is created after it is listening,
# so an `openwindow` in its log can only have come down the stream.
#
# If the event socket were the truncated one, everything above this
# point would still pass and this would time out -- which is the
# whole shape of the defect.
try:
machine.succeed(f"rm -f {EVENTS}")
machine.succeed(
background(
"ipc-watch",
"/run/current-system/sw/bin/hhs-ipc-watch"
f" --runtime-dir {COMPOSITOR_RUNTIME} --out {EVENTS}"
" --await-event openwindow --timeout 180",
),
timeout=120,
)
# Wait for the subscriber to be connected, not merely spawned:
# it writes its first line after `discover()` has returned and
# before it blocks, so the file appearing is the handshake.
machine.wait_for_file(EVENTS, timeout=60)
print(machine.succeed(f"cat {EVENTS}"))
session_id = machine.succeed(cli("start foot"), timeout=180).strip()
print(f"session: {session_id}")
# One bounded wait, for the unit to exit 0 -- which it does only
# when it has seen the event it was told to await.
machine.wait_until_fails(
"systemctl is-active ipc-watch.service", timeout=120
)
received = machine.succeed(f"cat {EVENTS}")
print(received)
result = machine.succeed(
"systemctl show -p Result --value ipc-watch.service"
).strip()
assert result == "success", (
f"the subscriber exited {result!r}: it never saw an openwindow "
"event. The request socket answers (above) and the event "
"socket does not -- which is exactly the sun_path defect."
)
assert "openwindow" in received, received
except Exception:
dump("no openwindow reached the event subscriber", locals().get("session_id"))
raise
with subtest("the event named the window the compositor also reports"):
# The event is not taken on trust: `openwindow>>address,workspace,
# class,title` carries an address, and the compositor's own client
# list has to agree that such a window exists.
try:
line = [
row
for row in machine.succeed(f"cat {EVENTS}").splitlines()
if row.startswith("openwindow\t")
][0]
payload = line.split("\t", 1)[1]
address = payload.split(",")[0]
print(f"openwindow payload: {payload!r} -> address {address!r}")
assert re.fullmatch(r"[0-9a-f]+", address), (
f"openwindow's first field is not an address: {address!r}"
)
addresses = [c["address"] for c in compositor("clients")]
print(f"compositor clients: {addresses}")
assert any(a.endswith(address) for a in addresses), (
f"the event announced {address} and `clients -j` has {addresses}"
)
except Exception:
dump("the openwindow event and the client list disagree")
raise
with subtest("teardown leaves the compositor with no client of ours"):
try:
reply = cli_json(f"kill --json {session_id}", timeout=180)
assert reply["ok"] is True, reply
machine.wait_until_succeeds(
f"{HYPRCTL} clients | jq -e 'length == 0' >/dev/null", timeout=60
)
except Exception:
dump("a client outlived its session", session_id)
raise
'';
}
)
+591
View File
@@ -0,0 +1,591 @@
# checks.<system>.vm-pointer -- the lease, the driver, and a click that lands.
#
# The lease's arithmetic is already proved by the unit suite with an injected
# clock. What no fake can prove is the half this check is for: that a warp
# through `zwlr_virtual_pointer_v1` reaches a real compositor, that the
# coordinates are the *output's* and not the desktop's, and that the button
# the broker sent arrives at the application underneath it.
#
# ─── "A CLICK LANDS WHERE IT WAS AIMED", AND WHY NOT PIXELS ──────────────────
# PLAN §14 says this must be verified by reading back the application's own
# state. A pixel comparison would prove the compositor drew a cursor
# somewhere; it would not prove any client was told about a button, and a
# cursor drawn at the right place with no `wl_pointer.button` delivered is
# precisely the failure a virtual pointer bound to the wrong output produces.
#
# So the victim is `hhs-pointer-target` (checks/lib/pointer_target.py), a
# Wayland client that prints every pointer event it receives with the
# surface-local coordinates the compositor sent it. The broker captures its
# stdout into the session log, so `hhstream session logs` is the read-back,
# and the assertion is on numbers the *client* reported.
#
# It also reads `$HHSTREAM_APP_ID` and sets its own `xdg_toplevel` app id from
# it, which is what gets its window into the container the pointer aims at.
# `foot` and `wev` cannot: they ignore the environment, so their windows are
# quarantined and there would be nothing under the cursor. See vm-containers.
# ─────────────────────────────────────────────────────────────────────────────
#
# The expiry subtest uses a caller-supplied `--ttl` of a few seconds and waits
# for it in real time. No clock is injected anywhere: an injected clock would
# prove the arithmetic the unit suite already proves, and not the sweeper, the
# driver call it makes, or the button it has to lift.
#
# `sessions.pointer.leaseTtl` is set on the machine anyway, and the acquire
# subtest *prints* it beside the TTL the broker reports. They disagree, and
# that is the point: the module renders the option into the generated TOML and
# `hhstreamd/policy.py` reads neither it nor any flag for it. Printed rather
# than asserted, because the broker is not this slice's file to change.
#
# ─── TWO THINGS THIS CHECK MEASURED, BOTH WORTH READING BEFORE EDITING IT ────
#
# 1. A WARP TO WHERE THE CURSOR ALREADY IS REPORTS NOTHING, and correctly so:
# nothing moved. It is only a trap for a check -- a second `acquire` that
# restores a bookmark the cursor never left delivers no `wl_pointer.motion`,
# so "the bookmark was restored" has no client-side evidence. The restore is
# therefore asserted on the broker's reply, where the bookmark lives, and
# *delivery* is asserted with a warp to somewhere the cursor is not.
#
# 2. `input:follow_mouse = 0` SENDS POINTER EVENTS TO THE FOCUSED WINDOW ONLY,
# and when the window under the cursor is not the focused one, to nobody at
# all. `nix/hyprland-conf.nix` ships it, justified by "No pointer will ever
# exist; do not let focus depend on one" -- a belief this build makes false.
#
# MEASURED, against the shipped config, with two sessions and the second
# one holding focus because its window opened last:
#
# aimed at target-le22h7: it reports [] <- the session the warp named
# focused is target-s76taj: it reports [] <- the session with focus
# cursor now at {'x': 2048, 'y': 288} <- EXACTLY where it was aimed
#
# The compositor moved the cursor to the right pixel, inside the right
# window, on the right output -- and told no client. The same warp and the
# same click are delivered perfectly in the subtests above, where the
# aimed-at session is also the focused one, which is why nothing before
# this check noticed.
#
# That defeats what containers and the lease exist for: an agent can only
# drive whichever session the compositor last focused. So this machine
# overrides the one line through the module's `extraConfig`, and the
# subtest "the cursor reaches a session that does not hold focus" is the
# assertion that goes red if the shipped default comes back.
# `nix/hyprland-conf.nix` is not this slice's file; the fix belongs there,
# and whether it should be `1` (Hyprland's own default, keyboard focus
# follows the cursor too) or a looser setting that leaves keyboard focus
# alone is a decision for the keyboard work in PLAN §6.7.
# ─────────────────────────────────────────────────────────────────────────────
{
testers,
hhstream,
hhsModule,
testTools,
hyprland,
foot,
jq,
grim,
procps,
coreutils,
dejavu_fonts,
width ? 1280,
height ? 720,
sessionUser ? "hermes",
# Short enough that the expiry subtest is seconds and not minutes, long
# enough that a `systemd-run` round trip inside the guest (several seconds)
# fits comfortably inside one lease.
leaseTtl ? 20,
leaseMax ? 120,
}:
testers.runNixOSTest (
{ pkgs, ... }:
let
tools = pkgs.callPackage ./lib/session-tools.nix { inherit hhstream; };
guest = import ./lib/session-machine.nix {
inherit
hhsModule
hhstream
hyprland
testTools
foot
jq
procps
grim
coreutils
dejavu_fonts
;
sessionTools = tools;
};
prelude = import ./lib/session-prelude.nix {
inherit hhstream coreutils sessionUser;
};
target = pkgs.writeShellScript "hhs-target-wrapper" ''
exec ${tools}/bin/hhs-pointer-target --app-id "$HHSTREAM_APP_ID" "$@"
'';
in
{
name = "hhstream-vm-pointer";
globalTimeout = 1800;
nodes.machine = guest {
inherit
width
height
sessionUser
leaseTtl
leaseMax
;
pointer = true;
apps.target = {
exec = "${target}";
argsAllow = [ ];
};
# Point 2 of the block at the top of this file. One line, overriding one
# line of nix/hyprland-conf.nix, because that file is not this slice's
# to edit -- not because there is any doubt about it.
extraConfig = "input:follow_mouse = 1";
};
testScript =
prelude
+ ''
import re
LEASE_TTL = ${toString leaseTtl}
POINTER_SOCKET = "/run/hhstream/pointer.sock"
#: wl_pointer surface coordinates are logical pixels. The budget covers
#: two things and nothing else: the protocol's integer extent (the
#: driver scales a normalised coordinate by 0xFFFF, so under a pixel on
#: a 1280-wide output) and Hyprland's default 2px border, which sits
#: between the window box `clients -j` reports and the surface the
#: client is given coordinates in. A pointer bound without an output
#: speaks *global* coordinates and would be out by hundreds, so this
#: tolerance does not blunt the assertion it guards.
TOLERANCE = 6.0
def pointer_log(session_id):
"""Every line the victim has printed so far."""
return machine.succeed(cli(f"logs {session_id} --lines 400"), timeout=120)
def positions(session_id):
"""(x, y) from every `enter`/`motion` line the client printed."""
found = []
for line in pointer_log(session_id).splitlines():
if line.startswith(("pointer enter", "pointer motion")):
pair = re.findall(r"[xy]=([-\d.]+)", line)
if len(pair) == 2:
found.append((float(pair[0]), float(pair[1])))
return found
def buttons(session_id):
"""(code, state, x, y) from every `button` line the client printed."""
found = []
for line in pointer_log(session_id).splitlines():
match = re.match(
r"pointer button code=(\d+) state=(\w+) x=([-\d.]+) y=([-\d.]+)",
line,
)
if match:
found.append(
(
int(match.group(1)),
match.group(2),
float(match.group(3)),
float(match.group(4)),
)
)
return found
def aimed_at(nx, ny):
"""Where a warp to (nx, ny) of the output should land *in the surface*.
Computed from the compositor's own geometry rather than assumed to
be a fraction of the window: Hyprland's default layout leaves 20px
outer gaps, so the window is not the output and the centre of one
is not the centre of the other. Asking `monitors` and `clients`
for both boxes is what makes this an assertion about aiming rather
than about the layout.
"""
monitor = monitor_named(output)
client = [c for c in compositor("clients") if c.get("initialClass") == output][0]
at = client["at"]
return (
monitor["x"] + nx * monitor["width"] - at[0],
monitor["y"] + ny * monitor["height"] - at[1],
)
def close_enough(got, want):
return abs(got[0] - want[0]) <= TOLERANCE and abs(got[1] - want[1]) <= TOLERANCE
start_all()
bring_up("the compositor and broker")
with subtest("the driver unit comes up and binds its socket"):
# Same reasoning as the broker's: `Type=simple` means wait_for_unit
# passes against a crash loop, so the socket and a restart count of
# zero are the honest test. The driver refuses to start at all if
# the compositor offers only a version-1 virtual-pointer manager --
# that refusal is deliberate (coordinates would be global and every
# warp would aim at the wrong output) and shows here as a restart
# loop with its own words in the journal.
try:
machine.wait_for_unit("hhstream-pointer.service", timeout=180)
machine.wait_for_file(POINTER_SOCKET, timeout=120)
machine.succeed("systemctl is-active hhstream-pointer.service")
restarts = machine.succeed(
"systemctl show -p NRestarts --value hhstream-pointer.service"
).strip()
assert restarts == "0", (
f"the driver has restarted {restarts} time(s); read its journal"
)
print(
machine.succeed(
"journalctl --no-pager --boot --unit hhstream-pointer.service"
)
)
except Exception:
dump("the pointer driver did not come up")
raise
with subtest("the broker reports the driver and a free cursor"):
try:
state = cli_json("pointer state --json")
print(json.dumps(state, indent=2, sort_keys=True))
assert state["holder"] is None, state
assert state["buttons"] == [], state
assert state["driver"] == POINTER_SOCKET, state
except Exception:
dump("pointer state is not what a fresh broker should report")
raise
with subtest("a session's window is in its container, under the cursor"):
try:
session_id = machine.succeed(cli("start target"), timeout=180).strip()
output = f"hh-{session_id}"
print(f"session {session_id} -> {output}")
machine.wait_until_succeeds(
f"{HYPRCTL} clients | jq -e --arg m {output}"
" 'any(.initialClass == $m)' >/dev/null",
timeout=120,
)
client = [
c for c in compositor("clients") if c.get("initialClass") == output
][0]
print(json.dumps(client, indent=2, sort_keys=True))
print(json.dumps(monitor_named(output), indent=2, sort_keys=True))
except Exception:
dump("the victim never got a window in its container", locals().get("session_id"))
raise
with subtest("acquire takes the cursor and the seat grows a pointer"):
# The seat of a headless session has *no* pointer capability until
# something creates a virtual one: there is no input device here.
# So the client cannot have bound `wl_pointer` before this point,
# and "target: pointer bound" appearing after the first warp is the
# proof that the driver's `zwlr_virtual_pointer_v1` reached the
# seat -- not merely that the broker thinks it sent something.
try:
reply = cli_json(f"pointer acquire --json {session_id}", timeout=120)
print(json.dumps(reply, indent=2, sort_keys=True))
bookmark = reply["bookmark"]
assert bookmark["output"] == output, bookmark
assert (bookmark["x"], bookmark["y"]) == (0.5, 0.5), (
f"with no bookmark the cursor must go to the centre: {bookmark}"
)
# A GAP, printed rather than asserted: the module's
# `sessions.pointer.leaseTtl` is rendered into the generated
# TOML and the broker reads neither the TOML nor any flag for
# it, so the lease runs on the broker's own default. The number
# below is the evidence.
print(
f"module leaseTtl={LEASE_TTL}s, broker reports "
f"expires_in_s={reply['expires_in_s']}"
)
wait_for(
lambda: "target: pointer bound" in pointer_log(session_id),
timeout=60,
what="the client to bind wl_pointer",
)
print(pointer_log(session_id))
except Exception:
dump("acquire did not reach the compositor", session_id)
raise
with subtest("a warp lands where it was aimed, as the application saw it"):
# Aimed off-centre so a wrong answer cannot coincide with the
# centre the acquire already warped to.
try:
aim = (0.25, 0.75)
before = len(positions(session_id))
moved = cli_json(
f"pointer move --json {session_id} --to {aim[0]},{aim[1]}", timeout=120
)
print(json.dumps(moved, indent=2, sort_keys=True))
assert (moved["bookmark"]["x"], moved["bookmark"]["y"]) == aim, moved
seen = wait_for(
lambda: positions(session_id)[before:],
timeout=60,
what="the client to report the warp",
)
want = aimed_at(*aim)
print(f"the client reports {seen}, aimed at {want}")
assert close_enough(seen[-1], want), (
f"the cursor arrived at {seen[-1]} and was aimed at {want}. "
"An offset of hundreds of pixels means the virtual pointer "
"speaks global coordinates, i.e. it was created without an "
"output."
)
except Exception:
dump("the warp did not land where it was aimed", session_id)
raise
with subtest("a click is delivered there, pressed and released"):
try:
before = len(buttons(session_id))
clicked = cli_json(f"pointer click --json {session_id}", timeout=120)
print(json.dumps(clicked, indent=2, sort_keys=True))
events = wait_for(
lambda: (
buttons(session_id)[before:]
if len(buttons(session_id)) >= before + 2
else None
),
timeout=60,
what="the client to report a press and a release",
)
print(f"the client reports: {events}")
assert {code for code, _, _, _ in events} == {0x110}, (
f"the client was sent {events}, not BTN_LEFT (0x110)"
)
assert [state for _, state, _, _ in events] == ["pressed", "released"], (
f"a click delivered {events}; it must be exactly one press "
"and one release, or something is left held down"
)
want = aimed_at(0.25, 0.75)
for _, state, x, y in events:
assert close_enough((x, y), want), (
f"the {state} arrived at ({x}, {y}), aimed at {want}"
)
except Exception:
dump("the click did not reach the application", session_id)
raise
with subtest("a second acquire is refused with BUSY, naming the holder"):
# The lock is broker-wide because the cursor is one (PLAN §6.2).
try:
other = machine.succeed(cli("start target"), timeout=180).strip()
print(f"second session: {other}")
code, out = machine.execute(
cli(f"pointer acquire {other}") + " 2>&1", timeout=120
)
print(f"exit {code}: {out}")
assert code == 8, f"a contended acquire exited {code}, not 8 (BUSY)"
assert session_id in out, (
f"the refusal does not name the holder {session_id}: {out!r}"
)
except Exception:
dump("a contended acquire was not refused", locals().get("other"))
raise
with subtest("a session that never acquired cannot move the cursor"):
# Exit 9 and not 8: an agent that sees 9 must acquire, one that
# sees 8 must wait, and conflating them is how a retry loop spins.
try:
code, out = machine.execute(
cli(f"pointer move {other} --to 0.5,0.5") + " 2>&1", timeout=120
)
print(f"exit {code}: {out}")
assert code == 9, f"a gesture with no lease exited {code}, not 9"
except Exception:
dump("a gesture without a lease was not refused", other)
raise
with subtest("release frees the lock and leaves the bookmark behind"):
try:
released = cli_json(f"pointer release --json {session_id}", timeout=120)
print(json.dumps(released, indent=2, sort_keys=True))
assert released["buttons_lifted"] == [], released
assert (released["bookmark"]["x"], released["bookmark"]["y"]) == (
0.25,
0.75,
), released
state = cli_json("pointer state --json")
assert state["holder"] is None, state
except Exception:
dump("release did not give the cursor back", session_id)
raise
with subtest("the cursor reaches a session that does not hold focus"):
# Two assertions in one, because they need the same situation: a
# second session exists and its window took focus when it opened
# (the BUSY subtest above started it).
#
# 1. `acquire` restores the bookmark the previous lease left --
# the point of a bookmark is that a gesture is resumable, and
# it is checked on the client's side as well as the broker's.
# 2. A warp is delivered to the session it was AIMED at, not to
# whichever window the compositor last focused -- and the
# focused one is told nothing. The lease and the containers
# are worth nothing if a click aimed at one session arrives at
# another, and `input:follow_mouse` is where that would go
# wrong (see the block at the top of this file).
try:
before = len(positions(session_id))
reply = cli_json(f"pointer acquire --json {session_id}", timeout=120)
print(json.dumps(reply, indent=2, sort_keys=True))
assert (reply["bookmark"]["x"], reply["bookmark"]["y"]) == (0.25, 0.75), (
f"acquire restored to {reply['bookmark']}, not where the "
"previous lease left the cursor"
)
focused = [
c.get("initialClass")
for c in compositor("clients")
if c.get("focusHistoryID") == 0
]
print(f"the compositor's focused window belongs to: {focused}")
assert focused and focused[0] != output, (
f"this subtest needs the OTHER session focused; {focused} is"
)
# Somewhere the cursor is not, so there is a motion to deliver
# (see the note at the top of this file).
elsewhere = (0.6, 0.4)
before_other = len(positions(other))
machine.succeed(
cli(f"pointer move {session_id} --to {elsewhere[0]},{elsewhere[1]}"),
timeout=120,
)
# Waits for EITHER client to report something, so a warp that
# went to the wrong one is a message naming where it went
# rather than a timeout naming nothing.
wait_for(
lambda: positions(session_id)[before:] or positions(other)[before_other:],
timeout=60,
what=f"either {session_id} or {other} to report the warp",
)
mine = positions(session_id)[before:]
theirs = positions(other)[before_other:]
print(f"aimed at {session_id}: it reports {mine}")
print(f"focused is {other}: it reports {theirs}")
print(f"cursor now at {compositor('cursorpos')}")
assert not theirs, (
f"the warp was aimed into {output} and {other}'s window got "
f"it: {theirs}. The compositor is routing pointer events by "
"keyboard focus, not by what is under the cursor -- read "
"input:follow_mouse in nix/hyprland-conf.nix."
)
want = aimed_at(*elsewhere)
print(f"the client reports {mine}, aimed at {want}")
assert close_enough(mine[-1], want), (mine[-1], want)
machine.succeed(cli(f"pointer release {session_id}"), timeout=120)
except Exception:
dump("the warp did not reach the session it was aimed at", session_id)
raise
with subtest("an expired lease is released and its button is lifted"):
# Real time, a caller-supplied TTL, and nothing touching the lease.
# The sweeper is what makes the TTL a promise: without it expiry
# would only be noticed by the next verb, so an agent that pressed
# a button and died would hold the cursor -- with the button down
# -- until somebody else happened to try.
try:
short = 8
cli_json(
f"pointer acquire --json --ttl {short}s {session_id}", timeout=120
)
before = len(buttons(session_id))
machine.succeed(cli(f"pointer down {session_id}"), timeout=120)
held = cli_json("pointer state --json")
print(json.dumps(held, indent=2, sort_keys=True))
assert held["holder"] == session_id, held
assert held["buttons"] == ["left"], (
f"the button is not recorded as down: {held}"
)
# One bounded wait for the deadline to arrive, not a retry of
# the assertion: the lease expires on its own or it does not.
machine.wait_until_succeeds(
cli("pointer state --json") + " | jq -e '.holder == null' >/dev/null",
timeout=short * 6 + 120,
)
state = cli_json("pointer state --json")
print(json.dumps(state, indent=2, sort_keys=True))
assert state["buttons"] == [], (
f"the lease expired with a button still down: {state}"
)
events = wait_for(
lambda: (
buttons(session_id)[before:]
if len(buttons(session_id)) >= before + 2
else None
),
timeout=60,
what="the client to be told the button came back up",
)
print(f"the client reports: {events}")
assert [s for _, s, _, _ in events] == ["pressed", "released"], (
"the application was told the button went down and never "
f"that it came up: {events}. A compositor left holding a "
"button is a drag nobody started."
)
except Exception:
dump("the lease did not expire cleanly", session_id)
raise
with subtest("a broker restart leaves the lock free and the bookmark intact"):
# Leases are stale by definition across a restart (PLAN §6.2); the
# bookmark is not, because it lives in the session record on disk.
try:
cli_json(f"pointer acquire --json {session_id}", timeout=120)
machine.succeed(cli(f"pointer move {session_id} --to 0.8,0.2"), timeout=120)
machine.succeed("systemctl restart hhstream-sessions.service", timeout=180)
machine.wait_for_unit("hhstream-sessions.service", timeout=180)
machine.wait_until_succeeds(cli("list") + " >/dev/null", timeout=120)
state = cli_json("pointer state --json")
print(json.dumps(state, indent=2, sort_keys=True))
assert state["holder"] is None, (
f"the restarted broker believes {state['holder']} still holds "
"a lease that died with the process that granted it"
)
record = cli_json(f"status --json {session_id}")["session"]
bookmark = (record.get("pointer") or {}).get("bookmark")
print(json.dumps(bookmark, indent=2, sort_keys=True))
assert bookmark is not None, record
assert (bookmark["x"], bookmark["y"]) == (0.8, 0.2), (
f"the bookmark did not survive the restart: {bookmark}"
)
assert bookmark["output"] == output, bookmark
except Exception:
dump("the restart lost the lock or the bookmark", session_id)
raise
with subtest("the driver is still reachable after the broker restarted"):
# The socket the two speak over lives in the broker's runtime
# directory. Without `RuntimeDirectoryPreserve` on that unit,
# restarting the broker deletes /run/hhstream and takes
# pointer.sock with it -- leaving the driver listening on an
# unlinked inode and every pointer verb answering exit 10 while
# `systemctl status hhstream-pointer` still says "active".
try:
machine.succeed(f"test -S {POINTER_SOCKET}")
machine.succeed("systemctl is-active hhstream-pointer.service")
reply = cli_json(f"pointer acquire --json {session_id}", timeout=120)
print(json.dumps(reply, indent=2, sort_keys=True))
assert reply["bookmark"]["x"] == 0.8, reply
machine.succeed(cli(f"pointer release {session_id}"), timeout=120)
except Exception:
dump("the driver was unreachable after the broker restarted", session_id)
raise
'';
}
)