The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
feat(api): list one Box's usage periods (#3155)
Jimmy2680da8eeb96
diff --git a/apps/api/src/app.module.ts b/apps/api/src/app.module.tsindex 442223f3f..a51c28ebb 100644--- a/apps/api/src/app.module.ts+++ b/apps/api/src/app.module.ts@@ -156,6 +156,7 @@ import { McpModule } from './mcp/mcp.module'{ name: 'authenticated', config: rateLimit.authenticated },{ name: 'box-create', config: rateLimit.boxCreate },{ name: 'box-lifecycle', config: rateLimit.boxLifecycle },+ { name: 'box-usage', config: rateLimit.boxUsage },].filter(({ config }) => config.ttl !== undefined && config.limit !== undefined).map(({ name, config }) => ({diff --git a/apps/api/src/audit/audit-targets.spec.ts b/apps/api/src/audit/audit-targets.spec.tsindex 7c12105f8..9a9b0064d 100644--- a/apps/api/src/audit/audit-targets.spec.ts+++ b/apps/api/src/audit/audit-targets.spec.ts@@ -11,6 +11,7 @@ import { BoxService } from '../box/services/box.service'import { BoxStateWaiterService } from '../box/services/box-state-waiter.service'import { CheckpointRecoverService } from '../box/services/checkpoint-recover.service'import { CommerceBoxLimitService } from '../boxlite-rest/commerce-box-limit.service'+import { BoxUsageService } from '../usage/services/box-usage.service'import { Box } from '../box/entities/box.entity'import { BoxState } from '../box/enums/box-state.enum'import { BoxDesiredState } from '../box/enums/box-desired-state.enum'@@ -46,6 +47,7 @@ describe('audit targets at HTTP boundaries', () => {{ provide: BoxStateWaiterService, useValue: { waitForStarted } },{ provide: CommerceBoxLimitService, useValue: { resolveMaxCreatedBoxes: async () => 10 } },{ provide: CheckpointRecoverService, useValue: { createBox: createFromCheckpoint } },+ { provide: BoxUsageService, useValue: {} },],}).overrideGuard(CombinedAuthGuard)diff --git a/apps/api/src/box/interceptors/box-readiness.interceptor.spec.ts b/apps/api/src/box/interceptors/box-readiness.interceptor.spec.tsindex 2bb5d042f..c11e470a1 100644--- a/apps/api/src/box/interceptors/box-readiness.interceptor.spec.ts+++ b/apps/api/src/box/interceptors/box-readiness.interceptor.spec.ts@@ -10,9 +10,11 @@ import { Reflector } from '@nestjs/core'import { lastValueFrom, Subject } from 'rxjs'import { CombinedAuthGuard } from '../../auth/combined-auth.guard'import { OrganizationResourceActionGuard } from '../../organization/guards/organization-resource-action.guard'+import { BoxUsageService } from '../../usage/services/box-usage.service'import { SystemRole } from '../../user/enums/system-role.enum'import { BoxliteBoxController } from '../../boxlite-rest/boxlite-box.controller'import { CommerceBoxLimitService } from '../../boxlite-rest/commerce-box-limit.service'+import { AuthenticatedRateLimitGuard } from '../../common/guards/authenticated-rate-limit.guard'import { subscribeBusinessEvents } from '../../common/utils/business-event.util'import { captureRequestTiming, requestTiming } from '../../common/utils/request-timing.util'import { BoxService } from '../services/box.service'@@ -64,8 +66,11 @@ describe('Cloud readiness metrics at actual REST routes', () => {{ provide: BoxStateWaiterService, useValue: waiter },{ provide: CommerceBoxLimitService, useValue: { resolveMaxCreatedBoxes: async () => undefined } },{ provide: CheckpointRecoverService, useValue: { createBox: async () => started } },+ { provide: BoxUsageService, useValue: {} },],})+ .overrideGuard(AuthenticatedRateLimitGuard)+ .useValue({ canActivate: () => true }).overrideGuard(CombinedAuthGuard).useValue({canActivate: (context) => {diff --git a/apps/api/src/box/services/memory-mib.spec.ts b/apps/api/src/box/services/memory-mib.spec.tsindex 4ee9285e0..7502a2610 100644--- a/apps/api/src/box/services/memory-mib.spec.ts+++ b/apps/api/src/box/services/memory-mib.spec.ts@@ -132,11 +132,12 @@ describe('memory billing output contract', () => {})it.each([- [300, '0.29'],- [639, '0.62'],- [640, '0.63'],- [641, '0.63'],- ] as const)('rounds %s MiB half-up to %s GiB in both output paths', (mib, expected) => {+ [128, '0.125'],+ [384, '0.375'],+ [640, '0.625'],+ [300, '0.292969'],+ [1, '0.000977'],+ ] as const)('sends %s MiB as %s GiB in both output paths', (mib, expected) => {const source = period(mib / 1024)expect(toUsageEventDto(source).mem).toBe(expected)expect(toOpenAllocationDto(source).mem).toBe(expected)@@ -144,10 +145,10 @@ describe('memory billing output contract', () => {})it('keeps exact source identities when billing quantities round together', () => {- const first = toUsageEventDto(period(300 / 1024))- const second = toUsageEventDto(period(301 / 1024))+ const first = toUsageEventDto(period(0.1234561))+ const second = toUsageEventDto(period(0.1234564))expect(first.mem).toBe(second.mem)expect(first.eventKey).not.toBe(second.eventKey)- expect(first.eventKey).toBe(usageEventKey(period(300 / 1024)))+ expect(first.eventKey).toBe(usageEventKey(period(0.1234561)))})})diff --git a/apps/api/src/boxlite-rest/box-inventory.integration.spec.ts b/apps/api/src/boxlite-rest/box-inventory.integration.spec.tsindex bb01d93de..55ce3aa19 100644--- a/apps/api/src/boxlite-rest/box-inventory.integration.spec.ts+++ b/apps/api/src/boxlite-rest/box-inventory.integration.spec.ts@@ -27,6 +27,8 @@ import { OrganizationResourceActionGuard } from '../organization/guards/organizaimport { McpCatalog } from '../mcp/mcp-catalog'import { McpDispatcher } from '../mcp/mcp-dispatcher'import { BoxliteBoxController } from './boxlite-box.controller'+import { AuthenticatedRateLimitGuard } from '../common/guards/authenticated-rate-limit.guard'+import { BoxUsageService } from '../usage/services/box-usage.service'import { CommerceBoxLimitService } from './commerce-box-limit.service'import { boxToBoxResponse } from './mappers/box-to-box.mapper'@@ -81,6 +83,7 @@ describeDatabase('Box inventory real PostgreSQL and HTTP', () => {{ provide: BoxStateWaiterService, useValue: {} },{ provide: CommerceBoxLimitService, useValue: {} },{ provide: CheckpointRecoverService, useValue: {} },+ { provide: BoxUsageService, useValue: {} },],}).overrideGuard(CombinedAuthGuard)@@ -95,6 +98,8 @@ describeDatabase('Box inventory real PostgreSQL and HTTP', () => {return true},})+ .overrideGuard(AuthenticatedRateLimitGuard)+ .useValue({ canActivate: () => true }).overrideGuard(OrganizationResourceActionGuard).useValue({async canActivate(context: any) {diff --git a/apps/api/src/boxlite-rest/boxlite-box-usage-rate-limit.spec.ts b/apps/api/src/boxlite-rest/boxlite-box-usage-rate-limit.spec.tsnew file mode 100644index 000000000..3c2cbf33a--- /dev/null+++ b/apps/api/src/boxlite-rest/boxlite-box-usage-rate-limit.spec.ts@@ -0,0 +1,83 @@+/*+ * Copyright 2026 BoxLite AI+ * SPDX-License-Identifier: AGPL-3.0+ */++import { type ExecutionContext, type INestApplication } from '@nestjs/common'+import { Reflector } from '@nestjs/core'+import { Test } from '@nestjs/testing'+import { ThrottlerStorageService } from '@nestjs/throttler'+import type { AddressInfo } from 'net'+import { CombinedAuthGuard } from '../auth/combined-auth.guard'+import { AuthenticatedRateLimitGuard } from '../common/guards/authenticated-rate-limit.guard'+import { OrganizationResourceActionGuard } from '../organization/guards/organization-resource-action.guard'+import { SystemRole } from '../user/enums/system-role.enum'+import { BoxUsageService } from '../usage/services/box-usage.service'+import { BoxliteBoxController } from './boxlite-box.controller'++jest.mock('uuid', () => ({ v4: jest.fn(() => 'mock-uuid'), validate: jest.fn(() => true) }))++describe('Box usage rate limit', () => {+ let app: INestApplication+ let storage: ThrottlerStorageService+ let getUsage: jest.Mock++ beforeEach(async () => {+ getUsage = jest.fn().mockResolvedValue({})+ storage = new ThrottlerStorageService()+ const limiter = new AuthenticatedRateLimitGuard(+ [+ { name: 'authenticated', ttl: 60_000, limit: 1 },+ { name: 'box-create', ttl: 60_000, limit: 1 },+ { name: 'box-usage', ttl: 60_000, limit: 2 },+ ],+ storage,+ new Reflector(),+ { get: async () => null, set: async () => 'OK' } as never,+ { findOne: async () => ({ authenticatedRateLimit: 1 }) } as never,+ )+ await limiter.onModuleInit()+ const moduleRef = await Test.createTestingModule({+ controllers: [BoxliteBoxController],+ providers: [{ provide: BoxUsageService, useValue: { getUsage } }],+ })+ .useMocker(() => ({}))+ .overrideGuard(CombinedAuthGuard)+ .useValue({+ canActivate(context: ExecutionContext) {+ const request = context.switchToHttp().getRequest()+ const id = request.headers['x-test-org'] ?? 'org-1'+ request.user = { userId: 'user-1', role: SystemRole.USER, organizationId: id, organization: { id } }+ return true+ },+ })+ .overrideGuard(OrganizationResourceActionGuard)+ .useValue({ canActivate: () => true })+ .overrideGuard(AuthenticatedRateLimitGuard)+ .useValue(limiter)+ .compile()+ app = moduleRef.createNestApplication()+ await app.listen(0, '127.0.0.1')+ })++ afterEach(async () => {+ await app?.close()+ storage?.onApplicationShutdown()+ })++ it('limits usage reads per organization, on their own quota and with a standard Retry-After', async () => {+ const { port } = app.getHttpServer().address() as AddressInfo+ const read = (headers = {}) => fetch(`http://127.0.0.1:${port}/v1/boxes/aB3cD4eF5gH6/usage`, { headers })++ for (let attempt = 0; attempt < 2; attempt += 1) {+ const response = await read()+ expect(response.status).toBe(200)+ expect(response.headers.has('x-ratelimit-limit-authenticated')).toBe(false)+ }+ const limited = await read()+ expect(limited.status).toBe(429)+ expect(Number(limited.headers.get('retry-after'))).toBeGreaterThan(0)+ expect(getUsage).toHaveBeenCalledTimes(2)+ expect((await read({ 'x-test-org': 'org-2' })).status).toBe(200)+ })+})diff --git a/apps/api/src/boxlite-rest/boxlite-box.controller.business-event.spec.ts b/apps/api/src/boxlite-rest/boxlite-box.controller.business-event.spec.tsindex 0dc2030f2..08d045450 100644--- a/apps/api/src/boxlite-rest/boxlite-box.controller.business-event.spec.ts+++ b/apps/api/src/boxlite-rest/boxlite-box.controller.business-event.spec.ts@@ -36,6 +36,7 @@ function makeController() {{} as never,commerceBoxLimitService as never,{} as never,+ {} as never,)return { controller, boxService }}@@ -55,6 +56,7 @@ describe('BoxliteBoxController business event actor', () => {waiter as never,{ resolveMaxCreatedBoxes: async () => 3 } as never,recovery as never,+ {} as never,)try {await controller.createBox(authContext as never, { checkpoint_id: 'base' } as never, ctx).catch(() => undefined)diff --git a/apps/api/src/boxlite-rest/boxlite-box.controller.creation-limit.spec.ts b/apps/api/src/boxlite-rest/boxlite-box.controller.creation-limit.spec.tsindex f92de4cef..2e3eae100 100644--- a/apps/api/src/boxlite-rest/boxlite-box.controller.creation-limit.spec.ts+++ b/apps/api/src/boxlite-rest/boxlite-box.controller.creation-limit.spec.ts@@ -36,6 +36,7 @@ function makeController() {boxStateWaiter as never,commerceBoxLimitService as never,{} as never,+ {} as never,)return { controller, boxService, boxStateWaiter, commerceBoxLimitService }}diff --git a/apps/api/src/boxlite-rest/boxlite-box.controller.spec.ts b/apps/api/src/boxlite-rest/boxlite-box.controller.spec.tsindex b6c1b0531..c46ee9fc9 100644--- a/apps/api/src/boxlite-rest/boxlite-box.controller.spec.ts+++ b/apps/api/src/boxlite-rest/boxlite-box.controller.spec.ts@@ -29,7 +29,7 @@ describe('BoxliteBoxController existing box lookup', () => {findOneByIdOrName: jest.fn().mockResolvedValue(box),toBoxDtoWithExitCode: jest.fn().mockResolvedValue({ id: box.id, name: box.name, state: 'started' }),}- const controller = new BoxliteBoxController(boxService as any, {} as any, {} as any, {} as any)+ const controller = new BoxliteBoxController(boxService as any, {} as any, {} as any, {} as any, {} as any)const response = await controller.getBox({ organizationId: organization.id, organization } as any, box.name)expect(response.box_id).toBe(box.id)expect(response).not.toHaveProperty('reuse_error')@@ -208,6 +208,7 @@ describe('BoxliteBoxController volume attachment authorization', () => {boxStateWaiter as any,commerceBoxLimitService as any,{} as any,+ {} as any,)return { controller, boxService }}@@ -344,6 +345,7 @@ describe('BoxliteBoxController creation diagnostics', () => {boxStateWaiter as any,{ resolveMaxCreatedBoxes: jest.fn().mockResolvedValue(10) } as any,{} as any,+ {} as any,)const log = jest.spyOn((controller as any).logger, 'error').mockImplementation(() => undefined)const auth = { role: 'admin', organization: { id: 'org-1' }, organizationId: 'org-1' } as any@@ -382,6 +384,7 @@ describe('BoxliteBoxController creation diagnostics', () => {{} as any,{ resolveMaxCreatedBoxes: jest.fn().mockResolvedValue(10) } as any,{} as any,+ {} as any,)const log = jest.spyOn((controller as any).logger, 'error').mockImplementation(() => undefined)const auth = { role: 'admin', organization: { id: 'org-1' }, organizationId: 'org-1' } as anydiff --git a/apps/api/src/boxlite-rest/boxlite-box.controller.ts b/apps/api/src/boxlite-rest/boxlite-box.controller.tsindex 23c347de5..1b1e66a9d 100644--- a/apps/api/src/boxlite-rest/boxlite-box.controller.ts+++ b/apps/api/src/boxlite-rest/boxlite-box.controller.ts@@ -24,6 +24,7 @@ import {ForbiddenException,HttpException,} from '@nestjs/common'+import { SkipThrottle } from '@nestjs/throttler'import { ApiTags, ApiBearerAuth, ApiResponse, ApiExcludeController } from '@nestjs/swagger'import { Request, Response } from 'express'import { CombinedAuthGuard } from '../auth/combined-auth.guard'@@ -34,7 +35,9 @@ import {import { RequiredOrganizationResourcePermissions } from '../organization/decorators/required-organization-resource-permissions.decorator'import { OrganizationResourcePermission } from '../organization/enums/organization-resource-permission.enum'import { AuthContext } from '../common/decorators/auth-context.decorator'+import { ThrottlerScope } from '../common/decorators/throttler-scope.decorator'import { UserContext } from '../common/decorators/user-context.decorator'+import { AuthenticatedRateLimitGuard } from '../common/guards/authenticated-rate-limit.guard'import { OrganizationAuthContext } from '../common/interfaces/auth-context.interface'import { BoxService } from '../box/services/box.service'import { BoxStateWaiterService } from '../box/services/box-state-waiter.service'@@ -50,6 +53,8 @@ import { Audit, AUDIT_TARGET_ID, MASKED_AUDIT_VALUE, TypedRequest } from '../audimport { AuditAction } from '../audit/enums/audit-action.enum'import { AuditTarget } from '../audit/enums/audit-target.enum'import { CommerceBoxLimitService } from './commerce-box-limit.service'+import { BoxUsageDto } from '../usage/dto/box-usage.dto'+import { BoxUsageService } from '../usage/services/box-usage.service'import { ReplayValidationPipe } from '../common/replay-validation.pipe'import { noEffect } from '../common/replay-no-effect'import { Context } from '../common/context/context'@@ -89,6 +94,7 @@ export class BoxliteBoxController {private readonly boxStateWaiter: BoxStateWaiterService,private readonly commerceBoxLimitService: CommerceBoxLimitService,private readonly checkpointRecoverService: CheckpointRecoverService,+ private readonly boxUsageService: BoxUsageService,) {}@Post()@@ -301,6 +307,18 @@ export class BoxliteBoxController {return boxToBoxResponse(dto)}+ // Polling usage must not use up the quota the organization's other requests share.+ @Get(':boxId/usage')+ @UseGuards(AuthenticatedRateLimitGuard)+ @ThrottlerScope('box-usage')+ @SkipThrottle({ authenticated: true })+ async getBoxUsage(+ @AuthContext() authContext: OrganizationAuthContext,+ @Param('boxId') boxId: string,+ ): Promise<BoxUsageDto> {+ return this.boxUsageService.getUsage(boxId, authContext.organizationId)+ }+@Head(':boxId')async headBox(@AuthContext() authContext: OrganizationAuthContext,diff --git a/apps/api/src/boxlite-rest/boxlite-checkpoint.controller.spec.ts b/apps/api/src/boxlite-rest/boxlite-checkpoint.controller.spec.tsindex 2f3f104ae..0c50b61a4 100644--- a/apps/api/src/boxlite-rest/boxlite-checkpoint.controller.spec.ts+++ b/apps/api/src/boxlite-rest/boxlite-checkpoint.controller.spec.ts@@ -26,6 +26,8 @@ import { OrganizationService } from '../organization/services/organization.serviimport { OrganizationUserService } from '../organization/services/organization-user.service'import { SystemRole } from '../user/enums/system-role.enum'import { BoxliteCheckpointController } from './boxlite-checkpoint.controller'+import { AuthenticatedRateLimitGuard } from '../common/guards/authenticated-rate-limit.guard'+import { BoxUsageService } from '../usage/services/box-usage.service'import { CommerceBoxLimitService } from './commerce-box-limit.service'import { BoxliteBoxController } from './boxlite-box.controller'import { BoxService } from '../box/services/box.service'@@ -113,6 +115,7 @@ describe('Checkpoint REST authentication and request admission', () => {{ provide: BoxService, useValue: boxes },{ provide: BoxStateWaiterService, useValue: waiter },{ provide: CommerceBoxLimitService, useValue: limits },+ { provide: BoxUsageService, useValue: {} },{ provide: getRedisConnectionToken(), useValue: redis },{ provide: OrganizationService, useValue: { findOne: async (id: string) => ({ id }) } },{@@ -145,7 +148,10 @@ describe('Checkpoint REST authentication and request admission', () => {),},],- }).compile()+ })+ .overrideGuard(AuthenticatedRateLimitGuard)+ .useValue({ canActivate: () => true })+ .compile()app = module.createNestApplication()app.setGlobalPrefix('api')app.useGlobalInterceptors(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.tsindex 4d85964e9..4581c3f57 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@@ -15,10 +15,12 @@ import { BoxState } from '../box/enums/box-state.enum'import { BoxService } from '../box/services/box.service'import { BoxStateWaiterService } from '../box/services/box-state-waiter.service'import { CheckpointRecoverService } from '../box/services/checkpoint-recover.service'+import { AuthenticatedRateLimitGuard } from '../common/guards/authenticated-rate-limit.guard'import { OrganizationMemberRole } from '../organization/enums/organization-member-role.enum'import { OrganizationResourcePermission as Permission } from '../organization/enums/organization-resource-permission.enum'import { OrganizationService } from '../organization/services/organization.service'import { OrganizationUserService } from '../organization/services/organization-user.service'+import { BoxUsageService } from '../usage/services/box-usage.service'import { SystemRole } from '../user/enums/system-role.enum'import { BoxliteBoxController } from './boxlite-box.controller'import { BoxliteMeController } from './boxlite-me.controller'@@ -74,6 +76,7 @@ describe('Hosted API key scope discovery and Box deletion', () => {{ provide: BoxStateWaiterService, useValue: {} },{ provide: CheckpointRecoverService, useValue: {} },{ provide: CommerceBoxLimitService, useValue: {} },+ { provide: BoxUsageService, useValue: {} },{ provide: getRedisConnectionToken(), useValue: redis },{ provide: OrganizationService, useValue: { findOne: async (id: string) => ({ id }) } },{@@ -93,7 +96,10 @@ describe('Hosted API key scope discovery and Box deletion', () => {),},],- }).compile()+ })+ .overrideGuard(AuthenticatedRateLimitGuard)+ .useValue({ canActivate: () => true })+ .compile()app = module.createNestApplication({ logger: false })app.setGlobalPrefix('api')await app.listen(0, '127.0.0.1')diff --git a/apps/api/src/boxlite-rest/boxlite-openapi.spec.ts b/apps/api/src/boxlite-rest/boxlite-openapi.spec.tsindex c8f189002..33f5d7429 100644--- a/apps/api/src/boxlite-rest/boxlite-openapi.spec.ts+++ b/apps/api/src/boxlite-rest/boxlite-openapi.spec.ts@@ -12,6 +12,7 @@ import { parse } from 'yaml'import { AllExceptionsFilter } from '../filters/all-exceptions.filter'import { ImageCatalogService } from '../image/services/image-catalog.service'import { RegistriesService } from '../registry/services/registries.service'+import { BoxUsageService } from '../usage/services/box-usage.service'import { BoxliteCheckpointController } from './boxlite-checkpoint.controller'import { BoxliteConfigController } from './boxlite-config.controller'import { BoxliteDomainController } from './boxlite-domain.controller'@@ -81,6 +82,31 @@ describe('Box API checkpoint schemas', () => {})})+describe('Box API usage schema', () => {+ it('validates actual usage responses, with and without periods', async () => {+ const period = {+ organizationId: 'org-1',+ boxId: 'aB3cD4eF5gH6',+ region: 'us',+ startAt: new Date('2026-11-25T10:00:00.000Z'),+ endAt: new Date('2026-11-25T10:00:15.000Z'),+ cpu: 1,+ gpu: 0,+ mem: 0.5,+ disk: 10,+ }+ const read = (periods: unknown[]) => {+ const query = jest.fn().mockResolvedValueOnce(periods).mockResolvedValueOnce([{}])+ return new BoxUsageService({ query } as never).getUsage('aB3cD4eF5gH6', 'org-1')+ }+ const usage = await read([period])+ expect(usage.periods).toHaveLength(1)+ expect(validator('BoxUsage')(usage)).toBe(true)+ expect(validator('BoxUsage')(await read([]))).toBe(true)+ expect(validator('BoxUsage')({ ...usage, periods: [{ ...usage.periods[0], cpu: '1' }] })).toBe(false)+ })+})+describe('Box API JSON Schema nullability', () => {const nullableFields = {Principal: ['path_prefix', 'expires_at'],diff --git a/apps/api/src/boxlite-rest/boxlite-rest-permissions.spec.ts b/apps/api/src/boxlite-rest/boxlite-rest-permissions.spec.tsindex 03f2eef60..c5bf46293 100644--- a/apps/api/src/boxlite-rest/boxlite-rest-permissions.spec.ts+++ b/apps/api/src/boxlite-rest/boxlite-rest-permissions.spec.ts@@ -35,6 +35,7 @@ const EXPECTED: Record<string, OrganizationResourcePermission[] | null> = {createBox: [WRITE_BOXES],listBoxes: null,getBox: null,+ getBoxUsage: null,headBox: null,removeBox: [DELETE_BOXES],startBox: [WRITE_BOXES],diff --git a/apps/api/src/boxlite-rest/boxlite-rest-routing.spec.ts b/apps/api/src/boxlite-rest/boxlite-rest-routing.spec.tsindex 604eb02b8..bbc112697 100644--- a/apps/api/src/boxlite-rest/boxlite-rest-routing.spec.ts+++ b/apps/api/src/boxlite-rest/boxlite-rest-routing.spec.ts@@ -31,6 +31,7 @@ import { ImageCatalogService } from '../image/services/image-catalog.service'import { BoxliteRegistryController } from './boxlite-registry.controller'import { RegistriesService } from '../registry/services/registries.service'import { CommerceBoxLimitService } from './commerce-box-limit.service'+import { BoxUsageService } from '../usage/services/box-usage.service'import { AUDIT_CONTEXT_KEY, AuditContext } from '../audit/decorators/audit.decorator'import { RequestReplayPolicy } from './request-replay-policy'@@ -91,6 +92,10 @@ describe('BoxLite REST routing', () => {provide: CheckpointRecoverService,useValue: {},},+ {+ provide: BoxUsageService,+ useValue: { getUsage: jest.fn(async (...args) => args) },+ },],)}@@ -227,6 +232,16 @@ describe('BoxLite REST routing', () => {expect(await legacy.json()).toEqual({ boxes: [] })})+ it.each(['/api/v1/boxes/aB3cD4eF5gH6/usage', '/api/v1/default/boxes/aB3cD4eF5gH6/usage'])(+ 'GET %s reads the usage for the authenticated organization',+ async (path) => {+ await startRoutingTestApp()+ const response = await get(path)+ expect(response.status).toBe(200)+ expect(await response.json()).toEqual(['aB3cD4eF5gH6', 'org-123'])+ },+ )+it.each([['/api/v1/boxes/box-1/network/inbound', 'enabled'],['/api/v1/default/boxes/box-1/network/inbound', 'disabled'],diff --git a/apps/api/src/boxlite-rest/boxlite-rest.module.ts b/apps/api/src/boxlite-rest/boxlite-rest.module.tsindex 8b72d889d..d358a758a 100644--- a/apps/api/src/boxlite-rest/boxlite-rest.module.ts+++ b/apps/api/src/boxlite-rest/boxlite-rest.module.ts@@ -22,6 +22,7 @@ import { BoxModule } from '../box/box.module'import { AuthModule } from '../auth/auth.module'import { ApiKeyModule } from '../api-key/api-key.module'import { OrganizationModule } from '../organization/organization.module'+import { UsageModule } from '../usage/usage.module'import { UserModule } from '../user/user.module'import { BoxliteMeController } from './boxlite-me.controller'import { BoxliteConfigController } from './boxlite-config.controller'@@ -49,6 +50,7 @@ import { BoxReadinessInterceptor } from '../box/interceptors/box-readiness.interApiKeyModule,OrganizationModule,UserModule,+ UsageModule,ImageModule,RegistryModule,AuditModule,diff --git a/apps/api/src/common/guards/authenticated-rate-limit.guard.ts b/apps/api/src/common/guards/authenticated-rate-limit.guard.tsindex 3ac3cd017..13487e113 100644--- a/apps/api/src/common/guards/authenticated-rate-limit.guard.ts+++ b/apps/api/src/common/guards/authenticated-rate-limit.guard.ts@@ -5,7 +5,13 @@*/import { Injectable, Logger, Inject, ExecutionContext, Optional } from '@nestjs/common'-import { ThrottlerGuard, ThrottlerRequest, ThrottlerModuleOptions, ThrottlerStorage } from '@nestjs/throttler'+import {+ ThrottlerGuard,+ ThrottlerLimitDetail,+ ThrottlerRequest,+ ThrottlerModuleOptions,+ ThrottlerStorage,+} from '@nestjs/throttler'import { Reflector } from '@nestjs/core'import { Request } from 'express'import { getRedisConnectionToken } from '@nestjs-modules/ioredis'@@ -57,10 +63,17 @@ export class AuthenticatedRateLimitGuard extends ThrottlerGuard {protected generateKey(context: ExecutionContext, suffix: string, name: string): string {// Override to make rate limiting per-rate-limit-type, not per-route- // This ensures all routes share the same counter per rate limit type (authenticated, box-create, box-lifecycle)+ // This ensures all routes share the same counter per rate limit type (authenticated, box-create, box-lifecycle, box-usage)return `${name}-${suffix}`}+ // The base guard suffixes Retry-After with the throttler name, which standard clients do not read.+ protected async throwThrottlingException(context: ExecutionContext, detail: ThrottlerLimitDetail): Promise<void> {+ const { res } = this.getRequestResponse(context)+ res.header('Retry-After', String(detail.timeToBlockExpire))+ return super.throwThrottlingException(context, detail)+ }+async handleRequest(requestProps: ThrottlerRequest): Promise<boolean> {const { context, throttler } = requestPropsconst request = context.switchToHttp().getRequest<AuthenticatedRequest>()@@ -82,15 +95,15 @@ export class AuthenticatedRateLimitGuard extends ThrottlerGuard {}// Check authenticated throttlers- const authenticatedThrottlers = ['authenticated', 'box-create', 'box-lifecycle']+ const authenticatedThrottlers = ['authenticated', 'box-create', 'box-lifecycle', 'box-usage']if (authenticatedThrottlers.includes(throttler.name)) {if (isAuthenticated) {// Only 'authenticated' applies to all routes by default- // 'box-create' and 'box-lifecycle' only apply if explicitly configured via @SkipThrottle or @Throttle+ // 'box-create', 'box-lifecycle' and 'box-usage' only apply if explicitly configured via @SkipThrottle or @Throttleconst isDefaultThrottler = throttler.name === 'authenticated'if (!isDefaultThrottler) {- // Box throttlers (box-create, box-lifecycle) are opt-in only+ // Box throttlers (box-create, box-lifecycle, box-usage) are opt-in only// Check if this route declares this throttler scope via @ThrottlerScope() decoratorconst scopes = this.reflector.getAllAndOverride<string[]>(THROTTLER_SCOPE_KEY, [context.getHandler(),diff --git a/apps/api/src/config/configuration.ts b/apps/api/src/config/configuration.tsindex d353d1675..f2bd5da0f 100644--- a/apps/api/src/config/configuration.ts+++ b/apps/api/src/config/configuration.ts@@ -904,6 +904,10 @@ const configuration = {? parseInt(process.env.RATE_LIMIT_BOX_LIFECYCLE_LIMIT, 10): undefined,},+ boxUsage: {+ ttl: process.env.RATE_LIMIT_BOX_USAGE_TTL ? parseInt(process.env.RATE_LIMIT_BOX_USAGE_TTL, 10) : undefined,+ limit: process.env.RATE_LIMIT_BOX_USAGE_LIMIT ? parseInt(process.env.RATE_LIMIT_BOX_USAGE_LIMIT, 10) : undefined,+ },},log: {console: {diff --git a/apps/api/src/mcp/mcp-tools.spec.ts b/apps/api/src/mcp/mcp-tools.spec.tsindex 7a0152f08..6884ce16a 100644--- a/apps/api/src/mcp/mcp-tools.spec.ts+++ b/apps/api/src/mcp/mcp-tools.spec.ts@@ -224,6 +224,7 @@ const API_KEY_ONLY = ['claimDomain','bindDomain','unbindDomain',+ 'getBoxUsage','listRegistries','createRegistry','removeRegistry',diff --git a/apps/api/src/migrations/pre-deploy/1795651200000-add-box-usage-archive-box-index-migration.ts b/apps/api/src/migrations/pre-deploy/1795651200000-add-box-usage-archive-box-index-migration.tsnew file mode 100644index 000000000..baeea8ef5--- /dev/null+++ b/apps/api/src/migrations/pre-deploy/1795651200000-add-box-usage-archive-box-index-migration.ts@@ -0,0 +1,26 @@+/*+ * Copyright 2026 BoxLite AI+ * SPDX-License-Identifier: AGPL-3.0+ */++import { MigrationInterface, QueryRunner } from 'typeorm'++const INDEX_NAME = 'box_usage_periods_archive_box_org_end_idx'++export class AddBoxUsageArchiveBoxIndex1795651200000 implements MigrationInterface {+ transaction = false++ async up(queryRunner: QueryRunner): Promise<void> {+ const [existing] = await queryRunner.query('SELECT indisvalid FROM pg_index WHERE indexrelid = to_regclass($1)', [+ INDEX_NAME,+ ])+ // Interrupted concurrent builds leave invalid indexes that IF NOT EXISTS would skip.+ if (existing?.indisvalid === false) await queryRunner.query(`DROP INDEX CONCURRENTLY ${INDEX_NAME}`)+ await queryRunner.query(`CREATE INDEX CONCURRENTLY IF NOT EXISTS ${INDEX_NAME}+ ON box_usage_periods_archive ("boxId", "organizationId", "endAt")`)+ }++ async down(queryRunner: QueryRunner): Promise<void> {+ await queryRunner.query(`DROP INDEX CONCURRENTLY IF EXISTS ${INDEX_NAME}`)+ }+}diff --git a/apps/api/src/usage/dto/box-usage.dto.ts b/apps/api/src/usage/dto/box-usage.dto.tsnew file mode 100644index 000000000..92c429345--- /dev/null+++ b/apps/api/src/usage/dto/box-usage.dto.ts@@ -0,0 +1,17 @@+/*+ * Copyright 2026 BoxLite AI+ * SPDX-License-Identifier: AGPL-3.0+ */++/** One archived usage period with the allocation the usage export billed for it. */+export type BoxUsagePeriodDto = {+ start_at: string+ end_at: string+ cpu: number+ memory_gib: number+ disk_gib: number+}++export type BoxUsageDto = {+ periods: BoxUsagePeriodDto[]+}diff --git a/apps/api/src/usage/services/box-usage.service.integration.spec.ts b/apps/api/src/usage/services/box-usage.service.integration.spec.tsnew file mode 100644index 000000000..2ddf14996--- /dev/null+++ b/apps/api/src/usage/services/box-usage.service.integration.spec.ts@@ -0,0 +1,173 @@+/*+ * Copyright 2026 BoxLite AI+ * SPDX-License-Identifier: AGPL-3.0+ */++import { NotFoundException } from '@nestjs/common'+import { randomUUID } from 'node:crypto'+import { DataSource, Repository } from 'typeorm'+import { BOX_WARM_POOL_UNASSIGNED_ORGANIZATION } from '../../box/constants/box.constants'+import { AddBoxUsagePeriods1785250000000 } from '../../migrations/pre-deploy/1785250000000-add-box-usage-periods-migration'+import { AddBoxUsageArchiveBoxIndex1795651200000 } from '../../migrations/pre-deploy/1795651200000-add-box-usage-archive-box-index-migration'+import { BoxUsagePeriod } from '../entities/box-usage-period.entity'+import { BoxUsagePeriodArchive } from '../entities/box-usage-period-archive.entity'+import { ARCHIVED_PERIODS_SQL, BoxUsageService } from './box-usage.service'++const describeIfDatabase = process.env.DB_HOST ? describe : describe.skip++const boxId = 'aB3cD4eF5gH6'+const organizationId = randomUUID()+const at = (time: string) => new Date(`2026-11-25T${time}.000Z`)++// The migrations build the usage tables; the box table holds only the columns the read uses.+describeIfDatabase('BoxUsageService (integration, real Postgres)', () => {+ let db: DataSource+ let schema: string+ let archive: Repository<BoxUsagePeriodArchive>+ let service: BoxUsageService++ beforeAll(async () => {+ schema = `box_usage_${randomUUID().replaceAll('-', '')}`+ db = await new DataSource({+ type: 'postgres',+ host: process.env.DB_HOST,+ port: Number(process.env.DB_PORT || 5432),+ username: process.env.DB_USERNAME,+ password: process.env.DB_PASSWORD,+ database: process.env.DB_DATABASE,+ schema,+ entities: [BoxUsagePeriod, BoxUsagePeriodArchive],+ extra: { options: `-c search_path=${schema},public` },+ }).initialize()+ await db.query(`CREATE SCHEMA "${schema}"`)+ await db.query(`CREATE TABLE box (id varchar PRIMARY KEY, "organizationId" uuid NOT NULL)`)+ const runner = db.createQueryRunner()+ try {+ await new AddBoxUsagePeriods1785250000000().up(runner)+ await new AddBoxUsageArchiveBoxIndex1795651200000().up(runner)+ } finally {+ await runner.release()+ }+ archive = db.getRepository(BoxUsagePeriodArchive)+ service = new BoxUsageService(archive)+ })++ afterAll(async () => {+ if (!db?.isInitialized) return+ await db.query(`DROP SCHEMA IF EXISTS "${schema}" CASCADE`)+ await db.destroy()+ })++ beforeEach(async () => {+ await db.query('TRUNCATE box, box_usage_periods, box_usage_periods_archive')+ })++ const addBox = (organization = organizationId) => db.query('INSERT INTO box VALUES ($1, $2)', [boxId, organization])+ const period = (startAt: Date, endAt: Date, resources: Partial<BoxUsagePeriodArchive> = {}) => ({+ boxId,+ organizationId,+ region: 'us',+ startAt,+ endAt,+ cpu: 0,+ gpu: 0,+ mem: 0,+ disk: 0,+ ...resources,+ })+ const read = (organization = organizationId) => service.getUsage(boxId, organization)++ it('answers every archived period in start order with the allocation the export bills', async () => {+ await addBox()+ await archive.save([+ period(at('10:00:15'), at('10:01:15'), { disk: 10 }),+ period(at('10:00:00'), at('10:00:15'), { cpu: 0.125, mem: 0.125, disk: 10 }),+ period(at('10:01:15'), new Date('2026-11-25T10:01:16.500Z'), { cpu: 1.5, mem: 1000 / 1024, disk: 10 }),+ ])++ expect(await read()).toEqual({+ periods: [+ {+ start_at: '2026-11-25T10:00:00.000Z',+ end_at: '2026-11-25T10:00:15.000Z',+ cpu: 0.125,+ memory_gib: 0.125,+ disk_gib: 10,+ },+ {+ start_at: '2026-11-25T10:00:15.000Z',+ end_at: '2026-11-25T10:01:15.000Z',+ cpu: 0,+ memory_gib: 0,+ disk_gib: 10,+ },+ {+ start_at: '2026-11-25T10:01:15.000Z',+ end_at: '2026-11-25T10:01:16.500Z',+ cpu: 1.5,+ memory_gib: 0.976563,+ disk_gib: 10,+ },+ ],+ })+ })++ it('reads a deleted box from the archive once its row is gone', async () => {+ await archive.save(period(at('10:00:00'), at('10:00:15'), { cpu: 2 }))++ expect((await read()).periods).toEqual([expect.objectContaining({ cpu: 2 })])+ })++ it('answers no periods for an owned box with no archived period, ignoring unarchived ones', async () => {+ await addBox()+ await db+ .getRepository(BoxUsagePeriod)+ .save([period(at('10:00:00'), at('10:00:15'), { cpu: 1 }), period(at('10:00:15'), null as never, { cpu: 1 })])++ expect(await read()).toEqual({ periods: [] })+ })++ it("answers 404 for another organization's box, with or without usage", async () => {+ const other = randomUUID()+ await addBox(other)+ await expect(read()).rejects.toBeInstanceOf(NotFoundException)++ await archive.save({ ...period(at('10:00:00'), at('10:00:15'), { cpu: 1 }), organizationId: other })+ await expect(read()).rejects.toBeInstanceOf(NotFoundException)+ expect((await read(other)).periods).toHaveLength(1)+ })++ it('answers 404 for an unknown box, a malformed ID and the unassigned warm pool', async () => {+ await expect(read()).rejects.toBeInstanceOf(NotFoundException)+ await expect(service.getUsage('not a box id', organizationId)).rejects.toBeInstanceOf(NotFoundException)+ await archive.save({+ ...period(at('10:00:00'), at('10:00:15'), { cpu: 1 }),+ organizationId: BOX_WARM_POOL_UNASSIGNED_ORGANIZATION,+ })+ await expect(read(BOX_WARM_POOL_UNASSIGNED_ORGANIZATION)).rejects.toBeInstanceOf(NotFoundException)+ })++ it('skips a period the export would refuse and keeps the others', async () => {+ await db.query(+ `INSERT INTO box_usage_periods_archive ("boxId", "organizationId", region, "startAt", "endAt", cpu, gpu, mem, disk)+ VALUES ($1, $2, 'us', $3, $4, 'NaN', 0, 0, 0)`,+ [boxId, organizationId, at('10:00:00'), at('10:00:15')],+ )+ await archive.save(period(at('10:00:15'), at('10:00:30'), { cpu: 1 }))++ expect((await read()).periods).toEqual([expect.objectContaining({ start_at: '2026-11-25T10:00:15.000Z', cpu: 1 })])+ })++ it('reads through the box index instead of scanning the archive', async () => {+ await db.query('SET enable_seqscan = off')+ try {+ const plan: { 'QUERY PLAN': string }[] = await db.query(`EXPLAIN ${ARCHIVED_PERIODS_SQL}`, [+ boxId,+ organizationId,+ ])+ expect(plan.map((row) => row['QUERY PLAN']).join('\n')).toContain('box_usage_periods_archive_box_org_end_idx')+ } finally {+ await db.query('SET enable_seqscan = on')+ }+ })+})diff --git a/apps/api/src/usage/services/box-usage.service.spec.ts b/apps/api/src/usage/services/box-usage.service.spec.tsnew file mode 100644index 000000000..3af8c82bf--- /dev/null+++ b/apps/api/src/usage/services/box-usage.service.spec.ts@@ -0,0 +1,81 @@+/*+ * Copyright 2026 BoxLite AI+ * SPDX-License-Identifier: AGPL-3.0+ */++import { BoxUsageService } from './box-usage.service'++const boxId = 'aB3cD4eF5gH6'+const period = (startAt: string, endAt: string, resources: { cpu?: number; mem?: number; disk?: number } = {}) => ({+ organizationId: 'org-1',+ boxId,+ region: 'us',+ startAt: new Date(startAt),+ endAt: new Date(endAt),+ cpu: 0,+ gpu: 0,+ mem: 0,+ disk: 0,+ ...resources,+})+const read = (periods: unknown[]) =>+ new BoxUsageService({ query: jest.fn().mockResolvedValue(periods) } as never).getUsage(boxId, 'org-1')++describe('BoxUsageService', () => {+ it('answers one line per archived period with the allocation the export bills', async () => {+ expect(+ await read([+ period('2026-11-29T10:00:00.347Z', '2026-11-29T10:20:01.912Z', { cpu: 0.125, mem: 0.125, disk: 10 }),+ period('2026-11-29T10:20:01.912Z', '2026-11-29T15:45:30.004Z', { disk: 10 }),+ period('2026-11-29T15:45:30.004Z', '2026-11-30T00:00:00.000Z', { cpu: 1.375, mem: 1000 / 1024, disk: 10 }),+ ]),+ ).toEqual({+ periods: [+ {+ start_at: '2026-11-29T10:00:00.347Z',+ end_at: '2026-11-29T10:20:01.912Z',+ cpu: 0.125,+ memory_gib: 0.125,+ disk_gib: 10,+ },+ {+ start_at: '2026-11-29T10:20:01.912Z',+ end_at: '2026-11-29T15:45:30.004Z',+ cpu: 0,+ memory_gib: 0,+ disk_gib: 10,+ },+ {+ start_at: '2026-11-29T15:45:30.004Z',+ end_at: '2026-11-30T00:00:00.000Z',+ cpu: 1.375,+ memory_gib: 0.976563,+ disk_gib: 10,+ },+ ],+ })+ })++ it('leaves out a period that lasted no time or that the export would refuse', async () => {+ const kept = period('2026-11-29T10:00:30.000Z', '2026-11-29T10:00:45.000Z', { cpu: 1 })++ expect(+ await read([+ period('2026-11-29T10:00:00.000Z', '2026-11-29T10:00:00.000Z', { cpu: 1 }),+ period('2026-11-29T10:00:00.000Z', '2026-11-29T10:00:15.000Z', { cpu: Number.NaN }),+ { ...period('2026-11-29T10:00:15.000Z', '2026-11-29T10:00:30.000Z', { cpu: 1 }), gpu: -1 },+ kept,+ ]),+ ).toEqual({+ periods: [+ {+ start_at: '2026-11-29T10:00:30.000Z',+ end_at: '2026-11-29T10:00:45.000Z',+ cpu: 1,+ memory_gib: 0,+ disk_gib: 0,+ },+ ],+ })+ })+})diff --git a/apps/api/src/usage/services/box-usage.service.ts b/apps/api/src/usage/services/box-usage.service.tsnew file mode 100644index 000000000..5b6021030--- /dev/null+++ b/apps/api/src/usage/services/box-usage.service.ts@@ -0,0 +1,76 @@+/*+ * Copyright 2026 BoxLite AI+ * SPDX-License-Identifier: AGPL-3.0+ */++import { Injectable, Logger, NotFoundException } from '@nestjs/common'+import { InjectRepository } from '@nestjs/typeorm'+import { Repository } from 'typeorm'+import { BOX_WARM_POOL_UNASSIGNED_ORGANIZATION } from '../../box/constants/box.constants'+import { isBoxId } from '../../box/utils/box-id.util'+import { BoxUsageDto, BoxUsagePeriodDto } from '../dto/box-usage.dto'+import { BoxUsagePeriodArchive } from '../entities/box-usage-period-archive.entity'+import { FinalizedUsagePeriod, InvalidUsagePeriodError, toUsageEventDto } from '../usage-event'++/** Exported so the integration suite EXPLAINs the query the read runs. */+export const ARCHIVED_PERIODS_SQL = `SELECT "organizationId", "boxId", region, "startAt", "endAt", cpu, gpu, mem, disk+ FROM box_usage_periods_archive+ WHERE "boxId" = $1 AND "organizationId" = $2 ORDER BY "startAt"`++/** Lists one Box's archived usage periods. A period counts once the archive job has moved it. */+@Injectable()+export class BoxUsageService {+ private readonly logger = new Logger(BoxUsageService.name)++ constructor(+ @InjectRepository(BoxUsagePeriodArchive)+ private readonly archiveRepository: Repository<BoxUsagePeriodArchive>,+ ) {}++ async getUsage(boxId: string, organizationId: string): Promise<BoxUsageDto> {+ if (!isBoxId(boxId) || organizationId === BOX_WARM_POOL_UNASSIGNED_ORGANIZATION) throw this.notFound(boxId)++ const periods: FinalizedUsagePeriod[] = await this.archiveRepository.query(ARCHIVED_PERIODS_SQL, [+ boxId,+ organizationId,+ ])+ // Archived periods outlive the Box row, so the row is only asked when there are none.+ if (periods.length === 0 && !(await this.ownsBox(boxId, organizationId))) throw this.notFound(boxId)++ return { periods: periods.flatMap((period) => this.toDto(period)) }+ }++ /** The period as the usage export sends it to billing; none when it lasted no time or the export would refuse it. */+ private toDto(period: FinalizedUsagePeriod): BoxUsagePeriodDto[] {+ if (!(period.endAt.getTime() > period.startAt.getTime())) return []+ try {+ const event = toUsageEventDto(period)+ return [+ {+ start_at: event.startAt,+ end_at: event.endAt,+ cpu: Number(event.cpu),+ memory_gib: Number(event.mem),+ disk_gib: Number(event.disk),+ },+ ]+ } catch (error) {+ if (!(error instanceof InvalidUsagePeriodError)) throw error+ // The export blocks the same period, so it is never billed either.+ this.logger.warn(`Skipping an unexportable usage period of box ${period.boxId}: ${error.message}`)+ return []+ }+ }++ private async ownsBox(boxId: string, organizationId: string): Promise<boolean> {+ const rows: unknown[] = await this.archiveRepository.query(+ `SELECT 1 FROM box WHERE id = $1 AND "organizationId"::text = $2`,+ [boxId, organizationId],+ )+ return rows.length > 0+ }++ private notFound(boxId: string): NotFoundException {+ return new NotFoundException(`Box with ID ${boxId} not found`)+ }+}diff --git a/apps/api/src/usage/usage-event.ts b/apps/api/src/usage/usage-event.tsindex 183dcf0bb..a8293e216 100644--- a/apps/api/src/usage/usage-event.ts+++ b/apps/api/src/usage/usage-event.ts@@ -166,10 +166,13 @@ export function toUsageEventDto(period: FinalizedUsagePeriod): UsageEventDto {}}-/** Round half-up only at the billing boundary; identity and ledger retain exact GiB. */+/**+ * Round half-up to the six fractional digits Commerce stores, only at the billing boundary; identity and+ * ledger retain exact GiB. Allocations in 0.125 GiB steps pass unchanged.+ */export function billingMemoryString(gib: number): string {quantityString(gib, 'mem')- const rounded = Math.round(gib * 100) / 100+ const rounded = Math.round(gib * 1_000_000) / 1_000_000if (gib > 0 && rounded === 0) throw new InvalidUsagePeriodError('mem is too small to bill without rounding away')return quantityString(rounded, 'mem')}diff --git a/apps/api/src/usage/usage.module.ts b/apps/api/src/usage/usage.module.tsindex 87555d91f..668bce8b0 100644--- a/apps/api/src/usage/usage.module.ts+++ b/apps/api/src/usage/usage.module.ts@@ -21,12 +21,14 @@ import { BoxLookupCacheInvalidationService } from '../box/services/box-lookup-caimport { Box } from '../box/entities/box.entity'import { Runner } from '../box/entities/runner.entity'import { UsageConcurrencyService } from './services/usage-concurrency.service'+import { BoxUsageService } from './services/box-usage.service'@Module({imports: [TypeOrmModule.forFeature([BoxUsagePeriod, Box, Runner, BoxUsagePeriodArchive, BoxUsageExportOutbox])],providers: [UsageService,UsageConcurrencyService,+ BoxUsageService,UsageExportOutboxService,UsageExportPublisherService,UsageAllocationSnapshotService,@@ -42,6 +44,6 @@ import { UsageConcurrencyService } from './services/usage-concurrency.service') => new BoxRepository(dataSource, eventEmitter, boxLookupCacheInvalidationService),},],- exports: [UsageService, UsageConcurrencyService],+ exports: [UsageService, UsageConcurrencyService, BoxUsageService],})export class UsageModule {}diff --git a/docs/contributing/architecture/platform/api.md b/docs/contributing/architecture/platform/api.mdindex 9463f6a98..97d8317a9 100644--- a/docs/contributing/architecture/platform/api.md+++ b/docs/contributing/architecture/platform/api.md@@ -777,7 +777,7 @@ Rollback must retain the public replay reader and fences, or stop affectedwrites; returning to a version that ignores valid keys can duplicate effects.<details>-<summary><b>Box lifecycle</b> · 7 routes</summary>+<summary><b>Box lifecycle</b> · 8 routes</summary>| Method | Path | What it does || -------- | ---------------------------------------- | ------------------------------------------- |@@ -785,6 +785,7 @@ writes; returning to a version that ignores valid keys can duplicate effects.| `GET` | `/v1[/{prefix}]/boxes` | Lists boxes in the organization. || `GET` | `/v1[/{prefix}]/boxes/{boxId}` | Gets a box by ID or name. || `HEAD` | `/v1[/{prefix}]/boxes/{boxId}` | Checks whether a box exists. |+| `GET` | `/v1[/{prefix}]/boxes/{boxId}/usage` | Gets one box's [usage](#box-usage) by ID. || `DELETE` | `/v1[/{prefix}]/boxes/{boxId}` | Destroys a box. || `POST` | `/v1[/{prefix}]/boxes/{boxId}/start` | Starts a box and waits until it is running. || `POST` | `/v1[/{prefix}]/boxes/{boxId}/stop` | Stops a box. |@@ -1035,6 +1036,51 @@ sign-in. See [invitation link lifetime](../../../../apps/infra/docs/configuratio</details>+### Box usage++[`BoxUsageService`](../../../../apps/api/src/usage/services/box-usage.service.ts) reads one box's+usage from `box_usage_periods_archive`, the same periods the usage export sends for billing.++1. It reads the archived periods of the box in the caller's organization, oldest `startAt` first.+2. With none, it reads the box row by ID and organization: a row answers an empty list, no row+ answers 404. Archived periods outlive the row, so a deleted box stays readable.+3. It encodes each period as the usage export does and returns `{"periods": [...]}`, one entry+ per period with its start, end and allocation. A box bills full compute while running and disk+ alone once stopped, so a stopped period has `cpu` and `memory_gib` of 0.++| Field | Value |+| --- | --- |+| `start_at`, `end_at` | ISO 8601 UTC, to the millisecond |+| `cpu` | vCPUs, as allocated |+| `memory_gib` | GiB, as the export bills it: rounded half-up to six decimal places, so 0.125 GiB steps are exact |+| `disk_gib` | GiB, as allocated |++Usage in a resource is its value times the seconds from `start_at` to `end_at`, counted to the+millisecond. Billing computes the same product from the same exported values, so totals summed+from the periods match the billed quantities.++Example: a box with 0.125 vCPU, 128 MiB memory and 10 GiB disk runs from 10:00:00 to 10:20:00,+then stops until 11:00:00. The read returns two periods:++```json+{"start_at":"2026-11-30T10:00:00.000Z","end_at":"2026-11-30T10:20:00.000Z","cpu":0.125,"memory_gib":0.125,"disk_gib":10}+{"start_at":"2026-11-30T10:20:00.000Z","end_at":"2026-11-30T11:00:00.000Z","cpu":0,"memory_gib":0,"disk_gib":10}+```++The first period bills 0.125 × 1200 = 150 vCPU-seconds and 0.125 × 1200 = 150 GiB-seconds of+memory.++- A running period is not listed. The roll-over closes a running period after a day, so a box+ that runs without stopping can show no usage for up to a day.+- A closed period is listed once the archive job moves it, within about a minute.+- A period that lasted no time is left out. A period the export refuses as malformed is skipped+ with a warning; it is never billed either.+- The route uses its own `box-usage` throttle, not the `authenticated` one. Set+ `RATE_LIMIT_BOX_USAGE_TTL` (seconds) and `RATE_LIMIT_BOX_USAGE_LIMIT`; with either unset it is+ unlimited. A limited response carries `Retry-After`.+- The index `("boxId", "organizationId", "endAt")` on the archive keeps the read off a scan of the+ organization's history.+### Runner CPU incidentsBackoffice uses `GET /admin/runner-cpu-incidents` with an administrator API keydiff --git a/docs/contributing/architecture/platform/schema.md b/docs/contributing/architecture/platform/schema.mdindex 9453d2850..07eb9ac04 100644--- a/docs/contributing/architecture/platform/schema.md+++ b/docs/contributing/architecture/platform/schema.md@@ -1157,8 +1157,9 @@ periods, so the live table stays small. `endAt` is `NOT NULL` here.| `cpu` / `gpu` / `mem` / `disk` | `double precision` | || `region` | `character varying` | |-**Index:** `(organizationId, endAt) INCLUDE (boxId, startAt)` for-compute-bearing periods.+**Indexes:** `(organizationId, endAt) INCLUDE (boxId, startAt)` for+compute-bearing periods; `(boxId, organizationId, endAt)`, which the+[box usage](api.md#box-usage) read uses.### `box_usage_export_outbox`@@ -1168,7 +1169,7 @@ adding one would not help, because Postgres sequences can commit out of orderand a `seq > cursor` reader would silently skip rows.The event key retains exact source quantities. Only the outbound payload's-memory quantity rounds half-up to two decimal GiB places; allocation snapshots+memory quantity rounds half-up to six decimal GiB places; allocation snapshotsuse the same rule. Existing outbox payloads are immutable across deployment.| Column | Type | Notes |diff --git a/docs/guides/resource-limits.md b/docs/guides/resource-limits.mdindex 538d283e3..a1b707d19 100644--- a/docs/guides/resource-limits.md+++ b/docs/guides/resource-limits.md@@ -67,14 +67,15 @@ The migration backfills existing rows with `mem * 1024`; readers use that fallbafor null rows and checkpoints written by previous versions.Memory range filters, quotas, admin byte counts, and usage periods use the exact allocation.-Billing event and open-allocation responses round memory GiB half-up to two decimal places:+Billing event and open-allocation responses round memory GiB half-up to six decimal places,+the precision Commerce stores. Allocations in 0.125 GiB steps are sent unchanged:| Requested memory | Exact GiB in the ledger | Billing `mem` string || --- | --- | --- |-| 300 MiB | 0.29296875 | `"0.29"` |-| 512 MiB | 0.5 | `"0.5"` |-| 640 MiB | 0.625 | `"0.63"` |+| 128 MiB | 0.125 | `"0.125"` |+| 640 MiB | 0.625 | `"0.625"` || 1536 MiB | 1.5 | `"1.5"` |+| 300 MiB | 0.29296875 | `"0.292969"` |Trailing zeros are omitted. Event identity uses the exact source quantity, soallocations that round to the same billing value retain distinct event keys.diff --git a/docs/reference/README.md b/docs/reference/README.mdindex 3acd67985..20842a76f 100644--- a/docs/reference/README.md+++ b/docs/reference/README.md@@ -38,12 +38,12 @@ Complete API documentation for each SDK:| **Reference server** | [`openapi/reference-server/`](../../openapi/reference-server/README.md) | A partial implementation used as a client test fixture, not a conformance target |The spec is the contract, not an inventory of any one server, and no-implementation currently serves all 49 paths:+implementation currently serves all 50 paths:| Server | Serves | Does not serve ||--------|--------|----------------|-| `boxlite serve` | boxes, lifecycle, exec, files, snapshots, clone/export/import, metrics, config, me, images (from its local image cache) | registries, `network/tunnel`, `network/inbound`. Volume routes are registered but every operation answers `400 UnsupportedError`, as do `images/usage` and both alias write routes |-| reference server | boxes, lifecycle, exec, files, snapshots, clone/export/import, metrics, config, me | volumes, images, registries, `network/tunnel`, `network/inbound`, attach, and `DELETE …/executions/{exec_id}` (kill) |+| `boxlite serve` | boxes, lifecycle, exec, files, snapshots, clone/export/import, metrics, config, me, images (from its local image cache) | registries, box usage, `network/tunnel`, `network/inbound`. Volume routes are registered but every operation answers `400 UnsupportedError`, as do `images/usage` and both alias write routes |+| reference server | boxes, lifecycle, exec, files, snapshots, clone/export/import, metrics, config, me | volumes, images, registries, box usage, `network/tunnel`, `network/inbound`, attach, and `DELETE …/executions/{exec_id}` (kill) |Use `POST /{prefix}/boxes/{box_id}/exec` with `"sync": true` (`sync` defaultsto `false`) for a non-interactive command that should return its exit code anddiff --git a/openapi/box.openapi.yaml b/openapi/box.openapi.yamlindex 5ef7fca0d..4ccb8cebb 100644--- a/openapi/box.openapi.yaml+++ b/openapi/box.openapi.yaml@@ -469,6 +469,51 @@ paths:"503":$ref: "#/components/responses/ServiceUnavailableError"+ /{prefix}/boxes/{box_id}/usage:+ parameters:+ - $ref: "#/components/parameters/prefix"+ - $ref: "#/components/parameters/boxId"++ get:+ operationId: getBoxUsage+ summary: Get what resources one box used+ description: |+ Returns every archived usage period of the box, oldest first, with the+ allocation metered for it, in every box state, including after the box+ is deleted. A period that is still running, or ended in the+ last minute or so, is not listed yet. Accepts a box ID only: a name can+ be reused by another box. Served by the hosted service only.+ tags: [Boxes]+ responses:+ "200":+ description: The box's archived usage periods+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/BoxUsage"+ "401":+ $ref: "#/components/responses/UnauthorizedError"+ "403":+ description: The caller cannot access the organization+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ErrorResponse"+ "404":+ $ref: "#/components/responses/NotFoundError"+ "429":+ description: Rate limit exceeded+ headers:+ Retry-After:+ description: Seconds to wait before the next request+ schema:+ type: integer+ minimum: 1+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ErrorResponse"+# -------------------------------------------------------------------------# Box Lifecycle# -------------------------------------------------------------------------@@ -4094,6 +4139,47 @@ components:description: Graceful shutdown timeout in seconds. After expiry, force-kill.default: 30+ BoxUsage:+ type: object+ required: [periods]+ properties:+ periods:+ type: array+ description: |+ One entry per archived period, ordered by `start_at`. Empty when the+ box has no archived period yet.+ items:+ $ref: "#/components/schemas/BoxUsagePeriod"++ BoxUsagePeriod:+ type: object+ description: |+ One period with the allocation as the usage export meters it. Usage in+ a resource is its allocation times the seconds from `start_at` to+ `end_at`, counted to the millisecond.+ required: [start_at, end_at, cpu, memory_gib, disk_gib]+ properties:+ start_at:+ type: string+ format: date-time+ end_at:+ type: string+ format: date-time+ cpu:+ type: number+ minimum: 0+ description: vCPUs allocated; 0 while the box is stopped+ memory_gib:+ type: number+ minimum: 0+ description: |+ GiB of memory allocated, rounded half-up to six decimal places as+ metered; 0 while the box is stopped+ disk_gib:+ type: number+ minimum: 0+ description: GiB of disk allocated+ListBoxesResponse:type: objectrequired: [boxes]