Skip to content

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

perf(api): reduce box destroy database pressure (#3234)

Lhfcwseabc2f5e5658
diff --git a/apps/api/.env.example b/apps/api/.env.example
index cd989e607..adbe72b40 100644
--- a/apps/api/.env.example
+++ b/apps/api/.env.example
@@ -112,6 +112,7 @@ AUDIT_CONSOLE_LOG_ENABLED=
# see https://www.iana.org/time-zones
CRON_TIMEZONE=
+BOX_ORGANIZATION_ACTIVITY_ASYNC=true
PROXY_TEMPLATE_URL=http://{{PORT}}-{{boxId}}.proxy.localhost:4000
diff --git a/apps/api/README.md b/apps/api/README.md
index 6c84ad6b8..4d276c6bd 100644
--- a/apps/api/README.md
+++ b/apps/api/README.md
@@ -196,14 +196,14 @@ Hosted Box API errors expose `code` and `message` at the top level; local runtim
nest these fields under `error`. Both use the shared OpenAPI `ErrorResponse` definition.
The mismatch, pending, and unknown status/code pairs follow [E2B's idempotent creation contract](https://docs.e2b.dev/sandbox/idempotency).
-| Condition | Response |
-| --- | --- |
-| Original success recorded | Original status, serialized bytes, Content-Type and Location |
-| Invalid or duplicate key, or a keyed request body with a non-JSON content type | `400` |
-| Same key with changed business input | `409 idempotency_request_mismatch` |
-| Original owner still active | `409 idempotency_in_progress` |
-| Outcome cannot be confirmed | `422 idempotency_outcome_unknown`; no redispatch |
-| Reservation storage unavailable | `503 idempotency_storage_unavailable`; no dispatch |
+| Condition | Response |
+| ------------------------------------------------------------------------------ | ------------------------------------------------------------ |
+| Original success recorded | Original status, serialized bytes, Content-Type and Location |
+| Invalid or duplicate key, or a keyed request body with a non-JSON content type | `400` |
+| Same key with changed business input | `409 idempotency_request_mismatch` |
+| Original owner still active | `409 idempotency_in_progress` |
+| Outcome cannot be confirmed | `422 idempotency_outcome_unknown`; no redispatch |
+| Reservation storage unavailable | `503 idempotency_storage_unavailable`; no dispatch |
Records expire 24 hours after first use. Heartbeats and retries preserve this absolute deadline.
Only trusted validation or proven pre-effect admission errors make the same key retryable.
@@ -1073,13 +1073,13 @@ See PostHog's [aggregations](https://posthog.com/docs/sql/aggregations) and
established tunnels, GitHub-reported CI job activity on an assigned BoxLite JIT runner, successful starts with tenant-owned images and committed checkpoint use.
It uses `cloud_metrics_schema='1'` and the same occurrence UUID/time in PostHog and OTLP logs.
-| Feature | Evidence boundary | Excluded evidence |
-| ------------ | --------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- |
-| SSH | Accepted signed key or certificate, once per authenticated connection | Key probes, denied logins, SSH configuration |
-| Tunnel | Accepted CONNECT with a Runner connection, HTTP 101, or guest HTTP 2xx/3xx | Tunnel preparation, authorization failures, failed upstream requests |
-| CI | Signed `workflow_job.in_progress` or `completed` with a BoxLite label and assigned JIT runner | Worker creation, queued jobs, external runners, unassigned cancellations |
-| Custom image | Successful create/start job with stored `imageIsOrgOwned=true` | Admission alone, failed jobs, curated images, unknown historical provenance |
-| Checkpoint | Archive upload committed as ready (`archive_ready`), or an owned import receipt committed as completed (`box_restored`) | Create clicks, queued exports, failed or cancelled imports and replay |
+| Feature | Evidence boundary | Excluded evidence |
+| ------------ | ----------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- |
+| SSH | Accepted signed key or certificate, once per authenticated connection | Key probes, denied logins, SSH configuration |
+| Tunnel | Accepted CONNECT with a Runner connection, HTTP 101, or guest HTTP 2xx/3xx | Tunnel preparation, authorization failures, failed upstream requests |
+| CI | Signed `workflow_job.in_progress` or `completed` with a BoxLite label and assigned JIT runner | Worker creation, queued jobs, external runners, unassigned cancellations |
+| Custom image | Successful create/start job with stored `imageIsOrgOwned=true` | Admission alone, failed jobs, curated images, unknown historical provenance |
+| Checkpoint | Archive upload committed as ready (`archive_ready`), or an owned import receipt committed as completed (`box_restored`) | Create clicks, queued exports, failed or cancelled imports and replay |
Feature attributes are `feature.name`, `feature.evidence` and `feature.source`.
`correlation.id` identifies the CI Job for CI events and the Box for other features. Login, key, command, URL, repository and workflow names are omitted.
@@ -1162,16 +1162,16 @@ Filter on `properties.environment` to select the deployment for Cloud API operat
Use `cloud.api.operation` for finished Cloud API requests. Select `properties['api.operation']` for the action, `properties['http.status_class']` for `2xx`, `4xx` or `5xx`, and `properties['client.source']` for attribution. For example, filter on `image.alias.create` and `2xx` to count successful alias requests across the supported clients. Each completed HTTP attempt counts separately, including client retries.
-| Product | Actions measured |
-| --- | --- |
-| Boxes, executions, files | Create, delete, start, stop, recover, request an attach ticket, start/signal/kill an execution, upload/download files |
-| Network, SSH, tunnels | Update inbound/outbound settings, configure/enable/disable SSH, prepare/revoke a tunnel |
-| Checkpoints | Request capture, delete, create a Box from a checkpoint (`checkpoint.restore`) |
-| Images, registries, volumes | Add/remove an alias, remove an image, create/update/delete credentials, create/delete a volume |
-| Domains | Claim, bind, unbind; create, verify, prepare, advance or delete a custom domain |
-| CI | Start/cancel a connection flow, select/complete an installation, update/remove a connection, change CI settings |
+| Product | Actions measured |
+| ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Boxes, executions, files | Create, delete, start, stop, recover, request an attach ticket, start/signal/kill an execution, upload/download files |
+| Network, SSH, tunnels | Update inbound/outbound settings, configure/enable/disable SSH, prepare/revoke a tunnel |
+| Checkpoints | Request capture, delete, create a Box from a checkpoint (`checkpoint.restore`) |
+| Images, registries, volumes | Add/remove an alias, remove an image, create/update/delete credentials, create/delete a volume |
+| Domains | Claim, bind, unbind; create, verify, prepare, advance or delete a custom domain |
+| CI | Start/cancel a connection flow, select/complete an installation, update/remove a connection, change CI settings |
| Onboarding and billing actions | Rename an organization, save onboarding, create/copy a quickstart handoff, submit a coupon claim or cancellation feedback. Only the operation and HTTP result are captured. |
-| Organization infrastructure | Create/update/delete a region, rotate its proxy key, create/delete one's own API key, open the webhook portal |
+| Organization infrastructure | Create/update/delete a region, rotate its proxy key, create/delete one's own API key, open the webhook portal |
For `volume.create`, group by `volume.storage_backend` to distinguish standard object storage (`standard`) from GCP Filestore (`performance`). The field reflects the requested class, including the default `standard` when omitted. Filter on `http.status_class=2xx` for successful requests. An unrecognized or null class leaves the field absent. Historical events without the field have an unknown class.
@@ -1580,12 +1580,19 @@ delayed physical cleanup do not advance them. Use current Box state to identify
running Boxes; timestamps do not measure ongoing execution or user interaction.
Automatic lifecycle actions also count.
-`BoxRepository` records these times after the Box write commits, with one
-upsert that only moves a time forward. Box transactions never wait
-on the facts row, and the follow-up waits at most one second for it before giving
-up. The update is best effort: a failure, or a process exit right
-after the commit, loses that advance and only logs it. A later event of the same
-kind repairs it. Writes that bypass `BoxRepository`, such as raw SQL, are not recorded.
+`BoxRepository` records these times after the Box write commits. By default it
+buffers activity in memory for one second, keeps the newest creation and
+modification times per organization, then writes pending organizations in ID
+order and chunks of at most 1000. Each chunk uses one transaction and one
+multi-row upsert. If an organization was deleted before flushing, the chunk's
+foreign-key failure falls back to per-organization writes so healthy
+organizations still commit. `GREATEST` keeps timestamps monotonic.
+Box transactions never wait on the facts row. Each attempt waits at most one
+second for it before giving up; the synchronous configuration instead performs one
+upsert immediately after each Box commit. Updates are best effort: a final
+failure is logged and drops the affected advances; a process exit before the
+buffer flushes loses unflushed advances. A later event of the same kind repairs
+them. Writes that bypass `BoxRepository`, such as raw SQL, are not recorded.
Facts survive Box deletion and are removed with the organization; a deleted
organization's foreign key rejects new writes. Preexisting organizations only
@@ -1643,6 +1650,40 @@ coverage. To test real compatible/new Go decoders, install Go 1.23+ and set
`COMPAT_API_CLIENT_ROOT` to an exported compatibility-release `apps/libs/api-client-go`
directory. Decoder tests consume unmodified responses from the current Box producer.
+## Destroy persistence and organization activity
+
+Ordinary destroy persistence uses one conditional `UPDATE` CTE that also deletes
+`secret_credential`; it does not open a separate transaction. A state/pending
+mismatch returns a Box conflict, and because credential deletion selects only
+updated rows, a conflict cannot revoke credentials. The CTE returns the committed
+`runnerId` and places it on the event's Box. A migration import that commits before
+the update therefore cannot send reconciliation to the previous Runner. The CTE also
+binds the post-invariant `pending` value, so re-destroying an already-destroyed Box
+keeps its terminal `pending=false` instead of recording a new state change. Checkpoint
+targets retain their separate multi-row locking and cancellation transaction. The explicit
+`DESTROYED` event carries the committed Box and post-cancellation checkpoint
+snapshot, which the manager uses after acquiring the lifecycle Redis lock.
+Events without that marker and periodic reconciliation still read fresh Box and
+checkpoint state. Conditional state writes and the lock-code check remain in
+force. Entering `DESTROYING` or `DESTROYED` does not advance `box_last_activity`;
+existing activity rows are retained for other readers. The destroy action returns
+the API version from the Runner it already loaded, so the manager does not issue
+a second Runner query; other lifecycle actions retain their existing cache.
+
+`BOX_ORGANIZATION_ACTIVITY_ASYNC` defaults to true. Organization activation-fact writes
+run after the Box transaction without delaying its caller. A one-second in-memory
+buffer coalesces each organization's maximum timestamps and flushes pending
+organizations in ID order, in chunks of at most 1000 with one transaction and
+upsert per chunk, with at most three attempts and
+jittered exponential backoff. At most one flush runs per process; writes buffered
+while a flush is in flight are written by the flush scheduled after it finishes.
+A write whose organization row no longer exists fails the foreign-key check once
+and is dropped without retries. Module shutdown cancels the scheduled flush.
+`GREATEST` keeps timestamps monotonic. A final
+failure or process exit before flushing can lose activity updates; set the
+variable to false to wait for one best-effort upsert synchronously after each Box
+commit, without retries.
+
## Mutation auditing
Business writes use `@Audit` to insert a pending `audit_log` row before the handler runs.
@@ -1679,8 +1720,7 @@ updates only the still-pending, unexpired row, so a late response cannot overwri
unknown result or recreate a published record. Initial audit insertion and lease acquisition
share one five-second deadline before the handler is called. Later renewals and result
writes each have their own five-second deadline. Pre-handler acquisition failures and
-database timeouts return 503 without invoking the handler; unexpected audit failures return
-500. Result-write failures log their cause and preserve the handler's result.
+database timeouts return 503 without invoking the handler; unexpected audit failures return 500. Result-write failures log their cause and preserve the handler's result.
Deploy the additive lease-column migration before the API; all reconcilers must be
upgraded before this protection applies. Remove new API writers before rolling back
the column.
@@ -1972,7 +2012,7 @@ cleanup using the original App. Delivery recovery keeps separate App checkpoints
| `CI_GITHUB_ORG_APP_CLIENT_SECRET` | Optional Organization App OAuth secret reference for legacy browser grants |
| `CI_SECRET_ENCRYPTION_KEY` | Secret reference resolving to a canonical base64 encoding of 32 bytes for temporary connect state |
| `CI_WORKER_CPUS` / `CI_WORKER_MEMORY_GB` | Defaults 2 CPUs / 2 GB; 1 GB = 1024 MiB |
-| `CI_WORKER_IMAGE` / `CI_WORKER_GROUP_NAME` | Defaults `ghcr.io/boxlite-ai/boxlite-jitbox:latest` / `boxlite-ci-runner`. Set `CI_WORKER_IMAGE` to select a different image. |
+| `CI_WORKER_IMAGE` / `CI_WORKER_GROUP_NAME` | Defaults `ghcr.io/boxlite-ai/boxlite-jitbox:latest` / `boxlite-ci-runner`. Set `CI_WORKER_IMAGE` to select a different image. |
| `CI_SCHEDULER_GENERATION` | Positive deployment generation; mdeploy uses `GITHUB_RUN_ID` or an explicit per-deploy override, never process startup time |
The default JitBox image includes GNU Make for Linux x86-64 jobs. After an
@@ -2065,8 +2105,7 @@ for execution immediately; a slow Box create or JIT delivery does not hold a
whole scheduling batch open. The PostgreSQL allocation journal is the durable
source; in-memory queues are bounded execution indexes, not another service.
-Scope planners use eight concurrent I/O positions and allocation consumers use
-32. These management budgets are separate from organization/Commerce limits.
+Scope planners use eight concurrent I/O positions and allocation consumers use 32. These management budgets are separate from organization/Commerce limits.
Scale Set target versions fence delayed allocation and retirement tasks. [Queue and shutdown contracts](../libs/ci-listener/README.md#asynchronous-allocation-queue)
### Hosted CI management
diff --git a/apps/api/src/admin/services/organization-activation.service.integration.spec.ts b/apps/api/src/admin/services/organization-activation.service.integration.spec.ts
index d373f4ba4..4f9d130bb 100644
--- a/apps/api/src/admin/services/organization-activation.service.integration.spec.ts
+++ b/apps/api/src/admin/services/organization-activation.service.integration.spec.ts
@@ -76,6 +76,10 @@ describeIfDatabase('AdminOrganizationActivationService (real PostgreSQL, applica
const at = (written: Box) => written.updatedAt.toISOString()
const factRows = async (id: string) =>
dataSource.query('SELECT * FROM organization_activation_facts WHERE "organizationId" = $1', [id])
+ const cancelAutomaticFlush = (repository: BoxRepository) => {
+ clearTimeout((repository as any).organizationActivityFlushTimer)
+ ;(repository as any).organizationActivityFlushTimer = undefined
+ }
const waitFor = async (check: () => Promise<boolean>, failure: string) => {
const deadline = Date.now() + 2000
while (Date.now() < deadline) {
@@ -106,6 +110,7 @@ describeIfDatabase('AdminOrganizationActivationService (real PostgreSQL, applica
dataSource,
{ emit: jest.fn() } as never,
{ invalidate: jest.fn(), invalidateOrgId: jest.fn() } as never,
+ { get: () => false } as never,
)
organizations = new OrganizationService(
dataSource.getRepository(Organization),
@@ -139,7 +144,7 @@ describeIfDatabase('AdminOrganizationActivationService (real PostgreSQL, applica
it('returns a committed Box start while another transaction holds the facts row', async () => {
const id = await organization()
const boxId = await box(id)
- const warn = jest.spyOn(Logger.prototype, 'warn').mockImplementation(() => undefined)
+ const error = jest.spyOn(Logger.prototype, 'error').mockImplementation(() => undefined)
const holder = dataSource.createQueryRunner()
await holder.connect()
await holder.startTransaction()
@@ -159,7 +164,13 @@ describeIfDatabase('AdminOrganizationActivationService (real PostgreSQL, applica
])
const [row] = await dataSource.query('SELECT state FROM box WHERE id = $1', [boxId])
expect([started.state, row.state]).toEqual([BoxState.STARTED, BoxState.STARTED])
- expect(warn).toHaveBeenCalledWith(expect.stringContaining(`Failed to record activity of box ${boxId}`))
+ expect(error).toHaveBeenCalledWith(
+ expect.objectContaining({
+ event: 'organization.activity.dropped',
+ boxId,
+ error: expect.stringContaining('lock timeout'),
+ }),
+ )
expect(await service.get(id)).toMatchObject({ lastBoxModifiedAt: null })
} finally {
clearTimeout(deadline)
@@ -183,11 +194,16 @@ describeIfDatabase('AdminOrganizationActivationService (real PostgreSQL, applica
expect(await dataSource.query('SELECT id FROM box')).toEqual([])
expect(await service.get(id)).toMatchObject({ lastBoxCreatedAt: later, lastBoxModifiedAt: at(started) })
- const warn = jest.spyOn(Logger.prototype, 'warn').mockImplementation(() => undefined)
+ const error = jest.spyOn(Logger.prototype, 'error').mockImplementation(() => undefined)
await dataSource.getRepository(Organization).delete(id)
const orphan = await box(id, later)
await transition(orphan, BoxState.STARTED)
- expect(warn).toHaveBeenCalledWith(expect.stringContaining('organization_activation_facts'))
+ expect(error).toHaveBeenCalledWith(
+ expect.objectContaining({
+ event: 'organization.activity.dropped',
+ error: expect.stringContaining('organization_activation_facts'),
+ }),
+ )
expect(await service.get(id)).toBeNull()
expect(await factRows(id)).toEqual([])
})
@@ -302,7 +318,7 @@ describeIfDatabase('AdminOrganizationActivationService (real PostgreSQL, applica
it('keeps the Box write when the facts update fails, and the next start records it', async () => {
const id = await organization()
const boxId = await box(id)
- const warn = jest.spyOn(Logger.prototype, 'warn').mockImplementation(() => undefined)
+ const error = jest.spyOn(Logger.prototype, 'error').mockImplementation(() => undefined)
await dataSource.query('ALTER TABLE organization_activation_facts RENAME TO organization_activation_facts_moved')
let started: Box
try {
@@ -311,7 +327,13 @@ describeIfDatabase('AdminOrganizationActivationService (real PostgreSQL, applica
await dataSource.query('ALTER TABLE organization_activation_facts_moved RENAME TO organization_activation_facts')
}
expect(started.state).toBe(BoxState.STARTED)
- expect(warn).toHaveBeenCalledWith(expect.stringContaining(`Failed to record activity of box ${boxId}`))
+ expect(error).toHaveBeenCalledWith(
+ expect.objectContaining({
+ event: 'organization.activity.dropped',
+ boxId,
+ error: expect.stringContaining('organization_activation_facts'),
+ }),
+ )
expect(await service.get(id)).toMatchObject({ lastBoxModifiedAt: null })
await transition(boxId, BoxState.STOPPED, BoxDesiredState.STOPPED)
const restarted = await transition(boxId, BoxState.STARTED, BoxDesiredState.STARTED)
@@ -332,7 +354,7 @@ describeIfDatabase('AdminOrganizationActivationService (real PostgreSQL, applica
it('backfills only retained creation maxima for existing organizations', async () => {
// Without the facts table, the repository's follow-up updates fail and only log.
- jest.spyOn(Logger.prototype, 'warn').mockImplementation(() => undefined)
+ jest.spyOn(Logger.prototype, 'error').mockImplementation(() => undefined)
await migrate('down')
const older = await legacyOrganization()
const unknown = await legacyOrganization()
@@ -373,4 +395,74 @@ describeIfDatabase('AdminOrganizationActivationService (real PostgreSQL, applica
await writer.release()
}
})
+
+ it('flushes buffered creation maxima for multiple organizations with one upsert', async () => {
+ const asyncBoxes = new BoxRepository(
+ dataSource,
+ { emit: jest.fn() } as never,
+ { invalidate: jest.fn(), invalidateOrgId: jest.fn() } as never,
+ { get: (key: string) => (key === 'boxSync.organizationActivityAsync' ? true : undefined) } as never,
+ )
+ const insert = async (organizationId: string, createdAt: string) => {
+ const entity = new Box('test-region', `box-${randomUUID().slice(0, 8)}`)
+ Object.assign(entity, {
+ organizationId,
+ osUser: 'fixture',
+ labels: {},
+ createdAt: new Date(createdAt),
+ })
+ await asyncBoxes.insert(entity)
+ cancelAutomaticFlush(asyncBoxes)
+ }
+ const first = await organization()
+ const second = await organization()
+
+ await insert(first, later)
+ await insert(first, earlier)
+ await insert(second, earlier)
+ expect(await factRows(first)).toEqual([])
+ expect(await factRows(second)).toEqual([])
+
+ await (asyncBoxes as any).flushOrganizationActivity()
+
+ expect(await service.get(first)).toMatchObject({ lastBoxCreatedAt: later })
+ expect(await service.get(second)).toMatchObject({ lastBoxCreatedAt: earlier })
+ })
+
+ it('keeps healthy organization updates when another buffered organization is deleted', async () => {
+ const asyncBoxes = new BoxRepository(
+ dataSource,
+ { emit: jest.fn() } as never,
+ { invalidate: jest.fn(), invalidateOrgId: jest.fn() } as never,
+ { get: (key: string) => (key === 'boxSync.organizationActivityAsync' ? true : undefined) } as never,
+ )
+ const insert = async (organizationId: string) => {
+ const entity = new Box('test-region', `box-${randomUUID().slice(0, 8)}`)
+ Object.assign(entity, {
+ organizationId,
+ osUser: 'fixture',
+ labels: {},
+ createdAt: new Date(later),
+ })
+ await asyncBoxes.insert(entity)
+ cancelAutomaticFlush(asyncBoxes)
+ }
+ const healthy = await organization()
+ const removed = await organization()
+ await insert(healthy)
+ await insert(removed)
+ await dataSource.getRepository(Organization).delete(removed)
+ const error = jest.spyOn(Logger.prototype, 'error').mockImplementation(() => undefined)
+
+ await (asyncBoxes as any).flushOrganizationActivity()
+
+ expect(error).toHaveBeenCalledWith(
+ expect.objectContaining({
+ event: 'organization.activity.dropped',
+ error: expect.stringContaining('organization_activation_facts'),
+ }),
+ )
+ expect(await service.get(healthy)).toMatchObject({ lastBoxCreatedAt: later })
+ expect(await factRows(removed)).toEqual([])
+ })
})
diff --git a/apps/api/src/box/box.module.ts b/apps/api/src/box/box.module.ts
index 3429fb00a..c8aeba6c6 100644
--- a/apps/api/src/box/box.module.ts
+++ b/apps/api/src/box/box.module.ts
@@ -48,6 +48,7 @@ import { JobService } from './services/job.service'
import { JobStateHandlerService } from './services/job-state-handler.service'
import { Job } from './entities/job.entity'
import { BoxLookupCacheInvalidationService } from './services/box-lookup-cache-invalidation.service'
+import { TypedConfigService } from '../config/typed-config.service'
import { BoxAccessGuard } from './guards/box-access.guard'
import { RunnerAccessGuard } from './guards/runner-access.guard'
import { RegionRunnerAccessGuard } from './guards/region-runner-access.guard'
@@ -178,12 +179,13 @@ import { GcpDiskClient } from './services/gcp-disk-client'
ProxyGuard,
{
provide: BoxRepository,
- inject: [DataSource, EventEmitter2, BoxLookupCacheInvalidationService],
+ inject: [DataSource, EventEmitter2, BoxLookupCacheInvalidationService, TypedConfigService],
useFactory: (
dataSource: DataSource,
eventEmitter: EventEmitter2,
boxLookupCacheInvalidationService: BoxLookupCacheInvalidationService,
- ) => new BoxRepository(dataSource, eventEmitter, boxLookupCacheInvalidationService),
+ configService: TypedConfigService,
+ ) => new BoxRepository(dataSource, eventEmitter, boxLookupCacheInvalidationService, configService),
},
],
exports: [
diff --git a/apps/api/src/box/events/box-destroyed.event.ts b/apps/api/src/box/events/box-destroyed.event.ts
index 9e88a0709..9cf3c8136 100644
--- a/apps/api/src/box/events/box-destroyed.event.ts
+++ b/apps/api/src/box/events/box-destroyed.event.ts
@@ -5,7 +5,11 @@
*/
import { Box } from '../entities/box.entity'
+import { BoxCheckpointState } from '../entities/box-checkpoint-state.entity'
export class BoxDestroyedEvent {
- constructor(public readonly box: Box) {}
+ constructor(
+ public readonly box: Box,
+ public readonly committedState?: { checkpointState: BoxCheckpointState | null },
+ ) {}
}
diff --git a/apps/api/src/box/managers/box-actions/box-destroy.action.spec.ts b/apps/api/src/box/managers/box-actions/box-destroy.action.spec.ts
new file mode 100644
index 000000000..3d9698aed
--- /dev/null
+++ b/apps/api/src/box/managers/box-actions/box-destroy.action.spec.ts
@@ -0,0 +1,101 @@
+/*
+ * Copyright 2026 BoxLite AI
+ * SPDX-License-Identifier: AGPL-3.0
+ */
+
+import { BoxDestroyAction } from './box-destroy.action'
+import { BoxState } from '../../enums/box-state.enum'
+import { BoxDesiredState } from '../../enums/box-desired-state.enum'
+import { RunnerState } from '../../enums/runner-state.enum'
+import { DONT_SYNC_AGAIN, SYNC_AGAIN } from './box.action'
+
+function makeAction() {
+ const runner = { id: 'runner-1', state: RunnerState.READY, apiVersion: '2' }
+ const adapter = {
+ boxInfo: jest.fn().mockResolvedValue({ state: BoxState.STOPPED }),
+ destroyBox: jest.fn().mockResolvedValue(undefined),
+ }
+ const runnerService = { findOneOrFail: jest.fn().mockResolvedValue(runner) }
+ const runnerAdapterFactory = { create: jest.fn().mockResolvedValue(adapter) }
+ const action = new BoxDestroyAction(runnerService as never, runnerAdapterFactory as never, {} as never, {} as never)
+ const updateBoxState = jest.spyOn(action as any, 'updateBoxState').mockResolvedValue(undefined)
+ return { action, runner, adapter, runnerService, runnerAdapterFactory, updateBoxState }
+}
+
+function destroyableBox(state = BoxState.STOPPED) {
+ return {
+ id: 'box-1',
+ runnerId: 'runner-1',
+ state,
+ desiredState: BoxDesiredState.DESTROYED,
+ pending: true,
+ } as never
+}
+
+describe('BoxDestroyAction', () => {
+ it('returns the apiVersion of the Runner it already read', async () => {
+ const { action } = makeAction()
+
+ await expect(action.run(destroyableBox(), {} as never)).resolves.toEqual({
+ syncState: SYNC_AGAIN,
+ runnerApiVersion: '2',
+ })
+ })
+
+ it('does not read a Runner for an already destroyed Box', async () => {
+ const { action, runnerService, runnerAdapterFactory } = makeAction()
+
+ await expect(action.run(destroyableBox(BoxState.DESTROYED), {} as never)).resolves.toEqual({
+ syncState: DONT_SYNC_AGAIN,
+ })
+ expect(runnerService.findOneOrFail).not.toHaveBeenCalled()
+ expect(runnerAdapterFactory.create).not.toHaveBeenCalled()
+ })
+
+ it('finishes an archived Box without reading a Runner', async () => {
+ const { action, runnerService, updateBoxState } = makeAction()
+ const box = destroyableBox(BoxState.ARCHIVED)
+ const lockCode = {} as never
+
+ await expect(action.run(box, lockCode)).resolves.toEqual({ syncState: DONT_SYNC_AGAIN })
+ expect(updateBoxState).toHaveBeenCalledWith(box, BoxState.DESTROYED, lockCode)
+ expect(runnerService.findOneOrFail).not.toHaveBeenCalled()
+ })
+
+ it('stops synchronization when the Runner is not ready', async () => {
+ const { action, runner, runnerAdapterFactory } = makeAction()
+ runner.state = RunnerState.DISABLED
+
+ await expect(action.run(destroyableBox(), {} as never)).resolves.toEqual({
+ syncState: DONT_SYNC_AGAIN,
+ runnerApiVersion: '2',
+ })
+ expect(runnerAdapterFactory.create).not.toHaveBeenCalled()
+ })
+
+ it('finishes when the Runner reports the Box as destroyed', async () => {
+ const { action, adapter, updateBoxState } = makeAction()
+ adapter.boxInfo.mockResolvedValue({ state: BoxState.DESTROYED })
+ const box = destroyableBox()
+ const lockCode = {} as never
+
+ await expect(action.run(box, lockCode)).resolves.toEqual({
+ syncState: DONT_SYNC_AGAIN,
+ runnerApiVersion: '2',
+ })
+ expect(updateBoxState).toHaveBeenCalledWith(box, BoxState.DESTROYED, lockCode)
+ })
+
+ it('finishes when the Runner no longer has the Box', async () => {
+ const { action, adapter, updateBoxState } = makeAction()
+ adapter.boxInfo.mockRejectedValue({ response: { status: 404 } })
+ const box = destroyableBox()
+ const lockCode = {} as never
+
+ await expect(action.run(box, lockCode)).resolves.toEqual({
+ syncState: DONT_SYNC_AGAIN,
+ runnerApiVersion: '2',
+ })
+ expect(updateBoxState).toHaveBeenCalledWith(box, BoxState.DESTROYED, lockCode)
+ })
+})
diff --git a/apps/api/src/box/managers/box-actions/box-destroy.action.ts b/apps/api/src/box/managers/box-actions/box-destroy.action.ts
index 5031ffd08..f73e1a879 100644
--- a/apps/api/src/box/managers/box-actions/box-destroy.action.ts
+++ b/apps/api/src/box/managers/box-actions/box-destroy.action.ts
@@ -7,7 +7,7 @@
import { Injectable } from '@nestjs/common'
import { Box } from '../../entities/box.entity'
import { BoxState } from '../../enums/box-state.enum'
-import { DONT_SYNC_AGAIN, BoxAction, SyncState, SYNC_AGAIN } from './box.action'
+import { DONT_SYNC_AGAIN, BoxAction, SyncState, SYNC_AGAIN, BoxActionResult } from './box.action'
import { RunnerState } from '../../enums/runner-state.enum'
import { RunnerService } from '../../services/runner.service'
import { RunnerAdapterFactory } from '../../runner-adapter/runnerAdapter'
@@ -27,19 +27,20 @@ export class BoxDestroyAction extends BoxAction {
}
@WithSpan()
- async run(box: Box, lockCode: LockCode): Promise<SyncState> {
+ async run(box: Box, lockCode: LockCode): Promise<BoxActionResult> {
if (box.state === BoxState.DESTROYED) {
- return DONT_SYNC_AGAIN
+ return { syncState: DONT_SYNC_AGAIN }
}
if (box.state === BoxState.ARCHIVED) {
await this.updateBoxState(box, BoxState.DESTROYED, lockCode)
- return DONT_SYNC_AGAIN
+ return { syncState: DONT_SYNC_AGAIN }
}
const runner = await this.runnerService.findOneOrFail(box.runnerId)
+ const result = (syncState: SyncState): BoxActionResult => ({ syncState, runnerApiVersion: runner.apiVersion })
if (runner.state !== RunnerState.READY) {
- return DONT_SYNC_AGAIN
+ return result(DONT_SYNC_AGAIN)
}
const runnerAdapter = await this.runnerAdapterFactory.create(runner)
@@ -49,7 +50,7 @@ export class BoxDestroyAction extends BoxAction {
if (boxInfo.state === BoxState.DESTROYED) {
await this.updateBoxState(box, BoxState.DESTROYED, lockCode)
- return DONT_SYNC_AGAIN
+ return result(DONT_SYNC_AGAIN)
}
const needsTransition = box.state !== BoxState.DESTROYING
@@ -58,12 +59,12 @@ export class BoxDestroyAction extends BoxAction {
if (needsTransition) await this.updateBoxState(box, BoxState.DESTROYING, lockCode)
}
- return SYNC_AGAIN
+ return result(SYNC_AGAIN)
} catch (error) {
// if the box is not found on runner, it is already destroyed
if (error.response?.status === 404 || error.statusCode === 404) {
await this.updateBoxState(box, BoxState.DESTROYED, lockCode)
- return DONT_SYNC_AGAIN
+ return result(DONT_SYNC_AGAIN)
}
throw error
diff --git a/apps/api/src/box/managers/box-actions/box.action.ts b/apps/api/src/box/managers/box-actions/box.action.ts
index 89dcba875..7b7446a12 100644
--- a/apps/api/src/box/managers/box-actions/box.action.ts
+++ b/apps/api/src/box/managers/box-actions/box.action.ts
@@ -16,6 +16,7 @@ import { LockCode, RedisLockProvider } from '../../common/redis-lock.provider'
export const SYNC_AGAIN = 'sync-again'
export const DONT_SYNC_AGAIN = 'dont-sync-again'
export type SyncState = typeof SYNC_AGAIN | typeof DONT_SYNC_AGAIN
+export type BoxActionResult = { syncState: SyncState; runnerApiVersion?: string }
@Injectable()
export abstract class BoxAction {
@@ -28,7 +29,7 @@ export abstract class BoxAction {
protected readonly redisLockProvider: RedisLockProvider,
) {}
- abstract run(box: Box, lockCode: LockCode): Promise<SyncState>
+ abstract run(box: Box, lockCode: LockCode): Promise<SyncState | BoxActionResult>
protected async updateBoxState(
box: Box,
diff --git a/apps/api/src/box/managers/box.manager.sync-error.spec.ts b/apps/api/src/box/managers/box.manager.sync-error.spec.ts
index e5a4e0c72..623651b8f 100644
--- a/apps/api/src/box/managers/box.manager.sync-error.spec.ts
+++ b/apps/api/src/box/managers/box.manager.sync-error.spec.ts
@@ -8,6 +8,8 @@ import { QueryFailedError } from 'typeorm'
import { BoxDesiredState } from '../enums/box-desired-state.enum'
import { BoxState } from '../enums/box-state.enum'
import { BoxManager } from './box.manager'
+import { BoxDestroyedEvent } from '../events/box-destroyed.event'
+import { DONT_SYNC_AGAIN, SYNC_AGAIN } from './box-actions/box.action'
const BOX = {
id: 'box-1',
@@ -25,18 +27,20 @@ function makeManager(startFailure: Error) {
}
const imagePullFailureService = { reasonFor: jest.fn().mockResolvedValue('explained') }
const start = { run: jest.fn().mockRejectedValue(startFailure) }
+ const destroy = { run: jest.fn().mockResolvedValue(DONT_SYNC_AGAIN) }
+ const runnerService = { getRunnerApiVersion: jest.fn().mockResolvedValue('0') }
const manager = new BoxManager(
boxRepository as never,
- {} as never,
+ runnerService as never,
{} as never,
{ lock: jest.fn().mockResolvedValue(true), unlock: jest.fn().mockResolvedValue(undefined) } as never,
start as never,
{} as never,
- {} as never,
+ destroy as never,
imagePullFailureService as never,
{ get: () => undefined } as never,
)
- return { manager, boxRepository, imagePullFailureService, start }
+ return { manager, boxRepository, imagePullFailureService, start, destroy, runnerService }
}
describe('BoxManager sync errors', () => {
@@ -93,4 +97,60 @@ describe('BoxManager sync errors', () => {
log.mockRestore()
}
})
+
+ it('uses the committed snapshot carried by an explicit destroy event', async () => {
+ const { manager, boxRepository, destroy } = makeManager(new Error('must not start'))
+ const box = {
+ ...BOX,
+ state: BoxState.STOPPED,
+ desiredState: BoxDesiredState.DESTROYED,
+ pending: true,
+ }
+ const event = new (BoxDestroyedEvent as any)(box, { checkpointState: null })
+
+ await (manager as any).handleBoxDestroyedEvent(event)
+
+ expect(boxRepository.findWithCheckpointState).not.toHaveBeenCalled()
+ expect(destroy.run).toHaveBeenCalledWith(box, expect.anything())
+ })
+
+ it('does not look up Runner apiVersion when a destroy action needs no more synchronization', async () => {
+ const { manager, boxRepository, runnerService } = makeManager(new Error('must not start'))
+ boxRepository.findWithCheckpointState.mockResolvedValue({
+ box: {
+ ...BOX,
+ state: BoxState.STOPPED,
+ desiredState: BoxDesiredState.DESTROYED,
+ pending: true,
+ runnerId: 'runner-1',
+ },
+ checkpointState: null,
+ })
+
+ await manager.syncInstanceState(BOX.id)
+
+ expect(runnerService.getRunnerApiVersion).not.toHaveBeenCalled()
+ })
+
+ it('uses the apiVersion returned by destroy instead of querying Runner again', async () => {
+ const { manager, boxRepository, destroy, runnerService } = makeManager(new Error('must not start'))
+ boxRepository.findWithCheckpointState.mockResolvedValue({
+ box: {
+ ...BOX,
+ state: BoxState.STOPPED,
+ desiredState: BoxDesiredState.DESTROYED,
+ pending: true,
+ runnerId: 'runner-1',
+ },
+ checkpointState: null,
+ })
+ destroy.run
+ .mockResolvedValueOnce({ syncState: SYNC_AGAIN, runnerApiVersion: '0' })
+ .mockResolvedValueOnce(DONT_SYNC_AGAIN)
+
+ await manager.syncInstanceState(BOX.id)
+
+ expect(destroy.run).toHaveBeenCalledTimes(2)
+ expect(runnerService.getRunnerApiVersion).not.toHaveBeenCalled()
+ })
})
diff --git a/apps/api/src/box/managers/box.manager.ts b/apps/api/src/box/managers/box.manager.ts
index c02ed8563..05960e1c9 100755
--- a/apps/api/src/box/managers/box.manager.ts
+++ b/apps/api/src/box/managers/box.manager.ts
@@ -27,13 +27,14 @@ import { BoxStartedEvent } from '../events/box-started.event'
import { BoxDestroyedEvent } from '../events/box-destroyed.event'
import { BoxCreatedEvent } from '../events/box-create.event'
import { Box } from '../entities/box.entity'
+import { BoxCheckpointState } from '../entities/box-checkpoint-state.entity'
import { WithInstrumentation, WithSpan } from '../../common/decorators/otel.decorator'
import { BoxStartAction } from './box-actions/box-start.action'
import { BoxStopAction } from './box-actions/box-stop.action'
import { BoxDestroyAction } from './box-actions/box-destroy.action'
-import { SYNC_AGAIN, DONT_SYNC_AGAIN } from './box-actions/box.action'
+import { SYNC_AGAIN, DONT_SYNC_AGAIN, SyncState, BoxActionResult } from './box-actions/box.action'
import { TrackJobExecution } from '../../common/decorators/track-job-execution.decorator'
import { TrackableJobExecutions } from '../../common/interfaces/trackable-job-executions'
@@ -333,7 +334,11 @@ export class BoxManager implements TrackableJobExecutions, OnApplicationShutdown
* The box entity is mutated in-place by repository.update() on each iteration,
* and the lock guarantees no concurrent modification.
*/
- async syncInstanceState(boxId: string, force?: boolean): Promise<void> {
+ async syncInstanceState(
+ boxId: string,
+ force?: boolean,
+ committed?: { box: Box; checkpointState: BoxCheckpointState | null },
+ ): Promise<void> {
// Track the start time of the sync operation.
const startedAt = new Date()
@@ -348,7 +353,7 @@ export class BoxManager implements TrackableJobExecutions, OnApplicationShutdown
}
try {
- const { box, checkpointState } = await this.boxRepository.findWithCheckpointState(boxId)
+ const { box, checkpointState } = committed ?? (await this.boxRepository.findWithCheckpointState(boxId))
// Checkpoint import commits its configuration before ordinary lifecycle
// reconciliation may start or stop the replacement.
@@ -370,20 +375,20 @@ export class BoxManager implements TrackableJobExecutions, OnApplicationShutdown
}
// Rely on the box action to return SYNC_AGAIN or DONT_SYNC_AGAIN to continue/break the sync loop.
- let syncState = DONT_SYNC_AGAIN
+ let actionResult: SyncState | BoxActionResult = DONT_SYNC_AGAIN
try {
switch (box.desiredState) {
case BoxDesiredState.STARTED: {
- syncState = await this.boxStartAction.run(box, lockCode)
+ actionResult = await this.boxStartAction.run(box, lockCode)
break
}
case BoxDesiredState.STOPPED: {
- syncState = await this.boxStopAction.run(box, lockCode, force)
+ actionResult = await this.boxStopAction.run(box, lockCode, force)
break
}
case BoxDesiredState.DESTROYED: {
- syncState = await this.boxDestroyAction.run(box, lockCode)
+ actionResult = await this.boxDestroyAction.run(box, lockCode)
break
}
}
@@ -431,16 +436,22 @@ export class BoxManager implements TrackableJobExecutions, OnApplicationShutdown
break
}
- // Do not sync again for v2 runners
- // Job completion will update the box state
- if (box.runnerId && (await this.runnerService.getRunnerApiVersion(box.runnerId)) === '2') {
- break
- }
+ const syncState = typeof actionResult === 'string' ? actionResult : actionResult.syncState
+ const runnerApiVersion = typeof actionResult === 'string' ? undefined : actionResult.runnerApiVersion
// Break sync loop if box action returned DONT_SYNC_AGAIN.
if (syncState !== SYNC_AGAIN) {
break
}
+
+ // Do not sync again for v2 runners
+ // Job completion will update the box state
+ if (
+ box.runnerId &&
+ (runnerApiVersion ?? (await this.runnerService.getRunnerApiVersion(box.runnerId))) === '2'
+ ) {
+ break
+ }
}
} finally {
await this.redisLockProvider.unlock(lockKey)
@@ -453,7 +464,10 @@ export class BoxManager implements TrackableJobExecutions, OnApplicationShutdown
@TrackJobExecution()
@WithSpan()
private async handleBoxDestroyedEvent(event: BoxDestroyedEvent) {
- await this.syncInstanceState(event.box.id)
+ const committed = event.committedState
+ ? { box: event.box, checkpointState: event.committedState.checkpointState }
+ : undefined
+ await this.syncInstanceState(event.box.id, undefined, committed)
}
@OnAsyncEvent({
diff --git a/apps/api/src/box/repositories/box.repository.spec.ts b/apps/api/src/box/repositories/box.repository.spec.ts
index 5016f405d..0725df5e1 100644
--- a/apps/api/src/box/repositories/box.repository.spec.ts
+++ b/apps/api/src/box/repositories/box.repository.spec.ts
@@ -7,6 +7,8 @@ import { BoxRepository } from './box.repository'
import { Box } from '../entities/box.entity'
import { BoxState } from '../enums/box-state.enum'
import { BoxDesiredState } from '../enums/box-desired-state.enum'
+import { BoxConflictError } from '../errors/box-conflict.error'
+import { BOX_WARM_POOL_UNASSIGNED_ORGANIZATION } from '../constants/box.constants'
// A chainable UPDATE query-builder stub whose terminal execute() is supplied
// per-test. update/set/where/andWhere/returning all return the same builder.
@@ -24,7 +26,7 @@ function makeQueryBuilder(execute: jest.Mock) {
// Build a BoxRepository whose `manager.transaction` runs the callback against a
// fake entityManager. We bypass DI: only `manager` (a BaseRepository getter
// over repository.manager) and the cache-invalidation hook are exercised here.
-function makeRepository(execute: jest.Mock) {
+function makeRepository(execute: jest.Mock, configService?: { get: (key: string) => unknown }) {
const query = jest.fn().mockResolvedValue(undefined)
const findOne = jest.fn()
const queryBuilder = makeQueryBuilder(execute)
@@ -34,20 +36,384 @@ function makeRepository(execute: jest.Mock) {
const entityManager = {
query,
findOne,
+ update: jest.fn().mockResolvedValue({ affected: 1 }),
+ upsert: jest.fn().mockResolvedValue(undefined),
createQueryBuilder: jest.fn(() => queryBuilder),
create,
}
const manager = {
+ query,
transaction: jest.fn(async (cb: (em: typeof entityManager) => Promise<unknown>) => cb(entityManager)),
}
- const dataSource = { getRepository: () => ({ manager }) } as any
- const repo = new BoxRepository(dataSource, {} as any, {} as any)
+ const dataSource = {
+ getRepository: () => ({ manager }),
+ transaction: manager.transaction,
+ } as any
+ const repo = new BoxRepository(dataSource, { emit: jest.fn() } as any, {} as any, configService as any)
// invalidateLookupCacheOnUpdate touches the real cache service; stub it out —
// it is incidental to the lock-timeout behavior under test.
jest.spyOn(repo as any, 'invalidateLookupCacheOnUpdate').mockImplementation(() => undefined)
- return { repo, query, execute, create, findOne }
+ return { repo, query, execute, create, findOne, entityManager, manager }
}
+describe('BoxRepository organization activity', () => {
+ it('does not make the committed Box write wait for activity persistence', async () => {
+ const { repo, manager } = makeRepository(jest.fn())
+ const box = Object.assign(new Box('region-1'), {
+ id: 'box-1',
+ organizationId: 'org-1',
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ })
+
+ await (repo as any).afterBoxWrite(box)
+
+ expect(manager.transaction).not.toHaveBeenCalled()
+ })
+
+ it('captures malformed activity snapshots without rejecting the background write', async () => {
+ const { repo } = makeRepository(jest.fn())
+ const box = Object.assign(new Box('region-1'), {
+ id: 'box-1',
+ organizationId: 'org-1',
+ createdAt: undefined,
+ updatedAt: new Date(),
+ })
+ const previous = {
+ organizationId: BOX_WARM_POOL_UNASSIGNED_ORGANIZATION,
+ createdAt: undefined,
+ }
+
+ await expect((repo as any).recordOrganizationActivity(box, previous)).resolves.toBeUndefined()
+ })
+
+ it('uses one synchronous write without retries when asynchronous activity is disabled', async () => {
+ jest.useFakeTimers()
+ const { repo } = makeRepository(jest.fn(), { get: () => false })
+ const manager = (repo as any).manager
+ manager.transaction = jest.fn().mockRejectedValueOnce(new Error('temporary failure'))
+ const box = Object.assign(new Box('region-1'), {
+ id: 'box-1',
+ organizationId: 'org-1',
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ })
+
+ const afterWrite = (repo as any).afterBoxWrite(box)
+ await jest.advanceTimersByTimeAsync(1_000)
+
+ await expect(afterWrite).resolves.toBeUndefined()
+ expect(manager.transaction).toHaveBeenCalledTimes(1)
+ jest.useRealTimers()
+ })
+
+ it('stops after three failed asynchronous activity writes', async () => {
+ jest.useFakeTimers()
+ const { repo } = makeRepository(jest.fn())
+ const manager = (repo as any).manager
+ const error = jest.spyOn((repo as any).logger, 'error')
+ manager.transaction = jest.fn().mockRejectedValue(new Error('persistent failure'))
+ const box = Object.assign(new Box('region-1'), {
+ id: 'box-1',
+ organizationId: 'org-1',
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ })
+
+ const recording = (repo as any).recordOrganizationActivity(box)
+ await jest.advanceTimersByTimeAsync(1_000)
+
+ await expect(recording).resolves.toBeUndefined()
+ expect(manager.transaction).toHaveBeenCalledTimes(3)
+ expect(error).toHaveBeenCalledWith(expect.objectContaining({ event: 'organization.activity.dropped', attempt: 3 }))
+ jest.useRealTimers()
+ })
+
+ it('retries a failed activity upsert with bounded backoff', async () => {
+ jest.useFakeTimers()
+ const { repo } = makeRepository(jest.fn())
+ const manager = (repo as any).manager
+ manager.transaction = jest
+ .fn()
+ .mockRejectedValueOnce(new Error('temporary failure'))
+ .mockResolvedValueOnce(undefined)
+ const box = Object.assign(new Box('region-1'), {
+ id: 'box-1',
+ organizationId: 'org-1',
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ })
+
+ const recording = (repo as any).recordOrganizationActivity(box)
+ await jest.advanceTimersByTimeAsync(1_000)
+
+ await expect(recording).resolves.toBeUndefined()
+ expect(manager.transaction).toHaveBeenCalledTimes(2)
+ jest.useRealTimers()
+ })
+ it('batches committed activity by organization and keeps only the newest timestamps', async () => {
+ jest.useFakeTimers()
+ try {
+ const { repo, manager, query } = makeRepository(jest.fn())
+ const first = Object.assign(new Box('region-1'), {
+ organizationId: 'org-1',
+ state: BoxState.STOPPED,
+ desiredState: BoxDesiredState.DESTROYED,
+ pending: true,
+ createdAt: new Date('2026-01-01T00:00:00Z'),
+ updatedAt: new Date('2026-01-01T00:00:01Z'),
+ })
+ const second = Object.assign(new Box('region-1'), {
+ organizationId: 'org-1',
+ state: BoxState.STOPPED,
+ desiredState: BoxDesiredState.DESTROYED,
+ pending: true,
+ createdAt: new Date('2026-01-01T00:00:00Z'),
+ updatedAt: new Date('2026-01-01T00:00:02Z'),
+ })
+ const previous = {
+ organizationId: 'org-1',
+ state: BoxState.STOPPED,
+ desiredState: BoxDesiredState.STOPPED,
+ createdAt: first.createdAt,
+ }
+
+ await (repo as any).afterBoxWrite(first, previous)
+ await (repo as any).afterBoxWrite(second, previous)
+ expect(manager.transaction).not.toHaveBeenCalled()
+
+ await jest.advanceTimersByTimeAsync(1_000)
+
+ expect(manager.transaction).toHaveBeenCalledTimes(1)
+ expect(query).toHaveBeenCalledTimes(2)
+ expect(query.mock.calls[1][0]).toContain('INSERT INTO organization_activation_facts')
+ expect(query.mock.calls[1][1]).toEqual(['org-1', null, second.updatedAt])
+ } finally {
+ jest.useRealTimers()
+ }
+ })
+
+ it('flushes different organizations in one transaction and one upsert', async () => {
+ jest.useFakeTimers()
+ try {
+ const { repo, manager, query } = makeRepository(jest.fn())
+ for (const organizationId of ['org-1', 'org-2']) {
+ const box = Object.assign(new Box('region-1'), {
+ organizationId,
+ createdAt: new Date('2026-01-01T00:00:00Z'),
+ updatedAt: new Date('2026-01-01T00:00:00Z'),
+ })
+ await (repo as any).afterBoxWrite(box)
+ }
+
+ await jest.advanceTimersByTimeAsync(1_000)
+
+ expect(manager.transaction).toHaveBeenCalledTimes(1)
+ expect(query).toHaveBeenCalledTimes(2)
+ expect(query.mock.calls[1][0]).toContain('VALUES ($1::uuid, $2::timestamptz, $3::timestamptz)')
+ expect(query.mock.calls[1][0]).toContain('($4::uuid, $5::timestamptz, $6::timestamptz)')
+ expect(query.mock.calls[1][1]).toEqual([
+ 'org-1',
+ new Date('2026-01-01T00:00:00Z'),
+ null,
+ 'org-2',
+ new Date('2026-01-01T00:00:00Z'),
+ null,
+ ])
+ } finally {
+ jest.useRealTimers()
+ }
+ })
+
+ it('sorts organizations and flushes at most 1000 per transaction', async () => {
+ jest.useFakeTimers()
+ try {
+ const { repo, manager, query } = makeRepository(jest.fn())
+ for (let index = 1000; index >= 0; index--) {
+ ;(repo as any).bufferOrganizationActivity({
+ organizationId: `org-${index.toString().padStart(4, '0')}`,
+ createdAt: new Date('2026-01-01T00:00:00Z'),
+ modifiedAt: null,
+ })
+ }
+
+ await (repo as any).flushOrganizationActivity()
+
+ expect(manager.transaction).toHaveBeenCalledTimes(2)
+ expect(query).toHaveBeenCalledTimes(4)
+ expect(query.mock.calls[1][1][0]).toBe('org-0000')
+ expect(query.mock.calls[1][1][3]).toBe('org-0001')
+ expect(query.mock.calls[1][1]).toHaveLength(3000)
+ expect(query.mock.calls[3][1]).toEqual(['org-1000', new Date('2026-01-01T00:00:00Z'), null])
+ } finally {
+ jest.useRealTimers()
+ }
+ })
+
+ it('drops a single-organization foreign-key violation without retrying', async () => {
+ jest.useFakeTimers()
+ try {
+ const { repo, manager } = makeRepository(jest.fn())
+ const error = jest.spyOn((repo as any).logger, 'error')
+ manager.transaction = jest
+ .fn()
+ .mockRejectedValue(Object.assign(new Error('violates foreign key constraint'), { code: '23503' }))
+ const box = Object.assign(new Box('region-1'), {
+ id: 'box-1',
+ organizationId: 'org-1',
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ })
+
+ await (repo as any).afterBoxWrite(box)
+ await jest.advanceTimersByTimeAsync(2_000)
+
+ expect(manager.transaction).toHaveBeenCalledTimes(1)
+ expect(error).toHaveBeenCalledWith(
+ expect.objectContaining({ event: 'organization.activity.dropped', organizationId: 'org-1', attempt: 1 }),
+ )
+ } finally {
+ jest.useRealTimers()
+ }
+ })
+
+ it('keeps a single flush in flight and drains activity buffered during it', async () => {
+ jest.useFakeTimers()
+ try {
+ const { repo } = makeRepository(jest.fn())
+ const manager = (repo as any).manager
+ const pendingTransactions: Array<() => void> = []
+ manager.transaction = jest.fn(() => new Promise<void>((resolve) => pendingTransactions.push(resolve)))
+ const boxOf = (organizationId: string) =>
+ Object.assign(new Box('region-1'), {
+ organizationId,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ })
+
+ await (repo as any).afterBoxWrite(boxOf('org-1'))
+ await jest.advanceTimersByTimeAsync(1_000)
+ expect(manager.transaction).toHaveBeenCalledTimes(1)
+
+ await (repo as any).afterBoxWrite(boxOf('org-2'))
+ await jest.advanceTimersByTimeAsync(2_000)
+ expect(manager.transaction).toHaveBeenCalledTimes(1)
+
+ pendingTransactions[0]()
+ await jest.advanceTimersByTimeAsync(1_000)
+ expect(manager.transaction).toHaveBeenCalledTimes(2)
+
+ pendingTransactions[1]()
+ await jest.advanceTimersByTimeAsync(1_000)
+ expect((repo as any).pendingOrganizationActivity.size).toBe(0)
+ } finally {
+ jest.useRealTimers()
+ }
+ })
+
+ it('stops scheduling activity flushes once the module is destroyed', async () => {
+ jest.useFakeTimers()
+ try {
+ const { repo, manager } = makeRepository(jest.fn())
+ const box = Object.assign(new Box('region-1'), {
+ organizationId: 'org-1',
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ })
+
+ await (repo as any).afterBoxWrite(box)
+ repo.onModuleDestroy()
+ await jest.advanceTimersByTimeAsync(2_000)
+ expect(manager.transaction).not.toHaveBeenCalled()
+
+ await (repo as any).afterBoxWrite(box)
+ await jest.advanceTimersByTimeAsync(2_000)
+ expect(manager.transaction).not.toHaveBeenCalled()
+ } finally {
+ jest.useRealTimers()
+ }
+ })
+})
+
+describe('BoxRepository.requestDestroy', () => {
+ function destroyableBox() {
+ return Object.assign(new Box('region-1', 'box-name'), {
+ organizationId: 'org-1',
+ state: BoxState.STOPPED,
+ desiredState: BoxDesiredState.STOPPED,
+ pending: false,
+ createdAt: new Date('2026-01-01T00:00:00Z'),
+ updatedAt: new Date('2026-01-01T00:00:00Z'),
+ })
+ }
+
+ it('marks the Box and deletes its credentials in one statement', async () => {
+ const { repo, query } = makeRepository(jest.fn())
+ const box = destroyableBox()
+ query.mockResolvedValue([{ id: box.id }])
+ jest.spyOn(repo as any, 'afterBoxWrite').mockResolvedValue(undefined)
+
+ const updated = await (repo as any).requestDestroy(box)
+
+ expect(query).toHaveBeenCalledTimes(1)
+ const [sql, parameters] = query.mock.calls[0]
+ expect(sql).toContain('WITH destroyed AS')
+ expect(sql).toContain('DELETE FROM secret_credential')
+ expect(sql).toContain('box_id IN (SELECT id FROM destroyed)')
+ expect(parameters).toEqual([
+ box.id,
+ updated.name,
+ updated.updatedAt,
+ BoxDesiredState.DESTROYED,
+ BoxState.STOPPED,
+ false,
+ true,
+ ])
+ expect(updated).toMatchObject({ desiredState: BoxDesiredState.DESTROYED, pending: true })
+ })
+
+ it('preserves the invariant pending value for an already-destroyed Box', async () => {
+ const { repo, query } = makeRepository(jest.fn())
+ const box = Object.assign(destroyableBox(), {
+ state: BoxState.DESTROYED,
+ desiredState: BoxDesiredState.DESTROYED,
+ runnerId: 'runner-1',
+ })
+ query.mockResolvedValue([{ id: box.id, runnerId: null }])
+ jest.spyOn(repo as any, 'afterBoxWrite').mockResolvedValue(undefined)
+
+ const updated = await (repo as any).requestDestroy(box)
+
+ const [sql, parameters] = query.mock.calls[0]
+ expect(sql).toContain('SET pending = $7')
+ expect(parameters[6]).toBe(false)
+ expect(updated).toMatchObject({ pending: false, runnerId: null })
+ })
+
+ it('persists the Runner release required for an archived Box', async () => {
+ const { repo, query } = makeRepository(jest.fn())
+ const box = Object.assign(destroyableBox(), {
+ state: BoxState.ARCHIVED,
+ runnerId: 'runner-1',
+ })
+ query.mockResolvedValue([{ id: box.id, runnerId: null }])
+ jest.spyOn(repo as any, 'afterBoxWrite').mockResolvedValue(undefined)
+
+ await (repo as any).requestDestroy(box)
+
+ expect(box.runnerId).toBeNull()
+ expect(query.mock.calls[0][0]).toContain('"runnerId" = NULL')
+ })
+
+ it('turns a zero-row conditional update into a conflict', async () => {
+ const { repo, query } = makeRepository(jest.fn())
+ query.mockResolvedValue([])
+
+ await expect((repo as any).requestDestroy(destroyableBox())).rejects.toThrow(BoxConflictError)
+ expect(query).toHaveBeenCalledTimes(1)
+ })
+})
+
describe('BoxRepository.updateWhere', () => {
it.each([500, undefined])(
'uses the optional lock timeout (%s) and propagates a row-lock failure',
@@ -80,6 +446,44 @@ describe('BoxRepository.updateWhere', () => {
)
})
+describe('BoxRepository terminal activity', () => {
+ function pendingDestroyBox() {
+ return Object.assign(new Box('region-1', 'box-name'), {
+ organizationId: 'org-1',
+ state: BoxState.STARTED,
+ desiredState: BoxDesiredState.DESTROYED,
+ pending: true,
+ createdAt: new Date('2026-01-01T00:00:00Z'),
+ updatedAt: new Date('2026-01-01T00:00:00Z'),
+ })
+ }
+
+ it.each([BoxState.DESTROYING, BoxState.DESTROYED])(
+ 'does not upsert lifecycle activity when updateWhere enters %s',
+ async (state) => {
+ const { repo, findOne, entityManager } = makeRepository(jest.fn())
+ const box = pendingDestroyBox()
+ findOne.mockResolvedValue(box)
+
+ await repo.updateWhere(box.id, {
+ updateData: { state },
+ whereCondition: { state: BoxState.STARTED, pending: true },
+ })
+
+ expect(entityManager.upsert).not.toHaveBeenCalled()
+ },
+ )
+
+ it('does not upsert lifecycle activity when update enters DESTROYED', async () => {
+ const { repo, entityManager } = makeRepository(jest.fn())
+ const box = pendingDestroyBox()
+
+ await repo.update(box.id, { updateData: { state: BoxState.DESTROYED }, entity: box })
+
+ expect(entityManager.upsert).not.toHaveBeenCalled()
+ })
+})
+
const startedRow = {
id: 'box-1',
organizationId: 'org-1',
diff --git a/apps/api/src/box/repositories/box.repository.ts b/apps/api/src/box/repositories/box.repository.ts
index aa66fc045..8e83401ad 100644
--- a/apps/api/src/box/repositories/box.repository.ts
+++ b/apps/api/src/box/repositories/box.repository.ts
@@ -16,7 +16,7 @@ import { BoxCheckpointState } from '../entities/box-checkpoint-state.entity'
import { BoxState } from '../enums/box-state.enum'
import { BoxDesiredState } from '../enums/box-desired-state.enum'
import { BoxMigrationState } from '../enums/box-migration-state.enum'
-import { ConflictException, Injectable, Logger, NotFoundException } from '@nestjs/common'
+import { ConflictException, Injectable, Logger, NotFoundException, OnModuleDestroy, Optional } from '@nestjs/common'
import { BoxConflictError } from '../errors/box-conflict.error'
import { InjectDataSource } from '@nestjs/typeorm'
import { EventEmitter2 } from '@nestjs/event-emitter'
@@ -34,10 +34,12 @@ import { matchingCredential } from '../../registry/utils/matching-credential'
import { parseImageRef, upstreamRefOf } from '../../image/utils/image-ref.util'
import { OutboundPolicy } from '../runner-adapter/network-policy'
import { BOX_WARM_POOL_UNASSIGNED_ORGANIZATION } from '../constants/box.constants'
+import { TypedConfigService } from '../../config/typed-config.service'
// SQLSTATE lock_not_available — a statement waited longer than lock_timeout to
// acquire a lock.
const PG_LOCK_TIMEOUT_CODE = '55P03'
+const PG_FOREIGN_KEY_VIOLATION_CODE = '23503'
// Cap how long the proxy auto-start UPDATE waits to acquire the box row's
// write lock. Concurrent start/stop/sync go through updateWhere(), which holds
@@ -62,6 +64,8 @@ const CREATION_ADMISSION_LANES = 8
// longer wait means something else holds it. The Box write has already
// committed; give up on the best-effort update rather than delay its response.
const ORGANIZATION_ACTIVITY_LOCK_TIMEOUT_MS = 1000
+const ORGANIZATION_ACTIVITY_FLUSH_DELAY_MS = 1000
+const ORGANIZATION_ACTIVITY_FLUSH_BATCH_SIZE = 1000
export const BOX_CREATION_LIMIT_EXCLUDED_STATES = [
BoxState.ERROR,
@@ -77,11 +81,16 @@ type ParkedBox = { id: string; updatedAt: Date }
// The fields of a Box before a write that decide its organization's activity.
type OrganizationActivitySource = Pick<Box, 'organizationId' | 'state' | 'desiredState' | 'createdAt'>
type OrganizationActivity = { createdAt: Date | null; modifiedAt: Date | null }
+type PendingOrganizationActivity = OrganizationActivity & { organizationId: string }
type AdmissionLockBudget = { remainingMs: number }
@Injectable()
-export class BoxRepository extends BaseRepository<Box> {
+export class BoxRepository extends BaseRepository<Box> implements OnModuleDestroy {
private readonly logger = new Logger(BoxRepository.name)
+ private readonly pendingOrganizationActivity = new Map<string, PendingOrganizationActivity>()
+ private organizationActivityFlushTimer?: NodeJS.Timeout
+ private organizationActivityFlushing = false
+ private organizationActivityFlushStopped = false
/** Bound background lookups without inheriting waits from the query cache. */
async findOne({ lockTimeoutMs, ...options }: FindOneOptions<Box> & { lockTimeoutMs?: number }): Promise<Box | null> {
@@ -159,6 +168,7 @@ export class BoxRepository extends BaseRepository<Box> {
@InjectDataSource() dataSource: DataSource,
eventEmitter: EventEmitter2,
private readonly boxLookupCacheInvalidationService: BoxLookupCacheInvalidationService,
+ @Optional() private readonly configService?: TypedConfigService,
) {
super(dataSource, eventEmitter, Box)
}
@@ -199,7 +209,7 @@ export class BoxRepository extends BaseRepository<Box> {
)
this.invalidateLookupCacheOnInsert(box)
- await this.recordOrganizationActivity(box)
+ await this.afterBoxWrite(box)
return box
}
@@ -290,14 +300,17 @@ export class BoxRepository extends BaseRepository<Box> {
}
box.updatedAt = new Date()
- if (previousBox.state !== box.state || previousBox.organizationId !== box.organizationId) {
+ if (
+ (previousBox.state !== box.state || previousBox.organizationId !== box.organizationId) &&
+ ![BoxState.DESTROYING, BoxState.DESTROYED].includes(box.state)
+ ) {
await this.upsertLastActivity(entityManager, id, box.updatedAt)
}
})
this.emitUpdateEvents(box, previousBox)
this.invalidateLookupCacheOnUpdate(box, previousBox)
- await this.recordOrganizationActivity(box, previousBox)
+ await this.afterBoxWrite(box, previousBox)
return box
}
@@ -438,7 +451,7 @@ export class BoxRepository extends BaseRepository<Box> {
})
this.emitUpdateEvents(changed.box, changed.previous)
this.invalidateLookupCacheOnUpdate(changed.box, changed.previous)
- await this.recordOrganizationActivity(changed.box, changed.previous)
+ await this.afterBoxWrite(changed.box, changed.previous)
return changed.box
}
@@ -479,6 +492,41 @@ export class BoxRepository extends BaseRepository<Box> {
)
}
+ async requestDestroy(box: Box): Promise<Box> {
+ const previousBox = { ...box }
+ Object.assign(box, Box.getSoftDeleteUpdate(box))
+ box.assertValid()
+ const invariantChanges = box.enforceInvariants()
+ box.updatedAt = new Date()
+ const runnerRelease = invariantChanges.runnerId === null ? ', "runnerId" = NULL' : ''
+
+ const destroyed = await this.manager.query(
+ `WITH destroyed AS (
+ UPDATE box
+ SET pending = $7,
+ "desiredState" = $4,
+ name = $2,
+ "updatedAt" = $3${runnerRelease}
+ WHERE id = $1
+ AND state = $5
+ AND pending = $6
+ RETURNING id, "runnerId"
+ ), credentials AS (
+ DELETE FROM secret_credential
+ WHERE box_id IN (SELECT id FROM destroyed)
+ )
+ SELECT id, "runnerId" FROM destroyed`,
+ [box.id, box.name, box.updatedAt, BoxDesiredState.DESTROYED, previousBox.state, previousBox.pending, box.pending],
+ )
+ if (destroyed.length !== 1) throw new BoxConflictError()
+ box.runnerId = destroyed[0].runnerId
+
+ this.emitUpdateEvents(box, previousBox)
+ this.invalidateLookupCacheOnUpdate(box, previousBox)
+ await this.afterBoxWrite(box, previousBox)
+ return box
+ }
+
/**
* Partially updates a box in the database and optionally emits a corresponding event based on the changes.
*
@@ -532,7 +580,10 @@ export class BoxRepository extends BaseRepository<Box> {
}
box.updatedAt = new Date()
- if (previousBox.state !== box.state || previousBox.organizationId !== box.organizationId) {
+ if (
+ (previousBox.state !== box.state || previousBox.organizationId !== box.organizationId) &&
+ ![BoxState.DESTROYING, BoxState.DESTROYED].includes(box.state)
+ ) {
await this.upsertLastActivity(entityManager, id, box.updatedAt)
}
@@ -542,7 +593,7 @@ export class BoxRepository extends BaseRepository<Box> {
return [box, previousBox] as const
})
- await this.recordOrganizationActivity(updatedBox, previousBox)
+ await this.afterBoxWrite(updatedBox, previousBox)
return updatedBox
}
@@ -725,41 +776,176 @@ export class BoxRepository extends BaseRepository<Box> {
await entityManager.upsert(BoxLastActivity, { boxId, lastActivityAt }, ['boxId'])
}
- /**
- * Advances the organization's activation facts after a Box write has committed.
- *
- * It runs outside the Box transaction, so same-organization writes never queue
- * on the facts row. The upsert is optimistic: it only moves a time forward, and
- * Read Committed rechecks that against the newest row, so late or concurrent
- * updates cannot move a time backwards. The foreign key rejects a deleted
- * organization, so its facts are not recreated. A failure, including a facts-row
- * lock wait past ORGANIZATION_ACTIVITY_LOCK_TIMEOUT_MS, is logged and dropped:
- * the Box write stands, and a later event supersedes the lost maximum.
- */
- private async recordOrganizationActivity(box: Box, previousBox?: OrganizationActivitySource): Promise<void> {
+ private afterBoxWrite(box: Box, previousBox?: OrganizationActivitySource): Promise<void> {
+ const asynchronous = this.configService?.get('boxSync.organizationActivityAsync') !== false
+ if (!asynchronous) return this.recordOrganizationActivity(box, previousBox, false)
+
+ const activity = this.committedOrganizationActivity(box, previousBox)
+ if (activity) this.bufferOrganizationActivity(activity)
+ return Promise.resolve()
+ }
+
+ private committedOrganizationActivity(
+ box: Box,
+ previousBox?: OrganizationActivitySource,
+ ): PendingOrganizationActivity | null {
try {
const activity = this.organizationActivityOf(box, previousBox)
- if (!activity) {
- return
- }
- await this.manager.transaction(async (entityManager) => {
- // SET takes a literal, so the constant is interpolated rather than bound.
- await entityManager.query(`SET LOCAL lock_timeout = '${ORGANIZATION_ACTIVITY_LOCK_TIMEOUT_MS}ms'`)
- await entityManager.query(
- `INSERT INTO organization_activation_facts AS facts ("organizationId", "lastBoxCreatedAt", "lastBoxModifiedAt")
- VALUES ($1::uuid, $2::timestamptz, $3::timestamptz)
- ON CONFLICT ("organizationId") DO UPDATE
- SET "lastBoxCreatedAt" = GREATEST(facts."lastBoxCreatedAt", EXCLUDED."lastBoxCreatedAt"),
- "lastBoxModifiedAt" = GREATEST(facts."lastBoxModifiedAt", EXCLUDED."lastBoxModifiedAt")
- WHERE facts."lastBoxCreatedAt" IS DISTINCT FROM GREATEST(facts."lastBoxCreatedAt", EXCLUDED."lastBoxCreatedAt")
- OR facts."lastBoxModifiedAt" IS DISTINCT FROM GREATEST(facts."lastBoxModifiedAt", EXCLUDED."lastBoxModifiedAt")`,
- [box.organizationId, activity.createdAt, activity.modifiedAt],
- )
- })
+ return activity ? { organizationId: box.organizationId, ...activity } : null
} catch (error) {
this.logger.warn(
`Failed to record activity of box ${box.id} for organization ${box.organizationId}: ${error instanceof Error ? error.message : String(error)}`,
)
+ return null
+ }
+ }
+
+ private bufferOrganizationActivity(activity: PendingOrganizationActivity): void {
+ const previous = this.pendingOrganizationActivity.get(activity.organizationId)
+ const newest = (left: Date | null | undefined, right: Date | null) =>
+ !left || (right && right > left) ? right : left
+ this.pendingOrganizationActivity.set(activity.organizationId, {
+ organizationId: activity.organizationId,
+ createdAt: newest(previous?.createdAt, activity.createdAt),
+ modifiedAt: newest(previous?.modifiedAt, activity.modifiedAt),
+ })
+
+ this.scheduleOrganizationActivityFlush()
+ }
+
+ // One flush at a time: a flush in flight holds the schedule, and anything
+ // buffered meanwhile is written by the flush this schedules when it finishes.
+ private scheduleOrganizationActivityFlush(): void {
+ if (
+ this.organizationActivityFlushStopped ||
+ this.organizationActivityFlushTimer ||
+ this.organizationActivityFlushing
+ ) {
+ return
+ }
+ this.organizationActivityFlushTimer = setTimeout(() => {
+ this.organizationActivityFlushTimer = undefined
+ void this.flushOrganizationActivity()
+ }, ORGANIZATION_ACTIVITY_FLUSH_DELAY_MS)
+ this.organizationActivityFlushTimer.unref()
+ }
+
+ private async flushOrganizationActivity(): Promise<void> {
+ if (this.organizationActivityFlushing || this.organizationActivityFlushStopped) return
+ this.organizationActivityFlushing = true
+ try {
+ if (this.organizationActivityFlushTimer) {
+ clearTimeout(this.organizationActivityFlushTimer)
+ this.organizationActivityFlushTimer = undefined
+ }
+ const updates = [...this.pendingOrganizationActivity.values()].sort((left, right) =>
+ left.organizationId.localeCompare(right.organizationId),
+ )
+ this.pendingOrganizationActivity.clear()
+ for (let offset = 0; offset < updates.length; offset += ORGANIZATION_ACTIVITY_FLUSH_BATCH_SIZE) {
+ await this.writeOrganizationActivity(
+ updates.slice(offset, offset + ORGANIZATION_ACTIVITY_FLUSH_BATCH_SIZE),
+ true,
+ )
+ }
+ } finally {
+ this.organizationActivityFlushing = false
+ if (this.pendingOrganizationActivity.size > 0) this.scheduleOrganizationActivityFlush()
+ }
+ }
+
+ /** Stops the activity flush timer so shutdown does not fire it against a closed DataSource. */
+ onModuleDestroy(): void {
+ this.organizationActivityFlushStopped = true
+ if (this.organizationActivityFlushTimer) {
+ clearTimeout(this.organizationActivityFlushTimer)
+ this.organizationActivityFlushTimer = undefined
+ }
+ }
+
+ /**
+ * Advances activation facts after the Box commits. GREATEST keeps late and
+ * concurrent retries monotonic. Three attempts bound transient-lock recovery;
+ * a final failure or process exit may lose this best-effort activity update.
+ */
+ private async recordOrganizationActivity(
+ box: Box,
+ previousBox?: OrganizationActivitySource,
+ retry = true,
+ ): Promise<void> {
+ const activity = this.committedOrganizationActivity(box, previousBox)
+ if (activity) await this.writeOrganizationActivity([activity], retry, box.id)
+ }
+
+ private async writeOrganizationActivity(
+ updates: PendingOrganizationActivity[],
+ retry: boolean,
+ boxId?: string,
+ ): Promise<void> {
+ const maxAttempts = retry ? 3 : 1
+ const values = updates
+ .map((_, index) => {
+ const first = index * 3 + 1
+ return `($${first}::uuid, $${first + 1}::timestamptz, $${first + 2}::timestamptz)`
+ })
+ .join(', ')
+ const parameters = updates.flatMap((update) => [update.organizationId, update.createdAt, update.modifiedAt])
+
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
+ try {
+ await this.manager.transaction(async (entityManager) => {
+ // SET takes a literal, so the constant is interpolated rather than bound.
+ await entityManager.query(`SET LOCAL lock_timeout = '${ORGANIZATION_ACTIVITY_LOCK_TIMEOUT_MS}ms'`)
+ await entityManager.query(
+ `INSERT INTO organization_activation_facts AS facts ("organizationId", "lastBoxCreatedAt", "lastBoxModifiedAt")
+ VALUES ${values}
+ ON CONFLICT ("organizationId") DO UPDATE
+ SET "lastBoxCreatedAt" = GREATEST(facts."lastBoxCreatedAt", EXCLUDED."lastBoxCreatedAt"),
+ "lastBoxModifiedAt" = GREATEST(facts."lastBoxModifiedAt", EXCLUDED."lastBoxModifiedAt")
+ WHERE facts."lastBoxCreatedAt" IS DISTINCT FROM GREATEST(facts."lastBoxCreatedAt", EXCLUDED."lastBoxCreatedAt")
+ OR facts."lastBoxModifiedAt" IS DISTINCT FROM GREATEST(facts."lastBoxModifiedAt", EXCLUDED."lastBoxModifiedAt")`,
+ parameters,
+ )
+ })
+ return
+ } catch (error) {
+ if ((error as { code?: string }).code === PG_FOREIGN_KEY_VIOLATION_CODE) {
+ if (updates.length > 1) {
+ for (const update of updates) await this.writeOrganizationActivity([update], retry)
+ return
+ }
+ // The referenced organization row is gone; retries and backoff cannot restore it.
+ this.logger.error({
+ event: 'organization.activity.dropped',
+ boxId,
+ organizationId: updates[0].organizationId,
+ organizationCount: updates.length,
+ attempt: attempt + 1,
+ error: error instanceof Error ? error.message : String(error),
+ })
+ return
+ }
+ const message = error instanceof Error ? error.message : String(error)
+ if (attempt === maxAttempts - 1) {
+ this.logger.error({
+ event: 'organization.activity.dropped',
+ boxId,
+ organizationId: updates.length === 1 ? updates[0].organizationId : undefined,
+ organizationCount: updates.length,
+ attempt: maxAttempts,
+ error: message,
+ })
+ } else {
+ this.logger.warn(`Failed to record Box activity for ${updates.length} organization(s): ${message}`)
+ }
+ if (attempt < maxAttempts - 1) {
+ const delay = 100 * 2 ** attempt + randomInt(100)
+ await new Promise<void>((resolve) => {
+ const timer = setTimeout(resolve, delay)
+ timer.unref()
+ })
+ }
+ }
}
}
diff --git a/apps/api/src/box/services/box.service.business-event.spec.ts b/apps/api/src/box/services/box.service.business-event.spec.ts
index fd34f9b8d..363645411 100644
--- a/apps/api/src/box/services/box.service.business-event.spec.ts
+++ b/apps/api/src/box/services/box.service.business-event.spec.ts
@@ -30,6 +30,7 @@ function makeService() {
boxRepository: {
findWithCheckpointState: jest.fn().mockResolvedValue({ box: startedBox, checkpointState: null }),
updateWhere: jest.fn().mockResolvedValue(startedBox),
+ requestDestroy: jest.fn().mockResolvedValue(startedBox),
},
eventEmitter: { emit: jest.fn() },
logger: { log: jest.fn(), warn: jest.fn(), error: jest.fn(), debug: jest.fn() },
diff --git a/apps/api/src/box/services/box.service.filestore-delete.spec.ts b/apps/api/src/box/services/box.service.filestore-delete.spec.ts
index 83d1c4b5d..82ef5dcb2 100644
--- a/apps/api/src/box/services/box.service.filestore-delete.spec.ts
+++ b/apps/api/src/box/services/box.service.filestore-delete.spec.ts
@@ -15,7 +15,7 @@ function makeDestroyService(box: any) {
const updatedBox = { ...box, desiredState: BoxDesiredState.DESTROYED }
const boxRepository = {
findWithCheckpointState: jest.fn().mockResolvedValue({ box, checkpointState: null }),
- updateWhere: jest.fn().mockResolvedValue(updatedBox),
+ requestDestroy: jest.fn().mockResolvedValue(updatedBox),
}
const eventEmitter = { emit: jest.fn() }
const service = Object.create(BoxService.prototype) as BoxService
@@ -52,10 +52,7 @@ describe('BoxService Filestore restart deletion', () => {
Object.assign(service as any, { filestoreInstanceResolver })
await expect(service.destroy('box-1', 'org-1', Context.user())).resolves.toBe(updatedBox)
- expect(boxRepository.updateWhere).toHaveBeenCalledWith('box-1', {
- updateData: expect.objectContaining({ desiredState: BoxDesiredState.DESTROYED, pending: true }),
- whereCondition: { pending: true, state: BoxState.STOPPED },
- })
+ expect(boxRepository.requestDestroy).toHaveBeenCalledWith(expect.objectContaining({ id: 'box-1' }))
expect(eventEmitter.emit).toHaveBeenCalledWith(BoxEvents.DESTROYED, expect.anything())
expect(filestoreInstanceResolver.resolve).not.toHaveBeenCalled()
})
@@ -67,7 +64,7 @@ describe('BoxService Filestore restart deletion', () => {
})
await expect(service.destroy('box-1', 'org-1', Context.user())).rejects.toThrow('Box state change in progress')
- expect(boxRepository.updateWhere).not.toHaveBeenCalled()
+ expect(boxRepository.requestDestroy).not.toHaveBeenCalled()
expect(eventEmitter.emit).not.toHaveBeenCalled()
})
})
diff --git a/apps/api/src/box/services/box.service.ts b/apps/api/src/box/services/box.service.ts
index b93da1ede..a9bb1d176 100644
--- a/apps/api/src/box/services/box.service.ts
+++ b/apps/api/src/box/services/box.service.ts
@@ -1119,18 +1119,19 @@ export class BoxService {
throw new BoxError('Box state change in progress')
}
- const updateData = Box.getSoftDeleteUpdate(box)
-
const updatedBox = checkpointState?.activeJobId
? await this.boxRepository.deleteCheckpointTarget(box, checkpointState)
- : await this.boxRepository.updateWhere(box.id, {
- updateData,
- whereCondition: { pending: box.pending, state: box.state },
- })
+ : await this.boxRepository.requestDestroy(box)
recordBoxRequested('box.delete', updatedBox, ctx)
- this.eventEmitter.emit(BoxEvents.DESTROYED, new BoxDestroyedEvent(updatedBox))
+ const committedCheckpointState = checkpointState?.activeJobId
+ ? { ...checkpointState, activeJobId: null, sequence: checkpointState.sequence + 1 }
+ : checkpointState
+ this.eventEmitter.emit(
+ BoxEvents.DESTROYED,
+ new BoxDestroyedEvent(updatedBox, { checkpointState: committedCheckpointState }),
+ )
return updatedBox
}
diff --git a/apps/api/src/box/services/credential-lifecycle.integration.spec.ts b/apps/api/src/box/services/credential-lifecycle.integration.spec.ts
index bb24b1181..bbf8f4e99 100644
--- a/apps/api/src/box/services/credential-lifecycle.integration.spec.ts
+++ b/apps/api/src/box/services/credential-lifecycle.integration.spec.ts
@@ -15,7 +15,9 @@ import { Box } from '../entities/box.entity'
import { BoxLastActivity } from '../entities/box-last-activity.entity'
import { BoxCheckpointState } from '../entities/box-checkpoint-state.entity'
import { BoxRepository } from '../repositories/box.repository'
+import { BoxConflictError } from '../errors/box-conflict.error'
import { Context } from '../../common/context/context'
+import { BoxEvents } from '../constants/box-events.constants'
;(process.env.DB_HOST ? describe : describe.skip)('Credential lifecycle transactions', () => {
let db: DataSource
let credentials: SecretCredentialService
@@ -96,6 +98,61 @@ import { Context } from '../../common/context/context'
expect((await db.query('SELECT "desiredState" FROM box'))[0].desiredState).toBe(BoxDesiredState.DESTROYED)
expect(await credentials.consume(issued.token, binding.runnerId)).toEqual({ active: false })
})
+ it('keeps credentials when the conditional deletion loses a race', async () => {
+ const issued = await credentials.issue(binding)
+ await db.getRepository(Box).update(box.id, { pending: true })
+
+ await expect(repository.requestDestroy(box)).rejects.toBeInstanceOf(BoxConflictError)
+
+ expect((await repository.findOneBy({ id: box.id }))?.desiredState).toBe(BoxDesiredState.STOPPED)
+ expect(await credentials.consume(issued.token, binding.runnerId)).toMatchObject({ active: true })
+ })
+
+ it('uses the Runner committed by a concurrent import for destroy reconciliation', async () => {
+ const boxes = lifecycleService()
+ const emit = (boxes as any).eventEmitter.emit as jest.Mock
+ const importedRunnerId = randomUUID()
+ const requestDestroy = repository.requestDestroy.bind(repository)
+ const destroy = jest.spyOn(repository, 'requestDestroy').mockImplementation(async (staleBox) => {
+ await db.getRepository(Box).update(staleBox.id, { runnerId: importedRunnerId })
+ return requestDestroy(staleBox)
+ })
+ try {
+ const destroyed = await boxes.destroy(box.id, box.organizationId, Context.user())
+
+ expect(destroyed.runnerId).toBe(importedRunnerId)
+ expect(emit).toHaveBeenCalledWith(
+ BoxEvents.DESTROYED,
+ expect.objectContaining({ box: expect.objectContaining({ runnerId: importedRunnerId }) }),
+ )
+ } finally {
+ destroy.mockRestore()
+ }
+ })
+
+ it('releases the Runner when deleting an archived Box', async () => {
+ box.state = BoxState.ARCHIVED
+ await db.getRepository(Box).save(box)
+
+ await repository.requestDestroy(box)
+
+ expect((await db.query('SELECT "runnerId" FROM box WHERE id = $1', [box.id]))[0].runnerId).toBeNull()
+ })
+
+ it('keeps terminal pending=false when destroy retries an already-destroyed Box', async () => {
+ await db.getRepository(Box).update(box.id, {
+ state: BoxState.DESTROYED,
+ desiredState: BoxDesiredState.DESTROYED,
+ pending: false,
+ runnerId: null,
+ })
+ const terminal = await db.getRepository(Box).findOneByOrFail({ id: box.id })
+
+ await repository.requestDestroy(terminal)
+
+ expect((await db.query('SELECT pending FROM box WHERE id = $1', [box.id]))[0].pending).toBe(false)
+ })
+
it('duplicate rejected job should leave exactly one credential', async () => {
const jobs = new JobService(db.getRepository(Job), { lpush: jest.fn() } as any, {} as any)
const adapter = new RunnerAdapterV2(repository, db.getRepository(Job), jobs)
diff --git a/apps/api/src/boxlite-rest/boxlite-key-scopes.integration.spec.ts b/apps/api/src/boxlite-rest/boxlite-key-scopes.integration.spec.ts
index 4581c3f57..b8497ecf0 100644
--- a/apps/api/src/boxlite-rest/boxlite-key-scopes.integration.spec.ts
+++ b/apps/api/src/boxlite-rest/boxlite-key-scopes.integration.spec.ts
@@ -44,7 +44,7 @@ describe('Hosted API key scope discovery and Box deletion', () => {
where.organizationId === box.organizationId && (where.id === box.id || where.name === box.name) ? box : null,
),
findWithCheckpointState: async () => ({ box, checkpointState: null }),
- updateWhere: async (_id: string, { updateData }: { updateData: Partial<Box> }) => Object.assign(box, updateData),
+ requestDestroy: async (target: Box) => Object.assign(target, Box.getSoftDeleteUpdate(target)),
}
beforeAll(async () => {
diff --git a/apps/api/src/config/configuration.ts b/apps/api/src/config/configuration.ts
index b87de656d..21b989984 100644
--- a/apps/api/src/config/configuration.ts
+++ b/apps/api/src/config/configuration.ts
@@ -965,6 +965,7 @@ const configuration = {
},
boxMigration: boxMigrationConfig(),
boxSync: {
+ organizationActivityAsync: process.env.BOX_ORGANIZATION_ACTIVITY_ASYNC !== 'false',
// How long a claimed startup job may sit without completing before a
// runner reporting the box as started is allowed to close it out. This is
// a backstop for a lost job-completion callback, not a fast path: raise it
diff --git a/apps/api/src/organization/organization.module.ts b/apps/api/src/organization/organization.module.ts
index 4a608de22..7cbe4533a 100644
--- a/apps/api/src/organization/organization.module.ts
+++ b/apps/api/src/organization/organization.module.ts
@@ -35,6 +35,7 @@ import { DataSource } from 'typeorm'
import { EventEmitter2 } from '@nestjs/event-emitter'
import { BoxRepository } from '../box/repositories/box.repository'
import { BoxLookupCacheInvalidationService } from '../box/services/box-lookup-cache-invalidation.service'
+import { TypedConfigService } from '../config/typed-config.service'
import { RegionModule } from '../region/region.module'
import { OrganizationRegionController } from './controllers/organization-region.controller'
import { EncryptionModule } from '../encryption/encryption.module'
@@ -83,12 +84,13 @@ import { UsageController } from '../usage/controllers/usage.controller'
BoxLookupCacheInvalidationService,
{
provide: BoxRepository,
- inject: [DataSource, EventEmitter2, BoxLookupCacheInvalidationService],
+ inject: [DataSource, EventEmitter2, BoxLookupCacheInvalidationService, TypedConfigService],
useFactory: (
dataSource: DataSource,
eventEmitter: EventEmitter2,
boxLookupCacheInvalidationService: BoxLookupCacheInvalidationService,
- ) => new BoxRepository(dataSource, eventEmitter, boxLookupCacheInvalidationService),
+ configService: TypedConfigService,
+ ) => new BoxRepository(dataSource, eventEmitter, boxLookupCacheInvalidationService, configService),
},
],
exports: [
diff --git a/apps/api/src/usage/usage.module.spec.ts b/apps/api/src/usage/usage.module.spec.ts
index ab29abeca..86edcf310 100644
--- a/apps/api/src/usage/usage.module.spec.ts
+++ b/apps/api/src/usage/usage.module.spec.ts
@@ -12,6 +12,7 @@ import { Box } from '../box/entities/box.entity'
import { Runner } from '../box/entities/runner.entity'
import { BoxRepository } from '../box/repositories/box.repository'
import { BoxLookupCacheInvalidationService } from '../box/services/box-lookup-cache-invalidation.service'
+import { TypedConfigService } from '../config/typed-config.service'
import { RedisLockProvider } from '../box/common/redis-lock.provider'
import { BoxUsagePeriod } from './entities/box-usage-period.entity'
import { BoxUsagePeriodArchive } from './entities/box-usage-period-archive.entity'
@@ -78,7 +79,12 @@ describe('UsageModule', () => {
const providers = Reflect.getMetadata(MODULE_METADATA.PROVIDERS, UsageModule) as Array<any>
const boxRepositoryProvider = providers.find((provider) => provider?.provide === BoxRepository)
- expect(boxRepositoryProvider.inject).toEqual([DataSource, EventEmitter2, BoxLookupCacheInvalidationService])
+ expect(boxRepositoryProvider.inject).toEqual([
+ DataSource,
+ EventEmitter2,
+ BoxLookupCacheInvalidationService,
+ TypedConfigService,
+ ])
expect(boxRepositoryProvider.inject).toHaveLength(BoxRepository.length)
})
})
diff --git a/apps/api/src/usage/usage.module.ts b/apps/api/src/usage/usage.module.ts
index 668bce8b0..c4c6977c7 100644
--- a/apps/api/src/usage/usage.module.ts
+++ b/apps/api/src/usage/usage.module.ts
@@ -18,6 +18,7 @@ import { UsageExportPublisherService } from './services/usage-export-publisher.s
import { UsageAllocationSnapshotService } from './services/usage-allocation-snapshot.service'
import { BoxRepository } from '../box/repositories/box.repository'
import { BoxLookupCacheInvalidationService } from '../box/services/box-lookup-cache-invalidation.service'
+import { TypedConfigService } from '../config/typed-config.service'
import { Box } from '../box/entities/box.entity'
import { Runner } from '../box/entities/runner.entity'
import { UsageConcurrencyService } from './services/usage-concurrency.service'
@@ -36,12 +37,13 @@ import { BoxUsageService } from './services/box-usage.service'
BoxLookupCacheInvalidationService,
{
provide: BoxRepository,
- inject: [DataSource, EventEmitter2, BoxLookupCacheInvalidationService],
+ inject: [DataSource, EventEmitter2, BoxLookupCacheInvalidationService, TypedConfigService],
useFactory: (
dataSource: DataSource,
eventEmitter: EventEmitter2,
boxLookupCacheInvalidationService: BoxLookupCacheInvalidationService,
- ) => new BoxRepository(dataSource, eventEmitter, boxLookupCacheInvalidationService),
+ configService: TypedConfigService,
+ ) => new BoxRepository(dataSource, eventEmitter, boxLookupCacheInvalidationService, configService),
},
],
exports: [UsageService, UsageConcurrencyService, BoxUsageService],
diff --git a/docs/contributing/investigations/organization-activation-facts.md b/docs/contributing/investigations/organization-activation-facts.md
index 91afd877f..7a9190758 100644
--- a/docs/contributing/investigations/organization-activation-facts.md
+++ b/docs/contributing/investigations/organization-activation-facts.md
@@ -19,10 +19,16 @@ Decision:
environment that applied an earlier, unreleased revision drops its two
activation triggers and functions, and the `boxHistoryComplete` column, manually;
otherwise the column's `NOT NULL` makes every upsert fail.
-- After `BoxRepository.insert`, `update` or `updateWhere` commits, the repository
- compares the previous and committed Box. In its own short transaction it sets
- a one-second `lock_timeout`, then upserts the row with `GREATEST`, updating only
- when a value advances. An organization without a recorded Box has no row.
+- After `BoxRepository.insert`, `update`, `updateWhere` or `requestDestroy`
+ commits, the repository compares the previous and committed Box. Asynchronous
+ mode buffers the result for one second, keeps each organization's maxima, and
+ flushes pending organizations in ID order and chunks of at most 1000. Each
+ chunk uses one multi-row upsert in a short transaction. A foreign-key failure
+ from a deleted organization falls back to individual writes for that chunk so
+ other organizations still commit. Synchronous mode
+ performs the same upsert for one organization immediately. Each transaction
+ sets a one-second `lock_timeout`; `GREATEST` updates only when a value advances.
+ An organization without a recorded Box has no row.
- A later review removed `boxHistoryComplete`. Updates are best effort, so the flag
never proved a complete history; consumers compare organization creation with
the tracking start instead.
@@ -46,18 +52,21 @@ unless deletion was requested, and both cleanup crons delete only such Boxes
(`apps/api/src/box/services/box.service.ts`, `cleanupDestroyedBoxes`,
`cleanupStaleErrorBoxes`).
-| Situation | Result |
-| --- | --- |
-| Facts row locked | The Box commits; the follow-up waits at most one second (`lock_timeout`), then is logged and dropped. |
-| Box transaction rolls back | No facts update runs. |
-| Concurrent or late updates | Read Committed rechecks `WHERE` on the newest row; times never regress. |
-| Update fails, or the process exits after commit | That advance is lost and logged; the Box result stands. |
-| Organization deleted | The foreign key rejects the upsert; facts are not recreated. |
-| Raw SQL, or instances on the previous revision | Not recorded; the next recorded event creates any missing row. |
-
-There is no retry, outbox or backlog. A lost advance is repaired only by a later
-event of the same kind for that organization. A null time therefore means none
-was recorded, not proof of inactivity.
+| Situation | Result |
+| ---------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
+| Facts row locked | The Box commits; the follow-up waits at most one second per attempt (`lock_timeout`), then is logged and dropped after bounded retries. |
+| Box transaction rolls back | No facts update runs. |
+| Concurrent or late updates | Read Committed rechecks `WHERE` on the newest row; times never regress. |
+| Final update attempt fails | The affected advances are lost and logged; the Box result stands. |
+| Process exits after commit but before flushing | Unflushed advances are lost; the Box result stands. |
+| Organization deleted | The foreign key rejects the upsert; facts are not recreated. |
+| Raw SQL, or instances on the previous revision | Not recorded; the next recorded event creates any missing row. |
+
+There is no durable outbox. Bounded retries recover transient flush failures;
+a final failure or process exit before flushing drops the affected advances.
+A lost advance is repaired only by a later event of the same kind for that
+organization. A null time therefore means none was recorded, not proof of
+inactivity.
[Row-level locks §13.3.2](https://www.postgresql.org/docs/current/explicit-locking.html#LOCKING-ROWS)
are released at transaction end, which is why the trigger serialized Box commits.
@@ -80,8 +89,8 @@ Rejected alternatives:
- `EventEmitter` listeners: `updateWhere` emits before commit, and payloads lack
the previous desired state.
- A Redis buffer like `BoxActivityService` adds a dependency with the same loss window.
-- A stage flag: without triggers the cost is one primary-key `UPDATE` per
- lifecycle event, and a disabled period would silently miss events.
+- A stage flag: a disabled period would silently miss events, including those
+ not repaired by a different kind of later activity.
Rollout and rollback: