Wait steps¶
A wait step waits for one thing belonging to a run, then ends with its value or the
TimedOut outcome. Declare an async def with @sensor when you write the waiting
yourself, or a function with @sensor.poke(every=...) when schedr should call it
repeatedly: an async def, or a plain def (see A plain def poke). To
wait for another DAG’s run or task, use wait_for(RunOf(...)), which can
also produce Failed. Wait steps and triggers side by
side compares every form.
"""Wait steps: a value, or the `TimedOut` outcome downstream tasks route on.
Two wait steps ask schedr's REST API about a task of their own run: one that succeeds after five
seconds, and one the run doesn't have. `full_report` runs when both have ended. A task always waits
for all its upstream tasks, so `fast_report` follows `first_of`, a node the master ends with the
first of them to have its value. Point `schedr_api` at your webserver; with sign-in on, the calls
would need a token too.
"""
import asyncio
import json
import time
import urllib.request
from collections.abc import AsyncIterator
from datetime import timedelta
from http.client import HTTPResponse
from typing import cast
from schedr import NOT_YET, Dag, NotYet, TimedOut, connection, dag_ctx, first_of, sensor, task
type Run = dict[str, list[dict[str, str | None]]]
"""What `GET /api/v1/runs/{run}` answers, as far as this example reads it."""
@connection(base_url="http://localhost:8080")
async def schedr_api(base_url: str) -> AsyncIterator[str]:
"""Stands in for an async client, opened with `async with`."""
yield base_url
def read_run(url: str) -> Run:
"""A blocking call: the wait steps make it in a thread, leaving their event loop free."""
with cast("HTTPResponse", urllib.request.urlopen(url, timeout=5)) as answer:
return cast("Run", json.load(answer))
async def has_succeeded(task_id: str) -> bool:
"""Whether a task of this run has succeeded, as the REST API says."""
async with schedr_api() as base_url:
url = f"{base_url}/api/v1/runs/{dag_ctx.run.id}"
run = await asyncio.to_thread(read_run, url)
return any(t["task_id"] == task_id and t["state"] == "success" for t in run["tasks"])
@task
def slow_task() -> None:
"""Succeeds after five seconds, well inside what the wait steps allow."""
time.sleep(5)
@sensor.poke(every=timedelta(seconds=1), max_wait=timedelta(seconds=10), connections=[schedr_api])
async def sees_slow_task() -> str | NotYet:
"""Called every second until it returns a value, for at most ten seconds."""
return "Task slow_task success" if await has_succeeded("slow_task") else NOT_YET
@sensor(max_wait=timedelta(seconds=10), connections=[schedr_api])
async def sees_absent_task() -> str:
"""Full control: it writes its own waiting. The run has no such task, so its time runs out."""
while not await has_succeeded("absent_task"):
await asyncio.sleep(1)
return "Task absent_task success"
@task
def full_report(first: str | TimedOut, second: str | TimedOut) -> str:
"""Runs on either outcome of each, and says what came of both."""
said = [
f"{name}: {'timed out' if isinstance(value, TimedOut) else value}"
for name, value in (("sees_slow_task", first), ("sees_absent_task", second))
]
print("\n".join(said))
return "; ".join(said)
@task
def fast_report(value: str, winner: str) -> str:
"""Runs as soon as one of them has its value, the other perhaps still waiting."""
said = f"{winner} came first: {value}"
print(said)
return said
with Dag("sensors_demo", description="Waits for a value, and routes on whether it came in time."):
slow_task()
slow = sees_slow_task()
absent = sees_absent_task()
full_report(slow.on(str, TimedOut), absent.on(str, TimedOut))
value, winner = first_of(slow.on(str), absent.on(str), with_winner=True)
fast_report(value, winner)
A poke returns its value when ready, or NOT_YET while waiting: annotate it -> str | NotYet. None is a value, not a signal to wait. Calls never overlap. A call that runs past
every is an overrun (its own time counts, not a stall of the event loop after it): it may
finish, and the next call comes right after it. The poke fails (PokeTooSlowError, with the
usual retries) after [watchers] poke_overruns overruns in a row while returning NOT_YET
(3 by default), or at once when one call runs three times every, when it is cancelled. A
call that returns its value within that hard limit ends the wait successfully. A call that
raises is a failure with the usual retries too. A call that holds the event loop is another
limit: see below.
A plain def poke¶
A poke may be a plain def, for a blocking client: schedr calls it on the host’s threads,
as asyncio.to_thread would, so it doesn’t hold up the other wait steps on the host. The
call belongs to its wait step, as an async call does: its prints go to the step’s log,
task_ctx and the step’s secrets work in it (task_ctx.secret(...), the plain form), and
its call has the same window as an async poke’s (it may run past every, up to three times
it). Past that, the call is stopped as an asyncio.to_thread call is (see below):
StepEndedError at its next Python line, or, for a call blocked in C, its host ending after
the cancel grace. A plain def opens a plain connection (with name() as client:). A plain
def that returns a coroutine (a plain wrapper of an async def) has it awaited. @sensor
itself, and wait_for=, stay async def.
@connection(folder="/tmp/schedr-plain-pokes", status_url="http://localhost:8080/api/v1/version")
def orders_inbox(folder: str, status_url: str) -> Iterator[tuple[Path, str]]:
"""A plain connection, opened with `with` in a plain `def`: the folder and a URL to ask."""
yield Path(folder), status_url
@sensor.poke(every=timedelta(seconds=30), max_wait=timedelta(hours=2), connections=[orders_inbox])
def orders_ready() -> int | NotYet:
"""A plain `def`: blocking calls are fine here, each with a timeout below `every`."""
with orders_inbox() as (folder, status_url):
marker = folder / "orders.done"
if not marker.exists():
return NOT_YET
# A blocking HTTP call, its own timeout (10 s) well inside the call's window (`every`).
with cast("HTTPResponse", urllib.request.urlopen(status_url, timeout=10)) as answer:
answer.read()
return int(marker.read_text() or "0")
@task
def load_orders(count: int) -> str:
"""Runs once the marker is there."""
return f"{count} orders"
with Dag("plain_poke_demo", description="A plain `def` poke waits for a marker file."):
load_orders(orders_ready().on(int))
Which to choose:
An async client where there is one: many pokes wait on one thread, and a call is cancelled where it awaits.
A plain
deffor a blocking client (a database driver,requests, a cloud SDK without async), rather than anasync defthat blocks the event loop, which holds up every wait step on the host and is killed past[watchers] block_limit.Give each blocking call a timeout of its own, below
every: a call that ends by itself is always cleaner than one stopped from outside, which may leave a library’s state half updated.Plain pokes run side by side, each on a thread of its own, so what they share (module globals, a client kept between calls) must be thread-safe.
Keep them light. A poke busy in Python, not waiting, holds the interpreter’s lock and slows every other wait step on the host. Put heavy work in a task.
The host sizes its thread pool for one call per wait step, plus Python’s default pool
size for the steps’ own asyncio.to_thread calls. Threads start as needed. This gives
plain pokes room to run alongside one another; it does not guarantee call timing.
max_wait= limits the wait. If omitted, [sensors] default_max_wait applies (24 hours by
default), except for delay given a timedelta, as described below. Set max_wait in
StepDefaults for a DAG or group; timeout there applies to task attempts. When the wait
expires, schedr produces TimedOut: leave it out of the function’s return type.
Waiting for a time¶
Import delay and until from schedr.sensors for built-in wait steps:
"""Wait for a duration and for a moment, then use the times they ended."""
from datetime import UTC, datetime, timedelta
from schedr import Dag, task
from schedr.sensors import delay, until
@task
def report(ended: datetime) -> None:
print(f"Wait ended at {ended.isoformat()}")
with Dag(
"wait_times",
description="Waits for a duration and for a moment, then uses the times they ended.",
):
pause = delay(timedelta(milliseconds=100))
scheduled = until(timedelta(milliseconds=100))
past = until(datetime(2020, 1, 1, tzinfo=UTC))
report(pause.on(datetime))
report.override(task_id="report_scheduled")(scheduled.on(datetime))
report.override(task_id="report_past")(past.on(datetime))
delay(timedelta(...)) waits from its first try’s start. If tried again, it waits only
what is left. until(timedelta(...)) waits until that duration after the run’s
planned_for; until(datetime) waits until that moment, which must have a time zone.
A moment already past ends at once. A run parameter can supply either argument.
Both steps return the moment they ended as a datetime; use .on(datetime) to pass it
to a task. They produce TimedOut past max_wait. For delay given a timedelta,
the default max_wait is that duration plus one minute; otherwise the usual wait step
default applies. Their IDs are delay and until, numbered from the second call
(delay_2, until_2, …); set task_id= to choose one.
What downstream tasks see¶
Suppose file is a call of a wait step returning str, and load takes path: str.
The call reads as Waited[str]: it can produce a value or TimedOut.
Expression |
What happens |
|---|---|
|
Runs with the value; the edge is not taken on timeout. |
|
Runs |
|
Receives either; write |
|
Orders |
|
Orders |
|
Refused at parse and by type checkers: the timeout is also possible. |
A failed wait step is not a timeout: downstream tasks end upstream_failed. When a
downstream task has another upstream task, run_if decides what happens when an edge is
not taken, as described in Routing by outcome. A timeout leaves the run
success whether or not a task takes it. Use .on(TimedOut) to do something about it.
A task normally waits for its upstream edges to be decided before it runs. To act on the first of several, as
fast_report does above, use first_of.
Running and deploying wait steps¶
This section describes sensors. The master ends wait_for(RunOf(...)) without a watcher.
Wait steps using the same interpreter and code copies run as coroutines in one long-lived
process, the watcher host. It stops when its last wait step ends. A DAG file’s top level is
imported once per host, so module globals are shared between its wait steps. The working
directory and environment belong to the host, not a run: use absolute paths and read run
values from dag_ctx and task_ctx, never SCHEDR_* environment variables.
Use asynchronous clients and yield while waiting: a blocking call holds up the other wait
steps on the host. If one holds the loop past [watchers] block_limit (30 seconds by
default), its host is killed and it fails blocked_event_loop without a retry. The other
wait steps start again on a new host in the same attempt, with their max_wait
still running and no retry used. Put heavy work in a task. Read declared secrets with
await task_ctx.asecret(...) or
await task_ctx.asecret_value(...); the plain forms hold the loop when a secret under a
SecretPrefix must be fetched. See Secrets.
A wait step can’t start a process or a thread of its own: nothing could stop what it left running
while other wait steps keep the host alive, and a retry could overlap it. Use an async client or
asyncio.to_thread, or run a command in a task after the wait step.
When its DAG is defined, so
schedr dags checksays so before you deploy: a wait step’s code usingsubprocess,os.system,os.fork,os.spawn*,os.exec*,multiprocessing,ProcessPoolExecutor,asyncio.create_subprocess_*,threading.Thread,threading.TimerorThreadPoolExecutor, or a function, decorator or class of your own that does, is an import error naming the call and its line. A class named inisinstance,issubclassor an annotation is fine. This reads what the code names, so it can miss a value it can’t follow.When it runs, for what can’t be read that way (a library’s insides,
getattr, a function passed in): starting a process raisesProcessInWaitStepError, from a thread of the step too. The standard library’splatformandctypes.utilhelpers still work, as client libraries call them and they wait for their command. A library may start threads; nothing refuses those.
This isn’t a sandbox: C code gets past both, and what it leaves running lives until the host stops.
asyncio.to_thread belongs to its wait step: its prints go to the step’s log, task_ctx works in
it, and it runs out of time with the step. When the call is cancelled (max_wait, three times every, a cancel,
your own asyncio.timeout) or the step ends with the call still running, StepEndedError is raised
in its thread at its next Python line. It isn’t an Exception, so except Exception doesn’t stop
it, and finally runs. Python can’t reach a thread blocked in C (time.sleep(600), a read with no
timeout): if it hasn’t ended after the cancel grace, the step’s result is reported and the host is
killed; the other wait steps start again as described above. Give blocking calls a timeout of
their own, and put heavy work, such as a large query in a library with its own threads, in a task.
That error can land on any Python line, also halfway through a library updating its own state, such
as a connection pool or a cache. with and finally run, but code with no cleanup for it stays
half done, and the other wait steps of the same code share that library in their process. So a call
that has a timeout of its own, and ends by itself, is always the safer way to stop.
When a step ends, asyncio tasks it left running are cancelled and awaited. print and
Python logging from the step go to its attempt log, as does a thread it started; output from
C code, or from a thread still running after its step ended, goes to the host’s log, masked
for secrets. Unmanaged library threads may live until the host stops; make sure the library
closes them when the step ends. The step’s log warns if a library leaves a thread running.
When new code arrives, a @sensor.poke moves between calls if it can start on that code.
It keeps its deadline and uses no retry; its log says it moved and the attempt reports the
code it moved to. If the task was renamed or removed, the file cannot be imported, or the
new signature does not fit the run’s arguments, it stays on its old code and its log says
why. A full-control @sensor stays on its code until it ends, keeping its host and code copy:
frequent deploys with very long waits can therefore cost memory. A retry starts on the newest
code.
A wait step takes a watcher slot ([watchers] slots, 500 per worker by default), not a task slot.
Its max_wait runs from its first start, over retries and moves. A draining worker hands its pokes
to others at once, using no retry; a full-control @sensor gets the drain’s grace time, then runs
again elsewhere, also using no retry. Cancellation gives it the usual grace time; if it does not end, its host is killed and the other wait steps start
again as above. A host crash is handled differently; see The watcher host.
After [watchers] switch_off_after host kills in a row (default 3), a wait step is switched
off: new attempts fail switched_off without reaching a host. A success resets the count.
New code gives it one chance: another strike switches it off again until a success. List these
steps with schedr sensors switched-off and switch one on with
schedr sensors switch-on <dag> <sensor>. The DAG page lists its switched-off wait steps
and has a Switch on button; the DAGs list shows a banner with their count and links to
their DAGs.
Limits for now¶
cleanup= is refused; use finally in the function. .expand() on a wait step is
refused. preload and fresh_process are not options.
A function that ignores cancellation at max_wait is stopped past the grace period and
fails timed_out.
Testing¶
await wait.fn(...), or asyncio.run(wait.fn(...)), calls the function itself. For a
poke this is one call, which may return NOT_YET; a plain def poke’s .fn runs it on a
thread, as its host does, so it is awaited the same way. run_dag runs the wait step for real;
see Testing a DAG.