Skip to content

Database Schema

Claude edited this page Nov 12, 2026 · 4 revisions

Checked against v0.7.6 on November 13, 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 four statements before anything else:

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

The engine code sets no connect_args and no custom pool class, so SQLAlchemy's default pool applies. tests/test_db_schema.py::test_wal_and_busy_timeout_on_every_connection asserts WAL, the timeout and foreign keys. Two more tests in that file (test_new_async_connections_use_normal_synchronous, test_new_sync_connections_use_normal_synchronous) assert that fresh connections, including ones opened after the engine was disposed, report synchronous as 1 (NORMAL).

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).
  • synchronous=NORMAL is the setting SQLite recommends with WAL. It skips syncing the WAL on every commit. After an application crash, committed data is intact. After a power loss, the most recent commits can be lost while the database stays consistent, and the task queue resumes from its last durable state.
  • 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 47 tables plus Alembic's own alembic_version. tests/test_db_schema.py lists 40 of them in EXPECTED_TABLES. It omits frontier_transmission (added by migration 0005) and the six that came with the later features: interview_question_set (0021), title_suggestion (0022), org_summary, contact_import and connection_position (all 0023), and letter (0028).

Group Tables
Profile and sources profile, source, scrape_run, title_suggestion
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, letter
Research and contacts org_research, org_summary, contact, contact_import, connection_position, outreach_draft, connection, interaction
Interview story, story_usage, prep_pack, interview_question_set, mock_session
Offers offer, engagement_offer
Learning label, outcome, calibration, ml_model, verdict_override, selection_override, requirement_correction

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. liveness records whether the posting is still open. Two columns from migration 0020 back it: liveness_strikes counts consecutive reads that looked expired, and a posting closes on the second one, not the first, so one transient 404 cannot close a role the operator is pursuing. closed_reason then says why (http_404, http_410, page_text; ats_missing is reserved, see CLOSED_REASONS in kestrel/db/enums.py).

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). Not every row is configuration. Some hold content or short-lived UI state: interview prep notes, a role kept with Save for later, and the Applications board's Undo snapshots, which are rows named undo.pursuit.<token> kept for a day (kestrel/services/pursuit_undo.py). NON_CONFIG_PREFIXES and STATE_KEYS in kestrel/services/setting_overrides.py list them, and the configuration layer excludes them in SQL so a polled page never reads them.

org carries hidden_at (migration 0023). A hidden company keeps its rows; its roles stay out of Pipeline and Today until it is shown again. profile has first_name and last_name beside full_name; the migration split an existing name on its first space and kept full_name as written, because it is the resume header.

org_summary is the sourced company summary, one row per organization (a unique org_id). contact_import records each LinkedIn connections import, and connection_position keeps a contact's position history across imports. Neither table has an email column. Migration 0023 adopted contacts from the older importer and erased any email address they held.

interview_question_set holds the likely interview questions generated when a role is marked Applied. The active set for a pursuit is the one whose superseded_at is null, and a partial unique index keeps it to one. title_suggestion holds job titles the model proposes for the target titles; its title is unique case-insensitively across every status, so a dismissed title is never suggested again.

letter holds cover letters and engagement outlines (migration 0028): the body, claims, flags, prompt version and word count, with the PDF render attached by render_id. At most one letter per role and kind is current, held by a partial unique index.

requirement_correction (migration 0032) holds the operator's corrections to one thing a posting asks for. Its scope is person (one row per track and requirement_hash, applying to every role on the track that asks the same thing) or posting (one row per role and requirement). Two partial unique indexes enforce that. It stores Kestrel's state and the operator's state for the requirement, the reason, an optional note, and the story it rested on. story_id is ON DELETE SET NULL, and story_deleted_at records that the story went, so an answer that rested on it stops applying. A correction is not a label: it never counts toward the learning thresholds. Migration 0034 re-derived every requirement_hash so the identity form keeps letters and digits of any script plus + and #, which keeps "C++", "C#" and "C" apart. The downgrade gives the old form back wherever it can and never merges or deletes rows.

evaluation.correction_ids (migration 0033) is a nullable JSON list of the correction ids a Tier 2 or Tier 3 read was given. A score reads as older when one of them was removed or changed since, or when a correction added since bears on the role. Rows from before the migration have null and keep the "added or changed since" rule only.

ml_model carries artifact_signature and pca_artifact_signature (migration 0031), the signatures stored for a saved reranker file and its PCA file. The loader verifies them before it unpickles, and a row with none is refused and retrained. See Security and privacy model.

task carries retry_at (0029) and opportunity_id (0030), and opportunity.lane_local_only (0030) records on the role itself that it came through the background lane, so retention of old task rows cannot lose the fact. See Task queue and concurrency.

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 ──1 org_summary
                │            ├──< org_research
                │            └──< contact ──< connection
                │                         ├──< interaction
                │                         └──< connection_position >── contact_import
                ├──< evaluation ──< verdict_override
                ├──< quarantine
                ├──< interview_question_set  (one active per pursuit)
                ├──< 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).
ux_interview_question_set_active interview_question_set Partial unique index on pursuit_id where superseded_at IS NULL: one active question set per pursuit (migration 0021).
ix_task_retry_at, ix_task_opportunity_id task Claim queries skip a task still backing off, and the per-role lookups (is this role being scored, did it fail) use a real column instead of a JSON expression (migrations 0029, 0030).
ix_opportunity_scrape_run_id, ix_quarantine_opportunity_id opportunity, quarantine Deleting a run and looking up a role's failures no longer scan the table (migration 0030).
ux_requirement_correction_person, ux_requirement_correction_posting requirement_correction Partial unique indexes: one person-scope row per track and requirement, one posting-scope row per role and requirement (migration 0032).
ux_title_suggestion_title title_suggestion Unique on lower(title), so a title is suggested once, whatever happened to it (migration 0022).

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. ux_interview_question_set_active and ux_title_suggestion_title are uniqueness rules in the same style: one active question set per pursuit, and one row per title.

Migrations

The schema is managed by Alembic. The revisions are in kestrel/db/migrations/versions/ and are numbered 0001 through 0034, 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, with recreate="never" when the table is a parent that other tables reference: with foreign_keys=ON, a batch rebuild drops and recreates the table, and the drop fails on any row that is still referenced (0013, 0015, 0023 and 0024 do this). 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 (six tables are missing from it today). 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