Skip to content

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

14.2 KB
Raw Blame
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 }>()
  const unwrap = (value: any): any => value?.value ?? value
  const output = (value: any): any => ({ value, apply: (fn: (value: any) => any) => output(fn(value)) })
  class Resource {
    [key: string]: any
    constructor(name: string, args: any, options: any = {}) {
      resources.set(name, { args, options })
      Object.assign(this, args, { id: output(name), name: output(name), arn: output(`${name}-arn`) })
    }
  }
  const constructors = new Proxy(
    {},
    {
      get: (_, name) => (name === 'getAmiOutput' ? () => ({ id: output('ami') }) : Resource),
    },
  )
  const globals = {
    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[]) =>
      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)
    Object.defineProperty(globalThis, key, { configurable: true, value })
    t.after(() =>
      previous ? Object.defineProperty(globalThis, key, previous) : Reflect.deleteProperty(globalThis, key),
    )
  }
  return { resources, output }
}

const requestFor = (size: RunnerRequest['size'] = 'large'): RunnerRequest => ({
  size,
  rootDiskGb: 100,
  nestedVirtualization: true,
  fleet: [
    {
      slot: { resourceName: 'Runner', nameTag: 'boxlite-app-dev-runner', controlPlaneRunnerName: 'default' },
      token: 'runner-token',
    },
  ],
  binary: {
    source: 'release',
    identity: '0.11.0',
    transport: 'https',
    tarballUrl: 'https://example.invalid/runner.tar.gz',
    checksumUrl: 'https://example.invalid/runner.tar.gz.sha256',
    tarballName: 'runner.tar.gz',
  },
  apiUrl: 'https://api.example.invalid',
  otlpUrl: 'http://otel:4317',
  registryProxyHost: null,
  checkpointBucket: null,
  environment: {},
  secrets: {},
})

const common = { artifactsBucket: 'artifacts', adminApiKey: 'admin', regionId: 'region', dependsOn: [] }

const gcpProvider = (output: (value: any) => any) =>
  gcpRunnerProvider({
    ...common,
    project: 'project',
    zone: 'us-east5-a',
    volumePrefix: 'boxlite-volume',
    placement: { cloud: 'gcp', subnetwork: output('subnet'), serviceAccount: output('[email protected]') } as any,
  })

test('GCP checkpoint object access names only the configured archive bucket', (t) => {
  const { resources, output } = captureResources(t)
  const provider = gcpProvider(output)
  const bucket = output('boxlite-app-dev-checkpoints')
  provider({ ...requestFor(), checkpointBucket: bucket })

  const grant = resources.get('RunnerCheckpointObjects')!
  assert.ok(grant)
  assert.equal(grant.args.bucket, bucket)
  assert.equal(grant.args.role, 'roles/storage.objectUser')
  assert.equal(grant.args.member.value, 'serviceAccount:[email protected]')
  assert.equal('project' in grant.args, false)

  resources.clear()
  provider(requestFor())
  assert.equal(resources.has('RunnerCheckpointObjects'), false)
})

test('GCP keeps existing machine types while supplying the requested size for new hosts', (t) => {
  const { resources, output } = captureResources(t)
  const provider = gcpProvider(output)
  for (const [size, machineType] of [
    ['small', 'n4-standard-4'],
    ['large', 'n4-standard-16'],
    ['xlarge', 'n4-standard-32'],
    ['2xlarge', 'n4-standard-64'],
  ] as const) {
    provider(requestFor(size))
    const host = resources.get('Runner')!
    assert.equal(host.args.machineType, machineType)
    assert.deepEqual(host.options.ignoreChanges, ['machineType', 'bootDisk', 'metadataStartupScript', 'attachedDisks'])
    assert.equal(host.args.deletionProtection, true)
    assert.equal(host.options.protect, true)
  }
  provider({ ...requestFor('small'), machineTypes: { small: 'n4-standard-8' } })
  assert.equal(resources.get('Runner')!.args.machineType, 'n4-standard-8')
})

test('GCP honors an explicit data disk capacity and retains the default and disk protections', (t) => {
  const { resources, output } = captureResources(t)
  const provider = gcpProvider(output)
  const request = { ...requestFor(), dataDiskGb: 2048 }
  provider(request)
  const disk = resources.get('RunnerData')!
  assert.equal(disk.args.size, 2048)
  assert.equal(disk.args.provisionedIops, 3600)
  assert.equal(disk.args.provisionedThroughput, 290)
  assert.deepEqual(disk.options.ignoreChanges, ['size', 'provisionedIops', 'provisionedThroughput'])
  assert.equal(disk.options.protect, true)
  for (const size of ['small', 'medium', 'large'] as const) {
    provider(requestFor(size))
    assert.equal(resources.get('RunnerData')!.args.size, 200)
  }
})

test('AWS refuses a GCP data disk size before creating resources', (t) => {
  const { resources } = captureResources(t)
  const provider = awsRunnerProvider({
    ...common,
    region: 'us-east-1',
    placement: { cloud: 'aws', exposure: 'egress-only-public', subnets: ['subnet'], securityGroups: [] } as any,
  })
  const request = { ...requestFor(), dataDiskGb: 2048 }
  assert.throws(() => provider(request), /AWS runners do not support dataDiskGb; configure rootDiskGb instead/)
  assert.equal(resources.size, 0)
  provider({ ...requestFor('2xlarge'), machineTypes: { '2xlarge': 'c8i.12xlarge' } })
  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}`,
      )
    }
  }
})