Skip to content

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

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

import { randomUUID } from 'node:crypto'
import { DataSource } from 'typeorm'
import { CustomNamingStrategy } from '../../common/utils/naming-strategy.util'
import { Image } from '../entities/image.entity'
import { ImageAlias } from '../entities/image-alias.entity'
import { ImageAliasEvent } from '../entities/image-alias-event.entity'
import { ImageVersion } from '../entities/image-version.entity'
import { isCuratedSelector } from '../utils/image-ref.util'
import { CuratedImagePinService } from './curated-image-pin.service'
import { ImageRegistrarService } from './image-registrar.service'

const describeIfDatabase = process.env.DB_HOST ? describe : describe.skip
const schemaName = `image_registrar_${process.pid}_${randomUUID().replaceAll('-', '')}`

const ORG = '00000000-0000-4000-8000-000000000001'
const OTHER_ORG = '00000000-0000-4000-8000-000000000002'
const DIGEST = `sha256:${'a'.repeat(64)}`
const OTHER_DIGEST = `sha256:${'b'.repeat(64)}`

describeIfDatabase('ImageRegistrarService (integration, real Postgres)', () => {
  let dataSource: DataSource
  let registrar: ImageRegistrarService
  const curatedImagePins = { remember: jest.fn(async () => undefined) }
  let ownsSchema = false

  beforeAll(async () => {
    dataSource = 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: schemaName,
      entities: [Image, ImageVersion, ImageAlias, ImageAliasEvent],
      namingStrategy: new CustomNamingStrategy(),
      entitySkipConstructor: true,
      synchronize: false,
      extra: { options: `-c search_path=${schemaName},public` },
    }).initialize()

    await dataSource.query(`CREATE SCHEMA "${schemaName}"`)
    ownsSchema = true
    await dataSource.synchronize()
    // Just the columns registration reads; the organization entity and its
    // relations are not this spec's to build.
    await dataSource.query(
      `CREATE TABLE "${schemaName}"."organization" ("id" uuid PRIMARY KEY, "image_count_limit" integer NOT NULL DEFAULT 20)`,
    )
    registrar = new ImageRegistrarService(dataSource, curatedImagePins as unknown as CuratedImagePinService)
  })

  afterAll(async () => {
    if (!dataSource?.isInitialized) {
      return
    }
    try {
      if (ownsSchema) {
        await dataSource.query(`DROP SCHEMA IF EXISTS "${schemaName}" CASCADE`)
      }
    } finally {
      await dataSource.destroy()
    }
  })

  beforeEach(async () => {
    await dataSource.query(`DELETE FROM "${schemaName}"."image_tag_event"`)
    await dataSource.query(`DELETE FROM "${schemaName}"."image_tag"`)
    await dataSource.query(`DELETE FROM "${schemaName}"."image_version"`)
    await dataSource.query(`DELETE FROM "${schemaName}"."image"`)
    await dataSource.query(`DELETE FROM "${schemaName}"."organization"`)
    await dataSource.query(`INSERT INTO "${schemaName}"."organization" ("id") VALUES ($1), ($2)`, [ORG, OTHER_ORG])
    curatedImagePins.remember.mockClear()
  })

  function setImageLimit(limit: number) {
    return dataSource.query(`UPDATE "${schemaName}"."organization" SET "image_count_limit" = $1 WHERE "id" = $2`, [
      limit,
      ORG,
    ])
  }

  function report(ref: string, digest = DIGEST, sizeBytes = 4096) {
    return registrar.onBoxStarted(ORG, { ref, isOrgOwned: true }, { digest, sizeBytes })
  }

  /** Waits, for at most 2s, until another backend waits on a lock `pid` holds. */
  async function waitUntilBlockedBy(pid: number): Promise<void> {
    const deadline = Date.now() + 2_000
    while (Date.now() < deadline) {
      const [{ blocked }] = await dataSource.query(
        `SELECT EXISTS (SELECT 1 FROM pg_stat_activity WHERE $1 = ANY(pg_blocking_pids(pid))) AS blocked`,
        [pid],
      )
      if (blocked) {
        return
      }
      await new Promise<void>((resolve) => setTimeout(resolve, 25))
    }
  }

  function countOf(table: string): Promise<number> {
    return dataSource
      .query(`SELECT COUNT(*)::int AS count FROM "${schemaName}"."${table}"`)
      .then((rows) => rows[0].count)
  }

  it('records the image, the version and the tag a box booted from', async () => {
    await report('quay.io/acme/app:v1')

    const [image] = await dataSource.getRepository(Image).find()
    expect(image).toMatchObject({ organizationId: ORG, name: 'quay.io/acme/app' })
    expect(image.lastUsedAt).not.toBeNull()

    const [version] = await dataSource.getRepository(ImageVersion).find()
    expect(version).toMatchObject({
      imageId: image.id,
      digest: DIGEST,
      sizeBytes: 4096,
      sourceSpec: { sourceRef: 'quay.io/acme/app:v1' },
      storageRef: `quay.io/acme/app@${DIGEST}`,
    })

    const [tag] = await dataSource.getRepository(ImageAlias).find()
    expect(tag).toMatchObject({ imageId: image.id, name: 'v1', versionId: version.id })
  })

  it('files a private image under its upstream name, not the registry proxy', async () => {
    const proxy = 'registry-proxy-abc.a.run.app'
    process.env.REGISTRY_PROXY_HOST = proxy
    try {
      await report(`${proxy}/${ORG}/ghcr.io/acme/app:v1`)
    } finally {
      delete process.env.REGISTRY_PROXY_HOST
    }

    const [image] = await dataSource.getRepository(Image).find()
    expect(image).toMatchObject({ organizationId: ORG, name: 'ghcr.io/acme/app' })
    const [version] = await dataSource.getRepository(ImageVersion).find()
    // What the tenant asked for, which is also what the catalog answers to.
    expect(version.sourceSpec).toEqual({ sourceRef: 'ghcr.io/acme/app:v1' })
  })

  /**
   * A report can arrive more than once for the same box — the runner retries,
   * and a replayed job starts the same box again.
   */
  it('is idempotent for the same image and digest', async () => {
    await report('quay.io/acme/app:v1')
    await report('quay.io/acme/app:v1')

    expect(await countOf('image')).toBe(1)
    expect(await countOf('image_version')).toBe(1)
    expect(await countOf('image_tag')).toBe(1)
  })

  /**
   * Two boxes can be the first to use the same new reference. The unique
   * constraint settles it, so neither report has to read before it writes.
   */
  it('produces one row when two boxes report the same new reference at once', async () => {
    await Promise.all([report('quay.io/acme/app:v1'), report('quay.io/acme/app:v1')])

    expect(await countOf('image')).toBe(1)
    expect(await countOf('image_version')).toBe(1)
  })

  /**
   * A pull never moves a tag. A tag that resolved once keeps naming that build
   * until someone moves it on purpose — without this, an upstream tag move
   * would silently change what a box boots from. The history agrees: the one
   * event is the tag being recorded, and the second pull adds none.
   */
  it('leaves a tag pointing at the build it first resolved to', async () => {
    await report('quay.io/acme/app:v1', DIGEST)
    await report('quay.io/acme/app:v1', OTHER_DIGEST)

    const versions = await dataSource.getRepository(ImageVersion).find()
    const aliases = await dataSource.getRepository(ImageAlias).find()
    const events = await dataSource.getRepository(ImageAliasEvent).find()
    const first = versions.find((version) => version.digest === DIGEST)

    expect(versions).toHaveLength(2)
    expect(aliases).toHaveLength(1)
    expect(aliases[0].versionId).toBe(first?.id)
    expect(events).toHaveLength(1)
    expect(events[0]).toMatchObject({ aliasName: 'v1', toVersionId: first?.id })
  })

  /**
   * Where a tag's history starts. No one moved it — a box pulling the image is
   * what recorded it — so it came from no version and was moved by no one.
   */
  it('starts the history of a tag a pull records', async () => {
    await report('quay.io/acme/app:v1')

    const [tag] = await dataSource.getRepository(ImageAlias).find()
    const events = await dataSource.getRepository(ImageAliasEvent).find()

    expect(events).toHaveLength(1)
    expect(events[0]).toMatchObject({
      imageId: tag.imageId,
      aliasName: 'v1',
      fromVersionId: null,
      toVersionId: tag.versionId,
      actorId: null,
    })
  })

  /**
   * Each start moves it, including the digest-pinned start every box after
   * the first gets from the catalog — the one path that records no tag.
   */
  it('moves when a version was last used each time a box starts from it', async () => {
    await report('quay.io/acme/app:v1')
    const [first] = await dataSource.getRepository(ImageVersion).find()
    const longAgo = new Date('2026-01-01T00:00:00.000Z')
    await dataSource.getRepository(ImageVersion).update({ id: first.id }, { lastUsedAt: longAgo })

    await report(`quay.io/acme/app@${DIGEST}`)

    const versions = await dataSource.getRepository(ImageVersion).find()
    expect(versions).toHaveLength(1)
    expect(versions[0].lastUsedAt?.getTime()).toBeGreaterThan(longAgo.getTime())
  })

  it('records no tag for a reference the caller already pinned', async () => {
    await report(`quay.io/acme/app@${DIGEST}`)

    expect(await countOf('image_version')).toBe(1)
    expect(await countOf('image_tag')).toBe(0)
    expect(await countOf('image_tag_event')).toBe(0)
  })

  /**
   * The acceptance criterion this pair exists for: a second create of the same
   * reference must be handed a digest. A bare repository is served by the
   * registry as `latest`, so that is the tag it booted from — and it has to be
   * recorded under the name the resolver looks it up by, or the reference
   * re-resolves forever and every box built from it can get a different build.
   */
  it('records a bare repository under the tag the registry served it as', async () => {
    await report('quay.io/acme/app')

    const [tag] = await dataSource.getRepository(ImageAlias).find()
    expect(tag?.name).toBe('latest')
    expect(await countOf('image_version')).toBe(1)
  })

  /**
   * An operator's image belongs to no tenant catalog: it is shared by every
   * organization, and a row would count against one tenant's limit and let
   * that tenant delete what everyone boots from.
   *
   * The ref here is deliberately one the curated set no longer holds — an
   * operator rotated past it while this box kept running. That is the case
   * this signature exists for: working ownership out from the ref would call
   * it the organization's and file it, because the set moved and `box.image`
   * did not. Only the box knows, and the box was told at create.
   */
  it('records nothing for an operator image the curated set has moved past', async () => {
    const rotatedAway = 'ghcr.io/boxlite-ai/boxlite-agent-base:v0.0.1'
    expect(isCuratedSelector(rotatedAway)).toBe(false)

    await registrar.onBoxStarted(
      ORG,
      { ref: rotatedAway, isOrgOwned: false, runnerId: 'runner-1' },
      { digest: DIGEST, sizeBytes: 4096 },
    )

    expect(await countOf('image')).toBe(0)
    expect(await countOf('image_version')).toBe(0)
  })

  /**
   * What a curated image gets instead of a row: the runner that booted it is
   * handed that build next time, so its next curated box reads the cache.
   */
  it('pins an operator image to the build the runner booted', async () => {
    const curated = 'ghcr.io/boxlite-ai/boxlite-agent-base:v0.1.0'

    await registrar.onBoxStarted(
      ORG,
      { ref: curated, isOrgOwned: false, runnerId: 'runner-1' },
      { digest: DIGEST, sizeBytes: 4096 },
    )

    expect(curatedImagePins.remember).toHaveBeenCalledWith('runner-1', curated, DIGEST)
  })

  it('pins no operator image to a digest it cannot use', async () => {
    const curated = 'ghcr.io/boxlite-ai/boxlite-agent-base:v0.1.0'

    await expect(
      registrar.onBoxStarted(
        ORG,
        { ref: curated, isOrgOwned: false, runnerId: 'runner-1' },
        { digest: 'sha512:deadbeef', sizeBytes: 4096 },
      ),
    ).rejects.toThrow(/not a sha256 digest/)
    expect(curatedImagePins.remember).not.toHaveBeenCalled()
  })

  /**
   * Deleting an image is how a tenant picks up a tag that moved. Using it
   * again has to bring it back — as a new active row beside the soft-deleted
   * one, which is exactly what the partial unique index exists to allow.
   */
  it('gives a soft-deleted name a new active row when the image is used again', async () => {
    await report('quay.io/acme/app:v1')
    await dataSource.getRepository(Image).update({ name: 'quay.io/acme/app' }, { deletedAt: new Date() })

    await report('quay.io/acme/app:v1', OTHER_DIGEST)

    const images = await dataSource.getRepository(Image).find()
    const active = images.filter((image) => image.deletedAt === null)
    expect(images).toHaveLength(2)
    expect(active).toHaveLength(1)

    const versions = await dataSource.getRepository(ImageVersion).find()
    expect(versions.find((version) => version.digest === OTHER_DIGEST)?.imageId).toBe(active[0].id)
  })

  /**
   * A digest this schema cannot hold is refused on its own. The caller catches
   * it and still records the box's state: a running box that reported an
   * unusable digest is still running, and rejecting the whole report would
   * leave the control plane believing it is still starting.
   */
  it('refuses a digest it cannot store and writes nothing', async () => {
    await expect(report('quay.io/acme/app:v1', 'sha512:deadbeef')).rejects.toThrow(/not a sha256 digest/)

    expect(await countOf('image')).toBe(0)
    expect(await countOf('image_version')).toBe(0)
  })

  /**
   * Admission counts only images already recorded, so first pulls in flight
   * each pass it. The count that holds the limit is the one taken here.
   */
  describe('image limit', () => {
    it('records no new image once the organization holds its limit', async () => {
      await setImageLimit(1)
      await report('quay.io/acme/a:v1')

      await expect(report('quay.io/acme/b:v1')).rejects.toThrow(/limit of 1 images/)

      expect(await countOf('image')).toBe(1)
    })

    it('still records a new build of an image the organization holds', async () => {
      await setImageLimit(1)
      await report('quay.io/acme/a:v1', DIGEST)

      await report('quay.io/acme/a:v2', OTHER_DIGEST)

      expect(await countOf('image')).toBe(1)
      expect(await countOf('image_version')).toBe(2)
    })

    it('counts the new image another registration has not yet committed', async () => {
      await setImageLimit(1)
      // The other registration, held open once it has locked the organization
      // and recorded its image, so the two cannot interleave any other way.
      const other = dataSource.createQueryRunner()
      await other.connect()
      try {
        await other.startTransaction()
        const [{ pid }] = await other.query(`SELECT pg_backend_pid()::int AS pid`)
        await other.query(`SELECT 1 FROM "${schemaName}"."organization" WHERE "id" = $1 FOR UPDATE`, [ORG])
        await other.manager.insert(Image, { organizationId: ORG, name: 'quay.io/acme/b' })

        const outcome = report('quay.io/acme/a:v1').then(
          () => 'recorded',
          (error: Error) => error.message,
        )
        await waitUntilBlockedBy(pid)
        await other.commitTransaction()

        expect(await outcome).toMatch(/limit of 1 images/)
      } finally {
        if (other.isTransactionActive) {
          await other.rollbackTransaction()
        }
        await other.release()
      }
      expect(await countOf('image')).toBe(1)
    })
  })

  it('keeps one organization out of another catalog', async () => {
    await report('quay.io/acme/app:v1')
    await registrar.onBoxStarted(
      OTHER_ORG,
      { ref: 'quay.io/acme/app:v1', isOrgOwned: true },
      { digest: DIGEST, sizeBytes: 4096 },
    )

    const images = await dataSource.getRepository(Image).find()
    expect(images).toHaveLength(2)
    expect(new Set(images.map((image) => image.organizationId))).toEqual(new Set([ORG, OTHER_ORG]))
  })
})