containers: a headless output and a persistent workspace per session

A session was a process group, so every application landed on whichever
workspace the compositor happened to show: one session's capture caught
another's windows, and a pointer aimed at one could land in the other.

This is the pure half of the fix. containers.py computes the argv lists
that create a session's container (headless output, numbered workspace
bound to it as default and persistent, an anchored window rule pinning
the session's class there, then the mode) and the one that tears it down,
plus the lowest-free allocator for the 1000+slot band and the
quarantine backstop for windows that match no container. It runs
nothing: no subprocess, no socket, no file, no clock, and no import of
ipc.py, so every decision that can be tested without a compositor is
asserted in a unit test.

Validation is a control, not style: these strings reach a compositor
that acts on them, and a rule body is comma-separated, so a session id
outside [a-z0-9-], a class outside [A-Za-z0-9._+-], a non-positive or
fractional size and a blank quarantine name all raise ValueError naming
the value. Releasing a workspace the allocator never handed out raises
rather than no-opping, because the quiet version hands the same
workspace to two sessions minutes later.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QS2JvrgmvXmimKFcqqDVoa
This commit is contained in:
HermenixandClaude Opus 5 committed 2026-10-02 00:02:40 +00:00
1 parent 98374b8457
commit 01460016e7
3 files changed
+633

No files matched your search

+304
View File
@@ -0,0 +1,304 @@
"""Spatial containers: one headless output and one workspace per session.
A session used to be a process group and nothing more, so every application
landed on whichever workspace the compositor happened to be showing. Two
sessions then shared a screen: a capture of one caught the other's windows, and
a pointer aimed at one could land in the other. A container fixes that by
giving the session a place of its own — a dedicated headless output, a numbered
workspace bound to that output as its default and marked persistent so it
survives the window closing, and a window rule that pins anything the session
spawns there.
**This module computes command lines and nothing else.** It does not run them,
does not talk to a socket, does not read a file, does not look at a clock and
does not import :mod:`hhstreamd.ipc`. That separation is deliberate: the
compositor is the part that cannot be tested without a compositor, so every
decision that *can* be made in a pure function is made here, where a unit test
can assert the exact argv list. The broker executes what comes back.
Three properties the callers depend on:
**Byte-identical output for identical arguments.** The ``create`` list is
emitted in a fixed order — create the output, bind the workspace, pin the
window, then set the mode — that does not depend on the inputs, and no set or
dict is ever iterated to build a command. The only thing a caller can vary is
what it passes in, in the order the signature names: nothing else here is a
source of order. So ``container_plan`` is safe to call twice and diff, which is
how ``container.reconcile`` decides whether a live container matches its plan.
**Argv lists, never strings.** These values reach a compositor that will act on
them, so there is no shell, no quoting and no interpolation of a caller's string
into a command *word*. The one place caller data lands inside a word is a rule
body (``workspace 1000, monitor:hh-x``), where a comma or a newline would end
one field and begin another — which is why the validation below is a control and
not a style preference.
**Validation raises, and names the value.** A session id that is not
``[a-z0-9-]``, a non-positive size, an empty app id: all :class:`ValueError`.
The broker mints its own ids and sizes, so a rejection here means a bug upstream
of us, and a message that quotes the offending value is what makes that bug
findable.
"""
from __future__ import annotations
import re
from dataclasses import dataclass
#: Every output this broker creates carries it. A start-up scan uses the prefix
#: to tell its own orphans — outputs left behind by a crash — from the outputs a
#: human or another tool made, which it must not remove.
OUTPUT_PREFIX = "hh-"
#: Session ids as the broker mints them. Deliberately narrower than "a safe
#: command word": lowercase, digits and the dash, so the name is also a legal
#: Hyprland output name and a regex literal with nothing to escape.
SESSION_ID_RE = re.compile(r"\A[a-z0-9-]+\Z")
#: An application's window class, which we do not mint — it is whatever the
#: toolkit reports, so it has to allow the shapes real classes take
#: (``org.gnome.Nautilus``, ``Alacritty``, ``firefox-esr``). It still excludes
#: every character that could end a field in a rule body or a line in the
#: request: comma, space, quote, newline, ``$``, ``^``.
APP_ID_RE = re.compile(r"\A[A-Za-z0-9._+-]+\Z")
class NoSlots(Exception):
"""The workspace band is full. The caller refuses the session; it never reuses."""
@dataclass(frozen=True, slots=True)
class ContainerPlan:
"""What a session's container is, and the two command lists that realise it.
``create`` and ``teardown`` are complete argv lists in the order they must
run. ``teardown`` is not the reverse of ``create``: removing the output is
enough, because the workspace and window rules are keywords that die with
the compositor's configuration and name an output that no longer exists.
"""
output: str
workspace: int
mode: tuple[int, int]
create: list[list[str]]
teardown: list[list[str]]
def output_name(session_id: str) -> str:
"""``hh-<session-id>`` — the name of the session's headless output."""
return OUTPUT_PREFIX + _checked_session_id(session_id)
def contains_output(name: str) -> bool:
"""True only for an output name this broker could have created.
Used by the start-up scan, which removes what it recognises. So it is
strict in the direction that matters: a bare ``hh-``, a trailing newline or
an upper-case suffix is *not* one of ours, and a scan that answered True
would delete someone else's output.
"""
if not name.startswith(OUTPUT_PREFIX):
return False
return SESSION_ID_RE.match(name[len(OUTPUT_PREFIX) :]) is not None
def app_id_for(session_id: str) -> str:
"""The bare ``hh-<session-id>`` the launcher sets as the app's class.
Same string as the output name, and that is the point: the launcher stamps
it on the application (``--class``, ``app_id``) and
:func:`container_plan` anchors it into the window rule, so the window finds
its own workspace with no lookup and no race against the window appearing.
"""
return OUTPUT_PREFIX + _checked_session_id(session_id)
def container_plan(
session_id: str,
workspace: int,
width: int,
height: int,
app_id: str,
) -> ContainerPlan:
"""The commands that create and tear down one session's container.
``app_id`` is passed in rather than derived from ``session_id`` because the
rule has to match whatever class the application actually reports: it is
:func:`app_id_for` for a well-behaved app the launcher could stamp, and the
app's own class for one that ignores the stamp.
"""
name = output_name(session_id)
slot = _checked_int(workspace, "workspace", minimum=1)
w = _checked_int(width, "width", minimum=1)
h = _checked_int(height, "height", minimum=1)
match = _checked_app_id(app_id)
return ContainerPlan(
output=name,
workspace=slot,
mode=(w, h),
create=[
# The output first: the workspace rule below names it, and a rule
# for an output that does not exist yet binds to nothing.
["hyprctl", "output", "create", "headless", name],
# `default:true` makes this the workspace the output shows, and
# `persistent:true` keeps it alive when the last window closes — a
# container that evaporated between two applications would send the
# next window back to the shared screen.
[
"hyprctl",
"keyword",
"workspace",
f"{slot}, monitor:{name}, default:true, persistent:true",
],
# Anchored (`^...$`) so a class that merely contains the app id
# cannot claim another session's workspace. `initial_class` rather
# than the live class: applications rename their window, and the
# placement has to be decided when it is mapped.
[
"hyprctl",
"keyword",
"windowrule",
f"match:initial_class ^{match}$, workspace {slot}, monitor {name}",
],
# Last, because the mode applies to an output that now exists and
# already has its workspace; setting it earlier would resize a
# screen that is about to be replaced.
["hyprctl", "keyword", "monitor", f"{name},{w}x{h},auto,1"],
],
teardown=[["hyprctl", "output", "remove", name]],
)
def quarantine_plan(quarantine_workspace: str) -> ContainerPlan | None:
"""The backstop rule: a window that matched no container goes here.
Without it, a window with an unexpected class — a dialog spawned by a
helper process, a toolkit that rewrites its class — lands on whatever
workspace is in front, which is the leak containers exist to prevent. The
rule matches every class and is therefore emitted *before* the per-session
rules, which are anchored and more specific.
``quarantine_workspace`` is a workspace *name* (``special:quarantine``), not
a slot out of the allocator's band, so the returned plan carries no output
and no mode: it is a rule, not a container. An empty or blank name means
the operator turned the backstop off, and the answer is ``None`` rather than
a plan with an empty command list — a caller that gets a plan should always
have something to run.
"""
target = quarantine_workspace.strip()
if not target:
return None
_checked_rule_value(target, "quarantine_workspace")
return ContainerPlan(
output="",
workspace=0,
mode=(0, 0),
create=[
[
"hyprctl",
"keyword",
"windowrule",
f"match:initial_class .*, workspace {target}",
]
],
# A keyword rule cannot be unset one at a time, and this one is not
# per-session anyway: it is installed once at start-up and goes away
# with the compositor.
teardown=[],
)
class WorkspaceAllocator:
"""Hands out workspace slots from a fixed band, lowest free first.
Lowest-free rather than monotonic so a long-lived broker's numbers stay
small and readable (``hyprctl workspaces`` is something a human reads), and
so the band is a real bound: ``count`` slots means at most ``count``
containers, with exhaustion surfacing as :class:`NoSlots` at allocation
rather than as a collision later.
"""
def __init__(self, base: int, count: int) -> None:
self._base = _checked_int(base, "base", minimum=1)
self._count = _checked_int(count, "count", minimum=1)
self._used: set[int] = set()
def allocate(self) -> int:
"""The lowest free slot in ``[base, base + count)``. Raises :class:`NoSlots`."""
for slot in range(self._base, self._base + self._count):
if slot not in self._used:
self._used.add(slot)
return slot
raise NoSlots(
f"workspace band {self._base}..{self._base + self._count - 1} is full "
f"({self._count} in use)"
)
def release(self, workspace: int) -> None:
"""Give a slot back. A slot we never handed out raises :class:`KeyError`.
Loudly, because the two ways to get here are a double release and a
caller releasing someone else's slot, and both mean the registry and
this allocator have drifted. Swallowing it would hand the same
workspace to two sessions a few minutes later, which is the leak that is
hard to trace back.
"""
if workspace not in self._used:
raise KeyError(
f"workspace {workspace} was not allocated by this allocator "
f"(in use: {sorted(self._used)})"
)
self._used.discard(workspace)
def in_use(self) -> list[int]:
"""Allocated slots, ascending. Sorted because callers log and diff it."""
return sorted(self._used)
def _checked_session_id(session_id: str) -> str:
if not isinstance(session_id, str) or not SESSION_ID_RE.match(session_id):
raise ValueError(
f"session id {session_id!r} is not [a-z0-9-]+; it names an output and "
"goes into a compositor command"
)
return session_id
def _checked_app_id(app_id: str) -> str:
if not isinstance(app_id, str) or not app_id:
raise ValueError(f"app id {app_id!r} is empty; a window rule needs a class to match")
if not APP_ID_RE.match(app_id):
raise ValueError(
f"app id {app_id!r} is not [A-Za-z0-9._+-]+; a window rule body is "
"comma-separated, so anything else could forge a rule field"
)
return app_id
def _checked_rule_value(value: str, label: str) -> str:
# Same reasoning as an app id, one rule field over: this ends up inside a
# `workspace <value>` field, where a comma starts the next field. The colon
# is allowed because `special:quarantine` needs it.
if not re.match(r"\A[A-Za-z0-9._:+-]+\Z", value):
raise ValueError(
f"{label} {value!r} is not [A-Za-z0-9._:+-]+; it is interpolated into "
"a comma-separated rule body"
)
return value
def _checked_int(value: int, label: str, *, minimum: int) -> int:
# bool is an int in Python, and `True` would silently become workspace 1.
if not isinstance(value, int) or isinstance(value, bool):
raise ValueError(f"{label} {value!r} is not an int")
if value < minimum:
raise ValueError(f"{label} {value!r} is not >= {minimum}")
return value