Compare commits

...

2 Commits

Author SHA1 Message Date
db44ca5b0b Split ci-mirror gate into <60 s steps
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Waiting to run
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint) (push) Waiting to run
Tests / test (push) Waiting to run
Tests / web-coverage (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
The single ci-mirror manual hook (clean venv + pre-commit --all-files +
serial pytest) ran past the 60 s per-command cap, so the tree could not be
stamped for a push. It is now nine gate steps, each under 55 s at load ~40:

- ci-mirror-venv / -precommit / -pytest: scripts/ci_mirror.sh parts;
  pytest runs on 4 xdist workers, pytest-cov still enforces 100 %.
- ci-mirror-pylint-{pkg,tests-1,tests-2,tests-3}: per-file checks over a
  partition of the pylint hook's targets; -dup and -cycles: the two
  cross-file checks on the whole tree. pylint is now a local hook so all of
  them share one env (&pylint_env, pylint==4.0.9).
- scripts/pylint_symilar_cache.py: pylint plugin that hashes each file once
  for duplicate-code instead of once per file pair (same R0801 output).

Tests: an autouse guard refuses non-loopback DNS (several tests made live
HLTB requests), two web fixtures poll at 0.01 s, and the rate-limit test
uses a fake clock. CLAUDE.md and AGENTS.md get the push line.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWWjUkRCFGNMnnXZrSP
2026-11-11 16:29:08 +01:00
87c6f200e3 Research window: keep Steam dir, extend once
kuhy 2026-11-11, multi-day research without re-setup.

W1: once a window was used in a lock, the block's purge spares
~/.local/share/Steam (Librarian's install and local saves) for the
rest of the lock; ~/steam, ~/.steam and the rest still go. The
package stays removed, hosts/iptables are re-applied, and since the
kept install could otherwise be launched without the package, every
Steam game is killed on sight. A record that cannot be read also
keeps the folder (an irreversible delete never rests on unknown
state); the block itself stays fully applied.

W2: the 48 h cap is gone; --until is bounded by the lock's end. An
open window may be extended ONCE, to the lock end at most, never
shortened, never reopened after it ended. The extension is a
separate extended_until field beside until, so a daemon still on
the previous code reads the original window instead of rejecting the
record as corrupt (which would have purged the folder).

Failure modes unchanged: missing/corrupt record = no window, and a
corrupt one refuses a new window or extension.

Checked: 3325 tests at 100% coverage; pylint 10/10 in parts; vmbox:
extension accepted once, refused beyond the lock end, earlier or
equal, second time and non-root; extended end honoured past the
original end; at close the Steam dir and a save survive, ~/steam and
~/.steam go, a game started after close is killed; extension to
exactly the lock end accepted. Not verified on the host.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWWzuCEg1m87jpKyRrw
2026-11-11 16:28:43 +01:00
28 changed files with 830 additions and 132 deletions

View File

@ -120,10 +120,19 @@ repos:
# ===========================================================================
# PYLINT
# ===========================================================================
- repo: https://github.com/pylint-dev/pylint
rev: v4.0.9
# A local hook (was the pylint-dev/pylint repo at v4.0.9) so the manual
# ci-mirror-pylint-* shards below can share its env: pre-commit gives local
# `language: python` hooks with the same additional_dependencies ONE env,
# and the &pylint_env anchor is the single place the pylint version and its
# import deps are pinned.
- repo: local
hooks:
- id: pylint
name: pylint
entry: pylint
language: python
types: [python]
require_serial: true
# Whole tree on every run, never the staged subset: `--fail-under`
# grades a score, and a score over whatever happened to be staged let a
# 9.99 tree pass at commit time and fail in CI. scripts/file_length/
@ -137,11 +146,13 @@ repos:
- --jobs=1
- steam_backlog_enforcer
- scripts/check_requirements_sync.py
- scripts/pylint_symilar_cache.py
# pylint resolves imports in its OWN isolated env, so anything the
# package imports has to be listed here or it reports import-error and
# drags the score under --fail-under. `mcp` is a real runtime import
# (steam_backlog_enforcer._mcp_server).
additional_dependencies:
additional_dependencies: &pylint_env
- pylint==4.0.9
- aiohttp==3.14.5
- earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.21.0#subdirectory=earned_time
- leisure-watch @ git+https://github.com/kuhyx/leisure-watch@leisure-watch-v0.2.7
@ -168,13 +179,97 @@ repos:
exclude: ^(tests/|.*test.*\.py$)
# ===========================================================================
# PYTEST + COVERAGE (push stage)
# CI MIRROR (manual stage: the gate steps before a push)
# ===========================================================================
# One gate step per hook, each under the 60 s per-command cap even on a
# loaded box: `scripts/check_gate_stamp.sh step <id>` per id of
# `scripts/check_gate_stamp.sh full --list`; the last one stamps the tree.
# The pylint hook above is split into the ci-mirror-pylint-* shards and
# ci-mirror-precommit skips it, so the union checks exactly what CI does:
# - per-file checks run per shard; the shards' `files` partition the hook's
# targets (tests by name: rest|test_[a-h], test_[i-r], test_[s-z]). With
# --fail-under=10.0 a shard passes only with zero scored messages, so
# every shard passing == the whole tree at 10.00;
# - the two cross-file checks (duplicate-code, cyclic-import) see the whole
# tree, as in the full hook (ci-mirror-pylint-dup, ci-mirror-pylint-cycles).
- repo: local
hooks:
- id: ci-mirror
name: CI mirror (clean-venv pytest + pre-commit --all-files)
entry: bash scripts/ci_mirror.sh steam_backlog_enforcer/tests/
- id: ci-mirror-venv
name: CI mirror (clean requirements.txt venv, rebuilt on change)
entry: bash scripts/ci_mirror.sh venv
language: system
pass_filenames: false
always_run: true
require_serial: true
stages: [manual]
- id: ci-mirror-precommit
name: CI mirror (pre-commit --all-files, pylint via the shards)
entry: bash scripts/ci_mirror.sh precommit
language: system
pass_filenames: false
always_run: true
require_serial: true
stages: [manual]
- &pylint_shard
id: ci-mirror-pylint-pkg
name: CI mirror pylint (package + scripts, per-file checks)
entry: pylint
language: python
additional_dependencies: *pylint_env
types: [python]
require_serial: true
stages: [manual]
files: ^(steam_backlog_enforcer/(?!tests/).*|scripts/(check_requirements_sync|pylint_symilar_cache))\.py$
args: &pylint_per_file
- --rcfile=pyproject.toml
- --fail-under=10.0
- --jobs=1
- --disable=duplicate-code,cyclic-import
- <<: *pylint_shard
id: ci-mirror-pylint-tests-1
name: CI mirror pylint (tests helpers + test_[a-h], per-file checks)
files: ^steam_backlog_enforcer/tests/(?!test_[i-z]).*\.py$
- <<: *pylint_shard
id: ci-mirror-pylint-tests-2
name: CI mirror pylint (test_[i-r], per-file checks)
files: ^steam_backlog_enforcer/tests/test_[i-r][^/]*\.py$
- <<: *pylint_shard
id: ci-mirror-pylint-tests-3
name: CI mirror pylint (test_[s-z], per-file checks)
files: ^steam_backlog_enforcer/tests/test_[s-z][^/]*\.py$
- &pylint_whole_tree
<<: *pylint_shard
id: ci-mirror-pylint-dup
name: CI mirror pylint (whole tree, duplicate-code)
files: ''
pass_filenames: false
always_run: true
args:
- --rcfile=pyproject.toml
- --fail-under=10.0
- --jobs=1
- --disable=all
# bad-plugin-value keeps a plugin that failed to load (the
# duplicate-code speed-up) loud instead of silently slow.
- --enable=duplicate-code,bad-plugin-value
- steam_backlog_enforcer
- scripts/check_requirements_sync.py
- scripts/pylint_symilar_cache.py
- <<: *pylint_whole_tree
id: ci-mirror-pylint-cycles
name: CI mirror pylint (whole tree, cyclic-import)
args:
- --rcfile=pyproject.toml
- --fail-under=10.0
- --jobs=1
- --disable=all
- --enable=cyclic-import
- steam_backlog_enforcer
- scripts/check_requirements_sync.py
- scripts/pylint_symilar_cache.py
- id: ci-mirror-pytest
name: CI mirror (clean-venv pytest, xdist, 100% coverage)
entry: bash scripts/ci_mirror.sh pytest steam_backlog_enforcer/tests/
language: system
pass_filenames: false
always_run: true

View File

@ -23,3 +23,4 @@ After running tests fix all coverage gaps and issues, do not ignore unless speci
- lint: `pre-commit run ruff --all-files`
- coverage: `python3 -m pytest -q`
- coverage-gaps: `coverage-gaps coverage.lcov`
- push: `scripts/check_gate_stamp.sh full && git push` (every manual-stage gate hook, ~3 min, then push). Agents (60 s cap): one call per id of `scripts/check_gate_stamp.sh full --list`: `CAP_MEM=4G CAP_CPU_PCT=20 ~/.claude/scripts/capped.sh timeout 55 scripts/check_gate_stamp.sh step <id>` (each < 55 s; the last stamps the tree), then `git push`.

View File

@ -24,3 +24,4 @@ After running tests fix all coverage gaps and issues, do not ignore unless speci
- coverage: `python3 -m pytest -q`
- coverage-gaps: `coverage-gaps coverage.lcov`
- deploy: `scripts/deploy.sh`
- push: `scripts/check_gate_stamp.sh full && git push` (every manual-stage gate hook, ~3 min, then push). Agents (60 s cap): one call per id of `scripts/check_gate_stamp.sh full --list`: `CAP_MEM=4G CAP_CPU_PCT=20 ~/.claude/scripts/capped.sh timeout 55 scripts/check_gate_stamp.sh step <id>` (each < 55 s; the last stamps the tree), then `git push`.

View File

@ -36,7 +36,7 @@ python -m python_pkg.steam_backlog_enforcer.main setup
| `unblock [minutes]` | Unblock the store for a window (default 15, max 30); the daemon keeps it open and re-blocks after |
| `buy-dlc` | Same 15-minute store window, to buy a game or DLC |
| `reset` | Reset all state |
| `total-block-research --until T` | Root. One window per total block (at most 48 h): Steam and the store open, only Librarian may be played; the daemon re-applies the full block at `T` |
| `total-block-research --until T` | Root. One window per total block, up to its end, extendable once: Steam and the store open, only Librarian may be played; the daemon re-applies the full block at `T` and keeps `~/.local/share/Steam` |
| `installed` | List currently installed Steam games |
| `uninstall` | Interactively uninstall non-assigned games |
| `setup` | First-time configuration |

View File

@ -49,6 +49,10 @@ include = ["*.py", "**/*.py"]
# byte-identical to upstream; ruff --unsafe-fixes otherwise strips its print()
# calls (T201) and silently guts the gate's reporting.
exclude = [".git", ".venv", "__pycache__", "build", "dist", ".eggs", "scripts/file_length"]
# scripts/ has no __init__.py on purpose (one would make it a second top-level
# package for requirements-sync), yet pylint imports scripts.pylint_symilar_cache
# from it: an implicit namespace package, declared so INP001 knows.
namespace-packages = ["scripts"]
[tool.ruff.lint]
select = ["ALL"]
@ -130,6 +134,10 @@ exclude = [".venv/"]
# The repo root on the path, so pylint resolves the package's own imports the
# same way pytest does instead of reporting import-error for them.
init-hook = "import sys; sys.path.insert(0, '.')"
# Hashes each file once for duplicate-code instead of once per file PAIR; same
# R0801 output, whole-tree pylint fits the 60 s cap. Needs the init-hook above
# (pylint runs it before loading config-file plugins, never CLI ones).
load-plugins = ["scripts.pylint_symilar_cache"]
analyse-fallback-blocks = true
persistent = true
# Serial on purpose: with jobs != 1 pylint ships the linter to its workers via

View File

@ -8,16 +8,26 @@
# requirements.txt. That gap is why green-locally repos went red in CI
# (missing runtime deps, --all-files lint debt, order-dependent test flakes).
#
# This script reproduces both CI workflows on the developer machine:
# 1. a venv built ONLY from requirements.txt (mirrors the Tests workflow's
# `pip install -r requirements.txt`), rebuilt only when requirements.txt
# changes (hash-gated so day-to-day pushes stay fast);
# 2. `pre-commit run --all-files` (mirrors the pre-commit workflow);
# 3. `python -m pytest` inside that clean venv (mirrors Tests).
# This script reproduces both CI workflows on the developer machine, split
# into parts that each fit the 60 s per-command cap (one gate step each, see
# the ci-mirror-* manual hooks in .pre-commit-config.yaml):
# venv a venv built ONLY from requirements.txt (mirrors the Tests
# workflow's `uv pip install -r requirements.txt`), rebuilt only
# when requirements.txt changes (hash-gated);
# precommit `pre-commit run --all-files` minus pylint (mirrors the
# pre-commit workflow; pylint runs as the ci-mirror-pylint-*
# shards, which together check exactly what the pylint hook does);
# pytest `python -m pytest` in that clean venv (mirrors Tests), spread
# over CI_MIRROR_WORKERS xdist workers (default 4); pytest-cov
# merges the workers and enforces the 100 % gate itself.
# `all` (or no part, or a first argument that is not a part name, the old
# `ci_mirror.sh <pytest args>` form) runs the three in order with the full
# pylint hook: kuhy's terminal, over 60 s, so agents run the gate steps.
# Arguments after the part go to pytest.
#
# Runs on demand (`scripts/check_gate_stamp.sh full`, pre-commit's manual
# stage) and in CI. It left the pre-push path on 2026-09-20: 10+ minutes
# per push under the resource cap, for work finish_auto.sh had just done.
# Runs on demand (`scripts/check_gate_stamp.sh step <hook-id>`, pre-commit's
# manual stage). It left the pre-push path on 2026-09-20: 10+ minutes per push
# under the resource cap, for work finish_auto.sh had just done.
# ============================================================================
set -euo pipefail
@ -25,6 +35,7 @@ set -euo pipefail
# Requirements file may be overridden (e.g. testsAndMisc uses meta/…).
REQUIREMENTS_FILE="${REQUIREMENTS_FILE:-requirements.txt}"
readonly REQUIREMENTS_FILE
readonly WORKERS="${CI_MIRROR_WORKERS:-4}"
ROOT="$(git rev-parse --show-toplevel)"
readonly ROOT
@ -48,47 +59,87 @@ require_file() {
fi
}
# Rebuild the venv only when requirements.txt changed since the last build.
ensure_venv() {
local current stored
current="$(sha256sum "$REQ_PATH" | cut -d' ' -f1)"
stored=""
if [[ -f "$HASH_FILE" ]]; then
stored="$(cat "$HASH_FILE")"
fi
requirements_hash() {
sha256sum "$REQ_PATH" | cut -d' ' -f1
}
if [[ -x "$VENV_DIR/bin/python" && "$current" == "$stored" ]]; then
log "venv up to date (requirements.txt unchanged)"
venv_is_fresh() {
[[ -x "$VENV_DIR/bin/python" && -f "$HASH_FILE" \
&& "$(requirements_hash)" == "$(cat "$HASH_FILE")" ]]
}
# uv when present: the installer CI uses, and fast enough for one gate step.
rebuild_venv() {
rm -rf "$VENV_DIR"
if command -v uv >/dev/null 2>&1; then
uv venv --quiet --python python3 "$VENV_DIR" \
|| fail "uv venv for the clean venv"
uv pip install --quiet --python "$VENV_DIR/bin/python" -r "$REQ_PATH" \
|| fail "uv pip install -r $REQUIREMENTS_FILE (a dep may be undeclared)"
return
fi
log "requirements.txt changed — rebuilding clean venv (mirrors CI install)"
rm -rf "$VENV_DIR"
python3 -m venv "$VENV_DIR"
"$VENV_DIR/bin/python" -m pip install --quiet --upgrade pip \
|| fail "pip self-upgrade in the clean venv"
"$VENV_DIR/bin/python" -m pip install --quiet -r "$REQ_PATH" \
|| fail "pip install -r $REQUIREMENTS_FILE (a dep may be undeclared)"
printf '%s' "$current" > "$HASH_FILE"
}
# Rebuild the venv only when requirements.txt changed since the last build.
ensure_venv() {
if venv_is_fresh; then
log "venv up to date (requirements.txt unchanged)"
return
fi
log "requirements.txt changed — rebuilding clean venv (mirrors CI install)"
rebuild_venv
requirements_hash > "$HASH_FILE"
log "clean venv ready"
}
# The pytest part never rebuilds: a rebuild would not fit its budget, and a
# stale venv would test the wrong dependencies. Fail closed instead.
require_fresh_venv() {
venv_is_fresh \
|| fail "clean venv missing or stale; run the ci-mirror-venv step first"
}
run_precommit_all_files() {
log "pre-commit run --all-files (mirrors the pre-commit workflow)"
pre-commit run --all-files || fail "pre-commit --all-files"
local skip="${1:-}"
log "pre-commit run --all-files${skip:+ minus $skip} (mirrors the pre-commit workflow)"
SKIP="${SKIP:+$SKIP,}$skip" pre-commit run --all-files \
|| fail "pre-commit --all-files"
}
run_pytest_clean_venv() {
log "pytest in the clean venv (mirrors the Tests workflow)"
"$VENV_DIR/bin/python" -m pytest "$@" || fail "pytest (clean requirements.txt venv)"
log "pytest in the clean venv, $WORKERS workers (mirrors the Tests workflow)"
"$VENV_DIR/bin/python" -m pytest -n "$WORKERS" "$@" \
|| fail "pytest (clean requirements.txt venv)"
}
run_all() {
ensure_venv
run_precommit_all_files
run_pytest_clean_venv "$@"
}
main() {
require_file
ensure_venv
run_precommit_all_files
run_pytest_clean_venv "$@"
log "all CI gates passed locally — safe to push"
case "${1:-all}" in
venv) ensure_venv ;;
precommit) run_precommit_all_files pylint ;;
pytest)
shift
require_fresh_venv
run_pytest_clean_venv "$@"
;;
all)
[[ $# -gt 0 ]] && shift
run_all "$@"
;;
*) run_all "$@" ;;
esac
log "CI gate passed locally"
}
main "$@"

View File

@ -0,0 +1,77 @@
"""Pylint plugin: hash each file once for the duplicate-code check (R0801).
pylint's similarity checker compares every pair of linted files, and
``Symilar._find_common`` calls ``symilar.hash_lineset`` on BOTH files of every
pair. With ~550 files that is ~150 000 hashings of the same ~550 files, and it
was the slowest part of a whole-tree pylint run (well over 28 s of ~55 s under
the resource cap).
``hash_lineset`` is a pure function of a file's stripped lines and the window
size, and ``_find_common`` only reads the two dicts it returns (the line limits
it mutates are ``copy.copy``-ed first). Caching the result per (file, window)
therefore yields the same R0801 messages, computed once per file.
Fails closed: if a pylint upgrade changes ``hash_lineset``'s signature, this
raises instead of caching a function whose contract it no longer knows.
Loaded through ``load-plugins`` in pyproject.toml; the ``init-hook`` there puts
the repo root on ``sys.path`` first, which makes ``scripts.`` importable.
"""
from __future__ import annotations
import functools
import inspect
from typing import TYPE_CHECKING
from pylint.checkers import symilar
if TYPE_CHECKING:
from collections.abc import Callable
from pylint.lint import PyLinter
HashResult = tuple[symilar.HashToIndex_T, symilar.IndexToLines_T]
HashFunc = Callable[[symilar.LineSet, int], HashResult]
EXPECTED_PARAMS = ("lineset", "min_common_lines")
def memoise(func: HashFunc) -> HashFunc:
"""Wrap ``hash_lineset`` with a per-(file, window) cache.
The key is ``id(lineset)``; the cache keeps the lineset itself alive and
checks identity on a hit, so a recycled id can never return another
file's hashes.
"""
cache: dict[tuple[int, int], tuple[symilar.LineSet, HashResult]] = {}
@functools.wraps(func)
def cached(
lineset: symilar.LineSet,
min_common_lines: int = symilar.DEFAULT_MIN_SIMILARITY_LINE,
) -> HashResult:
key = (id(lineset), min_common_lines)
hit = cache.get(key)
if hit is None or hit[0] is not lineset:
hit = (lineset, func(lineset, min_common_lines))
cache[key] = hit
return hit[1]
return cached
def register(_linter: PyLinter) -> None:
"""Patch ``symilar.hash_lineset`` once per process (pylint plugin hook)."""
current = symilar.hash_lineset
if hasattr(current, "__wrapped__"):
return
params = tuple(inspect.signature(current).parameters)
if params != EXPECTED_PARAMS:
msg = (
f"pylint_symilar_cache: symilar.hash_lineset{params} no longer "
f"matches {EXPECTED_PARAMS}; re-check that it is still pure and "
"update scripts/pylint_symilar_cache.py"
)
raise RuntimeError(msg)
symilar.hash_lineset = memoise(current)

View File

@ -2,10 +2,11 @@
kuhy 2026-11-11: game-design research needs "Librarian: Tidy Up the Arcane
Library" actually played during a 6-day total block. This command opens ONE
window per lock, ending at ``--until`` (at most 48 h away, never past the
lock's end, never extended by a rerun). It only validates and records the
window; the enforcer daemon opens Steam within a pass and re-applies the full
block at the deadline (:mod:`steam_backlog_enforcer._research_tick`).
window per lock, ending at ``--until`` (never past the lock's end). While it is
open, one rerun with a later ``--until`` extends it (again to the lock's end at
most); nothing shortens it. It only validates and records the window; the
enforcer daemon opens Steam within a pass and re-applies the full block at the
deadline (:mod:`steam_backlog_enforcer._research_tick`).
Root-only: the record sits in a root-only state directory. The lock and its
end date are untouched, so this can never shorten or end a total block.
@ -22,7 +23,7 @@ from steam_backlog_enforcer._echo import _echo
_USAGE = (
"Usage: total-block-research --until <ISO time, local unless it has an offset>"
"\n e.g. total-block-research --until 2026-11-13T00:00"
"\n One window per total block, at most 48 h, Librarian only."
"\n One window per total block, up to its end, extendable once. Librarian only."
)
@ -63,9 +64,16 @@ def cmd_total_block_research(args: list[str]) -> int:
except window.ResearchRefusedError as exc:
_echo(f"Refused: {exc}")
return 1
ends = datetime.fromtimestamp(record.until).astimezone()
_echo(f"Research window recorded until {ends:%Y-%m-%d %H:%M %Z}.")
ends = datetime.fromtimestamp(record.ends_at).astimezone()
extended = record.extended_until is not None
verb = "extended" if extended else "recorded"
_echo(f"Research window {verb} until {ends:%Y-%m-%d %H:%M %Z}.")
_echo(f"Only {window.LIBRARIAN_NAME} (AppID {window.LIBRARIAN_APP_ID}) may run.")
_echo("The enforcer opens Steam on its next pass and re-applies the full")
_echo("total block at the deadline. This window cannot be reopened or extended.")
_echo("total block at the deadline (the Steam folder is kept).")
_echo(
"That was the one extension; it is never reopened."
if extended
else "It is extendable once, never reopened."
)
return 0

View File

@ -41,9 +41,10 @@ _MANUAL_LOCK_EXEMPT_COMMANDS = frozenset(
# Commands that remain usable while a total gaming block is active. Far
# stricter than _MANUAL_LOCK_EXEMPT_COMMANDS: no done/pick/reset/
# add-exception - nothing here shortens or ends a total block. The one bounded
# opening is total-block-research: root-only, a single <= 48 h window per lock
# that only Librarian may use, recorded in a root-only state directory; the
# daemon re-applies the full block when it expires (the lock's end is fixed).
# opening is total-block-research: root-only, a single window per lock that
# only Librarian may use (up to the lock's end, extendable once), recorded in a
# root-only state directory; the daemon re-applies the full block when it
# expires. The lock and its end date are never touched.
#
# gaming-unblock is included because a playtime bind mount makes the total
# block's own `pacman -R steam` fail EBUSY - it must stay reachable exactly

View File

@ -6,6 +6,10 @@ so the unprivileged user can neither forge a window nor delete the used-up
marker. It holds numbers and two latches only; no free text. Anything that
does not parse exactly, or that no legitimate open could have produced, is an
error: the caller treats that as "no window" (fail closed).
The one extension is a separate ``extended_until`` beside the original
``until`` (never an overwrite of it): a daemon still on the earlier code reads
the record as the original window instead of rejecting it as corrupt.
"""
from __future__ import annotations
@ -18,7 +22,6 @@ from typing import Final
from steam_backlog_enforcer.config import atomic_write
MAX_WINDOW_SECONDS: Final = 48 * 3600.0
RESEARCH_FILE: Final = Path("/var/lib/steam-backlog-enforcer/total_block_research.json")
_NUMBER_KEYS: Final = ("lock_started_at", "lock_until", "opened_at", "until")
@ -41,10 +44,17 @@ class ResearchRecord:
"""Latched once the deadline passed: a clock set back cannot reopen it."""
store_reblocked: bool = False
"""Latched once the normal store block is back after the window."""
extended_until: float | None = None
"""The deadline after the window's single extension, if it was extended."""
@property
def ends_at(self) -> float:
"""The deadline in force: the extension if there is one, else ``until``."""
return self.until if self.extended_until is None else self.extended_until
def is_open(self, at: float) -> bool:
"""Whether the window is open at *at* (epoch seconds)."""
return not self.closed and self.opened_at <= at < self.until
return not self.closed and self.opened_at <= at < self.ends_at
def to_json(self) -> str:
"""The record as the JSON text stored on disk."""
@ -68,6 +78,11 @@ def _number(data: dict[str, object], key: str) -> float:
return number
def _optional_number(data: dict[str, object], key: str) -> float | None:
"""A finite number, or None when the key is absent or null."""
return None if data.get(key) is None else _number(data, key)
def _flag(data: dict[str, object], key: str) -> bool:
"""A real boolean from *data*, False when absent."""
value = data.get(key, False)
@ -94,7 +109,8 @@ def parse_record(raw: str) -> ResearchRecord:
raise ResearchStateError(msg)
numbers = {key: _number(data, key) for key in _NUMBER_KEYS}
flags = {key: _flag(data, key) for key in _FLAG_KEYS}
record = ResearchRecord(**numbers, **flags)
extended = _optional_number(data, "extended_until")
record = ResearchRecord(**numbers, **flags, extended_until=extended)
_check_policy(record)
return record
@ -105,10 +121,10 @@ def _check_policy(record: ResearchRecord) -> None:
msg = "lock ends before it starts"
elif not record.opened_at < record.until:
msg = "window ends before it opens"
elif record.until - record.opened_at > MAX_WINDOW_SECONDS:
msg = "window is longer than 48 h"
elif record.until > record.lock_until:
elif record.ends_at > record.lock_until:
msg = "window outlives its lock"
elif record.extended_until is not None and record.extended_until <= record.until:
msg = "extension does not extend"
else:
return
raise ResearchStateError(msg)

View File

@ -8,10 +8,13 @@ real assignment in ``state.json`` is never read or written, so there is
nothing to restore afterwards. Everything else the block does to Steam itself
(kill, uninstall, purge) is skipped while the window is open.
Once the deadline passes the record is latched closed (a clock set back cannot
reopen it) and every pass is the ordinary :func:`enforce_total_block_tick`
again: it kills Steam, removes the package, purges its files, rebuilds the
firewall chain from the kept IP cache, and puts the full hosts section back.
Once the deadline (the extension's, if the window was extended) passes, the
record is latched closed (a clock set back cannot reopen it) and every pass is
the ordinary :func:`enforce_total_block_tick` again: it kills Steam, removes the
package, rebuilds the firewall chain from the kept IP cache, and puts the full
hosts section back. The purge spares ``~/.local/share/Steam`` for the rest of
the lock (Librarian's install and saves stay), and since that install could
otherwise be launched without the package, every Steam game is killed on sight.
The lock's end date is never involved.
"""
@ -86,12 +89,18 @@ def _research_pass(record: ResearchRecord) -> None:
if not steam_is_installed():
return
allowed = {window.LIBRARIAN_APP_ID}
killed = enforce_allowed_game(allowed, kill_unauthorized=True, strict=True)
for _pid, app_id in killed:
send_notification("⛔🎮", f"{app_id} → 🎯 {window.LIBRARIAN_NAME}")
_kill_games_except(allowed)
guard_installed_games(allowed, strict=True)
def _kill_games_except(allowed: set[int]) -> None:
"""Kill every running Steam game outside *allowed* (runtimes excepted)."""
for _pid, app_id in enforce_allowed_game(
allowed, kill_unauthorized=True, strict=True
):
send_notification("⛔🎮", f"{app_id} → 🎯 {window.LIBRARIAN_NAME}")
def total_block_pass(config: Config) -> None:
"""The total-block branch of one enforce pass.
@ -108,8 +117,14 @@ def total_block_pass(config: Config) -> None:
except OSError, subprocess.SubprocessError:
logger.exception("Research window pass failed; retrying next tick")
return
if record is not None and not record.closed and at >= record.until:
if record is not None and not record.closed and at >= record.ends_at:
record = _latch_closed(record)
enforce_total_block_tick()
# Used window (or a record that cannot say): the Steam folder is kept, and
# so no Steam game may run from it. {0} only makes the allowed set non-empty;
# app 0 is the client itself, which the block's own tick kills by name.
used = record is not None or window.research_used(at)
enforce_total_block_tick(keep_steam_dir=used)
if used:
_kill_games_except({0})
if record is not None and record.closed and not record.store_reblocked:
_reblock_store(config, record)

View File

@ -4,8 +4,9 @@ kuhy 2026-11-11: to research a game by playing it ("Librarian: Tidy Up the
Arcane Library", app 4197610) he needs Steam during a total block. This module
is the one bounded way to get it, and the rules are all here:
* **At most 48 hours**, as an explicit expiry (``--until``), never an
open-ended switch; a rerun never extends it.
* **Bounded by the lock**: an explicit expiry (``--until``) no later than the
lock's end, never an open-ended switch. While open, the window may be
extended once (to the lock's end at most); nothing shortens it.
* **Once per lock**: the record names the lock it was spent on (that lock's
``started_at``/``until``) and stays after the window ends.
* **Fail closed**: a missing, unreadable, unparsable or out-of-policy record
@ -19,6 +20,7 @@ is the one bounded way to get it, and the rules are all here:
from __future__ import annotations
from dataclasses import replace
from datetime import datetime
import logging
import time
@ -26,7 +28,6 @@ from typing import Final
from steam_backlog_enforcer import _research_record as store
from steam_backlog_enforcer._research_record import (
MAX_WINDOW_SECONDS,
ResearchRecord,
ResearchStateError,
read_record,
@ -115,7 +116,11 @@ def parse_until(raw: str) -> datetime:
def open_research_window(until: datetime) -> ResearchRecord:
"""Record a research window ending at *until* for the lock in force.
"""Record a research window ending at *until*, or extend the one in force.
The first call for a lock opens the window. While that window is open, one
later call may extend it, to the lock's end at most. Nothing else reopens,
lengthens or shortens it.
Args:
until: The expiry (timezone-aware).
@ -125,9 +130,10 @@ def open_research_window(until: datetime) -> ResearchRecord:
Raises:
ResearchRefusedError: With the reason: no active total block, an
unreadable record (fail closed), a window already spent on this
lock, an expiry that is past, over 48 h away or beyond the lock's
end, or a record that cannot be written.
unreadable record (fail closed), an expiry that is past (or, for
an extension, not later than the current one) or beyond the lock's
end, a window already ended or already extended once, or a record
that cannot be written.
"""
at = now()
lock = current_lock(at)
@ -139,15 +145,11 @@ def open_research_window(until: datetime) -> ResearchRecord:
except ResearchStateError as exc:
msg = f"research record unreadable ({exc}); refusing (fail closed)"
raise ResearchRefusedError(msg) from exc
if previous is not None and _same_lock(previous, lock):
ended = datetime.fromtimestamp(previous.until).astimezone()
msg = f"a window was already used for this lock (until {ended:%F %H:%M})"
raise ResearchRefusedError(msg)
deadline = until.timestamp()
if previous is not None and _same_lock(previous, lock):
return _store(_extend(previous, deadline, at, lock[1]))
if deadline <= at:
msg = "--until must be in the future"
elif deadline - at > MAX_WINDOW_SECONDS:
msg = "--until is more than 48 h from now"
elif deadline > lock[1]:
msg = "--until is after the end of the total block"
else:
@ -155,6 +157,40 @@ def open_research_window(until: datetime) -> ResearchRecord:
raise ResearchRefusedError(msg)
def _extend(
previous: ResearchRecord, deadline: float, at: float, lock_end: float
) -> ResearchRecord:
"""*previous* with its single extension, or a refusal saying why not."""
if previous.extended_until is not None:
msg = "the window was already extended once"
elif not previous.is_open(at):
msg = "a window was already used for this lock and it has ended"
elif deadline <= previous.until:
msg = "--until must be later than the window's current end"
elif deadline > lock_end:
msg = "--until is after the end of the total block"
else:
return replace(previous, extended_until=deadline)
raise ResearchRefusedError(msg)
def research_used(at: float | None = None) -> bool:
"""Whether a research window was spent on the lock in force.
Gates the one irreversible step of the block, the purge of the Steam
folder. A record that cannot be read counts as used: when the answer is
unknown, nothing is deleted (the block itself stays fully applied).
"""
lock = current_lock(now() if at is None else at)
if lock is None:
return False
try:
record = read_record()
except ResearchStateError:
return True
return record is not None and _same_lock(record, lock)
def _store(record: ResearchRecord) -> ResearchRecord:
"""Write *record*, turning a write failure into a refusal."""
try:

View File

@ -7,10 +7,10 @@ mechanisms that enforce it: :mod:`steam_backlog_enforcer._total_block_purge`
:mod:`steam_backlog_enforcer._total_block_iptables` (Steam unreachable).
No in-app command lifts a block early; the one bounded exception is a single
<= 48 h Librarian-only window per lock (:mod:`._research_window`) that never
touches the lock or its end date. Tamper-resistance is guard-lib's: the lock
file's ``until`` sits in a chattr-immutable file-guard, and pacman refuses to
install ``steam`` while the lock is active (package-block).
Librarian-only window per lock (:mod:`._research_window`, extendable once, to
the lock's end) that never touches the lock or its end date. Tamper-resistance
is guard-lib's: the lock file's ``until`` sits in a chattr-immutable file-guard,
and pacman refuses to install ``steam`` while the lock is active (package-block).
"""
from __future__ import annotations
@ -201,11 +201,12 @@ def start_total_block(days: int) -> bool:
return True
def enforce_total_block_tick() -> None:
"""Re-assert the total block.
def enforce_total_block_tick(*, keep_steam_dir: bool = False) -> None:
"""Re-assert the total block (every pass while it is active).
Called every enforce-loop iteration while :func:`is_total_block_active`
is True.
Args:
keep_steam_dir: Spare ``~/.local/share/Steam`` in the purge: a research
window was used in this lock, so Librarian's install and saves stay.
"""
kill_steam_and_launchers(LAUNCHER_PROCESS_NAMES)
kill_processes_by_name(kill_target_names(config.CONFIG_FILE))
@ -214,7 +215,7 @@ def enforce_total_block_tick() -> None:
logger.warning("Steam reappeared during total block - removing again")
uninstall_steam_package()
purge_steam_and_proton()
purge_steam_and_proton(keep_steam_dir=keep_steam_dir)
apply_total_block_iptables()
refresh_total_block_hosts() # not apply: that keeps a window's open section

View File

@ -41,10 +41,12 @@ _STEAM_PURGE_LOG_FILE = CONFIG_DIR / "total_block_purge_log.json"
# machine: ~/.steam (symlink farm), ~/steam (secondary/portable install),
# ~/.local/share/Steam (the real install - steamapps, userdata, screenshots,
# and compatibilitytools.d's GE-Proton builds all live under here).
STEAM_DATA_DIR = Path.home() / ".local" / "share" / "Steam"
_STEAM_REMNANT_PATHS: tuple[Path, ...] = (
Path.home() / ".steam",
Path.home() / "steam",
Path.home() / ".local" / "share" / "Steam",
STEAM_DATA_DIR,
Path.home() / ".steampath",
Path.home() / ".steampid",
Path.home() / ".config" / "steamtinkerlaunch",
@ -153,15 +155,21 @@ def _uninstall_proton_helpers() -> list[str]:
return removed
def _remove_steam_remnants() -> list[str]:
def _remove_steam_remnants(*, keep_steam_dir: bool = False) -> list[str]:
"""Delete the curated Steam/Proton filesystem remnants that exist.
With *keep_steam_dir* the Steam data folder itself is spared (a research
window was used: its install and local saves stay); every other remnant,
the secondary ``~/steam`` included, is still removed.
Symlinks are unlinked directly rather than following them into
:func:`shutil.rmtree`, since e.g. ``~/.steampath`` -> a file inside
``~/.steam``, which this same pass may already have removed.
"""
removed: list[str] = []
for path in _STEAM_REMNANT_PATHS:
if keep_steam_dir and path == STEAM_DATA_DIR:
continue
if not (path.is_symlink() or path.exists()):
continue
try:
@ -201,14 +209,18 @@ def _log_steam_purge(removed_paths: list[str], removed_packages: list[str]) -> N
_atomic_write(_STEAM_PURGE_LOG_FILE, json.dumps(existing, indent=2) + "\n")
def purge_steam_and_proton() -> None:
def purge_steam_and_proton(*, keep_steam_dir: bool = False) -> None:
"""Remove curated Steam/Proton filesystem remnants and helper packages.
Args:
keep_steam_dir: Spare ``~/.local/share/Steam`` (see
:func:`_remove_steam_remnants`).
Best-effort and re-run every enforce tick, same as the Steam-package
reappearance check: a stat() per fixed path and a ``pacman -Qi`` per
helper package are cheap even when there is nothing left to do.
"""
removed_paths = _remove_steam_remnants()
removed_paths = _remove_steam_remnants(keep_steam_dir=keep_steam_dir)
removed_packages = _uninstall_proton_helpers()
if removed_paths or removed_packages:
logger.info(

View File

@ -0,0 +1,67 @@
"""Autouse guard: tests resolve loopback names only, never the internet.
Without it a test that walked into an unpatched HLTB lookup (the poll-count
backfill after a pick, for example) made real HTTPS requests to
howlongtobeat.com: ~1.5 s per test, and a result that depended on the network
and on HLTB's live data. Every outbound call starts with ``getaddrinfo``
(requests/urllib3 directly, aiohttp through asyncio's thread resolver), so
refusing non-loopback hosts there turns each leak into the same fast failure
the package already handles when the machine is offline.
Tests that need a resolver patch ``socket.getaddrinfo`` themselves; their patch
sits on top of this one for the test's duration.
Split out of ``conftest.py`` to keep every file inside the 250-line cap;
``conftest`` imports the fixture by name, which is what registers it.
"""
from __future__ import annotations
import ipaddress
import socket
from typing import TYPE_CHECKING
from unittest.mock import patch
import pytest
if TYPE_CHECKING:
from collections.abc import Iterator
_REAL_GETADDRINFO = socket.getaddrinfo
_LOCAL_NAMES = frozenset({"", "localhost"})
def is_local_host(host: bytes | str | None) -> bool:
"""Whether *host* names this machine (loopback, unspecified, or None)."""
if host is None:
return True
if isinstance(host, bytes):
host = host.decode("ascii", "replace")
name = str(host)
if name.lower() in _LOCAL_NAMES:
return True
try:
address = ipaddress.ip_address(name)
except ValueError:
return False
return address.is_loopback or address.is_unspecified
def local_only_getaddrinfo(
host: bytes | str | None,
port: bytes | str | int | None,
*args: int,
**kwargs: int,
) -> list[tuple[object, ...]]:
"""``socket.getaddrinfo`` for loopback hosts; offline for anything else."""
if not is_local_host(host):
msg = f"tests may not resolve {host!r}: patch the network call instead"
raise socket.gaierror(socket.EAI_NONAME, msg)
return list(_REAL_GETADDRINFO(host, port, *args, **kwargs))
@pytest.fixture(autouse=True)
def _no_internet() -> Iterator[None]:
"""Refuse DNS for non-loopback hosts for the whole test."""
with patch("socket.getaddrinfo", local_only_getaddrinfo):
yield

View File

@ -31,6 +31,7 @@ class Paths:
hosts_file: Path
purge_log_file: Path
remnant_paths: tuple[Path, ...]
steam_dir: Path
def build_paths(tmp_path: Path) -> Paths:
@ -57,6 +58,7 @@ def build_paths(tmp_path: Path) -> Paths:
hosts_file=tmp_path / "hosts",
purge_log_file=tmp_path / "total_block_purge_log.json",
remnant_paths=remnant_paths,
steam_dir=remnant_paths[2],
)

View File

@ -32,6 +32,7 @@ from steam_backlog_enforcer.tests._isolate_reading import _isolate_reading
from steam_backlog_enforcer.tests._isolate_research import _isolate_research
from steam_backlog_enforcer.tests._isolate_shadow import _isolate_shadow
from steam_backlog_enforcer.tests._no_fast_install import _no_fast_install
from steam_backlog_enforcer.tests._no_internet import _no_internet
from steam_backlog_enforcer.tests._no_live_focus_project import _no_live_focus_project
from steam_backlog_enforcer.tests._no_real_effects import (
_no_live_games,
@ -56,6 +57,7 @@ __all__ = [
"_isolate_research",
"_isolate_shadow",
"_no_fast_install",
"_no_internet",
"_no_live_focus_project",
"_no_live_games",
"_no_real_effects",
@ -241,5 +243,6 @@ def total_block_paths(tmp_path: Path) -> Iterator[Paths]:
patch(f"{HOSTS}.HOSTS_FILE", built.hosts_file),
patch(f"{PURGE}._STEAM_PURGE_LOG_FILE", built.purge_log_file),
patch(f"{PURGE}._STEAM_REMNANT_PATHS", built.remnant_paths),
patch(f"{PURGE}.STEAM_DATA_DIR", built.steam_dir),
):
yield built

View File

@ -1,4 +1,4 @@
"""The `total-block-research` command: root-only, bounded, lock-exempt."""
"""The `total-block-research` command: root-only, to the lock end, lock-exempt."""
from __future__ import annotations
@ -19,7 +19,7 @@ from steam_backlog_enforcer._command_locks import (
)
from steam_backlog_enforcer.config import Config, State
from steam_backlog_enforcer.main import _dispatch_extra_command
from steam_backlog_enforcer.tests._research_helpers import HOUR, NOW, lock
from steam_backlog_enforcer.tests._research_helpers import HOUR, LOCK_END, NOW, lock
if TYPE_CHECKING:
from collections.abc import Iterator
@ -72,19 +72,41 @@ class TestCommand:
assert cmd.cmd_total_block_research(["--until", UNTIL]) == 1
assert window.read_record() is None
def test_over_48_hours_is_refused(self, capsys: pytest.CaptureFixture[str]) -> None:
"""Test that the cap is enforced by the command."""
late = datetime.fromtimestamp(NOW + 49 * HOUR, tz=UTC).isoformat()
def test_after_the_lock_end_is_refused(
self, capsys: pytest.CaptureFixture[str]
) -> None:
"""Test that the lock's end is the ceiling, with the reason printed."""
late = datetime.fromtimestamp(LOCK_END + 1, tz=UTC).isoformat()
assert cmd.cmd_total_block_research(["--until", late]) == 1
assert "48" in capsys.readouterr().out
assert "end of the total block" in capsys.readouterr().out
assert window.read_record() is None
def test_second_run_is_refused(self) -> None:
"""Test that the second run is refused and the first expiry stands."""
def test_second_run_extends_once(self, capsys: pytest.CaptureFixture[str]) -> None:
"""Test that a later expiry extends the open window, one time only."""
assert cmd.cmd_total_block_research(["--until", UNTIL]) == 0
first = window.read_record()
assert first is not None
assert "extendable once" in capsys.readouterr().out
later = datetime.fromtimestamp(NOW + 30 * HOUR, tz=UTC).isoformat()
assert cmd.cmd_total_block_research(["--until", later]) == 1
assert cmd.cmd_total_block_research(["--until", later]) == 0
out = capsys.readouterr().out
assert "extended until" in out
assert "extendable once" not in out
assert "the one extension" in out
record = window.read_record()
assert record is not None
assert (record.opened_at, record.until) == (first.opened_at, first.until)
assert record.extended_until == NOW + 30 * HOUR
again = datetime.fromtimestamp(NOW + 31 * HOUR, tz=UTC).isoformat()
assert cmd.cmd_total_block_research(["--until", again]) == 1
assert window.read_record() == record
def test_earlier_expiry_never_shortens(self) -> None:
"""Test that a rerun with an earlier time leaves the window alone."""
assert cmd.cmd_total_block_research(["--until", UNTIL]) == 0
first = window.read_record()
sooner = datetime.fromtimestamp(NOW + HOUR, tz=UTC).isoformat()
assert cmd.cmd_total_block_research(["--until", sooner]) == 1
assert window.read_record() == first
def test_no_active_block_is_refused(self, total_block_paths: Paths) -> None:

View File

@ -238,7 +238,7 @@ class TestEnforceTotalBlockLock:
assert (
frozenset({"status", "enforce", "gaming-status", "gaming-unblock", "serve"})
| {"total-block-refresh"} # reconciles the list; cannot shorten the lock
| {"total-block-research"} # <= 48 h, once per lock, Librarian only
| {"total-block-research"} # once per lock, Librarian only
== _TOTAL_BLOCK_EXEMPT_COMMANDS
)
assert "gaming-reset" not in _TOTAL_BLOCK_EXEMPT_COMMANDS

View File

@ -20,7 +20,7 @@ class TestExpiry:
record = window.read_record()
assert record is not None
assert record.closed is True
tm.block_tick.assert_called_once_with()
tm.block_tick.assert_called_once_with(keep_steam_dir=True)
tm.reconcile.assert_not_called()
def test_store_is_reblocked_once(self, tm: Mocks) -> None:
@ -79,5 +79,44 @@ class TestExpiry:
window.write_record(make_record())
with patch.object(window, "write_record", side_effect=OSError("ro")):
run_pass(NOW + 2 * HOUR)
tm.block_tick.assert_called_once_with()
tm.block_tick.assert_called_once_with(keep_steam_dir=True)
tm.reconcile.assert_not_called()
class TestAfterTheWindow:
"""The block returns without the purge, and no Steam game may run."""
def test_steam_folder_is_kept_for_the_rest_of_the_lock(self, tm: Mocks) -> None:
"""Test that every later tick also keeps the folder."""
window.write_record(make_record())
for later in (2 * HOUR, 3 * HOUR, 30 * HOUR):
run_pass(NOW + later)
assert [c.kwargs for c in tm.block_tick.call_args_list] == [
{"keep_steam_dir": True}
] * 3
def test_extended_window_expires_at_the_extension(self, tm: Mocks) -> None:
"""Test that the latch waits for the extended deadline."""
window.write_record(make_record(extended_until=NOW + 9 * HOUR))
run_pass(NOW + 4 * HOUR)
record = window.read_record()
assert record is not None
assert record.closed is False
run_pass(NOW + 9 * HOUR)
record = window.read_record()
assert record is not None
assert record.closed is True
tm.block_tick.assert_called_once_with(keep_steam_dir=True)
def test_any_steam_game_is_killed_once_the_window_is_over(self, tm: Mocks) -> None:
"""Test that the kept install cannot be played outside the window."""
tm.enforce.return_value = [(4242, window.LIBRARIAN_APP_ID)]
window.write_record(make_record(closed=True, store_reblocked=True))
run_pass(NOW + 5 * HOUR)
tm.enforce.assert_called_once_with({0}, kill_unauthorized=True, strict=True)
tm.notify.assert_called_once()
def test_no_game_scan_when_no_window_was_ever_used(self, tm: Mocks) -> None:
"""Test that an untouched total block keeps its old behaviour."""
run_pass()
tm.enforce.assert_not_called()

View File

@ -1,7 +1,8 @@
"""Opening a research window: the 48 h cap, once per lock, fail closed."""
"""Opening a research window: up to the lock end, one extension, fail closed."""
from __future__ import annotations
from dataclasses import replace
from datetime import UTC, datetime
import os
import time
@ -58,14 +59,16 @@ class TestOpen:
assert (record.opened_at, record.until) == (NOW, NOW + 10 * HOUR)
assert (record.closed, record.store_reblocked) == (False, False)
def test_exactly_48_hours_is_allowed(self) -> None:
"""Test that the cap is inclusive."""
assert _open(48 * HOUR).until == NOW + 48 * HOUR
def test_up_to_the_lock_end_is_allowed(self) -> None:
"""Test that the only cap is the end of the lock (no 48 h limit)."""
record = _open(LOCK_END - NOW)
assert record.until == LOCK_END
assert record.until - record.opened_at > 48 * HOUR
def test_more_than_48_hours_is_refused(self) -> None:
"""Test that one second over the cap is refused and nothing written."""
with pytest.raises(window.ResearchRefusedError, match="48"):
_open(48 * HOUR + 1)
def test_one_second_past_the_lock_end_is_refused(self) -> None:
"""Test that the lock's end is a hard ceiling and nothing is written."""
with pytest.raises(window.ResearchRefusedError, match="end of the total"):
_open(LOCK_END - NOW + 1)
assert window.read_record() is None
@pytest.mark.parametrize("offset", [0.0, -1.0, -3 * HOUR])
@ -113,15 +116,64 @@ class TestNoLock:
@pytest.mark.usefixtures("live")
class TestOncePerLock:
"""One window per lock, however it ended; reruns never extend."""
"""One window per lock; the open one may be extended once, never more."""
def test_second_open_is_refused_and_changes_nothing(self) -> None:
"""Test that a rerun with a later expiry never extends the window."""
def test_extension_moves_only_the_deadline(self) -> None:
"""Test that a later expiry extends an open window, nothing else."""
first = _open(2 * HOUR)
extended = _open(40 * HOUR)
assert extended == replace(first, extended_until=NOW + 40 * HOUR)
assert window.read_record() == extended
def test_extension_up_to_the_lock_end(self) -> None:
"""Test that the extension may reach the lock end exactly."""
_open(2 * HOUR)
assert _open(LOCK_END - NOW).extended_until == LOCK_END
def test_extension_past_the_lock_end_is_refused(self) -> None:
"""Test that no extension goes beyond the lock, even by a second."""
first = _open(2 * HOUR)
with pytest.raises(window.ResearchRefusedError, match="end of the total"):
_open(LOCK_END - NOW + 1)
assert window.read_record() == first
@pytest.mark.parametrize("offset", [2 * HOUR, 2 * HOUR - 1, HOUR, 60.0])
def test_same_or_earlier_expiry_is_refused(self, offset: float) -> None:
"""Test that an extension can only make the window longer."""
first = _open(2 * HOUR)
before = store.RESEARCH_FILE.read_bytes()
with pytest.raises(window.ResearchRefusedError, match="already"):
_open(40 * HOUR)
with pytest.raises(window.ResearchRefusedError, match="later"):
_open(offset)
assert store.RESEARCH_FILE.read_bytes() == before
assert window.read_record() == first
def test_only_one_extension(self) -> None:
"""Test that the second extension is refused and changes nothing."""
_open(2 * HOUR)
_open(40 * HOUR)
before = store.RESEARCH_FILE.read_bytes()
with pytest.raises(window.ResearchRefusedError, match="once"):
_open(60 * HOUR)
assert store.RESEARCH_FILE.read_bytes() == before
def test_an_ended_window_cannot_be_extended(self) -> None:
"""Test that extending after the deadline would be a second window."""
_open(2 * HOUR)
with (
patch(NOW_PATCH, return_value=NOW + 3 * HOUR),
pytest.raises(window.ResearchRefusedError, match="already"),
):
window.open_research_window(_at(40 * HOUR))
def test_extension_write_failure_is_a_refusal(self) -> None:
"""Test that a failing write on extension is reported."""
first = _open(2 * HOUR)
with (
patch.object(window, "write_record", side_effect=OSError("ro")),
pytest.raises(window.ResearchRefusedError, match="write"),
):
_open(40 * HOUR)
assert window.read_record() == first
def test_used_window_stays_used_after_it_closed(self) -> None:
"""Test that an expired, latched window is not a free second window."""

View File

@ -0,0 +1,100 @@
"""The Steam folder survives the purge once a research window was used."""
from __future__ import annotations
import json
from typing import TYPE_CHECKING
from unittest.mock import patch
from steam_backlog_enforcer._total_block import enforce_total_block_tick
from steam_backlog_enforcer._total_block_purge import (
_remove_steam_remnants,
purge_steam_and_proton,
)
if TYPE_CHECKING:
from pathlib import Path
from steam_backlog_enforcer.tests._total_block_paths import Paths
PKG = "steam_backlog_enforcer._total_block_purge"
BLOCK = "steam_backlog_enforcer._total_block"
def _populate(paths: Paths) -> tuple[Path, Path, Path]:
"""Create the Steam folder (with a save), ~/.steam and ~/steam."""
save = paths.steam_dir / "steamapps" / "compatdata" / "4197610" / "save.dat"
save.parent.mkdir(parents=True)
save.write_text("progress", encoding="utf-8")
dot_steam, portable = paths.remnant_paths[0], paths.remnant_paths[1]
dot_steam.mkdir(parents=True)
portable.mkdir(parents=True)
return save, dot_steam, portable
class TestKeepSteamDir:
"""Only the Steam data folder is spared; every other remnant still goes."""
def test_default_purges_the_folder_too(self, total_block_paths: Paths) -> None:
"""Test that without research nothing changed."""
save, dot_steam, portable = _populate(total_block_paths)
removed = _remove_steam_remnants()
assert str(total_block_paths.steam_dir) in removed
assert not save.exists()
assert not dot_steam.exists()
assert not portable.exists()
def test_kept_folder_and_its_saves_survive(self, total_block_paths: Paths) -> None:
"""Test that the install and local saves are not touched."""
save, dot_steam, portable = _populate(total_block_paths)
removed = _remove_steam_remnants(keep_steam_dir=True)
assert str(total_block_paths.steam_dir) not in removed
assert save.read_text(encoding="utf-8") == "progress"
assert not dot_steam.exists()
assert not portable.exists()
def test_purge_passes_the_flag_and_logs_only_what_went(
self, total_block_paths: Paths
) -> None:
"""Test that the whole purge honours the flag and logs honestly."""
save, _, _ = _populate(total_block_paths)
with patch(f"{PKG}.is_package_installed", return_value=False):
purge_steam_and_proton(keep_steam_dir=True)
assert save.exists()
logged = json.loads(total_block_paths.purge_log_file.read_text("utf-8"))
assert str(total_block_paths.steam_dir) not in logged[0]["removed_paths"]
def test_default_purge_still_removes_the_folder(
self, total_block_paths: Paths
) -> None:
"""Test that the old call signature keeps its old behaviour."""
save, _, _ = _populate(total_block_paths)
with patch(f"{PKG}.is_package_installed", return_value=False):
purge_steam_and_proton()
assert not save.exists()
class TestTickPassesTheFlag:
"""enforce_total_block_tick is the only caller on the hot path."""
def _tick(self, **kwargs: bool) -> object:
with (
patch(f"{BLOCK}.kill_steam_and_launchers", return_value=[]),
patch(f"{BLOCK}.kill_processes_by_name", return_value=[]),
patch(f"{BLOCK}.is_steam_installed", return_value=False),
patch(f"{BLOCK}.apply_total_block_iptables", return_value=True),
patch(f"{BLOCK}.refresh_total_block_hosts", return_value=True),
patch(f"{BLOCK}.purge_steam_and_proton") as purge,
):
enforce_total_block_tick(**kwargs)
return purge
def test_default_purges_everything(self) -> None:
"""Test that the default is the full purge."""
purge = self._tick()
purge.assert_called_once_with(keep_steam_dir=False)
def test_keep_flag_reaches_the_purge(self) -> None:
"""Test that the research exemption reaches the purge."""
purge = self._tick(keep_steam_dir=True)
purge.assert_called_once_with(keep_steam_dir=True)

View File

@ -25,6 +25,7 @@ def _raw(**changes: object) -> str:
"until": NOW + HOUR,
"closed": False,
"store_reblocked": False,
"extended_until": None,
}
for key, value in changes.items():
if value is None:
@ -66,9 +67,14 @@ class TestParse:
_raw(lock_until=LOCK_START),
_raw(until=LOCK_END + 1),
_raw(opened_at=LOCK_END - HOUR, until=LOCK_END + HOUR),
_raw(until=NOW - 60 + 48 * HOUR + 2),
_raw(closed="yes"),
_raw(store_reblocked=1),
_raw(extended_until="later"),
_raw(extended_until=True),
_raw(extended_until=float("nan")),
_raw(extended_until=NOW + HOUR),
_raw(extended_until=NOW),
_raw(extended_until=LOCK_END + 1),
],
)
def test_invalid_is_an_error(self, raw: str) -> None:
@ -76,10 +82,19 @@ class TestParse:
with pytest.raises(store.ResearchStateError):
store.parse_record(raw)
def test_exactly_48_hours_is_valid(self) -> None:
"""Test that the cap is inclusive."""
parsed = store.parse_record(_raw(until=NOW - 60 + 48 * HOUR))
assert parsed.until - parsed.opened_at == 48 * HOUR
def test_no_cap_but_the_lock_end(self) -> None:
"""Test that a window may run to the lock's end, however long."""
parsed = store.parse_record(_raw(until=LOCK_END))
assert parsed.until - parsed.opened_at > 48 * HOUR
def test_extension_roundtrip_and_old_records_have_none(self) -> None:
"""Test that extended_until survives and is absent in an old record."""
record = make_record(extended_until=LOCK_END)
assert store.parse_record(record.to_json()) == record
assert store.parse_record(_raw(extended_until=None)).extended_until is None
old = json.loads(_raw())
del old["extended_until"]
assert store.parse_record(json.dumps(old)).extended_until is None
class TestReadWrite:
@ -134,6 +149,17 @@ class TestIsOpen:
"""Test that a late clock is closed."""
assert not make_record().is_open(NOW + 5 * HOUR)
def test_extension_moves_the_deadline(self) -> None:
"""Test that an extended window is open past its first deadline."""
record = make_record(extended_until=NOW + 5 * HOUR)
assert record.ends_at == NOW + 5 * HOUR
assert record.is_open(NOW + 2 * HOUR)
assert not record.is_open(NOW + 5 * HOUR)
def test_without_extension_ends_at_until(self) -> None:
"""Test that ends_at is the plain deadline by default."""
assert make_record().ends_at == NOW + HOUR
def test_latch_wins_over_the_clock(self) -> None:
"""Test that a closed record stays closed even for an in-range clock."""
assert not make_record(closed=True).is_open(NOW)

View File

@ -19,7 +19,7 @@ class TestFullBlock:
def test_no_record_runs_the_full_tick(self, tm: Mocks) -> None:
"""Test that the default is the full block."""
run_pass()
tm.block_tick.assert_called_once_with()
tm.block_tick.assert_called_once_with(keep_steam_dir=False)
tm.reconcile.assert_not_called()
tm.enforce.assert_not_called()
@ -28,14 +28,14 @@ class TestFullBlock:
store.RESEARCH_FILE.parent.mkdir(parents=True)
store.RESEARCH_FILE.write_text("{oops", encoding="utf-8")
run_pass()
tm.block_tick.assert_called_once_with()
tm.block_tick.assert_called_once_with(keep_steam_dir=True)
tm.reconcile.assert_not_called()
def test_clock_before_opening_blocks_without_latching(self, tm: Mocks) -> None:
"""Test that a clock set back blocks, but does not burn the window."""
window.write_record(make_record())
run_pass(NOW - 3 * HOUR)
tm.block_tick.assert_called_once_with()
tm.block_tick.assert_called_once_with(keep_steam_dir=True)
tm.reconcile.assert_not_called()
record = window.read_record()
assert record is not None
@ -45,13 +45,22 @@ class TestFullBlock:
"""Test that a finished window costs nothing but the block tick."""
window.write_record(make_record(closed=True, store_reblocked=True))
run_pass(NOW + 5 * HOUR)
tm.block_tick.assert_called_once_with()
tm.block_tick.assert_called_once_with(keep_steam_dir=True)
tm.restore_store.assert_not_called()
class TestOpenWindow:
"""Inside the window: Steam is left alone, everything but Librarian is not."""
def test_extended_window_stays_open_past_its_first_deadline(
self, tm: Mocks
) -> None:
"""Test that the extension keeps the research pass running."""
window.write_record(make_record(extended_until=NOW + 9 * HOUR))
run_pass(NOW + 4 * HOUR)
tm.reconcile.assert_called_once()
tm.block_tick.assert_not_called()
def test_reconciles_and_skips_the_full_block(self, tm: Mocks) -> None:
"""Test that the open window replaces the block tick."""
window.write_record(make_record())

View File

@ -7,6 +7,8 @@ import logging
from typing import TYPE_CHECKING
from unittest.mock import patch
import pytest
from steam_backlog_enforcer import _research_record as store
from steam_backlog_enforcer import _research_window as window
from steam_backlog_enforcer.tests._research_helpers import (
@ -19,8 +21,6 @@ from steam_backlog_enforcer.tests._research_helpers import (
)
if TYPE_CHECKING:
import pytest
from steam_backlog_enforcer.tests._total_block_paths import Paths
NOW_PATCH = "steam_backlog_enforcer._research_window.now"
@ -143,3 +143,46 @@ class TestOpenNow:
with patch("steam_backlog_enforcer._research_window.time.time") as clock:
clock.return_value = 42.5
assert window.now() == 42.5
class TestResearchUsed:
"""research_used decides whether the Steam folder may be purged."""
@staticmethod
def _used() -> bool:
with patch(NOW_PATCH, return_value=NOW):
return window.research_used()
def test_never_used(self, total_block_paths: Paths) -> None:
"""Test that a lock without a record purges as before."""
lock(total_block_paths)
assert self._used() is False
def test_no_lock(self) -> None:
"""Test that without a total block nothing is kept on its account."""
window.write_record(make_record())
assert self._used() is False
@pytest.mark.parametrize("closed", [False, True])
def test_used_for_this_lock(
self, total_block_paths: Paths, *, closed: bool
) -> None:
"""Test that an open or ended window both protect the Steam folder."""
lock(total_block_paths)
window.write_record(make_record(closed=closed))
assert self._used() is True
def test_other_locks_record_does_not_protect(
self, total_block_paths: Paths
) -> None:
"""Test that last lock's window gives this lock no exemption."""
lock(total_block_paths)
window.write_record(make_record(lock_started_at=LOCK_START - 99.0))
assert self._used() is False
def test_unreadable_record_keeps_the_data(self, total_block_paths: Paths) -> None:
"""Test that when the record cannot say, nothing irreversible happens."""
lock(total_block_paths)
store.RESEARCH_FILE.parent.mkdir(parents=True)
store.RESEARCH_FILE.write_text("{oops", encoding="utf-8")
assert self._used() is True

View File

@ -45,9 +45,18 @@ class TestSteamAPIClient:
"""A burst past the per-second budget makes the client sleep."""
client = SteamAPIClient("key", "id")
client.session.get = MagicMock(return_value=_owned_response())
with patch(
"steam_backlog_enforcer._steam_api_client.time.sleep",
) as mock_sleep:
# Only sleeping advances this clock: no busy-wait for a real second.
clock = [1000.0]
with (
patch(
"steam_backlog_enforcer._steam_api_client.time.time",
side_effect=lambda: clock[-1],
),
patch(
"steam_backlog_enforcer._steam_api_client.time.sleep",
side_effect=lambda seconds: clock.append(clock[-1] + seconds),
) as mock_sleep,
):
# Keep requesting until the window fills and the throttle kicks in.
for _ in range(_BURST_LIMIT):
client.get_owned_games()

View File

@ -26,7 +26,9 @@ _DATASET_PKG = "steam_backlog_enforcer._web_dataset"
def _running() -> Iterator[int]:
"""Start the server on an ephemeral port in a thread; yield the port."""
server = create_server("127.0.0.1", 0)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread = threading.Thread(
target=server.serve_forever, kwargs={"poll_interval": 0.01}, daemon=True
)
thread.start()
try:
yield server.server_address[1]

View File

@ -188,7 +188,9 @@ def _serve(status: int, body: bytes) -> Iterator[str]:
self.wfile.write(body)
server = ThreadingHTTPServer(("127.0.0.1", 0), _Handler)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread = threading.Thread(
target=server.serve_forever, kwargs={"poll_interval": 0.01}, daemon=True
)
thread.start()
try:
yield f"http://127.0.0.1:{server.server_address[1]}/api/status"