From 9386bf154db8738fbf5b7bc7201a0d7150359f83 Mon Sep 17 00:00:00 2001 From: Caleb Kinney Date: Wed, 2 Dec 2026 10:58:31 -0500 Subject: [PATCH 01/24] Refactor day_template.py: streamline input handling and simplify part solution logic --- elf/templates/day_template.py | 96 ++++++++++------------------------- 1 file changed, 27 insertions(+), 69 deletions(-) diff --git a/elf/templates/day_template.py b/elf/templates/day_template.py index 8a3c3f0..42dd364 100644 --- a/elf/templates/day_template.py +++ b/elf/templates/day_template.py @@ -1,86 +1,44 @@ # %% Setup -from hashlib import sha256 -from os import getenv - -from elf import get_puzzle_input, submit_puzzle_answer -from elf.utils import resolve_session +from elf import get_puzzle_input, submit_puzzle_answer # noqa: F401 (used in Submit) +from elf.helpers import parse_input YEAR = 2025 DAY = 1 PART = 1 -USE_SAMPLE = False -SUBMIT = False - -part1_answer = part2_answer = None -input_key = parsed_key = answer_key = None - -if type(PART) is not int or PART not in (1, 2): - raise ValueError("PART must be 1 or 2") +USE_SAMPLE = True -# %% Load Input -SUBMIT = False -part1_answer = part2_answer = None -input_key = parsed_key = answer_key = None +# Expected answers from the puzzle example. Leave as None to skip a check. +SAMPLE_ANSWERS = {1: None, 2: None} +expected = SAMPLE_ANSWERS[PART] sample = """\ """ -input_session_key = None -if USE_SAMPLE: - raw = sample -else: - _session = resolve_session(None) - try: - raw = get_puzzle_input(YEAR, DAY, session=_session) - input_session_key = sha256(_session.encode()).digest() - finally: - del _session -lines = raw.splitlines() -input_key = (YEAR, DAY, USE_SAMPLE) +data = parse_input(sample if USE_SAMPLE else get_puzzle_input(YEAR, DAY)) -# %% Parse Input -SUBMIT = False -part1_answer = part2_answer = None -parsed_key = answer_key = None - -data = lines -parsed_key = input_key +part1 = part2 = None # %% Part 1 -if PART == 1 and parsed_key == (YEAR, DAY, USE_SAMPLE): - SUBMIT = False - part1_answer = answer_key = None - part1_answer = None # Your Part 1 answer - if part1_answer is not None: - answer_key = (*parsed_key, 1) - print("Part 1:", part1_answer) +if PART == 1: + # Solve Part 1 here. + part1 = None + + if USE_SAMPLE and expected is not None: + assert part1 == expected, f"Expected {expected!r}, got {part1!r}" + print("Part 1:", part1) # %% Part 2 -if PART == 2 and parsed_key == (YEAR, DAY, USE_SAMPLE): - SUBMIT = False - part2_answer = answer_key = None - part2_answer = None # Your Part 2 answer - if part2_answer is not None: - answer_key = (*parsed_key, 2) - print("Part 2:", part2_answer) +if PART == 2: + # Solve Part 2 here. + part2 = None + + if USE_SAMPLE and expected is not None: + assert part2 == expected, f"Expected {expected!r}, got {part2!r}" + print("Part 2:", part2) # %% Submit -# Check the answer, then set SUBMIT = True in the console. -submit_requested, SUBMIT = SUBMIT is True, False -if ( - submit_requested - and USE_SAMPLE is False - and type(PART) is int - and answer_key == (YEAR, DAY, False, PART) -): - answer = part1_answer if PART == 1 else part2_answer - if answer is not None: - _session = getenv("AOC_SESSION") - try: - if _session and sha256(_session.encode()).digest() == input_session_key: - submission = submit_puzzle_answer(YEAR, DAY, PART, answer, session=_session) - print(submission) - else: - print("Advent of Code session changed. Rerun from Load Input before submitting.") - finally: - del _session +# Rerun Setup and the selected part with USE_SAMPLE = False. +# if not USE_SAMPLE and PART == 1 and part1 is not None: +# submit_puzzle_answer(YEAR, DAY, 1, part1) +# if not USE_SAMPLE and PART == 2 and part2 is not None: +# submit_puzzle_answer(YEAR, DAY, 2, part2) From 24f81edb20c0b41eb1bb2a4effe8eb10ea313ce6 Mon Sep 17 00:00:00 2001 From: Caleb Kinney Date: Wed, 2 Dec 2026 10:58:56 -0500 Subject: [PATCH 02/24] Update CI workflow and tests: add puzzle execution step and refactor test cases for clarity --- .github/workflows/quality.yml | 8 + tests/test_day_template.py | 277 +++++++++++----------------------- 2 files changed, 99 insertions(+), 186 deletions(-) diff --git a/.github/workflows/quality.yml b/.github/workflows/quality.yml index 6761943..33a5de1 100644 --- a/.github/workflows/quality.yml +++ b/.github/workflows/quality.yml @@ -67,3 +67,11 @@ jobs: run: | uvx --from twine twine check dist/* uvx check-wheel-contents dist/*.whl + + - name: Run a puzzle generated by the installed wheel + if: matrix.os == 'ubuntu-latest' && matrix.python-version == '3.11' + run: | + uv pip install --reinstall --no-deps dist/*.whl + cd "$RUNNER_TEMP" + "$GITHUB_WORKSPACE/.venv/bin/elf" new 2016 15 + "$GITHUB_WORKSPACE/.venv/bin/python" 2016/day15.py diff --git a/tests/test_day_template.py b/tests/test_day_template.py index faf48f7..71e8750 100644 --- a/tests/test_day_template.py +++ b/tests/test_day_template.py @@ -1,7 +1,6 @@ import ast -import importlib.util -import re from pathlib import Path +from unittest.mock import Mock import pytest @@ -12,26 +11,12 @@ TEMPLATE = Path(__file__).parents[1] / "elf" / "templates" / "day_template.py" CELL_MARKERS = [ "# %% Setup", - "# %% Load Input", - "# %% Parse Input", "# %% Part 1", "# %% Part 2", "# %% Submit", ] -def _mock_template_api(monkeypatch): - submissions = [] - monkeypatch.setenv("AOC_SESSION", "account-a") - monkeypatch.setattr(elf, "get_puzzle_input", lambda year, day, *, session: "10\n20\n") - monkeypatch.setattr( - elf, - "submit_puzzle_answer", - lambda *args, **kwargs: submissions.append((args, kwargs)), - ) - return submissions - - def test_template_is_valid_python_with_expected_cells(): source = TEMPLATE.read_text(encoding="utf-8") tree = ast.parse(source, filename=str(TEMPLATE)) @@ -69,174 +54,94 @@ def test_template_creation_supports_nested_output_and_validates_day(tmp_path): create_day_template(2025, 13, tmp_path / "day13.py") -def _implemented_source(): - return ( - render_day_template(2026, 1) - .replace(" part1_answer = None", " part1_answer = 0") - .replace(" part2_answer = None", " part2_answer = len(data)") - ) - - -@pytest.mark.parametrize( - ("part", "expected_answer", "expected_output"), - [ - (1, 0, "Part 1: 0\n"), - (2, 2, "Part 2: 2\n"), - ], -) -def test_rendered_template_runs_only_selected_part( - monkeypatch, capsys, part, expected_answer, expected_output -): - submissions = _mock_template_api(monkeypatch) - source = _implemented_source().replace("PART = 1", f"PART = {part}") - namespace = {"__name__": "__main__"} - - exec(compile(source, "day01.py", "exec"), namespace) - - assert namespace["raw"] == "10\n20\n" - assert namespace["lines"] == namespace["data"] == ["10", "20"] - assert namespace[f"part{part}_answer"] == expected_answer - assert namespace[f"part{3 - part}_answer"] is None - assert submissions == [] - assert capsys.readouterr().out == expected_output - - -def test_unfinished_rendered_template_is_silent(monkeypatch, capsys): - submissions = _mock_template_api(monkeypatch) - source = render_day_template(2026, 1) - namespace = {"__name__": "__main__"} - - exec(compile(source, "day01.py", "exec"), namespace) - - assert namespace["part1_answer"] is None - assert namespace["part2_answer"] is None - assert submissions == [] - assert capsys.readouterr().out == "" - - -def _run_cells(source): - cells = re.split(r"(?=^# %% )", source, flags=re.MULTILINE)[1:] - namespace = {"__name__": "__main__"} - - def run(*names): - for name in names: - cell = cells[CELL_MARKERS.index(f"# %% {name}")] - exec(compile(cell, "day01.py", "exec"), namespace) - - run("Setup") - return run, namespace - - -def test_template_cells_track_input_and_selected_part(monkeypatch, capsys): - submissions = _mock_template_api(monkeypatch) - fetches = [] - - def fetch(year, day, *, session): - fetches.append((year, day, session)) - return "10\n20\n" - +@pytest.fixture +def apis(monkeypatch): + monkeypatch.delenv("AOC_SESSION", raising=False) + fetch = Mock(return_value=" real \n\ninput\n") + submit = Mock() monkeypatch.setattr(elf, "get_puzzle_input", fetch) - source = _implemented_source().replace('\n"""\n', '\nsample\n"""\n') - run, namespace = _run_cells(source) - namespace.update(PART=2, USE_SAMPLE=True, SUBMIT=True) - run("Load Input", "Parse Input", "Part 1", "Part 2", "Submit") - - assert namespace["raw"] == "sample\n" - assert namespace["lines"] == namespace["data"] == ["sample"] - assert namespace["part2_answer"] == 1 - assert fetches == submissions == [] - assert capsys.readouterr().out == "Part 2: 1\n" - - namespace["USE_SAMPLE"] = False - run("Part 2", "Submit") - assert submissions == [] - - run("Load Input", "Parse Input", "Part 2") - for setting, changed_value in [("YEAR", 2024), ("DAY", 2), ("PART", 1)]: - original_value = namespace[setting] - namespace[setting] = changed_value - namespace["SUBMIT"] = True - run("Submit") - namespace[setting] = original_value - assert submissions == [] - - namespace["SUBMIT"] = True - run("Submit") - assert fetches == [(2026, 1, "account-a")] - assert submissions == [((2026, 1, 2, 2), {"session": "account-a"})] - assert capsys.readouterr().out == "Part 2: 2\nNone\n" - - -@pytest.mark.parametrize("failed_cell", ["Load Input", "Parse Input"]) -def test_failed_reload_or_reparse_invalidates_answers(monkeypatch, failed_cell): - submissions = _mock_template_api(monkeypatch) - source = _implemented_source().replace("data = lines", "data = list(map(int, lines))") - run, namespace = _run_cells(source) - run("Load Input", "Parse Input", "Part 1") - namespace.update(SUBMIT=True, lines=["invalid integer"]) - - def fail_fetch(year, day, *, session): - raise ValueError("Input unavailable") - - namespace["get_puzzle_input"] = fail_fetch - with pytest.raises(ValueError): - run(failed_cell) - run("Part 1", "Submit") - - assert namespace["part1_answer"] is None - assert namespace["part2_answer"] is None - assert submissions == [] - - -def test_template_requires_reloaded_input_after_account_switch(monkeypatch, capsys): - submissions = _mock_template_api(monkeypatch) - inputs = {"account-a": "10\n20\n", "account-b": "30\n"} - monkeypatch.setattr(elf, "get_puzzle_input", lambda year, day, *, session: inputs[session]) - run, namespace = _run_cells(_implemented_source()) - namespace["PART"] = 2 - run("Load Input", "Parse Input", "Part 2") - namespace["SUBMIT"] = True - - monkeypatch.setenv("AOC_SESSION", "account-b") - run("Submit") - - assert submissions == [] - assert "Rerun from Load Input" in capsys.readouterr().out - - run("Load Input", "Parse Input", "Part 2") - namespace["SUBMIT"] = True - run("Submit") - assert submissions == [((2026, 1, 2, 1), {"session": "account-b"})] - assert "_session" not in namespace - - -def test_submission_approval_is_single_use(monkeypatch): - submissions = _mock_template_api(monkeypatch) - run, namespace = _run_cells(_implemented_source()) - run("Load Input", "Parse Input", "Part 1") - namespace["SUBMIT"] = True - run("Submit", "Submit") - - assert [args[1] for args, _ in submissions] == [1] - - namespace.update(DAY=2, SUBMIT=True) - run("Load Input", "Parse Input", "Part 1", "Submit") - assert [args[1] for args, _ in submissions] == [1] - - namespace["SUBMIT"] = True - run("Submit") - assert [args[1] for args, _ in submissions] == [1, 2] - - -def test_importing_template_never_submits_answers(monkeypatch, capsys): - submissions = _mock_template_api(monkeypatch) - spec = importlib.util.spec_from_file_location("elf_day_template", TEMPLATE) - assert spec is not None and spec.loader is not None - module = importlib.util.module_from_spec(spec) - - spec.loader.exec_module(module) - - assert module.part1_answer is None - assert module.part2_answer is None - assert submissions == [] - assert capsys.readouterr().out == "" + monkeypatch.setattr(elf, "submit_puzzle_answer", submit) + return fetch, submit + + +def test_default_script_is_offline(apis, capsys): + fetch, submit = apis + exec(render_day_template(2026, 2), {}) + fetch.assert_not_called() + submit.assert_not_called() + assert capsys.readouterr().out == "Part 1: None\n" + + +@pytest.mark.parametrize("part, answer", [(1, 0), (2, "")]) +@pytest.mark.parametrize("expected_matches", [True, False]) +def test_sample_solution(apis, capsys, part, answer, expected_matches): + fetch, submit = apis + source = ( + render_day_template(2026, 2) + .replace("PART = 1", f"PART = {part}") + .replace('\n"""\n', '\n padded \n\nline\n"""\n') + .replace(f"{part}: None", f"{part}: {answer!r}") + .replace(f" part{3 - part} = None", " raise RuntimeError('inactive part')") + ) + actual = answer if expected_matches else "wrong" + source = source.replace( + f" part{part} = None", + f" first = data[0]\n part{part} = {actual!r}", + ) + namespace = {} + if expected_matches: + exec(source, namespace) + assert namespace["data"] == [" padded ", "", "line"] + assert namespace["first"] == " padded " + assert namespace[f"part{part}"] == answer + assert capsys.readouterr().out == f"Part {part}: {answer}\n" + else: + with pytest.raises(AssertionError) as exc: + exec(source, namespace) + assert str(exc.value) == f"Expected {answer!r}, got {actual!r}" + fetch.assert_not_called() + submit.assert_not_called() + + +@pytest.mark.parametrize("part", [1, 2]) +def test_missing_expected_answer_skips_check(apis, part): + source = ( + render_day_template(2026, 2) + .replace("PART = 1", f"PART = {part}") + .replace(f" part{part} = None", f" part{part} = 42") + ) + namespace = {} + exec(source, namespace) + assert namespace[f"part{part}"] == 42 + + +@pytest.mark.parametrize("part", [1, 2]) +def test_real_input_skips_sample_assertions(apis, part): + fetch, submit = apis + source = ( + render_day_template(2016, 15) + .replace("USE_SAMPLE = True", "USE_SAMPLE = False") + .replace("PART = 1", f"PART = {part}") + .replace(f"{part}: None", f"{part}: -1") + .replace(f" part{part} = None", f" part{part} = len(data)") + ) + namespace = {} + exec(source, namespace) + fetch.assert_called_once_with(2016, 15) + assert namespace["data"] == [" real ", "", "input"] + assert namespace[f"part{part}"] == 3 + submit.assert_not_called() + + +@pytest.mark.parametrize("part", [1, 2]) +def test_uncommented_submission_checks_mode_part_and_answer(apis, part): + _, submit = apis + block = render_day_template(2026, 2).split("# %% Submit\n")[1].splitlines()[1:] + assert all(line.startswith("# ") for line in block) + source = "\n".join(line.removeprefix("# ") for line in block) + namespace = dict(YEAR=2026, DAY=2, PART=part, part1=0, part2="", submit_puzzle_answer=submit) + exec(source, dict(namespace, USE_SAMPLE=True)) + exec(source, {**namespace, "USE_SAMPLE": False, f"part{part}": None}) + submit.assert_not_called() + exec(source, dict(namespace, USE_SAMPLE=False)) + submit.assert_called_once_with(2026, 2, part, namespace[f"part{part}"]) From ab6b1bcc17ba6810d7614bc0c45d4b93574216d7 Mon Sep 17 00:00:00 2001 From: Caleb Kinney Date: Wed, 2 Dec 2026 11:08:29 -0500 Subject: [PATCH 03/24] Refactor submit_answer and submit_to_aoc: improve error handling and add retry logic for rate limiting --- elf/answer.py | 42 +++++++++++++++++++++++++++++++----------- 1 file changed, 31 insertions(+), 11 deletions(-) diff --git a/elf/answer.py b/elf/answer.py index 4b763e4..584ac05 100644 --- a/elf/answer.py +++ b/elf/answer.py @@ -3,6 +3,7 @@ import re import warnings from datetime import UTC, datetime, timedelta +from email.utils import parsedate_to_datetime from enum import Enum, auto from html.parser import HTMLParser @@ -137,9 +138,6 @@ def submit_answer( if level not in (1, 2): raise ValueError(f"Invalid level {level!r}. Puzzle parts are 1 or 2.") - if isinstance(answer, str) and not answer.strip(): - raise ValueError("Answer cannot be empty.") - if year >= current_aoc_year(): status = get_unlock_status(year, day) if not status.unlocked: @@ -154,17 +152,18 @@ def submit_answer( legacy_cache_file = get_cache_guess_file(year, day) cache_file = get_cache_guess_file(year, day, session_token) - try: - migrate_legacy_cache_file(legacy_cache_file, cache_file) - except OSError as exc: - raise SubmissionError(f"Failed to migrate guess cache at {legacy_cache_file}.") from exc - # Serialize the cache check and submission for this account and puzzle. This # prevents two elf processes from both submitting before either records the # result. Guess-cache writes use their own shorter-lived lock. submission_lock = cache_file.with_name(f"{cache_file.name}.submission") try: with cache_file_lock(submission_lock, timeout=30.0): + try: + migrate_legacy_cache_file(legacy_cache_file, cache_file) + except OSError as exc: + raise SubmissionError( + f"Failed to migrate guess cache at {legacy_cache_file}." + ) from exc if cache_file.exists(): cached = check_cached_guesses( year=year, @@ -231,7 +230,7 @@ def submit_to_aoc( if 500 <= response.status_code < 600: raise SubmissionError(f"Server error from Advent of Code (HTTP {response.status_code}).") - if response.status_code != 200: + if response.status_code not in (200, 429): raise SubmissionError(f"Unexpected HTTP status {response.status_code} from Advent of Code.") if looks_like_login_content(response.text): @@ -245,7 +244,11 @@ def submit_to_aoc( parser.feed(response.text) content = parser.text() - message_type = classify_message(content) + message_type = ( + AocMessageType.RECENT_SUBMISSION + if response.status_code == 429 + else classify_message(content) + ) retry_at: datetime | None = None match message_type: case AocMessageType.EMPTY: @@ -262,7 +265,11 @@ def submit_to_aoc( status = SubmissionStatus.TOO_LOW case AocMessageType.RECENT_SUBMISSION: status = SubmissionStatus.WAIT - retry_at = _parse_wait_retry_at(content) or datetime.now(UTC) + WAIT_CACHE_TTL + retry_at = ( + _retry_after_header(response) + or _parse_wait_retry_at(content) + or datetime.now(UTC) + WAIT_CACHE_TTL + ) message = _wait_message(retry_at, cached=False) case AocMessageType.WRONG_LEVEL: # AoC has not judged this answer. The same guess may be valid @@ -509,6 +516,19 @@ def _updated_guess_cache(existing: str, row: dict[str, object]) -> str: return buffer.getvalue() +def _retry_after_header(response: httpx.Response) -> datetime | None: + value = response.headers.get("Retry-After", "").strip() + if not value: + return None + try: + if value.isascii() and value.isdigit(): + return datetime.now(UTC) + timedelta(seconds=int(value)) + deadline = parsedate_to_datetime(value) + return deadline.astimezone(UTC) if deadline.tzinfo else deadline.replace(tzinfo=UTC) + except (ValueError, OverflowError, TypeError): + return None + + def _parse_wait_retry_at(content: str, *, now: datetime | None = None) -> datetime | None: match = _WAIT_TIME_PATTERN.search(content) if match is None: From a5d53d482ff8b823a4d4b62bfdb2f84de8a4d459 Mon Sep 17 00:00:00 2001 From: Caleb Kinney Date: Wed, 2 Dec 2026 11:08:55 -0500 Subject: [PATCH 04/24] Refactor AOCClient HTTP methods: switch to build_request for improved request handling and add test for submission redirect behavior --- elf/aoc_client.py | 10 ++++++++-- tests/test_aoc_client.py | 15 +++++++++++++++ 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/elf/aoc_client.py b/elf/aoc_client.py index 0e65f84..43c078b 100644 --- a/elf/aoc_client.py +++ b/elf/aoc_client.py @@ -77,11 +77,17 @@ def __init__( def _get(self, path: str, params: dict[str, str] | None = None) -> httpx.Response: cookies = {"session": self.session_token} if self.session_token else None - return self._client.get(f"{self.base_url}{path}", params=params, cookies=cookies) + request = self._client.build_request( + "GET", f"{self.base_url}{path}", params=params, cookies=cookies + ) + return self._client.send(request) def _post(self, path: str, data: dict[str, str]) -> httpx.Response: cookies = {"session": self.session_token} if self.session_token else None - return self._client.post(f"{self.base_url}{path}", data=data, cookies=cookies) + request = self._client.build_request( + "POST", f"{self.base_url}{path}", data=data, cookies=cookies + ) + return self._client.send(request, follow_redirects=False) def _get_with_retries( self, diff --git a/tests/test_aoc_client.py b/tests/test_aoc_client.py index f7ca3bf..57c4bc8 100644 --- a/tests/test_aoc_client.py +++ b/tests/test_aoc_client.py @@ -83,3 +83,18 @@ def test_injected_http_client_is_not_closed(monkeypatch): assert transport.is_closed is False transport.close() + + +def test_submission_does_not_follow_a_redirect(): + requests = [] + + def respond(request): + requests.append(request) + return httpx.Response(307, headers={"Location": "/other"}) + + with httpx.Client(transport=httpx.MockTransport(respond), follow_redirects=True) as transport: + response = AOCClient("test-cookie", http_client=transport).submit_answer(2016, 1, "0", 1) + + assert response.status_code == 307 + assert len(requests) == 1 + assert requests[0].method == "POST" From a1d586933af1ecbeec08364fcbe5a25c17ace019 Mon Sep 17 00:00:00 2001 From: Caleb Kinney Date: Wed, 2 Dec 2026 11:09:23 -0500 Subject: [PATCH 05/24] Update cache and guesses handling: improve cache key naming, enhance file writing logic, and add tests for input handling --- elf/cache.py | 10 +++----- elf/guesses.py | 10 +++----- tests/test_guess_cache.py | 22 ++++++++++++++++ tests/test_input_cache.py | 53 +++++++++++++++++++++++++++++++++++++++ 4 files changed, 82 insertions(+), 13 deletions(-) diff --git a/elf/cache.py b/elf/cache.py index 3a27171..eb161a2 100644 --- a/elf/cache.py +++ b/elf/cache.py @@ -79,7 +79,7 @@ def get_cache_leaderboard_file( ) -> Path: """Return a leaderboard path scoped to its authentication mechanism.""" if view_key: - scope = "views" + scope = "view-keys" # Older view caches could be populated with a session cookie. fingerprint = _credential_fingerprint("view-key", view_key) elif session_token: scope = "accounts" @@ -147,18 +147,14 @@ def atomic_write_bytes(path: Path, content: bytes) -> None: ) temporary_path = Path(temporary_name) try: - _make_private(temporary_path, _PRIVATE_FILE_MODE) + # mkstemp creates a private file. fdopen owns the descriptor from here. with os.fdopen(file_descriptor, "wb") as temporary_file: temporary_file.write(content) temporary_file.flush() os.fsync(temporary_file.fileno()) os.replace(temporary_path, path) - _make_private(path, _PRIVATE_FILE_MODE) - except BaseException: - with suppress(OSError): - os.close(file_descriptor) + finally: temporary_path.unlink(missing_ok=True) - raise @contextmanager diff --git a/elf/guesses.py b/elf/guesses.py index 3b15196..95f9530 100644 --- a/elf/guesses.py +++ b/elf/guesses.py @@ -1,3 +1,4 @@ +import os from datetime import UTC, datetime from pathlib import Path @@ -8,7 +9,7 @@ from .cache import get_cache_dir, get_cache_guess_file from .exceptions import ElfError from .models import Guess, SubmissionStatus -from .utils import read_guesses +from .utils import read_guesses, resolve_session def get_guesses(year: int, day: int, session: str | None = None) -> Group: @@ -25,13 +26,10 @@ def get_guesses(year: int, day: int, session: str | None = None) -> Group: def _resolve_guess_file(year: int, day: int, session: str | None) -> Path: - if session: - return get_cache_guess_file(year, day, session) + if session or os.getenv("AOC_SESSION"): + return get_cache_guess_file(year, day, resolve_session(session)) legacy_file = get_cache_guess_file(year, day) - if legacy_file.exists(): - return legacy_file - pattern = f"accounts/*/{year:04d}/{day:02d}/guesses.csv" matches = list(get_cache_dir().glob(pattern)) if len(matches) == 1: diff --git a/tests/test_guess_cache.py b/tests/test_guess_cache.py index 341ac51..4e82197 100644 --- a/tests/test_guess_cache.py +++ b/tests/test_guess_cache.py @@ -4,6 +4,8 @@ from elf.answer import check_cached_guesses, write_guess_cache from elf.cache import get_cache_guess_file +from elf.exceptions import ElfError +from elf.guesses import _resolve_guess_file from elf.models import SubmissionStatus from elf.utils import read_guesses @@ -143,3 +145,23 @@ def test_check_cached_guesses_detects_duplicate_with_whitespace( ) assert result.status == SubmissionStatus.CORRECT + + +def test_text_guess_with_non_integer_digits_retains_completion(guess_file_factory): + guess_file_factory(2016, 2, [("2024-12-01", "1", "²", "CORRECT")]) + cached = check_cached_guesses(2016, 2, 1, "²", numeric_answer=None) + assert cached.status is SubmissionStatus.CORRECT + + +def test_offline_lookup_prefers_scoped_history_after_migration(monkeypatch, tmp_path): + monkeypatch.setenv("ELF_CACHE_DIR", str(tmp_path)) + monkeypatch.delenv("AOC_SESSION", raising=False) + for account in [None, "example"]: + write_guess_cache(2016, 1, 1, 42, SubmissionStatus.CORRECT, account) + scoped = get_cache_guess_file(2016, 1, "example") + assert _resolve_guess_file(2016, 1, None) == scoped + write_guess_cache(2016, 1, 1, 10, SubmissionStatus.TOO_LOW, "other") + with pytest.raises(ElfError, match="multiple accounts"): + _resolve_guess_file(2016, 1, None) + monkeypatch.setenv("AOC_SESSION", "example") + assert _resolve_guess_file(2016, 1, None) == scoped diff --git a/tests/test_input_cache.py b/tests/test_input_cache.py index 50e0fb6..cff3369 100644 --- a/tests/test_input_cache.py +++ b/tests/test_input_cache.py @@ -1,3 +1,5 @@ +import time +from concurrent.futures import ThreadPoolExecutor from typing import ClassVar import httpx @@ -67,3 +69,54 @@ def test_login_html_is_never_returned_or_cached_as_input(monkeypatch, tmp_path): get_input(2024, 1, "expired") assert cache_file.read_text() == "To play, please identify yourself" + + +@pytest.mark.parametrize( + ("status", "media_type", "body"), + [ + (206, "text/plain", b"partial"), + (204, "text/plain", b""), + (200, "text/html", b"Maintenance"), + (200, "text/plain", b"\xff"), + ], +) +def test_invalid_input_response_leaves_cache_empty(monkeypatch, tmp_path, status, media_type, body): + monkeypatch.setenv("ELF_CACHE_DIR", str(tmp_path)) + monkeypatch.setattr("elf.input.AOCClient", _FakeInputClient) + _FakeInputClient.responses = { + "example": httpx.Response(status, headers={"Content-Type": media_type}, content=body) + } + with pytest.raises(InputFetchError): + get_input(2016, 1, "example") + assert not get_cache_input_file(2016, 1, "example").exists() + + +@pytest.mark.parametrize("text", [" row \r\n\r\n", ""]) +def test_concurrent_reads_preserve_exact_input(monkeypatch, tmp_path, text): + monkeypatch.setenv("ELF_CACHE_DIR", str(tmp_path)) + + class SlowClient(_FakeInputClient): + def fetch_input(self, year, day): + time.sleep(0.03) + return super().fetch_input(year, day) + + monkeypatch.setattr("elf.input.AOCClient", SlowClient) + SlowClient.calls = [] + SlowClient.responses = {"example": _response(text)} + with ThreadPoolExecutor(max_workers=4) as pool: + results = list(pool.map(lambda _: get_input(2016, 1, "example"), range(4))) + assert results == [text] * 4 + assert SlowClient.calls == ["example"] + + +def test_warm_scoped_input_still_claims_legacy_file(monkeypatch, tmp_path): + monkeypatch.setenv("ELF_CACHE_DIR", str(tmp_path)) + monkeypatch.setattr("elf.input.AOCClient", _FakeInputClient) + _FakeInputClient.responses = {"account-b": _response("b")} + _FakeInputClient.calls = [] + atomic_write_text(get_cache_input_file(2016, 1), "older a") + atomic_write_text(get_cache_input_file(2016, 1, "account-a"), "a") + + assert get_input(2016, 1, "account-a") == "a" + assert get_input(2016, 1, "account-b") == "b" + assert _FakeInputClient.calls == ["account-b"] From 92322657e5800f31032fed0a178502e718229c8e Mon Sep 17 00:00:00 2001 From: Caleb Kinney Date: Wed, 2 Dec 2026 11:09:38 -0500 Subject: [PATCH 06/24] Update cache command output: enhance cache directory display and count of cached files --- elf/cli.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/elf/cli.py b/elf/cli.py index 5206317..678436b 100644 --- a/elf/cli.py +++ b/elf/cli.py @@ -342,12 +342,12 @@ def cache_cmd() -> None: cache_dir = get_cache_dir() if not cache_dir.exists(): console.print("[dim]No cache directory found yet.[/dim]") - console.print(f"[dim]Expected location: {cache_dir}[/dim]") + console.print(Text(f"Expected location: {cache_dir}", style="dim")) return - files = [p for p in cache_dir.rglob("*") if p.is_file()] - console.print(f"[green]Cache directory:[/green] {cache_dir}") - console.print(f"[green]Cached files:[/green] {len(files)}") + file_count = sum(1 for p in cache_dir.rglob("*") if p.is_file()) + console.print(Text.assemble(("Cache directory: ", "green"), str(cache_dir))) + console.print(f"[green]Cached files:[/green] {file_count}") console.print("[dim]To clear the cache, delete this directory manually.[/dim]") From c8db7c9f7f8d10adfe14266f5ae91dc3c0856d0e Mon Sep 17 00:00:00 2001 From: Caleb Kinney Date: Wed, 2 Dec 2026 11:09:54 -0500 Subject: [PATCH 07/24] Update private leaderboard documentation and enhance test coverage for puzzle APIs --- elf/client.py | 4 ++-- tests/test_client_api.py | 25 +++++++++++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/elf/client.py b/elf/client.py index 692e284..5e1f49f 100644 --- a/elf/client.py +++ b/elf/client.py @@ -132,7 +132,7 @@ def get_private_leaderboard( of ``AOC_SESSION`` is used. view_key The read-only “share code” for the leaderboard. When present, a session - token is optional. + token is unused. fmt ``MODEL`` returns a Leaderboard, ``TABLE`` returns a Rich table, ``JSON`` preserves the Advent of Code payload, and ``CSV`` produces @@ -157,7 +157,7 @@ def get_private_leaderboard( Notes ----- Responses are cached for 15 minutes per event, board, and credential. - When a view key is provided, it determines the cache scope. + A view key authorizes the request on its own and determines the cache scope. """ if year < 2015: raise ValueError(f"Invalid year {year!r}. Advent of Code started in 2015.") diff --git a/tests/test_client_api.py b/tests/test_client_api.py index 17f3b42..96de6b2 100644 --- a/tests/test_client_api.py +++ b/tests/test_client_api.py @@ -1,11 +1,15 @@ +from unittest.mock import Mock + import pytest +from elf.cache import atomic_write_text, get_cache_input_file from elf.client import ( get_private_leaderboard, get_puzzle_input, get_user_status, submit_puzzle_answer, ) +from elf.exceptions import ElfError from elf.models import OutputFormat @@ -44,6 +48,18 @@ def fake_submit(year, day, level, answer, session): assert submitted == [(2023, 2, 1, 12345, "manual-session")] +def test_puzzle_apis_use_environment_session(monkeypatch, tmp_path): + monkeypatch.setenv("AOC_SESSION", "example-account") + monkeypatch.setenv("ELF_CACHE_DIR", str(tmp_path)) + atomic_write_text(get_cache_input_file(2016, 15, "example-account"), "cached example") + assert get_puzzle_input(2016, 15) == "cached example" + + submit = Mock() + monkeypatch.setattr("elf.answer.submit_to_aoc", submit) + submit_puzzle_answer(2016, 15, 1, 42) + submit.assert_called_once_with(2016, 15, 1, 42, "example-account") + + def test_get_private_leaderboard_forwards_credentials(monkeypatch): calls = [] @@ -107,3 +123,12 @@ def test_status_csv_is_rejected_before_authentication(monkeypatch): with pytest.raises(ValueError, match="only supported for private leaderboards"): get_user_status(2025, fmt=OutputFormat.CSV) + + +def test_invalid_cookie_rejected_before_network_or_cache(monkeypatch, tmp_path): + monkeypatch.setenv("ELF_CACHE_DIR", str(tmp_path)) + monkeypatch.setenv("AOC_SESSION", "example;other=value") + with pytest.raises(ElfError, match="Invalid session cookie") as error: + get_puzzle_input(2016, 1) + assert "example" not in str(error.value) + assert list(tmp_path.iterdir()) == [] From eac7a11d97f751c6204c97e07e97692cba3b6cd4 Mon Sep 17 00:00:00 2001 From: Caleb Kinney Date: Wed, 2 Dec 2026 11:10:04 -0500 Subject: [PATCH 08/24] Enhance input fetching logic: implement legacy cache handling, improve error reporting, and ensure proper input validation --- elf/input.py | 55 ++++++++++++++++++++++++++++++++++++---------------- 1 file changed, 38 insertions(+), 17 deletions(-) diff --git a/elf/input.py b/elf/input.py index f8e420c..efa8092 100644 --- a/elf/input.py +++ b/elf/input.py @@ -1,8 +1,11 @@ +from pathlib import Path + import httpx from .aoc_client import AOCClient from .cache import ( atomic_write_text, + cache_file_lock, get_cache_input_file, migrate_legacy_cache_file, ) @@ -42,16 +45,37 @@ def get_input(year: int, day: int, session: str | None) -> str: legacy_cache_file = get_cache_input_file(year, day) cache_file = get_cache_input_file(year, day, session_token) + # Claim legacy data even when this account already has a scoped copy. + if not legacy_cache_file.is_file(): + cached = _cached_input(cache_file) + if cached is not None: + return cached + + try: + with cache_file_lock(cache_file, timeout=60): + migrate_legacy_cache_file(legacy_cache_file, cache_file) + cached = _cached_input(cache_file) + if cached is not None: + return cached + + text = _fetch_input(year, day, session_token) + atomic_write_text(cache_file, text) + return text + except OSError as exc: + raise InputFetchError(f"Failed to access puzzle input cache at {cache_file}.") from exc + + +def _cached_input(path: Path) -> str | None: try: - migrate_legacy_cache_file(legacy_cache_file, cache_file) - if cache_file.exists(): - cached_input = cache_file.read_text(encoding="utf-8") - if not looks_like_login_content(cached_input): - return cached_input - except (OSError, UnicodeError): - # A damaged or inaccessible cache should not prevent a fresh fetch. - pass + text = path.read_bytes().decode("utf-8") + except (FileNotFoundError, UnicodeError): + return None + except OSError as exc: + raise InputFetchError(f"Failed to read puzzle input cache at {path}.") from exc + return None if looks_like_login_content(text) else text + +def _fetch_input(year: int, day: int, session_token: str) -> str: if year >= current_aoc_year(): status = get_unlock_status(year, day) if not status.unlocked: @@ -86,19 +110,16 @@ def get_input(year: int, day: int, session: str | None) -> str: unexpected_status_message="Unexpected HTTP error: {status_code}.", ) - text = response.text - if looks_like_login_page(response): raise InputFetchError( "Session cookie invalid or expired. " "Update AOC_SESSION with a valid 'session' cookie from your browser." ) - input_data = text - + media_type = response.headers.get("content-type", "").partition(";")[0].strip().lower() + if response.status_code != 200 or media_type not in ("", "text/plain"): + raise InputFetchError("Expected a complete plain-text puzzle input from Advent of Code.") try: - atomic_write_text(cache_file, input_data) - except OSError as exc: - raise InputFetchError(f"Failed to cache puzzle input at {cache_file}.") from exc - - return input_data + return response.content.decode("utf-8") + except UnicodeDecodeError as exc: + raise InputFetchError("Puzzle input is not valid UTF-8.") from exc From 87ee901b76967a60dff43882a0416295f4a16a09 Mon Sep 17 00:00:00 2001 From: Caleb Kinney Date: Wed, 2 Dec 2026 11:10:15 -0500 Subject: [PATCH 09/24] Add MD5 hashing and integer extraction functions; implement tests for new helpers --- elf/helpers.py | 42 +++++++++++++++++++++++ tests/test_helpers.py | 79 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 121 insertions(+) create mode 100644 tests/test_helpers.py diff --git a/elf/helpers.py b/elf/helpers.py index 4b6331a..7e2d240 100644 --- a/elf/helpers.py +++ b/elf/helpers.py @@ -1,3 +1,5 @@ +import hashlib +import re import time from collections.abc import Callable from functools import wraps @@ -88,3 +90,43 @@ def read_input(path: Path) -> str: raise FileNotFoundError(f"Input file not found: {path}. Please add the missing file.") return path.read_text(encoding="utf-8").strip() + + +def md5(value: str) -> str: + """Return the hexadecimal MD5 digest of UTF-8 text for puzzle use only.""" + return hashlib.md5(value.encode("utf-8"), usedforsecurity=False).hexdigest() + + +def ints(text: str) -> list[int]: + """Extract signed ASCII decimal integers from left to right. + + A sign belongs to the digit run immediately after it, even inside a word. + For example, "r2: 3-5, --7" gives [2, 3, -5, -7]. For a range with a + hyphen separator, split on the separator instead. No matches gives []. + """ + return [int(token) for token in re.findall(r"[+-]?[0-9]+", text)] + + +def neighbors4(point: tuple[int, int]) -> tuple[tuple[int, int], ...]: + """Return the four adjacent (row, column) pairs in a tuple. + + Rows increase downward. Order is up, left, right, down (reading order). + The center is excluded and coordinates are unbounded. + """ + row, col = point + return (row - 1, col), (row, col - 1), (row, col + 1), (row + 1, col) + + +def neighbors8(point: tuple[int, int]) -> tuple[tuple[int, int], ...]: + """Return the eight surrounding (row, column) pairs in a tuple. + + Scan the three rows from top to bottom, each from left to right, skipping + the center. Diagonals are included and coordinates are unbounded. + """ + row, col = point + return tuple((row + dr, col + dc) for dr in (-1, 0, 1) for dc in (-1, 0, 1) if dr or dc) + + +def manhattan(a: tuple[int, int], b: tuple[int, int]) -> int: + """Return the sum of the absolute row and column differences between two points.""" + return abs(a[0] - b[0]) + abs(a[1] - b[1]) diff --git a/tests/test_helpers.py b/tests/test_helpers.py new file mode 100644 index 0000000..dbbbb64 --- /dev/null +++ b/tests/test_helpers.py @@ -0,0 +1,79 @@ +import pytest + +from elf.helpers import ints, manhattan, md5, neighbors4, neighbors8, parse_input, read_input, timer + + +@pytest.mark.parametrize( + ("value", "digest"), + [ + ("", "d41d8cd98f00b204e9800998ecf8427e"), + ("abc", "900150983cd24fb0d6963f7d28e17f72"), + ("café", "07117fe4a1ebd544965dc19573183da2"), + ], +) +def test_md5(value, digest): + assert md5(value) == digest + + +@pytest.mark.parametrize( + ("text", "expected"), + [ + ("Sensor at x=-12, y=34", [-12, 34]), + ("r2: 3-5, --7, +-8, -+9", [2, 3, -5, -7, -8, 9]), + ("+004, - 1, 0, 3.14", [4, 1, 0, 3, 14]), + ("", []), + ("no ASCII digits: 2", []), + ], +) +def test_ints(text, expected): + assert ints(text) == expected + + +def test_neighbors4_in_reading_order_at_origin(): + assert neighbors4((0, 0)) == ((-1, 0), (0, -1), (0, 1), (1, 0)) + + +def test_neighbors8_in_reading_order_at_offset(): + assert neighbors8((-1, 3)) == ( + (-2, 2), + (-2, 3), + (-2, 4), + (-1, 2), + (-1, 4), + (0, 2), + (0, 3), + (0, 4), + ) + + +@pytest.mark.parametrize( + ("a", "b", "distance"), + [((4, 2), (4, 2), 0), ((-3, 2), (2, -4), 11), ((0, 8), (0, 3), 5)], +) +def test_manhattan(a, b, distance): + assert manhattan(a, b) == manhattan(b, a) == distance + + +def test_public_input_helpers_preserve_their_whitespace_conventions(tmp_path): + path = tmp_path / "map.txt" + path.write_text(" ø\n\n x \n", encoding="utf-8") + assert parse_input(path.read_text(encoding="utf-8")) == [" ø", "", " x "] + assert read_input(path) == "ø\n\n x" + assert parse_input("") == [] + with pytest.raises(FileNotFoundError): + read_input(tmp_path / "missing.txt") + + +@pytest.mark.parametrize("enabled", [False, True]) +def test_timer_preserves_return_value_and_optional_reporting(enabled): + messages = [] + + @timer(enabled=enabled, logger=messages.append) + def double(value): + return 2 * value + + assert double(0) == 0 + assert double.__name__ == "double" + assert len(messages) == int(enabled) + if enabled: + assert "double" in messages[0] From 47746f5818fc9296f6de7d0c91cb69e87804ce44 Mon Sep 17 00:00:00 2001 From: Caleb Kinney Date: Wed, 2 Dec 2026 11:10:40 -0500 Subject: [PATCH 10/24] Refactor leaderboard handling: streamline session token resolution, enhance cache reading, and improve error handling in leaderboard fetching --- elf/leaderboard.py | 40 ++++++++++++++------------------- tests/test_leaderboard_cache.py | 33 +++++++++++++++++++++++++++ tests/test_leaderboard_csv.py | 7 ++++-- tests/test_leaderboard_table.py | 7 ++++-- 4 files changed, 60 insertions(+), 27 deletions(-) diff --git a/elf/leaderboard.py b/elf/leaderboard.py index 40f61ee..8f261d0 100644 --- a/elf/leaderboard.py +++ b/elf/leaderboard.py @@ -1,6 +1,5 @@ import csv import json -import os import time import warnings from datetime import UTC, datetime, timedelta @@ -20,7 +19,7 @@ cache_file_lock, get_cache_leaderboard_file, ) -from .exceptions import LeaderboardFetchError, MissingSessionTokenError +from .exceptions import LeaderboardFetchError from .models import Leaderboard, Member, OutputFormat from .utils import handle_http_errors, resolve_session @@ -50,11 +49,8 @@ def get_leaderboard( if board_id <= 0: raise ValueError("Board ID must be a positive integer.") - session_token = ( - resolve_session(session) if view_key is None else session or os.getenv("AOC_SESSION") - ) - if not session_token and not view_key: - raise MissingSessionTokenError(env_var="AOC_SESSION") + # Authorize the request with the same credential used to scope its cache. + session_token = None if view_key else resolve_session(session) cache_file = get_cache_leaderboard_file( year, @@ -62,15 +58,15 @@ def get_leaderboard( session_token=session_token, view_key=view_key, ) - payload = _read_fresh_cache(cache_file) + entry = _read_fresh_cache(cache_file) - if payload is None: + if entry is None: try: with cache_file_lock(cache_file, timeout=60.0): # Another process may have refreshed the cache while we waited. - payload = _read_fresh_cache(cache_file) - if payload is None: - payload = _fetch_leaderboard_payload( + entry = _read_fresh_cache(cache_file) + if entry is None: + entry = _fetch_leaderboard_payload( year=year, board_id=board_id, session_token=session_token, @@ -79,7 +75,7 @@ def get_leaderboard( try: atomic_write_text( cache_file, - json.dumps(payload, separators=(",", ":")), + json.dumps(entry[0], separators=(",", ":")), ) except OSError as exc: warnings.warn( @@ -92,7 +88,7 @@ def get_leaderboard( "Timed out waiting for another elf process to refresh the leaderboard cache." ) from exc - leaderboard = _validate_leaderboard(payload) + payload, leaderboard = entry match fmt: case OutputFormat.MODEL: @@ -114,7 +110,7 @@ def _fetch_leaderboard_payload( board_id: int, session_token: str | None, view_key: str | None, -) -> dict[str, Any]: +) -> tuple[dict[str, Any], Leaderboard]: """Fetch and decode a private leaderboard response.""" try: @@ -124,10 +120,10 @@ def _fetch_leaderboard_payload( raise LeaderboardFetchError( "Timed out while fetching leaderboard. Try again or check your network." ) from exc - except httpx.RequestError as exc: + except httpx.RequestError: raise LeaderboardFetchError( - f"Network error while connecting to Advent of Code: {exc}" - ) from exc + "Network error while fetching the private leaderboard." + ) from None handle_http_errors( response, @@ -152,11 +148,10 @@ def _fetch_leaderboard_payload( if not isinstance(payload, dict): raise LeaderboardFetchError("Unexpected leaderboard schema from Advent of Code.") - _validate_leaderboard(payload) - return payload + return payload, _validate_leaderboard(payload) -def _read_fresh_cache(cache_file: Path) -> dict[str, Any] | None: +def _read_fresh_cache(cache_file: Path) -> tuple[dict[str, Any], Leaderboard] | None: """Return a valid cache entry within AoC's 15-minute request interval.""" try: age_seconds = time.time() - cache_file.stat().st_mtime @@ -173,8 +168,7 @@ def _read_fresh_cache(cache_file: Path) -> dict[str, Any] | None: payload = json.loads(cache_file.read_text(encoding="utf-8")) if not isinstance(payload, dict): raise ValueError("Leaderboard cache must contain a JSON object.") - _validate_leaderboard(payload) - return payload + return payload, _validate_leaderboard(payload) except (OSError, ValueError, ValidationError, LeaderboardFetchError) as exc: raise LeaderboardFetchError( "The fresh leaderboard cache is unreadable or malformed. " diff --git a/tests/test_leaderboard_cache.py b/tests/test_leaderboard_cache.py index e864d54..42f32de 100644 --- a/tests/test_leaderboard_cache.py +++ b/tests/test_leaderboard_cache.py @@ -1,6 +1,7 @@ import json import os import time +import traceback from concurrent.futures import ThreadPoolExecutor import httpx @@ -110,3 +111,35 @@ def read(_index): assert all(result.members[1].name == "Elf" for result in results) assert _FakeClient.calls == 1 + + +def test_view_key_uses_only_share_authorization(monkeypatch, tmp_path): + monkeypatch.setenv("ELF_CACHE_DIR", str(tmp_path)) + monkeypatch.setenv("AOC_SESSION", "ambient-cookie") + sessions = [] + + class RecordingClient(_FakeClient): + def fetch_leaderboard(self, year, board_id, view_key): + sessions.append(self.session_token) + assert view_key == "example-key" + return super().fetch_leaderboard(year, board_id, view_key) + + monkeypatch.setattr("elf.leaderboard.AOCClient", RecordingClient) + for board, session in [(1, None), (2, "explicit-cookie")]: + get_leaderboard(2025, session, board, "example-key") + assert sessions == [None, None] + + +def test_view_key_absent_from_error_traceback(monkeypatch, tmp_path): + monkeypatch.setenv("ELF_CACHE_DIR", str(tmp_path)) + + class ForbiddenClient(_FakeClient): + def fetch_leaderboard(self, year, board_id, view_key): + request = httpx.Request("GET", "https://example.test/", params={"view_key": view_key}) + return httpx.Response(403, request=request) + + monkeypatch.setattr("elf.leaderboard.AOCClient", ForbiddenClient) + key = "private-example" + with pytest.raises(LeaderboardFetchError, match="403") as error: + get_leaderboard(2025, None, 1, key) + assert "private-example" not in "".join(traceback.format_exception(error.value)) diff --git a/tests/test_leaderboard_csv.py b/tests/test_leaderboard_csv.py index 10b7b22..bf67451 100644 --- a/tests/test_leaderboard_csv.py +++ b/tests/test_leaderboard_csv.py @@ -5,6 +5,7 @@ from rich.table import Table from elf import OutputFormat, get_private_leaderboard +from elf.cache import atomic_write_text, get_cache_leaderboard_file from elf.leaderboard import format_leaderboard_as_csv from elf.models import Leaderboard @@ -115,9 +116,11 @@ def test_empty_leaderboard_csv_contains_stable_header(): assert rows == [] -def test_public_api_returns_csv_and_unchanged_other_formats(monkeypatch): +def test_public_api_returns_csv_and_unchanged_other_formats(monkeypatch, tmp_path): payload = _payload() - monkeypatch.setattr("elf.leaderboard._read_fresh_cache", lambda _path: payload) + monkeypatch.setenv("ELF_CACHE_DIR", str(tmp_path)) + path = get_cache_leaderboard_file(2025, 123456, session_token="session", view_key=None) + atomic_write_text(path, json.dumps(payload)) csv_output = get_private_leaderboard( 2025, diff --git a/tests/test_leaderboard_table.py b/tests/test_leaderboard_table.py index 25b7f25..699c38f 100644 --- a/tests/test_leaderboard_table.py +++ b/tests/test_leaderboard_table.py @@ -4,6 +4,7 @@ import pytest from rich.console import Console +from elf.cache import atomic_write_text, get_cache_leaderboard_file from elf.leaderboard import ( _first_star_timestamp, _format_utc_timestamp, @@ -132,9 +133,11 @@ def test_timestamp_formatting_is_utc_regardless_of_machine_timezone(monkeypatch) assert _format_utc_timestamp(1764565800) == "2025-12-01 05:10:00" -def test_json_and_model_outputs_are_unchanged(monkeypatch): +def test_json_and_model_outputs_are_unchanged(monkeypatch, tmp_path): payload = _leaderboard_payload() - monkeypatch.setattr("elf.leaderboard._read_fresh_cache", lambda _path: payload) + monkeypatch.setenv("ELF_CACHE_DIR", str(tmp_path)) + path = get_cache_leaderboard_file(2025, 1, session_token="session", view_key=None) + atomic_write_text(path, json.dumps(payload)) json_output = get_leaderboard(2025, "session", 1, None, OutputFormat.JSON) model_output = get_leaderboard(2025, "session", 1, None, OutputFormat.MODEL) From 004675753436d0de585edf7e7f9a269cc3b3f901 Mon Sep 17 00:00:00 2001 From: Caleb Kinney Date: Wed, 2 Dec 2026 11:10:50 -0500 Subject: [PATCH 11/24] Refactor guess value parsing and session token resolution: improve error handling and validation --- elf/utils.py | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/elf/utils.py b/elf/utils.py index ea7d8c9..1c75862 100644 --- a/elf/utils.py +++ b/elf/utils.py @@ -1,6 +1,7 @@ import csv import os import warnings +from contextlib import suppress from datetime import UTC, datetime from pathlib import Path @@ -43,10 +44,11 @@ def read_guesses( guess_raw = row.get("guess", "") guess_str = guess_raw.strip() if isinstance(guess_raw, str) else str(guess_raw) + guess_val: int | str = guess_str if guess_str.lstrip("+-").isdigit(): - guess_val: int | str = int(guess_str) - else: - guess_val = guess_str + # Some digits (e.g. "²") are valid text answers but not integers. + with suppress(ValueError): + guess_val = int(guess_str) timestamp_raw = row.get("timestamp", "") or "" timestamp = _parse_cache_datetime(timestamp_raw) @@ -127,13 +129,12 @@ def get_unlock_status(year: int, day: int) -> UnlockStatus: def resolve_session(session: str | None, env_var: str = "AOC_SESSION") -> str: """Resolve a session token from an explicit arg or environment variable.""" - if session: - return session - env_session = os.getenv(env_var) - if env_session: - return env_session - - raise MissingSessionTokenError(env_var=env_var) + token = (session or os.getenv(env_var) or "").strip() + if not token: + raise MissingSessionTokenError(env_var=env_var) + if not token.isascii() or not token.isprintable() or any(c in token for c in ' ;,"\\'): + raise ElfError(f"Invalid session cookie. Check {env_var} or the explicit session value.") + return token def handle_http_errors( @@ -161,10 +162,9 @@ def _fmt(msg: str) -> str: if 500 <= response.status_code < 600: raise exc_cls(_fmt(server_error_message)) - try: - response.raise_for_status() - except httpx.HTTPStatusError as exc: - raise exc_cls(_fmt(unexpected_status_message)) from exc + if not response.is_success: + # HTTPStatusError includes the request URL, which may contain a view key. + raise exc_cls(_fmt(unexpected_status_message)) def looks_like_login_page(response: httpx.Response) -> bool: From fffa53c09e896c8220b481a31a74c12a540e52d5 Mon Sep 17 00:00:00 2001 From: Caleb Kinney Date: Wed, 2 Dec 2026 11:10:55 -0500 Subject: [PATCH 12/24] Add rate limit handling test: verify subsequent submissions are blocked and retry logic is correct --- tests/test_submission_http.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/tests/test_submission_http.py b/tests/test_submission_http.py index e25a3d8..d50c1b2 100644 --- a/tests/test_submission_http.py +++ b/tests/test_submission_http.py @@ -148,3 +148,32 @@ def test_wait_response_persists_server_retry_deadline(monkeypatch, tmp_path): assert result.retry_at.strftime("%Y-%m-%d %H:%M:%S UTC") in result.message [guess] = read_guesses(2025, 1, session_token="account") assert guess.retry_at == result.retry_at + + +@pytest.mark.parametrize("header", ["120", "Wed, 31 Dec 2098 00:00:00 GMT", "invalid"]) +def test_rate_limit_blocks_subsequent_submission(monkeypatch, tmp_path, header): + monkeypatch.setenv("ELF_CACHE_DIR", str(tmp_path)) + monkeypatch.setattr("elf.answer.AOCClient", _FakeSubmissionClient) + _FakeSubmissionClient.response = httpx.Response(429, headers={"Retry-After": header}) + before = datetime.now(UTC) + first = submit_answer(2016, 1, 1, "42", "account") + assert first.result is SubmissionStatus.WAIT + assert first.retry_at is not None + if header.isdigit(): + assert ( + before + timedelta(seconds=120) + <= first.retry_at + <= datetime.now(UTC) + timedelta(seconds=120) + ) + elif header == "invalid": + assert ( + before + timedelta(minutes=1) + <= first.retry_at + <= datetime.now(UTC) + timedelta(minutes=1) + ) + else: + assert first.retry_at == datetime(2098, 12, 31, tzinfo=UTC) + + _FakeSubmissionClient.response = AssertionError("unexpected second HTTP request") + second = submit_answer(2016, 1, 1, "43", "account") + assert second.is_cached and second.retry_at == first.retry_at From b8c1c8623f29e6a8d6f90a9c459cdacc5535bc62 Mon Sep 17 00:00:00 2001 From: Caleb Kinney Date: Wed, 2 Dec 2026 11:11:39 -0500 Subject: [PATCH 13/24] Update version to 1.2.2 in pyproject.toml and enhance CHANGELOG with new features, changes, fixes, security updates, and upgrade instructions --- CHANGELOG.md | 25 +++++++++++++++++++++++++ pyproject.toml | 2 +- uv.lock | 2 +- 3 files changed, 27 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 62cb528..cc656a0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,31 @@ Notable user-facing changes to elf are documented here. +## 1.2.2 + +### Added + +- Five optional functions in `elf.helpers` cover common puzzle operations: `ints`, `neighbors4`, `neighbors8`, `manhattan`, and `md5`. +- The Python puzzle cookbook includes runnable examples for parsing, grids, search, timing, and debugging. + +### Changed + +- `elf new` generates four interactive cells. Start offline with an inline example, set the expected answer for each part, and run only the selected part. Submission requires uncommenting the matching block. Rerun Setup and the selected part after changing the input, part, or account. +- Concurrent reads for the same input share one fetch. Cache hits preserve the original line endings. Reading a private leaderboard validates its model once. + +### Fixed + +- Incomplete input responses, explicit HTML error pages, and invalid UTF-8 are rejected before writing to the input cache. +- Submission POSTs stop on redirects and respect HTTP 429 retry deadlines. Guess history retains numeric-looking text answers and selects current account caches ahead of stale legacy copies. + +### Security + +- A leaderboard view key authorizes its request independently of the session cookie. View-key caches start fresh on upgrade, and HTTP status errors omit URLs carrying share keys. + +### Upgrade + +For a uv tool installation, run `uv tool upgrade elf`. For a pip installation, run `python -m pip install --upgrade elf`. Python 3.11+ remains supported. Existing solution files and session-scoped caches require no migration. + ## 1.2.1 ### Fixed diff --git a/pyproject.toml b/pyproject.toml index bb1091e..3f4b7d5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "elf" -version = "1.2.1" +version = "1.2.2" description = "Advent of Code helper for Python: fetch and cache inputs, submit answers, and pull private leaderboards." readme = "README.md" license = "MIT" diff --git a/uv.lock b/uv.lock index d6c260b..def393c 100644 --- a/uv.lock +++ b/uv.lock @@ -572,7 +572,7 @@ wheels = [ [[package]] name = "elf" -version = "1.2.1" +version = "1.2.2" source = { editable = "." } dependencies = [ { name = "beautifulsoup4" }, From 242fb28fde0655b06ccb4c2488fbc74db87dc09a Mon Sep 17 00:00:00 2001 From: Caleb Kinney Date: Wed, 2 Dec 2026 11:11:47 -0500 Subject: [PATCH 14/24] Update getting started guide for puzzle creation: change example year and part, enhance instructions for setup and submission --- user_guide/getting-started.qmd | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/user_guide/getting-started.qmd b/user_guide/getting-started.qmd index f4c6df2..de64efa 100644 --- a/user_guide/getting-started.qmd +++ b/user_guide/getting-started.qmd @@ -28,18 +28,27 @@ In PowerShell, use `$env:AOC_SESSION = "your-session-cookie"` and `$env:AOC_USER ## Solve a puzzle in Positron ```bash -uv run elf new 2025 1 +uv run elf new 2026 2 ``` -This creates `2025/day01.py`. Use `--output path/to/day01.py` for a custom location. Elf refuses to overwrite an existing file. +This creates `2026/day02.py`. Use `--output solutions/2026/day02.py` for a custom location. Elf creates missing parent directories and refuses to overwrite a file. -1. Open your puzzle folder in [Positron](https://positron.posit.co/download.html) and select the Python interpreter where you installed Elf. With uv, this is the project’s `.venv` interpreter. Open the generated file. In **Setup**, choose `PART = 1` or `PART = 2`. To work offline with an example, paste it into `sample` in **Load Input** and set `USE_SAMPLE = True`. -2. Run **Setup** through the selected part. Edit `data = lines` in **Parse Input** as needed, then replace the answer placeholder in the selected part. Inspect `raw`, `lines`, `data`, and your intermediate variables in the Variables pane. -3. For a real answer, set `USE_SAMPLE = False` and rerun **Setup** through the selected part. Inspect the result, set `SUBMIT = True` in the console, and run **Submit**. The flag resets after each attempt and when you reload, parse, or recompute. +1. Open the file in Positron or another editor that supports Python code cells. Select the interpreter where you installed Elf. +2. In **Setup**, paste the puzzle example into `sample`. Keep `PART = 1` and `USE_SAMPLE = True`. Set `SAMPLE_ANSWERS[1]` to the expected integer or string. Leave it as `None` to skip the check. +3. Run **Setup** and **Part 1**. Replace the solution placeholder and rerun the part until the assertion passes. The Variables pane shows `data`, the answer, and any intermediate variables you assign. Sample runs work offline and need no credentials. [Positron code cells](https://positron.posit.co/code-cells.html) · [Variables pane](https://positron.posit.co/variables-pane.html) +4. Set `USE_SAMPLE = False`. Rerun **Setup** and the selected part, then inspect the printed answer. Elf reads `AOC_SESSION` internally for real input and submission. +5. When ready, uncomment both lines of the matching **Submit** block, run it once, and immediately comment the lines again. +6. Switch to `PART = 2`, restore `USE_SAMPLE = True`, enter `SAMPLE_ANSWERS[2]`, and repeat. If Part 2 gives a different example, replace the text in `sample` before rerunning **Setup**. -Rerun from **Setup** after changing the puzzle, input mode, or Advent of Code account. Loading or parsing input clears both answers. Submission requires a computed answer for the selected part and real input for the current year and day. If the session cookie changes after input is loaded, rerun from **Load Input** through the selected part before submitting. +Rerun **Setup** and the selected part after changing the input, part, or authenticated account. The submission conditions check the current mode, selected part, and presence of an answer. Keeping that answer fresh is up to you. -You can also run `uv run python 2025/day01.py` in the configured environment. It prints the selected answer once implemented. Submission is off by default. +With the project environment active you can run the same file from a terminal. + +```bash +python 2026/day02.py +``` + +Ordinary Python execution checks sample answers with `assert`. Running Python with `-O` disables assertions. Both input modes use `parse_input`, which preserves spaces and internal blank lines. For puzzle-specific parsing and search examples, see the [Python puzzle cookbook](user-guide/puzzle-cookbook.qmd). ## Use Elf from Python From acfc310f9fe4235d8c8a77c447007624705a4b33 Mon Sep 17 00:00:00 2001 From: Caleb Kinney Date: Wed, 2 Dec 2026 11:11:55 -0500 Subject: [PATCH 15/24] Add Python puzzle cookbook: comprehensive guide with examples and explanations for puzzle input handling, parsing, collections, iteration, graphs, and more --- user_guide/puzzle-cookbook.qmd | 389 +++++++++++++++++++++++++++++++++ 1 file changed, 389 insertions(+) create mode 100644 user_guide/puzzle-cookbook.qmd diff --git a/user_guide/puzzle-cookbook.qmd b/user_guide/puzzle-cookbook.qmd new file mode 100644 index 0000000..ca47a81 --- /dev/null +++ b/user_guide/puzzle-cookbook.qmd @@ -0,0 +1,389 @@ +--- +title: "Python puzzle cookbook" +toc: true +--- + +Each recipe runs on synthetic input. Examples use Python 3.11 or later except where marked. Imports from `elf.helpers` are optional. + +## Working with puzzle input + +### Keep the spaces that describe a map + +A space at the left edge can be a real column. Use `splitlines()` to drop line endings while keeping the contents of each row. A blank line can then separate the map from its instructions. + +```python +text = " A.\r\n..B\r\n\r\nwalk 2\r\n" +lines = text.splitlines() +divider = lines.index("") +grid = [list(row) for row in lines[:divider]] +action, count = lines[divider + 1].split() +assert grid[0] == [" ", "A", "."] +assert (action, int(count)) == ("walk", 2) +``` + +For repeated groups, apply the same split rule at every blank line. This version ignores runs of empty lines and keeps a final group without a trailing separator. + +```python +from itertools import groupby + +lines = "red\nblue\n\n\ngreen".splitlines() +groups = [list(group) for has_text, group in groupby(lines, key=bool) if has_text] +assert groups == [["red", "blue"], ["green"]] +``` + +In an elf daily file, `data` is already the result of `parse_input(text)`, which uses `splitlines()`. For local files, `read_input(Path("input.txt"))` strips whitespace at both ends of the **whole file**. Use `Path("input.txt").read_text(encoding="utf-8")` when that whitespace matters. + +### Match the parser to the delimiter + +For a known format, unpack the fields. Use a regex when the integers can appear anywhere in a label. + +```python +import re + +numbers = list(map(int, " 8 -3 12 ".split())) +name, limits = "gate:3-5".split(":") +low, high = map(int, limits.split("-")) +assert (name, low, high) == ("gate", 3, 5) + +coords = [int(s) for s in re.findall(r"[+-]?[0-9]+", "row=-2 col=+5")] +assert coords == [-2, 5] +``` + +Elf's `ints(text)` uses that regex. It reads embedded digits and attaches the nearest adjacent sign. For example, `ints("v2: 3-5, --7")` gives `[2, 3, -5, -7]`. Split range endpoints explicitly when the hyphen is a separator. [Python regular expressions](https://docs.python.org/3/library/re.html) + +## Collections and counting + +### Keep order, count visits, or compare routes + +A list retains every visit. A tuple works as a dictionary key for a coordinate. A set answers membership questions, and dictionary keys can remove duplicates while preserving the order of first appearance. + +```python +from collections import Counter, defaultdict + +route = [(0, 1), (1, 1), (0, 1)] +first_visits = list(dict.fromkeys(route)) +assert first_visits == [(0, 1), (1, 1)] +assert Counter(route).most_common(1) == [((0, 1), 2)] + +other_route = {(1, 1), (2, 1)} +assert set(route) & other_route == {(1, 1)} # shared stops +assert set(route) - other_route == {(0, 1)} # unique to this route + +columns_by_row = defaultdict(list) +for row, col in first_visits: + columns_by_row[row].append(col) +assert columns_by_row[0] == [1] +``` + +Use a `deque` when you also need to take items off the front efficiently. The breadth-first search below uses one to process cells in arrival order. [Python collections](https://docs.python.org/3/library/collections.html) + +## Iteration and combinations + +### Compare neighboring readings + +`enumerate` gives a position and its value. `pairwise` gives consecutive values. For a fixed window of three, zip the sequence with two shifted slices. Sum a generator expression when you only need the final count. + +```python +from itertools import pairwise + +levels = [3, 1, 4, 6] +positions = [i for i, height in enumerate(levels) if height > 3] +assert positions == [2, 3] +assert sum(b > a for a, b in pairwise(levels)) == 2 +windows = [a + b + c for a, b, c in zip(levels, levels[1:], levels[2:])] +assert windows == [8, 11] +``` + +For **non-overlapping** chunks from an iterable, Python **3.12+** provides `itertools.batched`. The final chunk can be shorter. + +```python +from itertools import batched + +assert list(batched("ABCDE", 2)) == [("A", "B"), ("C", "D"), ("E",)] +``` + +### Choose the candidate space + +Choose unordered pairs for handshakes, ordered pairs for directed connections, and a Cartesian product when each selection is independent. Each iterator can feed a loop directly. + +```python +from itertools import combinations, permutations, product + +assert list(combinations("ABC", 2)) == [("A", "B"), ("A", "C"), ("B", "C")] +assert len(list(permutations("ABC", 2))) == 6 # A to B differs from B to A +assert list(product("AB", [1, 2])) == [("A", 1), ("A", 2), ("B", 1), ("B", 2)] +``` + +[Python iterator recipes](https://docs.python.org/3/library/itertools.html) + +## Grids and coordinates + +### Find a marker and take one legal step + +Use `(row, column)` so that `grid[row][col]` reads naturally. Row numbers increase downward. Check both lower bounds before indexing because Python accepts negative indices. + +```python +grid = ["S..", ".#.", "..E"] +start = next((r, c) for r, row in enumerate(grid) for c, ch in enumerate(row) if ch == "S") +r, c = start +adjacent = [(r - 1, c), (r, c - 1), (r, c + 1), (r + 1, c)] +moves = [(r, c) for r, c in adjacent + if 0 <= r < len(grid) and 0 <= c < len(grid[r]) and grid[r][c] != "#"] +assert moves == [(0, 1), (1, 0)] +``` + +`neighbors4(start)` gives the same candidates as a tuple. `neighbors8(start)` also includes diagonals. Both scan in reading order, skip the center, and leave boundary checks to you. For four-way travel on an open grid, `manhattan(a, b)` counts steps as `abs(a[0] - b[0]) + abs(a[1] - b[1])`. With walls, this is a lower bound. + +### Turn the map or store just the occupied cells + +Transpose a rectangular map to process columns as rows. Reverse the rows before transposing to rotate it clockwise. For a mostly empty map, a set can record walls and a dictionary can associate labels with positions. + +```python +rows = ["A.#", "..B"] +columns = ["".join(col) for col in zip(*rows, strict=True)] +clockwise = ["".join(col) for col in zip(*reversed(rows), strict=True)] +assert columns == ["A.", "..", "#B"] +assert clockwise == [".A", "..", "B#"] + +labels = {(r, c): ch for r, row in enumerate(rows) for c, ch in enumerate(row) if ch != "."} +walls = {pos for pos, ch in labels.items() if ch == "#"} +assert walls == {(0, 2)} +``` + +If your moves are mostly turns and steps, complex numbers offer a compact alternative. With columns on the real axis and rows on the imaginary axis, `1` moves east, `1j` moves south, and multiplying a direction by `1j` turns right. + +## Graphs and search + +### Fewest moves with breadth-first search + +When every edge costs one move, the first visit gives the shortest distance. Mark a node when you enqueue it so two paths arriving together cannot queue it twice. + +```python +from collections import deque + +links = {"A": "BC", "B": "D", "C": "D", "D": ""} +distance = {"A": 0} +queue = deque(["A"]) +while queue: + node = queue.popleft() + for dest in links[node]: + if dest not in distance: + distance[dest] = distance[node] + 1 + queue.append(dest) +assert distance["D"] == 2 +``` + +### Flood fill and count connected components + +To measure regions, visit order can be arbitrary. A list used as a stack gives depth-first search. Remove each cell from the unvisited set as you claim it. Each new seed starts one connected component. + +```python +remaining = {(0, 0), (1, 0), (1, 1), (0, 3)} +sizes = [] +while remaining: + stack = [remaining.pop()] + size = 0 + while stack: + r, c = stack.pop() + size += 1 + for pos in ((r - 1, c), (r + 1, c), (r, c - 1), (r, c + 1)): + if pos in remaining: + remaining.remove(pos) + stack.append(pos) + sizes.append(size) +assert sorted(sizes) == [1, 3] +``` + +### Cheapest route with Dijkstra's algorithm + +With nonnegative edge costs, use a priority queue. A node can be discovered again at a lower cost. Skip an older heap entry when it no longer matches the cheapest known arrival. + +```python +import heapq + +edges = {"A": [("B", 7), ("C", 2)], "B": [], "C": [("B", 1)]} +best = {"A": 0} +frontier = [(0, "A")] +while frontier: + cost, node = heapq.heappop(frontier) + if cost != best[node]: + continue + for dest, weight in edges[node]: + candidate = cost + weight + if dest not in best or candidate < best[dest]: + best[dest] = candidate + heapq.heappush(frontier, (candidate, dest)) +assert best["B"] == 3 +``` + +### Put prerequisites first + +Give `TopologicalSorter` a mapping from task to prerequisites. Several orders may be valid, so check the precedence constraints. A cycle raises `CycleError`. [Python graphlib](https://docs.python.org/3/library/graphlib.html) + +```python +from graphlib import TopologicalSorter + +needs = {"pack": {"cut", "fold"}, "fold": {"cut"}} +order = tuple(TopologicalSorter(needs).static_order()) +assert order == ("cut", "fold", "pack") +``` + +## Mathematics + +### Count exactly and wrap around + +Keep counts and indices as integers. Use `divmod` to split a flat index into row and column, `%` to wrap a position, and fractions when division must stay exact. + +```python +from fractions import Fraction +from math import gcd, lcm, prod + +widths = [3, 4, 6] +assert (sum(widths), prod(widths), min(widths), max(widths)) == (13, 72, 3, 6) +assert divmod(17, 5) == (3, 2) +assert (1 - 3) % 5 == 3 # two steps left on a ring +assert gcd(12, 18) == 6 # largest equal block size +assert lcm(4, 6) == 12 # cycles starting together realign +assert Fraction(1, 3) * 3 == 1 +``` + +### Track flags and intersect intervals + +A bitmask fits several yes/no flags in one integer. Use half-open intervals `[start, stop)` for spans so that subtracting the endpoints gives their length, just like a Python slice. + +```python +flags = int("0101", 2) +assert flags & (1 << 2) # bit 2 is set (numbering from 0) +assert (flags | (1 << 1)).bit_count() == 3 + +a, b = (2, 7), (5, 9) +overlap = max(0, min(a[1], b[1]) - max(a[0], b[0])) +assert overlap == 2 # positions 5 and 6 +``` + +## Performance and optimization + +### Reduce the number of candidates first + +A nested loop comparing every pair of 10,000 items can examine nearly 50 million pairs. To find two entries with a given sum, scan once and look up the complement in a set. Checking before insertion ensures the two entries come from different positions. + +```python +seen = set() +target = 10 +for value in [3, 2, 8, 5]: + if target - value in seen: + pair = (target - value, value) + break + seen.add(value) +else: + pair = None +assert pair == (2, 8) +``` + +### Reuse a subproblem or skip a repeated cycle + +If different choices reach the same state, cache its result. Here the number of ways to cover a length with tiles of size one or two depends only on the remaining length. Include every input that affects the answer in the cache key. + +```python +from functools import cache + +@cache +def ways(left): + if left <= 1: + return 1 + return ways(left - 1) + ways(left - 2) + +assert ways(5) == 8 +``` + +For a long deterministic simulation, save the **full state** and the step when you first saw it. On a repeat, the distance between the two visits is the period. This skips whole laps even when the starting state is outside the cycle. + +```python +jump = {"A": "B", "B": "C", "C": "D", "D": "B"} +state, step, goal = "A", 0, 1_000_000 +first_seen = {} +while step < goal and state not in first_seen: + first_seen[state] = step + state = jump[state] + step += 1 +if step < goal: + period = step - first_seen[state] + for _ in range((goal - step) % period): + state = jump[state] +assert state == "B" +``` + +### Time a cell and profile a whole run + +Wrap the expression you are investigating with `perf_counter()`. Keep input loading outside the measured block when comparing algorithms. + +```python +from time import perf_counter + +start = perf_counter() +total = sum(i * i for i in range(10_000)) +elapsed = perf_counter() - start +print(f"{total=} in {elapsed:.6f}s") +``` + +If the work already lives in a function, `elf.helpers.timer` can report each call. + +```python +from elf.helpers import timer + +@timer() +def score(values): + return sum(v * v for v in values) + +assert score([2, 3]) == 13 +``` + +For a surprising slowdown, run the file in sample mode with `python -m cProfile -s cumulative 2026/day02.py`. Look at the functions with high cumulative time **and** their call counts. A search exploring the same state thousands of times often gains more from recording visited states than from speeding up a single iteration. + +## Hashing and string manipulation + +### Hash exactly the text the puzzle specifies + +Encode text before hashing it. A trailing newline changes the digest. For historical puzzles that request MD5, `elf.helpers.md5("abc")` is the shortcut for the following expression. MD5 is unsuitable for cryptographic security. + +```python +from hashlib import md5 + +digest = md5("abc".encode("utf-8"), usedforsecurity=False).hexdigest() +assert digest[:6] == "900150" +``` + +### Transform a string in one pass + +Use slices to take a prefix or reverse a sequence. Use a translation table for repeated character substitutions, then join pieces to construct the output. + +```python +route = "N E S".split() +opposite = str.maketrans("NESW", "SWNE") +return_route = "".join(route[::-1]).translate(opposite) +assert return_route == "NWS" +``` + +## Testing and debugging + +### Start with a case you can check by hand + +Put an intermediate result at module level so Positron's Variables pane or the VS Code debugger can show it. Here you can inspect `rises` when the answer differs from the expected count. An empty input and a one-value input both have zero adjacent pairs. + +```python +# %% Setup +from itertools import pairwise + +sample = "3\n1\n4\n" +levels = list(map(int, sample.splitlines())) + +# %% Part 1 +rises = [(a, b) for a, b in pairwise(levels) if b > a] +assert rises == [(1, 4)] +assert len(rises) == 1 +assert list(pairwise([])) == list(pairwise([7])) == [] +``` + +In a generated elf file, enter the sample answers in `SAMPLE_ANSWERS`, run **Setup**, then run the cell selected by `PART`. When switching parts, rerun Setup so the expected answer matches the part. If Part 2 has a different example, replace the inline sample too. Ordinary Python runs these assertions. The `-O` flag disables them. + +Once the sample passes, set `USE_SAMPLE = False` and rerun Setup and the selected part with the same parser. Compare the row count, row widths, and first parsed record if the real input behaves differently. These checks often reveal a blank separator or a sign that the small example never exercised. From 4f7b887f5ea5582fee92dcc086613a46c99d287a Mon Sep 17 00:00:00 2001 From: Caleb Kinney Date: Wed, 2 Dec 2026 11:12:00 -0500 Subject: [PATCH 16/24] Add workflow_call trigger to Quality workflow --- .github/workflows/quality.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/quality.yml b/.github/workflows/quality.yml index 33a5de1..3d2c6aa 100644 --- a/.github/workflows/quality.yml +++ b/.github/workflows/quality.yml @@ -3,6 +3,7 @@ name: Quality on: push: pull_request: + workflow_call: permissions: contents: read From 3c61a08624603f9e571fd034b3ecacf1b4bd3f09 Mon Sep 17 00:00:00 2001 From: Caleb Kinney Date: Wed, 2 Dec 2026 11:12:12 -0500 Subject: [PATCH 17/24] Enhance publish workflow: add quality job dependency, release tag check, and trusted publishing option --- .github/workflows/publish.yml | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index f5896fe..7539765 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -8,7 +8,11 @@ permissions: contents: read jobs: + quality: + uses: ./.github/workflows/quality.yml + build: + needs: quality runs-on: ubuntu-latest steps: - name: Check out repository @@ -17,6 +21,11 @@ jobs: - name: Install uv uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 + - name: Check release tag against package version + env: + RELEASE_TAG: ${{ github.event.release.tag_name }} + run: test "$RELEASE_TAG" = "v$(uv version --short --frozen)" + - name: Build distributions run: uv build --no-sources @@ -48,4 +57,4 @@ jobs: path: dist/ - name: Publish to PyPI - run: uv publish + run: uv publish --trusted-publishing always From 2158a94c408c786632dfce45b3cdb5ed067b5f97 Mon Sep 17 00:00:00 2001 From: Caleb Kinney Date: Wed, 2 Dec 2026 11:12:33 -0500 Subject: [PATCH 18/24] Update GitHub Actions workflow: fix action versions for checkout, setup-python, quarto, upload-artifact, download-artifact, and deploy-pages --- .github/workflows/docs.yml | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index f698d8e..b73782d 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -15,12 +15,12 @@ jobs: name: "Build Docs" runs-on: ubuntu-latest steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 with: fetch-depth: 0 # Full history for accurate page timestamps persist-credentials: false - - uses: actions/setup-python@v6 + - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 with: python-version: "3.11" @@ -30,7 +30,7 @@ jobs: uv sync --locked --no-default-groups --group docs - name: Set up Quarto - uses: quarto-dev/quarto-actions/setup@v2 + uses: quarto-dev/quarto-actions/setup@8a96df13519ee81fd526f2dfca5962811136661b # v2 with: version: "1.11.9" @@ -41,7 +41,7 @@ jobs: run: uv run --locked --no-default-groups --group docs great-docs build - name: Save docs artifact - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 with: name: docs-html path: great-docs/_site @@ -52,7 +52,7 @@ jobs: run: uv run --locked --no-default-groups --group docs great-docs ci notice --run ${{ github.run_id }} --pr ${{ github.event.number }} - name: Upload build timings - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 with: name: build-timings path: great-docs/_site/build-timings.json @@ -69,20 +69,20 @@ jobs: name: github-pages url: ${{ steps.deployment.outputs.page_url }} steps: - - uses: actions/download-artifact@v7 + - uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7 with: name: docs-html path: great-docs/_site - name: Upload Pages artifact - uses: actions/upload-pages-artifact@v5 + uses: actions/upload-pages-artifact@fc324d3547104276b827a68afc52ff2a11cc49c9 # v5 with: path: great-docs/_site include-hidden-files: true - name: Deploy to GitHub Pages id: deployment - uses: actions/deploy-pages@v5 + uses: actions/deploy-pages@368f82528645a54fb793d4d04e342629a3f51346 # v5 preview-docs: name: "Preview Docs" @@ -99,6 +99,6 @@ jobs: # token. continue-on-error so fork PRs (read-only token) don't fail the run. - name: Post preview instructions to the PR continue-on-error: true - run: pipx run great-docs ci pr-comment --run ${{ github.run_id }} --pr ${{ github.event.number }} + run: pipx run --spec great-docs==0.17.0 great-docs ci pr-comment --run ${{ github.run_id }} --pr ${{ github.event.number }} env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} From 66cfb1f19768fbba5510268348d94209ccc549ed Mon Sep 17 00:00:00 2001 From: Caleb Kinney Date: Wed, 2 Dec 2026 11:12:55 -0500 Subject: [PATCH 19/24] Update README.md: enhance interactive puzzle template instructions and clarify session key handling --- README.md | 32 +++++++++++++++++++------------- 1 file changed, 19 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 813fbeb..7846139 100644 --- a/README.md +++ b/README.md @@ -276,6 +276,8 @@ Supports: - **json:** raw JSON - **model:** structured Pydantic model +With a view key, elf sends the key alone, even when a session cookie is configured. The upstream API takes the key in the query string, so keep HTTP client request logs private. + Leaderboard JSON is cached for 15 minutes, matching Advent of Code's minimum request interval. Cache entries are isolated by event, leaderboard ID, and a one-way fingerprint of the session cookie or view key. ### `elf status` @@ -346,7 +348,7 @@ do not fail the command; cache-access errors return exit code `1`. - Guess history stored under: `/accounts////guesses.csv` - Private leaderboard JSON is scoped by event, board ID, and account/view-key fingerprint and cached for at least 15 minutes - New cache files use private permissions where supported and are replaced atomically to avoid partial files after interruption -- Operating-system locks serialize leaderboard refreshes and guess-history writes. A process exit releases its locks automatically. Finish any running elf 1.2.0 commands before using 1.2.1 against the same cache. +- Operating-system locks serialize input fetches, leaderboard refreshes, and guess-history writes for each cache entry. A process exit releases its locks automatically. Finish any running elf 1.2.0 commands before using 1.2.1 against the same cache. - Duplicate/high/low guesses are short‑circuited locally when possible - Cooldown responses retain AoC's server-provided retry deadline; historical entries without one use a 60-second fallback - Guardrails rely on your local guess history only (new machines/cleared cache = fresh) @@ -393,31 +395,35 @@ print(status) ### Interactive Puzzle Template -Create a solution file from elf's [interactive template](https://github.com/typeerror/elf/blob/main/elf/templates/day_template.py): +Generate a daily file in your puzzle project with elf installed in its Python environment. ```sh -elf new 2025 1 -elf new 2025 2 --output solutions/2025/day02.py +elf new 2026 2 +elf new 2026 2 --output solutions/2026/day02.py ``` -By default, Elf creates `YEAR/dayDD.py`, creating parent directories as needed. It refuses to overwrite existing files. - -We recommend [Positron](https://positron.posit.co/download.html) for working through puzzles interactively. Open your puzzle project, select the Python interpreter where you installed elf, and run individual `# %%` cells. Use the Variables pane to inspect `raw`, `lines`, `data`, and your answers as you work. - -Set `PART` to `1` or `2` in **Setup**. To try an example, paste it into `sample` in **Load Input** and set `USE_SAMPLE = True`. Run **Setup** through the selected part. +The default path is `YEAR/dayNN.py`. Elf creates parent directories and refuses to overwrite existing files. -For a real submission, set `USE_SAMPLE = False`, rerun **Setup** through the selected part, and inspect the answer. Set `SUBMIT = True` in the console, then run **Submit**. The file also runs with `python 2025/day01.py` and defaults to submission off. +1. Open `2026/day02.py` in Positron or another cell-aware editor. In **Setup**, paste the example into `sample` and enter its expected answer in `SAMPLE_ANSWERS[1]`. +2. Run **Setup** and **Part 1**. Edit the solution and rerun the part until the sample assertion passes. Inspect `data`, intermediate variables, and the printed answer as you work. +3. Set `USE_SAMPLE = False`, rerun **Setup** and the selected part, and inspect the real answer. Uncomment the matching two-line block in **Submit**, execute it once, then comment it again. +4. Switch to `PART = 2` and `USE_SAMPLE = True`, set `SAMPLE_ANSWERS[2]`, and repeat. Replace the inline example if Part 2 uses a different one. -If your Advent of Code session changes, rerun from **Load Input** through the selected part before submitting. The template checks that the session used to load the input matches the session used to submit the answer. Each submission requires a fresh opt-in. +Rerun **Setup** and the selected part whenever you change the input, part, or authenticated account. You can also run the whole file with `python 2026/day02.py`. It prints only the selected part and works offline in sample mode. ### Puzzle Helpers -`elf.helpers` includes some small utilities you can use in your own AoC solutions: +Use `elf.helpers` when a puzzle mixes coordinates with text. For example, extract two positions and count the steps between them on an open grid. ```python -from elf.helpers import parse_input, read_input, timer +from elf.helpers import ints, manhattan + +r1, c1, r2, c2 = ints("from (-2, 3) to (1, 5)") +assert manhattan((r1, c1), (r2, c2)) == 5 ``` +The [Python puzzle cookbook](https://typeerror.com/elf/user-guide/puzzle-cookbook.html) covers parsing, collections, grids, graph search, mathematics, timing, and debugging with runnable examples. It also shows when to reach for `neighbors4`, `neighbors8`, `parse_input`, `read_input`, `md5`, and `timer`. + ### Leaderboard Example ```sh From c61fa2beebe4a5f97935cd1db3bd066d77450be6 Mon Sep 17 00:00:00 2001 From: Caleb Kinney Date: Wed, 2 Dec 2026 11:13:01 -0500 Subject: [PATCH 20/24] Update great-docs.yml: add puzzle-cookbook and additional helper functions to user guide and reference sections --- great-docs.yml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/great-docs.yml b/great-docs.yml index 297ba24..f1ceec3 100644 --- a/great-docs.yml +++ b/great-docs.yml @@ -14,6 +14,7 @@ user_guide: contents: - getting-started.qmd - command-line.qmd + - puzzle-cookbook.qmd reference: - title: Puzzle inputs and answers @@ -34,8 +35,13 @@ reference: - title: Puzzle helpers contents: - helpers.parse_input + - helpers.ints + - helpers.neighbors4 + - helpers.neighbors8 + - helpers.manhattan - helpers.read_input - helpers.timer + - helpers.md5 - title: Submission and leaderboard models contents: From 29ca48cb09e47dd9dcd1c11083f2df858b484281 Mon Sep 17 00:00:00 2001 From: Caleb Kinney Date: Wed, 2 Dec 2026 15:44:11 -0500 Subject: [PATCH 21/24] update deps --- uv.lock | 100 ++++++++++++++++++++++++++++---------------------------- 1 file changed, 50 insertions(+), 50 deletions(-) diff --git a/uv.lock b/uv.lock index def393c..a607287 100644 --- a/uv.lock +++ b/uv.lock @@ -226,7 +226,7 @@ version = "4.15.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "soupsieve", version = "2.10", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11.5'" }, - { name = "soupsieve", version = "4.1.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11.5'" }, + { name = "soupsieve", version = "4.1.4", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11.5'" }, { name = "typing-extensions" }, ] sdist = { url = "https://files.pythonhosted.org/packages/43/65/318323f98dbee45d42dff61d8f047181bc6f2268a9068cfad035a46be5af/beautifulsoup4-4.15.0.tar.gz", hash = "sha256:288e3ca7d54b06f2ac191970bc275c1939cb46d450b255bf6718b04aa37ab4f7", size = 632571, upload-time = "2026-06-07T16:44:20.453Z" } @@ -2535,16 +2535,16 @@ wheels = [ [[package]] name = "soupsieve" -version = "4.1.3" +version = "4.1.4" source = { registry = "https://pypi.org/simple" } resolution-markers = [ "python_full_version >= '3.15'", "python_full_version == '3.14.*'", "python_full_version >= '3.11.5' and python_full_version < '3.14'", ] -sdist = { url = "https://files.pythonhosted.org/packages/82/77/d59ca6aa338bdd8d880234d15b7c466cb176e44502899a9df81ba2e13cd0/soupsieve-4.1.3.tar.gz", hash = "sha256:13f70186c8f40bf8d0ff7bbab09a18fb149600b465269207b5e5b588f55fda08", size = 181564, upload-time = "2026-11-20T12:58:27.613Z" } +sdist = { url = "https://files.pythonhosted.org/packages/0c/68/ea74670eae744f7da505778c4e555dbd7b59bf4458342f56fded9fac09f0/soupsieve-4.1.4.tar.gz", hash = "sha256:9f12cb9fabef3bbde8eea07539412512960fe2320d67834b3c5be71d9aea522f", size = 189763, upload-time = "2026-12-01T16:02:51.365Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/f6/f7/be207468cac6ad79389f36cf1fce4f2836960df91659979ec486c727bb2e/soupsieve-4.1.3-py3-none-any.whl", hash = "sha256:7a390d1a57d1ab7bb228531e9b8a750a5ebf87db774e0ef6faeeac057d22a5bf", size = 59792, upload-time = "2026-11-20T12:58:26.459Z" }, + { url = "https://files.pythonhosted.org/packages/e6/50/3ff53ec2d16bac3a7b21def7c2773a32a5aebe45d01c6adf96b685cb6504/soupsieve-4.1.4-py3-none-any.whl", hash = "sha256:03bbb16915c1e13a4746fdc84a97e5999888aae3208516604d7bfc786aba0aef", size = 62119, upload-time = "2026-12-01T16:02:49.801Z" }, ] [[package]] @@ -2589,52 +2589,52 @@ wheels = [ [[package]] name = "tornado" -version = "6.6.1" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/64/2b/8ff2b41620cbba0eeb0862fed21dcaa5a2ad36c6dd9bb465f9ff7a147be2/tornado-6.6.1.tar.gz", hash = "sha256:28e6311402af59c8b02e3fa0f5e7d8eb465b25081381803b127d97e6a4395d5a", size = 623388, upload-time = "2026-11-09T21:09:22.71Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/77/d3/ef3a4d38d1a72c52ad07483ed760dbb93027d28f19c3a2d98148abdd63e1/tornado-6.6.1-cp311-abi3-macosx_10_9_universal2.whl", hash = "sha256:a8d3e6acde5a80d13b13b5e4c7c226ca682f31d0a62b6c33cea038714bc2de1b", size = 533249, upload-time = "2026-11-09T21:08:22.475Z" }, - { url = "https://files.pythonhosted.org/packages/38/4d/c65ea949a3cdc185f1afac8c337074d4f2d029b48293d2db4d2c3dea4849/tornado-6.6.1-cp311-abi3-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:1b6ff57cc69b339f8feb9e7b567b0e0eacb16bfaf234159496623ef7a67ba640", size = 534470, upload-time = "2026-11-09T21:08:24.27Z" }, - { url = "https://files.pythonhosted.org/packages/03/ff/20911f85dd399b56761496e8138810e8608ea25f0912377f4205d52af853/tornado-6.6.1-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:da6ce2da215810d56539fa6cac77d9e27f4d8139c6868c53436b2fe933f43c79", size = 535446, upload-time = "2026-11-09T21:08:25.625Z" }, - { url = "https://files.pythonhosted.org/packages/be/70/a4a159dd4f1fef39ff8eadae655b133a85722b39087a89e21ce463af9832/tornado-6.6.1-cp311-abi3-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:8cd28b2cacbe63d53e28a38546a3492b488417eeb3f7ecf10954476fc2508882", size = 535664, upload-time = "2026-11-09T21:08:27.191Z" }, - { url = "https://files.pythonhosted.org/packages/ed/d5/db70d5d23d3b4eaea0b26b710f28d2ca387bb44e68ccfede60ba3bbc2096/tornado-6.6.1-cp311-abi3-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:25b2619274bca77d0eb7b4d96dcf2d1142bb9bf172ad6a7491a1e1f82e6e48fa", size = 534660, upload-time = "2026-11-09T21:08:28.78Z" }, - { url = "https://files.pythonhosted.org/packages/f7/f6/0528ee039266902e707edd9996ee3ce7364dc1baf08bed585d8e6fb3ccd0/tornado-6.6.1-cp311-abi3-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:77dd6e0c659fdc45824e0746988ac5c060c2a9fee9b8cbbcdb999b3f29d3cd10", size = 532834, upload-time = "2026-11-09T21:08:30.432Z" }, - { url = "https://files.pythonhosted.org/packages/a6/bb/b733df2d487a78283080663bd6d96955121b58b6d445d9cb832607da9786/tornado-6.6.1-cp311-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:b62fded687e55acaf9e36c1230b006066a35b3f6df093ba1fd3b2ff592070e1d", size = 535289, upload-time = "2026-11-09T21:08:31.692Z" }, - { url = "https://files.pythonhosted.org/packages/a7/7c/c81cb83f2bbb5740fcba1eb83d794b6d6fab2063b16a475cc9039266091e/tornado-6.6.1-cp311-abi3-musllinux_1_2_ppc64le.whl", hash = "sha256:ecef88054d8a77878f61061ff67dfc5e1c17d1f7334890ab508b310e8e68ee46", size = 535382, upload-time = "2026-11-09T21:08:33.282Z" }, - { url = "https://files.pythonhosted.org/packages/8a/ae/c499da4cc8be1c1f31a5d8df2328f2aae091de2db13302ad5c20ed704ec4/tornado-6.6.1-cp311-abi3-musllinux_1_2_riscv64.whl", hash = "sha256:ca95e762df1ca761f330e3f2a034c15ac144569844b52527a5a9eca9f524c0f1", size = 534534, upload-time = "2026-11-09T21:08:34.57Z" }, - { url = "https://files.pythonhosted.org/packages/61/7c/6b163c9e58ca9df0c941bda9ba2dcabbd87ecb81c5fa546f54eeac689232/tornado-6.6.1-cp311-abi3-musllinux_1_2_s390x.whl", hash = "sha256:8cae3d8f2585be01670da9fd5010c61724c51b61ecd4c06820e95874739daf7c", size = 534728, upload-time = "2026-11-09T21:08:35.828Z" }, - { url = "https://files.pythonhosted.org/packages/18/11/b5107ac6a278387635d73d283e7ab5a5c76fb8ccf402efa57006ea25852f/tornado-6.6.1-cp311-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:6596f3e939962f13099ce8d1a96b83226e908ca369b193370a6efa84585a1601", size = 534676, upload-time = "2026-11-09T21:08:37.209Z" }, - { url = "https://files.pythonhosted.org/packages/65/df/0574c4479c565d9233def796afc9179fa840f41f8c240f740609f746da67/tornado-6.6.1-cp311-abi3-win32.whl", hash = "sha256:0f0f596a0dab6826aa21d103c7bc242e3fb7cfc99c5c3d44a35ba8c83abbdca4", size = 535565, upload-time = "2026-11-09T21:08:38.518Z" }, - { url = "https://files.pythonhosted.org/packages/36/57/35439a779582e3b19c98e799b6a41519fb3bdaa3a21b7a94ce4dd7b3b732/tornado-6.6.1-cp311-abi3-win_amd64.whl", hash = "sha256:5cb82ca38596e1350fceaf994f287847f82f7b8436380d36ba0937a03107d0ee", size = 535806, upload-time = "2026-11-09T21:08:39.892Z" }, - { url = "https://files.pythonhosted.org/packages/89/b8/2cb42845af01ea7e70ac23e6f6fe2f26b9b158bce186c6991c057c9abe1d/tornado-6.6.1-cp311-abi3-win_arm64.whl", hash = "sha256:58d2f47e7b54fded3407dbbbe4e59d29ca627f85bf6c0f21f0b151c6c7fc9c53", size = 535825, upload-time = "2026-11-09T21:08:41.339Z" }, - { url = "https://files.pythonhosted.org/packages/10/de/cfeae9e75c144ca22018ee3b858e343c1658d6edd2184f35d810ec1ef789/tornado-6.6.1-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:ed0bc5a1a9f6346e7bdadc106fa2d4c6e79d71d8b2df4366260ab3baf36a8399", size = 533356, upload-time = "2026-11-09T21:08:42.603Z" }, - { url = "https://files.pythonhosted.org/packages/3d/d8/7812a729c797fb8c15748c9a69faeaaa13630075cf9b76ba9f7fbcfb7f42/tornado-6.6.1-cp314-cp314t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:54c80f9bed0bf1533ecf5a90dc59651645622d62b0bcffa2692d108a1f794917", size = 537511, upload-time = "2026-11-09T21:08:43.84Z" }, - { url = "https://files.pythonhosted.org/packages/70/47/ebef304487feea6d8efb6a7d2642964ecb1f5cc785f687628e1d7cac4326/tornado-6.6.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:eb67ba2cbf598e842f14684eab029a5a4ba7ab587e8c4e40940a77ed0596b31e", size = 538566, upload-time = "2026-11-09T21:08:45.203Z" }, - { url = "https://files.pythonhosted.org/packages/a3/6a/87532e6745c415eb2daa9bc1c9c89c69ce9e8255b1c0bde9938f3299440b/tornado-6.6.1-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:d83bac141bd9360d8e995ec512097be19ead2e9213c3e7088510a036f3192b8d", size = 538793, upload-time = "2026-11-09T21:08:46.478Z" }, - { url = "https://files.pythonhosted.org/packages/e4/c7/26af60f71f7c32f19257bad58711500628f579edf1a2c3d8328ad15aae04/tornado-6.6.1-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:60aad449dbcebaa8d69bff50c6ba39858fab8d256e779a99bb30ebf6724b9b48", size = 537691, upload-time = "2026-11-09T21:08:47.975Z" }, - { url = "https://files.pythonhosted.org/packages/ba/9d/af233b8bf4311d3466099ab267eb595ec6f1655607d290dc7f706b6dbd6f/tornado-6.6.1-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:b9ce0d6548bd73b1329075b247d3fdc61538922f558ee42059e08f5df53fc197", size = 535877, upload-time = "2026-11-09T21:08:49.76Z" }, - { url = "https://files.pythonhosted.org/packages/95/66/78e7583ce69f66e5177c65988a98373be2ab25c1d22405d274e037acbc58/tornado-6.6.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:ce5a18654f5d56d11400ab5d87103660e14deceab41818a06a42acc8dbbe427d", size = 538295, upload-time = "2026-11-09T21:08:51.221Z" }, - { url = "https://files.pythonhosted.org/packages/a3/3a/ad336d4994547cf268a3bd6d10f6ef691e1e888fc776940c0bfe02e8d85c/tornado-6.6.1-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:3298fce72c35f836eab4c4db8b960104ff1ea718033a6b5e236f04efe3a1b6e1", size = 538349, upload-time = "2026-11-09T21:08:52.761Z" }, - { url = "https://files.pythonhosted.org/packages/cf/cf/563d24516afd266f6b3c3f1c7ac15ad39b8668966d2bccce917c169ab0c0/tornado-6.6.1-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:0223e827cedf4e35ebb035e57a0d9974563cd043e3a53f8bb72a859b6f53777e", size = 537469, upload-time = "2026-11-09T21:08:54.279Z" }, - { url = "https://files.pythonhosted.org/packages/c8/ea/1705ff4014c8bad5d7045022647156cfebd6c7014886da47e13512d27c08/tornado-6.6.1-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:533185c89be3ffb01656c9425da4ff42587a3af784b37d39fe762e8fce3b2dbe", size = 537624, upload-time = "2026-11-09T21:08:55.648Z" }, - { url = "https://files.pythonhosted.org/packages/50/5d/421168e62c8b80e3ef88f80d642e9a7e5b1d0c6e8cd136d99064f663951c/tornado-6.6.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:fbaa022a49a27b65668592cf43b898ff3978cbe4e6926fdfe24dbef59053bd26", size = 537632, upload-time = "2026-11-09T21:08:57.797Z" }, - { url = "https://files.pythonhosted.org/packages/6a/b4/13b2f98a3141c152915fa3e69531a04bdc1cd7dd203f442136f3792a486f/tornado-6.6.1-cp314-cp314t-win32.whl", hash = "sha256:4bc6c60faf86162df25ba2ff5611d27b6ef8226de9d61c07a0fab53c169630a5", size = 535424, upload-time = "2026-11-09T21:08:59.145Z" }, - { url = "https://files.pythonhosted.org/packages/84/83/6d54c37b3e437ab0ff2bddd71249c6ea2a17051104dd2995cb4e181e95a7/tornado-6.6.1-cp314-cp314t-win_amd64.whl", hash = "sha256:71c16b382b22d3234913a3f74a1ea84bede197d11eb03871df17bb123088dfa5", size = 535715, upload-time = "2026-11-09T21:09:00.456Z" }, - { url = "https://files.pythonhosted.org/packages/d4/38/75419d8cd577b7c4f335f4c5e75f127af286545ad49047a73afffdf877fe/tornado-6.6.1-cp314-cp314t-win_arm64.whl", hash = "sha256:510c7261ed986ecd6f74edc1a13412759e7abc2e8be3a6c85e15f6c53e1f3c84", size = 535718, upload-time = "2026-11-09T21:09:01.783Z" }, - { url = "https://files.pythonhosted.org/packages/91/8b/96e460653f3e2ad83d70328414394132d73d5655047c692ce7b69ae2f6c0/tornado-6.6.1-cp315-cp315t-macosx_10_15_universal2.whl", hash = "sha256:01dc73e3697eb94d78c42e03931ab621da97d12fdfb6339e64ff5a934b220fcf", size = 533376, upload-time = "2026-11-09T21:09:03.097Z" }, - { url = "https://files.pythonhosted.org/packages/1a/1e/644bace0700e533235f01ffa68a7b5e3d6cc9eb7380e3929039d04b648b9/tornado-6.6.1-cp315-cp315t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:95bd4751357bef52aa655e236b9667ff054885de4b118e4ce9ba5c06e12ef5d0", size = 537696, upload-time = "2026-11-09T21:09:04.519Z" }, - { url = "https://files.pythonhosted.org/packages/e6/0a/afccc23d1ed71bcb1ce4a5b6e0f61f82c7a0b275f3b377ee7aee6680a565/tornado-6.6.1-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:29bce3190c2973fcd2171c95eeab8bf06d2f7a7eb107455ce3e4662c704aecdb", size = 538796, upload-time = "2026-11-09T21:09:05.956Z" }, - { url = "https://files.pythonhosted.org/packages/e5/24/69692f8ba851ed2738c2623eab592360d646f0a2e16b6deea16516aa8595/tornado-6.6.1-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:b777fbe0bdb2c4dc764aadf5f70e9b23b2e536c339d61c799d3ea1b575a7c285", size = 538951, upload-time = "2026-11-09T21:09:07.298Z" }, - { url = "https://files.pythonhosted.org/packages/00/82/234306b41b33600a470da7e595b8064b85e2f509f64f5c1d39387c0abbb8/tornado-6.6.1-cp315-cp315t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:15443805d6b7aa11610cc6c5be7e71b4a93369aeb2ca5a13c2def53a3af5ba45", size = 537861, upload-time = "2026-11-09T21:09:08.857Z" }, - { url = "https://files.pythonhosted.org/packages/5b/87/6d13a60c320c0379cbfa4c2520b4ba076780c33e6a01ba3073fff74b71db/tornado-6.6.1-cp315-cp315t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:b77ab23d1520c807d11e703e79b020d3bc3676a0f5ebc8531f46d3fac8aecb2f", size = 536178, upload-time = "2026-11-09T21:09:10.424Z" }, - { url = "https://files.pythonhosted.org/packages/96/c7/e27f2a21e05d7c5aa9886db7368436e6436880b85349072988b4f62422e3/tornado-6.6.1-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:872249311539281c1e8a5d8d6f27f478bf705a9bd931bf374b6b31b05177dfda", size = 538491, upload-time = "2026-11-09T21:09:11.968Z" }, - { url = "https://files.pythonhosted.org/packages/f3/c7/1f981336039c51d81ee6f895e3412178edc409bd709e38767365c55c0daa/tornado-6.6.1-cp315-cp315t-musllinux_1_2_ppc64le.whl", hash = "sha256:08b808e8d3312c268f9fe1ffebfcfaaf342e7fe4ac40d219a7e1b58bac547d6f", size = 538491, upload-time = "2026-11-09T21:09:13.226Z" }, - { url = "https://files.pythonhosted.org/packages/5d/4f/7dafc65726778ac148b68c91920605892e84bf0ffcc02890aaf1a7d0ba8d/tornado-6.6.1-cp315-cp315t-musllinux_1_2_riscv64.whl", hash = "sha256:8d475f4053c693b5c1483eb4845824129b0b51c65712e736b3c2ea1c8f6080cd", size = 537775, upload-time = "2026-11-09T21:09:14.697Z" }, - { url = "https://files.pythonhosted.org/packages/a1/25/85c852307f9e49896b6dc5119f6a0131f5f6d97c478a687654c2c0c3f0f4/tornado-6.6.1-cp315-cp315t-musllinux_1_2_s390x.whl", hash = "sha256:e923e75c9d641cdb8bbac60070a2dccdb684fc555af2bff48b0eaded0f88c2dc", size = 537798, upload-time = "2026-11-09T21:09:15.946Z" }, - { url = "https://files.pythonhosted.org/packages/60/43/a37ec29b0f98c3c639da495e1d547d6c44c69a6727b9864cf149bf346433/tornado-6.6.1-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:a72f70b1aa630fa2106d39a025e2be75c272b7ec8233da94e2f407ea754cc32d", size = 537809, upload-time = "2026-11-09T21:09:17.265Z" }, - { url = "https://files.pythonhosted.org/packages/3b/d4/13973391071552e03acb308d93f6deb4fb535a769a6bbdafdb4cafcb2f91/tornado-6.6.1-cp315-cp315t-win32.whl", hash = "sha256:2fbfd2510b6163b189773155a8246c025cb260ccc7cd12ad18c36c54f5617bb9", size = 535422, upload-time = "2026-11-09T21:09:18.525Z" }, - { url = "https://files.pythonhosted.org/packages/19/94/c952b625904b63fdac5b747f2eeaca64ab5d36cdb8faff57effa57162d87/tornado-6.6.1-cp315-cp315t-win_amd64.whl", hash = "sha256:3c35091add5863feb9cf651851bb1b23592f1f9551b5dfed72837c83ea4e5b85", size = 535713, upload-time = "2026-11-09T21:09:20.061Z" }, - { url = "https://files.pythonhosted.org/packages/f8/62/8d0c0c42f3346f3f2455738d3bc689bbd8efba38abf7b90ab2b8294eae83/tornado-6.6.1-cp315-cp315t-win_arm64.whl", hash = "sha256:065bc741478b168df9baf754956a3010c04d1330bb45a84833d807c29e11b257", size = 535719, upload-time = "2026-11-09T21:09:21.317Z" }, +version = "6.6.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d9/6b/2d39e2981c79955ae24297126a381653932c737d67fb9344759798a1fe50/tornado-6.6.2.tar.gz", hash = "sha256:1e33a35c0c4add27f741305ba03a8730db5d15d2198c7bb85101843822bd1595", size = 633019, upload-time = "2026-12-02T19:31:21.471Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/6f/c2/0f5e29b1e9c0f99d60d1f1aa8f2451023dd116cd05f33f304074c4a79c58/tornado-6.6.2-cp311-abi3-macosx_10_9_universal2.whl", hash = "sha256:c1df9d6fec69771228f74a597e1d06b54828f6270ab67226c3ccbd27b5d6b86f", size = 541296, upload-time = "2026-12-02T19:30:18.087Z" }, + { url = "https://files.pythonhosted.org/packages/58/61/b7357f06f1cc45b0505d2fe0d2c227a4a5ee9b48593c8e3f151794fd6b1b/tornado-6.6.2-cp311-abi3-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:5fa3f777a5679422e6147a730cc6fec4eb08affc2683716e6e3a297e18b2c4eb", size = 542515, upload-time = "2026-12-02T19:30:19.925Z" }, + { url = "https://files.pythonhosted.org/packages/0a/04/9f39029350d4b51abff74c4f7c2260999b298b92f47a817f34094fbe9087/tornado-6.6.2-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e8b69793d35ed2a4fae44062ef97a48639c48a58a73bc4d2e5f862ca74345a8f", size = 543492, upload-time = "2026-12-02T19:30:21.624Z" }, + { url = "https://files.pythonhosted.org/packages/5f/b5/d6533ba22477e5ad3353bc82f7bbdca2bf138f5f80014638930eb9187c2b/tornado-6.6.2-cp311-abi3-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:bc8dc4242867f03fd9bbe7e195903fb3692c62d62dc80f147f3c347668513fb9", size = 543710, upload-time = "2026-12-02T19:30:23.572Z" }, + { url = "https://files.pythonhosted.org/packages/fb/47/36913b43cf6495af7fd9d03daf7045059a6587ebdc06d8591e7c251c330e/tornado-6.6.2-cp311-abi3-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:0595f2ee0ba829904e1cbd190268acfcd7da5e5c23ecc7eccdfc14db60a595c0", size = 542710, upload-time = "2026-12-02T19:30:25.205Z" }, + { url = "https://files.pythonhosted.org/packages/54/e5/f7e884eb9bfa666c0e8d22fed28a93adce18a1cce02b3e36227e3d8a733b/tornado-6.6.2-cp311-abi3-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:b448816ae3c5c420305a4fcfd9a8607123fa110e938f92d43cdb523166d54708", size = 540845, upload-time = "2026-12-02T19:30:26.667Z" }, + { url = "https://files.pythonhosted.org/packages/63/80/59277d8ac7df79136e82d9c374db9946ffa7b106525f729258257e9c3aa5/tornado-6.6.2-cp311-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:98efc7b7a01a940e0089493212e22a8315baad89680956eb09a8c0017d1a4f13", size = 543337, upload-time = "2026-12-02T19:30:28.08Z" }, + { url = "https://files.pythonhosted.org/packages/c2/66/f1266de5184224edd3f99d4ca641cd3870a7e142bdb25311479f41a8c394/tornado-6.6.2-cp311-abi3-musllinux_1_2_ppc64le.whl", hash = "sha256:c451c89244ec06b4e5981802383944e628e7d5ed0fbe6299e03fc62faea5b1af", size = 543429, upload-time = "2026-12-02T19:30:29.394Z" }, + { url = "https://files.pythonhosted.org/packages/88/77/c3f81f6a1751324c5cad526c1f14cf12edc0a824848c876f52769e095c6c/tornado-6.6.2-cp311-abi3-musllinux_1_2_riscv64.whl", hash = "sha256:e4c53fad78ae90e690d86b1db9aaf69413112e9bf7d7959284403c9e4817e41f", size = 542582, upload-time = "2026-12-02T19:30:30.71Z" }, + { url = "https://files.pythonhosted.org/packages/9e/28/7f3866348e98fd489e1bfe60f320b66e121d5f960cf8996c24bbaff76225/tornado-6.6.2-cp311-abi3-musllinux_1_2_s390x.whl", hash = "sha256:124a0aefb2bdead68484b6098ccf77f6841c2feae5c6f170a3067f60f2d3c41c", size = 542775, upload-time = "2026-12-02T19:30:32.277Z" }, + { url = "https://files.pythonhosted.org/packages/21/e6/fb1672a55738efc665ef07a0e0596a160a4848618726b3019eafd3206ac0/tornado-6.6.2-cp311-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:bc14f0d5dbd6a9ff82227fd453030b88a9845c04e80374609d7a20f93e226519", size = 542727, upload-time = "2026-12-02T19:30:33.996Z" }, + { url = "https://files.pythonhosted.org/packages/e8/98/a92602f37b8ef1f96d0c386ee9dc149ab24e50a710e69bce18d1f7e029df/tornado-6.6.2-cp311-abi3-win32.whl", hash = "sha256:cb606c1a5707d776c493381543948fd11bcbb6c862b615cb03900b9ab623ea65", size = 543681, upload-time = "2026-12-02T19:30:35.484Z" }, + { url = "https://files.pythonhosted.org/packages/f7/36/b803e8e9a05eeea529d3f9928c304dce55e11d5cd09f35ee9cea66c15717/tornado-6.6.2-cp311-abi3-win_amd64.whl", hash = "sha256:a45c671e60d7332b5ee722f49b6ae30d343ffb371902b8b56f544676bf2fcaf5", size = 543928, upload-time = "2026-12-02T19:30:36.904Z" }, + { url = "https://files.pythonhosted.org/packages/8e/8a/aaf2b6d635585a38657c28148fe673ae799cb803a59d0c1742de4332869a/tornado-6.6.2-cp311-abi3-win_arm64.whl", hash = "sha256:be3d8ed2f637466a600f02f0028b81a8ce1311aee6857f7fc04877fe8b58629d", size = 544147, upload-time = "2026-12-02T19:30:38.233Z" }, + { url = "https://files.pythonhosted.org/packages/a5/e0/e450346cb49d6d499fd5e44ab65b7b877c8ceecc9072e1c2497e285d9afd/tornado-6.6.2-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:81d0adbbeaa7eaa64ebca5b7bfe44ca34a0a65ea84ef4d5a90cb45d85753d9d9", size = 541399, upload-time = "2026-12-02T19:30:39.946Z" }, + { url = "https://files.pythonhosted.org/packages/15/a5/f8cd16fbf191561bb4f3d8c005a0ddef8790de2acb5358210628b96b6dc7/tornado-6.6.2-cp314-cp314t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:0360ac2c2f563f66f01d2e065518e80849a3af7ceb81710883b509ef9683e71f", size = 545554, upload-time = "2026-12-02T19:30:41.567Z" }, + { url = "https://files.pythonhosted.org/packages/44/f0/548e50bf19ce8e34c2b5475c0dd91a88061bc0c6263f0ae5c3f3ecb6801f/tornado-6.6.2-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:291deea796987c61f18a620b58b830d113d668ab3a6946cdddd87a231abf7877", size = 546613, upload-time = "2026-12-02T19:30:42.945Z" }, + { url = "https://files.pythonhosted.org/packages/77/54/89d6235daa24aa7dc77770aac8440a7e22a76e93f9d5aa958272b6b0c002/tornado-6.6.2-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:3df74f221bbd1273b0150dd5425655def9de4f463041a4e3cc1eeb1b1b9b668f", size = 546840, upload-time = "2026-12-02T19:30:44.331Z" }, + { url = "https://files.pythonhosted.org/packages/cf/0d/88bc6347fcfa72fda3ac5b5ca6220f558d5cedbbf6c70f52ace937ae3d93/tornado-6.6.2-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:fb0a1657fecad94aefc7084e0cd870f9495c8dccbc548d463acc20ddc2319cfb", size = 545737, upload-time = "2026-12-02T19:30:45.768Z" }, + { url = "https://files.pythonhosted.org/packages/91/27/4347a9c387f9eae00bc6beaf0767a124fe483083935624f29d74987d5aeb/tornado-6.6.2-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:08275ad29a8f10126fbe94bcb718c3c7cd3358828a5d946fd7bd531e9f8e9ff5", size = 543889, upload-time = "2026-12-02T19:30:47.383Z" }, + { url = "https://files.pythonhosted.org/packages/9e/5f/f89c3ad707e45239ed45260e4e78a2f48856bfc781c9f3125cabba0b8d63/tornado-6.6.2-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:ee6ed702330fefd09d5b375eaea77a37da9f517c88aade35afacfa8799aa4dd4", size = 546344, upload-time = "2026-12-02T19:30:48.81Z" }, + { url = "https://files.pythonhosted.org/packages/74/b2/c78b9bc1fb28c9dc395bc9b72c97dbf525265711d43e7fb60231fd964a9a/tornado-6.6.2-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:e043010edb64224bac234473eeb4ec912eb2187b56d9c6d1cd8e3e75ee209cae", size = 546395, upload-time = "2026-12-02T19:30:50.212Z" }, + { url = "https://files.pythonhosted.org/packages/87/97/2553a557368cbf6d47f412c8a02106c365d0dbf34d798e6e5bcf00dc9cc8/tornado-6.6.2-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:8481f6d416242bf77cc7a5e3c584a4dedf304a313a85535467a4b936ff36d139", size = 545516, upload-time = "2026-12-02T19:30:51.632Z" }, + { url = "https://files.pythonhosted.org/packages/36/bf/b20d25950ec8be63cbe614f0df35034d167e48af13cf52accd53607a704d/tornado-6.6.2-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:87ae85c9862665f111bbaace50c228d8d6d7e02bc42e26a5c363aefbc3c66a18", size = 545672, upload-time = "2026-12-02T19:30:53.064Z" }, + { url = "https://files.pythonhosted.org/packages/d2/41/ae93833a591e25a02e5d687de1b67b1e9045df6ba7cebd63d21114249ef8/tornado-6.6.2-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:4abe6d2fc1f82dfd3df931e107f85a5e17602537d8d118fccd407354318d7025", size = 545681, upload-time = "2026-12-02T19:30:54.584Z" }, + { url = "https://files.pythonhosted.org/packages/1a/26/6075dc94ae09c63a4a2a838f6180680210b3b0f6012d08ce5fce9928d625/tornado-6.6.2-cp314-cp314t-win32.whl", hash = "sha256:8a68d73d1026ecd7a7bccb6064211b7bb882a143a5750783ebcd62ac2f6dbd57", size = 543481, upload-time = "2026-12-02T19:30:56.322Z" }, + { url = "https://files.pythonhosted.org/packages/bf/03/ee4dd39dc24b4ec075d6d57a55ce5c8770f1012b9f13ed2ba87e7df69bda/tornado-6.6.2-cp314-cp314t-win_amd64.whl", hash = "sha256:0ec44d894b53eff86eeee73f66b21b73333716457f659e3b13a37bd898d275d7", size = 543789, upload-time = "2026-12-02T19:30:57.727Z" }, + { url = "https://files.pythonhosted.org/packages/4b/00/895b31638c977f471eda91380fcce57d699b81c3b0048817d9ed5853098b/tornado-6.6.2-cp314-cp314t-win_arm64.whl", hash = "sha256:75a92a55ef2c0bb5add8d3ed71d41dd11866f8b7c1cf446fc0816190be236a11", size = 543992, upload-time = "2026-12-02T19:30:59.34Z" }, + { url = "https://files.pythonhosted.org/packages/46/79/85c2272e6fa6e3204605a50b8760f73f69161f16b57d416bd2cba053ce07/tornado-6.6.2-cp315-cp315t-macosx_10_15_universal2.whl", hash = "sha256:8617bca7d0fa1afd8afcb60196835f6b0849557d6a13245e5579dda8b49f7198", size = 541418, upload-time = "2026-12-02T19:31:01.228Z" }, + { url = "https://files.pythonhosted.org/packages/ad/ff/6d506a36716143c69cf89659131b81e9fcec48dc64330224aa9360cb685d/tornado-6.6.2-cp315-cp315t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:66dee6089ebe0d38504cd18883539e8d97d86c11b004de976d29da8d5e57af72", size = 545741, upload-time = "2026-12-02T19:31:02.711Z" }, + { url = "https://files.pythonhosted.org/packages/19/f4/f743829499988c7960c455234d6cdef6c31807c6f49b0849d044e4a9d41f/tornado-6.6.2-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1adae250cf04a7cbd462dc639bbd5f3b106f9cbf4c852287241f73e33e5e4eed", size = 546843, upload-time = "2026-12-02T19:31:04.297Z" }, + { url = "https://files.pythonhosted.org/packages/53/dc/b6b480d47d4a10d965c218e9bdcb3738d2ceed1b408972df9e6ef150c3e0/tornado-6.6.2-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:09da6d088a8ace14ea16c68ec71341206023f86f136702a4bcf7c8a65487f7d8", size = 546998, upload-time = "2026-12-02T19:31:05.906Z" }, + { url = "https://files.pythonhosted.org/packages/fa/5f/b08879a497d79433ce5dcc4e5a222830108f659a91d15bcc2c0590604701/tornado-6.6.2-cp315-cp315t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:1aeb21483b6f52fd9f289fcd3f14140bb7a49a263b17b60007ebce401f2c642e", size = 545906, upload-time = "2026-12-02T19:31:07.342Z" }, + { url = "https://files.pythonhosted.org/packages/48/3c/f5062839d8448b1ccaba74012bfcd955a692189d902536043f00b5dad887/tornado-6.6.2-cp315-cp315t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:d291f876ef9d74706bcb0256498cdbbec68f3086b376a0e8c7b742dc659170a1", size = 544188, upload-time = "2026-12-02T19:31:08.71Z" }, + { url = "https://files.pythonhosted.org/packages/f3/dd/a3b8f706d9611c62fa88a61358531817b2685aec45db0e6777d9c3ef774b/tornado-6.6.2-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:eb2b0a62ce05d3aded1d225cdbe5bca754708c0580ac9e7feecda7625bc33507", size = 546541, upload-time = "2026-12-02T19:31:10.087Z" }, + { url = "https://files.pythonhosted.org/packages/1a/32/3eab2b7b8f19f6ca3c3c9a90f788a8aa9a5dc9b4cdcdf3db9d9860854d22/tornado-6.6.2-cp315-cp315t-musllinux_1_2_ppc64le.whl", hash = "sha256:9fcc0090644034f42c101c2c88d0a10c03d98dcfcc69cce79d219a40f9368db0", size = 546539, upload-time = "2026-12-02T19:31:11.504Z" }, + { url = "https://files.pythonhosted.org/packages/c5/5a/4d2ee1fec0dc7f25ec9cfe135afb528a16df5a9fc654cebc7bb3e59c3366/tornado-6.6.2-cp315-cp315t-musllinux_1_2_riscv64.whl", hash = "sha256:1bf460d4e639a06fbcb22c888eb1b6a7fa4b36f8e436a04cf6c2d2f5df9cc8d8", size = 545822, upload-time = "2026-12-02T19:31:12.942Z" }, + { url = "https://files.pythonhosted.org/packages/ea/93/11f6f992e6626711e5bfc89ae05e5b3366153cd469c51f3999f7d136e025/tornado-6.6.2-cp315-cp315t-musllinux_1_2_s390x.whl", hash = "sha256:71cf065c89e062a6a9ec54fc86d6ab1a2a3e78027488d7f59ba77db0c179af9e", size = 545842, upload-time = "2026-12-02T19:31:14.346Z" }, + { url = "https://files.pythonhosted.org/packages/7b/c3/68b4b0e5def79dc98a536249aecb88ee07846935be90d295209e7aaa6778/tornado-6.6.2-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:6672488ee1eb239cc11f75d62327e1da81bcd9aa4d932db131d80d8c58ee1d51", size = 545855, upload-time = "2026-12-02T19:31:15.746Z" }, + { url = "https://files.pythonhosted.org/packages/fe/3c/5c3382f601dc623ddde59aba4bb3429cf493782970d1ef2dc1e7fd03734b/tornado-6.6.2-cp315-cp315t-win32.whl", hash = "sha256:3318cfc35e26485cf438f9d0f05fa8a90d312a5434a4d4c5780e757f7e7d1482", size = 543481, upload-time = "2026-12-02T19:31:17.279Z" }, + { url = "https://files.pythonhosted.org/packages/96/9d/a267f6f264f4865721c0e302326dd640d04c5a0cbd7376394c443e2464c2/tornado-6.6.2-cp315-cp315t-win_amd64.whl", hash = "sha256:f0b42d816d789f022a7fddacac5e9c44cc8b6d454044fc49bf486ac0c19fb796", size = 543777, upload-time = "2026-12-02T19:31:18.625Z" }, + { url = "https://files.pythonhosted.org/packages/1e/98/7fda11f54b5c34546dd7c29431ef4b45b4da3025b81ff16cef311d5da9e6/tornado-6.6.2-cp315-cp315t-win_arm64.whl", hash = "sha256:6f2276c99b391103c8e28799523160b9684b55f68b1e4e87520a10f193a4fcef", size = 543990, upload-time = "2026-12-02T19:31:20.077Z" }, ] [[package]] From b2e30d9584eec4c6259d035e31895bf770b94ecd Mon Sep 17 00:00:00 2001 From: Caleb Kinney Date: Wed, 2 Dec 2026 15:49:07 -0500 Subject: [PATCH 22/24] Refactor GitHub Actions workflow: streamline test jobs, enhance caching, and improve puzzle execution --- .github/workflows/quality.yml | 81 ++++++++++++++++++----------------- 1 file changed, 41 insertions(+), 40 deletions(-) diff --git a/.github/workflows/quality.yml b/.github/workflows/quality.yml index 3d2c6aa..7c53860 100644 --- a/.github/workflows/quality.yml +++ b/.github/workflows/quality.yml @@ -5,74 +5,75 @@ on: pull_request: workflow_call: +concurrency: + group: quality-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + permissions: contents: read jobs: - test: - name: Python ${{ matrix.python-version }} on ${{ matrix.os }} - runs-on: ${{ matrix.os }} + tests: + name: Tests · Python ${{ matrix.python-version }} + runs-on: ubuntu-latest + timeout-minutes: 5 strategy: fail-fast: false matrix: - include: - - os: ubuntu-latest - python-version: "3.11" - - os: ubuntu-latest - python-version: "3.12" - - os: ubuntu-latest - python-version: "3.13" - - os: ubuntu-latest - python-version: "3.14" - - os: macos-latest - python-version: "3.14" - - os: windows-latest - python-version: "3.14" + python-version: ["3.11", "3.12", "3.13", "3.14"] steps: - - name: Check out repository - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Install uv and Python uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 with: python-version: ${{ matrix.python-version }} + enable-cache: true + cache-dependency-glob: uv.lock - name: Install project run: uv sync --locked --group dev - name: Test - run: uv run pytest -q + run: uv run pytest -q --faulthandler-timeout=30 - name: Smoke-test diagnostics run: uv run elf doctor + - name: Run a puzzle generated by the installed wheel + if: matrix.python-version == '3.11' + run: | + uv build + uvx --from twine twine check dist/* + uvx check-wheel-contents dist/*.whl + uv pip install --reinstall --no-deps dist/*.whl + cd "$RUNNER_TEMP" + "$GITHUB_WORKSPACE/.venv/bin/elf" new 2016 15 + "$GITHUB_WORKSPACE/.venv/bin/python" 2016/day15.py + + static-checks: + name: Lint and type check + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - name: Install uv and Python + uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 + with: + python-version: "3.11" + enable-cache: true + cache-dependency-glob: uv.lock + + - name: Install project + run: uv sync --locked --group dev + - name: Lint - if: matrix.os == 'ubuntu-latest' && matrix.python-version == '3.11' run: uv run ruff check elf tests - name: Check formatting - if: matrix.os == 'ubuntu-latest' && matrix.python-version == '3.11' run: uv run ruff format --check elf tests - name: Type check - if: matrix.os == 'ubuntu-latest' && matrix.python-version == '3.11' run: uv run mypy - - - name: Build distributions - if: matrix.os == 'ubuntu-latest' && matrix.python-version == '3.11' - run: uv build - - - name: Validate distributions - if: matrix.os == 'ubuntu-latest' && matrix.python-version == '3.11' - run: | - uvx --from twine twine check dist/* - uvx check-wheel-contents dist/*.whl - - - name: Run a puzzle generated by the installed wheel - if: matrix.os == 'ubuntu-latest' && matrix.python-version == '3.11' - run: | - uv pip install --reinstall --no-deps dist/*.whl - cd "$RUNNER_TEMP" - "$GITHUB_WORKSPACE/.venv/bin/elf" new 2016 15 - "$GITHUB_WORKSPACE/.venv/bin/python" 2016/day15.py From 861ae58d8184a77948f6dbbeee81116e5fbc71b3 Mon Sep 17 00:00:00 2001 From: Caleb Kinney Date: Wed, 2 Dec 2026 15:49:26 -0500 Subject: [PATCH 23/24] Update README.md: clarify GitHub Actions test matrix and workflow limits --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7846139..ae3a803 100644 --- a/README.md +++ b/README.md @@ -526,7 +526,7 @@ uv run mypy uv build ``` -GitHub Actions runs the full Python 3.11–3.14 suite on Linux, plus Python 3.14 smoke jobs on macOS and Windows. Tests block external network access, mock every Advent of Code interaction, and never fetch inputs or submit answers. +GitHub Actions runs the full Python 3.11–3.14 test matrix on Ubuntu. Linting, formatting, and type checks run once per workflow. Tests block external network access, mock every Advent of Code interaction, and never fetch inputs or submit answers. Superseded runs are cancelled, and each test job has a five-minute limit. Alternatively, you can still run: From 1ca65c24ba7c62f4dd9bd6d559c4c9ac22004758 Mon Sep 17 00:00:00 2001 From: Caleb Kinney Date: Wed, 2 Dec 2026 15:52:45 -0500 Subject: [PATCH 24/24] Fix pytest command syntax for faulthandler timeout in quality workflow --- .github/workflows/quality.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/quality.yml b/.github/workflows/quality.yml index 7c53860..082b01c 100644 --- a/.github/workflows/quality.yml +++ b/.github/workflows/quality.yml @@ -36,7 +36,7 @@ jobs: run: uv sync --locked --group dev - name: Test - run: uv run pytest -q --faulthandler-timeout=30 + run: uv run pytest -q -o faulthandler_timeout=30 - name: Smoke-test diagnostics run: uv run elf doctor