Skip to content

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

11.0 KB
Raw Blame

Database Migrations

This project uses the Expand and Contract pattern for database migrations to support zero-downtime deployments.

Pre-launch Baseline

Because BoxLite has not launched yet, the historical migration chain has been squashed into the root baseline 1741087887225-migration.ts. Fresh databases should run this single baseline first. Future schema changes should use the expand-and-contract workflow below.

Deprecated objects no entity maps

These database objects have no mapping in the current API. Schedule their removal in a later release after all older instances that use them have stopped and the rollback window has closed.

Object Present in Left behind by
table ssh_access databases created before the SSH gateway removal that removal, which edited the baseline instead of adding a contract migration
region.sshGatewayUrl same same
region.sshGatewayApiKeyHash (+ its unique index) same same
organization.template_deactivation_timeout_minutes every database the image catalog, which unmapped it and deferred the drop
organization.referralCode (and its unique constraint) databases with migration 1789500000000 removal of the organization referral-code endpoint

The SSH objects are absent from fresh databases, so their drop needs IF EXISTS. The baseline creates the template timeout column with NOT NULL DEFAULT 20160, so inserts can omit it until a later release drops it.

Older API instances can still read and assign organization referral codes during rollout or after an image rollback. New API instances omit the nullable column on reads and writes.

Overview

The expand and contract pattern splits database changes into two phases:

  • Pre-deploy (Expand): Additive, non-breaking changes that are backwards compatible with the current API version
  • Post-deploy (Contract): Breaking changes that require the new API version to be deployed first

This allows the database and API to be updated independently while maintaining compatibility during the deployment window.

Migration Folders

  • pre-deploy/ - Migrations that run before the API is deployed
  • post-deploy/ - Migrations that run after the API is deployed

Note: the root folder is reserved for the pre-launch baseline only. Do not add new root migrations; use pre-deploy/ or post-deploy/ for new changes.

Developer Workflow

1. Make Changes to Database Entities

Modify the TypeORM entity files in src/**/*.entity.ts as needed.

2. Generate Migrations

Run the migration generator:

npm run migration:generate

This creates the same autogenerated migration in both pre-deploy/ and post-deploy/ folders with a timestamp prefix.

3. Analyze and Adjust Migrations

This is the critical step. You MUST analyze the generated migrations and determine:

  • Which changes are safe to run before the API deployment (pre-deploy)
  • Which changes require the new API to be running first (post-deploy)
  • Whether manual adjustments are needed for zero-downtime compatibility

Example Scenarios

Adding a new field (Pre-deploy only)

When adding a new nullable column or a column with a default value:

// pre-deploy/migration.ts
public async up(queryRunner: QueryRunner): Promise<void> {
  await queryRunner.query(`ALTER TABLE "workspace" ADD "description" varchar NULL`);
}
// post-deploy/migration.ts
// DELETE the generated migration - no post-deploy changes needed

The new column can be added before the API deployment since the old API will simply ignore it.


Dropping a field (Post-deploy only)

When removing a column:

// pre-deploy/migration.ts
// DELETE the generated migration - no pre-deploy changes needed
// post-deploy/migration.ts
public async up(queryRunner: QueryRunner): Promise<void> {
  await queryRunner.query(`ALTER TABLE "workspace" DROP COLUMN "legacy_field"`);
}

The column must only be dropped after the new API is deployed, since the old API may still be reading from it.


Renaming a field (Expand then Contract)

Renaming requires both phases to maintain zero-downtime. Use a database trigger to keep columns synchronized automatically:

// pre-deploy/migration.ts (Expand)
public async up(queryRunner: QueryRunner): Promise<void> {
  // Add new column
  await queryRunner.query(`ALTER TABLE "workspace" ADD "display_name" varchar NULL`);
  // Copy existing data
  await queryRunner.query(`UPDATE "workspace" SET "display_name" = "name"`);
  // Create trigger to keep columns in sync during transition
  await queryRunner.query(`
    CREATE OR REPLACE FUNCTION sync_workspace_name()
    RETURNS TRIGGER AS $$
    BEGIN
      IF NEW.display_name IS NOT NULL THEN
        NEW.name := NEW.display_name;
      ELSIF NEW.name IS NOT NULL THEN
        NEW.display_name := NEW.name;
      END IF;
      RETURN NEW;
    END;
    $$ LANGUAGE plpgsql;
  `);
  await queryRunner.query(`
    CREATE TRIGGER workspace_name_sync
    BEFORE INSERT OR UPDATE ON "workspace"
    FOR EACH ROW EXECUTE FUNCTION sync_workspace_name();
  `);
}
// post-deploy/migration.ts (Contract)
public async up(queryRunner: QueryRunner): Promise<void> {
  // Remove trigger and old column
  await queryRunner.query(`DROP TRIGGER workspace_name_sync ON "workspace"`);
  await queryRunner.query(`DROP FUNCTION sync_workspace_name()`);
  await queryRunner.query(`ALTER TABLE "workspace" DROP COLUMN "name"`);
}

How the trigger works:

The trigger intercepts every INSERT and UPDATE on the table and automatically copies the value between columns:

API Version Writes to Trigger copies to Result
Old API name display_name Both columns have the value
New API display_name name Both columns have the value

Deployment timeline:

  1. Pre-deploy migration runs → Trigger is active, both columns exist
  2. Rolling deployment begins → Mix of old and new API instances, trigger keeps data in sync
  3. Rolling deployment completes → All instances are new API
  4. Post-deploy migration runs → Trigger and old column are removed

New API code changes:

The new API should read from and write to display_name only. The trigger handles backward compatibility with old API instances—no dual-write logic needed in application code.

Migration Scripts

npm run migration:run:init

Runs all migrations from both pre-deploy and post-deploy folders. Use this for:

  • Initial database setup
  • Development environments
  • Fresh database instances

npm run migration:run:pre-deploy

Runs only migrations in the pre-deploy/ folder. Use this:

  • Before deploying a new API version
  • As part of your CI/CD pipeline, before the rolling update begins

npm run migration:run:post-deploy

Runs only migrations in the post-deploy/ folder. Use this:

  • After the new API version is fully deployed
  • As part of your CI/CD pipeline, after the rolling update completes

Member Scopes and Invitation Retries

The historical tenant-scope migration remains in the chain. The Admin migration renames both enum labels to read:members and write:members for API keys and organization roles, preserving existing grants without adding permissions to unscoped keys. Rollback restores the old labels. The unmerged Tenant HTTP API is replaced directly; no compatibility deployment with that API is required.

API-key validation retains the existing Redis cache namespace. Old cached scope labels translate on read, so membership removal, key revocation, and identity linking continue to invalidate the same entries across deployment versions.

A separate pre-deploy migration adds organization_invitation_request. Creating an invite and saving its replay snapshot share a transaction and an advisory lock scoped to organization, user, and idempotency key. Replay records expire after 24 hours; subsequent keyed requests clean expired records for their organization. Deleting an organization cascades to its replay records. Rollback drops this table and loses retry history, so coordinate rollback with stopping Admin writes.

The integration tests run actual PostgreSQL migrations and services. Set DB_HOST, DB_PORT, DB_USERNAME, DB_PASSWORD, and DB_DATABASE; the migration suite needs permission to create temporary databases. Run make coverage:api FILTER='AddTenantScopes1792497600000|Admin organization storage'. The suites clean their temporary databases or schemas and run in API CI.

Reverting Migrations

CLI and application startup run pending migrations in each mode: each ordinary migration has its own transaction, while an explicit transaction = false allows operations such as concurrent index builds. A later failure leaves earlier completed migrations recorded; fix the failure and rerun to resume. The activation facts migration still creates its table and backfill atomically.

npm run migration:revert

This reverts the last executed migration from either folder (based on the combined migration history in the database).

When the last applied migration declares transaction = false and reverts with concurrent DDL, use:

npm run migration:revert -- --transaction none

For example, AddAdminUsageWindowIndexes1792470000000 and AddBoxCreationQuotaIndex1795478400000 both drop their indexes concurrently. TypeORM 0.3.31 starts a transaction for undoLastMigration in each mode despite the migration's transaction = false. Use the default command for transactional migrations.

Rerun an interrupted concurrent index build or drop. A retry keeps valid indexes, rebuilds invalid builds, and skips missing indexes on drop. Serialize migration runners; concurrent DDL still waits for older transactions and is not a production capacity guarantee.

Important behaviors:

  • Reverts one migration at a time - run multiple times to revert multiple migrations
  • Uses the combined data-source that sees all migrations
  • The revert order follows the execution timestamp, not the folder structure
  • Always test revert scripts in development before relying on them in production

Recommendation: After reverting, you may need to also revert the corresponding entity changes and regenerate migrations to keep everything in sync.