wire the broker to the compositor, containers and pointer

The four slices existed and nothing called them. Now the broker builds a
spatial container per session, reads back what the compositor actually did,
and aims the cursor into one container under a broker-wide lease.

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

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

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

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

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

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

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017mUq7QvQ9EZb2Wi35xj4cs
This commit is contained in:
HermenixandClaude Opus 5 committed 2026-10-02 19:47:33 +00:00
1 parent 20b2aee109
commit 129430bffd
20 files changed
+4805 -89

No files matched your search

@@ -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)
+288
View File
@@ -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)
@@ -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]
+222
View File
@@ -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()
+36 -1
View File
@@ -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."""
+592
View File
@@ -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()
+104 -1
View File
@@ -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