mirror of
https://github.com/kuhyx/utils.git
synced 2026-11-26 04:27:23 +01:00
Compare commits
4 Commits
ba4dd58545
...
22fdf2c344
| Author | SHA1 | Date | |
|---|---|---|---|
| 22fdf2c344 | |||
| de7d5d17eb | |||
| 640985a421 | |||
| 70c8aa8fbb |
@ -6,6 +6,24 @@ import json
|
|||||||
import math
|
import math
|
||||||
|
|
||||||
TOLERANCE = 1e-5 # LeetCode accepts floating answers within 1e-5
|
TOLERANCE = 1e-5 # LeetCode accepts floating answers within 1e-5
|
||||||
|
MAX_DEPTH = 64 # real answers nest a handful of levels; deeper is hostile
|
||||||
|
|
||||||
|
|
||||||
|
class TooDeepError(ValueError):
|
||||||
|
"""A compared value nests deeper than ``MAX_DEPTH``."""
|
||||||
|
|
||||||
|
|
||||||
|
def too_deep(value: object, limit: int = MAX_DEPTH) -> bool:
|
||||||
|
"""Whether ``value`` nests lists/dicts deeper than ``limit`` (iterative)."""
|
||||||
|
stack: list[tuple[object, int]] = [(value, 0)]
|
||||||
|
while stack:
|
||||||
|
node, depth = stack.pop()
|
||||||
|
if isinstance(node, list | dict):
|
||||||
|
if depth >= limit:
|
||||||
|
return True
|
||||||
|
children = node if isinstance(node, list) else node.values()
|
||||||
|
stack.extend((child, depth + 1) for child in children)
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
def _as_number(value: object) -> float | None:
|
def _as_number(value: object) -> float | None:
|
||||||
@ -55,7 +73,12 @@ def matches(expected: object, actual: object, order: str) -> bool:
|
|||||||
|
|
||||||
Raises:
|
Raises:
|
||||||
ValueError: ``order`` is none of those.
|
ValueError: ``order`` is none of those.
|
||||||
|
TooDeepError: a value nests deeper than ``MAX_DEPTH`` (the recursive
|
||||||
|
walks below would blow the stack).
|
||||||
"""
|
"""
|
||||||
|
if too_deep(expected) or too_deep(actual):
|
||||||
|
msg = f"value nested deeper than {MAX_DEPTH} levels"
|
||||||
|
raise TooDeepError(msg)
|
||||||
if order == "exact":
|
if order == "exact":
|
||||||
return _equal(expected, actual)
|
return _equal(expected, actual)
|
||||||
if order == "any":
|
if order == "any":
|
||||||
|
|||||||
@ -8,7 +8,7 @@ from pathlib import Path
|
|||||||
import stat
|
import stat
|
||||||
import tempfile
|
import tempfile
|
||||||
|
|
||||||
from code_runner._compare import matches
|
from code_runner._compare import TooDeepError, matches, too_deep
|
||||||
from code_runner._languages import Language, get_language
|
from code_runner._languages import Language, get_language
|
||||||
from code_runner._model import MAX_CAPTURE, CaseResult, Example, Limits
|
from code_runner._model import MAX_CAPTURE, CaseResult, Example, Limits
|
||||||
from code_runner._sandbox import BoxResult, execute
|
from code_runner._sandbox import BoxResult, execute
|
||||||
@ -16,6 +16,9 @@ from code_runner._starter import Entry, parse_starter
|
|||||||
|
|
||||||
Box = Callable[[list[str], Path, Limits, int, tuple[str, ...]], BoxResult]
|
Box = Callable[[list[str], Path, Limits, int, tuple[str, ...]], BoxResult]
|
||||||
_OUT_OF_MEMORY = ("out of memory", "allocation failed")
|
_OUT_OF_MEMORY = ("out of memory", "allocation failed")
|
||||||
|
_MAX_ERROR = 200
|
||||||
|
# Everything hostile JSON can raise on the host: deep nesting, huge numbers.
|
||||||
|
_HOSTILE = (ValueError, TypeError, RecursionError, MemoryError, OverflowError)
|
||||||
|
|
||||||
|
|
||||||
def _positional(example: Example, entry: Entry) -> list[object]:
|
def _positional(example: Example, entry: Entry) -> list[object]:
|
||||||
@ -41,9 +44,11 @@ def _read_result(scratch: Path) -> dict[str, object] | None:
|
|||||||
raw = handle.read(MAX_CAPTURE * 16)
|
raw = handle.read(MAX_CAPTURE * 16)
|
||||||
try:
|
try:
|
||||||
payload = json.loads(raw)
|
payload = json.loads(raw)
|
||||||
except ValueError:
|
except _HOSTILE: # ValueError, or RecursionError on "[" * 200000
|
||||||
return None
|
return None
|
||||||
return payload if isinstance(payload, dict) and "ok" in payload else None
|
if not isinstance(payload, dict) or "ok" not in payload:
|
||||||
|
return None
|
||||||
|
return None if too_deep(payload) else payload
|
||||||
|
|
||||||
|
|
||||||
def _crash(box: BoxResult) -> str:
|
def _crash(box: BoxResult) -> str:
|
||||||
@ -53,17 +58,25 @@ def _crash(box: BoxResult) -> str:
|
|||||||
return f"Crashed (exit {box.returncode})"
|
return f"Crashed (exit {box.returncode})"
|
||||||
|
|
||||||
|
|
||||||
|
def _took(ms: object, fallback: float) -> float:
|
||||||
|
if isinstance(ms, bool) or not isinstance(ms, int | float):
|
||||||
|
return fallback
|
||||||
|
try:
|
||||||
|
return float(ms)
|
||||||
|
except OverflowError: # an int too big for a float
|
||||||
|
return fallback
|
||||||
|
|
||||||
|
|
||||||
def _outcome(scratch: Path, box: BoxResult) -> tuple[object, str | None, float]:
|
def _outcome(scratch: Path, box: BoxResult) -> tuple[object, str | None, float]:
|
||||||
if box.timed_out:
|
if box.timed_out:
|
||||||
return None, "TimeLimitExceeded", box.elapsed_ms
|
return None, "TimeLimitExceeded", box.elapsed_ms
|
||||||
payload = _read_result(scratch)
|
payload = _read_result(scratch)
|
||||||
if payload is None:
|
if payload is None:
|
||||||
return None, _crash(box), box.elapsed_ms
|
return None, _crash(box), box.elapsed_ms
|
||||||
ms = payload.get("ms")
|
took = _took(payload.get("ms"), box.elapsed_ms)
|
||||||
took = float(ms) if isinstance(ms, int | float) else box.elapsed_ms
|
|
||||||
if payload["ok"] is True:
|
if payload["ok"] is True:
|
||||||
return payload.get("value"), None, took
|
return payload.get("value"), None, took
|
||||||
return None, str(payload.get("error", "Error")), took
|
return None, str(payload.get("error", "Error"))[:_MAX_ERROR], took
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
@ -95,7 +108,12 @@ def _case(job: _Job, example: Example) -> CaseResult:
|
|||||||
language.ro_binds(job.binary),
|
language.ro_binds(job.binary),
|
||||||
)
|
)
|
||||||
actual, error, ms = _outcome(scratch, done)
|
actual, error, ms = _outcome(scratch, done)
|
||||||
ok = error is None and matches(example.expected, actual, example.order)
|
ok = False
|
||||||
|
if error is None:
|
||||||
|
try:
|
||||||
|
ok = matches(example.expected, actual, example.order)
|
||||||
|
except (TooDeepError, RecursionError, MemoryError) as exc:
|
||||||
|
actual, error = None, f"InvalidResult: {type(exc).__name__}"
|
||||||
return CaseResult(
|
return CaseResult(
|
||||||
example.n, example.args, example.expected, actual, ok, done.stdout, error, ms
|
example.n, example.args, example.expected, actual, ok, done.stdout, error, ms
|
||||||
)
|
)
|
||||||
|
|||||||
@ -1,6 +1,6 @@
|
|||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from code_runner._compare import matches
|
from code_runner._compare import MAX_DEPTH, TooDeepError, matches, too_deep
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize(
|
@pytest.mark.parametrize(
|
||||||
@ -40,3 +40,26 @@ def test_matches(expected: object, actual: object, order: str, *, want: bool) ->
|
|||||||
def test_unknown_order_is_refused() -> None:
|
def test_unknown_order_is_refused() -> None:
|
||||||
with pytest.raises(ValueError, match="order"):
|
with pytest.raises(ValueError, match="order"):
|
||||||
matches(1, 1, "sideways")
|
matches(1, 1, "sideways")
|
||||||
|
|
||||||
|
|
||||||
|
def _nest(depth: int) -> object:
|
||||||
|
value: object = 1
|
||||||
|
for _ in range(depth):
|
||||||
|
value = [value]
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("order", ["exact", "any", "deep"])
|
||||||
|
def test_deep_nesting_is_refused_not_recursed(order: str) -> None:
|
||||||
|
deep = _nest(100_000) # would raise RecursionError in the recursive walks
|
||||||
|
with pytest.raises(TooDeepError):
|
||||||
|
matches(deep, deep, order)
|
||||||
|
with pytest.raises(TooDeepError):
|
||||||
|
matches(1, deep, order)
|
||||||
|
|
||||||
|
|
||||||
|
def test_nesting_up_to_the_limit_still_compares() -> None:
|
||||||
|
assert matches(_nest(MAX_DEPTH), _nest(MAX_DEPTH), "deep") is True
|
||||||
|
assert too_deep(_nest(MAX_DEPTH + 1)) is True
|
||||||
|
assert too_deep({"a": [{"b": _nest(MAX_DEPTH)}]}) is True
|
||||||
|
assert too_deep({"a": [{"b": 1}]}) is False
|
||||||
|
|||||||
@ -99,6 +99,49 @@ def test_result_file_variants() -> None:
|
|||||||
assert named.error == "KeyError: x"
|
assert named.error == "KeyError: x"
|
||||||
|
|
||||||
|
|
||||||
|
def test_hostile_result_files_cost_one_example_not_the_run() -> None:
|
||||||
|
hostile = {
|
||||||
|
"bomb": "[" * 200_000,
|
||||||
|
"deep": '{"ok": true, "value": ' + "[" * 5000 + "]" * 5000 + "}",
|
||||||
|
"huge_ms": '{"ok": true, "value": 1, "ms": 1' + "0" * 400 + "}",
|
||||||
|
"bool_ms": '{"ok": true, "value": 1, "ms": true}',
|
||||||
|
"long_error": '{"ok": false, "error": "' + "x" * 5000 + '"}',
|
||||||
|
}
|
||||||
|
results = {
|
||||||
|
name: _run(_fake(_box(), {"result.json": text}))
|
||||||
|
for name, text in hostile.items()
|
||||||
|
}
|
||||||
|
assert results["bomb"].error == "Crashed (exit 0)"
|
||||||
|
assert results["deep"].error == "Crashed (exit 0)"
|
||||||
|
assert (results["huge_ms"].ok, results["huge_ms"].ms) == (True, 7.0)
|
||||||
|
assert results["bool_ms"].ms == 7.0
|
||||||
|
assert len(results["long_error"].error) == 200
|
||||||
|
|
||||||
|
|
||||||
|
def test_too_deep_expected_or_actual_is_that_examples_error() -> None:
|
||||||
|
deep: object = 1
|
||||||
|
for _ in range(100):
|
||||||
|
deep = [deep]
|
||||||
|
files = {"result.json": '{"ok": true, "value": 1}'}
|
||||||
|
cases = [Example(1, {"a": 1}, deep), EXAMPLE]
|
||||||
|
results = run("python3", "", STARTER, cases, box=_fake(_box(), files))
|
||||||
|
assert (results[0].ok, results[0].actual) == (False, None)
|
||||||
|
assert results[0].error == "InvalidResult: TooDeepError"
|
||||||
|
assert results[1].ok is True # the run went on
|
||||||
|
|
||||||
|
|
||||||
|
def test_recursion_in_compare_is_that_examples_error(
|
||||||
|
monkeypatch: pytest.MonkeyPatch,
|
||||||
|
) -> None:
|
||||||
|
def boom(*args: object) -> bool:
|
||||||
|
raise RecursionError
|
||||||
|
|
||||||
|
monkeypatch.setattr("code_runner._run.matches", boom)
|
||||||
|
files = {"result.json": '{"ok": true, "value": 1}'}
|
||||||
|
result = _run(_fake(_box(), files))
|
||||||
|
assert result.error == "InvalidResult: RecursionError"
|
||||||
|
|
||||||
|
|
||||||
def test_unreadable_result_files_are_a_crash(tmp_path: Path) -> None:
|
def test_unreadable_result_files_are_a_crash(tmp_path: Path) -> None:
|
||||||
secret = tmp_path / "secret"
|
secret = tmp_path / "secret"
|
||||||
secret.write_text('{"ok": true, "value": "stolen"}')
|
secret.write_text('{"ok": true, "value": "stolen"}')
|
||||||
|
|||||||
@ -205,3 +205,23 @@ def test_unsupported_language_and_empty_examples() -> None:
|
|||||||
with pytest.raises(RunnerError, match="language"):
|
with pytest.raises(RunnerError, match="language"):
|
||||||
run("cobol", "", "", [])
|
run("cobol", "", "", [])
|
||||||
assert run("python3", "def f(a): pass\n", "def f(a):\n", []) == []
|
assert run("python3", "def f(a): pass\n", "def f(a):\n", []) == []
|
||||||
|
|
||||||
|
|
||||||
|
@needs_sandbox
|
||||||
|
def test_json_bomb_result_costs_that_example_only() -> None:
|
||||||
|
code = (
|
||||||
|
"import os\n"
|
||||||
|
"def f(a):\n"
|
||||||
|
" if a:\n"
|
||||||
|
" open('/work/result.json', 'w').write('[' * 200000)\n"
|
||||||
|
" os._exit(0)\n"
|
||||||
|
" return 1\n"
|
||||||
|
)
|
||||||
|
out = run(
|
||||||
|
"python3",
|
||||||
|
code,
|
||||||
|
"def f(a):\n",
|
||||||
|
[Example(1, {"a": 1}, 1), Example(2, {"a": 0}, 1)],
|
||||||
|
)
|
||||||
|
assert (out[0].ok, out[0].error) == (False, "Crashed (exit 0)")
|
||||||
|
assert out[1].ok is True
|
||||||
|
|||||||
@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|||||||
|
|
||||||
[project]
|
[project]
|
||||||
name = "code_runner"
|
name = "code_runner"
|
||||||
version = "0.1.0"
|
version = "0.1.1"
|
||||||
description = "Run a learner solution (Python, JavaScript, TypeScript) against a problem's examples in a bubblewrap sandbox"
|
description = "Run a learner solution (Python, JavaScript, TypeScript) against a problem's examples in a bubblewrap sandbox"
|
||||||
requires-python = ">=3.14"
|
requires-python = ">=3.14"
|
||||||
# Stdlib only on purpose: the tutor server imports it from the system python.
|
# Stdlib only on purpose: the tutor server imports it from the system python.
|
||||||
|
|||||||
@ -24,5 +24,15 @@ next project day; the bank never crosses the project's end. `minutes_for(day)` i
|
|||||||
capped pay figure, `status(day)["minutes"]` the real count (121/120) with `carried_in`,
|
capped pay figure, `status(day)["minutes"]` the real count (121/120) with `carried_in`,
|
||||||
`carry_out`, `own_minutes`, `counted_minutes`. Carry ledger rows: `<project>-<YYYYMMDD>-carry`
|
`carry_out`, `own_minutes`, `counted_minutes`. Carry ledger rows: `<project>-<YYYYMMDD>-carry`
|
||||||
(`detail.carry`), never over `daily_minutes` together with own rows.
|
(`detail.carry`), never over `daily_minutes` together with own rows.
|
||||||
|
Edits only ratchet (0.7.0): `update_project`/`apply_update(id, today=...)` never lowers
|
||||||
|
today's obligation. A lower `daily_minutes`/`unlock_minutes`, or a gate added to `replaces`,
|
||||||
|
on a started project holds from TOMORROW (a `history` row ends today with the old values,
|
||||||
|
`replaces_on(day)`/`daily_on`/`unlock_on` read it); a mixed edit defers as a whole. Raises,
|
||||||
|
gates removed and edits to a project that has not started hold from today.
|
||||||
|
`apply_update(...).effective_from` says which. `end` cannot be before today, so an edit never
|
||||||
|
uncovers today. A NEW project starting today may replace gates and set any targets: it is a
|
||||||
|
new obligation, not a reduction (but see the floor).
|
||||||
|
Floor (0.7.1, coordinator decision for kuhy): `daily_minutes >= 30 x replaced gates` (min 30; `book` = `reading`),
|
||||||
|
enforced on create and update (`daily_floor(replaces)`), so a day cannot be made cheap.
|
||||||
Open the work: `python3 -m focus_project.open [--no-site]` (tutor focus screen, `work_url`).
|
Open the work: `python3 -m focus_project.open [--no-site]` (tutor focus screen, `work_url`).
|
||||||
Install: `./install.sh` (stdlib only, editable user install for `/usr/bin/python3`).
|
Install: `./install.sh` (stdlib only, editable user install for `/usr/bin/python3`).
|
||||||
|
|||||||
@ -17,13 +17,14 @@ from __future__ import annotations
|
|||||||
from focus_project._api import (
|
from focus_project._api import (
|
||||||
active,
|
active,
|
||||||
create_project,
|
create_project,
|
||||||
|
daily_floor,
|
||||||
end_project,
|
end_project,
|
||||||
list_projects,
|
list_projects,
|
||||||
stands_down,
|
stands_down,
|
||||||
)
|
)
|
||||||
from focus_project._errors import RegistryError
|
from focus_project._errors import RegistryError
|
||||||
from focus_project._model import Limits, Project
|
from focus_project._model import Limits, Project
|
||||||
from focus_project._update import update_project
|
from focus_project._update import Update, apply_update, update_project
|
||||||
from focus_project.activity import record_activity
|
from focus_project.activity import record_activity
|
||||||
from focus_project.minutes import minutes_for
|
from focus_project.minutes import minutes_for
|
||||||
from focus_project.status import status
|
from focus_project.status import status
|
||||||
@ -32,8 +33,11 @@ __all__ = [
|
|||||||
"Limits",
|
"Limits",
|
||||||
"Project",
|
"Project",
|
||||||
"RegistryError",
|
"RegistryError",
|
||||||
|
"Update",
|
||||||
"active",
|
"active",
|
||||||
|
"apply_update",
|
||||||
"create_project",
|
"create_project",
|
||||||
|
"daily_floor",
|
||||||
"end_project",
|
"end_project",
|
||||||
"list_projects",
|
"list_projects",
|
||||||
"minutes_for",
|
"minutes_for",
|
||||||
|
|||||||
@ -17,6 +17,8 @@ from focus_project._model import GATES, Project, normalize_gate
|
|||||||
_LOG = logging.getLogger(__name__)
|
_LOG = logging.getLogger(__name__)
|
||||||
_ID = re.compile(r"[a-z0-9][a-z0-9-]*")
|
_ID = re.compile(r"[a-z0-9][a-z0-9-]*")
|
||||||
MAX_WORK_URL = 2000
|
MAX_WORK_URL = 2000
|
||||||
|
# A project must ask real work: the focus earner pays per minute of ``daily``.
|
||||||
|
MIN_DAILY_PER_GATE = 30
|
||||||
|
|
||||||
|
|
||||||
def list_projects() -> list[Project]:
|
def list_projects() -> list[Project]:
|
||||||
@ -46,7 +48,7 @@ def stands_down(gate: str, day: date) -> bool:
|
|||||||
"focus_project registry unreadable, gate %s stays on: %s", gate, exc
|
"focus_project registry unreadable, gate %s stays on: %s", gate, exc
|
||||||
)
|
)
|
||||||
return False
|
return False
|
||||||
return project is not None and project.replaces_gate(gate)
|
return project is not None and project.replaces_gate(gate, day)
|
||||||
|
|
||||||
|
|
||||||
def _validate_work_url(url: str) -> None:
|
def _validate_work_url(url: str) -> None:
|
||||||
@ -64,6 +66,11 @@ def _validate_work_url(url: str) -> None:
|
|||||||
raise ValueError(msg)
|
raise ValueError(msg)
|
||||||
|
|
||||||
|
|
||||||
|
def daily_floor(replaces: tuple[str, ...]) -> int:
|
||||||
|
"""The least ``daily_minutes`` a project replacing these gates may ask."""
|
||||||
|
return MIN_DAILY_PER_GATE * max(1, len(replaces))
|
||||||
|
|
||||||
|
|
||||||
def _validate(project: Project) -> None:
|
def _validate(project: Project) -> None:
|
||||||
_validate_work_url(project.work_url)
|
_validate_work_url(project.work_url)
|
||||||
if not _ID.fullmatch(project.id):
|
if not _ID.fullmatch(project.id):
|
||||||
@ -78,8 +85,12 @@ def _validate(project: Project) -> None:
|
|||||||
if not project.replaces or not set(project.replaces) <= GATES:
|
if not project.replaces or not set(project.replaces) <= GATES:
|
||||||
msg = f"replaces must be a non-empty subset of gates {sorted(GATES)}"
|
msg = f"replaces must be a non-empty subset of gates {sorted(GATES)}"
|
||||||
raise ValueError(msg)
|
raise ValueError(msg)
|
||||||
if project.daily_minutes <= 0:
|
floor = daily_floor(project.replaces)
|
||||||
msg = "daily_minutes must be positive"
|
if project.daily_minutes < floor:
|
||||||
|
msg = (
|
||||||
|
f"daily_minutes must be at least {floor} "
|
||||||
|
f"({MIN_DAILY_PER_GATE} per replaced gate)"
|
||||||
|
)
|
||||||
raise ValueError(msg)
|
raise ValueError(msg)
|
||||||
if not 0 <= project.unlock_minutes <= project.daily_minutes:
|
if not 0 <= project.unlock_minutes <= project.daily_minutes:
|
||||||
msg = "unlock_minutes must be within 0..daily_minutes"
|
msg = "unlock_minutes must be within 0..daily_minutes"
|
||||||
|
|||||||
@ -25,22 +25,29 @@ class Limits:
|
|||||||
until: date
|
until: date
|
||||||
daily_minutes: int
|
daily_minutes: int
|
||||||
unlock_minutes: int
|
unlock_minutes: int
|
||||||
|
# None = a row from before 0.7.0: the project's current gates apply.
|
||||||
|
replaces: tuple[str, ...] | None = None
|
||||||
|
|
||||||
def to_dict(self) -> dict[str, Any]:
|
def to_dict(self) -> dict[str, Any]:
|
||||||
"""The history row in projects.json."""
|
"""The history row in projects.json."""
|
||||||
return {
|
row: dict[str, Any] = {
|
||||||
"until": self.until.isoformat(),
|
"until": self.until.isoformat(),
|
||||||
"daily_minutes": self.daily_minutes,
|
"daily_minutes": self.daily_minutes,
|
||||||
"unlock_minutes": self.unlock_minutes,
|
"unlock_minutes": self.unlock_minutes,
|
||||||
}
|
}
|
||||||
|
if self.replaces is not None:
|
||||||
|
row["replaces"] = list(self.replaces)
|
||||||
|
return row
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def from_dict(cls, row: Any) -> Limits: # noqa: ANN401
|
def from_dict(cls, row: Any) -> Limits: # noqa: ANN401
|
||||||
"""Parse a history row (errors surface as RegistryError upstream)."""
|
"""Parse a history row (errors surface as RegistryError upstream)."""
|
||||||
|
gates = row.get("replaces")
|
||||||
return cls(
|
return cls(
|
||||||
until=date.fromisoformat(row["until"]),
|
until=date.fromisoformat(row["until"]),
|
||||||
daily_minutes=int(row["daily_minutes"]),
|
daily_minutes=int(row["daily_minutes"]),
|
||||||
unlock_minutes=int(row["unlock_minutes"]),
|
unlock_minutes=int(row["unlock_minutes"]),
|
||||||
|
replaces=None if gates is None else tuple(gates),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@ -77,6 +84,11 @@ class Project:
|
|||||||
past = self._limits_on(day)
|
past = self._limits_on(day)
|
||||||
return self.unlock_minutes if past is None else past.unlock_minutes
|
return self.unlock_minutes if past is None else past.unlock_minutes
|
||||||
|
|
||||||
|
def replaces_on(self, day: date) -> tuple[str, ...]:
|
||||||
|
"""The gates this project switched off on ``day``."""
|
||||||
|
past = self._limits_on(day)
|
||||||
|
return self.replaces if past is None or past.replaces is None else past.replaces
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def last_day(self) -> date:
|
def last_day(self) -> date:
|
||||||
"""The last active day: the early-end day if set, else ``end``."""
|
"""The last active day: the early-end day if set, else ``end``."""
|
||||||
@ -86,9 +98,9 @@ class Project:
|
|||||||
"""Whether this project is active on ``day``."""
|
"""Whether this project is active on ``day``."""
|
||||||
return self.start <= day <= self.last_day
|
return self.start <= day <= self.last_day
|
||||||
|
|
||||||
def replaces_gate(self, gate: str) -> bool:
|
def replaces_gate(self, gate: str, day: date) -> bool:
|
||||||
"""Whether this project switches ``gate`` off."""
|
"""Whether this project switches ``gate`` off on ``day``."""
|
||||||
return normalize_gate(gate) in self.replaces
|
return normalize_gate(gate) in self.replaces_on(day)
|
||||||
|
|
||||||
def to_dict(self) -> dict[str, Any]:
|
def to_dict(self) -> dict[str, Any]:
|
||||||
"""The projects.json row."""
|
"""The projects.json row."""
|
||||||
|
|||||||
@ -3,7 +3,7 @@
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from dataclasses import replace
|
from dataclasses import dataclass, replace
|
||||||
from datetime import date, timedelta
|
from datetime import date, timedelta
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
@ -27,7 +27,7 @@ _EDITABLE = frozenset(
|
|||||||
_TUPLES = ("subjects", "site_patterns")
|
_TUPLES = ("subjects", "site_patterns")
|
||||||
|
|
||||||
|
|
||||||
def _apply(project: Project, changes: dict[str, Any], today: date) -> Project:
|
def _apply(project: Project, changes: dict[str, Any], today: date) -> Update:
|
||||||
"""The edited project; ValueError for what an edit may not touch."""
|
"""The edited project; ValueError for what an edit may not touch."""
|
||||||
if project.ended_on is not None:
|
if project.ended_on is not None:
|
||||||
msg = f"project {project.id!r} ended on {project.ended_on}"
|
msg = f"project {project.id!r} ended on {project.ended_on}"
|
||||||
@ -50,37 +50,81 @@ def _apply(project: Project, changes: dict[str, Any], today: date) -> Project:
|
|||||||
if "end" in changes and changes["end"] < today:
|
if "end" in changes and changes["end"] < today:
|
||||||
msg = f"end {changes['end']} is in the past"
|
msg = f"end {changes['end']} is in the past"
|
||||||
raise ValueError(msg)
|
raise ValueError(msg)
|
||||||
edited = replace(project, **fields)
|
return _schedule(project, replace(project, **fields), today)
|
||||||
return _keep_past_limits(project, edited, today)
|
|
||||||
|
|
||||||
|
|
||||||
def _keep_past_limits(old: Project, new: Project, today: date) -> Project:
|
def _held(project: Project, day: date) -> Limits:
|
||||||
"""Freeze the old targets for the days before ``today`` if they changed."""
|
"""What held on ``day``: both targets and the replaced gates."""
|
||||||
changed = (old.daily_minutes, old.unlock_minutes) != (
|
return Limits(
|
||||||
|
day,
|
||||||
|
project.daily_on(day),
|
||||||
|
project.unlock_on(day),
|
||||||
|
project.replaces_on(day),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _reduces(held: Limits, new: Project) -> bool:
|
||||||
|
"""Whether ``new`` asks less than ``held``: lower target or a gate more."""
|
||||||
|
return (
|
||||||
|
new.daily_minutes < held.daily_minutes
|
||||||
|
or new.unlock_minutes < held.unlock_minutes
|
||||||
|
or not set(new.replaces) <= set(held.replaces or ())
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _schedule(old: Project, new: Project, today: date) -> Update:
|
||||||
|
"""Date the edit: a reduction of a started project waits for tomorrow.
|
||||||
|
|
||||||
|
A raise (or a project that has not started) applies from ``today``; the
|
||||||
|
days before keep what held. Anything that lowers a target or switches a
|
||||||
|
gate off defers the whole edit one day, so no edit can undo a lock or
|
||||||
|
cheapen the pay of a day already running.
|
||||||
|
"""
|
||||||
|
if (old.daily_minutes, old.unlock_minutes, old.replaces) == (
|
||||||
new.daily_minutes,
|
new.daily_minutes,
|
||||||
new.unlock_minutes,
|
new.unlock_minutes,
|
||||||
|
new.replaces,
|
||||||
|
):
|
||||||
|
return Update(new, today)
|
||||||
|
deferred = today >= old.start and _reduces(_held(old, today), new)
|
||||||
|
first = today + timedelta(days=1) if deferred else today
|
||||||
|
last = first - timedelta(days=1)
|
||||||
|
history = [h for h in old.history if h.until < first]
|
||||||
|
held = _held(old, last)
|
||||||
|
same = (held.daily_minutes, held.unlock_minutes, held.replaces) == (
|
||||||
|
new.daily_minutes,
|
||||||
|
new.unlock_minutes,
|
||||||
|
new.replaces,
|
||||||
)
|
)
|
||||||
cutoff = today - timedelta(days=1)
|
if last >= old.start and not same and not (history and history[-1].until == last):
|
||||||
if not changed or cutoff < old.start:
|
history.append(held)
|
||||||
return new
|
return Update(replace(new, history=tuple(history)), first)
|
||||||
if old.history and old.history[-1].until == cutoff:
|
|
||||||
return new
|
|
||||||
row = Limits(cutoff, old.daily_minutes, old.unlock_minutes)
|
|
||||||
return replace(new, history=(*old.history, row))
|
|
||||||
|
|
||||||
|
|
||||||
def update_project(
|
@dataclass(frozen=True)
|
||||||
|
class Update:
|
||||||
|
"""An edited project and the first day its new targets and gates hold."""
|
||||||
|
|
||||||
|
project: Project
|
||||||
|
effective_from: date
|
||||||
|
|
||||||
|
|
||||||
|
def apply_update(
|
||||||
project_id: str,
|
project_id: str,
|
||||||
*,
|
*,
|
||||||
today: date | None = None,
|
today: date | None = None,
|
||||||
**changes: Any, # noqa: ANN401
|
**changes: Any, # noqa: ANN401
|
||||||
) -> Project:
|
) -> Update:
|
||||||
"""Edit ``project_id``; ValueError on bad input, overlap or a past edit.
|
"""Edit ``project_id``; ValueError on bad input, overlap or a past edit.
|
||||||
|
|
||||||
Editable: name, start, end, replaces, daily_minutes, unlock_minutes,
|
Editable: name, start, end, replaces, daily_minutes, unlock_minutes,
|
||||||
subjects, site_patterns, work_url. A started project's start cannot move; changed
|
subjects, site_patterns, work_url. A started project's start cannot move.
|
||||||
minute targets apply from ``today`` (default: now) on, earlier days keep
|
An edit never lowers today's obligation (0.7.0): a lower daily or unlock
|
||||||
theirs. KeyError for an unknown id.
|
target, or a gate added to ``replaces``, holds from tomorrow, the earlier
|
||||||
|
days (today included) keep theirs. Raises, gates removed and edits to a
|
||||||
|
project that has not started hold from ``today`` (default: now). The
|
||||||
|
result says which: ``effective_from``. A mixed edit defers as a whole.
|
||||||
|
KeyError for an unknown id.
|
||||||
"""
|
"""
|
||||||
unknown = sorted(set(changes) - _EDITABLE)
|
unknown = sorted(set(changes) - _EDITABLE)
|
||||||
if unknown:
|
if unknown:
|
||||||
@ -92,7 +136,8 @@ def update_project(
|
|||||||
for i, project in enumerate(existing):
|
for i, project in enumerate(existing):
|
||||||
if project.id != project_id:
|
if project.id != project_id:
|
||||||
continue
|
continue
|
||||||
edited = _apply(project, changes, today)
|
done = _apply(project, changes, today)
|
||||||
|
edited = done.project
|
||||||
_validate(edited)
|
_validate(edited)
|
||||||
for other in existing:
|
for other in existing:
|
||||||
if other.id != project_id and (
|
if other.id != project_id and (
|
||||||
@ -102,5 +147,15 @@ def update_project(
|
|||||||
raise ValueError(msg)
|
raise ValueError(msg)
|
||||||
existing[i] = edited
|
existing[i] = edited
|
||||||
_store.write_all(existing)
|
_store.write_all(existing)
|
||||||
return edited
|
return done
|
||||||
raise KeyError(project_id)
|
raise KeyError(project_id)
|
||||||
|
|
||||||
|
|
||||||
|
def update_project(
|
||||||
|
project_id: str,
|
||||||
|
*,
|
||||||
|
today: date | None = None,
|
||||||
|
**changes: Any, # noqa: ANN401
|
||||||
|
) -> Project:
|
||||||
|
""":func:`apply_update` returning just the project."""
|
||||||
|
return apply_update(project_id, today=today, **changes).project
|
||||||
|
|||||||
@ -46,5 +46,5 @@ def status(day: date) -> dict[str, Any]:
|
|||||||
"daily_minutes": daily,
|
"daily_minutes": daily,
|
||||||
"unlock_minutes": project.unlock_on(day),
|
"unlock_minutes": project.unlock_on(day),
|
||||||
"ends": project.last_day.isoformat(),
|
"ends": project.last_day.isoformat(),
|
||||||
"replaces": list(project.replaces),
|
"replaces": list(project.replaces_on(day)),
|
||||||
}
|
}
|
||||||
|
|||||||
@ -130,13 +130,12 @@ def test_overlaps_never_double_count() -> None:
|
|||||||
|
|
||||||
|
|
||||||
def test_capped_at_daily_minutes() -> None:
|
def test_capped_at_daily_minutes() -> None:
|
||||||
project(daily=10)
|
project(daily=30)
|
||||||
events(
|
events(
|
||||||
("timer", "start", at(9)),
|
*(("tutor", "heartbeat", at(9, 5 * k)) for k in range(1, 9)),
|
||||||
("timer", "stop", at(9, 8)),
|
|
||||||
("tutor", "heartbeat", at(12)),
|
("tutor", "heartbeat", at(12)),
|
||||||
)
|
)
|
||||||
assert minutes.minutes_for(D1) == 10
|
assert minutes.minutes_for(D1) == 30
|
||||||
|
|
||||||
|
|
||||||
def test_other_day_and_other_project_events_ignored() -> None:
|
def test_other_day_and_other_project_events_ignored() -> None:
|
||||||
|
|||||||
@ -78,8 +78,13 @@ def test_unknown_id_and_field() -> None:
|
|||||||
({"replaces": ["workout"]}, "gate"),
|
({"replaces": ["workout"]}, "gate"),
|
||||||
({"replaces": []}, "replace"),
|
({"replaces": []}, "replace"),
|
||||||
({"daily_minutes": 0}, "daily_minutes"),
|
({"daily_minutes": 0}, "daily_minutes"),
|
||||||
|
({"daily_minutes": 59}, "at least 60"),
|
||||||
|
(
|
||||||
|
{"daily_minutes": 89, "replaces": ["leetcode", "reading", "tutor"]},
|
||||||
|
"at least 90",
|
||||||
|
),
|
||||||
({"unlock_minutes": 121}, "unlock_minutes"),
|
({"unlock_minutes": 121}, "unlock_minutes"),
|
||||||
({"daily_minutes": 20}, "unlock_minutes"),
|
({"daily_minutes": 60, "unlock_minutes": 61}, "unlock_minutes"),
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
def test_update_validation(kw: dict[str, object], match: str) -> None:
|
def test_update_validation(kw: dict[str, object], match: str) -> None:
|
||||||
@ -124,39 +129,44 @@ def test_end_in_the_past_refused() -> None:
|
|||||||
fp.update_project("hr", today=D1 + 2 * DAY, end=D1 + DAY)
|
fp.update_project("hr", today=D1 + 2 * DAY, end=D1 + DAY)
|
||||||
|
|
||||||
|
|
||||||
def test_daily_change_applies_from_today(data: Path) -> None:
|
def test_daily_cut_applies_from_tomorrow(data: Path) -> None:
|
||||||
_make()
|
_make()
|
||||||
fp.update_project("hr", today=D1 + 2 * DAY, daily_minutes=60, unlock_minutes=10)
|
fp.update_project("hr", today=D1 + 2 * DAY, daily_minutes=100, unlock_minutes=10)
|
||||||
p = fp.list_projects()[0]
|
p = fp.list_projects()[0]
|
||||||
assert (p.daily_minutes, p.unlock_minutes) == (60, 10)
|
assert (p.daily_minutes, p.unlock_minutes) == (100, 10)
|
||||||
assert p.daily_on(D1 + DAY) == 120
|
assert p.daily_on(D1 + DAY) == 120
|
||||||
assert p.unlock_on(D1 + DAY) == 30
|
assert p.daily_on(D1 + 2 * DAY) == 120 # today keeps its targets
|
||||||
assert p.daily_on(D1 + 2 * DAY) == 60
|
assert p.unlock_on(D1 + 2 * DAY) == 30
|
||||||
|
assert p.daily_on(D4) == 100
|
||||||
assert p.unlock_on(D4) == 10
|
assert p.unlock_on(D4) == 10
|
||||||
# a second edit the same day keeps the preserved past, a later day adds a row
|
# a deeper cut the same day keeps the one preserved row, a later day adds one
|
||||||
fp.update_project("hr", today=D1 + 2 * DAY, daily_minutes=90)
|
fp.update_project("hr", today=D1 + 2 * DAY, daily_minutes=80)
|
||||||
assert len(fp.list_projects()[0].history) == 1
|
assert len(fp.list_projects()[0].history) == 1
|
||||||
fp.update_project("hr", today=D4, daily_minutes=45, unlock_minutes=5)
|
fp.update_project("hr", today=D4, daily_minutes=65, unlock_minutes=5)
|
||||||
p = fp.list_projects()[0]
|
p = fp.list_projects()[0]
|
||||||
assert [h.until for h in p.history] == [D1 + DAY, D4 - DAY]
|
assert [h.until for h in p.history] == [D1 + 2 * DAY, D4]
|
||||||
assert p.daily_on(D1 + 2 * DAY) == 90
|
assert p.daily_on(D4) == 80
|
||||||
assert p.daily_on(D4) == 45
|
assert p.daily_on(D4 + DAY) == 65
|
||||||
raw = json.loads((data / "projects.json").read_text())["projects"][0]
|
raw = json.loads((data / "projects.json").read_text())["projects"][0]
|
||||||
assert raw["history"][0] == {
|
assert raw["history"][0] == {
|
||||||
"until": "2026-11-03",
|
"until": "2026-11-04",
|
||||||
"daily_minutes": 120,
|
"daily_minutes": 120,
|
||||||
"unlock_minutes": 30,
|
"unlock_minutes": 30,
|
||||||
|
"replaces": ["leetcode", "reading"],
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def test_future_project_daily_change_keeps_no_history() -> None:
|
def test_future_project_daily_change_keeps_no_history() -> None:
|
||||||
_make()
|
_make()
|
||||||
fp.update_project("hr", today=D1 - DAY, daily_minutes=60, unlock_minutes=10)
|
fp.update_project("hr", today=D1 - DAY, daily_minutes=100, unlock_minutes=10)
|
||||||
p = fp.list_projects()[0]
|
p = fp.list_projects()[0]
|
||||||
assert p.history == ()
|
assert p.history == ()
|
||||||
assert p.daily_on(D1) == 60
|
assert p.daily_on(D1) == 100
|
||||||
fp.update_project("hr", today=D1, daily_minutes=50) # first day: nothing past
|
# on the first day a cut waits for tomorrow, like any started project
|
||||||
assert fp.list_projects()[0].history == ()
|
fp.update_project("hr", today=D1, daily_minutes=70)
|
||||||
|
p = fp.list_projects()[0]
|
||||||
|
assert p.daily_on(D1) == 100
|
||||||
|
assert p.daily_on(D1 + DAY) == 70
|
||||||
|
|
||||||
|
|
||||||
def test_same_value_edit_adds_no_history() -> None:
|
def test_same_value_edit_adds_no_history() -> None:
|
||||||
@ -167,10 +177,11 @@ def test_same_value_edit_adds_no_history() -> None:
|
|||||||
|
|
||||||
def test_status_and_minutes_use_the_day_values(tmp_path: Path) -> None:
|
def test_status_and_minutes_use_the_day_values(tmp_path: Path) -> None:
|
||||||
_make()
|
_make()
|
||||||
fp.update_project("hr", today=D1 + DAY, daily_minutes=60, unlock_minutes=10)
|
fp.update_project("hr", today=D1 + DAY, daily_minutes=100, unlock_minutes=10)
|
||||||
assert fp.status(D1)["daily_minutes"] == 120
|
assert fp.status(D1)["daily_minutes"] == 120
|
||||||
assert fp.status(D1)["unlock_minutes"] == 30
|
assert fp.status(D1)["unlock_minutes"] == 30
|
||||||
assert fp.status(D1 + DAY)["daily_minutes"] == 60
|
assert fp.status(D1 + DAY)["daily_minutes"] == 120
|
||||||
|
assert fp.status(D1 + 2 * DAY)["daily_minutes"] == 100
|
||||||
|
|
||||||
|
|
||||||
def test_work_url_is_editable_kept_and_clearable() -> None:
|
def test_work_url_is_editable_kept_and_clearable() -> None:
|
||||||
|
|||||||
188
focus_project/focus_project/tests/test_update_ratchet.py
Normal file
188
focus_project/focus_project/tests/test_update_ratchet.py
Normal file
@ -0,0 +1,188 @@
|
|||||||
|
# Copyright (c) 2026 Krzysztof Rudnicki
|
||||||
|
"""An edit never lowers today's obligation: reductions apply from tomorrow."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import date, datetime, time, timedelta
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
import focus_project as fp
|
||||||
|
|
||||||
|
START = date(2026, 11, 2)
|
||||||
|
TODAY = date(2026, 11, 4)
|
||||||
|
TOMORROW = TODAY + timedelta(days=1)
|
||||||
|
YESTERDAY = TODAY - timedelta(days=1)
|
||||||
|
END = date(2026, 11, 20)
|
||||||
|
|
||||||
|
|
||||||
|
def _make(start: date = START, replaces: list[str] | None = None) -> fp.Project:
|
||||||
|
return fp.create_project(
|
||||||
|
"p",
|
||||||
|
name="P",
|
||||||
|
start=start,
|
||||||
|
end=END,
|
||||||
|
replaces=replaces or ["leetcode"],
|
||||||
|
daily_minutes=120,
|
||||||
|
unlock_minutes=30,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _noon(day: date) -> float:
|
||||||
|
return datetime.combine(day, time(12)).timestamp()
|
||||||
|
|
||||||
|
|
||||||
|
def _limits(day: date) -> tuple[int, int, tuple[str, ...]]:
|
||||||
|
p = fp.list_projects()[0]
|
||||||
|
return p.daily_on(day), p.unlock_on(day), p.replaces_on(day)
|
||||||
|
|
||||||
|
|
||||||
|
def test_red_team_unlock_zero_waits_for_tomorrow() -> None:
|
||||||
|
_make()
|
||||||
|
got = fp.apply_update("p", today=TODAY, unlock_minutes=0)
|
||||||
|
assert got.effective_from == TOMORROW
|
||||||
|
assert _limits(TODAY)[1] == 30
|
||||||
|
assert _limits(YESTERDAY)[1] == 30
|
||||||
|
assert _limits(TOMORROW)[1] == 0
|
||||||
|
assert fp.status(TODAY)["unlock_minutes"] == 30
|
||||||
|
|
||||||
|
|
||||||
|
def test_cut_to_the_floor_does_not_change_today() -> None:
|
||||||
|
_make()
|
||||||
|
fp.record_activity("tutor", "heartbeat", ts=_noon(TODAY), project="p")
|
||||||
|
before = fp.status(TODAY)
|
||||||
|
fp.update_project("p", today=TODAY, daily_minutes=30, unlock_minutes=0)
|
||||||
|
after = fp.status(TODAY)
|
||||||
|
assert after == before
|
||||||
|
assert after["daily_minutes"] == 120
|
||||||
|
assert fp.minutes_for(TODAY) == before["counted_minutes"]
|
||||||
|
assert fp.status(TOMORROW)["daily_minutes"] == 30
|
||||||
|
|
||||||
|
|
||||||
|
def test_raises_apply_today() -> None:
|
||||||
|
_make()
|
||||||
|
got = fp.apply_update("p", today=TODAY, daily_minutes=180, unlock_minutes=40)
|
||||||
|
assert got.effective_from == TODAY
|
||||||
|
assert _limits(TODAY)[:2] == (180, 40)
|
||||||
|
assert _limits(YESTERDAY)[:2] == (120, 30)
|
||||||
|
|
||||||
|
|
||||||
|
def test_mixed_edit_defers_whole_edit() -> None:
|
||||||
|
_make()
|
||||||
|
got = fp.apply_update("p", today=TODAY, daily_minutes=180, unlock_minutes=10)
|
||||||
|
assert got.effective_from == TOMORROW
|
||||||
|
assert _limits(TODAY)[:2] == (120, 30)
|
||||||
|
assert _limits(TOMORROW)[:2] == (180, 10)
|
||||||
|
|
||||||
|
|
||||||
|
def test_added_gate_waits_removed_gate_is_immediate() -> None:
|
||||||
|
_make(replaces=["leetcode", "reading"])
|
||||||
|
got = fp.apply_update("p", today=TODAY, replaces=["leetcode", "reading", "tutor"])
|
||||||
|
assert got.effective_from == TOMORROW
|
||||||
|
assert not fp.stands_down("tutor", TODAY)
|
||||||
|
assert fp.stands_down("tutor", TOMORROW)
|
||||||
|
assert fp.status(TODAY)["replaces"] == ["leetcode", "reading"]
|
||||||
|
got = fp.apply_update("p", today=TODAY, replaces=["leetcode"])
|
||||||
|
assert got.effective_from == TODAY
|
||||||
|
assert not fp.stands_down("reading", TODAY)
|
||||||
|
assert not fp.stands_down("reading", TOMORROW)
|
||||||
|
assert fp.stands_down("reading", YESTERDAY)
|
||||||
|
|
||||||
|
|
||||||
|
def test_pending_cut_then_second_edits_the_same_day() -> None:
|
||||||
|
_make()
|
||||||
|
fp.update_project("p", today=TODAY, daily_minutes=60, unlock_minutes=10)
|
||||||
|
assert _limits(TODAY)[:2] == (120, 30)
|
||||||
|
# a smaller cut than E is still a cut; a deeper cut still waits
|
||||||
|
fp.update_project("p", today=TODAY, daily_minutes=50)
|
||||||
|
assert _limits(TODAY)[:2] == (120, 30)
|
||||||
|
assert _limits(TOMORROW)[:2] == (50, 10)
|
||||||
|
assert len(fp.list_projects()[0].history) == 1
|
||||||
|
# a name-only edit leaves the pending cut alone
|
||||||
|
assert fp.apply_update("p", today=TODAY, name="Q").effective_from == TODAY
|
||||||
|
assert _limits(TOMORROW)[:2] == (50, 10)
|
||||||
|
# back up to (or over) today's targets cancels the pending cut, applies now
|
||||||
|
got = fp.apply_update("p", today=TODAY, daily_minutes=120, unlock_minutes=30)
|
||||||
|
assert got.effective_from == TODAY
|
||||||
|
assert fp.list_projects()[0].history == ()
|
||||||
|
got = fp.apply_update("p", today=TODAY, daily_minutes=60)
|
||||||
|
got = fp.apply_update("p", today=TODAY, daily_minutes=200)
|
||||||
|
assert got.effective_from == TODAY
|
||||||
|
assert _limits(TODAY)[:2] == (200, 30)
|
||||||
|
assert _limits(YESTERDAY)[:2] == (120, 30)
|
||||||
|
|
||||||
|
|
||||||
|
def test_not_yet_started_project_is_a_new_obligation() -> None:
|
||||||
|
_make(start=TOMORROW)
|
||||||
|
got = fp.apply_update("p", today=TODAY, daily_minutes=30, unlock_minutes=0)
|
||||||
|
assert got.effective_from == TODAY
|
||||||
|
assert fp.list_projects()[0].history == ()
|
||||||
|
assert _limits(TOMORROW)[:2] == (30, 0)
|
||||||
|
|
||||||
|
|
||||||
|
def test_project_starting_today_defers_a_cut() -> None:
|
||||||
|
_make(start=TODAY)
|
||||||
|
got = fp.apply_update("p", today=TODAY, daily_minutes=30, unlock_minutes=0)
|
||||||
|
assert got.effective_from == TOMORROW
|
||||||
|
assert _limits(TODAY)[:2] == (120, 30)
|
||||||
|
|
||||||
|
|
||||||
|
def test_early_end_keeps_today_covered() -> None:
|
||||||
|
_make()
|
||||||
|
fp.update_project("p", today=TODAY, end=TODAY)
|
||||||
|
assert fp.active(TODAY) is not None
|
||||||
|
assert fp.active(TOMORROW) is None
|
||||||
|
with pytest.raises(ValueError, match="past"):
|
||||||
|
fp.update_project("p", today=TODAY, end=YESTERDAY)
|
||||||
|
|
||||||
|
|
||||||
|
def test_legacy_history_row_without_replaces_round_trips() -> None:
|
||||||
|
old = {"until": "2026-11-03", "daily_minutes": 5, "unlock_minutes": 1}
|
||||||
|
row = fp.Limits.from_dict(old)
|
||||||
|
assert row.replaces is None
|
||||||
|
assert "replaces" not in row.to_dict()
|
||||||
|
with_r = fp.Limits(YESTERDAY, 5, 1, ("tutor",))
|
||||||
|
assert fp.Limits.from_dict(with_r.to_dict()) == with_r
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
("gates", "daily", "ok"),
|
||||||
|
[
|
||||||
|
(["leetcode"], 29, False),
|
||||||
|
(["leetcode"], 30, True),
|
||||||
|
(["leetcode", "reading"], 59, False),
|
||||||
|
(["leetcode", "reading", "tutor"], 89, False),
|
||||||
|
(["leetcode", "reading", "tutor"], 90, True),
|
||||||
|
(["leetcode", "book"], 60, True), # book = reading: still two gates
|
||||||
|
(["leetcode", "book", "reading"], 60, True), # one gate named twice
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_daily_floor_is_30_per_replaced_gate(
|
||||||
|
gates: list[str], daily: int, *, ok: bool
|
||||||
|
) -> None:
|
||||||
|
def make() -> fp.Project:
|
||||||
|
return fp.create_project(
|
||||||
|
"f",
|
||||||
|
name="F",
|
||||||
|
start=TODAY,
|
||||||
|
end=END,
|
||||||
|
replaces=gates,
|
||||||
|
daily_minutes=daily,
|
||||||
|
unlock_minutes=0,
|
||||||
|
)
|
||||||
|
|
||||||
|
if ok:
|
||||||
|
assert make().daily_minutes == daily
|
||||||
|
else:
|
||||||
|
with pytest.raises(ValueError, match="at least"):
|
||||||
|
make()
|
||||||
|
|
||||||
|
|
||||||
|
def test_edit_cannot_cut_below_the_floor_or_add_a_gate_it_cannot_pay() -> None:
|
||||||
|
_make(replaces=["leetcode", "reading", "tutor"])
|
||||||
|
for bad in ({"daily_minutes": 89}, {"daily_minutes": 1, "unlock_minutes": 0}):
|
||||||
|
with pytest.raises(ValueError, match="at least 90"):
|
||||||
|
fp.update_project("p", today=TODAY, **bad)
|
||||||
|
assert fp.update_project("p", today=TODAY, daily_minutes=90).daily_minutes == 90
|
||||||
|
assert fp.daily_floor(("a", "b")) == 60
|
||||||
|
assert fp.daily_floor(()) == 30
|
||||||
@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|||||||
|
|
||||||
[project]
|
[project]
|
||||||
name = "focus_project"
|
name = "focus_project"
|
||||||
version = "0.6.0"
|
version = "0.7.1"
|
||||||
description = "Time-boxed focus projects: replace chosen gates, pay a daily-minutes gate"
|
description = "Time-boxed focus projects: replace chosen gates, pay a daily-minutes gate"
|
||||||
requires-python = ">=3.14"
|
requires-python = ">=3.14"
|
||||||
# Stdlib only on purpose: guards import it from the system python.
|
# Stdlib only on purpose: guards import it from the system python.
|
||||||
|
|||||||
@ -1,3 +1,4 @@
|
|||||||
SQL drill engine (MySQL 8.0.33 + PostgreSQL 18.6, one container each): `import sql_drills as sd`.
|
SQL drill engine (MySQL 8.0.33 + PostgreSQL 18.6, one container each): `import sql_drills as sd`.
|
||||||
Drills: `sd.run(id, sql, dialect)`. LeetCode examples: `sd.run_problem(slug_or_statement, sql, dialect)`.
|
Drills: `sd.run(id, sql, dialect)`. LeetCode examples: `sd.run_problem(slug_or_statement, sql, dialect)`.
|
||||||
Data: `$SQL_DRILLS_DATA`. Install: `./install.sh`.
|
Data: `$SQL_DRILLS_DATA`. Install: `./install.sh`.
|
||||||
|
Root password: random, `~/.config/sql_drills/root_password` (0600); learner SQL runs as a per-run user, client commands (`\!`) refused.
|
||||||
|
|||||||
@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|||||||
|
|
||||||
[project]
|
[project]
|
||||||
name = "sql_drills"
|
name = "sql_drills"
|
||||||
version = "0.2.1"
|
version = "0.2.2"
|
||||||
description = "SQL drills (MySQL, PostgreSQL): sandboxed grading, LeetCode statement examples"
|
description = "SQL drills (MySQL, PostgreSQL): sandboxed grading, LeetCode statement examples"
|
||||||
requires-python = ">=3.14"
|
requires-python = ">=3.14"
|
||||||
# Stdlib only on purpose: the tutor server imports it from the system python.
|
# Stdlib only on purpose: the tutor server imports it from the system python.
|
||||||
|
|||||||
@ -3,13 +3,16 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
|
import os
|
||||||
import shutil
|
import shutil
|
||||||
import subprocess
|
import subprocess
|
||||||
import time
|
import time
|
||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
from sql_drills import _secret
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
from collections.abc import Callable
|
from collections.abc import Callable, Mapping
|
||||||
|
|
||||||
IMAGE = "mysql:8.0.33"
|
IMAGE = "mysql:8.0.33"
|
||||||
CONTAINER = "sql-drills-mysql"
|
CONTAINER = "sql-drills-mysql"
|
||||||
@ -18,6 +21,10 @@ NETWORK_ALIAS = "db"
|
|||||||
READY_TIMEOUT = 45.0
|
READY_TIMEOUT = 45.0
|
||||||
QUERY_TIMEOUT = 30.0
|
QUERY_TIMEOUT = 30.0
|
||||||
_DOCKER_TIMEOUT = 50.0
|
_DOCKER_TIMEOUT = 50.0
|
||||||
|
# Learner SQL runs as this OS user (nobody): no root shell, no datadir access.
|
||||||
|
_LEARNER_UID = "65534"
|
||||||
|
# ``mysql`` reads the root password from this variable, never from argv.
|
||||||
|
_ROOT_LOGIN_VAR = "MYSQL_PWD"
|
||||||
|
|
||||||
|
|
||||||
class EngineError(RuntimeError):
|
class EngineError(RuntimeError):
|
||||||
@ -32,7 +39,10 @@ class SqlResult:
|
|||||||
|
|
||||||
|
|
||||||
def _docker(
|
def _docker(
|
||||||
*args: str, stdin: str | None = None, timeout: float = _DOCKER_TIMEOUT
|
*args: str,
|
||||||
|
stdin: str | None = None,
|
||||||
|
timeout: float = _DOCKER_TIMEOUT,
|
||||||
|
env: Mapping[str, str] | None = None,
|
||||||
) -> subprocess.CompletedProcess[str]:
|
) -> subprocess.CompletedProcess[str]:
|
||||||
exe = shutil.which("docker")
|
exe = shutil.which("docker")
|
||||||
if exe is None:
|
if exe is None:
|
||||||
@ -46,6 +56,7 @@ def _docker(
|
|||||||
text=True,
|
text=True,
|
||||||
check=False,
|
check=False,
|
||||||
timeout=timeout,
|
timeout=timeout,
|
||||||
|
env=env,
|
||||||
)
|
)
|
||||||
except subprocess.TimeoutExpired as exc:
|
except subprocess.TimeoutExpired as exc:
|
||||||
msg = f"docker {args[0]} timed out after {timeout:.0f}s"
|
msg = f"docker {args[0]} timed out after {timeout:.0f}s"
|
||||||
@ -55,6 +66,11 @@ def _docker(
|
|||||||
docker = _docker # public alias for sibling engine modules
|
docker = _docker # public alias for sibling engine modules
|
||||||
|
|
||||||
|
|
||||||
|
def _root_env() -> dict[str, str]:
|
||||||
|
"""Environment carrying the root password to ``docker`` (not via argv)."""
|
||||||
|
return {**os.environ, _ROOT_LOGIN_VAR: _secret.root_password()}
|
||||||
|
|
||||||
|
|
||||||
def container_state() -> str:
|
def container_state() -> str:
|
||||||
res = _docker("inspect", "-f", "{{.State.Status}}", CONTAINER)
|
res = _docker("inspect", "-f", "{{.State.Status}}", CONTAINER)
|
||||||
return res.stdout.strip() if res.returncode == 0 else "missing"
|
return res.stdout.strip() if res.returncode == 0 else "missing"
|
||||||
@ -74,9 +90,10 @@ def _create() -> subprocess.CompletedProcess[str]:
|
|||||||
"run", "-d", "--name", CONTAINER,
|
"run", "-d", "--name", CONTAINER,
|
||||||
"--tmpfs", "/var/lib/mysql:rw,size=512m",
|
"--tmpfs", "/var/lib/mysql:rw,size=512m",
|
||||||
"--memory", "1500m",
|
"--memory", "1500m",
|
||||||
"-e", "MYSQL_ALLOW_EMPTY_PASSWORD=yes",
|
"-e", "MYSQL_ROOT_PASSWORD",
|
||||||
*(shared if net.returncode == 0 else []),
|
*(shared if net.returncode == 0 else []),
|
||||||
IMAGE,
|
IMAGE,
|
||||||
|
env={**os.environ, "MYSQL_ROOT_PASSWORD": _secret.root_password()},
|
||||||
) # fmt: skip
|
) # fmt: skip
|
||||||
|
|
||||||
|
|
||||||
@ -118,16 +135,45 @@ def ensure_running(
|
|||||||
"""Create or resume the container if needed, wait (bounded) for MySQL."""
|
"""Create or resume the container if needed, wait (bounded) for MySQL."""
|
||||||
start_or_create(CONTAINER, _create)
|
start_or_create(CONTAINER, _create)
|
||||||
wait_ready(is_ready, "MySQL", timeout, sleep, clock)
|
wait_ready(is_ready, "MySQL", timeout, sleep, clock)
|
||||||
|
secure_root()
|
||||||
|
|
||||||
|
|
||||||
|
def secure_root() -> None:
|
||||||
|
"""Make sure root has our password; adopt a legacy passwordless root once.
|
||||||
|
|
||||||
|
A container started before this existed (or restarted from its old
|
||||||
|
``ALLOW_EMPTY_PASSWORD`` config) has an empty root password. Set it live,
|
||||||
|
without recreating the container: its tmpfs holds databases we must keep.
|
||||||
|
"""
|
||||||
|
if run_sql("SELECT 1;").returncode == 0:
|
||||||
|
return
|
||||||
|
password = _secret.root_password()
|
||||||
|
alter = "".join(
|
||||||
|
f"ALTER USER IF EXISTS 'root'@'{host}' IDENTIFIED BY '{password}'; "
|
||||||
|
for host in ("localhost", "%")
|
||||||
|
)
|
||||||
|
res = exec_query(["exec", "-i", CONTAINER, "mysql", "-uroot"], alter, QUERY_TIMEOUT)
|
||||||
|
if res.returncode != 0:
|
||||||
|
msg = (
|
||||||
|
"MySQL root rejects the stored password and is not passwordless: "
|
||||||
|
f"{res.stderr.strip()}; remove {CONTAINER} to start over"
|
||||||
|
)
|
||||||
|
raise EngineError(msg)
|
||||||
|
|
||||||
|
|
||||||
def stop() -> None:
|
def stop() -> None:
|
||||||
_docker("rm", "-f", CONTAINER)
|
_docker("rm", "-f", CONTAINER)
|
||||||
|
|
||||||
|
|
||||||
def exec_query(argv: list[str], stdin: str | None, timeout: float) -> SqlResult:
|
def exec_query(
|
||||||
|
argv: list[str],
|
||||||
|
stdin: str | None,
|
||||||
|
timeout: float,
|
||||||
|
env: Mapping[str, str] | None = None,
|
||||||
|
) -> SqlResult:
|
||||||
"""``docker <argv>`` as a query: a timeout becomes a clear EngineError."""
|
"""``docker <argv>`` as a query: a timeout becomes a clear EngineError."""
|
||||||
try:
|
try:
|
||||||
res = _docker(*argv, stdin=stdin, timeout=timeout)
|
res = _docker(*argv, stdin=stdin, timeout=timeout, env=env)
|
||||||
except EngineError as exc:
|
except EngineError as exc:
|
||||||
if "timed out" in str(exc):
|
if "timed out" in str(exc):
|
||||||
msg = f"query timed out after {timeout:.0f}s"
|
msg = f"query timed out after {timeout:.0f}s"
|
||||||
@ -144,10 +190,19 @@ def run_sql(
|
|||||||
headers: bool = False,
|
headers: bool = False,
|
||||||
timeout: float = QUERY_TIMEOUT,
|
timeout: float = QUERY_TIMEOUT,
|
||||||
) -> SqlResult:
|
) -> SqlResult:
|
||||||
argv = ["exec", "-i", CONTAINER, "mysql", f"-u{user}"]
|
r"""Run ``sql`` through the ``mysql`` client as ``user``.
|
||||||
|
|
||||||
|
``--binary-mode`` turns every client command (``\!`` shell escape,
|
||||||
|
``source``, ``\.``) into an error for piped input. Only root gets the
|
||||||
|
password, and only the learner path drops to an unprivileged OS user.
|
||||||
|
"""
|
||||||
|
root = user == "root"
|
||||||
|
argv = ["exec", "-i"]
|
||||||
|
argv += ["-e", _ROOT_LOGIN_VAR] if root else ["-u", _LEARNER_UID]
|
||||||
|
argv += [CONTAINER, "mysql", f"-u{user}", "--binary-mode"]
|
||||||
argv += ["--default-character-set=utf8mb4", "-B"]
|
argv += ["--default-character-set=utf8mb4", "-B"]
|
||||||
if not headers:
|
if not headers:
|
||||||
argv.append("-N")
|
argv.append("-N")
|
||||||
if database:
|
if database:
|
||||||
argv.append(database)
|
argv.append(database)
|
||||||
return exec_query(argv, sql, timeout)
|
return exec_query(argv, sql, timeout, _root_env() if root else None)
|
||||||
|
|||||||
@ -6,6 +6,7 @@ import os
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
ENV_VAR = "SQL_DRILLS_DATA"
|
ENV_VAR = "SQL_DRILLS_DATA"
|
||||||
|
CONFIG_ENV_VAR = "SQL_DRILLS_CONFIG"
|
||||||
|
|
||||||
|
|
||||||
def data_dir() -> Path:
|
def data_dir() -> Path:
|
||||||
@ -21,3 +22,11 @@ def builtin_dir() -> Path:
|
|||||||
|
|
||||||
def generated_dir() -> Path:
|
def generated_dir() -> Path:
|
||||||
return data_dir() / "drills"
|
return data_dir() / "drills"
|
||||||
|
|
||||||
|
|
||||||
|
def config_dir() -> Path:
|
||||||
|
"""Where the engine's secret lives (never in git, never in the data dir)."""
|
||||||
|
override = os.environ.get(CONFIG_ENV_VAR, "")
|
||||||
|
if override:
|
||||||
|
return Path(override)
|
||||||
|
return Path.home() / ".config" / "sql_drills"
|
||||||
|
|||||||
@ -17,6 +17,8 @@ if TYPE_CHECKING:
|
|||||||
|
|
||||||
SNAPSHOT_ROWS = 200
|
SNAPSHOT_ROWS = 200
|
||||||
_MAX_EXECUTION_MS = 20000
|
_MAX_EXECUTION_MS = 20000
|
||||||
|
_NO_META = "mysql client commands (backslash) are not allowed"
|
||||||
|
_META = re.compile(r"(?:^|\r)[\s\ufeff]*\\", re.MULTILINE)
|
||||||
_CODE = re.compile(r"ERROR (\d+)")
|
_CODE = re.compile(r"ERROR (\d+)")
|
||||||
_COLUMNS_SQL = (
|
_COLUMNS_SQL = (
|
||||||
"SELECT table_name, column_name FROM information_schema.columns "
|
"SELECT table_name, column_name FROM information_schema.columns "
|
||||||
@ -43,12 +45,24 @@ def _outcome(res: _engine.SqlResult) -> Executed:
|
|||||||
return Executed(ok=True, error=None, code=None, rows=parse_rows(res.stdout))
|
return Executed(ok=True, error=None, code=None, rows=parse_rows(res.stdout))
|
||||||
|
|
||||||
|
|
||||||
|
def has_meta_command(sql: str) -> bool:
|
||||||
|
r"""True if any line starts with a backslash (after a BOM or whitespace).
|
||||||
|
|
||||||
|
The client's ``\!`` runs a shell. ``--binary-mode`` already turns every
|
||||||
|
such command into an error; refusing here too keeps a stray one from ever
|
||||||
|
reaching the client, whatever precedes it (comments, other statements).
|
||||||
|
"""
|
||||||
|
return _META.search(sql) is not None
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
class Sandbox:
|
class Sandbox:
|
||||||
db: str
|
db: str
|
||||||
user: str
|
user: str
|
||||||
|
|
||||||
def _run(self, sql: str, *, headers: bool) -> _engine.SqlResult:
|
def _run(self, sql: str, *, headers: bool) -> _engine.SqlResult:
|
||||||
|
if has_meta_command(sql):
|
||||||
|
return _engine.SqlResult(1, "", _NO_META)
|
||||||
limit = f"SET SESSION max_execution_time={_MAX_EXECUTION_MS}; "
|
limit = f"SET SESSION max_execution_time={_MAX_EXECUTION_MS}; "
|
||||||
return _engine.run_sql(limit + sql, self.db, self.user, headers=headers)
|
return _engine.run_sql(limit + sql, self.db, self.user, headers=headers)
|
||||||
|
|
||||||
|
|||||||
38
sql_drills/sql_drills/_secret.py
Normal file
38
sql_drills/sql_drills/_secret.py
Normal file
@ -0,0 +1,38 @@
|
|||||||
|
"""The MySQL root password: random, 0600, readable only by this engine.
|
||||||
|
|
||||||
|
The container's root used to be passwordless, so anything that reached a shell
|
||||||
|
in it (a backslash-bang meta-command) owned every database. Now root has this
|
||||||
|
password; learner SQL runs as a per-run user that never sees it.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import contextlib
|
||||||
|
import os
|
||||||
|
import secrets
|
||||||
|
|
||||||
|
from sql_drills import _paths
|
||||||
|
|
||||||
|
_FILE = "root_password"
|
||||||
|
|
||||||
|
|
||||||
|
def root_password() -> str:
|
||||||
|
"""Read the password, creating it on first use.
|
||||||
|
|
||||||
|
The file appears complete or not at all: written to a private temp name,
|
||||||
|
then hard-linked into place (which fails if another process won the race).
|
||||||
|
"""
|
||||||
|
path = _paths.config_dir() / _FILE
|
||||||
|
if path.exists():
|
||||||
|
return path.read_text(encoding="utf-8").strip()
|
||||||
|
path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||||
|
tmp = path.with_name(f".{_FILE}.{secrets.token_hex(4)}")
|
||||||
|
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
||||||
|
with os.fdopen(fd, "w", encoding="utf-8") as handle:
|
||||||
|
handle.write(secrets.token_urlsafe(24) + "\n")
|
||||||
|
try:
|
||||||
|
with contextlib.suppress(FileExistsError):
|
||||||
|
os.link(tmp, path)
|
||||||
|
finally:
|
||||||
|
tmp.unlink()
|
||||||
|
return path.read_text(encoding="utf-8").strip()
|
||||||
@ -14,9 +14,17 @@ if TYPE_CHECKING:
|
|||||||
|
|
||||||
|
|
||||||
@pytest.fixture(autouse=True)
|
@pytest.fixture(autouse=True)
|
||||||
def _redirect_data(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
|
def _redirect_data(
|
||||||
"""Generated drills never land in the real ``~/.local/share/sql_drills``."""
|
monkeypatch: pytest.MonkeyPatch, tmp_path: Path, request: pytest.FixtureRequest
|
||||||
|
) -> None:
|
||||||
|
"""Generated drills never land in the real ``~/.local/share/sql_drills``.
|
||||||
|
|
||||||
|
The root-password file is redirected too, except for the ``docker`` live
|
||||||
|
tests: they talk to the real container, which only knows the real password.
|
||||||
|
"""
|
||||||
monkeypatch.setenv("SQL_DRILLS_DATA", str(tmp_path / "data"))
|
monkeypatch.setenv("SQL_DRILLS_DATA", str(tmp_path / "data"))
|
||||||
|
if request.node.get_closest_marker("docker") is None:
|
||||||
|
monkeypatch.setenv("SQL_DRILLS_CONFIG", str(tmp_path / "config"))
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
|
|||||||
@ -9,7 +9,7 @@ from unittest.mock import MagicMock, patch
|
|||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from sql_drills import _engine
|
from sql_drills import _engine, _secret
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
from collections.abc import Iterator
|
from collections.abc import Iterator
|
||||||
@ -59,8 +59,8 @@ def test_is_ready_follows_ping_exit_code() -> None:
|
|||||||
|
|
||||||
|
|
||||||
def test_creates_container_on_shared_network_when_it_exists() -> None:
|
def test_creates_container_on_shared_network_when_it_exists() -> None:
|
||||||
# inspect(missing), network inspect(ok), run, ping.
|
# inspect(missing), network inspect(ok), run, ping, root login check.
|
||||||
with _run(_cp(1), _cp(0), _cp(0, "id"), _cp(0)) as run:
|
with _run(_cp(1), _cp(0), _cp(0, "id"), _cp(0), _cp(0)) as run:
|
||||||
_engine.ensure_running(timeout=5, sleep=_no_sleep)
|
_engine.ensure_running(timeout=5, sleep=_no_sleep)
|
||||||
argv = run.call_args_list[2].args[0]
|
argv = run.call_args_list[2].args[0]
|
||||||
assert argv[:3] == ["docker", "run", "-d"]
|
assert argv[:3] == ["docker", "run", "-d"]
|
||||||
@ -70,23 +70,60 @@ def test_creates_container_on_shared_network_when_it_exists() -> None:
|
|||||||
assert argv[argv.index("--network-alias") + 1] == _engine.NETWORK_ALIAS
|
assert argv[argv.index("--network-alias") + 1] == _engine.NETWORK_ALIAS
|
||||||
|
|
||||||
|
|
||||||
|
def test_new_container_gets_a_random_root_password_not_via_argv() -> None:
|
||||||
|
with _run(_cp(1), _cp(1), _cp(0, "id"), _cp(0), _cp(0)) as run:
|
||||||
|
_engine.ensure_running(timeout=5, sleep=_no_sleep)
|
||||||
|
argv = run.call_args_list[2].args[0]
|
||||||
|
password = run.call_args_list[2].kwargs["env"]["MYSQL_ROOT_PASSWORD"]
|
||||||
|
assert len(password) >= 24
|
||||||
|
assert "MYSQL_ALLOW_EMPTY_PASSWORD=yes" not in argv
|
||||||
|
assert not any(password in part for part in argv)
|
||||||
|
assert "MYSQL_ROOT_PASSWORD" in argv
|
||||||
|
|
||||||
|
|
||||||
def test_creates_container_plain_when_network_absent() -> None:
|
def test_creates_container_plain_when_network_absent() -> None:
|
||||||
with _run(_cp(1), _cp(1), _cp(0, "id"), _cp(0)) as run:
|
with _run(_cp(1), _cp(1), _cp(0, "id"), _cp(0), _cp(0)) as run:
|
||||||
_engine.ensure_running(timeout=5, sleep=_no_sleep)
|
_engine.ensure_running(timeout=5, sleep=_no_sleep)
|
||||||
assert "--network" not in run.call_args_list[2].args[0]
|
assert "--network" not in run.call_args_list[2].args[0]
|
||||||
|
|
||||||
|
|
||||||
def test_resumes_exited_container() -> None:
|
def test_resumes_exited_container() -> None:
|
||||||
with _run(_cp(0, "exited\n"), _cp(0), _cp(0)) as run:
|
with _run(_cp(0, "exited\n"), _cp(0), _cp(0), _cp(0)) as run:
|
||||||
_engine.ensure_running(timeout=5, sleep=_no_sleep)
|
_engine.ensure_running(timeout=5, sleep=_no_sleep)
|
||||||
assert run.call_args_list[1].args[0][:2] == ["docker", "start"]
|
assert run.call_args_list[1].args[0][:2] == ["docker", "start"]
|
||||||
|
|
||||||
|
|
||||||
def test_running_container_is_never_recreated() -> None:
|
def test_running_container_is_never_recreated() -> None:
|
||||||
with _run(_cp(0, "running\n"), _cp(0)) as run:
|
with _run(_cp(0, "running\n"), _cp(0), _cp(0)) as run:
|
||||||
_engine.ensure_running(timeout=5, sleep=_no_sleep)
|
_engine.ensure_running(timeout=5, sleep=_no_sleep)
|
||||||
verbs = [c.args[0][1] for c in run.call_args_list]
|
verbs = [c.args[0][1] for c in run.call_args_list]
|
||||||
assert verbs == ["inspect", "exec"]
|
assert verbs == ["inspect", "exec", "exec"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_legacy_passwordless_root_gets_the_password_live() -> None:
|
||||||
|
# inspect, ping, root login refused, passwordless ALTER USER works.
|
||||||
|
denied = _cp(1, "", "ERROR 1045 (28000): Access denied")
|
||||||
|
with _run(_cp(0, "running\n"), _cp(0), denied, _cp(0)) as run:
|
||||||
|
_engine.ensure_running(timeout=5, sleep=_no_sleep)
|
||||||
|
alter = run.call_args_list[3]
|
||||||
|
password = _secret.root_password()
|
||||||
|
assert "env" not in alter.kwargs or alter.kwargs["env"] is None
|
||||||
|
assert (
|
||||||
|
f"ALTER USER IF EXISTS 'root'@'localhost' IDENTIFIED BY '{password}'"
|
||||||
|
in (alter.kwargs["input"])
|
||||||
|
)
|
||||||
|
assert "'root'@'%'" in alter.kwargs["input"]
|
||||||
|
assert not any(password in part for part in alter.args[0])
|
||||||
|
assert "-p" not in alter.args[0]
|
||||||
|
|
||||||
|
|
||||||
|
def test_root_rejecting_our_password_is_a_clear_error() -> None:
|
||||||
|
denied = _cp(1, "", "ERROR 1045 (28000): Access denied")
|
||||||
|
with (
|
||||||
|
_run(_cp(0, "running\n"), _cp(0), denied, denied),
|
||||||
|
pytest.raises(_engine.EngineError, match="not passwordless"),
|
||||||
|
):
|
||||||
|
_engine.ensure_running(timeout=5, sleep=_no_sleep)
|
||||||
|
|
||||||
|
|
||||||
def test_create_failure_is_reported() -> None:
|
def test_create_failure_is_reported() -> None:
|
||||||
@ -110,18 +147,38 @@ def test_stop_removes_container() -> None:
|
|||||||
assert run.call_args.args[0] == ["docker", "rm", "-f", _engine.CONTAINER]
|
assert run.call_args.args[0] == ["docker", "rm", "-f", _engine.CONTAINER]
|
||||||
|
|
||||||
|
|
||||||
def test_run_sql_defaults_to_root_and_no_headers() -> None:
|
def test_run_sql_defaults_to_root_with_password_from_env_only() -> None:
|
||||||
with _run(_cp(0, "1\n", "")) as run:
|
with _run(_cp(0, "1\n", "")) as run:
|
||||||
res = _engine.run_sql("SELECT 1;", database="d1")
|
res = _engine.run_sql("SELECT 1;", database="d1")
|
||||||
argv = run.call_args.args[0]
|
argv = run.call_args.args[0]
|
||||||
assert argv[:4] == ["docker", "exec", "-i", _engine.CONTAINER]
|
assert argv[:6] == ["docker", "exec", "-i", "-e", "MYSQL_PWD", _engine.CONTAINER]
|
||||||
assert "-uroot" in argv
|
assert "-uroot" in argv
|
||||||
|
assert "-u" not in argv
|
||||||
|
password = _secret.root_password()
|
||||||
|
assert run.call_args.kwargs["env"]["MYSQL_PWD"] == password
|
||||||
|
assert not any(password in part for part in argv)
|
||||||
assert "-N" in argv
|
assert "-N" in argv
|
||||||
assert argv[-1] == "d1"
|
assert argv[-1] == "d1"
|
||||||
assert run.call_args.kwargs["input"] == "SELECT 1;"
|
assert run.call_args.kwargs["input"] == "SELECT 1;"
|
||||||
assert (res.returncode, res.stdout) == (0, "1\n")
|
assert (res.returncode, res.stdout) == (0, "1\n")
|
||||||
|
|
||||||
|
|
||||||
|
def test_every_run_is_binary_mode_so_client_commands_cannot_run() -> None:
|
||||||
|
with _run(_cp(0), _cp(0)) as run:
|
||||||
|
_engine.run_sql("SELECT 1;")
|
||||||
|
_engine.run_sql("SELECT 1;", user="u_x")
|
||||||
|
assert all("--binary-mode" in c.args[0] for c in run.call_args_list)
|
||||||
|
|
||||||
|
|
||||||
|
def test_learner_run_is_unprivileged_and_never_sees_the_password() -> None:
|
||||||
|
with _run(_cp(0)) as run:
|
||||||
|
_engine.run_sql("SELECT 1;", user="u_x")
|
||||||
|
argv = run.call_args.args[0]
|
||||||
|
assert argv[:6] == ["docker", "exec", "-i", "-u", "65534", _engine.CONTAINER]
|
||||||
|
assert "MYSQL_PWD" not in argv
|
||||||
|
assert run.call_args.kwargs["env"] is None
|
||||||
|
|
||||||
|
|
||||||
def test_run_sql_headers_user_and_no_database() -> None:
|
def test_run_sql_headers_user_and_no_database() -> None:
|
||||||
with _run(_cp(0)) as run:
|
with _run(_cp(0)) as run:
|
||||||
_engine.run_sql("SELECT 1;", user="u_x", headers=True)
|
_engine.run_sql("SELECT 1;", user="u_x", headers=True)
|
||||||
|
|||||||
@ -98,6 +98,64 @@ def test_user_sql_cannot_see_or_drop_other_databases() -> None:
|
|||||||
_engine.run_sql("DROP DATABASE IF EXISTS drill_canary_guard;")
|
_engine.run_sql("DROP DATABASE IF EXISTS drill_canary_guard;")
|
||||||
|
|
||||||
|
|
||||||
|
_ATTACKS = [
|
||||||
|
"\\! id",
|
||||||
|
"-- c\n\\! mysql -uroot -N -e 'show databases'",
|
||||||
|
"SELECT 1;\n\\! id",
|
||||||
|
"\ufeff\\! id",
|
||||||
|
"SELECT 1 -- \\! id",
|
||||||
|
"SELECT 1; \\! id",
|
||||||
|
"SELECT 1 \\! id",
|
||||||
|
"source /etc/passwd",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("attack", _ATTACKS)
|
||||||
|
def test_client_commands_never_reach_a_shell(attack: str) -> None:
|
||||||
|
"""Red-team: ``\\!`` used to run a root shell inside the container."""
|
||||||
|
drill = sd.get_drill("01_pivot_sum")
|
||||||
|
with _sandbox.sandbox(drill.schema_sql) as box:
|
||||||
|
done = box.query(attack)
|
||||||
|
# Even bypassing the text guard, the client itself must refuse.
|
||||||
|
raw = _engine.run_sql(attack, box.db, box.user)
|
||||||
|
assert "uid=" not in str(done.rows) + str(done.error)
|
||||||
|
assert "uid=" not in raw.stdout
|
||||||
|
assert "theory" not in raw.stdout
|
||||||
|
|
||||||
|
|
||||||
|
def test_client_runs_without_a_shell_escape_or_root_os_user() -> None:
|
||||||
|
drill = sd.get_drill("01_pivot_sum")
|
||||||
|
with _sandbox.sandbox(drill.schema_sql) as box:
|
||||||
|
raw = _engine.run_sql("\\! id", box.db, box.user)
|
||||||
|
assert raw.returncode != 0
|
||||||
|
assert "Unknown command" in raw.stderr
|
||||||
|
# The unprivileged OS user is what ``run_sql`` execs as.
|
||||||
|
ident = _engine.docker("exec", "-u", "65534", _engine.CONTAINER, "id", "-u")
|
||||||
|
assert ident.stdout.strip() == "65534"
|
||||||
|
|
||||||
|
|
||||||
|
def test_learner_cannot_see_theory_or_other_drill_databases() -> None:
|
||||||
|
drill = sd.get_drill("01_pivot_sum")
|
||||||
|
with _sandbox.sandbox(drill.schema_sql) as box, _sandbox.sandbox("") as other:
|
||||||
|
seen = {r[0] for r in box.execute("SHOW DATABASES;").rows}
|
||||||
|
assert seen <= {box.db, "information_schema", "performance_schema"}
|
||||||
|
assert "theory" not in seen
|
||||||
|
assert other.db not in seen
|
||||||
|
assert not box.execute("SELECT * FROM theory.anything;").ok
|
||||||
|
assert not box.execute("SELECT * FROM mysql.user;").ok
|
||||||
|
|
||||||
|
|
||||||
|
def test_root_is_passwordless_no_more() -> None:
|
||||||
|
"""Root without the engine's password is refused, locally and over TCP."""
|
||||||
|
for host in ("-hlocalhost", "-h127.0.0.1"):
|
||||||
|
res = _engine.docker(
|
||||||
|
"exec", _engine.CONTAINER, "mysql", "-uroot", host, "-N", "-e", "SELECT 1"
|
||||||
|
)
|
||||||
|
assert res.returncode != 0
|
||||||
|
assert "Access denied" in res.stderr
|
||||||
|
assert _engine.run_sql("SELECT 1;").stdout.strip() == "1"
|
||||||
|
|
||||||
|
|
||||||
def test_ensure_running_does_not_recreate_a_running_container() -> None:
|
def test_ensure_running_does_not_recreate_a_running_container() -> None:
|
||||||
before = _container_id()
|
before = _container_id()
|
||||||
sd.ensure_running()
|
sd.ensure_running()
|
||||||
|
|||||||
@ -31,3 +31,13 @@ def test_empty_env_falls_back(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -
|
|||||||
|
|
||||||
def test_builtin_dir_ships_fixtures() -> None:
|
def test_builtin_dir_ships_fixtures() -> None:
|
||||||
assert (_paths.builtin_dir() / "01_pivot_sum" / "meta.json").is_file()
|
assert (_paths.builtin_dir() / "01_pivot_sum" / "meta.json").is_file()
|
||||||
|
|
||||||
|
|
||||||
|
def test_config_dir_env_and_default(
|
||||||
|
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
||||||
|
) -> None:
|
||||||
|
monkeypatch.setenv("SQL_DRILLS_CONFIG", str(tmp_path / "c"))
|
||||||
|
assert _paths.config_dir() == tmp_path / "c"
|
||||||
|
monkeypatch.setenv("SQL_DRILLS_CONFIG", "")
|
||||||
|
monkeypatch.setenv("HOME", str(tmp_path))
|
||||||
|
assert _paths.config_dir() == tmp_path / ".config" / "sql_drills"
|
||||||
|
|||||||
@ -189,3 +189,38 @@ def test_query_error_has_no_columns(fake_mysql: FakeMysql) -> None:
|
|||||||
done = box.query("nope")
|
done = box.query("nope")
|
||||||
assert not done.ok
|
assert not done.ok
|
||||||
assert done.columns == []
|
assert done.columns == []
|
||||||
|
|
||||||
|
|
||||||
|
RED_TEAM = [
|
||||||
|
"\\! id",
|
||||||
|
"-- harmless comment\n\\! id",
|
||||||
|
"SELECT 1;\n\\! mysql -uroot -e 'show databases'",
|
||||||
|
"\\! id",
|
||||||
|
" \t\\system id",
|
||||||
|
"SELECT 1;\r\\! id",
|
||||||
|
"/* c */\n\n \\. /etc/passwd",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("payload", RED_TEAM)
|
||||||
|
def test_meta_commands_are_refused_before_reaching_the_client(
|
||||||
|
fake_mysql: FakeMysql, payload: str
|
||||||
|
) -> None:
|
||||||
|
with _sandbox.sandbox("") as box:
|
||||||
|
before = len(fake_mysql.calls)
|
||||||
|
done = box.query(payload)
|
||||||
|
also = box.execute(payload)
|
||||||
|
assert not done.ok
|
||||||
|
assert done.error == "mysql client commands (backslash) are not allowed"
|
||||||
|
assert not also.ok
|
||||||
|
assert all(payload not in str(c["sql"]) for c in fake_mysql.calls[before:]), (
|
||||||
|
"refused SQL must never be sent"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"sql",
|
||||||
|
["SELECT 1;", "SELECT 'a\\\\b';", "SELECT 1 -- \\! id", "SELECT 'x\\n';"],
|
||||||
|
)
|
||||||
|
def test_backslash_inside_a_line_is_ordinary_sql(sql: str) -> None:
|
||||||
|
assert not _sandbox.has_meta_command(sql)
|
||||||
|
|||||||
47
sql_drills/sql_drills/tests/test_secret.py
Normal file
47
sql_drills/sql_drills/tests/test_secret.py
Normal file
@ -0,0 +1,47 @@
|
|||||||
|
"""The root password is random, private and created exactly once."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
from sql_drills import _paths, _secret
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from _typeshed import StrPath
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
|
||||||
|
def test_created_once_random_and_private() -> None:
|
||||||
|
first = _secret.root_password()
|
||||||
|
assert len(first) >= 24
|
||||||
|
assert _secret.root_password() == first
|
||||||
|
path = _paths.config_dir() / "root_password"
|
||||||
|
assert path.stat().st_mode & 0o777 == 0o600
|
||||||
|
assert path.parent.stat().st_mode & 0o777 == 0o700
|
||||||
|
assert [p.name for p in path.parent.iterdir()] == ["root_password"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_different_homes_get_different_passwords(
|
||||||
|
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
||||||
|
) -> None:
|
||||||
|
one = _secret.root_password()
|
||||||
|
monkeypatch.setenv("SQL_DRILLS_CONFIG", str(tmp_path / "other"))
|
||||||
|
assert _secret.root_password() != one
|
||||||
|
|
||||||
|
|
||||||
|
def test_losing_the_race_reads_the_winners_password(
|
||||||
|
monkeypatch: pytest.MonkeyPatch,
|
||||||
|
) -> None:
|
||||||
|
path = _paths.config_dir() / "root_password"
|
||||||
|
real_link = os.link
|
||||||
|
|
||||||
|
def winner_first(src: StrPath, dst: StrPath) -> None:
|
||||||
|
path.write_text("winner\n", encoding="utf-8")
|
||||||
|
real_link(src, dst)
|
||||||
|
|
||||||
|
monkeypatch.setattr(os, "link", winner_first)
|
||||||
|
assert _secret.root_password() == "winner"
|
||||||
|
assert [p.name for p in path.parent.iterdir()] == ["root_password"]
|
||||||
Loading…
Reference in New Issue
Block a user