Skip to content

The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.

perf(infra): configure GCP runner host THP madvise/defer (#3272)

lfld28793593daf89e9
diff --git a/apps/infra/docs/gcp/runners.md b/apps/infra/docs/gcp/runners.md
index 79d4855fb..46d1cf46c 100644
--- a/apps/infra/docs/gcp/runners.md
+++ b/apps/infra/docs/gcp/runners.md
@@ -41,18 +41,19 @@ Each assignment has a 40-minute create/update timeout, covering convergence and
the initial migration from a whole-fleet assignment. This is an upper bound, not an added wait:
completed operations proceed immediately. Deletion keeps the provider's default timeout.
-Each assignment carries binary, unit-environment and NFS client package policies. An update converges
-the API address, volume backend, registry proxy host and `nfs-common`; the package policy also covers
+Each assignment carries binary (or `runner-enrolled-binary` when Secret Server host enrollment is enabled), NFS client package, and unit-environment policies. When `BOXLITE_RUNNER_ENV` sets `"KRUN_USE_THP":"1"`, `configure-thp` runs before `converge-unit-environment` in the same ordered resource group (`runner-unit-env`, or `runner-enrolled-binary` alongside `swap-binary`) so `KRUN_USE_THP=1` is not applied if host THP fails; when `KRUN_USE_THP` is unset, removed, or not `"1"`, `converge-unit-environment` (and `swap-binary` when enrolled) runs before `configure-thp` so THP opt-out, unrelated environment updates, and the enrolled binary swap can finish on the current host even if host THP fails afterward. Because `configure-thp` still attempts convergence in the same policy (`runner-unit-env`, or `runner-enrolled-binary`), its failure still leaves that policy non-compliant on that host: during `runner:update`, that non-compliance stops progression at the canary at its 900-second deadline (even when the canary's binary swap finished) without submitting `<app>-<stage>-runner-binary-fleet` until the canary's THP failure is repaired and `runner:update` is retried; `mdeploy` itself only waits for the canary assignment rollout LRO and does not verify per-policy compliance reports, so inspect reports after `mdeploy` as described below. An update converges
+the API address, volume backend, registry proxy host, host THP (`enabled=madvise`, `defrag=defer`) and `nfs-common`; the package policy also covers
existing hosts whose startup script predates Filestore, without requiring SSH or a boot-script rerun.
-`runner:update` preserves existing package policies but cannot add one to an older assignment; run
-mdeploy first to add `runner-nfs-client`. New hosts install the same package from their boot script. Existing hosts retain their disks, image
+`runner:update` preserves existing package, enrollment, and environment policies (`runner-nfs-client` and `runner-unit-env`, as well as `configure-thp` and `converge-unit-environment` inside `runner-enrolled-binary`) but cannot add new policies or resources to an older assignment; run
+mdeploy first to add `runner-nfs-client` or `configure-thp`. New hosts install the same package and THP configuration from their boot script.
+To enable `KRUN_USE_THP` on a stage's runners, inspect the stage's current `BOXLITE_RUNNER_ENV` JSON object in `mstage` and add or update `"KRUN_USE_THP":"1"` while preserving all existing keys (such as `BOXLITE_EXPERIMENTAL`): `BOXLITE_RUNNER_ENV` replaces the entire managed runner environment map, so do not overwrite an existing map with a single-key `BOXLITE_RUNNER_ENV='{"KRUN_USE_THP":"1"}'` assignment. Existing hosts retain their disks, image
caches and local box state; machine-type and boot-image/startup changes do not resize or replace them.
New hosts use the current [runner sizing settings](../configuration.md#runner-sizing).
`runner:update` checks host stage labels and both assignments' exact stage-and-runner selectors before
writing, refusing legacy or mismatched scopes, then updates them in the same order. It waits
-for each rollout and verifies that every policy on each targeted host reports compliant with the updated
-revision. A failed update, missing report or stale revision stops progression. The first runner must be
+for each rollout and verifies within its 900-second deadline that every policy on each targeted host reports `COMPLIANT` with the updated
+revision. A failed update, non-compliant policy (such as a canary THP failure even after the canary binary swap finishes), missing report or stale revision stops progression before the fleet assignment is submitted; repair the canary's THP failure before retrying the fleet rollout. The first runner must be
running, and runner labels must be unique after normalization. The command refuses `--host`;
the next mdeploy reasserts the checkout's policy target. Both paths verify binary checksums and readiness.
Already-converged hosts need no restart. Release downgrades require the explicit `--allow-downgrade` update command.
diff --git a/apps/infra/docs/runners.md b/apps/infra/docs/runners.md
index 17324cf83..85dde60fe 100644
--- a/apps/infra/docs/runners.md
+++ b/apps/infra/docs/runners.md
@@ -106,6 +106,47 @@ Custom-kernel selection is a local runtime capability; REST clients cannot suppl
host kernel paths. See the [custom-kernel guide](../../../docs/guides/custom-kernel.md)
for SDK opt-in and kernel persistence.
+## Host THP
+
+GCP cloud deployment configures Linux Transparent Huge Pages on runner hosts with
+`enabled=madvise` and `defrag=defer` in
+[`mdeploy/stack/runner-thp.ts`](../mdeploy/stack/runner-thp.ts). First boot and
+GCP OS Config (`configure-thp`, grouped with `converge-unit-environment` in
+`runner-unit-env`, or in `runner-enrolled-binary` alongside `swap-binary` when
+Secret Server enrollment is enabled) write `/etc/tmpfiles.d/boxlite-thp.conf`
+(`0644`, replacing any symlink at that path and failing explicitly if a real
+directory exists there) for reboot persistence and apply
+`/sys/kernel/mm/transparent_hugepage/{enabled,defrag}` immediately without
+restarting `boxlite-runner`.
+
+Step order follows the desired `KRUN_USE_THP` setting in `BOXLITE_RUNNER_ENV`:
+when `KRUN_USE_THP` is `"1"`, `configure-thp` runs before
+`converge-unit-environment` so `KRUN_USE_THP=1` is never applied if host THP
+fails; when `KRUN_USE_THP` is unset, removed, or any value other than `"1"`,
+`converge-unit-environment` (and `swap-binary` in `runner-enrolled-binary`) runs
+before `configure-thp` so removing `KRUN_USE_THP=1` during recovery, updating
+unrelated environment keys, and swapping the binary on the current host can
+still finish if host THP fails afterward. However, because `configure-thp`
+remains in the same policy (`runner-unit-env`, or `runner-enrolled-binary` when
+enrolled), its failure still leaves that policy non-compliant on the host:
+during `runner:update`, the updater polls every policy on the canary for
+`COMPLIANT` up to its 900-second deadline and stops at the canary without
+submitting `<app>-<stage>-runner-binary-fleet` even when the canary binary swap
+completed; operators must repair the canary's THP failure before retrying
+`runner:update`. By contrast, `mdeploy` waits only for the canary assignment's
+OS Config rollout LRO rather than verifying policy compliance reports, so
+inspect the assignment compliance reports after `mdeploy`. On an
+existing host where `boxlite-runner` is both disabled and inactive, OS Config
+skips writing THP configuration and reports compliant; the next convergence
+after the service is enabled or active applies it.
+
+`KRUN_USE_THP` is not enabled by default. `BOXLITE_RUNNER_ENV` replaces the entire
+managed runner environment map, so edit the stage's current `BOXLITE_RUNNER_ENV`
+JSON object in `mstage` to add, update, or remove only `KRUN_USE_THP` while
+preserving all existing keys (such as `BOXLITE_EXPERIMENTAL`) instead of
+overwriting the map with a single-key example such as
+`BOXLITE_RUNNER_ENV='{"KRUN_USE_THP":"1"}'` or `BOXLITE_RUNNER_ENV='{"KRUN_USE_THP":"0"}'`.
+
## Upgrade or roll back a release
```bash
diff --git a/apps/infra/mdeploy/stack/providers/gcp/runners.ts b/apps/infra/mdeploy/stack/providers/gcp/runners.ts
index 235de79e3..8b7709a65 100644
--- a/apps/infra/mdeploy/stack/providers/gcp/runners.ts
+++ b/apps/infra/mdeploy/stack/providers/gcp/runners.ts
@@ -48,6 +48,7 @@ import {
registrationPayload,
} from '../../runner-registration.ts'
import { renderPolicyScripts, renderUnitEnvironmentPolicyScripts } from '../../runner-upgrade.ts'
+import { thpDeployment } from '../../runner-thp.ts'
import { REGISTRY_PROXY_HOST_VARIABLE } from '../../registry-proxy.ts'
import { splitSecretRef } from './secret-env.ts'
import { volumeConditionFor } from './storage.ts'
@@ -217,6 +218,28 @@ chmod +x /usr/local/bin/boxlite-runner-start.sh
*/
const VOLUME_BACKEND = 'gcs'
+/** Only `"1"` enables `KRUN_USE_THP` in `bwrap.rs`; keep step ordering consistent with runtime opt-in. */
+const isThpOptInEnabled = (raw?: string): boolean => {
+ if (raw === undefined || raw === '') return false
+ if (typeof raw !== 'string') {
+ throw new Error('BOXLITE_RUNNER_ENV must be a JSON object of strings')
+ }
+ let parsed: unknown
+ try {
+ parsed = JSON.parse(raw)
+ } catch {
+ throw new Error('BOXLITE_RUNNER_ENV must be a JSON object of strings')
+ }
+ if (!parsed || Array.isArray(parsed) || typeof parsed !== 'object') {
+ throw new Error('BOXLITE_RUNNER_ENV must be a JSON object of strings')
+ }
+ const value = (parsed as Record<string, unknown>).KRUN_USE_THP
+ if (value !== undefined && typeof value !== 'string') {
+ throw new Error('BOXLITE_RUNNER_ENV requires valid environment names and single-line string values')
+ }
+ return value === '1'
+}
+
export const gcpRunnerProvider =
({
project,
@@ -249,6 +272,7 @@ export const gcpRunnerProvider =
'GCP runner labels must be unique; DEFAULT_RUNNER_NAME overlaps another runner after normalization',
)
}
+ const thp = thpDeployment()
const platform: BootPlatform = {
// Google's metadata server. `Metadata-Flavor` is what distinguishes a
// real request from a browser that wandered onto the address.
@@ -277,6 +301,7 @@ udevadm control --reload-rules
udevadm trigger --name-match=kvm || true`,
// Box state on a disk of its own: see `renderDataDiskMount`.
prepareHome: PREPARE_HOME,
+ prepareThp: thp.install,
startWrapper: null,
unitEnvironment: {
/*
@@ -745,6 +770,35 @@ udevadm trigger --name-match=kvm || true`,
port: RUNNER_PORT,
requireServingVersion: Boolean(request.deploySecretFetch),
})
+ const thpStep = {
+ id: 'configure-thp',
+ exec: {
+ validate: { interpreter: 'NONE', script: thp.policyScripts.validate },
+ enforce: { interpreter: 'NONE', script: thp.policyScripts.enforce },
+ },
+ }
+ const swapBinaryStep = {
+ id: 'swap-binary',
+ exec: {
+ validate: { interpreter: 'NONE', script: scripts.validate },
+ enforce: { interpreter: 'NONE', script: scripts.enforce },
+ },
+ }
+ const thpOptIn = $resolve([request.environment.BOXLITE_RUNNER_ENV ?? '']).apply(([runnerEnv]) =>
+ isThpOptInEnabled(runnerEnv as string | undefined),
+ )
+ // Gate KRUN_USE_THP=1 activation on host THP convergence. When disabled,
+ // opt-out, unrelated environment updates, and enrolled swap-binary complete
+ // before configure-thp on the current host, while a configure-thp failure
+ // still leaves that policy non-compliant: runner:update polls canary
+ // compliance for 900s and stops before the fleet assignment until repaired,
+ // whereas mdeploy only awaits the canary assignment rollout LRO.
+ const enrolledResources = thpOptIn.apply((optIn: boolean) =>
+ optIn ? [thpStep, environmentStep, swapBinaryStep] : [environmentStep, swapBinaryStep, thpStep],
+ )
+ const unitEnvResources = thpOptIn.apply((optIn: boolean) =>
+ optIn ? [thpStep, environmentStep] : [environmentStep, thpStep],
+ )
let previousBatch: any
for (const batch of runnerPolicyBatches({ app: $app.name, stage: $app.stage }, assignments)) {
previousBatch = new gcp.osconfig.OsPolicyAssignment(
@@ -768,17 +822,8 @@ udevadm trigger --name-match=kvm || true`,
mode: 'ENFORCEMENT',
resourceGroups: [
{
- resources: [
- // OS Config applies resources within a group in order.
- ...(request.deploySecretFetch ? [environmentStep] : []),
- {
- id: 'swap-binary',
- exec: {
- validate: { interpreter: 'NONE', script: scripts.validate },
- enforce: { interpreter: 'NONE', script: scripts.enforce },
- },
- },
- ],
+ // OS Config applies resources within a group in order.
+ resources: request.deploySecretFetch ? enrolledResources : [swapBinaryStep],
},
],
},
@@ -802,7 +847,7 @@ udevadm trigger --name-match=kvm || true`,
{
id: 'runner-unit-env',
mode: 'ENFORCEMENT',
- resourceGroups: [{ resources: [environmentStep] }],
+ resourceGroups: [{ resources: unitEnvResources }],
},
]),
],
diff --git a/apps/infra/mdeploy/stack/runner-boot.ts b/apps/infra/mdeploy/stack/runner-boot.ts
index 29670cd84..af77edea7 100644
--- a/apps/infra/mdeploy/stack/runner-boot.ts
+++ b/apps/infra/mdeploy/stack/runner-boot.ts
@@ -84,6 +84,11 @@ export type BootPlatform = {
* run at every boot.
*/
prepareHome: string
+ /**
+ * Shell that configures host Transparent Huge Pages before the runner starts,
+ * or omitted where the platform does not converge host THP.
+ */
+ prepareThp?: string
/**
* A start wrapper for cloud credentials and host enrollment when required.
*
@@ -178,6 +183,8 @@ ${input.binary.release ? recordRunnerDigest : `installed_identity='${input.binar
${kernelDeployment().install}
+${platform.prepareThp ?? ''}
+
${platform.hostAddress}
${platform.startWrapper?.script ?? ''}
# The unit's settings live in a file rather than in Environment= lines.
diff --git a/apps/infra/mdeploy/stack/runner-thp.ts b/apps/infra/mdeploy/stack/runner-thp.ts
new file mode 100644
index 000000000..7f3a15297
--- /dev/null
+++ b/apps/infra/mdeploy/stack/runner-thp.ts
@@ -0,0 +1,136 @@
+/** Host Transparent Huge Page policy shared by first boot and GCP OS Config. */
+export const CLOUD_RUNNER_THP = {
+ enabled: 'madvise',
+ defrag: 'defer',
+} as const
+
+export type RunnerThpPolicy = {
+ enabled: 'always' | 'madvise' | 'never'
+ defrag: 'always' | 'defer' | 'defer+madvise' | 'madvise' | 'never'
+}
+
+const VALID_ENABLED = new Set(['always', 'madvise', 'never'])
+const VALID_DEFRAG = new Set(['always', 'defer', 'defer+madvise', 'madvise', 'never'])
+
+/** Shared by first boot and GCP OS Config policy enforcement. */
+export const thpDeployment = (policy: RunnerThpPolicy = CLOUD_RUNNER_THP) => {
+ if (!VALID_ENABLED.has(policy.enabled)) {
+ throw new Error(`runner THP enabled policy must be always, madvise, or never (got ${policy.enabled})`)
+ }
+ if (!VALID_DEFRAG.has(policy.defrag)) {
+ throw new Error(
+ `runner THP defrag policy must be always, defer, defer+madvise, madvise, or never (got ${policy.defrag})`,
+ )
+ }
+
+ const setup = `THP_SYSFS_DIR="\${BOXLITE_THP_SYSFS_DIR:-/sys/kernel/mm/transparent_hugepage}"
+THP_TMPFILES_PATH="\${BOXLITE_THP_TMPFILES_PATH:-/etc/tmpfiles.d/boxlite-thp.conf}"
+THP_ENABLED_PATH="$THP_SYSFS_DIR/enabled"
+THP_DEFRAG_PATH="$THP_SYSFS_DIR/defrag"
+THP_TMPFILES_CONTENT='w /sys/kernel/mm/transparent_hugepage/enabled - - - - ${policy.enabled}
+w /sys/kernel/mm/transparent_hugepage/defrag - - - - ${policy.defrag}'
+
+runner_thp_sysfs_has() {
+ [ -r "$1" ] && grep -qF "[$2]" "$1"
+}
+
+runner_thp_tmpfiles_matches() {
+ local mode
+ [ ! -L "$THP_TMPFILES_PATH" ] &&
+ [ -f "$THP_TMPFILES_PATH" ] &&
+ mode=$(stat -c '%04a' "$THP_TMPFILES_PATH" 2>/dev/null || stat -f '%Mp%03Lp' "$THP_TMPFILES_PATH" 2>/dev/null || true) &&
+ [ "$mode" = "0644" ] &&
+ [ "$(cat "$THP_TMPFILES_PATH" 2>/dev/null)" = "$THP_TMPFILES_CONTENT" ]
+}
+
+runner_thp_matches() {
+ runner_thp_tmpfiles_matches &&
+ runner_thp_sysfs_has "$THP_ENABLED_PATH" '${policy.enabled}' &&
+ runner_thp_sysfs_has "$THP_DEFRAG_PATH" '${policy.defrag}'
+}
+
+write_runner_thp_tmpfiles() {
+ if runner_thp_tmpfiles_matches; then return 0; fi
+ if [ ! -L "$THP_TMPFILES_PATH" ] && [ -d "$THP_TMPFILES_PATH" ]; then
+ echo "FATAL: THP tmpfiles path is a directory: $THP_TMPFILES_PATH" >&2
+ return 1
+ fi
+ local dir next
+ dir="$(dirname "$THP_TMPFILES_PATH")"
+ mkdir -p "$dir" || return 1
+ next="$(mktemp "$dir/.boxlite-thp.XXXXXX")" || return 1
+ if printf '%s\\n' "$THP_TMPFILES_CONTENT" > "$next" && chmod 0644 "$next"; then
+ if mv -Tf "$next" "$THP_TMPFILES_PATH" 2>/dev/null; then
+ return 0
+ fi
+ if [ -L "$THP_TMPFILES_PATH" ]; then
+ if rm -f "$THP_TMPFILES_PATH" && mv -f "$next" "$THP_TMPFILES_PATH"; then
+ return 0
+ fi
+ elif [ ! -d "$THP_TMPFILES_PATH" ] && mv -f "$next" "$THP_TMPFILES_PATH"; then
+ return 0
+ fi
+ fi
+ rm -f "$next"
+ return 1
+}
+
+apply_runner_thp_value() {
+ local path="$1" value="$2" content
+ [ -e "$path" ] || { echo "FATAL: missing THP sysfs path $path" >&2; return 1; }
+ if runner_thp_sysfs_has "$path" "$value"; then return 0; fi
+ [ -w "$path" ] || { echo "FATAL: THP sysfs path is not writable: $path" >&2; return 1; }
+ printf '%s\\n' "$value" > "$path" || { echo "FATAL: failed writing $value to $path" >&2; return 1; }
+ content="$(cat "$path")" || { echo "FATAL: failed reading THP sysfs path $path" >&2; return 1; }
+ if printf '%s\\n' "$content" | grep -qF '['; then
+ printf '%s\\n' "$content" | grep -qF "[$value]" || {
+ echo "FATAL: THP sysfs $path did not select [$value]" >&2
+ return 1
+ }
+ else
+ [ "$content" = "$value" ] || {
+ echo "FATAL: THP sysfs $path did not store $value" >&2
+ return 1
+ }
+ fi
+}
+
+install_runner_thp() {
+ write_runner_thp_tmpfiles &&
+ apply_runner_thp_value "$THP_ENABLED_PATH" '${policy.enabled}' &&
+ apply_runner_thp_value "$THP_DEFRAG_PATH" '${policy.defrag}'
+}
+`
+
+ const enforceBody = `set -euo pipefail
+${setup}
+# First boot installs its own THP policy before enabling or starting the service.
+if ! systemctl is-enabled --quiet boxlite-runner 2>/dev/null &&
+ ! systemctl is-active --quiet boxlite-runner; then exit 0; fi
+if runner_thp_matches; then echo 'runner THP already current'; exit 0; fi
+install_runner_thp
+`
+
+ return {
+ install: `${setup}\ninstall_runner_thp\n`,
+ policyScripts: {
+ validate: `#!/bin/bash
+set -euo pipefail
+${setup}
+if ! systemctl is-enabled --quiet boxlite-runner 2>/dev/null &&
+ ! systemctl is-active --quiet boxlite-runner; then exit 100; fi
+if runner_thp_matches; then exit 100; fi
+echo "runner THP configuration needs updating"
+exit 101
+`,
+ enforce: `#!/bin/bash
+set -u
+bash <<'BOXLITE_RUNNER_THP'
+${enforceBody}BOXLITE_RUNNER_THP
+status=$?
+if [ "$status" -eq 0 ]; then exit 100; fi
+exit 101
+`,
+ },
+ }
+}
diff --git a/apps/infra/mdeploy/test/gcp-pitfalls.test.ts b/apps/infra/mdeploy/test/gcp-pitfalls.test.ts
index 2512be4a1..c69660ec3 100644
--- a/apps/infra/mdeploy/test/gcp-pitfalls.test.ts
+++ b/apps/infra/mdeploy/test/gcp-pitfalls.test.ts
@@ -986,7 +986,29 @@ test('a host that cannot be told the new control-plane name is converged to it',
* recreated, and recreating one loses `/var/lib/boxlite`.
*/
const source = sourceOf('runners')
+ assert.match(source, /id: 'runner-unit-env'/, 'nothing converges the unit environment')
assert.match(source, /id: 'converge-unit-environment'/, 'nothing converges the unit environment')
+ assert.doesNotMatch(
+ source,
+ /id: 'runner-thp'/,
+ 'THP must live inside the unit-env resource group rather than as an independent policy',
+ )
+ assert.match(source, /id: 'configure-thp'/, 'nothing converges host THP policy')
+ assert.match(
+ source,
+ /const thpOptIn = \$resolve\(\[request\.environment\.BOXLITE_RUNNER_ENV \?\? ''\]\)\.apply\(\(\[runnerEnv\]\) =>\s*isThpOptInEnabled\(/,
+ 'THP step ordering must derive inside apply on resolved BOXLITE_RUNNER_ENV for KRUN_USE_THP === "1"',
+ )
+ assert.match(
+ source,
+ /const enrolledResources = thpOptIn\.apply\(\(optIn: boolean\) =>\s*optIn \? \[thpStep, environmentStep, swapBinaryStep\] : \[environmentStep, swapBinaryStep, thpStep\],?\s*\)/,
+ 'enrolled policy must gate KRUN_USE_THP=1 activation without blocking opt-out or upgrades',
+ )
+ assert.match(
+ source,
+ /const unitEnvResources = thpOptIn\.apply\(\(optIn: boolean\) =>\s*optIn \? \[thpStep, environmentStep\] : \[environmentStep, thpStep\],?\s*\)/,
+ 'runner-unit-env must gate KRUN_USE_THP=1 activation without blocking opt-out',
+ )
assert.match(source, /renderUnitEnvironmentPolicyScripts/)
/*
diff --git a/apps/infra/mdeploy/test/runner-boot.test.ts b/apps/infra/mdeploy/test/runner-boot.test.ts
index 4098a69fb..7fa2959db 100644
--- a/apps/infra/mdeploy/test/runner-boot.test.ts
+++ b/apps/infra/mdeploy/test/runner-boot.test.ts
@@ -295,9 +295,28 @@ test('the policy compares against the exact line the boot script wrote', () => {
test('boot expands the runner map as quoted environment, never the wrapper itself', () => {
const script = render({ environment: { BOXLITE_RUNNER_ENV: '{"BOXLITE_EXPERIMENTAL":"nested-virtualization"}' } })
assert.match(script, /^BOXLITE_EXPERIMENTAL="nested-virtualization"$/m)
+ assert.doesNotMatch(script, /^KRUN_USE_THP=/m)
assert.doesNotMatch(script, /^BOXLITE_RUNNER_ENV=/m)
})
+test('boot omits THP setup unless prepareThp is supplied, and runs prepareThp before starting the runner', () => {
+ const without = render()
+ assert.doesNotMatch(without, /install_runner_thp/)
+ assert.doesNotMatch(without, /boxlite-thp\.conf/)
+
+ const withThp = render({
+ platform: platform({ prepareThp: '# configure host thp\ninstall_runner_thp' }),
+ })
+ const installThp = withThp.indexOf('\ninstall_runner_thp\n')
+ assert.ok(installThp >= 0, 'boot did not include prepareThp hook')
+ assert.ok(installThp < withThp.indexOf('systemctl start boxlite-runner'))
+})
+
+test('boot writes KRUN_USE_THP="1" only when BOXLITE_RUNNER_ENV sets it', () => {
+ const script = render({ environment: { BOXLITE_RUNNER_ENV: '{"KRUN_USE_THP":"1"}' } })
+ assert.match(script, /^KRUN_USE_THP="1"$/m)
+})
+
test('invalid maps and deployment-owned keys fail before rendering boot or policy', () => {
const invalid = ['null', '[]', '{', '{"X":false}', '{"BAD-KEY":"v"}', '{"X":"line\\nfeed"}', '{"X":"a\\u0000b"}']
for (const key of [
diff --git a/apps/infra/mdeploy/test/runner-scale-out.test.ts b/apps/infra/mdeploy/test/runner-scale-out.test.ts
index 0c6d77116..8ce76f0a9 100644
--- a/apps/infra/mdeploy/test/runner-scale-out.test.ts
+++ b/apps/infra/mdeploy/test/runner-scale-out.test.ts
@@ -4,15 +4,46 @@ import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'no
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import test from 'node:test'
+import * as pulumi from '@pulumi/pulumi'
import { mockRunnerStack } from './support/gcp-runner-stack.ts'
+const isDeferred = (value: any): boolean =>
+ Boolean(value) && (typeof value.then === 'function' || (typeof value.apply === 'function' && !('value' in value)))
+
+const resolveOutput = async (value: any): Promise<any> => {
+ if (value && typeof value.promise === 'function') return resolveOutput(await value.promise())
+ if (value && typeof value.then === 'function') return resolveOutput(await value)
+ if (value && typeof value.apply === 'function') {
+ return 'value' in value
+ ? resolveOutput(value.value)
+ : new Promise((resolve, reject) => {
+ try {
+ value.apply((resolved: any) => {
+ resolveOutput(resolved).then(resolve, reject)
+ })
+ } catch (error) {
+ reject(error)
+ }
+ })
+ }
+ return value
+}
+
+const asyncOutput = (promise: Promise<any>): any => {
+ promise.catch(() => {})
+ return {
+ promise: () => promise,
+ apply: (fn: (value: any) => any) => asyncOutput(promise.then((resolved) => resolveOutput(fn(resolved)))),
+ }
+}
+
test('GCP rollout batches observe one host before updating the fleet', async (t) => {
const { output, globals, resources, provider, requestFor, secretInputs } = mockRunnerStack(t)
const servingFetch = (url: string, ids: string[] = ['12345']) => ({
url: output(url),
enrolledInstanceIds: output(ids),
})
- await t.test('GCE identity lookup follows registration and feeds only OS Config with the verified fetch URL', () => {
+ await t.test('GCE identity lookup follows registration and feeds only OS Config with the verified fetch URL', async () => {
for (const count of [1, 2]) {
resources.clear()
const request = requestFor(count)
@@ -42,16 +73,104 @@ test('GCP rollout batches observe one host before updating the fleet', async (t)
}
if (count === 2) assert.ok(lookup.options.dependsOn.includes(resources.get('RegisterExtraRunners')!.resource))
const policy = resources.get('RunnerBinary')!.args.osPolicies.find((p: any) => p.id === 'runner-enrolled-binary')
- const steps = policy.resourceGroups[0].resources
+ const steps = await resolveOutput(policy.resourceGroups[0].resources)
assert.deepEqual(
steps.map((step: any) => step.id),
- ['converge-unit-environment', 'swap-binary'],
+ ['converge-unit-environment', 'swap-binary', 'configure-thp'],
)
assert.match(steps[1].exec.enforce.script, /Cannot confirm the running Runner version/)
assert.equal(steps[0].exec.enforce.script.value.match(/'SECRET_SERVER_URL=([^']+)'/)?.[1], url)
}
})
- await t.test('a new VM can start serving jobs only after its live identity and fetch URL converge', (t) => {
+ await t.test('THP step ordering gates KRUN_USE_THP=1 opt-in without blocking opt-out or upgrades', async () => {
+ for (const deploySecretFetch of [false, true]) {
+ for (const [runnerEnv, expected] of [
+ ['{"KRUN_USE_THP":"1"}', deploySecretFetch ? ['configure-thp', 'converge-unit-environment', 'swap-binary'] : ['configure-thp', 'converge-unit-environment']],
+ ['{}', deploySecretFetch ? ['converge-unit-environment', 'swap-binary', 'configure-thp'] : ['converge-unit-environment', 'configure-thp']],
+ ['{"KRUN_USE_THP":"0"}', deploySecretFetch ? ['converge-unit-environment', 'swap-binary', 'configure-thp'] : ['converge-unit-environment', 'configure-thp']],
+ ] as const) {
+ resources.clear()
+ const request = requestFor(1)
+ request.environment = { BOXLITE_RUNNER_ENV: runnerEnv }
+ if (deploySecretFetch) request.deploySecretFetch = () => servingFetch('https://fetch.example.test')
+ provider(request)
+ const policyId = deploySecretFetch ? 'runner-enrolled-binary' : 'runner-unit-env'
+ const assignment = resources.get('RunnerBinary')
+ assert.ok(assignment)
+ const policy = assignment.args.osPolicies.find((p: any) => p.id === policyId)
+ const steps = await resolveOutput(policy.resourceGroups[0].resources)
+ assert.deepEqual(
+ steps.map((step: any) => step.id),
+ expected,
+ )
+ }
+ }
+ })
+ await t.test('THP step ordering resolves deferred BOXLITE_RUNNER_ENV Inputs (Output and Promise)', async (t) => {
+ const previousResolve = Object.getOwnPropertyDescriptor(globalThis, '$resolve')
+ Object.defineProperty(globalThis, '$resolve', {
+ configurable: true,
+ value: (values: any[]) =>
+ values.some(isDeferred)
+ ? asyncOutput(Promise.all(values.map(resolveOutput)))
+ : previousResolve!.value(values),
+ })
+ t.after(() => {
+ if (previousResolve) Object.defineProperty(globalThis, '$resolve', previousResolve)
+ else Reflect.deleteProperty(globalThis, '$resolve')
+ })
+
+ for (const [kind, wrap] of [
+ ['string', (value: string) => value],
+ ['pulumi.output', (value: string) => pulumi.output(value) as unknown as $util.Input<string>],
+ ['Promise', (value: string) => Promise.resolve(value)],
+ ] as const) {
+ for (const deploySecretFetch of [false, true]) {
+ for (const [runnerEnv, expected] of [
+ [
+ '{"KRUN_USE_THP":"1"}',
+ deploySecretFetch
+ ? ['configure-thp', 'converge-unit-environment', 'swap-binary']
+ : ['configure-thp', 'converge-unit-environment'],
+ ],
+ [
+ '{"KRUN_USE_THP":"0"}',
+ deploySecretFetch
+ ? ['converge-unit-environment', 'swap-binary', 'configure-thp']
+ : ['converge-unit-environment', 'configure-thp'],
+ ],
+ ] as const) {
+ resources.clear()
+ const request = requestFor(1)
+ request.environment = { BOXLITE_RUNNER_ENV: wrap(runnerEnv) }
+ if (deploySecretFetch) request.deploySecretFetch = () => servingFetch('https://fetch.example.test')
+ provider(request)
+ const policyId = deploySecretFetch ? 'runner-enrolled-binary' : 'runner-unit-env'
+ const assignment = resources.get('RunnerBinary')
+ assert.ok(assignment, `${kind} failed to create RunnerBinary`)
+ const policy = assignment.args.osPolicies.find((p: any) => p.id === policyId)
+ const steps = await resolveOutput(policy.resourceGroups[0].resources)
+ assert.deepEqual(
+ steps.map((step: any) => step.id),
+ expected,
+ )
+ }
+ }
+ for (const invalidEnv of ['{', 'null', '[]', '{"KRUN_USE_THP":1}']) {
+ resources.clear()
+ await assert.rejects(async () => {
+ const request = requestFor(1)
+ request.environment = { BOXLITE_RUNNER_ENV: wrap(invalidEnv) }
+ provider(request)
+ const assignment = resources.get('RunnerBinary')
+ assert.ok(assignment, `${kind} invalid env failed before creating RunnerBinary`)
+ const policy = assignment.args.osPolicies.find((p: any) => p.id === 'runner-unit-env')
+ await resolveOutput(policy.resourceGroups[0].resources)
+ }, /BOXLITE_RUNNER_ENV/)
+ }
+ }
+ })
+ await t.test('a new VM can start serving jobs only after its live identity and fetch URL converge', async (t) => {
resources.clear()
const url = 'https://fetch.example.test'
provider({ ...requestFor(1), deploySecretFetch: () => servingFetch(url, ['44556']) })
@@ -93,7 +212,7 @@ exec bash ./start`
})
assert.notEqual(execute(launch, '44556').status, 0, 'unenrolled Runner started at boot')
const policy = resources.get('RunnerBinary')!.args.osPolicies.find((p: any) => p.id === 'runner-enrolled-binary')
- const { validate, enforce } = policy.resourceGroups[0].resources[0].exec
+ const { validate, enforce } = (await resolveOutput(policy.resourceGroups[0].resources))[0].exec
assert.notEqual(execute(enforce.script.value, '12345').status, 100, 'old registry admitted a replacement VM')
assert.equal(existsSync(served), false)
const activated = execute(enforce.script.value, '44556')
@@ -105,15 +224,21 @@ exec bash ./start`
assert.equal(execute(launch, '44556').status, 0, 'reboot erased enrollment')
assert.notEqual(execute(launch, '12345').status, 0, 'stale enrollment accepted another VM')
})
- await t.test('enrollment is delivered even when OS Config runs before bootstrap', (t) => {
+ await t.test('enrollment is delivered even when OS Config runs before bootstrap', async (t) => {
resources.clear()
provider({ ...requestFor(1), deploySecretFetch: () => servingFetch('https://fetch.example.test') })
- const policy = resources
- .get('RunnerBinary')!
- .args.osPolicies.find((p: any) =>
- p.resourceGroups[0].resources.some((r: any) => r.id === 'converge-unit-environment'),
- )
- const scripts = policy.resourceGroups[0].resources.find((r: any) => r.id === 'converge-unit-environment').exec
+ const resolvedPolicies = await Promise.all(
+ resources.get('RunnerBinary')!.args.osPolicies.map(async (p: any) => ({
+ ...p,
+ resolvedResources: await Promise.all(
+ p.resourceGroups.map(async (group: any) => await resolveOutput(group.resources)),
+ ),
+ })),
+ )
+ const policy = resolvedPolicies.find((p: any) =>
+ p.resolvedResources[0].some((r: any) => r.id === 'converge-unit-environment'),
+ )
+ const scripts = policy.resolvedResources[0].find((r: any) => r.id === 'converge-unit-environment').exec
const dir = mkdtempSync(join(tmpdir(), 'early-runner-'))
t.after(() => rmSync(dir, { recursive: true, force: true }))
writeFileSync(join(dir, 'curl'), '#!/bin/sh\necho 12345\n', { mode: 0o700 })
diff --git a/apps/infra/mdeploy/test/runner-sizing.test.ts b/apps/infra/mdeploy/test/runner-sizing.test.ts
index 5fed71871..5938148bf 100644
--- a/apps/infra/mdeploy/test/runner-sizing.test.ts
+++ b/apps/infra/mdeploy/test/runner-sizing.test.ts
@@ -1,9 +1,40 @@
import assert from 'node:assert/strict'
import test, { type TestContext } from 'node:test'
+import * as pulumi from '@pulumi/pulumi'
import { awsRunnerProvider } from '../stack/providers/aws/runners.ts'
import { gcpRunnerProvider } from '../stack/providers/gcp/runners.ts'
import type { RunnerRequest } from '../stack/runners.ts'
+const isDeferred = (value: any): boolean =>
+ Boolean(value) && (typeof value.then === 'function' || (typeof value.apply === 'function' && !('value' in value)))
+
+const resolveInput = async (value: any): Promise<any> => {
+ if (value && typeof value.promise === 'function') return resolveInput(await value.promise())
+ if (value && typeof value.then === 'function') return resolveInput(await value)
+ if (value && typeof value.apply === 'function') {
+ return 'value' in value
+ ? resolveInput(value.value)
+ : new Promise((resolve, reject) => {
+ try {
+ value.apply((resolved: any) => {
+ resolveInput(resolved).then(resolve, reject)
+ })
+ } catch (error) {
+ reject(error)
+ }
+ })
+ }
+ return value
+}
+
+const asyncOutput = (promise: Promise<any>): any => {
+ promise.catch(() => {})
+ return {
+ promise: () => promise,
+ apply: (fn: (value: any) => any) => asyncOutput(promise.then((resolved) => resolveInput(fn(resolved)))),
+ }
+}
+
// Record actual provider declarations; this does not simulate Pulumi state reconciliation.
const captureResources = (t: TestContext) => {
const resources = new Map<string, { args: any; options: any }>()
@@ -26,9 +57,11 @@ const captureResources = (t: TestContext) => {
gcp: new Proxy({}, { get: () => constructors }),
aws: new Proxy({}, { get: () => constructors }),
command: { local: constructors },
+ $jsonStringify: (input: unknown) => output(JSON.stringify(input, (_, v) => unwrap(v))),
$app: { name: 'boxlite-app', stage: 'dev' },
$util: { output, secret: output },
- $resolve: (values: any[]) => output(values.map(unwrap)),
+ $resolve: (values: any[]) =>
+ values.some(isDeferred) ? asyncOutput(Promise.all(values.map(resolveInput))) : output(values.map(unwrap)),
}
for (const [key, value] of Object.entries(globals)) {
const previous = Object.getOwnPropertyDescriptor(globalThis, key)
@@ -146,3 +179,170 @@ test('AWS refuses a GCP data disk size before creating resources', (t) => {
assert.equal(resources.get('Runner')!.args.instanceType, 'c8i.12xlarge')
assert.equal(resources.get('Runner')!.args.rootBlockDevice.volumeSize, 100)
})
+
+test('GCP orders configure-thp conditionally around converge-unit-environment depending on KRUN_USE_THP', async (t) => {
+ const { resources, output } = captureResources(t)
+ const provider = gcpProvider(output)
+ const secretFetch = () => ({ url: output('https://fetch.example.test'), enrolledInstanceIds: output(['12345']) })
+
+ for (const runnerEnv of [undefined, '{}', '{"KRUN_USE_THP":"0"}']) {
+ resources.clear()
+ provider({
+ ...requestFor(),
+ environment: runnerEnv === undefined ? {} : { BOXLITE_RUNNER_ENV: runnerEnv },
+ })
+ const assignment = resources.get('RunnerBinary')
+ assert.ok(assignment)
+ const policyIds = assignment.args.osPolicies.map((policy: any) => policy.id)
+ assert.equal(policyIds.includes('runner-thp'), false)
+ assert.deepEqual(policyIds, ['runner-binary', 'runner-nfs-client', 'runner-unit-env'])
+ const unitEnv = assignment.args.osPolicies.find((policy: any) => policy.id === 'runner-unit-env')
+ assert.equal(unitEnv.resourceGroups.length, 1)
+ assert.deepEqual(
+ (await resolveInput(unitEnv.resourceGroups[0].resources)).map((resource: any) => resource.id),
+ ['converge-unit-environment', 'configure-thp'],
+ )
+
+ resources.clear()
+ provider({
+ ...requestFor(),
+ environment: runnerEnv === undefined ? {} : { BOXLITE_RUNNER_ENV: runnerEnv },
+ deploySecretFetch: secretFetch,
+ })
+ const enrolledBinary = resources.get('RunnerBinary')
+ assert.ok(enrolledBinary)
+ const enrolled = enrolledBinary.args.osPolicies.find((policy: any) => policy.id === 'runner-enrolled-binary')
+ assert.equal(enrolled.resourceGroups.length, 1)
+ assert.deepEqual(
+ (await resolveInput(enrolled.resourceGroups[0].resources)).map((resource: any) => resource.id),
+ ['converge-unit-environment', 'swap-binary', 'configure-thp'],
+ )
+ }
+
+ resources.clear()
+ provider({
+ ...requestFor(),
+ environment: { BOXLITE_RUNNER_ENV: '{"KRUN_USE_THP":"1"}' },
+ })
+ const optInAssignment = resources.get('RunnerBinary')
+ assert.ok(optInAssignment)
+ const optInUnitEnv = optInAssignment.args.osPolicies.find((policy: any) => policy.id === 'runner-unit-env')
+ assert.equal(optInUnitEnv.resourceGroups.length, 1)
+ assert.deepEqual(
+ (await resolveInput(optInUnitEnv.resourceGroups[0].resources)).map((resource: any) => resource.id),
+ ['configure-thp', 'converge-unit-environment'],
+ )
+
+ resources.clear()
+ provider({
+ ...requestFor(),
+ environment: { BOXLITE_RUNNER_ENV: '{"KRUN_USE_THP":"1"}' },
+ deploySecretFetch: secretFetch,
+ })
+ const optInEnrolledAssignment = resources.get('RunnerBinary')
+ assert.ok(optInEnrolledAssignment)
+ const optInEnrolled = optInEnrolledAssignment.args.osPolicies.find(
+ (policy: any) => policy.id === 'runner-enrolled-binary',
+ )
+ assert.equal(optInEnrolled.resourceGroups.length, 1)
+ assert.deepEqual(
+ (await resolveInput(optInEnrolled.resourceGroups[0].resources)).map((resource: any) => resource.id),
+ ['configure-thp', 'converge-unit-environment', 'swap-binary'],
+ )
+
+ for (const invalidEnv of ['{', 'null', '[]', '{"KRUN_USE_THP":1}']) {
+ resources.clear()
+ await assert.rejects(
+ async () => {
+ provider({
+ ...requestFor(),
+ environment: { BOXLITE_RUNNER_ENV: invalidEnv },
+ })
+ const assignment = resources.get('RunnerBinary')
+ assert.ok(assignment)
+ const unitEnv = assignment.args.osPolicies.find((policy: any) => policy.id === 'runner-unit-env')
+ await resolveInput(unitEnv.resourceGroups[0].resources)
+ },
+ /BOXLITE_RUNNER_ENV/,
+ )
+ }
+})
+
+test('GCP boot installs THP before starting the runner while AWS boot omits THP setup', (t) => {
+ const { resources, output } = captureResources(t)
+ const gcp = gcpProvider(output)
+ gcp(requestFor())
+ const gcpHost = resources.get('Runner')
+ assert.ok(gcpHost)
+ const gcpScript: string = gcpHost.args.metadataStartupScript.value
+ const installThp = gcpScript.indexOf('\ninstall_runner_thp\n')
+ assert.ok(installThp >= 0, 'GCP boot script did not install host THP policy')
+ assert.ok(installThp < gcpScript.indexOf('systemctl start boxlite-runner'))
+
+ resources.clear()
+ const aws = awsRunnerProvider({
+ ...common,
+ region: 'us-east-1',
+ placement: { cloud: 'aws', exposure: 'egress-only-public', subnets: ['subnet'], securityGroups: [] } as any,
+ })
+ aws(requestFor())
+ const awsHost = resources.get('Runner')
+ assert.ok(awsHost)
+ const awsUserData = Buffer.from(awsHost.args.userDataBase64.value, 'base64').toString('utf8')
+ assert.doesNotMatch(awsUserData, /install_runner_thp/)
+ assert.doesNotMatch(awsUserData, /boxlite-thp\.conf/)
+})
+
+test('GCP derives THP step ordering when BOXLITE_RUNNER_ENV is a string, Pulumi Output, or Promise', async (t) => {
+ const { resources, output } = captureResources(t)
+ const provider = gcpProvider(output)
+ const secretFetch = () => ({ url: output('https://fetch.example.test'), enrolledInstanceIds: output(['12345']) })
+
+ for (const [kind, wrap] of [
+ ['string', (value: string) => value],
+ ['pulumi.output', (value: string) => pulumi.output(value) as unknown as $util.Input<string>],
+ ['Promise', (value: string) => Promise.resolve(value)],
+ ] as const) {
+ for (const [runnerEnv, deploySecretFetch, policyId, expected] of [
+ ['{"KRUN_USE_THP":"1"}', false, 'runner-unit-env', ['configure-thp', 'converge-unit-environment']],
+ ['{"KRUN_USE_THP":"1"}', true, 'runner-enrolled-binary', ['configure-thp', 'converge-unit-environment', 'swap-binary']],
+ ['{"KRUN_USE_THP":"0"}', false, 'runner-unit-env', ['converge-unit-environment', 'configure-thp']],
+ ['{"KRUN_USE_THP":"0"}', true, 'runner-enrolled-binary', ['converge-unit-environment', 'swap-binary', 'configure-thp']],
+ ] as const) {
+ resources.clear()
+ provider({
+ ...requestFor(),
+ environment: { BOXLITE_RUNNER_ENV: wrap(runnerEnv) },
+ ...(deploySecretFetch ? { deploySecretFetch: secretFetch } : {}),
+ })
+ const assignment = resources.get('RunnerBinary')
+ assert.ok(assignment, `${kind} failed to create RunnerBinary`)
+ const policy = assignment.args.osPolicies.find((entry: any) => entry.id === policyId)
+ assert.ok(policy, `${kind} missing policy ${policyId}`)
+ const resolvedResources = await resolveInput(policy.resourceGroups[0].resources)
+ assert.deepEqual(
+ resolvedResources.map((resource: any) => resource.id),
+ expected,
+ `unexpected step order for ${kind} (${runnerEnv}, enrolled=${deploySecretFetch})`,
+ )
+ }
+
+ for (const invalidEnv of ['{', 'null', '[]', '{"KRUN_USE_THP":1}']) {
+ resources.clear()
+ await assert.rejects(
+ async () => {
+ provider({
+ ...requestFor(),
+ environment: { BOXLITE_RUNNER_ENV: wrap(invalidEnv) },
+ })
+ const assignment = resources.get('RunnerBinary')
+ assert.ok(assignment, `${kind} invalid env failed before creating RunnerBinary`)
+ const unitEnv = assignment.args.osPolicies.find((entry: any) => entry.id === 'runner-unit-env')
+ await resolveInput(unitEnv.resourceGroups[0].resources)
+ },
+ /BOXLITE_RUNNER_ENV/,
+ `expected BOXLITE_RUNNER_ENV validation error for ${kind}: ${invalidEnv}`,
+ )
+ }
+ }
+})
diff --git a/apps/infra/mdeploy/test/runner-thp.test.ts b/apps/infra/mdeploy/test/runner-thp.test.ts
new file mode 100644
index 000000000..622980b32
--- /dev/null
+++ b/apps/infra/mdeploy/test/runner-thp.test.ts
@@ -0,0 +1,340 @@
+import assert from 'node:assert/strict'
+import { spawnSync } from 'node:child_process'
+import {
+ chmodSync,
+ lstatSync,
+ mkdirSync,
+ mkdtempSync,
+ readdirSync,
+ readFileSync,
+ rmSync,
+ statSync,
+ symlinkSync,
+ writeFileSync,
+} from 'node:fs'
+import { tmpdir } from 'node:os'
+import { dirname, join } from 'node:path'
+import test, { type TestContext } from 'node:test'
+import { CLOUD_RUNNER_THP, thpDeployment } from '../stack/runner-thp.ts'
+
+const setupFixture = (t: TestContext, options?: { enabled?: string; defrag?: string; tmpfiles?: string }) => {
+ const root = mkdtempSync(join(tmpdir(), 'runner-thp-'))
+ t.after(() => rmSync(root, { recursive: true, force: true }))
+ const bin = join(root, 'bin')
+ mkdirSync(bin, { recursive: true })
+ const eventsPath = join(root, 'events')
+ writeFileSync(
+ join(bin, 'systemctl'),
+ `#!/bin/bash
+echo "$*" >> "$BOXLITE_THP_EVENTS"
+if [ "$1" = is-enabled ] && [ -e "$BOXLITE_THP_TEST_ROOT/disabled" ]; then exit 1; fi
+if [ "$1" = is-active ] && [ -e "$BOXLITE_THP_TEST_ROOT/inactive" ]; then exit 3; fi
+exit 0
+`,
+ { mode: 0o755 },
+ )
+ const sysfs = join(root, 'sysfs')
+ mkdirSync(sysfs, { recursive: true })
+ const enabledPath = join(sysfs, 'enabled')
+ const defragPath = join(sysfs, 'defrag')
+ const tmpfilesPath = join(root, 'etc', 'tmpfiles.d', 'boxlite-thp.conf')
+
+ if (options?.enabled !== undefined) {
+ writeFileSync(enabledPath, options.enabled)
+ }
+ if (options?.defrag !== undefined) {
+ writeFileSync(defragPath, options.defrag)
+ }
+ if (options?.tmpfiles !== undefined) {
+ mkdirSync(join(root, 'etc', 'tmpfiles.d'), { recursive: true })
+ writeFileSync(tmpfilesPath, options.tmpfiles)
+ chmodSync(tmpfilesPath, 0o644)
+ }
+
+ return { root, bin, sysfs, enabledPath, defragPath, tmpfilesPath, eventsPath }
+}
+
+const runScript = (script: string, fixture: ReturnType<typeof setupFixture>) =>
+ spawnSync('bash', ['-c', script], {
+ encoding: 'utf8',
+ env: {
+ ...process.env,
+ PATH: `${fixture.bin}:${process.env.PATH ?? '/usr/bin:/bin'}`,
+ BOXLITE_THP_TEST_ROOT: fixture.root,
+ BOXLITE_THP_EVENTS: fixture.eventsPath,
+ BOXLITE_THP_SYSFS_DIR: fixture.sysfs,
+ BOXLITE_THP_TMPFILES_PATH: fixture.tmpfilesPath,
+ },
+ })
+
+test('thpDeployment validates enabled and defrag policies', () => {
+ assert.throws(
+ () => thpDeployment({ enabled: 'invalid' as any, defrag: 'defer' }),
+ /THP enabled policy/,
+ )
+ assert.throws(
+ () => thpDeployment({ enabled: 'madvise', defrag: 'invalid' as any }),
+ /THP defrag policy/,
+ )
+ assert.equal(CLOUD_RUNNER_THP.enabled, 'madvise')
+ assert.equal(CLOUD_RUNNER_THP.defrag, 'defer')
+})
+
+test('rendered THP scripts pass bash syntax check and do not restart systemd runner', () => {
+ const thp = thpDeployment()
+ for (const script of [thp.install, thp.policyScripts.validate, thp.policyScripts.enforce]) {
+ const check = spawnSync('bash', ['-n'], { input: script, encoding: 'utf8' })
+ assert.equal(check.status, 0, check.stderr)
+ assert.doesNotMatch(script, /systemctl\s+(restart|reload|daemon-reload|start|stop)/)
+ }
+})
+
+test('install converges tmpfiles.d (0644) and sysfs values and is idempotent', (t) => {
+ const fixture = setupFixture(t, {
+ enabled: '[always] madvise never\n',
+ defrag: 'always defer defer+madvise [madvise] never\n',
+ })
+ const thp = thpDeployment()
+
+ const first = runScript(`set -euo pipefail\n${thp.install}`, fixture)
+ assert.equal(first.status, 0, first.stderr)
+ assert.equal(
+ readFileSync(fixture.tmpfilesPath, 'utf8'),
+ 'w /sys/kernel/mm/transparent_hugepage/enabled - - - - madvise\nw /sys/kernel/mm/transparent_hugepage/defrag - - - - defer\n',
+ )
+ assert.equal(statSync(fixture.tmpfilesPath).mode & 0o777, 0o644)
+ assert.equal(readFileSync(fixture.enabledPath, 'utf8'), 'madvise\n')
+ assert.equal(readFileSync(fixture.defragPath, 'utf8'), 'defer\n')
+
+ writeFileSync(fixture.enabledPath, 'always [madvise] never\n')
+ writeFileSync(fixture.defragPath, 'always [defer] defer+madvise madvise never\n')
+ chmodSync(fixture.enabledPath, 0o444)
+ chmodSync(fixture.defragPath, 0o444)
+
+ const second = runScript(`set -euo pipefail\n${thp.install}`, fixture)
+ assert.equal(second.status, 0, second.stderr)
+})
+
+test('install and enforce write tmpfiles.d (0644) and apply sysfs values on drift', (t) => {
+ const fixture = setupFixture(t, {
+ enabled: '[always] madvise never\n',
+ defrag: 'always defer defer+madvise [madvise] never\n',
+ })
+ const thp = thpDeployment()
+
+ const validateBefore = runScript(thp.policyScripts.validate, fixture)
+ assert.equal(validateBefore.status, 101)
+
+ const enforce = runScript(thp.policyScripts.enforce, fixture)
+ assert.equal(enforce.status, 100, enforce.stderr)
+ assert.equal(
+ readFileSync(fixture.tmpfilesPath, 'utf8'),
+ 'w /sys/kernel/mm/transparent_hugepage/enabled - - - - madvise\nw /sys/kernel/mm/transparent_hugepage/defrag - - - - defer\n',
+ )
+ assert.equal(statSync(fixture.tmpfilesPath).mode & 0o777, 0o644)
+ assert.equal(readFileSync(fixture.enabledPath, 'utf8'), 'madvise\n')
+ assert.equal(readFileSync(fixture.defragPath, 'utf8'), 'defer\n')
+})
+
+test('validate and enforce are idempotent no-ops when tmpfiles.d and sysfs match', (t) => {
+ const fixture = setupFixture(t, {
+ enabled: 'always [madvise] never\n',
+ defrag: 'always [defer] defer+madvise madvise never\n',
+ tmpfiles:
+ 'w /sys/kernel/mm/transparent_hugepage/enabled - - - - madvise\nw /sys/kernel/mm/transparent_hugepage/defrag - - - - defer\n',
+ })
+ chmodSync(fixture.enabledPath, 0o444)
+ chmodSync(fixture.defragPath, 0o444)
+ const thp = thpDeployment()
+
+ const validate = runScript(thp.policyScripts.validate, fixture)
+ assert.equal(validate.status, 100, validate.stderr)
+
+ const policyEnforce = runScript(thp.policyScripts.enforce, fixture)
+ assert.equal(policyEnforce.status, 100, policyEnforce.stderr)
+ assert.match(policyEnforce.stdout, /runner THP already current/)
+})
+
+test('install and enforce fail explicitly when sysfs paths are missing', (t) => {
+ const fixture = setupFixture(t, {
+ enabled: '[always] madvise never\n',
+ })
+ const thp = thpDeployment()
+
+ const install = runScript(`set -euo pipefail\n${thp.install}`, fixture)
+ assert.notEqual(install.status, 0)
+ assert.match(install.stderr, /missing THP sysfs path/)
+
+ const policyEnforce = runScript(thp.policyScripts.enforce, fixture)
+ assert.equal(policyEnforce.status, 101)
+})
+
+test('defer+madvise literal match succeeds without regex quantifier confusion', (t) => {
+ const fixture = setupFixture(t, {
+ enabled: 'always [madvise] never\n',
+ defrag: 'always defer [defer+madvise] madvise never\n',
+ tmpfiles:
+ 'w /sys/kernel/mm/transparent_hugepage/enabled - - - - madvise\nw /sys/kernel/mm/transparent_hugepage/defrag - - - - defer+madvise\n',
+ })
+ const thp = thpDeployment({ enabled: 'madvise', defrag: 'defer+madvise' })
+ assert.equal(runScript(thp.policyScripts.validate, fixture).status, 100)
+ assert.equal(runScript(thp.policyScripts.enforce, fixture).status, 100)
+})
+
+test('bootstrapping guard skips disabled+inactive host but converges disabled+active host', (t) => {
+ const bootstrap = setupFixture(t, {
+ enabled: '[always] madvise never\n',
+ defrag: 'always defer [madvise] never\n',
+ })
+ writeFileSync(join(bootstrap.root, 'disabled'), '')
+ writeFileSync(join(bootstrap.root, 'inactive'), '')
+ const thp = thpDeployment()
+
+ assert.equal(runScript(thp.policyScripts.validate, bootstrap).status, 100)
+ assert.equal(runScript(thp.policyScripts.enforce, bootstrap).status, 100)
+ assert.equal(readFileSync(bootstrap.enabledPath, 'utf8'), '[always] madvise never\n')
+
+ const activeDisabled = setupFixture(t, {
+ enabled: '[always] madvise never\n',
+ defrag: 'always defer [madvise] never\n',
+ })
+ writeFileSync(join(activeDisabled.root, 'disabled'), '')
+ assert.equal(runScript(thp.policyScripts.validate, activeDisabled).status, 101)
+ assert.equal(runScript(thp.policyScripts.enforce, activeDisabled).status, 100)
+ assert.equal(readFileSync(activeDisabled.enabledPath, 'utf8'), 'madvise\n')
+ assert.equal(readFileSync(activeDisabled.defragPath, 'utf8'), 'defer\n')
+})
+
+test('enforce fails explicitly when sysfs path is not writable', (t) => {
+ if (process.getuid?.() === 0) {
+ t.skip('root bypasses 0444 write permission checks')
+ return
+ }
+ const fixture = setupFixture(t, {
+ enabled: '[always] madvise never\n',
+ defrag: 'always [defer] madvise never\n',
+ })
+ chmodSync(fixture.enabledPath, 0o444)
+ const thp = thpDeployment()
+ const res = runScript(thp.policyScripts.enforce, fixture)
+ assert.equal(res.status, 101)
+ assert.match(res.stderr, /not writable/)
+})
+
+test('apply_runner_thp_value fails when bracketed sysfs readback does not select target value', (t) => {
+ const fixture = setupFixture(t, {
+ enabled: '[always] madvise never\n',
+ defrag: 'always [defer] madvise never\n',
+ })
+ writeFileSync(
+ join(fixture.bin, 'cat'),
+ `#!/bin/bash
+if [ "$1" = "${fixture.enabledPath}" ]; then
+ echo "always madvise [never]"
+ exit 0
+fi
+exec /bin/cat "$@"
+`,
+ { mode: 0o755 },
+ )
+ const thp = thpDeployment()
+ const res = runScript(thp.policyScripts.enforce, fixture)
+ assert.equal(res.status, 101)
+ assert.match(res.stderr, /did not select \[madvise\]/)
+})
+
+test('validate detects tmpfiles.d mode drift (0666) and enforce/install restore 0644', (t) => {
+ const fixture = setupFixture(t, {
+ enabled: 'always [madvise] never\n',
+ defrag: 'always [defer] defer+madvise madvise never\n',
+ tmpfiles:
+ 'w /sys/kernel/mm/transparent_hugepage/enabled - - - - madvise\nw /sys/kernel/mm/transparent_hugepage/defrag - - - - defer\n',
+ })
+ const thp = thpDeployment()
+
+ assert.equal(runScript(thp.policyScripts.validate, fixture).status, 100)
+
+ chmodSync(fixture.tmpfilesPath, 0o666)
+ assert.equal(runScript(thp.policyScripts.validate, fixture).status, 101)
+ assert.equal(runScript(thp.policyScripts.enforce, fixture).status, 100)
+ assert.equal(statSync(fixture.tmpfilesPath).mode & 0o777, 0o644)
+ assert.equal(runScript(thp.policyScripts.validate, fixture).status, 100)
+
+ chmodSync(fixture.tmpfilesPath, 0o666)
+ assert.equal(runScript(`set -euo pipefail\n${thp.install}`, fixture).status, 0)
+ assert.equal(statSync(fixture.tmpfilesPath).mode & 0o777, 0o644)
+})
+
+test('validate rejects symlinked tmpfiles.d and enforce replaces it with a regular 0644 file', (t) => {
+ const fixture = setupFixture(t, {
+ enabled: 'always [madvise] never\n',
+ defrag: 'always [defer] defer+madvise madvise never\n',
+ })
+ const target = join(fixture.root, 'target.conf')
+ writeFileSync(
+ target,
+ 'w /sys/kernel/mm/transparent_hugepage/enabled - - - - madvise\nw /sys/kernel/mm/transparent_hugepage/defrag - - - - defer\n',
+ )
+ chmodSync(target, 0o644)
+ mkdirSync(join(fixture.root, 'etc', 'tmpfiles.d'), { recursive: true })
+ symlinkSync(target, fixture.tmpfilesPath)
+
+ const thp = thpDeployment()
+ assert.equal(runScript(thp.policyScripts.validate, fixture).status, 101)
+ assert.equal(runScript(thp.policyScripts.enforce, fixture).status, 100)
+ assert.equal(statSync(fixture.tmpfilesPath).mode & 0o777, 0o644)
+ assert.equal(runScript(thp.policyScripts.validate, fixture).status, 100)
+})
+
+test('validate rejects symlink-to-directory tmpfiles.d and enforce/install replace the symlink without writing inside the directory', (t) => {
+ const fixture = setupFixture(t, {
+ enabled: 'always [madvise] never\n',
+ defrag: 'always [defer] defer+madvise madvise never\n',
+ })
+ const targetDir = join(fixture.root, 'target-dir')
+ mkdirSync(targetDir, { recursive: true })
+ mkdirSync(dirname(fixture.tmpfilesPath), { recursive: true })
+ symlinkSync(targetDir, fixture.tmpfilesPath)
+
+ const thp = thpDeployment()
+ assert.equal(runScript(thp.policyScripts.validate, fixture).status, 101)
+ const enforce = runScript(thp.policyScripts.enforce, fixture)
+ assert.equal(enforce.status, 100, enforce.stderr)
+ assert.equal(lstatSync(fixture.tmpfilesPath).isSymbolicLink(), false)
+ assert.equal(lstatSync(fixture.tmpfilesPath).isFile(), true)
+ assert.equal(statSync(fixture.tmpfilesPath).mode & 0o777, 0o644)
+ assert.deepEqual(readdirSync(targetDir), [])
+ assert.equal(runScript(thp.policyScripts.validate, fixture).status, 100)
+
+ rmSync(fixture.tmpfilesPath)
+ symlinkSync(targetDir, fixture.tmpfilesPath)
+ const install = runScript(`set -euo pipefail\n${thp.install}`, fixture)
+ assert.equal(install.status, 0, install.stderr)
+ assert.equal(lstatSync(fixture.tmpfilesPath).isSymbolicLink(), false)
+ assert.equal(lstatSync(fixture.tmpfilesPath).isFile(), true)
+ assert.equal(statSync(fixture.tmpfilesPath).mode & 0o777, 0o644)
+ assert.deepEqual(readdirSync(targetDir), [])
+})
+
+test('validate, enforce, and install fail explicitly when tmpfiles.d path is a real directory without leaving temp files', (t) => {
+ const fixture = setupFixture(t, {
+ enabled: 'always [madvise] never\n',
+ defrag: 'always [defer] defer+madvise madvise never\n',
+ })
+ mkdirSync(fixture.tmpfilesPath, { recursive: true })
+
+ const thp = thpDeployment()
+ assert.equal(runScript(thp.policyScripts.validate, fixture).status, 101)
+
+ const enforce = runScript(thp.policyScripts.enforce, fixture)
+ assert.equal(enforce.status, 101)
+ assert.match(enforce.stderr, /is a directory/)
+
+ const install = runScript(`set -euo pipefail\n${thp.install}`, fixture)
+ assert.notEqual(install.status, 0)
+ assert.match(install.stderr, /is a directory/)
+
+ assert.equal(lstatSync(fixture.tmpfilesPath).isDirectory(), true)
+ assert.deepEqual(readdirSync(fixture.tmpfilesPath), [])
+ assert.deepEqual(readdirSync(dirname(fixture.tmpfilesPath)), ['boxlite-thp.conf'])
+})