Evening chain: settled LeetCode day not pending

A day closed by a non-paying charge (escape hatch, outage) never gets a
source=leetcode row, so its LeetCode gate could never be satisfied. The
rung is now pending only while payable: done_today false AND no
verified charge row for today, any source.

Failure paths: charge check unreadable (ledger, key, verify error) ->
rung unchecked -> pending exit 2 (FAIL CLOSED). An unsigned or old
charge never settles a day, so the gate still arms (closed). earned_time
has no public "any charge" helper, so the rows are read from the ledger
and checked with earned_time.verified.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWYGbnVt12uFXKgNYm8
This commit is contained in:
Krzysztof Rudnicki 2026-11-17 21:45:17 +01:00
parent 115e050110
commit b84a27eecf
6 changed files with 184 additions and 62 deletions

View File

@ -136,7 +136,9 @@ then LeetCode in front of night lockdown. Needs the `evening` extra
check (unreadable ledger or key, any exception; stderr says why) -- it
fails closed, so root enters lockdown. Reading and LeetCode use
`earned_time.done_today`; the tutor is quota-based
(`credit_units >= max_units`). Cheap: three small reads, root runs it
(`credit_units >= max_units`). The LeetCode rung is pending only while
payable: a day settled by any signed `charge:<day>` row (escape hatch,
outage) can never earn the bonus, so it is not listed. Cheap: three small reads, root runs it
every minute.
- `run` runs each unpaid rung's gate (`GATE_COMMANDS`, all `--production
--evening`) and re-checks before each. A gate's exit 10

View File

@ -9,6 +9,7 @@ from __future__ import annotations
from dataclasses import dataclass
from datetime import time
import json
import logging
from pathlib import Path
from typing import TYPE_CHECKING, Final, Protocol
@ -21,7 +22,7 @@ from gatelock.log_integrity import DEFAULT_HMAC_KEY_FILE
if TYPE_CHECKING:
from collections.abc import Mapping
from datetime import datetime
from datetime import date, datetime
class _Earner(Protocol):
@ -52,6 +53,7 @@ GATE_COMMANDS: Final[Mapping[str, tuple[str, ...]]] = {
"leetcode": (_PYTHON, "-m", "leetcode_guard", "--production", "--evening"),
}
TUTOR: Final = "tutor"
LEETCODE: Final = "leetcode"
# What a ledger read may raise; anything else is a bug and surfaces in main().
_CHECK_ERRORS: Final = (OSError, ValueError, TypeError, LookupError, RuntimeError)
@ -81,8 +83,33 @@ def production_sources() -> Sources:
return Sources(Path.home(), Path(DEFAULT_HMAC_KEY_FILE), None, None)
def _charged_today(ledger: Path, sources: Sources, day: date) -> bool:
"""Whether a verified ``charge`` row names ``day``, whatever its source.
A day settled by the escape hatch or a LeetCode outage carries a
non-paying charge, and the gate then writes no ``source=leetcode`` row, so
the rung can never be paid. earned_time has no public helper for "any
charge" (``done_today`` only sees the paying one), so this reads the rows
itself and trusts only signed ones. Raises OSError/ValueError when the
ledger or key cannot be read.
"""
key = sources.key_file.read_bytes().strip()
rows = json.loads(ledger.read_text(encoding="utf-8"))["entries"]
return any(
isinstance(row, dict)
and row.get("kind") == "charge"
and row.get("day") == day.isoformat()
and earned_time.verified(row, key)
for row in rows
)
def _paid(rung: str, earner: _Earner, sources: Sources, now: datetime) -> bool | None:
"""Whether ``rung`` is paid today; None when it could not be checked."""
"""Whether ``rung`` has nothing to run; None when it could not be checked.
The LeetCode rung also counts as settled on a day an unpaying charge
closed (see :func:`_charged_today`): it is not payable, so not pending.
"""
ledger = sources.home / earner.ledger
try:
if rung == TUTOR:
@ -94,7 +121,11 @@ def _paid(rung: str, earner: _Earner, sources: Sources, now: datetime) -> bool |
done = earned_time.done_today(
earner, ledger, sources.key_file, now=now, gate_off=False
)
return None if done is None else bool(done)
if done is None:
return None
if done or rung != LEETCODE:
return bool(done)
return _charged_today(ledger, sources, now.date())
except _CHECK_ERRORS:
_logger.exception("Could not check the %s rung", rung)
return None

View File

@ -0,0 +1,64 @@
# Copyright (c) 2026 Krzysztof Rudnicki
"""The chain's process edges: gate subprocesses, production paths, the unit."""
from __future__ import annotations
from pathlib import Path
import runpy
import subprocess
import sys
from types import SimpleNamespace
from unittest import mock
import pytest
from gatelock import evening_chain as chain
def test_subprocess_runner_returns_the_exit_code_with_the_timeout() -> None:
done = SimpleNamespace(returncode=7)
with mock.patch("gatelock.evening_chain.subprocess.run", return_value=done) as run:
assert chain.subprocess_runner(("gate", "--x"), 12.5) == 7
run.assert_called_once_with(("gate", "--x"), check=False, timeout=12.5)
def test_subprocess_runner_deadline_is_none() -> None:
expired = subprocess.TimeoutExpired(("gate",), 1)
with mock.patch("gatelock.evening_chain.subprocess.run", side_effect=expired):
assert chain.subprocess_runner(("gate",), 1) is None
def test_subprocess_runner_unstartable_gate_is_a_failure() -> None:
with mock.patch("gatelock.evening_chain.subprocess.run", side_effect=OSError):
assert chain.subprocess_runner(("gate",), 1) == 127
def test_production_sources_names_the_real_key_and_home() -> None:
sources = chain.production_sources()
assert str(sources.key_file) == "/etc/workout-locker/hmac.key"
assert sources.home == Path.home()
assert sources.free_log is None
assert sources.sick_log is None
def test_module_entry_point_rejects_an_unknown_command() -> None:
with (
pytest.warns(RuntimeWarning),
pytest.raises(SystemExit) as raised,
mock.patch.object(sys, "argv", ["evening_chain", "bogus"]),
):
runpy.run_module("gatelock.evening_chain", run_name="__main__")
assert raised.value.code == 2
UNIT = Path(__file__).parents[2] / "systemd" / "evening-gates.service"
def test_unit_matches_the_contract() -> None:
lines = UNIT.read_text(encoding="utf-8").splitlines()
assert "Type=simple" in lines
assert "Restart=no" in lines
assert "Environment=DISPLAY=:0" in lines
assert "Environment=XAUTHORITY=%h/.Xauthority" in lines
assert "ExecStart=/usr/bin/python3 -m gatelock.evening_chain run" in lines
assert "[Install]" not in lines

View File

@ -3,8 +3,11 @@
from __future__ import annotations
from datetime import timedelta
from typing import TYPE_CHECKING
import pytest
from gatelock import RANK_DIET_GUARD, RANK_SCREEN_LOCKER
from gatelock import evening_chain as chain
from gatelock._arbiter import RANK_EVENING_GATE
@ -17,6 +20,7 @@ from gatelock.tests.test_evening_rows import (
mark_sick,
pay_all,
seeded,
settled_row,
tutor_row,
write_ledger,
)
@ -25,8 +29,6 @@ if TYPE_CHECKING:
from datetime import datetime
from pathlib import Path
import pytest
def _run(sources: chain.Sources, now: datetime) -> tuple[int, str]:
out: list[str] = []
@ -162,3 +164,59 @@ def test_a_rung_the_registry_dropped_is_not_asked(
kept = tuple(e for e in earned_time.earners_for(DAY) if e.name != "reading")
monkeypatch.setattr("earned_time.earners_for", lambda _day: kept)
assert _run(sources, EVENING) == (0, "tutor leetcode")
@pytest.mark.parametrize("source", ["escape", "outage"])
def test_a_settled_leetcode_day_is_unpayable_so_not_pending(
tmp_path: Path, source: str
) -> None:
sources = seeded(tmp_path)
pay_all(sources)
write_ledger(sources, "leetcode", [settled_row(source)])
assert _run(sources, EVENING) == (1, "")
def test_a_settled_leetcode_day_leaves_the_other_rungs(tmp_path: Path) -> None:
sources = seeded(tmp_path)
write_ledger(sources, "reading", [])
write_ledger(sources, "tutor", [])
write_ledger(sources, "leetcode", [settled_row("escape")])
assert _run(sources, EVENING) == (0, "reading tutor")
def test_yesterdays_charge_does_not_settle_today(tmp_path: Path) -> None:
sources = seeded(tmp_path)
pay_all(sources)
yesterday = DAY - timedelta(days=1)
write_ledger(sources, "leetcode", [settled_row("escape", yesterday)])
assert _run(sources, EVENING) == (0, "leetcode")
def test_an_unsigned_charge_does_not_settle_the_day(tmp_path: Path) -> None:
sources = seeded(tmp_path)
pay_all(sources)
forged = {**settled_row("escape"), "hmac": "0" * 64}
write_ledger(sources, "leetcode", [forged])
assert _run(sources, EVENING) == (0, "leetcode")
def test_a_plain_unpaid_leetcode_day_is_still_pending(tmp_path: Path) -> None:
sources = seeded(tmp_path)
pay_all(sources)
write_ledger(sources, "leetcode", [])
assert _run(sources, EVENING) == (0, "leetcode")
def test_a_settled_check_that_cannot_verify_is_exit_2(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
sources = seeded(tmp_path)
pay_all(sources)
write_ledger(sources, "leetcode", [settled_row("escape")])
def boom(*_args: object) -> bool:
msg = "cannot verify"
raise ValueError(msg)
monkeypatch.setattr("earned_time.verified", boom)
assert _run(sources, EVENING) == (2, "")

View File

@ -55,6 +55,17 @@ def leetcode_row() -> dict[str, object]:
return _signed(row)
def settled_row(source: str, day: date = DAY) -> dict[str, object]:
"""A non-paying charge: the day settled by escape hatch or outage."""
row = {
"kind": "charge",
"entry_id": f"charge:{day.isoformat()}",
"day": day.isoformat(),
"detail": {"source": source},
}
return _signed(row)
def tutor_row(minutes: int) -> dict[str, object]:
"""``minutes`` of tutoring ending today."""
detail = {"minutes": minutes, "ended_at": stamp()}

View File

@ -7,14 +7,7 @@ from datetime import datetime, timedelta
import os
from pathlib import Path
import pwd
import runpy
import subprocess
import sys
from types import SimpleNamespace
from typing import TYPE_CHECKING
from unittest import mock
import pytest
from gatelock import evening_chain as chain
from gatelock.tests.test_evening_rows import (
@ -23,6 +16,7 @@ from gatelock.tests.test_evening_rows import (
pay_all,
reading_row,
seeded,
settled_row,
tutor_row,
write_ledger,
)
@ -30,6 +24,8 @@ from gatelock.tests.test_evening_rows import (
if TYPE_CHECKING:
from collections.abc import Callable, Sequence
import pytest
CMD_OF = {tuple(cmd): rung for rung, cmd in chain.GATE_COMMANDS.items()}
@ -174,24 +170,6 @@ def test_main_run_uses_the_injected_runner(tmp_path: Path) -> None:
assert gates.ran == []
def test_subprocess_runner_returns_the_exit_code_with_the_timeout() -> None:
done = SimpleNamespace(returncode=7)
with mock.patch("gatelock.evening_chain.subprocess.run", return_value=done) as run:
assert chain.subprocess_runner(("gate", "--x"), 12.5) == 7
run.assert_called_once_with(("gate", "--x"), check=False, timeout=12.5)
def test_subprocess_runner_deadline_is_none() -> None:
expired = subprocess.TimeoutExpired(("gate",), 1)
with mock.patch("gatelock.evening_chain.subprocess.run", side_effect=expired):
assert chain.subprocess_runner(("gate",), 1) is None
def test_subprocess_runner_unstartable_gate_is_a_failure() -> None:
with mock.patch("gatelock.evening_chain.subprocess.run", side_effect=OSError):
assert chain.subprocess_runner(("gate",), 1) == 127
def test_run_failing_to_evaluate_is_exit_1(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
@ -208,37 +186,6 @@ def test_run_failing_to_evaluate_is_exit_1(
assert gates.ran == []
def test_production_sources_names_the_real_key_and_home() -> None:
sources = chain.production_sources()
assert str(sources.key_file) == "/etc/workout-locker/hmac.key"
assert sources.home == Path.home()
assert sources.free_log is None
assert sources.sick_log is None
def test_module_entry_point_rejects_an_unknown_command() -> None:
with (
pytest.warns(RuntimeWarning),
pytest.raises(SystemExit) as raised,
mock.patch.object(sys, "argv", ["evening_chain", "bogus"]),
):
runpy.run_module("gatelock.evening_chain", run_name="__main__")
assert raised.value.code == 2
UNIT = Path(__file__).parents[2] / "systemd" / "evening-gates.service"
def test_unit_matches_the_contract() -> None:
lines = UNIT.read_text(encoding="utf-8").splitlines()
assert "Type=simple" in lines
assert "Restart=no" in lines
assert "Environment=DISPLAY=:0" in lines
assert "Environment=XAUTHORITY=%h/.Xauthority" in lines
assert "ExecStart=/usr/bin/python3 -m gatelock.evening_chain run" in lines
assert "[Install]" not in lines
def test_live_ledgers_are_untouched_by_a_run(tmp_path: Path) -> None:
home = Path(pwd.getpwuid(os.getuid()).pw_dir)
live = sorted((home / ".local" / "share").glob("*/ledger.json"))
@ -246,3 +193,12 @@ def test_live_ledgers_are_untouched_by_a_run(tmp_path: Path) -> None:
sources = seeded(tmp_path)
assert _run(sources, FakeGates(sources)) == 0
assert [(p, p.stat().st_mtime_ns) for p in live] == before
def test_a_settled_leetcode_day_never_runs_its_gate(tmp_path: Path) -> None:
sources = seeded(tmp_path)
pay_all(sources)
write_ledger(sources, "leetcode", [settled_row("outage")])
gates = FakeGates(sources)
assert _run(sources, gates) == 0
assert gates.ran == []