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

112 lines
3.8 KiB
Python

"""Tests for observing a gatelock screen hold through ``/proc/locks``.
The probe must never take the lock itself, so every case here is driven by
synthetic ``/proc/locks`` text rather than by acquiring anything.
"""
from __future__ import annotations
import os
from pathlib import Path
from unittest.mock import patch
import pytest
from steam_backlog_enforcer._screen_hold import (
ScreenHoldError,
holder_lock_path,
screen_hold,
)
SH = "steam_backlog_enforcer._screen_hold"
def _device_field(path: Path) -> str:
stat = path.stat()
return f"{os.major(stat.st_dev):02x}:{os.minor(stat.st_dev):02x}:{stat.st_ino}"
class TestHolderLockPath:
def test_uses_the_runtime_dir_of_the_session_owner(self) -> None:
assert holder_lock_path(1000) == Path("/run/user/1000/gatelock/holder.lock")
def test_differs_per_uid(self) -> None:
assert holder_lock_path(1000) != holder_lock_path(1001)
class TestScreenHold:
def test_missing_file_is_not_held_and_not_an_error(self, tmp_path: Path) -> None:
result = screen_hold(tmp_path / "never-created.lock")
assert result.held is False
assert result.holder_pid is None
def test_reports_held_with_the_holding_pid(self, tmp_path: Path) -> None:
lock = tmp_path / "holder.lock"
lock.touch()
locks = tmp_path / "locks"
locks.write_text(
f"1: FLOCK ADVISORY WRITE 4242 {_device_field(lock)} 0 EOF\n"
)
with patch(f"{SH}._PROC_LOCKS", locks):
result = screen_hold(lock)
assert result.held is True
assert result.holder_pid == 4242
def test_reports_free_when_another_file_is_locked(self, tmp_path: Path) -> None:
lock = tmp_path / "holder.lock"
lock.touch()
locks = tmp_path / "locks"
locks.write_text("1: FLOCK ADVISORY WRITE 4242 00:19:999999 0 EOF\n")
with patch(f"{SH}._PROC_LOCKS", locks):
assert screen_hold(lock).held is False
def test_a_waiter_row_is_not_a_holder(self, tmp_path: Path) -> None:
lock = tmp_path / "holder.lock"
lock.touch()
locks = tmp_path / "locks"
locks.write_text(
f"1: -> FLOCK ADVISORY WRITE 4242 {_device_field(lock)} 0 EOF\n"
)
with patch(f"{SH}._PROC_LOCKS", locks):
assert screen_hold(lock).held is False
def test_rows_without_a_device_field_are_skipped(self, tmp_path: Path) -> None:
lock = tmp_path / "holder.lock"
lock.touch()
locks = tmp_path / "locks"
locks.write_text(
"garbage row with no device\n"
f"2: FLOCK ADVISORY READ 7 {_device_field(lock)} 0 EOF\n"
)
with patch(f"{SH}._PROC_LOCKS", locks):
assert screen_hold(lock).held is True
def test_short_row_yields_no_pid(self, tmp_path: Path) -> None:
lock = tmp_path / "holder.lock"
lock.touch()
locks = tmp_path / "locks"
locks.write_text(f"1: FLOCK {_device_field(lock)}\n")
with patch(f"{SH}._PROC_LOCKS", locks):
result = screen_hold(lock)
assert result.held is True
assert result.holder_pid is None
def test_non_numeric_pid_yields_no_pid(self, tmp_path: Path) -> None:
lock = tmp_path / "holder.lock"
lock.touch()
locks = tmp_path / "locks"
locks.write_text(
f"1: FLOCK ADVISORY WRITE nope {_device_field(lock)} 0 EOF\n"
)
with patch(f"{SH}._PROC_LOCKS", locks):
assert screen_hold(lock).holder_pid is None
def test_unreadable_proc_locks_raises(self, tmp_path: Path) -> None:
lock = tmp_path / "holder.lock"
lock.touch()
with (
patch(f"{SH}._PROC_LOCKS", tmp_path / "absent"),
pytest.raises(ScreenHoldError),
):
screen_hold(lock)