Skip to content

API reference

Everything below is exported from django_spec_tasks directly, except the two backends, which stay on their own paths because each imports an optional queue. Kernel names a binding reads, such as SpecRegistry and resolve_principal, are documented on the kernel's site.

System checks

Registered by the app's config, so a project gets them by listing "django_spec_tasks" in INSTALLED_APPS.

  • django_spec_tasks.E001: a database router sends SpecRun away from the default alias, for reads or for writes. The kernel's transaction opens on the default alias, and the worker needs the row inside it.

Management commands

Calling

enqueue

enqueue(
    binding: TaskBinding, spec_name: str, params: Mapping[str, Any], *, actor: Any
) -> str

Record a run of spec_name and ask the binding's backend to execute it on commit.

Everything that can be refused while the caller is still on the stack is refused here, and a refusal writes no row and sends nothing. What is left is decided by the worker, which checks again through the kernel's dispatch: a grant cannot cross a process, so none is carried.

actor is required. None is the declared system run, which a spec admits or refuses by its own permissions; leaving it out is a TypeError, so an unauthenticated call cannot become a system run by omission.

A file parameter takes the key of a file default_storage holds, at any depth, and the worker hands the Validator that file opened. The Validator does not run here. A stock one queries, needs the row it acts on, and its answer would not hold by the time a worker ran.

Returns:

Type Description
str

The run's id, as a string. A backend that carries a task id is given this one.

Raises:

Type Description
LookupError

The binding's registry holds no spec of that name.

TypeError

A file parameter is given something other than a storage key, or a key default_storage does not hold or refuses to look up; actor is a principal with no primary key (an anonymous user); or params or the carried values would change on their way through JSON.

PrincipalUnavailable

actor is deactivated.

InvalidArguments

params do not fit the spec.

NotPermitted

actor fails the spec's class-level permissions.

ImproperlyConfigured

The spec presents a list of files, which no transport serves; or a parameter collides with one of the binding's pool seeds.

read_run

read_run(binding: TaskBinding, run_id: str, principal: Any) -> RunStatus

What principal may see of a run: its status, never what it was asked.

The call's params and its presented output are as sensitive as the call itself, so the default reader is the run's owner. binding.can_read(principal, run) widens that. A principal that is deactivated is refused either way: it never acts.

A run that is not this principal's, an id nobody wrote, a malformed id and another binding's run all raise the same NotPermitted with the same message, so an id cannot be probed for whether it exists. A system run has no owner, so only can_read reads it.

Raises:

Type Description
NotPermitted

For every refusal above.

state_of

state_of(binding: TaskBinding, run_id: str) -> RunState | None

The state of one of binding's runs, with no principal asked.

For a caller that is trusted, such as a queue reporting on a run it enqueued. It answers None for an id that is not this binding's, or not an id at all. Anything a person may reach goes through read_run.

Binding

TaskBinding dataclass

A registry served as background tasks, with everything a queue needs beside it.

Collaborators are objects passed here, never dotted paths in settings. A seam that takes a run is handed the SpecRun row, typed Any because nothing here imports a model: that is what keeps this class importable before the app registry is ready.

Constructing one registers it under its name, since a worker has only the name a row recorded. Autodiscovery of each installed app's spec_tasks module is what makes every binding known in a worker that imported Django. A file the kernel says no transport serves (a list of files) is refused here, and at enqueue for a spec registered later; a single file is saved to default_storage by the worker.

Attributes:

Name Type Description
name str

Recorded on every row, so it must not change while runs are pending.

registry SpecRegistry

Where enqueue and the worker find a spec by name.

backend TaskBackend

Where a run's code executes.

resolve_actor Callable[[str], Any]

Turns a row's actor_pk into the principal. Raises PrincipalUnavailable for anyone who may no longer act.

pool_seeds PoolSeeds

The same set at enqueue and in the worker, so the prelude's seed check agrees between them.

lease timedelta

How long a claimed run may take. Sized to the binding's longest run: a worker past it is refused at its terminal write.

grace timedelta

How long a PENDING row waits, from the last time a backend was asked for it, before the sweep asks again. Sized to how long the queue may back up: each ask past it is one more message.

max_attempts int

How many claims an idempotent run gets before it is abandoned.

max_output_bytes int

Past this, a run ends OUTPUT_TOO_LARGE. Output is never truncated.

can_read Callable[[Any, Any], bool] | None

(principal, run) -> bool, consulted beside the run's owner.

progress_using str | None

A database alias progress is written through, which is what makes it visible during an atomic=True run. A second connection to the same database: on any other it finds no row, and writes nothing.

carry Callable[[Any], Mapping[str, Any]] | None

(actor) -> JSON mapping, recorded on the row at enqueue and handed to the call context in both processes.

around_run Callable[[Any, Any], AbstractContextManager[Any]] | None

(run, principal) -> context manager around dispatch and present.

on_finish Callable[[Any], None] | None

(run) -> None, inside the transaction of the terminal write.

named classmethod

named(name: str) -> TaskBinding | None

The binding registered under name, or None.

A row naming no binding is a rolling deploy rather than a bug, so an unknown name is an answer here and not an exception.

clear_registry classmethod

clear_registry() -> None

Forget every binding: the one way a test suite empties the registry.

Backends

TaskBackend

Bases: Protocol

Where a run's code executes.

The row is the record, so a backend may lose a message without consequence: the sweep asks again. It may also deliver one twice or late, and the claim stops the second copy. That is what keeps this a single method, and what lets one protocol hold Django Tasks and Celery.

enqueue

enqueue(run_id: str) -> None

Arrange for run_spec(run_id) to be called somewhere.

CeleryBackend

Hands a run to a Celery worker.

queue names the queue to send to; None leaves routing to the project's task_routes, keyed by the stable task name. The package sets no retry, no late acknowledgement, no result backend and no schedule, each because the row already answers it: a second copy of a message finds the claim taken, a lost one is asked for again by the sweep, and the result is on the row.

enqueue

enqueue(run_id: str) -> None

Send the run, with its id as Celery's task_id so a log line names the run.

DjangoTasksBackend

Hands a run to Django's Tasks framework.

Name the backend in the binding; it is never chosen by what imports. django.tasks imports on any Django 6, and its default backend runs a task inline on the caller's thread, so choosing by availability would pick that in a project running Celery.

alias is the TASKS entry to send to, queue the queue on it; None leaves the framework's default. The module's task is built against the default entry, as any @task is, so TASKS needs one.

enqueue

enqueue(run_id: str) -> None

Send the run to the aliased backend.

The worker

run_spec

run_spec(run_id: str) -> None

Run the row run_id names, once, whatever number of messages name it.

Both backends call this. It returns nothing, and no retry policy of a queue's applies: whether a run may run again is read from the row, by the sweep.

A message for a row that is not PENDING costs one query and runs nothing. Otherwise the row is claimed, the principal resolved, and the spec called through the kernel's dispatch and present, so the worker re-checks everything enqueue checked and the Validator runs for the first time. The row ends in the state run_state_for gives what was raised, or in SUCCEEDED with what was presented, or in OUTPUT_TOO_LARGE. A service whose target is gone never ran, and ends REFUSED; a selector finding nothing has answered, and ends SUCCEEDED, each with kind="not_found".

Under atomic=True one transaction holds around_run, dispatch, present, the terminal write and on_finish, so the service's work and the row's state commit as one fact, and a worker that dies before the commit has left nothing but a RUNNING row. A refusal rolls that transaction back first, then writes its state and runs on_finish in a transaction of its own. Under atomic=False, and for a selector, no transaction surrounds the call, and only the write and on_finish share one.

A write finding the row is no longer this attempt's writes nothing and rolls its own transaction back: a worker that lost its claim cannot commit.

Only an Exception is an ending. A BaseException is the worker dying, and passes through untouched, as does anything on_finish raises: both leave the row RUNNING. The sweep answers a dead worker's. It calls the same hook, so a hook that always raises keeps its row RUNNING until it stops raising.

run_state_for

run_state_for(error: BaseException) -> RunState

The RunState error ends a run in.

Every refusal has one, a subclass a later release adds included: it takes its nearest listed base's, so a new refusal of the call is INVALID and a new refusal by the operation REFUSED. Anything else is FAILED: an exception nobody declared is a bug, and FAILED is never the answer to a refusal.

Operating

sweep_runs

sweep_runs(*, limit: int = 1000, batch_size: int = 100) -> SweepReport

Answer the runs the queue lost and end the ones whose worker did not come back.

Run it on a schedule the project owns: a beat entry, cron, the platform's scheduler. This package ships none, because whether a queue is one's own is not for a library to assume.

Each row's outcome:

  • PENDING, grace past its last ask: the backend is asked again; the claim stops a second run.
  • RUNNING past its lease, spec declares idempotent=True, attempts to spare: back to PENDING and the backend is asked.
  • The same, with attempts >= max_attempts: ABANDONED, because a poison run must not loop.
  • The same, with idempotent False or undeclared: ABANDONED.
  • Either, with the binding or the spec gone: SPEC_UNAVAILABLE.

idempotent is read off the registered spec now, never off the row, so a spec whose declaration changed answers with what it declares today. None is undeclared and does not read as True.

Every transition is a compare-and-swap on (state, attempts), so two sweeps agree and a worker that claimed the row meanwhile is not overwritten. An ask is stamped on asked_at before the backend hears it, conditioned on the value read as well, so two sweeps send one message, and a row waits out its grace again whether or not the backend took it. A backend that raises is counted in errors, and the sweep carries on.

on_finish runs for ABANDONED and SPEC_UNAVAILABLE in the transaction with the write. One that raises takes the write back: it is counted in errors, and the row stays as it was, on every sweep, until the hook stops raising.

Each binding is walked apart, its lapsed rows first and then its pending ones, longest waiting first, batch_size at a time, and limit is its own, so a binding whose queue is dead or whose hook is broken holds back nothing but itself.

Parameters:

Name Type Description Default
limit int

The most rows one sweep looks at for one binding.

1000
batch_size int

How many rows are read from the database at once.

100

Returns:

Type Description
SweepReport

What was done, counted by outcome.

prune_runs

prune_runs(*, older_than: timedelta, batch_size: int = 1000) -> int

Delete runs that finished more than older_than ago, and no others.

A run that is still PENDING or RUNNING is never deleted, however old: it is the sweep's to answer, and deleting it would lose work. A finished run without a finished_at is left too, since there is no age to measure. Retention is the project's call, so there is no default age.

Parameters:

Name Type Description Default
older_than timedelta

How long ago a run must have finished.

required
batch_size int

How many rows one delete takes, so no statement is unbounded.

1000

Returns:

Type Description
int

How many rows were deleted.

Admin

SpecRunAdmin

Bases: ModelAdmin

Runs, to look at and never to change.

Nothing here adds, changes or deletes a row, and there are no actions: an admin action skips the change permission, so an action that deleted would delete for a user who could not. params, carried and output hold what the call was given and what it returned, so they are hidden, and refused as URL lookups, since a count of results would answer a guess; a project that wants them in its admin sets show_payloads on a subclass. The traceback shows, because triage needs it.

Types and the row

SpecRun

Bases: Model

One call of a spec: what was asked, whose claim it is under, and how it ended.

Every column is the call or the queue's bookkeeping about it, and none copies a declaration: idempotent and atomic are read from the registered spec. All of them land in the first migration, since a column added later is empty for every earlier run.

output and refusal_detail hold what a presenter and a refusal produced, so they encode through DjangoJSONEncoder: a refusal's messages may be lazy strings, and a spec with no presenter hands back its value as it is. params and carried keep the default encoder, because enqueue asserts that they survive a JSON round trip.

state is indexed by the three composite indexes, each leading on it.

RunState

Bases: TextChoices

Where a run is. PENDING and RUNNING are live; the rest are terminal.

A state stays coarse: the row's refusal_class and refusal_code say which refusal ended a run. The whole table lands in the first release, because a state added later is missing from every run before it.

Each value spells its name, so a value read back off a row as a plain string compares equal and hashes equal, and run.state in TERMINAL_STATES holds.

TERMINAL_STATES module-attribute

TERMINAL_STATES: frozenset[RunState] = frozenset(RunState) - {
    RunState.PENDING,
    RunState.RUNNING,
}

Every state a run does not leave. A run in one is what pruning may delete.

RunStatus dataclass

What a reader of a run is shown: how it went, and none of what it was asked.

params, carried, traceback, actor_pk and refusal_class are left out on purpose. The call's arguments are as sensitive as the call, a traceback names code, and the owner is who is asking.

SweepReport dataclass

What one sweep did, counted by outcome.

reasked is a backend call and not a transition: a PENDING row the queue seems to have lost stays PENDING. requeued, abandoned and unavailable are transitions. errors counts rows left as they were because a backend or an on_finish raised.

moved property

moved: int

How many rows changed state.