Skip to content

Latest commit

 

History

History
3189 lines (2565 loc) · 203 KB

configuration.md

File metadata and controls

3189 lines (2565 loc) · 203 KB

Configuration

Table of Contents

For guided local setup, start with the initialization wizard.

SchemaBot loads config from the SCHEMABOT_CONFIG_FILE environment variable.

Local Mode

The SchemaBot process runs the engine directly. This is best for most users and recommended to start with.

storage:
  dsn: "env:SCHEMABOT_DSN"

databases:
  mydb:
    type: mysql
    environments:
      staging:
        dsn: "env:STAGING_DSN"
      production:
        dsn: "file:/run/secrets/prod-dsn"

Database keys under databases: and environment keys under environments: must be lowercase. The server refuses to start if either contains uppercase characters. Consumer schemabot.yaml files are not held to this rule: the database: and type: values are folded to lowercase when the file is read, so database: Payments resolves to the payments server key.

A PostgreSQL environment can set table_owner beside its dsn or dsn_from to choose the role that owns the tables SchemaBot creates. It means the same as on a dsn_from target. An environment routed to a target sets table_owner on the target instead.

For integrated local setup, storage.database: schemabot selects a separate database after resolving the storage DSN reference. The host, credentials, and connection options are preserved, including later credential updates. Both MySQL and PostgreSQL support this field. Only init --integrated creates the database; normal server startup does not.

Building DSNs from separate secrets

If your deployment stores database connection metadata separately from passwords, use dsn_from instead of a raw dsn. config_ref and password_ref support the same secret reference formats as dsn, including env:, file:, and secretsmanager:.

storage:
  dsn_from:
    config_ref: "file:/run/secrets/storage-config.yaml"
    username: "schemabot_user"
    password_ref: "file:/run/secrets/storage-password"
    params:
      parseTime: "true"

databases:
  mydb:
    type: mysql
    environments:
      staging:
        dsn_from:
          config_ref: "file:/run/secrets/mydb-config.yaml"
          username: "mydb_user"
          password_ref: "file:/run/secrets/mydb-password"
          config_paths:
            host: databases.mydb.host
            port: databases.mydb.port
            database: databases.mydb.database

By default, the referenced database config is expected to contain top-level host, port, and database fields. port is optional and defaults to 3306 when omitted.

host: db.example.com
port: 3307
database: appdb

For other config shapes, set config_paths to the dot-separated YAML paths that contain the connection fields. SchemaBot does not assign meaning to path names; it only reads the configured values and builds one DSN.

databases:
  mydb:
    host: db.example.com
    port: 3307
    database: appdb

With the config_paths example above, SchemaBot reads:

  • databases.mydb.host for the hostname
  • databases.mydb.port for the optional port
  • databases.mydb.database for the database name

dsn and dsn_from are mutually exclusive for each storage or database environment entry.

The DSN dsn_from assembles follows the database type. A mysql, vitess, or strata database gets a Go MySQL driver DSN, as above. A type: postgres database gets a libpq URL built the same way as on a target_resolver target: the database name is read from dbname (set config_paths.dbname to change it; config_paths.database is rejected), the port defaults to 5432, and the URL always carries sslmode=verify-full. params accepts only sslmode: verify-full. The host must be an RDS endpoint, verified against the embedded RDS CA bundle unless PGSSLROOTCERT in SchemaBot's environment names other roots, as for any verify-full DSN; for any other host use dsn.

databases:
  orders:
    type: postgres
    environments:
      staging:
        dsn_from:
          config_ref: "file:/run/secrets/orders-config.yaml"
          username: "orders_user"
          password_ref: "file:/run/secrets/orders-password"
host: orders.cluster-abc.us-west-2.rds.amazonaws.com
dbname: orders

Per-target schema overrides

Static target_resolver.targets entries require exact lowercase engine types without surrounding whitespace, such as mysql and postgres. Values such as MySQL or mysql are rejected at startup, with or without overrides.

A data plane can attach a canonical-to-physical schema mapping after resolving an exact (environment, target) through Etre or static inventory:

target_resolver:
  targets:
    cluster-002:
      type: mysql
      dsn: "env:CLUSTER_DSN" # namespace-free
  overrides:
    - environment: production
      target: cluster-002
      type: mysql
      schema_overrides:
        orders_production: orders_sandbox

overrides is not a discovery backend. Configure exactly one of targets or etre. Each override requires an explicit lowercase environment, exact target, and engine type, plus exactly one mapping. MySQL and PostgreSQL mappings use the same identifier validation as static schema_overrides; other engines, unknown fields, duplicate environment/target pairs, and empty mappings are rejected. An override cannot also own a mapping in static inventory or a custom resolver.

Discovery and credentials are resolved using the original request. There is no fallback environment or target. Only after successful discovery does the resolver check the resolved identity and type and attach a copied mapping. An absent entry preserves the backend result, including any static mapping. Enumeration and single-engine reporting retain the underlying resolver's capabilities. Startup logs name configured mappings; debug logs record use. Neither log includes connection strings or credentials.

The engine operates on the physical schema and returns canonical namespace keys. The mapping is a strict allowlist: another namespace is refused. MySQL connections must remain namespace-free. A PostgreSQL mapping selects a schema within the database already named by the DSN.

Before enabling a mapping, resolve the target and pull/plan using its canonical namespace. Configuration validation cannot prove that a target exists. In a multi-target rollout, plan every target against its own live schema; sharing desired SQL does not imply identical plans after partial completion.

Adding, changing, or removing mappings requires draining work. This includes the first override: an older plan may refer to the canonical schema directly. Hold new operations for the affected target. Complete or explicitly retire all active, deferred-cutover, stopped, or otherwise resumable applies first. Hold affected target operations until every serving replica has the same config, and re-plan after every mapping change. A new mapping changes the client cache identity, but does not durably bind an old MySQL plan across driver restarts. Never execute a pre-change plan with a new mapping. To roll back, withdraw the affected route and drain its work before removing the mapping: removal restores identity mapping and can address a different schema. There is no hot reload. Durable mapping identity on plans is not enforced; this release depends on the drain-and-replan procedure, including discarding unused pre-change plans.

PostgreSQL dsn_from targets

target_resolver is the data-plane connection resolver: a server exposing the gRPC listener (started with GRPC_PORT set) receives an opaque execution target over gRPC and resolves it to a connection through this inventory, rather than routing logical database names through the control plane's databases table.

dsn_from on a target_resolver target supports type: postgres in addition to mysql. The assembled DSN is a libpq URL that always names one database and always carries sslmode=verify-full.

target_resolver:
  targets:
    orders-pg:
      type: postgres
      table_owner: "app_owner"
      dsn_from:
        config_ref: "secretsmanager:orders-pg-config"
        username: "schemabot"
        password_ref: "secretsmanager:orders-pg-password"
        ca_ref: "embedded:rds-global"   # optional; see below

table_owner selects the role that owns greenfield tables. Create steps use SET LOCAL ROLE so that role's default privileges apply. Grant the owner role to the connected engine role (GRANT app_owner TO engine) and grant the owner role USAGE and CREATE on each target schema. The setting is valid only for PostgreSQL targets; when omitted, tables are created as the connected role. An owner the engine role cannot assume, or one the target has no role for, blocks the create step at plan time with the grant or correction it needs. Table ownership explains what the owner controls and shows the full set of grants.

table_owner names one role for the whole target. A target whose schemas belong to different owner roles cannot set an owner per schema yet.

The referenced config document is JSON with top-level host, port, and dbname fields by default; set config_paths to read other keys:

{"host": "orders.cluster-abc.us-east-1.rds.amazonaws.com", "port": 5432, "dbname": "orders"}

The PostgreSQL shape differs from MySQL in three ways:

  • config_paths.dbname (PostgreSQL only). A PostgreSQL connection is made to one database, so the config document must carry the database name and the assembled DSN includes it; the request namespace selects a schema within that database. MySQL is the opposite — the DSN stays namespace-free and each request supplies the schema — so dbname is rejected for MySQL targets.
  • params allowlist. Only sslmode: "verify-full" is accepted — the value every assembled DSN carries regardless — so the field is validate-only. Weaker modes (require, prefer, verify-ca, disable) prove at most encryption, not server identity, and are rejected at config load. TLS trust material is configured via ca_ref, never via raw libpq parameters.
  • ca_ref (PostgreSQL only). Selects the CA bundle the server certificate is verified against: embedded:rds-global (the embedded AWS RDS global bundle) or file:<absolute-path> (a read-only mounted PEM bundle, for private proxies and test endpoints whose chain is not in the RDS bundle). When omitted, an RDS endpoint defaults to the embedded bundle and a non-RDS endpoint fails resolution: a verified CA is required, and the ambient trust store is never an implicit fallback.

Etre inventory environment mapping

A logical environment can use clusters hosted in another infrastructure environment. Configure environment_mapping on the Etre resolver to change only the env_label selector:

target_resolver:
  etre:
    - addr: https://etre.example.com
      database_type: mysql
      entity_type: cluster
      target_label: dsid
      env_label: env
      environment_mapping:
        sandbox: production
      mysql:
        host_field: writer_endpoint
      credentials:
        type: secret_ref
        username: ddl
        password_ref: env:DDL_PASSWORD

A sandbox request for orders-002 queries dsid=orders-002,env=production. The exact target is unchanged. Credentials come from that resolved entity; credential resolvers still receive the original logical request. Schema names, plans, applies, checks and lifecycle requests retain sandbox. This does not rewrite orders_sandbox to orders_production.

Unmapped environments retain their request name. Values are literal inventory labels, never recursive aliases or fallback queries. A mapping requires env_label, and keys and values must be nonempty lowercase environment names containing only letters, digits, underscores or hyphens, starting with a letter or digit. Requests still require an environment when env_label is set.

Environment mapping is server-owned routing configuration (AZ-1). Before changing it, hold affected work, drain active or resumable applies, deploy consistent configuration to every replica, discard old plans, and replan. Never resume stored work across a mapping change.

Etre targets with more than one match

An etre resolver expects its lookup to match one entity. Some inventories record both sides of a replicated pair under one target, such as a cluster and its standby during a blue/green switchover. A mysql resolver handles these without any configuration: when its lookup matches more than one entity, it connects to each match and reads read_only, innodb_read_only, server_uuid, and SHOW REPLICA STATUS. The target resolves to the match that accepts writes only when both of these hold:

  • Exactly one match has read_only and innodb_read_only off.
  • Every other match replicates from it: its replication status names the writable match's server_uuid as a source.
  • The writable match replicates from no server outside the matches. It may replicate back from its own standby, but a writable relay fed from elsewhere is not the authoritative copy, and a change made on it would collide with the same change arriving from its source.

Anything else refuses to resolve the target, and the error names each match and what it reported. That covers no writable match, two writable matches, a read-only match that replicates from somewhere else or from nothing, and a match the probe cannot connect to. A read-only match that does not replicate from the writer is refused rather than ignored, because nothing then shows that the two matches are copies of one database.

A lookup that matches one entity is not probed. A lookup that matches more than four is refused without probing. The matches are probed at the same time, each under its own timeout. The probe runs each time the target is resolved, so a switchover is picked up on the next request without any change to the inventory. It chooses the writer when a request resolves the target; it does not watch an apply that is already running.

The probe connects with the same credentials and TLS settings as the schema change, and needs the REPLICATION CLIENT privilege to read the replication status. SHOW REPLICA STATUS needs MySQL 8.0.22 or later; on an older server the probe refuses the target and its error says so. Resolvers for the other database types refuse a lookup that matches more than one entity.

PostgreSQL Etre targets

An etre resolver with database_type: postgres discovers PostgreSQL targets the same way it discovers MySQL ones: it looks the opaque target up by a label, reads the host from an entity field, and fetches credentials from the configured backend. It reads its own postgres block.

target_resolver:
  etre:
    - addr: "https://etre.example.com"
      database_type: postgres
      entity_type: db_cluster
      target_label: target_id
      env_label: env
      attribute_fields: [cluster_name]
      postgres:
        host_field: writer_endpoint
        table_owner: "app_owner"           # optional; see table_owner above
        ca_ref: "embedded:rds-global"      # optional for RDS endpoints
      credentials:
        type: awssm
        region: us-east-1
        secret_name: "db/{cluster_name}/schemabot"

A PostgreSQL connection is made to one database, so the resolver needs its name. It comes from the credential secret, which is read as JSON in the format AWS uses for RDS database secrets; any engine, host, or port fields are ignored, because the entity decides where to connect:

{"username": "schemabot", "password": "...", "dbname": "orders"}

Because the secret names the user, leave credentials.username unset. A resolver whose engine decodes its secret (postgres or vitess) refuses to start when a username is configured, on both the secret_ref and awssm backends, rather than ignoring it.

The awssm backend reads the secret in the region its region settings choose; see Etre credentials from AWS Secrets Manager.

table_owner and ca_ref mean the same as on a dsn_from target. They apply to every target the resolver serves, so a resolver serves clusters that share one owner role.

Etre credentials from AWS Secrets Manager

An etre resolver with credentials.type: awssm reads each target's database credentials from AWS Secrets Manager. Three groups of settings decide which secret it reads:

Settings Decide Default
secret_name the secret, templated over {target} and any {attribute} required
role_arn, account_attribute, external_id the AWS account, by assuming role_arn in the account account_attribute names the data plane's own account
region, region_attribute, reachable_regions the region the secret is read in required: region
secrets_manager_endpoints the Secrets Manager endpoint each region's reads are sent to each region's public endpoint

Which region a secret is read in

region is the data plane's home region. Roles are assumed through STS there, and secrets are read there unless the two optional settings place a target elsewhere:

  • region_attribute names the entity attribute that holds the region of each target's cluster, for example aws_region.
  • reachable_regions lists the regions, besides region, whose Secrets Manager the data plane can call. It requires region_attribute, and every listed region must be in the same AWS partition as region.

For each target:

region of the target's cluster, from region_attribute
├─ region, or listed in reachable_regions → read the secret in the cluster's region
└─ any other region                       → read the secret in region, as a replica

Without region_attribute, every secret is read in region.

Each deployment shape below needs a different combination:

All clusters are in the data plane's region. Set region alone.

credentials:
  type: awssm
  region: us-east-1
  role_arn: "arn:aws:iam::{account}:role/schemabot-reader"
  secret_name: "{target}/schemabot"

Clusters run in several regions, and the data plane can call Secrets Manager only in its own. Replicate every secret into the home region and add region_attribute. Reads stay in region, and when a secret is missing the error names the cluster's region and the replica it expected.

credentials:
  type: awssm
  region: us-west-2
  region_attribute: aws_region
  role_arn: "arn:aws:iam::{account}:role/schemabot-reader"
  secret_name: "{target}/schemabot"

The data plane can call Secrets Manager in every region its clusters run in. List those regions in reachable_regions, and each secret is read beside its cluster with no replica needed. Roles are still assumed through STS in region, because credentials from a regional STS endpoint are valid in every region of the same AWS partition, so only Secrets Manager has to be reachable in the listed regions. For the same reason, every listed region must be in the partition of region: credentials from the commercial partition cannot read a secret in GovCloud, China, or an isolated partition, so the resolver refuses to start with such a region listed.

credentials:
  type: awssm
  region: us-west-2
  region_attribute: aws_region
  reachable_regions: [us-east-1]
  role_arn: "arn:aws:iam::{account}:role/schemabot-reader"
  secret_name: "{target}/schemabot"

Shapes can mix: a cluster in a region that is not listed still has its secret read in region, so it needs a replica there while the clusters in listed regions do not.

The data plane reaches Secrets Manager in a region only through a private endpoint. A data plane with no route to the public internet can often still call Secrets Manager in another region through an interface VPC endpoint in that region, reached over private networking. The SDK sends each read to the region's public endpoint unless told otherwise, so name the private one in secrets_manager_endpoints:

credentials:
  type: awssm
  region: us-west-2
  region_attribute: aws_region
  reachable_regions: [us-east-1]
  secrets_manager_endpoints:
    us-east-1: https://vpce-0example.secretsmanager.us-east-1.vpce.amazonaws.com
  role_arn: "arn:aws:iam::{account}:role/schemabot-reader"
  secret_name: "{target}/schemabot"

Each key must be region or a region listed in reachable_regions, and each value an https URL that names only a host. The resolver refuses to start otherwise, rather than ignore an entry for a region no secret is read in. Reads are still signed for the region, so an entry changes where a read is sent and never which region's secret it reads. A region without an entry uses its public endpoint. Roles are assumed through STS in region as before, so this setting does not change how STS is reached. Secrets Manager rejects a custom endpoint in FIPS or dual-stack mode, so the resolver also refuses to start with this setting when the AWS config enables either (for example through AWS_USE_FIPS_ENDPOINT).

What each target account provides

In the account and region a target's secret is read in, the read needs:

  • The secret, named as secret_name renders for the target. In the home region that is usually a replica of a secret whose primary is in the cluster's region.
  • With role_arn: the role, trusting the data plane's identity and allowed to call secretsmanager:GetSecretValue on the secret in that region.
  • Permission for the reading identity to decrypt with the KMS key that encrypts the secret in that region. A replica is encrypted by a key in the replica's own region, so a policy that grants decrypt by key alias needs the alias to exist in that region as well.

Errors

With reachable_regions set, the attribute chooses where a secret is read, so a target whose entity has no value for region_attribute, or a value that is not an AWS region name, fails before any read rather than having its secret read in a region chosen for it:

target "orders" has no "aws_region" attribute naming the region of its cluster
target "orders" has "aws_region" attribute "us-east", which is not an AWS region name

Without reachable_regions, every secret is read in region whatever the attribute says, so such a target is still read there. It only loses the cluster's region from the error below if its secret is missing, and the resolver logs a warning for a value that is not a region name.

A secret missing from the home region, for a cluster in a region that is not reachable, names the fix:

fetch secret "orders/schemabot" for target "orders" in account 111111111111, region us-west-2:
get secret value "orders/schemabot": ... ResourceNotFoundException: Secrets Manager can't find
the specified secret.; the target's cluster is in us-east-1, which is not a reachable region, so
its secret is read in us-west-2: replicate the secret to us-west-2, or list us-east-1 as a
reachable region if this data plane can call Secrets Manager there

For a cluster in another AWS partition, where neither fix can work, the error says instead that the target has to be served by a data plane in that partition.

Changing the region settings

A change to these settings moves the reads of every target the resolver serves at once, and a target it breaks fails only when something next resolves it. Before listing reachable_regions, query the inventory for the entities the resolver matches and confirm each one carries a region name in region_attribute, since from then on a target without one fails. Before listing a region there, also confirm that the data plane can call Secrets Manager there and that every target in that region has its secret there: a listed region the data plane cannot reach turns each of those reads into a connection failure. The same holds for an entry in secrets_manager_endpoints: confirm from the data plane that the endpoint resolves and accepts a connection, and that its endpoint policy allows the reading identity, before pointing a region's reads at it.

gRPC Mode

SchemaBot delegates to remote services that implement the Tern proto. This is useful for distributed deployments where schema changes need to run in separate isolated environments.

storage:
  dsn: "env:SCHEMABOT_DSN"

databases:
  payments:
    type: mysql
    environments:
      staging:
        target: "payments-staging"
        deployment: tenant1
      production:
        target: "payments-production"
        deployment: tenant1

tern_deployments:
  tenant1:
    staging: "tern-staging:9090"
    production: "tern-production:9090"

Deployment keys and their nested environment keys under tern_deployments: must be lowercase. The server refuses to start otherwise.

In gRPC mode, target is an opaque identifier understood by the remote Tern service. SchemaBot stores the resolved target and deployment on each plan, then reuses that stored route during apply. Callers do not send target or deployment in plan/apply requests.

The example above is a single SchemaBot deployment that owns both environments. In environment-isolated deployments, each SchemaBot config should contain only the targets for the environments that instance owns. Use allowed_environments to scope each instance.

Multi-Deployment Environments

A single environment can fan out to multiple Tern deployments by replacing the scalar target / deployment pair with a deployments map. Each entry's key is a Tern deployment name (which MUST also exist as a key in tern_deployments), and each value carries the per-deployment target.

Validate() accepts a deployments map with any number of entries, and ResolveDatabaseTargets returns one execution target per entry in rollout order. An apply resolves that whole set and creates one apply_operations row per deployment. The driver claims each row and sequences the rollout along deployment_order under the environment's cutover_policy and on_failure policies. Control requests (stop, cutover, cancel) are recorded durably and consumed per operation, and progress, PR comments, and CLI output render per deployment.

Planning fans out too, and every deployment is held to the same plan. See Planning and the Primary Deployment.

storage:
  dsn: "env:SCHEMABOT_DSN"

databases:
  payments:
    type: mysql
    environments:
      production:
        deployment_order:
          - payments-c
          - payments-a
          - payments-b
        deployments:
          payments-a:
            target: "payments"
          payments-b:
            target: "payments"
          payments-c:
            target: "payments"

tern_deployments:
  payments-a:
    production: "tern-payments-a:9090"
  payments-b:
    production: "tern-payments-b:9090"
  payments-c:
    production: "tern-payments-c:9090"

Rules:

  • deployments is mutually exclusive with the scalar target / deployment fields and with a local dsn / dsn_from. Fan-out is a gRPC-mode shape: every key must resolve through tern_deployments, so an environment that executes against a local DSN cannot fan out.
  • The map MUST contain at least one entry, each entry MUST set a non-empty target, and each map key MUST resolve through tern_deployments with an endpoint configured for this environment.
  • Keys under deployments: must be lowercase; the server refuses to start otherwise.
  • A single-entry map is accepted and behaves identically to the scalar target / deployment shape. Single-deployment environments should continue to use the scalar shape.
  • cutover_policy and on_failure are only valid alongside a deployments map or a targets list. cutover_policy accepts rolling, barrier, or parallel, and defaults to parallel when every member of the environment comes from a targets list and to rolling otherwise, including for a deployments map that mixes targets entries with single target entries; on_failure accepts halt (the default), continue, or pause. Both values are captured on every operation row when the apply is created, so the policy in force at that moment travels with the rollout.

Planning and the Primary Deployment

The schema files are the source of truth. At review time SchemaBot plans every member of an environment by diffing that member's own live schema against the files, and the plan check covers all of them: approving the pull request approves the change on every member, not on one of them. A member that cannot be planned at all blocks the merge, so an unreachable member never passes quietly.

The first member in rollout order is the primary. What it does depends on how the environment lists its members:

  • A deployments map whose entries each name one target. The deployments are mirrors: they are expected to hold the same schema, so they are expected to plan the same changes. The primary deployment's plan is the reference. SchemaBot stores it, compares every other deployment's plan against it using a diff that is not persisted, and runs it on every deployment at apply time. A deployment whose plan differs from the primary's blocks the merge, because the plan under review was not written for it.
  • A targets list, at the environment level or inside any deployments entry. Each target holds its own schema, so no target is compared against another, the primary included. Each target runs the plan made for it. When targets plan different changes, the differences are shown for review and do not block the merge by themselves: they can be a rollout that landed on some targets and not others, or drift worth a look. How targets are planned shows an example. An apply that spans several deployments, one of them with a targets list, is refused for now; Multi-Target Environment shows how to apply one target at a time instead.

Every member's plan is reviewed, regardless of which member is primary.

Deployment Order

deployment_order defines the rollout order across the deployments map for an environment, analogous to the server-wide environment_order. When set, it MUST list every key in deployments exactly once (no empty, duplicate, or unknown entries) and MUST accompany a deployments map. ResolveDatabaseTargets then returns deployments in this order. When omitted, deployments resolve in alphabetical key order, which stays the deterministic default.

Every deployment name in deployment_order must be lowercase; the server refuses to start otherwise.

Under cutover_policy: barrier or parallel, copies start in this order and cutovers follow it: a deployment's cutover runs only once every earlier deployment has completed, revert window included. An earlier deployment that failed stops holding the rollout under on_failure: continue, or under pause once the rollout is released; under halt, and under pause until a release, it holds every later cutover. An apply started with --defer-cutover follows the same order. Each schemabot cutover runs the cutover of the deployment whose turn it is, and only that deployment: a second deployment waits for a second command. A cutover requested while every ready deployment is still waiting on an earlier one is refused, and the refusal names the deployment holding the turn. Within a deployment, copies never wait on each other to start, and each shard's cutover runs as soon as it is parked, at most the server's max_drivers_per_apply operations of one apply at once. A schemabot cutover addresses the deployment's data-plane apply as a whole, so SchemaBot does not order that deployment's shards and tables among themselves. The targets of a targets list do not wait for each other this way; Multi-Target Environment describes how their cutovers run. An apply that spans several deployments while one of them has a targets list is refused, so one apply never mixes the two.

Multi-Target Environment

A database that lives on more than one target replaces the scalar target with a targets list. Each entry is one target the environment addresses, and rollout follows the listed order.

MySQL only. targets is rejected at startup on any other database type. Addressing N targets has to be represented on every operator-facing surface — the plan comment, progress, the terminal summary — and that presentation is built per engine, so the feature is enabled per engine as the work lands.

Each target is planned against its own live schema, and the apply runs each member against the plan that member was planned for, so one target's DDL is never run against another. The progress comment lists each target and its copy; the plan comment and terminal summary say how many targets the change rolls out to. Multi-target environments shows a rollout on a pull request.

databases:
  payments:
    type: mysql
    environments:
      production:
        deployment: payments-a
        targets:
          - payments-001
          - payments-002

How targets are planned

The schema files are the source of truth for every target. SchemaBot plans each target by diffing its own live schema against the files, so each target's plan is exactly the work that target needs. No target is compared against another target.

For example, a pull request adds an email column to users, and payments-002 is also missing an index the files already declare:

schema files in the PR
  │
  ├─ diff ─► payments-001 (primary) ─► ADD COLUMN email
  └─ diff ─► payments-002           ─► ADD COLUMN email, ADD INDEX idx_status

The plan comment shows each plan under the targets that run it, so both plans are reviewed together. The apply runs each target's own plan: payments-001 gets the column, and payments-002 gets the column and the index. A target that cannot be planned at all blocks the merge.

The first target in the list is the primary target. Nothing is compared against it, and the plan comment does not put it first: plans with work come first, the one the most targets run leading, and targets already at the desired schema follow.

An apply of the environment fans out to every listed target and follows each target's copy in one watcher. Under the default cutover_policy: parallel, the targets copy at once, as many as the server's max_drivers_per_apply allows (2 by default, so the rest wait as queued), and each target's cutover runs as soon as its own copy is ready. The animation runs with a cap of 4, so all four targets copy together:

Apply an index to four targets of one environment and follow their copies in parallel

A targets list can also sit inside a deployments map entry, for a database whose targets are spread across several deployments:

      production:
        deployments:
          payments-a:
            targets:
              - payments-001
              - payments-002
          payments-b:
            target: payments-003

An apply that spans several deployments, one of them with a targets list, is not supported yet and is refused before it takes the lock. Apply one target at a time instead, in rollout order: schemabot apply -e production --target payments-001, then the next target. The refusal names the first one. Apply to one target of a rollout shows a narrowed apply:

Plan and apply an index to one target of a multi-target environment

A rollout already up to date applies nothing, so an apply that confirms it converged still succeeds.

Selecting namespaces per target

When a database's namespaces are spread across its targets, an entry can be a mapping that names which namespaces live on that target. A bare string and a mapping without namespaces both mean the target holds every namespace the schema files declare.

      production:
        deployment: payments-a
        targets:
          - target: payments-001
            namespaces: [payments_0, payments_1]
          - target: payments-002
            namespaces: [payments_2, payments_3]

The schema directory declares the namespace set; namespaces only selects from it and can never add one. Each target's plan, stored plan, and apply cover only its selected namespaces. A pull of the whole environment asks each target for its selected namespaces by name rather than discovering them on the cluster, and an explicitly requested namespace a target does not select is left out of that target's pull. The pulled schema takes each namespace from the first target in rollout order that holds it, so a pull of an environment with an unsharded schema on one target and a shard schema on each of the others returns all of them, and each target is compared only on the namespaces it holds. A target holds the namespaces its entry selects, or every namespace when its entry selects none. A target without a selection that comes first therefore supplies every namespace, including one a later entry selects. If its cluster lacks that namespace, the pull leaves the namespace out and reports the later target's tables in it as extra, which is the same drift a plan of that target would act on.

A namespace that the schema files declare but a target's entry does not select is an unselected namespace of that target. In the example above, payments_2 and payments_3 are unselected namespaces of payments-001. They still exist, on another target, so they are withheld from that target's plan rather than removed. SchemaBot sends the target's plan only the files of its selected namespaces. It names the rest in the plan request's unselected_namespaces, so the Tern deployment knows those namespaces are left out on purpose. Their live tables are never treated as tables to drop.

Rules:

  • targets requires type: mysql. Configuring it on a vitess, strata, or postgres database fails validation at startup.
  • targets is mutually exclusive with target at the same level, and with a local dsn / dsn_from.
  • An environment-level targets list is mutually exclusive with an environment-level deployments map, the same way an environment-level target is. A targets list inside a deployments entry is how the two combine.
  • The list MUST contain at least one entry, and no entry may be empty.
  • A rollout across the listed targets runs table by table: each table lands on every target before any target starts the next. Tables run in the order the reviewed plan lists them, then any table only another target's plan changes, sorted by name. A target whose plan does not change a table has nothing to run for it, and two statements on one table run together. The exception is a rollout where a target's plan changes a VSchema, which applies with that target's tables, so each target then runs its whole change in one go.
  • cutover_policy and on_failure order the listed targets' copies within each table the same way they order the deployments of a deployments map: each target is a rollout member, taken in list order. Cutover is where targets differ from deployments. The default here is parallel: it starts up to the server's max_drivers_per_apply targets' copies at once, queues the rest, and cuts each target over as soon as its copy is ready: a target never waits for an earlier target's copy or cutover to finish, and an earlier target holds a later target's cutover only while it is failed, retrying a failure, stopped, cancelled, or reverted. The multi-target apply animation shows this default with four targets. A deployment with a targets list therefore refuses --defer-cutover; apply one target at a time with --target to hold a target's cutover. Under the default on_failure: halt a failed target stops every queued target from starting, and holds the cutover of every later target already copying: each of those finishes its copy and waits at the cutover barrier until an operator stops or cancels it. The failed target's own other shards do not wait: each one whose cutover has not begun is cancelled. max_drivers_per_apply is therefore what bounds how many targets copy at once, and how many a failure can leave holding a finished copy, so raising it widens both; size it for the targets that share a host's disk and network as well as for throughput. An environment that relies on an unset cutover_policy running one target at a time needs cutover_policy: rolling to keep doing so: a failed target then stops every later one before it starts copying. Whatever on_failure says, a table that failed on any target ends the rollout at that table: continue or a released pause still runs it on the remaining targets, but no target starts the next table.
  • No entry may contain /. A deployment addressing several targets names each one in its members' operation keys, and / separates a key's components.
  • One deployment may not list the same target twice. A rollout member is identified by its deployment and target together, so the same target under two different deployments is two distinct members and is allowed.
  • Members resolve deployments outermost: every target of the first deployment, then every target of the next.
  • A mapping entry accepts only target and namespaces; any other key, including a misspelling such as namespace, fails validation at startup.
  • namespaces is an enumerated list of names, not a pattern. When present it MUST contain at least one entry; each entry must be non-empty, listed once within the entry, and free of /. A namespaces key with no list (no value, ~, null, or items that are all commented out) fails validation at startup rather than reading as every namespace.
  • The target is still the rollout member, so a target may not be listed twice even with different namespaces.
  • A selected namespace the schema files do not declare, or one ignore_namespaces withholds, is an error at plan time that names the target and the namespace. For the primary target it fails the plan; for any other target it blocks the review.
  • Every declared namespace must be selected by some target; a target without namespaces selects all of them. A declared namespace no entry selects fails every plan of the environment, whether from a pull request or the CLI, since no target would plan or apply it. On a pull request that environment's check fails; the API answers 400 Bad Request naming the namespaces. To keep one out of the rollout on purpose, list it in ignore_namespaces.
  • Selecting namespaces needs a target whose DSN does not name a database. A database-scoped DSN is diffed as one unit, so the namespaces an entry does not select would have their live tables planned as DROP TABLE; the plan refuses instead, as it does for ignore_namespaces.

Rollout order: upgrade the Tern deployments serving an environment before adding namespaces to its entries. The refusal above for a database-scoped DSN happens in the Tern deployment, which needs unselected_namespaces to make it. There is no version check between SchemaBot and Tern. A Tern deployment from an earlier release discards unselected_namespaces without error and plans the unselected namespaces' live tables as DROP TABLE. SchemaBot reads every plan that comes back and refuses one that drops an unselected namespace's tables, with or without --allow-unsafe, so such a plan fails rather than going to review:

  • A drop the plan places in an unselected namespace is refused, and the error asks for the Tern deployment to be upgraded.
  • A drop placed in a selected namespace, or in none, is refused when an unselected namespace declares a table of that name, ignoring case. This is the MySQL case, where the engine attributes every drop to the namespace it was sent. A live table that no schema file declares is not caught this way, and is reviewed like any other unsafe drop.

targets and deployments both fan an environment out across several members, and both expect every member to end up holding the schema the files describe for it: every declared namespace, or, for a target whose entry selects namespaces, only those. What differs is what a difference between members means when one is found.

The deployments of one environment are mirrors, so a difference between them is a fault: the plan under review was not written for the member that disagrees, and the check blocks rather than apply it.

The targets of one environment are each planned against their own live schema, so a difference between them is the work to be done — a target added since the last change, a rollout that landed on some targets and not others. Blocking there would prevent the convergence that resolves it, so the check does not block. It does not block, but it is not silent either: a difference between targets is reported, because it is the first thing worth looking at.

Environment Order

Environment availability and promotion order are server-owned. Repository schemabot.yaml files identify the database and type; they do not list or opt into environments. SchemaBot resolves the environments for a database from server config:

environment_order:
  - staging
  - production

If omitted, SchemaBot defaults to staging before production. Before applying production from a PR comment, SchemaBot checks staging first because the server-owned environment_order says staging precedes production.

Every environment name in the top-level or per-database environment_order must be lowercase; the server refuses to start otherwise. Values in allowed_environments have the same lowercase requirement.

There are two related but separate concepts:

  • Routing environments — the databases.<name>.environments entries this SchemaBot process can plan/apply directly. These entries must include the local DSN or remote target/deployment needed to execute work for that environment.
  • Promotion order — the ordered environment chain used by PR comment applies. In a single deployment, this is normally the same set as the database's routing environments. In a deployment scoped with allowed_environments, promotion gating uses environment_order so a production-only deployment can still verify earlier environments that are owned by another SchemaBot deployment.

For example, this production-scoped deployment only has production routing metadata, but production applies still require the staging aggregate check to be successful because staging precedes production in environment_order:

allowed_environments:
  - production

environment_order:
  - staging
  - production

databases:
  payments:
    type: mysql
    environments:
      production:
        target: "payments-production"
        deployment: primary

tern_deployments:
  primary:
    production: "tern-production:9090"

The production deployment does not need a staging target. It verifies staging by reading the staging deployment's GitHub aggregate check, then resolves only the production target from its own config.

Per-Database Environment Order

Databases promote through different environment sequences — one database may run qa → sandbox → production while another runs qa → staging → production — and a single server-wide order cannot express both. A database entry may override the promotion order with its own environment_order. In this example a qa/sandbox-scoped instance promotes payments through qa → sandbox locally, with production owned by a peer instance:

allowed_environments:
  - qa
  - sandbox

environment_order:
  - qa
  - staging
  - production

databases:
  payments:
    type: mysql
    environment_order:
      - qa
      - sandbox
      - production
    environments:
      qa:
        target: "payments-qa"
        deployment: primary
      sandbox:
        target: "payments-sandbox"
        deployment: primary

When set, the database's environment_order replaces the server-wide order entirely for that database's promotion gating: an apply to an environment in the list requires a successful SchemaBot check for every earlier entry, and environments the database does not promote through simply do not appear. Databases without an override keep using the server-wide environment_order unchanged.

The override is validated at startup, fail-fast in both directions:

  • Every environment configured under the database's environments must appear in its environment_order — otherwise applies to it would be blocked as unlisted.
  • Every environment_order entry owned by this instance (per allowed_environments; all entries when the instance is unscoped) must be configured under the database's environments — otherwise a later environment's apply would wait on a prior check that can never exist.

Entries owned by another instance in the promotion chain (outside this instance's allowed_environments) may be absent from the database's local environments: the promotion gate verifies them through the peer's GitHub aggregate check, exactly as with the server-wide order. Instances sharing a database must declare the same effective order for it — render all instances' config from a single source.

Renaming identifiers

When lowercasing an existing database key, rename the server config key and the schema directory in lockstep. Consumer repositories' schemabot.yaml database: values are folded to lowercase when read, so they match the renamed key without a change of their own. That fold exists only on releases that canonicalize consumer config at ingress: while any instance in the fleet still runs an earlier release, keep the consumer database: values spelled exactly as the server key, or rename them in the same lockstep. Renaming while an apply is in flight is unsafe; drain all in-flight applies first.

When upgrading to a release that folds repository identity at ingress, drain in-flight applies before upgrading. Rows written by earlier versions may carry mixed-case identity values — repository names, database names, environments, deployments, and lock owner values such as Org/Repo#42; on PostgreSQL, the folded lookups cannot match those rows again, so locks cannot be reacquired or released and checks duplicate instead of updating. Once every writer — server and workers — runs the folding release (a writer still on an earlier release would keep writing mixed-case rows, reintroducing the rows the fold cures), fold the stored rows once with

schemabot storage canonicalize-identity-keys --config /etc/schemabot/config.yaml

Run it inside the maintenance window with the server quiesced — the command connects to storage itself and works while the server is down. The fold row-locks every row it rewrites until its table's fold commits; under live traffic, lock lookups and FOR UPDATE SKIP LOCKED claims would skip those rows for the duration. The rewrite is one-way — original spellings are not recorded anywhere — so the command prompts before touching rows; pass --auto-approve (-y) for scripted maintenance windows. It only rewrites rows whose spelling is not already canonical, so rerunning it is safe.

Each table folds in its own transaction. When two rows differ only by case (for example locks on Foo and foo of the same database type), that table's fold refuses rather than collapse them, naming the violated unique index — tables already folded stay folded. Delete or repair the duplicate rows by hand, then rerun to fold the rest. Force-release remains the fallback for any lock stranded before the fold runs.

Hybrid Mode

Both modes can be used simultaneously. Each database environment in the databases section chooses one route: local mode with dsn, or gRPC mode with target and deployment. This is useful when some databases are co-located with SchemaBot and others are in remote environments.

storage:
  dsn: "env:SCHEMABOT_DSN"

databases:
  local-db:
    type: mysql
    environments:
      staging:
        dsn: "env:LOCAL_DB_DSN"
  remote-db:
    type: mysql
    environments:
      staging:
        target: "remote-db-staging"
        deployment: default

tern_deployments:
  default:
    staging: "tern-staging:9090"
    production: "tern-production:9090"

Routing is always server-side. A database environment with dsn uses local mode. A database environment with target and deployment uses gRPC mode through the matching tern_deployments endpoint. A database that is not listed in databases is not routable.

Drivers

SchemaBot runs a background operator for apply work that needs server-side coordination. By default, four drivers poll for claimable work so a server can make progress across independent databases and environments concurrently.

drivers: 4

Increase drivers when one SchemaBot server should make operator progress across independent databases or environments concurrently. More drivers help high-scale installations with many schema changes because each driver can claim and resume a different target during the same operator tick. The operator still excludes overlapping work for the same database and environment, so this improves concurrency across independent targets, not parallel execution against one target.

A driver claim means selecting one stale apply and refreshing its heartbeat in the same storage transaction. That heartbeat refresh is the driver's lease while it reloads state and drives the apply to a terminal state.

Metrics

SchemaBot serves Prometheus metrics at /metrics on a dedicated HTTP listener, separate from the API port. A separate port lets scrapers reach metrics without traversing the API port's transport security — for example when a service mesh proxy terminates mutual TLS on the API port — and keeps the endpoint off any externally routed surface.

metrics_port: 9102

The listener binds :9102 by default; set metrics_port to move it. The API port (the PORT environment variable) does not serve /metrics.

Sizing: each driver drives one claimed apply synchronously to a terminal state, and that includes waiting states such as deferred cutovers and revert windows, so a server's effective apply concurrency is drivers × replicas. Size that product to the number of applies you expect to be in flight at once, counting parked ones — a deferred cutover holds its driver for the full wait. One driver on each server with two or more never starts, resumes, or recovers work for an apply that defers its cutover, whether it was started with --defer-cutover or is a rollout member a control plane dispatched with its cutover deferred, so a server whose other drivers are all waiting on an operator's cutover still picks up other databases' applies, recoveries, and stops. That driver still delivers stop and cancel requests to a deferred apply, including recovering a crashed drive of one to deliver them, and then hands the apply back so another driver resumes it if the request did not end it. Count it out when sizing for deferred applies: drivers: 4 across four replicas runs up to twelve deferred operations at once. A server with a single driver reserves nothing. A control plane that dispatches to remote servers bounds end-to-end concurrency with its own driver pool the same way.

Deferred cutover capacity

An apply started with --defer-cutover copies each table and then waits for someone to run schemabot cutover. While an operation (one shard, or one deployment) waits, it keeps its driver. SchemaBot accepts the cutover command only once every operation of the apply is waiting, so the apply needs a driver for each of them at the same time. Under barrier and parallel that is every shard of every deployment. Under rolling it is the shards of one deployment at a time.

If there aren't enough drivers, some operations wait and the rest never start, so the apply can never reach its cutover. It would hold its drivers until the waiting-for-cutover timeout ended it. SchemaBot refuses such an apply when it starts instead.

How SchemaBot counts drivers. Each server that runs drivers writes how many it has to the driver_pools table when it starts, updates the row every 15 seconds, and deletes the row when it stops. A server that hasn't updated its row in the last minute isn't counted. That is the same amount of time after which other servers take over its work. Each server keeps one driver free for other work, so a server with drivers: 4 adds three, and four such servers give twelve. Adding or removing servers changes the total, with no setting to update.

When SchemaBot refuses. A deferred apply of two or more operations is refused when either of these is true:

  • It has more operations than max_drivers_per_apply. The default is 2, so a deferred apply of more than two shards is refused until you raise it to at least the size of the largest deferred apply you run.
  • It has more operations than all the servers' drivers can hold together, counted as above.

The check is about the apply's own size. It counts every driver the servers have, not only the free ones, so waiting for other applies to finish does not change the answer. The refusal says what to raise and by how much: max_drivers_per_apply, the servers' drivers setting, or how many servers you run. You can always run the apply without --defer-cutover instead.

A deferred apply of a single operation is never refused, since one cutover command reaches all of it. On a pull request, schemabot apply checks before it asks you to confirm, so nothing is locked when it refuses. Creating the apply checks again.

Sharing drivers with other applies. Other applies don't count against the check. They use drivers as usual, and an operation that finds none free waits for one. Deferred applies get drivers in the order they started: a deferred apply doesn't start an operation while an earlier deferred apply still has one waiting for a driver. Without that order, two deferred applies could each hold part of the drivers, and neither could reach its cutover. An apply that was stopped and then started again goes behind the deferred applies that started while it was stopped, because it gave up its drivers when it stopped. The one driver each server keeps free is what stops deferred applies, all together, from leaving every driver waiting on a person.

Deployments on a remote data plane. When a deployment runs its operations on a remote data plane, each operation holds a driver there too. So for a deferred apply of two or more operations, SchemaBot also asks each such deployment how many drivers its servers run, how many of those can wait, and what its own max_drivers_per_apply is. It refuses the apply the same way if the operations it would send to that deployment are more than either, and the refusal names the deployment. The data plane gives drivers to deferred applies in the order they started, the same way. SchemaBot asks once per check, with the same time limit as a health check but separately from it, so a deployment that doesn't answer only refuses deferred applies and keeps running every other apply. A deployment on an older SchemaBot doesn't answer, so deferred applies to it are refused until it is upgraded.

Upgrade the data planes before the control plane. A control plane only defers the cutover of operations it sends to a deployment that answers, because answering also tells it that the deployment runs the cutover of every operation a cutover command names and records each command only once.

If a server goes away later. SchemaBot counts the drivers when the apply starts. If a server stops after that, the apply has fewer drivers than it counted on, and its waiting operations move to the other servers' drivers. If those aren't enough, no cutover runs: the apply waits until someone cancels it or the waiting-for-cutover timeout ends it.

Per-apply driver cap

A single apply that fans out across many deployments or shards claims its operations like any other work. Without a bound it takes every driver on the plane and holds them for as long as its slowest operation runs, so no other database's work — and no stop or cancel — is picked up until it finishes.

max_drivers_per_apply: 2

max_drivers_per_apply caps how many operations one apply may have in flight at once, across every replica. Size it against drivers × replicas: set too high it bounds nothing, set too low a sharded fan-out drives only a few operations at a time. For a multi-target environment, each target's copy of a table is one operation, so the cap is how many targets copy at once; the animation there shows four targets copying together under a cap of at least four.

The cap applies only to starting new operations — a first start, a resume after a stop, and a deferred deploy are all capped. Recovering an operation whose driver crashed, and consuming a stop or cancel request, are never capped: an apply already at its cap must still be able to recover and to be controlled, or the cap becomes the thing that wedges the apply it is bounding.

The cap is a steady-state bound, not a hard admission limit. Each claim evaluates the count independently, so drivers polling in the same instant can all read the same pre-claim value and admit together — a pod restart or rolling deploy, where every driver's first poll lands at once, is the shape that produces it. The transient ceiling is the number of drivers claiming in that window; once those leases commit, the next claim counts them and the cap binds again. Size against the steady-state number, and do not treat the cap as a guarantee that an apply can never briefly exceed it.

A multi-shard apply started with a manual --defer-cutover keeps its drivers while it waits: unlike the automatic barrier park, a manually deferred operation holds its claim and keeps heartbeating, so it stays counted. Its cutover is accepted only once every operation waits, which takes a cap no smaller than the apply's width, so a deferred apply that would hold more operations at once than max_drivers_per_apply is refused at the start. Run it without --defer-cutover, or raise max_drivers_per_apply to at least its width.

Change Events

Use change_events to send JSON lifecycle events to HTTP destinations. Each destination selects its environments and events. A server with no destinations configured sends no events.

change_events:
  - url: https://events.example.com/schema
    environments: [production]
    events: [operation.started, operation.finished, apply.finished]
    body: |
      {"app":{{json .App}},"environment":{{json .Environment}},
       "timestamp":{{.OccurredAtNanos}},"description":{{json .Description}}}

Templates receive .Type, .App, .Environment, .OccurredAtNanos, and .Description. Use the json function to encode string values. .App comes from the database registration's app field and falls back to the logical database name when no application is registered.

  • The executing worker reports operation.started when a fresh attempt reaches the engine. It reports operation.finished when a drive that called the engine commits the attempt outcome. After a takeover, the finish can be omitted if the drive cannot establish a new outcome for the attempt. An automatic retry opens a new attempt even when its outcome is again failed_retryable.
  • The control plane reports apply.finished when a state transition records the settled rollout outcome. If the rollout settles while the apply already has that outcome, the event is omitted. The description includes the apply ID and deployment outcomes for pull request and CLI applies.

Each server configures its own destinations. For a remote apply, configure the worker to report operation events and the control plane to report the aggregate outcome. Worker events use the executing deployment's apply and operation IDs. The worker receives the managed app label in the existing dispatch options.

Amazon SQS destinations

Use sqs_change_events to publish structured JSON to an existing standard SQS queue. Each queue selects its own events and environments. It works on its own or alongside the HTTP destinations above.

sqs_change_events:
  - queue_url: https://sqs.us-east-1.amazonaws.com/123456789012/schema-events
    region: us-east-1
    environments: [production]
    events: [apply.finished]

Grant the server role sqs:SendMessage on that queue. The publisher uses the AWS SDK credential chain. Set region to the queue's region or supply it through the AWS SDK configuration. Omitting sqs_change_events disables SQS delivery.

An apply.finished message for a successful apply looks like this:

{
  "event_id": "103dfb3a-5cb6-4b2c-b36a-6bc0d75ce5c7",
  "type": "apply.finished",
  "id": "apply_example",
  "app": "checkout",
  "database": "orders",
  "database_type": "mysql",
  "environment": "production",
  "repository": "example/schemas",
  "pull_request": 42,
  "outcome": "completed",
  "completed_at": "2026-11-20T00:00:00Z",
  "occurred_at_nanos": 1795132800000000000
}

Use event_id to deduplicate deliveries. With a local worker, operation events and the control plane’s apply.finished event share the same apply id. With a remote worker, operation events carry the worker’s apply ID and apply.finished carries the control plane’s apply ID. Joining on id only correlates events within the same apply record.

Apply outcomes include completed, failed, cancelled, and reverted. Consumers that react only to successful schema changes should select outcome == "completed". occurred_at_nanos is when the hook observed the event. completed_at is the stored apply completion time, falling back to the stored update time. Operation events include operation_id, deployment, and attempt. Only finish events carry an outcome, and only aggregate finish events carry completed_at. Repository and pull request fields are omitted when absent.

Delivery is best effort for both transports. Each destination uses a bounded in-memory queue and a three-second send deadline. A full queue, a failed send, or shutdown can lose events. The SQS publisher makes one send attempt. Once SQS accepts a message, the queue's retention and delivery policies apply. Delivery failures are logged. SchemaBot writes no outbox rows. When a reaper settles an apply, delivery workers load the event details in the background so the reaper can update GitHub without waiting.

Rate Limits

POST /api/pull reads a database's live schema. Per namespace, that opens a connection to the target, issues one SHOW CREATE TABLE per table, and (at detailed catalog detail) runs several information_schema scans that walk every table's metadata. A client in a loop, an automated onboarding sweep, or a service polling for schema inventory can therefore load the control plane and the target database at once, so the endpoint enforces a request budget and refuses anything over it with 429 Too Many Requests.

Rate limiting is on by default with the budgets below. They are sized so that no legitimate use reaches them while a runaway still trips them by orders of magnitude: a client stuck retrying issues hundreds of requests a second, not two. The point is to stop a runaway, not to pace normal work.

rate_limits:
  pull:
    enabled: true              # default: true
    per_caller:
      requests_per_minute: 600 # default: 600
      burst: 120               # default: 120
    per_target:
      requests_per_minute: 120 # default: 120
      burst: 30                # default: 30

The two lanes are not sized alike, because they bound different amounts of work. The control plane does little per pull: decode, resolve the route, forward one RPC per namespace, marshal the response. The target does the real work, and it scales with the schema rather than with the request, so the per-caller lane is generous and the per-target lane is the conservative one.

Each request must have budget in both lanes:

  • per_caller is keyed on the authenticated caller, which is the operator's identity for a request through the forward-auth proxy lane and the SPIFFE ID for a service caller through the gateway lane. It keeps one runaway client from consuming the server's capacity. When API auth is disabled every request arrives as the same anonymous caller, so this budget then applies to all traffic together, and a refusal in this lane says so rather than naming the caller in front of it.
  • per_target is keyed on the database and environment being read, across all callers. It protects the target database, whose load does not care how many distinct clients produced it.

A refused request carries error_code: rate_limited, a Retry-After header, and the same delay as retry_after_seconds in the response body. The code is retryable: a client should wait the advertised delay and retry rather than treating the response as a failure. The message names the budget that ran out, so a caller well inside its own budget can tell it is being limited for the load on one database:

HTTP/1.1 429 Too Many Requests
Content-Type: application/json
Retry-After: 1

{
  "error": "too many pull requests for this database and environment; retry in 1s",
  "error_code": "rate_limited",
  "retry_after_seconds": 1
}

The delay is always at least one second, since a client told to retry in zero seconds would retry immediately, which is what the budget is refusing. See Rate Limits in TEMPLATES.md for how a refusal renders at the terminal.

A malformed request is rejected before any budget is spent. A well-formed request naming a database this server does not route does spend budget, because resolving the route is server-side work and a client looping on an unknown database is exactly the runaway the budget exists to bound.

Omit a field to keep its default. Values must not be negative, which fails validation at startup rather than silently admitting everything; to turn enforcement off, set enabled: false.

Budgets are enforced per server process, so a deployment running N replicas admits up to N times the configured rate overall. Size the numbers as a per-replica ceiling.

Check inspection

An environment filter selects its Check Runs and its database rows, plus any unresolved local predecessors that explain its gate. Missing predecessor results appear as pending evidence. Expected names follow the same verified repository coverage as publication and guarded backfill; an unregistered optional environment is not reported as a missing check.

GET /api/checks/inspect (schemabot checks show) reads the pull request and each expected Check Run from GitHub on every call, uncached, through the same GitHub App installation SchemaBot publishes its Check Runs through. A caller polling it in a loop can spend the installation's hourly REST quota, and then SchemaBot's own Check Run writes start failing and the merge gate goes stale. The endpoint therefore has a per-caller budget, also on by default:

rate_limits:
  checks_inspect:
    enabled: true             # default: true
    per_caller:
      requests_per_minute: 6  # default: 6
      burst: 10               # default: 10

The budget limits each caller on each replica, not the installation. Every replica admits the configured rate on its own, and every admitted inspection draws on the one installation quota, so size it against the whole deployment. Each inspection costs one installation-authenticated GitHub read for the pull request plus at least one per expected check name. The most one caller can be admitted, when its requests spread across every replica, is approximately replicas × 60 × requests_per_minute × (1 + check names) calls an hour; size requests_per_minute so that ceiling, across the callers you expect, stays inside the installation quota. On the defaults, a deployment of three replicas publishing two check names admits one caller up to 3,240 calls an hour, about two thirds of the 5,000 an hour the smallest installation quota allows. Check Run pagination multiplies those reads, the initial burst permits additional inspections, and resolving the installation client adds three app-authenticated calls per inspection (the App, the repository's installation, and a fresh installation token) that count against the App rather than the installation. A client's own cost does not grow with the replica count: it is the client's request rate × (1 + check names). A dashboard polling three pull requests every 30 seconds makes 6 requests a minute and spends 360 × (1 + check names) calls an hour, 1,080 with two check names, on any number of replicas. A client that holds its connection open usually stays on one replica, so it needs requests_per_minute of at least its own poll rate there; the default of 6 fits that dashboard. A deployment that runs more replicas, publishes more check names, or has deep Check Run histories should lower requests_per_minute, but not below the poll rate of the clients it serves.

per_caller is keyed the same way as the pull endpoint's. With API auth disabled, every caller shares one budget. There is no per_target lane. A refusal is the same 429 with error_code: rate_limited and Retry-After, and it is returned before any GitHub call is made. Set enabled: false to turn enforcement off.

GitHub quota reserve

One GitHub App installation's hourly REST quota is shared by every pull request in every repository it serves. Planning a pull request reads its schema files and repository trees, and a burst of plans can spend the whole quota. Once it is gone, GitHub refuses SchemaBot's Check Run writes too, so required checks stop posting on every pull request the installation serves.

quota-reserve holds back that many requests per installation for the work that gates merges. Once GitHub reports that many or fewer requests remaining, SchemaBot stops sending the schema file, blob, and tree reads a plan makes until the quota resets. Check Run writes and reads, pull request reads, changed-file lists, and comments still go out, and so do the same file and tree reads when SchemaBot makes them to decide what a Check Run says, such as which environments a pull request's configs cover. A plan that needs a refused read fails closed: the pull request's SchemaBot check does not pass until a plan succeeds after the reset. When a refused read stops SchemaBot from finding a pull request's configs, or from running an apply command, SchemaBot retries it when the quota resets, plus up to one minute picked at random, so the events the reserve refused until the same reset do not all run again in the same second and spend the new quota down to the reserve. For three hours after the event arrived that wait does not use up its retry attempts. After those three hours each refusal uses one of the event's five attempts, so an event the quota keeps refusing at every hourly reset stops being retried about eight hours after it arrived, and its check stays failing until the next push or check re-run. A read refused while one database is being planned still fails that plan until the next push or check re-run.

GitHub's own primary rate limit is handled the same way, whether or not quota-reserve is set. When GitHub refuses a request because the installation's quota is spent, SchemaBot retries the event at the reset time GitHub reports, plus up to 30 seconds. For three hours after the event arrived that wait does not use up its retry attempts, and after that each refusal uses one of the five. If GitHub refuses the event with a reset that had already passed on the server's clock before the event became due, the server's clock is ahead of GitHub's: SchemaBot logs a warning with the reset time and its own time, and waits as long as the reset is overdue, between 10 seconds and 10 minutes plus up to 30 seconds, before trying again. Keep the server's clock synchronized (for example with NTP) so events retry promptly after a reset. A secondary rate limit, or a refusal that carries no readable reset time, is retried on the usual schedule.

Because each wait lasts until a reset, a PR command such as apply that the limit keeps refusing can run hours after it was typed, and about 13 hours after it in the worst case before its final comment says it failed. It posts nothing while it waits, since GitHub would refuse that comment too. When it does run, it checks the PR, its reviews, its head and the database lock again first.

github:
  quota-reserve: 1500  # default: 0 (disabled)

Under apps:, each App takes its own quota-reserve, since each App has its own installations and quotas. The value must not be negative. SchemaBot tracks the remaining quota from GitHub's response headers per installation and per server process, less the requests that process has sent and not yet had answered, so each replica reaches the reserve on its own reading of the shared quota; size the reserve to cover the Check Run traffic of every replica until the reset. Each refused read increments schemabot.github.primary_rate_limit_rejections_total with origin=reserve, and the first refusal in each reset window logs a warning naming the installation, App, remaining quota, reserve, and reset time.

Pending Drops

For MySQL databases executed by the Spirit engine, DROP TABLE statements can be quarantined instead of executed: the table is renamed into a _pending_drops database on the target server with a timestamp prefix, and the data stays recoverable until a background cleaner permanently drops it after the retention period. See Pending Drops for the full lifecycle and recovery steps.

The quarantine is off by default. With no pending_drops block, DROP TABLE executes as written.

pending_drops:
  enabled: true          # default: false (the quarantine is opt-in)
  cleanup_enabled: true  # default: true when enabled is true
  retention: 168h        # default: 168h (7 days)
  dry_run: false         # default: false — set true to log instead of dropping

Set enabled: true only on a deployment whose cleaner can reach its own targets: the quarantine leaves tables on the target server that only the cleaner removes, so enabling one without the other grows the target's disk with nothing scheduled to reclaim it. Set cleanup_enabled: false to keep quarantining drops while this server process does not run the background cleaner; use that for frequently redeployed executors when a stable operator deployment owns cleanup for the same targets. dry_run: true keeps the quarantine active but makes the cleaner log the tables it would drop without dropping them, which is useful when previewing a retention change.

The cleaner only runs against local-mode MySQL databases (environments with a dsn). For databases routed to a remote deployment over gRPC, the control-plane process has no target DSN and cannot clean that target. Cleanup runs only if the remote deployment is also a SchemaBot server with the target configured as local-mode MySQL and cleanup_enabled: true.

Direct Execution

For MySQL databases executed by the Spirit engine, some ALTER statements are deterministically refused by the engine — for example dropping a primary key or adding a foreign key, which its online copy cannot preserve. The direct_execution policy lets a refused statement instead run verbatim as native MySQL DDL when the target table is small enough. With no policy configured, the default applies: enabled, bounded at 100MiB of data and indexes, which is an estimate (see max_table_bytes below). Set enabled: false to leave refused statements blocked, or max_table_rows for a bound the engine corroborates with an exact count. See Direct Execution for how routing works and what other engines need to adopt it.

Set it at the top level of the server config to state one policy for every MySQL database the server drives:

direct_execution:
  enabled: true           # required to enable; omitted in a stated block means false
  max_table_rows: 100000  # the size bound: set exactly one of max_table_rows
                          # or max_table_bytes (e.g. max_table_bytes: 100MiB)
  lock_acquisition_timeout: 10s  # optional; whole seconds; default 10s

Only omitting the block entirely selects the default policy. A stated block is taken as written: it does not inherit the default's size bound, so one that enables direct execution must name its own.

State the policy, including an opt-out, on the control plane. A control plane forwards the policy it resolves with every plan, and the server that runs the statement uses it in place of its own. A control plane with no direct_execution block forwards the default, so enabled: false set only on a data plane is overridden.

Upgrade order: upgrade every server that executes statements to a build that reads max_table_bytes before upgrading the control plane to a build with this default. An older server rejects the forwarded default as missing its row bound, so every MySQL plan and apply it serves fails until it is upgraded. Stating a max_table_rows policy on the control plane first avoids this.

Between the two upgrades, plans and applies disagree. The older control plane forwards no policy, so an upgraded server plans a refused statement as direct under its own default. The control plane records that plan as judged under no policy, and the apply carries that record, so the server blocks at apply the statement the plan showed as direct. To keep the two in agreement, set enabled: false on the upgraded servers until the control plane is upgraded. Once it is, the control plane's policy is the one forwarded, so the setting no longer has any effect.

This is the form to reach for on a fleet: a per-database block for every database is the same policy written many times, and each copy is one more place for the size bounds to drift. It is also what covers a database with no databases entry at all — one a data-plane server resolves through its target_resolver, addressed by an opaque identifier.

A database environment may override the server-wide policy:

databases:
  payments:
    type: mysql
    environments:
      staging:
        dsn: "file:/run/secrets/payments-staging-dsn"
        direct_execution:
          enabled: true
          max_table_rows: 1000

An override replaces the server-wide policy whole rather than merging into it, so an environment that enables direct execution always states the bound it runs under, and enabled: false is a complete opt out. A resolved target whose own connection metadata carries any direct execution key is treated the same way: it states the whole policy, and the server-wide one does not apply.

State the policy on the server that holds the configuration. The resolved policy is stated on every plan and apply request, so it reaches a database this server routes to a remote deployment over gRPC as well as one it executes in process: the deployment that runs the statement judges it under this server's policy rather than its own, and an apply records the policy it was admitted under so a later drive routes it the same way. A request that states no policy leaves the executing server's own configuration in force.

An opt out travels the same way a grant does. enabled: false is stated on the request rather than left out of it, because leaving it out is how a request says nothing at all — and a request that says nothing hands the decision to whatever the executing server is configured with, which on a data plane serving several control planes may be a grant the opted-out database was never meant to have.

A rollback is planned under the policy its original apply was admitted under, read off that apply rather than resolved again. The two can differ: a rollback runs after the change it reverses, and withdrawing the grant in between would otherwise refuse the statement that undoes a change it allowed.

A direct statement is synchronous and blocks writes to the table while it runs — the size bound is the fail-closed blast-radius cap. An enabled policy sets exactly one of max_table_rows and max_table_bytes, and a refused statement runs directly only when the table is within it. A table above the bound, or whose size cannot be determined, stays blocked. The bound is re-evaluated when the apply executes, so a table that grew past it after planning is blocked, not run.

max_table_rows bounds the row count. The size gate trusts the InnoDB optimizer's estimate (information_schema TABLE_ROWS) only to block, and corroborates a verdict for direct execution with an exact row count whose scan is capped just past the bound — a stale estimate can never approve a large table.

max_table_bytes bounds the table's footprint, data plus indexes (information_schema DATA_LENGTH + INDEX_LENGTH). How long a native rebuild blocks writes tracks how much it copies more closely than how many rows there are, so a table of a few wide rows and one of many narrow rows are judged by what the rebuild actually moves. The byte figure is an InnoDB statistics estimate that, like TABLE_ROWS, can undercount a table that just grew, and there is no cheap exact measure to corroborate it, so the byte bound approves on the estimate alone. Choose max_table_rows when only the corroborated gate is acceptable. The value is a whole number followed by a binary unit, such as 100MiB or 2GiB. Decimal units such as MB are rejected rather than interpreted, because readers disagree on whether they mean 1000² or 1024² bytes.

A policy cannot set both. The two bounds differ in strength, and a second limit on a safety policy reads as a ceiling: requiring both would let the weaker estimate veto the corroborated count, and letting either approve would make a table the gate measured far above the byte limit run directly through the row bound. Choosing one keeps the configured limit the one that decides.

A server running a build that predates max_table_bytes ignores the byte bound when it arrives on a request or an apply record, so it rejects a byte-bound policy as missing its row bound, and its plans and applies for the database fail until it is upgraded. Switch a database to max_table_bytes once every server that executes statements for it runs a build that reads it.

lock_acquisition_timeout bounds how long each attempt of a direct statement waits to acquire its locks. Each engine maps it to its native session lock timeout — on MySQL, lock_wait_timeout and innodb_lock_wait_timeout. Native DDL queues on the table's metadata lock behind any open transaction that has touched the table — and by default MySQL lets it queue essentially forever, with all new table traffic stalling behind it. On MySQL, once the statement has waited 90% of the bound for the lock, it kills the transactions blocking it and tries again, up to 3 attempts, as Spirit does for its own DDL. It never kills while it holds the lock and runs, so traffic to a table being rebuilt is left alone. A session holding an explicit LOCK TABLES, or a transaction too large to roll back safely, is never killed, and a session the user is not allowed to kill survives the kill too. No later attempt can end such a blocker, so the statement stops after the attempt that met it, and the apply fails with a retryable "table is busy" error. The full 3 attempts go only to blockers the kill ends. Every attempt runs the statement from the start, so a rebuild that times out waiting to upgrade its lock at the end is rolled back and runs again. Traffic to the table can stall for up to one bound per attempt, and between attempts the statement waits up to 30 seconds for killed sessions to roll back. A lower bound shortens the stall and gives a blocker less time to finish before it is killed; the value must be a whole number of seconds (at least 1s).

The kill reads performance_schema and information_schema.innodb_trx to find the blocking sessions and ends other users' sessions, so the SchemaBot user needs SELECT on performance_schema.*, PROCESS, and either CONNECTION_ADMIN (or SUPER) or, on RDS, EXECUTE on mysql.rds_kill for a statement to run directly; without any of them the statement is blocked at plan time.

Config validation fails at startup when a per-database direct_execution block — even a disabled one — is set on a non-MySQL database, when a policy is enabled with neither max_table_rows nor max_table_bytes, when a policy sets both, when max_table_rows is negative, when max_table_bytes is malformed (not a positive whole number with a binary unit), or when lock_acquisition_timeout is malformed (not a duration, under a second, or not whole seconds). The size bounds and lock_acquisition_timeout are checked even on a disabled policy. A per-database policy that can never take effect is never silently carried in config.

The server-wide policy is held to the same shape rules but is not rejected alongside other engines: it names no database type, so a server that drives MySQL and PostgreSQL can state one policy, and it reaches only the engines that consume it. It is rejected when it reaches nothing — an enabled policy on a server with no target_resolver and no registered database whose engine can honor it fails startup, the same way a per-database block on the wrong engine does. A server holding a target_resolver is exempt, because the engines behind its targets are not knowable from config.

direct_execution is a policy rather than an engine setting, which is why it sits beside pending_drops at the top level rather than inside an engine block like spirit, planetscale, or postgres. Its fields mean the same thing on any engine — blast-radius bounds in rows and in bytes, and a bound on lock acquisition — and each engine supplies only the three pieces that are genuinely its own: which statements it refuses, how it estimates a table's size, and which native session timeout the lock bound maps to. Today the MySQL engine is the only one that implements those, so the policy reaches only MySQL databases; an engine that adopts direct execution later reads the same policy rather than needing a second copy of it. See Direct Execution → Engine compatibility.

Should an engine ever need a field the others have no meaning for, it nests inside direct_execution under the engine's own name rather than moving the block into that engine's settings:

direct_execution:
  enabled: true
  max_table_rows: 10000       # every engine
  postgres:
    some_engine_specific: v   # that engine only

This keeps the shared bounds stated once, in one place, for every engine — which is the property worth protecting, since the size bounds are the only thing between a refused statement and an unbounded write outage. There is no such field today, and one should only be added where the value genuinely has no cross-engine meaning; a bound that any engine could honor belongs at the top of the block.

Changing the policy does not retroactively change plans already reviewed under the old one. A plan records the policy its execution verdicts were judged against, and the apply created from it runs under that record rather than under a policy resolved again at admission, so narrowing or withdrawing a grant takes effect on the next plan instead of on a change an operator has already reviewed. See Direct Execution → The plan carries the policy its verdicts were judged under.

Storage Dialect

SchemaBot's internal storage database runs on MySQL by default. Set storage.dialect to select the database family; the dialect routes schema bootstrapping, connection handling, and the storage implementation together, so the whole storage stack always agrees on the database family.

storage:
  dialect: "postgres"   # default: "mysql"
  dsn: "env:SCHEMABOT_DSN"

Supported values are mysql (the default when unset) and postgres (matching is case-insensitive). Any other value fails config validation — an unknown dialect never falls back to the MySQL flow.

The DSN format follows the dialect: a Go MySQL driver DSN (user:pass@tcp(host:3306)/schemabot) for mysql, and a PostgreSQL URL or keyword/value string (postgres://user:pass@host:5432/schemabot) for postgres. Both dialects support the same secret reference formats (env:, file:, secretsmanager:). When storage.dsn is unset, the DSN is read from the STORAGE_DSN environment variable, falling back to MYSQL_DSN — a legacy name that is honored regardless of dialect. storage.dsn_from assembles a MySQL-format DSN and is only supported with the mysql storage dialect; combining it with postgres fails config validation. (This restriction is specific to the storage database: dsn_from on a databases environment or a target_resolver target supports both mysql and postgres.) See docs/storage-schema.md for how schema bootstrapping differs between the two dialects.

MySQL storage sessions run in UTC

Storage writes UTC timestamps from Go and compares them against the session's NOW() in lease, lock, and webhook retry predicates, so every session the MySQL storage pool opens runs with time_zone='+00:00' and the Go MySQL driver reads and writes DATETIME values as UTC. The storage server's own default time zone does not affect SchemaBot, and any time_zone the storage DSN carries is replaced. Target-database connections are not pinned: their timestamps are application data. PostgreSQL storage sessions are pinned the same way.

The server's default zone does matter once, on a storage server whose default zone is not UTC (@@GLOBAL.time_zone other than +00:00, or SYSTEM on a host whose clock is not UTC): a pod from a build that does not pin the session stamps lease heartbeats in that zone, while a pod from a build that does judges them against a UTC cutoff. Run side by side, the pinned pod reads a heartbeat written a moment ago as stale by the zone offset and reclaims the apply from its live driver. So when moving between such builds in either direction, upgrade or rollback, stop every old pod before starting a new one rather than rolling them. SchemaBot measures the server's default zone against UTC when it connects to storage and logs a warning naming this rule, with the offset, whenever the two differ; a server already in UTC (the RDS and Aurora default) logs nothing and needs no ordering.

Rows the database stamped before the first pinned pod connected keep the reading the old zone gave them: created_at, updated_at, and completed_at on existing applies and locks, for example, so history read across that point shows a step of the zone offset. Until a row is next stamped, anything that measures its age against the clock, from the lease staleness window to retention cutoffs, sees it as older by the offset west of UTC and younger by the offset east of it. The case that is visible is an apply in flight at the restart, whose last heartbeat carries the old reading: west of UTC the restarted fleet reclaims it as soon as it starts, east of UTC only once the offset has elapsed on top of the staleness window.

PostgreSQL storage needs a session-per-connection endpoint

SchemaBot coordinates its instances on PostgreSQL with session-scoped advisory locks: they serialize the startup schema bootstrap across pods and keep one apply per deployment at runtime. A transaction-mode connection pooler rebinds the server backend for every transaction, which leaves those locks on a session the pod no longer reaches. Two pods are then both told they hold the lock.

Startup proves the connection keeps its session before relying on it, and refuses to bootstrap when it proves otherwise, naming the fix. If you see that refusal, point storage.dsn at the database's direct endpoint. Hosted PostgreSQL platforms publish two connection strings and default to the pooled one, so this is the connection string you get by following their setup docs:

Endpoint Typical port Usable for storage.dsn
Direct / session 5432 Yes
Pooled, session pool mode 6432 Yes: one backend per client connection
Pooled, transaction pool mode 6543, 6432 No: refused at startup

A PostgreSQL target behind a transaction-mode pooler is refused too, when SchemaBot plans or pulls it. Where it runs lists the endpoint to use on each provider.

Resyncing PostgreSQL identity sequences

After an explicit-ID bulk load into PostgreSQL storage, advance the identity sequences before SchemaBot resumes default inserts. Run the command only after the load has fully committed. It advances sequences when needed, never rewinds them, and is idempotent and safe to rerun.

Pass the storage DSN directly:

schemabot storage resync-identity-sequences --dsn "$STORAGE_DSN"

Or resolve it from the server configuration:

schemabot storage resync-identity-sequences --config /etc/schemabot/config.yaml

The command refuses to run when the connection's search_path resolves to no existing schema, when none of SchemaBot's storage tables exist in the target database, and when any storage table that does exist carries no identity column, so a database that merely shares table names with SchemaBot's storage cannot appear to resync successfully. Confirm the target and complete the resync before restarting the server or otherwise allowing default inserts.

Storage Connection Pool

SchemaBot tunes the database/sql pool for its internal storage database with defaults that suit a typical single-pod deployment. Override any of them under storage.pool when a deployment needs different sizing or timeouts. Every field is optional; omit storage.pool entirely to keep the defaults.

storage:
  dsn: "env:SCHEMABOT_DSN"
  pool:
    max_idle_conns: 10        # default: 10
    max_open_conns: 0         # default: 0 (unbounded)
    conn_max_lifetime: "5m"   # default: 5m
    conn_max_idle_time: "3m"  # default: 3m
    connect_timeout: "5s"     # default: unset (driver default)
Field Default Meaning
max_idle_conns 10 Idle connections kept warm in the pool. Sized to cover the per-pod background concurrency (durable webhook drivers, operator drivers, and monitors) so idle connections are not closed and reopened every poll tick.
max_open_conns 0 (unbounded) Maximum total open connections (the max pool size). Set a positive value to cap concurrent connections against the storage database.
conn_max_lifetime 5m Maximum age of a pooled connection before it is retired, keeping connections well under MySQL's wait_timeout.
conn_max_idle_time 3m Maximum time a connection may sit idle before it is retired.
connect_timeout unset Bounds a single connection attempt (TCP dial plus handshake) via the driver's timeout DSN parameter. Does not bound query execution.

Durations are Go duration strings (for example 30s, 5m). When set, each duration must be positive, and max_idle_conns must not exceed a positive max_open_conns; SchemaBot rejects violations at config load rather than silently reverting to a default.

Separate schema user

By default SchemaBot converges its storage schema at startup over the same connection its pool uses, so the storage user needs DDL privileges for the life of the process. Set storage.schema_dsn to converge the schema as a different user, and let storage.dsn name a user that only reads and writes rows:

storage:
  dsn: "env:SCHEMABOT_DSN"               # SELECT, INSERT, UPDATE, DELETE
  schema_dsn: "env:SCHEMABOT_SCHEMA_DSN" # DDL on the storage database

schema_dsn is used only to read and converge the storage schema: at startup, through the storage schema API, and by the schemabot storage commands. The pool never dials it. It accepts the same env: and file: references as dsn, and storage.database applies to it too. Both must name the same server and database: SchemaBot refuses to start, and the storage commands and API refuse to run, when they differ, rather than converge storage the pool does not serve.

schema_dsn is supported for MySQL storage only. On PostgreSQL the same server and database can still resolve to a different schema per user, so SchemaBot rejects the setting at config load.

schema_dsn cannot be combined with storage.dsn_from. dsn_from reads the server and database from a secret, and a hand-written schema_dsn would not follow that secret when it changes. SchemaBot rejects the combination at config load; use storage.dsn with schema_dsn.

Storage Retention

SchemaBot keeps every row it writes unless told otherwise. The storage_retention block turns on a background pass that deletes old rows from SchemaBot's own storage tables. It is off by default, and when enabled it only counts and logs what it would delete until dry_run: false is set, because a deleted row cannot be recovered. The pass covers two tables: the webhook inbox (webhook_events), which it always purges, and the apply logs (apply_logs), which it purges only when you set a window for them. It only deletes rows whose work has finished. It never deletes a delivery that is still pending, being processed, or waiting to retry, however old.

storage_retention:
  enabled: true         # default: false
  dry_run: true         # default: true — count and log instead of deleting
  interval: 1h          # default: 1h — how often the pass runs
  batch_size: 500       # default: 500, at most 5000 — rows deleted per statement
  webhook_events: 168h  # default: 168h (7 days) — how long a finished delivery is kept
  apply_logs: 2160h     # default: unset — apply logs are kept forever; 2160h is 90 days

Every instance runs the pass on its own interval, and an advisory lock lets one instance purge at a time. A pass deletes in batches with a short pause between them, and stops after a fixed number of batches so a large first backlog drains over several passes instead of holding the database in one long run. Each pass logs one line per table naming the table, the rows it deleted (or would delete, in a dry run), the batches it took, the window, and whether it was a dry run. A pass that fails logs at error level and the next interval tries again. The two tables are purged independently, so a failure on one does not stop the other.

Read a dry run's log line before turning deletion on: set enabled: true, let a pass run, and check rows_would_delete for each table, webhook_events and, when you set apply_logs, apply_logs. Each count has one minute to finish; a table whose count runs out of time logs a warning that the pass has no figure for it, rather than a count of zero, and the other table is still counted.

Apply log window

apply_logs has no default. Leave it unset and every apply log is kept, even with the pass enabled. The startup line storage retention pass enabled shows apply_logs_window as unset in that case.

When you set it, the pass deletes the log entries of an apply that settled (completed, failed, cancelled, or reverted) more than the window ago. The age is measured from the apply's completed_at, on the database clock, so every instance cuts at the same moment. The pass keeps the entries of:

  • an apply that is stopped, because it can still be resumed;
  • an apply that is still in flight;
  • an apply that settled within the window;
  • an apply a driver still leases, which happens during a rollout when one deployment's failure settles the apply while another is still being driven.

The apply and its tasks are not touched; only its log entries are deleted. Once the window has passed, schemabot logs and GET /api/logs show nothing for those applies. Pick a window that covers how long your team looks back at an apply, such as 2160h (90 days).

apply_logs has a floor of 24h. For a day after an apply settles, SchemaBot can still re-post its summary comment, with the failure lines from its log, if the first post was lost. A shorter window is refused at startup.

Webhook inbox window

The inbox is also how SchemaBot tells whether it has already planned a pull request's latest commit. For each pull request the pass keeps the newest finished delivery that planned a commit, however old. Retention never makes a commit that was not planned read as planned. At worst the webhook reconciler plans a pull request once more, for example when the pull request goes back to an older commit whose delivery has aged out. The table therefore keeps about one row per pull request, plus every delivery newer than the window.

Finished deliveries include failed ones. A delivery that failed for good is kept for the window like any other, then deleted, and it stops counting in the schemabot.webhook.inbox_depth gauge once it is gone.

webhook_events has a floor, the longer of two times:

  • The 3 days GitHub keeps a delivery redeliverable. The inbox row is what stops a redelivered delivery from running its side effects twice, so a shorter window would let a redelivery run as if it were new.
  • The time the reconciler still looks back over: its lookback plus its grace period plus the cool-off after which a failed delivery stops counting as planned. With the default reconciler lookback of 48 hours that is a little under 49 hours, so the 3-day limit is the floor by default.

SchemaBot refuses to start when webhook_events is below the floor, and the error names the values behind it. The reconciler's lookback is set with the WEBHOOK_RECONCILE_LOOKBACK environment variable, and raising it above about 71 hours raises the floor. Each instance checks the floor against its own environment when it starts, so if you raise WEBHOOK_RECONCILE_LOOKBACK, raise it on every instance and raise webhook_events with it.

interval cannot be shorter than one minute.

Spirit Run Settings

For MySQL databases this server drives directly, the Spirit engine runs every schema change with a set of production-proven defaults. The spirit: block exists only to deviate from them — leave it out entirely to run with the defaults below.

spirit:
  checkpoint_max_age: 72h  # default: 72h (3 days)

The defaults, and why they were chosen:

  • Thread pools are autoscaled on Aurora (not configurable). Spirit sizes the copy, apply, and checksum thread pools from the Aurora instance and scales them dynamically from throttler feedback. A fixed thread count is the classic failure mode on large targets — throughput that made sense on one instance class silently starves or overloads another, and autoscaling is why there is no operator knob for copy aggressiveness. Autoscaling needs Aurora's load signal: on other MySQL targets Spirit leaves it disengaged and runs at fixed default thread counts. An Aurora instance with fewer than 4 vCPUs is too small to scale, so Spirit runs it in small-instance mode instead: every pool runs one worker with small chunks and does not scale, which makes a large copy on such an instance markedly slower.
  • The copy is verified with Spirit's lockless checksum (not configurable). It verifies with optimistic reads, retries, and hot-range splitting instead of a checksum setup lock held over long-lived REPEATABLE READ snapshots, so a long checksum does not pin InnoDB purge on the target. Rows that are updated continuously are settled against the change stream. Cutover still requires a complete clean pass, and cutover locking is unchanged.
  • checkpoint_max_age: 72h — a checkpoint older than this is not resumed; the copy restarts cleanly instead of replaying days of old binlogs, which on a busy target is slower and riskier than starting over.
  • GTID change source is auto-detected (no knob). Targets running with gtid_mode=ON and enforce_gtid_consistency=ON get Spirit's GTID-based change source, which tracks replication position across binlog rotation and failover more robustly than binlog file+position; every other target keeps the universally supported file+position source.

A database can override the server-level value by setting the same key (checkpoint_max_age) in its own metadata; the database's entry wins.

The keys enable_experimental_autoscaling, enable_experimental_lockless_checksum, and checksum_yield_timeout were removed: Spirit now chooses thread autoscaling and the checksum itself. A config that still sets one is rejected rather than ignored, because the operator set it to change how runs behave. In the spirit: block it fails startup; in a database's metadata it fails building that database's engine client. Both errors name the key. Deleting the key is the whole remedy.

These settings only apply where this server constructs the Spirit engine itself — local-mode MySQL databases. Databases routed to a remote deployment over gRPC run with that deployment's engine settings.

MySQL server settings Spirit refuses

Spirit checks the target server before every run, including a resumed one, and refuses to start on a setting it cannot run safely under. One of them, partial_revokes=ON, is a server-wide security setting an operator may have chosen on purpose. With it on, a REVOKE can remove a grant for one schema while SHOW GRANTS still lists the global grant, so a privilege check passes and the schema change fails at cutover. partial_revokes is OFF by default. A target with it ON fails every schema change, and an apply already in flight fails on its next drive. Turning it off is a server-wide security change, so plan it before upgrading rather than after.

Postgres

The postgres: block sets the largest table on which the PostgreSQL engine will execute native-safe DDL whose cost scales with the table's existing data (ALTER TABLE and a blocking CREATE INDEX), the maximum duration of a concurrent index build and of a constraint validation, and the statement budget SchemaBot's own storage connections run under. The size limit is expressed in bytes and defaults to 1 GiB:

postgres:
  native_safe_table_size_limit_bytes: 4294967296
  concurrent_index_max_duration: 24h
  validate_max_duration: 24h
  statement_timeout: 30s

The ceiling is SchemaBot's own conservatism about how much work to attempt under an exclusive lock, not a PostgreSQL limit. A native-safe ALTER that rewrites a table rebuilds its heap, its indexes, and its TOAST data while holding ACCESS EXCLUSIVE, and the size compared against the ceiling is the total relation size summed across the table's partition tree — indexes and TOAST included — so an index-heavy table cannot slip under it. Raising the ceiling converts an up-front refusal into a bounded attempt, not an unbounded lock. An oversized table appears in the Cannot apply section of the plan comment and of schemabot plan, with its size against the ceiling and the option to change; adjust postgres.native_safe_table_size_limit_bytes if operators decide the target is safe for a bounded attempt. Every apply still runs under short lock_timeout and statement_timeout budgets, so above the ceiling it is the statement timeout, not the ceiling, that stops a runaway rewrite. A greenfield CREATE TABLE does not consult the ceiling: the gate bounds rewrites of existing data, and a table that does not exist yet has none. Neither does an ALTER TABLE that pg-sprite proves changes only the catalog, such as adding a nullable column: it reads no rows, so its cost does not grow with the table. The apply proves it again against the live table and applies the ceiling if the change is no longer catalog-only. Catalog-only changes lists which changes qualify.

Every engine gate still runs when an earlier gate has already blocked all of a table's steps. A missing grant is appended to each blocked step whose statement needs that access, and an oversized table to each blocked rewrite step, as independent causes, so every remedy the gates can name is visible in the same plan comment. This holds whether the earlier gate was the planner or the privilege gate itself: on a table the plan creates, blocking the steps that depend on the table can leave nothing executable, and the CREATE TABLE step is then probed at its own tier like any other blocked step. Two blocked steps are not probed: a statement whose shape the engine does not execute has no access to check, and a step that depends on a table the plan itself creates can only be answered "table not found". A probe's answer is appended only when it names something the operator can provision — a grant, a table owner role the target lacks, or a schema that does not exist yet. A refusal about the table itself (it vanished, or is not an ordinary table) names nothing to provision on a plan nothing will run, and a lookup that fails outright is not a fact about the target; in both cases the existing blocked verdict remains blocked and the answer is logged instead.

The server fails startup validation when native_safe_table_size_limit_bytes is zero or negative.

concurrent_index_max_duration is a Go duration string and defaults to 24h. It is the build's server-side statement_timeout, and the engine's own deadline for the recovery of an abandoned leftover that a build runs before building. A concurrent build on a table that runs past it is refused, not retried, since a retry would run past the same bound. SchemaBot tries to drop the invalid index the build left, and the refusal says whether it did; the operator raises the bound and applies again. A partitioned table's build that finished some partitions is the exception: it is retried, and the retry resumes from the partitions already built. The server refuses zero, negative, and invalid durations at config load, durations below one millisecond (the resolution of statement_timeout; a shorter value would round to zero on the server and switch the timer off), and durations above the largest statement_timeout PostgreSQL itself accepts (about 24 days); omit the option to use the default rather than setting 0.

validate_max_duration is a Go duration string and defaults to 24h. It is the server-side statement_timeout of a VALIDATE CONSTRAINT, the scan that checks existing rows against a foreign key or check constraint added NOT VALID. The scan holds SHARE UPDATE EXCLUSIVE, so reads and writes continue while it runs. A scan that reaches the bound is cancelled and the step is refused; the constraint stays NOT VALID and keeps checking new writes. The scan's lock wait keeps the 3-second lock budget, or half the bound when the bound is shorter, so waiting behind other DDL is retried as lock contention rather than refused. It accepts 2ms up to the same maximum as concurrent_index_max_duration.

Concurrent index builds do not consult the size ceiling; their work is bounded by concurrent_index_max_duration instead. Constraint validations do not either; theirs is bounded by validate_max_duration.

The ceiling is process-wide: every PostgreSQL database this server drives shares the same value, and a database cannot override it in its own metadata. The ceiling only applies where this server constructs the PostgreSQL engine itself — local-mode PostgreSQL databases. Databases routed to a remote deployment over gRPC run with that deployment's engine settings.

Storage statement budget

postgres:
  statement_timeout: 30s   # default; "0" removes the limit

Time limit for a single query against SchemaBot's own storage database, on the long-lived pool and on the startup bootstrap alike. It applies in every mode, unlike the ceiling above. Must be at least 15s or the server refuses to start: a query can spend up to 10 seconds waiting for another instance's lock, the limit counts waiting as well as working, and the floor leaves the wait room to end on its own. A negative value or an unparseable duration is refused too. The limit is set when the connection opens, so a transaction pooler in front of storage discards it — point SchemaBot at a session pooler or directly at the database.

Schema changes are unaffected. They run under limits pg-sprite sets on the target database. The bootstrap raises the limit for its own schema DDL, where an index build legitimately outruns a query.

Target TLS Posture

This section is about a target DSN configured directly — dsn in a database entry, or the resolved value of a raw secret — not about a target assembled by dsn_from, whose transport settings are fixed by its own allowlist (see PostgreSQL dsn_from targets). For a direct DSN, MySQL and PostgreSQL differ in what SchemaBot injects for an RDS endpoint and in how an explicit weak setting is surfaced. Both apply only to endpoints in the commercial AWS partition (*.rds.amazonaws.com, any letter case); GovCloud and China endpoints are not recognized as RDS, because the embedded root bundle does not cover them, so their DSNs must spell out TLS explicitly.

A MySQL RDS DSN without a tls= parameter defaults to verified TLS against the embedded RDS root bundle. For compatibility with existing configurations, a tls= value that does not authenticate the server — false, skip-verify, preferred, or a config registered with the Go MySQL driver that skips certificate verification without installing its own — is honored as written; SchemaBot logs a warning naming the host and mode, once per endpoint and mode for the life of the process. The judgement is made on the TLS settings the driver resolves for the final DSN, so a mode weakened by the embedding program's connection options is reported the same way as one carried by the DSN, and a registered config is judged by what it verifies rather than by its name.

A PostgreSQL RDS DSN without an explicit sslmode gets sslmode=require injected, which encrypts the connection but does not by itself authenticate the server. An explicit sslmode, including disable, is honored as written. Either way, a connection to an RDS endpoint that does not authenticate the server logs a warning naming the endpoint, what the transport does prove (encrypted, unverified or none), and whether the posture came from the DSN or from SchemaBot's injected default, once per endpoint and posture for the life of the process. The judgement is made on the TLS settings pgx resolves for the DSN it dials, so sslmode=require with an sslrootcert — which pgx verifies through the named roots — does not warn. To authenticate an RDS server, set sslmode=verify-full explicitly; without an sslrootcert, the embedded RDS root bundle is used. The same DSN is handed to the engine's data-plane pool, which honors the injected sslmode=require rather than applying its own RDS default, so the warning describes both connections. Certificate verification is also required where a trust setting depends on it: a pinned CA bundle under a non-verifying sslmode is refused at CA resolution, as described under PostgreSQL dsn_from targets, rather than silently never consulted.

PlanetScale Service Token

The Vitess engine calls the PlanetScale API with a service token. The permissions it needs, and the ones it does not, are listed in Vitess on PlanetScale.

Branch Reconcile

The branch_reconcile block turns on a background pass that reclaims PlanetScale branches SchemaBot created and no apply will resume or delete. It is off by default, and when enabled it only logs what it would delete until delete: true is set. See Reclaiming orphaned branches for what the pass checks before it deletes a branch.

branch_reconcile:
  enabled: true   # default: false
  delete: false   # default: false — log the orphaned branches instead of deleting them
  grace: 24h      # default: 24h

PlanetScale mTLS

Some PlanetScale-compatible endpoints require mutual TLS: every MySQL connection must present a client certificate in addition to verifying the server. The planetscale: block registers that identity process-wide at startup, and the Vitess engine then applies it to every MySQL connection it opens — branch hosts and vtgates alike:

planetscale:
  mtls:
    ca_bundle: /etc/ssl/certs/ca-certificates.crt  # verifies the endpoint's server cert
    client_cert: /etc/secrets/pca/tls.crt          # client identity presented to the endpoint
    client_key: /etc/secrets/pca/tls.key

All three paths are required together, and the server fails startup when any file is missing or unparseable — a worker never comes up without the identity its endpoints require, where it would otherwise fail (or silently degrade) on every Vitess connection.

This is the knob for the Vitess engine's own connections, and it works the same for statically registered databases and dynamically resolved targets (a data plane using target_resolver, which has no per-database config to attach TLS to). The registration is process-wide with no per-database opt-out: once set, every Vitess database this server serves connects with mTLS. Serve endpoints that require mTLS and plaintext endpoints (such as a LocalScale instance) from separate server processes.

Certificate rotation on the configured paths takes effect without a restart: the client certificate and key are re-read from disk on every new connection's handshake, so replacing the mounted files (as a certificate manager does when renewing) rotates the presented identity on its own. The CA bundle is read once at startup — replacing it requires a restart.

Certificate delivery is deployment infrastructure, not server config: in the Helm chart, mount the certificate secret with extraVolumes / extraVolumeMounts and point these paths at the mount.

Storage Schema Changes

SchemaBot's internal storage schema is self-bootstrapping: on every startup, EnsureSchema converges the live storage database against the schema files embedded in the binary, before the server accepts traffic. Routine convergence is never a hand edit, and there is no schema directory to point the server at — what operators do run by hand is the exceptions: an index too large to build inside the startup budget, and whatever the convergence refuses.

docs/storage-schema.md is the operator guide — how the convergence works on each dialect, what it refuses, the storage plan and storage apply commands, and what to do when a deploy or a pod start does not converge. Every SchemaBot operator should read at least its first three sections. This section covers only the settings.

allow_destructive_schema_changes

On MySQL, destructive statements in the startup diff are refused and skipped by default, because a pod running an older binary does not declare a newer binary's tables, columns, and indexes, and would otherwise remove what the newer pods depend on. That covers statements that lose data — DROP TABLE, or an ALTER TABLE containing DROP COLUMN — and statements that remove a visible index, which destroy no rows and can still take the database down by regressing the plan of a query the rest of the fleet is running. An index already made invisible regresses nothing and is dropped by the next boot without the opt-in; a unique index carries one more caveat, covered in What is never automatic. Each refusal is logged at warn level with the exact DDL and counted in the schemabot.storage_schema.destructive_refusals_total metric. See What is never automatic for what a statement carrying both a removal and an addition does.

To intentionally remove a storage table, column, or visible index, first make sure every running pod is on a binary whose embedded schema no longer declares it, then opt in:

storage:
  dsn: "env:SCHEMABOT_DSN"
  allow_destructive_schema_changes: true  # default: false

Leave the flag false during normal operation and revert it after the removal converges. --allow-unsafe on schemabot storage apply opts in for one invocation instead; it widens this policy and never narrows it.

On PostgreSQL the setting has no effect: that convergence is additive-only and never produces destructive DDL. See What is never automatic.

Support Channel

SchemaBot can add an opt-in support link to GitHub PR comments so authors know where to ask for help when a plan, apply, gate, or command response needs operator attention.

support_channel:
  name: "#schema-help"
  url: "https://chat.example.com/schema-help"

Both name and url are required when support_channel is configured. The URL must be an absolute http or https link with no credentials, whitespace, or Markdown link delimiters. When omitted, SchemaBot comments are unchanged.

Agent Hint

SchemaBot can append an opt-in hint to plan comments pointing AI agents at the preferred way to drive SchemaBot, such as a skill or internal tool to install.

agent_hint: "Agents: fetch the SchemaBot command reference by commenting `schemabot help`."

The hint is appended to plan comments as an HTML comment:

<!-- 💡 Agents: fetch the SchemaBot command reference by commenting `schemabot help`. -->

GitHub never renders HTML comments, so the PR page is unchanged for human readers. Agents read comment bodies as raw markdown through the API and receive the hint verbatim — so the copy can address them directly with imperative instructions.

The hint must be a single bounded line and must not contain an HTML comment terminator (--> or --!>), which would end the comment early and render the rest of the hint on the PR page. When omitted, plan comments are unchanged.

CLI Name

PR comments name CLI commands an operator runs in a terminal, such as the command that prints a stored plan in full when a comment cuts its DDL. When operators run the CLI through a wrapper, set cli_name to the wrapper's invocation so a pasted hint reaches the wrapper instead of an unconfigured binary:

cli_name: "acme schemabot"

This is the server-side counterpart of the CLI's --cli-name flag (see Wrap the CLI for your team); set the same value in both places. Each hint is also scoped to its environment, so a wrapper that routes by environment reaches the server that wrote it:

_DDL truncated to fit GitHub's comment size limit; the full plan is available from the CLI with `acme schemabot list-plans -e staging plan_abc`._

Only terminal commands take the name. Commands a PR author comments on the PR, such as schemabot plan and schemabot apply -e staging, keep schemabot, the word the bot answers to. Terminal commands also never carry --tenant: the tenant routes PR comments, and the CLI reaches a tenant deployment through its endpoint or profile, so a tenant deployment's cli_name names the wrapper that points there. When omitted, hints start with schemabot. The name must be a single line of at most 100 characters with no backtick and no leading or trailing whitespace, because it renders inside inline code.

Repository Allowlist

By default, any repository with the GitHub App installed can use SchemaBot. Adding a repos section creates an allowlist — only listed repositories are permitted.

Repository names in repos: and consumer allowed_repos lists are matched case-insensitively and normalized to lowercase when loaded.

# Local mode — repos as allowlist only
repos:
  myorg/payments-service: {}
  myorg/user-service: {}

databases:
  payments:
    type: mysql
    environments:
      staging:
        dsn: "env:STAGING_DSN"
# gRPC mode — repos as allowlist, database targets as routing
repos:
  myorg/payments-service: {}
  myorg/user-service: {}

databases:
  payments:
    type: mysql
    environments:
      staging:
        target: "payments-staging"
        deployment: tenant1
  users:
    type: mysql
    environments:
      staging:
        target: "users-staging"
        deployment: tenant2

tern_deployments:
  tenant1:
    staging: "tern-staging:9090"
  tenant2:
    staging: "tern2-staging:9090"

When a SchemaBot command or auto-plan event reaches the allowlist check from an unlisted repository:

  • SchemaBot logs a warning and ignores the event without posting a PR comment because the repository is outside this SchemaBot instance's ownership.
  • SchemaBot increments schemabot.webhook.unregistered_repository_ignored_total so operators can detect unexpected webhook delivery or missing configuration.

If repos is not configured or empty, all repositories are allowed.

Pull request database limit

Set pr_schema_cap under a repository to pause planning and new applies when a pull request changes more than five logical databases managed by this control plane. The count covers the full pull request, including when a command names one database or target. Environments, keyspaces, and shards of the same database count once. Each control plane evaluates its own registrations.

repos:
  example-org/service:
    pr_schema_cap:
      control_plane: payments
      limit: 5
      observe: true
      label: "schemabot: allow-large-plan"

Use observe: true to record decisions and projected database planning fan-out before enforcement. Omit it to enforce the limit. Omit limit for the default of five. On shared repositories, give each deployment a distinct control_plane for the comment and Check Run summary. It defaults to the deployment's tenant, or the GitHub Check Run name when the deployment has no tenant.

Provision the configured label in the repository before enabling enforcement. Applying it acknowledges the current head and base. SchemaBot holds new work when the label is removed or the revision changes. On shared repositories, designate one deployment to remove stale labels with manage_label: true and set it to false on the others. By default, standalone deployments and aggregate leaders remove stale labels. If a stale label remains visible, remove it and add it again to acknowledge the new revision.

At or below the limit, admission skips label verification. Above the limit, SchemaBot verifies an exception using at most one page of 100 PR timeline events. If GitHub reports another page, the PR stays held. Split the changes into smaller PRs to proceed.

The exception enables planning and new work on that revision. Existing apply approval policies are evaluated independently.

Listen-only repositories

A listen-only repository is one SchemaBot reads from but never writes to. Use it to measure what a repository would cost in GitHub requests before you onboard it. For example, a separate SchemaBot deployment with its own GitHub App and no required checks can listen to your largest repository, and catch a release whose reads grow with pull request size before any deployment that gates merges runs it.

repos:
  myorg/monorepo:
    listen_only: true

For a listen-only repository, SchemaBot:

  • processes its webhooks and reads GitHub the same way it does for any other repository;
  • sends no comments, reactions, review requests, or Check Runs;
  • ignores comment commands, so no apply ever starts from the repository. Auto-plan still runs for any database this deployment manages in the repository, but its plan comment and checks are not posted;
  • reads a plan's inputs for a database the pull request changes that this deployment does not register: the schema files at the head for each environment in allowed_environments, then one base-branch comparison for all of them. A deployment without allowed_environments reads the environments of its environment_order (staging and production by default). Each environment reads its own directory where the repository keeps one, and the config directory otherwise, as a deployment that registers the database does. Nothing is planned, because there is no target to plan against, but the reads are the ones a deployment that registers the database makes, so the measurement covers plans and not only config discovery;
  • runs the default-branch push and merge queue paths up to the Check Run write, so their coverage and Check Run lookups are measured too.
  • reads the pull request head once after config discovery, as the release of a stored aggregate block does, and releases nothing: a listen-only repository has no aggregate check, so it has no block to release.

One path is not measured: the PR aggregate check sync, which reads the PR head and looks up the aggregate Check Run before it writes. A listen-only repository skips it, as any repository with enable_checks: false does. Its cost is a few reads per delivery, and it does not grow with the number of files in the pull request.

The GitHub client refuses every request to the repository that is not a read. It does this in its HTTP transport, below every client method. A write path added later is covered too, so the pull request shows nothing from this deployment. A GraphQL write that does not name its repository is refused as well, because the client cannot tell which repository it targets. The client installs this guard only when at least one repository is listen-only.

To read the cost, group schemabot.github.requests_total for the repository by operation. The client counts each refused write with status:suppressed, which shows how much the deployment would have written without counting it as traffic or as an error.

listen_only implies enable_checks: false. Config load rejects listen_only combined with enable_checks: true or with an aggregate role, because both of those publish checks.

The App's rate limit is shared by every repository it is installed on. A listen-only repository spends the same budget as the repositories the deployment serves.

PR Checks Gate

By default, SchemaBot blocks apply and apply-confirm when non-SchemaBot PR checks are not passing. This prevents applying schema changes on a PR with broken, cancelled, or incomplete CI, linters, or security scans.

# Block apply when PR checks are not passing (default: true)
require_passing_checks: true

Apply is blocked in two cases: completed checks that did not pass and checks that have not finished. Any status other than completed (such as in_progress, queued, pending, waiting, or requested) counts as not finished, so unrecognized statuses fail closed. A completed check passes only with conclusion success, neutral, or skipped; every other conclusion (such as failure, timed_out, cancelled, action_required, stale, or startup_failure) blocks apply, so unrecognized conclusions fail closed. Each case shows a distinct message — completed checks that are not passing prompt the user to get them passing (fix failures and re-run cancelled or stale checks), while in-progress checks prompt the user to wait. SchemaBot's own checks are always excluded.

For repositories with many optional checks, required_checks can narrow the gate to specific check names:

require_passing_checks: true
required_checks:
  - "Required Review"
  - "CI / required-tests"

When any configured check appears in the PR check statuses, only configured checks are evaluated. A configured check that is absent does not block apply. If none of the configured checks appear, SchemaBot falls back to the default behavior and evaluates all non-SchemaBot checks.

required_checks names must exactly match GitHub check run names or commit status contexts. Matching is case-sensitive, and config validation rejects names with leading or trailing whitespace.

When checks are not passing, SchemaBot posts a comment listing the non-passing checks and instructs the user to get them passing — fixing failures and re-running cancelled or stale checks — before retrying.

If the GitHub API is unreachable when checking statuses, the apply is blocked (fail-closed). SchemaBot posts a comment explaining the error and suggests retrying.

Set require_passing_checks: false to disable this gate.

Skipping Unrequired Branches

By default, SchemaBot plans, applies, and publishes Check Runs for PRs into every branch. Turn on skip_unrequired_branches to serve only PRs whose final target is the repository's default branch or a branch whose rulesets or classic branch protection require a SchemaBot check:

# Skip PRs into branches that do not require SchemaBot (default: false)
skip_unrequired_branches: true

Before turning it on, grant the GitHub App the Administration: read permission and audit which branches require SchemaBot checks. See PR target eligibility for how targets are evaluated and what an excluded PR receives.

Base Branch Schema Freshness

SchemaBot rejects apply and apply-confirm when a PR does not include schema changes that landed on its base branch after the PR diverged. A stale branch's plan would otherwise revert schema that already landed.

This is path-scoped rather than a whole-branch freshness requirement. At apply time, SchemaBot resolves the base branch ref to its current tip commit and compares the Git tree object for the managed schema directory at the PR merge base with the same directory at that tip. If the tree objects match, unrelated commits elsewhere in a busy repository do not block the apply. If they differ, SchemaBot rejects the apply and instructs the user to merge or rebase the current base branch before reviewing a new plan.

The freshness rejection outranks every plan-derived response, including the unsafe-change prompt: a stale branch whose plan would revert newer base schema is told to update the branch, never to re-run with --allow-unsafe.

The gate fails closed when GitHub cannot resolve the base branch tip, the merge base, or either tree.

Review Gate

When review_policy.enabled is true, SchemaBot blocks apply and apply-confirm until the PR has a qualifying approval. This is a server-instance setting: it applies to the environments served by that instance. Other instances can configure their review gate separately.

review_policy:
  enabled: true
  admin_teams:
    - myorg/admins
    - myorg/db-admins
  include_database_operators: true   # default: true
  include_codeowners: false          # default: false
  require_reapproval: false          # default: false

repos:
  myorg/monorepo:
    admin_teams:
      - myorg/monorepo-maintainers
    admin_users:
      - some-maintainer

databases:
  payments:
    type: mysql
    operator_teams:
      - myorg/payments-operators
    environments:
      staging:
        dsn: "env:STAGING_DSN"

An instance with the review gate off can still turn it on for one database. For example, a staging instance whose databases apply without review by default can require one for payments:

databases:
  payments:
    type: mysql
    operator_teams:
      - myorg/payments-operators
    review_policy:
      enabled: true
    environments:
      staging:
        dsn: "env:STAGING_DSN"

The database's own review_policy only adds the gate; it cannot turn off an instance-wide one. Who can approve comes from the instance's settings below, and SchemaBot refuses to start unless every PR the database accepts has someone who can approve it. That takes the database's operators, review_policy.admin_teams or admin_users, or admins on every repo the database accepts: each repo in its allowed_repos, or every repo under repos: when allowed_repos is empty. CODEOWNERS do not count toward this, because they approve only a PR whose files they own.

When enabled, SchemaBot checks PR approval before proceeding. A satisfying review can come from:

  1. review_policy.admin_teams or review_policy.admin_users, which apply to every configured database.
  2. The PR repository's admin_teams or admin_users (under repos:), which apply to every database managed through that repository.
  3. The target database's operator_teams or operator_users when include_database_operators is true.
  4. Matching CODEOWNERS when include_codeowners is true.

Repo admins sit between the global admin policy and per-database operators: they hold authority over every database whose schema changes flow through their repository — useful for monorepo maintainers — without gaining authority over databases managed through other repositories. The same principals may also run mutating PR comment commands when pr_command_authorization is enabled.

Note: a populated repos: map doubles as a repository allowlist — once any repository is listed, only listed repositories may use SchemaBot. If you add a repo entry solely to configure its admins, make sure every other repository this deployment serves is also listed, or they will be rejected as unregistered.

The PR author's own approval never counts, even if they match one of the configured principals. An approval from someone who is not one of these principals does not count either; the Review Required comment names that reviewer and, when the database's operators include a team, offers adding them to it. It never offers an admin or CODEOWNERS team, since joining one grants approval beyond this database. Team membership is checked on every apply, so once they join, running the apply again counts the approval they already gave. When re-approval is required (see below), that approval must still cover the PR's schema change, so a reviewer who approved an earlier commit is also asked to approve the latest one, which always counts once they join. If the GitHub API fails while checking reviews or team membership, SchemaBot blocks the apply and posts an error comment.

CODEOWNERS support is opt-in because CODEOWNERS is repo-controlled while review policy is server-controlled. When include_codeowners is true, SchemaBot looks for CODEOWNERS in the standard GitHub locations on the base branch:

  1. .github/CODEOWNERS
  2. CODEOWNERS
  3. docs/CODEOWNERS

The base branch is used, not the PR's head branch, to prevent a PR from relaxing its own approval requirements by modifying CODEOWNERS.

Only the owners of the database's schema directory count. The rule must match the schema directory path itself, which SchemaBot checks as a file directly inside it (<schema dir>/.schema), and the last matching rule wins. Rules such as /schema/payments/, /schema/, and /schema/payments/* match it. A file-glob rule such as *.sql or /schema/payments/*.sql, a rule on a subdirectory of the schema directory, and a rule on an environment symlink path do not, so they grant no approval even though GitHub would request review from their owners for the files they match. A schema directory that no rule matches, or that a rule leaves explicitly unowned, has no code owners, so CODEOWNERS adds no reviewers for it and only the other configured principals can approve. Owners of other paths in the repository never satisfy the gate. If CODEOWNERS is the only source of reviewers and no rule owns the schema directory, the review gate fails with an error until a rule covers it or another principal is configured; the error in the server log names the base branch and the schema directory.

Approval is checked at the time of schemabot apply and schemabot apply-confirm. Once an apply is executing, there is no ongoing approval check. Team membership and CODEOWNERS are read fresh for each command, and the checks within one command share one read of each membership.

Re-approval

SchemaBot reads the PR's current reviews and uses each reviewer's latest decisive review. By default, an authorized approval counts on whichever commit it was given, until the reviewer requests changes or GitHub dismisses it. To have a later push take approvals away, turn on "Dismiss stale pull request approvals when new commits are pushed" in the base branch's ruleset or branch protection: GitHub then dismisses them, and SchemaBot no longer counts them.

Set require_reapproval: true to have SchemaBot check this itself: an approval on an earlier commit then counts only while the PR's schema change is the one it reviewed.

Set require_reapproval under review_policy for every database on the instance, or under a database's own review_policy to override it for that database, in either direction:

review_policy:
  enabled: true

databases:
  payments:
    type: mysql
    operator_teams:
      - myorg/payments-operators
    review_policy:
      require_reapproval: true
    environments:
      staging:
        dsn: "env:STAGING_DSN"

SchemaBot refuses to start when a database sets require_reapproval but the review gate is off for it.

The rest of this section describes how SchemaBot decides whether an approval still applies when it compares the commits.

When SchemaBot compares the commits, an approval counts only for the schema change it reviewed. Each reviewer's latest decisive review is used, and an approval satisfies the gate when it was given on the PR's current head commit, or on an earlier commit at which the PR's change to the database's schema inputs is the same as at the head. A database's schema inputs are its schema directory, the environment symlink that directory was resolved through (if any), its schemabot.yaml, and the target of every symlink inside them. A symlink to a file that the PR repoints, as when a rebase follows a target directory the default branch renamed, is compared by the file it resolves to at each commit, so it keeps the approval when that file makes the same change. Changes elsewhere in the repository, including another database's schema, do not affect the approval.

The PR's change is measured against the default branch it was built on: SchemaBot finds the merge base of each commit with the base branch's current tip and compares content at all four commits. A schema input counts as unchanged when the PR turns the same base content into the same result at both commits, or when the PR leaves it as the base branch has it at both commits and the head was built on newer default branch content than the approved commit. So rebasing onto, or merging in, a newer default branch keeps the approval even when that default branch added tables beside the PR's, changed the database's schemabot.yaml, or removed a namespace: those changes are not the PR's, and they reached the default branch through their own PR and review. The same holds for a stacked PR: when the PR below it merges, even with revisions, and this PR is rebased onto it, the schema files that came from the lower PR are now the default branch's, and the approval keeps counting as long as this PR's own change is the same. When a rebase combines the PR's edit with a default branch edit to the same schema file, SchemaBot compares the DDL each commit runs: the diff from its merge base to the commit. The approval counts when every statement the head runs is one the approved commit runs, in the same order, and every approved statement the head does not run is one the default branch already made: the default branch ran that statement itself, or changed the same column, index, or constraint first, and the head runs nothing on it. On MySQL, Vitess, and Strata databases, each clause of an ALTER TABLE counts on its own. For example, when the default branch added two columns to a table the PR adds a third column to, both commits run the same ADD COLUMN, so the approval counts. When the head's ADD COLUMN declares another type, or the head reverts a column the default branch changed and the PR did not, the head runs DDL nobody approved and needs a new approval. A column both changed keeps the approval when the head runs the approved statement for it, since that statement is what the reviewer approved. The head may run fewer statements only when the default branch made the rest, as when a stacked PR below this one merges part of the edit. On the same default branch commit, the head must run every approved statement: a head that keeps only the DROP INDEX of an approved index redefinition, or drops the new column of an approved column replacement, needs a new approval. The diff ignores nothing it can act on, including AUTO_INCREMENT, engine, charset, partitioning, and row format. A clause the diff does not act on, such as ENCRYPTION on a table both commits edit, does not count: the planner computes the DDL it applies to an existing table with the same diff, so that clause never runs. The file must hold a single CREATE TABLE at all four commits; a file that does not, or more such files than a comparison reads, counts as changed. A table file the PR adds runs its CREATE TABLE as written, so it keeps the approval when that statement is the same at both commits in the parser's canonical form: reformatting it or editing its comments keeps the approval, and any change to a clause, including ENCRYPTION or a LIKE source, needs a new one. A table file present at one merge base but not the other counts as changed. On a Vitess database, a keyspace's vschema.json is compared the same way, by table, vindex, and keyspace settings: every one the head changes must be one the approved commit changes, to the same definition, and every one the approved commit changes the head must change too, unless the default branch changed it since. For example, when the default branch added a table to the keyspace beside the PR's, the approval counts; when the head routes the PR's table by another column, it needs a new one. A VSchema with a field the vendored Vitess definition does not know counts as changed. PostgreSQL databases follow the same rule. SchemaBot cannot tell which statements a PostgreSQL file generates without running it, so the environment's primary target runs all four versions on a scratch schema in a transaction it always rolls back and diffs the tables it built. A schema file the PR adds is compared by PostgreSQL's parse tree alone, without running it on the target database: it keeps the approval when its statements parse the same at both commits, in the same order. A file that declares row security or a foreign key, that the target cannot run, or that it cannot compare within 30 seconds counts as changed, and so does every such file when the target is unreachable or its data plane predates the comparison. One review gate check spends at most 90 seconds comparing files on the target across all its approvals, compares a file two approvals share once, and counts every file left after that as changed. A check cancelled while the target compares a file fails as an evaluation error that asks for a retry, rather than counting the file as changed. The approval stops counting when the PR edits, adds, or removes a schema input after it, stops changing a schema input the default branch has not changed since, or drops part of an approved edit the default branch has not made, including when a rebase combines the PR's edit with a default branch edit to the same file so that the head runs DDL the approved commit does not. Rebuilding the PR on an older default branch commit than the one it was approved on also stops the approval from counting when any schema input differs between the two, since the head would carry a version of that input nobody approved for this PR. These rules trust default branch content, so they apply only to a PR that targets the repository's default branch; a PR targeting any other branch keeps an approval only for a schema input whose base content and PR change are both the same at the two commits, so on such a PR, a rebase or merge that brings in any change to its schema inputs needs a new approval, and the Review Required comment names the target branch to say so. Keeping an approval across default branch changes relies on the default branch requiring review for every change that reaches it: a change pushed to it directly, without its own review, is carried past an earlier approval like any other default branch change. Protect the default branch with required reviews when the review gate is enabled.

If the PR's change differs, the Review Required comment names the reviewers whose approvals no longer count and the schema file whose change differs, and the reviewer must approve the current head. If the comparison cannot be completed (GitHub cannot find the approved commit, a directory is too large to list, a symlink points outside the repository, or there are more distinct symlinks than a comparison reads) and no other approval covers the head, that approval does not count and the apply is blocked with a Review Gate Error comment. The comment names the approval that did not count, lists who can approve, and asks for an approval of the latest commit, which needs no comparison. The reason goes to the server logs. Asking GitHub again would return the same answer, so the command is not retried. If GitHub is unavailable while the gate compares the commits, the command fails with a retryable error instead of reporting that a review is required. apply-confirm re-checks the gate, so a schema change pushed between apply and apply-confirm also needs a fresh approval.

Command Apps

SchemaBot ignores every PR comment written by a GitHub App, so that its own comments and those of sibling SchemaBot deployments never run as commands. A database can list Apps whose comments it does run in command_apps, such as the App a deploy pipeline's end-to-end test uses to drive plan, apply, and the control commands:

databases:
  orders:
    type: mysql
    command_apps: [deploy-gate]      # App slug, not its "deploy-gate[bot]" login
    environments:
      staging:
        dsn: "env:STAGING_ORDERS_DSN"
  • A listed App runs commands for this database only, and only from repositories the database accepts (allowed_repos).
  • The grant holds whether or not pr_command_authorization is enabled, and so does its limit: with authorization off, an App still cannot run plan or any other gated command for a database that does not list it. With it enabled, an App is never matched against admin or operator teams and users, so listing its login there grants nothing; command_apps is the only way to authorize an App.
  • An App listed by any database never counts as a reviewer, for any database, even when its login is also configured as a reviewer. It is left out of the reviewers a Review Required comment lists, and an approval it gives is called out as one that never counts. Where the review gate is on, an App can apply only a change that a person approved.
  • SchemaBot never runs its own comments: a comment from this deployment's App is ignored even when command_apps lists it, and while the deployment does not yet know its own App slug it ignores every App's comment.

SchemaBot refuses to start when a command_apps entry is not an App slug (letters, digits, hyphens and underscores, as in the App's URL), carries the [bot] suffix, is listed twice, or names an App in trusted-check-app-slugs, since those Apps are SchemaBot's own.

Authentication

This section is the YAML reference. For setup instructions, working examples, and help with denied requests, start with the authentication guide.

By default (auth.type: none or unset) the SchemaBot API is unauthenticated — every request is allowed, which suits local development and deployments where the network is the only boundary. Setting auth.type turns on per-request authentication and a two-tier authorization model:

  • Read tier — visibility: status, progress, logs, locks (list), history, database discovery, and pull (read a live schema).
  • Write tier — anything that stages or makes a change: plan, apply, controls (stop/start/cutover/revert/skip-revert/rollback), unlock, and settings mutation. plan is a write because it stages a change against a database.

Any unclassified /api route is treated as write (fail-closed). For the hosted server, /webhook and health endpoints are exempt — webhooks authenticate themselves via HMAC. The internal local host instead requires its private credential on every route, including probes; see AZ-6. Prometheus metrics are served on a dedicated listener (see Metrics), not on the API port. Two authenticators are available.

OIDC (Bearer tokens)

The server validates a JWT on each request against the issuer's public keys (JWKS) — it never calls the provider at request time, so it works with any OIDC provider.

auth:
  type: oidc
  issuer: "https://issuer.example.com"   # required
  audience: "schemabot"                   # required — the expected aud claim
  groups_claim: "groups"                  # optional (default "groups")

A valid token clears the read tier. The write tier additionally requires the token's groups to include an admin team from pr_command_authorization.admin_teams. Machine callers pass a token via --token / SCHEMABOT_TOKEN; a group-less service token (client-credentials grant) gets read access.

The browser login command caches the ID token as the bearer credential. Login and refresh use that token's exp claim for the cached token_expiry, independently of the access token's expires_in. Commands refresh within 60 seconds of the ID token expiry when a refresh token and its OIDC issuer and client ID are available. For OIDC profiles, commands read exp from the cached token on every load, so profiles saved by older versions automatically use the correct lifetime without another browser login.

The ID token must have a positive numeric exp value in Unix seconds; fractional seconds and exponent notation are supported and truncated to whole seconds for refresh timing. Login and refresh return an error for a missing, malformed, or out-of-range value; neither falls back to the access token's lifetime. An ordinary command that loads a malformed cached ID token attempts to repair the session using the refresh token. If no refresh token is available, or refresh fails, the command warns and preserves the existing cache. The CLI reads exp only to schedule renewal and does not reject login based on its local clock; the server still verifies every bearer token before granting access. Keep the client and server clocks synchronized: a fast client clock can cause a refresh and cache rewrite on every command, and a slow one can delay refresh until the server rejects the credential. When a refreshed token is already expired according to the client clock, the CLI saves the rotated session but warns to check the local clock and the provider's ID token lifetime. Explicit --token and SCHEMABOT_TOKEN credentials are not refreshed automatically.

To enable automatic refresh, configure the profile's public-client settings in ~/.schemabot/config.yaml:

default_profile: default
profiles:
  default:
    endpoint: "https://schemabot.example.com"
    oidc:
      issuer: "https://issuer.example.com"
      client_id: "schemabot-cli"
      redirect_port: 8765

The provider must register http://127.0.0.1:8765/callback as a redirect URI for that client and allow refresh tokens. Login flags override settings for that login attempt; they do not save the oidc: block. Login records the issuer and client ID the tokens came from as token_issuer and token_client_id next to the cached tokens, and refresh uses that pair, because a refresh token is valid only at the issuer and for the client that issued it. A login with --issuer and --client-id therefore keeps refreshing against that provider without an oidc: block, and the next login replaces the pair along with the tokens. Editing oidc: does not change where an existing session refreshes; run schemabot login after switching providers. schemabot configure show prints the recorded pair under each profile that has one. A profile that does not record the pair refreshes with its oidc: settings.

Forward-auth (authenticating proxy)

Use this when SchemaBot runs behind an authenticating reverse proxy that has already verified the caller and forwards the identity as HTTP headers — the pattern used by the Kubernetes API server's authenticating proxy, Grafana's auth proxy, and oauth2-proxy.

auth:
  type: forward_auth
  forward_auth:
    user_header: X-Forwarded-User        # optional (default)
    groups_header: X-Forwarded-Groups     # optional (default)
    groups_delimiter: ","                 # optional (default)
    # Trust anchor — configure at least one (neither is individually required):
    trusted_proxy_spiffe:                 # proxy SPIFFE IDs, read from the Envoy XFCC header
      - spiffe://example.org/ns/ingress/sa/proxy
    trusted_proxy_cidrs:                  # and/or source networks allowed to be the proxy
      - 127.0.0.1/32                      # port-forward break-glass
      - 127.0.0.6/32                      # the mesh source below
    read_groups: [readers]                # groups granted read (empty = any authenticated caller)
    write_groups: [operators]             # groups granted write (empty = no writes)
    # Optional service-caller lane — read-only access for services calling as
    # themselves through a caller-forwarding gateway:
    trusted_gateway_spiffe:               # gateways allowed to forward a verified caller SPIFFE ID
      - spiffe://example.org/ns/service-ingress/sa/gateway
    read_service_spiffe:                  # caller SPIFFE IDs granted read-tier access
      - spiffe://example.org/ns/reporting/sa/reporting
    caller_spiffe_header: X-Forwarded-Caller-Spiffe-Id   # optional (default)
    # Optional: loopback addresses a mesh sidecar delivers proxied requests
    # from. Requires trusted_proxy_spiffe; refuses 127.0.0.1 and ::1. With
    # trusted_proxy_cidrs set, each entry must be inside one of its networks.
    trusted_mesh_loopback_sources: [127.0.0.6]

The authorizer proves the request came from the trusted proxy, then reads the forwarded identity:

  • Trust anchor (required, fail-closed). With neither trusted_proxy_cidrs nor trusted_proxy_spiffe set, the server refuses to start. There are three modes: CIDR only (trust any request whose source IP is in a trusted network), SPIFFE only (trust any request whose XFCC carries a trusted SPIFFE ID), or both (require the source CIDR and a matching XFCC SPIFFE ID — defense in depth). X-Forwarded-Client-Cert (XFCC) is a spoofable HTTP header, so SPIFFE-only is safe only when the proxy sanitizes inbound XFCC and the server is not directly reachable (a service mesh) — the server logs a startup warning in that mode.
  • Loopback sources. On the identity-header lane, a request from a loopback address is the break-glass lane by default. A kubectl port-forward arrives that way, so its identity headers are typed by the person running it. Such a request is admitted, but its identity is not verified: features that record who acted, such as freeze attribution and override approval, treat it as unverified, and writes log a warning with reason loopback_source. trusted_mesh_loopback_sources names the loopback addresses a mesh sidecar delivers proxied requests from, such as Istio's 127.0.0.6 when the sidecar delivers to the pod IP. A request from one of them that passed the SPIFFE check is verified like any other proxied request, while a port-forward from 127.0.0.1 stays break-glass. Listing an address trusts every process in the pod's network namespace like the proxy: any of them can connect from 127.0.0.6 and send an XFCC header that names the proxy, just as it already can from the pod IP under SPIFFE-only trust. List one only when nothing else in the pod sends requests to SchemaBot. Each entry must be one loopback IP. 127.0.0.1 and ::1 are refused, including in IPv4-mapped form, and the setting requires trusted_proxy_spiffe: the source address does not identify the sender, so the SPIFFE check is the only check of who sent the request. With trusted_proxy_cidrs also set, the CIDR check runs first, so each listed address must be inside one of those networks (127.0.0.6/32), or the server refuses to start. Istio's IPv6 source, ::6, is not a loopback address, so it never needs listing. The service-caller gateway lane verifies its caller whatever the source address; there, the setting changes only whether a request from a listed address is counted with reason loopback_source.
  • Tiers. Reads are open to any authenticated caller unless read_groups is set; writes require membership in write_groups, or in a database's operator_groups (see Per-database write scoping). Only the canonical header is read, so a smuggled underscore variant (X_Forwarded_User) is ignored.
  • Service callers (read-only). trusted_gateway_spiffe + read_service_spiffe open a second lane for services calling as themselves: a caller-forwarding gateway terminates the caller's mTLS, verifies the client certificate, and forwards the caller's SPIFFE ID in caller_spiffe_header. The header is honored only when the XFCC-verified peer is a listed gateway, the forwarded caller must appear in read_service_spiffe, and service callers never get the write tier (denied with reason service_caller_write). The user and groups headers are never read on this lane, and the identity-header proxy always wins — the gateway lane is consulted only when the request did not arrive through the trusted proxy. trusted_proxy_cidrs, when set, gate this lane like everything else: a gateway SVID claimed from outside the trusted networks is never honored. List a gateway only if it strips inbound copies of the caller header before setting it from the verified certificate — otherwise any caller could forge an identity through it. The lane fails closed: gateways without callers (or callers without a gateway) refuse to start, the lane requires SPIFFE-anchored proxy trust (trusted_proxy_spiffe) — under CIDR-only trust an in-CIDR gateway request would be mistaken for the identity-header proxy, leaving the lane unreachable, so that combination refuses to start too — and an empty config disables the lane entirely.

Per-database write scoping (forward-auth)

write_groups grants every database in the deployment. To let a database's owning team run mutating CLI/API operations against their database only, set operator_groups on the database and operator_environments — the instance-wide list of environments where scoped writes are allowed at all — in the forward-auth settings:

auth:
  type: forward_auth
  forward_auth:
    operator_environments: [staging]      # scoped writes allowed here, instance-wide
databases:
  payments:
    type: mysql
    operator_groups: [payments-team]      # forwarded groups granted scoped write
    environments:
      staging:
        dsn: "env:STAGING_PAYMENTS_DSN"
      production:
        dsn: "env:PROD_PAYMENTS_DSN"

Which environments accept scoped writes is a deployment policy, uniform across databases, so it is stated once rather than repeated on every entry. On a server that hosts several environments, that one line is the guard keeping scoped writes out of the environments not named in it.

operator_groups is the direct API/CLI counterpart of the database's operator_teams/operator_users (PR comment commands). The suffix carries the identity domain, consistently across this file — *_teams/*_users are GitHub identities, *_groups are forwarded identity groups:

Field Identity domain Grants Verified by
operator_teams, operator_users GitHub teams and users Mutating PR comment commands for this database; also satisfies its review-gate required-reviewer policy GitHub team membership, checked at command time
operator_groups Forwarded identity groups (auth.forward_auth) Mutating direct API/CLI operations for this database, in operator_environments Groups header from the trusted forward-auth proxy

The two value namespaces do not overlap and are verified by different systems, so they are deliberately separate fields: a GitHub team slug has no meaning in the groups header, and a forwarded group name is not a GitHub team. Grant each lane explicitly.

The decision has two halves. The middleware admits any caller in write_groups or in any database's operator_groups to write-tier endpoints — it runs before the request body is parsed, so it cannot know the target. Each mutating handler then enforces the scope once the target database resolves: plan and apply from the request/stored plan, control operations (stop, start, cutover, cancel, release, revert, skip-revert, rollback plan) from the stored apply, and lock acquire/release from the named database (locks are operator controls in the same family as stop/cancel and have no environment dimension, so the grant applies database-wide). Operations with no single target database — settings mutation, checks scan/synthesize/repos — stay admin-only (write_groups). Operator members also get the read tier, deployment-wide.

Two consequences of the environment-less lock grant are worth stating outright. First, a scoped operator's lock holds applies off every environment of their database, including environments outside operator_environments — an operator scoped to staging can still freeze production applies of their own database. That direction is fail-safe (a lock only ever prevents changes), so the grant deliberately allows it. Second, the reverse direction is not: force release (force: true) bypasses the lock ownership check, so it could undo another holder's safety brake — for example an admin's incident lock. Force release therefore stays admin-only (write_groups). A force release that also sends id, the lock ID that POST /api/locks/acquire or GET /api/locks reported, removes only that lock, whoever owns it. If a different lock is held when the request arrives, the answer is a 409 that names the lock held now, nothing is released, and the lock stays held; if no lock is held, the answer is a 404. Without id, a force release removes whichever lock is held.

A scoped operator's normal release is held to who took the lock, not to the owner string it carries: that string is visible to anyone who can list locks, so sending it proves nothing. A lock acquired through POST /api/locks/acquire records its verified acquirer and which of the database's operator_groups that acquirer belonged to, and a scoped operator may release it only when they share at least one of those groups — a teammate can release a lock another member of their group took, and nobody outside the group can. A lock that records no acquirer (a PR apply's lock, a lock taken on a deployment with no operator_groups, a lock taken by a server version that did not record acquirers, or one taken through the loopback break-glass lane, whose identity headers are not proxy-verified) or whose acquirer held none of the database's operator groups belongs to no group, so a scoped operator cannot release it; a write_groups member can, by owner or with force. A scoped operator cannot create such a lock: an acquire from a scoped operator whose identity is not verified, as on the loopback break-glass lane, is refused with a 403 before anything is taken, since the lock would record no acquirer and they could never release or re-acquire it. The refusal is decided before the lock is read, so it also answers an unverified operator re-sending the owner of a lock their own group already holds: the lock stays held and unchanged, but the request is not told it holds it, because the groups of an unverified caller are only claimed. schemabot apply (unless --no-lock is set) and schemabot rollback take this lock before they start, so on the loopback break-glass lane they stop at the same refusal before changing anything; a deployment write group member can run them instead. A refused release is a 403 naming the groups that may release the lock, and the lock stays held. The release is decided against the lock row it read and deletes only that row, so a lock released and acquired again while the release runs is reported as a 409 and the new lock stays held. The same rule decides whether a scoped operator who acquires a lock already held under the owner they sent is told they hold it: re-acquiring a lock their own group took succeeds without changing it when their identity is verified, and sending the owner of another group's lock, or of a lock that belongs to no group, is a 403 naming the groups that may release it, with the lock unchanged. write_groups members, and every caller on a deployment without operator_groups, re-acquire and release by owner alone. A lock records its acquirer's groups when it is taken, while the caller's groups are read from the current configuration, so editing operator_groups strands locks: after a group is renamed, no scoped operator can release or re-acquire a lock taken under its old name, and an operator moved out of every group a lock recorded can no longer release or re-acquire the lock they took, until a write_groups member (or, for a moved operator, a remaining member of one of those groups) releases it.

The grant fails closed everywhere: an unconfigured database or an environment outside operator_environments denies scoped callers with a 403 naming the groups that would grant access, and a target that cannot be resolved at decision time — a stored plan or apply lookup failure — surfaces as the operation's own 500, never as an authorization. Misconfiguration is a startup error, not a silent no-op: any operator_groups grant requires a non-empty operator_environments (and the reverse), requires auth.type: forward_auth, and every granted database must have at least one of its environments in operator_environments — a grant that could never authorize anything is rejected at startup.

Group names in operator_groups match the same way as read_groups/write_groups: an exact string, or by final path segment when either side is a bare slug (bridging a proxy that forwards payments-team to a configured org/payments-team). Because operator_groups decides a per-database boundary, org-qualify its entries on deployments whose proxy forwards groups from more than one organization — a bare admins would match org-a/admins and org-b/admins alike.

These are server-instance values owned by the platform operator. Keep them in the server's own configuration — never in repo-editable config, where a database team could grant themselves direct write with a self-merged PR.

Scoped operators bypass PR source policy (allowed_repos/allowed_dirs are not evaluated for direct API plans), so a scoped grant trades the GitOps audit trail for direct access. Grant it for staging-style environments; before granting a production environment, add a trusted-source or stored-plan gate.

Multi-Environment Deployment

For organizations that need isolated infrastructure per environment (e.g., separate staging and production deployments with their own GitHub Apps and databases), SchemaBot supports scoping each instance to a subset of environments using allowed_environments.

Staging Instance

storage:
  dsn: "env:STAGING_SCHEMABOT_DSN"

allowed_environments:
  - staging
respond_to_unscoped: false  # production instance handles help and invalid commands

databases:
  payments:
    type: mysql
    environments:
      staging:
        dsn: "env:STAGING_PAYMENTS_DSN"

github:
  app-id: "env:STAGING_GITHUB_APP_ID"
  private-key: "file:/run/secrets/staging-github-key.pem"
  webhook-secret: "env:STAGING_WEBHOOK_SECRET"
  check-name: "SchemaBot X"
  trusted-check-app-slugs:  # the chain's App slugs — identical in every instance
    - schemabot-staging
    - schemabot-production

Production Instance

storage:
  dsn: "env:PROD_SCHEMABOT_DSN"

allowed_environments:
  - production

databases:
  payments:
    type: mysql
    environments:
      production:
        dsn: "env:PROD_PAYMENTS_DSN"

github:
  app-id: "env:PROD_GITHUB_APP_ID"
  private-key: "file:/run/secrets/prod-github-key.pem"
  webhook-secret: "env:PROD_WEBHOOK_SECRET"
  check-name: "SchemaBot X"
  trusted-check-app-slugs:  # the chain's App slugs — identical in every instance
    - schemabot-staging
    - schemabot-production

trusted-check-app-slugs declares the promotion chain's GitHub App identities. Like environment_order, it is chain-level shared configuration: every instance carries the same complete list (its own slug included, which is harmless). It serves two purposes:

  • Promotion gate: the production instance verifies the staging aggregate check run, which the staging App created. Without the staging slug, the production instance only trusts its own App's check runs and the staging gate fails closed — production applies stay blocked even when staging is green.
  • Passing-checks gate: checks created by trusted chain Apps are classified as SchemaBot checks and excluded from the require_passing_checks gate. Without the production slug, the staging instance treats the production App's SchemaBot X (production) aggregate — expected to be action_required until production applies — as failing external CI and blocks staging applies.

Trust is decided only by the creating GitHub App, never by check name: a same-named check from an app outside the list cannot satisfy the promotion gate and cannot be hidden from the passing-checks gate. When the passing-checks gate sees an aggregate-named check from an untrusted app, it blocks as usual and emits a warning log and metric so operators can distinguish a check-name spoof from a chain member missing from the list.

Shared prior environment: promotion-check-name

By default, the promotion gate looks for the prior environment's aggregate check run under this instance's own check-name base — for example, a production instance with check-name: "SchemaBot X" looks for SchemaBot X (staging). That works when each promotion chain is a matched pair of instances publishing under the same base name.

Some fleets instead share one staging instance across several production instances, each with its own distinct check-name. The shared staging instance publishes its aggregate under its base name, so a production instance's default lookup targets a check run that is never created and every apply fails closed. Set promotion-check-name to the shared prior deployment's check-name base to point the gate at the check run that actually exists:

github:
  check-name: "SchemaBot Y"            # this instance's own aggregate base
  promotion-check-name: "SchemaBot X"  # the shared staging instance's base
  trusted-check-app-slugs:
    - schemabot-x-staging              # the shared staging instance's App slug

The prior environment is still appended in parentheses: with the config above, a production apply requires SchemaBot X (staging) to be successful. The shared prior deployment's App slug must be listed in trusted-check-app-slugs — the overridden name is published by a different App, and the gate only accepts check runs from trusted Apps. Config load rejects an override that differs from the instance's own base while trusted-check-app-slugs is empty, since no check run could ever satisfy that gate. promotion-check-name only redirects the promotion gate's prior-env lookup; the instance's own aggregate check runs keep using check-name.

Command routing across instances. Every instance receives every PR comment through its own App's webhook. A command whose -e value is in the instance's allowed_environments is handled; one owned by a peer instance is silently left for that peer to answer. An -e value that names no configured environment — whether malformed (typically a flag glued on by a missing space, like -e production--allow-unsafe) or simply absent from allowed_environments, environment_order, and every database's routing environments — belongs to no instance, so it is rejected with an invalid-environment comment listing the configured environments. The rejection follows the respond_to_unscoped policy (on a repository with an aggregate role, the leader serving the first environment answers instead) so exactly one instance responds, and is acknowledged with an eyes reaction. Because environment_order doubles as the fleet-wide environment roster for this routing decision, keep it complete on every instance.

Environment-local gRPC targets

For remote Tern deployments, keep the target registry environment-local too. The staging instance only needs staging target identifiers:

storage:
  dsn: "env:STAGING_SCHEMABOT_DSN"

allowed_environments:
  - staging

databases:
  payments:
    type: mysql
    environments:
      staging:
        target: "payments-staging"
        deployment: primary

tern_deployments:
  primary:
    staging: "tern-staging:9090"

The production instance only needs production target identifiers:

storage:
  dsn: "env:PROD_SCHEMABOT_DSN"

allowed_environments:
  - production

databases:
  payments:
    type: mysql
    environments:
      production:
        target: "payments-production"
        deployment: primary

tern_deployments:
  primary:
    production: "tern-production:9090"

Do not require the staging ConfigMap to contain production targets, or the production ConfigMap to contain staging targets. Each instance resolves only the environments it owns.

Freeze groups (forward-auth)

An environment freeze marks an environment, or some of its deployments and databases, as frozen until it ends or someone lifts it. While a freeze is in effect, SchemaBot refuses every new apply, start and cutover it covers, unless a second person approved an override for that change. Each freeze records a running policy: continue, the default, lets applies that started before the freeze finish, and stop stops every pending, running or paused apply it covers when the freeze is set, and withdraws a start queued on a stopped one, recording the freeze as the stop's requester. While a stop freeze is in effect, SchemaBot stops an apply instead of starting work on it that has not started, and holds a PlanetScale deploy queued before the freeze until the freeze ends. Status and the pull request comment name the freeze that stopped an apply. A planned stop freeze stops an apply already running when it starts only at the apply's next checkpoint: when a rollout starts its next deployment, or when SchemaBot recovers a drive that crashed or failed. An apply that reaches neither keeps running. Whether a freeze is in effect is decided by the database clock, so every pod agrees. A freeze is stored by the instance that serves its environment. write_groups members may set and lift freezes. To let others, such as incident commanders, do so without any other write, list their forwarded groups in freeze.groups:

auth:
  type: forward_auth
freeze:
  groups: [incident-commanders]

The middleware admits freeze.groups members to write-tier endpoints, and the freeze handlers (POST /api/freezes, POST /api/freezes/{id}/lift) allow them. Approving an override (POST /api/freezes/overrides/{id}/approve) is for freeze.groups members only, not write_groups: the caller must be verified and must not be the requester. Every other mutating handler still requires write_groups or a database's operator_groups, and database operator grants do not cover freezes, which reach past any one database. Members also get the read tier, deployment-wide. freeze.groups requires auth.type: forward_auth, and its entries must be unique; either mistake is a startup error. Under other auth types, freezes follow the plain admin write gate.

The CLI sets, lists, shows and lifts freezes and approves override requests, and asks for an override with --override on apply, start and cutover: see Freeze an environment, and the freeze guide for the whole workflow. A PR author can ask for an override of a freeze from the pull request: schemabot apply -e production --override "reason", and the same flag on schemabot apply-confirm, schemabot start and schemabot cutover. When a freeze refuses the command, the default policy lets it through on that reason. Under approval, SchemaBot records an override request for the commenter and the PR author, and the comment names the request and how it is approved. The request is recorded as github:<login>, and an approval has to come from the same identity domain: the API route (POST /api/freezes/overrides/{id}/approve) refuses a request asked for on a pull request, and refuses an approver whose forwarded subject starts with github:. The identity rule holds both ways: a request asked for through the API or CLI is approved only there, and a request asked for on a pull request only on that pull request.

freeze.override_policy decides what an override reason does. reason, the default, admits the change on the requester's own reason, with no approver: SchemaBot stores the override already approved by its requester, keeps the reason for audit, and the refusal comment on a pull request says to go ahead with a reason. approval records a request that a freeze approver must approve, as described below. Under either policy the reason is required and the caller must be verified. Under reason the reason admits only the command that gave it, so a retry gives its own. Under approval an approval covers one change for one person for at most 24 hours. Any other value is a startup error. See choose the override policy.

freeze:
  override_policy: approval

Under approval, a freeze approver approves from the pull request by commenting schemabot freeze approve ovr-... on the pull request where the request was made. Who may is set by freeze.github_teams, a list of GitHub teams as org/team-slug:

freeze:
  github_teams: [acme/incident-commanders]

Members of these teams approve as github:<login>; apps never do. The list governs only this approval, so unlike freeze.groups it needs no forward_auth, and its entries must be well formed and unique or startup fails. With no team listed nobody can approve from a pull request, and the reply says so. SchemaBot reads membership through the repository's installation, which needs the GitHub App's Members: Read permission (see GitHub App setup) and must be able to see each listed team; check that before listing a team. A team it cannot read refuses the approval, never allows it. The comment must be on the pull request the request names: a request from another pull request, or from the API or CLI, is refused with a reply that says where to approve it. Storage refuses the requester and the pull request's author, a request already approved, and one that expired, each with its own reply. The reply names the approver and the change, and says the requester can run the command again. On a repository several deployments serve, a deployment that does not store the request stays silent, so an approval with a wrong or unscoped ID can get no reply; run schemabot freeze approve <ovr-id> -t <tenant> for the deployment that recorded the request, which always answers. The refusal that names the request already includes the --tenant.

Tenant-scoped command routing

When multiple isolated SchemaBot deployments are installed on the same repository and handle the same environment names, use the server-side tenant setting to give each deployment a stable command-routing identity:

tenant: alpha
allowed_environments:
  - production

A PR comment can then target exactly one deployment:

schemabot plan -e production --tenant alpha
schemabot apply -e production --tenant alpha
schemabot help -t alpha

Only the deployment whose configured tenant exactly matches the --tenant or -t flag reacts to the comment or posts a response. Other deployments accept the webhook delivery and skip it without adding reactions or comments, the same way an environment-scoped deployment skips commands for environments outside allowed_environments.

When tenant is set, work commands must include a matching --tenant or -t target. Untargeted commands such as schemabot plan -e production and schemabot apply -e production are accepted without a PR response by the tenant-scoped deployment. This keeps multiple isolated deployments from acting on the same PR command. Deployments without tenant configured keep the existing behavior and do not require the flag.

This routing identity is deliberately local to the server process. It is not stored on plans or applies and it does not change database target resolution. The isolated deployment's own storage, chart values, GitHub App configuration, and database routing remain the source of truth for the work it owns.

Use respond_to_unscoped separately for commands that do not carry --tenant. For example, if several deployments are installed on the same repository, pick one deployment to answer untargeted schemabot help and invalid commands by leaving respond_to_unscoped enabled there and setting it to false on the others. Operators can still direct help to a specific deployment with schemabot help --tenant <name> or schemabot help -t <name>.

On a repository with an aggregate role, the roles pick the deployment that answers help, unrecognized commands, and a malformed, missing, or unknown -e. Participants always leave these replies to the leader. The leader serving the first environment in environment_order (staging when environment_order is unset, since the default order is staging, production) always answers, whatever respond_to_unscoped says. A leader that does not serve that environment cannot tell whether another leader does, so it follows respond_to_unscoped. A sole leader answers with the default setting. Where several leaders split the repository's environments, set respond_to_unscoped: false on every leader except the one serving the first environment, so the command gets one reply.

How it works

  • Environment scoping: When allowed_environments is set, the instance only processes commands targeting those environments. Commands for other environments (e.g., schemabot apply -e production sent to the staging instance) are accepted without a PR response by this deployment. A deployment that allows the requested environment must process its own webhook delivery.

  • Tenant scoping: When tenant is set, work commands must include a matching --tenant or -t target. Tenant scoping is a webhook ownership filter, not a schema change state field; untargeted help and invalid-command responses continue through the unscoped-command routing.

  • Per-environment aggregate checks: Each instance creates its own aggregate check run scoped to its environments (e.g., SchemaBot (staging), SchemaBot (production)) instead of the default SchemaBot aggregate. Configure branch protection to require both aggregates. Set github.check-name when independent SchemaBot gates need distinct visible names; every instance in the same promotion chain should use the same base name.

  • Cross-instance environment verification: Environment ordering (e.g., staging must succeed before production) works across instances. The production instance queries the GitHub Checks API for the staging instance's aggregate check to verify the prior environment completed successfully. GitHub check runs are the shared authority for cross-environment state; the production instance does not need staging target configuration to enforce the staging gate.

  • Trusted check App slugs: SchemaBot gates trust check runs only by the creating GitHub App, never by check name. Every instance in a promotion chain carries the same github.trusted-check-app-slugs list — all of the chain's App slugs, like environment_order is shared chain configuration. The promotion gate accepts a prior environment's aggregate check only from a trusted App (fails closed otherwise), and the require_passing_checks gate excludes trusted Apps' aggregates from CI-health blocking (a sibling's action_required aggregate is expected workflow state, not failing CI). An aggregate-named check from an app outside the list cannot satisfy the promotion gate, cannot be hidden from the CI gate, and is flagged with a warning log and metric for operator triage.

  • Separate GitHub Apps: Each instance needs its own GitHub App installation. Both Apps must be installed on the same repositories and configured to receive the same webhook events. GitHub delivers webhooks to all installed Apps independently.

  • Unscoped command routing: With two Apps on the same repo, commands not scoped to an environment or tenant (help, invalid commands) would get duplicate responses. Set respond_to_unscoped: false on one instance so only the designated instance responds to these. Work commands (plan -e, apply -e) must include --tenant or -t when the deployment has tenant configured.

  • Backwards compatible: When allowed_environments is not set or empty, the instance handles all environments and creates a single SchemaBot aggregate check — the same behavior as a single-instance deployment.

Auto-plan behavior

When a PR is opened or updated, each instance auto-plans only the environments it owns. The staging instance plans staging, the production instance plans production. Each posts its own plan comment and creates its own per-environment aggregate check.

Check names follow repository environment coverage, resolved from server registrations with allowed_repos or verified repository discovery. An application without sandbox receives no sandbox run, including on documentation PRs. A repository registered in sandbox keeps its no-work sandbox result even when a particular PR changes only another database. Missing applicable outcomes remain pending before the planner stores its first row. Unknown ownership, discovery errors, stale results, and retained applies never establish no work.

Later checks also fold successful current-head outcomes of registered local predecessors from each database's environment_order. This covers clean later plans that never run an apply. It does not combine execution: every environment still needs its own command, plan, apply, and authorization.

Leaders may declare the checks each participant publishes:

repos:
  octocat/shared-repo:
    aggregate:
      role: leader
      expected_tenants:
        - tenant: tenant-a
          paths: [services/a]
          check_name: SchemaBot A
          environments: [production]
        - tenant: tenant-b
          paths: [services/b]
          check_name: SchemaBot B
          environments: [sandbox, production]

A leader selects contributions by touched paths and environment coverage. Declared coverage also contributes to the repository's published names. Omitted environments conservatively expects every served environment during migration. Explicit empty lists, duplicates, and invalid identifiers fail config validation. Populate coverage before enabling a new environment on the leader. Keep participants' allowed_dirs aligned with the leader's path prefixes: selected participants publish verified no-work results even for documentation changes in those paths, while unrelated PRs and merge-group commits remain silent on participants. Legacy unscoped aggregates retain their existing participant expectations.

Plan comment retirement

On a frequently updated PR, plan comments pile up — every push that touches a schema file posts a new one. To keep the PR readable, SchemaBot retires the plan comments a newer one supersedes. This applies to auto-plan and schemabot plan comments alike, and the retired comment's storage record always survives with its identifiers, so the plan history remains auditable.

A newer plan comment for the same database supersedes a prior one when the prior was rendered at an older commit, or when it re-renders the same commit for the same set of environments. A same-commit comment covering different environments is kept expanded — it may be the only visible plan for those environments.

Once a PR shows a plan comment, it keeps showing a current one. When an auto-plan resolves to no changes and a plan comment from a prior commit is still visible, the auto-plan posts its no-changes plan comment, which supersedes the prior one like any other plan comment. A PR that has never shown a plan comment gets no comment for a no-changes auto-plan; the check run alone reports the green state. A push that changes no schema input files leaves the newest visible plan comment for the same environments in place while it still matches the plan: a comment that shows changes stays while there are still changes, and one that shows none stays while there are still none. When the live database moved without the schema files changing and the plan flipped between those two outcomes, for example after the PR's change was applied outside the PR, the auto-plan posts a new plan comment that supersedes the outdated one. The comparison is changes against no changes, not the DDL itself: a comment whose DDL was partly applied elsewhere stays until the next plan comment replaces it. A plan for a commit the PR has already moved past never posts a replacement; the current commit's own plan answers instead.

By default, a superseded plan comment no apply ever acted on is deleted from the PR timeline outright — its DDL never ran and is reproducible from the commit it was rendered at, so on a busy PR the comment is pure noise. A superseded comment whose commit produced an apply is minimized (collapsed as Outdated) rather than deleted, keeping the record of what ran expandable on the PR.

A server can opt out to a minimize-based policy instead, which applies to every repository it manages:

delete_unactioned_plan_comments: false

Under this policy, a superseded comment is minimized and stays expandable on GitHub — with one safety hold: a plan comment whose commit produced an apply is never minimized, even after new pushes. That comment is the record of what actually ran against the database, and it stays visible until an operator reconciles the apply.

Unactioned means exactly that: no apply ran from the comment's commit. It says nothing about human engagement — a comment people reacted to or linked elsewhere is still deleted if its plan never became an apply. And unlike minimizing, deletion is irreversible: the comment's reactions are lost, any permalink to it (in chat, tickets, or other PRs) breaks, and SchemaBot's stored record keeps the comment's identifiers, not its rendered body.

Either way, retirement fails toward visibility — if GitHub or storage misbehaves, comments are left as they are (extra noise), never hidden or removed without a durable record.

Multi-App Routing

A single SchemaBot process can serve webhooks for repositories owned by multiple GitHub Apps — for example, one App per GitHub org, or one App per tenant within a single org. Each App has its own credentials and webhook secret, and each repository declares which App owns it.

apps:
  app-a:
    app-id: "env:APP_A_ID"
    private-key: "file:/secrets/app-a/private-key"
    webhook-secret: "file:/secrets/app-a/webhook-secret"
    check-name: "SchemaBot X"
  app-b:
    app-id: "env:APP_B_ID"
    private-key: "file:/secrets/app-b/private-key"
    webhook-secret: "file:/secrets/app-b/webhook-secret"
    check-name: "SchemaBot Y"

repos:
  org-a/repo-x:
    github_app: app-a
  org-b/repo-y:
    github_app: app-b

Rules:

  • github: and apps: are mutually exclusive — configure one or the other, not both.
  • When apps: is configured, every entry in repos: MUST set github_app: to one of the configured app names. Unknown names are rejected at config load.
  • When apps: is NOT configured, repositories must not set github_app: — it would be silently ignored, so it is rejected at config load to surface misconfiguration early.
  • The legacy single-App github: shape continues to work unchanged.

The map key under apps: is the App's stable logical name and the value that flows into log lines and metrics. Each entry MUST provide a non-empty app-id, private-key, and webhook-secret; all three accept the same secret-resolution prefixes as the legacy github: block (see Secret Resolution). check-name is optional and defaults to SchemaBot. previous-webhook-secret is optional and holds the App's old webhook secret while it is rotated out; see Rotating the webhook secret.

How dispatch works

GitHub sends X-GitHub-Hook-Installation-Target-ID (the App's numeric ID) and X-GitHub-Hook-Installation-Target-Type: integration on every App-originated webhook. SchemaBot uses that header to look up which configured App signed the request and verifies the HMAC against that App's secret only. Then it cross-checks that the App signing the delivery is the same App configured to own the repository in repos: so config drift fails closed rather than crossing tenant boundaries. Both outcomes are rejected with 401, but they are logged and counted differently because only one is actionable:

Cause Log level schemabot.webhook.events_total status
The repository has no entry in repos: at all — routine traffic from a repository this instance does not manage, since a shared App forwards deliveries for every repository it is installed on. debug (invisible at the default LOG_LEVEL=info) repo_not_configured, recorded without a repository attribute to keep the metric's cardinality bounded
The repository is declared but the signing App is not the App configured to own it — config drift or a hostile install. warn app_repo_mismatch, with the repository attribute

Both emit the same webhook rejected: signing App does not own repo message and carry the repository in the log record, so debugging constant 401s for an unmanaged repository means searching at debug level, not warn.

The legacy single-github: shape does not require the header and continues to verify against the single configured secret.

Operator commands inherit this scoping: a Check Run scan or backfill resolves each repository to its owning App and derives the expected check names from that App's check-name and the instance's allowed_environments. See Backfilling missing Check Runs.

Secret Resolution

Database DSNs and GitHub credentials (private-key and webhook-secret) support these secret resolution prefixes. Choose the source that fits your hosting setup; neither credential requires a particular source:

Prefix Example Description
env: env:STAGING_DSN Read from environment variable
file: file:/run/secrets/prod-dsn Read from file
secretsmanager: secretsmanager:prod/db-dsn Read from AWS Secrets Manager

See pkg/secrets for implementation details.

Experimental integrations

experimental-strata-enabled is a server-only boolean, defaulting to false. When false, Strata database registrations are rejected and setup comments do not offer it. Existing deployments using Strata must explicitly enable it before upgrading. A repository's schemabot.yaml cannot enable this setting.

Enabling the flag permits registrations and adds an experimental option to setup guidance. It does not make the integration available for open-source use. See Strata availability.

experimental-strata-enabled: false

With this configuration, registering a Strata database returns an error naming the database and the server setting required to enable it.