read the config the module writes: containers can be turned off

The module rendered containers_enabled, workspace_base, container_mode,
max_containers and the pointer lease keys into the TOML, and policy.py read only
[defaults] and [apps] -- so the settings were inert. The defaults coincided,
which made it look honoured, until a deployment tried to turn containers off and
found it could not.

Settings now come from the same file: parsed beside Policy (read by __main__, so
the manager keeps taking a plain ManagerConfig its tests build directly) and
carried into ContainerHost, which reports itself unavailable when switched off.
That is the whole mechanism -- the manager already treats an unavailable host as
'sessions without containers', which is what turning them off means -- and the
reason names the key, so a disabled machine cannot be mistaken for one whose
compositor is down.

This is what made the rollback on the host possible; the machine had containers
built, tested, and impossible to disable.
This commit is contained in:
Hermenix committed 2026-10-03 12:10:19 +00:00
1 parent c1dc60af00
commit 8f3f000783
6 files changed
+221 -1

No files matched your search

+12 -1
View File
@@ -23,7 +23,7 @@ from .clock import Clock, parse_duration
from .compositor import CompositorError, CompositorTarget
from .launcher import Launcher
from .manager import DEFAULT_SETTLE_S, ManagerConfig, SessionManager
from .policy import Policy, PolicyError, load_policy
from .policy import Policy, PolicyError, load_policy, load_settings
from .registry import Registry
from .server import ControlServer
@@ -166,12 +166,23 @@ async def serve(
# against whatever directory the app happens to be started in.
state_dir = Path(args.state_dir).resolve()
runtime_dir = Path(args.runtime_dir).resolve()
# The same file the allowlist comes from. Read here rather than in the
# manager so the manager keeps taking a plain ManagerConfig, which is what
# its tests build directly.
settings = load_settings(args.config)
config = ManagerConfig(
state_dir=state_dir,
runtime_dir=runtime_dir,
policy=policy,
settle_s=args.settle,
compositor=compositor,
containers_enabled=settings.containers_enabled,
container_base=settings.container_base,
container_slots=settings.container_slots,
container_mode=settings.container_mode,
quarantine_workspace=settings.quarantine_workspace,
pointer_ttl_s=settings.pointer_ttl_s,
pointer_max_s=settings.pointer_max_s,
)
manager = SessionManager(
config,
+17
View File
@@ -86,9 +86,15 @@ class ContainerHost:
mode: tuple[int, int] = DEFAULT_MODE,
quarantine_workspace: str = DEFAULT_QUARANTINE_WORKSPACE,
ipc: HyprlandIPC | None = None,
enabled: bool = True,
) -> None:
self.runtime_dir = None if runtime_dir is None else Path(runtime_dir)
self.allocator = allocator
#: Whether this broker gives sessions containers at all. Off is a
#: configuration, not a failure: `available()` reports it, and the manager
#: already knows what to do with an unavailable host (sessions without
#: containers), so nothing else has to branch on it.
self.enabled = enabled
self.mode = mode
self.quarantine_workspace = quarantine_workspace
self._wanted_signature = signature
@@ -138,8 +144,19 @@ class ContainerHost:
``version`` is the cheapest round trip that proves the socket is a live
compositor and not a leftover inode.
A host switched off by configuration is unavailable on purpose, and the
reason says which key turned it off -- otherwise a machine with
containers disabled looks identical to one whose compositor is down, and
the operator goes hunting for a broken compositor that is fine.
"""
if not self.enabled:
self._last_error = (
"containers are disabled in the config "
"([compositor] containers_enabled = false)"
)
return False
try:
self.ipc().version()
except CompositorUnavailable as exc:
+6
View File
@@ -161,6 +161,11 @@ class ManagerConfig:
signature: str | None = None
container_base: int = DEFAULT_CONTAINER_BASE
container_slots: int = DEFAULT_CONTAINER_SLOTS
#: Whether sessions get their own output and workspace. False means "process
#: groups on the shared output", which is what the machine ran before
#: containers existed, and what a deployment that cannot match windows to
#: containers yet should be configured with.
containers_enabled: bool = True
container_mode: tuple[int, int] = DEFAULT_MODE
quarantine_workspace: str = DEFAULT_QUARANTINE_WORKSPACE
readback_s: float = DEFAULT_READBACK_S
@@ -213,6 +218,7 @@ class SessionManager:
signature=config.signature,
mode=config.container_mode,
quarantine_workspace=config.quarantine_workspace,
enabled=config.containers_enabled,
)
# The lease runs on CLOCK_BOOTTIME like every other deadline here, so a
# host suspended mid-gesture does not come back believing the lease is
+88
View File
@@ -169,6 +169,94 @@ def check_argv(argv: Any) -> None:
# --------------------------------------------------------------------------
@dataclass(frozen=True, slots=True)
class Settings:
"""What the config file says that is not the allowlist.
Kept beside :class:`Policy` because both come out of the same TOML file, and
read by ``__main__`` rather than by the manager, so the manager keeps taking a
plain :class:`~hhstreamd.manager.ManagerConfig` that a test can build
directly. Before this existed the module rendered these keys into the file
and the broker read none of them: a deployment could turn containers off, or
move a lease deadline, and be silently ignored while the defaults happened to
make it look honoured.
The defaults mirror the manager's own; the module always renders every key,
so they matter only for a config written by hand.
"""
containers_enabled: bool = True
container_base: int = 1000
container_slots: int = 4
container_mode: tuple[int, int] = (1280, 720)
quarantine_workspace: str = "special:quarantine"
pointer_ttl_s: float = 30.0
pointer_max_s: float = 300.0
def _mode(value: Any, key: str) -> tuple[int, int]:
"""Parse ``"1280x720"`` into ``(1280, 720)``; refuse anything else.
Refusing matters more than being permissive here: a container created at the
wrong size is a session whose window does not fit its own screen, which looks
like an application bug rather than a typo in a config file.
"""
if isinstance(value, str) and "x" in value:
width, _, height = value.partition("x")
try:
return int(width), int(height)
except ValueError:
pass
if isinstance(value, (list, tuple)) and len(value) == 2:
return int(value[0]), int(value[1])
raise PolicyError(
"invalid_argument",
f"[compositor] {key} must look like \"1280x720\", got {value!r}",
)
def settings_from_dict(data: dict[str, Any]) -> Settings:
defaults = data.get("defaults", {})
if not isinstance(defaults, dict):
raise PolicyError("invalid_argument", "[defaults] must be a table")
compositor = data.get("compositor", {})
if not isinstance(compositor, dict):
raise PolicyError("invalid_argument", "[compositor] must be a table")
pointer = data.get("pointer", {})
if not isinstance(pointer, dict):
raise PolicyError("invalid_argument", "[pointer] must be a table")
return Settings(
containers_enabled=bool(compositor.get("containers_enabled", True)),
container_base=int(compositor.get("workspace_base", 1000)),
container_slots=int(defaults.get("max_containers", 4)),
container_mode=_mode(compositor.get("container_mode", "1280x720"), "container_mode"),
quarantine_workspace=str(
compositor.get("quarantine_workspace", "special:quarantine")
),
pointer_ttl_s=float(pointer.get("lease_ttl_s", 30.0)),
pointer_max_s=float(pointer.get("lease_max_s", 300.0)),
)
def load_settings(path: Path | str | None) -> Settings:
"""Read the non-allowlist settings from the file :func:`load_policy` reads.
A missing file is the defaults, for the same reason a missing allowlist is an
empty one: a misconfigured deployment should behave conservatively, not fail
to start.
"""
if path is None:
return Settings()
path = Path(path)
if not path.exists():
return Settings()
with open(path, "rb") as fh:
return settings_from_dict(tomllib.load(fh))
def load_policy(path: Path | str | None) -> Policy:
"""Read the allowlist from a TOML file.
@@ -28,6 +28,26 @@ def compositor(short_tmpdir: Path):
fake.stop()
def test_a_disabled_host_is_unavailable_and_says_why() -> None:
"""Turning containers off must be configuration, not a false compositor.
``available()`` is the whole mechanism: the manager already treats an
unavailable host as "sessions without containers", which is exactly what
turning them off means, so nothing else has to branch on it. It must also
not ask a compositor this deployment never intended to talk to -- and its
reason has to name the key, or a machine with containers disabled looks
identical to one whose compositor is down and the operator goes hunting for a
fault that is not there.
"""
host = ContainerHost(
None, allocator=containers.WorkspaceAllocator(1000, 4), enabled=False
)
assert host.available() is False
assert "containers_enabled" in (host.last_error or "")
def make_host(fake: FakeCompositor, *, slots: int = 4) -> ContainerHost:
return ContainerHost(
fake.runtime_dir,
+78
View File
@@ -0,0 +1,78 @@
"""The config file's non-allowlist half.
These keys are rendered by the NixOS module and, until this existed, read by
nothing: a deployment could turn containers off or move a lease deadline and be
silently ignored, while the defaults happened to make it look honoured. The
values here are therefore the ones the module actually writes -- if the module's
shape changes, these tests are where that shows up.
"""
from __future__ import annotations
from pathlib import Path
import tomllib
import pytest
from hhstreamd.policy import PolicyError, load_settings, settings_from_dict
#: Exactly what `nix/module.nix` renders today, through
#: `services.hyprland-headless-stream`, with containers turned off.
MODULE_SHAPE = """
[defaults]
max_sessions = 4
idle_timeout_s = 10800
max_containers = 2
[compositor]
runtime_dir = "/run/hypr-stream"
containers_enabled = false
workspace_base = 1000
container_mode = "1280x720"
[pointer]
enabled = true
lease_ttl_s = 30
lease_max_s = 300
[apps.chromium]
exec = "/nix/store/x/bin/chromium"
args_allow = ["--ozone-platform=wayland"]
"""
def test_the_module_shape_is_read() -> None:
settings = settings_from_dict(tomllib.loads(MODULE_SHAPE))
assert settings.containers_enabled is False
# max_containers lives in [defaults] while the rest live in [compositor];
# that split is the module's, and reading only one of them is how a budget
# silently stops applying.
assert settings.container_slots == 2
assert settings.container_base == 1000
assert settings.container_mode == (1280, 720)
assert (settings.pointer_ttl_s, settings.pointer_max_s) == (30.0, 300.0)
def test_containers_default_to_on_when_the_key_is_absent() -> None:
"""A config written before this setting existed keeps working."""
assert settings_from_dict({"apps": {}}).containers_enabled is True
def test_a_bad_mode_is_refused_by_name() -> None:
"""A typo must be loud: a container at the wrong size looks like an app bug."""
with pytest.raises(PolicyError) as exc:
settings_from_dict({"compositor": {"container_mode": "wide"}})
assert "container_mode" in str(exc.value)
def test_an_absent_file_is_the_defaults(tmp_path: Path) -> None:
"""Missing config behaves conservatively rather than refusing to start."""
settings = load_settings(tmp_path / "absent.toml")
assert settings.containers_enabled is True
assert settings.container_mode == (1280, 720)