Skip to content

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

5.8 KB
Raw Blame
/*
 * Copyright 2026 BoxLite AI
 * SPDX-License-Identifier: AGPL-3.0
 */

import { Logger } from '@nestjs/common'
import { QueryFailedError } from 'typeorm'
import { BoxDesiredState } from '../enums/box-desired-state.enum'
import { BoxState } from '../enums/box-state.enum'
import { BoxManager } from './box.manager'
import { BoxDestroyedEvent } from '../events/box-destroyed.event'
import { DONT_SYNC_AGAIN, SYNC_AGAIN } from './box-actions/box.action'

const BOX = {
  id: 'box-1',
  organizationId: 'org-1',
  image: 'quay.io/acme/app:v1',
  state: BoxState.CREATING,
  desiredState: BoxDesiredState.STARTED,
  runnerId: null,
}

function makeManager(startFailure: Error) {
  const boxRepository = {
    findWithCheckpointState: jest.fn().mockResolvedValue({ box: { ...BOX }, checkpointState: null }),
    updateWhere: jest.fn().mockResolvedValue(undefined),
  }
  const imagePullFailureService = { reasonFor: jest.fn().mockResolvedValue('explained') }
  const start = { run: jest.fn().mockRejectedValue(startFailure) }
  const destroy = { run: jest.fn().mockResolvedValue(DONT_SYNC_AGAIN) }
  const runnerService = { getRunnerApiVersion: jest.fn().mockResolvedValue('0') }
  const manager = new BoxManager(
    boxRepository as never,
    runnerService as never,
    {} as never,
    { lock: jest.fn().mockResolvedValue(true), unlock: jest.fn().mockResolvedValue(undefined) } as never,
    start as never,
    {} as never,
    destroy as never,
    imagePullFailureService as never,
    { get: () => undefined } as never,
  )
  return { manager, boxRepository, imagePullFailureService, start, destroy, runnerService }
}

describe('BoxManager sync errors', () => {
  it('does not start a replacement while checkpoint coordination owns the Box', async () => {
    const { manager, boxRepository, start } = makeManager(new Error('must not start'))
    boxRepository.findWithCheckpointState.mockResolvedValue({
      box: { ...BOX },
      checkpointState: { boxId: BOX.id, activeJobId: 'checkpoint-job', sequence: 1 },
    } as never)
    await manager.syncInstanceState(BOX.id)
    expect(start.run).not.toHaveBeenCalled()
    expect(boxRepository.updateWhere).not.toHaveBeenCalled()
  })

  /**
   * A runner that pulls while it answers the create call, rather than in a
   * job, fails the call itself, and this is where that failure is recorded.
   * It gets the same explanation a failed job would.
   */
  it('records the explained reason when starting a box fails', async () => {
    const failure = 'failed to pull manifest [MANIFEST_UNKNOWN]: manifest unknown'
    const { manager, boxRepository, imagePullFailureService } = makeManager(new Error(failure))

    await manager.syncInstanceState(BOX.id)

    expect(imagePullFailureService.reasonFor).toHaveBeenCalledWith(expect.objectContaining({ id: BOX.id }), failure)
    expect(boxRepository.updateWhere).toHaveBeenCalledWith(
      BOX.id,
      expect.objectContaining({
        updateData: expect.objectContaining({ state: BoxState.ERROR, errorReason: 'explained' }),
      }),
    )
  })

  it('keeps database query parameters out of the final sync error log', async () => {
    const failure = new QueryFailedError(
      'INSERT INTO job VALUES (?)',
      ['do-not-log'],
      Object.assign(new Error('insert failed'), { code: '58000' }),
    )
    const { manager } = makeManager(failure)
    const log = jest.spyOn(Logger.prototype, 'error').mockImplementation(() => undefined)

    try {
      await manager.syncInstanceState(BOX.id)
      const syncLog = log.mock.calls.find(
        ([first]) =>
          typeof first === 'object' && first !== null && 'event' in first && first.event === 'box.sync.failed',
      )
      expect(syncLog).toBeDefined()
      expect(JSON.stringify(log.mock.calls)).not.toContain('do-not-log')
      expect(JSON.stringify(log.mock.calls)).not.toContain('INSERT INTO job')
    } finally {
      log.mockRestore()
    }
  })

  it('uses the committed snapshot carried by an explicit destroy event', async () => {
    const { manager, boxRepository, destroy } = makeManager(new Error('must not start'))
    const box = {
      ...BOX,
      state: BoxState.STOPPED,
      desiredState: BoxDesiredState.DESTROYED,
      pending: true,
    }
    const event = new (BoxDestroyedEvent as any)(box, { checkpointState: null })

    await (manager as any).handleBoxDestroyedEvent(event)

    expect(boxRepository.findWithCheckpointState).not.toHaveBeenCalled()
    expect(destroy.run).toHaveBeenCalledWith(box, expect.anything())
  })

  it('does not look up Runner apiVersion when a destroy action needs no more synchronization', async () => {
    const { manager, boxRepository, runnerService } = makeManager(new Error('must not start'))
    boxRepository.findWithCheckpointState.mockResolvedValue({
      box: {
        ...BOX,
        state: BoxState.STOPPED,
        desiredState: BoxDesiredState.DESTROYED,
        pending: true,
        runnerId: 'runner-1',
      },
      checkpointState: null,
    })

    await manager.syncInstanceState(BOX.id)

    expect(runnerService.getRunnerApiVersion).not.toHaveBeenCalled()
  })

  it('uses the apiVersion returned by destroy instead of querying Runner again', async () => {
    const { manager, boxRepository, destroy, runnerService } = makeManager(new Error('must not start'))
    boxRepository.findWithCheckpointState.mockResolvedValue({
      box: {
        ...BOX,
        state: BoxState.STOPPED,
        desiredState: BoxDesiredState.DESTROYED,
        pending: true,
        runnerId: 'runner-1',
      },
      checkpointState: null,
    })
    destroy.run
      .mockResolvedValueOnce({ syncState: SYNC_AGAIN, runnerApiVersion: '0' })
      .mockResolvedValueOnce(DONT_SYNC_AGAIN)

    await manager.syncInstanceState(BOX.id)

    expect(destroy.run).toHaveBeenCalledTimes(2)
    expect(runnerService.getRunnerApiVersion).not.toHaveBeenCalled()
  })
})