middleware.ordering

Page actions AI-ready formats and sharing
Open LLM text
Share with AI
Ask Claude Ask ChatGPT Ask Gemini Ask Copilot

Stable priority ordering for user-registered middleware.

App.add_middleware(mw, priority=...) records a per-entry priorityparallel to the middleware list (seeMutableAppState.middleware_priorities). The resolved request pipeline must be deterministic and independent of registration order,…

Stable priority ordering for user-registered middleware.

App.add_middleware(mw, priority=...) records a per-entry priorityparallel to the middleware list (seeMutableAppState.middleware_priorities). The resolved request pipeline must be deterministic and independent of registration order, so the user middleware is sorted once at freeze (under the freeze lock, before publication) by(priority, registration_order).

Two invariants make this safe to add to existing apps:

  • Lower priority runs outermost. The compiled chain wraps later entries inside earlier ones (handler.compile_middleware_chainiterates reversed(...)), so a smaller priority sorts earlier and therefore wraps the rest — the first-registered / lowest-priority middleware sees the request first and the response last.
  • Default order is byte-identical to today.sortedis stable and the default priority is0, so an all-default stack keeps registration order exactly; the sort is a no-op for every app that never passespriority=.

Builtin middleware (added by the compiler) is intentionally NOT sorted here — it stays positionally pinned around the user middleware.

middleware.ordering

Name Type Default Description
type
qualified_name
element_type
description
source_file
line_number
is_autodoc
autodoc_element
_autodoc_template
_autodoc_url_path
_autodoc_page_type
title
doc_content_hash

Symbols on this page

sort_user_middleware
function
def sort_user_middleware(middleware_list: list[Any], priorities: list[int] | None) -> list[Any]

Return middleware_list stably sorted by(priority, registration).

priorities is the index-aligned priority list. When it isNoneor its length does not match (a defensively-handled inconsistency), the input order is returned unchanged so a length mismatch can never reorder or drop middleware silently. The input list is not mutated.

Parameters

Name Type Default Description
middleware_list list[Any]
priorities list[int] | None

View source · /home/runner/work/chirp/chirp/site/../src/chirp/middleware/ordering.py:1