Write a progress row with each review credit
Some checks are pending
earned_time pre-commit / pre-commit (push) Waiting to run
earned_time tests / test (push) Waiting to run
file length / file-length (push) Waiting to run
gatelock tests / test (push) Waiting to run
kuhy_credit drift / drift (push) Waiting to run
leetcode-coach pre-commit / pre-commit (push) Waiting to run
leetcode-coach tests / test (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
palette drift / palette (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
shared gate tests / gate unit tests (push) Waiting to run

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWZLyjnLjB1THD6ckou
This commit is contained in:
Krzysztof Rudnicki 2026-11-22 18:48:30 +01:00
parent 80f0ca13ca
commit 77827e9abb
7 changed files with 372 additions and 45 deletions

View File

@ -92,7 +92,11 @@ and +10 days), `cluster_progress()`, `next_new(...)`, `cluster_of(slug)`. A
(`DOCS-review.md`). `review-finish` takes only a slug the guard flags now and
writes one signed row per slug to
`~/.local/share/leetcode-coach/review_ledger.json` (`review_ledger.record`),
then the `review` event. It never touches the guard's ledger.
then the `review` event. It never touches the guard's ledger. Each credit row
is written with a `progress` row ("done N of target M", source `review`) in
the same rename: the target is the number of flagged solves when the day's
first review is finished and stays frozen that day, `done` is the day's signed
review rows capped at it (`earned_time` 0.24.0 pays `bonus * done // target`).
**Toolbox + cards.** `toolbox.load_safe() -> Toolbox` (`.entries`,
`.properties`), `toolbox_cards.cards_for(names) -> [Card]` (property list ->

View File

@ -59,6 +59,10 @@ taught. You find the one cause, log it, and that starts the cold re-test clock
- exit 0, `review logged: ...` and `ledger row: written`: the solve is no
longer flagged, and the re-test falls due 3 and 10 days from today
(`leetcode --retest <slug>`).
The same write adds a `progress` row (`progress:<day>:<done>:<target>`),
so a review pays its share of the day's bonus: the target is how many
solves were flagged when that day's first review finished and does not
change after it.
- `refused: ...` (exit 1): the slug is not flagged or an argument is
wrong. Nothing was written.
- `could not check: ...` (exit 2): nothing was written. Tell kuhy; do not

View File

@ -103,13 +103,13 @@ def review_finish(problem: str, cause: str, module: str | None) -> int:
return _unchecked(exc, "; nothing written")
if slug not in reviewable:
return _refuse(f"{slug} is not flagged, {NOTHING}; nothing written")
return _record(slug, cause, module)
return _record(slug, cause, module, due=len(reviewable))
def _record(slug: str, cause: str, module: str | None) -> int:
"""Write the row, then the event, and say which of the two happened."""
def _record(slug: str, cause: str, module: str | None, *, due: int) -> int:
"""Write the rows, then the event, and say which of the two happened."""
try:
fresh = review_ledger.record(slug, cause)
fresh = review_ledger.record(slug, cause, due=due)
except review_ledger.LedgerError as exc:
_LOG.warning("review of %s not recorded: %s", slug, exc)
print(

View File

@ -12,6 +12,11 @@ the coach does not depend on ``earned_time``;
``test_earned_time_verifies_the_row_and_signs_it_the_same`` holds the two
together.
Every credit row is written with a ``progress`` row in the same rename
(`record`): the review's share of the day's bonus is ``done`` of ``target``
(``earned_time`` 0.24.0, DOCS-progress.md). The target is frozen at the day's
first review; the facts are read back from the signed rows, never stored apart.
Fail closed: without a readable key, or over a ledger file that does not
parse, `record` raises `LedgerError` and writes nothing. Each slug gets one row
ever. The write is a rename over the target, so a crash leaves the old file.
@ -39,6 +44,8 @@ VERSION: Final = 1
"""The guard ledger's ``_ledger_io._VERSION``."""
SOURCE: Final = "leetcode-coach-review"
ID_PREFIX: Final = "review:"
PROGRESS_SOURCE: Final = "review"
"""``earned_time``'s ``Earner.progress_source`` for the review top-up."""
class LedgerError(RuntimeError):
@ -99,29 +106,72 @@ def _write(entries: list[Any]) -> None:
raise LedgerError(msg) from exc
def record(slug: str, cause: str, *, now: datetime | None = None) -> bool:
"""Sign and append the row for one finished review.
def _signed(row: dict[str, Any], key: bytes) -> bool:
"""True when `row` carries the signature `entry_signature` gives it."""
claim = row.get("hmac")
return isinstance(claim, str) and hmac.compare_digest(
claim, entry_signature(row, key)
)
Args:
slug: The reviewed problem.
cause: The one named cause.
now: The finish time, timezone-aware (default: now, local time).
Returns:
True when the row was written, False when the slug already had one.
def _is_credit(row: dict[str, Any], day: str) -> bool:
detail = row.get("detail")
return (
row.get("kind") == "credit"
and row.get("day") == day
and isinstance(detail, dict)
and detail.get("source") == SOURCE
)
Raises:
LedgerError: no key, an unreadable ledger or a failed write; nothing
on disk changed.
"""
key = _key()
entries = _entries()
entry_id = ID_PREFIX + slug
if any(isinstance(e, dict) and e.get("entry_id") == entry_id for e in entries):
return False
moment = now or datetime.now(tz=UTC).astimezone()
row: dict[str, object] = {
"entry_id": entry_id,
def _fact(row: dict[str, Any], day: str) -> tuple[int, int] | None:
"""``(done, target)`` of a progress row about `day` for the review source."""
detail = row.get("detail")
if row.get("kind") != "progress" or not isinstance(detail, dict):
return None
done, target = detail.get("done"), detail.get("target")
if (
detail.get("source") != PROGRESS_SOURCE
or detail.get("for_day") != day
or not all(
isinstance(v, str) and v.isascii() and v.isdigit() for v in (done, target)
)
):
return None
return int(str(done)), int(str(target))
def _progress_row(
rows: list[Any], key: bytes, day: str, due: int, moment: datetime
) -> dict[str, object] | None:
"""The row that makes the day's facts true, or None when they already are."""
signed = [r for r in rows if isinstance(r, dict) and _signed(r, key)]
facts = [f for r in signed if (f := _fact(r, day)) is not None]
paid = sum(1 for r in signed if _is_credit(r, day))
target = facts[0][1] if facts else max(due, paid, 1)
state = (min(paid, target), target)
if facts and facts[-1] == state:
return None
done = state[0]
return {
"entry_id": f"progress:{day}:{done}:{target}",
"kind": "progress",
"day": day,
"created_at": moment.isoformat(),
"amount": 0,
"device": "pc",
"detail": {
"source": PROGRESS_SOURCE,
"for_day": day,
"done": str(done),
"target": str(target),
},
}
def _credit_row(slug: str, cause: str, moment: datetime) -> dict[str, object]:
return {
"entry_id": ID_PREFIX + slug,
"kind": "credit",
"day": moment.date().isoformat(),
"created_at": moment.isoformat(),
@ -134,6 +184,48 @@ def record(slug: str, cause: str, *, now: datetime | None = None) -> bool:
"finished_at": str(int(moment.timestamp())),
},
}
row["hmac"] = entry_signature(row, key)
_write([*entries, row])
return True
def record(slug: str, cause: str, *, due: int, now: datetime | None = None) -> bool:
"""Sign and append the rows for one finished review: credit plus progress.
The progress row says "``done`` of ``target`` reviews for the day": ``done``
is the day's signed review credits, capped at ``target``, which is `due`
at the day's first progress row and never changes after it. Nothing is
appended for a state the last progress row already says, and a slug that
has its credit still gets the progress row it lacks (rows written before
this writer existed), with ``max(due, credits)`` as the target.
Args:
slug: The reviewed problem.
cause: The one named cause.
due: How many reviews are due right now, this one included.
now: The finish time, timezone-aware (default: now, local time).
Returns:
True when the credit row was written, False when the slug already had
one.
Raises:
LedgerError: no key, an unreadable ledger or a failed write; nothing
on disk changed, so neither row exists without the other.
"""
key = _key()
entries = _entries()
moment = now or datetime.now(tz=UTC).astimezone()
entry_id = ID_PREFIX + slug
fresh = not any(
isinstance(e, dict) and e.get("entry_id") == entry_id for e in entries
)
new: list[dict[str, object]] = []
if fresh:
credit = _credit_row(slug, cause, moment)
credit["hmac"] = entry_signature(credit, key)
new.append(credit)
day = moment.date().isoformat()
if (tally := _progress_row([*entries, *new], key, day, due, moment)) is not None:
tally["hmac"] = entry_signature(tally, key)
new.append(tally)
if new:
_write([*entries, *new])
return fresh

View File

@ -73,11 +73,12 @@ def test_review_finish_logs_the_event_and_signs_a_row(
"cause": "missing-idea",
"module": "hashing",
}
(row,) = _rows()
row, tally = _rows()
assert (row["entry_id"], row["detail"]["cause"]) == (
"review:two-sum",
"missing-idea",
)
assert tally["entry_id"] == f"progress:{row['day']}:1:1"
assert progress.history("two-sum").solved == progress.local_today()
assert capsys.readouterr().out.splitlines() == [
"review logged: two-sum, cause missing-idea, module hashing",
@ -86,6 +87,20 @@ def test_review_finish_logs_the_event_and_signs_a_row(
]
def test_the_target_is_how_many_solves_are_flagged_when_the_review_is_finished(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
fake_guard(tmp_path, monkeypatch, "two-sum", "3sum", "lru-cache")
assert review_cli.main(["review-finish", "two-sum", "--cause", "debugging"]) == 0
fake_guard(tmp_path, monkeypatch, "3sum")
assert review_cli.main(["review-finish", "3sum", "--cause", "debugging"]) == 0
day = _rows()[0]["day"]
assert [r["entry_id"] for r in _rows() if r["kind"] == "progress"] == [
f"progress:{day}:1:3",
f"progress:{day}:2:3",
]
@pytest.mark.parametrize("cause", ["statement", "debugging", "interruption"])
def test_a_cause_without_a_card_is_only_recorded(
tmp_path: Path,
@ -196,10 +211,13 @@ def test_a_slug_with_a_row_gets_its_event_but_no_second_row(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
) -> None:
fake_guard(tmp_path, monkeypatch, "two-sum")
review_ledger.record("two-sum", "statement")
review_ledger.record("two-sum", "statement", due=1)
assert review_cli.main(["review-finish", "two-sum", "--cause", "debugging"]) == 0
assert [e["event"] for e in _events("two-sum")] == ["review"]
assert [r["detail"]["cause"] for r in _rows()] == ["statement"]
assert [r["detail"]["cause"] for r in _rows() if r["kind"] == "credit"] == [
"statement"
]
assert len(_rows()) == 2
assert "ledger row: already there, not written twice" in capsys.readouterr().out
@ -217,4 +235,4 @@ def test_a_lost_event_is_reported_as_exactly_that(
out = capsys.readouterr().out
assert out.startswith("ledger row written, review event NOT logged (")
assert "run the same command again" in out
assert len(_rows()) == 1
assert len(_rows()) == 2

View File

@ -64,11 +64,12 @@ def test_the_seams_point_away_from_the_real_machine(tmp_path: Path) -> None:
def test_a_finished_review_writes_one_signed_row_in_the_guard_layout() -> None:
assert review_ledger.record("two-sum", "idea-to-code", now=NOW) is True
assert review_ledger.record("two-sum", "idea-to-code", due=1, now=NOW) is True
data = _ledger()
assert list(data) == ["version", "entries"]
assert data["version"] == 1
(row,) = data["entries"]
row, progress = data["entries"]
assert progress["entry_id"] == "progress:2026-11-21:1:1"
signature = row.pop("hmac")
assert row == {
"entry_id": "review:two-sum",
@ -94,8 +95,8 @@ def test_earned_time_verifies_the_row_and_signs_it_the_same(
monkeypatch: pytest.MonkeyPatch,
) -> None:
earned_time = _earned_time(monkeypatch)
review_ledger.record("two-sum", "missing-idea", now=NOW)
(row,) = _ledger()["entries"]
review_ledger.record("two-sum", "missing-idea", due=1, now=NOW)
row, _progress = _ledger()["entries"]
assert earned_time.verified(row, REVIEW_KEY) is True
assert row["hmac"] == earned_time.entry_signature(row, REVIEW_KEY)
odd = {**GUARD_ROW, "detail": {"title_slug": "zażółć", "n": 1.5, "x": None}}
@ -108,8 +109,8 @@ def test_earned_time_verifies_the_row_and_signs_it_the_same(
def test_the_default_clock_is_local_time_with_an_offset() -> None:
review_ledger.record("two-sum", "debugging")
(row,) = _ledger()["entries"]
review_ledger.record("two-sum", "debugging", due=1)
row, _progress = _ledger()["entries"]
created = dt.datetime.fromisoformat(row["created_at"])
assert created.utcoffset() is not None
assert row["day"] == created.date().isoformat()
@ -117,12 +118,12 @@ def test_the_default_clock_is_local_time_with_an_offset() -> None:
def test_a_slug_is_never_written_twice() -> None:
assert review_ledger.record("two-sum", "debugging", now=NOW) is True
assert review_ledger.record("two-sum", "debugging", due=1, now=NOW) is True
before = review_ledger.LEDGER_PATH.read_bytes()
assert review_ledger.record("two-sum", "statement", now=NOW) is False
assert review_ledger.record("two-sum", "statement", due=1, now=NOW) is False
assert review_ledger.LEDGER_PATH.read_bytes() == before
assert review_ledger.record("3sum", "statement", now=NOW) is True
assert [e["entry_id"] for e in _ledger()["entries"]] == [
assert review_ledger.record("3sum", "statement", due=1, now=NOW) is True
assert [e["entry_id"] for e in _ledger()["entries"] if e["kind"] == "credit"] == [
"review:two-sum",
"review:3sum",
]
@ -135,7 +136,7 @@ def test_without_a_key_nothing_is_written(content: bytes | None) -> None:
else:
review_ledger.KEY_FILE.write_bytes(content)
with pytest.raises(review_ledger.LedgerError, match="signing key"):
review_ledger.record("two-sum", "debugging", now=NOW)
review_ledger.record("two-sum", "debugging", due=1, now=NOW)
assert not review_ledger.LEDGER_PATH.exists()
@ -144,7 +145,7 @@ def test_an_unreadable_ledger_is_never_overwritten(text: str) -> None:
review_ledger.LEDGER_PATH.parent.mkdir(parents=True)
review_ledger.LEDGER_PATH.write_bytes(text.encode("latin-1"))
with pytest.raises(review_ledger.LedgerError, match="not overwritten"):
review_ledger.record("two-sum", "debugging", now=NOW)
review_ledger.record("two-sum", "debugging", due=1, now=NOW)
assert review_ledger.LEDGER_PATH.read_bytes() == text.encode("latin-1")
@ -155,4 +156,4 @@ def test_a_failed_write_is_a_ledger_error(
blocker.write_text("x", encoding="utf-8")
monkeypatch.setattr(review_ledger, "LEDGER_PATH", blocker / "review_ledger.json")
with pytest.raises(review_ledger.LedgerError, match="cannot write"):
review_ledger.record("two-sum", "debugging", now=NOW)
review_ledger.record("two-sum", "debugging", due=1, now=NOW)

View File

@ -0,0 +1,208 @@
"""The progress row every review credit is written with (earned_time 0.24.0)."""
from __future__ import annotations
import datetime as dt
import importlib
import json
import logging
from pathlib import Path
import tempfile
from typing import TYPE_CHECKING, Any
import pytest
from leetcode_coach import review_ledger
from leetcode_coach.tests._review_support import REVIEW_KEY
if TYPE_CHECKING:
from types import ModuleType
TZ = dt.timezone(dt.timedelta(hours=1))
MONDAY = dt.datetime(2026, 11, 23, 9, 0, 0, tzinfo=TZ)
TUESDAY = dt.datetime(2026, 11, 24, 9, 0, 0, tzinfo=TZ)
REPO_ROOT = Path(__file__).resolve().parents[3]
def _rows() -> list[dict[str, Any]]:
data = json.loads(review_ledger.LEDGER_PATH.read_text(encoding="utf-8"))
rows: list[dict[str, Any]] = data["entries"]
return rows
def _ids() -> list[str]:
return [row["entry_id"] for row in _rows()]
def _progress_ids() -> list[str]:
return [i for i in _ids() if i.startswith("progress:")]
def _finish(slug: str, due: int, now: dt.datetime = MONDAY) -> bool:
return review_ledger.record(slug, "debugging", due=due, now=now)
def _signed(row: dict[str, object]) -> dict[str, object]:
return {**row, "hmac": review_ledger.entry_signature(row, REVIEW_KEY)}
def _foreign_progress(
source: str, target: str, day: str = "2026-11-23"
) -> dict[str, object]:
return {
"entry_id": f"progress:{day}:0:{target}",
"kind": "progress",
"day": day,
"created_at": f"{day}T08:00:00+01:00",
"amount": 0,
"device": "pc",
"detail": {"source": source, "for_day": day, "done": "0", "target": target},
}
def test_the_first_review_of_a_day_writes_its_credit_and_progress_one_of_due() -> None:
assert _finish("two-sum", due=3) is True
credit, progress = _rows()
assert credit["entry_id"] == "review:two-sum"
progress.pop("hmac")
assert progress == {
"entry_id": "progress:2026-11-23:1:3",
"kind": "progress",
"day": "2026-11-23",
"created_at": "2026-11-23T09:00:00+01:00",
"amount": 0,
"device": "pc",
"detail": {
"source": "review",
"for_day": "2026-11-23",
"done": "1",
"target": "3",
},
}
def test_the_second_review_reuses_the_frozen_target_whatever_is_due_now() -> None:
_finish("two-sum", due=3)
_finish("3sum", due=1)
assert _progress_ids() == ["progress:2026-11-23:1:3", "progress:2026-11-23:2:3"]
_finish("lru-cache", due=9)
assert _progress_ids()[-1] == "progress:2026-11-23:3:3"
def test_a_repeat_of_the_same_state_writes_nothing() -> None:
_finish("two-sum", due=3)
before = review_ledger.LEDGER_PATH.read_bytes()
assert _finish("two-sum", due=2) is False
assert review_ledger.LEDGER_PATH.read_bytes() == before
def test_done_is_capped_at_the_target_and_adds_no_row_past_it() -> None:
_finish("a", due=1)
_finish("b", due=1)
assert _progress_ids() == ["progress:2026-11-23:1:1"]
assert _ids().count("review:b") == 1
def test_a_new_day_freezes_its_own_target() -> None:
_finish("a", due=3)
_finish("b", due=3)
_finish("c", due=2, now=TUESDAY)
assert _progress_ids() == [
"progress:2026-11-23:1:3",
"progress:2026-11-23:2:3",
"progress:2026-11-24:1:2",
]
def test_a_credit_with_no_progress_gets_it_on_the_next_call() -> None:
"""Rows from before the progress writer: done counts them, target is due."""
credit = _signed(
{
"entry_id": "review:old",
"kind": "credit",
"day": "2026-11-23",
"created_at": "2026-11-23T08:00:00+01:00",
"amount": 1,
"device": "pc",
"detail": {
"title_slug": "old",
"cause": "statement",
"source": review_ledger.SOURCE,
"finished_at": "1",
},
}
)
review_ledger.LEDGER_PATH.parent.mkdir(parents=True)
review_ledger.LEDGER_PATH.write_text(
json.dumps({"version": 1, "entries": [credit]}), encoding="utf-8"
)
assert _finish("old", due=2) is False
assert _progress_ids() == ["progress:2026-11-23:1:2"]
_finish("new", due=1)
assert _progress_ids()[-1] == "progress:2026-11-23:2:2"
@pytest.mark.parametrize(
("source", "signed"),
[("review", False), ("workout", True), ("leetcode", True)],
)
def test_only_a_signed_review_progress_row_freezes_the_target(
source: str, *, signed: bool
) -> None:
other = _foreign_progress(source, "99")
row = _signed(other) if signed else {**other, "hmac": "0" * 64}
review_ledger.LEDGER_PATH.parent.mkdir(parents=True)
review_ledger.LEDGER_PATH.write_text(
json.dumps({"version": 1, "entries": [row]}), encoding="utf-8"
)
_finish("two-sum", due=3)
assert _progress_ids()[-1] == "progress:2026-11-23:1:3"
def test_every_row_verifies_with_earned_time_and_the_credit_comes_with_progress(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.syspath_prepend(str(REPO_ROOT / "earned_time"))
earned_time: ModuleType = importlib.import_module("earned_time")
_finish("a", due=2)
_finish("b", due=2)
rows = _rows()
assert [r["kind"] for r in rows] == ["credit", "progress", "credit", "progress"]
assert all(earned_time.verified(r, REVIEW_KEY) for r in rows)
assert all(r["hmac"] == earned_time.entry_signature(r, REVIEW_KEY) for r in rows)
assert all(isinstance(v, str) for r in rows[1::2] for v in r["detail"].values())
def test_a_failed_write_leaves_neither_row_and_is_logged_loudly(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
caplog: pytest.LogCaptureFixture,
) -> None:
blocker = tmp_path / "a-file"
blocker.write_text("x", encoding="utf-8")
monkeypatch.setattr(review_ledger, "LEDGER_PATH", blocker / "review_ledger.json")
with caplog.at_level(logging.WARNING), pytest.raises(review_ledger.LedgerError):
_finish("two-sum", due=3)
assert any(r.levelno >= logging.WARNING for r in caplog.records)
assert not (blocker / "review_ledger.json").exists()
def test_the_failed_second_review_leaves_the_first_pair_untouched(
monkeypatch: pytest.MonkeyPatch,
) -> None:
_finish("a", due=2)
before = review_ledger.LEDGER_PATH.read_bytes()
def boom(*_a: object, **_k: object) -> None:
raise OSError(28, "No space left on device")
monkeypatch.setattr(tempfile, "mkstemp", boom)
with pytest.raises(review_ledger.LedgerError):
_finish("b", due=2)
assert review_ledger.LEDGER_PATH.read_bytes() == before
@pytest.mark.parametrize("due", [-1, 0])
def test_a_first_review_with_nothing_due_still_gets_a_target_of_one(due: int) -> None:
_finish("two-sum", due=due)
assert _progress_ids() == ["progress:2026-11-23:1:1"]