feat(api): define public problem errors, pagination, and retry contract

This commit is contained in:
shira committed 2026-10-05 22:09:36 +03:00
1 parent b2f6e87bfe
commit 565ca94bbb
86 files changed
+8200 -154

No files matched your search

+11 -5
View File
@@ -1,7 +1,7 @@
.DEFAULT_GOAL := help
UV ?= uv
API_PREPARED ?= 0
.PHONY: help install generate check-generated build run fmt fmt-check lint lint-fix typecheck test test-contract check verify
.PHONY: help install generate check-generated check-pydantic-compat build run fmt fmt-check lint lint-fix typecheck test test-contract check verify
help: ## Show available ML service commands.
@awk 'BEGIN {FS = ":.*## "} /^[a-zA-Z0-9_-]+:.*## / {printf "%-14s %s\n", $$1, $$2}' $(MAKEFILE_LIST)
@@ -16,6 +16,12 @@ generate: ## Generate Pydantic models from the shared ML contract.
check-generated: ## Check Pydantic models against the bundled contract without rewriting them.
cd codegen && $(UV) run --project .. datamodel-codegen --check
check-pydantic-compat: ## Generate Pydantic models from the OpenAPI 3.2 compatibility fixture into a temporary directory and check them.
@temporary_dir=$$(mktemp -d) && trap 'rm -rf "$$temporary_dir"' EXIT && \
(cd codegen && $(UV) run --project .. datamodel-codegen --input ../../api/testdata/openapi-3.2.0.yml --output "$$temporary_dir/fixture_models.py" --openapi-scopes schemas parameters paths) && \
$(UV) run mypy --strict "$$temporary_dir/fixture_models.py" && \
$(UV) run python scripts/check_fixture_models.py "$$temporary_dir/fixture_models.py"
build: ## Build the service wheel.
$(UV) build
@@ -23,16 +29,16 @@ run: ## Run the operational API on port 8000.
$(UV) run uvicorn lincodex_ml.main:app --host 0.0.0.0 --port 8000
fmt: ## Format Python source.
$(UV) run ruff format src tests
$(UV) run ruff format src tests scripts
fmt-check: ## Check Python formatting.
$(UV) run ruff format --check src tests
$(UV) run ruff format --check src tests scripts
lint: ## Run Ruff checks.
$(UV) run ruff check src tests
$(UV) run ruff check src tests scripts
lint-fix: ## Apply safe Ruff fixes.
$(UV) run ruff check --fix src tests
$(UV) run ruff check --fix src tests scripts
typecheck: ## Run strict mypy checks.
$(UV) run mypy src
+1
View File
@@ -7,6 +7,7 @@ A separate Python service using FastAPI for future resume analysis and candidate
- `src/lincodex_ml/` contains the application, HTTP routes, and infrastructure code.
- `codegen/` configures Pydantic model generation from `api/ml/`.
- `tests/` checks service health and contract conformance.
- `scripts/` checks Pydantic models generated from the OpenAPI 3.2 fixture.
- `pyproject.toml` and `uv.lock` define dependencies and Python tool settings.
From the repository root, `make -C ml check` runs checks and `make -C ml run` starts the service locally. To use its separate Compose project, run `make -C deploy ml-up` after preparing `.env`.
+1
View File
@@ -7,6 +7,7 @@
- `src/lincodex_ml/` - приложение, HTTP-маршруты и инфраструктурный код.
- `codegen/` - настройки генерации моделей Pydantic из `api/ml/`.
- `tests/` - проверки состояния сервиса и соответствия контракту.
- `scripts/` - проверка Pydantic-моделей, сгенерированных из фикстуры OpenAPI 3.2.
- `pyproject.toml` и `uv.lock` - зависимости и настройки Python-инструментов.
Из корня: `make -C ml check` запускает проверки, `make -C ml run` - сервис локально. Для запуска через отдельный Compose используйте `make -C deploy ml-up` после подготовки `.env`.
+2
View File
@@ -8,3 +8,5 @@ openapi-scopes = ["schemas"]
enum-field-as-literal = "all"
disable-timestamp = true
formatters = ["ruff-check", "ruff-format"]
field-constraints = true
use-annotated = true
+86
View File
@@ -0,0 +1,86 @@
"""Validate Pydantic models generated from the OpenAPI 3.2 compatibility fixture.
make check-pydantic-compat generates the models into a temporary file and
passes its path. The checks cover the api/core conventions that
datamodel-code-generator turns into models: Problem, PageInfo, Timestamp, and
the PageLimit and PageCursor query parameters. It does not generate header
parameters or response headers, so Idempotency-Key, If-Match, and ETag have no
model to check.
"""
import importlib.util
import sys
from pathlib import Path
from types import ModuleType
from pydantic import BaseModel, ValidationError
def load(path: Path) -> ModuleType:
spec = importlib.util.spec_from_file_location("fixture_models", path)
if spec is None or spec.loader is None:
raise SystemExit(f"cannot load generated models from {path}")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def rejects(model: type[BaseModel], payload: object) -> bool:
try:
model.model_validate(payload)
except ValidationError:
return True
return False
def main(path: Path) -> None:
models = load(path)
problem = models.Problem.model_validate(
{
"type": "urn:lincodex:problem:state_conflict",
"title": "Resource state conflict",
"status": 409,
"code": "state_conflict",
"errors": [{"in": "body", "pointer": "/name", "code": "invalid", "message": "m"}],
}
)
assert problem.code.root == "state_conflict"
assert rejects(models.Problem, {"type": "t", "title": "t", "status": 409, "code": "unknown"})
assert rejects(models.Problem, {"type": "t", "title": "t", "status": 200, "code": "internal"})
page = models.PageInfo.model_validate({"has_more": False, "next_cursor": None})
assert page.next_cursor is None
assert rejects(models.PageInfo, {"has_more": False})
assert rejects(models.PageInfo, {"has_more": True, "next_cursor": "a" * 513})
stamp = models.Timestamp.model_validate("2026-10-05T09:30:00Z")
assert models.Timestamp(stamp.root).model_dump_json() == '"2026-10-05T09:30:00Z"'
assert rejects(models.Timestamp, "2026-10-05T09:30:00")
query = models.ProbeItemsGetParametersQuery.model_validate({})
assert query.limit == 20
assert rejects(models.ProbeItemsGetParametersQuery, {"limit": 0})
assert rejects(models.ProbeItemsGetParametersQuery, {"limit": 101})
assert rejects(models.ProbeItemsGetParametersQuery, {"cursor": "a b"})
item_page = models.ProbeItemPage.model_validate(
{
"items": [
{
"id": "5f0c6a8e-3b0e-4c47-9f4c-2a8f9e5d7c11",
"name": "probe",
"updated_at": "2026-10-05T09:30:00Z",
}
],
"page": {"has_more": False, "next_cursor": None},
}
)
assert len(item_page.items) == 1
print("Pydantic compatibility fixture: generated models validated.")
if __name__ == "__main__":
if len(sys.argv) != 2:
raise SystemExit("usage: check_fixture_models.py <generated models file>")
main(Path(sys.argv[1]))
+141 -2
View File
@@ -1,9 +1,148 @@
# generated by datamodel-codegen:
# filename: openapi.bundle.yml
from typing import Literal
from typing import Annotated, Literal
from pydantic import BaseModel, ConfigDict
from pydantic import BaseModel, ConfigDict, Field, RootModel
class ProblemCode(
RootModel[
Literal[
"validation_failed",
"unauthenticated",
"forbidden",
"not_found",
"method_not_allowed",
"idempotency_in_progress",
"state_conflict",
"version_conflict",
"payload_too_large",
"unsupported_media_type",
"idempotency_key_reused",
"precondition_required",
"rate_limited",
"internal",
"not_implemented",
]
]
):
root: Annotated[
Literal[
"validation_failed",
"unauthenticated",
"forbidden",
"not_found",
"method_not_allowed",
"idempotency_in_progress",
"state_conflict",
"version_conflict",
"payload_too_large",
"unsupported_media_type",
"idempotency_key_reused",
"precondition_required",
"rate_limited",
"internal",
"not_implemented",
],
Field(
description="Stable public error code. Adding a code is a contract change; renaming or removing one is a breaking change. Clients must handle an unknown code by its HTTP status.\n\n- validation_failed (400): parameters or body do not match the contract, or a body violates a domain rule such as salary_from <= salary_to; `errors` points at the fields.\n- unauthenticated (401): no valid session or credentials.\n- forbidden (403): the caller is authenticated but not allowed.\n- not_found (404): the route or object does not exist or is not visible.\n- method_not_allowed (405): the route does not support the method.\n- idempotency_in_progress (409): a request with the same Idempotency-Key is still being processed.\n- state_conflict (409): the operation conflicts with the current state of the resource, for example an invitation that was already accepted.\n- version_conflict (412): If-Match does not match the current version.\n- payload_too_large (413): the request body exceeds the limit.\n- unsupported_media_type (415): the request Content-Type is not accepted.\n- idempotency_key_reused (422): the Idempotency-Key was already used with a different request.\n- precondition_required (428): the operation requires If-Match.\n- rate_limited (429): too many requests; see Retry-After.\n- internal (500): unexpected server error.\n- not_implemented (501): the operation is in the contract but not implemented yet."
),
]
class ProblemFieldLocation(RootModel[Literal["body", "query", "path", "header", "cookie"]]):
root: Annotated[
Literal["body", "query", "path", "header", "cookie"],
Field(description="Part of the request that contains the invalid field."),
]
class ProblemFieldError(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
in_: Annotated[ProblemFieldLocation, Field(alias="in")]
pointer: Annotated[
str,
Field(
description="JSON Pointer (RFC 6901). For `body` it points into the request body document, for example `/salary_from`; an empty string means the whole body. For a parameter it is `/` followed by the parameter name, for example `/limit` or `/Idempotency-Key`.",
max_length=1024,
pattern="^(/([^~/]|~[01])*)*$",
),
]
code: Annotated[
str,
Field(
description="Stable field reason. Current values are `required` (missing value) and `invalid` (malformed value or a value outside the schema). Clients must tolerate new values.",
max_length=64,
min_length=1,
pattern="^[a-z][a-z0-9_]*$",
),
]
message: Annotated[
str,
Field(
description="Fixed English message that never echoes the submitted value.",
max_length=500,
min_length=1,
),
]
class Problem(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
type: Annotated[
str,
Field(
description="URI that identifies the problem type. It has the form `urn:lincodex:problem:<code>` and is an identifier, not a link to dereference.",
max_length=256,
),
]
title: Annotated[
str,
Field(
description="Short, fixed English summary of the problem type. It does not change between occurrences.",
max_length=200,
min_length=1,
),
]
status: Annotated[
int, Field(description="HTTP status code generated by the origin server.", ge=400, le=599)
]
code: ProblemCode
detail: Annotated[
str | None,
Field(
description="Safe English explanation of this occurrence. It never contains internal error text or request values.",
max_length=1000,
),
] = None
instance: Annotated[
str | None,
Field(
description="URI reference that identifies this occurrence, when one exists.",
max_length=2048,
),
] = None
trace_id: Annotated[
str | None,
Field(
description="Request identifier of the call when the caller propagated one; it is not a secret.",
max_length=128,
min_length=1,
pattern="^[A-Za-z0-9._-]+$",
),
] = None
errors: Annotated[
list[ProblemFieldError] | None,
Field(
description="Field-level reasons for validation_failed. Other codes omit it.",
max_length=100,
),
] = None
class MLHealthResponse(BaseModel):
+281
View File
@@ -0,0 +1,281 @@
"""RFC 9457 problem responses that match the shared ML contract."""
import logging
import re
from collections.abc import Mapping, Sequence
from dataclasses import dataclass
from typing import Any, Final
from fastapi import FastAPI, Request, status
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from starlette.exceptions import HTTPException as StarletteHTTPException
from starlette.types import ASGIApp, Message, Receive, Scope, Send
from lincodex_ml.api.models import Problem, ProblemCode, ProblemFieldError, ProblemFieldLocation
PROBLEM_MEDIA_TYPE: Final = "application/problem+json"
_TYPE_PREFIX: Final = "urn:lincodex:problem:"
_REQUEST_ID_HEADER: Final = "X-Request-ID"
_REQUEST_ID_PATTERN: Final = re.compile(r"[A-Za-z0-9._-]{1,128}")
# Matches the maxItems bound of Problem.errors.
_MAX_FIELD_ERRORS: Final = 100
_FIELD_CODE_REQUIRED: Final = "required"
_FIELD_CODE_INVALID: Final = "invalid"
_FIELD_MESSAGES: Final = {
_FIELD_CODE_REQUIRED: "The value is required.",
_FIELD_CODE_INVALID: "The value does not match the contract.",
}
_FIELD_LOCATIONS: Final = frozenset({"body", "query", "path", "header", "cookie"})
logger = logging.getLogger(__name__)
@dataclass(frozen=True, slots=True)
class _Definition:
code: ProblemCode
status: int
title: str
detail: str
_VALIDATION_FAILED: Final = _Definition(
ProblemCode("validation_failed"),
status.HTTP_400_BAD_REQUEST,
"Request validation failed",
"One or more request fields are invalid.",
)
_INTERNAL: Final = _Definition(
ProblemCode("internal"),
status.HTTP_500_INTERNAL_SERVER_ERROR,
"Internal server error",
"The server could not complete the request.",
)
# Problem for each HTTP status that has a contract code. FastAPI reports body
# validation as 422, which the contract answers as 400 validation_failed; 422
# idempotency_key_reused belongs to the public API and has no ML use.
_STATUS_DEFINITIONS: Final[Mapping[int, _Definition]] = {
status.HTTP_400_BAD_REQUEST: _VALIDATION_FAILED,
status.HTTP_401_UNAUTHORIZED: _Definition(
ProblemCode("unauthenticated"),
status.HTTP_401_UNAUTHORIZED,
"Authentication required",
"Sign in and repeat the request.",
),
status.HTTP_403_FORBIDDEN: _Definition(
ProblemCode("forbidden"),
status.HTTP_403_FORBIDDEN,
"Access denied",
"You do not have permission to perform this operation.",
),
status.HTTP_404_NOT_FOUND: _Definition(
ProblemCode("not_found"),
status.HTTP_404_NOT_FOUND,
"Resource not found",
"The requested resource does not exist.",
),
status.HTTP_405_METHOD_NOT_ALLOWED: _Definition(
ProblemCode("method_not_allowed"),
status.HTTP_405_METHOD_NOT_ALLOWED,
"Method not allowed",
"The resource does not support this method; see the Allow header.",
),
status.HTTP_409_CONFLICT: _Definition(
ProblemCode("state_conflict"),
status.HTTP_409_CONFLICT,
"Resource state conflict",
"The resource is in a state that does not allow this operation.",
),
status.HTTP_412_PRECONDITION_FAILED: _Definition(
ProblemCode("version_conflict"),
status.HTTP_412_PRECONDITION_FAILED,
"Resource version conflict",
"The resource changed after it was read. Read it again before retrying.",
),
status.HTTP_413_CONTENT_TOO_LARGE: _Definition(
ProblemCode("payload_too_large"),
status.HTTP_413_CONTENT_TOO_LARGE,
"Request body too large",
"Reduce the request body size and retry.",
),
status.HTTP_415_UNSUPPORTED_MEDIA_TYPE: _Definition(
ProblemCode("unsupported_media_type"),
status.HTTP_415_UNSUPPORTED_MEDIA_TYPE,
"Unsupported media type",
"Send the request body with a media type that the operation accepts.",
),
status.HTTP_422_UNPROCESSABLE_CONTENT: _VALIDATION_FAILED,
status.HTTP_428_PRECONDITION_REQUIRED: _Definition(
ProblemCode("precondition_required"),
status.HTTP_428_PRECONDITION_REQUIRED,
"Precondition required",
"Send If-Match with the ETag of the version you read.",
),
status.HTTP_429_TOO_MANY_REQUESTS: _Definition(
ProblemCode("rate_limited"),
status.HTTP_429_TOO_MANY_REQUESTS,
"Too many requests",
"Wait for the Retry-After interval and retry.",
),
status.HTTP_501_NOT_IMPLEMENTED: _Definition(
ProblemCode("not_implemented"),
status.HTTP_501_NOT_IMPLEMENTED,
"Operation not implemented",
"This operation is not available yet.",
),
}
# Response headers of an HTTP exception that a problem response keeps.
_FORWARDED_HEADERS: Final = ("Allow", "Retry-After")
def install_problem_handlers(application: FastAPI) -> None:
"""Answer every framework and unhandled error with a problem response."""
application.add_exception_handler(RequestValidationError, _handle_validation_error)
application.add_exception_handler(StarletteHTTPException, _handle_http_exception)
application.add_middleware(UnhandledErrorMiddleware)
def _definition_for_status(status_code: int) -> _Definition:
"""Return the problem for an HTTP status raised inside the service.
A status without a contract code is still a client error when it is 4xx and
becomes 400 validation_failed; every other unmapped status is internal.
"""
definition = _STATUS_DEFINITIONS.get(status_code)
if definition is not None:
return definition
if status.HTTP_400_BAD_REQUEST <= status_code < status.HTTP_500_INTERNAL_SERVER_ERROR:
return _VALIDATION_FAILED
return _INTERNAL
class UnhandledErrorMiddleware:
"""Answer an unhandled exception with the internal problem.
Starlette's ServerErrorMiddleware re-raises after its handler, and uvicorn
then logs the exception with its text. Catching the exception here, inside
that middleware, ends it at this boundary: only its type is logged, and the
exception text reaches neither the client nor any log record. When the
response has already started it cannot be replaced, so the exception is
logged and the incomplete response is left for the server to close.
"""
def __init__(self, app: ASGIApp) -> None:
self._app = app
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] != "http":
await self._app(scope, receive, send)
return
response_started = False
async def tracked_send(message: Message) -> None:
nonlocal response_started
if message["type"] == "http.response.start":
response_started = True
await send(message)
try:
await self._app(scope, receive, tracked_send)
except Exception as exc:
request = Request(scope)
# Exception text may contain document content or model output, so
# only the type is logged.
logger.error(
"Unhandled %s in %s %s",
type(exc).__name__,
request.method,
request.url.path,
)
if response_started:
return
response = _problem_response(request, _INTERNAL)
await response(scope, receive, send)
async def _handle_validation_error(request: Request, exc: Exception) -> JSONResponse:
errors = exc.errors() if isinstance(exc, RequestValidationError) else []
return _problem_response(request, _VALIDATION_FAILED, _field_errors(errors))
async def _handle_http_exception(request: Request, exc: Exception) -> JSONResponse:
status_code = (
exc.status_code
if isinstance(exc, StarletteHTTPException)
else status.HTTP_500_INTERNAL_SERVER_ERROR
)
definition = _definition_for_status(status_code)
if definition is _INTERNAL:
logger.error("HTTP status %d in %s %s", status_code, request.method, request.url.path)
raised_headers = exc.headers if isinstance(exc, StarletteHTTPException) else None
headers = {
name: raised_headers[name]
for name in _FORWARDED_HEADERS
if raised_headers and name in raised_headers
}
return _problem_response(request, definition, headers=headers or None)
def _problem_response(
request: Request,
definition: _Definition,
errors: list[ProblemFieldError] | None = None,
headers: Mapping[str, str] | None = None,
) -> JSONResponse:
problem = Problem(
type=f"{_TYPE_PREFIX}{definition.code.root}",
title=definition.title,
status=definition.status,
code=definition.code,
detail=definition.detail,
trace_id=_request_id(request),
errors=errors,
)
return JSONResponse(
content=problem.model_dump(mode="json", by_alias=True, exclude_none=True),
status_code=definition.status,
headers=headers,
media_type=PROBLEM_MEDIA_TYPE,
)
def _request_id(request: Request) -> str | None:
value = request.headers.get(_REQUEST_ID_HEADER)
if value is not None and _REQUEST_ID_PATTERN.fullmatch(value):
return value
return None
def _field_errors(errors: Sequence[Any]) -> list[ProblemFieldError]:
fields: list[ProblemFieldError] = []
for error in errors[:_MAX_FIELD_ERRORS]:
if not isinstance(error, Mapping):
continue
location = tuple(error.get("loc", ()))
names_part = bool(location) and location[0] in _FIELD_LOCATIONS
part = str(location[0]) if names_part else "body"
path = location[1:] if names_part else location
if error.get("type") == "json_invalid":
# The location of a JSON syntax error is a character offset, not a
# field, so the error points at the whole body.
path = ()
code = _FIELD_CODE_REQUIRED if error.get("type") == "missing" else _FIELD_CODE_INVALID
fields.append(
ProblemFieldError.model_validate(
{
"in": ProblemFieldLocation.model_validate(part),
"pointer": "".join(f"/{_escape_pointer_token(str(token))}" for token in path),
"code": code,
"message": _FIELD_MESSAGES[code],
}
)
)
return fields
def _escape_pointer_token(token: str) -> str:
"""Escape a JSON Pointer reference token as RFC 6901 requires."""
return token.replace("~", "~0").replace("/", "~1")
+25 -11
View File
@@ -1,22 +1,32 @@
import json
import logging
from datetime import UTC, datetime
from typing import override
from typing import Final, override
# uvicorn configures these loggers with its own text handlers before it imports
# the application. They are routed through the service handler instead, so
# that no uvicorn record prints exception text or a traceback.
UVICORN_LOGGERS: Final = ("uvicorn", "uvicorn.error", "uvicorn.access")
class JsonFormatter(logging.Formatter):
"""Format records as JSON lines without exception text or tracebacks.
Exception messages may contain resume text, contact data, or model output,
so a record with exception information keeps only the exception type.
"""
@override
def format(self, record: logging.LogRecord) -> str:
return json.dumps(
{
"timestamp": datetime.now(UTC).isoformat(),
"level": record.levelname.lower(),
"logger": record.name,
"message": record.getMessage(),
},
ensure_ascii=False,
separators=(",", ":"),
)
entry: dict[str, str] = {
"timestamp": datetime.now(UTC).isoformat(),
"level": record.levelname.lower(),
"logger": record.name,
"message": record.getMessage(),
}
if record.exc_info and record.exc_info[0] is not None:
entry["exception_type"] = record.exc_info[0].__name__
return json.dumps(entry, ensure_ascii=False, separators=(",", ":"))
def configure_logging() -> None:
@@ -26,3 +36,7 @@ def configure_logging() -> None:
root_logger.handlers.clear()
root_logger.addHandler(handler)
root_logger.setLevel(logging.INFO)
for name in UVICORN_LOGGERS:
uvicorn_logger = logging.getLogger(name)
uvicorn_logger.handlers.clear()
uvicorn_logger.propagate = True
+2
View File
@@ -2,6 +2,7 @@ from fastapi import FastAPI
from prometheus_client import REGISTRY, make_asgi_app
from lincodex_ml.api.health import router as health_router
from lincodex_ml.api.problems import install_problem_handlers
from lincodex_ml.infra.logging import configure_logging
@@ -9,6 +10,7 @@ def create_app() -> FastAPI:
configure_logging()
application = FastAPI(title="Lincodex ML Operational API", version="0.1.0")
application.openapi_version = "3.1.2"
install_problem_handlers(application)
application.include_router(health_router)
application.mount("/metrics", make_asgi_app(registry=REGISTRY))
return application
+34 -1
View File
@@ -6,7 +6,7 @@ import pytest
import yaml
from pydantic import BaseModel, ValidationError
from lincodex_ml.api.models import MLHealthResponse, MLReadinessResponse
from lincodex_ml.api.models import MLHealthResponse, MLReadinessResponse, Problem
from lincodex_ml.main import app
CONTRACT_PATH = Path(__file__).resolve().parents[2] / "api" / "ml" / "openapi.bundle.yml"
@@ -20,6 +20,14 @@ def _resolve_schema(document: dict[str, Any], schema: dict[str, Any]) -> dict[st
return document["components"]["schemas"][component_name]
def _resolve_response(document: dict[str, Any], response: dict[str, Any]) -> dict[str, Any]:
reference = response.get("$ref")
if reference is None:
return response
component_name = reference.rsplit("/", maxsplit=1)[-1]
return document["components"]["responses"][component_name]
def _status_values(document: dict[str, Any], response: dict[str, Any]) -> list[str]:
content = response["content"]["application/json"]["schema"]
response_schema = _resolve_schema(document, content)
@@ -47,6 +55,10 @@ def test_health_and_readiness_match_shared_openapi_contract() -> None:
assert actual_operation["operationId"] == expected_operation["operationId"]
for response_code, expected_response in expected_operation["responses"].items():
# The default problem response is checked at runtime below; FastAPI
# cannot describe it with the problem media type.
if response_code == "default":
continue
actual_response = actual_operation["responses"][response_code]
assert _status_values(contract, expected_response) == _status_values(
implementation, actual_response
@@ -68,6 +80,27 @@ async def test_unready_probe_returns_the_contractual_503_response() -> None:
assert response.json()["status"] in _status_values(contract, readiness["503"])
@pytest.mark.anyio
@pytest.mark.parametrize(("method", "path"), [("POST", "/healthz"), ("GET", "/missing")])
async def test_error_responses_match_the_contractual_default_response(
method: str, path: str
) -> None:
contract = yaml.safe_load(CONTRACT_PATH.read_text(encoding="utf-8"))
default = _resolve_response(
contract, contract["paths"]["/healthz"]["get"]["responses"]["default"]
)
(media_type,) = default["content"]
async with httpx.AsyncClient(
transport=httpx.ASGITransport(app=app), base_url="http://test"
) as client:
response = await client.request(method, path)
assert response.headers["content-type"] == media_type
problem = Problem.model_validate(response.json())
assert problem.status == response.status_code
@pytest.mark.parametrize(
("model", "valid_status"),
[(MLHealthResponse, "ok"), (MLReadinessResponse, "ready"), (MLReadinessResponse, "not_ready")],
+215
View File
@@ -0,0 +1,215 @@
import logging
import logging.config
from typing import Annotated
import httpx
import pytest
from fastapi import FastAPI, HTTPException, Query
from pydantic import BaseModel
from uvicorn.config import LOGGING_CONFIG
from lincodex_ml.api.models import Problem
from lincodex_ml.api.problems import PROBLEM_MEDIA_TYPE
from lincodex_ml.infra.logging import UVICORN_LOGGERS, JsonFormatter, configure_logging
from lincodex_ml.main import create_app
SENSITIVE_TEXT = "resume of Jane Doe, phone +7 900 000-00-00"
class ProbeInput(BaseModel):
name: str
@pytest.fixture
def anyio_backend() -> str:
return "asyncio"
@pytest.fixture
def probe_app() -> FastAPI:
"""The service app plus test-only routes that the ML contract does not have."""
application = create_app()
@application.get("/probe")
async def probe(limit: Annotated[int, Query(ge=1, le=100)]) -> dict[str, int]:
return {"limit": limit}
@application.post("/probe")
async def create_probe(payload: ProbeInput) -> dict[str, str]:
return {"name": payload.name}
@application.get("/failure")
async def failure() -> None:
raise RuntimeError(SENSITIVE_TEXT)
@application.get("/status/{code}")
async def raise_status(code: int) -> None:
headers = {"Retry-After": "30"} if code == 429 else None
raise HTTPException(status_code=code, detail=SENSITIVE_TEXT, headers=headers)
return application
async def _request(
application: FastAPI,
method: str,
path: str,
json: object = None,
content: str | None = None,
headers: dict[str, str] | None = None,
) -> httpx.Response:
# Unhandled errors must reach the problem handler instead of the test client.
async with httpx.AsyncClient(
transport=httpx.ASGITransport(app=application, raise_app_exceptions=False),
base_url="http://test",
) as client:
return await client.request(method, path, json=json, content=content, headers=headers)
def _problem(response: httpx.Response, status: int, code: str) -> Problem:
assert response.status_code == status
assert response.headers["content-type"] == PROBLEM_MEDIA_TYPE
problem = Problem.model_validate(response.json())
assert problem.status == status
assert problem.code.root == code
assert problem.type == f"urn:lincodex:problem:{code}"
return problem
@pytest.mark.anyio
async def test_unhandled_exception_ends_at_the_problem_boundary(probe_app: FastAPI) -> None:
# The default transport re-raises anything that escapes the application,
# so a problem response here proves that nothing reaches Starlette's
# ServerErrorMiddleware, which would re-raise to uvicorn.
async with httpx.AsyncClient(
transport=httpx.ASGITransport(app=probe_app), base_url="http://test"
) as client:
response = await client.get("/failure", headers={"X-Request-ID": "req-1"})
problem = _problem(response, 500, "internal")
assert problem.trace_id == "req-1"
assert "Jane" not in response.text
@pytest.mark.anyio
async def test_unhandled_exception_text_reaches_no_log_record(
probe_app: FastAPI, caplog: pytest.LogCaptureFixture
) -> None:
# create_app replaced the root handlers, so capture at the root again.
logging.getLogger().addHandler(caplog.handler)
caplog.set_level(logging.DEBUG)
try:
response = await _request(probe_app, "GET", "/failure")
finally:
logging.getLogger().removeHandler(caplog.handler)
_problem(response, 500, "internal")
assert any("RuntimeError" in record.getMessage() for record in caplog.records)
formatter = JsonFormatter()
for record in caplog.records:
assert "Jane" not in record.getMessage()
assert "Jane" not in formatter.format(record)
assert record.exc_info is None or "Jane" not in str(record.exc_info[1])
def test_uvicorn_loggers_are_redacted_after_uvicorn_configures_them(
capsys: pytest.CaptureFixture[str],
) -> None:
# uvicorn applies its logging configuration before it imports the
# application; configure_logging then takes its loggers over.
logging.config.dictConfig(LOGGING_CONFIG)
configure_logging()
capsys.readouterr()
try:
raise RuntimeError(SENSITIVE_TEXT)
except RuntimeError:
logging.getLogger("uvicorn.error").exception("Exception in ASGI application")
output = capsys.readouterr().err
assert '"exception_type":"RuntimeError"' in output
assert "Exception in ASGI application" in output
assert "Jane" not in output
assert "Traceback" not in output
for name in UVICORN_LOGGERS:
assert logging.getLogger(name).handlers == []
@pytest.mark.anyio
@pytest.mark.parametrize(
("raised", "status", "code"),
[
(400, 400, "validation_failed"),
(401, 401, "unauthenticated"),
(403, 403, "forbidden"),
(409, 409, "state_conflict"),
(413, 413, "payload_too_large"),
(415, 415, "unsupported_media_type"),
(422, 400, "validation_failed"),
(428, 428, "precondition_required"),
(429, 429, "rate_limited"),
(501, 501, "not_implemented"),
(418, 400, "validation_failed"),
(503, 500, "internal"),
],
)
async def test_http_exceptions_map_to_contract_problems(
probe_app: FastAPI, raised: int, status: int, code: str
) -> None:
response = await _request(probe_app, "GET", f"/status/{raised}")
_problem(response, status, code)
assert "Jane" not in response.text
if raised == 429:
assert response.headers["retry-after"] == "30"
@pytest.mark.anyio
@pytest.mark.parametrize(
("method", "path", "body", "expected"),
[
("GET", "/probe?limit=0", None, [{"in": "query", "pointer": "/limit", "code": "invalid"}]),
("GET", "/probe", None, [{"in": "query", "pointer": "/limit", "code": "required"}]),
("POST", "/probe", {}, [{"in": "body", "pointer": "/name", "code": "required"}]),
("POST", "/probe", {"name": 1}, [{"in": "body", "pointer": "/name", "code": "invalid"}]),
("POST", "/probe", '{"name":', [{"in": "body", "pointer": "", "code": "invalid"}]),
],
)
async def test_request_validation_returns_validation_problem(
probe_app: FastAPI,
method: str,
path: str,
body: object,
expected: list[dict[str, str]],
) -> None:
if isinstance(body, str):
response = await _request(
probe_app, method, path, content=body, headers={"Content-Type": "application/json"}
)
else:
response = await _request(probe_app, method, path, json=body)
problem = _problem(response, 400, "validation_failed")
fields = [
{"in": field.in_.root, "pointer": field.pointer, "code": field.code}
for field in problem.errors or []
]
assert fields == expected
assert all(field.message for field in problem.errors or [])
@pytest.mark.anyio
async def test_unknown_route_and_method_return_problems(probe_app: FastAPI) -> None:
missing = await _request(probe_app, "GET", "/missing")
_problem(missing, 404, "not_found")
not_allowed = await _request(probe_app, "DELETE", "/healthz")
_problem(not_allowed, 405, "method_not_allowed")
assert not_allowed.headers["allow"] == "GET"
@pytest.mark.anyio
async def test_invalid_request_id_is_not_echoed(probe_app: FastAPI) -> None:
response = await _request(probe_app, "GET", "/missing", headers={"X-Request-ID": "bad id"})
assert _problem(response, 404, "not_found").trace_id is None