Skip to content

Database

Each environment gets an Aurora PostgreSQL Serverless v2 cluster. Application connections use IAM authentication rather than long-lived database passwords, while RDS maintains an AWS-managed master-user secret that Pulumi uses through the Data API for provisioning. With the default hawk:dbMinCapacity: "0", the cluster scales to zero after a few minutes of inactivity to save costs; the first connection after a pause takes ~30 seconds to wake up.

Hawk needs PostgreSQL 17 or later; the Aurora cluster runs 17. The identity schema uses MERGE ... WHEN NOT MATCHED BY SOURCE and the MAINTAIN privilege, both new in 17.

Database Roles

These login roles are created automatically:

Role Purpose
inspect_admin Migrations (rds_superuser)
inspect API read/write
inspect_ro Read-only access
middleman LLM proxy model configuration reads and admin API writes
inspect-importer Import pipeline (eval-log and scan importers); bypasses RLS. Name configurable via hawk:warehouseSystemUser
middleman_traffic_ingester Middleman traffic ingester Lambda; INSERT on middleman_traffic.request and nothing else
hawk-platform-metrics Platform-metrics poller; writes job_resource_sample and job_resource_summary and no other table, and bypasses RLS to look up every running job's id (so it also reads what rls_bypass reads: job, Middleman's registry)
inspect-audit Model-group audit; bypasses RLS, SELECT on eval, sample, sample_model and scan (plus what rls_bypass reads: job, Middleman's registry), and writes nothing

Row-level security is managed through NOLOGIN group roles that the login roles are granted into: rls_bypass (system pipelines), rls_reader (RLS-filtered reads), and model_access_all. See Security: Access Control for how permissions flow.

People and personal logins (identity schema)

The private identity schema holds Hawk's people (account), groups (account_group) and memberships, whichever identity source they come from. Each source writes only its own data:

  • Columns per source. account.scim holds the SCIM User resource as the identity provider last sent it (never its password); account.oidc is reserved for claims from verified logins, which nothing writes yet. Typed fields (user_name, email, display_name, external_id, active, issuer, subject) are generated columns over them. (issuer, subject) is unique, and email takes a login's email only once its issuer has verified it.
  • Rows per source. Each membership names its source (scim or oidc), so one source can't overwrite another's assertion. oidc memberships must carry an expires_at.
  • A role per write path. scim_writer may write only scim columns and scim memberships, and oidc_writer only the oidc ones, through column grants and row-level security. hawk_api holds both with SET but not INHERIT, so it switches into one for each write and can only read otherwise.

With hawk:scimEnabled, every account the identity provider has provisioned and marked active gets a LOGIN role named exactly its SCIM userName (an email address), holding:

  • warehouse_member: CONNECT, SELECT on public, rls_reader and rds_iam.
  • The role of each of their SCIM groups that maps to one: model-access-<slug> to itself when it is a middleman.model_group name, and code-access-<name> to code_group_<name> when it is a code_group name. Other groups, and memberships from any other source, grant nothing. Group roles are granted without INHERIT: membership is what RLS checks, and the group's own privileges stay with the group.

RLS then gives each person exactly the rows all of their groups allow, which no shared login can do for someone in two groups.

Statement-level triggers on the three tables reconcile the affected people in the same transaction as any write, whoever makes it, and record every grant, revoke, login change, rename and drop in the append-only identity.role_change. The roles are managed by identity_manager, a NOLOGIN role that owns the triggers' functions. It only alters roles it created and memberships it granted, and it holds ADMIN without INHERIT or SET on the roles it may grant, so it reads nothing itself. It grants only roles with nothing elevated and no WITH ADMIN grant anywhere in their membership chain, revokes a role from everyone who holds it once it stops qualifying, and if warehouse_member ever holds more than rds_iam, rls_reader and shared code_group_* roles it turns every personal login off. When a pushed group names a model group or code group that has no role yet, it creates the role (adding a model group's to model_access_all) and grants it, and gives the schema owner ADMIN on it without INHERIT or SET, since Postgres lets only a role's creator administer it and the deploy grants and revokes group roles as the schema owner; a group registered after the identity provider pushed it is granted to its members as the registry row is written. It never takes over a role it didn't create.

Each person is reconciled on their own. One whose role can't be brought into line (a role altered by hand, a name already taken, a role its session holds locked) gets a failed row in role_change, loses the memberships the manager granted and, where it can still be removed, their login, and doesn't hold up anyone else. A SCIM write that should give someone a login and can't is refused, so the identity provider retries it; a withdrawal keeps whatever it managed. Writes and reconciles serialize on identity.lock(), a lock only the identity roles can take. Every deploy also reconciles everyone as a backstop. Turning the flag off makes every person NOLOGIN and strips their memberships, and fails the deploy if a login survives. SCIM keeps writing while it is off, so turning it back on restores the logins the identity provider describes by then; a deactivation the provider couldn't deliver in the meantime (its agent stopped, say) is restored too, so retry the provider's failed pushes before turning it on. Removing a login doesn't end a session that is already open; end it with pg_terminate_backend when that matters.

A deactivated or unassigned person keeps their role, NOLOGIN and with no memberships; a userName changed meanwhile renames the role only once the login returns. A SCIM DELETE withdraws the account's SCIM data and drops its role (or keeps it, NOLOGIN, while the role still owns objects); the account itself goes once no source vouches for it. Provisioning reattaches an existing account only when it is the same person: one SCIM itself released (matched on externalId whenever the released record carries one, so a recycled email address never inherits a kept role), or one a login vouches for, whose subject is the SCIM externalId under the API's OIDC issuer or whose verified email is the userName. scripts/ops/check_rls_health.py reports drift between accounts and roles, and --fix reconciles it.

The middleman_traffic schema

middleman_traffic.request holds every Middleman request made with a token, direct and eval/scan traffic alike (see Security: Your own Middleman traffic). Its user_id is the person the request belongs to: the caller's sub, or for a run with restricted credentials the submitter from the signed grant, with the execution in restricted_execution_id. It also stores, for usage reporting, each request's upstream provider and the spend Middleman recorded for it: cost_usd, cost_partial, service_tier, speed, model_group, model_lab, the accounting teams, the credential_profile that served it (by name), the person's usage user_label and, for a delegated or restricted token, the signed usage_user_id the request is accounted to. The API serves none of these per row: they reach it only summed, through usage_daily(). It lives in its own schema because the role setup re-grants broad privileges on every table in public (to inspect_ro and every model-group login) and middleman (to the middleman service) whenever it runs. Grants on this schema are exact, and the role setup (infra/core/rds.py) reconciles them each time it runs:

Role Privileges
the API's role (inspect) USAGE, SELECT — and RLS shows it only rows whose user_id equals hawk.traffic_sub, which the API sets per transaction — and EXECUTE on three definer functions: model_raw_cot(text[]), returning each named model's raw_cot and self_hosted flags from Middleman's registry and nothing else; usage_daily(timestamptz, timestamptz), everyone's requests that used tokens or were charged, summed per UTC day (the spend rollup behind /usage/history's recorded costs and /usage/spend); and usage_data_through(), when the newest of those was received
middleman_traffic_ingester USAGE, INSERT
inspect_admin owner (migrations; operator removals)
everyone else nothing

Never add middleman_traffic to a broad grant (ON ALL TABLES IN SCHEMA, ALTER DEFAULT PRIVILEGES, model-group logins): every warehouse user could then read everyone's traffic. Removing a person's records (for example, on a privacy request) is an operator action as inspect_admin.

Rows are kept indefinitely, at roughly 1 GB per million requests including the indexes, and eval traffic likely dominates the row count. Watch the table's size. To estimate a deployment's growth, count its traffic by kind with Logs Insights on <env>/middleman/traffic:

filter ispresent(user_id) and user_id not in ["anonymous", "unknown", ""]
| fields coalesce(`correlation.x-hawk-job-type`, "direct") as kind
| stats count(*) as requests by kind, bin(1d)

Backfilling traffic history

The ingester only sees log events written after its subscription exists. scripts/ops/backfill_middleman_traffic.py replays the traffic log group's last 90 days through the same parse, filter and insert code. Pass --days <n> to read further back: the group keeps events for hawk:middlemanTrafficLogRetentionDays, and forever when that is unset. It is idempotent, so overlapping already-ingested time is safe:

uv run python scripts/ops/backfill_middleman_traffic.py --env <env> --dry-run
DATABASE_URL="postgresql+psycopg://inspect_admin@<endpoint>:5432/inspect" \
    uv run python scripts/ops/backfill_middleman_traffic.py --env <env>

Rows stored before the table kept spend have null spend columns. To fill them from the log (90 days back, or --days <n>), add --fill-spend: it also sets those columns on rows already stored, wherever they are null, and never replaces a stored value. Updating rows needs the table's owner, so run it as inspect_admin:

DATABASE_URL="postgresql+psycopg://inspect_admin@<endpoint>:5432/inspect" \
    uv run python scripts/ops/backfill_middleman_traffic.py --env <env> --fill-spend

Batches the ingester couldn't write land in its DLQ (<env>-inspect-ai-traffic_log_ingester-dlq, alarmed like the others). After fixing the cause, replay them with scripts/ops/dlq.py redrive --queue-url <url> --target lambda --function-name <env>-inspect-ai-traffic_log_ingester:current. Without --confirm the redrive is a dry run.

Execution state and history

A job identifies an eval set or scan; job_execution retains each hosted launch or resume, with restricted or user credentials, and its Kubernetes identity. Only the API writes execution state; warehouse writers and importers retain read access subject to the existing RLS.

Closure (lifecycle_state = ended, with an end reason and timestamp) ends a restricted execution's credential access. Cleanup separately records when deletion was requested and when resources were confirmed absent. For example: active → ended → deletion requested → resources absent. Closure alone does not mean resources are gone.

Parent jobs and execution rows are retained after cleanup, preserving launch and cleanup history across resumes. Downgrading migration 4a901c7de283 drops job_execution and destroys that history; upgrading again does not restore it.

Resource usage history

job_resource_sample holds a job's summed CPU and memory requests and usage, and its sandbox count, about once a minute while it has running pods. job_resource_summary holds one row per job with running sums, counts and peaks over every sample, so means and the requested/used ratio survive after the samples go. The platform-metrics poller is the only writer. It logs in as its own database user, hawk-platform-metrics, which can write these two tables and no other. That user is a member of rls_bypass, so it can look up the id of every running job, restricted ones included; the same membership lets it read job and Middleman's model registry. Every other login, the API and the importers included, can only read the two tables: the migration and each deploy revoke the write grants that new tables inherit. Readers see a job's rows exactly where they see the job, through the same parent-job policy as job_execution. A job keeps every sample until it holds more than 500, about eight hours of running. Its series is then thinned to one even step over the whole run (one sample per time bucket, counted from its first sample), and the step doubles as the run gets longer. After that, only the samples since the last thinning, at most about four hours, are kept per minute. The step is sized from the minutes that were sampled, so a job resumed days later keeps the detail of both runs. The series is deleted 30 days after its last sample; the summary row stays until the job row is deleted. Downgrading migration 319968df2b4a drops both tables and their history.

Connecting

After logging Pulumi in to the correct S3 backend, name the target stack explicitly. Resolve both the database endpoint and AWS region from that stack, then generate an IAM auth token for your database role:

export AWS_PROFILE="<profile-for-the-target-account>"
STACK="<stack>"
ENDPOINT="$(pulumi stack output database_url_admin -s "$STACK" | sed -E 's#.*@([^:/]+).*#\1#')"
REGION="$(pulumi stack output region -s "$STACK")"
TOKEN="$(aws rds generate-db-auth-token \
  --hostname "$ENDPOINT" --port 5432 --region "$REGION" --username inspect)"
PGPASSWORD="$TOKEN" psql "host=$ENDPOINT dbname=inspect user=inspect sslmode=require"

With a personal login, use your SCIM userName (your email) as the username, and keep libpq's keyword form so the @ needs no escaping. Your IAM role needs rds-db:connect on dbuser:<cluster-resource-id>/${aws:PrincipalTag/Username}, which the identity provider's AWS integration grants:

ME="you@example.org"
TOKEN="$(aws rds generate-db-auth-token \
  --hostname "$ENDPOINT" --port 5432 --region "$REGION" --username "$ME")"
PGPASSWORD="$TOKEN" psql "host=$ENDPOINT dbname=inspect user=$ME sslmode=require"

Running Migrations

After logging Pulumi in to the correct S3 backend, get the database URL for an isolated development stack. Production and shared staging migrations run as part of deployment.

export AWS_PROFILE="<profile-for-the-target-account>"
STACK="dev-<name>"
export DATABASE_URL="$(pulumi stack output database_url_admin -s "$STACK")"

Run migrations:

cd hawk
uv run alembic upgrade head

The inherited-output migration (f6a374000001) adds read helpers and policies without a data backfill. Policy changes take ACCESS EXCLUSIVE locks on job, eval, and scan, held until transaction commit; schedule a quiet deployment window and investigate long-running blockers before retrying.

Development databases that already applied an earlier version of this unreleased migration need it replayed: stop API access and jobs, run uv run alembic downgrade c7b439ef21a0, then uv run alembic upgrade head before restoring access. The downgrade preserves saved grants but temporarily removes their read checks.

Deploying import model discovery

Migration 5b61c7e80429 can run online through the normal deployment migration step, before the new importer/API starts. It adds two eval columns and a retained-group branch to the existing group function, with no historical backfill or table rewrite. It needs a brief exclusive lock and has a five-second lock timeout; investigate blocking transactions and retry if needed.

  1. Land the import resume fix and the download metadata fix first and use release code containing all three changes. Apply the migration before starting the new importer/API, then verify the installed revision and both new columns.
  2. Before new importer workers start, pause and drain old workers, including the live consumer. Finish old Batch jobs or cancel and resubmit them against the new job definition; queued jobs can still reference the old image. An old worker resuming a tracked import can write samples without recording their model names, leaving later retries to skip samples whose models were never recorded.
  3. Deploy compatible Middleman model-group responses before the strict Hawk API. Coordinate Control Tower and other ordinary callers' declarations, then deploy the importer/API and resume writers. Verify a restricted test import in both gates.

For rollback, pause writers before reverting importer code and review tracked partial imports before old workers resume them. Retain published policies, both columns, and the group function's retained-group branch; dropping that floor can reopen access. Keep the API reader fallback disabled on rollback: older code can replace stored groups on a read and undo published restrictions.

Backfilling folder model policies

The viewer and API decide who can read an eval set or scan folder from its .models.json policy. Policies written before the importers published them list only the models declared at launch, so they can be looser than the warehouse. scripts/ops/backfill_model_policies.py copies the model names and groups the warehouse recorded into those policies.

The backfill is union-only: it adds names and groups and removes none, with one exception: --kind scans drops a stale __unresolved__ marker (see below). It also adds each scan folder's inherited restricted floor, as the importers publish it. So on a folder that already has a policy it can only narrow who can read it, except that a scan folder whose scans have all resolved becomes readable again to holders of its remaining groups, as the importers would have left it. A restricted scan's folder keeps the marker only while one of its scans has results the warehouse can't classify yet; otherwise it is readable to holders of its groups and floor even while its scans are unresolved. A folder with no policy gets one only when the warehouse has groups for it. That widens access, from no reader to holders of those groups (who can already see the rows in the warehouse), so the report lists these folders separately as would create / created.

Modes, selected with --kind:

  • evals (default): each eval set's eval.observed_model_names and eval.model_groups into evals/<id>/.models.json. Names are written together with the groups they resolve to. Names that match no Middleman model are reported as unresolved and never written.
  • scans: each scan run folder's names (its source evals' observed_model_names) and scan.model_groups into scans/<run>/.models.json. A write run takes the importers' per-folder lock, so it can run while importers are live.
  • scan-usage: adds the groups of the models each scan's scanners actually called (its stored scan_model_usage keys) to scan.observed_model_groups and scan.model_groups, then republishes the scan folders. Only groups are written, since the keys are short model names. Keys that match no Middleman model are only reported, so review them in the dry run. It can't see scanners that return a list of results: their usage was never stored (Scout drops it from each result, and a run that returned none leaves no row).
  • scan-parquet-usage: reads only the scan_model_usage column of every scanner parquet of every scan (found in S3, not through warehouse rows) and records the Middleman names in scan.observed_model_names, as the scan importer does, so their groups restrict the scan, then republishes the scan folders. A name Middleman doesn't know hides the scan until it does, unless the folder's .models.json names it (a dynamic-catalog model). A scan missing a parquet for a scanner its _scan.json names, without a _summary.json entry accounting for it, or with an unreadable one, is reported as failed and left unchanged. A parquet written before Scout recorded usage takes its scanner's usage from _summary.json, or is reported if that has none. A scanner with no parquet that _summary.json says never ran is taken to have called nothing, and is listed in the report (no runs:) so it can be checked.

A scan result imported before the sample it scanned is marked __unresolved__, a group no one holds, and the backfill carries that marker into the folder policy (a restricted scan's too, since its grant's floor need not cover that transcript): the scan folder is hidden from everyone until the scanned transcripts are imported, at which point the importers remove it. --kind scans also removes it from a folder where no scan still carries it, which reopens that folder to holders of its other groups. The dry run counts folders that would gain the marker; check that count before a write run.

A scan whose scanners called a model that matches no middleman.model row is marked __unresolved__ too, and its import fails for retry. Models from Middleman's dynamic OpenRouter, Fireworks and Together catalog never get a row, so the scan importer accepts one when the scan folder's .models.json names it. Launch and API import write only names Middleman confirmed, and the importers' publish adds only names that match a row. The importer records such names in scan.confirmed_model_names and requires all of the folder's groups for them.

Run it as a database role that bypasses row-level security: BYPASSRLS, or a role that inherits rls_bypass (such as inspect-importer). Under RLS it would silently skip the restricted rows it exists to protect, so it refuses to start.

After deploying the importers that publish scan folder policies, run the modes in this order: --kind scans, then --kind scan-usage, then --kind scan-parquet-usage, then --kind evals. Run every mode with --dry-run first and review the report before writing:

DATABASE_URL=postgresql://... uv run python scripts/ops/backfill_model_policies.py \
    --bucket <bucket> [--kind scans|scan-usage|scan-parquet-usage] --dry-run
DATABASE_URL=postgresql://... uv run python scripts/ops/backfill_model_policies.py \
    --bucket <bucket> [--kind scans|scan-usage|scan-parquet-usage] [--id <folder-id> ...]

See scripts/ops/README.md for the full flag reference.

Creating a New Migration

After changing the SQLAlchemy models in hawk/hawk/core/db/models.py, use an isolated development database—never staging or production—to generate the migration:

cd hawk
uv run alembic revision --autogenerate -m "description of change"

Commit hawk/hawk/core/db/alembic/versions/head.txt with it; the alembic-head pre-commit hook sets it to the new revision. Two open PRs that each add a migration then conflict on that file, so the second one has to be re-parented before it can merge, instead of leaving main with two heads.

If head.txt conflicts after you rebase onto main, another migration landed first. Re-parent yours: set the down_revision of the first migration your PR adds (the one that points at the revision you branched from, not the newest) to main's new head, and rerun the hook so head.txt names your last revision. Moving only your newest migration leaves the earlier ones as a second head. If you had already applied your migrations to your own dev database, re-parenting makes that database skip the new parent, so downgrade to the revision you branched from (alembic downgrade <revision>; -1 undoes only your newest migration) before you change down_revision, and alembic upgrade head afterwards. alembic merge heads is only for repairing main after two heads have already landed.

Validate the complete migration chain against the disposable test database:

cd hawk
uv run pytest tests/core/db/test_alembic_migrations.py

Schema Conventions

  • All tables have a pk UUID primary key, and created_at/updated_at timestamps (exception: middleman_traffic.request, keyed by Middleman's request id and never updated)
  • All timestamps are timezone-aware and stored in UTC
  • Model names are singular