Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/test-helm-chart.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ jobs:
- name: Run unit tests
run: |
python3 -m unittest discover -s tests -p 'test_*.py'
node --test tests/test_loop_runtime_tls.cjs
helm unittest braintrust

lint-test:
Expand Down
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,16 @@ See the [Braintrust Helm Chart](./braintrust/README.md) for more details.

GKE Autopilot is the preferred solution for new Braintrust deployments. GKE Standard is supported when customer requirements prevent Autopilot use.

## Loop Runtime

On GKE, set `enable_loop_runtime = true` in the
[public GCP Terraform module](https://github.com/braintrustdata/terraform-google-braintrust-data-plane#loop-runtime-infrastructure)
(v4.0.0 or later).
Its infrastructure apply installs isolated workers and generates persistent TLS
in Secret Manager. Pass `loop_runtime_helm_values_yaml` after your existing Helm
values. See the
[Loop setup guide](braintrust/examples/gke-loop-runtime).

## GKE Standard node pool changes

The [Standard example](braintrust/examples/google-standard/values.yaml) uses stable workload selectors and enables optional API and Brainstore disruption budgets.
Expand Down
70 changes: 64 additions & 6 deletions braintrust/examples/gke-loop-runtime/README.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,66 @@
# Loop Runtime on GKE

Loop Runtime runs in the primary GKE cluster. Its sandboxes run on Sandbox
Service workers in a separate isolated cluster. Both clusters come from the
GCP Terraform module with:
With v4.0.0 or later, set `enable_loop_runtime = true` in the
[GCP data-plane module](https://github.com/braintrustdata/terraform-google-braintrust-data-plane#loop-runtime-infrastructure)
and apply infrastructure first. Workers run in an isolated cluster; Loop Runtime
stays in the primary cluster with its existing Autopilot or Standard mode.

## Helm-managed primary release

Infrastructure installs workers, waits for readiness and persists separate server
and client CA bundles in Secret Manager for reuse. Pass its configuration after
your existing Helm values:

```sh
terraform output -raw loop_runtime_helm_values_yaml > loop-values.yaml
helm upgrade --install braintrust oci://public.ecr.aws/braintrust/helm/braintrust \
--namespace braintrust --create-namespace --version <chart-version> \
--reset-then-reuse-values --values <existing-values.yaml> \
--values loop-values.yaml --wait
```

Use a chart supporting `loopRuntime.sandbox.clientTlsSecret`. The overlay supplies
the secret reference, runtime identity, worker version and connection settings;
keys stay out of Terraform state and Helm values. At Pod startup, Workload Identity
loads only the client bundle into memory for a read-only runtime mount, without
access to server credentials or CA keys. No setup root, worker providers or manual
TLS generation is required; use `loop_runtime_options` for worker overrides.

Deploy compatible API, Brainstore and routed AI Gateway versions first. Keep the
generated runtime/worker version compatible with those services. Before applying,
compare the chart's default with the generated overlay:

```sh
helm show values oci://public.ecr.aws/braintrust/helm/braintrust --version <chart-version> | yq '.loopRuntime.image.tag'
yq '.loopRuntime.image.tag' loop-values.yaml
```

If they differ, upgrade the data-plane module or deliberately pin
`loop_runtime_options.services_version` there. For a Standard
primary cluster, retain your `loopRuntime.nodeSelector` override for its services
pool. Explicit values after `--reset-then-reuse-values` replace retained settings.

## Terraform-managed primary release

If Terraform manages the primary `helm_release`, append the infrastructure's
`loop_runtime_helm_values_yaml` output to its existing `values` list, after your
existing values. Apply infrastructure first, then update the Helm release.

## Clusters managed by your platform

Call the [worker bootstrap module](https://github.com/braintrustdata/terraform-google-braintrust-data-plane/tree/main/modules/gke-loop-bootstrap)
from your existing Terraform with the worker cluster's DNS API endpoint and
networking/storage outputs. It installs workers and TLS without creating a cluster,
and returns `helm_values_yaml` for the same Helm command above; no manual worker
install, certificate copying or connection overlay is needed. Your platform still
owns cluster/network resources and cloud IAM; keep organization settings, node
placement and any Cloud SQL Proxy sidecar in your existing primary values.

## Custom worker installations

These optional steps are for installations managing the worker release and TLS
themselves. Platform-managed clusters can use the automatic bootstrap above.
Provision standalone workers with the GCP infrastructure module:

```hcl
gke_isolated_workers = {
Expand Down Expand Up @@ -59,9 +117,9 @@ or at those limits.

## Filesystem retention

Retention is off unless the overlay is applied. Keep the worker chart, worker image
and Loop Runtime image compatible. Terraform selects the worker package from
`loopRuntime.sandboxServiceChart` in the chosen Braintrust Helm release.
The automatic infrastructure bootstrap enables filesystem retention and supplies
the checkpoint store. The following overlay steps apply only to custom worker
installations. Keep the worker chart, worker image and Loop Runtime compatible.

Apply the GCP checkpoint-storage update first, then copy
`gke_isolated_workers.checkpoint_store` into `sandbox-service-retention.yaml`.
Expand Down
55 changes: 55 additions & 0 deletions braintrust/files/loop-runtime-tls.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
const fs = require('node:fs');
const path = require('node:path');
const { randomUUID } = require('node:crypto');

async function request(fetchImpl, url, options) {
for (let attempt = 0; attempt < 12; attempt++) {
const response = await fetchImpl(url, { ...options, signal: AbortSignal.timeout(10000) });
if (response.ok) return response;
if (![401, 403, 429, 500, 502, 503, 504].includes(response.status) || attempt === 11) {
throw new Error(`TLS credential request failed (${response.status})`);
}
await new Promise(resolve => setTimeout(resolve, Math.min(1000 * 2 ** attempt, 10000)));
}
}

async function installTls(secret, directory, fetchImpl = fetch) {
if (typeof secret !== 'string' || !/^projects\/[A-Za-z0-9.:-]+\/secrets\/[A-Za-z0-9_-]+\/versions\/(latest|[0-9]+)$/.test(secret)) {
throw new Error('Invalid sandbox TLS secret reference');
}
const metadata = await request(fetchImpl,
'http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token',
{ headers: { 'Metadata-Flavor': 'Google' } });
let token;
try { token = (await metadata.json()).access_token; } catch { throw new Error('Invalid Workload Identity response'); }
if (typeof token !== 'string' || !token) throw new Error('Invalid Workload Identity response');
const response = await request(fetchImpl, `https://secretmanager.googleapis.com/v1/${secret}:access`,
{ headers: { Authorization: `Bearer ${token}` } });
let bundle;
try {
const payload = await response.json();
bundle = JSON.parse(Buffer.from(payload.payload.data, 'base64').toString('utf8'));
} catch { throw new Error('Invalid sandbox TLS bundle'); }
if (!bundle || typeof bundle !== 'object' || Array.isArray(bundle) ||
!['cert', 'key', 'ca_cert'].every(key => typeof bundle[key] === 'string' && bundle[key].trim())) {
throw new Error('Invalid sandbox TLS bundle');
}
fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
for (const [file, field] of Object.entries({ 'client.pem': 'cert', 'client.key': 'key', 'server-ca.pem': 'ca_cert' })) {
const temporary = path.join(directory, `.${file}.${randomUUID()}`);
try {
fs.writeFileSync(temporary, bundle[field], { mode: 0o400 });
fs.renameSync(temporary, path.join(directory, file));
} finally {
if (fs.existsSync(temporary)) fs.unlinkSync(temporary);
}
}
}

module.exports = { installTls };
if (process.env.SANDBOX_TLS_BOOTSTRAP === '1') {
installTls(process.env.SANDBOX_TLS_SECRET, '/etc/sandbox-tls').catch(() => {
console.error('Sandbox TLS initialization failed; check Workload Identity and the referenced Secret Manager version');
process.exitCode = 1;
});
}
7 changes: 7 additions & 0 deletions braintrust/templates/_helpers.tpl
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,13 @@ predates Loop Runtime have no loopRuntime map, which means disabled.
{{- fail (printf "loopRuntime.sandbox.%s must be a positive integer" $field) -}}
{{- end -}}
{{- end -}}
{{- $secret := index $sandbox "clientTlsSecret" -}}
{{- if and (not (kindIs "invalid" $secret)) (not (kindIs "string" $secret)) -}}
{{- fail "loopRuntime.sandbox.clientTlsSecret must be a Secret Manager version reference or empty" -}}
{{- end -}}
{{- if and $secret (not (regexMatch "^projects/[A-Za-z0-9.:-]+/secrets/[A-Za-z0-9_-]+/versions/(latest|[0-9]+)$" $secret)) -}}
{{- fail "loopRuntime.sandbox.clientTlsSecret must be a Secret Manager version reference or empty" -}}
{{- end -}}
{{- $egress := $sandbox.egressGateway | default dict -}}
{{- $_ := required "objectStorage.google.brainstoreBucket is required" .Values.objectStorage.google.brainstoreBucket -}}
{{- $_ := required "objectStorage.google.apiBucket is required" .Values.objectStorage.google.apiBucket -}}
Expand Down
40 changes: 38 additions & 2 deletions braintrust/templates/loop-runtime-deployment.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -68,10 +68,41 @@ spec:
affinity:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- if $ordering.enabled }}
{{- if or $ordering.enabled .Values.loopRuntime.sandbox.clientTlsSecret }}
initContainers:
{{- if $ordering.enabled }}
{{- include "braintrust.migrations.initContainer" . | nindent 8 }}
{{- include "braintrust.brainstoreStartupGate.initContainer" (dict "root" . "api" .Values.api) | nindent 8 }}
{{- end }}
{{- with .Values.loopRuntime.sandbox.clientTlsSecret }}
- name: sandbox-tls-init
image: "{{ $.Values.loopRuntime.image.repository }}:{{ $.Values.loopRuntime.image.tag }}"
imagePullPolicy: {{ $.Values.loopRuntime.image.pullPolicy }}
command: ["node"]
args:
- -e
- |
{{- $.Files.Get "files/loop-runtime-tls.js" | nindent 14 }}
env:
- name: SANDBOX_TLS_BOOTSTRAP
value: "1"
- name: SANDBOX_TLS_SECRET
value: {{ . | quote }}
resources:
requests:
cpu: 25m
memory: 32Mi
limits:
cpu: 100m
memory: 128Mi
securityContext:
allowPrivilegeEscalation: false
capabilities:
drop: ["ALL"]
volumeMounts:
- name: sandbox-tls
mountPath: /etc/sandbox-tls
{{- end }}
{{- end }}
containers:
- name: loop-runtime
Expand Down Expand Up @@ -169,10 +200,15 @@ spec:
- name: cache
emptyDir:
sizeLimit: 6Gi
# Created by examples/gke-loop-runtime/create-sandbox-tls.sh.
- name: sandbox-tls
{{- if .Values.loopRuntime.sandbox.clientTlsSecret }}
emptyDir:
medium: Memory
sizeLimit: 1Mi
{{- else }}
secret:
secretName: sandbox-client-tls
{{- end }}
{{- with .Values.loopRuntime.extraVolumes }}
{{- toYaml . | nindent 8 }}
{{- end }}
Expand Down
17 changes: 17 additions & 0 deletions braintrust/tests/loop-runtime-secret-reference-ordering_test.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
suite: Native TLS loading with startup ordering
tests:
- it: loads credentials after the existing migration and Brainstore checks
template: loop-runtime-deployment.yaml
values:
- __fixtures__/base-values.yaml
- __fixtures__/loop-runtime-values.yaml
set:
deploymentOrdering.enabled: true
loopRuntime.sandbox.clientTlsSecret: projects/test-project/secrets/loop-client-tls/versions/17
asserts:
- equal:
path: spec.template.spec.initContainers[2].name
value: sandbox-tls-init
- equal:
path: spec.template.spec.initContainers[2].env[1].value
value: projects/test-project/secrets/loop-client-tls/versions/17
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
suite: Loop secret reference validation
templates:
- loop-runtime-configmap.yaml
values:
- __fixtures__/base-values.yaml
- __fixtures__/loop-runtime-values.yaml
tests:
- it: rejects a secret reference containing integer
set:
loopRuntime.sandbox.clientTlsSecret: 0
asserts: &invalid
- failedTemplate:
errorMessage: loopRuntime.sandbox.clientTlsSecret must be a Secret Manager version reference or empty

- it: rejects a secret reference containing boolean
set:
loopRuntime.sandbox.clientTlsSecret: false
asserts: *invalid

- it: rejects a secret reference containing map
set:
loopRuntime.sandbox.clientTlsSecret: {}
asserts: *invalid

- it: rejects a secret reference containing list
set:
loopRuntime.sandbox.clientTlsSecret: []
asserts: *invalid

- it: rejects a secret reference containing URL
set:
loopRuntime.sandbox.clientTlsSecret: https://example.com/tls
asserts: *invalid

- it: rejects a secret reference containing path traversal
set:
loopRuntime.sandbox.clientTlsSecret: projects/p/secrets/s/versions/../other
asserts: *invalid

- it: rejects a secret reference containing missing version
set:
loopRuntime.sandbox.clientTlsSecret: projects/p/secrets/s
asserts: *invalid

- it: rejects a secret reference containing query string
set:
loopRuntime.sandbox.clientTlsSecret: projects/p/secrets/s/versions/latest?token=value
asserts: *invalid
Loading
Loading