Files
HermenixandClaude Opus 5 b4abd085cc test(stream): both ends of live.sock, the broker's verbs, and a real viewer in a guest
Three layers, because the stream has three and each one can be wrong on its own.

`tests/live/test_live_control.py` (20 tests) runs `Control` against a fake
capture: the four ops, `attach` idempotent on the phrase, the same phrase aimed
at another output refused, a malformed phrase refused *without the value in the
message*, and `fps` defaulting to the daemon's when the broker sends none.

`tests/sessions/unit/test_stream_verbs.py` (24 tests) runs the broker against a
fake daemon, and its subjects are the decisions rather than the plumbing: no
container output is a refusal and never a fallback to the main output; a
re-`enable` returns the same phrase and a different one is exit 8; a down daemon
turns `attached` false rather than failing a read; the sweep touches a watched
session and leaves an unwatched one alone; teardown detaches before the
container is destroyed.

`tests/unit/test_mcp_*` grow the two tools, the two resources and the three
`session_start` arguments, with the read-only half asserted *absent* as a tool
by name -- re-adding one should be a failure, not a silent widening.

`checks/vm-stream.nix` is the new guest check, and it exists for the two things
none of the above can say:

1. **That `grim` captures a real compositor from inside a unit.** It reads
   actual JPEGs off `/<phrase>/stream.mjpg` with `checks/lib/mjpeg_read.py`, a
   hand-rolled multipart reader that shares no code with the server -- a parser
   that did could not tell you the boundary was wrong. It framed on SOI/EOI
   rather than `Content-Length` for the same reason. This is what caught the
   unit's missing `XDG_RUNTIME_DIR`: `frames: [25827, 25827, 25827]` now, ten
   capture failures and a stream that gave up before.
2. **That a connected viewer moves the idle clock.** That needs the broker's
   real sweep, on a real timer, with a client genuinely still there a minute
   later -- hence `--hold`, and hence a check that spends ~90 seconds twice. The
   negative control runs first, because if the sweep touched an unwatched stream
   the positive case would pass for the wrong reason. Measured in the guest:
   with nobody watching `580s -> 502s` remaining, with a viewer `499s -> 596s`.

It also asserts the phrase is in neither the audit log nor a 404 body, that the
old URL stops serving after `disable`, that `disable` then `enable` rotates it,
that `kill` takes the stream down and leaves the daemon up, and that
`start --stream` yields an id and a URL that serves frames.

No clock is injected anywhere in this check. An injected one would prove the
arithmetic, which the unit tests already do, and not the daemon.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011ZeH65zd6pFTgBSu52W9PE
2026-10-11 22:49:18 +00:00

328 lines
12 KiB
Python

"""``live.sock``: the four ops, over a real socket, against the shipped client.
The server is `hhstream_live.control` and the client is
`hhstreamd.live.LiveStreams` — both shipped, talking over a real ``AF_UNIX``
socket, so this is the one place the two halves of CONTRACT-sessions.md §3.5
are read against each other. Only the capture is substituted, because this
machine has no compositor.
The opposite choice from `tests/assert_stream.py`, and for the stated reason:
what is being asserted here is that *this* client reaches *this* daemon, which
a second implementation could say nothing about. The *wire format* is held
honest separately, by the raw-JSON tests at the bottom that bypass the client
entirely.
"""
from __future__ import annotations
import contextlib
import json
import socket
import threading
from pathlib import Path
import pytest
from fake_jpeg import jpeg_bytes
from hhstream_live import phrase as phrase_mod
from hhstream_live.control import Control, ControlServer
from hhstream_live.publisher import FPS_CAP, StreamRegistry
from hhstreamd.live import Attachment, LiveRejected, LiveStreams, LiveUnavailable
PORT = 9988
class FakeCapture:
def grab(self) -> bytes:
return jpeg_bytes()
class Daemon:
"""The shipped control server, with a poll-interval accept loop."""
def __init__(self, socket_path: Path) -> None:
self.registry = StreamRegistry()
self.control = Control(
self.registry,
capture_for=lambda output: FakeCapture(),
url_for=lambda phrase: f"http://127.0.0.1:{PORT}/{phrase}/",
)
self.server = ControlServer(socket_path, self.control)
self.server.listen()
self.connections: list[socket.socket] = []
self._stop = threading.Event()
self._listener = self.server._sock
self._listener.settimeout(0.05)
self._thread = threading.Thread(target=self._serve, daemon=True)
self._thread.start()
def _serve(self) -> None:
while not self._stop.is_set():
try:
conn, _ = self._listener.accept()
except (TimeoutError, socket.timeout):
continue
except OSError:
return
self.connections.append(conn)
with conn:
self.server._serve_connection(conn)
def stop(self) -> None:
self._stop.set()
for conn in self.connections:
with contextlib.suppress(OSError):
conn.shutdown(socket.SHUT_RDWR)
self._thread.join(timeout=2)
self.registry.stop_all()
self.server.close()
@pytest.fixture
def short_tmpdir():
"""A directory with a short path.
Its own fixture rather than `tmp_path`, and the reason is the same one
`tests/sessions/conftest.py` has: an ``AF_UNIX`` address is capped near 108
bytes and pytest's own paths are longer than that. Not imported from there
-- these two suites have separate conftests, and a cross-import between
them is how the collection collision in this tree started.
"""
import shutil
import tempfile
path = tempfile.mkdtemp(prefix="hhs")
try:
yield Path(path)
finally:
shutil.rmtree(path, ignore_errors=True)
@pytest.fixture
def daemon(short_tmpdir: Path):
daemon = Daemon(short_tmpdir / "live.sock")
try:
yield daemon
finally:
daemon.stop()
@pytest.fixture
def client(daemon):
client = LiveStreams(daemon.server.socket_path)
try:
yield client
finally:
client.close()
# ── attach ─────────────────────────────────────────────────────────────────
def test_attaching_publishes_an_output_and_returns_the_daemon_s_url(client, daemon):
phrase = phrase_mod.generate()
attachment = client.attach(
phrase=phrase, output="hh-x", fps=5, session="x", label="chromium"
)
assert isinstance(attachment, Attachment)
assert (attachment.output, attachment.fps, attachment.session) == ("hh-x", 5, "x")
assert attachment.viewers == 0
# The URL is the DAEMON's: the broker never assembles one, because it does
# not own the port.
assert attachment.url == f"http://127.0.0.1:{PORT}/{phrase}/"
assert daemon.registry.get(phrase) is not None
def test_attaching_the_same_phrase_twice_starts_no_second_capture(client, daemon):
phrase = phrase_mod.generate()
first = client.attach(phrase=phrase, output="hh-x", fps=5, session="x")
again = client.attach(phrase=phrase, output="hh-x", fps=5, session="x")
assert again.url == first.url
assert len(daemon.registry.all()) == 1
def test_the_same_phrase_aimed_somewhere_else_is_refused(client, daemon):
"""A phrase is a credential for one view; re-pointing it silently would
show somebody a desktop they were not given."""
phrase = phrase_mod.generate()
client.attach(phrase=phrase, output="hh-x", fps=5)
with pytest.raises(LiveRejected) as caught:
client.attach(phrase=phrase, output="hh-other", fps=5)
assert caught.value.kind == "invalid_argument"
assert daemon.registry.get(phrase).spec.output == "hh-x"
def test_a_phrase_that_is_not_of_the_shape_is_refused_without_echoing_it(client):
"""The refusal crosses a socket into the broker's log. It is a password."""
with pytest.raises(LiveRejected) as caught:
client.attach(phrase="hunter2", output="hh-x", fps=5)
assert caught.value.kind == "invalid_argument"
assert "hunter2" not in str(caught.value)
def test_a_rate_over_the_cap_is_refused_by_the_process_that_must_keep_up(client):
with pytest.raises(LiveRejected) as caught:
client.attach(phrase=phrase_mod.generate(), output="hh-x", fps=FPS_CAP + 1)
assert caught.value.kind == "invalid_argument"
assert str(FPS_CAP) in str(caught.value)
@pytest.mark.parametrize("fps", [0, -1])
def test_a_nonsensical_rate_is_refused(client, fps):
with pytest.raises(LiveRejected):
client.attach(phrase=phrase_mod.generate(), output="hh-x", fps=fps)
def test_an_empty_output_is_refused(client):
with pytest.raises(LiveRejected) as caught:
client.attach(phrase=phrase_mod.generate(), output=" ", fps=5)
assert caught.value.kind == "invalid_argument"
# ── detach, list, viewers ──────────────────────────────────────────────────
def test_detaching_stops_the_capture_and_says_it_did(client, daemon):
phrase = phrase_mod.generate()
client.attach(phrase=phrase, output="hh-x", fps=5)
assert client.detach(phrase) is True
assert daemon.registry.get(phrase) is None
def test_detaching_something_unattached_is_false_and_not_an_error(client):
"""`disable` after the daemon restarted is the ordinary case."""
assert client.detach(phrase_mod.generate()) is False
def test_listing_returns_every_stream(client):
phrases = [phrase_mod.generate() for _ in range(3)]
for index, phrase in enumerate(phrases):
client.attach(phrase=phrase, output=f"hh-{index}", fps=5, session=f"s-{index}")
listed = client.list()
assert {a.output for a in listed} == {"hh-0", "hh-1", "hh-2"}
assert all(isinstance(a, Attachment) for a in listed)
def test_viewers_reports_a_count_per_phrase(client, daemon):
phrase = phrase_mod.generate()
client.attach(phrase=phrase, output="hh-x", fps=5)
assert client.viewers() == {phrase: 0}
daemon.registry.get(phrase).add_viewer()
daemon.registry.get(phrase).add_viewer()
assert client.viewers() == {phrase: 2}
def test_an_empty_daemon_lists_nothing_rather_than_failing(client):
assert client.list() == []
assert client.viewers() == {}
# ── failure ────────────────────────────────────────────────────────────────
def test_a_socket_that_is_not_there_is_unavailable(short_tmpdir: Path):
client = LiveStreams(short_tmpdir / "nothing-here.sock")
with pytest.raises(LiveUnavailable):
client.list()
def test_a_daemon_that_went_away_is_unavailable_and_not_a_stale_answer(client, daemon):
client.attach(phrase=phrase_mod.generate(), output="hh-x", fps=5)
assert client.list() # the connection is now held
daemon.stop()
with pytest.raises(LiveUnavailable):
client.list()
def test_the_client_reconnects_after_the_daemon_restarts(short_tmpdir: Path):
"""The held connection is checked for EOF before each write, as the
driver's is -- so a restart costs one reconnect and not a dead client."""
path = short_tmpdir / "live.sock"
first = Daemon(path)
client = LiveStreams(path)
try:
client.attach(phrase=phrase_mod.generate(), output="hh-x", fps=5)
first.stop()
second = Daemon(path)
try:
# The new daemon knows nothing, which is the point: the client
# reached it at all.
assert client.list() == []
finally:
second.stop()
finally:
client.close()
# ── the wire format itself ─────────────────────────────────────────────────
#
# These bypass `LiveStreams` on purpose. The tests above prove the two shipped
# halves agree with each other; these prove the *format* §3.5 freezes, which a
# pair that agreed on something else would also pass.
def raw(path: Path, message: dict) -> dict:
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as sock:
sock.settimeout(5)
sock.connect(str(path))
with sock.makefile("rwb") as stream:
stream.write(json.dumps(message).encode() + b"\n")
stream.flush()
return json.loads(stream.readline())
def test_the_frozen_op_names_and_reply_shape(daemon):
path = daemon.server.socket_path
phrase = phrase_mod.generate()
attached = raw(path, {"op": "attach", "phrase": phrase, "output": "hh-x", "fps": 5})
assert attached["ok"] is True
stream = attached["stream"]
assert set(stream) >= {"phrase", "output", "fps", "session", "url", "viewers"}
assert raw(path, {"op": "list"})["streams"][0]["output"] == "hh-x"
assert raw(path, {"op": "viewers"})["viewers"] == {phrase: 0}
assert raw(path, {"op": "detach", "phrase": phrase}) == {"ok": True, "detached": True}
def test_an_unknown_op_is_refused_with_a_kind(daemon):
reply = raw(daemon.server.socket_path, {"op": "levitate"})
assert reply["ok"] is False
assert reply["kind"] == "invalid_argument"
def test_malformed_json_is_refused_without_closing_the_connection(daemon):
path = daemon.server.socket_path
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as sock:
sock.settimeout(5)
sock.connect(str(path))
with sock.makefile("rwb") as stream:
stream.write(b"{not json\n")
stream.flush()
first = json.loads(stream.readline())
assert first["ok"] is False
# Still answering: one bad line must not cost the broker its
# connection, because the next op may be a `detach` in a teardown.
stream.write(json.dumps({"op": "list"}).encode() + b"\n")
stream.flush()
assert json.loads(stream.readline())["ok"] is True
def test_a_request_that_is_not_an_object_is_refused(daemon):
reply = raw(daemon.server.socket_path, ["attach"]) # type: ignore[arg-type]
assert reply["ok"] is False
assert reply["kind"] == "invalid_argument"