Skip to content
Open
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
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,17 @@ 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).
Its infrastructure apply installs isolated workers and generates persistent TLS
in Secret Manager. Pass the `loop_runtime_helm_values_yaml` output after your
existing Helm values. The runtime reads its client bundle through Workload
Identity; no setup module, worker provider aliases or certificate files are
required. The GKE app module consumes the same configuration automatically.
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
63 changes: 57 additions & 6 deletions braintrust/examples/gke-loop-runtime/README.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,59 @@
# 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:
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. Loop Runtime stays in the primary cluster;
Sandbox Service workers run in a separate isolated cluster. The primary keeps
its existing Autopilot or Standard mode.

## Helm-managed primary release

The infrastructure apply installs workers, generates separate server and client
CAs, and retains their bundles in Secret Manager. It waits for worker installation
to succeed. Later applies reuse the bundles. Export the resulting configuration
and pass it 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 that supports `loopRuntime.sandbox.clientTlsSecret`. The overlay
contains a secret reference, runtime identity, worker version and connection
settings. Generated TLS keys are absent from Terraform state and Helm values.
At Pod startup, an init container uses Workload Identity to fetch only the client
bundle and writes it into an in-memory volume mounted read-only by the runtime.
The identity has no access to the server bundle or CA private keys.
No separate setup Terraform root, worker provider aliases or TLS generation is
required. Set worker sizing, version and Helm overrides through infrastructure's
optional `loop_runtime_options`.

Deploy compatible API, Brainstore and routed AI Gateway versions first. Keep the
generated runtime/worker version compatible with those services. 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

The [GKE app module](https://github.com/braintrustdata/terraform-google-braintrust-gke-app#managed-loop-runtime)
passes the same configuration to its primary Helm release automatically:

```hcl
loop_runtime = try(data.terraform_remote_state.infra.outputs.loop_runtime, null)
```

Apply infrastructure, then the app root. There is no separate app enable flag.
See its [remote-state example](https://github.com/braintrustdata/terraform-google-braintrust-gke-app/tree/main/examples/remote-state-app-root).
The full app module is optional for Helm installations.

## Custom worker installations

These optional steps are for installations that manage the worker release and
TLS themselves. Ordinary Terraform and Helm deployments use the automatic path
above. Provision standalone workers with the GCP infrastructure module:

```hcl
gke_isolated_workers = {
Expand Down Expand Up @@ -59,9 +110,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,77 @@
suite: Loop secret reference validation
templates:
- loop-runtime-configmap.yaml
tests:
- it: rejects a secret reference containing integer
template: loop-runtime-configmap.yaml
values: &values
- __fixtures__/base-values.yaml
- __fixtures__/loop-runtime-values.yaml
set:
loopRuntime.sandbox.clientTlsSecret: 0
asserts:
- failedTemplate:
errorMessage: loopRuntime.sandbox.clientTlsSecret must be a Secret Manager version reference or empty

- it: rejects a secret reference containing boolean
template: loop-runtime-configmap.yaml
values: *values
set:
loopRuntime.sandbox.clientTlsSecret: false
asserts:
- failedTemplate:
errorMessage: loopRuntime.sandbox.clientTlsSecret must be a Secret Manager version reference or empty

- it: rejects a secret reference containing map
template: loop-runtime-configmap.yaml
values: *values
set:
loopRuntime.sandbox.clientTlsSecret: {}
asserts:
- failedTemplate:
errorMessage: loopRuntime.sandbox.clientTlsSecret must be a Secret Manager version reference or empty

- it: rejects a secret reference containing list
template: loop-runtime-configmap.yaml
values: *values
set:
loopRuntime.sandbox.clientTlsSecret: []
asserts:
- failedTemplate:
errorMessage: loopRuntime.sandbox.clientTlsSecret must be a Secret Manager version reference or empty

- it: rejects a secret reference containing URL
template: loop-runtime-configmap.yaml
values: *values
set:
loopRuntime.sandbox.clientTlsSecret: https://example.com/tls
asserts:
- failedTemplate:
errorMessage: loopRuntime.sandbox.clientTlsSecret must be a Secret Manager version reference or empty

- it: rejects a secret reference containing path traversal
template: loop-runtime-configmap.yaml
values: *values
set:
loopRuntime.sandbox.clientTlsSecret: projects/p/secrets/s/versions/../other
asserts:
- failedTemplate:
errorMessage: loopRuntime.sandbox.clientTlsSecret must be a Secret Manager version reference or empty

- it: rejects a secret reference containing missing version
template: loop-runtime-configmap.yaml
values: *values
set:
loopRuntime.sandbox.clientTlsSecret: projects/p/secrets/s
asserts:
- failedTemplate:
errorMessage: loopRuntime.sandbox.clientTlsSecret must be a Secret Manager version reference or empty

- it: rejects a secret reference containing query string
template: loop-runtime-configmap.yaml
values: *values
set:
loopRuntime.sandbox.clientTlsSecret: projects/p/secrets/s/versions/latest?token=value
asserts:
- failedTemplate:
errorMessage: loopRuntime.sandbox.clientTlsSecret must be a Secret Manager version reference or empty
Loading
Loading