mirror of
https://github.com/kuhyx/steam-backlog-enforcer.git
synced 2026-11-26 21:47:16 +01:00
Compare commits
9 Commits
4e9987c428
...
d2c4ea7ace
| Author | SHA1 | Date | |
|---|---|---|---|
| d2c4ea7ace | |||
| 7957a1fe12 | |||
| bc02f83e7e | |||
| 0ffc773f52 | |||
| e0cf931d0e | |||
| cef98a998a | |||
| 04bd0837f1 | |||
| c99dd12984 | |||
| 26a2aabbc7 |
@ -110,8 +110,8 @@ repos:
|
||||
- --disable-error-code=list-item
|
||||
additional_dependencies:
|
||||
- types-requests
|
||||
- earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.14.0#subdirectory=earned_time
|
||||
- leisure-watch @ git+https://github.com/kuhyx/leisure-watch@leisure-watch-v0.1.2
|
||||
- earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.16.0#subdirectory=earned_time
|
||||
- leisure-watch @ git+https://github.com/kuhyx/leisure-watch@leisure-watch-v0.2.1
|
||||
|
||||
# ===========================================================================
|
||||
# PYLINT
|
||||
@ -131,8 +131,8 @@ repos:
|
||||
# (steam_backlog_enforcer._mcp_server).
|
||||
additional_dependencies:
|
||||
- aiohttp==3.14.5
|
||||
- earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.14.0#subdirectory=earned_time
|
||||
- leisure-watch @ git+https://github.com/kuhyx/leisure-watch@leisure-watch-v0.1.2
|
||||
- earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.16.0#subdirectory=earned_time
|
||||
- leisure-watch @ git+https://github.com/kuhyx/leisure-watch@leisure-watch-v0.2.1
|
||||
- howlongtobeatpy==1.0.24
|
||||
- mcp==2.3.0
|
||||
- pytest
|
||||
|
||||
@ -16,11 +16,11 @@ dependencies = [
|
||||
"websockets==17.2",
|
||||
# The earner registry (gaming budget terms); stdlib-only, so the root
|
||||
# daemon imports it from the desktop user's site-packages.
|
||||
"earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.14.0#subdirectory=earned_time",
|
||||
"earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.16.0#subdirectory=earned_time",
|
||||
# The shared /proc game scan and the signed leisure facts (shadow budget,
|
||||
# contract C4); stdlib-only, imported by root from the user site like
|
||||
# earned-time.
|
||||
"leisure-watch @ git+https://github.com/kuhyx/leisure-watch@leisure-watch-v0.1.2",
|
||||
"leisure-watch @ git+https://github.com/kuhyx/leisure-watch@leisure-watch-v0.2.1",
|
||||
]
|
||||
|
||||
# Optional extras. The `mcp` group is ONLY needed by the MCP server
|
||||
|
||||
@ -5,9 +5,9 @@ aiohttp==3.14.5
|
||||
bandit==1.9.4
|
||||
codespell==2.4.3
|
||||
coverage==7.16.2
|
||||
earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.14.0#subdirectory=earned_time
|
||||
earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.16.0#subdirectory=earned_time
|
||||
howlongtobeatpy==1.0.24
|
||||
leisure-watch @ git+https://github.com/kuhyx/leisure-watch@leisure-watch-v0.1.2
|
||||
leisure-watch @ git+https://github.com/kuhyx/leisure-watch@leisure-watch-v0.2.1
|
||||
mcp==2.3.0
|
||||
mypy==2.4.0
|
||||
pre-commit==4.7.0
|
||||
|
||||
@ -41,12 +41,13 @@ resolving a second time.
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime
|
||||
from datetime import date, datetime
|
||||
import logging
|
||||
from typing import TYPE_CHECKING, Final
|
||||
|
||||
import earned_time
|
||||
|
||||
from steam_backlog_enforcer._gaming_days import gaming_day_key
|
||||
from steam_backlog_enforcer._ledger_earners import (
|
||||
first_credits,
|
||||
ledger_answer,
|
||||
@ -58,8 +59,6 @@ from steam_backlog_enforcer._reading_bonus import read_today
|
||||
from steam_backlog_enforcer._workout_budget import workout_logged_today
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from datetime import date
|
||||
|
||||
from steam_backlog_enforcer.config import Config
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@ -68,6 +67,9 @@ _SECONDS_PER_MINUTE: Final = 60.0
|
||||
_SECONDS_PER_HOUR: Final = 3600.0
|
||||
# The last reason logged, so a long-lived daemon logs a budget only on change.
|
||||
_last_logged: Final[dict[str, str]] = {}
|
||||
# Passed explicitly: ``leisure_active``'s default is bound at import, so this
|
||||
# module constant is what a test redirects (as ``_leisure_mode`` does).
|
||||
LEISURE_FROM_PATH: Final = earned_time.LEISURE_FROM_PATH
|
||||
|
||||
# How each earner reads in the reason string: (earned, missed, unknown).
|
||||
# An earner registered later without an entry here gets a generic phrase.
|
||||
@ -126,7 +128,11 @@ def _price(
|
||||
*,
|
||||
leisure: bool,
|
||||
) -> earned_time.Resolution:
|
||||
"""Price one set of answers; ``leisure=False`` is exactly the old call."""
|
||||
"""Price one set of answers: ``leisure`` True = leisure, False = pre-leisure.
|
||||
|
||||
Always explicit (earned_time 0.16.0): ``False`` forces pre-leisure pricing,
|
||||
it no longer means "by the switch file".
|
||||
"""
|
||||
if first_paid is None:
|
||||
return earned_time.resolve(answers, today, registry, leisure=leisure)
|
||||
return earned_time.resolve(
|
||||
@ -168,6 +174,16 @@ def _answers(
|
||||
return answers
|
||||
|
||||
|
||||
def leisure_priced(now: datetime) -> bool:
|
||||
"""Whether the 06:00 gaming day holding *now* is priced as leisure.
|
||||
|
||||
The same question billing asks (``_leisure_mode.leisure_on`` of the billed
|
||||
day), so 00:00-05:59 on the go-live date stays pre-leisure, like its bill.
|
||||
"""
|
||||
day = date.fromisoformat(gaming_day_key(now))
|
||||
return bool(earned_time.leisure_active(day, LEISURE_FROM_PATH))
|
||||
|
||||
|
||||
def resolve_budget(config: Config) -> BudgetResolution:
|
||||
"""Return today's gaming budget, and what earned it.
|
||||
|
||||
@ -181,12 +197,13 @@ def resolve_budget(config: Config) -> BudgetResolution:
|
||||
"""
|
||||
# The registry is passed explicitly: _answers iterated this same tuple, so
|
||||
# the earners asked and the earners summed can never differ.
|
||||
today = datetime.now().astimezone().date()
|
||||
now = datetime.now().astimezone()
|
||||
today = now.date()
|
||||
registry = registry_for(today)
|
||||
answers = _answers(config, registry)
|
||||
# Maturity only delays a penalty: a gate that never paid out costs nothing.
|
||||
first_paid = first_credits(registry, today)
|
||||
day = _price(answers, today, registry, first_paid, leisure=False)
|
||||
day = _price(answers, today, registry, first_paid, leisure=leisure_priced(now))
|
||||
# The same answers, asked once: the shadow can never see a different day.
|
||||
# A missing answer was already warned about above; to earned_time it is
|
||||
# the same as None, so spell it out rather than warn a second time.
|
||||
|
||||
244
steam_backlog_enforcer/_leisure_kill.py
Normal file
244
steam_backlog_enforcer/_leisure_kill.py
Normal file
@ -0,0 +1,244 @@
|
||||
"""Phase 2 at 0: end every leisure app the watcher names (Steam is separate).
|
||||
|
||||
Runs every 3 s tick while the leisure budget is spent, beside the unchanged
|
||||
Steam cutoff (:mod:`_playtime_cutoff`). Which pids:
|
||||
|
||||
* **Trusted** ``now.json``: every ``focus``/``media`` reason's pid unless it is
|
||||
a browser (the extension redirects those to the "leisure spent" page), and
|
||||
every ``failclosed`` reason's pid -- a browser that is not reporting (another
|
||||
browser, an unreported private window) has nothing redirecting it.
|
||||
``game`` reasons belong to the Steam path.
|
||||
* **Untrusted** (stale, missing, badly signed, unreadable) for 30 s in a row:
|
||||
every browser, media player and wsg-grabber reviewer
|
||||
(:func:`_leisure_procs.sweep_targets`) until the watcher is fresh again. One
|
||||
stale moment (resume from sleep, a watcher restart) kills nothing: a trusted
|
||||
or paused tick, or a gap between ticks (a suspend), restarts the window.
|
||||
* **Paused** (a locker grab is held): nothing; the lock is not a stale watcher.
|
||||
|
||||
Each process gets SIGTERM once, then SIGKILL every tick from 30 s after *its*
|
||||
SIGTERM -- timed per process, so an app opened an hour into the block still
|
||||
gets its 30 s. A process is its (pid, start time), so a reused pid starts
|
||||
over; a reason carrying the start time it saw (leisure-watch 0.2.1 ``start``)
|
||||
names only that process, never a later one reusing the pid. Root/system
|
||||
processes, lockers and the enforcer itself are never signalled, nor --
|
||||
whatever ``now.json`` says -- the desktop session (:mod:`_leisure_never_kill`;
|
||||
each refusal logged once). Every SIGTERM and the first SIGKILL go to
|
||||
``budget.jsonl``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import math
|
||||
import os
|
||||
import signal
|
||||
from typing import TYPE_CHECKING, Final, Protocol
|
||||
|
||||
from steam_backlog_enforcer._leisure_never_kill import never_kill
|
||||
from steam_backlog_enforcer._leisure_procs import (
|
||||
exe_name,
|
||||
is_browser,
|
||||
is_protected,
|
||||
own_chain,
|
||||
start_time,
|
||||
sweep_targets,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from leisure_watch.facts import Now, Reason
|
||||
|
||||
from steam_backlog_enforcer._playtime_state import PlaytimeRules, PlaytimeState
|
||||
from steam_backlog_enforcer._shadow import ShadowVerdict
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
EVENT_LEISURE_KILL: Final = "leisure_kill"
|
||||
EVENT_KILL_REFUSED: Final = "leisure_kill_refused"
|
||||
SIGKILL_AFTER_SECONDS: Final = 30.0
|
||||
UNTRUSTED_SWEEP_AFTER: Final = 30.0
|
||||
# Ticks are 3 s apart; a longer gap (suspend, a stalled loop) is not "in a row".
|
||||
_MAX_TICK_GAP: Final = 10.0
|
||||
_KILLED_SOURCES: Final = frozenset({"focus", "media"})
|
||||
_FAILCLOSED: Final = "failclosed"
|
||||
|
||||
_Ident = tuple[int, int]
|
||||
|
||||
|
||||
class KillLog(Protocol):
|
||||
"""Where kills are recorded (``BudgetLog``)."""
|
||||
|
||||
def record(self, event: str, **fields: object) -> None:
|
||||
"""Append one record."""
|
||||
|
||||
|
||||
def _picks(fact: Now) -> dict[int, Reason]:
|
||||
"""Pids a trusted *fact* says must end, to the (first) reason naming them."""
|
||||
found: dict[int, Reason] = {}
|
||||
for reason in fact.reasons:
|
||||
if reason.pid is None:
|
||||
continue
|
||||
failclosed = reason.source == _FAILCLOSED
|
||||
if failclosed or (
|
||||
reason.source in _KILLED_SOURCES and not is_browser(reason.pid)
|
||||
):
|
||||
found.setdefault(reason.pid, reason)
|
||||
return found
|
||||
|
||||
|
||||
def fact_targets(fact: Now) -> dict[int, str]:
|
||||
"""Pids a trusted *fact* says must end, to the reason key that named them."""
|
||||
return {pid: reason.key for pid, reason in _picks(fact).items()}
|
||||
|
||||
|
||||
def _start(reason: Reason) -> int | None:
|
||||
# Optional from leisure-watch 0.2.1; absent (0.2.0) or unusable = unknown.
|
||||
start = getattr(reason, "start", None)
|
||||
usable = isinstance(start, int) and not isinstance(start, bool)
|
||||
return start if usable else None
|
||||
|
||||
|
||||
def fact_starts(fact: Now) -> dict[int, int]:
|
||||
"""Per target pid, the start time its reason saw (when it carries one)."""
|
||||
starts = {pid: _start(reason) for pid, reason in _picks(fact).items()}
|
||||
return {pid: start for pid, start in starts.items() if start is not None}
|
||||
|
||||
|
||||
class LeisureKiller:
|
||||
"""The per-daemon kill state: when each process got its SIGTERM."""
|
||||
|
||||
def __init__(self, log: KillLog | None = None) -> None:
|
||||
"""Start with nothing signalled.
|
||||
|
||||
Args:
|
||||
log: The budget audit log; ``None`` records nowhere.
|
||||
"""
|
||||
self.log = log
|
||||
self._termed: dict[_Ident, float] = {}
|
||||
self._killed: set[_Ident] = set()
|
||||
self._refused: set[_Ident] = set()
|
||||
self._untrusted_since: float | None = None
|
||||
self._last_stamp = -math.inf
|
||||
self._last_error = ""
|
||||
|
||||
def enforce(
|
||||
self,
|
||||
state: PlaytimeState,
|
||||
rules: PlaytimeRules,
|
||||
*,
|
||||
verdict: ShadowVerdict,
|
||||
stamp: float,
|
||||
) -> None:
|
||||
"""Signal this tick's leisure targets if the leisure budget is spent.
|
||||
|
||||
Never raises: the enforce loop has no per-tick guard.
|
||||
|
||||
Args:
|
||||
state: Accounting state after this tick's policy.
|
||||
rules: Policy for this tick (``leisure`` set by the billing step).
|
||||
verdict: This tick's shadow verdict, carrying the trusted fact.
|
||||
stamp: Epoch seconds of this tick.
|
||||
"""
|
||||
try:
|
||||
self._enforce(state, rules, verdict=verdict, stamp=stamp)
|
||||
except Exception as exc: # the loop must outlive any kill bug
|
||||
message = f"{type(exc).__name__}: {exc}"
|
||||
if message != self._last_error:
|
||||
self._last_error = message
|
||||
logger.warning("Leisure kill failed (%s).", message, exc_info=True)
|
||||
|
||||
def _enforce(
|
||||
self,
|
||||
state: PlaytimeState,
|
||||
rules: PlaytimeRules,
|
||||
*,
|
||||
verdict: ShadowVerdict,
|
||||
stamp: float,
|
||||
) -> None:
|
||||
if not rules.leisure or rules.demo or not rules.enforcement:
|
||||
return
|
||||
untrusted_for = self._untrusted_for(verdict, stamp)
|
||||
if state.seconds < rules.budget_seconds:
|
||||
self._termed.clear()
|
||||
self._killed.clear()
|
||||
return
|
||||
if verdict.paused_by is not None:
|
||||
return
|
||||
starts: dict[int, int] = {}
|
||||
if verdict.fact is None:
|
||||
if untrusted_for < UNTRUSTED_SWEEP_AFTER:
|
||||
return
|
||||
targets, why = sweep_targets(), "now.json untrusted"
|
||||
else:
|
||||
targets, why = fact_targets(verdict.fact), "now.json"
|
||||
starts = fact_starts(verdict.fact)
|
||||
live = self._identify(targets, starts)
|
||||
self._termed = {i: t for i, t in self._termed.items() if i in live}
|
||||
self._killed &= set(live)
|
||||
base = {
|
||||
"why": why,
|
||||
"day_key": state.day_key,
|
||||
"seconds": round(state.seconds, 3),
|
||||
}
|
||||
for ident, key in sorted(live.items()):
|
||||
note = {"key": key, "name": exe_name(ident[0]), **base}
|
||||
first = self._termed.get(ident)
|
||||
if first is None:
|
||||
self._termed[ident] = stamp
|
||||
self._signal(ident[0], signal.SIGTERM, note)
|
||||
elif stamp - first >= SIGKILL_AFTER_SECONDS:
|
||||
quiet = ident in self._killed
|
||||
if self._signal(ident[0], signal.SIGKILL, None if quiet else note):
|
||||
self._killed.add(ident)
|
||||
|
||||
def _untrusted_for(self, verdict: ShadowVerdict, stamp: float) -> float:
|
||||
"""Seconds ``now.json`` has been untrusted in a row, as of this tick."""
|
||||
gap = stamp - self._last_stamp
|
||||
self._last_stamp = stamp
|
||||
if verdict.fact is not None or verdict.paused_by is not None:
|
||||
self._untrusted_since = None
|
||||
return 0.0
|
||||
if self._untrusted_since is None or not 0.0 <= gap <= _MAX_TICK_GAP:
|
||||
self._untrusted_since = stamp
|
||||
return stamp - self._untrusted_since
|
||||
|
||||
def _identify(
|
||||
self, targets: dict[int, str], starts: dict[int, int]
|
||||
) -> dict[_Ident, str]:
|
||||
chain = own_chain()
|
||||
live: dict[_Ident, str] = {}
|
||||
refused: set[_Ident] = set()
|
||||
for pid, key in targets.items():
|
||||
started = start_time(pid)
|
||||
if started is None or starts.get(pid, started) != started:
|
||||
continue # gone, or the pid now belongs to another process
|
||||
if is_protected(pid, chain):
|
||||
continue
|
||||
guard = never_kill(pid)
|
||||
if guard is None:
|
||||
live[pid, started] = key
|
||||
continue
|
||||
refused.add((pid, started))
|
||||
if (pid, started) not in self._refused:
|
||||
self._refuse(pid, key, guard)
|
||||
self._refused = refused
|
||||
return live
|
||||
|
||||
def _refuse(self, pid: int, key: str, name: str) -> None:
|
||||
"""Log, once per process, a kill the never-kill set stopped."""
|
||||
logger.warning(
|
||||
"Refused leisure kill of pid %d (%s): %s is never killed.", pid, key, name
|
||||
)
|
||||
if self.log is not None:
|
||||
self.log.record(EVENT_KILL_REFUSED, pid=pid, key=key, name=name)
|
||||
|
||||
def _signal(
|
||||
self, pid: int, sig: signal.Signals, note: dict[str, object] | None
|
||||
) -> bool:
|
||||
"""Send *sig*; record it unless *note* is ``None``. True if delivered."""
|
||||
try:
|
||||
os.kill(pid, sig)
|
||||
except ProcessLookupError, PermissionError:
|
||||
return False
|
||||
if note is not None and self.log is not None:
|
||||
self.log.record(EVENT_LEISURE_KILL, pid=pid, signal=sig.name, **note)
|
||||
return True
|
||||
114
steam_backlog_enforcer/_leisure_mode.py
Normal file
114
steam_backlog_enforcer/_leisure_mode.py
Normal file
@ -0,0 +1,114 @@
|
||||
"""Phase 2 of the leisure rollout: is it on for this gaming day, and its billing.
|
||||
|
||||
Dormant until ``leisure-watch go-live`` writes the switch file. The only
|
||||
question asked of it is :func:`earned_time.leisure_active` for the *billed*
|
||||
gaming day (06:00 boundary, ``state.day_key`` after the roll-over), so the
|
||||
billing mode always matches the day being billed; no code here reads the file.
|
||||
|
||||
When on, the enforced ``seconds`` are billed by the shadow rule (contract C4,
|
||||
:mod:`_shadow`) instead of games-only: a held locker grab or i3lock pauses
|
||||
everything, games included; anything the watcher calls leisure -- or a watcher
|
||||
that cannot be trusted -- bills; overlaps bill the wall clock once.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, replace
|
||||
from datetime import date, datetime
|
||||
from typing import TYPE_CHECKING, Final
|
||||
|
||||
import earned_time
|
||||
from leisure_watch.procscan import attributed_key
|
||||
|
||||
from steam_backlog_enforcer._playtime_budget import accumulate, bill
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from steam_backlog_enforcer._playtime_state import PlaytimeRules, PlaytimeState
|
||||
from steam_backlog_enforcer._shadow import ShadowVerdict
|
||||
|
||||
# Passed explicitly on every call: ``leisure_active``'s default is bound at
|
||||
# import, so this module constant is what a test redirects.
|
||||
LEISURE_FROM_PATH: Final = earned_time.LEISURE_FROM_PATH
|
||||
|
||||
|
||||
def leisure_on(day_key: str) -> bool:
|
||||
"""Whether the gaming day *day_key* (``YYYY-MM-DD``) is on the leisure budget.
|
||||
|
||||
Args:
|
||||
day_key: The gaming day being billed.
|
||||
|
||||
Returns:
|
||||
``earned_time.leisure_active`` for that day; ``False`` for a key that is
|
||||
not a date (the games-only behaviour, which is what ran before).
|
||||
"""
|
||||
try:
|
||||
day = date.fromisoformat(day_key)
|
||||
except ValueError:
|
||||
return False
|
||||
return bool(earned_time.leisure_active(day, LEISURE_FROM_PATH))
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Tick:
|
||||
"""What one enforce-loop tick observed, for billing."""
|
||||
|
||||
now: datetime
|
||||
"""Timezone-aware local timestamp for this tick."""
|
||||
interval: float
|
||||
"""Nominal seconds between ticks."""
|
||||
owners: dict[int, str]
|
||||
"""Qualifying game PIDs to attribution keys."""
|
||||
verdict: ShadowVerdict
|
||||
"""This tick's shadow verdict."""
|
||||
|
||||
|
||||
def leisure_billed(state: PlaytimeState, tick: Tick) -> PlaytimeState:
|
||||
"""Bill this tick's enforced time by the shadow rule.
|
||||
|
||||
Only a game (``attributed_key``) is ever credited to ``per_game``; other
|
||||
leisure shows as unattributed, its split lives in ``shadow_per_source``.
|
||||
|
||||
Args:
|
||||
state: Accounting state (shadow already accumulated for this tick).
|
||||
tick: This tick's observations.
|
||||
|
||||
Returns:
|
||||
The billed state.
|
||||
"""
|
||||
billed = tick.verdict.paused_by is None and bool(tick.verdict.keys)
|
||||
return bill(
|
||||
state,
|
||||
now=tick.now,
|
||||
billed=billed,
|
||||
interval=tick.interval,
|
||||
credited_key=attributed_key(tick.owners) if billed else "",
|
||||
)
|
||||
|
||||
|
||||
def bill_tick(
|
||||
state: PlaytimeState, rules: PlaytimeRules, tick: Tick
|
||||
) -> tuple[PlaytimeState, PlaytimeRules]:
|
||||
"""Bill this tick's enforced time: games-only, or (Phase 2) by the shadow rule.
|
||||
|
||||
Dormant (no switch, a day before it, or a demo): exactly the old
|
||||
``accumulate`` call, and *rules* returned as they came.
|
||||
|
||||
Args:
|
||||
state: Accounting state (shadow already accumulated for this tick).
|
||||
rules: Policy for this tick.
|
||||
tick: This tick's observations.
|
||||
|
||||
Returns:
|
||||
The billed state, and the tick's rules -- with ``leisure=True`` when
|
||||
live, so the warnings, the cutoff and the kills act for leisure.
|
||||
"""
|
||||
if rules.demo or not leisure_on(state.day_key):
|
||||
billed = accumulate(
|
||||
state,
|
||||
now=tick.now,
|
||||
qualifying=set(tick.owners),
|
||||
interval=tick.interval,
|
||||
credited_key=attributed_key(tick.owners),
|
||||
)
|
||||
return billed, rules
|
||||
return leisure_billed(state, tick), replace(rules, leisure=True)
|
||||
121
steam_backlog_enforcer/_leisure_never_kill.py
Normal file
121
steam_backlog_enforcer/_leisure_never_kill.py
Normal file
@ -0,0 +1,121 @@
|
||||
"""What a leisure kill never signals, whatever ``now.json`` says.
|
||||
|
||||
Defence in depth: ``now.json`` is signed but a determined forger (or a watcher
|
||||
bug) could name any pid, and the enforcer is root. The desktop session -- the
|
||||
window manager and its bar, X, the user's systemd and bus, audio, ssh/gpg
|
||||
agents, multiplexers, terminals and shells, sudo, Claude, the password manager,
|
||||
the notification daemon, and every locker or accountant -- survives that.
|
||||
|
||||
Matched on the binary actually run (the ``exe`` link, never ``comm``, which any
|
||||
process may rename) or, for a Python interpreter, the script/module it runs.
|
||||
:mod:`_leisure_kill` asks :func:`never_kill` after :func:`is_protected`.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import PurePath
|
||||
from typing import Final
|
||||
|
||||
from steam_backlog_enforcer._leisure_procs import (
|
||||
LOCKER_NAMES,
|
||||
argv,
|
||||
exe_name,
|
||||
exe_path,
|
||||
script_of,
|
||||
)
|
||||
|
||||
_TERMINALS: Final = frozenset(
|
||||
{
|
||||
"alacritty",
|
||||
"foot",
|
||||
"footclient",
|
||||
"ghostty",
|
||||
"gnome-terminal",
|
||||
"gnome-terminal-server",
|
||||
"kitty",
|
||||
"konsole",
|
||||
"lxterminal",
|
||||
"mate-terminal",
|
||||
"qterminal",
|
||||
"rxvt",
|
||||
"sakura",
|
||||
"st",
|
||||
"terminator",
|
||||
"terminology",
|
||||
"tilix",
|
||||
"urxvt",
|
||||
"urxvtd",
|
||||
"uxterm",
|
||||
"wezterm",
|
||||
"wezterm-gui",
|
||||
"xfce4-terminal",
|
||||
"xterm",
|
||||
}
|
||||
)
|
||||
# Exact exe basenames (lower-case: ``exe_name`` lowers ``Xorg``).
|
||||
NEVER_KILL_NAMES: Final = _TERMINALS | frozenset(
|
||||
{
|
||||
"i3",
|
||||
"i3bar",
|
||||
"i3blocks",
|
||||
"xorg",
|
||||
"xwayland",
|
||||
"systemd",
|
||||
"wireplumber",
|
||||
"pulseaudio",
|
||||
"sshd",
|
||||
"ssh-agent",
|
||||
"gpg-agent",
|
||||
"tmux",
|
||||
"screen",
|
||||
"zsh",
|
||||
"bash",
|
||||
"fish",
|
||||
"sh",
|
||||
"dash",
|
||||
"sudo",
|
||||
"keepassxc",
|
||||
"dunst",
|
||||
"xfce4-notifyd",
|
||||
"claude",
|
||||
}
|
||||
)
|
||||
NEVER_KILL_PREFIXES: Final = ("dbus-", "pipewire", "systemd-")
|
||||
# Python programs by script/module stem: Python terminals, and every locker,
|
||||
# accountant and the limits bar (LOCKER_NAMES already spares their children).
|
||||
NEVER_KILL_SCRIPTS: Final = LOCKER_NAMES | frozenset(
|
||||
{"daily_limits", "guake", "terminator"}
|
||||
)
|
||||
_CLAUDE: Final = "claude"
|
||||
# Claude Code's native build: ~/.local/share/claude/versions/<version>.
|
||||
_CLAUDE_DIRS: Final = frozenset({"claude", "claude-code"})
|
||||
_JS_RUNTIMES: Final = frozenset({"node", "bun"})
|
||||
|
||||
|
||||
def _is_claude(pid: int, name: str) -> bool:
|
||||
if _CLAUDE_DIRS & set(PurePath(exe_path(pid).lower()).parts):
|
||||
return True
|
||||
if name not in _JS_RUNTIMES:
|
||||
return False
|
||||
script = argv(pid)[1:2]
|
||||
return bool(script) and bool(_CLAUDE_DIRS & set(PurePath(script[0]).parts))
|
||||
|
||||
|
||||
def never_kill(pid: int) -> str | None:
|
||||
"""Why *pid* is never signalled by a leisure kill, ``None`` if it may be.
|
||||
|
||||
Args:
|
||||
pid: Candidate process (already past :func:`is_protected`).
|
||||
|
||||
Returns:
|
||||
The protected name that matched (for the refusal log), or ``None``.
|
||||
"""
|
||||
name = exe_name(pid)
|
||||
if name in NEVER_KILL_NAMES or name.startswith(NEVER_KILL_PREFIXES):
|
||||
return name
|
||||
if _is_claude(pid, name):
|
||||
return _CLAUDE
|
||||
script = script_of(pid)
|
||||
if script is not None and script[0] in NEVER_KILL_SCRIPTS:
|
||||
return script[0]
|
||||
return None
|
||||
244
steam_backlog_enforcer/_leisure_procs.py
Normal file
244
steam_backlog_enforcer/_leisure_procs.py
Normal file
@ -0,0 +1,244 @@
|
||||
"""Who a leisure kill may touch: browsers, players, lockers, the desktop user.
|
||||
|
||||
Read straight from ``/proc`` (the daemon is root), never from ``comm`` alone:
|
||||
Firefox content processes rename it ("Isolated Web Co") and Chromium children
|
||||
run as ``/proc/self/exe``, so a browser is named by its ``exe`` basename.
|
||||
|
||||
Nothing here signals anything; :mod:`_leisure_kill` does, after
|
||||
:func:`is_protected` says no to root/system processes, the enforcer's own
|
||||
chain, and every locker and its children.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
from typing import Final
|
||||
|
||||
from leisure_watch.facts import DESKTOP_UID
|
||||
|
||||
_PROC: Final = Path("/proc")
|
||||
|
||||
# THE browser list (Phase 2): exempt from focus/media kills because the
|
||||
# extension redirects instead, and swept when the watcher cannot be trusted.
|
||||
# Matched as the exe basename, or that name plus a "-"/"_" suffix
|
||||
# (vivaldi-bin, firefox-bin, helium_crashpad_handler).
|
||||
BROWSER_FAMILIES: Final = (
|
||||
"helium",
|
||||
"chromium",
|
||||
"chrome",
|
||||
"google-chrome",
|
||||
"brave",
|
||||
"vivaldi",
|
||||
"opera",
|
||||
"msedge",
|
||||
"microsoft-edge",
|
||||
"firefox",
|
||||
"librewolf",
|
||||
"zen",
|
||||
"thorium",
|
||||
"floorp",
|
||||
"waterfox",
|
||||
"mullvad-browser",
|
||||
)
|
||||
MEDIA_PLAYERS: Final = ("mpv", "vlc", "totem", "freetube")
|
||||
_WSG: Final = "wsg_grabber"
|
||||
# An interpreter by exe basename (python, python3, python3.14), and its
|
||||
# options that take a separate value, so the script after them is found.
|
||||
_PYTHON: Final = re.compile(r"python[0-9.]*")
|
||||
_OPTS_WITH_VALUE: Final = frozenset({"-W", "-X", "--check-hash-based-pycs"})
|
||||
# An updated binary's exe link (the package manager replaced the file).
|
||||
_DELETED: Final = " (deleted)"
|
||||
# Headless `wsg-grabber scrape` never counts as leisure (Q7): never swept.
|
||||
_WSG_HEADLESS: Final = "scrape"
|
||||
# A process whose argv names one of these -- or any ancestor's does -- is a
|
||||
# locker (or the accountant itself) and is never signalled.
|
||||
LOCKER_NAMES: Final = frozenset(
|
||||
{
|
||||
"i3lock",
|
||||
"xss_lock",
|
||||
"gatelock",
|
||||
"screen_locker",
|
||||
"leetcode_guard",
|
||||
"leetcode_guard_tray",
|
||||
"book_guard",
|
||||
"diet_guard",
|
||||
"anki_guard",
|
||||
"home_guard",
|
||||
"meal_gate",
|
||||
"workout_locker",
|
||||
"steam_backlog_enforcer",
|
||||
"leisure_watch",
|
||||
}
|
||||
)
|
||||
_STAT_PPID: Final = 1
|
||||
_STAT_START: Final = 19
|
||||
_MAX_DEPTH: Final = 32
|
||||
|
||||
|
||||
def _read(pid: int, name: str) -> str | None:
|
||||
try:
|
||||
return (_PROC / str(pid) / name).read_text(encoding="utf-8", errors="replace")
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
|
||||
def exe_path(pid: int) -> str:
|
||||
"""The pid's binary, without an update's `` (deleted)``; ``""`` if unreadable."""
|
||||
try:
|
||||
return str((_PROC / str(pid) / "exe").readlink()).removesuffix(_DELETED)
|
||||
except OSError:
|
||||
return ""
|
||||
|
||||
|
||||
def exe_name(pid: int) -> str:
|
||||
"""Lower-case basename of the pid's binary (``comm`` if exe is unreadable)."""
|
||||
path = exe_path(pid)
|
||||
if path:
|
||||
return Path(path).name.lower()
|
||||
return (_read(pid, "comm") or "").strip().lower()
|
||||
|
||||
|
||||
def argv(pid: int) -> tuple[str, ...]:
|
||||
"""The pid's command line, ``()`` if gone."""
|
||||
raw = _read(pid, "cmdline") or ""
|
||||
return tuple(arg for arg in raw.split("\0") if arg)
|
||||
|
||||
|
||||
def real_uid(pid: int) -> int | None:
|
||||
"""The real uid from ``status``, ``None`` if unreadable."""
|
||||
for line in (_read(pid, "status") or "").splitlines():
|
||||
if line.startswith("Uid:"):
|
||||
fields = line.split()
|
||||
return int(fields[1]) if fields[1:] and fields[1].isdigit() else None
|
||||
return None
|
||||
|
||||
|
||||
def _stat_field(pid: int, index: int) -> int | None:
|
||||
# comm may hold spaces and parentheses: split after the last ") ".
|
||||
rest = (_read(pid, "stat") or "").rpartition(") ")[2].split()
|
||||
if len(rest) <= index or not rest[index].isdigit():
|
||||
return None
|
||||
return int(rest[index])
|
||||
|
||||
|
||||
def parent(pid: int) -> int | None:
|
||||
"""The parent pid, ``None`` if unreadable."""
|
||||
return _stat_field(pid, _STAT_PPID)
|
||||
|
||||
|
||||
def start_time(pid: int) -> int | None:
|
||||
"""Start time in clock ticks: with the pid, the process's identity."""
|
||||
return _stat_field(pid, _STAT_START)
|
||||
|
||||
|
||||
def _family(name: str, families: tuple[str, ...]) -> bool:
|
||||
return any(
|
||||
name == fam or name.startswith((f"{fam}-", f"{fam}_")) for fam in families
|
||||
)
|
||||
|
||||
|
||||
def is_browser(pid: int) -> bool:
|
||||
"""Whether *pid* runs a browser binary (any process of it)."""
|
||||
return _family(exe_name(pid), BROWSER_FAMILIES)
|
||||
|
||||
|
||||
def _stem(arg: str) -> str:
|
||||
# "/x/leetcode_guard_tray.py" -> leetcode_guard_tray; "screen_locker._web"
|
||||
# -> screen_locker; "book-guard" -> book_guard.
|
||||
stem = Path(arg).name.lower().removesuffix(".py").partition(".")[0]
|
||||
return stem.replace("-", "_")
|
||||
|
||||
|
||||
def _arg_names(pid: int) -> set[str]:
|
||||
return {_stem(arg) for arg in argv(pid)}
|
||||
|
||||
|
||||
def script_of(pid: int) -> tuple[str, tuple[str, ...]] | None:
|
||||
"""What a Python interpreter runs: (script or ``-m`` module stem, its args).
|
||||
|
||||
``None`` for any other binary, ``-c`` code or a bare interpreter.
|
||||
"""
|
||||
if not _PYTHON.fullmatch(exe_name(pid)):
|
||||
return None
|
||||
args = argv(pid)[1:]
|
||||
i = 0
|
||||
while i < len(args) and args[i].startswith("-"):
|
||||
if args[i] == "-c":
|
||||
return None
|
||||
if args[i] == "-m":
|
||||
return (_stem(args[i + 1]), args[i + 2 :]) if args[i + 1 :] else None
|
||||
i += 2 if args[i] in _OPTS_WITH_VALUE else 1
|
||||
return (_stem(args[i]), args[i + 1 :]) if i < len(args) else None
|
||||
|
||||
|
||||
def _ancestry(pid: int) -> list[int]:
|
||||
chain: list[int] = []
|
||||
current: int | None = pid
|
||||
while current is not None and current > 0 and current not in chain:
|
||||
if len(chain) >= _MAX_DEPTH:
|
||||
break
|
||||
chain.append(current)
|
||||
current = parent(current)
|
||||
return chain
|
||||
|
||||
|
||||
def own_chain() -> set[int]:
|
||||
"""This daemon and its ancestors: never signalled."""
|
||||
return set(_ancestry(os.getpid()))
|
||||
|
||||
|
||||
def is_protected(pid: int, chain: set[int]) -> bool:
|
||||
"""Whether *pid* must never be signalled by a leisure kill.
|
||||
|
||||
Args:
|
||||
pid: Candidate process.
|
||||
chain: :func:`own_chain`, computed once per tick.
|
||||
|
||||
Returns:
|
||||
True for anything not the desktop user's (root, system, other users,
|
||||
unreadable or gone), the enforcer's own chain, and lockers with
|
||||
everything under them.
|
||||
"""
|
||||
if pid in chain or real_uid(pid) != DESKTOP_UID:
|
||||
return True
|
||||
return any(_arg_names(p) & LOCKER_NAMES for p in _ancestry(pid) if p > 1)
|
||||
|
||||
|
||||
def _wsg_reviewer(pid: int) -> bool:
|
||||
# Only the program actually run: a path naming the repo (git -C, pytest,
|
||||
# an editor) is not the reviewer.
|
||||
if _stem(exe_name(pid)) == _WSG:
|
||||
rest = argv(pid)[1:]
|
||||
else:
|
||||
script = script_of(pid)
|
||||
if script is None or script[0] != _WSG:
|
||||
return False
|
||||
rest = script[1]
|
||||
return rest[:1] != (_WSG_HEADLESS,)
|
||||
|
||||
|
||||
def sweep_targets() -> dict[int, str]:
|
||||
"""Every browser, media player and wsg-grabber reviewer on the machine.
|
||||
|
||||
The kill set while the watcher cannot be trusted (stale, missing or badly
|
||||
signed ``now.json``).
|
||||
|
||||
Returns:
|
||||
Pid to a ``sweep:...`` key naming why it was picked.
|
||||
"""
|
||||
try:
|
||||
pids = [int(e.name) for e in _PROC.iterdir() if e.name.isdigit()]
|
||||
except OSError:
|
||||
return {}
|
||||
found: dict[int, str] = {}
|
||||
for pid in sorted(pids):
|
||||
name = exe_name(pid)
|
||||
if _family(name, BROWSER_FAMILIES):
|
||||
found[pid] = f"sweep:browser:{name}"
|
||||
elif _family(name, MEDIA_PLAYERS):
|
||||
found[pid] = f"sweep:media:{name}"
|
||||
elif _wsg_reviewer(pid):
|
||||
found[pid] = "sweep:wsg-grabber"
|
||||
return found
|
||||
@ -23,9 +23,10 @@ suspends, missed ticks, daemon restarts and NTP steps all behave.
|
||||
``python3``. The scan (``leisure_watch.procscan``, shared with the leisure
|
||||
watcher) therefore reads argv as well as ``comm``.
|
||||
|
||||
**Shadow leisure time rides the same tick** (:mod:`_shadow`, contract C4): it
|
||||
is measured from the same stamp and clamp, before ``accumulate``, and never
|
||||
touches an enforced field. Under a total block it is not billed.
|
||||
**Shadow leisure time rides the same tick** (:mod:`_shadow`, contract C4),
|
||||
from the same stamp and clamp, before ``accumulate``; under a total block it
|
||||
is not billed. From the go-live day (:mod:`_leisure_mode`, Phase 2) its rule
|
||||
bills the enforced count too, and at 0 :mod:`_leisure_kill` ends leisure apps.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@ -36,15 +37,13 @@ import logging
|
||||
import time
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from leisure_watch.procscan import attributed_key, qualifying_pids
|
||||
from leisure_watch.procscan import qualifying_pids
|
||||
|
||||
from steam_backlog_enforcer import config as config_mod
|
||||
from steam_backlog_enforcer._gaming_days import gaming_day_key
|
||||
from steam_backlog_enforcer._leisure_mode import Tick, bill_tick
|
||||
from steam_backlog_enforcer._playtime_block import mounted_targets
|
||||
from steam_backlog_enforcer._playtime_budget import (
|
||||
accumulate,
|
||||
roll_over,
|
||||
)
|
||||
from steam_backlog_enforcer._playtime_budget import roll_over
|
||||
from steam_backlog_enforcer._playtime_cutoff import (
|
||||
_begin_cutoff,
|
||||
_sustain_block,
|
||||
@ -125,14 +124,11 @@ def playtime_tick(
|
||||
state = shadow_accumulate(
|
||||
state, stamp=now.timestamp(), interval=interval, verdict=shadow
|
||||
)
|
||||
state = accumulate(
|
||||
state,
|
||||
now=now,
|
||||
qualifying=pids,
|
||||
interval=interval,
|
||||
credited_key=attributed_key(owners),
|
||||
)
|
||||
tick = Tick(now=now, interval=interval, owners=owners, verdict=shadow)
|
||||
state, rules = bill_tick(state, rules, tick)
|
||||
state = _policy(state, rules, now=now)
|
||||
if rules.leisure:
|
||||
session.leisure.enforce(state, rules, verdict=shadow, stamp=now.timestamp())
|
||||
session.journal.observe(pids, state, rules=rules, now_monotonic=time.monotonic())
|
||||
session.shadow.observe(shadow, state)
|
||||
save_state(state, demo=demo)
|
||||
|
||||
@ -51,6 +51,39 @@ def accumulate(
|
||||
charged to a guess, which is why ``per_game`` only ever sums to at
|
||||
most ``seconds``.
|
||||
|
||||
Returns:
|
||||
The updated state.
|
||||
"""
|
||||
return bill(
|
||||
state,
|
||||
now=now,
|
||||
billed=bool(qualifying),
|
||||
interval=interval,
|
||||
credited_key=credited_key,
|
||||
)
|
||||
|
||||
|
||||
def bill(
|
||||
state: PlaytimeState,
|
||||
*,
|
||||
now: datetime,
|
||||
billed: bool,
|
||||
interval: float,
|
||||
credited_key: str = "",
|
||||
) -> PlaytimeState:
|
||||
""":func:`accumulate` with the "anything qualifies?" answer given directly.
|
||||
|
||||
The leisure budget (Phase 2) decides billing from the shadow verdict, not
|
||||
from game PIDs; everything else -- the clamp, the first tick, a backward
|
||||
step, the attribution -- is the same arithmetic.
|
||||
|
||||
Args:
|
||||
state: Current accounting state.
|
||||
now: Timezone-aware local timestamp for this tick.
|
||||
billed: Whether this tick counts against the budget.
|
||||
interval: Nominal seconds between ticks.
|
||||
credited_key: Attribution key to charge, or ``""``.
|
||||
|
||||
Returns:
|
||||
The updated state.
|
||||
"""
|
||||
@ -59,7 +92,7 @@ def accumulate(
|
||||
return replace(state, last_tick_at=stamp)
|
||||
|
||||
delta = stamp - state.last_tick_at
|
||||
if delta <= 0.0 or not qualifying:
|
||||
if delta <= 0.0 or not billed:
|
||||
return replace(state, last_tick_at=stamp)
|
||||
|
||||
credited = min(delta, interval * _DELTA_CLAMP_FACTOR)
|
||||
|
||||
@ -53,6 +53,19 @@ def reconcile_for(rules: PlaytimeRules, *, should_block: bool) -> None:
|
||||
reconcile(should_block=should_block)
|
||||
|
||||
|
||||
_CUTOFF_BODY = {
|
||||
False: "Daily budget used up. Steam and games are shutting down. "
|
||||
"Unblocks at 06:00.",
|
||||
True: "Daily leisure budget used up. Steam, games and leisure apps are "
|
||||
"shutting down. Unblocks at 06:00.",
|
||||
}
|
||||
|
||||
|
||||
def _noun(rules: PlaytimeRules) -> str:
|
||||
"""What the budget is called: "Leisure" from the go-live day (Phase 2)."""
|
||||
return "Leisure" if rules.leisure else "Gaming"
|
||||
|
||||
|
||||
def _warn(state: PlaytimeState, rules: PlaytimeRules) -> PlaytimeState:
|
||||
"""Fire the due warning, if any, and record that it fired.
|
||||
|
||||
@ -67,14 +80,16 @@ def _warn(state: PlaytimeState, rules: PlaytimeRules) -> PlaytimeState:
|
||||
if threshold is None:
|
||||
return state
|
||||
|
||||
left = f"{_humanise(threshold)} of today's gaming budget left."
|
||||
noun = _noun(rules)
|
||||
left = f"{_humanise(threshold)} of today's {noun.lower()} budget left."
|
||||
logger.info(
|
||||
"Gaming warning: %s (billed %.0fs of %.0fs)",
|
||||
"%s warning: %s (billed %.0fs of %.0fs)",
|
||||
noun,
|
||||
left,
|
||||
state.seconds,
|
||||
rules.budget_seconds,
|
||||
)
|
||||
notify_desktop_user("Gaming time running out", left)
|
||||
notify_desktop_user(f"{noun} time running out", left)
|
||||
return replace(state, warned_seconds=[*state.warned_seconds, threshold])
|
||||
|
||||
|
||||
@ -98,11 +113,10 @@ def _begin_cutoff(
|
||||
Returns:
|
||||
The updated state.
|
||||
"""
|
||||
logger.warning("Daily gaming budget exhausted; shutting Steam down.")
|
||||
notify_desktop_user(
|
||||
"Gaming time is up",
|
||||
"Daily budget used up. Steam and games are shutting down. Unblocks at 06:00.",
|
||||
logger.warning(
|
||||
"Daily %s budget exhausted; shutting Steam down.", _noun(rules).lower()
|
||||
)
|
||||
notify_desktop_user(f"{_noun(rules)} time is up", _CUTOFF_BODY[rules.leisure])
|
||||
request_steam_shutdown()
|
||||
kill_gaming_processes(_kill_set(rules), force=False)
|
||||
if rules.demo:
|
||||
|
||||
@ -12,9 +12,10 @@ would otherwise have caught.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from dataclasses import dataclass, field
|
||||
from typing import TYPE_CHECKING, Protocol
|
||||
|
||||
from steam_backlog_enforcer._leisure_kill import LeisureKiller
|
||||
from steam_backlog_enforcer._playtime_history import HistoryWriter
|
||||
from steam_backlog_enforcer._playtime_log import (
|
||||
BudgetLog,
|
||||
@ -56,6 +57,20 @@ class ShadowRecorder(Protocol):
|
||||
"""Record the shadow verdict if it changed."""
|
||||
|
||||
|
||||
class LeisureEnforcer(Protocol):
|
||||
"""What the budget tick needs from the Phase 2 leisure killer."""
|
||||
|
||||
def enforce(
|
||||
self,
|
||||
state: PlaytimeState,
|
||||
rules: PlaytimeRules,
|
||||
*,
|
||||
verdict: ShadowVerdict,
|
||||
stamp: float,
|
||||
) -> None:
|
||||
"""Signal leisure apps if the leisure budget is spent."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PlaytimeSession:
|
||||
"""Per-daemon logging state."""
|
||||
@ -63,6 +78,9 @@ class PlaytimeSession:
|
||||
journal: TickRecorder
|
||||
history: HistoryRecorder
|
||||
shadow: ShadowRecorder
|
||||
# Defaulted (records nowhere) so a session built without it still kills;
|
||||
# new_session wires it to the budget log.
|
||||
leisure: LeisureEnforcer = field(default_factory=LeisureKiller)
|
||||
|
||||
|
||||
def new_session(*, demo: bool = False) -> PlaytimeSession:
|
||||
@ -81,4 +99,5 @@ def new_session(*, demo: bool = False) -> PlaytimeSession:
|
||||
journal=TickJournal(log),
|
||||
history=HistoryWriter(),
|
||||
shadow=ShadowJournal(log),
|
||||
leisure=LeisureKiller(log),
|
||||
)
|
||||
|
||||
@ -97,6 +97,9 @@ class PlaytimeRules:
|
||||
budget_reason: str = ""
|
||||
# The shadow leisure budget (C4), held like budget_seconds; never enforced.
|
||||
shadow_budget_seconds: float = 0.0
|
||||
# Phase 2: the billed gaming day is on the leisure budget (set per tick by
|
||||
# _leisure_mode.leisure_billed, never by rules_for). Only wording and kills.
|
||||
leisure: bool = False
|
||||
|
||||
|
||||
def rules_for(config: Config, *, demo: bool) -> PlaytimeRules:
|
||||
|
||||
@ -23,7 +23,7 @@ Overlapping sources bill the wall clock once and split it evenly, so
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, replace
|
||||
from dataclasses import dataclass, field, replace
|
||||
import logging
|
||||
from pathlib import Path
|
||||
import time
|
||||
@ -67,6 +67,11 @@ class ShadowVerdict:
|
||||
"""``gatelock:<app>`` / ``i3lock`` while paused, else ``None``."""
|
||||
keys: tuple[str, ...]
|
||||
"""Sources billed this tick; empty = free (or paused)."""
|
||||
fact: Now | None = field(default=None, compare=False, repr=False)
|
||||
"""The trusted watcher fact (Phase 2 kills); ``None`` if paused or untrusted.
|
||||
|
||||
Out of equality: ts/seq change every 5 s and the journal dedups on it.
|
||||
"""
|
||||
|
||||
@property
|
||||
def state(self) -> str:
|
||||
@ -121,7 +126,7 @@ def observe_shadow(owners: dict[int, str], *, stamp: float) -> ShadowVerdict:
|
||||
"Shadow inputs unreadable (%r); failing closed.", exc, exc_info=True
|
||||
)
|
||||
fact = None
|
||||
return ShadowVerdict(paused_by=None, keys=shadow_keys(owners, fact))
|
||||
return ShadowVerdict(paused_by=None, keys=shadow_keys(owners, fact), fact=fact)
|
||||
|
||||
|
||||
def _should_warn(exc: BaseException) -> bool:
|
||||
|
||||
@ -5,13 +5,13 @@ on: ``READING.penalty_from``, delayed by maturity (0.6.0) to the day after
|
||||
``confirmed_on`` when no credit is on record. A budget test that reads the
|
||||
real clock would change its answer on that day, so every such test pins the
|
||||
date on one side of the cut.
|
||||
The module asks ``datetime.now().astimezone().date()``, so that chain is what
|
||||
the pin answers.
|
||||
The module asks ``datetime.now().astimezone()``, so that chain is what the
|
||||
pin answers (at noon, so the gaming day is the same date).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import timedelta
|
||||
from datetime import datetime, time, timedelta
|
||||
from typing import TYPE_CHECKING
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
@ -40,5 +40,7 @@ def pin_today(day: date) -> AbstractContextManager[object]:
|
||||
A patch context manager replacing the module's ``datetime`` binding.
|
||||
"""
|
||||
clock = MagicMock()
|
||||
clock.now.return_value.astimezone.return_value.date.return_value = day
|
||||
# A real aware noon: the module also takes the 06:00 gaming day from it.
|
||||
noon = datetime.combine(day, time(12)).astimezone()
|
||||
clock.now.return_value.astimezone.return_value = noon
|
||||
return patch("steam_backlog_enforcer._budget_resolve.datetime", clock)
|
||||
|
||||
74
steam_backlog_enforcer/tests/_isolate_leisure.py
Normal file
74
steam_backlog_enforcer/tests/_isolate_leisure.py
Normal file
@ -0,0 +1,74 @@
|
||||
"""Autouse isolation of the Phase-2 leisure switch and the leisure kill scan.
|
||||
|
||||
The switch file ``/etc/leisure-watch/leisure_from`` is read per tick by
|
||||
``earned_time`` itself (``is_leisure``, looked up at call time from
|
||||
``earned_time._leisure``), by the enforcer's billing gate and by its budget
|
||||
pricing, which pass their own constants explicitly. All point at an absent
|
||||
file under ``tmp_path``, so no
|
||||
test ever reads the real one and every test starts dormant. A test turns
|
||||
Phase 2 on by writing a date to :func:`switch_file`.
|
||||
|
||||
The leisure kill scan reads ``/proc`` through its own constant; it gets an
|
||||
empty directory (:func:`leisure_proc`), so no test can see -- or signal -- a
|
||||
live browser or player.
|
||||
|
||||
Module-level code runs at collection, before any fixture: it wraps itself in
|
||||
:func:`collection_isolated` instead.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from contextlib import ExitStack, contextmanager
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Iterator
|
||||
|
||||
_SWITCH_NAME = "leisure_from"
|
||||
_PROC_NAME = "leisure_proc"
|
||||
# Every switch reader, by the module attribute it looks up at call time.
|
||||
_SWITCH_READERS = (
|
||||
"earned_time._leisure.LEISURE_FROM_PATH",
|
||||
"steam_backlog_enforcer._leisure_mode.LEISURE_FROM_PATH",
|
||||
"steam_backlog_enforcer._budget_resolve.LEISURE_FROM_PATH",
|
||||
)
|
||||
# Can never exist (/dev/null is not a directory): always the parked date.
|
||||
_NO_SWITCH = Path(os.devnull) / _SWITCH_NAME
|
||||
|
||||
|
||||
@contextmanager
|
||||
def collection_isolated() -> Iterator[None]:
|
||||
"""Point every switch reader at a file that cannot exist (no ``tmp_path``)."""
|
||||
with ExitStack() as stack:
|
||||
for target in _SWITCH_READERS:
|
||||
stack.enter_context(patch(target, _NO_SWITCH))
|
||||
yield
|
||||
|
||||
|
||||
def switch_file(tmp_path: Path) -> Path:
|
||||
"""The redirected switch file for this test (absent until written)."""
|
||||
return tmp_path / "etc-leisure-watch" / _SWITCH_NAME
|
||||
|
||||
|
||||
def leisure_proc(tmp_path: Path) -> Path:
|
||||
"""The redirected ``/proc`` the leisure kill scan reads for this test."""
|
||||
return tmp_path / _PROC_NAME
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _isolate_leisure(tmp_path: Path) -> Iterator[None]:
|
||||
"""Point both switch readers and the kill scan at ``tmp_path``."""
|
||||
switch = switch_file(tmp_path)
|
||||
switch.parent.mkdir(exist_ok=True)
|
||||
proc = leisure_proc(tmp_path)
|
||||
proc.mkdir(exist_ok=True)
|
||||
with ExitStack() as stack:
|
||||
for target in _SWITCH_READERS:
|
||||
stack.enter_context(patch(target, switch))
|
||||
stack.enter_context(patch("steam_backlog_enforcer._leisure_procs._PROC", proc))
|
||||
yield
|
||||
48
steam_backlog_enforcer/tests/_leisure_fake_proc.py
Normal file
48
steam_backlog_enforcer/tests/_leisure_fake_proc.py
Normal file
@ -0,0 +1,48 @@
|
||||
"""A tiny fake ``/proc`` for the leisure kill tests: one directory per pid."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
# Fields after ``comm``: state, ppid, then 17 more, then starttime (index 19).
|
||||
_FILLER_BEFORE_START = 17
|
||||
_FILLER_AFTER_START = 5
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class FakeProc:
|
||||
"""What one fake ``/proc/<pid>`` holds."""
|
||||
|
||||
pid: int
|
||||
exe: str = "/usr/bin/mpv"
|
||||
argv: tuple[str, ...] = ("mpv",)
|
||||
comm: str = "mpv"
|
||||
uid: int = 1000
|
||||
ppid: int = 1
|
||||
start: int = 100
|
||||
|
||||
|
||||
def add_proc(root: Path, spec: FakeProc) -> None:
|
||||
"""Create ``root/<pid>`` with exe, cmdline, comm, status and stat.
|
||||
|
||||
Args:
|
||||
root: The fake ``/proc``.
|
||||
spec: The process to plant (a dangling ``exe`` target is fine).
|
||||
"""
|
||||
proc = root / str(spec.pid)
|
||||
proc.mkdir(parents=True)
|
||||
(proc / "exe").symlink_to(spec.exe)
|
||||
(proc / "cmdline").write_bytes(b"".join(a.encode() + b"\0" for a in spec.argv))
|
||||
(proc / "comm").write_text(spec.comm + "\n", encoding="utf-8")
|
||||
uid = spec.uid
|
||||
(proc / "status").write_text(
|
||||
f"Name:\t{spec.comm}\nUid:\t{uid}\t{uid}\t{uid}\t{uid}\n", encoding="utf-8"
|
||||
)
|
||||
rest = ["S", str(spec.ppid), *["0"] * _FILLER_BEFORE_START, str(spec.start)]
|
||||
rest += ["0"] * _FILLER_AFTER_START
|
||||
line = f"{spec.pid} ({spec.comm}) {' '.join(rest)}\n"
|
||||
(proc / "stat").write_text(line, encoding="utf-8")
|
||||
@ -26,6 +26,7 @@ from steam_backlog_enforcer.tests._isolate_control_plane import (
|
||||
_isolate_cover_art,
|
||||
)
|
||||
from steam_backlog_enforcer.tests._isolate_incidents import _isolate_incidents
|
||||
from steam_backlog_enforcer.tests._isolate_leisure import _isolate_leisure
|
||||
from steam_backlog_enforcer.tests._isolate_playtime import _isolate_playtime
|
||||
from steam_backlog_enforcer.tests._isolate_reading import _isolate_reading
|
||||
from steam_backlog_enforcer.tests._isolate_shadow import _isolate_shadow
|
||||
@ -46,6 +47,7 @@ __all__ = [
|
||||
"_isolate_control_plane",
|
||||
"_isolate_cover_art",
|
||||
"_isolate_incidents",
|
||||
"_isolate_leisure",
|
||||
"_isolate_playtime",
|
||||
"_isolate_reading",
|
||||
"_isolate_shadow",
|
||||
|
||||
78
steam_backlog_enforcer/tests/test_budget_resolve_leisure.py
Normal file
78
steam_backlog_enforcer/tests/test_budget_resolve_leisure.py
Normal file
@ -0,0 +1,78 @@
|
||||
"""The enforced budget is priced by the 06:00 gaming day, like billing.
|
||||
|
||||
earned_time 0.16.0: ``resolve(leisure=False)`` forces pre-leisure pricing, so
|
||||
the enforcer asks ``leisure_active`` for the gaming day itself; 00:00-05:59 on
|
||||
the go-live date still belongs to the day before.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, time, timedelta
|
||||
from typing import TYPE_CHECKING
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import earned_time
|
||||
import pytest
|
||||
|
||||
from steam_backlog_enforcer._budget_resolve import resolve_budget
|
||||
from steam_backlog_enforcer.config import Config
|
||||
from steam_backlog_enforcer.tests._budget_dates import AFTER_CUT
|
||||
from steam_backlog_enforcer.tests._isolate_leisure import switch_file
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
_HOUR = 3600.0
|
||||
|
||||
|
||||
def _at(hour: int) -> MagicMock:
|
||||
"""A ``datetime`` stand-in whose ``now().astimezone()`` is AFTER_CUT at *hour*."""
|
||||
clock = MagicMock()
|
||||
clock.now.return_value.astimezone.return_value = datetime.combine(
|
||||
AFTER_CUT, time(hour)
|
||||
).astimezone()
|
||||
return clock
|
||||
|
||||
|
||||
def _resolve(hour: int) -> tuple[float, list[object]]:
|
||||
"""Enforced base seconds at *hour*, and every ``leisure=`` resolve was given."""
|
||||
with (
|
||||
patch("steam_backlog_enforcer._budget_resolve.datetime", _at(hour)),
|
||||
patch.object(earned_time, "resolve", wraps=earned_time.resolve) as spy,
|
||||
):
|
||||
base = resolve_budget(Config()).base_seconds
|
||||
return base, [c.kwargs["leisure"] for c in spy.call_args_list]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def dormant(tmp_path: Path) -> float:
|
||||
"""The dormant base at noon, then the switch dated the go-live day."""
|
||||
base = _resolve(12)[0]
|
||||
switch_file(tmp_path).write_text(AFTER_CUT.isoformat() + "\n", encoding="ascii")
|
||||
return base
|
||||
|
||||
|
||||
def test_dormant_prices_pre_leisure_with_a_leisure_shadow() -> None:
|
||||
assert _resolve(12)[1] == [False, True]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("hour", [6, 12, 23])
|
||||
def test_the_go_live_gaming_day_is_priced_as_leisure(dormant: float, hour: int) -> None:
|
||||
base, leisure = _resolve(hour)
|
||||
assert leisure == [True, True]
|
||||
assert base - dormant == 2 * _HOUR
|
||||
|
||||
|
||||
@pytest.mark.parametrize("hour", [0, 3, 5])
|
||||
def test_before_06_on_the_go_live_date_stays_pre_leisure(
|
||||
dormant: float, hour: int
|
||||
) -> None:
|
||||
base, leisure = _resolve(hour)
|
||||
assert leisure == [False, True]
|
||||
assert base == dormant
|
||||
|
||||
|
||||
def test_a_switch_dated_tomorrow_is_dormant_today(tmp_path: Path) -> None:
|
||||
tomorrow = (AFTER_CUT + timedelta(days=1)).isoformat()
|
||||
switch_file(tmp_path).write_text(tomorrow + "\n", encoding="ascii")
|
||||
assert _resolve(12)[1] == [False, True]
|
||||
@ -22,6 +22,7 @@ from steam_backlog_enforcer._budget_view import (
|
||||
from steam_backlog_enforcer._playtime_history import HistoryDay
|
||||
from steam_backlog_enforcer._playtime_state import PlaytimeState, rules_for
|
||||
from steam_backlog_enforcer.config import Config
|
||||
from steam_backlog_enforcer.tests._isolate_leisure import collection_isolated
|
||||
from steam_backlog_enforcer.tests._no_workout_http import earned_budget, fixed_budget
|
||||
|
||||
# Built at import time, so the autouse _no_workout_http fixture is not in
|
||||
@ -30,8 +31,10 @@ from steam_backlog_enforcer.tests._no_workout_http import earned_budget, fixed_b
|
||||
# have earned. Stub it explicitly so the constant is the earned budget always.
|
||||
# The held budget is pinned for the same reason: conftest's redirects are not
|
||||
# active at import either, so rules_for would read the LIVE playtime_state.json
|
||||
# and hold RULES at whatever high-water mark it records today.
|
||||
# and hold RULES at whatever high-water mark it records today. Nor would the
|
||||
# leisure switch be: the host's /etc/leisure-watch/leisure_from would price it.
|
||||
with (
|
||||
collection_isolated(),
|
||||
patch("steam_backlog_enforcer._playtime_state.held_today", return_value=0.0),
|
||||
patch(
|
||||
"steam_backlog_enforcer._playtime_state.resolve_budget",
|
||||
|
||||
32
steam_backlog_enforcer/tests/test_budget_view_collection.py
Normal file
32
steam_backlog_enforcer/tests/test_budget_view_collection.py
Normal file
@ -0,0 +1,32 @@
|
||||
"""Collecting test_budget_view never reads the host's leisure switch file."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
from typing import TYPE_CHECKING
|
||||
from unittest.mock import patch
|
||||
|
||||
from steam_backlog_enforcer._playtime_state import rules_for
|
||||
from steam_backlog_enforcer.config import Config
|
||||
from steam_backlog_enforcer.tests import test_budget_view
|
||||
from steam_backlog_enforcer.tests._no_workout_http import earned_budget
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def test_a_live_host_switch_does_not_leak_into_rules(tmp_path: Path) -> None:
|
||||
with (
|
||||
patch("steam_backlog_enforcer._playtime_state.held_today", return_value=0.0),
|
||||
patch(
|
||||
"steam_backlog_enforcer._playtime_state.resolve_budget",
|
||||
side_effect=earned_budget,
|
||||
),
|
||||
):
|
||||
dormant = rules_for(Config(), demo=False)
|
||||
# The host went live long ago: what the import-time read would see.
|
||||
host = tmp_path / "host_leisure_from"
|
||||
host.write_text("2000-01-01\n", encoding="utf-8")
|
||||
with patch("earned_time._leisure.LEISURE_FROM_PATH", host):
|
||||
reloaded = importlib.reload(test_budget_view)
|
||||
assert dormant == reloaded.RULES
|
||||
247
steam_backlog_enforcer/tests/test_leisure_kill.py
Normal file
247
steam_backlog_enforcer/tests/test_leisure_kill.py
Normal file
@ -0,0 +1,247 @@
|
||||
"""Phase 2 at 0: which leisure pids die, how, and what the audit log says."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import replace
|
||||
import os
|
||||
import signal
|
||||
from typing import TYPE_CHECKING
|
||||
from unittest.mock import patch
|
||||
|
||||
from leisure_watch.facts import Focus, Now, Reason
|
||||
import pytest
|
||||
|
||||
from steam_backlog_enforcer import _leisure_kill
|
||||
from steam_backlog_enforcer._leisure_kill import (
|
||||
EVENT_LEISURE_KILL,
|
||||
LeisureKiller,
|
||||
fact_targets,
|
||||
)
|
||||
from steam_backlog_enforcer._playtime_state import PlaytimeRules, PlaytimeState
|
||||
from steam_backlog_enforcer._shadow import ShadowVerdict
|
||||
from steam_backlog_enforcer.tests._isolate_leisure import leisure_proc
|
||||
from steam_backlog_enforcer.tests._leisure_fake_proc import FakeProc, add_proc
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Iterator
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
_HELIUM = "/opt/helium-browser-bin/helium"
|
||||
_RULES = PlaytimeRules(
|
||||
budget_seconds=100.0,
|
||||
warn_at=(),
|
||||
sigkill_after=30.0,
|
||||
count_launchers=False,
|
||||
enforcement=True,
|
||||
demo=False,
|
||||
leisure=True,
|
||||
)
|
||||
_SPENT = PlaytimeState(day_key="2026-11-02", seconds=100.0)
|
||||
|
||||
|
||||
class StubLog:
|
||||
def __init__(self) -> None:
|
||||
self.records: list[tuple[str, dict[str, object]]] = []
|
||||
|
||||
def record(self, event: str, **fields: object) -> None:
|
||||
self.records.append((event, fields))
|
||||
|
||||
|
||||
def _now(*reasons: Reason) -> Now:
|
||||
return Now(
|
||||
ts=0.0,
|
||||
seq=1,
|
||||
state="leisure",
|
||||
paused_by=None,
|
||||
reasons=reasons,
|
||||
focus=Focus("Helium", "", None, idle=False),
|
||||
)
|
||||
|
||||
|
||||
def _verdict(fact: Now | None, paused: str | None = None) -> ShadowVerdict:
|
||||
return ShadowVerdict(paused_by=paused, keys=("k",), fact=fact)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def proc(tmp_path: Path) -> Path:
|
||||
root = leisure_proc(tmp_path)
|
||||
add_proc(root, FakeProc(10, exe="/usr/bin/mpv"))
|
||||
add_proc(root, FakeProc(20, exe=_HELIUM, comm="helium"))
|
||||
add_proc(root, FakeProc(30, exe="/usr/bin/chromium", comm="chromium"))
|
||||
add_proc(root, FakeProc(40, exe="/usr/bin/vesktop", uid=0))
|
||||
return root
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def kill() -> Iterator[MagicMock]:
|
||||
with patch.object(os, "kill") as mock:
|
||||
yield mock
|
||||
|
||||
|
||||
class TestFactTargets:
|
||||
def test_media_and_focus_apps_die_browsers_and_games_do_not(
|
||||
self, proc: Path
|
||||
) -> None:
|
||||
del proc
|
||||
fact = _now(
|
||||
Reason("media", "app:mpv", 10, "mpv"),
|
||||
Reason("focus", "domain:youtube.com", 20, "YouTube"),
|
||||
Reason("media", "domain:youtube.com", None, "url"),
|
||||
Reason("game", "steam:440", 50, "tf2"),
|
||||
Reason("mystery", "x", 10, "?"),
|
||||
)
|
||||
assert fact_targets(fact) == {10: "app:mpv"}
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("pid", "key"),
|
||||
[
|
||||
(20, "failclosed:helium"),
|
||||
(20, "failclosed:helium:unreported"),
|
||||
(20, "failclosed:helium:audio"),
|
||||
(30, "browser:chromium"),
|
||||
],
|
||||
)
|
||||
def test_a_non_reporting_browser_dies(self, proc: Path, pid: int, key: str) -> None:
|
||||
del proc
|
||||
fact = _now(Reason("failclosed", key, pid, "x"))
|
||||
assert fact_targets(fact) == {pid: key}
|
||||
|
||||
def test_failclosed_without_a_pid_names_nothing(self) -> None:
|
||||
fact = _now(Reason("failclosed", "failclosed:display", None, "X"))
|
||||
assert fact_targets(fact) == {}
|
||||
|
||||
|
||||
class TestEnforce:
|
||||
def test_mpv_is_terminated_then_killed_after_30_s(
|
||||
self, proc: Path, kill: MagicMock
|
||||
) -> None:
|
||||
del proc
|
||||
log = StubLog()
|
||||
killer = LeisureKiller(log)
|
||||
verdict = _verdict(
|
||||
_now(
|
||||
Reason("media", "app:mpv", 10, "mpv"),
|
||||
Reason("focus", "domain:x.com", 20, "x"),
|
||||
)
|
||||
)
|
||||
for stamp in (1000.0, 1003.0, 1029.0, 1030.0, 1033.0):
|
||||
killer.enforce(_SPENT, _RULES, verdict=verdict, stamp=stamp)
|
||||
assert [c.args for c in kill.call_args_list] == [
|
||||
(10, signal.SIGTERM),
|
||||
(10, signal.SIGKILL),
|
||||
(10, signal.SIGKILL),
|
||||
]
|
||||
assert [(e, f["pid"], f["signal"]) for e, f in log.records] == [
|
||||
(EVENT_LEISURE_KILL, 10, "SIGTERM"),
|
||||
(EVENT_LEISURE_KILL, 10, "SIGKILL"),
|
||||
]
|
||||
first = log.records[0][1]
|
||||
assert first["key"] == "app:mpv"
|
||||
assert first["name"] == "mpv"
|
||||
assert first["why"] == "now.json"
|
||||
assert first["day_key"] == "2026-11-02"
|
||||
|
||||
def test_untrusted_watcher_sweeps_but_spares_root(
|
||||
self, proc: Path, kill: MagicMock
|
||||
) -> None:
|
||||
add_proc(proc, FakeProc(41, exe="/usr/bin/mpv", uid=0))
|
||||
killer = LeisureKiller(StubLog())
|
||||
for stamp in range(0, 31, 3): # untrusted for the whole 30 s window
|
||||
killer.enforce(_SPENT, _RULES, verdict=_verdict(None), stamp=stamp)
|
||||
assert sorted(c.args[0] for c in kill.call_args_list) == [10, 20, 30]
|
||||
|
||||
def test_paused_is_not_stale(self, proc: Path, kill: MagicMock) -> None:
|
||||
del proc
|
||||
LeisureKiller(StubLog()).enforce(
|
||||
_SPENT, _RULES, verdict=_verdict(None, paused="i3lock"), stamp=1.0
|
||||
)
|
||||
kill.assert_not_called()
|
||||
|
||||
def test_under_budget_forgets_the_timers(self, proc: Path, kill: MagicMock) -> None:
|
||||
del proc
|
||||
killer = LeisureKiller(None)
|
||||
verdict = _verdict(_now(Reason("media", "app:mpv", 10, "mpv")))
|
||||
killer.enforce(_SPENT, _RULES, verdict=verdict, stamp=0.0)
|
||||
under = PlaytimeState(day_key="2026-11-02", seconds=50.0)
|
||||
killer.enforce(under, _RULES, verdict=verdict, stamp=10.0)
|
||||
killer.enforce(_SPENT, _RULES, verdict=verdict, stamp=40.0)
|
||||
assert [c.args[1] for c in kill.call_args_list] == [signal.SIGTERM] * 2
|
||||
|
||||
def test_a_target_that_drops_out_restarts_its_timer(
|
||||
self, proc: Path, kill: MagicMock
|
||||
) -> None:
|
||||
del proc
|
||||
killer = LeisureKiller(None)
|
||||
listed = _verdict(_now(Reason("media", "app:mpv", 10, "mpv")))
|
||||
killer.enforce(_SPENT, _RULES, verdict=listed, stamp=0.0)
|
||||
killer.enforce(_SPENT, _RULES, verdict=_verdict(_now()), stamp=3.0)
|
||||
killer.enforce(_SPENT, _RULES, verdict=listed, stamp=40.0)
|
||||
assert [c.args[1] for c in kill.call_args_list] == [signal.SIGTERM] * 2
|
||||
|
||||
def test_a_pid_reused_by_a_new_process_starts_over(
|
||||
self, proc: Path, kill: MagicMock
|
||||
) -> None:
|
||||
killer = LeisureKiller(None)
|
||||
verdict = _verdict(_now(Reason("media", "app:mpv", 10, "mpv")))
|
||||
killer.enforce(_SPENT, _RULES, verdict=verdict, stamp=0.0)
|
||||
(proc / "10" / "stat").write_text(
|
||||
"10 (mpv) S 1 " + "0 " * 17 + "999 0", encoding="utf-8"
|
||||
)
|
||||
killer.enforce(_SPENT, _RULES, verdict=verdict, stamp=40.0)
|
||||
assert [c.args[1] for c in kill.call_args_list] == [signal.SIGTERM] * 2
|
||||
|
||||
def test_a_vanished_or_unsignallable_pid_is_not_logged(
|
||||
self, proc: Path, kill: MagicMock
|
||||
) -> None:
|
||||
add_proc(proc, FakeProc(11, exe="/usr/bin/vlc"))
|
||||
(proc / "12").mkdir()
|
||||
(proc / "12" / "status").write_text("Uid:\t1000\t1000\n", encoding="utf-8")
|
||||
kill.side_effect = ProcessLookupError
|
||||
log = StubLog()
|
||||
verdict = _verdict(
|
||||
_now(
|
||||
Reason("media", "app:vlc", 11, "vlc"),
|
||||
Reason("media", "app:ghost", 12, "?"),
|
||||
)
|
||||
)
|
||||
LeisureKiller(log).enforce(_SPENT, _RULES, verdict=verdict, stamp=0.0)
|
||||
assert [c.args[0] for c in kill.call_args_list] == [11]
|
||||
assert log.records == []
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"rules",
|
||||
[
|
||||
replace(_RULES, enforcement=False),
|
||||
replace(_RULES, demo=True),
|
||||
replace(_RULES, leisure=False),
|
||||
],
|
||||
)
|
||||
def test_never_with_enforcement_off_in_a_demo_or_dormant(
|
||||
self, proc: Path, kill: MagicMock, rules: PlaytimeRules
|
||||
) -> None:
|
||||
del proc
|
||||
LeisureKiller(None).enforce(_SPENT, rules, verdict=_verdict(None), stamp=0.0)
|
||||
kill.assert_not_called()
|
||||
|
||||
def test_a_bug_never_escapes_into_the_loop(
|
||||
self, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
killer = LeisureKiller(None)
|
||||
with patch.object(_leisure_kill, "sweep_targets", side_effect=RecursionError):
|
||||
for stamp in range(0, 34, 3): # sweeps (and fails) at 30 and 33
|
||||
killer.enforce(_SPENT, _RULES, verdict=_verdict(None), stamp=stamp)
|
||||
assert sum("Leisure kill failed" in r.message for r in caplog.records) == 1
|
||||
|
||||
def test_a_failed_sigkill_is_retried_and_logged_once_delivered(
|
||||
self, proc: Path, kill: MagicMock
|
||||
) -> None:
|
||||
del proc
|
||||
kill.side_effect = [None, ProcessLookupError, None, None]
|
||||
log = StubLog()
|
||||
killer = LeisureKiller(log)
|
||||
verdict = _verdict(_now(Reason("media", "app:mpv", 10, "mpv")))
|
||||
for stamp in (0.0, 30.0, 33.0, 36.0):
|
||||
killer.enforce(_SPENT, _RULES, verdict=verdict, stamp=stamp)
|
||||
assert [f["signal"] for _e, f in log.records] == ["SIGTERM", "SIGKILL"]
|
||||
assert kill.call_count == 4
|
||||
110
steam_backlog_enforcer/tests/test_leisure_kill_debounce.py
Normal file
110
steam_backlog_enforcer/tests/test_leisure_kill_debounce.py
Normal file
@ -0,0 +1,110 @@
|
||||
"""An untrusted watcher is swept only after 30 s of continuous untrust."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from typing import TYPE_CHECKING
|
||||
from unittest.mock import patch
|
||||
|
||||
from leisure_watch.facts import Focus, Now
|
||||
import pytest
|
||||
|
||||
from steam_backlog_enforcer._leisure_kill import UNTRUSTED_SWEEP_AFTER, LeisureKiller
|
||||
from steam_backlog_enforcer._playtime_state import PlaytimeRules, PlaytimeState
|
||||
from steam_backlog_enforcer._shadow import ShadowVerdict
|
||||
from steam_backlog_enforcer.tests._isolate_leisure import leisure_proc
|
||||
from steam_backlog_enforcer.tests._leisure_fake_proc import FakeProc, add_proc
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Iterable, Iterator
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
_RULES = PlaytimeRules(
|
||||
budget_seconds=100.0,
|
||||
warn_at=(),
|
||||
sigkill_after=30.0,
|
||||
count_launchers=False,
|
||||
enforcement=True,
|
||||
demo=False,
|
||||
leisure=True,
|
||||
)
|
||||
_SPENT = PlaytimeState(day_key="2026-11-02", seconds=100.0)
|
||||
_FREE = PlaytimeState(day_key="2026-11-02", seconds=1.0)
|
||||
_TRUSTED = ShadowVerdict(
|
||||
paused_by=None,
|
||||
keys=(),
|
||||
fact=Now(0.0, 1, "free", None, (), Focus("i3", "", None, idle=False)),
|
||||
)
|
||||
_STALE = ShadowVerdict(paused_by=None, keys=("k",), fact=None)
|
||||
_PAUSED = ShadowVerdict(paused_by="i3lock", keys=(), fact=None)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def kill(tmp_path: Path) -> Iterator[MagicMock]:
|
||||
add_proc(leisure_proc(tmp_path), FakeProc(10, exe="/usr/bin/mpv"))
|
||||
with patch.object(os, "kill") as mock:
|
||||
yield mock
|
||||
|
||||
|
||||
def _ticks(
|
||||
killer: LeisureKiller,
|
||||
stamps: Iterable[float],
|
||||
verdict: ShadowVerdict = _STALE,
|
||||
state: PlaytimeState = _SPENT,
|
||||
) -> None:
|
||||
for stamp in stamps:
|
||||
killer.enforce(state, _RULES, verdict=verdict, stamp=float(stamp))
|
||||
|
||||
|
||||
def test_the_window_is_30_s() -> None:
|
||||
assert UNTRUSTED_SWEEP_AFTER == 30.0
|
||||
|
||||
|
||||
def test_one_stale_moment_kills_nothing(kill: MagicMock) -> None:
|
||||
killer = LeisureKiller(None)
|
||||
_ticks(killer, range(0, 28, 3))
|
||||
kill.assert_not_called()
|
||||
_ticks(killer, [30])
|
||||
assert [c.args[0] for c in kill.call_args_list] == [10]
|
||||
|
||||
|
||||
def test_a_trusted_tick_restarts_the_window(kill: MagicMock) -> None:
|
||||
killer = LeisureKiller(None)
|
||||
_ticks(killer, range(0, 25, 3))
|
||||
_ticks(killer, [27], _TRUSTED)
|
||||
_ticks(killer, range(30, 58, 3))
|
||||
kill.assert_not_called()
|
||||
_ticks(killer, [60])
|
||||
kill.assert_called_once()
|
||||
|
||||
|
||||
def test_a_pause_restarts_the_window(kill: MagicMock) -> None:
|
||||
killer = LeisureKiller(None)
|
||||
_ticks(killer, range(0, 25, 3))
|
||||
_ticks(killer, [27], _PAUSED)
|
||||
_ticks(killer, range(30, 55, 3))
|
||||
kill.assert_not_called()
|
||||
|
||||
|
||||
def test_resume_from_sleep_restarts_the_window(kill: MagicMock) -> None:
|
||||
killer = LeisureKiller(None)
|
||||
_ticks(killer, range(0, 28, 3))
|
||||
_ticks(killer, range(3600, 3628, 3))
|
||||
kill.assert_not_called()
|
||||
_ticks(killer, [3630])
|
||||
kill.assert_called_once()
|
||||
|
||||
|
||||
def test_untrust_counts_while_the_budget_lasts(kill: MagicMock) -> None:
|
||||
killer = LeisureKiller(None)
|
||||
_ticks(killer, range(0, 31, 3), state=_FREE)
|
||||
_ticks(killer, [33])
|
||||
kill.assert_called_once()
|
||||
|
||||
|
||||
def test_a_clock_step_back_restarts_the_window(kill: MagicMock) -> None:
|
||||
killer = LeisureKiller(None)
|
||||
_ticks(killer, range(100, 128, 3))
|
||||
_ticks(killer, range(0, 28, 3))
|
||||
kill.assert_not_called()
|
||||
89
steam_backlog_enforcer/tests/test_leisure_kill_start.py
Normal file
89
steam_backlog_enforcer/tests/test_leisure_kill_start.py
Normal file
@ -0,0 +1,89 @@
|
||||
"""PID reuse: a reason carrying its process start time kills only that process.
|
||||
|
||||
leisure-watch 0.2.1 adds an optional ``start`` (``/proc/<pid>/stat`` field 22)
|
||||
to each reason; :class:`_R` stands in for it, so this runs on 0.2.0 too.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import os
|
||||
from typing import TYPE_CHECKING
|
||||
from unittest.mock import patch
|
||||
|
||||
from leisure_watch.facts import Focus, Now, Reason
|
||||
import pytest
|
||||
|
||||
from steam_backlog_enforcer._leisure_kill import LeisureKiller, fact_starts
|
||||
from steam_backlog_enforcer._playtime_state import PlaytimeRules, PlaytimeState
|
||||
from steam_backlog_enforcer._shadow import ShadowVerdict
|
||||
from steam_backlog_enforcer.tests._isolate_leisure import leisure_proc
|
||||
from steam_backlog_enforcer.tests._leisure_fake_proc import FakeProc, add_proc
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
_RULES = PlaytimeRules(
|
||||
budget_seconds=100.0,
|
||||
warn_at=(),
|
||||
sigkill_after=30.0,
|
||||
count_launchers=False,
|
||||
enforcement=True,
|
||||
demo=False,
|
||||
leisure=True,
|
||||
)
|
||||
_SPENT = PlaytimeState(day_key="2026-11-02", seconds=100.0)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _R(Reason):
|
||||
start: int | None = None
|
||||
|
||||
|
||||
def _killed(tmp_path: Path, *reasons: Reason) -> list[int]:
|
||||
root = leisure_proc(tmp_path)
|
||||
add_proc(root, FakeProc(10, exe="/usr/bin/mpv", start=500))
|
||||
fact = Now(0.0, 1, "leisure", None, reasons, Focus("mpv", "", None, idle=False))
|
||||
verdict = ShadowVerdict(paused_by=None, keys=("k",), fact=fact)
|
||||
with patch.object(os, "kill") as kill:
|
||||
LeisureKiller(None).enforce(_SPENT, _RULES, verdict=verdict, stamp=0.0)
|
||||
return [c.args[0] for c in kill.call_args_list]
|
||||
|
||||
|
||||
def test_a_matching_start_is_killed(tmp_path: Path) -> None:
|
||||
assert _killed(tmp_path, _R("media", "app:mpv", 10, "mpv", start=500)) == [10]
|
||||
|
||||
|
||||
def test_a_reused_pid_is_spared(tmp_path: Path) -> None:
|
||||
assert _killed(tmp_path, _R("media", "app:mpv", 10, "mpv", start=499)) == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"reason",
|
||||
[
|
||||
Reason("media", "app:mpv", 10, "mpv"),
|
||||
_R("media", "app:mpv", 10, "mpv", start=None),
|
||||
_R("media", "app:mpv", 10, "mpv", start=True),
|
||||
],
|
||||
)
|
||||
def test_no_usable_start_keeps_the_old_behaviour(
|
||||
tmp_path: Path, reason: Reason
|
||||
) -> None:
|
||||
assert _killed(tmp_path, reason) == [10]
|
||||
|
||||
|
||||
def test_starts_come_from_the_reason_that_named_the_pid() -> None:
|
||||
fact = Now(
|
||||
0.0,
|
||||
1,
|
||||
"leisure",
|
||||
None,
|
||||
(
|
||||
_R("game", "steam:1", 10, "x", start=1),
|
||||
_R("media", "app:mpv", 10, "mpv", start=500),
|
||||
_R("focus", "app:mpv", 10, "mpv", start=7),
|
||||
_R("media", "app:vlc", None, "vlc", start=9),
|
||||
),
|
||||
Focus("mpv", "", None, idle=False),
|
||||
)
|
||||
assert fact_starts(fact) == {10: 500}
|
||||
160
steam_backlog_enforcer/tests/test_leisure_mode.py
Normal file
160
steam_backlog_enforcer/tests/test_leisure_mode.py
Normal file
@ -0,0 +1,160 @@
|
||||
"""Phase 2 gate and billing: ``leisure_on`` and ``leisure_billed``."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
import importlib
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
import earned_time
|
||||
import pytest
|
||||
|
||||
from steam_backlog_enforcer import _leisure_mode
|
||||
from steam_backlog_enforcer._budget_resolve import resolve_budget
|
||||
from steam_backlog_enforcer._leisure_mode import (
|
||||
Tick,
|
||||
bill_tick,
|
||||
leisure_billed,
|
||||
leisure_on,
|
||||
)
|
||||
from steam_backlog_enforcer._playtime_state import PlaytimeRules, PlaytimeState
|
||||
from steam_backlog_enforcer._shadow import ShadowVerdict, shadow_accumulate
|
||||
from steam_backlog_enforcer.config import Config
|
||||
from steam_backlog_enforcer.tests._budget_dates import AFTER_CUT, pin_today
|
||||
from steam_backlog_enforcer.tests._isolate_leisure import switch_file
|
||||
|
||||
_LOCAL = timezone(timedelta(hours=2))
|
||||
_NOW = datetime(2026, 11, 2, 20, 0, tzinfo=_LOCAL)
|
||||
_DAY = "2026-11-02"
|
||||
_REAL_SWITCH = Path("/etc/leisure-watch/leisure_from")
|
||||
_RULES = PlaytimeRules(
|
||||
budget_seconds=100.0,
|
||||
warn_at=(),
|
||||
sigkill_after=30.0,
|
||||
count_launchers=False,
|
||||
enforcement=True,
|
||||
demo=False,
|
||||
)
|
||||
|
||||
|
||||
def _switch_on(tmp_path: Path, day: str) -> None:
|
||||
switch_file(tmp_path).write_text(day + "\n", encoding="ascii")
|
||||
|
||||
|
||||
class TestHygiene:
|
||||
def test_no_test_reads_the_real_switch_file(self) -> None:
|
||||
assert _leisure_mode.LEISURE_FROM_PATH != _REAL_SWITCH
|
||||
reader = importlib.import_module("earned_time._leisure")
|
||||
assert reader.LEISURE_FROM_PATH != _REAL_SWITCH
|
||||
|
||||
def test_the_redirect_reaches_both_readers(self, tmp_path: Path) -> None:
|
||||
with pin_today(AFTER_CUT):
|
||||
dormant = resolve_budget(Config()).base_seconds
|
||||
_switch_on(tmp_path, AFTER_CUT.isoformat())
|
||||
live = resolve_budget(Config()).base_seconds
|
||||
assert leisure_on(AFTER_CUT.isoformat())
|
||||
assert live - dormant == 2 * 3600.0
|
||||
|
||||
|
||||
class TestLeisureOn:
|
||||
def test_absent_switch_is_dormant(self) -> None:
|
||||
assert not leisure_on(_DAY)
|
||||
|
||||
def test_the_switch_day_and_later_are_on(self, tmp_path: Path) -> None:
|
||||
_switch_on(tmp_path, _DAY)
|
||||
assert leisure_on(_DAY)
|
||||
assert leisure_on("2026-11-03")
|
||||
|
||||
def test_the_day_before_is_off(self, tmp_path: Path) -> None:
|
||||
_switch_on(tmp_path, _DAY)
|
||||
assert not leisure_on("2026-11-01")
|
||||
|
||||
def test_a_garbage_day_key_is_dormant(self, tmp_path: Path) -> None:
|
||||
_switch_on(tmp_path, _DAY)
|
||||
assert not leisure_on("not-a-day")
|
||||
|
||||
def test_the_gate_asks_earned_time(self) -> None:
|
||||
with patch.object(earned_time, "leisure_active", return_value=True) as ask:
|
||||
assert leisure_on(_DAY)
|
||||
ask.assert_called_once_with(date(2026, 11, 2), _leisure_mode.LEISURE_FROM_PATH)
|
||||
|
||||
|
||||
def _start() -> PlaytimeState:
|
||||
return PlaytimeState(day_key=_DAY, last_tick_at=_NOW.timestamp() - 3.0)
|
||||
|
||||
|
||||
def _tick(verdict: ShadowVerdict, owners: dict[int, str] | None = None) -> Tick:
|
||||
return Tick(now=_NOW, interval=3.0, owners=owners or {}, verdict=verdict)
|
||||
|
||||
|
||||
def _bill(
|
||||
verdict: ShadowVerdict, owners: dict[int, str] | None = None
|
||||
) -> tuple[PlaytimeState, bool]:
|
||||
state, rules = bill_tick(_start(), _RULES, _tick(verdict, owners))
|
||||
return state, rules.leisure
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def live(tmp_path: Path) -> None:
|
||||
_switch_on(tmp_path, _DAY)
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("live")
|
||||
class TestLeisureBilled:
|
||||
def test_leisure_bills_enforced_seconds_unattributed(self) -> None:
|
||||
state, leisure = _bill(ShadowVerdict(paused_by=None, keys=("app:mpv",)))
|
||||
assert (state.seconds, state.per_game, leisure) == (3.0, {}, True)
|
||||
assert state.last_tick_at == _NOW.timestamp()
|
||||
|
||||
def test_a_game_tick_credits_the_game(self) -> None:
|
||||
verdict = ShadowVerdict(paused_by=None, keys=("app:440",))
|
||||
state, _ = _bill(verdict, {7: "app:440"})
|
||||
assert state.per_game == {"app:440": 3.0}
|
||||
|
||||
def test_paused_bills_nothing_even_with_a_game(self) -> None:
|
||||
verdict = ShadowVerdict(paused_by="i3lock", keys=())
|
||||
state, leisure = _bill(verdict, {7: "app:440"})
|
||||
assert (state.seconds, state.per_game, leisure) == (0.0, {}, True)
|
||||
assert state.last_tick_at == _NOW.timestamp()
|
||||
|
||||
def test_free_bills_nothing(self) -> None:
|
||||
state, _ = _bill(ShadowVerdict(paused_by=None, keys=()))
|
||||
assert state.seconds == 0.0
|
||||
|
||||
def test_enforced_and_shadow_move_together(self) -> None:
|
||||
verdicts = (
|
||||
ShadowVerdict(paused_by=None, keys=("domain:youtube.com",)),
|
||||
ShadowVerdict(paused_by="i3lock", keys=()),
|
||||
ShadowVerdict(paused_by=None, keys=()),
|
||||
ShadowVerdict(paused_by=None, keys=("app:440", "app:mpv")),
|
||||
)
|
||||
state = _start()
|
||||
for i, verdict in enumerate(verdicts):
|
||||
now = _NOW + timedelta(seconds=3 * i)
|
||||
before = state
|
||||
state = shadow_accumulate(
|
||||
state, stamp=now.timestamp(), interval=3.0, verdict=verdict
|
||||
)
|
||||
tick = Tick(now=now, interval=3.0, owners={}, verdict=verdict)
|
||||
state = leisure_billed(state, tick)
|
||||
moved = state.seconds - before.seconds
|
||||
assert moved == state.shadow_seconds - before.shadow_seconds
|
||||
|
||||
|
||||
class TestDormantBilling:
|
||||
def test_games_only_and_rules_untouched(self) -> None:
|
||||
verdict = ShadowVerdict(paused_by=None, keys=("app:mpv",))
|
||||
state, leisure = _bill(verdict)
|
||||
assert (state.seconds, leisure) == (0.0, False)
|
||||
state, _ = _bill(ShadowVerdict(paused_by="i3lock", keys=()), {7: "app:440"})
|
||||
assert state.per_game == {"app:440": 3.0}
|
||||
|
||||
def test_a_demo_is_never_live(self, live: None) -> None:
|
||||
del live
|
||||
demo = PlaytimeRules(
|
||||
1.0, (), 1.0, count_launchers=False, enforcement=True, demo=True
|
||||
)
|
||||
verdict = ShadowVerdict(paused_by=None, keys=("app:mpv",))
|
||||
state, rules = bill_tick(_start(), demo, _tick(verdict))
|
||||
assert (state.seconds, rules) == (0.0, demo)
|
||||
177
steam_backlog_enforcer/tests/test_leisure_never_kill.py
Normal file
177
steam_backlog_enforcer/tests/test_leisure_never_kill.py
Normal file
@ -0,0 +1,177 @@
|
||||
"""The never-kill set: the desktop survives a forged or buggy now.json."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
from typing import TYPE_CHECKING
|
||||
from unittest.mock import patch
|
||||
|
||||
from leisure_watch.facts import Focus, Now, Reason
|
||||
import pytest
|
||||
|
||||
from steam_backlog_enforcer._leisure_kill import LeisureKiller
|
||||
from steam_backlog_enforcer._leisure_never_kill import never_kill
|
||||
from steam_backlog_enforcer._playtime_state import PlaytimeRules, PlaytimeState
|
||||
from steam_backlog_enforcer._shadow import ShadowVerdict
|
||||
from steam_backlog_enforcer.tests._isolate_leisure import leisure_proc
|
||||
from steam_backlog_enforcer.tests._leisure_fake_proc import FakeProc, add_proc
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
_PY = "/usr/bin/python3.14"
|
||||
_RULES = PlaytimeRules(
|
||||
budget_seconds=100.0,
|
||||
warn_at=(),
|
||||
sigkill_after=30.0,
|
||||
count_launchers=False,
|
||||
enforcement=True,
|
||||
demo=False,
|
||||
leisure=True,
|
||||
)
|
||||
_SPENT = PlaytimeState(day_key="2026-11-02", seconds=100.0)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def proc(tmp_path: Path) -> Path:
|
||||
return leisure_proc(tmp_path)
|
||||
|
||||
|
||||
class TestNeverKill:
|
||||
@pytest.mark.parametrize(
|
||||
("exe", "args", "why"),
|
||||
[
|
||||
("/usr/bin/i3", ("i3",), "i3"),
|
||||
("/usr/bin/i3bar", ("i3bar",), "i3bar"),
|
||||
("/usr/bin/i3blocks", ("i3blocks",), "i3blocks"),
|
||||
("/usr/lib/Xorg", ("Xorg", ":0"), "xorg"),
|
||||
("/usr/bin/Xwayland", ("Xwayland",), "xwayland"),
|
||||
("/usr/lib/systemd/systemd", ("systemd", "--user"), "systemd"),
|
||||
("/usr/bin/dbus-broker", ("dbus-broker",), "dbus-broker"),
|
||||
("/usr/bin/dbus-daemon", ("dbus-daemon",), "dbus-daemon"),
|
||||
("/usr/bin/pipewire-pulse", ("pipewire-pulse",), "pipewire-pulse"),
|
||||
("/usr/bin/pipewire", ("pipewire",), "pipewire"),
|
||||
("/usr/bin/wireplumber", ("wireplumber",), "wireplumber"),
|
||||
("/usr/bin/pulseaudio", ("pulseaudio",), "pulseaudio"),
|
||||
("/usr/bin/sshd", ("sshd",), "sshd"),
|
||||
("/usr/bin/ssh-agent", ("ssh-agent",), "ssh-agent"),
|
||||
("/usr/bin/gpg-agent", ("gpg-agent",), "gpg-agent"),
|
||||
("/usr/bin/tmux", ("tmux",), "tmux"),
|
||||
("/usr/bin/screen", ("screen",), "screen"),
|
||||
("/usr/bin/alacritty", ("alacritty",), "alacritty"),
|
||||
("/usr/bin/kitty", ("kitty",), "kitty"),
|
||||
("/usr/bin/xterm", ("xterm",), "xterm"),
|
||||
("/usr/bin/foot", ("foot",), "foot"),
|
||||
("/usr/bin/zsh", ("-zsh",), "zsh"),
|
||||
("/usr/bin/bash", ("bash",), "bash"),
|
||||
("/usr/bin/fish", ("fish",), "fish"),
|
||||
("/usr/bin/sh", ("sh", "-c", "x"), "sh"),
|
||||
("/usr/bin/sudo", ("sudo", "x"), "sudo"),
|
||||
("/usr/bin/keepassxc", ("keepassxc",), "keepassxc"),
|
||||
("/usr/bin/dunst", ("dunst",), "dunst"),
|
||||
("/usr/lib/xfce4/notifyd/xfce4-notifyd", ("x",), "xfce4-notifyd"),
|
||||
("/usr/bin/vim (deleted)", ("vim",), None),
|
||||
("/usr/bin/mpv", ("mpv",), None),
|
||||
("/usr/bin/shellcheck", ("shellcheck",), None),
|
||||
("/usr/bin/screenkey", ("screenkey",), None),
|
||||
("/opt/helium-browser-bin/helium", ("helium",), None),
|
||||
],
|
||||
)
|
||||
def test_by_binary(
|
||||
self, proc: Path, exe: str, args: tuple[str, ...], why: str | None
|
||||
) -> None:
|
||||
add_proc(proc, FakeProc(10, exe=exe, argv=args))
|
||||
assert never_kill(10) == why
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("args", "why"),
|
||||
[
|
||||
(("/usr/bin/python", "/usr/bin/terminator"), "terminator"),
|
||||
(("python3", "-m", "leisure_watch", "run"), "leisure_watch"),
|
||||
(
|
||||
("python3", "/home/kuhy/.local/bin/daily-limits", "--sync"),
|
||||
"daily_limits",
|
||||
),
|
||||
(("python3", "-m", "screen_locker._web"), "screen_locker"),
|
||||
(("python3", "/x/leetcode_guard_tray.py"), "leetcode_guard_tray"),
|
||||
(("python3", "-m", "wsg_grabber"), None),
|
||||
(("python3", "-c", "import leisure_watch"), None),
|
||||
],
|
||||
)
|
||||
def test_by_python_script(
|
||||
self, proc: Path, args: tuple[str, ...], why: str | None
|
||||
) -> None:
|
||||
add_proc(proc, FakeProc(10, exe=_PY, argv=args))
|
||||
assert never_kill(10) == why
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("exe", "args", "why"),
|
||||
[
|
||||
("/home/kuhy/.local/share/claude/versions/2.1.302", ("x",), "claude"),
|
||||
("/x/claude_agent_sdk/_bundled/claude", ("claude",), "claude"),
|
||||
(
|
||||
"/usr/bin/node",
|
||||
("node", "/x/@anthropic-ai/claude-code/cli.js"),
|
||||
"claude",
|
||||
),
|
||||
("/usr/bin/node", ("node", "/x/server.js"), None),
|
||||
("/usr/bin/node", ("node",), None),
|
||||
],
|
||||
)
|
||||
def test_claude(
|
||||
self, proc: Path, exe: str, args: tuple[str, ...], why: str | None
|
||||
) -> None:
|
||||
add_proc(proc, FakeProc(10, exe=exe, argv=args))
|
||||
assert never_kill(10) == why
|
||||
|
||||
|
||||
class TestKillerRefuses:
|
||||
def test_a_forged_fact_cannot_kill_the_desktop(
|
||||
self, proc: Path, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
add_proc(proc, FakeProc(10, exe="/usr/bin/i3", argv=("i3",)))
|
||||
add_proc(proc, FakeProc(11, exe="/usr/bin/alacritty", argv=("alacritty",)))
|
||||
add_proc(proc, FakeProc(12, exe="/usr/bin/mpv"))
|
||||
fact = Now(
|
||||
ts=0.0,
|
||||
seq=1,
|
||||
state="leisure",
|
||||
paused_by=None,
|
||||
reasons=(
|
||||
Reason("failclosed", "failclosed:x", 10, "x"),
|
||||
Reason("focus", "app:alacritty", 11, "x"),
|
||||
Reason("media", "app:mpv", 12, "mpv"),
|
||||
),
|
||||
focus=Focus("i3", "", None, idle=False),
|
||||
)
|
||||
verdict = ShadowVerdict(paused_by=None, keys=("k",), fact=fact)
|
||||
records: list[tuple[str, dict[str, object]]] = []
|
||||
|
||||
class Log:
|
||||
def record(self, event: str, **fields: object) -> None:
|
||||
records.append((event, fields))
|
||||
|
||||
killer = LeisureKiller(Log())
|
||||
with patch.object(os, "kill") as kill, caplog.at_level(logging.WARNING):
|
||||
for stamp in (0.0, 3.0, 40.0):
|
||||
killer.enforce(_SPENT, _RULES, verdict=verdict, stamp=stamp)
|
||||
assert {c.args[0] for c in kill.call_args_list} == {12}
|
||||
refused = [f for e, f in records if e == "leisure_kill_refused"]
|
||||
assert sorted((f["pid"], f["name"]) for f in refused) == [
|
||||
(10, "i3"),
|
||||
(11, "alacritty"),
|
||||
]
|
||||
assert sum("never killed" in r.getMessage() for r in caplog.records) == 2
|
||||
|
||||
def test_a_refusal_without_a_log_only_warns(
|
||||
self, proc: Path, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
add_proc(proc, FakeProc(10, exe="/usr/bin/i3", argv=("i3",)))
|
||||
reasons = (Reason("failclosed", "failclosed:x", 10, "x"),)
|
||||
fact = Now(0.0, 1, "leisure", None, reasons, Focus("i3", "", None, idle=False))
|
||||
verdict = ShadowVerdict(paused_by=None, keys=("k",), fact=fact)
|
||||
with patch.object(os, "kill") as kill, caplog.at_level(logging.WARNING):
|
||||
LeisureKiller(None).enforce(_SPENT, _RULES, verdict=verdict, stamp=0.0)
|
||||
kill.assert_not_called()
|
||||
assert "never killed" in caplog.text
|
||||
174
steam_backlog_enforcer/tests/test_leisure_procs.py
Normal file
174
steam_backlog_enforcer/tests/test_leisure_procs.py
Normal file
@ -0,0 +1,174 @@
|
||||
"""Process identity for leisure kills: browsers, players, lockers, ownership."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import pytest
|
||||
|
||||
from steam_backlog_enforcer import _leisure_procs as procs
|
||||
from steam_backlog_enforcer.tests._isolate_leisure import leisure_proc
|
||||
from steam_backlog_enforcer.tests._leisure_fake_proc import FakeProc, add_proc
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def proc(tmp_path: Path) -> Path:
|
||||
return leisure_proc(tmp_path)
|
||||
|
||||
|
||||
class TestNames:
|
||||
@pytest.mark.parametrize(
|
||||
"exe",
|
||||
[
|
||||
"/opt/helium-browser-bin/helium",
|
||||
"/usr/lib/librewolf/librewolf",
|
||||
"/usr/lib/chromium/chromium",
|
||||
"/opt/google/chrome/chrome",
|
||||
"/opt/brave.com/brave/brave",
|
||||
"/opt/vivaldi/vivaldi-bin",
|
||||
"/usr/lib/opera/opera",
|
||||
"/opt/microsoft/msedge/msedge",
|
||||
"/usr/lib/firefox/firefox-bin",
|
||||
"/opt/zen-browser-bin/zen-bin",
|
||||
"/opt/helium-browser-bin/helium_crashpad_handler",
|
||||
],
|
||||
)
|
||||
def test_browser_families_by_exe(self, proc: Path, exe: str) -> None:
|
||||
add_proc(proc, FakeProc(10, exe=exe, comm="Isolated Web Co"))
|
||||
assert procs.is_browser(10)
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"exe", ["/usr/bin/mpv", "/usr/bin/operator", "/usr/bin/frozen", "/x/knowledge"]
|
||||
)
|
||||
def test_non_browsers(self, proc: Path, exe: str) -> None:
|
||||
add_proc(proc, FakeProc(10, exe=exe))
|
||||
assert not procs.is_browser(10)
|
||||
|
||||
def test_unreadable_exe_falls_back_to_comm(self, proc: Path) -> None:
|
||||
add_proc(proc, FakeProc(10, comm="helium"))
|
||||
(proc / "10" / "exe").unlink()
|
||||
assert procs.exe_name(10) == "helium"
|
||||
assert procs.is_browser(10)
|
||||
|
||||
def test_a_vanished_pid_has_no_name(self) -> None:
|
||||
assert procs.exe_name(99) == ""
|
||||
assert procs.argv(99) == ()
|
||||
assert procs.real_uid(99) is None
|
||||
assert procs.start_time(99) is None
|
||||
assert procs.parent(99) is None
|
||||
|
||||
def test_reads_uid_start_and_parent(self, proc: Path) -> None:
|
||||
add_proc(proc, FakeProc(10, uid=1000, ppid=7, start=4242))
|
||||
assert (procs.real_uid(10), procs.start_time(10), procs.parent(10)) == (
|
||||
1000,
|
||||
4242,
|
||||
7,
|
||||
)
|
||||
|
||||
def test_malformed_status_and_stat(self, proc: Path) -> None:
|
||||
add_proc(proc, FakeProc(10))
|
||||
(proc / "10" / "status").write_text("Name:\tmpv\nUid:\tx\n", encoding="utf-8")
|
||||
(proc / "10" / "stat").write_text("10 (mpv) S", encoding="utf-8")
|
||||
assert procs.real_uid(10) is None
|
||||
assert procs.start_time(10) is None
|
||||
(proc / "10" / "stat").write_text("10 (mpv) S x", encoding="utf-8")
|
||||
assert procs.parent(10) is None
|
||||
|
||||
def test_status_without_a_uid_line(self, proc: Path) -> None:
|
||||
add_proc(proc, FakeProc(10))
|
||||
(proc / "10" / "status").write_text("Name:\tmpv\n", encoding="utf-8")
|
||||
assert procs.real_uid(10) is None
|
||||
|
||||
|
||||
class TestProtected:
|
||||
def test_a_plain_user_player_is_fair_game(self, proc: Path) -> None:
|
||||
add_proc(proc, FakeProc(10))
|
||||
assert not procs.is_protected(10, set())
|
||||
|
||||
@pytest.mark.parametrize("uid", [0, 999, 1001])
|
||||
def test_anything_not_the_desktop_users(self, proc: Path, uid: int) -> None:
|
||||
add_proc(proc, FakeProc(10, uid=uid))
|
||||
assert procs.is_protected(10, set())
|
||||
|
||||
def test_a_vanished_pid_is_never_signalled(self) -> None:
|
||||
assert procs.is_protected(99, set())
|
||||
|
||||
def test_own_chain(self, proc: Path) -> None:
|
||||
add_proc(proc, FakeProc(10))
|
||||
assert procs.is_protected(10, {10})
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"argv",
|
||||
[
|
||||
("i3lock", "--nofork"),
|
||||
("/usr/bin/python3", "-m", "screen_locker._web_server"),
|
||||
("python3", "/home/kuhy/.config/i3/scripts/leetcode_guard_tray.py"),
|
||||
("/usr/bin/book-guard",),
|
||||
],
|
||||
)
|
||||
def test_lockers_and_their_children(
|
||||
self, proc: Path, argv: tuple[str, ...]
|
||||
) -> None:
|
||||
add_proc(proc, FakeProc(5, exe="/usr/bin/python3", argv=argv, comm="x"))
|
||||
add_proc(proc, FakeProc(10, ppid=5))
|
||||
assert procs.is_protected(5, set())
|
||||
assert procs.is_protected(10, set())
|
||||
|
||||
def test_a_parent_loop_terminates(self, proc: Path) -> None:
|
||||
add_proc(proc, FakeProc(10, ppid=11))
|
||||
add_proc(proc, FakeProc(11, ppid=10))
|
||||
assert not procs.is_protected(10, set())
|
||||
|
||||
def test_own_chain_walks_up(self, proc: Path) -> None:
|
||||
me = os.getpid()
|
||||
add_proc(proc, FakeProc(me, ppid=77))
|
||||
add_proc(proc, FakeProc(77, ppid=1))
|
||||
assert procs.own_chain() == {me, 77, 1}
|
||||
|
||||
|
||||
class TestSweep:
|
||||
def test_untrusted_watcher_sweeps_browsers_players_and_the_reviewer(
|
||||
self, proc: Path
|
||||
) -> None:
|
||||
add_proc(proc, FakeProc(10, exe="/opt/helium-browser-bin/helium"))
|
||||
add_proc(proc, FakeProc(11, exe="/usr/bin/mpv"))
|
||||
add_proc(proc, FakeProc(12, exe="/opt/FreeTube/freetube"))
|
||||
add_proc(
|
||||
proc,
|
||||
FakeProc(
|
||||
13, exe="/usr/bin/python3.14", argv=("python3", "-m", "wsg_grabber")
|
||||
),
|
||||
)
|
||||
add_proc(
|
||||
proc,
|
||||
FakeProc(
|
||||
14,
|
||||
exe="/usr/bin/python3.14",
|
||||
argv=("python3", "-m", "wsg_grabber", "scrape"),
|
||||
),
|
||||
)
|
||||
add_proc(proc, FakeProc(15, exe="/usr/bin/terminator"))
|
||||
add_proc(proc, FakeProc(16, exe="/usr/bin/wsg-grabber", argv=("wsg-grabber",)))
|
||||
(proc / "self").mkdir()
|
||||
assert procs.sweep_targets() == {
|
||||
10: "sweep:browser:helium",
|
||||
11: "sweep:media:mpv",
|
||||
12: "sweep:media:freetube",
|
||||
13: "sweep:wsg-grabber",
|
||||
16: "sweep:wsg-grabber",
|
||||
}
|
||||
|
||||
def test_an_unlistable_proc_sweeps_nothing(self, proc: Path) -> None:
|
||||
proc.rmdir()
|
||||
assert procs.sweep_targets() == {}
|
||||
|
||||
def test_a_deep_tree_walk_is_bounded(self, proc: Path) -> None:
|
||||
for pid in range(100, 150):
|
||||
add_proc(proc, FakeProc(pid, ppid=pid + 1))
|
||||
add_proc(proc, FakeProc(150, argv=("i3lock",)))
|
||||
# The locker is 50 generations up: past the bound, so not seen.
|
||||
assert not procs.is_protected(100, set())
|
||||
74
steam_backlog_enforcer/tests/test_leisure_procs_identity.py
Normal file
74
steam_backlog_enforcer/tests/test_leisure_procs_identity.py
Normal file
@ -0,0 +1,74 @@
|
||||
"""What a process really runs: wsg-grabber as the program, updated binaries."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import pytest
|
||||
|
||||
from steam_backlog_enforcer import _leisure_procs as procs
|
||||
from steam_backlog_enforcer.tests._isolate_leisure import leisure_proc
|
||||
from steam_backlog_enforcer.tests._leisure_fake_proc import FakeProc, add_proc
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
_PY = "/usr/bin/python3.14"
|
||||
_WSG = "/home/kuhy/.local/bin/wsg-grabber"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def proc(tmp_path: Path) -> Path:
|
||||
return leisure_proc(tmp_path)
|
||||
|
||||
|
||||
class TestWsgIsTheProgram:
|
||||
@pytest.mark.parametrize(
|
||||
("exe", "args"),
|
||||
[
|
||||
("/usr/bin/git", ("git", "-C", "/home/kuhy/src/wsg-grabber", "status")),
|
||||
(_PY, ("python3", "-m", "pytest", "/home/kuhy/src/wsg-grabber")),
|
||||
("/usr/bin/vim", ("vim", _WSG)),
|
||||
(_PY, ("python3", _WSG, "scrape")),
|
||||
(_PY, ("python3", "-u", "-m", "wsg_grabber", "scrape")),
|
||||
("/usr/bin/wsg-grabber", ("wsg-grabber", "scrape")),
|
||||
(_PY, ("python3", "-c", "import wsg_grabber")),
|
||||
(_PY, ("python3", "-m")),
|
||||
(_PY, ("python3", "-X", "dev")),
|
||||
(_PY, ("python3",)),
|
||||
],
|
||||
)
|
||||
def test_not_a_reviewer(self, proc: Path, exe: str, args: tuple[str, ...]) -> None:
|
||||
add_proc(proc, FakeProc(10, exe=exe, argv=args))
|
||||
assert procs.sweep_targets() == {}
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("exe", "args"),
|
||||
[
|
||||
(_PY, ("python3", _WSG)),
|
||||
(_PY, ("python3", _WSG, "review")),
|
||||
(_PY, ("python3", "-X", "dev", "-m", "wsg_grabber.cli")),
|
||||
("/usr/bin/python", ("python", "/x/wsg_grabber.py")),
|
||||
("/usr/bin/wsg_grabber", ("wsg_grabber", "review")),
|
||||
],
|
||||
)
|
||||
def test_a_reviewer(self, proc: Path, exe: str, args: tuple[str, ...]) -> None:
|
||||
add_proc(proc, FakeProc(10, exe=exe, argv=args))
|
||||
assert procs.sweep_targets() == {10: "sweep:wsg-grabber"}
|
||||
|
||||
def test_script_of_a_non_interpreter_is_none(self, proc: Path) -> None:
|
||||
add_proc(proc, FakeProc(10, exe="/usr/bin/git", argv=("git", "x.py")))
|
||||
assert procs.script_of(10) is None
|
||||
|
||||
|
||||
class TestDeletedExe:
|
||||
def test_an_updated_browser_is_still_a_browser(self, proc: Path) -> None:
|
||||
add_proc(proc, FakeProc(10, exe="/opt/helium-browser-bin/helium (deleted)"))
|
||||
assert procs.exe_name(10) == "helium"
|
||||
assert procs.is_browser(10)
|
||||
assert procs.sweep_targets() == {10: "sweep:browser:helium"}
|
||||
|
||||
def test_an_updated_player_is_still_swept(self, proc: Path) -> None:
|
||||
add_proc(proc, FakeProc(10, exe="/usr/bin/mpv (deleted)"))
|
||||
assert procs.sweep_targets() == {10: "sweep:media:mpv"}
|
||||
assert procs.exe_path(10) == "/usr/bin/mpv"
|
||||
183
steam_backlog_enforcer/tests/test_leisure_tick.py
Normal file
183
steam_backlog_enforcer/tests/test_leisure_tick.py
Normal file
@ -0,0 +1,183 @@
|
||||
"""The tick with Phase 2 dormant (no new path runs) and live (leisure billing)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from contextlib import ExitStack
|
||||
from dataclasses import replace
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import TYPE_CHECKING
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from steam_backlog_enforcer import _leisure_mode, _shadow
|
||||
from steam_backlog_enforcer._leisure_kill import LeisureKiller
|
||||
from steam_backlog_enforcer._playtime import playtime_tick
|
||||
from steam_backlog_enforcer._playtime_cutoff import _begin_cutoff, _warn
|
||||
from steam_backlog_enforcer._playtime_session import new_session
|
||||
from steam_backlog_enforcer._playtime_state import (
|
||||
PlaytimeRules,
|
||||
PlaytimeState,
|
||||
load_state,
|
||||
save_state,
|
||||
)
|
||||
from steam_backlog_enforcer.config import Config
|
||||
from steam_backlog_enforcer.tests._fake_session import fake_session
|
||||
from steam_backlog_enforcer.tests._isolate_leisure import switch_file
|
||||
from steam_backlog_enforcer.tests._no_workout_http import fixed_budget
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Iterator
|
||||
from pathlib import Path
|
||||
|
||||
from steam_backlog_enforcer._shadow import ShadowVerdict
|
||||
|
||||
_LOCAL = timezone(timedelta(hours=2))
|
||||
_NOW = datetime(2026, 7, 27, 20, 0, tzinfo=_LOCAL)
|
||||
_TODAY = "2026-07-27"
|
||||
_PKG = "steam_backlog_enforcer._playtime"
|
||||
_CUTOFF = "steam_backlog_enforcer._playtime_cutoff"
|
||||
|
||||
|
||||
class SpyLeisure:
|
||||
def __init__(self) -> None:
|
||||
self.calls: list[tuple[PlaytimeState, PlaytimeRules]] = []
|
||||
|
||||
def enforce(
|
||||
self,
|
||||
state: PlaytimeState,
|
||||
rules: PlaytimeRules,
|
||||
*,
|
||||
verdict: ShadowVerdict,
|
||||
stamp: float,
|
||||
) -> None:
|
||||
del verdict, stamp
|
||||
self.calls.append((state, rules))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def notify() -> Iterator[MagicMock]:
|
||||
with ExitStack() as stack:
|
||||
stack.enter_context(patch(f"{_CUTOFF}.reconcile"))
|
||||
stack.enter_context(patch(f"{_CUTOFF}.request_steam_shutdown"))
|
||||
stack.enter_context(patch(f"{_CUTOFF}.kill_gaming_processes"))
|
||||
stack.enter_context(patch(f"{_PKG}.mounted_targets", return_value=set()))
|
||||
stack.enter_context(patch(f"{_PKG}.is_total_block_active", return_value=False))
|
||||
yield stack.enter_context(patch(f"{_CUTOFF}.notify_desktop_user"))
|
||||
|
||||
|
||||
def _tick(
|
||||
owners: dict[int, str], *, budget: float = 3600.0, demo: bool = False
|
||||
) -> tuple[PlaytimeState, SpyLeisure]:
|
||||
save_state(
|
||||
PlaytimeState(day_key=_TODAY, last_tick_at=_NOW.timestamp() - 3.0),
|
||||
demo=demo,
|
||||
)
|
||||
spy = SpyLeisure()
|
||||
session = replace(fake_session(), leisure=spy)
|
||||
with (
|
||||
fixed_budget(budget),
|
||||
patch(f"{_PKG}.qualifying_pids", return_value=owners),
|
||||
patch(f"{_PKG}.datetime") as mock_dt,
|
||||
):
|
||||
mock_dt.now.return_value = _NOW
|
||||
playtime_tick(Config(), interval=3.0, session=session, demo=demo)
|
||||
state = load_state(demo=demo)
|
||||
assert state is not None
|
||||
return state, spy
|
||||
|
||||
|
||||
def _go_live(tmp_path: Path) -> None:
|
||||
switch_file(tmp_path).write_text(_TODAY + "\n", encoding="ascii")
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("notify")
|
||||
class TestDormant:
|
||||
def test_no_new_code_path_runs_without_the_switch(self) -> None:
|
||||
with patch.object(
|
||||
_leisure_mode, "leisure_billed", side_effect=AssertionError("ran")
|
||||
):
|
||||
state, spy = _tick({})
|
||||
assert spy.calls == []
|
||||
# Games-only, exactly as before: the fail-closed shadow does not bill.
|
||||
assert (state.seconds, state.shadow_seconds) == (0.0, 3.0)
|
||||
|
||||
def test_games_still_bill_games_only(self) -> None:
|
||||
state, spy = _tick({7: "app:440"})
|
||||
assert (state.seconds, state.per_game, spy.calls) == (3.0, {"app:440": 3.0}, [])
|
||||
|
||||
def test_a_demo_ignores_the_switch(self, tmp_path: Path) -> None:
|
||||
_go_live(tmp_path)
|
||||
state, spy = _tick({}, demo=True)
|
||||
assert (state.seconds, spy.calls) == (0.0, [])
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("notify")
|
||||
class TestLive:
|
||||
def test_leisure_bills_the_enforced_count(self, tmp_path: Path) -> None:
|
||||
_go_live(tmp_path)
|
||||
state, spy = _tick({})
|
||||
assert state.seconds == state.shadow_seconds == 3.0
|
||||
assert state.shadow_per_source == {_shadow.FAILCLOSED_KEY: 3.0}
|
||||
[(_seen, rules)] = spy.calls
|
||||
assert rules.leisure
|
||||
|
||||
def test_a_lock_pauses_the_enforced_count_too(self, tmp_path: Path) -> None:
|
||||
_go_live(tmp_path)
|
||||
with patch.object(_shadow, "paused_by", return_value="i3lock"):
|
||||
state, _ = _tick({7: "app:440"})
|
||||
assert (state.seconds, state.shadow_paused_seconds) == (0.0, 3.0)
|
||||
|
||||
def test_at_zero_the_cutoff_says_leisure_and_kills_run(
|
||||
self, tmp_path: Path, notify: MagicMock
|
||||
) -> None:
|
||||
_go_live(tmp_path)
|
||||
state, spy = _tick({}, budget=3.0)
|
||||
assert state.is_blocked()
|
||||
assert notify.call_args.args[0] == "Leisure time is up"
|
||||
assert "leisure" in notify.call_args.args[1]
|
||||
assert spy.calls[0][0].seconds >= spy.calls[0][1].budget_seconds
|
||||
|
||||
|
||||
_RULES = PlaytimeRules(
|
||||
budget_seconds=3600.0,
|
||||
warn_at=(3600, 1800),
|
||||
sigkill_after=30.0,
|
||||
count_launchers=False,
|
||||
enforcement=True,
|
||||
demo=False,
|
||||
)
|
||||
|
||||
|
||||
class TestWording:
|
||||
def test_warnings_say_gaming_while_dormant(self) -> None:
|
||||
with patch(f"{_CUTOFF}.notify_desktop_user") as notify:
|
||||
_warn(PlaytimeState(day_key=_TODAY, seconds=10.0), _RULES)
|
||||
notify.assert_called_once_with(
|
||||
"Gaming time running out", "1 hour of today's gaming budget left."
|
||||
)
|
||||
|
||||
def test_warnings_say_leisure_when_live(self) -> None:
|
||||
with patch(f"{_CUTOFF}.notify_desktop_user") as notify:
|
||||
_warn(
|
||||
PlaytimeState(day_key=_TODAY, seconds=10.0),
|
||||
replace(_RULES, leisure=True),
|
||||
)
|
||||
notify.assert_called_once_with(
|
||||
"Leisure time running out", "1 hour of today's leisure budget left."
|
||||
)
|
||||
|
||||
@pytest.mark.usefixtures("notify")
|
||||
def test_the_dormant_cutoff_text_is_unchanged(self, notify: MagicMock) -> None:
|
||||
_begin_cutoff(PlaytimeState(day_key=_TODAY), _RULES, now=_NOW)
|
||||
notify.assert_called_once_with(
|
||||
"Gaming time is up",
|
||||
"Daily budget used up. Steam and games are shutting down. "
|
||||
"Unblocks at 06:00.",
|
||||
)
|
||||
|
||||
|
||||
def test_new_session_kills_through_the_budget_log() -> None:
|
||||
session = new_session()
|
||||
assert isinstance(session.leisure, LeisureKiller)
|
||||
assert session.leisure.log is not None
|
||||
Loading…
Reference in New Issue
Block a user