# jobs


<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->

Fetching a page, ingesting a batch of files and rebuilding the topic map
can fail or stop part way.
[`Queue`](https://vedicreader.github.io/vishalakshi/jobs.html#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`](https://vedicreader.github.io/vishalakshi/jobs.html#queue)
needs only a database and knows nothing about a vault.
[acquire](01_acquire.ipynb) registers the vault’s own jobs on it.

------------------------------------------------------------------------

<a
href="https://github.com/vedicreader/vishalakshi/blob/main/vishalakshi/jobs.py#L27"
target="_blank" style="float:right; font-size:smaller">source</a>

### backoff

``` python
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.*

------------------------------------------------------------------------

<a
href="https://github.com/vedicreader/vishalakshi/blob/main/vishalakshi/jobs.py#L24"
target="_blank" style="float:right; font-size:smaller">source</a>

### Terminal

``` python
def Terminal(
    *args, **kwargs
):
```

*Raise from a handler to mark the job dead at once, for a failure that
retrying cannot fix, such as a 401 or a missing file.*

------------------------------------------------------------------------

<a
href="https://github.com/vedicreader/vishalakshi/blob/main/vishalakshi/jobs.py#L18"
target="_blank" style="float:right; font-size:smaller">source</a>

### Retry

``` python
def Retry(
    msg:str='', after:float=None
):
```

*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.

------------------------------------------------------------------------

<a
href="https://github.com/vedicreader/vishalakshi/blob/main/vishalakshi/jobs.py#L43"
target="_blank" style="float:right; font-size:smaller">source</a>

### Queue

``` python
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.*

------------------------------------------------------------------------

<a
href="https://github.com/vedicreader/vishalakshi/blob/main/vishalakshi/jobs.py#L103"
target="_blank" style="float:right; font-size:smaller">source</a>

### Queue.enqueue_all

``` python
def enqueue_all(
    kind:str, payloads, **kw
)->fastcore.foundation.L:
```

*Enqueue many jobs of one kind in a single transaction.*

------------------------------------------------------------------------

<a
href="https://github.com/vedicreader/vishalakshi/blob/main/vishalakshi/jobs.py#L81"
target="_blank" style="float:right; font-size:smaller">source</a>

### Queue.enqueue

``` python
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`.

------------------------------------------------------------------------

<a
href="https://github.com/vedicreader/vishalakshi/blob/main/vishalakshi/jobs.py#L159"
target="_blank" style="float:right; font-size:smaller">source</a>

### Queue.reclaim

``` python
def reclaim(
    now:float=None
)->fastcore.foundation.L:
```

*Fail each running job whose lease expired with `lease expired`; this
counts one attempt, and the job is dead after `max_attempts`.*

------------------------------------------------------------------------

<a
href="https://github.com/vedicreader/vishalakshi/blob/main/vishalakshi/jobs.py#L141"
target="_blank" style="float:right; font-size:smaller">source</a>

### Queue.fail

``` python
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.*

------------------------------------------------------------------------

<a
href="https://github.com/vedicreader/vishalakshi/blob/main/vishalakshi/jobs.py#L132"
target="_blank" style="float:right; font-size:smaller">source</a>

### Queue.ack

``` python
def ack(
    job
)->fastcore.basics.AttrDict:
```

*Mark a claimed job done, or return it as `lost` when this worker’s
lease was reclaimed.*

------------------------------------------------------------------------

<a
href="https://github.com/vedicreader/vishalakshi/blob/main/vishalakshi/jobs.py#L109"
target="_blank" style="float:right; font-size:smaller">source</a>

### Queue.claim

``` python
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:

<table>
<colgroup>
<col style="width: 50%" />
<col style="width: 50%" />
</colgroup>
<thead>
<tr>
<th>the handler</th>
<th>the job</th>
</tr>
</thead>
<tbody>
<tr>
<td>returns normally</td>
<td>is done</td>
</tr>
<tr>
<td>returns a dict with a true <code>skipped</code> value</td>
<td>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</td>
</tr>
<tr>
<td>raises <a
href="https://vedicreader.github.io/vishalakshi/jobs.html#retry"><code>Retry</code></a></td>
<td>is retried after <code>Retry.after</code> 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</td>
</tr>
<tr>
<td>raises any other exception</td>
<td>is retried after the backoff delay, and dead once its attempts are
spent</td>
</tr>
<tr>
<td>raises <a
href="https://vedicreader.github.io/vishalakshi/jobs.html#terminal"><code>Terminal</code></a></td>
<td>is dead at once</td>
</tr>
</tbody>
</table>

Use
[`Terminal`](https://vedicreader.github.io/vishalakshi/jobs.html#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.

------------------------------------------------------------------------

<a
href="https://github.com/vedicreader/vishalakshi/blob/main/vishalakshi/jobs.py#L214"
target="_blank" style="float:right; font-size:smaller">source</a>

### Queue.drain

``` python
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.*

------------------------------------------------------------------------

<a
href="https://github.com/vedicreader/vishalakshi/blob/main/vishalakshi/jobs.py#L192"
target="_blank" style="float:right; font-size:smaller">source</a>

### Queue.run_one

``` python
def run_one(
    job
)->fastcore.basics.AttrDict:
```

*Run the handler for one claimed job, then ack or fail the job, and
record the run.*

------------------------------------------------------------------------

<a
href="https://github.com/vedicreader/vishalakshi/blob/main/vishalakshi/jobs.py#L176"
target="_blank" style="float:right; font-size:smaller">source</a>

### Queue.register

``` python
def register(
    kind:str, fn
):
```

*Register the handler for `kind`.*

------------------------------------------------------------------------

<a
href="https://github.com/vedicreader/vishalakshi/blob/main/vishalakshi/jobs.py#L168"
target="_blank" style="float:right; font-size:smaller">source</a>

### Queue.on

``` python
def on(
    kind:str
):
```

*Decorator registering the handler for `kind`.*

### Looking at it

`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.

------------------------------------------------------------------------

<a
href="https://github.com/vedicreader/vishalakshi/blob/main/vishalakshi/jobs.py#L271"
target="_blank" style="float:right; font-size:smaller">source</a>

### Queue.purge

``` python
def purge(
    before:float=None
)->dict:
```

*Delete finished jobs and run history older than `keep`. Dead jobs
stay.*

------------------------------------------------------------------------

<a
href="https://github.com/vedicreader/vishalakshi/blob/main/vishalakshi/jobs.py#L264"
target="_blank" style="float:right; font-size:smaller">source</a>

### Queue.stats

``` python
def stats()->dict:
```

*How many jobs in each state, and when the next one is due.*

------------------------------------------------------------------------

<a
href="https://github.com/vedicreader/vishalakshi/blob/main/vishalakshi/jobs.py#L258"
target="_blank" style="float:right; font-size:smaller">source</a>

### Queue.history

``` python
def history(
    job_id:str=None, limit:int=50
)->fastcore.foundation.L:
```

*Run history, newest first.*

------------------------------------------------------------------------

<a
href="https://github.com/vedicreader/vishalakshi/blob/main/vishalakshi/jobs.py#L250"
target="_blank" style="float:right; font-size:smaller">source</a>

### Queue.retry

``` python
def retry(
    job_id:str, after:float=0
)->fastcore.basics.AttrDict:
```

*Put a dead or pending job back on the queue now, with its attempt count
reset.*

------------------------------------------------------------------------

<a
href="https://github.com/vedicreader/vishalakshi/blob/main/vishalakshi/jobs.py#L244"
target="_blank" style="float:right; font-size:smaller">source</a>

### Queue.pending

``` python
def pending(
    kind:str=None
)->int:
```

*Count the jobs still waiting or running, optionally of one kind.*

------------------------------------------------------------------------

<a
href="https://github.com/vedicreader/vishalakshi/blob/main/vishalakshi/jobs.py#L239"
target="_blank" style="float:right; font-size:smaller">source</a>

### Queue.dead

``` python
def dead(
    limit:int=100
)->fastcore.foundation.L:
```

*Dead jobs: those that used up their attempts or failed with
[`Terminal`](https://vedicreader.github.io/vishalakshi/jobs.html#terminal),
each with its last error.*

------------------------------------------------------------------------

<a
href="https://github.com/vedicreader/vishalakshi/blob/main/vishalakshi/jobs.py#L230"
target="_blank" style="float:right; font-size:smaller">source</a>

### Queue.jobs

``` python
def jobs(
    state:str=None, kind:str=None, limit:int=100
)->fastcore.foundation.L:
```

*Jobs, soonest first, filtered by state and kind.*

## Ledger

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`](https://vedicreader.github.io/vishalakshi/jobs.html#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`](https://vedicreader.github.io/vishalakshi/jobs.html#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.

------------------------------------------------------------------------

<a
href="https://github.com/vedicreader/vishalakshi/blob/main/vishalakshi/jobs.py#L289"
target="_blank" style="float:right; font-size:smaller">source</a>

### Ledger

``` python
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.

------------------------------------------------------------------------

<a
href="https://github.com/vedicreader/vishalakshi/blob/main/vishalakshi/jobs.py#L360"
target="_blank" style="float:right; font-size:smaller">source</a>

### Ledger.purge

``` python
def purge(
    before:float=None
)->int:
```

*Delete the ended rows that ended before `before`, by default `keep`
seconds ago. Return the count.*

------------------------------------------------------------------------

<a
href="https://github.com/vedicreader/vishalakshi/blob/main/vishalakshi/jobs.py#L353"
target="_blank" style="float:right; font-size:smaller">source</a>

### Ledger.rows

``` python
def rows(
    state:str=None, kind:str=None, obj:str=None
)->fastcore.foundation.L:
```

*The rows, newest first, filtered by `state`, `kind` and `obj`.*

------------------------------------------------------------------------

<a
href="https://github.com/vedicreader/vishalakshi/blob/main/vishalakshi/jobs.py#L347"
target="_blank" style="float:right; font-size:smaller">source</a>

### Ledger.end

``` python
def end(
    key:str, state:str='done', why:str='', **kv
)->fastcore.basics.AttrDict | None:
```

*End the row `key` now in `state`, with `why` for a failure. None when
there is no row.*

------------------------------------------------------------------------

<a
href="https://github.com/vedicreader/vishalakshi/blob/main/vishalakshi/jobs.py#L340"
target="_blank" style="float:right; font-size:smaller">source</a>

### Ledger.start

``` python
def start(
    key:str, kind:str, title:str='', said:str='', url:str='', obj:str='', quiet:bool=False, **meta
)->fastcore.basics.AttrDict:
```

*Write the row `key` of a job of `kind` that runs now. Ended rows older
than `keep` go.*

------------------------------------------------------------------------

<a
href="https://github.com/vedicreader/vishalakshi/blob/main/vishalakshi/jobs.py#L328"
target="_blank" style="float:right; font-size:smaller">source</a>

### Ledger.put

``` python
def put(
    key:str, **kv
)->fastcore.basics.AttrDict:
```

*Merge `kv` into the row `key`, and make the row when it is new. A key
that is not a column goes in `meta`.*

------------------------------------------------------------------------

<a
href="https://github.com/vedicreader/vishalakshi/blob/main/vishalakshi/jobs.py#L323"
target="_blank" style="float:right; font-size:smaller">source</a>

### Ledger.get

``` python
def get(
    key:str
)->fastcore.basics.AttrDict | None:
```

*The row `key`, or None.*

`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.

------------------------------------------------------------------------

<a
href="https://github.com/vedicreader/vishalakshi/blob/main/vishalakshi/jobs.py#L394"
target="_blank" style="float:right; font-size:smaller">source</a>

### Ledger.say

``` python
def say(
    key:str, line:str
)->bool:
```

*Write the progress line `line` to the row `key` while its job runs.
Whether the row changed.*

------------------------------------------------------------------------

<a
href="https://github.com/vedicreader/vishalakshi/blob/main/vishalakshi/jobs.py#L368"
target="_blank" style="float:right; font-size:smaller">source</a>

### Ledger.track

``` python
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.

------------------------------------------------------------------------

<a
href="https://github.com/vedicreader/vishalakshi/blob/main/vishalakshi/jobs.py#L418"
target="_blank" style="float:right; font-size:smaller">source</a>

### Ledger.activity

``` python
def activity(
    fresh:float=21600, # seconds an ended row shows until it is seen, 6 hours
    now:float=None
)->fastcore.foundation.L:
```

*The running rows, newest first, then the rows that ended in the last
`fresh` seconds and are not seen, newest first.*

------------------------------------------------------------------------

<a
href="https://github.com/vedicreader/vishalakshi/blob/main/vishalakshi/jobs.py#L411"
target="_blank" style="float:right; font-size:smaller">source</a>

### Ledger.seen

``` python
def seen(
    obj:str
)->int:
```

*Mark each ended row of the object `obj` as seen. Return the count that
changed.*

------------------------------------------------------------------------

<a
href="https://github.com/vedicreader/vishalakshi/blob/main/vishalakshi/jobs.py#L403"
target="_blank" style="float:right; font-size:smaller">source</a>

### Ledger.close_running

``` python
def close_running()->int:
```

*Mark `closed` each running row that another process wrote. Return the
count.*

## Try it

``` python
from litesearch import database

db = database()
q  = Queue(db, lease=60, max_attempts=3, base=1)
seen = []
q.register('echo', lambda p: seen.append(p['n']) or dict(n=p['n']))
q.enqueue_all('echo', [dict(n=i) for i in range(3)])
q.drain('w1')
seen, q.stats()
```

    ([0, 1, 2], {'ready': 0, 'running': 0, 'done': 3, 'dead': 0, 'next_due': None})
