steam-backlog-enforcer/steam_backlog_enforcer/tests/_fake_session.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

124 lines
3.3 KiB
Python

"""A :class:`PlaytimeSession` stub for tests that are not about engagement.
Most budget tests predate the engagement gate and care only about accounting,
warnings and the cutoff. They get a session that always says "engaged", which
reproduces the pre-gate behaviour exactly, so those tests keep asserting what
they were written to assert.
Deliberately hand-written rather than ``MagicMock``: a mock satisfies every
attribute lookup, including ones a later refactor renamed, so a stub that must
actually match the protocol is the point.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
from steam_backlog_enforcer._engagement_types import (
STATE_ENGAGED,
STATE_PAUSED,
EngagementVerdict,
)
from steam_backlog_enforcer._playtime_session import PlaytimeSession
if TYPE_CHECKING:
from steam_backlog_enforcer._playtime_state import PlaytimeRules, PlaytimeState
class StubTracker:
"""An engagement tracker with a fixed answer and no probes."""
def __init__(self, *, engaged: bool = True) -> None:
"""Record the answer this tracker always gives.
Args:
engaged: Whether every tick should count.
"""
self.engaged = engaged
self.verdicts: list[EngagementVerdict] = []
def assess(
self,
rules: PlaytimeRules,
*,
qualifying: set[int],
now_monotonic: float,
) -> EngagementVerdict:
"""Return the fixed verdict.
Args:
rules: Ignored.
qualifying: PIDs recorded on the verdict.
now_monotonic: Ignored.
Returns:
The verdict.
"""
del rules, now_monotonic
verdict = EngagementVerdict(
state=STATE_ENGAGED if self.engaged else STATE_PAUSED,
causes=() if self.engaged else ("focus",),
qualifying=tuple(sorted(qualifying)),
)
self.verdicts.append(verdict)
return verdict
def backdate(
self,
state: PlaytimeState,
verdict: EngagementVerdict,
*,
rules: PlaytimeRules,
) -> PlaytimeState:
"""Return *state* untouched.
Args:
state: Accounting state.
verdict: Ignored.
rules: Ignored.
Returns:
The unchanged state.
"""
del verdict, rules
return state
class StubJournal:
"""A journal that keeps records in memory instead of on disk."""
def __init__(self) -> None:
"""Start with nothing recorded."""
self.observed: list[EngagementVerdict] = []
def observe(
self,
verdict: EngagementVerdict,
state: PlaytimeState,
*,
rules: PlaytimeRules,
now_monotonic: float,
) -> None:
"""Remember *verdict*.
Args:
verdict: This tick's verdict.
state: Ignored.
rules: Ignored.
now_monotonic: Ignored.
"""
del state, rules, now_monotonic
self.observed.append(verdict)
def fake_session(*, engaged: bool = True) -> PlaytimeSession:
"""Build a session that never touches X, /proc/locks or the log file.
Args:
engaged: Whether every tick should count against the budget.
Returns:
The session.
"""
return PlaytimeSession(tracker=StubTracker(engaged=engaged), journal=StubJournal())