Files
hyprland-headless-stream-pl…/tests/sessions/unit/test_registry.py
T
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

375 lines
13 KiB
Python

"""Registry unit tests: atomic persistence, adoption, tombstones."""
from __future__ import annotations
import base64
import json
import os
from pathlib import Path
import pytest
from hhstreamd.clock import ManualClock
from hhstreamd.registry import (
SCHEMA,
ContainerState,
Registry,
Session,
State,
atomic_write_json,
container_record,
migrate,
mint_id,
pointer_record,
)
def make_session(sid: str = "foot-aaaaaa", **overrides) -> Session:
base = dict(
id=sid,
app="foot",
argv=["/usr/bin/foot"],
pid=4242,
pgid=4242,
sid=4242,
pid_starttime=918342,
cmdline_sha256="9f2c",
home="/home/someone",
runtime_dir="/run/hhstream/sessions/" + sid,
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,
)
base.update(overrides)
return Session(**base)
@pytest.fixture
def registry(tmp_path: Path) -> Registry:
reg = Registry(tmp_path, ManualClock(boottime=1000.0))
reg.ensure_dirs()
return reg
# ---------------------------------------------------------------------------
# atomic persistence
# ---------------------------------------------------------------------------
def test_atomic_write_leaves_no_temporary_files_behind(tmp_path: Path):
target = tmp_path / "rec.json"
atomic_write_json(target, {"hello": "world"})
assert json.loads(target.read_text()) == {"hello": "world"}
assert [p.name for p in tmp_path.iterdir()] == ["rec.json"]
def test_a_failed_write_leaves_the_previous_record_intact(tmp_path: Path, monkeypatch):
"""The point of tmp + os.replace: a reader never sees a half-written record."""
target = tmp_path / "rec.json"
atomic_write_json(target, {"generation": 1})
def explode(*args, **kwargs):
raise OSError("disk full")
monkeypatch.setattr(json, "dump", explode)
with pytest.raises(OSError):
atomic_write_json(target, {"generation": 2})
assert json.loads(target.read_text()) == {"generation": 1}
assert [p.name for p in tmp_path.iterdir()] == ["rec.json"] # temp cleaned up
def test_the_temp_file_is_written_in_the_target_directory(tmp_path: Path, monkeypatch):
"""os.replace is only atomic within one filesystem, so the temp must be adjacent."""
seen: list[str] = []
real_replace = os.replace
def spy(src, dst, *args, **kwargs):
seen.append(str(src))
return real_replace(src, dst, *args, **kwargs)
monkeypatch.setattr(os, "replace", spy)
target = tmp_path / "deep" / "rec.json"
atomic_write_json(target, {"a": 1})
assert Path(seen[0]).parent == target.parent
def test_persist_writes_the_record_and_it_round_trips(registry: Registry):
session = registry.add(make_session())
path = registry.record_path(session.id)
assert path.exists()
restored = Session.from_dict(json.loads(path.read_text()))
assert restored == session
def test_a_mirror_write_failure_never_fails_the_command(registry: Registry, monkeypatch, caplog):
session = registry.add(make_session())
monkeypatch.setattr(
"hhstreamd.registry.atomic_write_json",
lambda *a, **k: (_ for _ in ()).throw(OSError("read-only filesystem")),
)
registry.touch(session, force_flush=True) # must not raise
assert session.command_count == 1
assert "mirror write failed" in caplog.text
def test_activity_flushes_are_rate_limited_but_transitions_are_not(registry: Registry):
clock: ManualClock = registry.clock # type: ignore[assignment]
session = registry.add(make_session())
registry.touch(session) # within the 15 s window: memory only
on_disk = Session.from_dict(json.loads(registry.record_path(session.id).read_text()))
assert session.command_count == 1
assert on_disk.command_count == 0
clock.advance(16.0)
registry.touch(session)
on_disk = Session.from_dict(json.loads(registry.record_path(session.id).read_text()))
assert on_disk.command_count == 2
# ---------------------------------------------------------------------------
# handles
# ---------------------------------------------------------------------------
def test_a_colliding_draw_is_discarded_and_another_taken():
"""Handles are never reused: a draw already in the set is refused."""
class TwoDraws:
def __init__(self):
self.calls = 0
def token_bytes(self, n):
self.calls += 1
return b"\x00" * n if self.calls == 1 else b"\xff" * n
rng = TwoDraws()
collision = f"foot-{base64.b32encode(b'\x00' * 5).decode().rstrip('=').lower()[:6]}"
minted = mint_id("foot", {collision}, rng=rng)
assert rng.calls == 2
assert minted != collision
assert minted.startswith("foot-")
def test_a_tombstoned_id_still_blocks_reuse(registry: Registry):
session = registry.add(make_session())
registry.terminate(session, State.KILLED)
assert session.id in registry.taken_ids()
assert registry.new_id("foot") != session.id
def test_the_slug_is_sanitised_but_never_parsed():
assert mint_id("Chromium", set()).startswith("chromium-")
assert mint_id("/bin/odd name", set()).startswith("bin-odd-name-")
assert mint_id("!!!", set()).startswith("app-")
# ---------------------------------------------------------------------------
# tombstones
# ---------------------------------------------------------------------------
def test_terminate_writes_a_tombstone_with_an_expiry(registry: Registry):
clock: ManualClock = registry.clock # type: ignore[assignment]
session = registry.add(make_session())
registry.terminate(session, State.EXITED, exit_code=0, exit_detected_by="sigchld")
assert not session.live
assert session.exit_code == 0
assert session.tombstoned_boottime == clock.boottime()
assert session.tombstone_expires() == clock.boottime() + 3600.0
assert session.deadline() is None # a tombstone can never be idle-reaped
assert registry.tombstones() == [session]
assert registry.live() == []
def test_an_adopted_exit_records_no_exit_code_rather_than_inventing_a_zero(registry: Registry):
session = registry.add(make_session(adopted=True))
registry.terminate(session, State.EXITED, exit_detected_by="pidfd")
assert session.exit_code is None
assert session.exit_detected_by == "pidfd"
def test_drop_removes_the_record_and_its_mirror(registry: Registry):
session = registry.add(make_session())
path = registry.record_path(session.id)
registry.drop(session.id)
assert not path.exists()
assert registry.get(session.id) is None
# ---------------------------------------------------------------------------
# loading / adoption
# ---------------------------------------------------------------------------
def test_load_records_reads_back_what_was_persisted(tmp_path: Path):
writer = Registry(tmp_path, ManualClock())
writer.ensure_dirs()
writer.add(make_session("foot-aaaaaa"))
writer.add(make_session("foot-bbbbbb", pid=99))
reader = Registry(tmp_path, ManualClock())
records, quarantined = reader.load_records()
assert quarantined == []
assert sorted(r.id for r in records) == ["foot-aaaaaa", "foot-bbbbbb"]
def test_a_corrupt_record_is_quarantined_not_deleted_and_not_acted_on(tmp_path: Path, caplog):
registry = Registry(tmp_path, ManualClock())
registry.ensure_dirs()
bad = registry.sessions_dir / "foot-broken.json"
bad.write_text("{this is not json")
records, quarantined = registry.load_records()
assert records == []
assert len(quarantined) == 1
assert not bad.exists()
moved = list(registry.quarantine_dir.iterdir())
assert len(moved) == 1
assert moved[0].read_text() == "{this is not json"
assert "quarantining unreadable record" in caplog.text
def test_a_record_that_is_not_an_object_is_quarantined(tmp_path: Path):
registry = Registry(tmp_path, ManualClock())
registry.ensure_dirs()
(registry.sessions_dir / "x.json").write_text("[1, 2, 3]")
records, quarantined = registry.load_records()
assert records == [] and len(quarantined) == 1
def test_unknown_fields_from_a_newer_schema_are_dropped_not_fatal(caplog):
data = make_session().to_dict()
data["invented_by_a_later_version"] = True
session = Session.from_dict(data)
assert session.id == "foot-aaaaaa"
assert "dropping unknown record fields" in caplog.text
def test_a_record_from_a_previous_boot_is_recognised_as_stale(tmp_path: Path):
"""Pids restart from zero at boot, so /proc cannot be trusted about them."""
registry = Registry(tmp_path, ManualClock())
this_boot = make_session("foot-aaaaaa")
this_boot.boot_id = registry._boot_id
previous_boot = make_session("foot-bbbbbb")
previous_boot.boot_id = "00000000-0000-0000-0000-000000000000"
assert registry.stale_boot(this_boot) is False
assert registry.stale_boot(previous_boot) is True
def test_derived_fields_reported_to_callers(registry: Registry):
session = registry.add(make_session())
public = session.public(now=1000.0 + 600.0)
assert public["idle_s"] == 600.0
assert public["expires_in_s"] == 10800.0 - 600.0
assert public["live"] is True
assert public["schema"] == SCHEMA
# ---------------------------------------------------------------------------
# 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 == SCHEMA
# 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"] == SCHEMA
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