Repository navigation
Task Queue and Concurrency
Checked against v0.7.6 on November 13, 2026.
Kestrel does its background work through one table, task. Scraping a source, embedding a posting, scoring at Tier 1 and Tier 2, and the longer jobs behind the buttons (stories, interview questions, company summaries, Model check, training the sorting model) are all rows in it. This page explains how a row is claimed, retried and recovered, how the worker orders its work, and why everything shares one event loop. For the table definition, see Database schema. For the larger picture, see Architecture overview.
The design follows hard rule 5 in CLAUDE.md: every unit of work is a task row, so killing the process at any moment and restarting continues cleanly. Nothing that matters lives only in memory.
Task in kestrel/db/models.py has these columns:
| Column | Meaning |
|---|---|
type |
What to do: scrape, embed, t1, t2, t0_recheck, build_stories, interview_questions, title_suggestions, org_summary, org_research, org_contacts, follow_up, letter_draft, train_reranker, bench, ollama_pull, ollama_create. Architecture overview says who creates and who handles each. |
payload |
JSON, usually {"opportunity_id": N} or {"source_id": N}, plus flags such as requested, model_override or lane. |
status |
pending, leased, done, dead or cancelled. |
priority |
Higher runs first. Scoring tasks use int(pre_score * 100), so the best Tier 0 survivors reach the models first. |
attempts, max_attempts
|
How many times it has been leased, and the ceiling (default 3). |
lease_until, worker_id
|
Who holds it and until when. |
retry_at |
When a task that failed and was requeued becomes claimable again (migration 0029). Null means now. |
opportunity_id |
The role the task is about, copied from the payload by database triggers so per-role lookups use an index (migration 0030). The payload stays the source. |
last_error |
The most recent failure text, cut to 4,000 characters. |
TASK_STATUS in kestrel/db/enums.py also lists failed, but no queue code writes it. A failed task ends as dead, and kestrel/services/model_tasks.py checks for both values when it reports on downloads.
Not every type is scoring. t3 does not appear in the list above because the hosted Tier 3 escalation is not a worker stage: the operator starts it for one opportunity (kestrel/pipeline/tier3.py). Score again is not a type either: it sets rescore in the payload of a t1 or t2 task (kestrel/queue/rescore.py). The partial unique index below does name t3 and rescore as types it protects, but nothing creates or leases a task of either type.
TaskQueue in kestrel/queue/queue.py is a thin layer of guarded UPDATE statements. It has no in-memory state.
TaskQueue.enqueue(type, payload, priority=..., max_attempts=...) inserts a row. Scoring work goes through a different function, enqueue_once in kestrel/pipeline/tasks.py, which adds a task only if no live one (pending or leased) already exists for that type and opportunity. It adds the row to the caller's session, so the stage change and the next task commit together. A crash cannot leave a role advanced with no task behind it, or a task with no advance.
Two processes can run the pipeline at once (the desktop app and kestrel worker from a terminal). Both could pass the "does a live task exist?" check. Migration 0014 adds a partial unique index so the database decides:
CREATE UNIQUE INDEX ux_task_live_scoring ON task (type, json_extract(payload, '$.opportunity_id'))
WHERE status IN ('pending', 'leased') AND type IN ('t1', 't2', 't3', 'rescore')
AND json_extract(payload, '$.opportunity_id') IS NOT NULL;enqueue_once inserts with INSERT OR IGNORE. If the insert changes zero rows, another process won the race and the function returns False, meaning "already queued".
lease() claims one task with a single guarded update and checks rowcount == 1. It picks the highest priority, then the lowest id, among tasks that are claimable:
-
status = 'pending'with noretry_at, or one whoseretry_athas passed, or -
status = 'leased'withlease_untilin the past andattempts < max_attempts.
The update repeats the same condition, so if two workers pick the same candidate, only one update matches and the loser moves on to the next candidate (up to eight tries). attempts goes up at lease time, not at failure time. A worker that crashes without ever calling fail() still uses an attempt, so a task that kills its worker cannot loop forever. An expired lease on a task with no attempts left is not re-run. reclaim_expired() moves it to dead.
claimable() is shared with the run log and the Cancel scan logic, so "is there work" and "what would a lease take" cannot disagree.
-
heartbeat(task_id, worker_id)extendslease_untilonly if that worker still holds the task. Renewal loops are canceled when a task ends, often mid-write, and a cancel landing inside a database call would abandon its connection unclosed. So the write is shielded (asyncio.shield): it runs to the end even when the caller is canceled, and the cancel is raised afterwards. -
complete(task_id, worker_id)marks itdoneonly for the owning worker. A stale worker whose lease expired cannot overwrite a task that was re-leased to someone else. -
fail(task_id, error, retry=True)recordslast_error. Ifretryis true andattempts < max_attempts, the task goes back topendingwith its lease cleared andretry_atset, so it backs off before the next try: 30 seconds after the first failed attempt, 2 minutes after the second, 10 minutes after any later one (_RETRY_BACKOFF_Sinkestrel/queue/queue.py). Otherwise it becomesdead. A task waiting out its backoff still counts as live work, so the run summary does not report an idle queue. When the operator asks again for work that is already waiting (Score again, Try again, Download, Draft, Build stories),run_nowclearsretry_atso it runs at the next pass. -
defer(task_id, note)gives a leased task back unstarted:pendingagain, the lease's attempt refunded, the reason kept inlast_error. It is for work that cannot go out right now and is neither failed nor lost (see Pause, hold and stop).
The worker passes retry=False for scrapes. A scrape that failed already recorded a scrape_run, and retrying through the queue would hit a public site that just answered with an error.
Several scoring lanes commit lease, result and completion back to back. On a slow disk, a waiting writer can lose the lock race for longer than the five second busy_timeout, and SQLite answers "database is locked". Every queue call goes through _with_lock_retry: it retries the whole operation up to six times with jittered exponential backoff (a 0.05 second base, doubled each attempt) and re-raises anything that is not a lock error. Because each queue write is one short transaction, retrying it whole is safe. lease() claims in one call and reads the row in a second, so a lock on the read can never cause a second claim.
| Situation | What happens |
|---|---|
| Handler returns an error outcome or raises |
fail(..., retry=True): back to pending until max_attempts, then dead. The worker keeps draining. |
| Process killed mid-task | The lease expires. At the next worker start, reclaim_expired() returns the row to pending, or to dead if its attempts are used up. The crashed attempt stays spent, so a task that keeps failing still stops after three tries. |
| Graceful quit | The worker is told to stop. Idle work stops at once. A model call already running gets server.quit_grace_s (default 5 seconds, 0 to 30; WORKER_STOP_S in kestrel/web/app.py is the fallback when settings cannot be read), then it is canceled, and the whole quit is bounded by that grace plus two small fixed waits. release_all_leased() then returns what this process still had leased to pending and gives the in-flight attempt back, because quitting on purpose is not a failure. A lease an earlier process left behind after a crash is not refunded; it is reclaimed like an expired lease. |
| Orphaned role | A role at t0_pass or t1_pass with no live task, no newer evaluation and no quarantine gets its task re-enqueued once (kestrel/pipeline/orphans.py). A second orphaning is shown as "stuck" with a Score again button instead of looping. |
| Open run left by a killed process |
close_orphaned_runs closes the stale run row at startup. |
Handlers are idempotent on opportunity.stage. If the process dies after a handler commits its stage change but before the task is marked done, the re-leased task sees the advanced stage and finishes without a second model call.
Model downloads and builds (ollama_pull, ollama_create) are long. For those types, a stale-lease reclaim also gives the used attempt back (RESTART_REFUND_TYPES), so a crash mid-download does not exhaust the retries. A restore or a reset hands back only the work it stops: it passes the worker ids of a running download or build to release_all_leased(keep_worker_ids=...), which leaves those leases alone so the download finishes once.
A Tier 2 call can outlive any fixed lease. The per-request timeout is 600 seconds, and the guarded call may make an attempt, a repair, and a re-ask in one task. If the lease expired mid-call, the next cycle would re-lease the row while the first handler was still scoring, and two handlers would write duplicate evaluations and race on opp.stage. A role one handler set to t1_reject could lose to another handler's t1_pass. Wrongly rejecting a role is the failure hard rule 4 exists to prevent.
kestrel/pipeline/worker.py defends in two ways:
- The lease is 900 seconds (
_TASK_LEASE_S), longer than one request. - A heartbeat task (
_renew_lease) renews it every 120 seconds while the handler runs. A "database is locked" answer backs off and retries sooner. If the heartbeat finds the lease already lost, it stops renewing and logspipeline_lease_lost.
Scrapes use a 1,800 second lease with no heartbeat. The default for a bare lease() call is 300 seconds. Each background drain of a long job leases its own tasks and renews the lease while the job runs: story builds, interview questions, title suggestions, company summaries and Model check use _renew in kestrel/interview/story_task.py (a 600 second lease, renewed every 120), research and follow-up drafts reuse the scoring heartbeat _renew_lease, and training the sorting model has its own.
The worker, the scheduler, the update check, the delivery loop and every database session run on uvicorn's one event loop. They are started from the FastAPI lifespan in build_app() (kestrel/web/app.py). A second loop gives cross-loop aiosqlite errors that look like database corruption.
In the desktop app the threads are:
- the main thread, blocked in the pywebview window,
- a tray thread,
- a
uvicornthread, which owns the loop.
Because uvicorn.Server.run() is not on the main thread, the server disables its signal handlers (install_signal_handlers is replaced with a no-op in kestrel/web/serve.py).
Sharing one loop has a cost: any synchronous work on it freezes the UI. The code guards against that in a few ways:
- Blocking work goes through
asyncio.to_thread(migrations after a restore, backup snapshots, JobSpy, the embedding model). -
_stall_monitorsleeps for 0.5 seconds and logsevent_loop_stallif it wakes more than 0.25 seconds late, so "the app froze" can be matched to a cause in the log. - A middleware logs
slow_requestfor any request over 400 ms. - The scrape drain checks for claimable work before building its HTTP client, because creating the TLS context parses the CA bundle synchronously, and the loop runs that check every few seconds.
Each background task gets a done callback (_log_task_failure) so a task that dies is logged immediately instead of being reported at garbage collection.
_worker_loop in kestrel/web/app.py repeats a cycle. Worker.run in kestrel/pipeline/worker.py (behind kestrel run) is the same core without scraping and without the background drains in step 6, and kestrel worker runs only the embed, Tier 1 and Tier 2 drains.
- Re-read settings from the
settingtable layer, so a change in the UI applies with no restart, and consume a one-shot run mode if "Run now" queued one. Open a Run row for the cycle when there is pipeline work. - Drain
scrapetasks, one source at a time. Each source rate-limits its own host, and running sources in parallel would only multiply that. - Re-check roles the rules set aside under an older profile (
recheck.drain, below). Then run the Tier 0 sweep. It movesnewroles tot0_passort0_rejectand enqueues at1task per survivor. - Drain
embed, thent1, thent2. - Release the day's share of waiting lane tasks, if Kestrel is otherwise idle, and drain
t1andt2once more (below). The lane now holds only rows from earlier versions. - Unless paused, run the background drains, each after every tier has drained so none swaps a model under scoring: story builds (
build_stories), likely interview questions (interview_questions), suggested titles (maybe_request, thentitle_suggestions), company summaries (request_weekly, thenorg_summary), company research and contacts (org_research,org_contacts), follow-up drafts (follow_up), cover letter and outline drafts (letter_draft, see Document engine), then Model check (bench, see Benchmarking). - Check reranker drift (at most every 15 minutes, or after any Tier 1 work), run a liveness check at most hourly, and give the sorting-model training drain (
train_reranker, see Learning loop internals) a turn. - If nothing was done, wait five seconds, then go again.
Model downloads and builds (ollama_pull, ollama_create) are not in this loop. _setup_models_loop in kestrel/web/app.py runs them beside it (kestrel/services/model_tasks.py), so a long download never holds up scoring and a long scoring cycle never holds up a download.
The worker finishes one tier completely before starting the next. With 16 GB of VRAM, alternating Tier 1 and Tier 2 models forces an unload and reload on every task. Embeddings come first because the Tier 1 reranker gate and the Tier 2 few-shot selection both read the stored vector, and they quietly degrade without one.
Within a tier, drain_tier runs concurrency leases in parallel (asyncio.gather over that many coroutines). Tier 2 adds one more rule. Its claimable tasks are grouped by the model they will run on, which is the configured Tier 2 model or a per-task model_override from Score again. The configured model's group drains first, then the largest group, each to empty, so a mixed queue never alternates models.
CLAUDE.md now says the same as the code: tiers drain one at a time with no exception when two tiers share a model. The worker drains embed, t1 and t2 in that order whatever models they use.
Earlier versions did not drop a role from a company board that the smart filter judged unrelated. They stored it, ran Tier 0, and parked its t1 task in a background lane to be scored when Kestrel was idle. That is no longer how it works. Now the area and title checks run at ingest, before anything is stored, and a role they reject costs no row and no task. It is counted on its scrape run as dropped_outside_area or dropped_unrelated_title (see Adding a job board adapter). Nothing creates a lane task now: kestrel/pipeline/lane.py opens with "No new roles enter this lane". The code stays to drain rows that databases from earlier versions still hold.
A lane task has payload lane 1, priority -1000 (LANE_PRIORITY), and the priority it will have once released in lane_priority. claimable() excludes lane tasks through in_lane() in kestrel/queue/queue.py, so the lease never takes one and the drain counts ignore them. A role you ask for with Score anyway or Score again is exempt and runs at once, and that request takes a waiting task out of the lane (kestrel/queue/rescore.py).
Worker.release_lane runs at the end of a cycle and calls lane.release_due:
- It rechecks every waiting task.
reject_mismatchapplies today's ingest rules to the role without a model (the country allowlist throughparse_location, thensmart_filter.keep). A clear mismatch is set tot0_rejectwith a reason beginningoutside_area:orunrelated_title:, and its task is markeddone. This runs whether Kestrel is busy, capped or on an online model. - If Tier 1 or Tier 2 runs on an online model it stops there and frees nothing, so the lane never spends money unprompted.
- If
pipeline.lane_daily_capis 0, or anything is claimable (a scrape, embed or scoring task) or a role waits for Tier 0, it stops. - Otherwise it frees up to the day's remaining share (the cap, default 200, minus those already released on the person's local date), highest
lane_priorityfirst. A freed task getslane0, its priority back,lane_local_onlytrue andlane_released_onstamped, so the cap survives a restart.
Freed tasks then drain tier by tier like any other. lane_local_only keeps them local for good: _score_one rechecks the role again before scoring, and if a scoring tier now points at an online backend it defers the task with "held: background roles use local models only" instead of running it.
The Sources page shows the waiting count only when it is above zero, with a Score everything now button. POST /sources/score-everything refuses a request without the confirm field (400), refuses when Tier 1 or Tier 2 is online (400, "Nothing was sent"), and otherwise calls release_all, which makes the same recheck and then frees every survivor, ignoring the daily cap. The confirmation panel states the estimated time first (the median of the last 100 evaluation latencies, or a rough 60 seconds per role when fewer than five exist). There is no online cost to state, because the lane scores locally only. All of this state lives on task rows, so a kill mid-way resumes (hard rule 5).
Saving a profile change to anything the Tier 0 rules read queues a t0_recheck task, one live per track (kestrel/pipeline/recheck.py). The handler runs the rules only, with no model, over active roles at t0_reject, and moves each one that now passes back to new so the ordinary sweep carries it on. Roles you labeled, scored anyway or took into a pursuit are left alone. A fingerprint of the last completed inputs means a save that changes nothing queues nothing.
- The tray's Pause sets a process-wide flag.
is_paused()is also true while a maintenance operation holds the worker (worker_held()), and a tray Resume cannot release that hold. Restore and reset take the hold so the worker never writes into data being replaced. - Every drain checks
_halted()between tasks. A pause lets the leased task finish and claims nothing more. - A switched-off track is a hold on tasks, not a deletion. Tasks for that track's sources and roles stay
pendingand are not claimable (held_by_trackinkestrel/queue/queue.py), so switching the track back on resumes them. Tasks the operator explicitly requested (Score again, a retry) are never held. - Work that cannot go out right now is deferred, not failed (
TaskQueue.defer). The worker defers a task when its online destination changed or was not confirmed ("held: online destination changed or was not confirmed"), when a lane task would reach an online model, and when a key is out of credit (OutOfCredit). Work that would run on a backend on credit hold is not leased at all (_hold_exclusion). A deferred task is excluded for the rest of that drain, so it is not leased again in a loop. The reason is kept in the payload (defer_reason:local_only,approval,corrections,creditorstopped). A held task is not leased at all while its hold lasts, is shown as waiting rather than failed, and runs once when the hold clears.release_holdsends a hold when its reason is gone, and a sweep every 60 seconds (SWEEP_SECONDS) gives any deferred task one trial lease so a missed release cannot strand work. The worker checks the hold again before sending, so a trial lease sends nothing. A score held because the operator's corrections changed since the online confirmation uses thecorrectionsreason. - A crashed lane does not take the run down.
_gather_workersawaits every sibling, counts the crash in the tier's error count, and lets the next tier run. The run is then reported as having errors instead of clean. - Letter drafts (
letter_draft) are drained only by the web app's worker loop (_worker_loopinkestrel/web/app.py), not bykestrel runorkestrel worker. A draft whose confirmed model or destination changed is held. It stayspendingwith the message "held: online destination changed or was not confirmed" and is not leased again until the person confirms in the letter's panel. An online draft that stopped partway fails with a message asking the person to draft again, and is not run again by itself.
Tier concurrency is set in settings.yml (kestrel/resources/config/settings.yml) and in Settings:
concurrency:
tier1: 4
tier2: 2The Concurrency model in kestrel/config.py adds embed: 4. Embedding is a small model that does not compete with the tier models for VRAM, and the in-process embedding engine serializes its own runs.
Ollama must be able to serve that many requests at once. The relevant variables belong to the Ollama server, not to Kestrel, and Kestrel does not set them. kestrel doctor checks them (_check_ollama_env in kestrel/doctor.py):
-
OLLAMA_NUM_PARALLELshould be at least the largest of the three concurrency values (4 with the defaults). If it is lower or unset, doctor warns that requests will serialize no matter how many Kestrel sends. -
OLLAMA_KEEP_ALIVEshould be set so weights stay loaded between tiers. Doctor warns when it is unset and suggests2h.
# Windows, then restart Ollama
setx OLLAMA_NUM_PARALLEL 4
setx OLLAMA_KEEP_ALIVE 2h# Linux or macOS, in the environment Ollama starts from
export OLLAMA_NUM_PARALLEL=4
export OLLAMA_KEEP_ALIVE=2hIf every tier is hosted, doctor skips both checks. If you raise a concurrency value in Kestrel, raise OLLAMA_NUM_PARALLEL to match.
For a quick look at a database in a dev checkout:
SELECT type, status, COUNT(*) FROM task GROUP BY type, status;
SELECT id, type, attempts, max_attempts, last_error FROM task WHERE status = 'dead';A dead scoring task leaves its role waiting at t0_pass or t1_pass. The orphan sweep at the next start re-enqueues it once, and the Pipeline page offers Score again after that.
Kestrel never submits an application, sends a message or acts on a third-party site for you. The queue only fetches public pages, calls your configured model, and writes to the local database.
-
Testing for
tests/test_queue.py,tests/test_queue_lock_retry.pyand the fake LLM used for pipeline tests. - Contributing for the check script to run before a push.
-
CLI reference for
kestrel worker.
Start here
Interfaces
Extending Kestrel
How it works
- Prompts and context budgets
- Document engine
- Learning loop internals
- Analytics internals
- Task queue and concurrency
- Database schema
Shipping and safety
- Packaging and releases
- Preflight and diagnostics
- Security and privacy model
- Outbound calls
- Benchmarking
Workarounds and Troubleshooting