earned_time 0.18.0: a LeetCode bonus needs the day paid in full; gate_off lets one solve earn on a stood-down day

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Krzysztof Rudnicki 2026-10-24 13:13:23 +02:00
parent 29ea6e2c50
commit fc2014d01d
7 changed files with 178 additions and 12 deletions

View File

@ -10,7 +10,7 @@ gaming time and shutdown time, read by both consumers.
A gate (leetcode-guard, book-guard, anki-guard, screen-locker's workout
credit, ...) never touches either. It publishes a fact — HMAC-signed `credit`
rows in its ledger — and is registered here once. LeetCode also counts its signed `source == "leetcode"` `charge` for the day (0.17.0, `ROW_KINDS`): a day paid ahead from banked credits earns like a solve; escape and outage charges never do.
rows in its ledger — and is registered here once. LeetCode also counts its signed `source == "leetcode"` `charge` for the day (0.17.0, `ROW_KINDS`): a day paid ahead from banked credits earns like a solve; escape and outage charges never do. Since 0.18.0 that charge is the *only* LeetCode row that earns while the gate is on: a credit is one unit of a price that may be 5, so one solve on a 5-credit day earns nothing. A consumer passes `gate_off=True` (live: a free day, or a sick day not keeping `leetcode`) to `done_today` / `first_credit_at` / `credit_units`, and then one verified solve earns again (`PAID_DAY_KINDS`).
## The model
@ -243,7 +243,7 @@ on the day itself is logged and does not count.
## Install
```console
pip install --user --break-system-packages --no-deps "earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.17.0#subdirectory=earned_time"
pip install --user --break-system-packages --no-deps "earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.18.0#subdirectory=earned_time"
```
The root `steam-backlog-enforcer.service` sets `HOME=/home/kuhy`, so it imports

View File

@ -61,7 +61,12 @@ def credit_time(earner: Earner, row: dict[str, object]) -> float | None:
def first_credit_at(
earner: Earner, ledger: Path, key_file: Path, day: date
earner: Earner,
ledger: Path,
key_file: Path,
day: date,
*,
gate_off: bool = False,
) -> float | None:
"""When ``earner``'s first verified credit that counts for ``day`` happened.
@ -70,6 +75,7 @@ def first_credit_at(
ledger: The gate's ledger file, resolved by the caller.
key_file: The shared HMAC key, resolved by the caller.
day: The local day the credit must count for (by ``match``).
gate_off: Whether the gate is off on ``day`` (``counting_rows``).
Returns:
The earliest :func:`credit_time` among the counting rows, as unix
@ -79,7 +85,7 @@ def first_credit_at(
Raises:
ValueError: ``earner`` has no ``match``; its answer is the consumer's.
"""
rows = counting_rows(earner, ledger, key_file, day_window(day))
rows = counting_rows(earner, ledger, key_file, day_window(day), gate_off=gate_off)
if rows is None:
return None
times = [t for t in (credit_time(earner, row) for row in rows) if t is not None]
@ -96,7 +102,14 @@ def row_units(earner: Earner, row: dict[str, object]) -> int:
return 1 if reader is None else reader(row) or 0
def credit_units(earner: Earner, ledger: Path, key_file: Path, day: date) -> int | None:
def credit_units(
earner: Earner,
ledger: Path,
key_file: Path,
day: date,
*,
gate_off: bool = False,
) -> int | None:
"""How many units the verified credit rows pay for ``day``.
Each row pays :func:`row_units`: 1 for most earners (the workout), its
@ -111,6 +124,7 @@ def credit_units(earner: Earner, ledger: Path, key_file: Path, day: date) -> int
ledger: The gate's ledger file, resolved by the caller.
key_file: The shared HMAC key, resolved by the caller.
day: The local day the rows must count for (by ``match``).
gate_off: Whether the gate is off on ``day`` (``counting_rows``).
Returns:
The sum (``0`` included), or ``None`` when the ledger or key could
@ -122,7 +136,7 @@ def credit_units(earner: Earner, ledger: Path, key_file: Path, day: date) -> int
Raises:
ValueError: ``earner`` has no ``match``; its answer is the consumer's.
"""
rows = counting_rows(earner, ledger, key_file, day_window(day))
rows = counting_rows(earner, ledger, key_file, day_window(day), gate_off=gate_off)
if rows is None:
return None
by_id: dict[object, int] = {}

View File

@ -35,7 +35,7 @@ if TYPE_CHECKING:
from earned_time._policy import Earner, Window
from earned_time._match import ROW_KINDS
from earned_time._match import PAID_DAY_KINDS, ROW_KINDS
_logger: Final = logging.getLogger(__name__)
@ -119,11 +119,19 @@ def read_rows(ledger: Path, earner: Earner) -> list[object] | None:
def counting_rows(
earner: Earner, ledger: Path, key_file: Path, window: Window
earner: Earner,
ledger: Path,
key_file: Path,
window: Window,
*,
gate_off: bool = False,
) -> Iterator[dict[str, object]] | None:
"""The verified rows that ``earner.match`` counts in ``window``.
``credit`` rows, plus whatever else ``ROW_KINDS`` shows that matcher.
``credit`` rows, plus whatever else ``ROW_KINDS`` shows that matcher --
narrowed to ``PAID_DAY_KINDS`` unless the consumer says the gate is off
today. ``gate_off`` defaults to False so a caller that forgets it fails
closed: no bonus for a part-paid day.
``None`` when the key or the ledger cannot be read.
@ -141,6 +149,8 @@ def counting_rows(
return None
match = earner.match
kinds = ROW_KINDS.get(match, _CREDIT_ONLY)
if not gate_off:
kinds = PAID_DAY_KINDS.get(match, kinds)
return (
row
for row in rows
@ -157,6 +167,7 @@ def done_today(
key_file: Path,
*,
now: datetime | None = None,
gate_off: bool = False,
) -> bool | None:
"""Whether ``earner``'s ledger holds a verified credit that counts today.
@ -165,6 +176,8 @@ def done_today(
ledger: The gate's ledger file, resolved by the caller.
key_file: The shared HMAC key, resolved by the caller.
now: Stand-in for the current time, for tests.
gate_off: The consumer's live answer to "is this gate off today?"
(see :func:`counting_rows`). Never read from a ledger.
Returns:
True or False when the ledger could be read and verified, ``None``
@ -173,7 +186,7 @@ def done_today(
Raises:
ValueError: ``earner`` has no ``match``; its answer is the consumer's.
"""
rows = counting_rows(earner, ledger, key_file, today_window(now))
rows = counting_rows(earner, ledger, key_file, today_window(now), gate_off=gate_off)
if rows is None:
return None
return any(True for _ in rows)

View File

@ -191,3 +191,12 @@ ROW_UNITS: Final[Mapping[CreditMatch, Callable[[dict[str, object]], int | None]]
ROW_KINDS: Final[Mapping[CreditMatch, frozenset[str]]] = MappingProxyType(
{leetcode_match: frozenset({"credit", "charge"})}
)
# The narrower kinds a matcher is shown while its gate is on (0.18.0). A
# LeetCode credit is one unit of a price that may be 5, so while the gate
# gates only the charge it writes once the price is covered earns (kuhy,
# 2026-10-24: one solve on a 5-credit day paid the whole bonus). The
# consumer passes ``gate_off`` live on a free or stood-down sick day, when
# there is no price, and the ``ROW_KINDS`` view applies again.
PAID_DAY_KINDS: Final[Mapping[CreditMatch, frozenset[str]]] = MappingProxyType(
{leetcode_match: frozenset({"charge"})}
)

View File

@ -94,7 +94,9 @@ def test_unreadable_ledger(tmp_path: Path) -> None:
def test_done_today(tmp_path: Path, key_file: Path) -> None:
good = _signed({"kind": "credit", "detail": {"submitted_at": INSIDE}})
path = _ledger(tmp_path, [good])
assert done_today(LEETCODE, path, key_file, now=NOON) is True
# A bare credit earns only while the gate is off (0.18.0,
# test_paid_day_only.py); the reader itself is what this pins.
assert done_today(LEETCODE, path, key_file, now=NOON, gate_off=True) is True
def test_not_done_today(tmp_path: Path, key_file: Path) -> None:

View File

@ -0,0 +1,128 @@
# Copyright (c) 2026 Krzysztof Rudnicki
"""A LeetCode bonus needs the day paid in full, not one solve (0.18.0).
kuhy, 2026-10-24: Saturday cost 5 credits (4 + 1 debt), one problem was
solved, and both the +1 h shutdown and the +1 h gaming paid anyway. A credit
row is one unit of the day's price; only the signed ``charge`` leetcode-guard
writes once verified credits cover the price says the day was done.
On a day the gate stands down (a free day, or a sick day that does not keep
``leetcode``) there is no price and no charge, so one verified solve still
earns -- but only when the consumer says so live (``gate_off``). It is never
ledger state: a marker written during a two-minute sick claim would outlive
the claim being cleared.
"""
from __future__ import annotations
from datetime import UTC, datetime
import json
from typing import TYPE_CHECKING
import pytest
from earned_time import (
LEETCODE,
READING,
credit_units,
done_today,
entry_signature,
first_credit_at,
)
if TYPE_CHECKING:
from pathlib import Path
KEY = b"test-key"
NOON = datetime(2026, 10, 24, 12, tzinfo=UTC)
TODAY = NOON.astimezone().date()
SOLVED_AT = NOON.timestamp() - 3600
CHARGED_AT = "2026-10-24T11:30:00+00:00"
def _signed(row: dict[str, object]) -> dict[str, object]:
return {**row, "hmac": entry_signature(row, KEY)}
def _credit() -> dict[str, object]:
return _signed(
{
"entry_id": "ac:1",
"kind": "credit",
"day": TODAY.isoformat(),
"created_at": "2026-10-24T11:10:00+00:00",
"amount": 1,
"detail": {"source": "leetcode", "submitted_at": str(int(SOLVED_AT))},
}
)
def _charge(source: str = "leetcode") -> dict[str, object]:
return _signed(
{
"entry_id": f"charge:{TODAY.isoformat()}",
"kind": "charge",
"day": TODAY.isoformat(),
"created_at": CHARGED_AT,
"amount": 5,
"detail": {"source": source},
}
)
@pytest.fixture
def key_file(tmp_path: Path) -> Path:
path = tmp_path / "hmac.key"
path.write_bytes(KEY)
return path
def _ledger(tmp_path: Path, rows: list[object]) -> Path:
path = tmp_path / "ledger.json"
path.write_text(json.dumps({"entries": rows}), encoding="utf-8")
return path
def test_one_solve_on_an_unpaid_day_earns_nothing(
tmp_path: Path, key_file: Path
) -> None:
path = _ledger(tmp_path, [_credit()])
assert done_today(LEETCODE, path, key_file, now=NOON) is False
assert first_credit_at(LEETCODE, path, key_file, TODAY) is None
assert credit_units(LEETCODE, path, key_file, TODAY) == 0
def test_the_paid_day_earns_from_its_charge(tmp_path: Path, key_file: Path) -> None:
path = _ledger(tmp_path, [_credit(), _charge()])
assert done_today(LEETCODE, path, key_file, now=NOON) is True
expected = datetime.fromisoformat(CHARGED_AT).timestamp()
assert first_credit_at(LEETCODE, path, key_file, TODAY) == expected
@pytest.mark.parametrize("source", ["escape", "leetcode-outage"])
def test_a_forgiven_day_earns_nothing_even_with_a_solve(
tmp_path: Path, key_file: Path, source: str
) -> None:
path = _ledger(tmp_path, [_credit(), _charge(source)])
assert done_today(LEETCODE, path, key_file, now=NOON) is False
def test_a_solve_earns_while_the_gate_is_off(tmp_path: Path, key_file: Path) -> None:
path = _ledger(tmp_path, [_credit()])
assert done_today(LEETCODE, path, key_file, now=NOON, gate_off=True) is True
assert first_credit_at(LEETCODE, path, key_file, TODAY, gate_off=True) == (
SOLVED_AT
)
assert credit_units(LEETCODE, path, key_file, TODAY, gate_off=True) == 1
def test_the_gate_being_off_is_not_a_solve(tmp_path: Path, key_file: Path) -> None:
path = _ledger(tmp_path, [_charge("escape")])
assert done_today(LEETCODE, path, key_file, now=NOON, gate_off=True) is False
def test_gate_off_changes_nothing_for_other_earners(
tmp_path: Path, key_file: Path
) -> None:
path = _ledger(tmp_path, [_charge()])
assert done_today(READING, path, key_file, now=NOON, gate_off=True) is False

View File

@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "earned-time"
version = "0.17.0"
version = "0.18.0"
description = "Penalty-then-reward registry: what every gate app earns in gaming time and shutdown time"
requires-python = ">=3.14"
dependencies = []