Skip to content

Database Schema

Mark Crowle-Groves edited this page Oct 19, 2026 · 4 revisions

Checked against v0.6.1 (commit 3b06892) on October 19, 2026.

Database schema

Kestrel keeps everything it knows in one SQLite file, kestrel.db. This page covers the tables and how they relate, how the schema is created and changed with Alembic, and the connection settings every part of the app depends on. For how the task table is used as a work queue, see Task queue and concurrency. For the process layout around it, see Architecture overview.

The models are in kestrel/db/models.py. Where this page and the models disagree, the models are right.

Where the file lives

paths.db_path() in kestrel/paths.py returns <data home>/data/kestrel.db. The data home depends on the operating system:

OS Data home
Windows %LOCALAPPDATA%\Kestrel
macOS ~/Library/Application Support/Kestrel
Linux $XDG_DATA_HOME/kestrel, else ~/.local/share/kestrel

KESTREL_DATA_HOME overrides all three. The test suite sets it to a fresh temporary folder for every test (tests/conftest.py). Nothing writable lives beside the executable, because a packaged install runs from a read-only folder.

Connection settings

kestrel/db/engine.py builds two engines against the same file:

  • make_async_engine uses sqlite+aiosqlite:// and serves the app: the worker, the scheduler and every web request.
  • make_sync_engine uses plain sqlite:// and exists for Alembic and for code that has to run outside the event loop.

Both register the same connect listener, _apply_pragmas, so every connection runs three statements before anything else:

PRAGMA journal_mode=WAL;
PRAGMA busy_timeout=5000;
PRAGMA foreign_keys=ON;

The engine code sets no synchronous pragma, no connect_args and no custom pool class, so SQLite's defaults and SQLAlchemy's default pool apply. tests/test_db_schema.py::test_wal_and_busy_timeout_on_every_connection asserts all three values.

What each setting does in practice:

  • WAL lets readers continue while a writer commits. The web UI polls (the live run summary reads every 5 seconds) while the worker writes, and WAL is what keeps those from blocking each other. It also means the database is three files on disk while open: kestrel.db, kestrel.db-wal and kestrel.db-shm.
  • busy_timeout=5000 makes a writer wait up to five seconds for the lock before SQLite answers "database is locked". There is still only one writer at a time. On a slow disk, five seconds can run out when several scoring lanes commit back to back, and TaskQueue retries those errors itself (see the queue page).
  • foreign_keys=ON is off by default in SQLite and per connection, so it has to be set here. Deleting a parent row that other rows reference fails instead of leaving orphans.

The app engine is a module-level singleton (get_engine, get_sessionmaker in kestrel/db/engine.py). The sessionmaker uses expire_on_commit=False, so objects stay readable after a commit. reset_engine disposes the engine. forget_engine drops it without awaiting, for the case where the event loop that owned it has already gone. Using an engine from a second event loop gives cross-loop aiosqlite errors that look like corruption, which is why the app runs everything on one loop.

Tests replace the pool with NullPool (tests/conftest.py) because they create many short event loops. Production keeps the default pool.

Backups and WAL

Copying kestrel.db while the app runs can pair a stale main file with a WAL that does not match it. snapshot_database in kestrel/services/backup.py uses SQLite's online backup API instead, which writes a consistent image including what still sits in the WAL. The backup zip holds that snapshot, never the -wal and -shm files, and never .env.

Conventions

  • Timestamps are text. Every timestamp column is a String holding ISO 8601 UTC. iso() in kestrel/db/base.py always emits six microsecond digits. Fixed width matters because the app compares timestamps as strings (lease_until < now). Without the padding, ...:00+00:00 sorts before ...:00.000001+00:00, because + sorts before ., and lease comparisons go wrong.
  • JSON columns hold structured values: settings dictionaries, evaluation dimensions, payloads. SQLite's json_extract reads them in queries.
  • Enum-like columns are plain strings. The allowed values live in kestrel/db/enums.py (TASK_STATUS, PURSUIT_STATUS, SOURCE_KINDS and so on). The migrations contain no CHECK constraints, so the application is the only thing enforcing them.
  • Integer primary keys everywhere except setting (keyed by name) and opportunity_embedding (keyed by its opportunity).
  • Each model declares its own timestamp columns. kestrel/db/base.py holds only the declarative base and the timestamp helpers. The unused TimestampMixin it once defined was removed.

The tables

There are 40 tables plus Alembic's own alembic_version. tests/test_db_schema.py lists them in EXPECTED_TABLES (it omits frontier_transmission, which was added later by migration 0005).

Group Tables
Profile and sources profile, source, scrape_run
Roles and organizations org, opportunity, opportunity_embedding, comp_observation
Scoring evaluation, quarantine, frontier_transmission
Tracking pursuit, status_event, notification, saved_view
Infrastructure task, run, setting
Documents doc_master, doc_layout, doc_section, doc_slot, doc_variant, doc_render
Research and contacts org_research, contact, outreach_draft, connection, interaction
Interview story, story_usage, prep_pack, mock_session
Offers offer, engagement_offer
Learning label, outcome, calibration, ml_model, verdict_override, selection_override

opportunity is the center of the schema. One row per posting or trigger, with a track (employment or consulting), the normalized fields (location, compensation, remote type), description_md, the content_hash and dedup_group_id used by deduplication, a ghost_score, and the pipeline stage (new, t0_pass, t0_reject, t1_pass, t1_reject, t2_done, t3_done, error, quarantined). stage tracks tier progress. Hiding a role sets archived_at and archive_reason and leaves stage alone, so the two stay independent.

evaluation holds one row per scoring result, tagged with tier, model, prompt_version and content_version. The last one ties a result to the version of the posting it scored, which makes re-evaluating unchanged content idempotent. raw_response keeps the model's reply.

quarantine keeps the prompt and raw response of any call that failed schema validation twice. Nothing is dropped silently.

pursuit is the tracked application, unique per opportunity (opportunity_id has a unique constraint). status_event is its append-only history.

doc_variant.text is the operator's own wording, stored byte for byte. The document engine only ever selects among variants; it never writes new text into a rendered document.

setting is a key-value table holding the highest-precedence layer of configuration, above environment, dotenv and YAML (Settings in kestrel/config.py).

frontier_transmission is the audit trail for Tier 3 escalation, one row per payload actually sent to a hosted model. See Security and privacy model.

Relationships

source ──< scrape_run
source ──< opportunity >── org ──< org_research
                │            └──< contact ──< connection
                │                         └──< interaction
                ├──< evaluation ──< verdict_override
                ├──< quarantine
                ├──< opportunity_embedding   (one per opportunity)
                ├──1 pursuit ──< status_event
                │       ├──< offer
                │       ├──< engagement_offer
                │       └──< outcome
                ├──< doc_render >── doc_master
                ├──< prep_pack, mock_session, story_usage
                └──< frontier_transmission, label, comp_observation

doc_master ──< doc_section ──< doc_slot ──< doc_variant

pursuit.document_id and pursuit.cover_letter_id both point at doc_render, so a pursuit remembers which rendered files it used. task rows have no foreign key columns. The ids they refer to (opportunity_id, source_id) sit inside the JSON payload, and the queue code reads them with json_extract, so the database does not enforce that the row a task names still exists.

Indexes that matter

The model file defines the indexes with index=True or an explicit Index. The ones with a stated purpose:

Index Table Why it exists
ix_opportunity_track_stage opportunity Pipeline pages filter by track and stage.
ix_opportunity_source_external opportunity Every scrape looks up a posting by (source_id, external_id); this keeps ingestion fast (migration 0002).
ix_task_status_priority task The lease query orders pending work by priority.
ux_task_live_scoring task Partial unique index: one live t1, t2, t3 or rescore task per opportunity (migration 0014).
ix_task_updated, ix_evaluation_created, ix_quarantine_created, ix_scrape_run_started various The live run summary reads recent rows by time on a 5 second poll (migration 0016).
ux_frontier_transmission_payload frontier_transmission One transmission per confirmed payload; the database settles a double confirm (migration 0017).

Two of these, ux_task_live_scoring and ux_frontier_transmission_payload, are the database acting as the referee for a race between two writers. Application-level "have I done this already?" checks cannot close that window, and a unique index can.

Migrations

The schema is managed by Alembic. The revisions are in kestrel/db/migrations/versions/ and are numbered 0001 through 0019, each pointing at the previous one. 0001_initial_schema.py creates the whole starting schema (its header says Alembic generated it). The later ones are small and additive: a column, an index, or a table. Some also repair existing rows first. 0014 cancels duplicate live tasks before it creates the unique index, because the CREATE would fail on existing duplicates.

How they run

Migrations run in code, not from an alembic command. There is no alembic.ini in the repository. run_migrations() in kestrel/db/migrate.py builds an Alembic Config in memory and calls command.upgrade(..., "head"). Three details are load-bearing:

  • A sync URL. The URL is sqlite:///..., never sqlite+aiosqlite:///.... Alembic needs a synchronous engine.
  • An absolute script location. The migrations folder is package data resolved through importlib.resources (paths.packaged_migrations()), so it works from a read-only frozen install. env.py does no __file__ arithmetic.
  • Pragmas at connect time. env.py registers the same _apply_pragmas on its engine. Running them as statements on an open connection would start an implicit transaction and break Alembic's version stamping. It also uses NullPool and render_as_batch=True, because SQLite cannot ALTER most things in place and batch mode rebuilds the table.

run_migrations() is called at startup by the desktop shell (kestrel/desktop/shell.py) and kestrel serve (kestrel/web/serve.py), and again by most CLI commands, by backup, and by the settings page after a restore. It is safe to call repeatedly.

From the command line:

kestrel db upgrade    # apply pending migrations; prints the revision it ends on
kestrel db current    # print the applied revision, or "not initialized"

Reading the state

kestrel/db/migrate.py has three read helpers besides the upgrade:

  • head_revision() is the newest revision the shipped scripts define.
  • current_revision() is what the database file says it is at.
  • known_revisions() is every revision the shipped scripts define.

kestrel doctor compares the first two, so a database left behind by an older build reports as pending instead of clean. Restore uses the third to refuse a backup made by a newer Kestrel: that database is stamped with a revision this build has never heard of, and upgrade would fail only after the restore had already replaced the live data.

Adding a migration

  1. Change the model in kestrel/db/models.py.
  2. Add versions/00NN_short_name.py with revision = "00NN" and down_revision set to the previous revision. Use op.batch_alter_table for column changes. Put the reason in the docstring, as the existing ones do.
  3. Keep it additive where you can. If an index or constraint could fail on existing rows, fix the rows in the same migration, as 0014 does.
  4. If you add a table, add its name to EXPECTED_TABLES in tests/test_db_schema.py. If you add an index the app depends on, add it to test_required_indexes_exist.
  5. Run uv run --extra dev python scripts/check.py.

Every test that uses the sm fixture builds its database by running the real migration chain (tests/conftest.py), so a broken revision fails the suite broadly rather than in one place. No test compares the models to the migrated schema (no compare_metadata), so a model column without a matching migration is caught only when something touches that column.

In a frozen build, the migration .py files ship as data files, not as analyzed modules, and keep their kestrel/ prefix so importlib.resources finds them. packaging/kestrel.spec does this, and tests/test_packaging.py guards it. See Packaging and releases.

Related

Clone this wiki locally