Skip to content

Connexion 3 AsyncApp: request log is lost when a background task fails after response #167

Open

Description

@suppagoddo

Summary

In the new Connexion 3 AsyncApp instrumentation, the HTTP response can be successfully sent to the client, yet the library emits no request log if a post-response background task raises. This creates an observability gap: an HTTP 200 can be delivered without the matching structured request record.

Discovered during the independent 1.7.0 release-qualification review by @suppagoddo. The behavior was reproduced in-process with Connexion 3.3.0, Python 3.9.6 and 3.13.5, using an ASGI test transport. The limitation is documented in the 1.7.0 changelog via #166.

Impact: missing access/request records for otherwise completed HTTP responses when background processing fails. Proposed priority: P2 correctness/observability.

Root cause

In json_logging/framework/connexion/asgi.py, the JSONLoggingConnexionASGIMiddleware.__call__ method awaits:

await self.app(scope, receive, send_wrapper)
if response is not None:
    request_response_data.on_request_complete(response)
    self.request_logger.info("", extra={'request_response_data': request_response_data})

If the inner ASGI app sends http.response.start and the final http.response.body, then a background task raises, await self.app(...) exits with an exception and the logging block is skipped.

Minimal middleware-level reproduction

The following isolates the same middleware path using a small ASGI app. It does not replace the full Connexion 3.3.0 test from the release audit.

import asyncio
import logging

from json_logging.dto import DefaultRequestResponseDTO
from json_logging.framework.connexion.asgi import JSONLoggingConnexionASGIMiddleware

records = []

class Capture(logging.Handler):
    def emit(self, record):
        records.append(record)

logger = logging.getLogger("connexion-request-logger")
logger.setLevel(logging.INFO)
logger.addHandler(Capture())

async def app_that_fails_after_response(scope, receive, send):
    await send({"type": "http.response.start", "status": 200, "headers": []})
    await send({"type": "http.response.body", "body": b"OK", "more_body": False})
    raise RuntimeError("background task failed")

middleware = JSONLoggingConnexionASGIMiddleware(
    app_that_fails_after_response,
    request_response_dto_class=DefaultRequestResponseDTO,
)
scope = {
    "type": "http",
    "asgi": {"version": "3.0"},
    "http_version": "1.1",
    "method": "GET",
    "scheme": "http",
    "path": "/background",
    "raw_path": b"/background",
    "query_string": b"",
    "headers": [],
    "server": ("example.org", 80),
    "client": ("127.0.0.1", 1234),
}
sent = []
async def receive():
    return {"type": "http.request", "body": b"", "more_body": False}
async def send(message):
    sent.append(message)

async def main():
    try:
        await middleware(scope, receive, send)
    except RuntimeError as exc:
        assert str(exc) == "background task failed"
    assert [m["type"] for m in sent] == [
        "http.response.start", "http.response.body"
    ]
    assert sent[0]["status"] == 200
    # Current behavior: no request record even though HTTP 200 was sent.
    assert len(records) == 0, records

asyncio.run(main())

Run from a clean environment with this repository installed and the Connexion 3/Starlette dependencies available. This exact standalone snippet has not been re-executed as part of filing this issue; the prior in-process release-audit reproduction is the observed evidence.

Expected behavior

Once a complete HTTP response has been sent, exactly one request log should be emitted with its actual status code and correlation ID, even if a subsequent background task fails. The background-task exception must still propagate according to the ASGI application's existing exception handling; logging should not swallow it.

Actual behavior

The background task raises; no request log is emitted. The previous release audit reproduced this for a 200 response in the Connexion 3.3.0 AsyncApp stack, on Python 3.9 and 3.13.

Proposed fix / design discussion

Consider observing the final successfully sent http.response.body message (more_body false) in send_wrapper, rather than waiting for the entire ASGI application call, with a carefully defined fallback for failures before response completion.

The change should preserve the actual HTTP status, correlation-ID isolation, exception propagation, exclusions, and exactly-once logging; do not naively add unconditional logging to finally.

Acceptance criteria

  • A background task raises after the final HTTP response: one request log is emitted, with the sent status (e.g. 200); the task exception still propagates.
  • A normal successful response emits exactly one request log (no duplication).
  • A multi-chunk streaming response emits exactly one record after the final body, not per chunk.
  • A route excluded via exclude_url_patterns emits zero request records.
  • An exception before response start or an error response from an exception handler has correct behavior and status; no fabricated HTTP 200.
  • Concurrent requests preserve independent correlation IDs.
  • Include regression tests in the project suite and (if practical) one live Uvicorn integration check.
  • No unintended JSON schema changes or compatibility regression for the existing Connexion FlaskApp path.

Related finding (scope to decide)

The same late completion point also inflates response_time_ms with background-task duration (audit finding R-02, approximately 500–516 ms for a 0.5 s background task). This is documented in #166. If the middleware change naturally resolves both issues without broadening risk, test that explicitly; otherwise track response timing as a separate issue.

References

Owner requested: @suppagoddo. Please triage and mark ready when the project agrees on the fix and test scope, per CONTRIBUTING.md / MAINTENANCE.md. A follow-up code PR will be separate from 1.7.0 publication.

Activity

  1. self-assigned this
    on Nov 23, 2026
  2. added
    needs triage
    on Nov 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

needs triage

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions