The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
BoxLite application data model
The allowlist adds organization.nestedVirtualizationEnabled, an Admin-controlled
boolean defaulting to false, and a Runner capability report defaulting to false.
There is no Cloud per-box nested virtualization column. The owner-writable
experimentalConfig cannot grant permission; each new Box resolves current policy and capability, then the local runtime
saves its existing creation options for subsequent starts. See rollout and API.
This catalog describes the durable state owned by the applications in this directory: the control-plane Postgres schema, and the satellite stores that sit beside it. Each table entry names its columns, its keys, and the constraints and indexes the database actually enforces.
The model is implementation-grounded:
- Tables and columns come from the TypeORM entities under
api/src. The data source globs every*.entity.tsin that tree (seedata-source.ts), so the entity files are the complete list of mapped tables. - Column types, constraints, and index definitions come from the migrations in
api/src/migrations: the baseline1741087887225-migration.tsand thepre-deployset create the tables. - Satellite stores come from
rauthy/config.toml,otel-collector/config.yaml, and the ClickHouse queries inbox-telemetry.
apps/api owns the control-plane PostgreSQL database. The standalone CI Listener
uses a private SQLite store for the same controller records. The Go services —
runner and proxy — hold no persistence: neither
imports an ORM, database/sql, or an embedded store. Runner state reaches the
control plane through runner telemetry columns, job results and CPU incident reports.
Experimental CI authorization state
The SQL-owned tables below are created by
1793664000000-add-ci-connect-migration.ts
and extended by the later CI migrations listed in the
development CI reset procedure.
They are accessed by CiConnectService and have no TypeORM entity mapping.
| Table | Stored state | Enforced boundaries |
|---|---|---|
ci_installation_binding |
Stable GitHub host/App/installation/account IDs, BoxLite organization, actor, explicit Private/follow policy, provisioning state and generation | UUID primary key; unique host/App/installation; positive GitHub IDs; account/state checks; organization FK with cascade |
ci_connect_attempt |
Initiating user/org, account and policy, grant flow, encrypted device code or web PKCE verifier/token, original OAuth client, encrypted selected CI App/account/installation state, OAuth state hash, expiry, poll/claim lease, result binding | UUID primary key; state/positive interval checks; organization FK with cascade; binding FK; partial expiry index for remaining ciphertext |
The initial connection migration creates allow_private in both tables with a
false default. Hosted Public access is always eligible within App authorization
and is not a stored opt-in. CI has not shipped, so there is no conversion of old
Public consent into Private consent.
For existing dev state, finish resource cleanup with the old version, stop its Listeners, and follow that reset procedure: recreate the CI tables and journal, remove only their five migration-history entries, then rerun the complete CI migration chain. Replaying only the initial connect migration omits OAuth and account-selection fields; deleting rows alone retains the old schema. Shared scope hashes include both Public and Private decisions, so standalone operators also need old-resource cleanup and a fresh journal; their Public configuration remains independent and Private stays allowed.
Device ciphertext uses AES-256-GCM with transaction/user/organization AAD. Completion, cancellation and terminal failure clear it. Expired ciphertext is removed when another attempt starts. Binding ownership is committed only after live GitHub authorization; failed authorization cannot reserve an installation.
Organization deletion cascades these authorization-only rows. Execution history is separate and has no cascade foreign keys: revocation must not erase original cleanup identity or uncertain resource allocations.
Migration 1793700000000-add-ci-listener-state-migration.ts
adds one shared controller table, ci_listener_state:
| Columns / keys | Stored state | Enforcement |
|---|---|---|
(namespace, record_key) |
App-scoped record identity | Composite primary key; C ordering for record keys |
record_version, schema_version |
UUID CAS revision and payload schema | Required; positive schema version |
owner_epoch, owner_id, lease_until |
Execution owner metadata for the @owner record |
Current payload/lease validated by the shared storage contract |
payload, updated_at |
JSON facts and actual database update clock | Required JSONB and timestamptz |
The native API namespace is ci:<App client ID>. @anchor and @owner are permanent
initialization roots. backend/native fixes the configured App; catalog/scopes
indexes immutable scope/<digest> records. worker/<allocation-id> contains the
original job identity, resource phases/IDs, one external operation intent and quota
ownership. box-native/<allocation-id> stores the platform-confirmed Box ID and
JIT delivery claim. Those ledger writes commit in the Box creation transaction.
receipt/<delivery UUID>, notice/<installation>/<job> and
wake/<installation>/<repository> form the durable inbox. Repository ID zero is an
installation discovery hint. Shared inbox writes atomically commit receipts, notices
and wakes under live binding authorization. UUID CAS revisions prevent stale settlement
and delete/recreate ABA. Receipts currently remain stored; automatic pruning is pending.
replay/progress stores App delivery scan checkpoints, cursor hashes and cooldowns;
replay/item/<GUID> stores exact decimal delivery IDs, target metadata and retry
intents. A leased bounded scan reads these records without treating a page as a
complete allocation snapshot. Page records commit before their checkpoint, and
successful GUID observations cannot be reopened by older failed attempts. Replay
metadata has a three-day retention window; unconfirmed expiry reports a gap and
never removes a notice or releases allocation quota. These records select no
tenant and create no connect binding. Business receipts remain retained.
No GitHub token, JIT configuration, App private key or BoxLite API Key is stored in
these controller payloads. Historical scopes and uncertain effects survive binding
and organization deletion. Unknown effects retain capacity rather than being retried
or erased. The standalone host implements the same record contract in private
listener.sqlite and its WAL/SHM sidecar files.
Overview
The tables sort into three planes. Tenancy is who a caller is and what they may do; fleet is the microVMs and the machines that run them; metering is what gets billed.
flowchart LR
subgraph tenancy["Tenancy · access · audit"]
t_org["organization"]
t_orguser["organization_user"]
t_role["organization_role"]
t_invite["organization_invitation"]
t_assign["organization_role_assignment"]
t_assigninv["organization_role_assignment_invitation"]
t_user["user"]
t_apikey["api_key"]
t_webhook["webhook_initialization"]
t_audit["audit_log"]
end
subgraph fleet["Fleet"]
t_box["box"]
t_activity["box_last_activity"]
t_migration["box_migration"]
t_tunnel["tunnel"]
t_domain["domain"]
t_runner["runner"]
t_region["region"]
t_volume["volume"]
t_job["job"]
t_warm["warm_pool"]
t_image["image"]
t_imgver["image_version"]
t_imgtag["image_tag"]
t_imgevent["image_tag_event"]
t_regcred["registry_credential"]
end
subgraph metering["Metering"]
t_period["box_usage_periods"]
t_archive["box_usage_periods_archive"]
t_outbox["box_usage_export_outbox"]
end
t_orguser ==>|"organizationId"| t_org
t_role ==>|"organizationId"| t_org
t_invite ==>|"organizationId"| t_org
t_assign ==>|"organizationId, userId"| t_orguser
t_assign ==>|"roleId"| t_role
t_assigninv ==>|"invitationId"| t_invite
t_assigninv ==>|"roleId"| t_role
t_activity ==>|"boxId"| t_box
t_migration ==>|"boxId"| t_box
t_tunnel ==>|"box_id"| t_box
t_domain -.->|"box_id"| t_box
t_imgver ==>|"imageId"| t_image
t_imgtag ==>|"imageId"| t_image
t_imgtag ==>|"versionId"| t_imgver
t_imgevent ==>|"imageId"| t_image
t_imgevent ==>|"fromVersionId, toVersionId"| t_imgver
t_orguser -.->|"userId"| t_user
t_apikey -.->|"organizationId, userId"| t_org
t_webhook -.->|"organizationId"| t_org
t_audit -.->|"organizationId"| t_org
t_box -.->|"organizationId"| t_org
t_box -.->|"region"| t_region
t_box -.->|"runnerId"| t_runner
t_box -.->|"volumes[].volumeId"| t_volume
t_volume -.->|"organizationId"| t_org
t_regcred -.->|"organizationId"| t_org
t_job -.->|"resourceId"| t_box
t_job -.->|"runnerId"| t_runner
t_period -.->|"boxId"| t_box
t_archive -.->|"boxId"| t_box
t_period ==>|"closed period"| t_archive
t_period ==>|"same transaction"| t_outbox
Thick edges are foreign keys the database enforces. Dashed edges are
references the application enforces alone. warm_pool references nothing: a
box request is matched against the pool by shape, not by id.
Referential integrity
The schema declares foreign keys within the control plane. They live
inside the tenancy cluster, on tables owned outright by a box, or inside the
image catalog.
Every edge that crosses a plane boundary — including box.organizationId,
the most widely joined column in the system — is a bare uuid or
character varying column with no constraint behind it.
The practical consequence: deleting an organization row cascades its roles,
users, invitations, and role assignments, and leaves its boxes, API
keys, audit entries, regions, volumes, and usage history pointing at an id
that no longer resolves.
| From | Column(s) | To | Enforcement | On delete |
|---|---|---|---|---|
organization_user |
organizationId |
organization.id |
foreign key | CASCADE |
organization_role |
organizationId |
organization.id |
foreign key | CASCADE |
organization_invitation |
organizationId |
organization.id |
foreign key | CASCADE |
organization_role_assignment |
organizationId, userId |
organization_user (PK) |
foreign key | CASCADE |
organization_role_assignment |
roleId |
organization_role.id |
foreign key | NO ACTION |
organization_role_assignment_invitation |
invitationId |
organization_invitation.id |
foreign key | CASCADE |
organization_role_assignment_invitation |
roleId |
organization_role.id |
foreign key | NO ACTION |
box_last_activity |
boxId |
box.id |
foreign key | CASCADE |
box_migration |
boxId |
box.id |
foreign key | CASCADE |
tunnel |
box_id |
box.id |
foreign key | CASCADE |
domain |
box_id |
box.id |
application | retained |
image_version |
imageId |
image.id |
foreign key | CASCADE |
image_tag |
imageId |
image.id |
foreign key | CASCADE |
image_tag |
versionId |
image_version.id |
foreign key | RESTRICT |
image_tag_event |
imageId |
image.id |
foreign key | CASCADE |
image_tag_event |
fromVersionId |
image_version.id |
foreign key | RESTRICT |
image_tag_event |
toVersionId |
image_version.id |
foreign key | RESTRICT |
organization_user |
userId |
user.id |
application | — |
api_key |
organizationId, userId |
organization.id, user.id |
application | — |
webhook_initialization |
organizationId |
organization.id |
application | — |
audit_log |
organizationId |
organization.id |
application | — |
audit_log |
targetType, targetId |
any table | application | polymorphic, untyped |
region |
organizationId |
organization.id |
application | null for shared regions |
image |
organizationId |
organization.id |
application | never null |
organization |
defaultRegionId |
region.id |
application | — |
volume |
organizationId |
organization.id |
application | — |
box |
organizationId |
organization.id |
application | — |
box |
region |
region.id |
application | holds the id, not the name |
box |
runnerId, prevRunnerId |
runner.id |
application | nulled on destroy/archive |
box |
volumes[].volumeId |
volume.id |
application | jsonb array, GIN-indexed |
box_migration |
runnerId |
runner.id |
application | the migration's second runner |
runner |
region |
region.id |
application | — |
job |
runnerId |
runner.id |
application | — |
job |
resourceType, resourceId |
box.id |
application | polymorphic across resource types |
box_usage_periods |
boxId, organizationId |
box.id, organization.id |
application | org id denormalized for billing |
box_usage_periods_archive |
boxId, organizationId |
box.id, organization.id |
application | — |
Invariants held by partial unique indexes
Four correctness properties are enforced by the database rather than by application locking. The per-box Redis locks are advisory and expire, so an interleaved pair of handlers could otherwise violate all four.
| Index | Table | Definition |
|---|---|---|
box_usage_periods_one_open_period_per_box_idx |
box_usage_periods |
unique ("boxId") where "endAt" IS NULL |
IDX_UNIQUE_INCOMPLETE_JOB |
job |
unique ("resourceType","resourceId","runnerId") where "completedAt" IS NULL |
organization_user_default_user_unique |
organization_user |
unique ("userId") where "isDefaultForUser" = true |
image_org_name_active_unique |
image |
unique ("organizationId","name") where "deletedAt" IS NULL |
Tenancy, access and audit
organization
app_hosting_permissions text[] NOT NULL DEFAULT '{}' contains the App Hosting scopes enabled
by Backoffice. PostgreSQL restricts entries to read:apps, write:apps and delete:apps.
Existing and new organizations start with an empty array. Changing the array affects access to
existing Apps and leaves their deployment state intact.
The tenant. Carries per-box resource ceilings, rate limits, and suspension state inline.
| Column | Type | Notes |
|---|---|---|
id |
uuid |
primary key |
referralCode |
character varying(10) |
nullable, unique (organization_referral_code_uq), retained for older API instances through the rollback window |
name |
character varying |
|
createdBy |
character varying |
|
telemetryEnabled |
boolean |
default true |
defaultRegionId |
character varying |
nullable; references region.id |
max_cpu_per_box |
integer |
default 4 |
max_memory_per_box |
integer |
default 8 |
max_disk_per_box |
integer |
default 10 |
authenticated_rate_limit |
integer |
nullable |
box_create_rate_limit |
integer |
nullable |
box_lifecycle_rate_limit |
integer |
nullable |
authenticated_rate_limit_ttl_seconds |
integer |
nullable |
box_create_rate_limit_ttl_seconds |
integer |
nullable |
box_lifecycle_rate_limit_ttl_seconds |
integer |
nullable |
suspended |
boolean |
default false |
suspendedAt |
timestamptz |
nullable |
suspendedUntil |
timestamptz |
nullable |
suspensionReason |
character varying |
nullable |
suspensionCleanupGracePeriodHours |
integer |
default 24 |
image_count_limit |
integer |
default 20; catalog entries an organization may keep |
domain_count_limit |
integer |
default 1; domain names an organization may hold, bound or released |
boxLimitedNetworkEgress |
boolean |
default false |
experimentalConfig |
jsonb |
nullable |
createdAt / updatedAt |
timestamptz |
organization_activation_facts
After each committed Box write, BoxRepository upserts the row with a best-effort update
outside the Box transaction; an organization without a recorded Box has no row. Organization
deletion cascades to its facts; Box deletion does not. The API reads it only when activation
is selected with include=activation on the existing organization detail.
| Column | Type | Notes |
|---|---|---|
organizationId |
uuid |
primary key; FK to organization with ON DELETE CASCADE |
lastBoxCreatedAt |
timestamptz |
nullable; maximum retained creation or warm-pool claim |
lastBoxModifiedAt |
timestamptz |
nullable; maximum successful-start or accepted-deletion time |
The activation design describes the optimistic update, migration locking, backfill and uncertainty.
user
Identity, keyed by the subject the IdP issues rather than a generated uuid.
| Column | Type | Notes |
|---|---|---|
id |
character varying |
primary key |
name |
character varying |
|
email |
character varying |
default '' |
emailVerified |
boolean |
default false |
role |
enum |
admin | user, default user |
publicKeys |
simple-json |
|
createdAt |
timestamptz |
organization_user
Membership. The composite primary key means a user joins an organization at most once.
| Column | Type | Notes |
|---|---|---|
organizationId |
uuid |
primary key, FK → organization.id |
userId |
character varying |
primary key |
role |
enum |
owner | member, default member |
isDefaultForUser |
boolean |
default false |
createdAt / updatedAt |
timestamptz |
Partial unique: one isDefaultForUser = true row per userId.
organization_role
A named permission bundle. Rows with isGlobal have a null organizationId
and are shared by all tenants.
| Column | Type | Notes |
|---|---|---|
id |
uuid |
primary key |
name |
character varying |
|
description |
character varying |
|
permissions |
enum[] |
OrganizationResourcePermission |
isGlobal |
boolean |
default false |
organizationId |
uuid |
nullable, FK → organization.id |
createdAt / updatedAt |
timestamptz |
organization_role_assignment
Join table: which roles a member holds.
| Column | Type | Notes |
|---|---|---|
organizationId |
uuid |
primary key, FK → organization_user |
userId |
character varying |
primary key, FK → organization_user |
roleId |
uuid |
primary key, FK → organization_role.id |
The member-side FK cascades. roleId is NO ACTION, so a role that is still
assigned cannot be deleted — it has to be unassigned first.
organization_invitation
A pending membership, addressed by email rather than by user id.
| Column | Type | Notes |
|---|---|---|
id |
uuid |
primary key |
organizationId |
uuid |
FK → organization.id |
email |
character varying |
|
invitedBy |
character varying |
default '' |
role |
enum |
owner | member, default member |
status |
enum |
default pending |
expiresAt |
timestamptz |
|
createdAt / updatedAt |
timestamptz |
organization_role_assignment_invitation
Join table: the roles an invitee will hold once the invitation is accepted.
Same cascade asymmetry as organization_role_assignment.
| Column | Type | Notes |
|---|---|---|
invitationId |
uuid |
primary key, FK → organization_invitation.id |
roleId |
uuid |
primary key, FK → organization_role.id |
api_key
Machine credential. The name is part of the identity, so a key is addressed by
(organization, user, name); only the hash is stored.
Cloud Apps use these organization credentials without adding an App scope column or index.
The permissions enum includes read:apps, write:apps and delete:apps. Omitting the
permission list requests every non-App scope plus the App scopes enabled for the organization.
The caller must be able to delegate every requested scope. A stored key regains access after an
organization grant is restored only if the key already holds that scope and remains valid.
No foreign key ties a key to its organization_user row, so the application
revokes it: removing a member, or a member leaving, deletes that member's keys
in the organization within the same transaction as the membership
(OrganizationUserService.delete). Deleting an account applies the same
revocation to its default and invited organizations within the user-deletion
transaction. Key and membership caches are cleared and notification sockets
leave those organization rooms only after commit. A shared default organization
and its other members' keys remain; the existing fallback-owner rule still applies.
Removal events capture membership identifiers before deleting the entity, because TypeORM clears its primary columns during removal.
| Column | Type | Notes |
|---|---|---|
organizationId |
uuid |
primary key |
userId |
character varying |
primary key |
name |
character varying |
primary key |
keyHash |
character varying |
unique, default '' |
keyPrefix |
character varying |
default '' |
keySuffix |
character varying |
default '' |
permissions |
enum[] |
OrganizationResourcePermission |
createdAt |
timestamp |
|
lastUsedAt |
timestamp |
nullable |
expiresAt |
timestamp |
nullable |
Index: api_key_org_user_idx (organizationId, userId).
audit_log
Action record inserted before a mutation, then completed with its result. A null status means pending; zero means unknown, including an interrupted response or a request unresolved after 30 minutes without a live response lease. Nonzero completed statuses are immutable through the entity subscriber. The target is a polymorphic, untyped string pair — deliberately not a foreign key, so an entry survives deletion of what it describes.
| Column | Type | Notes |
|---|---|---|
id |
uuid |
primary key |
actorId |
character varying |
|
actorEmail |
character varying |
default '' |
organizationId |
character varying |
nullable |
action |
character varying |
|
targetType |
character varying |
nullable |
targetId |
character varying |
nullable |
statusCode |
integer |
nullable |
leaseExpiresAt |
timestamptz |
nullable; internal response liveness, omitted from API DTOs |
errorMessage |
character varying |
nullable |
ipAddress |
character varying |
nullable |
userAgent |
text |
nullable |
source |
character varying |
nullable |
metadata |
jsonb |
nullable |
createdAt |
timestamptz |
Indexes: (createdAt) · (organizationId, createdAt) ·
idx_audit_log_pending_created_at on (createdAt) WHERE "statusCode" IS NULL.
The pending index is built concurrently before deployment. Every minute the resolver
claims batches of 500 expired pending rows with FOR UPDATE SKIP LOCKED, until a
batch returns fewer than 500 rows. The run renews its 30-second Redis lease and stops
starting batches or issuing updates after detecting lost ownership. Each batch
atomically changes only null statuses to zero, with a five-second statement budget
and one-second lock timeout; locked rows remain eligible next run. The cutoff stays
fixed at 30 minutes before the run started and has no lower time bound, so downtime
cannot strand old pending records. Cron invocations on the same instance do not overlap.
This dedicated SQL transition preserves final statuses without the ORM subscriber;
ordinary per-record updates still use that subscriber.
Response-completion audits acquire a five-minute lease using the database clock and renew it every minute. The resolver excludes live leases before its batch limit and rechecks expiry during the update. Null leases retain the existing age rule. Terminal response writes require a pending, unexpired row and clear its lease; they cannot overwrite an unknown result or recreate a published row. The additive lease migration must precede deployment. Old reconcilers ignore leases, so upgrade every reconciler before relying on this protection; remove new writers before dropping the column.
webhook_initialization
Tracks provisioning of the organization's Svix application, with its own retry counter and last error.
| Column | Type | Notes |
|---|---|---|
organizationId |
character varying |
primary key |
svixApplicationId |
character varying |
nullable |
lastError |
text |
nullable |
retryCount |
integer |
default 0 |
createdAt / updatedAt |
timestamptz |
Fleet
box
The microVM, and the busiest table in the schema. The id is a 12-character alphanumeric string, not a uuid.
box records a gap rather than a fact: state is what the runner last
reported, desiredState is what the caller asked for, and pending is a
materialized state ≠ desiredState so the reconciler can find work through an
index instead of a scan. enforceInvariants() on the entity re-derives
pending on every write, and nulls runnerId once a box reaches destroyed
or archived.
| Column | Type | Notes |
|---|---|---|
id |
character varying(12) |
primary key |
organizationId |
uuid |
|
app_id |
text |
nullable owning Cloud App; null for standalone Boxes |
environment_id |
text |
nullable provisioning environment; paired with app_id |
name |
character varying |
unique per organization |
region |
character varying |
holds region.id |
image |
character varying |
nullable |
imageIsOrgOwned |
boolean |
nullable; false for the operator's curated set. Null means the row predates the column, and the reader falls back to matching image against the curated set as it stands now — which is what every row used to do, and why the column exists |
runnerId |
uuid |
nullable |
prevRunnerId |
uuid |
nullable; the runner to revert to if reassignment fails |
class |
enum |
small | medium | large, default small |
state |
enum |
13 values, default unknown |
desiredState |
enum |
started | stopped | destroyed | resized |
pending |
boolean |
default false |
recoverable |
boolean |
default false |
errorReason |
character varying |
nullable |
cpu |
double precision |
default 2; CPU allocation in cores, precision 0.001 |
gpu |
integer |
default 0 |
mem |
integer |
default 4; compatibility GiB ceiling |
memory_mib |
integer |
nullable; authoritative exact MiB; null falls back to mem * 1024 |
disk |
integer |
default 10 |
autoStop |
integer |
seconds, default 900; 0 disables |
autoDelete |
integer |
default 0 = disabled |
autoResume |
boolean |
default true |
osUser |
character varying |
|
env |
jsonb |
default {} |
labels |
jsonb |
nullable |
volumes |
jsonb |
array of { volumeId, mountPath } |
inboundEnabled |
boolean |
default false; true lets the proxy serve exposed services under each tunnel's access policy (public: no sign-in; private: tunnel token or member) |
outboundEnabled |
boolean |
default true; false blocks all egress |
outboundAllowNet |
text[] |
nullable egress allowlist (hosts, wildcards, IPv4, CIDRs); null = full egress |
authToken |
character varying |
nanoid(32), lowercased |
daemonVersion |
character varying |
nullable |
createdAt / updatedAt |
timestamptz |
The network policy columns store the /v1 NetworkSpec's enabled / disabled
modes as booleans (true = enabled); the API converts mode strings at its
edges, and its internal create input and the runner create, recover and
network-settings bodies carry the same outboundEnabled / outboundAllowNet.
The control-plane Box DTO reports them as network.outbound {mode, allow_net}
and network.inbound {mode, allow_net}, the same NetworkInfo schema the /v1
box read returns, and nothing else.
Unique: (organizationId, name).
App ownership: box_app_owner requires app_id and environment_id to be
both null or both populated. BoxService.create validates the App environment in
the Box's organization and records both fields before persistence. Ordinary Box
creation leaves both null; labels and process variables do not assign an owner.
The nonunique box_app_environment_idx covers (organizationId, app_id, environment_id), allowing several Boxes per App and per environment.
cloud_app.envs.active_box_id selects the current deployment and ingress runtime.
It is not the ownership relation. App/environment lifecycle operations enumerate
box.app_id and box.environment_id, including owned Boxes absent from the active
selection. cloud_app.deployments.box_id and spec.assigned.box_id retain their
execution-history and Supervisor protocol meanings. The post-deploy migration
removes the former cloud_app.envs.box_id column. App references are validated by
the application, without cascading foreign keys, so destroyed Box history remains
after the owning App or environment is purged.
Partial indexes: (runnerId, state, desiredState) where pending = false
· (id) where pending = true · (id) where
state NOT IN ('destroyed','archived').
GIN indexes: labels and volumes, both jsonb_path_ops.
Other indexes: (state) · (desiredState) · (runnerId) ·
(runnerId, state) · (organizationId) · (region) ·
(cpu, mem, disk, gpu) · (authToken) · (image).
runner
A host machine. Roughly half the columns are live telemetry the scheduler reads to place boxes: declared capacity, current load, current allocation, and a derived availability score.
| Column | Type | Notes |
|---|---|---|
id |
uuid |
primary key |
name |
character varying |
unique per region |
region |
character varying |
holds region.id |
domain |
character varying |
nullable |
apiUrl |
character varying |
nullable; required when apiVersion is 0 |
proxyUrl |
character varying |
nullable; falls back to apiUrl |
apiKey |
character varying |
|
state |
enum |
initializing | ready | disabled | decommissioned | unresponsive |
class |
enum |
default small |
cpu |
double precision |
declared capacity |
memoryGiB |
double precision |
declared capacity |
diskGiB |
double precision |
declared capacity; each heartbeat overwrites it with the size of the filesystem holding the runner's BoxLite home |
gpu |
integer |
nullable |
gpuType |
character varying |
nullable |
currentCpuLoadAverage |
double precision |
|
currentCpuUsagePercentage |
double precision |
|
currentMemoryUsagePercentage |
double precision |
|
currentDiskUsagePercentage |
double precision |
use of that filesystem (df Use%) |
currentAllocatedCpu |
double precision |
|
currentAllocatedMemoryGiB |
double precision |
|
currentAllocatedDiskGiB |
double precision |
used GiB on that filesystem (df Used), not a sum of box sizes |
currentStartedBoxes |
integer |
|
availabilityScore |
integer |
|
unschedulable |
boolean |
default false |
draining |
boolean |
default false |
appVersion |
character varying |
default v0.0.0-dev |
apiVersion |
character varying |
default 0 |
serviceHealth |
jsonb |
nullable |
lastChecked |
timestamptz |
nullable |
createdAt / updatedAt |
timestamptz |
Unique: (region, name). Index:
(state, unschedulable, region) — the placement query.
runner_cpu_incident
Immutable evidence from each two-minute capture after a runner's five-minute CPU
saturation trigger. Captures repeat while high CPU observations continue. Created by the additive
1793232000000-add-runner-cpu-incidents pre-deploy migration.
| Column | Type | Notes |
|---|---|---|
id |
bigint identity |
primary key; exposed as a decimal string |
runnerId / eventId |
uuid |
unique pair; runner identity comes from authentication |
highCpuSince |
timestamptz |
start of the continuously observed high-load interval |
windowStartedAt / windowEndedAt |
timestamptz |
actual attribution window; at least two minutes |
runnerCpuPercent |
double precision |
host-wide percent at trigger, greater than 80 and at most 100 |
boxId |
varchar(128) |
business box ID of largest observed consumer; nullable |
image |
text |
winner's exact BoxInfo.Image string from its last successful sample; null for no winner or older reports; empty string is preserved |
cpuSeconds |
double precision |
cumulative measured CPU time, all cores; zero iff box ID is null |
samplingComplete |
boolean |
false for missing samples, lifecycle changes or counter resets |
receivedAt |
timestamptz |
server receipt time |
Indexes on (runnerId,id) and windowEndedAt support runner and capture-completion
time-range filters. No foreign-key cascade or automatic retention job: evidence
survives resource deletion. A single insert ignores duplicate (runnerId,eventId)
reports through the unique constraint. Admin queries
select the largest cpuSeconds row per Box within the time/Runner filters, with
smaller row IDs breaking ties. Null-attribution rows remain separate. Selection
precedes ID ordering and limit; there is no pagination or commit-order guarantee.
Each window has a distinct event ID. Image is recorded in the same insert and
cannot change on retry; no box-table lookup or organization field is involved.
runner_memory_incident
Immutable snapshots from minute host memory readings strictly above 80%, created
by pre-deploy migration 1793836800000-add-runner-memory-incidents.
Each row contains the five largest readable running-Box usages from one immediate
scan, or fewer if fewer are readable. No rolling window or sustained-load timer applies.
| Column | Type | Notes |
|---|---|---|
id |
bigint identity |
Primary key; decimal string in responses. |
runnerId / eventId |
uuid |
Unique pair; Runner identity comes from authentication. |
sampledAt |
timestamptz |
Time of the host reading that triggered the scan. |
runnerMemoryPercent |
double precision |
Host percentage in (80,100], enforced in the database. |
boxes |
jsonb |
Ordered array, at most five entries; array shape and length enforced in the database. |
samplingComplete |
boolean |
False when Box enumeration or any attribution read fails. |
receivedAt |
timestamptz |
Server receipt time, default now(). |
Each boxes item contains boxId, image, and decimal-string memoryBytes.
Ingestion validates distinct business IDs, nonnegative signed-64-bit byte values,
and ordering by bytes descending then ID ascending. Strings preserve exact bytes
through JSONB and JavaScript. An empty array represents no readable Boxes;
zero-byte Boxes remain valid observations. Image strings come from the same scan,
including empty strings. No Box-table lookup is needed.
Indexes on sampledAt and (runnerId,id) support the
administrator query. A duplicate event is ignored
atomically, preserving all original rankings. There are no resource foreign-key
cascades or automatic retention jobs. A single JSONB snapshot keeps the bounded
ranking atomic without a separate child table.
Queries select each Box's maximum numeric memoryBytes within the time/Runner
filters, with smaller snapshot IDs breaking ties. They return only winning entries
in their source snapshots, preserving entry order and originally empty snapshots,
then apply ID ordering and the snapshot limit. These projections do not modify
the persisted JSONB arrays.
runner_disk_expansion
One data-disk expansion attempt per row, created by pre-deploy migration
1794528002000-add-runner-disk-expansion. Written only by the runner-disk-expansion
cron (runner-disk-expansion.service.ts); everything else reads it.
Expansion is enabled by default; setting RUNNER_DISK_EXPANSION_ENABLED=false
stops that cron and its sampling. Existing disk_expand_exhausted marks are
not lifted while it is off.
The disk identity the controller expands is the runner's own report
(dataDiskRef, refreshed on each heartbeat that carries it). The API records
no independent binding between a runner and its disk: a runner's ref sits in
the same trust tier as its other heartbeat telemetry (sizes, usage, health),
and the write's reach is bounded by the service account's IAM scope, the
per-runner resize budget, and the cap. Recording an authoritative identity at
provisioning was considered and rejected — the precondition, a compromised
runner host, already grants more damaging capabilities (2026-11-12).
| Column | Type | Notes |
|---|---|---|
id |
uuid |
primary key |
runnerId |
uuid |
cascades with the runner row |
fromGiB / toGiB |
double precision |
toGiB is the requested block-device size; fromGiB is the runner-reported filesystem total at request time (~2% below the device) |
accepted |
boolean |
whether the cloud accepted the request; only accepted rows count against the resize budget |
performanceUpdated |
boolean |
whether the PATCH carried provisioned-performance fields; every such attempt starts the per-disk performance cooldown regardless of outcome |
operation |
text |
nullable; zone operation name to poll for completion |
status |
enum |
pending | confirmed | failed |
error |
text |
nullable; rate_limited, not_accepted, unconfirmed, or the raw operation error |
requestedAt / confirmedAt |
timestamptz |
confirmedAt set only on confirmed |
Index: (runnerId, requestedAt) — the trailing resize-budget window, the
rate-limit cooldown, and per-runner history all query by it.
runner_disk_usage_sample
Per-runner disk usage history for the expansion water level, created by pre-deploy
migration 1794528003000-add-runner-disk-usage-sample. Once per round the expansion
cron samples each READY runner that reports an expandable disk, upserting into the
runner's current bucket and keeping the maximum usage seen in it: a spike is
preserved when a round still sees it as the runner's latest heartbeat state, while
one that appears and recovers entirely between two rounds is lost. The expansion
cron deletes rows past the retention window (48h by default). usedGiB is the df
Used figure the runner reports as currentAllocatedDiskGiB, not a sum of box sizes.
| Column | Type | Notes |
|---|---|---|
runnerId / bucketAt |
composite primary key | bucketAt is the bucket start, truncated to the sampling interval |
usedGiB |
double precision |
max df Used seen in the bucket |
capacityGiB |
double precision |
filesystem total at the time of the sample |
Foreign key: runnerId cascades with the runner row.
region
A placement domain. Two check constraints keep type and ownership consistent,
and the entity repeats them as a @BeforeInsert/@BeforeUpdate guard.
| Column | Type | Notes |
|---|---|---|
id |
character varying |
primary key; <name>_<nanoid(4)> when not supplied |
name |
character varying |
|
organizationId |
uuid |
nullable |
regionType |
enum |
shared | dedicated | custom |
enforceQuotas |
boolean |
default true |
proxyUrl |
character varying |
nullable |
proxyApiKeyHash |
character varying |
nullable |
createdAt / updatedAt |
timestamptz |
Checks: region_not_shared — a shared region may not belong to an
organization; region_not_custom — a custom region must.
Partial unique: (organizationId, name) where organizationId is not
null · (name) where organizationId is null · (proxyApiKeyHash) where not
null.
volume
Persistent storage, backed one-to-one by an object-store bucket whose name is
derived from the row id (boxlite-volume-<id>).
| Column | Type | Notes |
|---|---|---|
id |
uuid |
primary key |
organizationId |
uuid |
nullable |
name |
character varying |
unique per organization |
state |
enum |
7 values, default pending_create |
target_type |
character varying |
box for ordinary organization volumes, app for App-owned volumes |
app_id |
text |
stable App ID, required for an App target |
environment_id |
text |
stable provisioning environment ID, required for an App target |
errorReason |
character varying |
nullable |
lastUsedAt |
timestamp |
nullable |
createdAt / updatedAt |
timestamptz |
Attachment lives in box.volumes, so attaching or detaching a volume never
writes to this table.
volume_target requires both ownership references for target_type = 'app' and
null references for target_type = 'box'. volume_app_environment_idx indexes
the App/environment owner. BoxService.create resolves the trusted App
environment before permitting an App-owned mount. The App is the sharing
boundary, including Boxes from another environment of the same App. Ordinary
Boxes and Boxes of another App receive 403.
App provisioning, listing and cleanup use these columns directly. The
pre-deploy migration backfills ownership and synchronizes old mapping writes
during rollout. The post-deploy migration drops cloud_app.env_volumes and its
temporary synchronization trigger. Purging an App destroys all its Boxes before
deleting its volumes, so same-App sharing cannot block cleanup on another Box.
image
One row per upstream repository an organization has pulled, written after a box
built from it reaches STARTED. Curated images are never rows here: they stay
env-driven, and the catalog endpoints union them in at read time. GET /images,
GET /images/usage, GET /images/:idOrRef and DELETE /images/:idOrRef read
these tables; nothing but a box reaching STARTED writes them.
| Column | Type | Notes |
|---|---|---|
id |
uuid |
primary key |
organizationId |
uuid |
not null — there is no shared row |
name |
character varying(255) |
upstream repository path, e.g. docker.io/library/python |
lastUsedAt |
timestamptz |
nullable |
deletedAt |
timestamptz |
nullable — soft delete |
createdAt / updatedAt |
timestamptz |
Uniqueness is a partial index rather than a table constraint, so a soft-deleted
name can be used again; image_org_lastused_index serves the count the
admission gate takes when a create names an image the organization does not
hold yet, and the per-org listing the catalog API serves. A soft delete leaves
the versions and aliases behind — the cascade only fires on a real delete — so
every catalog read joins back to image and filters deletedAt IS NULL.
image_version
One row per distinct manifest digest of an image. Rows appear only after a pull
succeeds, so there is no pending state to go stale — a failed pull is recorded
on the box that attempted it. The one thing a failed pull writes here is
upstreamMissingAt, on a build the registry no longer has.
| Column | Type | Notes |
|---|---|---|
id |
uuid |
primary key |
imageId |
uuid |
→ image.id, cascade delete |
digest |
character varying(71) |
OCI manifest digest, unique per image |
sizeBytes |
bigint |
sum of the declared layer sizes |
state |
enum |
ready | deleted, default ready |
sourceKind |
enum |
pull |
sourceSpec |
jsonb |
{ sourceRef } — what the user typed |
storageRef |
text |
where to fetch the bytes from |
lastUsedAt |
timestamptz |
nullable; when a box last started from this build |
upstreamMissingAt |
timestamptz |
nullable; when a pull first failed with the registry's MANIFEST_UNKNOWN or NAME_UNKNOWN. A mark, not a state: never cleared, and the version stays usable on runners that cached it |
createdAt |
timestamptz |
The digest is unique per image, not per organization: the same public image reached through two upstream paths is normal usage.
Catalog bindings are called aliases in the API, SDKs and entity classes.
ImageAlias and ImageAliasEvent map to the existing image_tag and
image_tag_event storage names; aliasName maps to column tagName.
These explicit mappings preserve existing data and rolling-deployment compatibility.
Alias creation uses the unique image/name constraint and refuses conflicts;
deletion removes only the binding. Registry tags remain upstream reference metadata.
image_tag
The version a catalog alias selects. Pulls seed aliases from registry tags.
Explicit creation refuses every existing name; replacing a binding requires
deleting the alias and creating it again. Picking up where a tag points upstream
is DELETE /images/:idOrRef followed by using the reference again, which brings
the name back as a fresh entry.
| Column | Type | Notes |
|---|---|---|
id |
uuid |
primary key |
imageId |
uuid |
→ image.id, cascade delete |
name |
character varying(128) |
unique per image |
versionId |
uuid |
→ image_version.id, restrict delete |
updatedAt |
timestamptz |
versionId restricts rather than cascades: a version an alias still names must not
disappear underneath it. Postgres does not index a foreign key on its own, and
this one is walked whenever a version is deleted, so image_tag_version_index
covers it.
image_tag_event
Alias registration history. A row is written when a pull seeds an alias or an explicit creation succeeds, and is never updated. The history of an image is this table read newest first.
| Column | Type | Notes |
|---|---|---|
id |
uuid |
primary key |
imageId |
uuid |
→ image.id, cascade delete |
tagName |
character varying(128) |
|
fromVersionId |
uuid |
nullable; → image_version.id, restrict delete. Null for alias creation |
toVersionId |
uuid |
→ image_version.id, restrict delete |
actorId |
character varying |
nullable; the identity provider subject of whoever created it. Null when a pull seeded the alias |
createdAt |
timestamptz |
default clock_timestamp() |
createdAt is the moment the row is written, not the start of its transaction:
registration writes use the time the row is inserted, so concurrent creations
sort by their observed write time. image_tag_event_image_created_index on
("imageId","createdAt") serves the newest-first read backwards.
registry_credential
A login an organization registered for a private registry. The password is in no column: it is written to Secret Manager, which the API can write but not read, and the row keeps only the name of the version that holds it.
| Column | Type | Notes |
|---|---|---|
id |
uuid |
primary key |
organizationId |
uuid |
not null |
kind |
enum |
basic |
registryHost |
character varying(255) |
e.g. ghcr.io |
repositoryPrefix |
character varying(255) |
default '', the whole host |
username |
character varying(255) |
|
secretVersion |
text |
the Secret Manager version holding the password |
createdBy |
character varying |
nullable — the identity provider's subject, not a uuid |
createdAt / updatedAt |
timestamptz |
registry_credential_org_host_prefix_unique allows one credential per host and
prefix in an organization; its leading columns also serve the lookup by
organization and host. registry_credential_prefix_shape holds a prefix to
whole path segments, '' or ending in /, so acme/ cannot match
acme-other/app.
job
A unit of work handed to exactly one runner. Optimistic-locked through
version; the target resource is polymorphic.
| Column | Type | Notes |
|---|---|---|
id |
uuid |
primary key |
version |
integer |
TypeORM @VersionColumn |
type |
character varying |
9 values; see below |
status |
enum |
PENDING | IN_PROGRESS | COMPLETED | FAILED |
runnerId |
character varying |
|
resourceType |
enum |
BOX | ARTIFACT | BACKUP |
resourceId |
character varying |
|
payload |
character varying |
nullable; JSON text |
resultMetadata |
character varying |
nullable; JSON text |
traceContext |
jsonb |
nullable |
errorMessage |
text |
nullable |
startedAt |
timestamptz |
nullable |
completedAt |
timestamptz |
nullable |
createdAt / updatedAt |
timestamptz |
Job types: CREATE_BOX, START_BOX, STOP_BOX, DESTROY_BOX, EXPORT_BOX,
IMPORT_BOX, ROLLBACK_EXPORT_BOX, ROLLBACK_IMPORT_BOX,
DISCARD_EXPORTED_BOX.
Partial unique: (resourceType, resourceId, runnerId) where
completedAt IS NULL — history accumulates freely, but at most one job per
(resource, runner) is ever in flight.
Indexes: (runnerId, status) · (status, createdAt) ·
(resourceType, resourceId).
checkpoint
Durable metadata for captured Box checkpoints, independent of the source Box's
lifetime. Created by 1793923200000-add-checkpoints-migration.ts and extended
by 1795564800000-add-checkpoint-kind-migration.ts.
| Column | Type | Notes |
|---|---|---|
id |
uuid |
primary key |
organizationId |
uuid |
|
name |
character varying |
unique per organization |
sourceBoxId |
character varying |
historical source identity; no FK |
sourceRunnerId |
uuid |
|
sourceState |
character varying |
source Box state at capture |
state |
character varying |
creating | ready | failed | deleting, default creating |
kind |
character varying |
disk | full, default disk; check-constrained |
memorySizeBytes |
bigint |
nullable; check-constrained >= 0; populated for full checkpoints |
arcPath |
character varying |
object store URI |
exportJobId / activeJobId |
uuid |
nullable; activeJobId has a partial unique index when non-null |
environment / archive |
jsonb |
captured Box environment and immutable export artifact metadata |
errorReason |
text |
nullable |
createdAt / updatedAt |
timestamptz |
The migration defaults existing checkpoints to disk. An accepted full export
records its memory size both in memorySizeBytes and in the archive JSON; disk
archives omit it. Reverting the migration locks the table and refuses rollback if
any row has kind = 'full'.
box_migration
A box in flight between runners, one row per box being moved. The row is the migration: it appears when the marker claims a parked box and is deleted once the box is no longer migrating, so "not migrating" has a single representation and the table stays the size of the work in flight rather than the size of the fleet.
| Column | Type | Notes |
|---|---|---|
boxId |
character varying |
primary key, FK → box.id |
state |
enum |
pending_export | pending_import | pending_discard_exported | pending_rollback | completed |
arcPath |
character varying |
default ''; object key of the archive, empty means none to reclaim |
runnerId |
uuid |
nullable; the migration's second runner |
updatedAt |
timestamptz |
a copy of box.updatedAt |
updatedAt is the interlock. Every migration step copies box.updatedAt
while holding the box row, so equality reads as "nothing outside the migration
has touched this box". A write from anywhere else moves box.updatedAt past
the copy and breaks the equality, which is the signal to roll back. The column
type deliberately matches box.updatedAt: narrower precision would round the
copy and fail the comparison it exists for.
Index: (state).
tunnel
One access declaration per box port, public or private. A private tunnel stores only its token's hash and a display mask; the full token is returned once.
| Column | Type | Notes |
|---|---|---|
id |
uuid |
primary key |
box_id |
character varying(12) |
FK → box.id, cascades on hard deletion |
port |
integer |
1–65535 |
access_mode |
character varying |
public or private |
token_hash |
character varying |
null for public; non-null for private |
token_mask |
character varying |
nullable; display mask of a private token |
auth_generation |
integer |
default 1; incremented on revoke and on redeclaring after revoke, invalidating browser sessions |
created_at |
timestamptz |
creation time |
revoked_at |
timestamptz |
null while active |
Unique: (box_id, port). Repeating an authorized tunnel request keeps the
declaration active. DELETE …/network/tunnel?port={port} sets revoked_at;
declaring the port again clears it.
The migration creates no declarations for existing boxes. Existing preview and
tunnel hostnames become reachable only after the owner prepares that port with
POST /api/v1/boxes/{boxId}/network/tunnel?port={port}. Rows survive box
stop/start and proxy restart; hard deletion of a box removes its rows.
domain
A hostname an organization holds, and its typed target. The hostname belongs to
the organization for as long as the row exists. target_type selects Box or App;
its reference (box_id or app_id) is null while held but unbound. Box bindings
name the port independently of its tunnel, and several hostnames can share a port.
| Column | Type | Notes |
|---|---|---|
id |
uuid |
primary key |
hostname |
character varying(253) |
the full lowercase hostname, such as demo.apps.example |
kind |
character varying |
persisted platform or custom; only platform rows consume the domain allowance |
organization_id |
uuid |
holder; no FK, like box.organization_id |
target_type |
character varying |
box (default) or app; selects which reference is meaningful |
app_id |
character varying(255) |
stable Cloud App reference; nullable, nonblank when set; no FK |
environment_id |
text |
stable Cloud App environment reference; nullable while unbound |
box_id |
character varying(12) |
Box reference without FK; retained after Box deletion; null for App targets or unbound Box targets |
port |
integer |
the target port, 1–65535; required when box_id is set, ignored when it is null |
created_at / updated_at |
timestamptz |
Unique: hostname, so one organization holds a name. Index:
(organization_id), (box_id, port), (app_id) and non-null (environment_id), not unique. Check: Box
targets have no app_id, and a non-null box_id requires a valid port. App targets
have no box_id or port. Unsupported target types and blank App references fail.
Claim and binding run under SELECT … FOR UPDATE on the organization row; claim
counts only platform names against organization.domain_count_limit. Neither
operation touches tunnel. Binding a name held for another of the organization's
ports sets the Box type/reference/port, clears app_id and environment_id, and leaves other names on
that port alone. Unbinding (by full hostname, DELETE /api/v1/domains/{hostname}/target)
clears the target references, environment and port, retaining the target type and the row.
Destroying a Box and later deleting its database row preserve box_id and port.
Lists and target resolution continue to return that stored target until explicit
unbind or rebind. The REST binding endpoint validates the live Box and its
organization; no foreign key ties the domain's lifetime to Box cleanup.
Revoking the tunnel also preserves the target: the name answers 404 until the port
is declared again. Held names, including unbound names and bindings to deleted
Boxes, count against the limit only when their persisted kind is platform, and
can be rebound only by their organization. Custom rows require a matching ready
configuration with completed setup; bind/resolve independently enforce the current subscription grant.
The latest verified application may transfer custom ownership, clearing the old target and invalidating older applications.
Legacy custom rows without a configuration fail closed. New custom ownership is
inserted only after configuration-specific DNS proof; historical kinds are not reclassified.
DomainService.resolve reads the stored target independently of port publication.
PreviewController.resolveDomain applies TunnelService.isPublicAccessAllowed to
Box targets. App targets resolve their stored environment against a live App and
return its stable environment ID for the App gateway. This keeps domain ownership and
binding separate from tunnel policy while preserving the same public-access,
inbound and box-state checks. A stored target may therefore resolve internally
while its preview endpoint returns 404. Destroy requests first update the desired
Box state; preview refusal follows the actual-state check and its existing
three-second access cache. Destroyed or missing Boxes fail that check even when
the domain retains their ID and port.
App binding locks the App and environment rows, checks organization ownership and records both stable IDs. Default App environment URLs and additional aliases use this table and the same domain allowance. A deleted App or missing environment returns 404 from preview resolution while ownership remains stored. App gateway access and end-user identity checks run after domain resolution.
custom_domain_config
Durable custom-domain setup, ownership evidence, provider progress and cleanup tombstones; organization subscription grants live separately in Redis.
| Fields | Contract |
|---|---|
organization_id, hostname, domain_id |
Draft organization and, after verification, the unique held domain |
challenge, generation, provider_state |
Stable TXT challenge and exact cloud resource/operation identities |
phase, confirmed_at, submission_status |
Setup completion and distinct not-submitted/unknown/accepted submission outcomes |
dns_checks, dns_checked_at, tls_checked_at |
Per-record results and actual observation times |
certificate_expires_at, certificate_observed_at |
Observed certificate lifetime; never a permanent route deadline |
lease_owner, lease_until, next_check_at |
Hostname-wide execution exclusion, fenced publication and retry timing |
superseded_by, deleted_at, cleaned_at, last_action_at |
Invalidation, recoverable cleanup and abandoned draft age |
Database phases remain pending_verification, pending_certificate_dns, provisioning, ready and deleting.
The response presents a superseded tombstone as superseded; provider_state.progress describes the finer issuance/map/TLS stage.
A winner transaction clears other configs' unique domain_id, supersedes them and transfers the held domain while clearing its binding.
Every execution claim considers all configurations for the hostname, including tombstones; a stale lease cannot publish Ready.
Legacy dns_valid_until, certificate_valid_until and challenge_expires_at remain for migration compatibility but no longer authorize routing.
Capped legacy certificate deadlines are not actual expiration times; unfinished legacy setups require explicit verification.
The migration refuses automatic downgrade after ownership transfers; see deployment cutover.
Unbind retains resources. Delete and supersession revoke routing before cloud cleanup, preserving deterministic resource IDs without organization foreign keys. Explicit deletion clears the supersession marker so a replaced configuration no longer appears in the organization's list. The API task uses saved retry times and hostname leases to resume setup and cleanup; see the API contract.
box_last_activity
Heartbeat timestamp, one row per box, in its own table. Writing it therefore
never touches box.updatedAt — the column the migration interlock compares
against.
| Column | Type | Notes |
|---|---|---|
boxId |
character varying |
primary key, FK → box.id |
lastActivityAt |
timestamptz |
nullable |
warm_pool
Pre-started capacity. The table holds no box id: a request is matched against the pool by shape, which is why one index covers every shape column at once.
| Column | Type | Notes |
|---|---|---|
id |
uuid |
primary key |
pool |
integer |
target pool size |
image |
character varying |
|
target |
character varying |
|
class |
enum |
default small |
cpu |
double precision |
allocation in cores, precision 0.001 |
mem / disk / gpu |
integer |
|
gpuType |
character varying |
|
osUser |
character varying |
|
env |
simple-json |
default {} |
errorReason |
character varying |
nullable |
createdAt / updatedAt |
timestamptz |
Index: warm_pool_find_idx (image, target, class, cpu, mem, disk, gpu, osUser, env).
Fractional CPU allocations
Creation, query responses, warm-pool matching, Runner requests, and usage periods retain the requested CPU allocation.
Runner allocation telemetry and usage exports count configured cores, not the rounded guest vCPU topology.
For example, 0.5 CPU for one hour records 1800 vCPU-seconds.
The existing availability-score scheduler does not reserve CPU capacity per request. The CPU-column migration preserves defaults and indexes; rollback refuses fractional or out-of-range rows rather than rounding allocations. See the deployment sequence and rollback constraints before enabling fractional requests.
Metering
A box bills against exactly one open period at a time. Closing a period writes the archive row and the outbox row in the same transaction, so a usage fact can never be archived without an export intent, and an intent can never survive a rolled-back archive.
box_usage_periods
Open intervals — the hot table. One row per box currently accruing usage, closed and moved to the archive on stop, resize, or destroy.
| Column | Type | Notes |
|---|---|---|
id |
uuid |
primary key |
boxId |
character varying |
|
organizationId |
character varying |
denormalized to keep billing queries single-table |
startAt |
timestamptz |
|
endAt |
timestamptz |
nullable; null means the period is open |
cpu / gpu / mem / disk |
double precision |
|
region |
character varying |
Partial unique: (boxId) where endAt IS NULL.
Running periods store exact memory GiB from box.memory_mib / 1024, with the
legacy fallback for null rows. Disk-only periods keep memory at zero.
Indexes: (boxId, endAt); (organizationId, startAt) INCLUDE (boxId, endAt)
for compute-bearing periods.
box_usage_periods_archive
Column-for-column duplicate of box_usage_periods holding only closed
periods, so the live table stays small. endAt is NOT NULL here.
| Column | Type | Notes |
|---|---|---|
id |
uuid |
primary key |
boxId |
character varying |
|
organizationId |
character varying |
|
startAt / endAt |
timestamptz |
both non-null |
cpu / gpu / mem / disk |
double precision |
|
region |
character varying |
Indexes: (organizationId, endAt) INCLUDE (boxId, startAt) for
compute-bearing periods; (boxId, organizationId, endAt), which the
box usage read uses.
box_usage_export_outbox
Transactional outbox for finalized usage periods. Progress is recorded per row
rather than as a watermark: neither usage table has a monotonic column, and
adding one would not help, because Postgres sequences can commit out of order
and a seq > cursor reader would silently skip rows.
The event key retains exact source quantities. Only the outbound payload's memory quantity rounds half-up to six decimal GiB places; allocation snapshots use the same rule. Existing outbox payloads are immutable across deployment.
| Column | Type | Notes |
|---|---|---|
eventKey |
character varying |
primary key; deterministic identity of the usage fact |
payload |
jsonb |
the exact message, built once at enqueue |
status |
character varying(16) |
pending | delivered | blocked |
attempts |
integer |
default 0 |
availableAt |
timestamptz |
retry backoff and claim visibility timeout |
deliveredAt |
timestamptz |
nullable |
lastError |
text |
nullable |
There is deliberately no delivering status. A status that a crashed worker
can leave behind strands the row forever, which loses usage silently — the one
failure direction billing cannot tolerate. Claiming instead pushes
availableAt forward, so a crashed worker's row simply becomes claimable
again, and the duplicate delivery that may cause is absorbed downstream.
Partial index: (status, availableAt) where status = 'pending'.
Checks: attempts >= 0; status restricted to the three values above.
Satellite stores
None of these shares the Postgres schema above, and nothing joins across the boundary.
| Store | Owner | Contents |
|---|---|---|
ClickHouse database otel |
written by otel-collector, read by apps/api |
otel_logs, otel_traces, otel_metrics_gauge — the upstream ClickHouse exporter's own schema, queried by box-telemetry to serve per-box logs, traces, and metrics. The collector uses create_schema: false; self-hosted infrastructure owns table TTLs through CLICKHOUSE_RETENTION_HOURS, defaulting to 720 hours (30 days). |
| Rauthy's embedded SQLite (local stacks only) | rauthy |
Rauthy's own OIDC state — users, clients, auth codes, refresh tokens, signing keys. The control plane knows a person only by the subject Rauthy issues, stored as user.id. |
| Redis | apps/api |
Advisory locks, rate-limit counters, and caches. Not a table store, and not a source of truth: because the locks expire, the invariants that matter live in the partial unique indexes listed above. |
Known gaps
Type drift on five reference columns
organization.id and runner.id are uuid, but five columns that reference
them are declared character varying. A foreign key cannot be added across
that gap without a cast, so the drift and the missing constraint reinforce
each other, and any join between these tables needs an explicit cast today.
| Column | Declared | References | Target type |
|---|---|---|---|
audit_log.organizationId |
character varying |
organization.id |
uuid |
webhook_initialization.organizationId |
character varying |
organization.id |
uuid |
box_usage_periods.organizationId |
character varying |
organization.id |
uuid |
box_usage_periods_archive.organizationId |
character varying |
organization.id |
uuid |
job.runnerId |
character varying |
runner.id |
uuid |
The other eight organization-referencing columns — on box, volume,
region, api_key, organization_user,
organization_role, organization_invitation, and
organization_role_assignment — are uuid, as are box.runnerId,
box.prevRunnerId, and box_migration.runnerId.
Orphaned columns
user.keyPair remains a nullable physical column for older API instances and rollback.
The current User entity no longer maps it, and registration and account linking no longer write or copy generated SSH keys.
The regenerate-key-pair endpoint is removed. Physical column removal requires a later migration after the older reader rollback window closes.
CI Listener execution history
Execution history is stored in the shared ci_listener_state records described
above, independently of current binding/organization rows. Original scope, Box/runner
IDs and pending effects remain available for cleanup after authorization changes.
The current PostgreSQL owner/epoch fences execution writes; admission additionally
requires the live binding and current owner/admin. Deleting history is not cleanup.