Skip to content

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

13.4 KB
Raw Blame
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'])
})