Ir para o conteúdo

tempest_fastapi_sdk.tasks

Tarefas em background sobre o TaskIQ: fila, agendador com lock e jobs persistidos.

« Tempo real e mensageria


tasks

TaskIQ-backed background task primitives.

Imports the optional taskiq package lazily so the rest of the SDK remains importable when the [tasks] extra is not installed.

TaskQueue is the recommended typed facade (tasks + scheduler folded into one object); AsyncTaskBrokerManager / AsyncTaskScheduler are the older lifecycle-only wrappers, kept for backward compatibility. The cron helpers (CronEnum / CronOffsetEnum / WeekdayEnum + builder functions) have no third-party dependency and import without the extra.

DEFAULT_POLL_SECONDS module-attribute

DEFAULT_POLL_SECONDS: float = 2.0

How often :func:run_cancellable re-reads the cancellation predicate.

Short enough that a cancel feels immediate to whoever clicked (a screen polling for status is usually on the same order), long enough that the cost is noise next to work measured in tens of seconds.

DEFAULT_HEARTBEAT_EVERY module-attribute

DEFAULT_HEARTBEAT_EVERY: Final[timedelta] = timedelta(seconds=30)

Default period between two heartbeats.

HEARTBEAT_FILE_MODE module-attribute

HEARTBEAT_FILE_MODE: Final[int] = 420

Permission bits of a written heartbeat file.

:func:tempfile.mkstemp creates 0600; a checker running as another user on a shared volume could then not read the file and would report a healthy process as unhealthy.

HEARTBEAT_FUTURE_TOLERANCE_SECONDS module-attribute

HEARTBEAT_FUTURE_TOLERANCE_SECONDS: Final[float] = 5.0

How far in the future a heartbeat may be and still read as fresh.

A little skew is normal when the writer and the checker read different clocks (two containers sharing a volume). Beyond this, a timestamp from the future is evidence of a broken clock or a forged file, and a file that "will be fresh" for hours would hide a dead process the whole time.

HEARTBEAT_SCHEDULE_ID module-attribute

HEARTBEAT_SCHEDULE_ID: Final[str] = 'tempest-heartbeat'

Fixed schedule_id of the scheduler heartbeat schedule.

Fixed rather than random so the scheduler source recognises its own schedule in pre_send and every scheduler start reuses the same id.

HEARTBEAT_TASK_NAME module-attribute

HEARTBEAT_TASK_NAME: Final[str] = 'tempest:heartbeat'

Task name carried by the scheduler heartbeat schedule.

The schedule is cancelled in pre_send every time it fires, so no message with this name ever reaches the broker and no task by this name is registered.

CANCELLABLE_JOB_STATUSES module-attribute

CANCELLABLE_JOB_STATUSES: frozenset[str] = frozenset(
    {JobStatusEnum.QUEUED.value, JobStatusEnum.RUNNING.value}
)

Statuses with work left to stop — what :meth:JobStore.cancel accepts.

STALE_JOB_ERROR module-attribute

STALE_JOB_ERROR: str = "The worker stopped responding while this job was running, and the claim budget is spent."

error written by :meth:JobStore.reclaim_stale when it gives up.

A constant rather than a per-row message because the sweep is a single UPDATE and interpolating each row's attempt count into it would mean reading the rows first — the read-then-write shape this module avoids.

STORE_OWNED_JOB_COLUMNS module-attribute

STORE_OWNED_JOB_COLUMNS: frozenset[str] = frozenset(
    {
        "id",
        "is_active",
        "created_at",
        "updated_at",
        "kind",
        "status",
        "stage",
        "progress",
        "params",
        "payload",
        "result_id",
        "error",
        "attempts",
        "max_attempts",
        "started_at",
        "finished_at",
    }
)

Columns of :class:BaseJobModel that :meth:JobStore.succeed refuses in values.

Every column the abstract model declares — its own and the four it inherits from :class:~tempest_fastapi_sdk.db.model.BaseModel. Each one either is a transition the store owns (status, finished_at, progress, payload, attempts), has a parameter of its own (result_id), or is identity (id, kind, created_at). values exists for the columns a project adds on its subclass, so letting it reach these would make succeed able to write a DONE row that says RUNNING. A test pins this set against a concrete model, so a column added to :class:BaseJobModel fails there instead of becoming writable by accident.

TERMINAL_JOB_STATUSES module-attribute

TERMINAL_JOB_STATUSES: frozenset[str] = frozenset(
    {
        JobStatusEnum.DONE.value,
        JobStatusEnum.FAILED.value,
        JobStatusEnum.CANCELLED.value,
    }
)

Statuses a job never leaves: the poll stops, the payload is gone.

DEFAULT_LOCK_NAME module-attribute

DEFAULT_LOCK_NAME = 'tempest:tasks:scheduler'

Redis key the lease lives under, when the caller names none.

DEFAULT_LOCK_TTL_SECONDS module-attribute

DEFAULT_LOCK_TTL_SECONDS = 30.0

How long a lease survives without renewal.

Long enough that a garbage-collection pause or a slow tick does not hand the lease to another replica, short enough that a replica killed mid-tick does not stall the schedule for minutes. The renew loop runs at a third of this, so two consecutive missed renewals still hold.

DEFAULT_RESULT_PREFIX module-attribute

DEFAULT_RESULT_PREFIX: Final[str] = 'tempest:results'

Key prefix for stored task results.

RedisAsyncResultBackend._task_name writes the bare task id when no prefix is given, which made results the only keys this SDK writes without a namespace — tasks/lock.py, sessions/store.py, queue/dedup.py and the response cache all carry one. Without a prefix a shared Redis cannot even be swept for these keys, so the manual cleanup is unavailable too.

Pass "" to restore the bare task id.

DEFAULT_RESULT_SERIALIZER module-attribute

DEFAULT_RESULT_SERIALIZER: Final[ResultSerializer] = 'json'

The result encoding used unless result_serializer= says otherwise.

DEFAULT_RESULT_TTL_SECONDS module-attribute

DEFAULT_RESULT_TTL_SECONDS: Final[int] = 86400

How long a stored task result lives, in seconds.

Ported from Celery's result_expires, whose default is timedelta(days=1) — read from celery.app.defaults.NAMESPACES on celery 5.6.3, not from memory.

taskiq_redis itself defaults to no expiry (result_ex_time=None, result_px_time=None, keep_results=True), so every execution used to leave a permanent key. Measured against Redis 8.2.9: a result for a task returning None occupies 144 bytes with TTL -1, and a once-a-minute cron writes 1440 of them a day. On a shared Redis running allkeys-lru that growth evicts the keys of whoever is using Redis to work — a rate limit, an idempotency marker, the scheduler lease — while the service paying for it may never read a result at all.

Pass 0 to restore the unbounded behaviour deliberately.

Hook module-attribute

Hook = Callable[[], Awaitable[None] | None]

A lifecycle callback taking no arguments. Sync or async.

LifecycleScope module-attribute

LifecycleScope = Literal['worker', 'client', 'both']

Which process a lifecycle hook runs in.

"worker" is the taskiq worker process, "client" is whoever calls :meth:TaskQueue.connect (typically the web application's lifespan), "both" is either. TaskQueue.memory() runs both sides in one process, so a worker-scoped hook fires there as well.

ResultSerializer module-attribute

ResultSerializer = Literal['json', 'pickle']

How stored task results are encoded in Redis.

"json" (the default) stores data only. "pickle" is what taskiq_redis uses on its own, and reading a pickled value runs whatever code the stored bytes name: anyone able to write the result keys (a co-tenant on a shared Redis, a leaked credential) gets code execution in the process that reads the result. It stays available as an explicit opt-in for a Redis nobody else can write.

RUNNING_STAGE_STATUSES module-attribute

RUNNING_STAGE_STATUSES: frozenset[StageStatusEnum] = frozenset(
    {StageStatusEnum.PENDING, StageStatusEnum.RUNNING}
)

Statuses with work left to stop — what :meth:StageMap.cancel accepts.

PENDING counts: the message is on the queue and the worker will pick it up, so there is something to stop even though nothing is running yet.

TERMINAL_STAGE_STATUSES module-attribute

TERMINAL_STAGE_STATUSES: frozenset[StageStatusEnum] = frozenset(
    {StageStatusEnum.DONE, StageStatusEnum.FAILED, StageStatusEnum.CANCELLED}
)

Statuses a stage does not leave on its own; only an explicit restart.

StageInterruptedError

Bases: Exception

The work was cancelled, or taken over, before it finished.

Nothing went wrong. Raised by :func:run_cancellable when the predicate says to stop, after the wrapped coroutine has already been cancelled. The handler's job is to return quietly: do not mark anything FAILED, and do not write a partial result.

The Error suffix follows the convention rather than the meaning — the same trade asyncio.CancelledError makes, which is also control flow rather than a fault.

CronEnum

Bases: BaseStrEnum

Ready-made cron expressions for the most common schedules.

Pass a member straight to @tq.cron(...) - it is a cron string, so no conversion is needed. For anything parameterized (a specific hour, weekday, day of month) use the builder functions instead.

CronOffsetEnum

Bases: BaseStrEnum

Timezone offsets for cron_offset, by place instead of digits.

A cron expression is anchored to UTC unless you pass an offset. Pick the member for your region instead of hand-writing "-03:00":

  • UTC - +00:00.
  • BRASILIA - -03:00 (BRT; most of Brazil, incl. SP/RJ/DF).
  • FERNANDO_DE_NORONHA - -02:00.
  • MANAUS - -04:00 (Amazonas / Mato Grosso).
  • ACRE - -05:00 (Acre / western Amazonas).

WeekdayEnum

Bases: BaseStrEnum

Day-of-week tokens for the cron day-of-week field.

Members carry the three-letter cron token ("MON" … "SUN") so they read clearly in a schedule and drop straight into the builder functions.

BaseDeadLetterModel

Bases: BaseModel

A terminally-failed task call, persisted for inspection + requeue.

Abstract — subclass it (setting __tablename__) in the project, or build a concrete class with :func:make_dead_letter_model. Inherits the SDK base columns (id / is_active / created_at / updated_at); created_at is when the failure was recorded.

from_dead_letter classmethod

from_dead_letter(dead_letter: DeadLetter) -> BaseDeadLetterModel

Build a row from a :class:DeadLetter.

Parameters:

Name Type Description Default
dead_letter DeadLetter

The terminal failure to persist.

required

Returns:

Name Type Description
BaseDeadLetterModel BaseDeadLetterModel

An unsaved row instance.

DbDeadLetterSink

DbDeadLetterSink(db: AsyncDatabaseManager, model: type[BaseDeadLetterModel])

A :class:DeadLetterSink that persists dead letters to the database.

Example:

>>> model = make_dead_letter_model()
>>> tq.dead_letter(DbDeadLetterSink(db, model))

Runs inside TaskIQ's on_error middleware, which swallows and logs any sink exception — so a DB hiccup never crashes the worker.

Configure the sink.

Parameters:

Name Type Description Default
db AsyncDatabaseManager

The database manager (opens its own short transaction per dead letter).

required
model type[BaseDeadLetterModel]

The concrete dead-letter table.

required

TaskInfo dataclass

TaskInfo(
    name: str,
    schedule: list[dict[str, Any]],
    retry_on_error: bool,
    max_retries: int | None,
)

One registered task's declared shape (for the inventory view).

Attributes:

Name Type Description
name str

The registered task name.

schedule list[dict[str, Any]]

The cron/interval schedule labels, or an empty list for an on-demand task.

retry_on_error bool

Whether the task opts into retries.

max_retries int | None

The attempt cap, when the task set one.

HeartbeatLoop

HeartbeatLoop(writer: HeartbeatWriter, every: float)

Rewrite a heartbeat file every period from inside one process.

The worker heartbeat: started on the worker's startup event and cancelled on its shutdown, so each worker process (and each replica) writes its own file, independent of what the broker delivers to it. What a fresh file proves is that the process is alive and its event loop is not blocked — a task that blocks the loop with synchronous work stops the beat. A task that awaits forever without blocking the loop does not; that is a task-timeout problem.

Attributes:

Name Type Description
writer HeartbeatWriter

Writes the file.

every float

Seconds between two beats.

Initialize the loop.

Parameters:

Name Type Description Default
writer HeartbeatWriter

Writes the file.

required
every float

Seconds between two beats.

required

start async

start() -> None

Start the loop on the running event loop (idempotent).

stop async

stop() -> None

Cancel the loop and wait for it to stand down.

HeartbeatWriter

HeartbeatWriter(path: str | Path)

Write a heartbeat file without ever failing the caller.

The writer runs inside the worker's heartbeat loop or the scheduler loop, where an exception would end the loop or surface in the scheduler's logs every period. A failed write is logged as a warning once, then silenced until a write succeeds again: the healthcheck reports the stale file, which is the signal an operator acts on.

Attributes:

Name Type Description
path Path

The heartbeat file.

Initialize the writer.

Parameters:

Name Type Description Default
path str | Path

The heartbeat file. Its directory must exist when the first beat is written.

required

write

write() -> bool

Write the current time to :attr:path.

Returns:

Name Type Description
bool bool

True when the file was written, False when the

bool

write failed (already logged).

BaseJobModel

Bases: BaseModel

Abstract job table — one row per unit of long-running work.

The consuming project subclasses this and picks a __tablename__, mirroring :class:~tempest_fastapi_sdk.db.outbox.BaseOutboxModel. Inherits the canonical four columns from :class:~tempest_fastapi_sdk.db.model.BaseModel (id, is_active, created_at, updated_at), so created_at is when the work was requested.

Attributes:

Name Type Description
kind str

Which work this is — the discriminator a worker branches on and a filter the interface offers. Indexed.

status str

One of :class:JobStatusEnum. Indexed, because every listing and every poll filters on it.

params dict[str, Any]

Small input, as JSON. What fits in a message.

payload bytes | None

Large input — the uploaded document a broker has no business carrying. Dropped when the job reaches a terminal state.

result_id UUID | None

The row the work produced, so the interface can navigate to it without a second lookup table.

error str | None

Why it stopped, written for the user rather than as a traceback.

attempts int

How many times the job was claimed. Incremented by :meth:JobStore.claim.

max_attempts int

Claim budget. :meth:JobStore.reclaim_stale gives up on a job that reached it instead of readmitting it forever.

started_at datetime | None

When the current attempt was claimed; None while queued.

finished_at datetime | None

When it reached DONE or FAILED.

stage str

Which part of the work is running, as the work names it. Free text, because only the work knows its own parts.

progress float

How much of the work is done, 0.0 to 1.0. Advanced by :meth:JobStore.report_progress, which refuses to move it backwards, and set to 1.0 by :meth:JobStore.succeed. A job that stopped keeps the value it had reached — the bar freezes where the work did, which is the honest picture of a reading that died at 40%.

is_terminal property

is_terminal: bool

Whether the job will never change status again.

Returns:

Name Type Description
bool bool

True for DONE and FAILED.

new_job classmethod

new_job(
    kind: str,
    *,
    params: dict[str, Any] | None = None,
    payload: bytes | None = None,
    max_attempts: int = 3,
) -> Self

Build a fresh queued job row.

Parameters:

Name Type Description Default
kind str

Which work this is.

required
params dict[str, Any] | None

Small JSON input.

None
payload bytes | None

Large binary input.

None
max_attempts int

Claim budget. Defaults to 3.

3

Returns:

Name Type Description
Self Self

A new QUEUED instance ready to add to the session.

JobAlreadyFinishedError

Bases: RuntimeError

Raised when finishing a job that already reached a terminal state.

Surfaced rather than swallowed: a second succeed or fail on the same row means two workers believe they own the job, or one worker ran the same job twice. Silently overwriting the first outcome would erase the evidence.

JobCancelledError

Bases: JobAlreadyFinishedError

Raised when finishing a job the user cancelled meanwhile.

A subclass so existing except JobAlreadyFinishedError keeps working, and a separate type because the two mean opposite things: a plain JobAlreadyFinishedError says something is wrong with your concurrency, while this one says the system did exactly what it was told. A worker that races past its last cancellation checkpoint and calls succeed should log this and move on, not alert.

The write is refused either way — a cancelled job never gets a result written over it.

JobNotFoundError

Bases: LookupError

Raised when a job id matches no row.

A LookupError rather than an :class:~tempest_fastapi_sdk.exceptions.AppException because the store runs in the worker as often as in a request, and a worker has no HTTP status to answer with. Map it at the boundary — a route that exposes job status can raise its own 404 from :func:~tempest_fastapi_sdk.not_found_exception.

JobStatusEnum

Bases: StrEnum

Lifecycle of a unit of long-running work.

  • QUEUED — the row exists, nobody has picked it up.
  • RUNNING — a worker claimed it (see :meth:JobStore.claim).
  • DONE — finished; result_id points at what it produced.
  • FAILED — stopped; error says why, in the user's language.
  • CANCELLED — the user asked it to stop (see :meth:JobStore.cancel). Terminal like the two above, but not a failure: nothing went wrong, so an interface that highlights FAILED should leave this one alone, and an alert that pages on failures should not fire.

JobStore

JobStore(
    db: AsyncDatabaseManager,
    *,
    model: type[JobT],
    stale_after: float | timedelta | None = None,
)

Bases: Generic[JobT]

Enqueue, claim and close jobs — one short transaction per call.

The store takes the :class:~tempest_fastapi_sdk.db.AsyncDatabaseManager rather than a session on purpose. Its callers are a request handler that enqueues, a worker that claims and closes, and a UI poll that asks every couple of seconds; none of them should hold a session across the long work in between — on SQLite that is exactly the read-then-write transaction no busy timeout can rescue.

Example

store = JobStore(db, model=JobModel, stale_after=300.0) job = await store.enqueue("extract", payload=pdf_bytes) await extract_task.enqueue(str(job.id))

in the worker

claimed = await store.claim(job_id) if claimed is not None: ... await store.succeed(job_id, result_id=draft.id)

Attributes:

Name Type Description
stale_after timedelta | None

How long a job may stay RUNNING before :meth:reclaim_stale considers its worker dead. None disables reclaiming.

Initialize the store.

Parameters:

Name Type Description Default
db AsyncDatabaseManager

The database manager; the store opens its own session per call.

required
model type[JobT]

The concrete job model.

required
stale_after float | timedelta | None

Seconds (or a timedelta) a job may stay RUNNING before :meth:reclaim_stale readmits it. None — the default — means :meth:reclaim_stale refuses to run.

None

Raises:

Type Description
ValueError

If stale_after is not positive.

enqueue async

enqueue(
    kind: str,
    *,
    params: dict[str, Any] | None = None,
    payload: bytes | None = None,
    max_attempts: int = 3,
) -> JobT

Record a unit of work as QUEUED.

Enqueueing the row and enqueueing the task are two steps on purpose: the row is what the interface reads, and it must exist before the worker can claim it. Write the row first, then send the task its id.

Parameters:

Name Type Description Default
kind str

Which work this is.

required
params dict[str, Any] | None

Small JSON input.

None
payload bytes | None

Large binary input — the file a broker should not be carrying.

None
max_attempts int

Claim budget. Defaults to 3.

3

Returns:

Name Type Description
JobT JobT

The persisted, queued job.

get async

get(job_id: UUID) -> JobT

Return one job.

Parameters:

Name Type Description Default
job_id UUID

The job to read.

required

Returns:

Name Type Description
JobT JobT

The job row, payload included.

Raises:

Type Description
JobNotFoundError

When no row has that id.

claim async

claim(job_id: UUID) -> JobT | None

Move a queued job to RUNNING and return it.

The transition is a single conditional UPDATE, so two workers racing for the same id cannot both win: exactly one sees a row change, the other gets None.

None means "not yours to run" and covers both a job someone else already claimed and an id that does not exist — which is what a competing worker should do either way. Call :meth:get when the difference matters.

Parameters:

Name Type Description Default
job_id UUID

The job to claim.

required

Returns:

Type Description
JobT | None

JobT | None: The claimed job, payload included, or None

JobT | None

when it was not claimable.

report_progress async

report_progress(job_id: UUID, *, progress: float, stage: str | None = None) -> bool

Move a running job's progress bar forward.

One conditional UPDATE, no read first — the same shape as :meth:claim, and for the same reason: a tick that reads the row and writes it back is a lock promotion, which on SQLite fails outright against the interface writing at the same moment.

The bar cannot go backwards. The progress < clause is in the statement rather than in the caller, because the caller is exactly who cannot enforce it: two ticks can be in flight at once, and the one that arrives second is not the one that measured second. A refused write is not an error — it is the row already being further along than this tick believed.

A job that is not RUNNING is not written either. Progress on a cancelled job would repaint a bar the user already stopped.

Parameters:

Name Type Description Default
job_id UUID

The job to advance.

required
progress float

Completed fraction, clamped to [0, 1].

required
stage str | None

Which part of the work is running. None leaves the stage as it is.

None

Returns:

Name Type Description
bool bool

Whether the row moved — False when the job is no

bool

longer running, or was already further along.

succeed async

succeed(
    job_id: UUID,
    *,
    result_id: UUID | None = None,
    values: Mapping[str, Any] | None = None,
) -> JobT

Close a job as DONE.

The payload is dropped here: a table of finished jobs that still carries every uploaded document is a table that outgrows the data it was serving.

values writes the columns a project added to its job model — the object_key of the file the work generated, say — in the same conditional UPDATE that sets DONE. Writing them from a session of your own before calling succeed is two transactions, and between them the row is RUNNING with the key already set: a cancel landing there makes succeed raise :class:JobCancelledError and leaves a cancelled row pointing at a file the worker is about to delete. Here a cancelled job gets nothing, because the statement that would write the values is the one the cancellation refuses.

Example

await store.succeed(job_id, values={"object_key": key})

Parameters:

Name Type Description Default
job_id UUID

The job to close.

required
result_id UUID | None

The row the work produced, so the interface can link straight to it.

None
values Mapping[str, Any] | None

Project columns to write with the transition, keyed by attribute name. Validated before any SQL runs.

None

Returns:

Name Type Description
JobT JobT

The finished job.

Raises:

Type Description
JobNotFoundError

When no row has that id.

JobAlreadyFinishedError

When the job is already terminal.

JobCancelledError

When the job was cancelled; values is not written.

ValueError

When values names a column the model does not have, or one in :data:STORE_OWNED_JOB_COLUMNS.

fail async

fail(job_id: UUID, reason: str) -> JobT

Close a job as FAILED.

Parameters:

Name Type Description Default
job_id UUID

The job to close.

required
reason str

Why it stopped, written for the person who will read it on a screen — not a traceback.

required

Returns:

Name Type Description
JobT JobT

The failed job.

Raises:

Type Description
JobNotFoundError

When no row has that id.

JobAlreadyFinishedError

When the job is already terminal.

cancel async

cancel(job_id: UUID, *, reason: str | None = None) -> JobT | None

Ask a queued or running job to stop.

This writes CANCELLED and returns; it does not reach into the worker. There is no portable way to kill a coroutine running in another process, so cancellation is cooperative: the worker reads this status at checkpoints and gives up (:func:~tempest_fastapi_sdk.tasks.run_cancellable). The screen can therefore reflect the cancellation immediately, while the work behind it takes a few seconds more to actually stop.

Idempotent. Cancelling something that is not running answers None rather than raising — a user double-clicking, or clicking just as the job finished on its own, is not an error. That makes None mean "there was nothing to stop", covering an unknown id, a job already done, already failed, or already cancelled.

Parameters:

Name Type Description Default
job_id UUID

The job to cancel.

required
reason str | None

Stored in error for the screen. Not a failure message — say who asked, not what broke.

None

Returns:

Type Description
JobT | None

JobT | None: The cancelled job, or None when it was not

JobT | None

cancellable.

is_cancelled async

is_cancelled(job_id: UUID) -> bool

Has this job been cancelled?

Reads in a fresh session on purpose. The worker's own session is inside a transaction that started before the cancel was committed, so asking it would serve the pre-cancel snapshot — the exact opposite of what a checkpoint needs.

Parameters:

Name Type Description Default
job_id UUID

The job to check.

required

Returns:

Name Type Description
bool bool

True when the row says CANCELLED. A job that no

bool

longer exists answers True: there is nothing left to

bool

produce a result for, so stopping is the right move.

cancellation_watch

cancellation_watch(job_id: UUID) -> Callable[[], Awaitable[bool]]

Build the predicate :func:run_cancellable polls.

Parameters:

Name Type Description Default
job_id UUID

The job to watch.

required

Returns:

Name Type Description
Callable[[], Awaitable[bool]]

Callable[[], Awaitable[bool]]: A no-argument coroutine

answering Callable[[], Awaitable[bool]]

meth:is_cancelled.

Example:

>>> await run_cancellable(
...     transcribe(audio),
...     interrupted=store.cancellation_watch(job.id),
... )

list_recent async

list_recent(
    *,
    kind: str | None = None,
    status: JobStatusEnum | str | None = None,
    statuses: Sequence[JobStatusEnum | str] | None = None,
    limit: int = 20,
) -> list[JobT]

Return the most recently requested jobs, newest first.

Returns an empty list when nothing matches — "no jobs yet" is a successful answer, not a 404.

statuses is what a screen showing work in flight actually needs: "queued or running" is one question, and asking it as two queries makes the two halves disagree the moment a worker claims a job between them.

Parameters:

Name Type Description Default
kind str | None

Restrict to one kind of work.

None
status JobStatusEnum | str | None

Restrict to one status.

None
statuses Sequence[JobStatusEnum | str] | None

Restrict to any of several statuses.

None
limit int

Maximum rows. Defaults to 20.

20

Returns:

Type Description
list[JobT]

list[JobT]: The matching jobs, newest first.

Raises:

Type Description
ValueError

If limit is not positive, or if both status and statuses are given — one of them would silently win.

reclaim_stale async

reclaim_stale() -> ReclaimedJobs

Readmit jobs whose worker died holding them.

A RUNNING row nobody will ever finish is the failure mode a queue cannot see: the task is gone, the row is not. Rows whose started_at is older than :attr:stale_after go back to QUEUED — unless they already spent their max_attempts, in which case they are closed as FAILED, because a job that kills its worker would otherwise be readmitted forever.

Two conditional UPDATE ... RETURNING id statements over disjoint conditions, deliberately with no SELECT first: a sweep that reads the rows and then writes them is a lock promotion, which on SQLite fails outright against a concurrent writer — measured, and the reason busy_timeout cannot help there (see :func:~tempest_fastapi_sdk.enable_sqlite_wal). The cost is that the give-up message names the budget rather than the row's own attempt count. RETURNING needs SQLite 3.35+ or PostgreSQL.

A requeued row is not sent to a worker by this method: its message died with the worker. Dispatch the returned ids::

reclaimed = await store.reclaim_stale()
for job_id in reclaimed.requeued:
    await extract_task.enqueue(str(job_id))

or let :meth:redispatch_queued find them on a later sweep.

Returns:

Name Type Description
ReclaimedJobs ReclaimedJobs

The ids requeued and the ids given up on. Its

ReclaimedJobs

len() is the old int count; comparing it with a number

needs ReclaimedJobs

attr:ReclaimedJobs.total.

Raises:

Type Description
RuntimeError

When the store was built without stale_after, since there is no threshold to apply.

redispatch_queued async

redispatch_queued(
    dispatch: Callable[[JobT], Awaitable[None]],
    *,
    older_than: float | timedelta,
    limit: int = 100,
) -> list[UUID]

Send QUEUED rows nobody touched for a while back to a worker.

The documented flow writes the row and then sends its id to the queue — two steps, and the second can be lost: the broker was down, the process died between them, or :meth:reclaim_stale requeued a row whose message died with its worker. Either way the row is QUEUED and nothing will ever claim it. This sweep is meant to run as a scheduled task::

async def _send(job: JobModel) -> None:
    await extract_task.enqueue(str(job.id))

@tq.interval(timedelta(minutes=5))
async def redispatch() -> None:
    await store.redispatch_queued(_send, older_than=600.0)

Sending twice is harmless. A row whose message is merely waiting in a long backlog is sent again, and both messages reach :meth:claim; its conditional UPDATE lets exactly one of them run the job and answers None to the other. Pick older_than above the backlog you expect so that stays rare, not to keep it correct.

Age is updated_at, not created_at: every write to the row refreshes it, and this method refreshes it after each dispatch, so a row is resent at most once per older_than rather than on every sweep. No session is held while dispatch runs — the candidate read is its own short transaction, and the refresh is a conditional UPDATE that skips a row a worker claimed in the meantime.

Parameters:

Name Type Description Default
dispatch Callable[[JobT], Awaitable[None]]

Sends one job to a worker — typically task.enqueue(str(job.id)).

required
older_than float | timedelta

Seconds (or a timedelta) a QUEUED row must sit untouched before it is resent.

required
limit int

Most rows resent per call, oldest first. Defaults to 100.

100

Returns:

Type Description
list[UUID]

list[UUID]: The ids handed to dispatch, oldest first.

list[UUID]

Empty when nothing was waiting.

Raises:

Type Description
ValueError

When older_than or limit is not positive.

Exception

Whatever dispatch raises propagates. The rows not yet sent keep their age, so the next sweep retries them.

watch async

watch(
    job_id: UUID,
    *,
    interval: float = 2.0,
    timeout: float | None = None,
    emit_on: Sequence[str] = ("status",),
) -> AsyncIterator[JobT]

Yield the job whenever a watched field changes, until it is terminal.

This replaces the while True: sleep; get every application writes by hand — including the part that is easy to get wrong: no session is held between ticks. Each poll opens and closes its own, so a worker writing to the same database is never blocked by the screen watching it.

The current state is yielded immediately, so a caller that subscribes after the job already finished still gets exactly one value and the loop ends.

emit_on is what makes this usable for a progress bar. Watching only the status yields three times for a whole reading — claimed, finished, and nothing in between — so a screen driven by it shows a bar that never moves. Add "progress" and every tick the worker wrote comes through.

Example

async for job in store.watch( ... job_id, ... interval=2.0, ... emit_on=("status", "progress", "stage"), ... ): ... await session.render(job.status, job.progress)

Parameters:

Name Type Description Default
job_id UUID

The job to follow.

required
interval float

Seconds between polls. Defaults to 2.0.

2.0
timeout float | None

Give up after this many seconds. None — the default — waits for a terminal status.

None
emit_on Sequence[str]

Column names whose change triggers a yield. Defaults to ("status",).

('status',)

Yields:

Name Type Description
JobT AsyncIterator[JobT]

The job, each time one of the watched fields differs

AsyncIterator[JobT]

from the last value yielded.

Raises:

Type Description
JobNotFoundError

When no row has that id.

TimeoutError

When timeout elapses with the job still running or queued.

ValueError

If interval is not positive, or if emit_on is empty or names a column the model does not have.

ReclaimedJobs dataclass

ReclaimedJobs(requeued: list[UUID] = list(), failed: list[UUID] = list())

What :meth:JobStore.reclaim_stale did, row by row.

The ids are what make the sweep useful. A requeued row is QUEUED again, but its message is gone with the worker that died — nothing sends it to a worker until somebody calls task.enqueue(str(id)) for it, and the old int return gave the caller nothing to call it with.

len() and truthiness count both lists, so if await store.reclaim_stale(): reads as it did when the method returned an int. Comparing with a number (== 1) or adding to one does not: use :attr:total.

Attributes:

Name Type Description
requeued list[UUID]

Rows moved back to QUEUED, in the order the database returned them. Dispatch these.

failed list[UUID]

Rows closed as FAILED because their claim budget was spent.

total property

total: int

Return how many rows left RUNNING.

Returns:

Name Type Description
int int

len(requeued) + len(failed).

RedisLockClient

Bases: Protocol

The one method :class:RedisSchedulerLock needs from a client.

redis.asyncio.Redis satisfies this, and so does fakeredis's async client — which is what the suite runs against, since a lock is only worth testing where two holders can actually contend.

lock

lock(
    name: str, /, *, timeout: float | None = ..., blocking: bool = ...
) -> RedisLockHandle

Build a lock object for one key.

Parameters:

Name Type Description Default
name str

The Redis key the lock lives under.

required
timeout float | None

Lease TTL in seconds.

...
blocking bool

Whether acquire waits.

...

Returns:

Name Type Description
RedisLockHandle RedisLockHandle

The lock, not yet acquired.

RedisLockHandle

Bases: Protocol

The lock object redis-py returns from Redis.lock.

Written positional-only for the required argument on purpose: mypy accepts a parameter-name mismatch in protocol compatibility and basedpyright rejects it, and the implementer here is a library whose parameter names are not ours to keep in sync.

acquire

acquire() -> Awaitable[bool]

Take the lock.

Returns:

Type Description
Awaitable[bool]

Awaitable[bool]: Whether the lock was taken.

extend

extend(additional_time: float, /, *, replace_ttl: bool = ...) -> Awaitable[bool]

Push the expiry out, verifying ownership first.

Parameters:

Name Type Description Default
additional_time float

Seconds to add, or to set when replace_ttl is true.

required
replace_ttl bool

Replace the remaining TTL rather than adding to it, so a long-lived leader's lease does not grow without bound.

...

Returns:

Type Description
Awaitable[bool]

Awaitable[bool]: Whether the extension applied.

release

release() -> Awaitable[None]

Delete the key, verifying ownership first.

Returns:

Type Description
Awaitable[None]

Awaitable[None]: Completes once the key is gone.

RedisSchedulerLock

RedisSchedulerLock(
    client: RedisLockClient,
    *,
    name: str = DEFAULT_LOCK_NAME,
    ttl_seconds: float = DEFAULT_LOCK_TTL_SECONDS,
)

A :class:SchedulerLock over the lock redis-py ships.

Example:

>>> import redis.asyncio as redis
>>> from tempest_fastapi_sdk.tasks import RedisSchedulerLock
>>>
>>> lock: RedisSchedulerLock = RedisSchedulerLock(
...     redis.Redis.from_url("redis://localhost:6379/0"),
... )

Attributes:

Name Type Description
name str

The Redis key the lease lives under.

ttl_seconds float

How long the lease survives unrenewed.

Wrap a Redis client as a scheduler lease.

Parameters:

Name Type Description Default
client RedisLockClient

An async Redis client. Anything with lock fits, which is what lets the suite run this against fakeredis.

required
name str

The key to lock. Give two services sharing one Redis instance different names, or one of them will never schedule.

DEFAULT_LOCK_NAME
ttl_seconds float

Lease duration. See :data:DEFAULT_LOCK_TTL_SECONDS for why the default is what it is.

DEFAULT_LOCK_TTL_SECONDS

Raises:

Type Description
ValueError

When ttl_seconds is not positive, which would make every lease expire on arrival and hand the schedule to whichever replica polled last.

from_url classmethod

from_url(
    url: str,
    *,
    name: str = DEFAULT_LOCK_NAME,
    ttl_seconds: float = DEFAULT_LOCK_TTL_SECONDS,
) -> RedisSchedulerLock

Build the lease from a Redis URL.

Parameters:

Name Type Description Default
url str

A redis:// / rediss:// URL.

required
name str

The key to lock.

DEFAULT_LOCK_NAME
ttl_seconds float

Lease duration.

DEFAULT_LOCK_TTL_SECONDS

Returns:

Name Type Description
RedisSchedulerLock RedisSchedulerLock

The lease, over a client of its own.

Raises:

Type Description
ImportError

When redis is not installed, which means the [cache] extra is missing.

acquire async

acquire() -> bool

Try to take the lease without waiting.

Returns:

Name Type Description
bool bool

Whether this process now holds it.

renew async

renew() -> bool

Extend the lease this process holds.

replace_ttl is set, so the lease is pushed to a fixed ttl_seconds from now rather than accumulating: a leader up for a week would otherwise hold a week-long lease, and its death would stop the schedule until that ran out.

A renewal that fails because the transport failed is indistinguishable, from here, from one that fails because another replica took the lease. Standing down is the safe direction in both: a gap of at most one TTL costs a late tick, while guessing the other way runs two schedulers. The key is released on the way out, so a lease this process still owned goes back immediately instead of waiting out the TTL.

Returns:

Name Type Description
bool bool

Whether the lease is still held afterwards. False

bool

once it has been lost, and it stays False.

release async

release() -> None

Give up the lease if it is still held.

A failure here is logged and swallowed: this runs on shutdown, and raising would replace whatever actually stopped the process. The lease expires on its own within ttl_seconds anyway.

SchedulerLock

Bases: Protocol

The three calls leader election needs from a lease.

A service with its own coordination — etcd, ZooKeeper, a Postgres advisory lock — implements this and passes it to :meth:~tempest_fastapi_sdk.tasks.TaskQueue.lifespan; nothing here knows about Redis.

Every method is a coroutine because acquiring a lease is I/O in every implementation worth having.

acquire async

acquire() -> bool

Try to take the lease without waiting.

Returns:

Name Type Description
bool bool

True when this process now holds it, False

bool

when another one does. Must not block: a replica that

bool

waited here would delay its own startup behind the leader's

bool

entire lifetime.

renew async

renew() -> bool

Extend a lease this process already holds.

Returns:

Name Type Description
bool bool

True when the lease was extended, False when

bool

it was lost — expired, or taken over. False must stop

bool

the scheduler loop: a lost lease means another replica is

bool

already running it.

release async

release() -> None

Give up the lease, if this process still holds it.

Releasing on shutdown is what lets another replica take over in seconds instead of after the TTL. Must tolerate being called when the lease was never acquired or was already lost.

AsyncTaskBrokerManager

AsyncTaskBrokerManager(broker: AsyncBroker)

Manage the lifecycle of a TaskIQ broker.

Wraps any TaskIQ broker (AioPikaBroker for RabbitMQ, RedisBroker, InMemoryBroker for tests, etc.) with a uniform startup / shutdown surface that matches the SDK's other backends and exposes the task decorator so application code never imports the broker directly.

The broker is injected so consumers stay free to choose the transport without forcing TaskIQ to import every backend.

Typical usage::

from taskiq_aio_pika import AioPikaBroker
from tempest_fastapi_sdk import AsyncTaskBrokerManager

broker = AioPikaBroker("amqp://guest:guest@localhost:5672/")
tasks = AsyncTaskBrokerManager(broker)

@tasks.task
async def send_email(to: str) -> None:
    ...

# FastAPI lifespan
await tasks.connect()
...
await tasks.disconnect()

# enqueue from a request handler
await send_email.kiq("user@example.com")

Attributes:

Name Type Description
broker AsyncBroker

The wrapped broker instance.

Initialize the manager.

Parameters:

Name Type Description Default
broker AsyncBroker

A TaskIQ broker instance.

required

is_connected property

is_connected: bool

Return True once :meth:connect succeeded.

Returns:

Name Type Description
bool bool

True while the broker is started.

connect async

connect() -> None

Start the broker so tasks can be enqueued and processed.

Safe to call multiple times — subsequent calls are no-ops while the same broker is alive.

disconnect async

disconnect() -> None

Shut the broker down and release its resources.

task

task(
    task_name: Callable[_P, _R], **labels: Any
) -> AsyncTaskiqDecoratedTask[_P, _R]
task(
    task_name: str | None = None, **labels: Any
) -> Callable[[Callable[_P, _R]], AsyncTaskiqDecoratedTask[_P, _R]]
task(
    task_name: Callable[_P, _R] | str | None = None, **labels: Any
) -> (
    AsyncTaskiqDecoratedTask[_P, _R]
    | Callable[[Callable[_P, _R]], AsyncTaskiqDecoratedTask[_P, _R]]
)

Forward to broker.task so callers don't import TaskIQ.

Can be used as either @manager.task or @manager.task(task_name="..."). Both forms mirror the overloads of AsyncBroker.task, so the decorated name keeps the function's parameters and return type.

Parameters:

Name Type Description Default
task_name Callable[_P, _R] | str | None

The function itself (bare @manager.task) or the task-name override (@manager.task(task_name="...")).

None
**labels Any

TaskIQ labels forwarded to AsyncBroker.task.

{}

Returns:

Type Description
AsyncTaskiqDecoratedTask[_P, _R] | Callable[[Callable[_P, _R]], AsyncTaskiqDecoratedTask[_P, _R]]

AsyncTaskiqDecoratedTask[_P, _R] | Callable[[Callable[_P, _R]],

AsyncTaskiqDecoratedTask[_P, _R] | Callable[[Callable[_P, _R]], AsyncTaskiqDecoratedTask[_P, _R]]

AsyncTaskiqDecoratedTask[_P, _R]]: The decorated task (bare

AsyncTaskiqDecoratedTask[_P, _R] | Callable[[Callable[_P, _R]], AsyncTaskiqDecoratedTask[_P, _R]]

form), or the decorator that produces one.

register_task

register_task(
    func: Callable[_P, _R], *, task_name: str | None = None, **kwargs: Any
) -> AsyncTaskiqDecoratedTask[_P, _R]

Register func as a task without using decorator syntax.

Useful when wiring third-party callables that you can't decorate at definition time.

Parameters:

Name Type Description Default
func Callable[_P, _R]

The async callable to register.

required
task_name str | None

Override the task name. Defaults to TaskIQ's auto-generated module:function form.

None
**kwargs Any

Extra keyword arguments forwarded to AsyncBroker.task.

{}

Returns:

Type Description
AsyncTaskiqDecoratedTask[_P, _R]

AsyncTaskiqDecoratedTask[_P, _R]: The registered task,

AsyncTaskiqDecoratedTask[_P, _R]

preserving func's parameters and return type.

lifespan async

lifespan() -> AsyncGenerator[AsyncBroker, None]

Yield the broker inside an async with block.

Connects on entry, disconnects on exit.

Yields:

Name Type Description
AsyncBroker AsyncGenerator[AsyncBroker, None]

The connected broker.

broker_dependency async

broker_dependency() -> AsyncIterator[AsyncBroker]

Async generator dependency suitable for FastAPI Depends.

Yields:

Name Type Description
AsyncBroker AsyncIterator[AsyncBroker]

The connected broker.

Raises:

Type Description
RuntimeError

When :meth:connect was not called yet.

health_check async

health_check() -> bool

Return True when the broker is started.

TaskIQ brokers don't expose a generic ping, so we only report whether the startup handshake completed.

Returns:

Name Type Description
bool bool

True while the broker is started.

DeadLetter dataclass

DeadLetter(
    task_name: str,
    task_id: str,
    exception: BaseException,
    retries: int,
    args: list[Any] = list(),
    kwargs: dict[str, Any] = dict(),
)

A task call that failed terminally, handed to a :class:DeadLetterSink.

Attributes:

Name Type Description
task_name str

The registered task name.

task_id str

The failed invocation's id.

args list[Any]

Positional arguments of the failed call.

kwargs dict[str, Any]

Keyword arguments of the failed call.

exception BaseException

The exception that ended the last attempt.

retries int

Number of attempts made before giving up.

DeadLetterSink

Bases: Protocol

Where terminally-failed tasks go.

Implement this to route dead letters wherever you want — a :class:~tempest_fastapi_sdk.queue.MessageBroker channel, a database table, a log line, an alert. The sink is called at most once per task invocation, only after retries (if any) are exhausted.

The parameter is positional-only, so a plain function works whatever it names it — async def sink(letter: DeadLetter) -> None is a DeadLetterSink. Both checkers compare parameter names when matching a function against a callback protocol; with a named parameter mypy and basedpyright rejected every sink not spelled dead_letter.

RetryPolicy dataclass

RetryPolicy(max_retries: int = 3, on_error: bool = True)

Typed retry configuration for a background task.

Attributes:

Name Type Description
max_retries int

Total attempts before the task is given up on (matches TaskIQ's max_retries label semantics).

on_error bool

Whether the task is retried on failure at all.

as_labels

as_labels() -> dict[str, Any]

Render this policy as the TaskIQ labels the retry middleware reads.

Returns:

Type Description
dict[str, Any]

dict[str, Any]: {"retry_on_error": ..., "max_retries": ...}.

TaskMetrics

TaskMetrics(*, namespace: str = 'tasks', registry: Any = None)

Prometheus run count + duration histogram for background tasks.

Example:

>>> from tempest_fastapi_sdk.tasks import TaskMetrics, TaskQueue
>>> tq = TaskQueue.rabbitmq("amqp://guest:guest@localhost/")
>>> tq.enable_metrics(TaskMetrics())

Attributes:

Name Type Description
namespace str

Metric name prefix.

Build the metric objects.

Parameters:

Name Type Description Default
namespace str

Prefix for every metric name.

'tasks'
registry Any

A prometheus_client.CollectorRegistry to register on; None uses the client's default registry (the same one the SDK's /metrics endpoint scrapes).

None

record

record(task: str, *, status: str, duration_seconds: float) -> None

Record one completed task execution.

Parameters:

Name Type Description Default
task str

The task name label.

required
status str

"success" or "error".

required
duration_seconds float

Wall-clock execution time.

required

middleware

middleware() -> TaskiqMiddleware

Build the TaskIQ middleware that records this bundle.

Returns:

Name Type Description
TaskiqMiddleware TaskiqMiddleware

The middleware instance (needs the [tasks]

TaskiqMiddleware

extra).

TaskBinding dataclass

TaskBinding(
    key: str,
    func: Callable[..., Awaitable[Any]],
    name: str | None,
    options: dict[str, Any] = dict(),
    retry: RetryPolicy | None = None,
)

One task registration produced by a :class:TaskDef.

Attributes:

Name Type Description
key str

A stable key (the method name, or "run" for the constructor form) used to look the task up after registration.

func Callable[..., Awaitable[Any]]

The async callable to run.

name str | None

Explicit task name override, or None.

options dict[str, Any]

Extra TaskIQ labels / options.

retry RetryPolicy | None

Retry configuration, kept apart from :attr:options because it is rendered into labels rather than forwarded as one.

TaskDef

TaskDef(*, name: str | None = None, retry: RetryPolicy | None = None, **options: Any)

Bases: Generic[TaskReturnT]

Base class for class-based background tasks.

Subclass it in either style from the module docstring. Register an instance with :meth:~tempest_fastapi_sdk.tasks.TaskQueue.register, which returns a single Task (constructor form) or a dict[str, Task] keyed by method name (grouped form).

Attributes:

Name Type Description
name str | None

Task name for the constructor form; None lets TaskIQ derive module:function.

retry RetryPolicy | None

Retry configuration for every task this definition declares. A :func:task_method naming its own overrides it for that task.

options dict[str, Any]

Extra TaskIQ labels for the constructor form. Never mutated, so the empty class-level default is safe to share.

Configure the constructor form.

Parameters:

Name Type Description Default
name str | None

Override the task name. Omit in the grouped (@task_method) form.

None
retry RetryPolicy | None

Retry configuration, the same keyword @tq.task takes. Applies to every task this definition declares, including the grouped form's, unless a :func:task_method names its own. Needs :meth:~tempest_fastapi_sdk.tasks.TaskQueue.enable_retries.

None
**options Any

Extra TaskIQ labels / options for the constructor form. The grouped form takes its own on each :func:task_method.

{}

is_grouped property

is_grouped: bool

Return True when this uses the grouped @task_method form.

Returns:

Name Type Description
bool bool

True if any method is marked with :func:task_method.

run async

run(*args: Any, **kwargs: Any) -> TaskReturnT

Run the task — override in the constructor form.

Raises:

Type Description
NotImplementedError

When neither run is overridden nor any :func:task_method is defined.

Parameters:

Name Type Description Default
*args Any

Positional arguments forwarded to the task.

()
**kwargs Any

Keyword arguments forwarded to the task.

{}

Returns:

Name Type Description
TaskReturnT TaskReturnT

Whatever the wrapped task returns.

task_bindings

task_bindings() -> list[TaskBinding]

Return every task this definition declares.

Grouped @task_method methods take precedence; if none are present, the constructor form (run + name) is used. A binding with no retry of its own inherits :attr:retry.

Returns:

Type Description
list[TaskBinding]

list[TaskBinding]: One entry per task.

Phase dataclass

Phase(
    name: str, weight: float, seconds: float = 0.0, seconds_per_kilochar: float = 0.0
)

One measured step of a longer job.

Attributes:

Name Type Description
name str

What the step is called, as the interface will show it and as the row will record it.

weight float

How much of the whole job this step accounts for, relative to the other phases. Measured seconds are the natural value; they are normalised, so any scale works.

seconds float

How long the step usually takes — the median of real runs. 0.0 means unmeasured, and a phase with no expected duration does not interpolate: its bar sits at the phase floor until the phase ends.

seconds_per_kilochar float

How much each thousand characters of input adds, when the caller passes size. Zero means duration does not track input size, or was not fitted.

PhasePlan

PhasePlan(phases: Sequence[Phase], *, ceiling_margin: float = 0.95)

Measured phases, turned into the fraction to write on the row.

Attributes:

Name Type Description
ceiling_margin float

How far into a phase's span the interpolation is allowed to climb before the phase actually ends.

Build a plan from measured phases.

Parameters:

Name Type Description Default
phases Sequence[Phase]

The steps, in the order they run.

required
ceiling_margin float

Fraction of a phase's span the interpolation may reach. Defaults to 0.95, so a phase that is taking longer than usual stops just short of claiming to be finished.

0.95

Raises:

Type Description
ValueError

When there are no phases, a name repeats, a weight is not positive, or ceiling_margin is outside (0, 1].

names property

names: tuple[str, ...]

The phase names, in order.

Returns:

Type Description
tuple[str, ...]

tuple[str, ...]: The names this plan knows.

from_seconds classmethod

from_seconds(
    medians: Mapping[str, float],
    *,
    per_kilochar: Mapping[str, float] | None = None,
    ceiling_margin: float = 0.95,
) -> PhasePlan

Build a plan straight out of a measurement run.

The median duration is both the weight and the expected duration, which is what a measurement gives you without further arithmetic.

Parameters:

Name Type Description Default
medians Mapping[str, float]

Median seconds per phase, in the order the phases run.

required
per_kilochar Mapping[str, float] | None

Fitted seconds per thousand characters, for the phases that have one.

None
ceiling_margin float

Passed through to the constructor.

0.95

Returns:

Name Type Description
PhasePlan PhasePlan

The plan.

Raises:

Type Description
ValueError

When a median is not positive — a phase that takes no time is not a phase to show.

bounds

bounds(phase: str) -> tuple[float, float]

Where a phase starts and ends on the bar.

Parameters:

Name Type Description Default
phase str

The phase name.

required

Returns:

Type Description
float

tuple[float, float]: Its floor and ceiling, both in

float

[0, 1].

Raises:

Type Description
KeyError

When the plan has no such phase.

expected

expected(phase: str, *, size: float | None = None) -> float

How long this phase should take, given its input.

Parameters:

Name Type Description Default
phase str

The phase name.

required
size float | None

Input size in characters, when the phase was fitted against it.

None

Returns:

Name Type Description
float float

Expected seconds, 0.0 when the phase was never

float

measured.

Raises:

Type Description
KeyError

When the plan has no such phase.

fraction

fraction(
    phase: str,
    *,
    elapsed: float = 0.0,
    size: float | None = None,
    done: float | None = None,
) -> float

The number to write on the row right now.

Parameters:

Name Type Description Default
phase str

The phase that is running.

required
elapsed float

Seconds since the phase started.

0.0
size float | None

Input size in characters, when known.

None
done float | None

A real fraction of this phase, from a counter the work actually has — pages read out of pages total. Given, it wins: a measured count beats an interpolation, and it is allowed to reach the phase ceiling because it is not a guess.

None

Returns:

Name Type Description
float float

The completed fraction of the whole job, in

float

[0, 1].

Raises:

Type Description
KeyError

When the plan has no such phase.

ProgressSink

Bases: Protocol

The two things a tracker needs from a job store.

Narrow on purpose: a tracker asks the row how far along it is allowed to say the work is, and whether the user stopped it. Anything that answers those two questions can be tracked, which is what keeps the tests here free of a database.

report_progress async

report_progress(job_id: UUID, *, progress: float, stage: str | None = None) -> bool

Move the recorded progress forward.

Parameters:

Name Type Description Default
job_id UUID

The job to advance.

required
progress float

Completed fraction.

required
stage str | None

Which part of the work is running.

None

Returns:

Name Type Description
bool bool

Whether the row moved.

is_cancelled async

is_cancelled(job_id: UUID) -> bool

Answer whether the user stopped this job.

Parameters:

Name Type Description Default
job_id UUID

The job to check.

required

Returns:

Name Type Description
bool bool

True when the job is cancelled or gone.

ProgressTracker

ProgressTracker(
    sink: ProgressSink,
    job_id: UUID,
    *,
    plan: PhasePlan,
    interval: float = DEFAULT_POLL_SECONDS,
    clock: Callable[[], float] = monotonic,
)

Runs a job's phases, writing where each one has got to.

Attributes:

Name Type Description
plan PhasePlan

The measured phases being followed.

interval float

Seconds between ticks — each tick writes the interpolated progress and asks whether the job was cancelled.

Bind a tracker to one job.

Parameters:

Name Type Description Default
sink ProgressSink

Where progress is written and cancellation is read — normally a :class:~tempest_fastapi_sdk.tasks.JobStore.

required
job_id UUID

The job being tracked.

required
plan PhasePlan

The measured phases.

required
interval float

Seconds between ticks.

DEFAULT_POLL_SECONDS
clock Callable[[], float]

Monotonic seconds source; injectable so a test does not have to wait.

monotonic

enter async

enter(phase: str) -> None

Announce a phase without running anything in it.

Parameters:

Name Type Description Default
phase str

The phase starting now.

required

report async

report(phase: str, *, done: float) -> None

Write a phase's own count of how far it has got.

For work that can actually count — pages extracted, rows written — this beats interpolation and is what the bar should show.

Parameters:

Name Type Description Default
phase str

The phase that is running.

required
done float

Its completed fraction, 0.0 to 1.0.

required

run async

run(
    phase: str,
    work: Awaitable[ResultT],
    *,
    size: float | None = None,
    stop_event: Event | None = None,
) -> ResultT

Run one phase, ticking the bar and honouring cancellation.

Parameters:

Name Type Description Default
phase str

The phase this work is.

required
work Awaitable[ResultT]

The work itself. It must be genuinely cancellable — async I/O, not a thread wrapper, for the reason :func:~tempest_fastapi_sdk.tasks.run_cancellable explains.

required
size float | None

Input size in characters, when the phase was fitted against it. With it, a call over 40.000 characters is not paced like one over 4.000.

None
stop_event Event | None

Forwarded to :func:~tempest_fastapi_sdk.tasks.run_cancellable, for work that runs in a thread and watches an event, which no coroutine cancellation reaches on its own. TextGenerator does not need it: it sets its own event when cancelled.

None

Returns:

Name Type Description
ResultT ResultT

Whatever work returned.

Raises:

Type Description
StageInterruptedError

The job was cancelled while this phase was running; work is already cancelled when this propagates.

KeyError

When the plan has no such phase.

Exception

Anything work itself raises, unchanged.

LifecycleResource

Bases: Protocol

Anything the queue can open on startup and close on shutdown.

:class:~tempest_fastapi_sdk.db.AsyncDatabaseManager, :class:~tempest_fastapi_sdk.queue.MessageBroker and :class:~tempest_fastapi_sdk.storage.AsyncMinIOClient all satisfy it, which is what makes resources=[db, broker] work without the SDK naming any of them.

connect async

connect() -> None

Open the resource.

disconnect async

disconnect() -> None

Close the resource.

Task

Task(taskiq_task: Any, func: Callable[P, Awaitable[R]])

Bases: Generic[P, R]

A background-runnable function — the result of :meth:TaskQueue.task.

Wraps a TaskIQ task so the two things you actually do read clearly and stay typed against the original signature:

  • await my_task.enqueue(...) — hand the call to a worker and return immediately (the worker runs it out-of-process).
  • await my_task.run(...) — run the body right here, in-process, returning its real value. Handy in tests and for reuse from other tasks.

Attributes:

Name Type Description
taskiq_task Any

The underlying TaskIQ decorated task — the escape hatch for .schedule_by_cron and friends.

Wrap a TaskIQ decorated task.

Parameters:

Name Type Description Default
taskiq_task Any

The object returned by broker.task(...).

required
func Callable[P, Awaitable[R]]

The original async function, kept for :meth:run and to preserve the typed signature.

required

task_name property

task_name: str

Return the registered task name.

Returns:

Name Type Description
str str

TaskIQ's module:function name (or the override).

enqueue async

enqueue(*args: args, **kwargs: kwargs) -> AsyncTaskiqTask[R]

Send this call to a worker and return without waiting for it.

Parameters:

Name Type Description Default
*args args

Positional arguments for the task.

()
**kwargs kwargs

Keyword arguments for the task.

{}

Returns:

Type Description
AsyncTaskiqTask[R]

AsyncTaskiqTask[R]: The TaskIQ task handle, typed by the wrapped

AsyncTaskiqTask[R]

function's return value. await handle.wait_result() blocks

AsyncTaskiqTask[R]

for a TaskiqResult[R] when a result backend is wired.

run async

run(*args: args, **kwargs: kwargs) -> R

Run the task body inline (no broker) and return its value.

Parameters:

Name Type Description Default
*args args

Positional arguments for the task.

()
**kwargs kwargs

Keyword arguments for the task.

{}

Returns:

Name Type Description
R R

Whatever the wrapped function returns.

TaskIQSettingsLike

Bases: Protocol

The two settings fields :meth:TaskQueue.from_settings reads.

Typed as a protocol rather than as :class:~tempest_fastapi_sdk.settings.TaskIQSettings so a service composing its own Settings from the mixins passes without an import cycle, and so a test can hand over a plain object.

Every member is a read-only @property. A bare annotation in a Protocol declares a settable attribute, and :class:~tempest_fastapi_sdk.settings.BaseAppSettings is frozen=True — so mypy rejected the very Settings the mixins build (expected settable variable, got read-only attribute) and the documented TaskQueue.from_settings(Settings()) needed a type: ignore. A property accepts both the frozen settings and a plain object with ordinary attributes.

Attributes:

Name Type Description
TASKIQ_BROKER_URL str

Broker URL. Empty selects the in-memory broker, which is the shape a test suite and a dev box without Redis actually run in.

TASKIQ_RESULT_BACKEND_URL str | None

Where task results go. None means "same place as the broker" when the broker can store results, and "nowhere" when it cannot.

TASKIQ_STORE_RESULTS bool

Whether results are stored at all. False leaves TaskIQ's DummyResultBackend in place on both transports, which is the shape of a cron-only service: no caller is waiting on a return value, so every stored result is pure cost.

TASKIQ_RESULT_TTL_SECONDS int

Seconds a stored result survives; 0 keeps results forever.

TASKIQ_BROKER_URL property

TASKIQ_BROKER_URL: str

Return the broker URL.

TASKIQ_RESULT_BACKEND_URL property

TASKIQ_RESULT_BACKEND_URL: str | None

Return where task results go.

TASKIQ_STORE_RESULTS property

TASKIQ_STORE_RESULTS: bool

Return whether results are stored at all.

TASKIQ_RESULT_TTL_SECONDS property

TASKIQ_RESULT_TTL_SECONDS: int

Return the seconds a stored result survives.

TaskQueue

TaskQueue(
    broker: AsyncBroker,
    *,
    resources: Sequence[LifecycleResource] = (),
    lock_url: str | None = None,
)

Typed facade over a TaskIQ broker plus its periodic scheduler.

Declare tasks with :meth:task, enqueue them with :meth:Task.enqueue, and schedule periodic ones with :meth:cron / :meth:interval — all on one object::

from tempest_fastapi_sdk.tasks import TaskQueue

tq = TaskQueue.rabbitmq("amqp://guest:guest@localhost:5672/")

@tq.task
async def send_welcome(to: str, name: str) -> None:
    await email.send(to, "Welcome", f"Hi {name}")

@tq.cron("0 9 * * MON-FRI", cron_offset="-03:00")
async def daily_digest() -> None:
    ...

# FastAPI lifespan
await tq.connect()
await tq.start_scheduler()          # dev / single-process only
...
await tq.stop_scheduler()
await tq.disconnect()

# from a request handler
await send_welcome.enqueue(to=user.email, name=user.name)

In production run the worker (and one scheduler) as separate processes. The TaskIQ CLI resolves module:attr with a plain getattr, so bind :attr:broker / :attr:scheduler to names of their own — myapp.tasks:tq.broker raises AttributeError: module 'myapp.tasks' has no attribute 'tq.broker'::

# myapp/tasks.py
broker = tq.broker
scheduler = tq.scheduler

# shell
taskiq worker    myapp.tasks:broker
taskiq scheduler myapp.tasks:scheduler

Attributes:

Name Type Description
broker AsyncBroker

The underlying TaskIQ broker (for the worker CLI and escape hatches).

Wrap an already-constructed TaskIQ broker.

Prefer :meth:from_settings, or :meth:rabbitmq / :meth:redis / :meth:memory; use this to inject a custom or pre-configured broker.

Parameters:

Name Type Description Default
broker AsyncBroker

A TaskIQ broker instance.

required
resources Sequence[LifecycleResource]

Resources the worker opens on startup and closes on shutdown, in order — see :meth:use.

()
lock_url str | None

Redis URL the scheduler lease is derived from when :meth:lifespan is asked for a scheduler. The transport constructors set this for you; pass it when you build the broker yourself, or pass scheduler_lock= to lifespan instead.

None

scheduler property

scheduler: TaskiqScheduler

Return the underlying TaskIQ scheduler (for the CLI).

Lazily built on first access. Point the standalone scheduler process at it. The CLI resolves module:attr with a plain getattr, so bind it to a module-level name first — scheduler = tq.scheduler, then taskiq scheduler myapp.tasks:scheduler.

Returns:

Name Type Description
TaskiqScheduler TaskiqScheduler

The underlying TaskIQ scheduler, so

TaskiqScheduler

scheduler = tq.scheduler is typed without an annotation.

is_connected property

is_connected: bool

Return True once :meth:connect has succeeded.

Returns:

Name Type Description
bool bool

True while the broker is started.

rabbitmq classmethod

rabbitmq(
    url: str, *, resources: Sequence[LifecycleResource] = (), **options: Any
) -> TaskQueue

Build a RabbitMQ-backed task queue ([tasks] extra).

Parameters:

Name Type Description Default
url str

AMQP URL.

required
resources Sequence[LifecycleResource]

Resources the worker opens on startup and closes on shutdown — see :meth:use.

()
**options Any

Extra keyword arguments forwarded to taskiq_aio_pika.AioPikaBroker.

{}

Returns:

Name Type Description
TaskQueue TaskQueue

A facade around an AioPikaBroker.

Raises:

Type Description
ImportError

When the [tasks] extra is not installed, so taskiq_aio_pika is unavailable.

redis classmethod

redis(
    url: str,
    *,
    results: bool | str = True,
    result_ttl_seconds: int = DEFAULT_RESULT_TTL_SECONDS,
    result_prefix: str = DEFAULT_RESULT_PREFIX,
    result_serializer: ResultSerializer = DEFAULT_RESULT_SERIALIZER,
    resources: Sequence[LifecycleResource] = (),
    **options: Any,
) -> TaskQueue

Build a Redis-backed task queue ([tasks-redis] extra).

Parameters:

Name Type Description Default
url str

Redis URL.

required
results bool | str

Where task results are stored. True (default) uses url; a string uses that URL instead; False stores nothing, which leaves TaskIQ's DummyResultBackend in place and makes reading a result impossible. Until v0.282.0 there was no result backend at all and no way to ask for one, so every service rebuilt the broker by hand to get .kiq + result to work.

True
result_ttl_seconds int

Seconds a stored result survives. Defaults to :data:DEFAULT_RESULT_TTL_SECONDS; 0 keeps results forever, which is what taskiq_redis does on its own.

DEFAULT_RESULT_TTL_SECONDS
result_prefix str

Namespace for the result keys. Defaults to :data:DEFAULT_RESULT_PREFIX; "" writes the bare task id.

DEFAULT_RESULT_PREFIX
result_serializer ResultSerializer

How results are encoded. "json" (default) stores data only; "pickle" is the explicit opt-in to taskiq_redis's own default, which runs code named by the stored bytes when a result is read — only for a Redis nobody else can write. Until 0.334.1 results were always pickled.

DEFAULT_RESULT_SERIALIZER
resources Sequence[LifecycleResource]

Resources the worker opens on startup and closes on shutdown — see :meth:use.

()
**options Any

Extra keyword arguments forwarded to taskiq_redis.RedisStreamBroker. Result-backend arguments do not belong here: RedisStreamBroker absorbs unknown keys into its connection kwargs, so result_ex_time=3600 is accepted at construction, the backend keeps its default, and the connection raises TypeError later inside connect(). That is why the two knobs above are named parameters.

{}

Returns:

Name Type Description
TaskQueue TaskQueue

A facade around a Redis stream broker, carrying

TaskQueue

the URL its scheduler lease can be derived from — see

TaskQueue

meth:lifespan.

Raises:

Type Description
ImportError

When taskiq_redis is not installed.

from_settings classmethod

from_settings(
    settings: TaskIQSettingsLike,
    *,
    results: bool | str | None = None,
    result_ttl_seconds: int | None = None,
    result_prefix: str | None = None,
    result_serializer: ResultSerializer = DEFAULT_RESULT_SERIALIZER,
    resources: Sequence[LifecycleResource] = (),
    **options: Any,
) -> TaskQueue

Build the queue the settings describe, transport included.

The branch this replaces was written once per service, and each copy decided the same three things again: which transport the URL means, whether results are stored, and what an empty URL does. The last one is the load-bearing case — a test suite and a dev box without Redis run with TASKIQ_BROKER_URL empty, and the answer has to be a broker that still registers @tq.task, not a parse error on an empty string.

Heartbeat files are read from the settings too: TASKIQ_WORKER_HEARTBEAT_FILE / TASKIQ_SCHEDULER_HEARTBEAT_FILE (empty, the default, leaves that heartbeat off) and TASKIQ_HEARTBEAT_SECONDS. When either file is set, :meth:enable_heartbeat is called. They are read with getattr and a default, because :class:TaskIQSettingsLike keeps its four members — adding three to the protocol would reject the plain objects that satisfy it today.

Example:

>>> from tempest_fastapi_sdk.settings import TaskIQSettings
>>> from tempest_fastapi_sdk.tasks import TaskQueue
>>>
>>> class Settings(TaskIQSettings):
...     '''Service settings.'''
>>>
>>> tq: TaskQueue = TaskQueue.from_settings(Settings())

Parameters:

Name Type Description Default
settings TaskIQSettingsLike

Anything carrying the four fields of that protocol — the :class:~tempest_fastapi_sdk.settings.TaskIQSettings mixin, or a service Settings composing it.

required
results bool | str | None

Overrides where results go. None (default) derives it from the settings, so the environment stays in charge; a value wins over the derived one instead of colliding with it, which is what passing results= through **options used to do.

None
result_ttl_seconds int | None

Overrides the result TTL. None derives it from TASKIQ_RESULT_TTL_SECONDS; 0 keeps results forever.

None
result_prefix str | None

Overrides the result key namespace. None uses :data:DEFAULT_RESULT_PREFIX; "" writes the bare task id.

None
result_serializer ResultSerializer

How results are encoded, on both transports. "json" (default) stores data only; "pickle" is the explicit, unsafe-on-shared-Redis opt-in described on :meth:redis.

DEFAULT_RESULT_SERIALIZER
resources Sequence[LifecycleResource]

Resources the worker opens on startup and closes on shutdown.

()
**options Any

Extra keyword arguments forwarded to the selected broker.

{}

Returns:

Name Type Description
TaskQueue TaskQueue

A facade over the transport the URL scheme names —

TaskQueue

redis/rediss for Redis Streams, amqp/amqps

TaskQueue

for RabbitMQ, and the in-memory broker for an empty URL.

Raises:

Type Description
ValueError

When the URL carries a scheme none of the transports handles. Falling back to memory here would turn a typo in a deployed environment variable into a queue that silently runs every task in the web process.

ImportError

When the transport the URL selects needs an extra that is not installed. The message names TASKIQ_BROKER_URL and its value (password masked), because the setting is what chose the transport: a project pinned to [tasks-redis] still reading the amqp:// default needs a different URL, not the [tasks] extra.

memory classmethod

memory(*, resources: Sequence[LifecycleResource] = ()) -> TaskQueue

Build an in-memory task queue for tests.

enqueue runs the task synchronously in-process, so tests need no worker and no broker connection. The in-memory broker runs the client and worker lifecycle events on :meth:connect, so worker-scoped hooks fire here too — which is what makes them testable without a worker process.

Parameters:

Name Type Description Default
resources Sequence[LifecycleResource]

Resources opened on startup and closed on shutdown — see :meth:use.

()

Returns:

Name Type Description
TaskQueue TaskQueue

A facade around taskiq.InMemoryBroker.

task

task(
    func: Callable[P, Awaitable[R]],
    *,
    name: str | None = None,
    retry: RetryPolicy | None = None,
    schedule: list[dict[str, Any]] | None = None,
    **options: Any,
) -> Task[P, R]
task(
    func: None = None,
    *,
    name: str | None = None,
    retry: RetryPolicy | None = None,
    schedule: list[dict[str, Any]] | None = None,
    **options: Any,
) -> Callable[[Callable[P, Awaitable[R]]], Task[P, R]]
task(
    func: Callable[P, Awaitable[R]] | None = None,
    *,
    name: str | None = None,
    retry: RetryPolicy | None = None,
    schedule: list[dict[str, Any]] | None = None,
    **options: Any,
) -> Task[P, R] | Callable[[Callable[P, Awaitable[R]]], Task[P, R]]

Register an async function as a background task.

Usable bare or with options::

@tq.task
async def a() -> None: ...

@tq.task(name="reports:nightly", retry=RetryPolicy(max_retries=5))
async def b() -> None: ...

Parameters:

Name Type Description Default
func Callable[P, Awaitable[R]] | None

The function, when used as a bare @tq.task. None when called with arguments (@tq.task(...)).

None
name str | None

Override the auto-generated module:function task name.

None
retry RetryPolicy | None

Per-task retry configuration; its labels are merged into options. Needs :meth:enable_retries to have installed the retry middleware.

None
schedule list[dict[str, Any]] | None

A raw TaskIQ schedule spec, for the triggers :meth:cron and :meth:interval do not cover (time, or several triggers on one task). Any cron_offset it carries is normalized, which is why this is a named parameter rather than a key read out of options.

None
**options Any

Extra TaskIQ labels / options forwarded to broker.task.

{}

Returns:

Name Type Description
Task[P, R] | Callable[[Callable[P, Awaitable[R]]], Task[P, R]]

Task[P, R] | Callable[[Callable[P, Awaitable[R]]], Task[P, R]]:

A Task[P, R] | Callable[[Callable[P, Awaitable[R]]], Task[P, R]]

class:Task (bare form) or a decorator returning one. Both

Task[P, R] | Callable[[Callable[P, Awaitable[R]]], Task[P, R]]

forms are overloaded so the decorated name keeps the wrapped

Task[P, R] | Callable[[Callable[P, Awaitable[R]]], Task[P, R]]

function's parameters and return type — Any here made

Task[P, R] | Callable[[Callable[P, Awaitable[R]]], Task[P, R]]

mypy --strict reject @tq.task(...) as an untyped

Task[P, R] | Callable[[Callable[P, Awaitable[R]]], Task[P, R]]

decorator (disallow_untyped_decorators).

Raises:

Type Description
ValueError

When an entry's cron_offset is a string that is neither a "±HH:MM" offset nor a resolvable time zone key.

enqueue_by_name async

enqueue_by_name(name: str, *args: Any, **kwargs: Any) -> AsyncTaskiqTask[Any]

Send a call to the task registered under name, without importing it.

The API process enqueues work the worker owns: importing the task module there would pull the task's whole dependency graph (and its import-time side effects) into every request process, and couple the two. Sending by name keeps the API to a string — a *_TASK_NAME constant next to the task — and the worker resolves it.

Every :class:TaskQueue installs, first in its broker, the middleware from :func:~tempest_fastapi_sdk.tasks.observability.make_registered_labels_middleware, so the labels the task was registered with (retry policy, timeout, ack_type) still apply to a call sent this way. Nothing checks name on the sending side, because that process does not know the tasks: over Redis or RabbitMQ an unknown name is logged by the worker as task "..." is not found and dropped. The in-memory broker is its own worker, so there it raises taskiq.exceptions.SendTaskError right away.

Parameters:

Name Type Description Default
name str

The registered task name — the name= given to :meth:task / :meth:cron / :meth:interval, or TaskIQ's module:function default.

required
*args Any

Positional arguments for the task.

()
**kwargs Any

Keyword arguments for the task.

{}

Returns:

Type Description
AsyncTaskiqTask[Any]

AsyncTaskiqTask[Any]: The TaskIQ task handle; untyped, since the

AsyncTaskiqTask[Any]

sender never sees the task's signature.

Raises:

Type Description
SendTaskError

When the broker refuses the message — with the in-memory broker, for a name no task is registered under.

register

register(
    definition: TaskDef[TaskReturnT],
) -> Task[Any, TaskReturnT] | dict[str, Task[Any, Any]]

Register a class-based :class:~tempest_fastapi_sdk.tasks.TaskDef.

Reads the definition's task bindings (constructor form or grouped @task_method methods) and registers each with the broker.

A binding's retry is rendered into labels here, exactly as :meth:task does — TaskIQ's middleware reads retry_on_error / max_retries, so a RetryPolicy forwarded as a label would be ignored and the task would never retry, silently.

Parameters:

Name Type Description Default
definition TaskDef[TaskReturnT]

The task-definition instance.

required

Returns:

Type Description
Task[Any, TaskReturnT] | dict[str, Task[Any, Any]]

Task[Any, TaskReturnT] | dict[str, Task[Any, Any]]: A single

Task[Any, TaskReturnT] | dict[str, Task[Any, Any]]

class:Task for the constructor form, or a dict keyed by

Task[Any, TaskReturnT] | dict[str, Task[Any, Any]]

method name for the grouped form.

Notes

TaskIQ needs a plain function with a settable __name__, and a bound method has neither, so the method is wrapped. Deliberately without functools.wraps: that would make inspect.signature follow __wrapped__ back to a signature including self.

enable_retries

enable_retries(*, default_max_retries: int = 3) -> None

Install TaskIQ's retry middleware so failing tasks are re-run.

A task opts in with a :class:~tempest_fastapi_sdk.tasks.RetryPolicy (@tq.task(retry=RetryPolicy(...))); this installs the middleware that honours it. Call it before :meth:connect.

Parameters:

Name Type Description Default
default_max_retries int

Attempt cap for a retrying task that sets no max_retries of its own.

3

enable_metrics

enable_metrics(metrics: TaskMetrics) -> None

Record Prometheus run count + duration for every task.

Call it before :meth:connect.

Parameters:

Name Type Description Default
metrics TaskMetrics

The metric bundle to record into.

required

dead_letter

dead_letter(sink: DeadLetterSink, *, default_max_retries: int = 3) -> None

Route terminally-failed tasks to sink.

A task that fails with no retry configured, or after its retries are exhausted, is handed to sink exactly once. Call it before :meth:connect.

Parameters:

Name Type Description Default
sink DeadLetterSink

Where dead letters go (a channel publisher, a DB write, an alert — the target is yours).

required
default_max_retries int

Must match the value passed to :meth:enable_retries so the "retries exhausted" point lines up for tasks that set no explicit max_retries.

3

enable_heartbeat

enable_heartbeat(
    *,
    worker_file: str | Path | None = None,
    scheduler_file: str | Path | None = None,
    every: timedelta = DEFAULT_HEARTBEAT_EVERY,
) -> None

Make the worker and the scheduler prove they are alive.

  • worker_file — each worker process rewrites it with the current UTC time every every, from an asyncio task started on the worker's startup event and cancelled on its shutdown (:class:~tempest_fastapi_sdk.tasks.heartbeat.HeartbeatLoop). The beat is local: it goes through no broker and no scheduler, so every replica keeps its own file fresh however the broker spreads tasks between them. A fresh file proves the process is alive and its event loop is not blocked; a task that blocks the loop with synchronous work stops the beat.
  • scheduler_file — the scheduler rewrites it once per every from inside TaskIQ's scheduler loop, through the pre_send of a schedule source attached to :attr:scheduler (:class:~tempest_fastapi_sdk.tasks.heartbeat.source.HeartbeatScheduleSource). The send is then cancelled, so nothing is published. A fresh file proves the loop is ticking — not that the scheduler can still publish.

Both are written atomically (temporary file plus :func:os.replace, mode 0644). A failed write — read-only filesystem, missing directory — logs one warning and never stops the worker or the scheduler; the stale file is the signal.

Call this in the module the worker and the scheduler import, before binding scheduler = tq.scheduler; taskiq scheduler myapp.tasks:scheduler then picks the source up with no extra wiring. Each process only writes the file that belongs to it, so configuring both paths in both containers is safe. With :meth:memory the worker events fire on :meth:connect, so the worker loop runs in that process too.

Check the file from the container with python -m tempest_fastapi_sdk.tasks.heartbeat <file> --max-age <seconds>, using a max_age of about three times every.

Parameters:

Name Type Description Default
worker_file str | Path | None

Heartbeat file each worker process writes; None writes none.

None
scheduler_file str | Path | None

Heartbeat file the scheduler writes; None writes none.

None
every timedelta

Heartbeat period. Whole seconds, at least one — TaskIQ's interval schedules accept nothing else.

DEFAULT_HEARTBEAT_EVERY

Raises:

Type Description
ValueError

When neither file is given, or every is not a whole number of seconds of at least one.

RuntimeError

When the heartbeat was already enabled on this queue.

cron

cron(
    expr: str,
    *,
    cron_offset: str | timedelta | None = None,
    name: str | None = None,
    **options: Any,
) -> Callable[[Callable[P, Awaitable[R]]], Task[P, R]]

Register a task to run on a cron schedule.

For readable schedules without hand-writing cron syntax, pass a :class:tempest_fastapi_sdk.tasks.CronEnum member or a builder result (:func:~tempest_fastapi_sdk.tasks.daily, :func:~tempest_fastapi_sdk.tasks.weekdays, …) as expr, and a :class:~tempest_fastapi_sdk.tasks.CronOffsetEnum member as cron_offset.

Parameters:

Name Type Description Default
expr str

A cron expression ("*/5 * * * *" = every five minutes), a :class:CronEnum member, or a builder result.

required
cron_offset str | timedelta | None

Timezone offset applied to expr — "-03:00", a :class:CronOffsetEnum member, or a :class:~datetime.timedelta.

None
name str | None

Override the task name.

None
**options Any

Extra TaskIQ labels forwarded to the task.

{}

Returns:

Type Description
Callable[[Callable[P, Awaitable[R]]], Task[P, R]]

Callable[[Callable[P, Awaitable[R]]], Task[P, R]]: A decorator

Callable[[Callable[P, Awaitable[R]]], Task[P, R]]

returning the wrapped :class:Task.

interval

interval(
    seconds: float | timedelta, *, name: str | None = None, **options: Any
) -> Callable[[Callable[P, Awaitable[R]]], Task[P, R]]

Register a task to run every seconds.

Parameters:

Name Type Description Default
seconds float | timedelta

Interval between runs. A number is coerced to seconds.

required
name str | None

Override the task name.

None
**options Any

Extra TaskIQ labels forwarded to the task.

{}

Returns:

Type Description
Callable[[Callable[P, Awaitable[R]]], Task[P, R]]

Callable[[Callable[P, Awaitable[R]]], Task[P, R]]: A decorator

Callable[[Callable[P, Awaitable[R]]], Task[P, R]]

returning the wrapped :class:Task.

on_startup

on_startup(handler: HookT, *, scope: LifecycleScope = 'worker') -> HookT
on_startup(
    handler: None = None, *, scope: LifecycleScope = "worker"
) -> Callable[[HookT], HookT]
on_startup(
    handler: HookT | None = None, *, scope: LifecycleScope = "worker"
) -> HookT | Callable[[HookT], HookT]

Run a callback when the process this queue lives in starts.

The worker has no FastAPI lifespan, so without this there is nowhere to open the database, the message broker or an HTTP client — and nowhere to close them either. This is that place::

queue = TaskQueue.rabbitmq(settings.TASKIQ_BROKER_URL)

@queue.on_startup
async def _open() -> None:
    await db.connect()

@queue.on_shutdown
async def _close() -> None:
    await db.disconnect()

For the common case of resources that already speak connect / disconnect, :meth:use does both in one line.

Parameters:

Name Type Description Default
handler HookT | None

The callback, when used as a bare @queue.on_startup. None when called with arguments.

None
scope LifecycleScope

Which process runs it. The default "worker" deliberately leaves the web process alone — it has its own lifespan — so a module imported by both does not open the same resource twice.

'worker'

Returns:

Type Description
HookT | Callable[[HookT], HookT]

HookT | Callable[[HookT], HookT]: The handler, unchanged (bare

HookT | Callable[[HookT], HookT]

form), or a decorator returning it.

on_shutdown

on_shutdown(handler: HookT, *, scope: LifecycleScope = 'worker') -> HookT
on_shutdown(
    handler: None = None, *, scope: LifecycleScope = "worker"
) -> Callable[[HookT], HookT]
on_shutdown(
    handler: HookT | None = None, *, scope: LifecycleScope = "worker"
) -> HookT | Callable[[HookT], HookT]

Run a callback when the process this queue lives in stops.

The mirror of :meth:on_startup; see it for the example.

Parameters:

Name Type Description Default
handler HookT | None

The callback, when used as a bare @queue.on_shutdown. None when called with arguments.

None
scope LifecycleScope

Which process runs it.

'worker'

Returns:

Type Description
HookT | Callable[[HookT], HookT]

HookT | Callable[[HookT], HookT]: The handler, unchanged (bare

HookT | Callable[[HookT], HookT]

form), or a decorator returning it.

use

use(*resources: LifecycleResource, scope: LifecycleScope = 'worker') -> None

Open resources when the process starts, close them when it stops.

The shortcut behind TaskQueue.rabbitmq(url, resources=[db, broker]). Anything with connect / disconnect fits — :class:~tempest_fastapi_sdk.db.AsyncDatabaseManager, :class:~tempest_fastapi_sdk.queue.MessageBroker, :class:~tempest_fastapi_sdk.storage.AsyncMinIOClient::

queue = TaskQueue.rabbitmq(url, resources=[db, broker])

They are opened left to right and closed right to left, so a resource that depends on an earlier one still has it while closing. connect / disconnect are looked up when the hook fires, not when use runs, so patching them later — on the class or on the instance, as a test does to keep the in-memory queue off a real broker — takes effect.

Parameters:

Name Type Description Default
*resources LifecycleResource

The resources to manage.

()
scope LifecycleScope

Which process manages them; see :meth:on_startup.

'worker'

connect async

connect() -> None

Start the broker so tasks can be enqueued and processed.

Idempotent — extra calls are no-ops while the broker is alive.

disconnect async

disconnect() -> None

Stop the scheduler (if running) and shut the broker down.

start_scheduler async

start_scheduler() -> Task[None]

Start the periodic scheduler loop in this process, unguarded.

This is the raw loop: it fires every schedule it owns, in every process that calls it. With more than one replica that means every schedule fires once per replica, and nothing says so — prefer lifespan(scheduler=True), which holds a lease so exactly one replica runs the loop.

Returns:

Type Description
Task[None]

asyncio.Task[None]: The scheduler loop task (cancelled by

Task[None]

meth:stop_scheduler / :meth:disconnect).

Raises:

Type Description
RuntimeError

When :meth:connect has not been called yet.

stop_scheduler async

stop_scheduler() -> None

Stop the in-process scheduler started by :meth:start_scheduler.

lifespan async

lifespan(
    *,
    scheduler: bool | Literal["unlocked"] = False,
    scheduler_lock: SchedulerLock | None = None,
    lease_name: str | None = None,
    lease_ttl_seconds: float = DEFAULT_LOCK_TTL_SECONDS,
) -> AsyncGenerator[TaskQueue, None]

Connect on entry, disconnect on exit — and optionally schedule.

Plugs straight into FastAPI, which is what removes the second process from a small deployment::

from contextlib import asynccontextmanager
from collections.abc import AsyncGenerator

from fastapi import FastAPI

tq = TaskQueue.from_settings(settings)


@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
    '''Open the queue and run periodic tasks in-process.'''
    async with tq.lifespan(scheduler=True):
        yield


app = FastAPI(lifespan=lifespan)

Parameters:

Name Type Description Default
scheduler bool | Literal['unlocked']

Whether to run the periodic scheduler here. False (default) keeps the pre-v0.282.0 behavior — broker only. True runs it behind a lease, so scaling the API to N replicas still fires each schedule once. "unlocked" runs it in every replica, which is a choice and not a default: a sweep that expires charges would expire them N times, and nothing raises.

False
scheduler_lock SchedulerLock | None

The lease to use. None derives a :class:~tempest_fastapi_sdk.tasks.RedisSchedulerLock from the broker's Redis URL, and needs none at all for the in-memory broker, which is one process by construction.

None
lease_name str | None

Redis key for the derived lease. Two services sharing one Redis instance need different names, or only one of them ever schedules.

None
lease_ttl_seconds float

How long the derived lease survives unrenewed. Renewals run at a third of it.

DEFAULT_LOCK_TTL_SECONDS

Yields:

Name Type Description
TaskQueue AsyncGenerator[TaskQueue, None]

This connected facade.

Raises:

Type Description
ValueError

When scheduler=True and no lease could be found or derived — see :meth:_resolve_scheduler_lock.

health_check async

health_check() -> bool

Return True while the broker is started.

Returns:

Name Type Description
bool bool

True while the broker is started.

AsyncTaskScheduler

AsyncTaskScheduler(
    broker: AsyncBroker, sources: Sequence[ScheduleSource] | None = None
)

Manage the lifecycle of a TaskIQ periodic-task scheduler.

Wraps :class:taskiq.TaskiqScheduler together with :class:taskiq.schedule_sources.LabelScheduleSource so periodic tasks are declared with decorators alongside regular tasks and the scheduler is started, stopped and (optionally) driven in-process from the FastAPI lifespan.

The scheduler does not execute task bodies directly — it kicks them into the same broker used by :class:AsyncTaskBrokerManager, where the worker process consumes and runs them. For production deployments, prefer running the standalone taskiq scheduler <module>:<name> CLI process, where <name> is a module-level binding of :attr:scheduler (the CLI resolves the spec with a plain getattr, so a dotted attribute path raises AttributeError); :meth:run_in_background is convenient for development and single-process services.

Typical usage::

from taskiq_aio_pika import AioPikaBroker
from tempest_fastapi_sdk.tasks import (
    AsyncTaskBrokerManager,
    AsyncTaskScheduler,
)

broker = AioPikaBroker("amqp://guest:guest@localhost:5672/")
tasks = AsyncTaskBrokerManager(broker)
scheduler = AsyncTaskScheduler(broker)

@scheduler.cron("*/5 * * * *")
async def heartbeat() -> None:
    ...

@scheduler.interval(seconds=30)
async def poll_remote() -> None:
    ...

# FastAPI lifespan
await tasks.connect()
await scheduler.connect()
await scheduler.run_in_background()  # dev / single-process only
...
await scheduler.disconnect()
await tasks.disconnect()

Attributes:

Name Type Description
broker AsyncBroker

The TaskIQ broker tasks are kicked into.

sources list[ScheduleSource]

Active schedule sources.

scheduler TaskiqScheduler

Underlying TaskIQ scheduler.

Initialize the scheduler manager.

Parameters:

Name Type Description Default
broker AsyncBroker

The TaskIQ broker periodic tasks will be kicked into. Reuse the same broker instance that :class:AsyncTaskBrokerManager wraps so registered tasks are visible to the schedule source.

required
sources Sequence[ScheduleSource] | None

Schedule sources to read scheduled tasks from. Defaults to a single :class:taskiq.schedule_sources.LabelScheduleSource bound to broker.

None

is_connected property

is_connected: bool

Return True once :meth:connect succeeded.

Returns:

Name Type Description
bool bool

True while the scheduler is started.

cron

cron(
    expr: str,
    *,
    cron_offset: str | timedelta | None = None,
    task_name: str | None = None,
    **labels: Any,
) -> Callable[[Callable[_P, _R]], AsyncTaskiqDecoratedTask[_P, _R]]

Register a task to run on a cron schedule.

Parameters:

Name Type Description Default
expr str

A cron expression (e.g. "*/5 * * * *" for every five minutes).

required
cron_offset str | timedelta | None

Optional timezone offset applied to expr ("-03:00" or a :class:datetime.timedelta).

None
task_name str | None

Override the auto-generated module:function task name.

None
**labels Any

Extra TaskIQ labels forwarded to broker.task.

{}

Returns:

Type Description
Callable[[Callable[_P, _R]], AsyncTaskiqDecoratedTask[_P, _R]]

Callable[[Callable[_P, _R]], AsyncTaskiqDecoratedTask[_P, _R]]:

Callable[[Callable[_P, _R]], AsyncTaskiqDecoratedTask[_P, _R]]

The decorator broker.task returns; the decorated name keeps

Callable[[Callable[_P, _R]], AsyncTaskiqDecoratedTask[_P, _R]]

the function's parameters and return type.

interval

interval(
    seconds: float | timedelta, *, task_name: str | None = None, **labels: Any
) -> Callable[[Callable[_P, _R]], AsyncTaskiqDecoratedTask[_P, _R]]

Register a task to run every seconds interval.

Parameters:

Name Type Description Default
seconds float | timedelta

Interval between runs. A :class:datetime.timedelta is used verbatim; a number is coerced to seconds via :class:datetime.timedelta.

required
task_name str | None

Override the auto-generated task name.

None
**labels Any

Extra TaskIQ labels forwarded to broker.task.

{}

Returns:

Type Description
Callable[[Callable[_P, _R]], AsyncTaskiqDecoratedTask[_P, _R]]

Callable[[Callable[_P, _R]], AsyncTaskiqDecoratedTask[_P, _R]]:

Callable[[Callable[_P, _R]], AsyncTaskiqDecoratedTask[_P, _R]]

The decorator broker.task returns; the decorated name keeps

Callable[[Callable[_P, _R]], AsyncTaskiqDecoratedTask[_P, _R]]

the function's parameters and return type.

schedule

schedule(
    spec: list[dict[str, Any]], *, task_name: str | None = None, **labels: Any
) -> Callable[[Callable[_P, _R]], AsyncTaskiqDecoratedTask[_P, _R]]

Register a task with a raw TaskIQ schedule spec.

Use this when you need time (one-shot at a specific datetime), multiple triggers on the same task, or any combination not covered by :meth:cron / :meth:interval.

Any cron_offset in spec goes through :func:~tempest_fastapi_sdk.tasks.normalize_cron_offset, so a numeric offset reaches the scheduler in the form it applies rather than as an unresolvable time zone key.

Parameters:

Name Type Description Default
spec list[dict[str, Any]]

The schedule list (each entry must carry one of cron, interval or time).

required
task_name str | None

Override the auto-generated task name.

None
**labels Any

Extra TaskIQ labels forwarded to broker.task.

{}

Returns:

Type Description
Callable[[Callable[_P, _R]], AsyncTaskiqDecoratedTask[_P, _R]]

Callable[[Callable[_P, _R]], AsyncTaskiqDecoratedTask[_P, _R]]:

Callable[[Callable[_P, _R]], AsyncTaskiqDecoratedTask[_P, _R]]

The decorator broker.task returns; the decorated name keeps

Callable[[Callable[_P, _R]], AsyncTaskiqDecoratedTask[_P, _R]]

the function's parameters and return type.

Raises:

Type Description
ValueError

When an entry's cron_offset is a string that is neither a "±HH:MM" offset nor a resolvable time zone key.

register

register(
    func: Callable[_P, _R],
    *,
    schedule: list[dict[str, Any]],
    task_name: str | None = None,
    **labels: Any,
) -> AsyncTaskiqDecoratedTask[_P, _R]

Register func as a scheduled task without decorator syntax.

Parameters:

Name Type Description Default
func Callable[_P, _R]

The async callable to register.

required
schedule list[dict[str, Any]]

The schedule list (see :meth:schedule for the format). Any cron_offset is normalized the same way.

required
task_name str | None

Override the auto-generated task name.

None
**labels Any

Extra TaskIQ labels forwarded to broker.task.

{}

Returns:

Type Description
AsyncTaskiqDecoratedTask[_P, _R]

AsyncTaskiqDecoratedTask[_P, _R]: The registered task,

AsyncTaskiqDecoratedTask[_P, _R]

preserving func's parameters and return type.

Raises:

Type Description
ValueError

When an entry's cron_offset is a string that is neither a "±HH:MM" offset nor a resolvable time zone key.

connect async

connect() -> None

Start the scheduler and every configured source.

:class:taskiq.TaskiqScheduler itself only starts the broker; we additionally call startup() on each source so the default :class:LabelScheduleSource discovers tasks declared via :meth:cron / :meth:interval / :meth:schedule / :meth:register. Safe to call multiple times — subsequent calls are no-ops while the scheduler is alive.

disconnect async

disconnect() -> None

Stop the background loop (if any) and shut the scheduler down.

run_in_background async

run_in_background() -> Task[None]

Run TaskIQ's scheduler loop as an in-process asyncio task.

Suitable for development and single-process services. For production deployments with multiple workers, run the standalone CLI instead so only one scheduler is active. Bind :attr:scheduler to a module-level name — the CLI resolves module:attr with a plain getattr, so a dotted path raises AttributeError::

# myapp/tasks.py
taskiq_scheduler = scheduler.scheduler

# shell
taskiq scheduler myapp.tasks:taskiq_scheduler

Returns:

Type Description
Task[None]

asyncio.Task[None]: The spawned task running

Task[None]

class:taskiq.cli.scheduler.run.SchedulerLoop. Calling

Task[None]

meth:disconnect cancels it.

Raises:

Type Description
RuntimeError

When :meth:connect has not been called yet.

lifespan async

lifespan() -> AsyncGenerator[TaskiqScheduler, None]

Yield the scheduler inside an async with block.

Connects on entry, disconnects on exit. The in-process loop is not started automatically — call :meth:run_in_background explicitly when you need it.

Yields:

Name Type Description
TaskiqScheduler AsyncGenerator[TaskiqScheduler, None]

The connected scheduler.

health_check async

health_check() -> bool

Return True when the scheduler has been started.

Schedule sources don't expose a generic ping, so we only report whether :meth:connect succeeded and (when applicable) the background loop is still alive.

Returns:

Name Type Description
bool bool

True while the scheduler is started and any

bool

in-process loop is still running.

StageColumns dataclass

StageColumns(name: str, status: str, error: str, result: str)

The resolved column names of one stage on one record.

Attributes:

Name Type Description
name str

The stage's name.

status str

Attribute holding the :class:StageStatusEnum.

error str

Attribute holding the failure message.

result str

Attribute holding what the stage produced.

StageMap

StageMap(
    stages: Sequence[str],
    *,
    prefix: str = "",
    status_template: str = "status_{stage}",
    error_template: str = "error_{stage}",
    result_template: str = "result_{stage}",
)

Declares a record's stages and performs their transitions.

Attributes:

Name Type Description
prefix str

Prepended to every resolved column name.

Declare the stages and how their columns are named.

The templates exist because column naming is a house convention, not something a library gets to impose — a codebase spelling them summary_status should not have to rename its schema to use this.

Parameters:

Name Type Description Default
stages Sequence[str]

Stage names, in the order the interface should show them.

required
prefix str

Prepended to every column name, for schemas that namespace a record's columns (doc_, meeting_).

''
status_template str

Column name for a stage's status, with {stage} substituted.

'status_{stage}'
error_template str

Column name for a stage's error.

'error_{stage}'
result_template str

Column name for a stage's result.

'result_{stage}'

Raises:

Type Description
ValueError

When stages is empty, or holds a duplicate, or when two stages would resolve to the same column name.

names property

names: tuple[str, ...]

The declared stage names, in declaration order.

Returns:

Type Description
tuple[str, ...]

tuple[str, ...]: The names.

columns

columns(stage: str) -> StageColumns

Resolve one stage's column names.

Parameters:

Name Type Description Default
stage str

The stage name.

required

Returns:

Name Type Description
StageColumns StageColumns

The resolved names.

Raises:

Type Description
KeyError

When the stage was not declared.

status

status(record: object, stage: str) -> StageStatusEnum | None

Read a stage's status off a record.

Parameters:

Name Type Description Default
record object

The row.

required
stage str

The stage name.

required

Returns:

Type Description
StageStatusEnum | None

StageStatusEnum | None: The status, or None when the column is

StageStatusEnum | None

empty — which means the stage was never requested, a state

StageStatusEnum | None

worth distinguishing from PENDING.

Raises:

Type Description
KeyError

When the stage was not declared.

is_running

is_running(record: object, stage: str) -> bool

Does this stage still have work to stop?

Parameters:

Name Type Description Default
record object

The row.

required
stage str

The stage name.

required

Returns:

Name Type Description
bool bool

True when the status is PENDING or RUNNING.

Raises:

Type Description
KeyError

When the stage was not declared.

owns

owns(record: object, stage: str, expected: StageStatusEnum) -> bool

Does the run that set expected still own this stage?

The check to make before writing a result, and it is about ownership rather than cancellation on purpose: a status that is no longer expected covers both the user cancelling and a newer run having restarted the stage. Writing in either case is wrong — one resurrects stopped work, the other clobbers a fresher result.

Parameters:

Name Type Description Default
record object

A freshly read row. Re-read it before calling this; an object loaded before the long work started still holds the old status and would answer True no matter what happened meanwhile.

required
stage str

The stage name.

required
expected StageStatusEnum

What this run left the stage at.

required

Returns:

Name Type Description
bool bool

True when the stage is still at expected.

Raises:

Type Description
KeyError

When the stage was not declared.

mark

mark(
    record: object,
    stage: str,
    status: StageStatusEnum,
    *,
    error: str | None = None,
    result: object = None,
) -> None

Move a stage, writing the error and result columns with it.

Mutates record in place and does not persist it — the caller owns the session and decides when to flush, which is what lets several stage writes share one transaction.

The error column is cleared on any status other than FAILED, so a restarted stage stops showing the message from the run before it.

Parameters:

Name Type Description Default
record object

The row.

required
stage str

The stage name.

required
status StageStatusEnum

The new status.

required
error str | None

The failure message; only meaningful with FAILED.

None
result object

What the stage produced. None leaves the result column untouched, so marking DONE without a value does not erase one written earlier.

None

Raises:

Type Description
KeyError

When the stage was not declared.

ValueError

When error is given with a status other than FAILED — that pairing means the caller mixed up two transitions, and silently dropping the message would hide it.

cancel

cancel(
    record: object, stages: Iterable[str] | None = None
) -> tuple[list[str], list[str]]

Cancel every requested stage that still has work to stop.

Idempotent, and deliberately partial: a stage that already finished is reported as ignored rather than raising. A screen polling for status will routinely ask to cancel something that completed a moment ago, and that is not an error.

There is no cascade, and none is needed when each stage only enqueues the next one on success: cancelling the first means the second is never created.

Parameters:

Name Type Description Default
record object

The row.

required
stages Iterable[str] | None

Which to cancel; None cancels every declared stage that is running.

None

Returns:

Type Description
list[str]

tuple[list[str], list[str]]: The stages cancelled, and those

list[str]

ignored, each in the order requested. Duplicates in the request

tuple[list[str], list[str]]

are collapsed, so a caller cannot get the same stage twice.

Raises:

Type Description
KeyError

When a requested stage was not declared.

snapshot

snapshot(record: object) -> dict[str, StageStatusEnum | None]

Read every stage's status at once.

What a status endpoint serializes, and what a test asserts on without naming a column.

Parameters:

Name Type Description Default
record object

The row.

required

Returns:

Type Description
dict[str, StageStatusEnum | None]

dict[str, StageStatusEnum | None]: Status per stage, in declaration

dict[str, StageStatusEnum | None]

order.

StageStatusEnum

Bases: StrEnum

Where one stage of a pipeline is.

  • PENDING — queued, nobody has started it.
  • RUNNING — a worker is on it.
  • DONE — finished; the result column is filled.
  • FAILED — stopped; the error column says why.
  • CANCELLED — the user asked it to stop. Terminal like the two above, and like them it is not re-entered on its own — but it is not a failure, so an interface highlighting FAILED should leave it alone.

run_cancellable async

run_cancellable(
    work: Awaitable[ResultT],
    *,
    interrupted: Callable[[], Awaitable[bool]],
    poll_seconds: float = DEFAULT_POLL_SECONDS,
    stop_event: Event | None = None,
) -> ResultT

Run work, aborting it as soon as interrupted() says to.

Parameters:

Name Type Description Default
work Awaitable[ResultT]

The coroutine doing the long work. It must be genuinely cancellable — async I/O, not a to_thread wrapper (see the module docstring) — unless it honours stop_event.

required
interrupted Callable[[], Awaitable[bool]]

Polled between checks; True means stop. Usually :meth:~tempest_fastapi_sdk.tasks.JobStore.cancellation_watch.

required
poll_seconds float

Seconds between checks.

DEFAULT_POLL_SECONDS
stop_event Event | None

Set before the coroutine is cancelled, so work running in a thread that watches this event stops too. Without it, a thread keeps going after the await is abandoned.

None

Returns:

Name Type Description
ResultT ResultT

Whatever work returned, when it finished first.

Raises:

Type Description
StageInterruptedError

The predicate said to stop. work is already cancelled by the time this propagates.

ValueError

When poll_seconds is not positive — a zero or negative interval would spin on the database.

Exception

Anything work itself raises, unchanged.

daily

daily(hour: int = 0, minute: int = 0) -> str

Return a cron expression firing once a day at hour:minute.

Parameters:

Name Type Description Default
hour int

Hour of day, 0-23.

0
minute int

Minute past the hour, 0-59.

0

Returns:

Name Type Description
str str

e.g. "0 9 * * *" for hour=9.

Raises:

Type Description
ValueError

When hour / minute is out of range.

every_minute

every_minute() -> str

Return a cron expression firing every minute ("* * * * *").

Returns:

Name Type Description
str str

The cron expression.

every_n_minutes

every_n_minutes(n: int) -> str

Return a cron expression firing every n minutes.

Parameters:

Name Type Description Default
n int

The minute step, 1-59.

required

Returns:

Name Type Description
str str

e.g. "*/5 * * * *" for n=5.

Raises:

Type Description
ValueError

When n is outside 1-59.

hourly

hourly(minute: int = 0) -> str

Return a cron expression firing once an hour at minute.

Parameters:

Name Type Description Default
minute int

Minute past the hour, 0-59.

0

Returns:

Name Type Description
str str

e.g. "30 * * * *" for minute=30.

Raises:

Type Description
ValueError

When minute is out of range.

monthly

monthly(day: int = 1, hour: int = 0, minute: int = 0) -> str

Return a cron expression firing once a month on day at hour:minute.

Parameters:

Name Type Description Default
day int

Day of month, 1-31.

1
hour int

Hour of day, 0-23.

0
minute int

Minute past the hour, 0-59.

0

Returns:

Name Type Description
str str

e.g. "0 0 1 * *" for the first of the month at midnight.

Raises:

Type Description
ValueError

When day / hour / minute is out of range.

normalize_cron_offset

normalize_cron_offset(value: str | timedelta) -> str | timedelta

Return cron_offset in the form TaskIQ actually applies.

TaskIQ reads cron_offset two different ways (taskiq/cli/scheduler/run.py, measured on taskiq 0.12.6): a :class:~datetime.timedelta is added to the current time, while a :class:str is handed to :class:zoneinfo.ZoneInfo as an IANA key. A numeric string such as "-03:00" is therefore not a key at all, and reaches the scheduler loop as ZoneInfoNotFoundError — which the loop does not catch (its except covers CronValueError only), so it stops scheduling for every task in the process, not just the one that declared the offset.

So the numeric forms this SDK hands out (:class:CronOffsetEnum) are converted to the timedelta TaskIQ applies, and any other string is resolved as an IANA key here, at declaration time, where the traceback still names the caller.

A fixed offset also needs no time zone database, which an IANA key does: on an image without one, ZoneInfo("UTC") already raises.

Parameters:

Name Type Description Default
value str | timedelta

A :class:CronOffsetEnum member, a "±HH:MM" offset, an IANA key ("America/Sao_Paulo"), or a :class:~datetime.timedelta.

required

Returns:

Type Description
str | timedelta

str | timedelta: A timedelta for the numeric forms, or the

str | timedelta

IANA key unchanged once it is known to resolve.

Raises:

Type Description
ValueError

When value is a string that is neither a "±HH:MM" offset nor a resolvable time zone key.

normalize_schedule

normalize_schedule(spec: Iterable[dict[str, Any]]) -> list[dict[str, Any]]

Return spec with every entry's cron_offset normalized.

Applies :func:normalize_cron_offset to each entry that declares one, so a raw schedule spec reaches the broker in the form TaskIQ applies. Entries are shallow-copied, leaving the caller's list and dicts untouched.

Parameters:

Name Type Description Default
spec Iterable[dict[str, Any]]

Schedule entries, each carrying one of cron, interval or time, and optionally cron_offset.

required

Returns:

Type Description
list[dict[str, Any]]

list[dict[str, Any]]: The normalized entries, in order.

Raises:

Type Description
ValueError

When an entry's cron_offset is a string that is neither a "±HH:MM" offset nor a resolvable time zone key.

weekdays

weekdays(hour: int = 0, minute: int = 0) -> str

Return a cron expression firing Mon-Fri at hour:minute.

Parameters:

Name Type Description Default
hour int

Hour of day, 0-23.

0
minute int

Minute past the hour, 0-59.

0

Returns:

Name Type Description
str str

e.g. "0 9 * * MON-FRI".

Raises:

Type Description
ValueError

When hour / minute is out of range.

weekends

weekends(hour: int = 0, minute: int = 0) -> str

Return a cron expression firing Sat-Sun at hour:minute.

Parameters:

Name Type Description Default
hour int

Hour of day, 0-23.

0
minute int

Minute past the hour, 0-59.

0

Returns:

Name Type Description
str str

e.g. "0 9 * * SAT,SUN".

Raises:

Type Description
ValueError

When hour / minute is out of range.

weekly

weekly(day: WeekdayEnum | str, hour: int = 0, minute: int = 0) -> str

Return a cron expression firing once a week on day at hour:minute.

Parameters:

Name Type Description Default
day WeekdayEnum | str

The weekday (WeekdayEnum.MON or a raw token).

required
hour int

Hour of day, 0-23.

0
minute int

Minute past the hour, 0-59.

0

Returns:

Name Type Description
str str

e.g. "0 9 * * MON".

Raises:

Type Description
ValueError

When hour / minute is out of range.

make_dead_letter_admin_model

make_dead_letter_admin_model(
    model: type[BaseDeadLetterModel],
    *,
    tq: TaskQueue | None = None,
    requeue_label: str = "Requeue task",
    delete_after: bool = True,
) -> AdminModel[Any]

Build a read-mostly :class:AdminModel over a dead-letter table.

Register the result on your :class:~tempest_fastapi_sdk.admin.AdminSite to get the dead-letter panel: a filterable, searchable list of terminal failures. Pass tq to add the requeue bulk action.

Parameters:

Name Type Description Default
model type[BaseDeadLetterModel]

The concrete dead-letter table.

required
tq TaskQueue | None

When given, adds a requeue bulk action wired to this queue.

None
requeue_label str

Label for the requeue action.

'Requeue task'
delete_after bool

Delete a row once requeued.

True

Returns:

Type Description
AdminModel[Any]

AdminModel[Any]: A preconfigured admin registration (no create/edit).

make_dead_letter_model

make_dead_letter_model(
    *, tablename: str = "dead_letters", class_name: str = "DeadLetterModel"
) -> type[BaseDeadLetterModel]

Build a concrete dead-letter model bound to tablename.

For tests and lightweight scripts; production code should subclass :class:BaseDeadLetterModel by hand so migrations pick it up statically.

Parameters:

Name Type Description Default
tablename str

The table name.

'dead_letters'
class_name str

The generated class name.

'DeadLetterModel'

Returns:

Type Description
type[BaseDeadLetterModel]

type[BaseDeadLetterModel]: The concrete model class.

make_requeue_action

make_requeue_action(
    tq: TaskQueue, *, label: str = "Requeue task", delete_after: bool = True
) -> Callable[[AdminActionContext], Awaitable[AdminActionResult | None]]

Build an admin bulk action that re-enqueues selected dead letters.

Each selected row is re-enqueued on tq's broker with its stored args / kwargs; rows whose task is no longer registered are skipped. Successfully requeued rows are deleted when delete_after is set.

Parameters:

Name Type Description Default
tq TaskQueue

The queue to re-enqueue onto.

required
label str

The action label shown in the admin dropdown.

'Requeue task'
delete_after bool

Delete a row once its call is re-enqueued.

True

Returns:

Type Description
Callable[[AdminActionContext], Awaitable[AdminActionResult | None]]

Callable[[AdminActionContext], Awaitable[AdminActionResult | None]]:

Callable[[AdminActionContext], Awaitable[AdminActionResult | None]]

An @admin_action-decorated handler, ready for

Callable[[AdminActionContext], Awaitable[AdminActionResult | None]]

AdminModel(actions=[...]) (needs the admin module).

task_inventory

task_inventory(tq: TaskQueue) -> list[TaskInfo]

List every task registered on tq's broker, sorted by name.

Reads the declared task set (name + schedule + retry labels) off the broker — no live queue state is involved.

Parameters:

Name Type Description Default
tq TaskQueue

The task queue whose broker to inspect.

required

Returns:

Type Description
list[TaskInfo]

list[TaskInfo]: One entry per registered task, sorted by name.

heartbeat_age

heartbeat_age(path: str | Path, *, now: datetime | None = None) -> float | None

Return how many seconds ago the heartbeat in path was written.

The age comes from the timestamp inside the file, not from its modification time, so copying or touching the file does not make a dead process look alive.

Parameters:

Name Type Description Default
path str | Path

The heartbeat file.

required
now datetime | None

The reference instant; defaults to the current time.

None

Returns:

Type Description
float | None

float | None: The age in seconds (negative when the file is from

float | None

the future, e.g. clock skew between containers sharing a volume),

float | None

or None when there is no readable heartbeat.

is_heartbeat_fresh

is_heartbeat_fresh(
    path: str | Path, max_age: float, *, now: datetime | None = None
) -> bool

Return whether the heartbeat in path is younger than max_age.

Parameters:

Name Type Description Default
path str | Path

The heartbeat file.

required
max_age float

The oldest acceptable heartbeat, in seconds. Pick about three times the heartbeat period, so one late beat does not flip the container to unhealthy.

required
now datetime | None

The reference instant; defaults to the current time.

None

Returns:

Name Type Description
bool bool

True when the file holds a timestamp at most max_age

bool

seconds old and no more than

bool

data:HEARTBEAT_FUTURE_TOLERANCE_SECONDS in the future;

bool

False when it is older, too far ahead, missing or unreadable.

Raises:

Type Description
ValueError

When max_age is not finite or not positive.

read_heartbeat

read_heartbeat(path: str | Path) -> datetime | None

Read the timestamp a heartbeat file holds.

Parameters:

Name Type Description Default
path str | Path

The heartbeat file.

required

Returns:

Type Description
datetime | None

datetime | None: The recorded instant (timezone-aware, UTC), or

datetime | None

None when the file is missing, unreadable or does not hold a

datetime | None

timestamp.

validate_max_age

validate_max_age(max_age: float) -> float

Refuse a max_age no heartbeat can be judged against.

nan compares false with everything, so age <= nan would call every file stale — and inf would call every file fresh, forever. Zero or a negative value can never be met.

Parameters:

Name Type Description Default
max_age float

The oldest acceptable heartbeat, in seconds.

required

Returns:

Name Type Description
float float

max_age unchanged.

Raises:

Type Description
ValueError

When max_age is not finite or not positive.

write_heartbeat

write_heartbeat(path: str | Path, *, now: datetime | None = None) -> None

Atomically write the current UTC time to path.

The timestamp goes to a temporary file in the same directory, which then replaces path with :func:os.replace. A reader therefore sees the previous timestamp or the new one, never a half-written file — which a healthcheck running every few seconds would otherwise hit sooner or later and report as a failure.

Parameters:

Name Type Description Default
path str | Path

The heartbeat file. Its directory must exist.

required
now datetime | None

The instant to record; defaults to the current time. A naive value is read as UTC.

None

The file ends up with :data:HEARTBEAT_FILE_MODE (0644), so a checker running as another user can read it.

Raises:

Type Description
OSError

When the directory is missing, read-only or full.

make_job_admin_model

make_job_admin_model(
    model: type[BaseJobModel], *, can_delete: bool = False
) -> AdminModel[Any]

Build a read-mostly :class:AdminModel over a job table.

Register the result on your :class:~tempest_fastapi_sdk.admin.AdminSite and the admin gets the list half of the task panel for free — pagination, filtering, sorting and CSV/JSON export over the same rows the workers write. Symmetric to :func:~tempest_fastapi_sdk.tasks.make_dead_letter_admin_model, which does the same for terminal failures.

Create and edit are off: a job row is a record of what a worker did, and an operator typing a new one describes work nobody will run. Deleting is off by default for the same reason, and available for the retention sweep an operator does want.

Parameters:

Name Type Description Default
model type[BaseJobModel]

The concrete job table.

required
can_delete bool

Whether the admin may delete rows. Defaults to False.

False

Returns:

Type Description
AdminModel[Any]

AdminModel[Any]: A preconfigured admin registration (no

AdminModel[Any]

create/edit). The admin package is imported under

AdminModel[Any]

TYPE_CHECKING and inside the function, so tasks still

AdminModel[Any]

imports without it.

make_job_model

make_job_model(
    *, tablename: str = "jobs", class_name: str = "JobModel"
) -> type[BaseJobModel]

Build a concrete job model bound to tablename.

For tests and lightweight scripts; production code should subclass :class:BaseJobModel by hand so Alembic picks it up statically.

Parameters:

Name Type Description Default
tablename str

The table name.

'jobs'
class_name str

The generated class name.

'JobModel'

Returns:

Type Description
type[BaseJobModel]

type[BaseJobModel]: The concrete model class.

make_dead_letter_middleware

make_dead_letter_middleware(
    sink: DeadLetterSink, *, default_max_retries: int = 3
) -> TaskiqMiddleware

Build a TaskIQ middleware routing terminally-failed tasks to sink.

Parameters:

Name Type Description Default
sink DeadLetterSink

Where dead letters go. Its own failures are swallowed (logged) so a broken sink never crashes the worker.

required
default_max_retries int

Fallback attempt cap for tasks that enable retries without setting their own max_retries.

3

Returns:

Name Type Description
TaskiqMiddleware TaskiqMiddleware

The middleware instance (needs the [tasks]

TaskiqMiddleware

extra).

make_registered_labels_middleware

make_registered_labels_middleware() -> TaskiqMiddleware

Build the worker middleware that restores a task's registered labels.

A call sent by name (:meth:TaskQueue.enqueue_by_name) comes from a process that never imported the task, so the message carries none of the labels the task was registered with — retry_on_error / max_retries from a :class:RetryPolicy, timeout, ack_type. TaskIQ's worker reads only the message labels, so without this the retry policy silently stops applying. Before any other middleware runs, it merges the labels of the task as the worker registered it under the message's own, which still win.

Returns:

Name Type Description
TaskiqMiddleware TaskiqMiddleware

The middleware instance (needs the [tasks]

TaskiqMiddleware

extra).

task_method

task_method(
    name: str | None = None, *, retry: RetryPolicy | None = None, **options: Any
) -> Callable[[Callable[..., Awaitable[Any]]], Callable[..., Awaitable[Any]]]

Mark a :class:TaskDef method as a background task (grouped form).

Parameters:

Name Type Description Default
name str | None

Override the auto-generated module:function task name.

None
retry RetryPolicy | None

Per-task retry configuration, the same keyword :meth:~tempest_fastapi_sdk.tasks.TaskQueue.task takes. Named rather than left to **options because TaskIQ reads labels, not objects: a RetryPolicy forwarded verbatim lands as a retry label nothing looks at, and the task silently never retries. Overrides :attr:TaskDef.retry. Needs :meth:~tempest_fastapi_sdk.tasks.TaskQueue.enable_retries.

None
**options Any

Extra TaskIQ labels / options forwarded to the task registration.

{}

Returns:

Name Type Description
Callable Callable[[Callable[..., Awaitable[Any]]], Callable[..., Awaitable[Any]]]

The same method, tagged so register can find it.

SchedulerLock

Bases: Protocol

The three calls leader election needs from a lease.

A service with its own coordination — etcd, ZooKeeper, a Postgres advisory lock — implements this and passes it to :meth:~tempest_fastapi_sdk.tasks.TaskQueue.lifespan; nothing here knows about Redis.

Every method is a coroutine because acquiring a lease is I/O in every implementation worth having.

acquire async

acquire() -> bool

Try to take the lease without waiting.

Returns:

Name Type Description
bool bool

True when this process now holds it, False

bool

when another one does. Must not block: a replica that

bool

waited here would delay its own startup behind the leader's

bool

entire lifetime.

renew async

renew() -> bool

Extend a lease this process already holds.

Returns:

Name Type Description
bool bool

True when the lease was extended, False when

bool

it was lost — expired, or taken over. False must stop

bool

the scheduler loop: a lost lease means another replica is

bool

already running it.

release async

release() -> None

Give up the lease, if this process still holds it.

Releasing on shutdown is what lets another replica take over in seconds instead of after the TTL. Must tolerate being called when the lease was never acquired or was already lost.

RedisSchedulerLock

RedisSchedulerLock(
    client: RedisLockClient,
    *,
    name: str = DEFAULT_LOCK_NAME,
    ttl_seconds: float = DEFAULT_LOCK_TTL_SECONDS,
)

A :class:SchedulerLock over the lock redis-py ships.

Example:

>>> import redis.asyncio as redis
>>> from tempest_fastapi_sdk.tasks import RedisSchedulerLock
>>>
>>> lock: RedisSchedulerLock = RedisSchedulerLock(
...     redis.Redis.from_url("redis://localhost:6379/0"),
... )

Attributes:

Name Type Description
name str

The Redis key the lease lives under.

ttl_seconds float

How long the lease survives unrenewed.

Wrap a Redis client as a scheduler lease.

Parameters:

Name Type Description Default
client RedisLockClient

An async Redis client. Anything with lock fits, which is what lets the suite run this against fakeredis.

required
name str

The key to lock. Give two services sharing one Redis instance different names, or one of them will never schedule.

DEFAULT_LOCK_NAME
ttl_seconds float

Lease duration. See :data:DEFAULT_LOCK_TTL_SECONDS for why the default is what it is.

DEFAULT_LOCK_TTL_SECONDS

Raises:

Type Description
ValueError

When ttl_seconds is not positive, which would make every lease expire on arrival and hand the schedule to whichever replica polled last.

from_url classmethod

from_url(
    url: str,
    *,
    name: str = DEFAULT_LOCK_NAME,
    ttl_seconds: float = DEFAULT_LOCK_TTL_SECONDS,
) -> RedisSchedulerLock

Build the lease from a Redis URL.

Parameters:

Name Type Description Default
url str

A redis:// / rediss:// URL.

required
name str

The key to lock.

DEFAULT_LOCK_NAME
ttl_seconds float

Lease duration.

DEFAULT_LOCK_TTL_SECONDS

Returns:

Name Type Description
RedisSchedulerLock RedisSchedulerLock

The lease, over a client of its own.

Raises:

Type Description
ImportError

When redis is not installed, which means the [cache] extra is missing.

acquire async

acquire() -> bool

Try to take the lease without waiting.

Returns:

Name Type Description
bool bool

Whether this process now holds it.

renew async

renew() -> bool

Extend the lease this process holds.

replace_ttl is set, so the lease is pushed to a fixed ttl_seconds from now rather than accumulating: a leader up for a week would otherwise hold a week-long lease, and its death would stop the schedule until that ran out.

A renewal that fails because the transport failed is indistinguishable, from here, from one that fails because another replica took the lease. Standing down is the safe direction in both: a gap of at most one TTL costs a late tick, while guessing the other way runs two schedulers. The key is released on the way out, so a lease this process still owned goes back immediately instead of waiting out the TTL.

Returns:

Name Type Description
bool bool

Whether the lease is still held afterwards. False

bool

once it has been lost, and it stays False.

release async

release() -> None

Give up the lease if it is still held.

A failure here is logged and swallowed: this runs on shutdown, and raising would replace whatever actually stopped the process. The lease expires on its own within ttl_seconds anyway.

TaskIQSettingsLike

Bases: Protocol

The two settings fields :meth:TaskQueue.from_settings reads.

Typed as a protocol rather than as :class:~tempest_fastapi_sdk.settings.TaskIQSettings so a service composing its own Settings from the mixins passes without an import cycle, and so a test can hand over a plain object.

Every member is a read-only @property. A bare annotation in a Protocol declares a settable attribute, and :class:~tempest_fastapi_sdk.settings.BaseAppSettings is frozen=True — so mypy rejected the very Settings the mixins build (expected settable variable, got read-only attribute) and the documented TaskQueue.from_settings(Settings()) needed a type: ignore. A property accepts both the frozen settings and a plain object with ordinary attributes.

Attributes:

Name Type Description
TASKIQ_BROKER_URL str

Broker URL. Empty selects the in-memory broker, which is the shape a test suite and a dev box without Redis actually run in.

TASKIQ_RESULT_BACKEND_URL str | None

Where task results go. None means "same place as the broker" when the broker can store results, and "nowhere" when it cannot.

TASKIQ_STORE_RESULTS bool

Whether results are stored at all. False leaves TaskIQ's DummyResultBackend in place on both transports, which is the shape of a cron-only service: no caller is waiting on a return value, so every stored result is pure cost.

TASKIQ_RESULT_TTL_SECONDS int

Seconds a stored result survives; 0 keeps results forever.

TASKIQ_BROKER_URL property

TASKIQ_BROKER_URL: str

Return the broker URL.

TASKIQ_RESULT_BACKEND_URL property

TASKIQ_RESULT_BACKEND_URL: str | None

Return where task results go.

TASKIQ_STORE_RESULTS property

TASKIQ_STORE_RESULTS: bool

Return whether results are stored at all.

TASKIQ_RESULT_TTL_SECONDS property

TASKIQ_RESULT_TTL_SECONDS: int

Return the seconds a stored result survives.

LifecycleResource

Bases: Protocol

Anything the queue can open on startup and close on shutdown.

:class:~tempest_fastapi_sdk.db.AsyncDatabaseManager, :class:~tempest_fastapi_sdk.queue.MessageBroker and :class:~tempest_fastapi_sdk.storage.AsyncMinIOClient all satisfy it, which is what makes resources=[db, broker] work without the SDK naming any of them.

connect async

connect() -> None

Open the resource.

disconnect async

disconnect() -> None

Close the resource.

LifecycleScope module-attribute

LifecycleScope = Literal['worker', 'client', 'both']

Which process a lifecycle hook runs in.

"worker" is the taskiq worker process, "client" is whoever calls :meth:TaskQueue.connect (typically the web application's lifespan), "both" is either. TaskQueue.memory() runs both sides in one process, so a worker-scoped hook fires there as well.

ResultSerializer module-attribute

ResultSerializer = Literal['json', 'pickle']

How stored task results are encoded in Redis.

"json" (the default) stores data only. "pickle" is what taskiq_redis uses on its own, and reading a pickled value runs whatever code the stored bytes name: anyone able to write the result keys (a co-tenant on a shared Redis, a leaked credential) gets code execution in the process that reads the result. It stays available as an explicit opt-in for a Redis nobody else can write.

Hook module-attribute

Hook = Callable[[], Awaitable[None] | None]

A lifecycle callback taking no arguments. Sync or async.

TERMINAL_JOB_STATUSES module-attribute

TERMINAL_JOB_STATUSES: frozenset[str] = frozenset(
    {
        JobStatusEnum.DONE.value,
        JobStatusEnum.FAILED.value,
        JobStatusEnum.CANCELLED.value,
    }
)

Statuses a job never leaves: the poll stops, the payload is gone.

STALE_JOB_ERROR module-attribute

STALE_JOB_ERROR: str = "The worker stopped responding while this job was running, and the claim budget is spent."

error written by :meth:JobStore.reclaim_stale when it gives up.

A constant rather than a per-row message because the sweep is a single UPDATE and interpolating each row's attempt count into it would mean reading the rows first — the read-then-write shape this module avoids.

STORE_OWNED_JOB_COLUMNS module-attribute

STORE_OWNED_JOB_COLUMNS: frozenset[str] = frozenset(
    {
        "id",
        "is_active",
        "created_at",
        "updated_at",
        "kind",
        "status",
        "stage",
        "progress",
        "params",
        "payload",
        "result_id",
        "error",
        "attempts",
        "max_attempts",
        "started_at",
        "finished_at",
    }
)

Columns of :class:BaseJobModel that :meth:JobStore.succeed refuses in values.

Every column the abstract model declares — its own and the four it inherits from :class:~tempest_fastapi_sdk.db.model.BaseModel. Each one either is a transition the store owns (status, finished_at, progress, payload, attempts), has a parameter of its own (result_id), or is identity (id, kind, created_at). values exists for the columns a project adds on its subclass, so letting it reach these would make succeed able to write a DONE row that says RUNNING. A test pins this set against a concrete model, so a column added to :class:BaseJobModel fails there instead of becoming writable by accident.

make_job_admin_model

make_job_admin_model(
    model: type[BaseJobModel], *, can_delete: bool = False
) -> AdminModel[Any]

Build a read-mostly :class:AdminModel over a job table.

Register the result on your :class:~tempest_fastapi_sdk.admin.AdminSite and the admin gets the list half of the task panel for free — pagination, filtering, sorting and CSV/JSON export over the same rows the workers write. Symmetric to :func:~tempest_fastapi_sdk.tasks.make_dead_letter_admin_model, which does the same for terminal failures.

Create and edit are off: a job row is a record of what a worker did, and an operator typing a new one describes work nobody will run. Deleting is off by default for the same reason, and available for the retention sweep an operator does want.

Parameters:

Name Type Description Default
model type[BaseJobModel]

The concrete job table.

required
can_delete bool

Whether the admin may delete rows. Defaults to False.

False

Returns:

Type Description
AdminModel[Any]

AdminModel[Any]: A preconfigured admin registration (no

AdminModel[Any]

create/edit). The admin package is imported under

AdminModel[Any]

TYPE_CHECKING and inside the function, so tasks still

AdminModel[Any]

imports without it.