From b7a8b7674a1efbf9ca116bdfcd5eec1d3b9eba2e Mon Sep 17 00:00:00 2001 From: JsNcAr Date: Wed, 14 Oct 2026 12:23:01 -0500 Subject: [PATCH 1/5] refactor: collections.abc aliases, re.prefixmatch, no __future__ import AsyncGenerator comes from collections.abc with the single type parameter 3.13+ allows; typing's alias is the deprecated spelling. scripts/release.py drops `from __future__ import annotations`, redundant since 3.14's deferred annotations, and uses re.prefixmatch, the explicit name 3.15 adds for match, which it soft-deprecates. No behaviour change. AGENTS.md records the rules. Co-Authored-By: Claude Fable 5.1 --- AGENTS.md | 9 ++++++--- scripts/release.py | 8 +++----- src/basic_api/database.py | 4 ++-- tests/conftest.py | 6 +++--- 4 files changed, 14 insertions(+), 13 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 937ad97..37a71df 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -22,9 +22,12 @@ Poetry-managed. in the change that fixes it. * **Style**: no emojis or em-dashes in code or docs; do not guess APIs, versions, flags or package names, verify in code or docs. -* **Typing**: `X | None`, never `Optional[X]`; generic classes use PEP 695 - (`class Envelope[T](BaseModel)`); route dependencies are `Annotated`, via - the `SessionDep` and `CurrentUserDep` aliases in `dependencies.py`. +* **Typing**: `X | None`, never `Optional[X]`; generic aliases come from + `collections.abc` (`AsyncGenerator[T]`, `Callable`), not `typing`; generic + classes use PEP 695 (`class Envelope[T](BaseModel)`); route dependencies + are `Annotated`, via the `SessionDep` and `CurrentUserDep` aliases in + `dependencies.py`. Read-only module constants that are mappings are + `frozendict` (Python 3.15); regexes use `prefixmatch`, not `match`. ## Project Structure ``` diff --git a/scripts/release.py b/scripts/release.py index 60a233e..76bcfea 100644 --- a/scripts/release.py +++ b/scripts/release.py @@ -33,8 +33,6 @@ Standard library only, so CI can run it before installing anything. """ -from __future__ import annotations - import argparse import datetime as dt import os @@ -89,7 +87,7 @@ class ReleaseError(Exception): def parse_version(text: str) -> tuple[int, int, int, str | None]: """Split X.Y.Z[-pre] into its parts, or raise ReleaseError.""" - match = VERSION_RE.match(text.strip()) + match = VERSION_RE.prefixmatch(text.strip()) if not match: raise ReleaseError(f"not a version: {text!r} (expected X.Y.Z or X.Y.Z-rc.N)") major, minor, patch, pre = match.groups() @@ -189,7 +187,7 @@ def render_section(commits: list[Commit]) -> str: """Changelog entries grouped by Conventional Commit type; '' if none.""" groups: dict[str, list[str]] = {} for commit in commits: - match = COMMIT_RE.match(commit.subject) + match = COMMIT_RE.prefixmatch(commit.subject) if not match: continue # not conventional (merges and the like): nothing to file it under kind, scope, desc = match["type"], match["scope"], match["desc"] @@ -457,7 +455,7 @@ def pipelines_url(remote: str) -> str: Returns: A URL, or a short hint when the remote is not recognised. """ - match = re.match( + match = re.prefixmatch( r"^(?:[a-z+]+://)?(?:[^@/]+@)?(?P[^:/]+)(?::\d+)?" r"[:/](?P.+?)(?:\.git)?/?$", remote.strip(), diff --git a/src/basic_api/database.py b/src/basic_api/database.py index 9c1647f..de41e14 100644 --- a/src/basic_api/database.py +++ b/src/basic_api/database.py @@ -4,7 +4,7 @@ import asyncio import logging -from typing import AsyncGenerator +from collections.abc import AsyncGenerator from sqlalchemy import text from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine @@ -69,7 +69,7 @@ async def ping(timeout: float = 2.0) -> bool: return False -async def get_session() -> AsyncGenerator[AsyncSession, None]: +async def get_session() -> AsyncGenerator[AsyncSession]: """One session per request; closed when the request ends.""" async with async_session_factory() as session: yield session diff --git a/tests/conftest.py b/tests/conftest.py index e99699b..41ccfd0 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -11,7 +11,7 @@ import asyncio import os -from typing import AsyncGenerator +from collections.abc import AsyncGenerator import pytest from dotenv import load_dotenv @@ -71,7 +71,7 @@ async def teardown(): @pytest.fixture -async def session() -> AsyncGenerator[AsyncSession, None]: +async def session() -> AsyncGenerator[AsyncSession]: """A session per test; every row is deleted afterwards.""" async with async_session_maker() as session: yield session @@ -84,7 +84,7 @@ async def session() -> AsyncGenerator[AsyncSession, None]: @pytest.fixture -async def client(session: AsyncSession) -> AsyncGenerator[AsyncClient, None]: +async def client(session: AsyncSession) -> AsyncGenerator[AsyncClient]: """HTTP client over the app, sharing the test session and sending the API key.""" def get_session_override(): From d46f102855d78f966b5b0a63f27d7d849f44a09b Mon Sep 17 00:00:00 2001 From: JsNcAr Date: Wed, 14 Oct 2026 12:23:02 -0500 Subject: [PATCH 2/5] refactor: read-only constant mappings are frozendict Python 3.15's frozendict builtin for the four module-level mappings that are only read: _SECRET_MINIMUM_BYTES (config), _TAKEN_MESSAGES (services.users), _DESCRIPTIONS (schemas.errors) and SECTIONS (scripts/release.py). They are Mappings, so .get, .values() and subscripting are unchanged; a stray assignment is now a TypeError instead of a silent edit. Co-Authored-By: Claude Fable 5.1 --- scripts/release.py | 18 ++++++++++-------- src/basic_api/config.py | 2 +- src/basic_api/schemas/errors.py | 26 ++++++++++++++------------ src/basic_api/services/users.py | 12 +++++++----- 4 files changed, 32 insertions(+), 26 deletions(-) diff --git a/scripts/release.py b/scripts/release.py index 76bcfea..e3d3036 100644 --- a/scripts/release.py +++ b/scripts/release.py @@ -64,14 +64,16 @@ # Conventional Commit type -> changelog heading, in display order. Types not # listed (chore, ci, test, build, style) are housekeeping and left out. -SECTIONS = { - "feat": "Added", - "refactor": "Changed", - "perf": "Performance", - "fix": "Fixed", - "security": "Security", - "docs": "Documentation", -} +SECTIONS = frozendict( + { + "feat": "Added", + "refactor": "Changed", + "perf": "Performance", + "fix": "Fixed", + "security": "Security", + "docs": "Documentation", + } +) BREAKING = "Breaking changes" COMMIT_RE = re.compile( r"^(?P[a-z]+)(?:\((?P[^)]+)\))?(?P!)?: (?P.+)$" diff --git a/src/basic_api/config.py b/src/basic_api/config.py index 56ac0c0..1773651 100644 --- a/src/basic_api/config.py +++ b/src/basic_api/config.py @@ -185,7 +185,7 @@ def _test_database_url() -> str: _ALLOWED_ALGORITHMS = ("HS256", "HS384", "HS512") # RFC 7518 section 3.2: an HMAC key should be at least as long as the hash it # drives. PyJWT 2.15 checks the same rule at sign and verify time. -_SECRET_MINIMUM_BYTES = {"HS256": 32, "HS384": 48, "HS512": 64} +_SECRET_MINIMUM_BYTES = frozendict({"HS256": 32, "HS384": 48, "HS512": 64}) _MIN_BCRYPT_ROUNDS = 12 diff --git a/src/basic_api/schemas/errors.py b/src/basic_api/schemas/errors.py index 4f98994..09c4a6a 100644 --- a/src/basic_api/schemas/errors.py +++ b/src/basic_api/schemas/errors.py @@ -18,18 +18,20 @@ class ErrorDetail(BaseModel): # Code -> what it means in this API. Kept in step with docs/api.md. -_DESCRIPTIONS: dict[int, str] = { - 400: "A confirmation password was wrong", - 401: ( - "Missing or invalid X-API-Key; or missing, invalid, expired or orphaned " - "bearer token; or wrong login credentials" - ), - 403: "The account is disabled", - 409: "Username, email or phone number already in use", - 413: "Request body over MAX_REQUEST_BODY_BYTES (plain-text body)", - 429: "Over the rate limit; wait for Retry-After seconds", - 503: "Database unreachable", -} +_DESCRIPTIONS: frozendict[int, str] = frozendict( + { + 400: "A confirmation password was wrong", + 401: ( + "Missing or invalid X-API-Key; or missing, invalid, expired or orphaned " + "bearer token; or wrong login credentials" + ), + 403: "The account is disabled", + 409: "Username, email or phone number already in use", + 413: "Request body over MAX_REQUEST_BODY_BYTES (plain-text body)", + 429: "Over the rate limit; wait for Retry-After seconds", + 503: "Database unreachable", + } +) def error_responses(*codes: int) -> dict[int | str, dict[str, Any]]: diff --git a/src/basic_api/services/users.py b/src/basic_api/services/users.py index c15ef5f..60e7dfe 100644 --- a/src/basic_api/services/users.py +++ b/src/basic_api/services/users.py @@ -26,11 +26,13 @@ # What a client is told when an identifier collides, per field, so a form can # mark the right input. Checked before the insert; the unique constraints are # the backstop for two requests racing past the checks. -_TAKEN_MESSAGES = { - "username": "Username is already taken", - "email": "Email address is already registered", - "phone_number": "Phone number is already associated with an account", -} +_TAKEN_MESSAGES = frozendict( + { + "username": "Username is already taken", + "email": "Email address is already registered", + "phone_number": "Phone number is already associated with an account", + } +) _RACE_MESSAGE = "A user with this username, email, or phone number already exists" From 795e5cc8c57e914c98f14aed37afb95eae02c73e Mon Sep 17 00:00:00 2001 From: JsNcAr Date: Wed, 14 Oct 2026 12:23:03 -0500 Subject: [PATCH 3/5] fix(release): explicit UTF-8 for every file and subprocess read scripts/release.py and its test decoded git and poetry output and read or wrote pyproject.toml and CHANGELOG.md with the default encoding. Python 3.15 makes UTF-8 that default (PEP 686) and advises naming it; every read_text, write_text and subprocess.run(text=True) now passes encoding="utf-8", and `python -X warn_default_encoding -W error::EncodingWarning` is clean for the app import and the pure test set. Co-Authored-By: Claude Fable 5.1 --- scripts/release.py | 36 +++++++++++++++++++++++++----------- tests/test_release_script.py | 31 ++++++++++++++++++++++--------- 2 files changed, 47 insertions(+), 20 deletions(-) diff --git a/scripts/release.py b/scripts/release.py index e3d3036..792298d 100644 --- a/scripts/release.py +++ b/scripts/release.py @@ -259,7 +259,10 @@ def release_notes(changelog: str, version: str) -> str: def git(*args: str, check: bool = True) -> str: - result = subprocess.run(["git", *args], cwd=ROOT, capture_output=True, text=True) + # UTF-8 is the 3.15 default; stated so the intent survives PYTHONUTF8=0. + result = subprocess.run( + ["git", *args], cwd=ROOT, capture_output=True, text=True, encoding="utf-8" + ) if check and result.returncode != 0: raise ReleaseError(f"git {' '.join(args)} failed:\n{result.stderr.strip()}") return result.stdout.strip() @@ -352,6 +355,7 @@ def refresh_installed_metadata() -> None: cwd=ROOT, capture_output=True, text=True, + encoding="utf-8", ) if result.returncode == 0: print("Reinstalled the project so APP_VERSION reports the new version.") @@ -363,14 +367,18 @@ def refresh_installed_metadata() -> None: def cmd_prepare(args: argparse.Namespace) -> None: - project = read_project(PYPROJECT.read_text()) + project = read_project(PYPROJECT.read_text(encoding="utf-8")) version = bump(project.version, args.part) tag = f"v{version}" preflight(project, tag, allow_branch=args.allow_branch) previous = last_tag() generated = render_section(commits_since(previous)) - changelog = CHANGELOG.read_text() if CHANGELOG.exists() else UNRELEASED + "\n" + changelog = ( + CHANGELOG.read_text(encoding="utf-8") + if CHANGELOG.exists() + else UNRELEASED + "\n" + ) new_changelog, notes = add_release(changelog, version, generated, dt.date.today()) print( @@ -394,14 +402,16 @@ def cmd_prepare(args: argparse.Namespace) -> None: run_tests() files = { - PYPROJECT: write_version(PYPROJECT.read_text(), version), + PYPROJECT: write_version(PYPROJECT.read_text(encoding="utf-8"), version), CHANGELOG: new_changelog, } - originals = {p: p.read_text() if p.exists() else None for p in files} + originals = { + p: p.read_text(encoding="utf-8") if p.exists() else None for p in files + } relative = [str(p.relative_to(ROOT)) for p in files] try: for path, text in files.items(): - path.write_text(text) + path.write_text(text, encoding="utf-8") editor = os.environ.get("VISUAL") or os.environ.get("EDITOR") if ( editor @@ -410,7 +420,7 @@ def cmd_prepare(args: argparse.Namespace) -> None: and confirm("Edit CHANGELOG.md before committing?", False) ): subprocess.run([*shlex.split(editor), str(CHANGELOG)], check=True) - notes = release_notes(CHANGELOG.read_text(), version) + notes = release_notes(CHANGELOG.read_text(encoding="utf-8"), version) if not confirm(f"Commit and tag {tag}?", args.yes): raise ReleaseError("stopped before committing") git("add", *relative) @@ -420,7 +430,7 @@ def cmd_prepare(args: argparse.Namespace) -> None: if original is None: path.unlink(missing_ok=True) else: - path.write_text(original) + path.write_text(original, encoding="utf-8") git("reset", "-q", "--", *relative, check=False) print("The version files were restored; nothing was committed.") raise @@ -486,11 +496,15 @@ def _emit_outputs(version: str) -> None: def cmd_notes(args: argparse.Namespace) -> None: - print(release_notes(CHANGELOG.read_text(), args.version.removeprefix("v"))) + print( + release_notes( + CHANGELOG.read_text(encoding="utf-8"), args.version.removeprefix("v") + ) + ) def cmd_check_version(args: argparse.Namespace) -> None: - version = read_project(PYPROJECT.read_text()).version + version = read_project(PYPROJECT.read_text(encoding="utf-8")).version tag_version = args.tag.removeprefix("refs/tags/").removeprefix("v") if tag_version != version: raise ReleaseError( @@ -501,7 +515,7 @@ def cmd_check_version(args: argparse.Namespace) -> None: def cmd_version(_args: argparse.Namespace) -> None: - version = read_project(PYPROJECT.read_text()).version + version = read_project(PYPROJECT.read_text(encoding="utf-8")).version print(version) _emit_outputs(version) diff --git a/tests/test_release_script.py b/tests/test_release_script.py index 463e909..3f11b54 100644 --- a/tests/test_release_script.py +++ b/tests/test_release_script.py @@ -237,7 +237,12 @@ def test_release_notes_needs_the_section(): def _git(cwd, *args): return subprocess.run( - ["git", *args], cwd=cwd, check=True, capture_output=True, text=True + ["git", *args], + cwd=cwd, + check=True, + capture_output=True, + text=True, + encoding="utf-8", ).stdout.strip() @@ -250,8 +255,8 @@ def repo(tmp_path, monkeypatch): _git(tmp_path, "clone", "-q", str(remote), str(work)) _git(work, "config", "user.email", "t@example.com") _git(work, "config", "user.name", "Test") - (work / "pyproject.toml").write_text(PYPROJECT) - (work / "CHANGELOG.md").write_text(CHANGELOG) + (work / "pyproject.toml").write_text(PYPROJECT, encoding="utf-8") + (work / "CHANGELOG.md").write_text(CHANGELOG, encoding="utf-8") _git(work, "add", ".") _git(work, "commit", "-q", "-m", "feat: first") _git(work, "push", "-q", "-u", "origin", "main") @@ -267,13 +272,18 @@ def test_prepare_commits_tags_and_leaves_unreleased_empty(repo, capsys): assert release.main(["prepare", "minor", "--skip-tests", "--no-push", "--yes"]) == 0 assert ( - release.read_project((repo / "pyproject.toml").read_text()).version == "0.2.0" + release.read_project( + (repo / "pyproject.toml").read_text(encoding="utf-8") + ).version + == "0.2.0" ) assert _git(repo, "log", "-1", "--format=%s") == "chore(release): v0.2.0" assert _git(repo, "status", "--porcelain") == "" tag_message = _git(repo, "tag", "-l", "--format=%(contents)", "v0.2.0") assert tag_message.startswith("v0.2.0\n\n### Added\n- A thing (#3).") - _head, body, _rest = release.split_unreleased((repo / "CHANGELOG.md").read_text()) + _head, body, _rest = release.split_unreleased( + (repo / "CHANGELOG.md").read_text(encoding="utf-8") + ) assert body == "" assert "Not pushed" in capsys.readouterr().out assert _git(repo, "ls-remote", "--tags", "origin") == "" # --no-push kept it local @@ -297,7 +307,7 @@ def test_prepare_dry_run_changes_nothing(repo, capsys): def test_prepare_refuses_in_the_starter(repo, capsys): - (repo / "pyproject.toml").write_text(PYPROJECT + STARTER_TABLE) + (repo / "pyproject.toml").write_text(PYPROJECT + STARTER_TABLE, encoding="utf-8") _git(repo, "commit", "-q", "-am", "chore: mark as starter") _git(repo, "push", "-q") assert release.main(["prepare", "minor", "--skip-tests", "--no-push", "--yes"]) == 1 @@ -305,7 +315,10 @@ def test_prepare_refuses_in_the_starter(repo, capsys): assert _git(repo, "status", "--porcelain") == "" assert _git(repo, "tag") == "" assert ( - release.read_project((repo / "pyproject.toml").read_text()).version == "0.1.0" + release.read_project( + (repo / "pyproject.toml").read_text(encoding="utf-8") + ).version + == "0.1.0" ) @@ -315,7 +328,7 @@ def test_prepare_refuses_off_main_dirty_or_behind(repo, capsys): assert "cut from main" in capsys.readouterr().err _git(repo, "switch", "-q", "main") - (repo / "scratch.txt").write_text("x") + (repo / "scratch.txt").write_text("x", encoding="utf-8") assert release.main(["prepare", "minor", "--skip-tests", "--no-push", "--yes"]) == 1 assert "uncommitted" in capsys.readouterr().err (repo / "scratch.txt").unlink() @@ -324,7 +337,7 @@ def test_prepare_refuses_off_main_dirty_or_behind(repo, capsys): _git(repo.parent, "clone", "-q", str(repo.parent / "remote.git"), str(other)) _git(other, "config", "user.email", "t@example.com") _git(other, "config", "user.name", "Test") - (other / "note.txt").write_text("y") + (other / "note.txt").write_text("y", encoding="utf-8") _git(other, "add", ".") _git(other, "commit", "-q", "-m", "docs: a note") _git(other, "push", "-q") From a429f953ec28f96e83479ac63bfe3aa0ca0fcb5c Mon Sep 17 00:00:00 2001 From: JsNcAr Date: Wed, 14 Oct 2026 12:25:37 -0500 Subject: [PATCH 4/5] docs(setup): the 3.15 sampling profiler next to the asyncio commands profiling.sampling (Tachyon) in dump, attach and run form with --async-aware, and the one fact that decides whether it works: reading another process's memory needs ptrace permission on Linux (scope 0, root or CAP_SYS_PTRACE), which `run` avoids by starting the server as its child. Tried on this machine: run works unprivileged, dump on a sibling is refused with ptrace_scope=1, as the text says. Co-Authored-By: Claude Fable 5.1 --- docs/setup.md | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/docs/setup.md b/docs/setup.md index 74f61ae..0683c48 100644 --- a/docs/setup.md +++ b/docs/setup.md @@ -166,10 +166,10 @@ Everything a new project renames or changes, in one list: The starter itself stays at `0.1.0`. 7. **Docs**: this folder and the README. -## Debugging a hung process +## Debugging a hung or slow process -Python 3.14 can show what an asyncio program is waiting on, from outside the -process and without stopping it: +Python can show what an asyncio program is waiting on, from outside the +process and without stopping it (3.14): ```bash python -m asyncio ps # one line per task: id, name, coroutine stack @@ -178,3 +178,20 @@ python -m asyncio pstree # the same as an await tree Point it at the uvicorn worker's pid. A task stuck on a database call or a lock shows up with its full await chain; that is usually enough to name the culprit. + +Python 3.15 adds a sampling profiler, `profiling.sampling` (Tachyon). It reads +the worker's memory from outside, so the worker pays nothing and need not be +restarted; `--async-aware` reports stacks per task rather than event-loop +internals: + +```bash +python -m profiling.sampling dump --async-aware # one snapshot of every task +python -m profiling.sampling attach --async-aware -d 30 --flamegraph -o profile.html +python -m profiling.sampling run --async-aware -d 30 -m uvicorn basic_api.main:app --app-dir src +``` + +All of these read another process's memory. On Linux the same user is not +enough while `kernel.yama.ptrace_scope` is `1` (the usual default): run the +profiler as root, give it `CAP_SYS_PTRACE` (`--cap-add=SYS_PTRACE` for a +container), or set the scope to `0`. `run` starts the server as the profiler's +own child and needs none of that, which makes it the way to profile locally. From b1ba2ff2022a8046e48cf240627f6405352c88f3 Mon Sep 17 00:00:00 2001 From: JsNcAr Date: Wed, 14 Oct 2026 12:25:37 -0500 Subject: [PATCH 5/5] docs(changelog): Python 3.15 idioms adopted and features left unused (#23) Co-Authored-By: Claude Fable 5.1 --- CHANGELOG.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index f7e5db5..586df59 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -80,6 +80,21 @@ notes (see [docs/releasing.md](docs/releasing.md)). `RequestBodyLimitMiddleware` answers 413 before any route runs (#13). ### Changed +- Python 3.15 idioms. Read-only module constants are `frozendict` + (`_SECRET_MINIMUM_BYTES`, `_TAKEN_MESSAGES`, `_DESCRIPTIONS`, the release + script's `SECTIONS`); generic aliases come from `collections.abc` with the + single parameter 3.13+ allows; `scripts/release.py` uses `re.prefixmatch` + (3.15's explicit name for the soft-deprecated `match`), drops `from + __future__ import annotations` and names `encoding="utf-8"` on every file + and subprocess read, PEP 686's advice now that UTF-8 is the default, so + `-X warn_default_encoding` is clean. The setup guide adds the 3.15 sampling + profiler (`profiling.sampling`) next to the asyncio commands. Evaluated and + left unused, so the question need not be reopened: lazy imports (PEP 810; + the server imports everything at startup and the release script starts in + milliseconds), `sentinel` (no sentinel pattern), unpacking in comprehensions + (nothing to flatten), `TaskGroup.cancel` (no task groups), TypedDict + `closed` and `TypeForm` (no TypedDicts), free-threading and the JIT (nothing + CPU-bound) (#23). - The rate limiter is built directly on `limits` (fixed window, in-process memory) instead of slowapi, whose `asyncio.iscoroutinefunction` call is removed in Python 3.16 and unfixed upstream. A limited route now declares