Skip to content

Dispatching

dispatch runs one spec for one principal with one set of arguments, and returns a DispatchResult. It is the whole of what a transport calls: an HTTP view, an MCP tool, a command and a task worker each build a principal and a mapping of arguments, dispatch, and answer the result in their own terms.

result = dispatch(spec, principal=user, arguments={"pk": 3, "title": "Final"})

The order

A deactivated principal is refused first, as PrincipalUnavailable: an authenticated one whose is_active is false. One with no is_active reads as active, and anonymous goes on to the permission check, which decides whether anonymous may act. Then the same seven steps for a read and a write, and for the async entry point:

  1. The shape check and the closed argument set, over spec.parameters(): presence, JSON type, format, choices and nullability at every level of nesting, with no query. An argument no parameter declares is refused. A partial write's absent Validator parameters are not refused, nor one its input_data provider is annotated to fill. A read a provider requires itself, by name with no default, is not relaxed: only the caller can send it, and a call leaving it out is refused here, before any provider runs (example).
  2. Class-level authorization: every permission check's has_permission, or the grant a transport passed instead. A seed a check names is resolved just before it, and only such a seed (permissions).
  3. Target resolution: a read's own selector, or a write's instance or collection selector, called with the arguments its reads declare and what its kwargs provider returns, then shaped. A retrieve that finds nothing is kind="not_found", unless the selector allows None; a selector raising Http404, as get_object_or_404 does, is that missing row on a retrieve, and kind="not_found" on a list or a collection, whatever allow_none says (see Declaring). A target= the caller passed stands in for this step.
  4. Object-level authorization: every check's has_object_permission on a retrieved row, and its has_scope_permission where no single row is: a list a read returns or a write's collection, empty or not, and the None of a create, of a many write and of a missing row a write's allow_none lets through. A read's own None under allow_none is asked of neither.
  5. Validation: a write's input_data provider, then its Validator on only the arguments it declares, with the provider's values merged over the caller's, and the resolved target and partial in its context. A dataclass Validator decodes each value of a dict[str, X] field there and refuses one under its own key (example); the shape check sees only an object.
  6. Affordances, then preconditions: a write's affordances, in declaration order - the first one not met refuses the call with ActionUnavailable, carrying its code - then its preconditions, the first to raise aborting the call with what it raised.
  7. The run: the service, inside transaction.atomic() unless the spec says atomic=False, called with what its kwargs provider returns beside the validated values, then the output selector if one is declared.

A read stops after step four and its preconditions, which run on what its selector found: its selector is its run. Its affordances are answers about each row, for a list to report, and refuse nothing.

A many write resolves nothing in steps three and four, where its scope check is asked of None, never of the caller's rows. Step one raises only the top level's refusal; a row's is raised in step five, beside the Validator's refusals of the other rows, so a principal refused in step two learns nothing about the rows it sent. That node reads in index order, then the list's own non_field_errors. Where it carries that message it mixes int keys with a string one, so json.dumps(..., sort_keys=True) over it raises TypeError - write it as it stands.

The order is the design, and each place reads as if it could move:

  • The shape check comes first because it costs nothing and reveals nothing the declaration does not already say, so a malformed call is refused before it costs a row lookup.
  • Class-level authorization comes before resolution, so a principal it refuses learns nothing about which rows exist: a missing row and a present one are refused alike.
  • Resolution comes before validation, so the Validator's context carries the row. An update's uniqueness check has to exclude the row being updated, and it cannot if the row is resolved afterwards.
  • A deactivated principal is refused before the shape check, so it learns nothing about its arguments, and it is refused at the same point whether it was handed over, named by principal_id or read off request.user.
  • Affordances come after object-level authorization and validation, so a principal who may not see the row is never told what state it is in. They come before the run's transaction opens, so a refusal never opens one. Preconditions follow them, in the same place, as djangorestframework-services orders the two.

Per-call values beneath the provider

A transport sometimes knows a service keyword per call that the spec cannot carry: what an HTTP view's per-request hook returns. dispatch and adispatch take it as extra_kwargs, so the spec need not be rebuilt for the call:

def stamp(*, title: str, source: str, channel: str) -> str:
    return f"{title} via {source} on {channel}"


stamp_spec = ServiceSpec(
    service=stamp,
    permissions=[IsSignedIn()],
    validator=DataclassValidator(Rename),
    kwargs=lambda: {"channel": "api"},  # the spec's own provider
)


def stamp_from_a_view(user: Any, arguments: dict[str, Any]) -> DispatchResult:
    # What the view's per-request hook resolved, beneath the spec's provider.
    return dispatch(
        stamp_spec,
        principal=user,
        arguments=arguments,
        extra_kwargs={"source": "web", "channel": "web"},
    )

The view's hook resolved source and channel: the provider's channel wins, and the hook's source fills the gap. A value for the Validator goes into arguments instead, where the permission checks read it too.

extra_kwargs is the lowest of three tiers: beneath the spec's kwargs provider, so the spec's own provider wins on a clash, and beneath what the spec's Validator computed or bound. It is read as the provider's return is:

  • an entry whose value is UNSET is dropped;
  • a key the spec's provider is annotated to fill is the provider's alone, and the overlay's value for it is dropped, so a provider that leaves the key out leaves it absent; one annotated UNSET-able lets the overlay's value through when it declines;
  • a key naming a seed, such as user, is refused as ImproperlyConfigured.

A key naming a parameter the spec declares is refused, as ImproperlyConfigured, before the shape check, the way a seed's name is. A declared parameter is anything spec.parameters() lists: the spec's reads, its Validator's fields, its target selector's reads, and a many spec's list. The caller's value for one is what the permission checks are handed and what the target selector looks the row up by, so an overlay standing in for it would run the call on a value neither saw: the value authorized is the value run. Two keys that name one are not refused: an UNSET entry, which supplies nothing, and a parameter the spec's own typed kwargs provider fills, whose caller's value is dropped before any check and whose overlay value is dropped beneath the provider. To set such a value per call, fill it from that provider.

A key naming a value the spec's Validator computed is never the overlay's: a key of the values its validated() returned, or of the pool it bound, is left to the Validator, and the overlay's entry is dropped for that call rather than refused. Whether a Validator computes a key can turn on what the caller sent - a slug derived from a title only when one arrives - so a refusal there would let a request decide whether a misconfiguration error fires. The overlay fills such a key on the calls where the Validator leaves it out. Refusal is kept for what is static: a key naming a declared parameter, or a seed, is refused on every call alike.

extra_kwargs reaches a read's own selector and a write's service, never a target or output selector.

There is no overlay for the Validator's input. Every value one could carry to the Validator is a field the caller sends, so an overlay would stand in for a value the permission checks saw. A transport with per-request values for the Validator merges them into the arguments it hands dispatch, where the checks and the Validator read the same value.

The result

A DispatchResult has a kind and a value:

kind When value
"list" A LIST read, a write whose output selector is a LIST, or a many or returns_many write with no output selector whose service returned something that is a set of rows (a mapping, str, bytes or non-iterable is ImproperlyConfigured, after the write) The rows, a queryset when the selector returned one, [] when a selector declaring allow_none returned None
"instance" Everything else that ran The row, the service's return, or what the output selector re-read
"not_found" A required row does not exist None

A write's result also carries service_result (the service's own return, before any output selector), instance (the resolved target) and data (the Validator's data the service received: the validated values, or the instance a DataclassValidator built, or a many write's list of them).

Not-found is reported, not raised. A transport decides what a missing row means on its own wire - a 404, an exit code, a tool error - and most transports have no status codes for the kernel to choose from.

def list_notes(user: Any) -> list[dict[str, Any]]:
    result = dispatch(list_notes_spec, principal=user, arguments={"ordering": "-title"})
    return present(list_notes_spec, result)

A list's result.kind is "list" and its value the shaped queryset, not yet read; present reads it into one dict per row, in order.

note_spec = SelectorSpec(
    kind=SelectorKind.RETRIEVE,
    selector=lambda *, user, pk: Note.objects.filter(owner=user, pk=pk),
    permissions=[IsSignedIn()],
    reads=Parameters.of(Parameter("pk", "integer", required=True)),
    presenter=DataclassPresenter(NoteRow),
)


def show_note(user: Any, pk: int) -> tuple[int, Any]:
    result = dispatch(note_spec, principal=user, arguments={"pk": pk})
    if result.kind == "not_found":
        return 404, {"detail": "Not found."}
    return 200, present(note_spec, result)

note_spec scopes its selector to the principal, so another user's note is not found rather than refused: it does not exist for them.

One case is not reported as not-found: a retrieve output selector that finds nothing. The service has already run and, under atomic, committed, so reporting not-found would tell the caller the write did not happen. The value is None under kind="instance" instead, whether the re-read returned None or raised DoesNotExist or Http404. A list output selector raising Http404 is a fault for the same reason, and raises a RuntimeError chained from it.

The output selector is called from the base pool plus the service's return, under two names: result, and instance, as djangorestframework-services binds it. They are one value, whatever the service returned, None included, so a re-read declares whichever its author wrote. instance there is what the service returned, not the target it acted on, which the result carries as result.instance.

Presenting

Nothing is rendered by dispatch. present renders a result through the spec's presenter when the transport asks, so one that hands the row to a template never pays for rendering it.

  • A "list" result is presented item by item, into a list. With no presenter the items come back as they are, still in a list: a queryset is evaluated here rather than handed back lazily.
  • An "instance" result is presented through the presenter. A value of None is returned as None, never handed to a presenter to render as a row of blank fields.
  • A "not_found" result raises ValueError. Presenting nothing as a success is the bug this refuses; answer the not-found first.

apresent does the same from async code, in one executor hop, since a presenter may query.

Permissions

A PermissionCheck takes a principal and a spec, and nothing else by position: no request and no view, because most transports have neither. A check that wants them declares request or view by keyword and is handed what the call's context holds under that key, None where it holds none (the call's request and view). Checks are instances, so a check can carry its own configuration - a codename, a group - and a spec reads as the list of checks it applies. has_permission is the class-level check; has_object_permission runs on a resolved row and allows unless overridden; has_scope_permission is the same question for a call that resolves no single row - asked of the set a collection write acts on or a list read returns, and of None where the call acts on no existing row, a create - and allows unless overridden too. It is a method of its own rather than has_object_permission handed a set or None, because a check written for a row reads an attribute off it and would fail on either. message is what NotPermitted says when the check refuses.

A check's denial is marked. A check answering False, at any of the three questions, raises PermissionCheckDenied, a NotPermitted carrying the check that answered and the spec it was asked about. Every other NotPermitted stays bare: a grant or a seeds carrier that does not cover the call, a service's own refusal, and a check that raises NotPermitted itself rather than answering. So a transport can answer a check's denial of an anonymous caller with an authentication challenge, as DRF's permission_denied does, and every other refusal as forbidden. A combinator's denial names the combinator, the rule the spec declares. A denial inside a dispatch the service makes propagates out of the outer call as the same class, so a transport treats it as its own call's only where exc.spec is kernel_spec(spec) for the spec it dispatched: spec is the compiled spec, the one the check was handed, and kernel_spec answers the same one for a declaration every time.

A check can read the call's arguments by declaring a keyword arguments on any of its three methods. Dispatch then hands that method the call's shape-checked arguments as a read-only mapping - a route's captured pk, a filter the caller sent - as an HTTP permission class reads the view's captured kwargs. Only the mapping is read-only: its values are the call's own objects, the ones the run receives, so a check must not mutate them.

class NotLocked(PermissionCheck):
    message = "That note is locked."

    def __init__(self, *locked: int) -> None:
        self.locked = frozenset(locked)

    def has_permission(
        self, principal: Any, spec: Any, *, arguments: Mapping[str, Any] | None = None
    ) -> bool:
        if arguments is None:
            return False
        return arguments.get("pk") not in self.locked


lockable_note_spec = SelectorSpec(
    kind=SelectorKind.RETRIEVE,
    selector=lambda *, user, pk: Note.objects.filter(owner=user, pk=pk),
    permissions=[IsSignedIn(), NotLocked(7)],
    reads=Parameters.of(Parameter("pk", "integer", required=True)),
)

A method that does not declare the keyword is asked exactly as before, so no existing check changes. The base methods do not declare it, which keeps every check written without it a valid override under a type checker. Opt-in is by name. What is read is what dispatch calls, getattr(check, method): a callable set on the instance, or a mock patched over the method, answers for its own signature. Behind decorators, the __wrapped__ chain functools.wraps leaves is read one layer at a time, each by its own signature, since each is called in turn: a layer naming arguments takes it, a layer spreading **kwargs passes it to the layer beneath, and a layer with neither would refuse it. So the keyword is handed only where a layer names it before any layer without **kwargs: an ordinary forwarding decorator, or several, keeps an opted-in check opted in, while a narrower layer anywhere in the chain, or **kwargs with nothing beneath that asked, is handed nothing. A callable with no signature to read, such as a builtin behind functools.partial, is asked as a check that never opted in. arguments is None where a transport calls authorize() without arguments=, and a check that needs them decides for itself what that means: the example above refuses. A many call's rows are not among the arguments: they are validated after every check, so a check sees the call's reads alone. The authorize functions take the same mapping as arguments= for a transport that calls them itself.

A transport listing what a principal may run has no arguments to hand a check that declares them. checks_read_arguments says whether any does, without calling a check: True when a check declares arguments on the class question or, for a service spec with no target selector (a create), the scope question. It answers what a check declares, not what it does with None: a check declaring arguments=None reads True though it answers when handed nothing. The object question and a target's scope question are asked of a resolved row, which a listing has none of, so they are not read. The declaration is read as authorize reads it - a forwarding wrapper over a method naming arguments counts, a check taking only **kwargs or naming arguments in a position the call fills does not - so the two cannot disagree.

class OwnsTheNamedNote(PermissionCheck):
    def has_permission(self, principal: Any, spec: Any, *, arguments: Any) -> bool:
        # Decided by what the call names, so it is asked with the call's arguments.
        return Note.objects.filter(owner=principal, pk=arguments["pk"]).exists()


owned_note_spec = SelectorSpec(
    kind=SelectorKind.RETRIEVE,
    selector=lambda *, user, pk: Note.objects.filter(owner=user, pk=pk),
    permissions=[OwnsTheNamedNote()],
    reads=Parameters.of(Parameter("pk", "integer", required=True)),
)


def listed_before_any_call(specs: list[SelectorSpec]) -> list[SelectorSpec]:
    return [spec for spec in specs if not checks_read_arguments(spec)]

A listing has no arguments to give a check that declares them, so it neither asks that check nor guesses its answer: such a spec is decided at the call, which has them.

To ask the checks rather than read their declarations, authorize_without_arguments asks a spec what a call with no arguments is asked: authorize, then, for a service spec with no target selector (a create), authorize_scope of None. That is the same rule checks_read_arguments reads, so the two agree on which questions there are. Each question is handed arguments=None, and grant=, call_context= and pool_seeds= as authorize takes them, with one call_context dict between the two, a fresh one where none is handed; a grant's target_checked does not answer a create's scope question here, since no target is handed in. It returns the grant authorize returned. It catches nothing: a refusal, PrincipalUnavailable, a configuration error and a check that cannot answer without the arguments it reads each reach the caller as they were raised, because what each means for a listing, an OPTIONS answer or a call whose arguments failed their shape is the transport's decision:

class UnderQuota(PermissionCheck):
    def has_permission(self, principal: Any, spec: Any) -> bool:
        return principal.is_authenticated

    def has_scope_permission(self, principal: Any, spec: Any, scope: Any) -> bool:
        # A create's scope is nothing (None): may one more note be made?
        return Note.objects.filter(owner=principal).count() < 3


def add_untitled_note(*, user: Any) -> Note:
    return Note.objects.create(owner=user, title="Untitled")


add_note_spec = ServiceSpec(service=add_untitled_note, permissions=[UnderQuota()])


def offered_to(principal: Any, specs: list[Any]) -> list[Any]:
    offered = []
    for spec in specs:
        if not checks_read_arguments(spec):
            try:
                authorize_without_arguments(spec, principal, pool_seeds=DEFAULT_POOL_SEEDS)
            except (NotPermitted, PrincipalUnavailable):
                continue
        offered.append(spec)
    return offered

Hiding a refused operation is this listing's policy, not the kernel's, and a spec whose checks read the arguments is left to the call.

A check can read the call's context and a registered seed the same way. A keyword call_context is handed the one dict every stage of the call shares (the call's context), and a keyword named after a seed the call's PoolSeeds register is handed that seed's value, at whichever of the three questions declares it. A parameter the call fills by position - the principal, the spec, the target or scope, whatever the method calls them - is never an opt-in, whatever its name, so a DRF-style has_permission(self, request, spec) under a transport registering a request seed is asked as it always was. A seed named arguments is never handed this way: a check declaring arguments gets the call's. Only the seeds a spec's checks name are resolved early, before the class-level check, and every pool after reuses those values, so each resolves once per call and the check and the service see one object; every other seed resolves after the class-level check, as it always has. A seed resolver raising PrincipalUnavailable there ends the call before any check is asked, as a refusal does. The authorize functions take call_context= and seeds= to offer the same, or pool_seeds= to resolve the seeds their checks name (admitting a request before the form), and with no call_context a check declaring it is handed a fresh dict.

A check is sync-only: it may query, so the async entry point runs it in the executor. An async def method would answer with a coroutine, which is truthy and would allow every call, so a spec refuses a check declaring one when it is built, with ImproperlyConfigured naming the method. A method that hands back a coroutine from a plain def - a decorated async def - is refused where its answer is read, so the call fails closed.

Checks combine into one. A spec's permissions= passes only when every check passes. To say "its owner, or staff" or "anyone not suspended", AllOf, AnyOf and NoneOf each take checks and an optional message=, and are a check like any other, so they nest and sit in permissions= beside other checks.

class OwnsTheNote(PermissionCheck):
    def has_permission(self, principal: Any, spec: Any) -> bool:
        return principal.is_authenticated

    def has_object_permission(self, principal: Any, spec: Any, target: Any) -> bool:
        return target.owner_id == principal.pk


class IsStaff(PermissionCheck):
    def has_permission(self, principal: Any, spec: Any) -> bool:
        return principal.is_staff


class IsSuspended(PermissionCheck):
    def __init__(self, *usernames: str) -> None:
        self.usernames = frozenset(usernames)

    def has_permission(self, principal: Any, spec: Any) -> bool:
        return principal.username in self.usernames


open_note_spec = SelectorSpec(
    kind=SelectorKind.RETRIEVE,
    selector=lambda *, pk: Note.objects.filter(pk=pk),
    permissions=[
        # Its owner, or anyone on staff. At the row question a check counts
        # only where it passes the class-level one too: IsStaff allows every
        # row, but only for staff, so a signed-in stranger is refused the row.
        AnyOf(OwnsTheNote(), IsStaff(), message="Only its owner or staff may open a note."),
        NoneOf(IsSuspended("mallory"), message="Suspended accounts may open nothing."),
    ],
    reads=Parameters.of(Parameter("pk", "integer", required=True)),
)
  • AllOf asks every check each question, in order, and stops at the first that fails.
  • AnyOf passes the class-level question at the first check that passes it. At the row and scope questions a check counts only where it passes the class-level question too, asked again, and then the row or scope question, as an HTTP framework's OR of permission classes does: a check that allows every row by default does not admit a principal it refused at class level because another check admitted them there. The class-level question is asked again rather than remembered, so the row is judged the same under a grant that answered the class-level question without asking.
  • NoneOf passes only when no check passes has_permission. It inverts that question alone and allows at the row and scope questions, so a check whose has_object_permission or has_scope_permission is its own, inside it at any depth, is refused when it is built: the opposite of "may act on this row" is no rule.

A check inside a combinator is handed what it declares and nothing else - the call's arguments, its context, a seed - and a seed it names is resolved for the call as one the spec's own checks name would be, bar the names a combinator's own methods take: principal and spec at every question, target at the row one and scope at the scope one, as asked of the combinator or of a check it asks again there (AnyOf asks has_permission again at both). A check naming one is refused when the combinator is built, since a seed of that name cannot reach it through the combinator; rename the keyword. checks_read_arguments reads through a combinator the same way. Every answer inside one is read as an answer at the top is, so a coroutine fails closed, and a check that raises ends the call with its error rather than being read as a refusal. A refusal says the combinator's message, not that of a check inside it, or the generic wording without one.

A combinator is refused when it is built, with ImproperlyConfigured, when it holds no checks, when a check inside it would be refused in permissions= (a class, something that is not a PermissionCheck, an async def method), and when it holds Unrestricted, a subclass included: the explicit allow is a decision a spec makes by name. A combinator is equal only to itself.

A spec with no permission check is refused, with ImproperlyConfigured, at dispatch and at registration. Off HTTP there is no view whose policy an undeclared operation could inherit, and running it anyway is how an off-HTTP runner skips authorization with nothing warning. An operation that is genuinely open says so with permissions=[Unrestricted()], which is also one search away when someone asks which operations are open.

Grants

Dispatch enforces the permission check by default. A transport that has already authorized through its own machinery - an HTTP view that ran its framework's permission classes - says so with a Grant rather than by skipping the check, and pays for one class-level evaluation instead of two:

def rename_from_a_view(user: Any, arguments: dict[str, Any]) -> DispatchResult:
    grant = Grant(spec=rename_note_spec, principal=user)
    return dispatch(rename_note_spec, principal=user, arguments=arguments, grant=grant)

A grant is bound by identity to one spec object and one principal object. Carried to another operation or another user it covers nothing, and dispatch refuses it with NotPermitted. It covers the class-level check only, unless it says target_checked=True, which a transport can claim once it has resolved the row and run the object-level check itself, and which covers a service spec's target only when that target is handed to dispatch as target=; otherwise dispatch still runs has_object_permission on the row it resolves. On a selector spec the claim covers nothing: a selector spec takes no target=, so there is no row handed in to bind the claim to, and the row the arguments make the selector find may be one the transport never checked. Dispatch runs the check on the row the call returns, shaped and annotated, and the scope check on the list it returns, whatever the grant says, as djangorestframework-services checks the row its selector returned. A grant stands in for neither check that is not about permission: a deactivated principal is refused with one, and a write's affordances are still answered. And a grant cannot be serialized: pickling one raises TypeError, so it cannot ride a queue into a worker. A task runs later, against state that may have moved, and re-authorizes by construction.

authorize, authorize_target and authorize_scope are the three checks dispatch runs, exported for a transport that runs them itself; authorize returns the grant it honoured or a new one covering the spec and principal, and dispatch skips the other two under target_checked only where a service spec's target was handed in as target=.

Admitting a request before the form

A page asks the class-level check before it shows anything, so a principal the check refuses never sees the form. Where that check names a seed - the club a route captured, a tenant read off the request - the transport has the registry it would hand dispatch rather than the seed's value. It resolves the seeds the spec's checks name once, with resolve_seeds, and hands the carrier that returns to authorize and then to dispatch as seeds=, so the check that admitted the request and the run see one value:

class InClub(PermissionCheck):
    """Admits a member of the club the route names, read from a seed."""

    message = "Members of this club only."

    def has_permission(self, principal: Any, spec: Any, *, club: str) -> bool:
        return principal.groups.filter(name=club).exists()
def club_seeds(club: str) -> PoolSeeds:
    return DEFAULT_POOL_SEEDS.extend(club=lambda: club)


def club_note_page(user: Any, club: str, title: str | None = None) -> Any:
    pool_seeds = club_seeds(club)
    context: dict[str, Any] = {}
    seeds = resolve_seeds(
        club_note_spec, principal=user, pool_seeds=pool_seeds, call_context=context
    )
    # Before the form: a principal the class-level check refuses never sees it.
    grant = authorize(
        club_note_spec, user, seeds=seeds, pool_seeds=pool_seeds, call_context=context
    )
    if title is None:
        extra = form_keywords(club_note_spec, user, pool_seeds=pool_seeds, call_context=context)
        return ClubNoteForm(**extra)
    try:
        return dispatch(
            club_note_spec,
            principal=user,
            arguments={"title": title},
            pool_seeds=pool_seeds,
            grant=grant,
            seeds=seeds,
            call_context=context,
        )
    except InvalidArguments:
        extra = form_keywords(club_note_spec, user, pool_seeds=pool_seeds, call_context=context)
        return ClubNoteForm(data={"title": title}, **extra)

The registry is built per request, from what the route captured, and the club is resolved once for the call, so InClub and the service see one value. The page authorizes before the form, so a principal the class-level check refuses never sees it: NotPermitted for anyone outside the club. On the GET the form is built as dispatch will build it, with form_keywords. When the POST fails validation, the page renders the form again, bound to what was posted, with the keywords dispatch bound it with and the dict dispatch ran with.

resolve_seeds resolves the seeds a check of the spec names at any of its three questions, the class-level, object-level and scope ones, for the principal as user, exactly as dispatch resolves them before its own class-level check; a seed no check names stays unresolved and resolves in each of dispatch's pools as it always does. A deactivated principal is refused first, as PrincipalUnavailable, before any seed resolves. The carrier it returns is a CallSeeds, and the whole authorize-first path takes it as seeds=, each step resolving nothing:

  • a single row: resolve_seeds, then authorize(seeds=), then resolve_target(seeds=, grant=), then dispatch(seeds=found.seeds, grant=, target=);
  • a many call or a create: resolve_seeds, then authorize(seeds=), then authorize_scope(seeds=), then dispatch(seeds=, grant=).

The carrier is bound by identity to the spec, the principal, the call_context dict and the registry, and each of authorize, authorize_scope, authorize_target and resolve_target refuses one that does not cover its call with NotPermitted, before a grant can answer and before any check is asked. So hand every step one dict: a carrier minted with no call_context is bound to a fresh one, seeds.call_context, and an authorize(seeds=) handed none is refused. Beside a carrier, pool_seeds= is only the registry it is matched against, DEFAULT_POOL_SEEDS when left out.

authorize also takes pool_seeds= alone, for a transport that only asks the class-level check: it resolves the seeds the spec's has_permission checks name, once, and no other, and nothing when a covering grant answers first. The values are not carried on the grant, so a dispatch that follows resolves them again for its own call. authorize_target and authorize_scope take pool_seeds= the same way, for the seeds their own question names. seeds= a mapping is the alternative for a caller holding resolved values, and handing one with pool_seeds= raises TypeError, since one would silently outrank the other, whether or not a grant would have answered the call first. A deactivated principal handed with pool_seeds= raises PrincipalUnavailable before any seed resolves, as dispatch refuses one before anything else, grant or no grant; without pool_seeds= nothing is resolved and the call is asked as it always was. A check naming a seed the registry does not hold is asked without it, as under seeds=, so its own signature decides.

Building the form before the call

The page above builds its form itself, to show it, and the form's __init__ takes a keyword of its own, which the spec's FormValidator supplies through form_kwargs on dispatch:

class ClubNoteForm(forms.Form):
    title = forms.CharField()

    def __init__(self, *args: Any, club: str, **kwargs: Any) -> None:
        super().__init__(*args, **kwargs)
        self.fields["title"].help_text = f"Posted to {club}."


def post_to_club(*, user: Any, title: str, club: str) -> Note:
    return Note.objects.create(owner=user, title=f"{club}: {title}")


club_note_spec = ServiceSpec(
    service=post_to_club,
    permissions=[InClub()],
    validator=FormValidator(ClubNoteForm, form_kwargs=lambda *, club: {"club": club}),
)

form_keywords returns what that form_kwargs returns, off dispatch, so the page's GET builds the form as the POST's dispatch will: ClubNoteForm(**extra) in the page above, and the POST that fails validation shows it again, bound to what was posted, built the same way. It binds form_kwargs from the pool dispatch would - the principal as user, the no-op reporter as progress, the call's context and the target under the name the service receives it by (instance or collection, nothing for a create) - and resolves only the seeds of pool_seeds= that form_kwargs would be handed: those it names, or every one for a callable taking **kwargs. A page hands it the call_context= it hands dispatch, so the failed POST's re-rendered form reads the dict that dispatch ran with, and the row resolve_target found as target=. Its answer is checked as the Validator checks it: anything but a mapping, or a mapping returning data, files or instance, is refused with ImproperlyConfigured. A spec whose Validator is not a FormValidator is refused with TypeError, and a FormValidator with no form_kwargs returns {}. Where it would resolve a seed for a deactivated principal it raises PrincipalUnavailable first, as dispatch does, and a call that resolves none is not refused. It neither authorizes nor looks the target up, and it is sync: an async caller hops once with sync_to_async.

A target resolved ahead of the call

A page that shows the row before the call acts on it - the form in front of an update, the confirmation in front of a delete - must show the row dispatch would find, refused where dispatch would refuse it. resolve_target runs dispatch's own steps for a write's target and nothing else: the deactivated principal, the shape check over the target selector's parameters alone, class-level authorization, then the very lookup and checks dispatch runs. A Validator field is neither required nor unknown there, and a target read the selector's kwargs provider fills or may fill is not required, as in dispatch, unless that provider requires it itself, so a GET carrying the route's arguments resolves as a POST carrying the whole form does.

def rename_page(user: Any, pk: int, title: str | None = None) -> Any:
    context: dict[str, Any] = {}
    found = resolve_target(
        rename_note_spec, principal=user, arguments={"pk": pk}, call_context=context
    )
    if isinstance(found, DispatchResult):
        return None
    note, grant = found
    if title is None:
        return note
    result = dispatch(
        rename_note_spec,
        principal=user,
        arguments={"pk": pk, "title": title},
        target=note,
        grant=grant,
        seeds=found.seeds,
        call_context=context,
    )
    return present(rename_note_spec, result)

On the GET the page shows the row the form will act on: a missing one is the not-found answer dispatch would give, and NotPermitted was raised already for anyone else. The POST acts on the row already found and checked, so it looks nothing up a second time; the grant says has_object_permission was asked, and a seed a check named is not resolved again. The lookup and the call it checked share one call_context dict.

It returns (target, grant): the row, the set, or None for a create, and a grant covering the spec and the principal with target_checked set. Both go to dispatch(..., target=, grant=), which then looks nothing up and asks no object-level or scope check again. The pair is a ResolvedTarget, whose .seeds hold the values its checks were offered of the registered seeds they name; handed on as dispatch(..., seeds=found.seeds), with the same call_context dict, the run takes them rather than resolving those seeds again, as below. The grant is honoured only with the target it was resolved for: handed on without target=, dispatch looks the row up itself and runs the checks on it. A missing row that allow_none does not let through comes back as DispatchResult(kind="not_found"), so it is never mistaken for the None it lets through, and so does a collection selector raising Http404. A read, whose selector is its run, raises TypeError, and a many write declaring no collection_selector_spec, which has no target, ImproperlyConfigured. It is sync; an async caller hops once with sync_to_async.

target= on dispatch and adispatch takes any target the caller resolved - what an HTTP view's get_object() found, too - and stands in for step three. Step four still runs on it unless the grant says target_checked; without target= step four always runs. None is a missing row, not-found unless the instance selector says allow_none; a create takes None and refuses anything else. Dispatch trusts it: the target's reads are still checked as declared, and keeping them and the target in agreement is the caller's.

Principals off HTTP

HTTP has a session to resolve a user from; a queue payload, a command argument or an agent's notion of who is asking carries an identifier. resolve_principal is the one place that becomes a user row, and it refuses a missing, malformed or deactivated one, or a key past its integer column's range, an infinite one included, with PrincipalUnavailable. It never falls back to an anonymous user: an operation dispatched with no resolvable principal has no principal, not an anonymous one. The stock permission classes of the HTTP frameworks pass a deactivated user, which is why the refusal does not wait for them: resolve_principal refuses one at lookup, and dispatch refuses one it is handed, by the same rule.

Binding without dispatching

Some transports bind input themselves: an MCP server answering a malformed call before it opens a transaction, a queue validating a task in the worker. bind_arguments runs the same two steps dispatch does - the shape check over spec.parameters(), relaxing what dispatch relaxes for partial and for a provider's filled keys, then the Validator on its own arguments - so a transport that binds for itself cannot drift from the gate dispatch applies. It runs no provider: a field an input_data provider would fill passes the shape check and, left out, is the Validator's to refuse; a read a kwargs provider would fill passes too, unless a provider requires it itself.

Hand it the call's seeds with pool_seeds=, the registry dispatch is handed, and it binds as dispatch binds with them. A reflected read a registered seed fills is not demanded of the caller, and the caller's value for it is refused under REJECT and dropped under IGNORE; a parameter dispatch refuses for sharing a seed's name is refused with ImproperlyConfigured. The Validator's ambient is dispatch's base pool, every seed resolved once for the principal, so a FormValidator's form_kwargs naming a seed is handed it, and every seed resolves on each such bind, as on dispatch. A deactivated principal is refused with PrincipalUnavailable first, before the arguments are checked, as dispatch refuses one. Any registry counts, an empty one too, since the call's request and view are seeds of every pool dispatch builds. Without pool_seeds= it resolves no seed and checks every read as declared. The club page above checks its form as the member types, bound with the club seed:

def check_club_note(user: Any, club: str, title: str) -> dict[str, Any]:
    pool_seeds = club_seeds(club)
    authorize(club_note_spec, user, pool_seeds=pool_seeds)
    return bind_arguments(club_note_spec, {"title": title}, principal=user, pool_seeds=pool_seeds)
def bind_rename(user: Any, note: Note, arguments: dict[str, Any]) -> dict[str, Any]:
    return bind_arguments(rename_note_spec, arguments, principal=user, target=note)

It returns the Validator's values: {"title": "Final"} here, without the pk the instance selector reads. A read has no Validator, and gets its checked arguments back.

It does not resolve or authorize. Dispatch runs both between the two steps. A caller of bind_arguments owns them: it authorizes before binding, and passes the row it resolved as target, or None for a create.

Checking a call before it runs

A transport that accepts a call now and runs it later - a task queue - can refuse at enqueue what the worker's dispatch would refuse before it resolves anything. check_call runs dispatch's prelude alone, through the same function, in dispatch's order: a deactivated principal, an unmarked read or a shape a registered seed occupies, the shape check, then the class-level permission check. Its keywords are dispatch's, less what only a run reads. Nothing after the prelude runs - no lookup, object or scope check, Validator, affordance or precondition - so a call it passes may still be refused when it runs.

def enqueue_rename(user: Any, arguments: dict[str, Any], queue: list[Any]) -> None:
    check_call(rename_note_spec, principal=user, arguments=arguments)
    queue.append((user.pk, arguments))

The call is refused here, before anything is queued, by the steps dispatch runs first; the job carries what was sent, and the worker dispatches it.

It returns the checked arguments and the grant, which dispatch honours for the same spec and principal in the same process; a grant is not serializable, so it never crosses a queue. The pair is a CheckedCall, still a 2-tuple, carrying the call's seeds on .seeds. The kernel's own steps run no query. It is bind_arguments' complement: check_call authorizes and does not validate, bind_arguments validates and does not authorize, and neither resolves a target. A many call's refused rows are raised by it, after the permission check, in the tree dispatch raises them in.

That one refusal is marked: its after_authorize is True, and it is False on every refusal before the permission check and on dispatch's own refusal of the same rows. A transport that checks a call before charging a rate limit reads it to tell a refused row, where the caller was admitted and only its rows are wrong, from a refused call, without asking the checks a second time.

def spend_a_call_on_the_admitted(
    user: Any, arguments: dict[str, Any], charge: Callable[[], None]
) -> dict[str, Any]:
    try:
        checked, _ = check_call(add_notes_spec, principal=user, arguments=arguments)
    except InvalidArguments as refused:
        if refused.after_authorize:
            charge()
        return refused.detail
    charge()
    return checked

Seeds handed on from the prelude

A registered seed a permission check names is resolved before the class-level check. Run check_call or resolve_target and then dispatch, and each resolves it once for its own call: the check judged one value and the run received another, and a resolver that reads moving state - a club off the request, a tenant row - can answer the two differently. Both hand back the values their checks were offered as a CallSeeds on .seeds, and dispatch(seeds=) or adispatch(seeds=) takes them, with the grant they came with, in place of resolving those seeds again. A page that admits the request with authorize before it finds the row makes the carrier first, with resolve_seeds, and hands it to every step:

def post_to_a_club_checked_first(user: Any, club: Callable[[], str], title: str) -> DispatchResult:
    pool_seeds = DEFAULT_POOL_SEEDS.extend(club=club)
    context: dict[str, Any] = {}
    checked = check_call(
        club_note_spec,
        principal=user,
        arguments={"title": title},
        pool_seeds=pool_seeds,
        call_context=context,
    )
    _, grant = checked
    return dispatch(
        club_note_spec,
        principal=user,
        arguments={"title": title},
        grant=grant,
        seeds=checked.seeds,
        pool_seeds=pool_seeds,
        call_context=context,
    )

club reads the club off the request, and a resolver asked twice may answer twice differently, so the call asks it once: the club InClub admitted is the club the form and the service are handed.

Only the seeds a check names travel; every other seed resolves in each pool as it always does, from the pool_seeds dispatch is handed. The carrier is bound by identity to the spec (compared as compiled, as a grant compares it), the principal, the call_context dict and the pool_seeds registry its prelude ran with, and dispatch refuses one that does not cover its call with NotPermitted, before any seed resolves and before the class-level check. So hand the prelude and the call one call_context dict: a prelude handed none runs with a dict of its own, readable as seeds.call_context, and its carrier covers only a call handed that same dict: a later call that passes none, or a fresh one, is refused. dispatch's and adispatch's seeds= that are anything but the carrier, seeds= without grant=, or adispatch(seeds=) with principal_id=, raise TypeError before anything runs. Like a grant, it cannot be pickled, so it never crosses a queue: a worker resolves its own.

Checking a spec where it is registered

Some declarations cannot hold as written on a mount, and which ones turns on the seeds that mount registers: a service requiring tenant runs where a tenant seed is registered and raises TypeError everywhere else. So the spec cannot refuse them when it is built, and a transport that lists it as a tool or a route lists something whose calls fail in a way the declaration already settled. check_seeds takes the spec and the mount's pool_seeds and refuses it, as one ImproperlyConfigured naming every offender in a sorted list such as ['tenant'], for any of these:

  • a parameter a registered seed or the call's own request or view would meet, which dispatch refuses on every call before it reads the arguments, in the words it refuses it in;
  • a positional-only parameter with no default, which no pool fills, so every call reaching the callable fails, of any callable listed below as well as the service, the selector and the target selector;
  • a keyword the service, the selector or the target selector requires that nothing fills: no read of its seat, no seed, no key a typed provider names, and none of what every pool carries. A service is handed data, and instance or collection only where a target selector resolves one; a selector is handed neither, and a service none of its target selector's reads or its shapes. The same is asked of these callables, against what dispatch hands that one: a service spec's preconditions are handed the service's pool, and a selector spec's the selector's with the rows as collection or the row as instance; an affordance condition, the spec's own or one a selector's affordances maps to, is handed only the call's seeds (user, progress, call_context, request, view and those the mount registers), so a rename whose condition reads frozen is refused on a mount registering no frozen seed; the output selector is handed the service's return as instance and result and what every pool carries, never an argument nor its own reads; an extend_queryset its selector's pool with the queryset; a kwargs provider, the spec's own or its target selector's, and a service spec's input_data are handed what every pool carries, the mount's seeds and their seat's reads less those the seat's typed kwargs provider fills, and for a service the target as instance or collection, but never data, a Validator's value or a provider's answer, so a kwargs provider requiring an unregistered tenant is refused, whether it annotates its keys or not and whether a Validator stands beside it or not; and a progress_reporter is handed only the call's seeds, and read only where its run takes progress, by name or through **kwargs, which is where dispatch may call it: before an async def run, or on a sync run's first report. It is refused either way, though a sync run that never reports never calls it. Each is named as the spec names it, such as ServiceSpec.affordances[0] ('frozen').when, SelectorSpec.preconditions[0] (owns_it) or ServiceSpec.instance_selector_spec.kwargs;
  • an optional read over a keyword that requires it: a call sending the read runs, and one leaving it out, as the declaration says it may, is refused as missing, or on a provider fails with the provider's own TypeError. A precondition, an extend_queryset and a kwargs or input_data provider are asked this against the reads they are handed; a condition, the output selector and a progress_reporter are handed none, so it finds nothing on them;
  • an array read with no items over a keyword its own seat annotates with an element: list[int], tuple[int, ...] or Sequence[int], or one of those | None. Such a read takes any element, so a selector annotated pks: list[int] is handed a query string's strings, and the message says to declare items, which it never derives from the annotation. An element of Any, object or a type variable, a bare list, a fixed-length tuple, an unannotated keyword, a keyword a seed fills and one a provider fills or may fill - a typed provider's key, declinable or not, or any keyword of a seat whose provider is untyped - are not refused, and neither is a hint that does not resolve, such as a forward reference to a name not importable where the callable is defined: it is resolved on its own, so it leaves the callable's other keywords readable;
  • any of those callables whose signature cannot be read, such as a builtin type like dict: dispatch binds every callable's keywords from its signature, so every call reaching it fails. That seat is refused for this alone, and the other seats are still checked.
class ToolRegistry:
    """A transport's registry: a declaration its mount cannot hold is refused at registration."""

    def __init__(self, pool_seeds: PoolSeeds = DEFAULT_POOL_SEEDS) -> None:
        self.pool_seeds = pool_seeds
        self.tools: dict[str, ServiceSpec | SelectorSpec] = {}

    def register(self, name: str, spec: ServiceSpec | SelectorSpec) -> None:
        # The mount's own seeds: a keyword one mount fills, another leaves unfilled.
        check_seeds(spec, pool_seeds=self.pool_seeds)
        self.tools[name] = spec


def tenant_name(*, tenant: str) -> str:
    return tenant


tenant_name_spec = ServiceSpec(service=tenant_name, permissions=[IsSignedIn()])


def notes_by_pk(*, user: Any, pks: list[int]) -> QuerySet[Note]:
    return Note.objects.filter(owner=user, pk__in=pks)


# Refused: an array with no items takes any element, so a query string's
# ``?pks=1,3`` would hand ``notes_by_pk`` the strings "1" and "3".
any_pks_spec = SelectorSpec(
    kind=SelectorKind.LIST,
    selector=notes_by_pk,
    permissions=[IsSignedIn()],
    reads=Parameters.of(Parameter("pks", "array", required=True)),
)
# Registered: the declared element is what the shape check holds each one to.
integer_pks_spec = SelectorSpec(
    kind=SelectorKind.LIST,
    selector=notes_by_pk,
    permissions=[IsSignedIn()],
    reads=Parameters.of(Parameter("pks", "array", required=True, items="integer")),
)

It runs nothing: no seed resolves and no provider is called. What it cannot see it leaves to dispatch: a provider that does not annotate its keys may fill any keyword of the callable it provides for, and a Validator may return or bind a value it does not declare, so neither callable is held to the keywords it requires (a provider's own keywords are read all the same), nor is a precondition or an extend_queryset beside one, though a positional-only parameter is refused whatever stands beside it. An extra_kwargs overlay fills keywords it cannot see either. A read a provider requires by name is not refused even where that provider may fill it, as in kwargs=lambda *, pk: {...} over a required pk: a provider is handed the caller's reads and the seeds, never another provider's answer, so dispatch demands such a read of the caller and refuses a call leaving it out before any provider runs, as the example runs. The array check alone is not run on a precondition, a condition, the output selector, an extend_queryset, a provider or a progress_reporter. A callable taking **kwargs requires nothing, so one forwarding into a stricter callable is not judged by what that callable requires; and a pool a transport builds itself to answer a condition before any call is its own, not the one this reads. A filter_set, a form's form_kwargs and a seed's resolver are not read either.

Two of the readers it shares with dispatch are public for a transport building its own answer: seed_named_parameters, the reflected reads a seed fills and the parameters dispatch refuses, and provider_reached, every parameter a provider fills or may fill, which the shape check does not demand of the caller, less a read a provider requires itself, which it does.

A Validator field the service never receives is not among the refusals, because such a spec runs and may mean to: a Validator checking that password and confirm agree returns password alone, and its service never takes confirm, on purpose. unreceived_fields answers it instead: the fields the service takes neither by name, nor through data, nor through **kwargs, so a value sent for one is validated and then reaches the service by no route. A field named like a registered seed reaches the service through data alone. A Validator may return a field under a name other than its parameter's, as a pydantic field validated by its alias is, so a service taking a keyword nothing declared explains is answered for none of its fields, and so is one beside a kwargs provider that does not annotate its keys. The transport decides what an answer means for it. One whose tools advertise every field refuses the spec:

class AdvertisingToolRegistry(ToolRegistry):
    """A registry whose tools advertise every field, so a field nobody reads is refused too."""

    def register(self, name: str, spec: ServiceSpec | SelectorSpec) -> None:
        unreceived = unreceived_fields(spec, pool_seeds=self.pool_seeds)
        if unreceived:
            raise ImproperlyConfigured(
                f"{name} would advertise {sorted(unreceived)}, which its service never reads."
            )
        super().register(name, spec)


@dataclass
class Retitle:
    title: str
    note: str = ""


def retitle(*, title: str) -> str:
    return title


retitle_spec = ServiceSpec(
    service=retitle, permissions=[IsSignedIn()], validator=DataclassValidator(Retitle)
)

One serving the confirmation form registers it, and one listing it for an agent might warn instead.

Arguments the server supplies

A transport sometimes knows a declared parameter's value better than its caller does: an agent's toolset scoped to one project, a mount that serves one account. The caller must not choose it, and should not be asked for it. ServerArguments says so for one spec, in two parts:

  • values are the server's, and outrank the caller's. A bound value satisfies a required parameter and replaces a declared default. It takes the wire's spelling, as a caller's value would: a UUID's, a date's or a decimal's string rather than a uuid.UUID, a date or a Decimal.
  • withheld names are taken from no one. The parameter is absent, so the callable's own default answers, as for any argument nobody sent.

Each name is a parameter the spec declares, so every reader of the call sees the one value: the permission checks, the selector or service, and a kwargs provider. The binding is a value, and a transport puts it to work at three points:

def notes_by(*, author_pk: int, search: str = "", ordering: str = "title") -> QuerySet[Note]:
    return Note.objects.filter(owner_id=author_pk, title__icontains=search).order_by(ordering)


notes_by_spec = SelectorSpec(
    kind=SelectorKind.LIST,
    selector=notes_by,
    permissions=[IsSignedIn()],
    reads=Parameters.of(
        Parameter("author_pk", "integer", required=True),
        Parameter("search", "string"),
        Parameter("ordering", "string", choices=["title", "-title"], default="title"),
    ),
)


def notes_tool(user: Any) -> Callable[[Mapping[str, Any]], DispatchResult]:
    # The signed-in user's own notes, in the server's order: neither name is the caller's.
    server = ServerArguments(values={"author_pk": user.pk}, withheld=frozenset({"ordering"}))
    check_server_arguments(notes_by_spec, server)

    def call(arguments: Mapping[str, Any]) -> DispatchResult:
        context: dict[str, Any] = {}  # this call's, handed to the binding and to dispatch alike
        applied = apply_server_arguments(notes_by_spec, arguments, server, call_context=context)
        return dispatch(notes_by_spec, principal=user, arguments=applied, call_context=context)

    return call


def offered(schema: Mapping[str, Any], server: ServerArguments) -> list[str]:
    # What a transport's own schema builder lists, less the server's names.
    return sorted(set(schema["properties"]) - server.names())
  1. Where the transport is built, check_server_arguments refuses a binding that cannot mean what it says, with ImproperlyConfigured, naming the spec's callable: a name that is no top-level parameter, so not a field inside a many spec's rows; one both bound and withheld; one a pool seed occupies; a reflected read a seed fills, which binding or withholding would do nothing for; one a typed provider fills or may fill, whose answer dispatch would keep over the bound value on any call where it gives one; a withheld name no call could then do without; and a bound value its own parameter refuses, such as a uuid.UUID for a format="uuid" string. A withheld name cannot be done without when the shape check demands it (required, with no declared default, its Validator parameters relaxed on a partial spec as dispatch relaxes them) or when it is a read the callable receiving it declares with no default of its own. Dispatch applies no declared default, so the callable's is the one that answers, and a call without one would be refused as missing. Two limits of what it can see. The callable it reads a default off is the one the read is handed to - the selector, the service, or the target's selector - and not any other callable that also declares the read, such as a kwargs provider; a Validator parameter is judged by the shape check alone. And a provider whose return annotation names no keys may fill any name, so, as for server_owned_keys, it names none and a binding beside it is not refused.
  2. On each call, apply_server_arguments returns a new mapping for dispatch or adispatch. It first drops the caller's value for every bound or withheld name, before anything reads it, so a value the caller sends for a name it was never offered cannot refuse the call, "null" for an integer included. It then lays the bound values over the rest, as the shape check hands them on: a UUID in its canonical spelling. Every other key is left for the shape check, so REJECT still refuses a name nobody declared. Hand it the call_context= the call is dispatched with, as the snippet does, and the bound values are checked against what the spec declares to that call, as a Validator that opted into the call describes itself there. Step 1 has no call to read, so a name such a Validator declares only to a call is refused there: declare it to no call too.
  3. In the input schema the transport advertises, the binding is passed to spec_caller_input_schema as server_arguments, which leaves names() - the bound and the withheld together - out of the properties and out of required, beside server_owned_keys, less a many spec's list, which dispatch demands of the caller whatever a provider is annotated to fill. spec_input_schema takes no binding and lists every parameter as declared. Only the top level loses them: a binding names no row field of a many spec, which check_server_arguments refuses, so a row field sharing a bound read's name is still offered in each row.

Dispatch itself takes no binding. The helpers are synchronous and pure, and the applied mapping is ordinary arguments, so dispatch and adispatch answer it alike and the permission checks read the bound values from the first step. A transport path that skips apply_server_arguments is unbound.

A bound value that fails its own declaration is the server's mistake, so apply_server_arguments raises it as ImproperlyConfigured, with the shape check's refusal as its cause, never as InvalidArguments. A client refusal would ask the caller to fix a value it neither sent nor can see. That is where this parts from a route's captured kwargs, which are a client's 400: the client chose the URL, and nobody but the server chose a bound value.

The async entry point

adispatch takes the same steps in the same order, from async code, and apresent renders its result.

Only the run may be async def: a write's service, or a read's own selector. Every other callable a spec carries is sync-only - a permission check, a Validator, a Presenter, a selector nested in a write, extend_queryset, filter_set, an affordance's condition, the providers, the preconditions, a seed's resolver - each refused with ImproperlyConfigured naming its seat if declared async def, when the spec is built - because each may query, and because a spec is written once for both entry points: a check written async def could not be called from dispatch. The run is the one callable no step shares.

Most of them are refused when they are declared async def, with ImproperlyConfigured naming the seat: a permission check's methods, extend_queryset, filter_set, the providers and the preconditions when the spec is built, an affordance's condition when it is declared, and a seed's resolver when PoolSeeds is built. Each is called from sync code and never awaited, and its unawaited answer is truthy, so a check would allow every call and a condition would read as met. An answer still to be awaited from a plain def is refused where it is read, for a permission check, a condition, a seed and extend_queryset alike, so the call fails closed: a lambda calling an async def from extend_queryset would otherwise hand dispatch a coroutine for the queryset, and a list's value would be that coroutine.

So adispatch runs the steps in one thread-sensitive executor hop, and the run's shape decides only what joins it:

  • A sync run joins the hop, so a sync spec costs exactly one.
  • An atomic async def service joins it too. transaction.atomic is sync-only, so the transaction is opened on the executor thread and the coroutine is driven inside it, where its own ORM calls reach the connection holding the transaction.
  • A non-atomic async def run is awaited on the event loop after the hop. Holding the executor thread while it waits on the network would stall every thread-sensitive call queued behind it. Anything after it - an output selector, a read's shaping and object-level check - takes a second hop.

Every refusal before the run is made inside that hop, an affordance included: a condition on the row is a query.

from typing import Any

from django_service_specs import ServiceSpec, adispatch, apresent
from docs.examples.quickstart import IsOwner, rename_note_spec
from tests.dispatch_app.models import Note


async def rename_note_async(*, instance: Note, title: str) -> Note:
    instance.title = title
    await instance.asave(update_fields=["title"])
    return instance


# The same declaration as the sync quickstart, with an async run. The permission
# check, the selector and the Validator stay sync: adispatch runs them in one
# executor hop, and runs this service inside the transaction ``atomic`` opens.
arename_note_spec = ServiceSpec(
    service=rename_note_async,
    permissions=[IsOwner()],
    validator=rename_note_spec.validator,
    instance_selector_spec=rename_note_spec.instance_selector_spec,
    presenter=rename_note_spec.presenter,
)


async def rename_from_a_worker(user_id: Any, arguments: dict[str, Any]) -> Any:
    result = await adispatch(arename_note_spec, principal_id=user_id, arguments=arguments)
    if result.kind == "not_found":
        return None
    return await apresent(arename_note_spec, result)

adispatch takes exactly one of principal and principal_id. A queue carries an identifier, not a user, so a worker passes principal_id; it is resolved with resolve_principal inside the hop, since resolving it is a query, and a missing or deactivated user is refused with PrincipalUnavailable. A grant never covers a principal resolved there, because a grant is bound to the principal object it was made for, and neither do seeds handed on from a prelude, which adispatch(seeds=) takes as dispatch does on every route, refusing a mistyped one or one without a grant before any hop. Seeds with principal_id= are refused the same way, as a TypeError before any hop, since the principal resolved there is not the one the carrier is bound to; pass the principal= the prelude was handed. A deactivated row is refused inside the hop, with its identifier in the message.

The sync dispatch accepts an async def run as well, and drives it to completion, inside the transaction when the spec is atomic. run_service and arun_service are that bridge, exported for a transport that calls a service directly.

Pool seeds

Off HTTP there is no request for ambient values to hang off: a tenant, a correlation id, a locale, a clock. A PoolSeeds registry is that channel. Each registration is a name and a resolver, and the resolver's value is in every pool dispatch builds - the service's, each selector's, extend_queryset's - for any of them to declare:

seeds = DEFAULT_POOL_SEEDS.extend(signature=lambda *, user: user.get_username())


def sign_note(*, user: Any, title: str, signature: str) -> Note:
    return Note.objects.create(owner=user, title=f"{title}, by {signature}")


sign_note_spec = ServiceSpec(
    service=sign_note,
    permissions=[IsSignedIn()],
    validator=DataclassValidator(Rename),
)


def create_signed_note(user: Any, title: str) -> DispatchResult:
    return dispatch(sign_note_spec, principal=user, arguments={"title": title}, pool_seeds=seeds)

A resolver declares what it wants from the pool like any other callable, and sees the principal, never an argument: a seed is ambient, and a caller must not steer one by naming an argument after something its resolver reads. A resolver is sync-only: an async def one is refused with ImproperlyConfigured when it is registered, and a plain def handing back an awaitable is refused where it is resolved.

A registered name is reserved, and that is half of what registering does. A spec that declares a parameter by that name is refused at dispatch with ImproperlyConfigured, and by check_seeds where a transport registers it; a caller that sends it is refused like any other undeclared argument; and PoolSeeds refuses one of the dispatcher's own names, or a name registered twice, with ValueError, from extend() and from the constructor alike. Either half alone is a trap: a value with no reservation would share the pool with an argument of the same name, and a reservation with no value would fail the callable that declares it.

The call's request and view

dispatch and adispatch hand two values to every callable they bind that names one, read off the call's context: CALL_SEEDS, request and view. Each is the very object the transport put in call_context under that key, and None where it put none, so a spec callable written for HTTP binds on every route and learns from a None that the call came from no request. Every stage is handed them by declaring them: a seed's resolver, the selectors (the target selector on every route, resolve_target included), extend_queryset, a FilterSet, the providers, a FormValidator's form_kwargs, the affordance conditions, the preconditions, the run's progress_reporter, the service, the output selector, and the row services and callable scopes of a nested write.

They are handed by name only, as call_context itself is: a **kwargs catch-all is handed neither, and neither is a pool entry, so the Validator's ambient holds neither and a Validator reads them off its context's call_context. A seed's resolver may declare them; the commonest seed, a tenant read off the request, is tenant=lambda *, request: request.tenant. The three authorize functions offer both to a permission check that declares one, and form_keywords and the affordance functions read them off the call_context they are handed, so a page or a listing asks what dispatch would.

A service spec's read, its target selector's or its shape named request or view is refused with ImproperlyConfigured when the spec is built. A selector spec dispatched on its own is refused at dispatch instead, on every route, for a read or a shape of either name, and so is a many spec's list of either name. A selector spec is not refused when it is built, because it is also built where its parameters are no call's: as an output selector, whose reads never become the call's arguments and whose selector is handed the call's own value by name, and for shape_queryset, where a FilterSet's filter named view is a filter like any other. A kwargs provider or an extra_kwargs key of either name is refused at dispatch, on every route. A read marked reflected is not refused: the call's value fills it, as a registered seed fills one named like it. A shape is refused though it is marked, since no seat fills a shape. The refusal when the spec is built ends with 'request' and 'view' are the call's own, read off its context., as dispatch's does on a mount registering no seed of either name; where one is registered, dispatch's refusal names the seed instead. A top-level Validator field of either name is the caller's: it takes a registered seed's seat, as below, validating into data while a service naming it reads the call's own. Neither name is in RESERVED_POOL_SEEDS or PoolSeeds.reserved, so a mount may still register either through PoolSeeds, by the constructor or extend(), as transports released before dispatch supplied them do. Such a mount keeps its own: the registered seed is a pool entry, the value at every stage and every check, and a **kwargs catch-all is handed it as any seed; another seed's resolver still reads the call's.

Two declarations of a seed's name are not refused, because neither shares the pool with an argument. A read marked reflected=True is one an adapter took off a callable's signature rather than one an author wrote, such as a selector's signature parameter a project's seed is meant to fill. The seed fills it on every call: the read is no argument of the call, so a caller sending its name is refused as unknown under REJECT and dropped under IGNORE, and its value never reaches the pool. An unmarked read, or a shape, by that name is still refused.

def notes_signed_by(*, user: Any, signature: str) -> QuerySet[Note]:
    return Note.objects.filter(owner=user, title__endswith=f", by {signature}")


# The read is marked reflected, so the registered ``signature`` seed fills it
# on every call: it is no argument of the call, and a caller naming it is
# refused as an unknown argument.
signed_notes_spec = SelectorSpec(
    kind=SelectorKind.LIST,
    selector=notes_signed_by,
    permissions=[IsSignedIn()],
    reads=Parameters.of(Parameter("signature", "string", required=True, reflected=True)),
)


def my_signed_notes(user: Any) -> DispatchResult:
    return dispatch(signed_notes_spec, principal=user, arguments={}, pool_seeds=seeds)

A top-level Validator field by a registered seed's name, on a service spec that is not many, stays the caller's argument. It is validated into data and never spread into the service's pool, so the service reads the caller's value on data and the seed's under its own name. A field named like one of the dispatcher's own names is still refused when the spec's parameters are assembled.

@dataclass
class Countersign:
    title: str
    signature: str  # the caller's own: validated into ``data``, never the pool


def countersign(*, user: Any, data: Countersign, signature: str) -> Note:
    # ``signature`` is the seed's, whatever the caller sent under that name.
    return Note.objects.create(
        owner=user, title=f"{data.title}, by {data.signature} for {signature}"
    )


countersign_spec = ServiceSpec(
    service=countersign,
    permissions=[IsSignedIn()],
    validator=DataclassValidator(Countersign),
)


def create_countersigned_note(user: Any, title: str, signature: str) -> DispatchResult:
    return dispatch(
        countersign_spec,
        principal=user,
        arguments={"title": title, "signature": signature},
        pool_seeds=seeds,
    )

PoolSeeds is immutable and extend() returns a new registry, so pass one per dispatch rather than installing one process-wide: two mounts with different ambient context need them to differ. An adapter that builds a pool of its own builds it with base_pool and binds a callable with resolve_callable_kwargs, the declare-to-receive rule every callable here is called through. A transport with a call context builds it with seeded_pool instead, rather than spreading its own request beside a registered seed, which base_pool refuses: a resolver declaring request or view reads the context's, a seed registered under either name is the value, and the context itself is not in the pool that comes back.

# A seed registered under ``request``: what a service reads from the request, not
# the request itself.
request_seeds = DEFAULT_POOL_SEEDS.extend(request=lambda *, request: request.META["REMOTE_ADDR"])


def pool_for(user: Any, request: Any) -> dict[str, Any]:
    return seeded_pool(user=user, seeds=request_seeds, call_context={"request": request})

Progress

progress= on dispatch and adispatch takes the transport's own ProgressReporter: a callable taking how far along, and optionally total, message and meta. It is seeded under the reserved name progress, as it is, into the pool of the call's run - the service, or a read's own selector - and of that spec's callable affordance conditions. A reporter must not raise, because nothing between it and the service catches it. Under adispatch a sync run calls it on the executor thread, and an async def run on an event loop.

def retitle_all(*, user: Any, title: str, progress: ProgressReporter) -> int:
    notes = list(Note.objects.filter(owner=user).order_by("pk"))
    for done, note in enumerate(notes, start=1):
        note.title = title
        note.save(update_fields=["title"])
        progress(done, total=len(notes), message="retitling notes")
    return len(notes)


retitle_all_spec = ServiceSpec(
    service=retitle_all,
    permissions=[IsSignedIn()],
    validator=DataclassValidator(Rename),
)


def retitle_all_reporting(user: Any, title: str, report: ProgressReporter) -> int:
    # The transport's own reporter; with none, the service gets null_progress.
    result = dispatch(retitle_all_spec, principal=user, arguments={"title": title}, progress=report)
    return result.value

With no reporter the pool carries null_progress, so a service that declares progress runs unchanged on every transport and in tests. A transport with more than one sink of its own - its client channel beside a task record - hands dispatch combine_progress of them: every sink hears each report, and one that raises neither silences the rest nor reaches the service. A spec's own progress_reporter provider adds a sink of the author's beside the transport's - a task record, an audit trail - for the run alone, and only for a run that takes progress: called on its first report, or before an async def run once nothing before the run can refuse the call. A call refused before its run never calls it, a selector spec's whose selector is refused a read the caller left out included. A selector spec's selector is its run, though, and its object check, scope check and preconditions answer what the run returned, so a selector spec refused at one of those may already have called it. The selector spec's affordance conditions, extend_queryset and preconditions read the transport's reporter, as a service spec's do. A target or output selector always gets null_progress: a lookup has nothing to report, and one reporting after the service finished would read to a watching client as the work restarting.

The call's shapes

shapes is a reserved seed, as progress is: what the caller sent for the spec's declared shapes, keyed by shape name and read-only. It is the mapping the presenter reads as PresentationContext.shapes, so a selector that eager-loads by what the presenter will render, as django-restql's query does, reads the value the presenter reads. Any callable dispatch resolves receives it by naming it: a selector and its extend_queryset, a kwargs or input_data provider, a precondition, the run's progress_reporter, the service, and a service spec's output selector, which is handed the write's shapes. Its target selector is the exception, and is handed an empty mapping (see the last item below).

  • Always there. A spec declaring no shapes hands an empty mapping, and a shape the caller left out is absent from it rather than None, as on the presenter's context. A reservation with no value would fail the callable that declares it.
  • By name only, as call_context is: a callable taking **kwargs is never handed it, so a selector forwarding its keywords into filter() runs unchanged.
  • Never the caller's. It is in server_owned_keys, and a parameter, read, shape or many list named shapes is refused when the spec is built, a Validator field of that name when the spec's parameters are first read (a transport's registration, or the first dispatch). Each of those refusals carries the rename in its message: name the parameter for what it holds, such as fields or query, and have the callable that read it declare shapes. PoolSeeds refuses a seed of that name, built directly or through extend(), and says to register it under another.
  • Not for an affordance condition or the Validator. A condition naming shapes is refused when it is declared, because what the caller sent would decide whether the operation is available, and the Validator, which is no pool callable, reads only its own arguments. Neither context's ambient holds it.
  • Empty for a target selector. A write's target lookup is handed no shapes, on every route. resolve_target checks the target selector's own parameters alone, so a shape sent there is no argument of the lookup, and a lookup that read the shapes under dispatch would find a different row from the one resolve_target found. A target selector that names shapes is not refused, since it is often a read's own selector reused: it receives an empty mapping, and the row it finds is the row dispatch finds.

A selector joining only what the caller chose is shown under shaping each row by the call.

The call's context

A call's stages often want one value more than once: a lookup the Validator makes and the presenter needs again, a count across the rows of a list. A seed is resolved from the principal before the stages run; the call's context is for what a stage computes as it goes. It is one plain dict, the transport's, created for its natural scope - a request, an agent run - and carried as call_context on both ValidationContext and PresentationContext.

  • One object, never copied. The Validator and the presenter are handed the same dict, as are every row of a "list" result and a nested presenter a presenter hands its context on to, so a later stage reads what an earlier one put there.
  • The stages', to read and write, as a DRF serializer's context is. The kernel writes nothing to it, and unlike ambient it is not read-only.
  • A context built by hand gets an empty dict of its own, never one shared with another context, so a stage that writes to it needs no guard for a call that was handed none.
  • It takes no part in equality or the hash, as ambient does not, and it comes after the fields each context had before it, so an existing construction is unchanged.

Every stage shares the one dict, so key what a stage keeps by something of its own, and cache a computed value under setdefault: it hands back what an earlier stage put there, or puts the default and hands that back. The default is evaluated either way, so make it a container to fill rather than the computation itself, as the forms adapter's example does.

Handing dispatch the call's context

dispatch, adispatch, check_call, bind_arguments and resolve_target take the transport's dict as call_context=, and make a fresh one for the call when none is passed:

class FromBackOffice(PermissionCheck):
    message = "Only the back office may archive a note."

    def has_permission(self, principal: Any, spec: Any, *, call_context: dict[str, Any]) -> bool:
        return call_context.get("client") == "back-office"


def archive_note(*, user: Any, pk: int, call_context: dict[str, Any]) -> Note:
    note = Note.objects.get(owner=user, pk=pk)
    note.archived = True
    note.save(update_fields=["archived"])
    # Left for whatever stage of the request comes next.
    call_context.setdefault("archived", []).append(note.pk)
    return note


archive_note_spec = ServiceSpec(
    service=archive_note,
    permissions=[IsSignedIn(), FromBackOffice()],
    reads=Parameters.of(Parameter("pk", "integer", required=True)),
)


def archive_from_back_office(user: Any, pk: int) -> dict[str, Any]:
    # One dict per request, created by the transport and filled as it likes.
    context: dict[str, Any] = {"client": "back-office"}
    dispatch(archive_note_spec, principal=user, arguments={"pk": pk}, call_context=context)
    return context

The same object, never a copy, reaches every callable that names call_context: a kwargs or input_data provider, a selector of any role and its extend_queryset, an affordance condition, a precondition, the service, the run's progress_reporter, FormValidator's form_kwargs, a permission check's methods, the Validator's and the presenter's contexts, and a PydanticValidator's field validators, on pydantic's info.context beside principal and target. So the back office's dict above comes back holding what the service left there.

  • By name only. A callable taking **kwargs for the rest of the pool is never handed it, so a catch-all forwarding what it gets runs as it did before the name existed. One that wants it names it.
  • A reserved name, in RESERVED_POOL_SEEDS: a seed, a provider's key, an overlay or an argument named call_context is refused. Seed resolvers do not see it, since a seed is resolved before anything the call adds.
  • Dispatch pre-fills nothing. What goes in is the transport's convention: a transport over DRF is expected to put DRF's request there, and a key such as request, view or format means what the transport that wrote it says. Dispatch writes nothing to it and keeps nothing across calls. It reads two keys, request and view, for a callable naming one (the call's request and view). One more key is the family's: transport, which names the transport that built the dict (reading which transport is calling).
  • Calls sharing one dict. The stages of one call run in sequence. A transport handing one dict to calls on several threads should have them write by compute-if-absent: read with get, and on a miss compute the value and store it with call_context.setdefault(key, value), so the first write wins and every call reads one value. Fit for a value any of them would compute the same.
  • The Validator's declaration is asked with it. A Validator declaring parameters(self, *, call_context=None) is handed the call's dict on every ask of its parameters() inside the call - the shape check, the seed check, validation and the service's keywords alike - and None on every ask outside one, such as registration or a schema handed no context (the Validator). So a transport describing a serializer under its own request can tell its own call from a dispatch the service makes inside it, which is handed a dict of its own. A transport asking the Validator itself during the call does so through validator_parameters, handing it the same dict.
  • An inner dispatch handed the outer dict is described as the outer call. A service that forwards its own call_context to a dispatch it makes for another principal or operation has every stage of that inner call - its Validator's declaration included - read what the outer call put there, and a transport keyed on the dict describes the inner call as its own. Hand an inner dispatch a fresh dict, or none, unless it is meant to be the same call.

The affordance functions a transport calls ahead of the call or in place of dispatch - unmet_operation_affordance, enforce_affordances and their async twins - take call_context= too, for a condition that names it: the dict passed, else the one the pool carries, else a fresh one. Handed one dict as the parameter and a different one in the pool, they refuse with ImproperlyConfigured rather than choose.

Reading which transport is calling

A stage that answers one transport differently from another - a condition, a provider, a presenter - reads one key whichever transport it runs under: TRANSPORT_KEY, read with call_transport.

def note_heading(*, user: Any, pk: int, call_context: dict[str, Any]) -> str:
    note = Note.objects.get(owner=user, pk=pk)
    if call_transport(call_context) == "agent":
        return note.title
    return f"Note: {note.title}"


note_heading_spec = ServiceSpec(
    service=note_heading,
    permissions=[IsSignedIn()],
    reads=Parameters.of(Parameter("pk", "integer", required=True)),
)


def heading_for_an_agent(user: Any, pk: int) -> tuple[str, dict[str, Any]]:
    context: dict[str, Any] = {"client": "back-office"}
    context[TRANSPORT_KEY] = "agent"
    result = dispatch(note_heading_spec, principal=user, arguments={"pk": pk}, call_context=context)
    return result.value, context

Each transport package owns the string it stamps and states it in its own documentation, so a new transport needs no kernel release.

The contract, for a transport writing it and a stage reading it:

  • The transport that builds a context stamps it, last. Its own name is the last thing it writes to the dict, replacing any entry there, on every call it builds. So the key names who built this call's context and not how the call arrived: an agent run that came over HTTP and carries its request reads "agent" when the agent's tools serve it, and an MCP call django-spec-agents proxies in process reads "mcp", because django-spec-mcp's handler builds that context.
  • Nothing a client sends reaches it. A transport builds the dict on the server and stamps it last, so an entry a caller smuggled in would be overwritten, and a stage may branch on what it reads.
  • A stamp is the plain string, "agent" and not a wrapper of it. So call_context["transport"] == "agent" holds with nothing imported, and the value serializes as itself. Compare it with ==.
  • A missing key means an in-process caller: a dispatch made directly, from a script, a shell or a test, or by a service handing an inner call a dict of its own. call_transport returns None there, and for a Validator's parameters() asked outside a call, which is handed no dict, unless a transport describing a spec hands a stamped dict with no call under way.
  • The schema a transport offers is read under its stamp too, when the transport hands spec_caller_input_schema its dict, so a stage's field for one transport is offered there (a field declared to one transport).
  • A transport stamps from the release that adopts the key. Until a transport's release does, its calls read as missing too, and a stage cannot tell them from an in-process caller, so check the release of each transport you run before branching on None.
  • The values are not a closed set. A third-party transport stamps a string of its own, and the reader hands back whatever was stamped, so a stage compares a stamp to the strings it cares about and treats any other as a transport it does not know.
  • Dispatch neither writes nor reads it. It runs the same with the key or without, and it is not a reserved name: a seed or an argument may be called transport, in a different namespace from this dict.

A transport builds the dict with build_call_context, which keeps that contract in one place. It returns a new dict holding every entry of the base it is handed, such as an agent run's own dict, and the four standard entries, request, view, format and action, each None where nothing gave one, so call_context["action"] never raises on a transport that builds through it. An argument wins over the entry of its name in base, an argument left at None leaves that entry, and the transport's string goes in last, over any transport the base carried. base is never changed, and the result is a fresh plain dict for the transport to keep: one that hands every callable of a request the same dict builds it once. A None entry binds as a missing one, so a callable declaring request is handed None either way.

def heading_for_a_tool_call(
    user: Any, pk: int, run_context: dict[str, Any]
) -> tuple[str, dict[str, Any]]:
    context = build_call_context("agent", base=run_context, action="note_heading")
    result = dispatch(note_heading_spec, principal=user, arguments={"pk": pk}, call_context=context)
    return result.value, context

Answering every refusal

Dispatch refuses in two families, and a transport answers each refusal in its own vocabulary: an exit code, an HTTP status, the state a background run ends in. Those vocabularies stay the transport's, and one check is shared: unanswered_refusals says what a map leaves unanswered of REFUSALS, every refusal the kernel defines, so a transport holds its map total from its own test suite:

from django_service_specs import (
    AdditionalInputRequired,
    DispatchError,
    NotPermitted,
    PrincipalUnavailable,
    ServiceConflict,
    ServiceError,
    ServiceNotFound,
    unanswered_refusals,
)

OUTCOMES = (
    (NotPermitted, "denied"),
    (PrincipalUnavailable, "denied"),
    (DispatchError, "invalid"),
    (ServiceNotFound, "gone"),
    (ServiceConflict, "conflict"),
    (ServiceError, "refused"),
)
"""Read top to bottom, first match wins, so each subclass sits above its base."""


def outcome_for(error: BaseException) -> str:
    """The outcome a run that raised ``error`` ends in: ``failed`` for anything undeclared."""
    return next((outcome for kind, outcome in OUTCOMES if isinstance(error, kind)), "failed")


NO_QUESTIONS = ((AdditionalInputRequired, "failed"), *OUTCOMES)
"""For a queue with nobody to ask: a run that needs more input fails like a bug."""


# In the transport's own test suite:
def test_every_refusal_has_an_outcome() -> None:
    assert unanswered_refusals(OUTCOMES) == ()
    assert unanswered_refusals(outcome_for, unanswered="failed") == ()


def test_the_queue_leaves_one_refusal_unanswered_on_purpose() -> None:
    # Filtered by class, never by the finding's words.
    found = unanswered_refusals(NO_QUESTIONS, unanswered="failed")
    assert [finding for finding in found if finding.refusal is not AdditionalInputRequired] == []

It takes the map as it is written. An ordered table of (refusal class, outcome) rows is read the way an isinstance ladder reads it, top to bottom with the first match winning, so a row for a base answers every refusal under it. A row whose outcome is the unanswered= value is no answer: a refusal it catches first stays unanswered whatever a later row says. A callable written as branches is passed as it is, with unanswered= naming the value it falls back to; a mapping looked up by an error's exact class is a callable too, lambda error: table.get(type(error)), since reading its keys as ordered rows would let a base answer for a subclass the lookup never reaches.

Each finding is a RefusalFinding: the refusal it is about, its RefusalFindingKind (UNANSWERED, BARE_BASE or SHADOWED_ROW), and for a shadowed row the row above it. A transport that leaves a gap on purpose filters the findings by refusal or kind, as the queue above does with NO_QUESTIONS, and never by their words: str() of a finding is the sentence quoted below, and the wording is free to change.

Two traps make a map look complete when it is not, and each has its own finding. Either base may be raised bare: the kernel raises neither a plain DispatchError nor a plain ServiceError itself, but both are public classes a project's own code may raise, so a map with a row for every refusal under a base and none for the base leaves it unanswered:

nothing in the map answers DispatchError itself, though it answers every refusal under it, and DispatchError may be raised bare

A subclass below its base never answers: in an ordered table, the base's row catches it first, so the subclass's row is dead and the subclass takes the base's outcome:

the row for ServiceConflict never answers: the row for ServiceError above it answers every ServiceConflict first

The second is reported for a table only. A callable written as branches orders them in code, and a branch for a subclass below its base's is a body that never runs, which the transport's own branch coverage reports; a table's order is data, which coverage reads as one expression.

A refusal a transport defines itself, such as django-spec-html's UnsupportedMediaType, is not in REFUSALS: that transport maps it and tests it. Its row is still read for the precedence trap, since a row nothing reaches is dead whoever's refusal it names.