steam-backlog-enforcer/steam_backlog_enforcer/_steam_restart_guard.py
Krzysztof kuhy Rudnicki b3e629e3f0 Bill gaming time only while the user is actually playing
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
2026-08-28 19:24:14 +02:00

67 lines
2.5 KiB
Python

"""When it is *not* safe to bounce a running Steam.
Opening the CDP debug port requires restarting Steam, and a restart is never
free: it takes down whatever the client is currently doing. Two situations make
that unacceptable, and both defer rather than abort — the enforce loop retries
every few seconds, so waiting costs a pass and nothing else.
Split out of :mod:`_steam_launch` to keep it under the 250-line cap, and because
"is a restart safe right now" is a question worth being able to ask on its own.
"""
from __future__ import annotations
import logging
from steam_backlog_enforcer._steam_errors import (
GameInProgressError,
SteamUpdateInProgressError,
)
from steam_backlog_enforcer._steam_state import steam_update_in_progress
from steam_backlog_enforcer.enforcer import get_running_steam_game_pids
logger = logging.getLogger(__name__)
def game_is_running() -> bool:
"""Whether a Steam game is currently running.
Uses the same ``SteamAppId != 0`` predicate as the playtime budget, which
excludes the Steam client's own process tree — the client being up is not a
reason to defer, only an actual game is.
Returns:
Whether any game process is live.
"""
return any(app_id != 0 for app_id in get_running_steam_game_pids().values())
def assert_safe_to_restart() -> None:
"""Refuse to restart Steam while doing so would destroy something.
Raises:
GameInProgressError: If a game is running. Bouncing Steam kills it and
any unsaved progress with it — observed on 2026-08-28, when
restarting the daemon to deploy an unrelated change ended a live
session. Library hiding can wait; an afternoon cannot be returned.
SteamUpdateInProgressError: If a game update is downloading or
committing. The shutdown suspends it and can leave a partially
written install (the root cause of the AoE2 launch crash).
"""
if game_is_running():
msg = (
"Deferring Steam restart: a game is running. Restarting now would "
"kill it and lose unsaved progress; will retry once it exits."
)
logger.info(msg)
raise GameInProgressError(msg)
if steam_update_in_progress():
msg = (
"Deferring Steam restart: a game update is in progress. Restarting "
"now would interrupt and can corrupt it; will retry once the "
"update settles."
)
logger.info(msg)
raise SteamUpdateInProgressError(msg)