Skip to content

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

10.4 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (c) 2026 BoxLite AI
import assert from 'node:assert/strict'
import { chownSync, globSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
import { spawnSync } from 'node:child_process'
import { data, Evaluator, Lexer, Parser } from '@actions/expressions'
import { createRequire } from 'node:module'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import test from 'node:test'
import { load } from 'js-yaml'
import { buildKey, planBuilds } from './release-build-plan.mjs'
import { saveFiles } from '../../../.github/actions/release-build-cache/files.mjs'

const root = new URL('../../../', import.meta.url)
const actionDir = fileURLToPath(new URL('.github/actions/release-build-cache/', root))
const action = load(readFileSync(join(actionDir, 'action.yml'), 'utf8'))
const workflow = load(readFileSync(new URL('.github/workflows/build-wheels.yml', root), 'utf8'))
const platforms = JSON.parse(readFileSync(new URL('.github/ci-config.json', root))).platforms
const scope = buildKey('v0.16.1', 'a'.repeat(40), 10)

async function runScript(id, env) {
  const script = action.runs.steps.find(step => step.id === id).with.script
  const outputs = {}
  const execute = new Function('core', 'process', 'require', 'return (async () => {' + script + '})()')
  await execute({ setOutput: (name, value) => { outputs[name] = value } }, { env }, createRequire(import.meta.url))
  return outputs
}

test('wheel cache receipts survive save, retry planning and verified restore for every platform and literal label', async t => {
  const steps = workflow.jobs.build_wheels.steps
  const unitFor = (id, platform) => steps.find(step => step.id === id).with.unit
    .replace(/\$\{\{ matrix\.(\w+) \}\}/g, (_, field) => platform[field])
  const units = platforms.map(platform => {
    assert.equal(unitFor('cache', platform), unitFor('saved', platform))
    return unitFor('saved', platform)
  })
  assert.equal(new Set(units).size, platforms.length)
  for (const unit of new Set(['wheels-ubuntu-24.04-arm', ...units, 'wheels-平台 +_[]?,(v2)'])) {
    const dir = mkdtempSync(join(tmpdir(), 'wheel-cache-'))
    t.after(() => rmSync(dir, { recursive: true, force: true }))
    const output = join(dir, 'wheelhouse')
    mkdirSync(output)
    writeFileSync(join(output, 'boxlite.whl'), unit)
    writeFileSync(join(output, 'producer.json'), '{}')
    const env = { ACTION_DIR: actionDir, GITHUB_WORKSPACE: dir, UNIT: unit, PLAN: JSON.stringify({key: scope}), CHECK_ID: '123', GITHUB_RUN_ATTEMPT: '1', MANIFEST: '' }
    const saved = await runScript('pack', env)
    const job = { name: 'Build wheels', run_attempt: 1, check_run_url: 'checks/123', conclusion: 'success',
      steps: [{ name: 'Build cache receipt ' + saved.record, conclusion: 'success' }] }
    const source = planBuilds({ key: scope, attempt: 2, jobs: [job] }).sources[unit]
    assert.match(saved.key, /^release-output-v2-[a-f0-9]{64}$/)
    assert.equal(source.key, saved.key)
    rmSync(output, { recursive: true })
    const restored = await runScript('verify', { ...env, RECEIPT: source.receipt })
    assert.equal(restored.hit, true)
    assert.equal(readFileSync(join(output, 'boxlite.whl'), 'utf8'), unit)
  }
})

test('cache inventory matches target punctuation literally and rejects path components', async t => {
  const dir = mkdtempSync(join(tmpdir(), 'release-cache-path-'))
  t.after(() => rmSync(dir, { recursive: true, force: true }))
  writeFileSync(join(dir, 'producer.json'), '{}')
  const target = 'linux.[ab]+_x64'
  const name = 'boxlite-c-v1-' + target + '.tar.gz'
  writeFileSync(join(dir, name), 'literal')
  writeFileSync(join(dir, 'boxlite-c-v1-linux.a+_x64.tar.gz'), 'other target')
  await saveFiles({ root: dir, unit: 'c-' + target })
  const { files } = JSON.parse(readFileSync(join(dir, '.release-build-cache/receipt.json')))
  assert.deepEqual(Object.keys(files).sort(), [name, 'producer.json'])
  for (const suffix of ['', '.', '..', 'x/y', 'x\\y', 'x\ny']) {
    await assert.rejects(saveFiles({ root: dir, unit: 'wheels-' + suffix }), /cache unit/i)
  }
})

function expression(input, context) {
  const ast = new Parser(new Lexer(input.replace(/^\$\{\{\s*|\s*\}\}$/g, '')).lex().tokens, Object.keys(context), []).parse()
  return new Evaluator(ast, JSON.parse(JSON.stringify(context), data.reviver)).evaluate().coerceString()
}

test('restore selects the exact case-sensitive unit from the actual retry plan', async () => {
  const units = ['wheels-linux-A', 'wheels-linux-a']
  const jobs = units.map((unit, i) => {
    const check = String(123 + i), receipt = String(3 + i).repeat(64)
    const record = JSON.stringify({ scope, unit, attempt: 1, check, receipt, manifest: '' })
    return { name: unit, conclusion: 'success', run_attempt: 1, check_run_url: 'checks/' + check,
      steps: [{ name: 'Build cache receipt ' + record, conclusion: 'success' }] }
  })
  const plan = planBuilds({ key: scope, attempt: 2, jobs })
  const restore = action.runs.steps.find(step => step.id === 'restore')
  const select = action.runs.steps.find(step => step.id === 'select')
  assert.equal(select.env.PLAN, '${{ inputs.plan }}')
  assert.equal(select.env.UNIT, '${{ inputs.unit }}')
  for (const unit of [...units, 'wheels-LINUX-a']) {
    const inputs = { mode: 'restore', plan: JSON.stringify(plan), unit }
    const context = { inputs, github: { run_attempt: 2 }, steps: {} }
    context.steps.select = { outputs: await runScript('select', { PLAN: inputs.plan, UNIT: unit, GITHUB_RUN_ATTEMPT: '2' }) }
    assert.equal(expression(restore.with.key, context), plan.sources[unit]?.key ?? '', unit)
    assert.equal(expression(restore.if, context), String(Object.hasOwn(plan.sources, unit)))
    for (const [id, field] of [['verify', 'receipt'], ['registry', 'manifest']]) {
      const step = action.runs.steps.find(item => item.id === id)
      assert.equal(expression(step.env[field.toUpperCase()], context), plan.sources[unit]?.[field] ?? '')
    }
  }
  for (const [attempt, sources] of [[3, plan.sources], [1, {}]]) {
    const selected = await runScript('select', { PLAN: JSON.stringify({ ...plan, sources }), UNIT: units[0], GITHUB_RUN_ATTEMPT: String(attempt) })
    assert.deepEqual(selected, {}, 'a stale plan cannot restore a previous build')
  }
})

test('platform artifact uploads select the literal archive with its required origin', async t => {
  const target = 'linux.[ab]+_x64'
  const cases = [
    ['c', 'Upload artifact', 'boxlite-c-v1.2.3-' + target + '.tar.gz', true],
    ['runtime', 'Upload CLI artifact', 'boxlite-cli-v1.2.3-' + target + '.tar.gz', true],
    ['node', 'Upload artifacts', 'sdks/node/artifacts-' + target + '.tar', false],
  ]
  for (const [component, stepName, archive, origin] of cases) {
    await t.test(stepName + ' in ' + component, () => {
      const dir = mkdtempSync(join(tmpdir(), 'release-upload-'))
      t.after(() => rmSync(dir, { recursive: true, force: true }))
      mkdirSync(join(dir, 'sdks/node'), { recursive: true })
      writeFileSync(join(dir, archive), 'archive')
      writeFileSync(join(dir, 'producer.json'), '{}')
      writeFileSync(join(dir, 'Cargo.toml'), 'version = "1.2.3"\n')
      const job = load(readFileSync(new URL('.github/workflows/build-' + component + '.yml', root))).jobs.build
      const index = job.steps.findIndex(step => step.name === stepName)
      const upload = job.steps[index]
      const stage = job.steps[index - 1]
      const env = { ...process.env, TARGET: target, RUST_TARGET: target, REQUIRE_ORIGIN: 'true' }
      const prepare = () => spawnSync('bash', ['-e', '-c', stage.run], { cwd: dir, env, encoding: 'utf8' })
      assert.match(stage.name, /^Stage archive for /)
      const result = prepare()
      assert.equal(result.status, 0, result.stderr)
      const paths = upload.with.path.trim().replace(/\$\{\{ matrix\.(?:rust_)?target \}\}/g, target).split('\n')
      const files = paths.flatMap(pattern => globSync(pattern, { cwd: dir })).flatMap(item =>
        statSync(join(dir, item)).isDirectory() ? readdirSync(join(dir, item)) : [item.split('/').pop()])
      assert.deepEqual(files.sort(), [archive.split('/').pop(), ...(origin ? ['producer.json'] : [])].sort())
      rmSync(join(dir, paths[0]), { recursive: true })
      if (origin) {
        rmSync(join(dir, 'producer.json'))
        assert.notEqual(prepare().status, 0, 'a missing required origin must stop the upload')
        rmSync(join(dir, paths[0]), { recursive: true })
        if (component === 'runtime') {
          env.REQUIRE_ORIGIN = 'false'
          assert.equal(prepare().status, 0, 'standalone CLI archives can omit origin')
          rmSync(join(dir, paths[0]), { recursive: true })
        }
        writeFileSync(join(dir, 'producer.json'), '{}')
      }
      rmSync(join(dir, archive))
      assert.notEqual(prepare().status, 0, 'a missing archive must stop the upload')
    })
  }
})

test('runtime uploads the single readable archive directly from its build location', t => {
  const dir = mkdtempSync(join(tmpdir(), 'runtime-upload-'))
  t.after(() => rmSync(dir, { recursive: true, force: true }))
  const steps = load(readFileSync(new URL('.github/workflows/build-runtime.yml', root))).jobs.build.steps
  const index = steps.findIndex(step => step.name === 'Upload runtime artifact')
  const upload = steps[index].with
  const target = 'linux.[ab]+_arm64'
  const archive = 'boxlite-runtime-v0.16.1-' + target + '.tar.gz'
  // manylinux creates the archive as root. The host runner owns the workspace.
  const runner = process.platform === 'linux' && process.getuid() === 0 ? { uid: 65534, gid: 65534 } : {}
  if (runner.uid !== undefined) chownSync(dir, runner.uid, runner.gid)
  writeFileSync(join(dir, archive), 'runtime', { mode: 0o644 })
  writeFileSync(join(dir, 'producer.json'), '{}')
  const verify = () => spawnSync('bash', ['-e', '-c', steps[index - 1].run], {
    cwd: dir, env: { ...process.env, TARGET: target }, ...runner, encoding: 'utf8',
  })
  const result = verify()
  assert.equal(result.status, 0, result.stderr)
  assert.deepEqual(globSync(upload.path, { cwd: dir }), [archive])
  assert.deepEqual(readdirSync(dir).sort(), [archive, 'producer.json'], 'upload must use the original file')
  const other = 'boxlite-runtime-v0.16.1-linux.a+_arm64.tar.gz'
  writeFileSync(join(dir, other), 'other')
  assert.notEqual(verify().status, 0, 'ambiguous upload')
  rmSync(join(dir, archive))
  assert.notEqual(verify().status, 0, 'wrong target')
  rmSync(join(dir, other))
  assert.notEqual(verify().status, 0, 'missing archive')
})