Skip to content

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

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

import { NotFoundException } from '@nestjs/common'
import { randomUUID } from 'node:crypto'
import { DataSource, Repository } from 'typeorm'
import { BOX_WARM_POOL_UNASSIGNED_ORGANIZATION } from '../../box/constants/box.constants'
import { AddBoxUsagePeriods1785250000000 } from '../../migrations/pre-deploy/1785250000000-add-box-usage-periods-migration'
import { AddBoxUsageArchiveBoxIndex1795651200000 } from '../../migrations/pre-deploy/1795651200000-add-box-usage-archive-box-index-migration'
import { BoxUsagePeriod } from '../entities/box-usage-period.entity'
import { BoxUsagePeriodArchive } from '../entities/box-usage-period-archive.entity'
import { ARCHIVED_PERIODS_SQL, BoxUsageService } from './box-usage.service'

const describeIfDatabase = process.env.DB_HOST ? describe : describe.skip

const boxId = 'aB3cD4eF5gH6'
const organizationId = randomUUID()
const at = (time: string) => new Date(`2026-11-25T${time}.000Z`)

// The migrations build the usage tables; the box table holds only the columns the read uses.
describeIfDatabase('BoxUsageService (integration, real Postgres)', () => {
  let db: DataSource
  let schema: string
  let archive: Repository<BoxUsagePeriodArchive>
  let service: BoxUsageService

  beforeAll(async () => {
    schema = `box_usage_${randomUUID().replaceAll('-', '')}`
    db = await new DataSource({
      type: 'postgres',
      host: process.env.DB_HOST,
      port: Number(process.env.DB_PORT || 5432),
      username: process.env.DB_USERNAME,
      password: process.env.DB_PASSWORD,
      database: process.env.DB_DATABASE,
      schema,
      entities: [BoxUsagePeriod, BoxUsagePeriodArchive],
      extra: { options: `-c search_path=${schema},public` },
    }).initialize()
    await db.query(`CREATE SCHEMA "${schema}"`)
    await db.query(`CREATE TABLE box (id varchar PRIMARY KEY, "organizationId" uuid NOT NULL)`)
    const runner = db.createQueryRunner()
    try {
      await new AddBoxUsagePeriods1785250000000().up(runner)
      await new AddBoxUsageArchiveBoxIndex1795651200000().up(runner)
    } finally {
      await runner.release()
    }
    archive = db.getRepository(BoxUsagePeriodArchive)
    service = new BoxUsageService(archive)
  })

  afterAll(async () => {
    if (!db?.isInitialized) return
    await db.query(`DROP SCHEMA IF EXISTS "${schema}" CASCADE`)
    await db.destroy()
  })

  beforeEach(async () => {
    await db.query('TRUNCATE box, box_usage_periods, box_usage_periods_archive')
  })

  const addBox = (organization = organizationId) => db.query('INSERT INTO box VALUES ($1, $2)', [boxId, organization])
  const period = (startAt: Date, endAt: Date, resources: Partial<BoxUsagePeriodArchive> = {}) => ({
    boxId,
    organizationId,
    region: 'us',
    startAt,
    endAt,
    cpu: 0,
    gpu: 0,
    mem: 0,
    disk: 0,
    ...resources,
  })
  const read = (organization = organizationId) => service.getUsage(boxId, organization)

  it('answers every archived period in start order with the allocation the export bills', async () => {
    await addBox()
    await archive.save([
      period(at('10:00:15'), at('10:01:15'), { disk: 10 }),
      period(at('10:00:00'), at('10:00:15'), { cpu: 0.125, mem: 0.125, disk: 10 }),
      period(at('10:01:15'), new Date('2026-11-25T10:01:16.500Z'), { cpu: 1.5, mem: 1000 / 1024, disk: 10 }),
    ])

    expect(await read()).toEqual({
      periods: [
        {
          start_at: '2026-11-25T10:00:00.000Z',
          end_at: '2026-11-25T10:00:15.000Z',
          cpu: 0.125,
          memory_gib: 0.125,
          disk_gib: 10,
        },
        {
          start_at: '2026-11-25T10:00:15.000Z',
          end_at: '2026-11-25T10:01:15.000Z',
          cpu: 0,
          memory_gib: 0,
          disk_gib: 10,
        },
        {
          start_at: '2026-11-25T10:01:15.000Z',
          end_at: '2026-11-25T10:01:16.500Z',
          cpu: 1.5,
          memory_gib: 0.976563,
          disk_gib: 10,
        },
      ],
    })
  })

  it('reads a deleted box from the archive once its row is gone', async () => {
    await archive.save(period(at('10:00:00'), at('10:00:15'), { cpu: 2 }))

    expect((await read()).periods).toEqual([expect.objectContaining({ cpu: 2 })])
  })

  it('answers no periods for an owned box with no archived period, ignoring unarchived ones', async () => {
    await addBox()
    await db
      .getRepository(BoxUsagePeriod)
      .save([period(at('10:00:00'), at('10:00:15'), { cpu: 1 }), period(at('10:00:15'), null as never, { cpu: 1 })])

    expect(await read()).toEqual({ periods: [] })
  })

  it("answers 404 for another organization's box, with or without usage", async () => {
    const other = randomUUID()
    await addBox(other)
    await expect(read()).rejects.toBeInstanceOf(NotFoundException)

    await archive.save({ ...period(at('10:00:00'), at('10:00:15'), { cpu: 1 }), organizationId: other })
    await expect(read()).rejects.toBeInstanceOf(NotFoundException)
    expect((await read(other)).periods).toHaveLength(1)
  })

  it('answers 404 for an unknown box, a malformed ID and the unassigned warm pool', async () => {
    await expect(read()).rejects.toBeInstanceOf(NotFoundException)
    await expect(service.getUsage('not a box id', organizationId)).rejects.toBeInstanceOf(NotFoundException)
    await archive.save({
      ...period(at('10:00:00'), at('10:00:15'), { cpu: 1 }),
      organizationId: BOX_WARM_POOL_UNASSIGNED_ORGANIZATION,
    })
    await expect(read(BOX_WARM_POOL_UNASSIGNED_ORGANIZATION)).rejects.toBeInstanceOf(NotFoundException)
  })

  it('skips a period the export would refuse and keeps the others', async () => {
    await db.query(
      `INSERT INTO box_usage_periods_archive ("boxId", "organizationId", region, "startAt", "endAt", cpu, gpu, mem, disk)
       VALUES ($1, $2, 'us', $3, $4, 'NaN', 0, 0, 0)`,
      [boxId, organizationId, at('10:00:00'), at('10:00:15')],
    )
    await archive.save(period(at('10:00:15'), at('10:00:30'), { cpu: 1 }))

    expect((await read()).periods).toEqual([expect.objectContaining({ start_at: '2026-11-25T10:00:15.000Z', cpu: 1 })])
  })

  it('reads through the box index instead of scanning the archive', async () => {
    await db.query('SET enable_seqscan = off')
    try {
      const plan: { 'QUERY PLAN': string }[] = await db.query(`EXPLAIN ${ARCHIVED_PERIODS_SQL}`, [
        boxId,
        organizationId,
      ])
      expect(plan.map((row) => row['QUERY PLAN']).join('\n')).toContain('box_usage_periods_archive_box_org_end_idx')
    } finally {
      await db.query('SET enable_seqscan = on')
    }
  })
})