Skip to content

Database: roles, backups and restarts

The tables, their columns and the links between them: Database schema, generated from knowtation_api.db and committed; the docs site shows the same file. With every table change, add a migration and a doc= for each new column, and regenerate the page (uv run python -m knowtation_api.docgen). Tests fail if a column has no description, if the migrations and db.py differ, or if the page is out of date.

Two roles

  • The owner (KNOWTATION_OWNER_DATABASE_URL, knowtation in compose.yaml) runs the migrations at start-up.
  • The app role (KNOWTATION_DATABASE_URL, knowtation_app) is what the API uses for everything else. At start-up the API, connected as the owner, creates it (or updates its password) and grants it only SELECT, INSERT, UPDATE and DELETE on the tables, including tables added by later migrations. It can't create, alter, drop or truncate anything.

Set POSTGRES_PASSWORD and KNOWTATION_APP_DB_PASSWORD for anything other than local use. Without an owner URL (for example in tests), the API uses one role for both.

Backups

A backup has two parts: the database, and the uploaded files in the API's data volume.

scripts/db-backup.sh                        # writes backups/knowtation-YYYYmmdd-HHMMSS/
scripts/db-restore.sh backups/knowtation-…  # replaces the database and the files

Both scripts run pg_dump/pg_restore and tar inside the compose containers (podman compose exec). To use Docker, or tools outside the containers, set DB_EXEC, FILES_EXEC and DATA_DIR (see the scripts' comments). Stop using the app while restoring. The restore leaves out the backup's privileges, since its roles may not exist on a new machine; the script then restarts the API, which grants its role access again. The round trip is tested by test_backup_and_restore_round_trip.

Accounts

Passwords are stored only as Argon2id hashes (users.password_hash). Session ids and API tokens are random and stored only as SHA-256 hashes (sessions.id_hash, users.token_hash), so a copy of the database can't be used to sign in. Datasets, rule sets and policies point to their owner (owner_id); deleting a user is refused by the database while they still own something, which is why the admin's delete dialog transfers or deletes it first.

Review changes

Each review's changes (action, element, property, value, and the value before and after) are stored with its version in dictionary_versions.changes (migration 0002). Reviews saved before that column existed have none stored; the history rebuilds them from the difference with the parent version and marks them reconstructed. A rebuilt history misses accepts that changed nothing, since nothing changed in the stored version.

Deleting datasets

DELETE /datasets/{id} (and Delete dataset on the Overview tab) removes the dataset, its runs, trials and versions, its uploaded files, and the LLM answers only it used. A run still identifying when its dataset is deleted ends without saving anything.

Restarts

Runs and trials execute inside the API process. If the API stops during one, it is marked failed ("interrupted by a restart") at the next start-up; start it again.

Datasets read in the background

A file URL source creates its dataset at once with datasets.status = 'reading'; a background job downloads it into the dataset's folder (progress: stage, bytes, total), reads it and sets ready. A restart marks unfinished ones failed with a reason in error. The stored source keeps the URL without its query string when that carries credentials (signed links).

Default version and archived runs

datasets.default_version is the dictionary version shown and exported when none is asked for (empty: the latest). runs.archived_at and archived_by hide a run from the history by default; archiving deletes nothing.

LLM answers

llm_answers stores each LLM answer, keyed by a hash of the model, prompt version, call settings and the exact context sent (not the rules), so the same request is never sent twice; all users share it. llm_answer_uses links each answer to the datasets that asked for or reused it. Deleting a dataset deletes the answers no other dataset uses (they hold column names, example values and documentation passages). The admin can clear all answers (Clear LLM cache on the Users page); KNOWTATION_LLM_CACHE_DAYS also deletes answers unused that long, at start-up. Unticking Reuse saved LLM answers on a run replaces the answers it touches.

LLM spending

llm_spend keeps one row per run or trial that used an LLM: who, which dataset (by id and name, not a link), model, who paid (key_source: the server's keys or the person's own), calls, cached batches, tokens and estimated cost. It stays when the dataset or user is deleted, so totals don't change; a deleted user's rows are renamed name (deleted), so a later account with that username doesn't see them. The admin sees it by month, person and model on the Users page (GET /llm/spending, /llm/spending.csv), and everyone sees their own on their account page (GET /me/llm-spending, /me/llm-spending.csv); the figures are estimates from the providers' list prices, computed without calling them.

LLM keys, model lists and model settings

llm_keys holds people's own provider keys, one per person and provider, encrypted with KNOWTATION_SECRET_KEY (Fernet), with only the last four characters in clear; deleting the user deletes them. llm_model_lists keeps what each key can use, as the provider last listed it (owner is server or the user's id), with when it was fetched and the last error. llm_model_settings holds what the admin set per model: hidden from the server's list, and a price per million tokens.

Storage

GET /admin/storage (the Storage card on the Users page) measures each dataset's database space with pg_column_size over its rows, and its files by walking its folder in the data volume. Nothing is stored.

Draft rules

Drafts are computed from the latest version whenever they are asked for (GET /datasets/{id}/rule-drafts), so nothing about them is stored except decisions: rule_draft_decisions records each approval (and the rule set it became) or discard, by whom, with a hash of the draft's rules. The latest decision with the same hash applies, so a later run that gives the same draft shows it as decided; changed values give a new hash and a fresh draft. An approved draft is a normal row in rule_sets.

Trials

Analyse on the Advanced tab starts a trial (POST /datasets/{id}/trials) and polls GET /trials/{id}, like a run. A trial stores its result in trials, never a run or a version; only whoever started it can read it, and it is deleted after 24 hours.