From 0c50b4ff1c8295515fb948cf0bc322134113fbe8 Mon Sep 17 00:00:00 2001 From: agustin18 Date: Fri, 13 Nov 2026 16:14:39 +0000 Subject: [PATCH 1/4] fix(decorator): do not cache error responses (#575) Return Response objects with status >= 400 directly instead of encoding and caching them. A cached 404 could be served as HTTP 200 on a later request. Add a regression test for 404 and 500 responses, the changelog fragment, and update the migration/compatibility status. --- COMPATIBILITY.md | 32 ++++++++++++++++---------------- MIGRATION.md | 15 +++++++++------ changelog.d/554.bugfix.md | 1 + examples/in_memory/main.py | 11 +++++++++++ fastapi_cache/decorator.py | 2 ++ tests/test_decorator.py | 10 ++++++++++ 6 files changed, 49 insertions(+), 22 deletions(-) create mode 100644 changelog.d/554.bugfix.md diff --git a/COMPATIBILITY.md b/COMPATIBILITY.md index 2fc42596..39b9ada5 100644 --- a/COMPATIBILITY.md +++ b/COMPATIBILITY.md @@ -121,22 +121,22 @@ Status definitions: ## Intentional behavior changes -These are bug fixes targeted for `0.3.0`. The current alpha does not include all of them. -Each one will be documented in [`MIGRATION.md`](MIGRATION.md) and covered by a regression -test when implemented. - -| Version | Change | Why | -|---|---|---| -| 0.3.0 | Error `Response` objects (status >= 400) are not cached | A cached 404 could be returned as 200 | -| 0.3.0 | Authenticated requests bypass the cache by default | Prevent cross-user response reuse | -| 0.3.0 | ETag is stable across processes and correctly quoted | `hash()` is randomized per process and the old header was invalid | -| 0.3.0 | `clear(key=...)` deletes only that key | It used to delete the whole prefix namespace | -| 0.3.0 | `clear("app:user")` does not delete `app:users` | Namespace matching requires the `:` boundary | -| 0.3.0 | `expire=None` means no expiration in `InMemoryBackend` | It used to expire almost immediately | -| 0.3.0 | `Cache-Control` never emits `max-age=None` or `max-age=-1` | Invalid headers | -| 0.3.0 | User payloads with a `_spec_type` key are not interpreted as internal metadata | The marker collided with user data | -| 0.3.0 | Non-JSON responses (streaming, file, redirect) are not cached blindly | Status/headers/body were lost or corrupted | -| 0.3.0 | A second `FastAPICache.init(...)` is not a silent no-op | Configuration was impossible to change | +These are bug fixes targeted for `0.3.0`. The error-response fix is implemented on `stable`; +the remaining rows are targeted for later pre-releases. Each one is documented in +[`MIGRATION.md`](MIGRATION.md) and covered by a regression test when implemented. + +| Version | Change | Why | Status | +|---|---|---|---| +| 0.3.0 | Error `Response` objects (status >= 400) are not cached | A cached 404 could be returned as 200 | Implemented on `stable` | +| 0.3.0 | Authenticated requests bypass the cache by default | Prevent cross-user response reuse | Targeted | +| 0.3.0 | ETag is stable across processes and correctly quoted | `hash()` is randomized per process and the old header was invalid | Targeted | +| 0.3.0 | `clear(key=...)` deletes only that key | It used to delete the whole prefix namespace | Targeted | +| 0.3.0 | `clear("app:user")` does not delete `app:users` | Namespace matching requires the `:` boundary | Targeted | +| 0.3.0 | `expire=None` means no expiration in `InMemoryBackend` | It used to expire almost immediately | Targeted | +| 0.3.0 | `Cache-Control` never emits `max-age=None` or `max-age=-1` | Invalid headers | Targeted | +| 0.3.0 | User payloads with a `_spec_type` key are not interpreted as internal metadata | The marker collided with user data | Targeted | +| 0.3.0 | Non-JSON responses (streaming, file, redirect) are not cached blindly | Status/headers/body were lost or corrupted | Targeted | +| 0.3.0 | A second `FastAPICache.init(...)` is not a silent no-op | Configuration was impossible to change | Targeted | ## Cache data compatibility diff --git a/MIGRATION.md b/MIGRATION.md index 0f3b850a..596d4de8 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -14,9 +14,9 @@ normal success-path behavior. Bug fixes that change edge-case behavior are liste are covered by regression tests. See [`COMPATIBILITY.md`](COMPATIBILITY.md) for the full contract. -> **Status:** this guide describes the target `0.3.0` behavior. The current `0.3.0a0` alpha -> does not include these changes yet; they land in the `0.3.0` pre-releases. Check the -> installed version before relying on a behavior listed here. +> **Status:** this guide describes the target `0.3.0` behavior. The error-response fix is +> implemented on `stable`; the remaining changes are targeted for later `0.3.0` pre-releases. +> Check the installed version before relying on a behavior listed here. ## Who should migrate @@ -76,9 +76,9 @@ python -c "from fastapi_cache import FastAPICache; print('ok')" ## Behavior changes in 0.3.0 -These are intentional bug fixes targeted for `0.3.0`. The current alpha does not include -all of them yet. Each one will have a regression test and is listed here so you can decide -whether it affects you. +These are intentional bug fixes targeted for `0.3.0`. The error-response fix is implemented +on `stable`; the remaining changes are targeted for later pre-releases. Each one will have a +regression test and is listed here so you can decide whether it affects you. | Change | Before (0.2.2) | After (0.3.0) | |---|---|---| @@ -93,6 +93,9 @@ whether it affects you. | Non-JSON responses | Streaming/file/redirect could be cached incorrectly | Bypassed unless the coder supports them | | Second `init` | Silent no-op | Reconfiguration is explicit and documented | +The error-response fix is implemented on `stable`. The remaining rows are targeted for later +`0.3.0` pre-releases. + **Action required:** if you were affected by cached error responses or by `clear(key=...)`, flush the cache namespace after upgrading. If the ETag changes, clients may revalidate once. diff --git a/changelog.d/554.bugfix.md b/changelog.d/554.bugfix.md new file mode 100644 index 00000000..7d50d1e3 --- /dev/null +++ b/changelog.d/554.bugfix.md @@ -0,0 +1 @@ +Do not cache `Response` objects with status codes >= 400, so a cached error response cannot be returned as HTTP 200. diff --git a/examples/in_memory/main.py b/examples/in_memory/main.py index f4de1a0b..533cfdb7 100644 --- a/examples/in_memory/main.py +++ b/examples/in_memory/main.py @@ -78,6 +78,17 @@ async def cache_response_obj(): return JSONResponse({"a": 1}) +error_ret = 0 + + +@app.get("/error_response_obj") +@cache(namespace="test", expire=5) +async def error_response_obj(status_code: int = 404): + global error_ret + error_ret += 1 + return JSONResponse({"error": "error response", "n": error_ret}, status_code=status_code) + + class SomeClass: def __init__(self, value): self.value = value diff --git a/fastapi_cache/decorator.py b/fastapi_cache/decorator.py index 7df09e88..19ab0b79 100644 --- a/fastapi_cache/decorator.py +++ b/fastapi_cache/decorator.py @@ -185,6 +185,8 @@ async def ensure_async_func(*args: P.args, **kwargs: P.kwargs) -> R: if cached is None or (request is not None and request.headers.get("Cache-Control") == "no-cache") : # cache miss result = await ensure_async_func(*args, **kwargs) + if isinstance(result, Response) and result.status_code >= 400: + return result to_cache = coder.encode(result) try: diff --git a/tests/test_decorator.py b/tests/test_decorator.py index 3441dab3..7556d310 100644 --- a/tests/test_decorator.py +++ b/tests/test_decorator.py @@ -109,6 +109,16 @@ def test_non_get() -> None: assert second.json()["value"] == first.json()["value"] + 1 +def test_cache_error_response_obj_is_not_cached() -> None: + with TestClient(app) as client: + for status_code in (404, 500): + first = client.get("/error_response_obj", params={"status_code": status_code}) + second = client.get("/error_response_obj", params={"status_code": status_code}) + assert first.status_code == status_code + assert second.status_code == status_code + assert second.json()["n"] == first.json()["n"] + 1 + + def test_alternate_injected_namespace() -> None: with TestClient(app) as client: response = client.get("/namespaced_injection") From b3675ac7df022876db6c74148c4e6a4dae14eed3 Mon Sep 17 00:00:00 2001 From: agustin18 Date: Fri, 13 Nov 2026 16:14:39 +0000 Subject: [PATCH 2/4] chore(ci): scope typecheck to changed files Check only changed Python files with a minimal mypy config. The inherited strict config follows imports into modules with pre-existing errors; the full baseline is a follow-up. --- .github/workflows/ci.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 264121af..4e8ba432 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -51,9 +51,9 @@ jobs: pip install -e . mypy pytest httpx - name: Mypy changed Python files run: | - files=$(git diff --name-only origin/stable...HEAD -- '*.py') + files=$(git diff --name-only origin/stable...HEAD -- '*.py' ':!examples/*') if [ -n "$files" ]; then - mypy --python-version 3.12 --ignore-missing-imports $files + mypy --config-file=/dev/null --python-version 3.12 --ignore-missing-imports --follow-imports=skip $files else echo "No Python files changed" fi From 7c539315ce78c41f932e9a7dbe27598111594e5e Mon Sep 17 00:00:00 2001 From: agustin18 Date: Fri, 13 Nov 2026 16:19:31 +0000 Subject: [PATCH 3/4] fix(ci): use towncrier 26 for setuptools compatibility Towncrier 22.12 imports pkg_resources, which current setuptools no longer exposes. Use towncrier 26 in the workflow and lockfile; the dev dependency is restricted to Python >=3.9. --- .github/workflows/towncrier.yml | 2 +- poetry.lock | 65 ++++----------------------------- pyproject.toml | 2 +- 3 files changed, 10 insertions(+), 59 deletions(-) diff --git a/.github/workflows/towncrier.yml b/.github/workflows/towncrier.yml index 4b2c7b7e..9c8ab38d 100644 --- a/.github/workflows/towncrier.yml +++ b/.github/workflows/towncrier.yml @@ -29,7 +29,7 @@ jobs: - name: Install towncrier run: | python -m pip install --upgrade pip - pip install "towncrier>=22.12,<23" + pip install "towncrier>=26,<27" - name: Check changelog fragment run: | if [[ "${{ contains(github.event.pull_request.labels.*.name, 'skip-changelog') }}" == "true" ]]; then diff --git a/poetry.lock b/poetry.lock index 2381104e..dd6699b6 100644 --- a/poetry.lock +++ b/poetry.lock @@ -517,23 +517,6 @@ files = [ [package.dependencies] colorama = {version = "*", markers = "platform_system == \"Windows\""} -[[package]] -name = "click-default-group" -version = "1.2.4" -description = "click_default_group" -optional = false -python-versions = ">=2.7" -files = [ - {file = "click_default_group-1.2.4-py2.py3-none-any.whl", hash = "sha256:9b60486923720e7fc61731bdb32b617039aba820e22e1c88766b1125592eaa5f"}, - {file = "click_default_group-1.2.4.tar.gz", hash = "sha256:eb3f3c99ec0d456ca6cd2a7f08f7d4e91771bef51b01bdd9580cc6450fe1251e"}, -] - -[package.dependencies] -click = "*" - -[package.extras] -test = ["pytest"] - [[package]] name = "colorama" version = "0.4.6" @@ -1025,21 +1008,6 @@ zipp = {version = ">=3.1.0", markers = "python_version < \"3.10\""} docs = ["furo", "jaraco.packaging (>=9.3)", "jaraco.tidelift (>=1.4)", "rst.linker (>=1.9)", "sphinx (<7.2.5)", "sphinx (>=3.5)", "sphinx-lint"] testing = ["jaraco.test (>=5.4)", "pytest (>=6)", "pytest-checkdocs (>=2.4)", "pytest-cov", "pytest-enabler (>=2.2)", "pytest-mypy", "pytest-ruff (>=0.2.1)", "zipp (>=3.17)"] -[[package]] -name = "incremental" -version = "22.10.0" -description = "\"A small library that versions your Python projects.\"" -optional = false -python-versions = "*" -files = [ - {file = "incremental-22.10.0-py2.py3-none-any.whl", hash = "sha256:b864a1f30885ee72c5ac2835a761b8fe8aa9c28b9395cacf27286602688d3e51"}, - {file = "incremental-22.10.0.tar.gz", hash = "sha256:912feeb5e0f7e0188e6f42241d2f450002e11bbc0937c65865045854c24c0bd0"}, -] - -[package.extras] -mypy = ["click (>=6.0)", "mypy (==0.812)", "twisted (>=16.4.0)"] -scripts = ["click (>=6.0)", "twisted (>=16.4.0)"] - [[package]] name = "iniconfig" version = "2.0.0" @@ -2105,22 +2073,6 @@ files = [ cryptography = ">=2.0" jeepney = ">=0.6" -[[package]] -name = "setuptools" -version = "71.1.0" -description = "Easily download, build, install, upgrade, and uninstall Python packages" -optional = false -python-versions = ">=3.8" -files = [ - {file = "setuptools-71.1.0-py3-none-any.whl", hash = "sha256:33874fdc59b3188304b2e7c80d9029097ea31627180896fb549c578ceb8a0855"}, - {file = "setuptools-71.1.0.tar.gz", hash = "sha256:032d42ee9fb536e33087fb66cac5f840eb9391ed05637b3f2a76a7c8fb477936"}, -] - -[package.extras] -core = ["importlib-metadata (>=6)", "importlib-resources (>=5.10.2)", "jaraco.text (>=3.7)", "more-itertools (>=8.8)", "ordered-set (>=3.1.1)", "packaging (>=24)", "platformdirs (>=2.6.2)", "tomli (>=2.0.1)", "wheel (>=0.43.0)"] -doc = ["furo", "jaraco.packaging (>=9.3)", "jaraco.tidelift (>=1.4)", "pygments-github-lexers (==0.0.5)", "pyproject-hooks (!=1.1)", "rst.linker (>=1.9)", "sphinx (>=3.5)", "sphinx-favicon", "sphinx-inline-tabs", "sphinx-lint", "sphinx-notfound-page (>=1,<2)", "sphinx-reredirects", "sphinxcontrib-towncrier"] -test = ["build[virtualenv] (>=1.0.3)", "filelock (>=3.4.0)", "importlib-metadata", "ini2toml[lite] (>=0.14)", "jaraco.develop (>=7.21)", "jaraco.envs (>=2.2)", "jaraco.path (>=3.2.0)", "jaraco.test", "mypy (==1.11.*)", "packaging (>=23.2)", "pip (>=19.1)", "pyproject-hooks (!=1.1)", "pytest (>=6,!=8.1.*)", "pytest-checkdocs (>=2.4)", "pytest-cov", "pytest-enabler (>=2.2)", "pytest-home (>=0.5)", "pytest-mypy", "pytest-perf", "pytest-ruff (<0.4)", "pytest-ruff (>=0.2.1)", "pytest-ruff (>=0.3.2)", "pytest-subprocess", "pytest-timeout", "pytest-xdist (>=3)", "tomli", "tomli-w (>=1.0.0)", "virtualenv (>=13.0.0)", "wheel"] - [[package]] name = "shellingham" version = "1.5.4" @@ -2185,25 +2137,24 @@ files = [ [[package]] name = "towncrier" -version = "22.12.0" +version = "26.9.0" description = "Building newsfiles for your project." optional = false -python-versions = ">=3.7" +python-versions = ">=3.9" files = [ - {file = "towncrier-22.12.0-py3-none-any.whl", hash = "sha256:9767a899a4d6856950f3598acd9e8f08da2663c49fdcda5ea0f9e6ba2afc8eea"}, - {file = "towncrier-22.12.0.tar.gz", hash = "sha256:9c49d7e75f646a9aea02ae904c0bc1639c8fd14a01292d2b123b8d307564034d"}, + {file = "towncrier-26.9.0-py3-none-any.whl", hash = "sha256:ae4d223e6aadaff98d29b7f09e58d9c9ccf4cd3b455a2d2e0486d432cd8bf660"}, + {file = "towncrier-26.9.0.tar.gz", hash = "sha256:ace9031631c718cc0709107b8755e6e31350eb8acdc877af43df3177addb9a55"}, ] [package.dependencies] click = "*" -click-default-group = "*" -incremental = "*" +importlib-metadata = {version = ">=4.6", markers = "python_version < \"3.10\""} +importlib-resources = {version = ">=5", markers = "python_version < \"3.10\""} jinja2 = "*" -setuptools = "*" tomli = {version = "*", markers = "python_version < \"3.11\""} [package.extras] -dev = ["furo", "packaging", "sphinx (>=5)", "twisted"] +dev = ["codespell (>=2.4)", "furo (>=2024.05.06)", "nox", "packaging", "sphinx (>=5)", "twisted"] [[package]] name = "tox" @@ -3276,4 +3227,4 @@ redis = ["redis"] [metadata] lock-version = "2.0" python-versions = "^3.8" -content-hash = "da8b0ef348311d19688177870043d5a177ba724e23efa05b9dd421f09b4ecb25" +content-hash = "b16775b4a6ec60e1965d9934a1220ba7db1f9f0653149c345983b41b6530cad4" diff --git a/pyproject.toml b/pyproject.toml index a2343b65..542381b2 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -63,7 +63,7 @@ requests = "*" coverage = ">=6.5,<8.0" httpx = "*" tox = "^4.5.1" -towncrier = "^22.12.0" +towncrier = { version = ">=26,<27", python = ">=3.9" } [tool.poetry.group.distributing] optional = true From bee9f54b63664a601b65de2b234b0e18e3ec2f29 Mon Sep 17 00:00:00 2001 From: agustin18 Date: Fri, 13 Nov 2026 16:45:47 +0000 Subject: [PATCH 4/4] docs(changelog): link the #575 fragment to PR #2 Rename the fragment from 554 to 2 so Towncrier links to the fork PR instead of a non-existent fork issue. Keep the upstream credit in the fragment text. --- changelog.d/2.bugfix.md | 1 + changelog.d/554.bugfix.md | 1 - 2 files changed, 1 insertion(+), 1 deletion(-) create mode 100644 changelog.d/2.bugfix.md delete mode 100644 changelog.d/554.bugfix.md diff --git a/changelog.d/2.bugfix.md b/changelog.d/2.bugfix.md new file mode 100644 index 00000000..170dda50 --- /dev/null +++ b/changelog.d/2.bugfix.md @@ -0,0 +1 @@ +Avoid caching explicitly returned `Response` objects with status codes >= 400. Adapted from upstream PR #575 by RitiGrover. diff --git a/changelog.d/554.bugfix.md b/changelog.d/554.bugfix.md deleted file mode 100644 index 7d50d1e3..00000000 --- a/changelog.d/554.bugfix.md +++ /dev/null @@ -1 +0,0 @@ -Do not cache `Response` objects with status codes >= 400, so a cached error response cannot be returned as HTTP 200.