mirror of
https://github.com/kuhyx/steam-backlog-enforcer.git
synced 2026-11-11 13:27:33 +01:00
A running game process was treated as proof of play. On 2026-08-28 the budget
billed ~2h23m while a gatelock screen locker covered the display and the
machine could not be touched at all -- the game was simply still resident.
A tick now bills only when all three hold, evaluated together rather than
short-circuited so the audit log can answer "was the screen ALSO locked?":
* no gatelock guard owns the screen (_screen_hold, via /proc/locks)
* the focused window belongs to a qualifying process or its ancestry
* some input source has been used within idle_grace_seconds (default 300)
Any probe that cannot answer BILLS the tick and is recorded in `degraded`.
A broken detector must never become an unlimited-gaming exploit.
Three findings from measuring this machine rather than assuming:
* /dev/input/js0 here is an *ASRock LED Controller* -- the kernel exposes
the motherboard RGB device as a joystick. A presence check would have
disabled the idle criterion permanently, so _controller_input watches for
real events instead (skipping joydev's synthetic open burst).
* Aseprite's window carries no _NET_WM_PID at all, so focus attribution
falls back to XRes, which asks the server who owns the window rather than
trusting the client to have announced itself.
* /proc/locks reports gatelock's hold without taking it; gatelock's own
read_claim_if_held detects held-ness by acquiring, which would race a
guard every 3 seconds.
Idle pauses also refund the grace period once per walk-away, on the
engaged->paused edge only, never across a day rollover, and never on the first
tick after a restart -- the only place the counter moves backwards.
Everything is recorded to /var/log/steam-backlog-enforcer/budget.jsonl, on
change plus a heartbeat rather than one line per 3s tick. Records name the
qualifying PIDs: reconstructing this incident from journald alone was only
possible by inferring accrual from the spacing of two warning notifications.
Also: refuse to bounce Steam while a game is running. ensure_steam_debug_port
relaunches Steam when the CDP port is closed, which kills the running game --
that is how restarting the daemon to deploy this change ended a live session.
It now defers exactly as it already did for in-flight game updates.
Talks to X through ctypes over one cached connection: at a 3s tick, forking
xprintidle and xprop would cost ~40 forks a minute.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019CEsG6BzHtYR9cHcdxPZqG
125 lines
3.6 KiB
Python
125 lines
3.6 KiB
Python
"""Detecting that a gatelock guard currently owns the screen.
|
|
|
|
The screen lockers (``screen_locker``, ``leetcode_guard``) coordinate through a
|
|
single advisory ``flock`` on ``$XDG_RUNTIME_DIR/gatelock/holder.lock``. The file's
|
|
*contents* cannot answer "is it held right now" — a stale record left by a dead
|
|
process is byte-identical to a live one — and gatelock's own
|
|
``read_claim_if_held`` answers the question by *taking* the lock.
|
|
|
|
The enforcer must not do that. Taking the lock every three seconds, even for
|
|
microseconds, would race a guard trying to claim the screen. ``/proc/locks``
|
|
reports the same fact by observation, so this reads that instead and never
|
|
touches the file.
|
|
|
|
Line format is ``idx: FLOCK ADVISORY WRITE <pid> <maj:min:inode> <start> <end>``,
|
|
with major and minor in hex. Lines containing ``->`` describe processes *waiting*
|
|
for a lock, not holding one, and are skipped.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from dataclasses import dataclass
|
|
import os
|
|
from pathlib import Path
|
|
import re
|
|
from typing import Final
|
|
|
|
_PROC_LOCKS: Final = Path("/proc/locks")
|
|
_HOLDER_RELATIVE: Final = Path("gatelock/holder.lock")
|
|
|
|
# `maj:min:inode`, major and minor hex, inode decimal.
|
|
_DEVICE_FIELD: Final = re.compile(r"^[0-9a-f]+:[0-9a-f]+:\d+$")
|
|
|
|
_WAITER_MARKER: Final = "->"
|
|
_PID_FIELD_INDEX: Final = 4
|
|
|
|
|
|
class ScreenHoldError(RuntimeError):
|
|
"""Whether the screen is held could not be determined."""
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class ScreenHold:
|
|
"""Whether a guard owns the screen, and which process does."""
|
|
|
|
held: bool
|
|
holder_pid: int | None = None
|
|
|
|
|
|
def holder_lock_path(uid: int) -> Path:
|
|
"""Return the gatelock holder-lock path for *uid*.
|
|
|
|
Args:
|
|
uid: Owner of the desktop session.
|
|
|
|
Returns:
|
|
Path to ``holder.lock``.
|
|
"""
|
|
return Path(f"/run/user/{uid}") / _HOLDER_RELATIVE
|
|
|
|
|
|
def screen_hold(path: Path) -> ScreenHold:
|
|
"""Report whether *path*'s advisory lock is currently held.
|
|
|
|
Args:
|
|
path: The gatelock holder-lock file.
|
|
|
|
Returns:
|
|
The hold state, with the holding PID when there is one.
|
|
|
|
Raises:
|
|
ScreenHoldError: If ``/proc/locks`` cannot be read. A missing *path* is
|
|
not an error — it means no guard has ever run this boot.
|
|
"""
|
|
try:
|
|
stat = path.stat()
|
|
except OSError:
|
|
return ScreenHold(held=False)
|
|
|
|
target = f"{os.major(stat.st_dev):02x}:{os.minor(stat.st_dev):02x}:{stat.st_ino}"
|
|
|
|
try:
|
|
raw = _PROC_LOCKS.read_text(encoding="utf-8")
|
|
except OSError as exc:
|
|
msg = f"cannot read {_PROC_LOCKS}: {exc}"
|
|
raise ScreenHoldError(msg) from exc
|
|
|
|
return _find_holder(raw, target)
|
|
|
|
|
|
def _find_holder(raw: str, target: str) -> ScreenHold:
|
|
"""Scan ``/proc/locks`` text for a live lock on *target*.
|
|
|
|
Args:
|
|
raw: Contents of ``/proc/locks``.
|
|
target: ``maj:min:inode`` string to match.
|
|
|
|
Returns:
|
|
The hold state.
|
|
"""
|
|
for line in raw.splitlines():
|
|
fields = line.split()
|
|
if _WAITER_MARKER in fields:
|
|
continue
|
|
if not any(field == target for field in fields if _DEVICE_FIELD.match(field)):
|
|
continue
|
|
return ScreenHold(held=True, holder_pid=_pid_of(fields))
|
|
return ScreenHold(held=False)
|
|
|
|
|
|
def _pid_of(fields: list[str]) -> int | None:
|
|
"""Return the PID column of a ``/proc/locks`` row.
|
|
|
|
Args:
|
|
fields: Whitespace-split row.
|
|
|
|
Returns:
|
|
The PID, or ``None`` if the row is shaped unexpectedly.
|
|
"""
|
|
if len(fields) <= _PID_FIELD_INDEX:
|
|
return None
|
|
try:
|
|
return int(fields[_PID_FIELD_INDEX])
|
|
except ValueError:
|
|
return None
|