A job queue kept in the vault file: work survives a crash, failures are retried with a growing delay, and jobs that keep failing are set aside for a person
Fetching a page, ingesting a batch of files and rebuilding the topic map can fail or stop part way. Queue keeps such work as rows in a jobs table in the vault’s own SQLite file. A job outlives the process that queued it. No separate server is needed.
enqueue adds a job. A worker takes jobs with claim. claim marks the jobs as running and gives the worker a lease, which is a time limit on the claim (lease, 10 minutes by default). Two workers that claim at the same time never get the same job.
If a worker dies, its lease runs out. reclaim then fails the job with the error lease expired. This counts as one attempt.
A job that fails runs again after a delay. The delay doubles with each failure, from 30 seconds up to 6 hours. After max_attempts failures (5 by default) the job is dead. A dead job stays in the table with its error, for a person to examine.
The queue lives in the same file as the documents. A job queued inside a write_txn is committed with the write that caused it. Queue needs only a database and knows nothing about a vault. acquire registers the vault’s own jobs on it.
def backoff( attempt:int, # failures so far; 1 on the first base:float=30, # first delay, seconds cap:float=21600, # longest delay, 6h jitter:float=0.25, # +/- fraction of the delay; spreads out jobs that failed together)->float:
The delay before the next attempt: base seconds doubled for each failure so far, at most cap, with some random jitter.
Raise from a handler to have the job run again when nothing failed but the work should be retried, such as a bot wall, an HTTP 429 or an empty read.
The queue
A job has a kind, which names the handler that runs it, and a payload, a dict stored as JSON. key makes queueing idempotent. While a job with the same kind and key is waiting or running, enqueue returns that job and adds no second one. A repeated fan-out does not double the work. A job with a lower priority number runs first.
def Queue( db, # open litesearch/fastlite Database; the queue lives in its file lease:float=600, # seconds a claim is held before another worker may take the job max_attempts:int=5, # attempts before a job is dead-lettered base:float=30, # first retry delay; doubles per attempt keep:float=604800, # how long finished jobs and run history survive `purge`, 7d busy_ms:int=30000, # lock wait before a write gives up; apsw's stock default is 100ms):
A job queue stored in an open litesearch database, which runs every job at least once.
def enqueue( kind:str, # which handler runs it payload:dict=None, # arguments, stored as JSON run_at:float=None, # epoch seconds; defaults to now priority:int=0, # lower runs first key:str=None, # idempotency key: an identical key still ready or running wins max_attempts:int=None)->fastcore.basics.AttrDict:
Add one job, or return the waiting or running job that already has this key.
Claiming
claim picks and marks its jobs in one SQL statement. SQLite runs one write at a time. No other worker can take a job between the pick and the mark. Every job that claim returns is already running and already leased.
ack (finished) and fail (failed) count only while the job is still running under the caller’s worker name. Each worker needs its own name. A handler slower than lease loses its job to reclaim, and another worker can claim it. Without this check, the late ack could mark as done a job that another worker is still running. The late fail could send a finished job back for a third run. A late call returns the job with the state lost, and the run history records lost.
def fail( job, # the claimed job error:str, # what went wrong; truncated to 500 chars on the row after:float=None, # seconds until the retry; None uses `backoff` dead:bool=False, # dead-letter now, whatever the attempts left: retrying a 401 never turns into success)->fastcore.basics.AttrDict:
Record a failure and schedule a retry after the backoff delay, or mark the job dead once its attempts are spent.
def claim( worker:str='worker', # who is holding the lease; recorded on the row and in history n:int=1, # how many jobs to take now:float=None)->fastcore.foundation.L:
Claim up to n due jobs in one statement; no job was claimed twice over 400 jobs and 8 processes (evals/jobs.py).
Running
A handler is a function fn(payload). Register it with register or the on decorator. run_one runs one claimed job. drain claims and runs jobs until the queue is empty or limit jobs have run. A cron job calls drain. The way a handler ends sets what happens to the job:
the handler
the job
returns normally
is done
returns a dict with a true skipped value
is done, recorded as a skip, and not retried. The acquisition methods do this when a page has no transcript or is not a PDF
is retried after Retry.after seconds or the backoff delay, and uses one attempt. Use it for work that did not fail but must run again, such as a page behind a bot wall
raises any other exception
is retried after the backoff delay, and dead once its attempts are spent
Use Terminal for a failure that waiting cannot fix, such as a 401, a model name that does not exist or a file that is gone. Without it, the default schedule retries a doomed job for most of a day. A job whose kind has no handler is dead at once, for the same reason.
def drain( worker:str='worker', # lease holder recorded on each job limit:int=1000, # jobs to run before returning; a ceiling, not a target batch:int=1, # jobs claimed per round trip now:float=None)->fastcore.foundation.L:
Claim and run jobs until the queue is empty or limit jobs have run.
jobs lists jobs by state and kind. pending counts the jobs that are waiting or running. stats counts the jobs in each state. history lists past runs.
dead lists the dead jobs with the error that ended each one. A failure deletes nothing. retry puts a dead job back on the queue and resets its attempt count. purge deletes finished jobs and run history older than keep (7 days by default). purge leaves dead jobs alone.
Some work does not run on the queue. An app runs it in its own thread pool and shows its progress, such as a download, a model call or a build. Ledger keeps one row for each such job, so the app can show what runs and what ended, also after a restart. A row has kind, state, title, said (the progress line), start, end, url, obj (the thing the job is about), why (the reason for a failure), seen and quiet. Other keys go in the meta of the row.
The rows are in their own job_ledger table in the vault file. Queue does not see them: it never claims, retries or counts a ledger row. version goes up at each write, also in another process, so a page can ask whether anything changed.
def Ledger( db, # open litesearch/fastlite Database; the rows live in its file keep:float=172800, # seconds an ended row stays, 2 days run:str=None, # the id of this process; None -> `RUN` busy_ms:int=30000):
Rows for jobs that run elsewhere, such as an in-process future: their state, a progress line and a change counter.
put merges keys into a row and makes the row when it is new. start writes a running row and end ends it. get reads one row and rows lists them, newest first.
track writes the row of a future and ends it when the future ends: done, or failed with why. A row is never retried: the work is the caller’s. A row that ended first, such as a job that you stopped, stays as it is. say writes the progress line of a running job. A write that fails never breaks the job.
def track( kind:str, # what the job is fut, # a `concurrent.futures.Future`, or a function that returns one, called after the row is written key:str=None, # the row; None -> a new key, which the future has as `fut.key` ok:NoneType=None, # `ok(result) -> dict`: more keys for the row when it ends, and `state` to end in another state why:NoneType=None, # `why(error) -> str`: the line of a failure**meta):
Write a running row for the future fut, and end it when fut ends. Return the future.
A row that says running after a restart belongs to a job that died with its process. close_running, called at the start of an app, marks each such row closed. It closes only the rows of other processes. seen marks the ended rows of one object as seen, and activity gives the rows an app shows now: the running ones, then the ended ones not seen yet. A row that you stopped and a quiet row are left out.