# Operating on Kubernetes

**Last updated:** 2026-11-27T14:53:32-03:00 (UTC-3)

How to install, verify, upgrade, and stop the gateway on a Kubernetes cluster. The manifests are standard Kubernetes: they do not depend on a distribution, driver, or ingress controller, and they work on a local or managed cluster, with Helm or Kustomize.

## Diagnose a readiness probe

For the binary/Docker probe, check the safe `healthcheck_failed` code and status, then correlate its request/trace IDs with the target's request logs. Success is quiet. Configuration errors fail before an HTTP send; connection refusal, timeout and non-200 status remain distinct without exposing private targets. Configure the final URL rather than a redirect. The [CLI contract](/docs/reference/cli/#healthcheck) defines file precedence, syntax, wildcard/IPv6 defaults and the unchanged two-second deadline. Kubernetes HTTP GET probes remain governed by their manifests. The console reports startup selection metadata, not a live check; a new CLI invocation resolves its own inputs.

## Investigate an action failure

Start from the response `X-Request-Id` and `traceparent`. Find the matching contextual failure event in JSON output or the configured OTLP log backend, then follow provider-attempt and derived helper IDs. Do not infer the final request status from a failed attempt that later fell back. Client cancellation is 499/Info; operator stop is the expected 503 policy result.

A storage failure should name its owning operation and safe cause exactly once. A synchronization failure after a committed configuration write requires reading the current version before retrying; the log is not evidence of rollback. For OTLP delivery problems, inspect local structured export/shutdown diagnostics and dropped counters; export diagnostics intentionally bypass their own failed exporter. The [observability guide](/docs/features/observability/#failure-events-and-ownership) describes event fields and the distinction between persisted request metadata and detailed logs.

## Before you start

- Kubernetes 1.27 or newer, and `kubectl` (and `helm`, if you will use the chart).
- The gateway image where the nodes can reach it ([below](#the-image)). Prefer a reference by **digest**.
- PostgreSQL 16 or newer. It is mandatory: the root Kustomization and the chart run one by default (a StatefulSet with a PVC on the default StorageClass), or you point `GATEWAY_DATABASE_URL` at your own database ([deployment modes](/docs/operate/deployment-modes/#kubernetes)).
- The `gateway-secrets` Secret, created before the gateway.

For a local environment, `python3 scripts/bootstrap-local-secrets.py` generates the Secret's files (ignored by Git, mode `0600`, without printing tokens) and the login tokens in `deploy/kubernetes/admin-token.env.local` and `viewer-token.env.local`.

The Secret contains:

```text
GATEWAY_CLIENT_KEY_SHA256=<hash of the client token>
GATEWAY_UI_ADMIN_SHA256=<hash of the admin token>
GATEWAY_UI_VIEWER_SHA256=<hash of the global viewer token>
GATEWAY_UI_SESSION_KEY=<32+ random bytes>
GATEWAY_PROVIDER_ENCRYPTION_KEY=<32 random bytes in hex>
GATEWAY_DATABASE_URL=postgres://gateway:<password>@gateway-postgres:5432/gateway?sslmode=disable
GATEWAY_DATABASE_PASSWORD=<local PostgreSQL password>
OPENAI_API_KEY=<provider key>
```

| Key | What it holds |
| --- | --- |
| `GATEWAY_CLIENT_KEY_SHA256` | Hex SHA-256 of the client token of the shipped YAML key `local-app` (`keys[].sha256_env`); applications send the token itself as `Authorization: Bearer` |
| `GATEWAY_UI_ADMIN_SHA256` | Hex SHA-256 of the admin token that opens the console ([console](/docs/features/console/)) |
| `GATEWAY_UI_VIEWER_SHA256` | Hex SHA-256 of the read-only viewer token |
| `GATEWAY_UI_SESSION_KEY` | Key that signs console session cookies, at least 32 random bytes |
| `GATEWAY_PROVIDER_ENCRYPTION_KEY` | 32 random bytes in hex that encrypt the provider credentials stored in PostgreSQL |
| `GATEWAY_DATABASE_URL` | The PostgreSQL connection URL the gateway uses |

Without `OPENAI_API_KEY`, the script uses a placeholder: the gateway starts, but calls to the provider fail.

## The image

Releases publish the image as `ghcr.io/m7gtw/gateway:<version>` (linux/amd64 and linux/arm64, one tag per version, no `latest`), and [RELEASED.md](https://github.com/m7gtw/gateway/blob/main/RELEASED.md) records each digest. The release candidates published so far are private, so until the first public release build it from the repository, as the [Quickstart](/docs/start/quickstart/#2-get-the-gateway-image) does. The chart and the Kustomize base both default to `gateway:local`, the tag `scripts/build-image.sh` produces; with a published image, set the repository and the digest as below.

```sh
scripts/build-image.sh                        # gateway:local, for this machine's platform
minikube image load gateway:local          # a local cluster: minikube, or `kind load docker-image`
```

A shared cluster pulls from a registry instead:

```sh
scripts/build-image.sh registry.example.com/gateway:1.0 linux/amd64
docker push registry.example.com/gateway:1.0
# Helm: --set image.repository=registry.example.com/gateway --set image.digest=sha256:<pushed digest>
# Kustomize: kustomize edit set image gateway:local=registry.example.com/gateway@sha256:<pushed digest>
```

With the default tag and no image in the cluster, the Pod stays in `ImagePullBackOff`, and `helm upgrade --atomic` rolls the release back when its timeout ends.

## Verifying a release image

From the first public release (`0.0.1`) on, the release workflow signs every published image keyless with [Sigstore](https://docs.sigstore.dev/) and attaches, as signed attestations, the CycloneDX SBOM of each platform and GitHub's build provenance (how the workflow does it). The release candidates (`0.0.1-rc.N`) were published privately and are **not signed**: identify them by the digest RELEASED records.

What a valid signature proves: this exact image (by digest) was signed by a job of `.github/workflows/release.yml` at the tag `v<version>` in `m7gtw/gateway`, and the signature is in Sigstore's public log. The identity alone does not say the runner was GitHub-hosted; `gh attestation verify --deny-self-hosted-runners` checks that on the provenance. It does not prove that the image is free of vulnerabilities (the release scans are a separate check, recorded with the release) and it says nothing about an image you built yourself.

Use cosign 3.x (cosign 3 reads the Sigstore bundles the release writes; older verifiers may not). Always pin the **exact** identity, at the tag of the version you deploy, and the version annotation; a loose pattern such as `--certificate-identity-regexp '.*ai-gateway.*'` also accepts a fork's signatures. Take the digests from RELEASED:

```sh
VERSION=0.0.1
IDENTITY="https://github.com/m7gtw/gateway/.github/workflows/release.yml@refs/tags/v$VERSION"
ISSUER=https://token.actions.githubusercontent.com

# The image: the index digest RELEASED records for $VERSION.
cosign verify --certificate-identity "$IDENTITY" --certificate-oidc-issuer "$ISSUER" \
  -a org.opencontainers.image.version="$VERSION" \
  ghcr.io/m7gtw/gateway@sha256:<index digest>

# Each platform's SBOM (linux/amd64 and linux/arm64 manifest digests).
cosign verify-attestation --type cyclonedx \
  --certificate-identity "$IDENTITY" --certificate-oidc-issuer "$ISSUER" \
  ghcr.io/m7gtw/gateway@sha256:<platform manifest digest>

# The build provenance, with the GitHub CLI.
gh attestation verify oci://ghcr.io/m7gtw/gateway@sha256:<index digest> \
  --repo m7gtw/gateway --cert-identity "$IDENTITY" --deny-self-hosted-runners
```

Why both the identity and the annotation: the signature's payload names the digest, not the tag. Someone able to move the tag `0.0.1` onto an older signed image would pass a check that asks only "signed by this repository"; the identity at `refs/tags/v0.0.1` and `-a org.opencontainers.image.version=0.0.1` both fail it. Verifying by the digest RELEASED records closes the same gap. To accept any released version (an admission policy, for example), anchor a regular expression on the whole identity: `^https://github\.com/m7gtw/gateway/\.github/workflows/3-proxy-release\.yml@refs/tags/v[0-9]+\.[0-9]+\.[0-9]+$`.

After `helm install` or `helm upgrade`, the chart's notes print these commands for the image it deployed, and warn when it is deployed by tag instead of digest. `imageVerification.releaseWorkflow` names the workflow they pin (the default is this project's).

**Admission policy (optional).** With [Kyverno](https://kyverno.io/) 1.13 or later in the cluster, `imageVerification.policy: kyverno` renders a `ClusterPolicy` that admits the gateway image in the release's namespace only when its build provenance was signed by that workflow at a version tag, and rewrites a tag to the verified digest; `imageVerification.failureAction: Audit` only reports. The install fails without Kyverno's CRDs. Kyverno enforces the policy only once it has registered it, and the chart's migration Job is a pre-install hook, so a first install with the policy runs that Job unverified: apply the policy before the install it guards (install Kyverno and the policy with a first release, or render it with `helm template --show-only templates/imageverification.yaml` and apply it), then install or upgrade the gateway. It admits final versions only (`vX.Y.Z`), never a release candidate. The cluster must reach the registry and Sigstore (Rekor and TUF). A registry mirror works when the image was copied with `cosign copy`, which keeps the signatures and attestations. For the [Sigstore policy-controller](https://docs.sigstore.dev/policy-controller/overview/) instead, the equivalent is a `ClusterImagePolicy` with `images: [{glob: "ghcr.io/m7gtw/gateway:**"}, {glob: "ghcr.io/m7gtw/gateway@**"}]` (a bare `ai-gateway**` would also match `ai-gateway-anything`) and a `keyless` authority with `url: https://fulcio.sigstore.dev`, issuer `https://token.actions.githubusercontent.com` and the anchored `subjectRegExp` above, enabled per namespace with the label `policy.sigstore.dev/include=true`; the chart does not render it.

```sh
helm upgrade --install gateway deploy/helm/gateway -n m7gtw \
  --set image.repository=ghcr.io/m7gtw/gateway --set image.digest=sha256:<index digest> \
  --set imageVerification.policy=kyverno
```

**Air-gapped clusters** cannot reach Sigstore: verify with the commands above on a connected machine before importing the image, then rely on the [offline bundle](/docs/operate/offline-bundle/)'s own checksum verification inside.

## Installing with Helm

The chart installs the gateway, its PostgreSQL and an example OTLP Collector. It can also render an Ingress for a controller the cluster already runs ([below](#ingress)); the controller itself and the secrets manager are outside it.

```sh
helm lint deploy/helm/gateway
helm upgrade --install gateway deploy/helm/gateway -n m7gtw --create-namespace --atomic --wait
kubectl -n m7gtw rollout status deployment/gateway-gateway
```

Helm 4 names `--atomic` `--rollback-on-failure` and still accepts the old flag with a warning. Create the `gateway-secrets` Secret in the namespace first (as in [Installing with Kustomize](#installing-with-kustomize)): the gateway and its PostgreSQL read it.

| Value | What it is for |
| --- | --- |
| `image.repository`, `image.tag`, `image.digest` | The image; the digest takes precedence over the tag |
| `image.pullPolicy`, `database.bundled.pullPolicy` | `IfNotPresent`: the Kubernetes pull policy of the gateway image and of the chart's PostgreSQL image |
| `nameOverride` | Replaces the chart name (`gateway`) in the object names and the `app.kubernetes.io/name` label; empty by default |
| `fullnameOverride` | Replaces the whole object name prefix (`<release>-gateway` by default); empty by default |
| `gateway.config` (`--set-file gateway.config=my.yaml`) | The whole YAML; the ConfigMap gets a checksum and forces a rollout |
| `gateway.existingConfigMap` | Your own ConfigMap, with the `gateway.yaml` key (the rollout is up to you) |
| `gateway.existingSecret` | An existing Secret |
| `gateway.existingTrustSecret` | CAs and client certificates, mounted at `/var/run/gateway/trust` |
| `database.engine` | The database engine, `postgres` (the only one today); the chart refuses any other value |
| `database.bundled.enabled` | `false` uses your own database through `GATEWAY_DATABASE_URL` in the Secret, or through `database.external` |
| `database.external.*` | Your own database addressed by fields, with the username and password from an existing Secret ([below](#external-database-from-a-username-and-password-secret)) |
| `ingress.*` | An optional Ingress to the gateway Service ([below](#ingress)) |
| `database.bundled.image`, `database.bundled.storage`, `database.bundled.storageClassName`, `database.bundled.resources` | The chart's PostgreSQL; `database.bundled.serviceName` (`gateway-postgres`) is the host of the URL |
| `collector.enabled` | `false` removes the example Collector |
| `collector.image` | The example OpenTelemetry Collector image, pinned by digest |
| `collector.config` | `""`: the chart's example pipeline; a string replaces the whole Collector configuration |
| `collector.resources` | Requests and limits of the Collector container (50m/64Mi requested by default) |
| `service.type` | `ClusterIP` by default; the Kubernetes Service type in front of the gateway Pods |
| `service.annotations` | `{}`: annotations of the gateway Service, passed through unchanged, where a cloud load balancer controller reads its settings (on GKE `cloud.google.com/neg: '{"ingress": true}'` for container-native load balancing and `cloud.google.com/backend-config: '{"default": "<name>"}'` for a BackendConfig's timeout, draining and health check). Values are strings. The `prometheus.io/*` keys belong to `metrics.serviceAnnotations`; setting one in both places fails the render |
| `gateway.otlpLogsEndpoint`, `gateway.otlpTracesEndpoint` | An external Collector |
| `gateway.httpReadTimeoutSeconds` | [HTTP read timeout](/docs/operate/http-input-limits/) |
| `gateway.startupProbe.periodSeconds` | `2`: how often, in seconds, the startup probe asks `/health/live` while the gateway boots and migrates |
| `gateway.startupProbe.failureThreshold` | `30`: failed probes tolerated before the kubelet restarts the container; with the period, 60 s for the first boot |
| `nodeSelector`, `tolerations`, `affinity` | Scheduling of the gateway Pods; empty by default |
| `database.bundled.nodeSelector`, `database.bundled.tolerations`, `database.bundled.affinity` | Scheduling of the chart's PostgreSQL, for example on the nodes that can attach its volume |
| `analyticsStore.bundled.image`, `analyticsStore.bundled.pullPolicy`, `analyticsStore.bundled.serviceName`, `analyticsStore.bundled.storage`, `analyticsStore.bundled.storageClassName`, `analyticsStore.bundled.resources` | The chart's ClickHouse, with `analyticsStore.bundled.enabled` ([analytics store](/docs/features/analytics-store/)): the image pinned by digest, pulled `IfNotPresent`; the Service `gateway-clickhouse`; a 20Gi volume on the default class; 250m/1Gi requested and 2/4Gi limits |
| `analyticsStore.bundled.nodeSelector`, `analyticsStore.bundled.tolerations`, `analyticsStore.bundled.affinity` | Scheduling of the chart's ClickHouse; empty by default |
| `serviceAccount.*`, `imagePullSecrets` | The Pods' ServiceAccount (cloud workload identity) and registry credentials ([below](#pod-identity-and-registry-credentials)) |
| `podAnnotations`, `podLabels`, `extraEnv`, `extraEnvFrom`, `extraVolumes`, `extraVolumeMounts` | Extra Pod metadata and container settings ([below](#extra-pod-metadata-and-container-settings)) |
| `serviceMonitor.*` | An optional Prometheus Operator ServiceMonitor ([below](#servicemonitor)) |
| `networkPolicy.*` | Optional NetworkPolicies for the gateway and the chart's PostgreSQL ([below](#networkpolicy)) |

The values schema rejects unknown types and keys, and the chart rejects `gateway.config` together with `gateway.existingConfigMap`. Values configure the deployment; `gateway.yaml` configures the behavior; credentials stay in the Secret. Replicas, autoscaling and the PodDisruptionBudget are in [high availability](/docs/operate/kubernetes-availability/#helm).

Every option below is off or empty by default, and the default release renders byte for byte what it rendered before they existed: an upgrade that sets none of them changes no object.

### Pod identity and registry credentials

```yaml
serviceAccount:
  create: true                     # false (default): the namespace's default account
  name: ""                         # empty with create: the release's full name
  annotations:
    eks.amazonaws.com/role-arn: arn:aws:iam::<account>:role/<role>
  automountServiceAccountToken: false
imagePullSecrets:
  - name: registry-login           # a kubernetes.io/dockerconfigjson Secret you create
```

| Value | Default | Contract |
| --- | --- | --- |
| `serviceAccount.create` | `false` | Renders a ServiceAccount and runs the gateway Pods as it |
| `serviceAccount.name` | `""` | With `create`, the account's name (empty: `<release>-gateway`); without it, an existing account the Pods and the migration Job run as (empty: the namespace's `default`) |
| `serviceAccount.annotations` | `{}` | Copied to the created account; this is where a cloud identity is bound |
| `serviceAccount.automountServiceAccountToken` | `null` | `false` keeps the Kubernetes API token out of the gateway and migration Pods; `null` leaves the Kubernetes default (mounted) |
| `imagePullSecrets` | `[]` | `[{name: ...}]`, set on every Pod the chart runs: gateway, migration Job, PostgreSQL and Collector |

Why a ServiceAccount: a cloud maps a Kubernetes ServiceAccount to a cloud identity, so the gateway reaches cloud providers, secret managers or object storage without a stored key. The annotation each cloud reads:

| Cloud | Annotation on the account | Also needed |
| --- | --- | --- |
| AWS (IRSA) | `eks.amazonaws.com/role-arn: arn:aws:iam::<account>:role/<role>` | The role's trust policy names `system:serviceaccount:<namespace>:<account>` |
| Google Cloud (GKE Workload Identity, impersonating a Google service account) | `iam.gke.io/gcp-service-account: <name>@<project>.iam.gserviceaccount.com` | `roles/iam.workloadIdentityUser` for `<project>.svc.id.goog[<namespace>/<account>]` on that service account. With direct workload identity federation, no annotation: grant the roles to the account's principal instead |
| Azure (Workload Identity) | `azure.workload.identity/client-id: <client id>` | The Pod label `azure.workload.identity/use: "true"` (in `podLabels`) and a federated credential for `system:serviceaccount:<namespace>:<account>` |

**Measured on GKE (2026-11-20, T176), direct workload identity federation:** with `serviceAccount: {create: true, name: ai-gateway, automountServiceAccountToken: false}`, no annotation, a node pool with `workload_metadata_config.mode: GKE_METADATA`, and `roles/aiplatform.user` granted to `principal://iam.googleapis.com/projects/<number>/locations/global/workloadIdentityPools/<project>.svc.id.goog/subject/ns/<namespace>/sa/ai-gateway`, a `vertex_ai` provider (`auth: gcp_adc`) answered chat, stream and embeddings with no key file and no Google service account. Current Gemini models are served at the `global` location (`https://aiplatform.googleapis.com/v1/projects/<project>/locations/global/publishers/google`); a regional URL answered 404 for them on a new project, while the text embedding models stay regional.

The gateway never calls the Kubernetes API, so `automountServiceAccountToken: false` removes a credential it does not use. The three cloud webhooks project their own token into the Pod, so they keep working with it.

**The migration Job.** A `pre-install`/`pre-upgrade` hook runs before the release's objects exist, so it cannot use the account the chart creates. With `serviceAccount.create` and `migrations.job.enabled`, the chart renders a hook copy, `<account>-migrate`, with the same annotations, deleted after the hooks succeed; the cloud identity must trust that account too (one more subject in the IAM trust policy, workload identity binding or federated credential). With `create: false` and a `name`, the Deployment and the Job both run as that existing account, which is the simplest setup with a migration Job. The copy is separate on purpose: recreating the Deployment's own account on every upgrade would invalidate the tokens bound to the running Pods.

### Extra Pod metadata and container settings

```yaml
podAnnotations:
  example.com/owner: platform
podLabels:
  azure.workload.identity/use: "true"
extraEnv:
  - {name: HTTPS_PROXY, value: "http://proxy.example.com:3128"}
  - name: PROVIDER_KEY
    valueFrom: {secretKeyRef: {name: provider-keys, key: primary}}
extraEnvFrom:
  - secretRef: {name: more-provider-keys}
extraVolumes:
  - name: provider-ca
    configMap: {name: provider-ca}
extraVolumeMounts:
  - {name: provider-ca, mountPath: /var/run/provider-ca, readOnly: true}
```

| Value | Default | Contract |
| --- | --- | --- |
| `podAnnotations` | `{}` | String values, added to the gateway and migration Job Pods next to `checksum/config` (which they cannot override) |
| `podLabels` | `{}` | Valid label keys and values, added to the same Pods. They never enter a selector. The chart's own keys (`app.kubernetes.io/name`, `instance`, `managed-by`, `component`) and controller-owned ones (`pod-template-hash`, the Job and StatefulSet labels) are refused |
| `extraEnv` | `[]` | Kubernetes `EnvVar` objects, after the chart's own variables |
| `extraEnvFrom` | `[]` | `EnvFromSource` objects, after `gateway.existingSecret` |
| `extraVolumes` | `[]` | `Volume` objects, after the chart's own |
| `extraVolumeMounts` | `[]` | `VolumeMount` objects with an absolute `mountPath`, each naming a volume in `extraVolumes` |
| `extraEnv[].name` | required | Name of each extra variable; the chart refuses one that would replace a variable it sets itself |
| `extraVolumes[].name` | required | Name of each extra volume, which `extraVolumeMounts[].name` refers to |
| `extraVolumeMounts[].name` | required | The `extraVolumes` entry this mount uses |

All six apply to the gateway container and to the migration Job, which runs the same binary with the same configuration, so a variable or file the gateway needs at boot is there for `gateway migrate` too. Why labels never enter a selector: a Deployment's selector is immutable, so a label added to it would make the next upgrade fail, and a selector that included a label only some Pods carry would orphan the others.

What the chart refuses at render time, naming the value, instead of leaving it to Kubernetes' last-one-wins rule or to a failed apply:

- an `extraEnv` name the chart already sets on the container: `GATEWAY_CONFIG`; with `database.external`, the URL variable, `PGUSER` and `PGPASSWORD`; with the migration Job, `GATEWAY_DATABASE_AUTO_MIGRATE`; and the HTTP, lifecycle and OTLP variables the chart renders from their own values. Use those values instead;
- the same `extraEnv` name, volume name or mount path twice;
- the volume names `config` and `infrastructure-trust`, a mount path at or inside `/etc/gateway` or `/var/run/gateway/trust`, which the chart mounts read-only, and a mount above them (`/etc`, `/var/run`, ...), which would hide the image's own files there, the CA bundle in `/etc/ssl` included;
- a mount naming no volume in `extraVolumes`.

The container's root file system stays read-only: mount an `emptyDir` for any path a tool must write. A sidecar injector annotation in `podAnnotations` also reaches the migration Job; an injected sidecar that never exits keeps the Job from finishing, so check that your injector handles Jobs (Kubernetes native sidecars do).

### ServiceMonitor

For clusters that run the Prometheus Operator. Off by default.

```yaml
serviceMonitor:
  enabled: true
  interval: 30s
  scrapeTimeout: 10s
  scheme: http                     # https when a sidecar or mesh serves the port over TLS
  tlsConfig: {}                    # with https: how Prometheus checks the gateway's certificate
  labels: {release: prometheus}    # whatever your Prometheus's serviceMonitorSelector matches
  relabelings: []
  metricRelabelings: []
```

| Value | Default | Contract |
| --- | --- | --- |
| `serviceMonitor.enabled` | `false` | Renders a `monitoring.coreos.com/v1` ServiceMonitor for `/metrics` on the gateway Service's `http` port |
| `serviceMonitor.interval` | `30s` | Whole seconds, minutes or hours (`30s`, `1m`) |
| `serviceMonitor.scrapeTimeout` | `10s` | Same format; not above `interval`, which Prometheus would refuse |
| `serviceMonitor.scheme` | `http` | `http` or `https`, rendered on the endpoint (set it to an empty string to leave Prometheus's own default). The gateway itself serves plain HTTP; set `https` when something in the Pod serves the Service's `http` port over TLS (a sidecar proxy or a service mesh with strict TLS), or the scrape fails |
| `serviceMonitor.tlsConfig` | `{}` | The endpoint's Prometheus Operator `TLSConfig` (`ca`, `cert`, `keySecret` from Secrets or ConfigMaps in the release namespace, `serverName`, `insecureSkipVerify`; or `caFile`, `certFile`, `keyFile` mounted in Prometheus), passed through and rendered only when set. It needs `scheme: https`; the chart refuses it with `http`, where Prometheus would ignore it |
| `serviceMonitor.labels` | `{}` | Added to the object, for the Prometheus selector; the chart's own label keys are refused |
| `serviceMonitor.relabelings`, `serviceMonitor.metricRelabelings` | `[]` | Prometheus Operator `RelabelConfig` objects, passed through |

To scrape through such a TLS port, trust its certificate authority and name the certificate's host:

```yaml
serviceMonitor:
  enabled: true
  scheme: https
  tlsConfig:
    ca:
      secret: {name: gateway-ca, key: ca.crt}   # a Secret in the release namespace
    serverName: gateway.example.com            # a name in that certificate
```

The ServiceMonitor selects only the gateway Service (`app.kubernetes.io/name` and `instance`), not PostgreSQL or the Collector. Two conditions: the cluster must have the Prometheus Operator CRDs, or the install fails naming the missing `ServiceMonitor` kind (the chart does not skip it silently, so a release never looks monitored when it is not); and `metrics_endpoint` must be on in the gateway YAML (it is in the bundled one), or `/metrics` answers 404 and the target shows down. The metrics themselves are in [observability](/docs/features/observability/#metrics-prometheus). `metrics.serviceAnnotations` (the `prometheus.io/*` annotations) is the alternative for a Prometheus without the operator.

### NetworkPolicy

Off by default, and it needs a CNI that enforces NetworkPolicy (most managed clusters offer one; a CNI that does not silently ignores the objects).

```yaml
networkPolicy:
  enabled: true
  ingressFrom:                     # NetworkPolicyPeer objects; empty: any source
    - namespaceSelector: {matchLabels: {kubernetes.io/metadata.name: ingress-system}}
    - namespaceSelector: {matchLabels: {kubernetes.io/metadata.name: monitoring}}
  egress:
    enabled: true                  # false (default): egress stays open
    extraRules:                    # NetworkPolicyEgressRule objects
      - to: [{ipBlock: {cidr: 0.0.0.0/0, except: [10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16]}}]
        ports: [{port: 443, protocol: TCP}]
```

| Value | Default | Contract |
| --- | --- | --- |
| `networkPolicy.enabled` | `false` | Renders a policy for the gateway Pods and, with `database.bundled.enabled`, one for the chart's PostgreSQL |
| `networkPolicy.ingressFrom` | `[]` | Who may connect to the gateway's `http` port; empty allows any source on that port |
| `networkPolicy.egress.enabled` | `false` | Restricts the gateway's outbound connections to DNS, the chart's PostgreSQL and Collector, and `extraRules` |
| `networkPolicy.egress.extraRules` | `[]` | Every other destination: providers, an external database, identity and secret services, OTLP and log destinations |

What the policies do:

- **The gateway Pods** accept connections only on the `http` port, which carries inference, the console, health and `/metrics`. List Prometheus's namespace in `ingressFrom` with the ingress controller's, or scraping stops. Kubelet probes come from the node, and the common enforcing CNIs allow node-to-Pod traffic, so readiness keeps working.
- **The chart's PostgreSQL** accepts connections on 5432 only from the gateway Pods of the release. Its selectors never match the migration Job (which requires an external database anyway) or the Collector.
- **Egress** stays open unless `egress.enabled`. Why: the gateway calls providers, identity providers, secret managers and export destinations whose addresses only you know, and a policy that guessed them would break inference without a clear error. With it on, the chart allows DNS on port 53 to any destination (a DNS Pod, a node-local cache or the node itself), its own PostgreSQL on 5432 and its own Collector on 4318; add everything else in `extraRules`. A cloud workload identity needs its endpoints too: on GKE, the metadata server (`169.254.169.254/32`, ports 80 and 988); on AWS and Azure, the token services over 443. A NetworkPolicy matches addresses, not host names: for a provider behind a CDN, allow 443 to the internet as in the example, or use an egress gateway or firewall that filters by name ([hardening](/docs/security/hardening/#what-is-up-to-the-operator)).

Tested on 2026-11-08 on an ephemeral Kubernetes 1.35 cluster with Calico, installing the chart with `serviceAccount.create`, `automountServiceAccountToken: false`, `imagePullSecrets`, `podLabels`, `podAnnotations`, `extraEnv`, an `emptyDir` extra volume and `networkPolicy` with `egress.enabled` and `ingressFrom` one namespace: the gateway Pod ran as the new account with no API token volume, its Deployment selector kept only the two chart labels, and it became Ready through the egress policy (DNS and PostgreSQL); `/health/ready` answered from the allowed namespace and timed out from another; PostgreSQL gave no response to either namespace. The same upgrade with `serviceMonitor.enabled` and no Prometheus Operator CRDs failed with `no matches for kind "ServiceMonitor"` and left the release as it was.

### Ingress

Off by default. With `ingress.enabled: true` the chart renders one `networking.k8s.io/v1` Ingress whose every path goes to the gateway Service on `service.port`. It installs no controller and assumes none: the cluster must already run one.

```yaml
ingress:
  enabled: true
  className: edge                 # an IngressClass in the cluster; empty uses the default class
  annotations: {}                 # passed to the controller unchanged
  hosts:
    - host: gateway.example.com   # "" or omitted matches any host
      paths:
        - {path: /, pathType: Prefix}
  tls:
    - secretName: gateway-tls     # a kubernetes.io/tls Secret you or a certificate controller manage
      hosts: [gateway.example.com]
```

| Value | Default | Contract |
| --- | --- | --- |
| `ingress.enabled` | `false` | Renders the Ingress; requires at least one entry in `ingress.hosts` |
| `ingress.className` | `""` | `spec.ingressClassName`; empty leaves it out, so the cluster's default IngressClass applies |
| `ingress.annotations` | `{}` | String values only, copied to the object |
| `ingress.hosts[].host` | omitted | A DNS name, optionally with a leading `*.` wildcard |
| `ingress.hosts[].paths[].path` | required | Starts with `/`; each host needs at least one path |
| `ingress.hosts[].paths[].pathType` | `Prefix` | `Prefix`, `Exact` or `ImplementationSpecific` |
| `ingress.tls[].secretName` | omitted | The certificate Secret, in the release namespace |
| `ingress.tls[].hosts` | required | At least one DNS name the certificate covers |

What changes behind HTTPS:

- **`admin.allow_insecure_http: false`** in the gateway YAML (`gateway.config` or your ConfigMap). The bundled YAML keeps `true` only for a local port-forward; with `false` the console session cookie carries `Secure`, so a browser never sends it over plain HTTP ([hardening](/docs/security/hardening/)). The chart does not flip it for you: values configure the deployment, the YAML configures the gateway.
- **Streaming.** Chat completions and other SSE responses arrive token by token only when the controller does not buffer the response, and only as long as its read timeout covers the longest stream. Both are controller settings, set through `ingress.annotations` with the keys your controller documents; the gateway's own budgets are in [network configuration](/docs/operate/network-configuration/) and [HTTP input limits](/docs/operate/http-input-limits/).

An Ingress routes HTTP only; it does not replace the gateway's authentication. Tested on 2026-11-08 with a TLS entry and a self-signed certificate: `/health/ready` answered 200 over HTTPS through the controller, plain HTTP was redirected (308), an unknown host got the controller's 404, and an unauthenticated `/v1/chat/completions` got the gateway's own 401.

### External database from a username and password Secret

Off by default. Use it when the database login already lives in a Secret of its own (written by a database operator, a secrets manager or your pipeline) and you do not want to assemble a URL with the password inside it:

```yaml
database:
  bundled:
    enabled: false
  external:
    enabled: true
    host: db.internal.example.com
    port: 5432
    name: gateway
    sslmode: require
    existingSecret: gateway-db-login    # holds the username and password
    usernameKey: username
    passwordKey: password
```

The chart then sets three variables on the gateway container:

```yaml
- {name: GATEWAY_DATABASE_URL, value: "postgres://db.internal.example.com:5432/gateway?sslmode=require"}
- name: PGUSER
  valueFrom:
    secretKeyRef: {name: "gateway-db-login", key: "username"}
- name: PGPASSWORD
  valueFrom:
    secretKeyRef: {name: "gateway-db-login", key: "password"}
```

Why this shape: the URL carries no credentials, and the PostgreSQL driver takes the username and password from `PGUSER` and `PGPASSWORD` when the URL has none, exactly as libpq does. The driver also reads any other `PG*` variable it finds (`PGOPTIONS`, `PGSSLROOTCERT`, `PGAPPNAME`, ...), so keep them out of `gateway.existingSecret` unless you mean them. The values are read raw, so a password with `@`, `:`, `/`, `?`, `#`, `%`, quotes, spaces or `$(...)` works without URL escaping, and it never appears in the rendered manifest, in `helm get manifest` or in the Deployment object. A URL assembled with Kubernetes `$(VAR)` expansion would have neither property: the expansion inserts the value unescaped, and a password with `@` or `/` breaks the URL.

| Value | Default | Contract |
| --- | --- | --- |
| `database.external.enabled` | `false` | Requires `database.bundled.enabled: false`, `host` and `existingSecret`; the chart refuses the release otherwise, naming the missing value |
| `database.external.host` | `""` | A DNS name or IPv4 address, or an IPv6 address in brackets |
| `database.external.port` | `5432` | 1–65535 |
| `database.external.name` | `gateway` | The database; letters, digits, `_` and `-`, up to 63 characters |
| `database.external.sslmode` | `require` | `disable`, `allow`, `prefer`, `require`, `verify-ca` or `verify-full` |
| `database.external.existingSecret` | `""` | A Secret in the release namespace; the chart never creates it |
| `database.external.usernameKey` | `username` | The key holding the username |
| `database.external.passwordKey` | `password` | The key holding the password |

- **Which variable.** The URL goes to the name in `storage.database_url_env` of the chart's YAML (`GATEWAY_DATABASE_URL` by default). With `gateway.existingConfigMap` the chart cannot read that YAML and uses `GATEWAY_DATABASE_URL`; keep that name there.
- **Precedence.** An explicit `env` entry wins over the same name from `envFrom`, so a `GATEWAY_DATABASE_URL` left in `gateway.existingSecret` is ignored while this mode is on. Remove it anyway, so that switching the mode off does not silently fall back to an old URL.
- **TLS.** `sslmode` is the libpq mode in the URL. For a managed database, mount its CA with `gateway.existingTrustSecret` and set `storage.database.tls.mode: verify_full` in the YAML, which takes precedence over `sslmode` ([managed PostgreSQL](/docs/operate/managed-postgres/)).
- **Rotation.** Kubernetes reads `secretKeyRef` values when the container starts. After changing the password in the Secret, restart the Deployment (`kubectl rollout restart`); running Pods keep the old password for every new connection until then, so keep the old one valid on the server until the rollout completes.

Tested on 2026-11-08 against a PostgreSQL 16 in the same namespace, with a 42-character password holding 16 URL-special characters: both replicas logged `database_ready` (107 migrations on the first, none pending on the second), PostgreSQL listed their sessions under the Secret's username, the password occurred zero times in the release manifest and the live Deployment, and a deliberately wrong `GATEWAY_DATABASE_URL` in `gateway.existingSecret` was ignored.

### Upgrading a release that used `deploy/datastore`

A release installed before the chart carried PostgreSQL ran the database from `deploy/datastore`. Upgrade it with `--set database.bundled.enabled=false`, so the release keeps using that database. Without it, Helm stops before changing anything, with `Service "gateway-postgres" ... exists and cannot be imported into the current release`.

### Uninstalling

`helm uninstall gateway -n m7gtw` removes the gateway, the Collector, the chart's PostgreSQL StatefulSet, their Services and the ConfigMap. Two things stay:

- **The `gateway-secrets` Secret:** you created it.
- **The PostgreSQL volume, `data-gateway-postgres-0`:** a StatefulSet never deletes the claims its template created. A later install with the same release name and password finds the same data. Delete the claim to drop the data for good.

The gateway Pods themselves have no volume to keep: they run with a read-only root filesystem and keep their state only in PostgreSQL.

## Installing with Kustomize

```sh
kubectl apply --server-side --field-manager=ai-gateway -f deploy/base/namespace.yaml
kubectl -n m7gtw create secret generic gateway-secrets \
  --from-env-file=deploy/kubernetes/.env.local --dry-run=client -o yaml \
  | kubectl apply --server-side --field-manager=ai-gateway -f -
kubectl apply --server-side --field-manager=ai-gateway -k .   # includes PostgreSQL; see deployment modes to use your own
kubectl -n m7gtw rollout status statefulset/gateway-postgres
kubectl -n m7gtw rollout status deployment/ai-gateway
kubectl -n m7gtw port-forward service/ai-gateway 8080:8080
```

- To remove it, `kubectl delete -k .` deletes the gateway, the Collector, the PostgreSQL StatefulSet, their Services and the ConfigMaps. The namespace is not part of the root (you applied it in the first step), so the `gateway-secrets` Secret and the PostgreSQL volume claim `data-gateway-postgres-0` stay, as with a Helm uninstall ([Uninstalling](#uninstalling)). To drop the data for good, delete that claim, or the whole namespace (`kubectl delete namespace m7gtw`).
- Always use **server-side apply** with the `ai-gateway` field manager: the OpenAPI contract in the ConfigMap exceeds the 256 KiB limit of the client-side apply annotation.
- Do not use `--force-conflicts` by default. Pick one owner for each deployment: do not alternate between Helm and `kubectl` on the same objects.
- Kustomize generates the ConfigMap with a hash, and a change in the YAML triggers a rollout.

Open `http://localhost:8080/ui` with the admin token. In production: TLS at the ingress, `admin.allow_insecure_http: false`, Secrets from a manager compatible with the cluster, and database backup and retention.

## Verifying

```sh
curl -i http://localhost:8080/health/ready
curl -i http://localhost:8080/v1/models -H "Authorization: Bearer $GATEWAY_CLIENT_TOKEN" -H 'X-Request-Id: smoke-001'
kubectl -n m7gtw logs deployment/otel-collector
kubectl top pods -n m7gtw
```

Use the `X-Request-Id` to follow the request in **Request logs** and in your OTLP backend ([logs, traces, and metrics](/docs/features/observability/)). Swagger is at `/docs/swagger/`; this site is published separately (`docs_site.url`), or at `/docs/` when the gateway serves a build of it.

## Optional metrics and dashboard

- **metrics-server** gives node and pod CPU and memory (`kubectl top`) and is a prerequisite for the HPA. It does not replace application metrics.
- **Prometheus and Grafana** (`deploy/observability`): create the `grafana-admin` Secret with a strong username and password and apply the overlay. The **m7gtw · Journey and Capacity** dashboard comes provisioned. The overlay uses `emptyDir`: the history is lost when the pods are recreated.

For OTLP, set [signal destinations](/docs/features/observability/#destinations-and-startup) to your Collector service; loopback defaults address the gateway container itself. Endpoint/flag changes require a rollout. Check delivery at the Collector: Configured in the console is startup provenance, not health, and an export outage must not stop inference.

Keep `/metrics`, Prometheus, Grafana, and OTLP internal or protected. Replicas, HPA, and topology are in [high availability](/docs/operate/kubernetes-availability/).

## Upgrading and rolling back

1. Read the version's `CHANGELOG.md` and check flags, YAML, and migrations.
2. **Back up PostgreSQL** and preserve `GATEWAY_PROVIDER_ENCRYPTION_KEY`: without it, the provider credentials encrypted in the database cannot be opened.
3. Roll out (`helm upgrade --atomic --wait` or `kubectl apply`). An invalid configuration keeps the new pod from becoming ready. To change the schema as a separate step first, see [migrations as a separate step](#migrations-as-a-separate-step).
4. Follow along with `kubectl rollout status` and `kubectl rollout history`.

Rules for rolling back:
- Migrations are additive, transactional, and serialized. **Do not drop tables** to go back a version.
- **A rollback does not undo the schema.** `helm rollback`, `helm upgrade --atomic` (which rolls back on failure) and `kubectl rollout undo` restore the previous Deployment, not the database. Once the new release migrated, the previous binary refuses to start against the newer schema (`database schema newer than this binary`): its Pods that are still running keep serving, but any of them that restarts, and every new one, stays down. With the migration Job this happens as soon as the Job succeeded, even if the rollout then fails. To go back for real, restore the backup taken before the upgrade, or fix forward with the new release.
- An older version does not know about new flags, roles, protocols, or fields. Before the rollback, while still on the new version, revert through the console or the API the overrides the old version does not understand, and remove anything unknown from the YAML.
- **Turning a restriction off widens access.** Team policies, plans, and limits stop applying in a version that does not know them: express the critical restrictions in the YAML or at the edge before going back.
- Never change the provider encryption key without the [offline keyring check/apply/recheck and recovery procedure](/docs/security/keyring-rotation/). Stop all writers; preserve the matching backup and keys. A successful scan is snapshot proof, not an online old-writer fence.
- Reload `/ui` after the rollout to pick up the new console.

### Upgrading from 0.0.1-rc.2: infrastructure names

The infrastructure parameters are named by their function, not by the engine behind them, so that another engine would change a value and never a name. Releases after 0.0.1-rc.2 renamed the parameters of the main database, the analytics store, the cache backend API and the metrics endpoint flag. There are no aliases: each old name is refused with a message that names the new one, so nothing is silently dropped. Provider and API-dialect names, typed values (`engine: postgres`, `cache_backend.backend: redis`, `read_store.source: clickhouse`) and resource names are unchanged.

| Where | 0.0.1-rc.2 | Now |
| --- | --- | --- |
| Gateway YAML | `storage.postgres` (and every key under it) | `storage.database`, the keys inside unchanged, plus `engine: postgres` (optional; omitted means `postgres`) |
| Gateway YAML | `clickhouse` (and every key under it) | `analytics_store`, the keys inside unchanged, plus `engine: clickhouse` (required once `addresses` is set) |
| Feature flags (YAML `features`, `PUT /api/admin/features/{id}`, stored overrides, edition manifest) | `clickhouse_analytics`, `clickhouse_request_logs`, `prometheus_metrics` | `analytics_store_usage`, `analytics_store_request_logs`, `metrics_endpoint` |
| Environment | `GATEWAY_POSTGRES_AUTO_MIGRATE` | `GATEWAY_DATABASE_AUTO_MIGRATE` |
| Secret key (Helm, Kustomize, Compose, offline bundle) | `GATEWAY_POSTGRES_PASSWORD` | `GATEWAY_DATABASE_PASSWORD` |
| Secret key and variable of the bundled analytics store (Helm, Compose) | `GATEWAY_CLICKHOUSE_PASSWORD`, `GATEWAY_CLICKHOUSE_USER` | `GATEWAY_ANALYTICS_STORE_PASSWORD`, `GATEWAY_ANALYTICS_STORE_USER` |
| Helm values | `postgresql.*` | `database.bundled.*`, plus `database.engine: postgres`; `database.external` unchanged |
| Helm values | `clickhouse.*` | `analyticsStore.bundled.*`, plus `analyticsStore.engine: clickhouse` |
| Compose profile | `clickhouse` | `analytics-store` (the `clickhouse` service and the `gateway_clickhouse` volume keep their names) |
| Admin API (`GET /api/v1/admin/config`) | `infrastructure.postgres`, `infrastructure.postgres_settings` | `infrastructure.database` (now with `engine` and `engine_source`), `infrastructure.database_settings` |
| Admin API (`/api/v1/admin/cache-backend`) | `redis_url` (PUT), `redis_endpoint`, `redis_url_configured` | `url` (PUT, write-only), `endpoint`, `url_configured` |
| Admin API (`GET /api/v1/admin/analytics-store`) | — | new `engine` field (`clickhouse`) |
| Log fields | `config_applied` field `postgres_settings` | `database_settings` |
| Parameter registry (API, logs, OTLP) | keys `storage.postgres.*`, group `postgres` | keys `storage.database.*`, group `database`, in every catalog version |
| Console | **PostgreSQL startup settings**; **ClickHouse read store**; **Redis URL** | **Database startup settings**, with the Infrastructure row reading **Database · postgres · Configured** and the engine source on the line below; **Analytics store · clickhouse**; **Connection URL** |

Upgrade steps, in this order:

1. **Back up PostgreSQL** (as for any upgrade). Migration 195 renames feature overrides stored under the old flag ids, keeping their value, and migration 196 renames them in the flags the entitlement base approval recorded (`feature_grants`); a rollback to 0.0.1-rc.2 then needs that backup anyway, because the old binary refuses the newer schema.
2. **Gateway YAML** (your `gateway.config`, ConfigMap or file): rename the `postgres:` block under `storage:` to `database:`; rename the top-level `clickhouse:` block to `analytics_store:` and add `engine: clickhouse` to it; rename the three flags in `features:`. A configuration that still has an old name is refused by `gateway validate`, `gateway migrate` and the server, for example with `configuration key clickhouse was renamed to analytics_store; rename it in the YAML (add engine: clickhouse to it; the keys inside keep their names)` or `feature prometheus_metrics was renamed to metrics_endpoint; rename it in the features block`. With Helm the render itself fails with the same message (when the chart renders the YAML, not with `gateway.existingConfigMap`), so `helm upgrade` stops before any Pod changes. If the YAML names `username_env: GATEWAY_CLICKHOUSE_USER` or `password_env: GATEWAY_CLICKHOUSE_PASSWORD` (the names the shipped Compose and Helm setups used), change them to `GATEWAY_ANALYTICS_STORE_USER` and `GATEWAY_ANALYTICS_STORE_PASSWORD` and set those in the environment. Every mode refuses the old names when it loads the YAML (`gateway validate`, the server, Compose, the native binary, NPX, Helm with `gateway.existingConfigMap`), naming the new variable; the chart also refuses them at render time when it renders the YAML with the bundled analytics store.
3. **Environment:** if you set `GATEWAY_POSTGRES_AUTO_MIGRATE` yourself (an `extraEnv`, a systemd unit, a Kustomize patch), set `GATEWAY_DATABASE_AUTO_MIGRATE` instead and remove the old one. A process that still sees the old variable refuses to start with `GATEWAY_POSTGRES_AUTO_MIGRATE was renamed to GATEWAY_DATABASE_AUTO_MIGRATE`; the chart refuses it in `extraEnv` too. The Helm migration Job sets the new name by itself.
4. **Secrets, before the upgrade:** add `GATEWAY_DATABASE_PASSWORD` to `gateway-secrets` with the **same value** as `GATEWAY_POSTGRES_PASSWORD`, and, with the bundled analytics store, `GATEWAY_ANALYTICS_STORE_PASSWORD` with the value of `GATEWAY_CLICKHOUSE_PASSWORD`. The data volumes keep the password they were initialized with, so a different value would lock the server out. For example: `kubectl -n m7gtw get secret gateway-secrets -o jsonpath='{.data.GATEWAY_POSTGRES_PASSWORD}'` and patch that base64 value in as `GATEWAY_DATABASE_PASSWORD`.
   - **Keep the old keys until a rollback is no longer possible.** `helm rollback`, `helm upgrade --atomic` (which rolls back on failure) and a Kustomize rollback restore StatefulSets that read the old keys: without them the bundled PostgreSQL (or ClickHouse) Pod stays in `CreateContainerConfigError`, and with PostgreSQL every replica loses its database. Remove the old keys once the new release is accepted.
   - **When a secret manager writes the Secret** (External Secrets Operator, the Vault Secrets Operator, argocd-vault-plugin), add the new field in the vault or in the mapping that projects it ([secret managers](/docs/operate/secret-managers/)), not by patching the Kubernetes Secret: the operator would overwrite the patch at its next sync.
   - **Compose and the offline bundle:** add the new keys to the `.env` file; `scripts/bootstrap-local-secrets.py` copies each old key to the new one with the same value, keeps the old one, and warns when both exist with different values.
   - The bundled PostgreSQL (and ClickHouse) Pod **restarts once** during the upgrade, because its environment now names the new key: expect a brief database outage while it restarts. A missing new key keeps it down (`CreateContainerConfigError`) until the key is added.
5. **Helm values:** move every key of `postgresql:` under `database.bundled:` and every key of `clickhouse:` under `analyticsStore.bundled:` (`enabled`, `image`, `pullPolicy`, `serviceName`, `storage`, `storageClassName`, `resources`, `nodeSelector`, `tolerations`, `affinity`). A values file, `--set postgresql.*` / `--set clickhouse.*` or `--reuse-values` that still carries them is refused with `postgresql was renamed to database.bundled` or `clickhouse was renamed to analyticsStore.bundled`. Do not use `--reuse-values` for this upgrade. `database.engine` and `analyticsStore.engine` must match the engines your gateway YAML selects; a mismatch is refused. **Add `nameOverride: ai-gateway` to your values**: the chart was called `ai-gateway` in 0.0.1-rc.2 and is called `gateway` now, and that value keeps every object name and label ([names and upgrading](/docs/operate/product-names/)). With it, the StatefulSets, the `gateway-postgres` and `gateway-clickhouse` Services, the labels, the selectors and the PVCs keep their names, so the upgrade does not touch the data.
6. **Compose:** start the analytics store with `--profile analytics-store` instead of `--profile clickhouse`.
7. **API clients, scripts and dashboards** that read `infrastructure.postgres` or `infrastructure.postgres_settings`, write `redis_url` or read `redis_endpoint`/`redis_url_configured`, toggle the old flag ids, or read the registry keys `storage.postgres.*` or the `config_applied.postgres_settings` log field, use the new names. `PUT /api/admin/features/{old id}` answers 422 naming the new id, and a cache backend body with `redis_url` answers 400 naming `url`.

During the rolling upgrade, replicas of both releases serve side by side. A console from the new release in front of a 0.0.1-rc.2 replica shows the Database row and the analytics store engine as **Unavailable** instead of failing, and cannot save the cache backend (the old replica refuses `url`). Once migration 195 has renamed a stored override, a 0.0.1-rc.2 replica's control refresh refuses the new flag id: it keeps serving its last configuration but stops following control-plane changes until it is replaced. Finish the rollout, and make control-plane changes after it. If a 0.0.1-rc.2 replica still writes a flag under an old id after the migrations ran (an operator toggling it from an old console), the new replicas that are already running refuse that control refresh with `persisted feature override "clickhouse_analytics" was renamed to "analytics_store_usage" ...; restart one replica of this release or run gateway migrate with it`. Every boot of a replica of this release (in both migration modes) and every `gateway migrate` (for example the Helm migration Job) moves overrides and approved grants from old ids to new ones; the read-only `gateway audit-verify` and the maintenance commands (`source-of-truth`, `import-identities`, `reencrypt`, `content-rewrap`, the native MFA reset) never do, and with an old id left they stop on the same message. When both ids hold an override, the one changed last is kept, so the latest operator change survives; the other value is reported. The pass bumps the control version once, so the running replicas refresh, and each rename writes a `feature.rename` audit row with actor `system`, and logs `retired_feature_id_renamed` (`from`, `to`, and with a collision `kept` and `discarded_enabled`). A database with nothing to rename is not written, and the read-only `gateway audit-verify` never runs this pass. So once the last 0.0.1-rc.2 replica is gone, restart one replica of the new release or run `gateway migrate`. This pass will be removed once upgrades from 0.0.1-rc.2 are no longer supported.

### Migrations as a separate step

By default every gateway process applies the pending migrations when it starts, under one PostgreSQL advisory lock: during a rolling upgrade the first new Pod migrates and the others wait for it (`migration_lock_wait_ms`). That needs no extra step, and it is the right default for most installations.

Run migrations as their own step instead when you want the schema to change once, at a moment you choose, under your deploy tooling: right after a backup, in a change window, or from a CI stage that must succeed before any Pod changes. Two pieces make that work:

- **`gateway migrate`** applies the pending migrations and exits, with the same lock, timeouts and `database_ready` log as a booting gateway; `gateway migrate --check` only reports (exit 0 current, 3 pending). See the [CLI](/docs/reference/cli/#migrate).
- **`storage.database.auto_migrate: false`** (default `true`; boot setting, restart to change; `GATEWAY_DATABASE_AUTO_MIGRATE=true|false` overrides it) stops the serving process from migrating. At boot it reads the migration history without the lock and without changing anything. When the schema is current it starts normally (`database_ready` with `"migration_mode":"verify"`). When the schema is behind the binary it refuses to start, before the listener, with `startup_failed`, stage `database schema out of date`:

```json
{"level":"ERROR","msg":"startup_failed","stage":"database schema out of date","error":"postgres schema check: database schema is at version 107 but this binary requires version 108 (1 migration pending) and storage.database.auto_migrate is false: run `gateway migrate` with this release first"}
```

A schema newer than the binary is refused in both modes, as before, now with stage `database schema newer than this binary` and the versions. The console shows the effective value and its source (Default, YAML or Environment) as the last row of **Database startup settings**.

The order of an upgrade becomes: back up, run `gateway migrate` with the **new** release (its image or binary), then roll out the new release. An old replica still running when the schema moves ahead keeps serving: it checked the schema when it started. A replica that restarts on the old release afterwards refuses the newer schema, so finish the rollout.

#### Helm migration Job

```yaml
database:
  bundled: {enabled: false} # required: see below
  external: {enabled: true, host: db.internal.example.com, existingSecret: gateway-db-login}
migrations:
  job:
    enabled: true
    backoffLimit: 1
    activeDeadlineSeconds: 240
    ttlSecondsAfterFinished: null
    resources: {}
```

With `migrations.job.enabled`, the chart renders a Job that runs `gateway migrate` as a `pre-install,pre-upgrade` hook, with the gateway's image, `gateway.existingSecret`, `database.external` variables, trust Secret, scheduling and security context, and sets `GATEWAY_DATABASE_AUTO_MIGRATE=false` on the Deployment. Helm creates the Job before it applies anything else of the release and waits for it: a failed Job fails `helm install`/`helm upgrade` and the Deployment is not changed, so the running Pods keep serving the previous release.

| Value | Default | Contract |
| --- | --- | --- |
| `migrations.job.enabled` | `false` | Requires `database.bundled.enabled: false`; the chart refuses the release otherwise |
| `migrations.job.backoffLimit` | `1` | 0–10 retries; each attempt resumes after the last committed step |
| `migrations.job.activeDeadlineSeconds` | `240` | 30–86400; the whole Job, every attempt included |
| `migrations.job.ttlSecondsAfterFinished` | `null` | `null` keeps the finished Job until the next hook run replaces it; 0–2592000 lets Kubernetes delete it that many seconds after it finishes |
| `migrations.job.resources` | `{}` | Empty uses the gateway's `resources` |

- **Why `database.bundled.enabled: false`, on install and upgrade alike.** A pre-install hook runs before the release's own objects exist, so the chart's PostgreSQL StatefulSet is not there yet and the Job would wait for a database that cannot appear. On an upgrade that database exists, but the chart refuses the combination there too: a chart that ran the Job only on upgrades would install Pods with migrations off against an empty database, and those Pods could never start. One rule for both keeps the release reproducible from its values. Use your own database (`database.external` or a URL in `gateway.existingSecret`). With the chart's PostgreSQL, keep the default: every Pod migrates at boot under the lock.
- **Which YAML.** Hooks also run before the release ConfigMap is updated, so the Job mounts its own copy of this revision's YAML (`<release>-gateway-migrate-config`), created just before the Job and deleted when the hooks finish. With `gateway.existingConfigMap` the Job mounts that ConfigMap: update it before the upgrade.
- **Timeouts.** Each attempt stops by itself after `storage.database.startup_timeout` + `migration_timeout` of the YAML (120 s with the shipped profile), so the default `backoffLimit` and `activeDeadlineSeconds` fit two attempts. Helm waits for the hook within `--timeout` (5 minutes by default): keep `activeDeadlineSeconds` below it. When the deadline kills an attempt, Kubernetes deletes its Pod and its log with it; a timeout inside the gateway is logged as `migration_failed` first.
- **Its own labels.** The Job and its Pod are labeled `app.kubernetes.io/name: gateway-migrations` (component `migrations`), like the chart's PostgreSQL has its own name: no gateway selector (Service, Deployment, topology spread, PodDisruptionBudget) reaches the finished Pod. Otherwise the PDB would count a Pod owned by a Job, fail with `jobs.batch does not implement the scale subresource`, allow zero disruptions and block every `kubectl drain`.
- **Logs.** `kubectl -n <namespace> logs job/<release>-gateway-migrate` shows `migration_applied` per step, as each commits, and `database_ready`. The Job stays after success (`hook-delete-policy: before-hook-creation`) and is replaced on the next upgrade. `helm uninstall` does not delete hooks: remove the last Job with `kubectl delete job <release>-gateway-migrate`.

Tested on 2026-11-08 on a two-node cluster, namespace of its own, with a PostgreSQL 16 reached through `database.external`:

| Step | Result |
| --- | --- |
| `helm install`, empty database | Job applied 107 migrations in 1,103 ms (`schema_from` 0 → 108, lock wait 0 ms), finished 4 s after it started; both Pods then logged `migration_mode: verify`, 0 applied, and became Ready; install took 12 s |
| Schema set back to 107, one Pod deleted | Its replacement refused to start (`database schema out of date`, versions 107 and 108) and restarted in back-off; the other Pod kept serving |
| `helm upgrade` to a new image | Job applied migration 108 in 15 ms (`schema_from` 107 → 108); the Deployment then rolled both Pods to the new image, each in verify mode; upgrade took 19 s |
| `helm upgrade` with an unreachable database host | Job failed at its 30 s deadline, the upgrade failed, the Deployment kept its previous database host and both Pods stayed Ready |
| `/api/v1/admin/config` | 11 PostgreSQL rows; `storage.database.auto_migrate` value `false`, source `environment` |
| PDB on, finished Job kept | PDB `SufficientPods`, 2 healthy, 1 disruption allowed; the Service lists only the two gateway Pods; a server-side dry-run eviction of a gateway Pod and a dry-run `kubectl drain` of its node both accepted |

Run again on 2026-11-20 (T176) on a three-zone GKE cluster (Kubernetes 1.36.4, one `e2-standard-2` node per zone), build `35dfda33`, PostgreSQL 16.15:

| Case | Result |
| --- | --- |
| Three replicas created together (scale 0 → 3) on an empty database, `auto_migrate: true` | One Pod applied the 187 migrations (`schema_from` 0 → 192, 6,034 ms, lock wait 2 ms); the other two waited on the advisory lock (`pg_locks` sampled every 100 ms: one granted holder, two waiting backends) and logged `migrations_applied: 0` after waiting 4,637 and 5,738 ms. All three reached `database_ready`, none restarted, each version is recorded once, and the schema dump equals the one of a database migrated by rolling upgrades |
| Job mode, `helm install --no-hooks` on an empty database | `gateway migrate --check` exit 3 (0 of 187); both Pods refused to start with stage `database schema out of date`, naming `gateway migrate` |
| Job mode, `helm upgrade` with hooks | The Job applied the 187 migrations in 9 s; both Pods then started with `migration_mode: verify`; `gateway migrate --check` exit 0 |
| Job mode upgrade under load, schema 166 → 192 (a build of `7175f2cb` to `35dfda33`) | While the Job applied the 26 migrations (1,007 ms), the old Pods served 120 of 120 requests; the replacement of those Pods afterwards followed their own drain behavior (the build before the keep-alive fix: 61 `503 draining` and 2 refused connections at 20 requests per second) |

#### Kustomize and other tools

The root Kustomization keeps migrating at boot. To run the step yourself, add a Job and the override in your overlay:

```yaml
# my-overlay/kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
namespace: m7gtw # required: without it the Job keeps the unhashed ConfigMap name
resources:
  - ../path/to/m7gtw
  - migrate-job.yaml
patches:
  - target: {kind: Deployment, name: ai-gateway}
    patch: |-
      - op: add
        path: /spec/template/spec/containers/0/env/-
        value: {name: GATEWAY_DATABASE_AUTO_MIGRATE, value: "false"}
```

```yaml
# my-overlay/migrate-job.yaml
apiVersion: batch/v1
kind: Job
metadata:
  name: ai-gateway-migrate
spec:
  backoffLimit: 1
  activeDeadlineSeconds: 240
  template:
    spec:
      restartPolicy: Never
      securityContext: {runAsNonRoot: true, seccompProfile: {type: RuntimeDefault}}
      containers:
        - name: migrate
          image: gateway:local # the same image as the Deployment
          args: [migrate]
          envFrom:
            - secretRef: {name: gateway-secrets}
          env:
            - {name: GATEWAY_CONFIG, value: /etc/gateway/gateway.yaml}
          securityContext: {allowPrivilegeEscalation: false, readOnlyRootFilesystem: true, capabilities: {drop: [ALL]}}
          volumeMounts:
            - {name: config, mountPath: /etc/gateway, readOnly: true}
      volumes:
        - name: config
          configMap:
            name: gateway-config # Kustomize appends the same hash as the Deployment's
```

`kubectl apply -k` has no ordering: the Job and the new Pods start together. New Pods that start before the Job finishes refuse to start and restart in back-off, while the old Pods keep serving (`maxUnavailable: 0`), and they become Ready once the Job completes. To keep the rollout waiting, apply the Job first and wait for it (`kubectl -n m7gtw wait --for=condition=complete job/ai-gateway-migrate --timeout=5m`), then apply the overlay. A Job's Pod template is immutable: delete the finished Job before applying a new image (`kubectl -n m7gtw delete job ai-gateway-migrate`). The overlay above was rendered with `kubectl kustomize` (the Job mounts the hashed ConfigMap and the Deployment gets the override); it was not applied to a cluster.

Outside Kubernetes, run `gateway migrate` (same `GATEWAY_CONFIG` and database URL as the server) from the deploy pipeline before replacing the processes, and check it with `gateway migrate --check` (exit 3 means pending).

### Schema upgrades and pending branch adoption

PostgreSQL records each applied migration in `gateway_schema_migrations`. Startup owns a dedicated database session and holds the migration advisory lock across the upgrade; this coordinates with both current replicas and the previous transaction-lock runner. Each missing migration runs in its own transaction: its SQL and history marker commit together. If a later step fails, the completed prefix remains, the failed step rolls back and the next startup resumes after the cause is corrected. The existing migration timeout bounds the operation; the dedicated session closes on every exit.

The canonical inventory has104 migrations: versions1–105 with the historical gap at89 preserved. Unsupported history, including a newer unknown version, is refused before any pending migration is applied. A high version alone never stands in for missing earlier migrations. Preserve the history table, its timestamps and the data when moving a database; do not erase markers to bypass a failure.

The current additive sequence after v91 is:

| Version | Schema preparation | Runtime behavior |
| --- | --- | --- |
| v92 | Quota settings override and reservation alert metadata | Quota feature integration and validation remain separate work. |
| v93 | Cost-adjustment override table | The table alone does not enable editing or change prices. |
| v94 | Request timeout classification column | Does not enable new stream deadlines. |
| v95 | Stream-clock override table | Editor availability still requires its stream-timeout flags and permissions. |
| v96 | Encrypted enterprise license override | Existing licensing flag/rights and private encryption boundary remain required. |
| v97 | Runtime logging minimum override | Roll out all supporting replicas before enabling logging management; older binaries reject the newer schema. |
| v98 | Realtime policy override | Roll out all supporting replicas before enabling Realtime policy management; connected sessions retain their snapshot. |
| v99 | Approved destination instance policy | Roll all supporting replicas before management; connection trust remains YAML-owned. |
| v100 | Three-field desired HTTP boot policy | Roll all supporting replicas before management; save does not restart listeners. |
| v101 | Captured quota-charge cardinality28 | Does not rewrite existing reservation proofs. |
| v102 | Durable trial activation and terminal state | Requires the separate enterprise trial flag and signed activation. |
| v103 | Organization-plan bindings | Optional organization ceilings require their separate flag. |
| v104 | Classified base/flag activation approval | Unchanged approved activation survives expiry; no inference bypass. |
| v105 | Rankings fetch/cache policy override | Default-off management with CAS/audit; new operations only. |

Older development branches used v193 for the timeout column and v194 for the stream-clock table. The gateway retains those historical rows and their timestamps. Before applying pending migrations for a database with those legacy markers, a read-only preflight verifies the corresponding schema when canonical v94/v95 are absent; absent or incompatible legacy schema fails startup without changing that history or applying a pending prefix. It does not erase migration history or overwrite existing override/usage rows. A database with only one legacy marker still receives all other missing migrations.

Back up first and test the upgrade against a copy before production rollout. These checks cover the named development schemas; they are not a guarantee of arbitrary manual schema changes or binary downgrades. Never edit migration markers to bypass a failure. The migration-v85 feature-override cleanup uses a fixed accepted reconciliation baseline, rather than consulting a later feature catalog. This freezes the accepted upgrade behavior; it is not a reconstruction of the original v85 release catalog.

### Provider authentication upgrades

Before upgrading, check static provider credentials for HTTP-invalid ASCII controls (C0 except HTAB, and DEL) without printing them. Invalid YAML-resolved values now prevent startup; invalid/missing later rotations return503 without a provider attempt. Repair the declared external value and retry; do not turn off security checks or replace the database. API/console secret writes refuse invalid values without changing metadata, version, ciphertext or audit. This validation adds no migration, parameter or feature flag.


Before rolling out a version with strict per-type authentication validation:

1. Run the configuration validator on your YAML. Remove only misplaced nonempty options; retain every option consumed by the selected type.
2. Inspect provider metadata through the currently deployed version's administrative API. With its current version and CSRF/session permissions, explicitly replace any stored override that contains previously ignored options. Its write-only key field can remain blank for an ordinary static-key edit. Do this before upgrading, rather than expecting the new binary to silently normalize invalid metadata.
3. Back up PostgreSQL and retain the provider encryption master key. Freeze provider-configuration writes while versions are mixed; replace/drain old replicas before using the new authentication-switch contract. An older process can reintroduce unused key material or inherit a YAML reference differently. Test the new version with your configuration/overrides before rollout; mixed-version authentication edits are not certified. Validation failure keeps the new process/pod from serving a partially accepted configuration.
4. Verify read-only metadata, one unchanged edit and applicable key/identity behavior after rollout. A save is not a cloud-authentication test. Use an authorized provider check separately when needed.

There is no schema change or automatic historical ciphertext sweep in this repair. Startup/read ignores unused encrypted keys on nonstatic connections. It does not delete or reinterpret ambiguous stored records.

To remove a legacy unused key, inspect the current connection's nonsecret metadata, then explicitly save that connection in its existing identity/no-auth mode through **Providers → Edit → Save**. Automation uses the same authorized PUT with the full supported provider definition, the reviewed control version and no static secret. This preserves the connection, clears its old ciphertext atomically and records the operator/request ID. On HTTP 409, reload and review; never silently adopt a newer revision or retry against changed authentication. Unknown/unsupported records need explicit correction with the compatible version. An ordinary static-key save with an empty key field retains its key and is not a cleanup command.

A successful explicit identity/no-auth switch removes local key material; an older binary or rollback does not recover that ciphertext. Returning to static mode needs a fresh key, while **Revert to YAML** intentionally restores the declared credential reference. Provider-side key revocation and external-secret lifecycle remain the operator's actions. Preserve historical request/audit records.

## Clocks

Keep the clocks of the nodes, the gateway, and PostgreSQL in sync. RPM, leases, and receipt timestamps use the database clock; a clock that runs ahead can push recent events out of the query window and confuse the reading of traces. A long-lived receipt may stay pending while its actual operation renews the lease; age since acceptance alone is not abandonment. Inspect `durable_lease_renew_failed` and the [receipt recovery procedure](/docs/features/durable-usage/#diagnosing-a-long-running-receipt), and never replay inference to recover a receipt.

## Budgets

To turn on [budgets and TPM](/docs/features/budgets-and-tpm/): review connections, approved rates, subjects, and ceilings; turn on the flags; roll out to **all** replicas before announcing the limit. On rollback, preserve the tables and do not reset counters. A provider failure or an aggregate invoice does not authorize releasing unknown reservations: use [reconciliation](/docs/features/quota-finance/).

## Replaceable infrastructure

Start with the standalone profile: your own PostgreSQL and in-memory cache, with no Redis or Memcached. To replace a piece, change the endpoint in the YAML and in the Secret, validate connectivity, TLS, failure, and recovery in the environment, and back up before touching durable data.

- [Local or managed PostgreSQL](/docs/operate/managed-postgres/): pool, TLS and mTLS, backup, cutover, restore.
- [Cache backends](/docs/operate/cache-backends/): Redis and Memcached.
- [Network](/docs/operate/network-configuration/): proxy, CA, mTLS, and timeouts.

In a cache incident, the gateway keeps going without cache, after authorization. In a PostgreSQL incident, whatever depends on it fails closed. Do not turn off TLS or release unknown balance to recover availability.

## Emergency stop (panic)

In an incident that is out of control, a global admin triggers **!panic** in the console or through the API:

```bash
curl -X POST https://gateway.example.com/api/v1/admin/panic \
  -H "X-CSRF-Token: $CSRF" -b "$COOKIE_FILE" -d '{"reason": "provider incident"}'
```

- **Inference:** new requests while engaged and in-flight calls interrupted before headers get `503 gateway_panic`. An unfinished response or stream whose headers were sent is interrupted without changing its sent HTTP status, reporting a normal end or replaying the call. A client cancellation or deadline that happened first retains its own classification. The policy stop is not a provider-health failure.
- **Background processes:** they pause; batches and evals resume where they left off.
- **Stay up:** console, administrative API, health, and metrics.
- **Replicas:** all of them stop within 5 s.
- **Release:** `DELETE /api/v1/admin/panic` or the **Release** button on the red banner.

See also [incident response](/docs/security/incident-response/).

## See also

- [Deployment modes](/docs/operate/deployment-modes/).
- [High availability](/docs/operate/kubernetes-availability/).
- [Business continuity](/docs/security/business-continuity/): backup and restore.

## Verify lifecycle configuration

Use [graceful shutdown](/docs/operate/shutdown/) for YAML defaults, overrides, safe applied-source inspection and rollout checks. Validate before starting; an invalid lifecycle override now fails before database/exporter startup. During a controlled SIGTERM test, correlate admission refusal, existing-stream completion/cancellation and persisted usage/receipts by request and trace IDs. Size the external deadline beyond application drain/shutdown and cleanup; the 180s shipped grace and 40s Helm allowance are sizing defaults, not a whole-process exit guarantee. External ConfigMap/Secret contents require operator alignment.

## Inspect Go runtime policy

Validate the [runtime YAML](/docs/operate/runtime-configuration/) and compare configured policy with actual startup observations for each replica after rollout. Exact bytes matter for non-MiB environment values and the disabled soft-cap sentinel. An Environment source can legitimately show Go's fallback 100 for malformed `GOGC`. A malformed `GOMEMLIMIT` may terminate before the application starts or exports logs; gateway redaction cannot intercept that Go diagnostic. Distinguish GC soft limits from admission and OS limits, preserve headroom, and measure workload-specific tuning separately.

## Interpret persistence and recovery outcomes

A provider HTTP 200 is not proof of event persistence, and a completed durable receipt is not proof of financial settlement. Use the captured IDs and the relevant receipt/ledger states; unknown work is not released or replayed by inference. During a database failure, a safe configuration view may return its last valid snapshot while database-backed authority, reads and mutations fail. See [the operation contracts](/docs/operate/persistence-contracts/) for exact boundaries and recovery ownership.

## Realtime policy rollout

Migration98 adds the singleton policy override. Back up PostgreSQL and roll all replicas to the current binary before enabling `realtime_management`; active old replicas lack policy support and old binaries refuse the new schema at startup. Policy saves converge asynchronously. Compare the dedicated endpoint on each replica; existing connections deliberately retain their snapshots. Flagoff restores the baseline for new requests without deleting the override or existing leases. On `configuration_sync_pending`, read current version/state before retrying. [Full policy and reversion](/docs/features/realtime/#manage-policy-without-reconnecting-existing-sessions).

## Destination policy rollout and loss accounting

Migration99 adds a nonsecret instance/tuning policy. Back up and roll out every replica before enabling `log_destination_management`. Keep approved template IDs stable: update/revert saved references before deleting or renaming a YAML template. Endpoint/credential/profile changes require operator YAML and rollout. Compare policy versions per replica; a success is not instantaneous cluster convergence or acknowledgement of every queued log. Inspect current-generation destination counters and `dropped_during_reconfiguration`. Queues are volatile; older superseded workers may be cancelled to bound ownership. Read current version after `configuration_sync_pending` before retrying. [Detailed lifecycle](/docs/features/observability/#generations-loss-and-recovery).

## Restart-required settings rollout

1. Back up PostgreSQL and deploy supporting binaries to every replica. Migration100 is additive; older binaries refuse the newer history. Do not remove markers or assume schema downgrade.
2. Keep YAML as the per-instance baseline. Enable `boot_settings_management` only in a storage-backed profile; an already-enabled YAML feature such as `feature_management` must still cause PostgreSQL to open when the management flag itself is persisted. A DSN alone with all storage features disabled is not a database-flag discovery mechanism.
3. Read the current version and local instance ID, then save the complete three-field policy through the API/console. Inspect raw override, desired values/sources and the unchanged applied observation. A global version change alone does not mean restart is pending.
4. Check environment masking before rollout: nonempty `GATEWAY_HTTP_READ_TIMEOUT` still wins and is captured once. Remove/update that deployment override explicitly if the console policy should take effect. Offline `gateway validate` checks YAML/ENV only, not persisted desired state.
5. Restart replicas explicitly using the chosen deployment system. Check each new instance's actual values/sources and pending state; no cluster-wide atomic adoption or automatic restart is promised. Preserve unrelated readiness, shutdown, stream and pool settings.
6. To revert, delete the override at its current version and restart again where the baseline differs. Disabling management keeps the saved override dormant and affects next-startup selection only. Invalid persisted boot policy stops startup before listen; fix/revert using another healthy supporting instance or restore a tested backup, never edit migration history. Runtime database/read failures retain the last valid snapshot.

Source ownership is part of pending state, including equal-valued console/default transitions. The older HTTP inspector cannot represent console provenance and shows paired unavailable rows; the dedicated panel and safe startup record remain authoritative. This finite writer does not provision infrastructure or replace the [HTTP contract](/docs/operate/http-input-limits/#save-changes-for-the-next-startup).

## Trial activation recovery

Before enabling `enterprise_trial`, back up and migrate to schema102, deploy compatible binaries on all replicas and verify the compiled public trust catalog. Trial state is shared in PostgreSQL, survives key reversion/restart and is not a deletion/retention target. `expired` and `clock_rollback` are terminal: repair clock synchronization and activate a definitive key using the existing license API/console; do not reset ledger rows to extend a trial. Preserve activation/audit history with backups. A new database or full historical restore is an explicit offline trust limitation, not a certified anti-rollback mechanism. [Licensing and classification](/docs/operate/licensing/).

## Organization plan ceiling rollout

Back up before migration103 and deploy compatible binaries to all replicas before enabling `organization_plan_entitlements`. Keep the required `organizations` and `plan_entitlements` flags enabled. Prepare actual organization IDs and bindings; inspect effective source/version in Plans & entitlements. Test an allowed team and a restricted team before rollout. Disabling only the organization flag makes assignments dormant while preserving team ceilings; re-enabling restores them. A versioned revert restores YAML or no additional ceiling, with audit. Referenced active-organization assignments guard plan deletion even while dormant. Older binaries reject schema103; reverting configuration does not downgrade schema. See [the contract and recovery boundary](/docs/features/entitlements/#optional-organization-ceiling).

## Expanded feature-plan rollout

Back up before migration104, deploy compatible binaries to every replica, and prepare tenant rights before enabling `feature_plan_entitlements`. The mode requires `plan_entitlements`; missing rights deny inference/resources as well as scoped product views. Inspect the complete applicability catalog and use an allowed and denied team to verify the rollout. Operator quotas, authentication, guardrails, telemetry and admission remain mandatory.

Migration104 records approved YAML/flag activation. With the default empty vendor commercial catalog there is no commercial restriction. A nonempty classified edition requires PostgreSQL approval storage; first/new activation needs a valid signed key, while unchanged approved activation survives expiry/restart. Dormant plans are checked when enabled. A rejected feature/YAML activation rolls back version, override, approval and audit together. Renew through the normal license API/console; for a rejected startup YAML restore the last approved configuration or provide valid activation. Do not delete approval/trial rows. API revert does not downgrade the schema; older binaries refuse104. [Plan/activation contract](/docs/features/entitlements/#upgrade-and-recovery).

### External rankings policy rollout

Migration105 adds only the PostgreSQL rankings-policy override table. Back up and roll out compatible binaries before enabling `model_rankings_management`; retain the default-off `model_rankings` viewing switch and its prerequisites until the source/read profile is desired. The policy writer uses the existing control version/audit lock; new operations adopt refreshed duration settings, while in-flight fetches keep their captured budget. Save/revert never triggers inference or changes billing.

If the source fails initially, inspect the request-correlated `rankings_unavailable` failure and network reachability to the fixed original source; do not replace it with an arbitrary mirror or fabricated scores. A refresh failure with an existing successful snapshot returns explicit stale provenance. Restart clears the process-local cache. Use versioned override revert for the policy, or disable the feature; neither rolls back schema. Older binaries refuse105, and removing migration markers is unsupported. Managed store failure retains the existing last-valid configuration behavior; no other engine is silently selected. See [rankings](/docs/features/model-rankings/).

## Public research rollout

Back up before PostgreSQL migration 106, roll out compatible replicas, then enable the independent default-off registry/management flags. Inspect anonymous disclosure, global policy permissions and effective source provenance before activation. Saved source policy affects new fetches/cache lookups after replica refresh; YAML requires restart. Required-source failure serves only explicitly stale accepted data or 503; optional enrichment failure keeps the primary catalog with an explicit warning and no unsubstantiated enrichment. Neither reconfigures routes/prices. Disable the registry flag to stop new public reads; deleting policy restores YAML/defaults without downgrading schema. See [configuration, failure and recovery](/docs/features/public-model-research/).

## Activate the client-source perimeter

Before enabling `source_ip_controls`, upgrade all replicas, validate the [proxy/CIDR profile](/docs/security/source-ip-controls/), prevent direct bypass of trusted ingress ranges and include operator/IdP/provisioner recovery sources. The administrative ceiling covers login/UI/API and SSO/SCIM callbacks; use the deployment control plane to restore a locked-out startup policy. This does not provision a proxy/firewall. Migration118 adds only managed-key policy/version metadata; old replicas cannot enforce it. `client_ip_logging` is separately opt-in and sends only canonical stdout/OTLP metadata; configure collector access and retention explicitly.

## Rolling out provider pools

Upgrade every replica and apply migration119 before admitting pool configuration. Keep a reviewed primary for existing account-bound objects; changing it or its secret does not migrate those objects. Stage/test the [pool profile](/docs/features/provider-credentials/) before enabling weighting/cooldowns. State is local and restarts cold; disabling weighting retains primary and never bypasses disabled/missing credentials. Back up the new ciphertext table with matching keyring, and use the standard pre-upgrade backup/configuration procedure for an older binary. No optional cache service or managed infrastructure is provisioned.

## Temporary budget schema upgrade

Migration122 adds the adopted temporary-profile context and the narrow atomic change journal, and widens the existing bounded alert-policy snapshot to262144bytes (still128policies). It does not reset counters or change the56-charge reservation bound.

Before enabling temporary allowances or writing new captures, quiesce **all** pre122 gateway replicas, administrative writers and settlement/reconciliation workers. Old JSON readers would ignore the captured effective ceiling; the startup schema guard cannot fence an already running old process. Take the coordinated PostgreSQL/matching-key backup, migrate with the new binary and resume only new writers. Do not run mixed financial writers or roll back to an old binary on the migrated state; recover using the backup/new-binary procedure. Default `temporary_budget_increases:false` preserves base enforcement. See [temporary allowance semantics and recovery](/docs/features/budgets-and-tpm/#temporary-budget-increases).

## Global/provider budget upgrade

Migration123 adopts one protected monetary obligation per original retained record into the new global/provider views. It preserves terminal/archive originals and hashes, reconciled unknown baselines, and all open holds. Every appended old open-calendar charge has a backing counter, including ended windows; lifetime includes all retained protected history. New reservations capture68 bounded charge views at most, without multiplying a provider bill.

Quiesce every pre123 financial/admin/settlement/reconciliation writer, take the coordinated database/matching-key backup, migrate and resume only new binaries. Old processes are not fenced by startup schema checks. Ambiguous/corrupt/overflowing history fails the transaction; preserve it for diagnosis. Do not skip the migration or point an older binary at the new state. Default flags remain false; a configured applicable new ceiling fails closed until enabled. Shared global counters introduce intentional transactional contention; complete branch/load qualification remainsT048. See [scope and retained coverage](/docs/features/budgets-and-tpm/#global-and-provider-budgets).

## Conditional routing rollout

Target conditions are stored in existing model JSON, without a new schema migration. Before persisting them, replace or quiesce **all older replicas and admin writers**: an older reader can ignore unknown JSON or serve its last unrestricted snapshot. Select only the upgraded pool, then stage/enable `conditional_routing`. Keep the normal database/config/key backup and new-binary recovery procedure. A configured conditional alias with the flag off is deliberately503; zero eligible targets is403 before provider/cache. Existing resource polling/settlement remains owner/provider-bound. See [rollout and limits](/docs/features/conditional-routing/#upgrade-and-rollout).

## Enforced prompt rollout

[System-prompt bindings](/docs/features/enforced-system-prompt/#upgrade-and-recovery) require all readers/writers upgraded or quiesced before storing a new field. Stage a static system-only publication, bind its current revision and owner, and activate the flag. Publication or ownership loss fails protected traffic closed; restore the reviewed publication/reference rather than route through an older binary. No schema change or additional infrastructure is introduced.

## Provider network rollout and rotation

Mount [provider CA/mTLS/proxy references](/docs/features/provider-network/) consistently and quiesce/upgrade older replicas before storing profiles. New reference admission needs YAML/deployment rollout; file replacement alone does not promise rotation. Capture failure rejects a candidate and leaves the last valid snapshot; already admitted work keeps its transport until close. Do not restore availability through silent direct/global fallback or skipped TLS validation.

## Native passthrough rollout

Upgrade all model writers/readers before storing a [passthrough policy](/docs/features/passthrough/). Keep provider secrets and network mounts on the existing deployment boundary. Test the chosen native action and authorized key before enabling client traffic. A failed operation is not replayed; missing native usage stays unknown and cannot relax a financial limit.
