Skip to content

fix: resolve lifecycle policy from the actual matched route #47

Closed

Description

@mojtaba-arvin

Audit finding

The current LifecycleMiddleware.__call__() extracts the version before calling get_response. Django resolves the URL and sets request.resolver_match inside its inner request handler, after request middleware has started; DRF determines its Request.version later during APIView dispatch. Normal middleware execution therefore cannot rely on either value and falls back to parsing the raw path.

The current nested-prefix regex uses re.search(), which can select an earlier matching API_BASE_PATH segment in a parent mount instead of the version belonging to the resolved child route. That can apply the wrong lifecycle headers or return 410 for a route served by another version.

Acceptance criteria

  1. Resolve lifecycle policy from the actual matched URL route/version, not the first matching substring in request.path.
  2. Preserve support for Django function/class views, @endpoint, VersionedRouter, nested includes/namespaces, custom API_BASE_PATH, and explicit URLconf overrides.
  3. Retired/sunset requests must still be rejected before the view executes; deprecation/Sunset headers must be applied to the appropriate responses.
  4. Do not assume DRF authentication has run when determining the version.
  5. Add full Django-client integration tests using the real middleware chain, including a parent prefix that itself contains an API-like version segment and a child router serving a different version.
  6. Cover sync and async middleware behavior and preserve the existing public lifecycle contract.

Research gate

Before implementation, document Django middleware/resolution order, DRF versioning timing, and the chosen route-metadata mechanism. Avoid replacing one regex with another untested path heuristic.

Activity

  1. mojtaba-arvin commented on Nov 18, 2026

    @mojtaba-arvin
    OwnerAuthor

    Research findings and proposed implementation boundary (2026-11-18)

    The framework timing concern is confirmed against Django's middleware contract and resolver implementation:

    • HttpRequest.resolver_match is populated by URL resolution; it is not available in the ordinary request-middleware phase.
    • Django's process_view(request, view_func, view_args, view_kwargs) hook runs after resolution and before the selected view. Django adapts process-view hooks for sync/async handler modes when required.
    • ResolverMatch exposes the selected callback, full joined route, captured kwargs, and namespace components. This is materially stronger evidence than scanning request.path for the first API_BASE_PATH occurrence.
    • DRF's router adapter already uses the matched namespace (vN) to determine the DRF version. It does so before APIView authentication, so lifecycle policy must not depend on request.user or authentication having run.

    Proposed resolver strategy

    1. Make the middleware's policy decision at process_view, not in the pre-resolution __call__ phase.
    2. Resolve router-backed versions from the actual matched namespace component generated by VersionedRouter.
    3. Resolve decorator-generated routes from registry-owned route metadata matched against the actual ResolverMatch.route (including the parent include prefix); do not use a substring search over the raw request path.
    4. Keep process_response responsible for applying Deprecation and Sunset headers to the view response. Keep 410 short-circuiting in process_view, so the view is never invoked.
    5. Add full Django-client tests for root mounts, nested includes, URLconf overrides, duplicate API-like prefixes, DRF namespace selection, and sync/async request handlers. Unit tests that manually assign request.version remain useful only for parser/helper behavior, not as proof of middleware integration.

    Compatibility question that must be settled by tests

    process_view only runs when Django has selected a view. The current path-based middleware can return 410 for a request whose path looks versioned even if that URL would otherwise be a 404. A route-aware implementation must not silently change that observable behavior. Before implementation, add an explicit test and decide whether the contract is:

    • lifecycle policy applies only to successfully resolved endpoints (unknown/removed paths remain 404), or
    • sunset policy also overrides unresolved paths, in which case the middleware needs a resolver-aware not-found strategy that does not reintroduce ambiguous path scanning.

    I recommend the first contract unless existing public docs/tests explicitly promise version-wide 410 for unknown paths. Endpoint tombstones already define removed routes as 404 and explicitly separate them from version retirement; keeping that distinction avoids turning every arbitrary path under a retired-looking prefix into a 410.

    No implementation is being made until the compatibility behavior is verified against the package's published lifecycle contract and the integration tests are specified.

  2. mojtaba-arvin commented on Nov 18, 2026

    @mojtaba-arvin
    OwnerAuthor

    Correction after checking the canonical lifecycle contract

    I inspected the actual lifecycle section in docs/reference/versioning-contract.md and docs/reference/index.md after writing the compatibility question above. The canonical contract explicitly calls this a version-wide policy, and the current middleware intentionally checks the configured version before invoking the view. Therefore, my earlier recommendation to default to resolved-endpoints-only was too narrow: it could violate the published behavior for an unknown URL under a retired version.

    Implementation must preserve version-wide 410 semantics while eliminating false positives when a nested parent path and a child route both contain API-like version segments. For successfully resolved routes, use the actual ResolverMatch. For unresolved routes, define and test a conservative resolver-aware fallback (or an explicit ambiguity rule); do not silently let all unresolved paths bypass sunset enforcement. Add tests distinguishing resolver-generated 404s from view-generated 404s, and test a nested route where parent and child versions differ.

    This correction supersedes the tentative recommendation in my previous comment. The public contract and its behavior tests take precedence over the proposed default.

  3. mojtaba-arvin commented on Nov 18, 2026

    @mojtaba-arvin
    OwnerAuthor

    Refined implementation design

    Given the published version-wide contract, the least invasive design is a two-stage middleware policy rather than a second full resolve() call:

    Resolved request: add a process_view() hook. Django calls it after resolve_request() has set request.resolver_match and before the callback runs. Determine the version in this order: explicit resolver kwargs, exact registry metadata matched against the full ResolverMatch.route, then a conservative parse of the matched route. Registry matching should use the longest registered route suffix, so a nested parent mount containing /api/v1/ cannot override a child endpoint registered under /api/v2/. Use this metadata for decorator routes and VersionedRouter; do not depend on DRF's Request.version, which is set later during APIView dispatch.

    Unresolved request: process_view() is not called. In the response phase, if Django produced a resolver 404 and there is no resolver_match, retain the version-wide sunset behavior using a conservative raw-path fallback. If exactly one configured API_BASE_PATH version segment matches, apply that version's lifecycle policy (including converting 404 to 410 after sunset). If multiple version segments match and no route was resolved, treat the version as ambiguous and do not guess. This is safer than selecting the first substring and prevents a false 410 for a nested child API whose version differs from its parent. Record this ambiguity behavior in docs/tests.

    Response semantics: a past sunset still short-circuits before a resolved view executes and returns 410 without adding the normal deprecation/sunset headers, matching current behavior. Non-expired deprecated/retired versions get headers on all responses, including view-level 404s. An unresolved path with one unambiguous version keeps the same version-wide headers/410 behavior.

    Async: keep the middleware's sync/async capability explicit. The existing class is sync-only; Django adapts process_view hooks for async handlers, but tests must exercise both WSGI-style sync clients and ASGI async clients. Do not claim native async performance unless the middleware's callable and hooks actually support it.

    This avoids a second full URL resolution per request, preserves the public version-wide policy for unambiguous unknown paths, and makes the only ambiguous case explicit instead of silently applying the wrong version.

  4. mojtaba-arvin commented on Nov 18, 2026

    @mojtaba-arvin
    OwnerAuthor

    Implemented the resolver-aware lifecycle fix in draft PR #55: #55

    The implementation uses process_view() for resolved routes, registry metadata matched against the longest complete route suffix, and a conservative unresolved-path fallback. It preserves 410 for a single unambiguous version segment; unresolved paths containing multiple different versions remain 404 rather than guessing. The middleware still adds lifecycle headers to a resolved view's own 404 response.

    Added full Django Client/AsyncClient tests for nested decorator routes, nested VersionedRouter routes, pre-view 410 short-circuiting, unresolved 404/410, ambiguous nested paths, and view-level 404 headers. Also changed the unit-test precedence rule so the actual resolver match is authoritative over an inconsistent request.version.

    CI is currently running on head e8e7b5470dc26db3e508705fde8f0a010e0317d7; no pass is claimed yet. The PR remains Draft until the full configured matrix and CodeQL are inspected.

  5. mojtaba-arvin commented on Nov 18, 2026

    @mojtaba-arvin
    OwnerAuthor

    Follow-up from the next integration run: Django/DRF exposed the exact resolver route as api/v1/proxy/api/v2/orders/$ (the child RegexPattern's trailing $ remains in ResolverMatch.route, while its registered pattern is ^api/v2/orders/$). The earlier normalization stripped anchors only from the registered pattern, so the suffix still did not match.

    Updated the registry matcher to compare both raw and normalized forms of the resolver route and registered pattern, while retaining the segment-boundary check and longest-suffix rule. The integration test now asserts this exact resolver-derived mapping. A fresh CI run is pending on the updated head.

  6. mojtaba-arvin commented on Nov 18, 2026

    @mojtaba-arvin
    OwnerAuthor

    The latest full run confirmed the lifecycle integration tests themselves passed, including the DRF regex-route assertion. The remaining failures were a stale source-evidence fixture that still expected the old sunset condition line, plus Black formatting in the lifecycle file and source-evidence generator. I updated the generator's symbol/line anchor and its test to assert the new pre-view 410 marker, and applied the formatting corrections. The new head is eafd1a54a3c12421540e7d41f991ca04e89b9996; its full CI run is pending.

  7. mojtaba-arvin commented on Nov 18, 2026

    @mojtaba-arvin
    OwnerAuthor

    I also moved get_resolved_route_version() to a stable position after _find_route_index() in registry.py. PR #44 adds tombstone methods between get_route_version() and get_version_matrix(); keeping the new helper away from that insertion area reduces the chance of a merge conflict when #44 and #55 are integrated. The latest head is 6ebe78a83ce8e469b4affe2346a49c001f5d7675; CI is pending.

  8. mojtaba-arvin commented on Nov 18, 2026

    @mojtaba-arvin
    OwnerAuthor

    Latest PR #55 run on 6ebe78a83ce8e469b4affe2346a49c001f5d7675: unit/integration tests, lint, package build, website verification, tox/workflow validation, Windows, and all completed Python/Django combinations passed; CodeQL passed. Only the macOS compatibility job is still queued. This is strong evidence for the route-aware design, but I am waiting for the final job before calling the matrix green.

  9. mojtaba-arvin commented on Nov 18, 2026

    @mojtaba-arvin
    OwnerAuthor

    Added the previously missing request-level request.urlconf override integration test. It deliberately defines conflicting version metadata in ROOT_URLCONF (V1) and the per-request URLconf (V2), so the response proves Django's actual override is used rather than merely testing override_settings(ROOT_URLCONF=...). This closes the URLconf-override acceptance gap. New head 684e9273c6a5c372b59af090ece57faada78be57; fresh CI is required.

  10. mojtaba-arvin commented on Nov 18, 2026

    @mojtaba-arvin
    OwnerAuthor

    Combined integration evidence: Draft PR #58 combines the endpoint-removal/tombstone implementation from #44 with the resolver-aware lifecycle changes from #55, including the merged registry helper and merged canonical lifecycle/endpoint-removal reference. On exact combined head a6d24cbf16862373ccb6a6cec8ee8e520c3638d0, the OpenAPI consumer contract passed; path classification, agent/workflow policy validation, tox/workflow verification, package build, and macOS compatibility also passed. Unit/integration, Windows, website and remaining PR-smoke jobs are still running. This is the first test of the two PRs as one tree; no merge performed.

  11. mojtaba-arvin commented on Nov 18, 2026

    @mojtaba-arvin
    OwnerAuthor

    Final combined verification: PR #58 on exact head a6d24cbf16862373ccb6a6cec8ee8e520c3638d0 passed the complete PR gate, OpenAPI consumer contract, CodeQL, unit/integration, lint, package build, website, tox/workflow validation, Windows, macOS, and all configured PR smoke environments. This verifies #44's tombstone implementation and #55's route-aware lifecycle together, including their merged registry and canonical reference changes. The integration candidate remains Draft; no merge performed.

  12. mojtaba-arvin commented on Nov 18, 2026

    @mojtaba-arvin
    OwnerAuthor

    Delivered in the consolidated roadmap merge #58 → main commit a8b39343c478bb5a8afbe1de20d95a2b10630f37. Lifecycle resolution now uses the actual matched route after Django URL resolution, covers nested mounts, request-level URLconf overrides, sync/async execution, pre-view 410 and response headers. The exact integrated head passed the full required PR gate.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions