The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
perf(api): parallelize quota-limited Box creation (#3047)
lfld28780c9e66c505c
diff --git a/apps/api/README.md b/apps/api/README.mdindex 4ad9ac6ae..7f93ae30e 100644--- a/apps/api/README.md+++ b/apps/api/README.md@@ -1377,6 +1377,62 @@ start endpoint retains its existing startup wait; the Listener observes the origID and registers a JIT runner only after `running`. A lost creation response remainsan uncertain outcome and must not trigger a blind retry or adoption by name.+### Creation quota index++Limited creates use PostgreSQL transaction locks and count committed Boxes in a+separate `READ COMMITTED` statement after locking. Cached Box data cannot admit a request.+Older API instances, warm-pool claims, checkpoint restores, and other callback-based+creates take the original organization lock exclusively.++To try parallel admission, an ordinary one-Box insert needs a safe integer request+limit of at least 8.+It randomly selects one of 8 organization lanes without checking whether it is free.+It locks that lane, then takes the original lock in shared mode.++Parallel admission requires a nonnegative safe integer count and at least 8 slots+under the request's resolved limit.++At the count snapshot, other admitted inserts that are not yet visible still hold+their lanes. At most 8 additional slots are needed, including this insert.++Otherwise the first transaction finishes without writing. A new transaction takes the+exclusive lock and checks the exact limit against a fresh count. Limits below 8 and+limits that are not safe integers take the exclusive path directly.++A limit of 1000 allows parallel admission at 850 or 992 counted Boxes. At 993 the+exclusive path can still fill the remaining slots. No separate threshold is configured.++Each request's resolved limit is checked at admission, not refreshed at commit. With a+common resolved limit, concurrent limited creates do not exceed it.++A later request with a higher limit can bring the count above an earlier request's+lower limit before the earlier request commits. A plan change does not revoke an+existing admission.++Lock waits share about five seconds; the count and writes retain the connection's+default lock timeout. Box and last activity still commit together.++Older exclusive-only instances still exclude parallel writers on the original key.+Parallel releases must use that same key, lane namespaces, and lane count. An earlier+parallel release may fall back sooner, but shares the same eight lanes and does not+add capacity.++Mix these releases only if the admission-time contract above is acceptable. A mixed+rollout does not preserve the earlier request's lower limit at its commit.++The partial B-tree `box_creation_quota_idx` on `box("organizationId")` limits the+count scan to rows outside `error`, `destroying`, `destroyed`, `archiving`, and `archived`.+If PostgreSQL cannot use the index, including during rollout or rollback, admission+still enforces the same cap. Recheck index eligibility if the quota predicate changes.++The pre-deploy migration runs outside a transaction. Use one migration runner+and allow for extra database I/O during the build. Retry after cancellation:+the migration replaces a matching invalid index but refuses a same-name object+with a different definition.++For online rollback, use TypeORM revert with `--transaction none` when this is+the latest applied migration. The concurrent drop does not require an API rollback.+## Native hosted CI Listener (in development)`CiListenerService` imports the shared TypeScript `Listener` directly. Every APIdiff --git a/apps/api/src/box/entities/box.entity.ts b/apps/api/src/box/entities/box.entity.tsindex 1ba628133..5b9b12b71 100644--- a/apps/api/src/box/entities/box.entity.ts+++ b/apps/api/src/box/entities/box.entity.ts@@ -25,6 +25,7 @@ import {@Index('box_runnerid_idx', ['runnerId'])@Index('box_runner_state_idx', ['runnerId', 'state'])@Index('box_organizationid_idx', ['organizationId'])+@Index('box_creation_quota_idx', { synchronize: false })@Index('box_region_idx', ['region'])@Index('box_resources_idx', ['cpu', 'mem', 'disk', 'gpu'])@Index('box_runner_state_desired_idx', ['runnerId', 'state', 'desiredState'], {diff --git a/apps/api/src/box/repositories/box.repository.creation-limit.integration.spec.ts b/apps/api/src/box/repositories/box.repository.creation-limit.integration.spec.tsindex ba88afdfe..a0c4f6c50 100644--- a/apps/api/src/box/repositories/box.repository.creation-limit.integration.spec.ts+++ b/apps/api/src/box/repositories/box.repository.creation-limit.integration.spec.ts@@ -3,10 +3,13 @@* SPDX-License-Identifier: AGPL-3.0*/-import { randomUUID } from 'node:crypto'+import crypto, { randomUUID } from 'node:crypto'+import { setTimeout as delay } from 'node:timers/promises'import { DataSource, EntityManager, Repository } from 'typeorm'import { IsolationLevel } from 'typeorm/driver/types/IsolationLevel'import { CustomNamingStrategy } from '../../common/utils/naming-strategy.util'+import { AddOrganizationActivationFacts1792490000000 } from '../../migrations/pre-deploy/1792490000000-add-organization-activation-facts-migration'+import { AddBoxCreationQuotaIndex1795478400000 } from '../../migrations/pre-deploy/1795478400000-add-box-creation-quota-index-migration'import { BOX_WARM_POOL_UNASSIGNED_ORGANIZATION } from '../constants/box.constants'import { Box } from '../entities/box.entity'import { BoxLastActivity } from '../entities/box-last-activity.entity'@@ -16,7 +19,66 @@ import { BoxRepository, CREATION_ADMISSION_LOCK_NAMESPACE } from './box.repositoconst describeIfDatabase = process.env.DB_HOST ? describe : describe.skipconst schemaName = `box_creation_limit_${process.pid}_${randomUUID().replaceAll('-', '')}`-const organizationId = '00000000-0000-4000-8000-0000000000aa'+// Advisory locks are scoped to the database, not the test schema.+const organizationId = randomUUID()+const otherOrganizationId = randomUUID()+const firstLaneNamespace = 0x43525000+const lastLaneNamespace = firstLaneNamespace + 7++function mockAdmissionLanes(...lanes: number[]) {+ const { randomInt } = crypto+ return jest.spyOn(crypto, 'randomInt').mockImplementation((...args: unknown[]) => {+ // Preserve other uses of crypto, including Box ID generation.+ const lane = args.length === 1 && args[0] === 8 ? lanes.shift() : undefined+ return lane ?? Reflect.apply(randomInt, crypto, args)+ })+}++function gate() {+ let open!: () => void+ const ready = new Promise<void>((resolve) => {+ open = resolve+ })+ return { ready, open }+}++async function within<T>(work: Promise<T>, message: string, ms = 2000): Promise<T> {+ const timer = new AbortController()+ try {+ return await Promise.race([+ work,+ delay(ms, undefined, { signal: timer.signal }).then(() => {+ throw new Error(message)+ }),+ ])+ } finally {+ timer.abort()+ }+}++async function admissionLocks(dataSource: DataSource) {+ return dataSource.query<Array<{ pid: number; namespace: number; mode: string; granted: boolean }>>(+ `SELECT pid, classid::int AS namespace, mode, granted FROM pg_locks+ WHERE locktype = 'advisory' AND database = (SELECT oid FROM pg_database WHERE datname = current_database())+ AND objid::bigint = (hashtext($1)::bigint & 4294967295) AND objsubid = 2+ AND (classid::bigint = $2 OR classid::bigint BETWEEN $3 AND $4)`,+ [organizationId, CREATION_ADMISSION_LOCK_NAMESPACE, firstLaneNamespace, lastLaneNamespace],+ )+}++async function waitForCompatibilityWaiter(dataSource: DataSource, mode: 'ShareLock' | 'ExclusiveLock') {+ const deadline = Date.now() + 2000+ do {+ const locks = await admissionLocks(dataSource)+ if (+ locks.some((lock) => lock.namespace === CREATION_ADMISSION_LOCK_NAMESPACE && !lock.granted && lock.mode === mode)+ ) {+ return locks+ }+ await delay(10)+ } while (Date.now() < deadline)+ throw new Error(`Did not observe a waiting ${mode} on the organization compatibility key`)+}const excludedStates = new Set([BoxState.ERROR,@@ -94,6 +156,7 @@ describeIfDatabase('BoxRepository creation admission (integration, real Postgreslet boxes: Repository<Box>let repository: BoxRepositorylet ownsSchema = false+ const invalidateOrgId = jest.fn()beforeAll(async () => {dataSource = await new DataSource({@@ -108,17 +171,22 @@ describeIfDatabase('BoxRepository creation admission (integration, real PostgresnamingStrategy: new CustomNamingStrategy(),entitySkipConstructor: true,synchronize: false,- extra: { options: `-c search_path=${schemaName},public` },+ migrations: [AddOrganizationActivationFacts1792490000000, AddBoxCreationQuotaIndex1795478400000],+ migrationsTransactionMode: 'each',+ extra: { max: 10, options: `-c search_path=${schemaName},public` },}).initialize()await dataSource.query(`CREATE SCHEMA "${schemaName}"`)ownsSchema = trueawait dataSource.synchronize()+ await dataSource.query('CREATE TABLE organization (id uuid PRIMARY KEY)')+ await dataSource.query('INSERT INTO organization (id) VALUES ($1), ($2)', [organizationId, otherOrganizationId])+ await dataSource.runMigrations()boxes = dataSource.getRepository(Box)repository = new BoxRepository(dataSource,{ emit: jest.fn() } as never,- { invalidate: jest.fn(), invalidateOrgId: jest.fn() } as never,+ { invalidate: jest.fn(), invalidateOrgId } as never,)})@@ -140,6 +208,250 @@ describeIfDatabase('BoxRepository creation admission (integration, real Postgresawait dataSource.query(`DELETE FROM "${schemaName}"."box"`)})+ it.each([+ { count: 0, limit: 100 },+ { count: 850, limit: 1000 },+ ])('persists two same-organization creates concurrently at $count of $limit', async ({ count, limit }) => {+ if (count > 0) await boxes.insert(Array.from({ length: count }, (_, i) => newBox(`seed-${i}`)))+ const inserted = gate()+ const commit = gate()+ const pids: number[] = []+ const originalInsert = EntityManager.prototype.insert+ const insert = jest.spyOn(EntityManager.prototype, 'insert').mockImplementation(async function (+ this: EntityManager,+ ...args: Parameters<EntityManager['insert']>+ ) {+ const result = await originalInsert.apply(this, args)+ if (args[0] === Box && this.queryRunner?.isTransactionActive) {+ const [{ pid }] = await this.query('SELECT pg_backend_pid() AS pid')+ pids.push(pid)+ if (pids.length === 2) inserted.open()+ await commit.ready+ }+ return result+ })+ const candidates = [newBox('parallel-a'), newBox('parallel-b')]+ const random = mockAdmissionLanes(0, 7)+ const requests = candidates.map((candidate) => repository.insert(candidate, limit))+ const creates = Promise.all(requests)+ try {+ await within(+ Promise.race([inserted.ready, creates]),+ 'Two Box INSERTs did not overlap: the first transaction still has not committed',+ )+ // The pool has room for this observer while both writer connections are occupied.+ expect(await boxes.countBy({ organizationId })).toBe(count)+ expect(new Set(pids).size).toBe(2)+ const locks = await admissionLocks(dataSource)+ const lanes = pids.map((pid) => {+ const own = locks.filter((lock) => lock.pid === pid && lock.granted)+ expect(own).toHaveLength(2)+ expect(own).toContainEqual({+ pid,+ namespace: CREATION_ADMISSION_LOCK_NAMESPACE,+ mode: 'ShareLock',+ granted: true,+ })+ return own.find((lock) => lock.mode === 'ExclusiveLock')?.namespace+ })+ expect(new Set(lanes)).toEqual(new Set([firstLaneNamespace, lastLaneNamespace]))+ } finally {+ commit.open()+ await Promise.allSettled(requests)+ insert.mockRestore()+ random.mockRestore()+ }+ await expect(creates).resolves.toEqual(candidates)+ expect(await boxes.countBy({ organizationId })).toBe(count + 2)+ expect(await dataSource.getRepository(BoxLastActivity).count()).toBe(2)+ })++ it('shares the original key with an exclusive-only writer and counts each predecessor after commit', async () => {+ const firstInserted = gate()+ const releaseFirst = gate()+ const oldInserted = gate()+ const releaseOld = gate()+ const snapshots: number[] = []+ const originalCount = EntityManager.prototype.count+ const count = jest.spyOn(EntityManager.prototype, 'count').mockImplementation(async function (+ this: EntityManager,+ ...args: Parameters<EntityManager['count']>+ ) {+ const result = await originalCount.apply(this, args)+ if (args[0] === Box && this.queryRunner?.isTransactionActive) snapshots.push(result)+ return result+ })+ const originalInsert = EntityManager.prototype.insert+ const insert = jest.spyOn(EntityManager.prototype, 'insert').mockImplementation(async function (+ this: EntityManager,+ ...args: Parameters<EntityManager['insert']>+ ) {+ const result = await originalInsert.apply(this, args)+ if (args[0] === Box && (args[1] as Box).name === 'first-shared') {+ firstInserted.open()+ await releaseFirst.ready+ }+ return result+ })+ const random = mockAdmissionLanes(0, 7)+ const first = repository.insert(newBox('first-shared'), 100)+ const requests: Promise<unknown>[] = [first]+ try {+ await within(Promise.race([firstInserted.ready, first]), 'First shared writer did not reach INSERT')+ const oldWriter = dataSource.transaction('READ COMMITTED', async (manager) => {+ await manager.query('SELECT pg_advisory_xact_lock($1, hashtext($2))', [+ CREATION_ADMISSION_LOCK_NAMESPACE,+ organizationId,+ ])+ await manager.count(Box, { where: { organizationId } })+ await manager.insert(Box, newBox('old-exclusive'))+ oldInserted.open()+ await releaseOld.ready+ })+ requests.push(oldWriter)+ await Promise.race([waitForCompatibilityWaiter(dataSource, 'ExclusiveLock'), oldWriter])+ const later = repository.insert(newBox('later-shared'), 100)+ requests.push(later)+ await Promise.race([waitForCompatibilityWaiter(dataSource, 'ShareLock'), later])+ releaseFirst.open()+ await within(Promise.race([oldInserted.ready, oldWriter]), 'Exclusive-only writer did not reach INSERT')+ await waitForCompatibilityWaiter(dataSource, 'ShareLock')+ expect(snapshots).toEqual([0, 1])+ releaseOld.open()+ await Promise.all(requests)+ expect(snapshots).toEqual([0, 1, 2])+ } finally {+ releaseFirst.open()+ releaseOld.open()+ await Promise.allSettled(requests)+ count.mockRestore()+ insert.mockRestore()+ random.mockRestore()+ }+ })++ it('admits higher-limit inserts against their own limit while a lower-limit count is paused', async () => {+ await boxes.insert(Array.from({ length: 92 }, (_, i) => newBox(`seed-${i}`)))+ const counted = gate()+ const releaseCount = gate()+ const higher = ['higher-limit', 'higher-limit-again'].map((name) => ({+ candidate: newBox(name),+ inserted: gate(),+ commit: gate(),+ }))+ let lowerPid: number+ const originalCount = EntityManager.prototype.count+ const count = jest.spyOn(EntityManager.prototype, 'count').mockImplementationOnce(async function (+ this: EntityManager,+ ...args: Parameters<EntityManager['count']>+ ) {+ const result = await originalCount.apply(this, args)+ const [{ pid }] = await this.query('SELECT pg_backend_pid() AS pid')+ lowerPid = pid+ counted.open()+ await releaseCount.ready+ return result+ })+ const originalInsert = EntityManager.prototype.insert+ const insert = jest.spyOn(EntityManager.prototype, 'insert').mockImplementation(async function (+ this: EntityManager,+ ...args: Parameters<EntityManager['insert']>+ ) {+ const result = await originalInsert.apply(this, args)+ const attempt = higher.find(({ candidate }) => args[0] === Box && args[1] === candidate)+ if (attempt) {+ attempt.inserted.open()+ await attempt.commit.ready+ }+ return result+ })+ // Reuse the same lane for both higher-limit writes while the lower-limit writer is paused.+ const random = mockAdmissionLanes(0, 7, 7)+ const low = repository.insert(newBox('lower-limit'), 100)+ const requests = [low]+ try {+ await within(Promise.race([counted.ready, low]), 'Lower-limit writer did not take its count snapshot')+ expect(await boxes.countBy({ organizationId })).toBe(92)+ let firstHigherLane: number | undefined+ for (const [i, { candidate, inserted, commit }] of higher.entries()) {+ const request = repository.insert(candidate, 200)+ requests.push(request)+ await within(Promise.race([inserted.ready, request]), `${candidate.name} waited on the lower-limit writer`)+ const locks = await admissionLocks(dataSource)+ const shared = locks.filter((lock) => lock.namespace === CREATION_ADMISSION_LOCK_NAMESPACE)+ const lanes = locks.filter((lock) => lock.namespace !== CREATION_ADMISSION_LOCK_NAMESPACE)+ expect(shared).toHaveLength(2)+ expect(lanes).toHaveLength(2)+ for (const lock of shared) {+ expect(lock).toMatchObject({ mode: 'ShareLock', granted: true })+ expect(lanes.filter((lane) => lane.pid === lock.pid)).toEqual([+ expect.objectContaining({ mode: 'ExclusiveLock', granted: true }),+ ])+ }+ expect(new Set(lanes.map((lane) => lane.namespace)).size).toBe(2)+ expect(shared.map((lock) => lock.pid)).toContain(lowerPid)+ const higherLane = lanes.find((lane) => lane.pid !== lowerPid)?.namespace+ if (i === 0) firstHigherLane = higherLane+ else expect(higherLane).toBe(firstHigherLane)+ expect(await boxes.countBy({ organizationId })).toBe(92 + i)+ commit.open()+ await request+ expect(await boxes.countBy({ organizationId })).toBe(93 + i)+ }+ releaseCount.open()+ await low+ expect(await boxes.countBy({ organizationId })).toBe(95)+ } finally {+ releaseCount.open()+ for (const { commit } of higher) commit.open()+ await Promise.allSettled(requests)+ count.mockRestore()+ insert.mockRestore()+ random.mockRestore()+ }+ })++ it.each([1, 2])('releases the probe connection before exact fallback at pool size %d', async (max) => {+ await boxes.insert(Array.from({ length: 99 }, (_, i) => newBox(`seed-${i}`)))+ const narrowPool = await new DataSource({+ ...dataSource.options,+ extra: { ...dataSource.options.extra, max, connectionTimeoutMillis: 1000 },+ }).initialize()+ const random = mockAdmissionLanes(0, 7)+ try {+ const repo = new BoxRepository(narrowPool, { emit: jest.fn() } as never, { invalidateOrgId } as never)+ const results = await Promise.allSettled([+ repo.insert(newBox('near-limit-a'), 100),+ repo.insert(newBox('near-limit-b'), 100),+ ])+ expectOneSuccessAndOneLimitFailure(results)+ const failure = results.find((result): result is PromiseRejectedResult => result.status === 'rejected')+ expect(failure?.reason.getResponse().message).toContain('100 of 100')+ expect(await boxes.countBy({ organizationId })).toBe(100)+ expect(await dataSource.getRepository(BoxLastActivity).count()).toBe(1)+ expect(await admissionLocks(dataSource)).toEqual([])+ } finally {+ random.mockRestore()+ await narrowPool.destroy()+ }+ })++ it('rolls back the Box and releases both locks when last-activity persistence fails', async () => {+ const candidate = newBox('activity-rolls-back')+ const failure = new Error('last activity unavailable')+ const upsert = jest.spyOn(EntityManager.prototype, 'upsert').mockRejectedValueOnce(failure)+ try {+ await expect(repository.insert(candidate, 100)).rejects.toBe(failure)+ expect(upsert).toHaveBeenCalledTimes(1)+ expect(await boxes.countBy({ organizationId })).toBe(0)+ expect(await admissionLocks(dataSource)).toEqual([])+ } finally {+ upsert.mockRestore()+ }+ await expect(repository.insert(candidate, 100)).resolves.toBe(candidate)+ expect(await dataSource.getRepository(BoxLastActivity).count()).toBe(1)+ })+it('allows exactly one of two fresh creates competing for the final slot', async () => {const barrier = installInitialCountBarrier(dataSource)try {@@ -179,6 +491,17 @@ describeIfDatabase('BoxRepository creation admission (integration, real Postgres}})+ it('enforces the limit after a committed create whose lookup cache invalidation fails', async () => {+ invalidateOrgId.mockImplementationOnce(() => {+ throw new Error('cache unavailable')+ })++ await expect(repository.insert(newBox('admitted'), 1)).resolves.toBeInstanceOf(Box)+ await expect(repository.insert(newBox('rejected'), 1)).rejects.toBeInstanceOf(BoxCreationLimitExceededError)+ expect(invalidateOrgId).toHaveBeenLastCalledWith(expect.objectContaining({ organizationId, name: 'admitted' }))+ expect(await boxes.countBy({ organizationId })).toBe(1)+ })+it('lets a warm-pool assignment outwait a Box row lock held past the admission lock timeout', async () => {const warmPoolBox = newBox('warm-locked', BOX_WARM_POOL_UNASSIGNED_ORGANIZATION)warmPoolBox.state = BoxState.STARTEDdiff --git a/apps/api/src/box/repositories/box.repository.creation-limit.spec.ts b/apps/api/src/box/repositories/box.repository.creation-limit.spec.tsindex f7a22652b..d7b7d6b93 100644--- a/apps/api/src/box/repositories/box.repository.creation-limit.spec.ts+++ b/apps/api/src/box/repositories/box.repository.creation-limit.spec.ts@@ -3,8 +3,10 @@* SPDX-License-Identifier: AGPL-3.0*/+import crypto from 'node:crypto'+import { performance } from 'node:perf_hooks'import { FindOperator } from 'typeorm'-import { BoxRepository } from './box.repository'+import { BoxRepository, CREATION_ADMISSION_LOCK_NAMESPACE } from './box.repository'import { Box } from '../entities/box.entity'import { BoxState } from '../enums/box-state.enum'import {@@ -55,6 +57,15 @@ function box(organizationId = '11111111-1111-4111-8111-111111111111'): Box {return entity}+function mockAdmissionLanes(...lanes: number[]) {+ const { randomInt } = crypto+ return jest.spyOn(crypto, 'randomInt').mockImplementation((...args: unknown[]) => {+ // Preserve other uses of crypto, including Box ID generation.+ const lane = args.length === 1 && args[0] === 8 ? lanes.shift() : undefined+ return lane ?? Reflect.apply(randomInt, crypto, args)+ })+}+function responseCode(error: BoxCreationLimitExceededError | BoxCreationAdmissionUnavailableError): string {return (error.getResponse() as { code: string }).code}@@ -67,7 +78,7 @@ function expectAdmissionLock(entityManager: ReturnType<typeof makeEntityManager>const [sql, params] = lockCalls[0] as [string, unknown[]]expect(sql.indexOf("set_config('lock_timeout', $1, true)")).toBeLessThan(sql.indexOf('pg_advisory_xact_lock($2'))expect(sql.lastIndexOf('reset_val')).toBeGreaterThan(sql.indexOf('pg_advisory_xact_lock($2'))- expect(params).toEqual(['5000ms', expect.any(Number), organizationId])+ expect(params).toEqual(['5000ms', CREATION_ADMISSION_LOCK_NAMESPACE, organizationId])}describe('BoxRepository creation admission', () => {@@ -78,8 +89,9 @@ describe('BoxRepository creation admission', () => {const onPersist = jest.fn().mockResolvedValue(undefined)const afterInsert = jest.fn().mockResolvedValue(undefined)- await boxRepository.insert(entity, 2, onPersist, initialize, afterInsert)+ await boxRepository.insert(entity, 100, onPersist, initialize, afterInsert)+ expectAdmissionLock(entityManager, entity.organizationId)expect(initialize).toHaveBeenCalledWith(entityManager)expect(onPersist).toHaveBeenCalledWith(entityManager, entity)expect(afterInsert).toHaveBeenCalledWith(entityManager)@@ -122,6 +134,131 @@ describe('BoxRepository creation admission', () => {])})+ it.each(['onPersist', 'initialize', 'afterInsert'])('keeps a create with just %s exclusive', async (callback) => {+ const { boxRepository, entityManager } = makeRepository()+ const entity = box()+ const persist = jest.fn().mockResolvedValue(undefined)+ await boxRepository.insert(+ entity,+ 100,+ callback === 'onPersist' ? persist : undefined,+ callback === 'initialize' ? persist : undefined,+ callback === 'afterInsert' ? persist : undefined,+ )+ expect(persist).toHaveBeenCalledTimes(1)+ expectAdmissionLock(entityManager, entity.organizationId)+ })++ it.each([7, 100.5, Infinity, Number.MAX_SAFE_INTEGER + 1])('uses the exclusive path for limit %s', async (limit) => {+ const { boxRepository, entityManager } = makeRepository()+ const entity = box()+ await boxRepository.insert(entity, limit)+ expectAdmissionLock(entityManager, entity.organizationId)+ })++ it.each([+ { count: 0, limit: 8, attempts: 1 },+ { count: 1, limit: 8, attempts: 2 },+ { count: 91, limit: 99, attempts: 1 },+ { count: 92, limit: 100, attempts: 1 },+ { count: 93, limit: 100, attempts: 2 },+ { count: 93, limit: 200, attempts: 1 },+ { count: 100, limit: 150, attempts: 1 },+ { count: 992, limit: 1000, attempts: 1 },+ { count: 993, limit: 1000, attempts: 2 },+ { count: Number.MAX_SAFE_INTEGER - 8, limit: Number.MAX_SAFE_INTEGER, attempts: 1 },+ { count: Number.MAX_SAFE_INTEGER - 7, limit: Number.MAX_SAFE_INTEGER, attempts: 2 },+ ])('uses $attempts admission transactions for $count counted of $limit', async ({ count, limit, attempts }) => {+ const { boxRepository, entityManager, transaction } = makeRepository(count)+ await boxRepository.insert(box(), limit)+ expect(transaction).toHaveBeenCalledTimes(attempts)+ expect(entityManager.query).toHaveBeenCalledTimes(attempts + 1)+ expect(entityManager.count).toHaveBeenCalledTimes(attempts)+ expect(entityManager.insert).toHaveBeenCalledTimes(1)+ })++ it.each([Number.NaN, -1, 12.5, Number.MAX_SAFE_INTEGER + 1])(+ 'recounts under the exclusive lock rather than trusting an invalid parallel count of %s',+ async (count) => {+ const { boxRepository, entityManager, transaction } = makeRepository(1000)+ entityManager.count.mockResolvedValueOnce(count)++ await expect(boxRepository.insert(box(), 1000)).rejects.toBeInstanceOf(BoxCreationLimitExceededError)+ expect(transaction).toHaveBeenCalledTimes(2)+ expect(entityManager.count).toHaveBeenCalledTimes(2)+ expect(entityManager.query.mock.calls[2][0]).toContain('pg_advisory_xact_lock($2')+ expect(entityManager.query.mock.calls[2][1][1]).toBe(CREATION_ADMISSION_LOCK_NAMESPACE)+ expect(entityManager.insert).not.toHaveBeenCalled()+ },+ )++ it('propagates a parallel count error without retrying or writing', async () => {+ const { boxRepository, entityManager, transaction } = makeRepository(850)+ const countError = Object.assign(new Error('canceling count due to lock timeout'), { code: '55P03' })+ entityManager.count.mockRejectedValueOnce(countError)++ await expect(boxRepository.insert(box(), 1000)).rejects.toBe(countError)+ expect(transaction).toHaveBeenCalledTimes(1)+ expect(entityManager.query).toHaveBeenCalledTimes(2)+ expect(entityManager.insert).not.toHaveBeenCalled()+ })++ it('uses the selected random lane for each create, including repeated lanes', async () => {+ const { boxRepository, entityManager } = makeRepository()+ const random = mockAdmissionLanes(7, 0, 7)++ try {+ const entities = [box(), box(), box()]+ for (const entity of entities) await boxRepository.insert(entity, 100)++ const laneCalls = entityManager.query.mock.calls.filter(([sql]) => sql.includes('pg_advisory_xact_lock($2'))+ expect(laneCalls.map(([, params]) => params.slice(1))).toEqual([+ [0x43525007, entities[0].organizationId],+ [0x43525000, entities[1].organizationId],+ [0x43525007, entities[2].organizationId],+ ])+ expect(random.mock.calls.filter(([max]) => max === 8)).toHaveLength(3)+ } finally {+ random.mockRestore()+ }+ })++ it('shares one lock budget across the lane, shared key, and fallback without charging the count', async () => {+ const { boxRepository, entityManager } = makeRepository(993)+ const random = mockAdmissionLanes(0)+ const clock = jest.spyOn(performance, 'now')+ for (const ms of [0, 1200, 1200, 3100, 9000, 9001]) clock.mockReturnValueOnce(ms)++ try {+ await boxRepository.insert(box(), 1000)+ const calls = entityManager.query.mock.calls as Array<[string, [string, number, string]]>+ expect(calls.map(([, params]) => params[0])).toEqual(['5000ms', '3800ms', '1900ms'])+ expect(calls[0][0]).toContain('pg_advisory_xact_lock($2')+ expect(calls[0][1][1]).toBe(0x43525000)+ expect(calls[1][0]).toContain('pg_advisory_xact_lock_shared($2')+ expect(calls[1][1][1]).toBe(CREATION_ADMISSION_LOCK_NAMESPACE)+ expect(calls[2][0]).toContain('pg_advisory_xact_lock($2')+ expect(calls[2][1][1]).toBe(CREATION_ADMISSION_LOCK_NAMESPACE)+ } finally {+ clock.mockRestore()+ random.mockRestore()+ }+ })++ it('does not start another lock wait once the admission budget is exhausted', async () => {+ const { boxRepository, entityManager, transaction } = makeRepository()+ const clock = jest.spyOn(performance, 'now').mockReturnValueOnce(0).mockReturnValue(5000)++ try {+ await expect(boxRepository.insert(box(), 100)).rejects.toBeInstanceOf(BoxCreationAdmissionUnavailableError)+ expect(entityManager.query).toHaveBeenCalledTimes(1)+ expect(entityManager.count).not.toHaveBeenCalled()+ expect(transaction).toHaveBeenCalledTimes(1)+ } finally {+ clock.mockRestore()+ }+ })+it('rejects at the limit before persistence or post-commit side effects', async () => {const { boxRepository, entityManager, cacheInvalidation, eventEmitter } = makeRepository(2)@@ -179,12 +316,12 @@ describe('BoxRepository creation admission', () => {expect(entityManager.insert).not.toHaveBeenCalled()})- it('propagates a lock timeout raised while persisting instead of reporting admission contention', async () => {+ it.each([3, 100])('propagates a persistence lock timeout at limit %d as the original error', async (limit) => {const { boxRepository, entityManager } = makeRepository(0)const rowLockTimeout = Object.assign(new Error('canceling statement due to lock timeout'), { code: '55P03' })entityManager.insert.mockRejectedValue(rowLockTimeout)- const error = await boxRepository.insert(box(), 3).catch((caught) => caught)+ const error = await boxRepository.insert(box(), limit).catch((caught) => caught)expect(error).not.toBeInstanceOf(BoxCreationAdmissionUnavailableError)expect(error).toBe(rowLockTimeout)diff --git a/apps/api/src/box/repositories/box.repository.ts b/apps/api/src/box/repositories/box.repository.tsindex 5cee17c9b..aa66fc045 100644--- a/apps/api/src/box/repositories/box.repository.ts+++ b/apps/api/src/box/repositories/box.repository.ts@@ -4,6 +4,8 @@* SPDX-License-Identifier: AGPL-3.0*/+import { randomInt } from 'node:crypto'+import { performance } from 'node:perf_hooks'import { DataSource, EntityManager, FindOneOptions, FindOptionsWhere, In, Not } from 'typeorm'import { Box } from '../entities/box.entity'import { BoxLastActivity } from '../entities/box-last-activity.entity'@@ -47,18 +49,15 @@ const PG_LOCK_TIMEOUT_CODE = '55P03'// boxlite-proxy.controller.ts (PROXY_START_HINT_TIMEOUT_MS).const PROXY_START_LOCK_TIMEOUT_MS = 2000-// Same-organization admissions queue on a transaction-scoped advisory lock-// keyed by the organization, so a burst waits instead of aborting. The lock-// must come before the count, under READ COMMITTED: each statement then reads-// a fresh snapshot that includes the previous holder's committed Box. Cap only-// the advisory-lock wait, since a queued admission pins a pooled connection;-// the count and persist keep the default lock_timeout.const CREATION_ADMISSION_LOCK_TIMEOUT_MS = 5000-// First key of the two-key advisory lock: keeps this lock apart from other-// advisory-lock uses. Each two-key advisory lock use takes its own value.-export const CREATION_ADMISSION_LOCK_NAMESPACE = 0x424f5841 // 'BOXA'const CREATION_ADMISSION_RETRY_AFTER_SECONDS = 5+// Cross-version protocol: the original two-int key is the shared/exclusive+// compatibility barrier. Parallel releases must share the same lane keys and count.+export const CREATION_ADMISSION_LOCK_NAMESPACE = 0x424f5841 // 'BOXA'+const CREATION_ADMISSION_FIRST_LANE_NAMESPACE = 0x43525000+const CREATION_ADMISSION_LANES = 8+// Facts updates hold an organization's facts row for one short statement, so a// 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.@@ -78,6 +77,7 @@ 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 AdmissionLockBudget = { remainingMs: number }@Injectable()export class BoxRepository extends BaseRepository<Box> {@@ -181,17 +181,22 @@ export class BoxRepository extends BaseRepository<Box> {box.assertValid()box.enforceInvariants()- await this.withCreationAdmission(box.organizationId, maxCreatedBoxes, async (entityManager) => {- // Provisioning work and ownership must commit with the new Box. Run- // initialization before insertion so checkpoint use can hold its row lock.- await initialize?.(entityManager)- await this.lockRegistryCredential(box, entityManager)- await entityManager.insert(Box, box)- // Resource ownership and admission must commit with the Box itself.- await onPersist?.(entityManager, box)- await afterInsert?.(entityManager)- await this.upsertLastActivity(entityManager, box.id, box.createdAt)- })+ await this.withCreationAdmission(+ box.organizationId,+ maxCreatedBoxes,+ async (entityManager) => {+ // Provisioning work and ownership must commit with the new Box. Run+ // initialization before insertion so checkpoint use can hold its row lock.+ await initialize?.(entityManager)+ await this.lockRegistryCredential(box, entityManager)+ await entityManager.insert(Box, box)+ // Resource ownership and admission must commit with the Box itself.+ await onPersist?.(entityManager, box)+ await afterInsert?.(entityManager)+ await this.upsertLastActivity(entityManager, box.id, box.createdAt)+ },+ onPersist === undefined && initialize === undefined && afterInsert === undefined,+ )this.invalidateLookupCacheOnInsert(box)await this.recordOrganizationActivity(box)@@ -297,32 +302,66 @@ export class BoxRepository extends BaseRepository<Box> {return box}- private async withCreationAdmission<T>(+ private async withCreationAdmission(organizationId: string,maxCreatedBoxes: number | undefined,- persist: (entityManager: EntityManager) => Promise<T>,- ): Promise<T> {+ persist: (entityManager: EntityManager) => Promise<void>,+ singleInsertWithoutCallbacks = false,+ ): Promise<void> {if (maxCreatedBoxes === undefined) {return this.dataSource.transaction(persist)}- return this.dataSource.transaction('READ COMMITTED', async (entityManager) => {- await this.acquireCreationAdmissionLock(entityManager, organizationId)-- const currentCount = await entityManager.count(Box, {- where: {+ const budget = { remainingMs: CREATION_ADMISSION_LOCK_TIMEOUT_MS }+ if (+ singleInsertWithoutCallbacks &&+ Number.isSafeInteger(maxCreatedBoxes) &&+ maxCreatedBoxes >= CREATION_ADMISSION_LANES+ ) {+ const laneNamespace = CREATION_ADMISSION_FIRST_LANE_NAMESPACE + randomInt(CREATION_ADMISSION_LANES)+ const admitted = await this.dataSource.transaction('READ COMMITTED', async (manager) => {+ // Take the lane first so lane waiters do not hold the shared barrier.+ await this.acquireCreationAdmissionLock(manager, organizationId, budget, laneNamespace)+ await this.acquireCreationAdmissionLock(+ manager,organizationId,- state: Not(In(BOX_CREATION_LIMIT_EXCLUDED_STATES)),- },+ budget,+ CREATION_ADMISSION_LOCK_NAMESPACE,+ 'shared',+ )+ const currentCount = await this.countForCreationAdmission(manager, organizationId)+ if (!this.hasParallelCreationHeadroom(currentCount, maxCreatedBoxes)) return false+ await persist(manager)+ return true})+ if (admitted) return+ // The no-write transaction has released its locks and connection. Take+ // the exclusive key in a new transaction, never upgrade it in place.+ }++ return this.dataSource.transaction('READ COMMITTED', async (manager) => {+ await this.acquireCreationAdmissionLock(manager, organizationId, budget)+ const currentCount = await this.countForCreationAdmission(manager, organizationId)if (currentCount >= maxCreatedBoxes) {throw new BoxCreationLimitExceededError(currentCount, maxCreatedBoxes)}-- return persist(entityManager)+ return persist(manager)})}+ private countForCreationAdmission(manager: EntityManager, organizationId: string): Promise<number> {+ // A separate READ COMMITTED statement sees commits made before lock grant.+ return manager.count(Box, { where: { organizationId, state: Not(In(BOX_CREATION_LIMIT_EXCLUDED_STATES)) } })+ }++ private hasParallelCreationHeadroom(count: number, max: number): boolean {+ // At the count snapshot, other admitted inserts not yet visible still hold+ // their lanes: PostgreSQL makes a commit visible before releasing its lane.+ // Including this insert, at most eight slots are needed beyond the count.+ // This checks the request's resolved limit at admission, not at commit.+ return Number.isSafeInteger(count) && count >= 0 && count <= max - CREATION_ADMISSION_LANES+ }+/** Read lifecycle state and ownership in one snapshot, without changing ordinary Box projections. */async findWithCheckpointState(id: string,@@ -408,23 +447,36 @@ export class BoxRepository extends BaseRepository<Box> {// PostgreSQL evaluating select-list entries in order (ExecBuildProjectionInfo// in src/backend/executor/execExpr.c); the docs leave expression order// unspecified, so the real-Postgres integration spec checks both halves.- private async acquireCreationAdmissionLock(entityManager: EntityManager, organizationId: string): Promise<void> {- try {- await entityManager.query(- `SELECT set_config('lock_timeout', $1, true),- pg_advisory_xact_lock($2, hashtext($3)),- set_config('lock_timeout', (SELECT reset_val FROM pg_settings WHERE name = 'lock_timeout'), true)`,- [`${CREATION_ADMISSION_LOCK_TIMEOUT_MS}ms`, CREATION_ADMISSION_LOCK_NAMESPACE, organizationId],- )- } catch (error) {- if ((error as { code?: string }).code === PG_LOCK_TIMEOUT_CODE) {- throw new BoxCreationAdmissionUnavailableError(- 'Box creation admission remained contended; retry the request',- CREATION_ADMISSION_RETRY_AFTER_SECONDS,+ private async acquireCreationAdmissionLock(+ manager: EntityManager,+ organizationId: string,+ budget: AdmissionLockBudget,+ namespace = CREATION_ADMISSION_LOCK_NAMESPACE,+ mode: 'exclusive' | 'shared' = 'exclusive',+ ): Promise<void> {+ const timeoutMs = Math.ceil(budget.remainingMs)+ if (timeoutMs > 0) {+ const lock = mode === 'shared' ? 'pg_advisory_xact_lock_shared' : 'pg_advisory_xact_lock'+ const startedAt = performance.now()+ try {+ await manager.query(+ `SELECT set_config('lock_timeout', $1, true),+ ${lock}($2, hashtext($3)),+ set_config('lock_timeout', (SELECT reset_val FROM pg_settings WHERE name = 'lock_timeout'), true)`,+ [`${timeoutMs}ms`, namespace, organizationId],)+ return+ } catch (error) {+ if ((error as { code?: string }).code !== PG_LOCK_TIMEOUT_CODE) throw error+ } finally {+ // Share the budget across lock queries, not pool checkout, count or persist.+ budget.remainingMs -= performance.now() - startedAt}- throw error}+ throw new BoxCreationAdmissionUnavailableError(+ 'Box creation admission remained contended; retry the request',+ CREATION_ADMISSION_RETRY_AFTER_SECONDS,+ )}/**diff --git a/apps/api/src/migrations/README.md b/apps/api/src/migrations/README.mdindex d8e62f3e2..021610213 100644--- a/apps/api/src/migrations/README.md+++ b/apps/api/src/migrations/README.md@@ -235,17 +235,21 @@ npm run migration:revertThis reverts the **last executed migration** from either folder (based on the combined migration history in the database).-When that last migration is `AddAdminUsageWindowIndexes1792470000000`, use:+When the last applied migration declares `transaction = false` and reverts with+concurrent DDL, use:```bashnpm run migration:revert -- --transaction none```+For example, `AddAdminUsageWindowIndexes1792470000000` and+`AddBoxCreationQuotaIndex1795478400000` both drop their indexes concurrently.TypeORM 0.3.31 starts a transaction for `undoLastMigration` in `each` mode despite-the migration's `transaction = false`; concurrent index drops require `none`.-Use the default transactional command for other migrations. If a concurrent index-build or drop is interrupted, rerun it: valid completed indexes are retained,-invalid build leftovers are removed and rebuilt, and missing indexes are skipped on drop.+the migration's `transaction = false`. Use the default command for transactional+migrations.++Rerun an interrupted concurrent index build or drop. A retry keeps valid indexes,+rebuilds invalid builds, and skips missing indexes on drop.Serialize migration runners; concurrent DDL still waits for older transactions andis not a production capacity guarantee.diff --git a/apps/api/src/migrations/pre-deploy/1795478400000-add-box-creation-quota-index-migration.integration.spec.ts b/apps/api/src/migrations/pre-deploy/1795478400000-add-box-creation-quota-index-migration.integration.spec.tsnew file mode 100644index 000000000..f7fe58a4d--- /dev/null+++ b/apps/api/src/migrations/pre-deploy/1795478400000-add-box-creation-quota-index-migration.integration.spec.ts@@ -0,0 +1,193 @@+/*+ * Copyright 2026 BoxLite AI+ * SPDX-License-Identifier: AGPL-3.0+ */++import { randomUUID } from 'node:crypto'+import { DataSource, QueryRunner } from 'typeorm'+import { BOX_CREATION_LIMIT_EXCLUDED_STATES } from '../../box/repositories/box.repository'+import { AddBoxCreationQuotaIndex1795478400000 } from './1795478400000-add-box-creation-quota-index-migration'++const describeIfDatabase = process.env.DB_HOST ? describe : describe.skip+const migration = new AddBoxCreationQuotaIndex1795478400000()+const indexName = 'box_creation_quota_idx'+const connectionOptions = {+ type: 'postgres' as const,+ host: process.env.DB_HOST,+ port: Number(process.env.DB_PORT || 5432),+ username: process.env.DB_USERNAME,+ password: process.env.DB_PASSWORD,+ database: process.env.DB_DATABASE,+}++describeIfDatabase('Box creation quota index (integration, real Postgres)', () => {+ let db: DataSource+ let schema: string+ let shadow: string+ let runner: QueryRunner++ async function index() {+ const [entry] = await db.query(+ `SELECT c.oid, i.indisvalid AS valid, am.amname AS method,+ pg_get_indexdef(i.indexrelid, 1, true) AS key,+ pg_get_expr(i.indpred, i.indrelid) AS predicate+ FROM pg_class c+ LEFT JOIN pg_index i ON i.indexrelid = c.oid+ LEFT JOIN pg_am am ON am.oid = c.relam+ WHERE c.oid = to_regclass($1)`,+ [`"${schema}".${indexName}`],+ )+ return entry+ }++ beforeEach(async () => {+ const suffix = randomUUID().replaceAll('-', '')+ schema = `quota_Migration_${suffix}`+ shadow = `quota_shadow_${suffix}`+ db = await new DataSource({+ ...connectionOptions,+ schema,+ extra: { options: `-c search_path=${shadow},public` },+ migrations: [AddBoxCreationQuotaIndex1795478400000],+ migrationsTransactionMode: 'each',+ }).initialize()+ await db.query(`CREATE SCHEMA "${schema}"`)+ await db.query(`CREATE SCHEMA "${shadow}"`)+ await db.query(`CREATE TYPE "${schema}".box_state_enum AS ENUM+ ('error', 'destroying', 'destroyed', 'archiving', 'archived', 'started')`)+ await db.query(`CREATE TABLE "${schema}".box (+ "organizationId" uuid NOT NULL, state "${schema}".box_state_enum NOT NULL)`)+ runner = db.createQueryRunner()+ })++ afterEach(async () => {+ if (db?.isInitialized) {+ try {+ await runner?.release()+ await db.query(`DROP SCHEMA IF EXISTS "${schema}" CASCADE`)+ await db.query(`DROP SCHEMA IF EXISTS "${shadow}" CASCADE`)+ } finally {+ await db.destroy()+ }+ }+ })++ it('applies, verifies, preserves, and reverts the valid index in the configured schema', async () => {+ await db.query(`CREATE TYPE "${shadow}".box_state_enum AS ENUM ('unrelated')`)+ await db.query(`CREATE TABLE "${shadow}".box (id int)`)+ await db.query(`CREATE INDEX ${indexName} ON "${shadow}".box (id)`)+ const [{ oid: shadowOid }] = await db.query(`SELECT '${indexName}'::regclass::oid AS oid`)+ expect(await index()).toBeUndefined()++ expect(await db.runMigrations()).toHaveLength(1)+ const literals = BOX_CREATION_LIMIT_EXCLUDED_STATES.map((state) => `'${state}'::"${schema}".box_state_enum`)+ const installed = await index()+ expect(installed).toEqual({+ oid: expect.any(Number),+ valid: true,+ method: 'btree',+ key: '"organizationId"',+ predicate: `(state <> ALL (ARRAY[${literals.join(', ')}]))`,+ })+ await migration.up(runner)+ expect(await index()).toEqual(installed)++ await db.undoLastMigration({ transaction: 'none' })+ expect(await index()).toBeUndefined()+ await migration.down(runner)+ expect(await db.query(`SELECT '${indexName}'::regclass::oid AS oid`)).toEqual([{ oid: shadowOid }])+ expect(await db.runMigrations()).toHaveLength(1)+ const rebuilt = await index()+ expect(rebuilt).toEqual({ ...installed, oid: expect.any(Number) })+ expect(rebuilt.oid).not.toBe(installed.oid)+ })++ it('preserves and drops the same index when PostgreSQL quotes all identifiers', async () => {+ await runner.query('SET quote_all_identifiers = on')+ try {+ await migration.up(runner)+ const installed = await index()+ expect(installed).toMatchObject({ oid: expect.any(Number), valid: true })+ await migration.up(runner)+ expect(await index()).toEqual(installed)+ await migration.down(runner)+ expect(await index()).toBeUndefined()+ } finally {+ await runner.query('RESET quote_all_identifiers')+ }+ })++ it('targets the schema of the visible box table when no schema is configured', async () => {+ const connection = await new DataSource(connectionOptions).initialize()+ const session = connection.createQueryRunner()+ try {+ await session.query(`SET search_path TO "${shadow}", "${schema}", public`)+ await migration.up(session)+ expect(await index()).toMatchObject({ method: 'btree', valid: true })+ await migration.down(session)+ expect(await index()).toBeUndefined()+ } finally {+ await session.release()+ await connection.destroy()+ }+ })++ it('retries a matching index left invalid by a canceled concurrent build', async () => {+ const snapshot = db.createQueryRunner()+ let build: Promise<void> | undefined+ try {+ await snapshot.startTransaction('REPEATABLE READ')+ await snapshot.query(`SELECT * FROM "${schema}".box`)+ const [{ pid }] = await runner.query('SELECT pg_backend_pid() AS pid')+ await runner.query("SET statement_timeout = '10s'")+ build = migration.up(runner)+ void build.catch(() => undefined)+ const deadline = Date.now() + 5000+ let phase: string | undefined+ while (Date.now() < deadline) {+ phase = (await db.query('SELECT phase FROM pg_stat_progress_create_index WHERE pid = $1', [pid]))[0]?.phase+ if (phase === 'waiting for old snapshots') break+ await new Promise((resolve) => setTimeout(resolve, 10))+ }+ expect(phase).toBe('waiting for old snapshots')+ expect(await db.query('SELECT pg_cancel_backend($1) AS canceled', [pid])).toEqual([{ canceled: true }])+ await expect(build).rejects.toMatchObject({ code: '57014' })+ } finally {+ if (snapshot.isTransactionActive) await snapshot.rollbackTransaction()+ await snapshot.release()+ await build?.catch(() => undefined)+ await runner.query('RESET statement_timeout')+ }++ const invalid = await index()+ expect(invalid.valid).toBe(false)+ expect(await db.runMigrations()).toHaveLength(1)+ expect(await index()).toEqual({ ...invalid, oid: expect.any(Number), valid: true })+ expect((await index()).oid).not.toBe(invalid.oid)+ }, 15000)++ it.each([+ ['a table', (schema: string) => `CREATE TABLE "${schema}".${indexName} (id int)`],+ [+ 'a different key',+ (schema: string) => `CREATE INDEX ${indexName} ON "${schema}".box (state)+ WHERE state NOT IN ('error', 'destroying', 'destroyed', 'archiving', 'archived')`,+ ],+ [+ 'a different predicate',+ (schema: string) => `CREATE INDEX ${indexName} ON "${schema}".box ("organizationId") WHERE state <> 'error'`,+ ],+ [+ 'a different access method',+ (schema: string) => `CREATE INDEX ${indexName} ON "${schema}".box USING hash ("organizationId")+ WHERE state NOT IN ('error', 'destroying', 'destroyed', 'archiving', 'archived')`,+ ],+ ])('refuses to replace or drop %s with the same name', async (_description, create) => {+ await db.query(create(schema))+ const collision = await index()+ expect(collision.oid).toEqual(expect.any(Number))+ await expect(migration.up(runner)).rejects.toThrow('unexpected definition')+ await expect(migration.down(runner)).rejects.toThrow('unexpected definition')+ expect(await index()).toEqual(collision)+ })+})diff --git a/apps/api/src/migrations/pre-deploy/1795478400000-add-box-creation-quota-index-migration.ts b/apps/api/src/migrations/pre-deploy/1795478400000-add-box-creation-quota-index-migration.tsnew file mode 100644index 000000000..9d3bdb13d--- /dev/null+++ b/apps/api/src/migrations/pre-deploy/1795478400000-add-box-creation-quota-index-migration.ts@@ -0,0 +1,84 @@+/*+ * Copyright 2026 BoxLite AI+ * SPDX-License-Identifier: AGPL-3.0+ */++import type { MigrationInterface, QueryRunner } from 'typeorm'++const INDEX_NAME = 'box_creation_quota_idx'+const EXCLUDED_STATES = ['error', 'destroying', 'destroyed', 'archiving', 'archived']++type IndexTarget = {+ tableName: string+ indexName: string+ stateColumn: string+ stateType: string+ exists: boolean+ expectedShape: boolean | null+ valid: boolean | null+ predicate: string | null+}++export class AddBoxCreationQuotaIndex1795478400000 implements MigrationInterface {+ transaction = false++ async up(runner: QueryRunner): Promise<void> {+ const target = await this.inspectIndex(runner)+ if (target.exists) {+ if (target.valid) return+ // An interrupted concurrent build leaves an invalid index under the same name.+ await runner.query(`DROP INDEX CONCURRENTLY ${target.indexName}`)+ }+ await runner.query(`CREATE INDEX CONCURRENTLY ${INDEX_NAME}+ ON ${target.tableName} USING btree ("organizationId")+ WHERE "state" NOT IN (${this.excludedStateLiterals(target.stateType).join(', ')})`)+ }++ async down(runner: QueryRunner): Promise<void> {+ const target = await this.inspectIndex(runner)+ if (target.exists) await runner.query(`DROP INDEX CONCURRENTLY ${target.indexName}`)+ }++ private excludedStateLiterals(stateType: string): string[] {+ return EXCLUDED_STATES.map((state) => `'${state}'::${stateType}`)+ }++ private async inspectIndex(runner: QueryRunner): Promise<IndexTarget> {+ const { options } = runner.connection+ const schema = 'schema' in options ? options.schema : undefined+ // PostgreSQL places indexes in the table's schema, even when another schema comes first in search_path.+ const [target]: IndexTarget[] = await runner.query(+ `SELECT format('%I.%I', ns.nspname, b.relname) AS "tableName",+ format('%I.%I', ns.nspname, $2::text) AS "indexName",+ quote_ident(state.attname) AS "stateColumn",+ format_type(state.atttypid, NULL) AS "stateType",+ c.oid IS NOT NULL AS "exists",+ i.indisvalid AS valid,+ c.relkind = 'i' AND i.indrelid = b.oid AND NOT i.indisunique AND NOT i.indisexclusion+ AND i.indnatts = 1 AND i.indnkeyatts = 1 AND i.indkey[0] = org.attnum+ AND i.indoption[0] = 0 AND am.amname = 'btree'+ AND opc.opcnamespace = 'pg_catalog'::regnamespace AND opc.opcname = 'uuid_ops' AS "expectedShape",+ pg_get_expr(i.indpred, i.indrelid) AS predicate+ FROM pg_class b+ JOIN pg_namespace ns ON ns.oid = b.relnamespace+ JOIN pg_attribute org ON org.attrelid = b.oid AND org.attname = 'organizationId' AND NOT org.attisdropped+ JOIN pg_attribute state ON state.attrelid = b.oid AND state.attname = 'state' AND NOT state.attisdropped+ JOIN pg_type state_type ON state_type.oid = state.atttypid AND state_type.typtype = 'e'+ LEFT JOIN pg_class c ON c.relnamespace = b.relnamespace AND c.relname = $2+ LEFT JOIN pg_index i ON i.indexrelid = c.oid+ LEFT JOIN pg_am am ON am.oid = c.relam+ LEFT JOIN pg_opclass opc ON opc.oid = i.indclass[0]+ WHERE b.oid = to_regclass(CASE WHEN $1::text IS NULL THEN 'box' ELSE format('%I.box', $1) END)+ AND b.relkind = 'r'`,+ [schema ?? null, INDEX_NAME],+ )+ if (!target) throw new Error('Could not find the box table with its creation quota columns')++ // PostgreSQL deparses NOT IN as <> ALL using the session's identifier quoting and type visibility.+ const expectedPredicate = `(${target.stateColumn} <> ALL (ARRAY[${this.excludedStateLiterals(target.stateType).join(', ')}]))`+ if (target.exists && (!target.expectedShape || target.predicate !== expectedPredicate)) {+ throw new Error(`${target.indexName} exists with an unexpected definition`)+ }+ return target+ }+}