The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
feat(volumes): add Filestore Volume API and Box mount dispatch (#2732)
Lhfcwsbf1e30df6322
diff --git a/apps/api/src/box/controllers/volume-caller-http.spec.ts b/apps/api/src/box/controllers/volume-caller-http.spec.tsindex 683e12c55..cdf2100ca 100644--- a/apps/api/src/box/controllers/volume-caller-http.spec.ts+++ b/apps/api/src/box/controllers/volume-caller-http.spec.ts@@ -60,6 +60,7 @@ describe('Volume HTTP caller attribution', () => {{ assertOrganizationIsNotSuspended: jest.fn() } as never,{ get: () => 'gcs' } as never,{} as never,+ {} as never,)const module = Test.createTestingModule({controllers: [VolumeController, BoxliteVolumeController],diff --git a/apps/api/src/box/dto/box.dto.spec.ts b/apps/api/src/box/dto/box.dto.spec.tsindex 8214bfbc6..f2db7e567 100644--- a/apps/api/src/box/dto/box.dto.spec.ts+++ b/apps/api/src/box/dto/box.dto.spec.ts@@ -21,6 +21,32 @@ describe('BoxDto public identity', () => {})})+describe('BoxDto volume confidentiality', () => {+ it('exposes only the logical Filestore instance, not its resolved NFS target', () => {+ const box = new Box('us', 'filestore-box')+ box.volumes = [+ {+ volumeId: 'volume-1',+ mountPath: '/data',+ filestore: { instance: 'ml-scratch', server: '10.0.0.7', export: '/vol1' },+ },+ ]++ const dto = BoxDto.fromBox(box)++ expect(dto.volumes).toEqual([+ {+ volumeId: 'volume-1',+ mountPath: '/data',+ subpath: undefined,+ filestore: { instance: 'ml-scratch' },+ },+ ])+ expect(JSON.stringify(dto.volumes)).not.toContain('10.0.0.7')+ expect(JSON.stringify(dto.volumes)).not.toContain('/vol1')+ })+})+describe('BoxDto main command exit code', () => {function box(): Box {const box = new Box('us', 'loader')diff --git a/apps/api/src/box/dto/box.dto.ts b/apps/api/src/box/dto/box.dto.tsindex 236cc0ac7..ab2a0893a 100644--- a/apps/api/src/box/dto/box.dto.ts+++ b/apps/api/src/box/dto/box.dto.ts@@ -4,7 +4,7 @@* SPDX-License-Identifier: AGPL-3.0*/-import { ApiProperty, ApiPropertyOptional, ApiSchema } from '@nestjs/swagger'+import { ApiHideProperty, ApiProperty, ApiPropertyOptional, ApiSchema } from '@nestjs/swagger'import { BoxState } from '../enums/box-state.enum'import { IsEnum, IsOptional } from 'class-validator'import { IMAGE_PREPARATION_RETRY_AFTER_MS } from '../constants/box-progress.constant'@@ -16,6 +16,7 @@ import { NetworkInfoResponseDto } from './network-info.dto'import { BoxProgressPhase } from '../enums/box-progress-phase.enum'import { reportedBoxState } from '../utils/box-state.util'import { upstreamRefOf } from '../../image/utils/image-ref.util'+import { boxVolumeForPublic } from '../utils/box-volume.util'@ApiSchema({ name: 'BoxProgress' })export class BoxProgressDto {@@ -35,10 +36,36 @@ export class BoxProgressDto {retryAfterMs: number}+/**+ * The filestore reference of a box volume. `instance` is the logical name the+ * Volume row persists; `server`/`export` are what the API resolves from GCP at+ * dispatch time. The address travels only inside internal dispatch and persisted+ * volume metadata. Public responses expose only `instance`; every dispatch+ * discovers the current address.+ */+@ApiSchema({ name: 'BoxVolumeFilestoreRef' })+export class BoxVolumeFilestoreRef {+ @ApiProperty({+ description: 'Filestore instance logical name selected from the API configuration',+ example: 'boxlite-dev-shared',+ })+ instance: string++ @ApiHideProperty()+ server: string++ @ApiHideProperty()+ export: string+}+@ApiSchema({ name: 'BoxVolume' })export class BoxVolume {+ /**+ * The volume's server-assigned id. Filestore volumes are Volume rows like+ * any other and carry an id the same way.+ */@ApiProperty({- description: 'The ID of the volume',+ description: 'The ID of the volume (bucket-backed or Filestore-backed)',example: 'volume123',})volumeId: string@@ -49,6 +76,16 @@ export class BoxVolume {})mountPath: string+ /**+ * Filestore-only. Present on a box volume whose Volume row carries an+ * `instance`; absent for bucket-backed volumes.+ */+ @ApiPropertyOptional({+ description: 'The Filestore instance reference; absent for bucket-backed volumes',+ type: BoxVolumeFilestoreRef,+ })+ filestore?: BoxVolumeFilestoreRef+@ApiPropertyOptional({description:'Optional subpath within the volume to mount. When specified, only this S3 prefix will be accessible. When omitted, the entire volume is mounted.',@@ -388,7 +425,7 @@ export class BoxDto {privileged: box.privileged,network: NetworkInfoResponseDto.fromBox(box),labels: box.labels,- volumes: box.volumes,+ volumes: box.volumes?.map(boxVolumeForPublic),state,desiredState: box.desiredState,errorReason: box.errorReason,diff --git a/apps/api/src/box/dto/create-volume.dto.spec.ts b/apps/api/src/box/dto/create-volume.dto.spec.tsindex f4306e443..b62fe2211 100644--- a/apps/api/src/box/dto/create-volume.dto.spec.ts+++ b/apps/api/src/box/dto/create-volume.dto.spec.ts@@ -1,6 +1,9 @@import { plainToInstance } from 'class-transformer'import { validate } from 'class-validator'-import { CreateVolumeDto } from './create-volume.dto'+import { CreateVolumeDto, FILESTORE_INSTANCE_PATTERN } from './create-volume.dto'+import { readFileSync } from 'node:fs'+import path from 'node:path'+import { parse } from 'yaml'describe('CreateVolumeDto name', () => {async function errorsFor(payload: Record<string, unknown>) {@@ -31,3 +34,49 @@ describe('CreateVolumeDto name', () => {expect(await errorsFor({ name: 'a' })).toContain('matches')})})++// The instance name becomes a component of the runner's host mount path+// (/mnt/boxlite-filestore-<name>), so the API configuration grammar must keep+// out path separators and relative components, and stay free of characters a+// `-v` source could never address.+describe('CreateVolumeDto filestore instance', () => {+ async function errorsFor(payload: Record<string, unknown>) {+ return JSON.stringify(await validate(plainToInstance(CreateVolumeDto, payload)))+ }++ it('accepts an absent instance (object-storage kind)', async () => {+ expect(await validate(plainToInstance(CreateVolumeDto, {}))).toHaveLength(0)+ })++ it('validates names matching the runner path-safety grammar', async () => {+ for (const instance of ['ml-scratch', 'a', 'vol-1']) {+ expect(await validate(plainToInstance(CreateVolumeDto, { instance }))).toHaveLength(0)+ expect(await validate(plainToInstance(CreateVolumeDto, { storageBackend: 'performance', instance }))).toHaveLength(+ 0,+ )+ }+ })++ it.each(['ML', '-x', 'a/b', 'a:b', ''])(+ 'rejects a Filestore instance outside the path-safety grammar (%s)',+ async (instance) => {+ expect(await errorsFor({ storageBackend: 'performance', instance })).toContain('matches')+ },+ )++ it('rejects an unsupported backend', async () => {+ expect(await errorsFor({ storageBackend: 'unknown' })).toContain('storageBackend')+ })+})++describe('CreateVolumeDto OpenAPI contract', () => {+ it('uses the server-side Filestore instance grammar in the public schema', () => {+ const document = parse(readFileSync(path.resolve(__dirname, '../../../../../openapi/box.openapi.yaml'), 'utf8'))+ const pattern = document.components.schemas.CreateVolumeRequest.properties.instance.pattern++ expect(pattern).toBe(FILESTORE_INSTANCE_PATTERN.source)+ for (const instance of ['1foo', 'foo-']) {+ expect(new RegExp(pattern).test(instance)).toBe(false)+ }+ })+})diff --git a/apps/api/src/box/dto/create-volume.dto.ts b/apps/api/src/box/dto/create-volume.dto.tsindex b4f75934a..6bd4a9f8f 100644--- a/apps/api/src/box/dto/create-volume.dto.ts+++ b/apps/api/src/box/dto/create-volume.dto.ts@@ -4,8 +4,9 @@* SPDX-License-Identifier: AGPL-3.0*/-import { ApiProperty, ApiSchema } from '@nestjs/swagger'-import { IsString, Matches, ValidateIf } from 'class-validator'+import { ApiProperty, ApiPropertyOptional, ApiSchema } from '@nestjs/swagger'+import { IsEnum, IsNotEmpty, IsString, Matches, ValidateIf } from 'class-validator'+import { FILESTORE_INSTANCE_NAME_PATTERN } from '../../config/filestore-instances'/*** A volume can be mounted by name in place of its id, so a name has to be@@ -25,6 +26,20 @@ import { IsString, Matches, ValidateIf } from 'class-validator'*/export const VOLUME_NAME_PATTERN = /^[a-zA-Z0-9][a-zA-Z0-9_.-]+$/+/**+ * The Filestore instance's logical name pattern. Shared with the API's+ * FILESTORE_INSTANCES configuration parser (FILESTORE_INSTANCE_NAME_PATTERN in+ * config/filestore-instances.ts), which validates the same names at startup:+ * the instance name becomes a component of the runner-side mount path+ * (/mnt/boxlite-filestore-<name>), so the constraints are — no path+ * separators, no relative components.+ */+export const FILESTORE_INSTANCE_PATTERN = FILESTORE_INSTANCE_NAME_PATTERN++export const VOLUME_STORAGE_BACKENDS = ['standard', 'performance'] as const++export type VolumeStorageBackend = (typeof VOLUME_STORAGE_BACKENDS)[number]+@ApiSchema({ name: 'CreateVolume' })export class CreateVolumeDto {@ApiProperty({ required: false, example: 'my-data' })@@ -38,4 +53,34 @@ export class CreateVolumeDto {'If you intended to pass a host directory, use an absolute path.',})name?: string++ @ApiPropertyOptional({+ description: 'The storage class of the volume; defaults to standard',+ enum: VOLUME_STORAGE_BACKENDS,+ example: 'performance',+ })+ @ValidateIf((_, value) => value !== undefined)+ @IsEnum(VOLUME_STORAGE_BACKENDS)+ storageBackend?: VolumeStorageBackend++ /**+ * The Filestore instance this volume's data directory lives on. It is+ * accepted only with `storageBackend: "performance"`; if omitted, Filestore+ * placement is assigned from the configured instances.+ */+ @ApiPropertyOptional({+ description:+ 'The Filestore instance the volume stores its data on; filestore volumes only. Omit to assign from configured instances.',+ example: 'boxlite-dev-shared',+ })+ @ValidateIf((_, value) => value !== undefined)+ @IsString()+ @IsNotEmpty()+ @Matches(FILESTORE_INSTANCE_PATTERN, {+ message:+ 'instance must be the logical name of a Filestore instance: 1-63 characters of ' ++ '[a-z0-9] and -, starting with a lowercase letter and ending alphanumeric. It must match an instance entry in the ' ++ "API's FILESTORE_INSTANCES configuration.",+ })+ instance?: string}diff --git a/apps/api/src/box/dto/volume.dto.spec.ts b/apps/api/src/box/dto/volume.dto.spec.tsnew file mode 100644index 000000000..c40d75030--- /dev/null+++ b/apps/api/src/box/dto/volume.dto.spec.ts@@ -0,0 +1,31 @@+import { Volume } from '../entities/volume.entity'+import { VolumeState } from '../enums/volume-state.enum'+import { VolumeDto } from './volume.dto'++function volume(overrides: Partial<Volume> = {}): Volume {+ return {+ id: 'volume-1',+ name: 'my-volume',+ organizationId: 'org-1',+ state: VolumeState.READY,+ createdAt: new Date('2026-01-01T00:00:00Z'),+ updatedAt: new Date('2026-01-02T00:00:00Z'),+ ...overrides,+ } as Volume+}++describe('VolumeDto', () => {+ it('derives an object-storage backend from an absent instance', () => {+ const dto = VolumeDto.fromVolume(volume())++ expect(dto.storageBackend).toBe('standard')+ expect(dto.instance).toBeUndefined()+ })++ it('derives a Filestore backend and preserves only the logical instance name', () => {+ const dto = VolumeDto.fromVolume(volume({ instance: 'ml-scratch' }))++ expect(dto.storageBackend).toBe('performance')+ expect(dto.instance).toBe('ml-scratch')+ })+})diff --git a/apps/api/src/box/dto/volume.dto.ts b/apps/api/src/box/dto/volume.dto.tsindex c487342c9..205fc426a 100644--- a/apps/api/src/box/dto/volume.dto.ts+++ b/apps/api/src/box/dto/volume.dto.ts@@ -6,8 +6,9 @@import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger'import { IsEnum } from 'class-validator'+import { VOLUME_STORAGE_BACKENDS, VolumeStorageBackend } from './create-volume.dto'import { VolumeState } from '../enums/volume-state.enum'-import { Volume } from '../entities/volume.entity'+import { isFilestoreVolume, Volume } from '../entities/volume.entity'export class VolumeDto {@ApiProperty({@@ -37,6 +38,19 @@ export class VolumeDto {@IsEnum(VolumeState)state: VolumeState+ @ApiProperty({+ description: 'The storage class of the volume',+ enum: VOLUME_STORAGE_BACKENDS,+ example: 'standard',+ })+ storageBackend: VolumeStorageBackend++ @ApiPropertyOptional({+ description: 'Filestore instance name; filestore volumes only',+ example: 'boxlite-dev-shared',+ })+ instance?: string+@ApiProperty({description: 'Creation timestamp',example: '2023-01-01T00:00:00.000Z',@@ -69,6 +83,8 @@ export class VolumeDto {name: volume.name,organizationId: volume.organizationId,state: volume.state,+ storageBackend: isFilestoreVolume(volume) ? 'performance' : 'standard',+ instance: volume.instance || undefined,createdAt: volume.createdAt?.toISOString(),updatedAt: volume.updatedAt?.toISOString(),lastUsedAt: volume.lastUsedAt?.toISOString(),diff --git a/apps/api/src/box/entities/volume.entity.ts b/apps/api/src/box/entities/volume.entity.tsindex c00a782d6..1efce0982 100644--- a/apps/api/src/box/entities/volume.entity.ts+++ b/apps/api/src/box/entities/volume.entity.ts@@ -45,7 +45,19 @@ export class Volume {@Column({ nullable: true })lastUsedAt?: Date+ // Filestore-only: the Filestore instance's logical name in the API's+ // FILESTORE_INSTANCES configuration that holds the volume's data directory. Null+ // for object-storage volumes, whose data lives in `boxlite-volume-<id>` on+ // the API's own object storage backend. The volume kind is derived: a row+ // with an instance is a filestore volume, without one an object-storage one.+ @Column({ nullable: true })+ instance?: string+public getBucketName(): string {return `boxlite-volume-${this.id}`}}++export function isFilestoreVolume<T extends Pick<Volume, 'instance'>>(volume: T): volume is T & { instance: string } {+ return Boolean(volume.instance)+}diff --git a/apps/api/src/box/managers/box-actions/box-start.action.spec.ts b/apps/api/src/box/managers/box-actions/box-start.action.spec.tsindex 5e38b130b..e5b6a8511 100644--- a/apps/api/src/box/managers/box-actions/box-start.action.spec.ts+++ b/apps/api/src/box/managers/box-actions/box-start.action.spec.ts@@ -10,15 +10,108 @@ jest.mock('uuid', () => ({}))import { BoxStartAction } from './box-start.action'-import { BoxAction, SYNC_AGAIN } from './box.action'+import { BoxAction, DONT_SYNC_AGAIN, SYNC_AGAIN } from './box.action'import { Box } from '../../entities/box.entity'import { Runner } from '../../entities/runner.entity'import { BoxState } from '../../enums/box-state.enum'import { BoxDesiredState } from '../../enums/box-desired-state.enum'import { RunnerState } from '../../enums/runner-state.enum'import { LockCode } from '../../common/redis-lock.provider'+import { RunnerAdapterV0 } from '../../runner-adapter/runnerAdapter.v0'+import { ServiceUnavailableException } from '@nestjs/common'describe('BoxStartAction.handleRunnerBoxStoppedStateOnDesiredStateStart', () => {+ function stoppedFilestoreFixture(adapter: any) {+ const box = new Box('region-1', 'filestore-box')+ box.runnerId = 'runner-1'+ box.state = BoxState.STOPPED+ box.desiredState = BoxDesiredState.STARTED+ box.pending = true+ box.volumes = [+ {+ volumeId: 'volume-1',+ mountPath: '/data',+ filestore: { instance: 'ml-scratch', server: '10.0.0.7', export: '/vol1' },+ },+ ] as any+ const lockCode = new LockCode('lock-filestore-start')+ const update = jest.fn(async () => box)+ const filestoreInstanceResolver = {+ resolve: jest.fn().mockResolvedValue({ server: '10.0.0.9', export: '/vol2' }),+ }+ const action = new BoxStartAction(+ { findOneOrFail: jest.fn(async () => ({ id: 'runner-1', state: RunnerState.READY })) } as any,+ { create: jest.fn(async () => adapter) } as any,+ { update } as any,+ { findOne: jest.fn(async () => ({ boxMetadata: {} })) } as any,+ { getOrThrow: () => 1 } as any,+ { getCode: jest.fn(async () => lockCode) } as any,+ {} as any,+ {} as any,+ filestoreInstanceResolver as any,+ )+ return { box, lockCode, action, update, filestoreInstanceResolver }+ }++ it('keeps a stopped box retryable until the runner regains Filestore capability', async () => {+ const capabilityError = Object.assign(new Error('FILESTORE_CAPABILITY_MISSING'), {+ code: 'FILESTORE_CAPABILITY_MISSING',+ })+ const assertFilestoreVolumeSupport = jest+ .fn()+ .mockRejectedValueOnce(capabilityError)+ .mockResolvedValueOnce(undefined)+ const startBox = jest.fn(async () => undefined)+ const { box, lockCode, action, update } = stoppedFilestoreFixture({ assertFilestoreVolumeSupport, startBox })++ await expect((action as BoxAction).run(box, lockCode)).resolves.toBe(DONT_SYNC_AGAIN)+ expect(assertFilestoreVolumeSupport).toHaveBeenCalledWith(expect.objectContaining({ id: box.id }))+ expect(startBox).not.toHaveBeenCalled()+ expect(update).not.toHaveBeenCalled()+ expect(box.state).toBe(BoxState.STOPPED)++ await expect((action as BoxAction).run(box, lockCode)).resolves.toBe(SYNC_AGAIN)+ expect(startBox).toHaveBeenCalledTimes(1)+ expect(update).toHaveBeenCalledWith(+ box.id,+ expect.objectContaining({ updateData: expect.objectContaining({ state: BoxState.STARTING }) }),+ )+ })++ it('does not send a Filestore restart to a v0 runner', async () => {+ const adapter = new RunnerAdapterV0()+ await adapter.init({ id: 'runner-1', apiVersion: '0', apiUrl: 'http://runner.invalid' } as any)+ const start = jest.fn().mockResolvedValue({ data: {} })+ ;(adapter as any).boxApiClient = { start }+ const { box, lockCode, action } = stoppedFilestoreFixture(adapter)++ await expect((action as BoxAction).run(box, lockCode)).rejects.toThrow(/requires a v2 runner/)+ expect(start).not.toHaveBeenCalled()+ })++ it('keeps a stopped box retryable when Filestore resolution is temporarily unavailable', async () => {+ const startBox = jest.fn(async () => undefined)+ const { box, lockCode, action, update, filestoreInstanceResolver } = stoppedFilestoreFixture({+ startBox,+ assertFilestoreVolumeSupport: jest.fn(async () => undefined),+ })+ filestoreInstanceResolver.resolve+ .mockRejectedValueOnce(new ServiceUnavailableException('temporary GCP outage'))+ .mockResolvedValueOnce({ server: '10.0.0.9', export: '/vol2' })++ await expect((action as BoxAction).run(box, lockCode)).resolves.toBe(DONT_SYNC_AGAIN)+ expect(startBox).not.toHaveBeenCalled()+ expect(update).not.toHaveBeenCalled()+ expect(box.state).toBe(BoxState.STOPPED)++ await expect((action as BoxAction).run(box, lockCode)).resolves.toBe(SYNC_AGAIN)+ expect(startBox).toHaveBeenCalledTimes(1)+ expect(update).toHaveBeenCalledWith(+ box.id,+ expect.objectContaining({ updateData: expect.objectContaining({ state: BoxState.STARTING }) }),+ )+ })+it('restarts a stopped box on its own runner (no cross-runner reassignment)', async () => {const ownRunnerId = 'runner-own-1'@@ -47,7 +140,7 @@ describe('BoxStartAction.handleRunnerBoxStoppedStateOnDesiredStateStart', () =>const runnerAdapterFactory = {create: jest.fn(async (runner: Runner) => {runnerUsedForStart = runner- return { startBox } as any+ return { startBox, assertFilestoreVolumeSupport: jest.fn(async () => undefined) } as any}),}@@ -76,6 +169,7 @@ describe('BoxStartAction.handleRunnerBoxStoppedStateOnDesiredStateStart', () =>redisLockProvider as any,{} as any, // boxActivityService{} as any, // curatedImagePins+ {} as any,)const result = await (action as BoxAction).run(box, lockCode)@@ -91,6 +185,83 @@ describe('BoxStartAction.handleRunnerBoxStoppedStateOnDesiredStateStart', () =>expect(updatedFields.some((u) => u.state === BoxState.STARTING)).toBe(true)})+ it('re-resolves the filestore target in the start metadata of a restarted box', async () => {+ const ownRunnerId = 'runner-own-1'++ const box = new Box('region-1', 'my-box')+ box.runnerId = ownRunnerId+ box.state = BoxState.STOPPED+ box.desiredState = BoxDesiredState.STARTED+ box.pending = true+ box.volumes = [+ {+ volumeId: 'volume-1',+ mountPath: '/data',+ filestore: { instance: 'ml-scratch', server: '10.0.0.7', export: '/vol1' },+ },+ ] as any++ const ownRunner = { id: ownRunnerId, state: RunnerState.READY } as Runner+ const runnerService = {+ findOneOrFail: jest.fn(async (id: string) => {+ if (id !== ownRunnerId) {+ throw new Error(`unexpected runner lookup: ${id}`)+ }+ return ownRunner+ }),+ }++ const startBox = jest.fn(async (_boxId: string, _token: string, _metadata: Record<string, string>) => undefined)+ const runnerAdapterFactory = {+ create: jest.fn(async () => ({ startBox, assertFilestoreVolumeSupport: jest.fn(async () => undefined) }) as any),+ }++ const lockCode = new LockCode('lock-1')+ const updatedFields: Partial<Box>[] = []+ const boxRepository = {+ update: jest.fn(async (_id: string, opts: { updateData: Partial<Box> }) => {+ updatedFields.push(opts.updateData)+ return box+ }),+ }+ const redisLockProvider = {+ getCode: jest.fn(async () => lockCode),+ }+ const organizationService = {+ findOne: jest.fn(async () => ({ boxMetadata: {} })),+ }++ const action = new BoxStartAction(+ runnerService as any,+ runnerAdapterFactory as any,+ boxRepository as any,+ organizationService as any,+ { getOrThrow: () => 1 } as any, // configService+ redisLockProvider as any,+ {} as any, // boxActivityService+ {} as any, // curatedImagePins+ {} as any,+ )+ const filestoreInstanceResolver = {+ resolve: jest.fn().mockResolvedValue({ server: '10.0.0.9', export: '/vol2' }),+ }+ Object.assign(action, { filestoreInstanceResolver })++ await (action as BoxAction).run(box, lockCode)++ expect(filestoreInstanceResolver.resolve).toHaveBeenCalledWith('ml-scratch', 'configured')+ const metadata = startBox.mock.calls[0][2] as { volumes: string }+ const volumes = JSON.parse(metadata['volumes'])+ expect(volumes).toEqual([+ {+ volumeId: 'volume-1',+ mountPath: '/data',+ subpath: undefined,+ filestore: { instance: 'ml-scratch', server: '10.0.0.9', export: '/vol2' },+ },+ ])+ })+it('moves a stopped box with no runner to ERROR (cross-runner recovery is not supported)', async () => {const box = new Box('region-1', 'orphan-box')box.runnerId = null@@ -123,6 +294,7 @@ describe('BoxStartAction.handleRunnerBoxStoppedStateOnDesiredStateStart', () =>redisLockProvider as any,{} as any,{} as any,+ {} as any,)await (action as BoxAction).run(box, lockCode)@@ -135,6 +307,46 @@ describe('BoxStartAction.handleRunnerBoxStoppedStateOnDesiredStateStart', () =>})describe('BoxStartAction.handleRunnerBoxUnknownStateOnDesiredStateStart', () => {+ it('uses the refreshed Filestore target in both the create payload and start metadata', async () => {+ const box = new Box('region-1', 'filestore-create')+ box.runnerId = 'runner-1'+ box.image = 'boxlite/base'+ box.state = BoxState.UNKNOWN+ box.desiredState = BoxDesiredState.STARTED+ box.pending = true+ box.volumes = [+ {+ volumeId: 'volume-1',+ mountPath: '/data',+ filestore: { instance: 'ml-scratch', server: '10.0.0.7', export: '/vol1' },+ },+ ] as any+ const createBox: jest.Mock = jest.fn(async () => undefined)+ const lockCode = new LockCode('lock-filestore-create')+ const action = new BoxStartAction(+ { findOneOrFail: jest.fn(async () => ({ id: 'runner-1', state: RunnerState.READY })) } as any,+ { create: jest.fn(async () => ({ createBox })) } as any,+ { update: jest.fn(async () => box) } as any,+ {+ findOne: jest.fn(async () => ({ boxMetadata: {} })),+ isNestedVirtualizationEnabled: jest.fn().mockResolvedValue(false),+ } as any,+ { getOrThrow: () => 1 } as any,+ { getCode: jest.fn(async () => lockCode) } as any,+ {} as any,+ { refFor: jest.fn(async (_runnerId, image) => image) } as any,+ { resolve: jest.fn().mockResolvedValue({ server: '10.0.0.9', export: '/vol2' }) } as any,+ )++ await (action as BoxAction).run(box, lockCode)++ const [dispatchBox, , metadata] = createBox.mock.calls[0]+ const refreshed = { instance: 'ml-scratch', server: '10.0.0.9', export: '/vol2' }+ expect(dispatchBox.volumes[0].filestore).toEqual(refreshed)+ expect(JSON.parse(metadata.volumes)[0].filestore).toEqual(refreshed)+ expect(box.volumes[0].filestore.server).toBe('10.0.0.7')+ })+it('boots an unknown box via runnerAdapter.createBox and moves it to CREATING', async () => {const runnerId = 'runner-boot-1'@@ -174,6 +386,7 @@ describe('BoxStartAction.handleRunnerBoxUnknownStateOnDesiredStateStart', () =>redisLockProvider as any,{} as any,{} as any,+ {} as any,)const result = await (action as BoxAction).run(box, lockCode)@@ -221,6 +434,7 @@ describe('BoxStartAction.handleRunnerBoxUnknownStateOnDesiredStateStart', () =>redisLockProvider as any,{} as any,{} as any,+ {} as any,)await (action as BoxAction).run(box, lockCode)@@ -257,6 +471,7 @@ describe('BoxStartAction image dispatch', () => {{ getCode: jest.fn(async () => lockCode) } as any,{} as any,curatedImagePins as any,+ {} as any,)await (action as BoxAction).run(box, lockCode)diff --git a/apps/api/src/box/managers/box-actions/box-start.action.ts b/apps/api/src/box/managers/box-actions/box-start.action.tsindex 56cdabe48..ef0ba8e90 100644--- a/apps/api/src/box/managers/box-actions/box-start.action.ts+++ b/apps/api/src/box/managers/box-actions/box-start.action.ts@@ -4,7 +4,7 @@* SPDX-License-Identifier: AGPL-3.0*/-import { Injectable, Logger } from '@nestjs/common'+import { Injectable, Logger, ServiceUnavailableException } from '@nestjs/common'import { BoxRepository } from '../../repositories/box.repository'import { Box } from '../../entities/box.entity'import { BoxState } from '../../enums/box-state.enum'@@ -19,6 +19,8 @@ import { WithSpan } from '../../../common/decorators/otel.decorator'import { BoxActivityService } from '../../services/box-activity.service'import { CuratedImagePinService } from '../../../image/services/curated-image-pin.service'import { boxImageIsOrgOwned } from '../../utils/image-ownership.util'+import { boxVolumeForDispatch } from '../../utils/box-volume.util'+import { FilestoreInstanceResolver } from '../../services/filestore-instance.resolver'import { resolveNestedVirtualization } from '../../runner-adapter/nested-virtualization-policy'@@ -34,6 +36,7 @@ export class BoxStartAction extends BoxAction {protected readonly redisLockProvider: RedisLockProvider,private readonly boxActivityService: BoxActivityService,private readonly curatedImagePins: CuratedImagePinService,+ private readonly filestoreInstanceResolver: FilestoreInstanceResolver,) {super(runnerService, runnerAdapterFactory, boxRepository, redisLockProvider)}@@ -74,12 +77,8 @@ export class BoxStartAction extends BoxAction {const organization = await this.organizationService.findOne(box.organizationId)- const metadata: { [key: string]: string } = { ...organization?.boxMetadata }- if (box.volumes?.length) {- metadata['volumes'] = JSON.stringify(- box.volumes.map((v) => ({ volumeId: v.volumeId, mountPath: v.mountPath, subpath: v.subpath })),- )- }+ const volumes = await this.resolveBoxVolumes(box)+ const metadata = this.volumeMetadata({ ...organization?.boxMetadata }, volumes)// A tenant's image was pinned by the resolver when the box was created. A// curated one keeps its tag on the box — the warm pool matches on it — and@@ -88,7 +87,7 @@ export class BoxStartAction extends BoxAction {const runnerAdapter = await this.runnerAdapterFactory.create(runner)await runnerAdapter.createBox(- box,+ this.withVolumes(box, volumes),image,metadata,await resolveNestedVirtualization(@@ -120,19 +119,61 @@ export class BoxStartAction extends BoxAction {const runnerAdapter = await this.runnerAdapterFactory.create(runner)- const metadata: { [key: string]: string } = { ...organization?.boxMetadata }- if (box.volumes?.length) {- metadata['volumes'] = JSON.stringify(- box.volumes.map((v) => ({ volumeId: v.volumeId, mountPath: v.mountPath, subpath: v.subpath })),- )+ let volumes: Box['volumes']+ try {+ volumes = await this.resolveBoxVolumes(box)+ } catch (error) {+ if (error instanceof ServiceUnavailableException) {+ this.logger.warn(`Filestore resolution for box ${box.id} is temporarily unavailable; restart will be retried`)+ return DONT_SYNC_AGAIN+ }+ throw error}+ const dispatchBox = this.withVolumes(box, volumes)+ const metadata = this.volumeMetadata({ ...organization?.boxMetadata }, volumes)- await runnerAdapter.startBox(box.id, box.authToken, metadata)+ try {+ await runnerAdapter.assertFilestoreVolumeSupport(dispatchBox)+ } catch (error) {+ if ((error as { code?: string })?.code === 'FILESTORE_CAPABILITY_MISSING') {+ this.logger.warn(`Filestore capability for box ${box.id} is not currently available; restart will be retried`)+ return DONT_SYNC_AGAIN+ }+ throw error+ }+ await runnerAdapter.startBox(dispatchBox.id, dispatchBox.authToken, metadata)await this.updateBoxState(box, BoxState.STARTING, lockCode)return SYNC_AGAIN}+ private async resolveBoxVolumes(box: Box): Promise<Box['volumes']> {+ if (!box.volumes?.length) return box.volumes++ return Promise.all(+ box.volumes.map(async (volume) => {+ const dispatch = boxVolumeForDispatch(volume)+ if (!volume.filestore) return dispatch++ const target = await this.filestoreInstanceResolver.resolve(volume.filestore.instance, 'configured')+ return {+ ...dispatch,+ filestore: { instance: volume.filestore.instance, ...target },+ }+ }),+ )+ }++ private withVolumes(box: Box, volumes: Box['volumes']): Box {+ if (!box.volumes?.length) return box+ return Object.assign(Object.create(Object.getPrototypeOf(box)) as Box, box, { volumes })+ }++ private volumeMetadata(metadata: Record<string, string>, volumes: Box['volumes']): Record<string, string> {+ if (!volumes?.length) return metadata+ return { ...metadata, volumes: JSON.stringify(volumes) }+ }+// used to check if box is started on runner and update box state accordingly// also used to handle the case where a box is started on a runner and then transferred to a new runnerprivate async handleRunnerBoxStartedStateCheck(box: Box, lockCode: LockCode): Promise<SyncState> {diff --git a/apps/api/src/box/managers/box-actions/box-start.nested.spec.ts b/apps/api/src/box/managers/box-actions/box-start.nested.spec.tsindex 958a2fd18..3116dea19 100644--- a/apps/api/src/box/managers/box-actions/box-start.nested.spec.ts+++ b/apps/api/src/box/managers/box-actions/box-start.nested.spec.ts@@ -24,13 +24,21 @@ describe('Cloud create-only nesting', () => {const getCode = jest.fn().mockResolvedValue(lock)const action = new BoxStartAction({ findOneOrFail: jest.fn().mockResolvedValue({ id: 'runner', state: RunnerState.READY }) } as any,- { create: jest.fn().mockResolvedValue({ startBox, createBox, runnerInfo }) } as any,+ {+ create: jest.fn().mockResolvedValue({+ startBox,+ createBox,+ runnerInfo,+ assertFilestoreVolumeSupport: jest.fn(async () => undefined),+ }),+ } as any,{ update } as any,{ findOne: jest.fn().mockResolvedValue({ boxMetadata: {} }), isNestedVirtualizationEnabled: policy } as any,{ getOrThrow: () => 0.01 } as any,{ getCode } as any,{} as any,{ refFor: jest.fn().mockResolvedValue('alpine') } as any,+ {} as any,)return { action, box, lock, startBox, createBox, runnerInfo, update, policy, getCode }}diff --git a/apps/api/src/box/managers/box.manager.sync-error.spec.ts b/apps/api/src/box/managers/box.manager.sync-error.spec.tsindex 4a300a0dd..e5a4e0c72 100644--- a/apps/api/src/box/managers/box.manager.sync-error.spec.ts+++ b/apps/api/src/box/managers/box.manager.sync-error.spec.ts@@ -3,6 +3,8 @@* SPDX-License-Identifier: AGPL-3.0*/+import { Logger } from '@nestjs/common'+import { QueryFailedError } from 'typeorm'import { BoxDesiredState } from '../enums/box-desired-state.enum'import { BoxState } from '../enums/box-state.enum'import { BoxManager } from './box.manager'@@ -68,4 +70,27 @@ describe('BoxManager sync errors', () => {}),)})++ it('keeps database query parameters out of the final sync error log', async () => {+ const failure = new QueryFailedError(+ 'INSERT INTO job VALUES (?)',+ ['do-not-log'],+ Object.assign(new Error('insert failed'), { code: '58000' }),+ )+ const { manager } = makeManager(failure)+ const log = jest.spyOn(Logger.prototype, 'error').mockImplementation(() => undefined)++ try {+ await manager.syncInstanceState(BOX.id)+ const syncLog = log.mock.calls.find(+ ([first]) =>+ typeof first === 'object' && first !== null && 'event' in first && first.event === 'box.sync.failed',+ )+ expect(syncLog).toBeDefined()+ expect(JSON.stringify(log.mock.calls)).not.toContain('do-not-log')+ expect(JSON.stringify(log.mock.calls)).not.toContain('INSERT INTO job')+ } finally {+ log.mockRestore()+ }+ })})diff --git a/apps/api/src/box/managers/box.manager.ts b/apps/api/src/box/managers/box.manager.tsindex 0a85649b6..c02ed8563 100755--- a/apps/api/src/box/managers/box.manager.ts+++ b/apps/api/src/box/managers/box.manager.ts@@ -398,9 +398,16 @@ export class BoxManager implements TrackableJobExecutions, OnApplicationShutdownbreak}- this.logger.error(`Error processing desired state for box ${boxId}:`, error)-const { recoverable, errorReason } = sanitizeBoxError(error)+ this.logger.error(+ {+ event: 'box.sync.failed',+ boxId,+ code: (error as { code?: string | number } | null)?.code,+ errorName: error instanceof Error ? error.name : typeof error,+ },+ 'Error processing desired state',+ )const updateData: Partial<Box> = {state: BoxState.ERROR,diff --git a/apps/api/src/box/managers/volume.manager.spec.ts b/apps/api/src/box/managers/volume.manager.spec.tsindex ed42bfddb..8edb6e0a9 100644--- a/apps/api/src/box/managers/volume.manager.spec.ts+++ b/apps/api/src/box/managers/volume.manager.spec.ts@@ -5,6 +5,7 @@*/import { ListObjectsV2Command, S3Client } from '@aws-sdk/client-s3'+import { VolumeState } from '../enums/volume-state.enum'import { VolumeManager } from './volume.manager'const mockSend = jest.fn()@@ -88,3 +89,79 @@ describe('VolumeManager S3 client setup', () => {)})})++describe('VolumeManager pending volume selection', () => {+ it('leaves object-storage rows pending when this instance has no bucket store', async () => {+ const objectStorage = { id: 'object-1', state: VolumeState.PENDING_DELETE }+ const filestore = { id: 'filestore-1', state: VolumeState.PENDING_DELETE, instance: 'ml-scratch' }+ const volumeRepository = { find: jest.fn().mockResolvedValue([objectStorage, filestore]) }+ const configService = { get: jest.fn().mockReturnValue(undefined) }+ const redisLockProvider = {+ lock: jest.fn().mockResolvedValue(true),+ unlock: jest.fn().mockResolvedValue(undefined),+ }+ const manager = new VolumeManager(+ volumeRepository as any,+ configService as any,+ {} as any,+ redisLockProvider as any,+ {} as any,+ )+ const processVolumeState = jest.spyOn(manager as any, 'processVolumeState').mockResolvedValue(undefined)++ await manager.processPendingVolumes()++ expect(processVolumeState).toHaveBeenCalledTimes(1)+ expect(processVolumeState).toHaveBeenCalledWith(filestore)+ })+})++describe('VolumeManager filestore volume deletion', () => {+ function buildManagerForDeletion() {+ const configService = {+ get: jest.fn(() => undefined),+ getOrThrow: jest.fn(() => {+ throw new Error('Missing config')+ }),+ }+ const volumeRepository = {+ save: jest.fn().mockImplementation(async (v) => v),+ delete: jest.fn().mockResolvedValue({}),+ }+ const redis = { setex: jest.fn().mockResolvedValue(1) }+ return {+ manager: new VolumeManager(volumeRepository as any, configService as any, redis as any, {} as any, {} as any),+ volumeRepository,+ }+ }++ it('lands a filestore volume DELETED without any bucket operation', async () => {+ // No storage backend is configured at all (bucketStore is null): the+ // filestore branch must not need one, and the DELETED landing is the same+ // tombstone + rename the bucket path uses.+ const { manager, volumeRepository } = buildManagerForDeletion()+ const volume = {+ id: 'volume-1',+ organizationId: 'org-1',+ name: 'nfs-data',+ state: VolumeState.PENDING_DELETE,+ instance: 'ml-scratch',+ } as any++ await (manager as any).handlePendingDelete(volume, 'lock-key')++ expect(volumeRepository.save).toHaveBeenNthCalledWith(+ 2,+ expect.objectContaining({+ id: 'volume-1',+ state: VolumeState.DELETED,+ name: 'nfs-data-deleted',+ }),+ )+ expect(volumeRepository.delete).toHaveBeenCalledWith({+ organizationId: 'org-1',+ name: 'nfs-data-deleted',+ state: VolumeState.DELETED,+ })+ })+})diff --git a/apps/api/src/box/managers/volume.manager.ts b/apps/api/src/box/managers/volume.manager.tsindex 54a71d224..143446923 100644--- a/apps/api/src/box/managers/volume.manager.ts+++ b/apps/api/src/box/managers/volume.manager.ts@@ -7,7 +7,7 @@import { Injectable, Logger, OnApplicationBootstrap, OnApplicationShutdown, OnModuleInit } from '@nestjs/common'import { InjectRepository } from '@nestjs/typeorm'import { Repository, In } from 'typeorm'-import { Volume } from '../entities/volume.entity'+import { isFilestoreVolume, Volume } from '../entities/volume.entity'import { VolumeState } from '../enums/volume-state.enum'import { Cron, CronExpression, SchedulerRegistry } from '@nestjs/schedule'import { InjectRedis } from '@nestjs-modules/ioredis'@@ -61,10 +61,9 @@ export class VolumeManager}onApplicationBootstrap() {- if (!this.bucketStore) {- return- }-+ // The cron runs even without a bucket store: filestore volumes ride the+ // same state machine and have no object storage to connect to, so an API+ // serving filestore-only orgs must still process their pending states.this.schedulerRegistry.getCronJob('process-pending-volumes').start()}@@ -91,10 +90,6 @@ export class VolumeManager@LogExecution('process-pending-volumes')@WithInstrumentation()async processPendingVolumes() {- if (!this.bucketStore) {- return- }-try {// Lock the entire processconst lockKey = 'process-pending-volumes'@@ -102,11 +97,13 @@ export class VolumeManagerreturn}- const pendingVolumes = await this.volumeRepository.find({- where: {- state: In([VolumeState.PENDING_CREATE, VolumeState.PENDING_DELETE]),- },- })+ const pendingVolumes = (+ await this.volumeRepository.find({+ where: {+ state: In([VolumeState.PENDING_CREATE, VolumeState.PENDING_DELETE]),+ },+ })+ ).filter((volume) => this.bucketStore !== null || isFilestoreVolume(volume))await Promise.all(pendingVolumes.map(async (volume) => {@@ -211,14 +208,22 @@ export class VolumeManager// Refresh lock before the object-store operationawait this.redis.setex(lockKey, 30, '1')- // A bucket that is already gone is absorbed by the store as success.- try {- await this.bucketStore.destroy(volume.getBucketName())- } catch (error) {- if (error instanceof VolumeBucketNotEmptyError) {- throw new Error('Volume deletion failed because the bucket is not empty. You may retry deletion.')+ // TODO: real deletion dispatches a runner-side delete — the NFS data+ // directory is only reachable on runner hosts. Until that lands, a+ // filestore volume has no storage operation here: the data directory is+ // left in place for ops cleanup, and only the row lands DELETED below.+ // The landing is shared with the bucket path, including the+ // `name-deleted` rename that frees the name for reuse.+ if (!isFilestoreVolume(volume)) {+ // A bucket that is already gone is absorbed by the store as success.+ try {+ await this.bucketStore.destroy(volume.getBucketName())+ } catch (error) {+ if (error instanceof VolumeBucketNotEmptyError) {+ throw new Error('Volume deletion failed because the bucket is not empty. You may retry deletion.')+ }+ throw error}- throw error}// Refresh lock before final state updatediff --git a/apps/api/src/box/runner-adapter/runnerAdapter.ts b/apps/api/src/box/runner-adapter/runnerAdapter.tsindex dbbbb4096..600ae3db3 100644--- a/apps/api/src/box/runner-adapter/runnerAdapter.ts+++ b/apps/api/src/box/runner-adapter/runnerAdapter.ts@@ -50,6 +50,7 @@ export interface RunnerAdapter {runnerInfo(signal?: AbortSignal): Promise<RunnerInfo>boxInfo(boxId: string): Promise<RunnerBoxInfo>+ assertFilestoreVolumeSupport(box: Box): Promise<void>/** `image` is the ref the runner pulls, which may be pinned tighter than `box.image`. */createBox(box: Box,diff --git a/apps/api/src/box/runner-adapter/runnerAdapter.v0.spec.ts b/apps/api/src/box/runner-adapter/runnerAdapter.v0.spec.tsindex 2c85a50f0..60a928324 100644--- a/apps/api/src/box/runner-adapter/runnerAdapter.v0.spec.ts+++ b/apps/api/src/box/runner-adapter/runnerAdapter.v0.spec.ts@@ -215,3 +215,33 @@ describe('RunnerAdapterV0 updateNetworkSettings', () => {expect(body).not.toHaveProperty('networkAllowList')})})++describe('RunnerAdapterV0 filestore guard', () => {+ const filestoreBox = {+ id: 'box-fs',+ image: 'base',+ volumes: [+ {+ volumeId: 'volume-1',+ mountPath: '/data',+ filestore: { instance: 'ml-scratch', server: '10.0.0.7', export: '/vol1' },+ },+ ],+ } as any++ // Failing loudly is the point: stripping the reference would create a box+ // whose volume silently never mounts on a v0 runner.+ it('refuses createBox for a box referencing a Filestore volume', async () => {+ const adapter = new RunnerAdapterV0()+ await adapter.init({ id: 'runner-1', apiUrl: 'http://runner.invalid', supportsPrivileged: true } as any)++ await expect(adapter.createBox(filestoreBox, 'base')).rejects.toThrow(/requires a v2 runner/)+ })++ it('refuses recoverBox for a box referencing a Filestore volume', async () => {+ const adapter = new RunnerAdapterV0()+ await adapter.init({ id: 'runner-1', apiUrl: 'http://runner.invalid', supportsPrivileged: true } as any)++ await expect(adapter.recoverBox(filestoreBox)).rejects.toThrow(/requires a v2 runner/)+ })+})diff --git a/apps/api/src/box/runner-adapter/runnerAdapter.v0.ts b/apps/api/src/box/runner-adapter/runnerAdapter.v0.tsindex 7cecfc05d..15d31eae1 100644--- a/apps/api/src/box/runner-adapter/runnerAdapter.v0.ts+++ b/apps/api/src/box/runner-adapter/runnerAdapter.v0.ts@@ -266,6 +266,21 @@ export class RunnerAdapterV0 implements RunnerAdapter {}}+ async assertFilestoreVolumeSupport(box: Box): Promise<void> {+ this.assertNoFilestoreVolumes(box)+ }++ // A filestore volume needs the runner-side NFS mount support that only the+ // v2 runner protocol carries. Failing loudly here is the point: stripping+ // the reference would create a box whose volume silently never mounts.+ private assertNoFilestoreVolumes(box: Box): void {+ if (box.volumes?.some((volume) => volume.filestore)) {+ throw new Error(+ `Box ${box.id} references a Filestore volume, which requires a v2 runner; runner ${this.runner.id} only speaks the v0 protocol`,+ )+ }+ }+async createBox(box: Box,image: string,@@ -273,6 +288,7 @@ export class RunnerAdapterV0 implements RunnerAdapter {nestedVirtualization = false,): Promise<StartBoxResponse | undefined> {this.rejectSecretReferences(box)+ this.assertNoFilestoreVolumes(box)if (box.privileged && !this.runner.supportsPrivileged) {throw new Error(`Runner ${this.runner.id} does not support privileged Boxes`)}@@ -356,6 +372,7 @@ export class RunnerAdapterV0 implements RunnerAdapter {async recoverBox(box: Box): Promise<void> {this.rejectSecretReferences(box)+ this.assertNoFilestoreVolumes(box)if (box.privileged && !this.runner.supportsPrivileged) {throw new Error(`Runner ${this.runner.id} does not support privileged Boxes`)}diff --git a/apps/api/src/box/runner-adapter/runnerAdapter.v2.spec.ts b/apps/api/src/box/runner-adapter/runnerAdapter.v2.spec.tsindex ed9e4362f..78c9443ff 100644--- a/apps/api/src/box/runner-adapter/runnerAdapter.v2.spec.ts+++ b/apps/api/src/box/runner-adapter/runnerAdapter.v2.spec.ts@@ -4,7 +4,10 @@*/import { JobType } from '../enums/job-type.enum'+import { BoxState } from '../enums/box-state.enum'import { ResourceType } from '../enums/resource-type.enum'+import { BoxStateWaiterService } from '../services/box-state-waiter.service'+import { sanitizeBoxError } from '../utils/sanitize-error.util'import { RunnerAdapterV2 } from './runnerAdapter.v2'describe('RunnerAdapterV2 createBox', () => {@@ -55,6 +58,168 @@ describe('RunnerAdapterV2 createBox', () => {expect(jobService.createJob).not.toHaveBeenCalled()})+ it.each([undefined, [], ['gpu-passthrough']])(+ 'rejects a filestore volume create when the runner declared capabilities %p',+ async (capabilities) => {+ const jobService = { createJob: jest.fn().mockResolvedValue(undefined) } as any+ const adapter = new RunnerAdapterV2({} as any, {} as any, jobService)+ Object.assign(adapter as any, { config: { get: () => false },+ runnerRepository: { findOne: jest.fn().mockResolvedValue({ id: 'runner-1', capabilities }) },+ })+ await adapter.init({ id: 'runner-1', capabilities } as any)++ await expect(+ adapter.createBox(+ {+ id: 'box-1',+ volumes: [+ {+ volumeId: 'vol-1',+ mountPath: '/data',+ filestore: { instance: 'ml-scratch', server: '10.0.0.7', export: '/vol1' },+ },+ ],+ } as any,+ 'base',+ ),+ ).rejects.toThrow('requires a runner with the filestore capability')+ expect(jobService.createJob).not.toHaveBeenCalled()+ },+ )++ it('uses the latest persisted capability instead of a stale scheduling snapshot', async () => {+ const jobService = { createJob: jest.fn().mockResolvedValue(undefined) } as any+ const runnerRepository = {+ findOne: jest.fn().mockResolvedValue({ id: 'runner-1', capabilities: ['filestore'] }),+ }+ const adapter = new RunnerAdapterV2({} as any, {} as any, jobService)+ Object.assign(adapter as any, { config: { get: () => false }, runnerRepository })+ await adapter.init({ id: 'runner-1', capabilities: null } as any)++ await adapter.createBox(+ {+ id: 'box-1',+ volumes: [+ {+ volumeId: 'vol-1',+ mountPath: '/data',+ filestore: { instance: 'ml-scratch', server: '10.0.0.7', export: '/vol1' },+ },+ ],+ } as any,+ 'base',+ )++ expect(runnerRepository.findOne).toHaveBeenCalledWith({ where: { id: 'runner-1' }, cache: false })+ expect(jobService.createJob).toHaveBeenCalled()+ })++ it('returns capability diagnostics through the new-Box error response', async () => {+ const lastChecked = new Date('2026-11-14T02:00:00Z')+ const jobService = { createJob: jest.fn().mockResolvedValue(undefined) } as any+ const adapter = new RunnerAdapterV2({} as any, {} as any, jobService)+ Object.assign(adapter as any, { config: { get: () => false },+ runnerRepository: {+ findOne: jest.fn().mockResolvedValue({+ id: 'runner-1',+ state: 'ready',+ apiVersion: '2',+ appVersion: '0.13.1+abc123',+ capabilities: ['gpu-passthrough'],+ lastChecked,+ }),+ },+ })+ await adapter.init({ id: 'runner-1', capabilities: null } as any)++ const failure = await adapter+ .createBox(+ {+ id: 'box-1',+ volumes: [+ {+ volumeId: 'vol-1',+ mountPath: '/data',+ filestore: { instance: 'ml-scratch', server: '10.0.0.7', export: '/vol1' },+ },+ ],+ } as any,+ 'base',+ )+ .catch((error) => error)+ const { errorReason } = sanitizeBoxError(failure)+ const subscriber = { on: jest.fn(), subscribe: jest.fn().mockResolvedValue(undefined) }+ const waiter = new BoxStateWaiterService(+ {+ findOneByIdOrName: jest.fn().mockResolvedValue({+ id: 'box-1',+ state: BoxState.ERROR,+ errorReason,+ }),+ } as any,+ { duplicate: jest.fn(() => subscriber) } as any,+ )++ const response = await waiter.waitForStarted('box-1', 'org-1', 1).catch((error) => error)+ const body = response.getResponse()+ expect(body).toMatchObject({ boxId: 'box-1', code: 'BOX_STATE_TRANSITION_FAILED' })+ for (const detail of [+ 'runnerRecordFound=true',+ 'runnerState=ready',+ 'apiVersion=2',+ 'appVersion=0.13.1+abc123',+ 'capabilities=["gpu-passthrough"]',+ 'volumeIds=["vol-1"]',+ 'filestoreInstances=["ml-scratch"]',+ `lastChecked=${lastChecked.toISOString()}`,+ 'lastHealthcheckAgeSeconds=',+ 'No Box job was dispatched',+ 'FILESTORE_CAPABILITY_MISSING',+ ]) {+ expect(body.message).toContain(detail)+ }+ expect(jobService.createJob).not.toHaveBeenCalled()+ })++ it('dispatches a filestore volume when the runner declared the capability', async () => {+ const jobService = { createJob: jest.fn().mockResolvedValue(undefined) } as any+ const adapter = new RunnerAdapterV2({} as any, {} as any, jobService)+ Object.assign(adapter as any, { config: { get: () => false },+ runnerRepository: { findOne: jest.fn().mockResolvedValue({ id: 'runner-1', capabilities: ['filestore'] }) },+ })+ await adapter.init({ id: 'runner-1', capabilities: ['filestore'] } as any)++ await adapter.createBox(+ {+ id: 'box-1',+ volumes: [+ {+ volumeId: 'vol-1',+ mountPath: '/data',+ filestore: { instance: 'ml-scratch', server: '10.0.0.7', export: '/vol1' },+ },+ ],+ } as any,+ 'base',+ )++ expect(jobService.createJob).toHaveBeenCalledWith(+ null,+ JobType.CREATE_BOX,+ 'runner-1',+ ResourceType.BOX,+ 'box-1',+ expect.objectContaining({+ volumes: [+ expect.objectContaining({+ volumeId: 'vol-1',+ filestore: { instance: 'ml-scratch', server: '10.0.0.7', export: '/vol1' },+ }),+ ],+ }),+ )+ })+it('passes secrets through to the CREATE_BOX job payload', async () => {const jobService = { createJob: jest.fn().mockResolvedValue(undefined) } as anyconst adapter = new RunnerAdapterV2({} as any, {} as any, jobService)diff --git a/apps/api/src/box/runner-adapter/runnerAdapter.v2.ts b/apps/api/src/box/runner-adapter/runnerAdapter.v2.tsindex 6d1fc574e..b3a6b10f6 100644--- a/apps/api/src/box/runner-adapter/runnerAdapter.v2.ts+++ b/apps/api/src/box/runner-adapter/runnerAdapter.v2.ts@@ -21,6 +21,7 @@ import { ResourceType } from '../enums/resource-type.enum'import { JobService } from '../services/job.service'import { BoxRepository } from '../repositories/box.repository'import { RunnerState } from '../enums/runner-state.enum'+import { boxVolumeForDispatch } from '../utils/box-volume.util'/*** RunnerAdapterV2 implements RunnerAdapter for v2 runners.@@ -109,6 +110,65 @@ export class RunnerAdapterV2 implements RunnerAdapter {}}+ // A filestore volume needs runner-side NFS mount support. apiVersion 2 alone+ // does not imply it: v2 predates filestore, so an un-upgraded v2 runner+ // drops the filestore reference and mounts a bucket that does not exist.+ // The runner declares the capability in its healthcheck; refusing here —+ // instead of dispatching — keeps the failure at the API with the real+ // cause instead of a misleading bucket error on the runner.+ async assertFilestoreVolumeSupport(box: Box): Promise<void> {+ if (!box.volumes?.some((volume) => volume.filestore)) return++ // Runner lookup caching is local to an API replica. Read the declaration+ // again so a heartbeat received by another replica cannot leave this one+ // rejecting a capable runner from an hour-old snapshot.+ const runner = await this.runnerRepository.findOne({ where: { id: this.runner.id }, cache: false })+ if (runner?.capabilities?.includes('filestore')) return++ const filestoreVolumes = box.volumes?.filter((volume) => volume.filestore) ?? []+ const lastChecked = runner?.lastChecked+ const lastHealthcheckAgeSeconds = lastChecked+ ? Math.max(0, Math.floor((Date.now() - lastChecked.getTime()) / 1000))+ : undefined+ const diagnostics = [+ `runnerRecordFound=${runner !== null}`,+ `runnerState=${runner?.state ?? 'unknown'}`,+ `apiVersion=${runner?.apiVersion ?? 'unknown'}`,+ `appVersion=${runner?.appVersion ?? 'unknown'}`,+ `capabilities=${JSON.stringify(runner?.capabilities ?? [])}`,+ `volumeIds=${JSON.stringify(filestoreVolumes.map((volume) => volume.volumeId))}`,+ `filestoreInstances=${JSON.stringify(filestoreVolumes.map((volume) => volume.filestore?.instance ?? 'unknown'))}`,+ `lastChecked=${lastChecked?.toISOString() ?? 'never'}`,+ ...(lastHealthcheckAgeSeconds === undefined ? [] : [`lastHealthcheckAgeSeconds=${lastHealthcheckAgeSeconds}`]),+ ].join('; ')+ const error = Object.assign(+ new Error(+ `FILESTORE_CAPABILITY_MISSING: Box ${box.id} requires a runner with the filestore capability, but runner ${this.runner.id} has not declared it (${diagnostics}). No Box job was dispatched. If the healthcheck is recent, inspect why the running binary omitted filestore; otherwise inspect healthcheck delivery to the API.`,+ ),+ { code: 'FILESTORE_CAPABILITY_MISSING' },+ )+ this.logger.error(+ {+ event: 'box.dispatch_rejected',+ boxId: box.id,+ runnerId: this.runner.id,+ runnerRecordFound: runner !== null,+ runnerState: runner?.state,+ runnerApiVersion: runner?.apiVersion,+ runnerAppVersion: runner?.appVersion,+ runnerCapabilities: runner?.capabilities ?? [],+ volumeIds: filestoreVolumes.map((volume) => volume.volumeId),+ filestoreInstances: filestoreVolumes.map((volume) => volume.filestore?.instance ?? 'unknown'),+ runnerLastChecked: lastChecked,+ lastHealthcheckAgeSeconds,+ code: error.code,+ err: error,+ },+ 'Filestore Box dispatch rejected',+ )+ throw error+ }+async createBox(box: Box,image: string,@@ -130,6 +190,8 @@ export class RunnerAdapterV2 implements RunnerAdapter {if (enabled && secrets.some((secret) => !secret.secretId)) {throw new Error('Secret Server requires secret references; migrate inline secrets before enabling')}++ await this.assertFilestoreVolumeSupport(box)const payload = {id: box.id,...(nestedVirtualization ? { nestedVirtualization: true } : {}),@@ -145,11 +207,7 @@ export class RunnerAdapterV2 implements RunnerAdapter {workingDir: box.workingDir,entrypoint: box.entrypoint,cmd: box.cmd,- volumes: box.volumes?.map((volume) => ({- volumeId: volume.volumeId,- mountPath: volume.mountPath,- subpath: volume.subpath,- })),+ volumes: box.volumes?.map(boxVolumeForDispatch),secrets: box.secrets?.map((secret) => ({name: secret.name,...(!enabled ? { value: secret.value } : {}),diff --git a/apps/api/src/box/services/box-state-waiter.service.spec.ts b/apps/api/src/box/services/box-state-waiter.service.spec.tsindex bd5127a8f..2787918fe 100644--- a/apps/api/src/box/services/box-state-waiter.service.spec.ts+++ b/apps/api/src/box/services/box-state-waiter.service.spec.ts@@ -38,6 +38,23 @@ describe('BoxStateWaiterService', () => {])})+ it('returns the failed Box identity and a stable error code', async () => {+ const { waiter } = makeWaiter(BoxState.ERROR)+ ;(waiter as any).boxService.findOneByIdOrName.mockResolvedValue({+ id: 'box-1',+ state: BoxState.ERROR,+ errorReason: 'runner has not declared filestore',+ })++ const error = await waiter.waitForStarted('box-1', 'org-1', 1).catch((failure) => failure)++ expect(error.getResponse()).toMatchObject({+ message: 'Box state transition failed: runner has not declared filestore',+ code: 'BOX_STATE_TRANSITION_FAILED',+ boxId: 'box-1',+ })+ })+it('rejects instead of returning a non-target state on timeout', async () => {jest.useFakeTimers()const { waiter } = makeWaiter()diff --git a/apps/api/src/box/services/box-state-waiter.service.ts b/apps/api/src/box/services/box-state-waiter.service.tsindex 132dfc068..2d281fcef 100644--- a/apps/api/src/box/services/box-state-waiter.service.ts+++ b/apps/api/src/box/services/box-state-waiter.service.ts@@ -5,9 +5,8 @@*/import { InjectRedis } from '@nestjs-modules/ioredis'-import { Injectable, Logger, OnModuleDestroy, RequestTimeoutException } from '@nestjs/common'+import { BadRequestException, Injectable, Logger, OnModuleDestroy, RequestTimeoutException } from '@nestjs/common'import Redis from 'ioredis'-import { BadRequestError } from '../../exceptions/bad-request.exception'import { BOX_EVENT_CHANNEL } from '../../common/constants/constants'import { BoxDto } from '../dto/box.dto'import { BoxPreparingImageTimeoutError } from '../errors/box-preparing-image-timeout.error'@@ -70,7 +69,7 @@ export class BoxStateWaiterService implements OnModuleDestroy {const current = await this.boxService.findOneByIdOrName(boxId, organizationId)if (current.state === targetState) return this.boxService.toBoxDto(current)await this.ensureSubscribed()- this.assertNotFailed(current.state, current.errorReason)+ this.assertNotFailed(current.id, current.state, current.errorReason)return new Promise<BoxDto>((resolve, reject) => {let finished = false@@ -104,7 +103,7 @@ export class BoxStateWaiterService implements OnModuleDestroy {return}try {- this.assertNotFailed(event.box.state, event.box.errorReason)+ this.assertNotFailed(event.box.id, event.box.state, event.box.errorReason)} catch (error) {fail(error)}@@ -120,7 +119,7 @@ export class BoxStateWaiterService implements OnModuleDestroy {.findOneByIdOrName(boxId, organizationId).then((box) => {if (box.state === targetState) return finish(box)- this.assertNotFailed(box.state, box.errorReason)+ this.assertNotFailed(box.id, box.state, box.errorReason)}).catch(fail)@@ -166,12 +165,16 @@ export class BoxStateWaiterService implements OnModuleDestroy {return new RequestTimeoutException({ message, boxId })}- private assertNotFailed(state: BoxState, errorReason?: string | null) {+ private assertNotFailed(boxId: string, state: BoxState, errorReason?: string | null) {if (state === BoxState.ERROR) {- throw new BadRequestError(`Box state transition failed: ${errorReason || 'Unknown error'}`)+ throw new BadRequestException({+ message: `Box state transition failed: ${errorReason || 'Unknown error'}`,+ code: 'BOX_STATE_TRANSITION_FAILED',+ boxId,+ })}if (state === BoxState.DESTROYED || state === BoxState.DESTROYING) {- throw new BadRequestError('Box has been destroyed and cannot be resumed')+ throw new BadRequestException('Box has been destroyed and cannot be resumed')}}}diff --git a/apps/api/src/box/services/box.service.filestore-delete.spec.ts b/apps/api/src/box/services/box.service.filestore-delete.spec.tsnew file mode 100644index 000000000..83d1c4b5d--- /dev/null+++ b/apps/api/src/box/services/box.service.filestore-delete.spec.ts@@ -0,0 +1,73 @@+/*+ * Copyright 2026 BoxLite AI+ * SPDX-License-Identifier: AGPL-3.0+ */++import { BoxService } from './box.service'+import { BoxState } from '../enums/box-state.enum'+import { BoxDesiredState } from '../enums/box-desired-state.enum'+import { BoxEvents } from '../constants/box-events.constants'+import { Context } from '../../common/context/context'++jest.mock('../utils/box-business-event.util', () => ({ recordBoxRequested: jest.fn() }))++function makeDestroyService(box: any) {+ const updatedBox = { ...box, desiredState: BoxDesiredState.DESTROYED }+ const boxRepository = {+ findWithCheckpointState: jest.fn().mockResolvedValue({ box, checkpointState: null }),+ updateWhere: jest.fn().mockResolvedValue(updatedBox),+ }+ const eventEmitter = { emit: jest.fn() }+ const service = Object.create(BoxService.prototype) as BoxService+ Object.assign(service as any, {+ findOneByIdOrName: jest.fn().mockResolvedValue(box),+ boxRepository,+ eventEmitter,+ })+ return { service, boxRepository, eventEmitter, updatedBox }+}++const waitingRestart = {+ id: 'box-1',+ name: 'box-1',+ organizationId: 'org-1',+ state: BoxState.STOPPED,+ desiredState: BoxDesiredState.STARTED,+ pending: true,+}++describe('BoxService Filestore restart deletion', () => {+ it('deletes a stopped Filestore Box without resolving its missing instance', async () => {+ const filestoreInstanceResolver = { resolve: jest.fn() }+ const { service, boxRepository, eventEmitter, updatedBox } = makeDestroyService({+ ...waitingRestart,+ volumes: [+ {+ volumeId: 'volume-1',+ mountPath: '/data',+ filestore: { instance: 'removed-instance', server: '10.0.0.7', export: '/vol1' },+ },+ ],+ })+ Object.assign(service as any, { filestoreInstanceResolver })++ await expect(service.destroy('box-1', 'org-1', Context.user())).resolves.toBe(updatedBox)+ expect(boxRepository.updateWhere).toHaveBeenCalledWith('box-1', {+ updateData: expect.objectContaining({ desiredState: BoxDesiredState.DESTROYED, pending: true }),+ whereCondition: { pending: true, state: BoxState.STOPPED },+ })+ expect(eventEmitter.emit).toHaveBeenCalledWith(BoxEvents.DESTROYED, expect.anything())+ expect(filestoreInstanceResolver.resolve).not.toHaveBeenCalled()+ })++ it('keeps rejecting other pending restarts', async () => {+ const { service, boxRepository, eventEmitter } = makeDestroyService({+ ...waitingRestart,+ volumes: [{ volumeId: 'volume-1', mountPath: '/data' }],+ })++ await expect(service.destroy('box-1', 'org-1', Context.user())).rejects.toThrow('Box state change in progress')+ expect(boxRepository.updateWhere).not.toHaveBeenCalled()+ expect(eventEmitter.emit).not.toHaveBeenCalled()+ })+})diff --git a/apps/api/src/box/services/box.service.spec.ts b/apps/api/src/box/services/box.service.spec.tsindex f466bd0e0..bec3839f3 100644--- a/apps/api/src/box/services/box.service.spec.ts+++ b/apps/api/src/box/services/box.service.spec.ts@@ -25,6 +25,8 @@ import { OrganizationService } from '../../organization/services/organization.seimport { SecretServerClient } from './secret-server-client'import { createServer } from 'node:http'import { AddressInfo } from 'node:net'+import { Volume } from '../entities/volume.entity'+import { VolumeState } from '../enums/volume-state.enum'const disabledSecretServer = () => new SecretServerClient({ get: () => false } as any)@@ -37,6 +39,7 @@ function makeService() {const boxRepository = {findOneByIdOrName: jest.fn(),conditionalStartForProxy: jest.fn(),+ insert: jest.fn(),} as anyconst eventEmitter = { emit: jest.fn(), emitAsync: jest.fn() } as any// assertOrganizationIsNotSuspended mirrors the real implementation: throw@@ -73,6 +76,7 @@ function makeService() {passThroughPullFailures(), // imagePullFailureService{} as any, // organizationBoxLimits (unused by these lifecycle tests)disabledSecretServer(),+ noop,)return { service, boxRepository, eventEmitter, organizationService }}@@ -214,6 +218,7 @@ function makeNetworkTunnelService() {passThroughPullFailures(), // imagePullFailureService{} as any, // organizationBoxLimits (unused by these lifecycle tests)disabledSecretServer(),+ noop,)jest.spyOn(service, 'findOneByIdOrName').mockResolvedValue({id: 'MixedCaseBox',@@ -403,6 +408,17 @@ describe('BoxService inbound defaults', () => {resolve: jest.fn().mockResolvedValue({ ref: 'quay.io/acme/app@sha256:resolved', isOrgOwned: true }),},secretServerClient: disabledSecretServer(),+ configService: {+ getOrThrow: jest.fn((key: string) => {+ if (key === 'volume.filestoreInstances') {+ return { instances: [{ instance: 'ml-scratch', projectId: 'boxlite-dev', zone: 'asia-southeast1-b' }] }+ }+ throw new Error(`unexpected config key ${key}`)+ }),+ },+ filestoreInstanceResolver: {+ resolve: jest.fn().mockResolvedValue({ server: '10.0.0.7', export: '/vol1' }),+ },...overrides,})return { service, boxRepository, runnerService, warmPoolService }@@ -718,6 +734,32 @@ describe('BoxService inbound defaults', () => {)})+ it('persists the resolved volume id when a ready volume is selected by name', async () => {+ const volume = Object.assign(new Volume(), {+ id: '09f81aef-69a3-488b-b872-e193831549f3',+ name: 'shared-data',+ state: VolumeState.READY,+ })+ const validateVolumes = jest.fn().mockResolvedValue(new Map([['shared-data', volume]]))+ const { service, boxRepository } = makeCreateService({ volumeService: { validateVolumes } })++ await service.create(+ {+ name: 'volume-box',+ image: 'quay.io/acme/app:v1',+ volumes: [{ volumeId: 'shared-data', mountPath: '/data' }],+ } as any,+ { id: 'org-1' } as any,+ Context.user(),+ )++ expect(validateVolumes).toHaveBeenCalledWith('org-1', ['shared-data'])+ expect(boxRepository.insert).toHaveBeenCalledWith(+ expect.objectContaining({ volumes: [{ volumeId: volume.id, mountPath: '/data' }] }),+ undefined,+ )+ })+/*** The one path every existing caller takes, and the only one asserted through* the real resolver: a mocked one would make this a test of the mock. The@@ -1426,3 +1468,139 @@ describe('BoxService runner assignment', () => {expect(boxRepository.insert).not.toHaveBeenCalled()})})++// A box's persisted volume entry must carry the resolved entity id — and,+// for a filestore volume, the entity's instance, which is what the runner's+// mount dispatch (create now, start-after-reboot metadata later) hands over.+// Persisting the caller's selector or dropping the instance would leave the+// runner unable to mount the volume.+describe('BoxService volume reference resolution', () => {+ function makeService(overrides: Record<string, unknown> = {}) {+ const boxRepository = { insert: jest.fn(async (box: any) => box) } as any+ const service = Object.create(BoxService.prototype) as BoxService+ Object.assign(service as any, {+ getValidatedOrDefaultRegion: jest.fn().mockResolvedValue({ id: 'region-1' }),+ getValidatedOrDefaultClass: jest.fn().mockReturnValue('small'),+ organizationService: {+ assertOrganizationIsNotSuspended: jest.fn(),+ isNestedVirtualizationEnabled: jest.fn().mockResolvedValue(false),+ },+ organizationBoxLimits: { resolve: jest.fn(async (organization) => organization) },+ redis: { exists: jest.fn().mockResolvedValue(1) },+ logger: { log: jest.fn(), warn: jest.fn(), error: jest.fn(), debug: jest.fn() },+ warmPoolService: { fetchWarmPoolBox: jest.fn().mockResolvedValue(undefined) },+ runnerService: {+ getRandomAvailableRunner: jest+ .fn()+ .mockResolvedValue({ id: 'runner-1', draining: false, state: RunnerState.READY }),+ },+ boxRepository,+ eventEmitter: { emitAsync: jest.fn().mockResolvedValue(undefined) },+ toBoxDto: jest.fn((box) => box),+ imageAdmissionService: {+ assert: jest.fn().mockResolvedValue(undefined),+ spendColdPullBudget: jest.fn().mockResolvedValue(undefined),+ },+ imageResolverService: {+ resolve: jest.fn().mockResolvedValue({ ref: 'quay.io/acme/app@sha256:resolved', isOrgOwned: true }),+ },+ secretServerClient: disabledSecretServer(),+ configService: {+ getOrThrow: jest.fn((key: string) => {+ if (key === 'volume.filestoreInstances') {+ return { instances: [{ instance: 'ml-scratch', projectId: 'boxlite-dev', zone: 'asia-southeast1-b' }] }+ }+ throw new Error(`unexpected config key ${key}`)+ }),+ },+ filestoreInstanceResolver: {+ resolve: jest.fn().mockResolvedValue({ server: '10.0.0.7', export: '/vol1' }),+ },+ ...overrides,+ })+ return { service, boxRepository }+ }++ it('stamps the resolved id and the filestore instance into the persisted volume entry', async () => {+ const { service, boxRepository } = makeService({+ volumeService: {+ validateVolumes: jest+ .fn()+ .mockResolvedValue(new Map([['my-data', { id: 'vol-uuid-1', instance: 'ml-scratch' }]])),+ },+ })++ await service.create(+ {+ name: 'nfs-box',+ image: 'quay.io/acme/app:v1',+ volumes: [{ volumeId: 'my-data', mountPath: '/data' }],+ } as any,+ { id: 'org-1' } as any,+ Context.user(),+ )++ expect(boxRepository.insert.mock.calls[0][0]).toEqual(+ expect.objectContaining({+ volumes: [+ {+ volumeId: 'vol-uuid-1',+ mountPath: '/data',+ filestore: { instance: 'ml-scratch', server: '10.0.0.7', export: '/vol1' },+ },+ ],+ }),+ )+ })++ it('fails the dispatch loudly when the instance left the configuration after the volume was created', async () => {+ const { service, boxRepository } = makeService({+ volumeService: {+ validateVolumes: jest+ .fn()+ .mockResolvedValue(new Map([['my-data', { id: 'vol-uuid-1', instance: 'ml-scratch' }]])),+ },+ filestoreInstanceResolver: {+ resolve: jest.fn().mockRejectedValue(new BadRequestError("unknown Filestore instance 'ml-scratch'")),+ },+ })++ await expect(+ service.create(+ {+ name: 'nfs-box',+ image: 'quay.io/acme/app:v1',+ volumes: [{ volumeId: 'my-data', mountPath: '/data' }],+ } as any,+ { id: 'org-1' } as any,+ Context.user(),+ ),+ ).rejects.toThrow("unknown Filestore instance 'ml-scratch'")+ // A failed dispatch must not leave a persisted box row behind.+ expect(boxRepository.insert).not.toHaveBeenCalled()+ })++ it('keeps a bucket-backed volume entry free of any filestore key', async () => {+ const { service, boxRepository } = makeService({+ volumeService: {+ validateVolumes: jest.fn().mockResolvedValue(new Map([['my-data', { id: 'vol-uuid-2', instance: undefined }]])),+ },+ })++ await service.create(+ {+ name: 'bucket-box',+ image: 'quay.io/acme/app:v1',+ volumes: [{ volumeId: 'my-data', mountPath: '/data' }],+ } as any,+ { id: 'org-1' } as any,+ Context.user(),+ )++ expect(boxRepository.insert.mock.calls[0][0]).toEqual(+ expect.objectContaining({+ volumes: [{ volumeId: 'vol-uuid-2', mountPath: '/data' }],+ }),+ )+ })+})diff --git a/apps/api/src/box/services/box.service.ts b/apps/api/src/box/services/box.service.tsindex e4a07dfe5..9b697e77b 100644--- a/apps/api/src/box/services/box.service.ts+++ b/apps/api/src/box/services/box.service.ts@@ -25,6 +25,8 @@ import { reportedBoxState } from '../utils/box-state.util'import { Box } from '../entities/box.entity'import { persistWithGeneratedBoxName } from '../utils/box-name-generator'import { boxImageIsOrgOwned } from '../utils/image-ownership.util'+import { boxVolumeForDispatch } from '../utils/box-volume.util'+import { isFilestoreVolume } from '../entities/volume.entity'import { CreateBoxDto } from '../dto/create-box.dto'import { BoxState } from '../enums/box-state.enum'import { BoxClass } from '../enums/box-class.enum'@@ -68,6 +70,7 @@ import {import { NetworkMode } from '../enums/network-mode.enum'import { networkMode } from '../utils/network-policy.util'import { VolumeService } from './volume.service'+import { FilestoreInstanceResolver } from './filestore-instance.resolver'import { PaginatedList } from '../../common/interfaces/paginated-list.interface'import {BoxSortField,@@ -227,6 +230,7 @@ export class BoxService {private readonly imagePullFailureService: ImagePullFailureService,private readonly organizationBoxLimits: OrganizationBoxLimitsService,private readonly secretServerClient: SecretServerClient,+ private readonly filestoreInstanceResolver: FilestoreInstanceResolver,) {}protected getLockKey(id: string): string {@@ -363,23 +367,44 @@ export class BoxService {const needsFreshBox = !!options.onPersist || requiresFreshBox(createBoxDto, organization, resolvedImage)if (createBoxDto.volumes && createBoxDto.volumes.length > 0) {- const volumeIdOrNames = createBoxDto.volumes.map((v) => v.volumeId)- const canonical = await this.volumeService.validateVolumes(organization.id, volumeIdOrNames)- // Replace the caller's selector with the id it resolved to inside this- // organization. A name is only unique per organization, but everything- // downstream (the runner, the `boxlite-volume-<id>` bucket) reads this- // field as a global id - see VolumeService.validateVolumes.- createBoxDto.volumes = createBoxDto.volumes.map((volume) => {- const canonicalId = canonical.get(volume.volumeId)- if (!canonicalId) {+ const volumes = await this.volumeService.validateVolumes(+ organization.id,+ createBoxDto.volumes.map((v) => v.volumeId),+ )+ // Replace the caller's selector with the volume it resolved to inside+ // this organization. A name is only unique per organization, but+ // everything downstream (the runner, the `boxlite-volume-<id>` bucket,+ // a filestore data directory `boxlite-filestore-<instance>/<id>`) reads+ // the stored value as a globally canonical id - see+ // VolumeService.validateVolumes. The filestore reference rides along+ // for the runner's mount dispatch with the address the API resolves+ // from its FILESTORE_INSTANCES configuration; the runner configures+ // no instances of its own. A name that left the configuration between+ // the volume's create and this dispatch fails loudly here.+ const resolvedVolumes = []+ for (const volume of createBoxDto.volumes) {+ const resolved = volumes.get(volume.volumeId)+ if (!resolved) {// validateVolumes keys every selector or throws, so this is// unreachable today. Fail closed anyway: the alternative fallback// is silently persisting the caller's own string, which is exactly// the tenant-controlled passthrough the resolution exists to stop.throw new BadRequestError(`Volume '${volume.volumeId}' could not be resolved`)}- return { ...volume, volumeId: canonicalId }- })+ const instance = isFilestoreVolume(resolved)+ ? await this.filestoreInstanceResolver.resolve(resolved.instance, 'configured')+ : undefined+ resolvedVolumes.push(+ boxVolumeForDispatch({+ ...volume,+ volumeId: resolved.id,+ ...(instance+ ? { filestore: { instance: resolved.instance, server: instance.server, export: instance.export } }+ : {}),+ }),+ )+ }+ createBoxDto.volumes = resolvedVolumes} else if (image && !needsFreshBox) {// No volumes requested — try to claim a pre-warmed box matching this image/spec// before creating a fresh one.@@ -1039,7 +1064,11 @@ export class BoxService {selected.organizationId,)- if (box.pending && !checkpointState?.activeJobId) {+ const waitingFilestoreRestart =+ box.state === BoxState.STOPPED &&+ box.desiredState === BoxDesiredState.STARTED &&+ box.volumes?.some((volume) => volume.filestore)+ if (box.pending && !checkpointState?.activeJobId && !waitingFilestoreRestart) {throw new BoxError('Box state change in progress')}diff --git a/apps/api/src/box/services/job.service.transaction.spec.ts b/apps/api/src/box/services/job.service.transaction.spec.tsindex c000090a9..947d93f51 100644--- a/apps/api/src/box/services/job.service.transaction.spec.ts+++ b/apps/api/src/box/services/job.service.transaction.spec.ts@@ -3,7 +3,7 @@* SPDX-License-Identifier: AGPL-3.0-only*/-import { ConflictException } from '@nestjs/common'+import { ConflictException, Logger, ServiceUnavailableException } from '@nestjs/common'import { Job } from '../entities/job.entity'import { JobStatus, JobType, ResourceType } from '../dto/job.dto'import { JobService } from './job.service'@@ -48,6 +48,43 @@ function makeService(transactionalJob: Job) {return { entityManager, jobRepository, jobStateHandlerService, service }}+describe('JobService creation diagnostics', () => {+ it('logs the job, runner, resource and database code without logging its payload', async () => {+ const failure = Object.assign(new Error('insert failed'), {+ code: '58000',+ query: 'INSERT INTO job VALUES (?)',+ parameters: ['do-not-log'],+ })+ const jobRepository = { insert: jest.fn().mockRejectedValue(failure) }+ const service = new JobService(jobRepository as any, {} as any, {} as any)+ const log = jest.spyOn(Logger.prototype, 'error').mockImplementation(() => undefined)++ try {+ await expect(+ service.createJob(null, JobType.CREATE_BOX, 'runner-1', ResourceType.BOX, 'box-1', {+ env: { SECRET: 'do-not-log' },+ }),+ ).rejects.toBeInstanceOf(ServiceUnavailableException)+ expect(log).toHaveBeenCalledWith(+ expect.objectContaining({+ event: 'job.create.failed',+ jobType: JobType.CREATE_BOX,+ runnerId: 'runner-1',+ resourceType: ResourceType.BOX,+ resourceId: 'box-1',+ code: '58000',+ errorName: 'Error',+ }),+ 'Job creation failed',+ )+ expect(log.mock.calls[0][0]).not.toHaveProperty('err')+ expect(JSON.stringify(log.mock.calls)).not.toContain('do-not-log')+ } finally {+ log.mockRestore()+ }+ })+})+describe('JobService.updateJobStatus transaction boundary', () => {it('locks, validates, and saves the Job in one transaction before completion handling', async () => {const job = makeJob(JobStatus.IN_PROGRESS)diff --git a/apps/api/src/box/services/job.service.ts b/apps/api/src/box/services/job.service.tsindex 97fb4f298..5f8347978 100644--- a/apps/api/src/box/services/job.service.ts+++ b/apps/api/src/box/services/job.service.ts@@ -87,11 +87,21 @@ export class JobService {}throw new JobConflictError()}+ this.logger.error(+ {+ event: 'job.create.failed',+ jobType: type,+ runnerId,+ resourceType,+ resourceId,+ code: (error as { code?: string | number } | null)?.code,+ errorName: error instanceof Error ? error.name : typeof error,+ },+ 'Job creation failed',+ )if (type === JobType.CREATE_BOX) {- this.logger.error(`Could not create job for box ${resourceId} on runner ${runnerId}`)throw new ServiceUnavailableException('Could not create box job')}- this.logger.error(`Error creating job: ${error}`)throw error}}diff --git a/apps/api/src/box/services/volume.service.spec.ts b/apps/api/src/box/services/volume.service.spec.tsindex bc6055b7a..5e87ab9df 100644--- a/apps/api/src/box/services/volume.service.spec.ts+++ b/apps/api/src/box/services/volume.service.spec.ts@@ -1,6 +1,13 @@import { Context } from '../../common/context/context'-import { NotFoundException, RequestTimeoutException } from '@nestjs/common'+import {+ ForbiddenException,+ NotFoundException,+ NotImplementedException,+ RequestTimeoutException,+ ServiceUnavailableException,+} from '@nestjs/common'import { VolumeState } from '../enums/volume-state.enum'+import { BadRequestError } from '../../exceptions/bad-request.exception'import { VolumeService } from './volume.service'describe('VolumeService delete', () => {@@ -8,7 +15,14 @@ describe('VolumeService delete', () => {const volumeRepository = {findOne: jest.fn().mockResolvedValue(volume),}- const service = new VolumeService(volumeRepository as never, {} as never, {} as never, {} as never, {} as never)+ const service = new VolumeService(+ volumeRepository as never,+ {} as never,+ {} as never,+ {} as never,+ {} as never,+ {} as never,+ )return { service, volumeRepository }}@@ -48,7 +62,14 @@ describe('VolumeService waitForReady', () => {const volumeRepository = {findOne: jest.fn().mockImplementation(() => Promise.resolve(volumes.shift() ?? null)),}- const service = new VolumeService(volumeRepository as never, {} as never, {} as never, {} as never, {} as never)+ const service = new VolumeService(+ volumeRepository as never,+ {} as never,+ {} as never,+ {} as never,+ {} as never,+ {} as never,+ )return { service, volumeRepository }}@@ -81,7 +102,14 @@ describe('VolumeService validateVolumes canonicalization', () => {const volumeRepository = {find: jest.fn().mockResolvedValue(volumes),}- const service = new VolumeService(volumeRepository as never, {} as never, {} as never, {} as never, {} as never)+ const service = new VolumeService(+ volumeRepository as never,+ {} as never,+ {} as never,+ {} as never,+ {} as never,+ {} as never,+ )return { service, volumeRepository }}@@ -90,7 +118,7 @@ describe('VolumeService validateVolumes canonicalization', () => {const canonical = await service.validateVolumes('org-1', ['my-data'])- expect(canonical.get('my-data')).toBe('uuid-mine')+ expect(canonical.get('my-data')?.id).toBe('uuid-mine')})// The tenant-boundary case: a caller may name their own volume after another@@ -103,8 +131,8 @@ describe('VolumeService validateVolumes canonicalization', () => {const canonical = await service.validateVolumes('org-1', [otherTenantId])- expect(canonical.get(otherTenantId)).toBe('uuid-mine')- expect(canonical.get(otherTenantId)).not.toBe(otherTenantId)+ expect(canonical.get(otherTenantId)?.id).toBe('uuid-mine')+ expect(canonical.get(otherTenantId)?.id).not.toBe(otherTenantId)})// When one volume's id equals another's name, the id must win: an id is@@ -117,7 +145,7 @@ describe('VolumeService validateVolumes canonicalization', () => {const canonical = await service.validateVolumes('org-1', ['collide'])- expect(canonical.get('collide')).toBe('collide')+ expect(canonical.get('collide')?.id).toBe('collide')})it('returns an empty map for no selectors', async () => {@@ -133,7 +161,14 @@ describe('VolumeService validateVolumes query safety', () => {function createService(volumes: Array<Record<string, unknown>>) {const volumeRepository = { find: jest.fn().mockResolvedValue(volumes) }- const service = new VolumeService(volumeRepository as never, {} as never, {} as never, {} as never, {} as never)+ const service = new VolumeService(+ volumeRepository as never,+ {} as never,+ {} as never,+ {} as never,+ {} as never,+ {} as never,+ )return { service, volumeRepository }}@@ -171,7 +206,9 @@ describe('VolumeService validateVolumes query safety', () => {{ id: 'uuid-other', name: 'wanted', state: VolumeState.PENDING_CREATE },])- await expect(service.validateVolumes('org-1', ['wanted'])).resolves.toEqual(new Map([['wanted', 'wanted']]))+ await expect(service.validateVolumes('org-1', ['wanted'])).resolves.toEqual(+ new Map([['wanted', { id: 'wanted', name: 'by-id', state: VolumeState.READY }]]),+ )})it('still rejects a selected volume that is not ready', async () => {@@ -186,3 +223,216 @@ describe('VolumeService validateVolumes query safety', () => {await expect(service.validateVolumes('org-1', ['missing'])).rejects.toThrow("Volume 'missing' not found")})})++// Filestore volumes are Volume rows with an `instance`; their lifecycle+// differs from the bucket kind in exactly two places: nothing to provision+// API-side (the runner creates the data directory lazily at first mount, so+// the volume is READY at once) and nothing to tear down (the NFS directory is+// left in place for ops cleanup, so delete tombstones the row directly — the+// volume manager cron runs even when only filestore volumes exist, because+// deletion is row-only for them).+describe('VolumeService filestore volumes', () => {+ function createService(+ volume: Record<string, unknown> | null,+ boxes: Array<Record<string, unknown>> = [],+ filestoreInstances: Array<{ instance: string; projectId: string; zone: string }> = [+ { instance: 'ml-scratch', projectId: 'boxlite-dev', zone: 'asia-southeast1-b' },+ ],+ filestoreSupported = true,+ ) {+ const volumeRepository = {+ findOne: jest.fn().mockResolvedValue(volume),+ save: jest.fn().mockImplementation(async (v) => v),+ }+ const boxRepository = {+ createQueryBuilder: jest.fn(() => {+ const builder = {+ where: () => builder,+ andWhere: () => builder,+ select: () => builder,+ getOne: jest.fn().mockResolvedValue(boxes[0] ?? null),+ }+ return builder+ }),+ }+ const organizationService = { assertOrganizationIsNotSuspended: jest.fn() }+ const configService = {+ get: jest.fn((key: string) => {+ expect(key).toBe('volume.filestoreSupported')+ return filestoreSupported+ }),+ getOrThrow: jest.fn((key: string) => {+ expect(key).toBe('volume.filestoreInstances')+ return { instances: filestoreInstances }+ }),+ }+ const filestoreInstanceResolver = {+ resolve: jest.fn().mockResolvedValue({ server: '10.0.0.7', export: '/vol1' }),+ select: jest.fn().mockImplementation(() => {+ if (!filestoreInstances.length) throw new ServiceUnavailableException('Filestore is not configured')+ return filestoreInstances[0]+ }),+ }+ const service = new VolumeService(+ volumeRepository as never,+ boxRepository as never,+ organizationService as never,+ configService as never,+ {} as never,+ filestoreInstanceResolver as never,+ )+ return { service, volumeRepository, filestoreInstanceResolver, organizationService }+ }++ const organization = { id: 'org-1' } as never++ it('creates a filestore volume READY, without consulting object storage', async () => {+ const { service } = createService(null)++ const volume = await service.create(+ organization,+ { name: 'nfs-data', storageBackend: 'performance', instance: 'ml-scratch' },+ Context.user(),+ )++ expect(volume.state).toBe(VolumeState.READY)+ expect(volume.instance).toBe('ml-scratch')+ })++ it('rejects a duplicate name before consulting GCP', async () => {+ const { service, filestoreInstanceResolver } = createService({+ id: 'existing',+ name: 'nfs-data',+ state: VolumeState.READY,+ instance: 'ml-scratch',+ })+ filestoreInstanceResolver.resolve.mockRejectedValue(new ServiceUnavailableException('GCP unavailable'))++ await expect(+ service.create(+ organization,+ { name: 'nfs-data', storageBackend: 'performance', instance: 'ml-scratch' },+ Context.user(),+ ),+ ).rejects.toThrow('already exists')+ expect(filestoreInstanceResolver.resolve).not.toHaveBeenCalled()+ })++ it('rejects a suspended organization before consulting GCP', async () => {+ const { service, filestoreInstanceResolver, organizationService } = createService(null)+ organizationService.assertOrganizationIsNotSuspended.mockImplementation(() => {+ throw new ForbiddenException('Organization is suspended')+ })+ filestoreInstanceResolver.resolve.mockRejectedValue(new ServiceUnavailableException('GCP unavailable'))++ await expect(+ service.create(+ organization,+ { name: 'nfs-data', storageBackend: 'performance', instance: 'ml-scratch' },+ Context.user(),+ ),+ ).rejects.toBeInstanceOf(ForbiddenException)+ expect(filestoreInstanceResolver.resolve).not.toHaveBeenCalled()+ })++ it('assigns an omitted Filestore instance from the configured objects', async () => {+ const { service, filestoreInstanceResolver } = createService(+ null,+ [],+ [+ { instance: 'zeta', projectId: 'zeta-project', zone: 'us-east5-a' },+ { instance: 'alpha', projectId: 'alpha-project', zone: 'us-east5-b' },+ ],+ )++ const volume = await service.create(organization, { name: 'nfs-data', storageBackend: 'performance' }, Context.user())++ const [selected, source] = filestoreInstanceResolver.resolve.mock.calls[0]+ expect(volume.instance).toBe(selected)+ expect(['alpha', 'zeta']).toContain(selected)+ expect(source).toBe('configured')+ })++ it('rejects Filestore placement when no instances are configured', async () => {+ const { service, volumeRepository } = createService(null, [], [])++ await expect(service.create(organization, { storageBackend: 'performance' }, Context.user())).rejects.toBeInstanceOf(+ ServiceUnavailableException,+ )+ expect(volumeRepository.save).not.toHaveBeenCalled()+ })++ it('rejects Filestore creation on an unsupported deployment without persisting a row', async () => {+ const { service, volumeRepository, filestoreInstanceResolver } = createService(null, [], [+ { instance: 'ml-scratch', projectId: 'boxlite-dev', zone: 'asia-southeast1-b' },+ ], false)++ await expect(+ service.create(organization, { name: 'nfs-data', storageBackend: 'performance' }, Context.user()),+ ).rejects.toMatchObject({+ constructor: NotImplementedException,+ response: { code: 'unsupported', message: expect.stringContaining('not supported') },+ })+ expect(volumeRepository.save).not.toHaveBeenCalled()+ expect(filestoreInstanceResolver.resolve).not.toHaveBeenCalled()+ })++ it('rejects an explicit instance the resolver cannot find, without persisting a row', async () => {+ const { service, volumeRepository, filestoreInstanceResolver } = createService(null)+ filestoreInstanceResolver.resolve.mockRejectedValue(new BadRequestError('Filestore instance ... not found'))++ await expect(+ service.create(+ organization,+ { name: 'nfs-data', storageBackend: 'performance', instance: 'ml-scratch' },+ Context.user(),+ ),+ ).rejects.toBeInstanceOf(BadRequestError)+ expect(volumeRepository.save).not.toHaveBeenCalled()+ })++ it('rejects a hash-assigned instance whose lookup fails, without persisting a row', async () => {+ const { service, volumeRepository, filestoreInstanceResolver } = createService(null)+ filestoreInstanceResolver.resolve.mockRejectedValue(+ new ServiceUnavailableException('Filestore instance ... not found'),+ )++ await expect(+ service.create(organization, { name: 'nfs-data', storageBackend: 'performance' }, Context.user()),+ ).rejects.toBeInstanceOf(ServiceUnavailableException)+ expect(volumeRepository.save).not.toHaveBeenCalled()+ })++ it('rejects instance placement without the explicit Filestore backend', async () => {+ const { service, volumeRepository } = createService(null)++ await expect(service.create(organization, { instance: 'ml-scratch' }, Context.user())).rejects.toThrow(+ 'instance is valid only when storageBackend is "performance"',+ )+ expect(volumeRepository.save).not.toHaveBeenCalled()+ })++ it('sends a filestore volume through the same async delete path as buckets', async () => {+ const { service, volumeRepository } = createService({+ id: 'volume-1',+ name: 'nfs-data',+ state: VolumeState.READY,+ instance: 'ml-scratch',+ })++ await service.delete('volume-1', Context.user())++ expect(volumeRepository.save).toHaveBeenCalledWith(+ expect.objectContaining({ id: 'volume-1', state: VolumeState.PENDING_DELETE }),+ )+ })++ it('still refuses to delete a filestore volume a live box references', async () => {+ const { service } = createService(+ { id: 'volume-1', name: 'nfs-data', state: VolumeState.READY, instance: 'ml-scratch' },+ [{ id: 'box-1', name: 'my-box' }],+ )++ await expect(service.delete('volume-1', Context.user())).rejects.toThrow('in use by one or more boxes')+ })+})diff --git a/apps/api/src/box/services/volume.service.ts b/apps/api/src/box/services/volume.service.tsindex 9bfd14c43..f9e62f3ac 100644--- a/apps/api/src/box/services/volume.service.ts+++ b/apps/api/src/box/services/volume.service.ts@@ -9,6 +9,7 @@ import {Injectable,Logger,NotFoundException,+ NotImplementedException,RequestTimeoutException,ServiceUnavailableException,} from '@nestjs/common'@@ -27,6 +28,7 @@ import { OrganizationService } from '../../organization/services/organization.seimport { TypedConfigService } from '../../config/typed-config.service'import { RedisLockProvider } from '../common/redis-lock.provider'import { BoxRepository } from '../repositories/box.repository'+import { FilestoreInstanceResolver } from './filestore-instance.resolver'import { BoxDesiredState } from '../enums/box-desired-state.enum'import { setTimeout as sleep } from 'timers/promises'import { isVolumeStorageConfigured } from '../stores/volume-bucket.store'@@ -48,6 +50,7 @@ export class VolumeService {private readonly organizationService: OrganizationService,private readonly configService: TypedConfigService,private readonly redisLockProvider: RedisLockProvider,+ private readonly filestoreInstanceResolver: FilestoreInstanceResolver,) {}async create(organization: Organization, createVolumeDto: CreateVolumeDto, ctx: Context): Promise<Volume> {@@ -64,7 +67,22 @@ export class VolumeService {createVolumeDto: CreateVolumeDto,volumeId: string,): Promise<Volume> {- if (!isVolumeStorageConfigured(this.configService)) {+ const isFilestore = createVolumeDto.storageBackend === 'performance'+ if (isFilestore && this.configService.get('volume.filestoreSupported') === false) {+ throw new NotImplementedException({+ message: 'Filestore volumes are not supported in this deployment',+ code: 'unsupported',+ })+ }+ if (!isFilestore && createVolumeDto.instance !== undefined) {+ throw new BadRequestError('instance is valid only when storageBackend is "performance"')+ }++ // Only the object-storage kind needs the API's own bucket backend. A+ // filestore volume's storage is an NFS data directory the runner creates+ // lazily at first mount, so an API without object storage configured can+ // still serve filestore volumes — an org can run on filestore volumes alone.+ if (!isFilestore && !isVolumeStorageConfigured(this.configService)) {throw new ServiceUnavailableException('Object storage is not configured')}@@ -91,14 +109,34 @@ export class VolumeService {throw new BadRequestError(`Volume with name ${volume.name} already exists`)}+ const filestoreInstance = await this.selectFilestoreInstance(createVolumeDto, volumeId)volume.organizationId = organization.id- volume.state = VolumeState.PENDING_CREATE+ volume.instance = filestoreInstance || undefined++ // Filestore volumes have no API-side provisioning step: the data+ // directory on the NFS instance is created by the runner lazily at first+ // mount, so the volume is READY the moment the row exists. Object-storage+ // volumes keep the async PENDING_CREATE path the bucket store walks.+ volume.state = isFilestore ? VolumeState.READY : VolumeState.PENDING_CREATEconst savedVolume = await this.volumeRepository.save(volume)this.logger.debug(`Created volume ${savedVolume.id} for organization ${organization.id}`)return savedVolume}+ private async selectFilestoreInstance(createVolumeDto: CreateVolumeDto, volumeId: string): Promise<string> {+ if (createVolumeDto.storageBackend !== 'performance') return ''++ if (createVolumeDto.instance) {+ await this.filestoreInstanceResolver.resolve(createVolumeDto.instance, 'request')+ return createVolumeDto.instance+ }++ const selected = this.filestoreInstanceResolver.select(volumeId)+ await this.filestoreInstanceResolver.resolve(selected.instance, 'configured')+ return selected.instance+ }+async waitForReady(volumeId: string, timeoutSeconds: number): Promise<Volume> {const deadline = Date.now() + timeoutSeconds * 1000@@ -214,14 +252,16 @@ export class VolumeService {/*** Resolve each selector to the volume it names, or throw.*- * Returns a selector -> canonical id map rather than void: a selector may be+ * Returns a selector -> Volume entity map rather than void: a selector may be* a *name*, and a name is only unique within an organization. Everything* downstream - the persisted box, the runner dispatch, the derived bucket* `boxlite-volume-<id>` - treats the stored value as a globally canonical id.* Persisting the caller's selector instead would let one tenant name a volume- * after another tenant's id and have the runner resolve it there.+ * after another tenant's id and have the runner resolve it there. Callers that+ * need only the id derive it from the entity; the entity also carries the+ * filestore instance a box's mount dispatch must hand the runner.*/- async validateVolumes(organizationId: string, volumeIdOrNames: string[]): Promise<Map<string, string>> {+ async validateVolumes(organizationId: string, volumeIdOrNames: string[]): Promise<Map<string, Volume>> {if (!volumeIdOrNames.length) {return new Map()}@@ -265,7 +305,7 @@ export class VolumeService {}}- return new Map(Array.from(selected, ([selector, volume]) => [selector, volume.id]))+ return selected}async getOrganizationId(params: { id: string } | { name: string; organizationId: string }): Promise<string> {diff --git a/apps/api/src/box/utils/box-volume.util.ts b/apps/api/src/box/utils/box-volume.util.tsnew file mode 100644index 000000000..e68b70504--- /dev/null+++ b/apps/api/src/box/utils/box-volume.util.ts@@ -0,0 +1,25 @@+/*+ * Copyright 2025 Daytona Platforms Inc.+ * Modified by BoxLite AI, 2025-2026+ * SPDX-License-Identifier: AGPL-3.0+ */++import type { BoxVolume, BoxVolumeFilestoreRef } from '../dto/box.dto'++export function boxVolumeForDispatch(volume: BoxVolume): BoxVolume {+ return {+ volumeId: volume.volumeId,+ mountPath: volume.mountPath,+ subpath: volume.subpath,+ ...(volume.filestore ? { filestore: volume.filestore } : {}),+ }+}++export function boxVolumeForPublic(volume: BoxVolume): BoxVolume {+ return {+ ...boxVolumeForDispatch(volume),+ ...(volume.filestore+ ? { filestore: { instance: volume.filestore.instance } as BoxVolumeFilestoreRef }+ : {}),+ }+}diff --git a/apps/api/src/box/utils/sanitize-error.util.spec.ts b/apps/api/src/box/utils/sanitize-error.util.spec.tsindex a2a67153d..338212f81 100644--- a/apps/api/src/box/utils/sanitize-error.util.spec.ts+++ b/apps/api/src/box/utils/sanitize-error.util.spec.ts@@ -64,6 +64,24 @@ describe('sanitizeBoxError', () => {})})+ it('keeps Filestore mount targets out of public error reasons', () => {+ const failure =+ 'FILESTORE_VOLUME_PREPARE_FAILED: failed to prepare filestore volume volume-1 on instance ml-scratch for box box-1: ' ++ 'filestore ml-scratch mount target mismatch at /mnt/boxlite-filestore-ml-scratch: ' ++ 'mounted source "10.0.0.7:/vol1", requested source "10.0.0.9:/vol2"'++ const { errorReason } = sanitizeBoxError(new Error(failure))++ expect(errorReason).toBe(+ 'FILESTORE_VOLUME_PREPARE_FAILED: failed to prepare filestore volume volume-1 on instance ml-scratch for box box-1',+ )+ expect(errorReason).not.toContain('10.0.0.7')+ expect(errorReason).not.toContain('10.0.0.9')+ expect(errorReason).not.toContain('/vol1')+ expect(errorReason).not.toContain('/vol2')+ expect(errorReason).not.toContain('/mnt/')+ })+it('leaves a reason that names no registry proxy as it was', () => {process.env.REGISTRY_PROXY_HOST = PROXYconst direct = failedPull('quay.io/acme/app:1', 'https://quay.io/v2/acme/app/manifests/1')diff --git a/apps/api/src/box/utils/sanitize-error.util.ts b/apps/api/src/box/utils/sanitize-error.util.tsindex fadcf4ec7..d9bf9ff93 100644--- a/apps/api/src/box/utils/sanitize-error.util.ts+++ b/apps/api/src/box/utils/sanitize-error.util.ts@@ -6,16 +6,34 @@import { withoutRegistryProxy } from '../../image/utils/image-ref.util'+const FILESTORE_PREPARE_PREFIX =+ /FILESTORE_VOLUME_PREPARE_FAILED: failed to prepare filestore volume (\S+) on instance (\S+) for box (\S+):/++function withoutFilestoreMountTarget(errorReason: string): string {+ const match = errorReason.match(FILESTORE_PREPARE_PREFIX)+ if (match) {+ return `FILESTORE_VOLUME_PREPARE_FAILED: failed to prepare filestore volume ${match[1]} on instance ${match[2]} for box ${match[3]}`+ }+ if (errorReason.includes('FILESTORE_VOLUME_PREPARE_FAILED')) {+ return 'FILESTORE_VOLUME_PREPARE_FAILED: Filestore volume preparation failed'+ }+ return errorReason+}+/*** A runner's failure as the box records it. A runner's words can name the* registry proxy a private image was pulled through; the recorded reason names* the upstream image the tenant asked for instead, and never the proxy's- * address.+ * address. Filestore preparation errors likewise keep resolved NFS targets+ * out of the public reason while retaining their stable code and logical IDs.*/export function sanitizeBoxError(error: any): { recoverable: boolean; errorReason: string } {const { recoverable, errorReason } = parseBoxError(error)// JSON a runner did not write can carry anything as its reason.- return { recoverable, errorReason: typeof errorReason === 'string' ? withoutRegistryProxy(errorReason) : errorReason }+ return {+ recoverable,+ errorReason: typeof errorReason === 'string' ? withoutFilestoreMountTarget(withoutRegistryProxy(errorReason)) : errorReason,+ }}function parseBoxError(error: any): { recoverable: boolean; errorReason: string } {diff --git a/apps/api/src/box/utils/volume-mount-path-validation.util.spec.ts b/apps/api/src/box/utils/volume-mount-path-validation.util.spec.tsnew file mode 100644index 000000000..61dd9506b--- /dev/null+++ b/apps/api/src/box/utils/volume-mount-path-validation.util.spec.ts@@ -0,0 +1,60 @@+/*+ * Copyright 2025 Daytona Platforms Inc.+ * Modified by BoxLite AI, 2025-2026+ * SPDX-License-Identifier: AGPL-3.0+ */++import { BoxVolume } from '../dto/box.dto'+import { validateMountPaths } from './volume-mount-path-validation.util'++// The mount-path rules are backend-agnostic by construction: every volume+// reference (managed and filestore alike) carries mountPath at the top level,+// so both shapes must pass the same rules through the same function. Each+// rejection case pins the branch that rejects it via the error message, so a+// case cannot pass merely because an earlier branch also rejects the input.+describe('validateMountPaths', () => {+ it.each([+ ['a managed volume', { volumeId: 'volume-123', mountPath: '/data' }],+ ['a filestore volume', { volumeId: 'volume-123', mountPath: '/nfs', filestore: { instance: 'ml-scratch', server: '10.0.0.7', export: '/vol1' } }],+ ['a managed volume with a subpath', { volumeId: 'volume-123', mountPath: '/data', subpath: 'users/alice' }],+ ])('accepts an absolute mount path on %s', (_label, volume: BoxVolume) => {+ expect(() => validateMountPaths([volume])).not.toThrow()+ })++ it.each([+ ['a relative path', 'data', 'must be absolute'],+ ['the root directory', '/', 'cannot mount to the root directory'],+ ['a parent traversal', '/data/../etc', 'cannot contain relative path components'],+ ['a relative path with double slashes', 'a//b', 'must be absolute'],+ ['an absolute path with consecutive slashes', '/a//b', 'cannot contain consecutive slashes'],+ ['a system file', '/etc/passwd', 'cannot mount to system directory'],+ ['a directory under a system path', '/etc/nginx/conf', 'cannot mount to system directory'],+ ])('rejects %s', (_label, mountPath: string, message) => {+ const volume: BoxVolume = { volumeId: 'volume-123', mountPath, filestore: { instance: 'ml-scratch', server: '10.0.0.7', export: '/vol1' } }++ expect(() => validateMountPaths([volume])).toThrow(message)+ })++ it('reports every invalid volume, not just the first', () => {+ expect(() =>+ validateMountPaths([+ { volumeId: 'volume-123', mountPath: '/data' },+ { volumeId: 'volume-123', mountPath: 'relative', filestore: { instance: 'ml-scratch', server: '10.0.0.7', export: '/vol1' } },+ { volumeId: 'volume-123', mountPath: '/proc', filestore: { instance: 'ml-scratch', server: '10.0.0.7', export: '/vol1' } },+ ]),+ ).toThrow('must be absolute')+ // toThrow checks the whole joined message; assert the second error is in+ // there too rather than letting the first mask it.+ let thrown: unknown+ try {+ validateMountPaths([+ { volumeId: 'volume-123', mountPath: '/data' },+ { volumeId: 'volume-123', mountPath: 'relative', filestore: { instance: 'ml-scratch', server: '10.0.0.7', export: '/vol1' } },+ { volumeId: 'volume-123', mountPath: '/proc', filestore: { instance: 'ml-scratch', server: '10.0.0.7', export: '/vol1' } },+ ])+ } catch (error) {+ thrown = error+ }+ expect((thrown as Error).message).toContain('cannot mount to system directory')+ })+})diff --git a/apps/api/src/box/utils/volume-mount-path-validation.util.ts b/apps/api/src/box/utils/volume-mount-path-validation.util.tsindex 50e06d80f..ff32a6d04 100644--- a/apps/api/src/box/utils/volume-mount-path-validation.util.ts+++ b/apps/api/src/box/utils/volume-mount-path-validation.util.ts@@ -7,7 +7,13 @@import { BoxVolume } from '../dto/box.dto'/**- * Validates mount paths for box volumes to ensure they are safe and valid+ * Validates mount paths for box volumes to ensure they are safe and valid.+ *+ * Backend-agnostic by construction: every volume reference carries mountPath+ * at the top level (managed volumes and filestore volumes alike), so this+ * needs no per-backend branch and filestore volumes get the same rules for+ * free.+ ** @param volumes - Array of BoxVolume objects to validate* @throws Error with descriptive message if any mount path is invalid*/diff --git a/apps/api/src/boxlite-rest/boxlite-box.controller.spec.ts b/apps/api/src/boxlite-rest/boxlite-box.controller.spec.tsindex 584f6b9ad..b6c1b0531 100644--- a/apps/api/src/boxlite-rest/boxlite-box.controller.spec.ts+++ b/apps/api/src/boxlite-rest/boxlite-box.controller.spec.ts@@ -242,7 +242,7 @@ describe('BoxliteBoxController volume attachment authorization', () => {const { controller, boxService } = makeController()await expect(controller.createBox(keyContext([WRITE_BOXES]), dtoWithVolume, Context.user())).rejects.toThrow(- /managed volume/,+ /Attaching a volume requires/,)expect(boxService.create).not.toHaveBeenCalled()})@@ -314,7 +314,7 @@ describe('BoxliteBoxController volume attachment authorization', () => {await expect(controller.createBox(memberContext([{ permissions: [WRITE_BOXES] }]), dtoWithVolume, Context.user()),- ).rejects.toThrow(/managed volume/)+ ).rejects.toThrow(/Attaching a volume requires/)expect(boxService.create).not.toHaveBeenCalled()})@@ -322,12 +322,86 @@ describe('BoxliteBoxController volume attachment authorization', () => {const { controller, boxService } = makeController()await expect(controller.createBox(memberContext(undefined), dtoWithVolume, Context.user())).rejects.toThrow(- /managed volume/,+ /Attaching a volume requires/,)expect(boxService.create).not.toHaveBeenCalled()})})+describe('BoxliteBoxController creation diagnostics', () => {+ it('logs non-sensitive context when an admitted Box fails while starting', async () => {+ const failure = new BadRequestException({+ message: 'runner has not declared filestore',+ code: 'BOX_STATE_TRANSITION_FAILED',+ boxId: 'box-1',+ })+ const boxService = {+ create: jest.fn().mockResolvedValue({ id: 'box-1', state: 'creating' }),+ }+ const boxStateWaiter = { waitForStarted: jest.fn().mockRejectedValue(failure) }+ const controller = new BoxliteBoxController(+ boxService as any,+ boxStateWaiter as any,+ { resolveMaxCreatedBoxes: jest.fn().mockResolvedValue(10) } 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+ const dto = { image: 'alpine:latest', volumes: [{ managed_volume: 'vol-1', guest_path: '/data' }] } as any++ await expect(controller.createBox(auth, dto, Context.user())).rejects.toBe(failure)+ expect(log).toHaveBeenCalledWith(+ expect.objectContaining({+ event: 'box.create.failed',+ boxId: 'box-1',+ organizationId: 'org-1',+ statusCode: 400,+ code: 'BOX_STATE_TRANSITION_FAILED',+ volumeCount: 1,+ volumeIds: ['vol-1'],+ mountPaths: ['/data'],+ errorName: 'BadRequestException',+ }),+ 'Box creation failed',+ )+ expect(log.mock.calls[0][0]).not.toHaveProperty('image')+ expect(log.mock.calls[0][0]).not.toHaveProperty('env')+ expect(log.mock.calls[0][0]).not.toHaveProperty('err')+ })++ it('does not serialize database queries or parameters when Box insertion fails', async () => {+ const secret = 'do-not-log-box-auth-token'+ const failure = Object.assign(new Error('duplicate key value'), {+ name: 'QueryFailedError',+ query: 'INSERT INTO box (env, authToken) VALUES ($1, $2)',+ parameters: ['secret-environment-value', secret],+ driverError: { code: '23505', detail: secret },+ })+ const controller = new BoxliteBoxController(+ { create: jest.fn().mockRejectedValue(failure) } as any,+ {} as any,+ { resolveMaxCreatedBoxes: jest.fn().mockResolvedValue(10) } 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++ await expect(controller.createBox(auth, { image: 'alpine:latest' } as any, Context.user())).rejects.toBe(failure)++ expect(JSON.stringify(log.mock.calls)).not.toContain(secret)+ expect(JSON.stringify(log.mock.calls)).not.toContain('secret-environment-value')+ expect(log).toHaveBeenCalledWith(+ expect.objectContaining({+ event: 'box.create.failed',+ errorName: 'QueryFailedError',+ databaseErrorCode: '23505',+ }),+ 'Box creation failed',+ )+ expect(log.mock.calls[0][0]).not.toHaveProperty('err')+ })+})+// The audit log for a visibility change must name the box and the mode asked// for, and nothing else from the body. Driven through the real interceptor// with the handler's own @Audit metadata, so a wrong extractor fails here.diff --git a/apps/api/src/boxlite-rest/boxlite-box.controller.ts b/apps/api/src/boxlite-rest/boxlite-box.controller.tsindex eaa2da12c..2b80d528c 100644--- a/apps/api/src/boxlite-rest/boxlite-box.controller.ts+++ b/apps/api/src/boxlite-rest/boxlite-box.controller.ts@@ -149,15 +149,47 @@ export class BoxliteBoxController {const createBoxDto = createBoxToCreateBox(dto)const maxCreatedBoxes = await this.commerceBoxLimitService.resolveMaxCreatedBoxes(organization.id)- let box = await this.boxService.create(createBoxDto, organization, ctx, {- maxCreatedBoxes,- createdBy: authContext.userId,- })- if (request) request[AUDIT_TARGET_ID] = box.id- if (box.state !== BoxState.STARTED) {- box = await this.boxStateWaiter.waitForStarted(box.id, organization.id, 30)+ let boxId: string | undefined+ try {+ let box = await this.boxService.create(createBoxDto, organization, ctx, {+ maxCreatedBoxes,+ createdBy: authContext.userId,+ })+ boxId = box.id+ if (request) request[AUDIT_TARGET_ID] = box.id+ if (box.state !== BoxState.STARTED) {+ box = await this.boxStateWaiter.waitForStarted(box.id, organization.id, 30)+ }+ return boxToBoxResponse(box)+ } catch (error) {+ this.logCreateFailure(error, dto, organization.id, boxId)+ throw error}- return boxToBoxResponse(box)+ }++ private logCreateFailure(error: unknown, dto: CreateBoxDto, organizationId: string, boxId?: string): void {+ const statusCode = error instanceof HttpException ? error.getStatus() : 500+ const response = error instanceof HttpException ? error.getResponse() : undefined+ const responseCode =+ response && typeof response === 'object' && !Array.isArray(response)+ ? (response as Record<string, unknown>).code+ : undefined+ const databaseErrorCode = (error as { driverError?: { code?: unknown } })?.driverError?.code+ this.logger.error(+ {+ event: 'box.create.failed',+ organizationId,+ ...(boxId ? { boxId } : {}),+ statusCode,+ ...(typeof responseCode === 'string' ? { code: responseCode } : {}),+ errorName: error instanceof Error ? error.name : 'Error',+ ...(typeof databaseErrorCode === 'string' ? { databaseErrorCode } : {}),+ volumeCount: dto.volumes?.length ?? 0,+ volumeIds: dto.volumes?.map((volume) => volume.managed_volume) ?? [],+ mountPaths: dto.volumes?.map((volume) => volume.guest_path) ?? [],+ },+ 'Box creation failed',+ )}/** Admit an inherited configuration, record its request, then wait without losing its identity. */@@ -215,7 +247,7 @@ export class BoxliteBoxController {private assertCanAttachVolumes(authContext: OrganizationAuthContext): void {const required = [OrganizationResourcePermission.READ_VOLUMES, OrganizationResourcePermission.WRITE_VOLUMES]if (!hasOrganizationResourcePermissions(authContext, required)) {- throw new ForbiddenException(`Attaching a managed volume requires: ${required.join(', ')}`)+ throw new ForbiddenException(`Attaching a volume requires: ${required.join(', ')}`)}}diff --git a/apps/api/src/boxlite-rest/boxlite-config.controller.spec.ts b/apps/api/src/boxlite-rest/boxlite-config.controller.spec.tsindex d7d56284c..224703ccb 100644--- a/apps/api/src/boxlite-rest/boxlite-config.controller.spec.ts+++ b/apps/api/src/boxlite-rest/boxlite-config.controller.spec.ts@@ -1,6 +1,32 @@-import { ConfigService } from '@nestjs/config'+import { TypedConfigService } from '../config/typed-config.service'import { BoxliteConfigController } from './boxlite-config.controller'+function createConfig(values: {+ checkpoint?: { archivePrefix?: string; enabled?: boolean }+ objectStorageConfigured?: boolean+ filestoreSupported?: boolean+ filestoreInstanceCount?: number+}) {+ return {+ get: (key: string) => {+ if (key === 'checkpoint.enabled') return values.checkpoint?.enabled+ if (key === 'checkpoint.archivePrefix') return values.checkpoint?.archivePrefix+ if (key === 's3.endpoint') return values.objectStorageConfigured ? 'http://object-storage.test' : undefined+ if (key === 'volume.filestoreSupported') return values.filestoreSupported ?? true+ return undefined+ },+ getOrThrow: (key: string) => {+ if (key === 'volume.filestoreInstances')+ return {+ instances: Array(values.filestoreInstanceCount ?? 0)+ .fill('ml')+ .map((instance) => ({ instance, projectId: 'boxlite-dev', zone: 'us-east5-a' })),+ }+ throw new Error(`Unexpected configuration key: ${key}`)+ },+ } as TypedConfigService+}+describe('checkpoint capability discovery', () => {it.each([{ archivePrefix: undefined, enabled: true, expected: false },@@ -8,9 +34,36 @@ describe('checkpoint capability discovery', () => {{ archivePrefix: 'gs://checkpoint-test/archives/', enabled: false, expected: false },{ archivePrefix: 'gs://checkpoint-test/archives/', enabled: true, expected: true },])('advertises checkpoint admission only after rollout: %j', ({ archivePrefix, enabled, expected }) => {- const controller = new BoxliteConfigController(new ConfigService({ checkpoint: { archivePrefix, enabled } }))+ const controller = new BoxliteConfigController(+ createConfig({ checkpoint: { archivePrefix, enabled }, objectStorageConfigured: true }),+ )expect(controller.getConfig().capabilities.checkpoints_enabled).toBe(expected)expect(controller.getConfig().capabilities.memory_checkpoints_enabled).toBe(false)expect(controller.getConfig().capabilities.import_enabled).toBe(false)})})++describe('volume storage capability discovery', () => {+ it.each([+ { objectStorageConfigured: false, filestoreInstanceCount: 0, objectExpected: false, filestoreExpected: false },+ { objectStorageConfigured: true, filestoreInstanceCount: 0, objectExpected: true, filestoreExpected: false },+ { objectStorageConfigured: false, filestoreInstanceCount: 2, objectExpected: false, filestoreExpected: true },+ {+ objectStorageConfigured: false,+ filestoreInstanceCount: 2,+ filestoreSupported: false,+ objectExpected: false,+ filestoreExpected: false,+ },+ ])(+ 'advertises configured volume backends: %j',+ ({ objectStorageConfigured, filestoreInstanceCount, filestoreSupported, objectExpected, filestoreExpected }) => {+ const controller = new BoxliteConfigController(+ createConfig({ objectStorageConfigured, filestoreInstanceCount, filestoreSupported }),+ )++ expect(controller.getConfig().capabilities.object_storage_enabled).toBe(objectExpected)+ expect(controller.getConfig().capabilities.filestore_enabled).toBe(filestoreExpected)+ },+ )+})diff --git a/apps/api/src/boxlite-rest/boxlite-config.controller.ts b/apps/api/src/boxlite-rest/boxlite-config.controller.tsindex e63963ee0..af389949a 100644--- a/apps/api/src/boxlite-rest/boxlite-config.controller.ts+++ b/apps/api/src/boxlite-rest/boxlite-config.controller.ts@@ -5,15 +5,16 @@*/import { Controller, Get, Optional } from '@nestjs/common'-import { ConfigService } from '@nestjs/config'import { ApiTags, ApiExcludeController } from '@nestjs/swagger'+import { TypedConfigService } from '../config/typed-config.service'+import { isVolumeStorageConfigured } from '../box/stores/volume-bucket.store'// Spec-first surface: the contract is openapi/box.openapi.yaml.@ApiExcludeController()@ApiTags('BoxLite REST')@Controller('v1')export class BoxliteConfigController {- constructor(@Optional() private readonly config?: ConfigService) {}+ constructor(@Optional() private readonly config?: TypedConfigService) {}@Get('config')getConfig() {@@ -22,6 +23,10 @@ export class BoxliteConfigController {checkpoints_enabled:this.config?.get('checkpoint.enabled') === true && !!this.config?.get('checkpoint.archivePrefix'),memory_checkpoints_enabled: false,+ object_storage_enabled: this.config ? isVolumeStorageConfigured(this.config) : false,+ filestore_enabled:+ this.config?.get('volume.filestoreSupported') !== false &&+ (this.config?.getOrThrow('volume.filestoreInstances').instances.length ?? 0) > 0,privileged_enabled: true,snapshots_enabled: false,clone_enabled: false,diff --git a/apps/api/src/boxlite-rest/boxlite-rest-routing.spec.ts b/apps/api/src/boxlite-rest/boxlite-rest-routing.spec.tsindex ba32bca00..303699b47 100644--- a/apps/api/src/boxlite-rest/boxlite-rest-routing.spec.ts+++ b/apps/api/src/boxlite-rest/boxlite-rest-routing.spec.ts@@ -9,6 +9,7 @@ import { readFileSync } from 'node:fs'import { join } from 'node:path'import { Reflector } from '@nestjs/core'import { ConfigService } from '@nestjs/config'+import { TypedConfigService } from '../config/typed-config.service'import { Test } from '@nestjs/testing'import { ValidationPipe, type INestApplication } from '@nestjs/common'import type { AddressInfo } from 'net'@@ -60,8 +61,13 @@ describe('BoxLite REST routing', () => {[BoxliteConfigController, BoxliteBoxController, BoxliteProxyController],[{- provide: ConfigService,- useValue: new ConfigService({ checkpoint: { archivePrefix: 'gs://checkpoint-test/', enabled: true } }),+ provide: TypedConfigService,+ useValue: new TypedConfigService(+ new ConfigService({+ checkpoint: { archivePrefix: 'gs://checkpoint-test/', enabled: true },+ volume: { filestoreInstances: { instances: [] } },+ }),+ ),},{provide: BoxService,diff --git a/apps/api/src/boxlite-rest/boxlite-volume.controller.spec.ts b/apps/api/src/boxlite-rest/boxlite-volume.controller.spec.tsindex cecb441a2..e7669b2d7 100644--- a/apps/api/src/boxlite-rest/boxlite-volume.controller.spec.ts+++ b/apps/api/src/boxlite-rest/boxlite-volume.controller.spec.ts@@ -50,6 +50,7 @@ describe('BoxliteVolumeController', () => {id: volume.id,name: volume.name,state: volume.state,+ storage_backend: 'standard',created_at: createdAt.toISOString(),updated_at: updatedAt.toISOString(),last_used_at: lastUsedAt.toISOString(),@@ -96,6 +97,7 @@ describe('BoxliteVolumeController', () => {id: volume.id,name: volume.name,state: volume.state,+ storage_backend: 'standard',created_at: createdAt.toISOString(),},],@@ -110,6 +112,7 @@ describe('BoxliteVolumeController', () => {id: volume.id,name: volume.name,state: volume.state,+ storage_backend: 'standard',created_at: createdAt.toISOString(),updated_at: updatedAt.toISOString(),last_used_at: lastUsedAt.toISOString(),@@ -118,6 +121,16 @@ describe('BoxliteVolumeController', () => {expect(volumeService.findOne).toHaveBeenCalledWith(volume.id)})+ it('marks a Filestore volume and exposes only its logical instance', async () => {+ const { controller, volumeService } = createController()+ volumeService.findOne.mockResolvedValue({ ...volume, instance: 'ml-scratch' })++ await expect(controller.get(volume.id)).resolves.toMatchObject({+ storage_backend: 'performance',+ instance: 'ml-scratch',+ })+ })+it('deletes a volume by ID', async () => {const { controller, volumeService } = createController()diff --git a/apps/api/src/boxlite-rest/boxlite-volume.controller.ts b/apps/api/src/boxlite-rest/boxlite-volume.controller.tsindex 41497ff5f..1585a044e 100644--- a/apps/api/src/boxlite-rest/boxlite-volume.controller.ts+++ b/apps/api/src/boxlite-rest/boxlite-volume.controller.ts@@ -16,12 +16,17 @@ import { RequiredOrganizationResourcePermissions } from '../organization/decoratimport { OrganizationResourcePermission } from '../organization/enums/organization-resource-permission.enum'import { VolumeAccessGuard } from '../box/guards/volume-access.guard'import { VolumeState } from '../box/enums/volume-state.enum'+import { isFilestoreVolume } from '../box/entities/volume.entity'type RestVolumeSummary = {id: stringname: stringstate: VolumeState+ storage_backend: 'standard' | 'performance'created_at: string+ // Filestore-only: the NFS instance holding the volume's data directory.+ // Absent for object-storage volumes, whose data lives in boxlite-volume-<id>.+ instance?: string}type RestVolumeResponse = RestVolumeSummary & {@@ -96,7 +101,9 @@ export class BoxliteVolumeController {id: volume.id,name: volume.name,state: volume.state,+ storage_backend: isFilestoreVolume(volume) ? 'performance' : 'standard',created_at: volume.createdAt.toISOString(),+ ...(volume.instance ? { instance: volume.instance } : {}),}}}diff --git a/apps/api/src/boxlite-rest/dto/create-box.dto.ts b/apps/api/src/boxlite-rest/dto/create-box.dto.tsindex dbb475640..fc07e69a1 100644--- a/apps/api/src/boxlite-rest/dto/create-box.dto.ts+++ b/apps/api/src/boxlite-rest/dto/create-box.dto.ts@@ -191,6 +191,9 @@ class IsNotHostPathConstraint implements ValidatorConstraintInterface {export class VolumeSpecDto {/*** The volume's server-assigned id or its name - the server resolves either.+ * This includes Filestore volumes: they are Volume rows like any other+ * (their `instance` column names the NFS instance holding the data+ * directory), and they are referenced exactly like bucket-backed ones.** IsNotEmpty (not just IsString) so an explicit `managed_volume: ''` is a* validation error on its own rather than reaching the mapper as a lookup@@ -205,9 +208,9 @@ export class VolumeSpecDto {guest_path: string/**- * Read-only managed mounts are not implemented yet. Rejected rather than- * silently downgraded to read-write, which would hand the caller a writable- * mount they believe is protected.+ * Read-only mounts are not implemented yet. Rejected rather than silently+ * downgraded to read-write, which would hand the caller a writable mount+ * they believe is protected.*/@ValidateIf((_, value) => value !== undefined)@IsIn([false])diff --git a/apps/api/src/boxlite-rest/mappers/box-to-box.mapper.ts b/apps/api/src/boxlite-rest/mappers/box-to-box.mapper.tsindex 7e2c696ee..72ce14f33 100644--- a/apps/api/src/boxlite-rest/mappers/box-to-box.mapper.ts+++ b/apps/api/src/boxlite-rest/mappers/box-to-box.mapper.ts@@ -64,7 +64,8 @@ export function createBoxToCreateBox(dto: RestCreateBoxDto, target?: string): CrcreateDto.autoResume = dto.auto_resumecreateDto.volumes = dto.volumes?.map((volume) => ({// `volumeId` is the internal DTO's name for what the volume service looks- // up by id *or* by name (see VolumeService.validateVolumes).+ // up by id *or* by name (see VolumeService.validateVolumes). Filestore+ // volumes are Volume rows like any other and resolve the same way.volumeId: volume.managed_volume,mountPath: volume.guest_path,}))diff --git a/apps/api/src/common/utils/activity-mutation-events.spec.ts b/apps/api/src/common/utils/activity-mutation-events.spec.tsindex b92b2c82d..88526c9a2 100644--- a/apps/api/src/common/utils/activity-mutation-events.spec.ts+++ b/apps/api/src/common/utils/activity-mutation-events.spec.ts@@ -45,6 +45,7 @@ describe('Activity business events for mutations', () => {{ assertOrganizationIsNotSuspended: jest.fn() } as never,{ get: () => 'gcs' } as never,{} as never,+ {} as never,)return { repository, query, service }}diff --git a/apps/api/src/config/filestore-instances.ts b/apps/api/src/config/filestore-instances.tsindex 43758e6c7..63f3cfb8a 100644--- a/apps/api/src/config/filestore-instances.ts+++ b/apps/api/src/config/filestore-instances.ts@@ -6,6 +6,7 @@ import {type FilestoreInstanceConfig,} from '../../../shared/filestore-instances'+export { FILESTORE_INSTANCE_NAME_PATTERN } from '../../../shared/filestore-instances'export type { FilestoreInstanceConfig }export interface FilestoreInstancesConfig {diff --git a/apps/api/src/migrations/pre-deploy/1792000000000-volume-instance-column-migration.spec.ts b/apps/api/src/migrations/pre-deploy/1792000000000-volume-instance-column-migration.spec.tsnew file mode 100644index 000000000..eceeaebe0--- /dev/null+++ b/apps/api/src/migrations/pre-deploy/1792000000000-volume-instance-column-migration.spec.ts@@ -0,0 +1,16 @@+import { QueryRunner } from 'typeorm'+import { VolumeInstanceColumn1792000000000 } from './1792000000000-volume-instance-column-migration'++describe('VolumeInstanceColumn1792000000000', () => {+ it('adds the instance column idempotently', async () => {+ const calls: string[] = []+ const runner = { query: jest.fn((sql: string) => calls.push(sql)) } as unknown as QueryRunner++ const migration = new VolumeInstanceColumn1792000000000()+ await migration.up(runner)+ await migration.up(runner)++ expect(calls).toContain(`ALTER TABLE "volume" ADD COLUMN IF NOT EXISTS "instance" character varying`)+ expect(calls.filter((sql) => sql.includes('ADD COLUMN'))).toHaveLength(2)+ })+})diff --git a/apps/api/src/migrations/pre-deploy/1792000000000-volume-instance-column-migration.ts b/apps/api/src/migrations/pre-deploy/1792000000000-volume-instance-column-migration.tsnew file mode 100644index 000000000..eb32cef0c--- /dev/null+++ b/apps/api/src/migrations/pre-deploy/1792000000000-volume-instance-column-migration.ts@@ -0,0 +1,18 @@+import { MigrationInterface, QueryRunner } from 'typeorm'++// Adds the filestore-volume support column. A volume row with a non-null+// `instance` is a filestore volume (its data directory lives on that NFS+// instance); null keeps the object-storage kind and its `boxlite-volume-<id>`+// bucket. Branch is unreleased, so no existing row carries a kind and the+// column ships nullable with no backfill.+export class VolumeInstanceColumn1792000000000 implements MigrationInterface {+ name = 'VolumeInstanceColumn1792000000000'++ public async up(queryRunner: QueryRunner): Promise<void> {+ await queryRunner.query(`ALTER TABLE "volume" ADD COLUMN IF NOT EXISTS "instance" character varying`)+ }++ public async down(queryRunner: QueryRunner): Promise<void> {+ await queryRunner.query(`ALTER TABLE "volume" DROP COLUMN IF EXISTS "instance"`)+ }+}diff --git a/apps/infra/docs/gcp/filestore-mount-meta.md b/apps/infra/docs/gcp/filestore-mount-meta.mdnew file mode 100644index 000000000..9ccf5251f--- /dev/null+++ b/apps/infra/docs/gcp/filestore-mount-meta.md@@ -0,0 +1,76 @@+# Runbook: query Filestore mount metadata on a GCP VM++[Infrastructure index](../../README.md)++Use this when a GCE VM has a Filestore share mounted and you need to answer,+quickly and in order: **what is mounted, how it got there, what it points at,+and which GCP instance you are on.** The commands are read-only.++## 1. Confirm what is mounted++```bash+mount | grep -i nfs # source, mountpoint, type (nfs4), and all options+df -h | grep nfs # capacity and usage of the share+```++`mount` is the ground truth for "what is mounted"; `df` adds the capacity line+(the Filestore share advertises its provisioned size — 1.0T for the standard+zonal 1 TiB tier).++## 2. Find how it got there (fstab? or another mechanism)++```bash+grep -i nfs /etc/fstab # often empty on managed hosts — exit code 1 here+ # means "no match", not "error"+```++If fstab is silent, the next place to look is **systemd mount units** — this is+the key jump of the whole runbook:++```bash+systemctl list-units --type=mount | grep mnt # spot the unit name (e.g. mnt-filestore.mount)+ls /etc/systemd/system/ # see the unit files present+```++`systemctl list-units` is what turns "fstab has nothing" into a concrete+answer in one step: the unit name tells you which files to read next.++## 3. Read the configuration for the details++```bash+cat /etc/systemd/system/mnt-filestore.mount # What=/Where=/Type=/Options=, plus Requires= wiring+cat /etc/systemd/system/filestore-route.service # ExecStart= pointing at the route script+cat /usr/local/sbin/filestore-route # the VLAN subinterface logic itself+ip -br addr # confirm filestore0@ens4 exists+```++Typical shape on our hosts: the `.mount` unit declares the NFS target and+`Requires=` a companion service that builds a dedicated VLAN subinterface+(`filestore0@ens4`) before the mount is attempted — the route service exists+so the mount has a path to the Filestore's network. Read all three files; the+`.mount` unit alone does not show the network preparation.++## 4. GCP instance metadata (from inside the VM)++GCE exposes a metadata server to every VM at **169.254.169.254**+(`metadata.google.internal` is its resolvable name). Inside the machine the+queries need **no credentials**: they are authenticated by the network+location itself, provided the instance's service account has the default+access scopes (the default access mode covers read-only metadata).++```bash+curl -H "Metadata-Flavor: Google" http://metadata.google.internal/computeMetadata/v1/instance/name+curl -H "Metadata-Flavor: Google" http://metadata.google.internal/computeMetadata/v1/instance/id+curl -H "Metadata-Flavor: Google" http://metadata.google.internal/computeMetadata/v1/instance/machine-type+curl -H "Metadata-Flavor: Google" http://metadata.google.internal/computeMetadata/v1/project/project-id+```++Use these to correlate the VM you are on with the GCP console: instance name+and numeric id identify it in the console, machine-type tells you the shape,+project-id confirms which project you are operating on.++---++Read-only end to end: nothing here changes mount state or instance state; the+curl calls are authenticated by the metadata server by virtue of running+inside the VM.diff --git a/apps/libs/api-client-go/.openapi-generator/FILES b/apps/libs/api-client-go/.openapi-generator/FILESindex 56690a3f8..4f2f33d88 100644--- a/apps/libs/api-client-go/.openapi-generator/FILES+++ b/apps/libs/api-client-go/.openapi-generator/FILES@@ -71,6 +71,7 @@ model_box_progress.gomodel_box_progress_phase.gomodel_box_state.gomodel_box_volume.go+model_box_volume_filestore_ref.gomodel_boxlite_configuration.gomodel_cpu_incident_list_dto.gomodel_create_api_key.godiff --git a/apps/libs/api-client-go/api/openapi.yaml b/apps/libs/api-client-go/api/openapi.yamlindex 517f8680d..0f3cab17f 100644--- a/apps/libs/api-client-go/api/openapi.yaml+++ b/apps/libs/api-client-go/api/openapi.yaml@@ -6002,20 +6002,35 @@ components:- stopped- resizedtype: string+ BoxVolumeFilestoreRef:+ properties:+ instance:+ description: Filestore instance logical name selected from the API configuration+ example: boxlite-dev-shared+ type: string+ required:+ - instance+ type: objectBoxVolume:example:volumeId: volume123mountPath: /data+ filestore: ""subpath: users/aliceproperties:volumeId:- description: The ID of the volume+ description: The ID of the volume (bucket-backed or Filestore-backed)example: volume123type: stringmountPath:description: The mount path for the volumeexample: /datatype: string+ filestore:+ allOf:+ - $ref: "#/components/schemas/BoxVolumeFilestoreRef"+ description: The Filestore instance reference; absent for bucket-backed+ volumessubpath:description: "Optional subpath within the volume to mount. When specified,\\ only this S3 prefix will be accessible. When omitted, the entire volume\@@ -6075,9 +6090,11 @@ components:volumes:- volumeId: volume123mountPath: /data+ filestore: ""subpath: users/alice- volumeId: volume123mountPath: /data+ filestore: ""subpath: users/alicecreatedAt: 2024-10-01T12:00:00ZupdatedAt: 2024-10-01T12:00:00Z@@ -6273,9 +6290,11 @@ components:volumes:- volumeId: volume123mountPath: /data+ filestore: ""subpath: users/alice- volumeId: volume123mountPath: /data+ filestore: ""subpath: users/alicecreatedAt: 2024-10-01T12:00:00ZupdatedAt: 2024-10-01T12:00:00Z@@ -6311,9 +6330,11 @@ components:volumes:- volumeId: volume123mountPath: /data+ filestore: ""subpath: users/alice- volumeId: volume123mountPath: /data+ filestore: ""subpath: users/alicecreatedAt: 2024-10-01T12:00:00ZupdatedAt: 2024-10-01T12:00:00Z@@ -6998,6 +7019,8 @@ components:name: my-volumeorganizationId: 123e4567-e89b-12d3-a456-426614174000state: ready+ storageBackend: standard+ instance: boxlite-dev-sharedcreatedAt: 2023-01-01T00:00:00.000ZupdatedAt: 2023-01-01T00:00:00.000ZlastUsedAt: 2023-01-01T00:00:00.000Z@@ -7020,6 +7043,17 @@ components:- $ref: "#/components/schemas/VolumeState"description: Volume stateexample: ready+ storageBackend:+ description: The storage class of the volume+ enum:+ - standard+ - performance+ example: standard+ type: string+ instance:+ description: Filestore instance name; filestore volumes only+ example: boxlite-dev-shared+ type: stringcreatedAt:description: Creation timestampexample: 2023-01-01T00:00:00.000Z@@ -7045,15 +7079,30 @@ components:- name- organizationId- state+ - storageBackend- updatedAttype: objectCreateVolume:example:name: my-data+ storageBackend: performance+ instance: boxlite-dev-sharedproperties:name:example: my-datatype: string+ storageBackend:+ description: The storage class of the volume; defaults to standard+ enum:+ - standard+ - performance+ example: performance+ type: string+ instance:+ description: The Filestore instance the volume stores its data on; filestore+ volumes only. Omit to assign from configured instances.+ example: boxlite-dev-shared+ type: stringtype: objectJobStatus:enum:diff --git a/apps/libs/api-client-go/model_box_volume.go b/apps/libs/api-client-go/model_box_volume.goindex e6614751d..dda2f320a 100644--- a/apps/libs/api-client-go/model_box_volume.go+++ b/apps/libs/api-client-go/model_box_volume.go@@ -21,10 +21,12 @@ var _ MappedNullable = &BoxVolume{}// BoxVolume struct for BoxVolumetype BoxVolume struct {- // The ID of the volume+ // The ID of the volume (bucket-backed or Filestore-backed)VolumeId string `json:"volumeId"`// The mount path for the volumeMountPath string `json:"mountPath"`+ // The Filestore instance reference; absent for bucket-backed volumes+ Filestore *BoxVolumeFilestoreRef `json:"filestore,omitempty"`// Optional subpath within the volume to mount. When specified, only this S3 prefix will be accessible. When omitted, the entire volume is mounted.Subpath *string `json:"subpath,omitempty"`AdditionalProperties map[string]interface{}@@ -99,6 +101,38 @@ func (o *BoxVolume) SetMountPath(v string) {o.MountPath = v}+// GetFilestore returns the Filestore field value if set, zero value otherwise.+func (o *BoxVolume) GetFilestore() BoxVolumeFilestoreRef {+ if o == nil || IsNil(o.Filestore) {+ var ret BoxVolumeFilestoreRef+ return ret+ }+ return *o.Filestore+}++// GetFilestoreOk returns a tuple with the Filestore field value if set, nil otherwise+// and a boolean to check if the value has been set.+func (o *BoxVolume) GetFilestoreOk() (*BoxVolumeFilestoreRef, bool) {+ if o == nil || IsNil(o.Filestore) {+ return nil, false+ }+ return o.Filestore, true+}++// HasFilestore returns a boolean if a field has been set.+func (o *BoxVolume) HasFilestore() bool {+ if o != nil && !IsNil(o.Filestore) {+ return true+ }++ return false+}++// SetFilestore gets a reference to the given BoxVolumeFilestoreRef and assigns it to the Filestore field.+func (o *BoxVolume) SetFilestore(v BoxVolumeFilestoreRef) {+ o.Filestore = &v+}+// GetSubpath returns the Subpath field value if set, zero value otherwise.func (o *BoxVolume) GetSubpath() string {if o == nil || IsNil(o.Subpath) {@@ -143,6 +177,9 @@ func (o BoxVolume) ToMap() (map[string]interface{}, error) {toSerialize := map[string]interface{}{}toSerialize["volumeId"] = o.VolumeIdtoSerialize["mountPath"] = o.MountPath+ if !IsNil(o.Filestore) {+ toSerialize["filestore"] = o.Filestore+ }if !IsNil(o.Subpath) {toSerialize["subpath"] = o.Subpath}@@ -192,6 +229,7 @@ func (o *BoxVolume) UnmarshalJSON(data []byte) (err error) {if err = json.Unmarshal(data, &additionalProperties); err == nil {delete(additionalProperties, "volumeId")delete(additionalProperties, "mountPath")+ delete(additionalProperties, "filestore")delete(additionalProperties, "subpath")o.AdditionalProperties = additionalProperties}diff --git a/apps/libs/api-client-go/model_box_volume_filestore_ref.go b/apps/libs/api-client-go/model_box_volume_filestore_ref.gonew file mode 100644index 000000000..f37e98e98--- /dev/null+++ b/apps/libs/api-client-go/model_box_volume_filestore_ref.go@@ -0,0 +1,170 @@+/*+BoxLite++BoxLite AI platform API Docs++API version: 1.0+Contact: [email protected]+*/++// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT.++package apiclient++import (+ "encoding/json"+ "fmt"+)++// checks if the BoxVolumeFilestoreRef type satisfies the MappedNullable interface at compile time+var _ MappedNullable = &BoxVolumeFilestoreRef{}++// BoxVolumeFilestoreRef struct for BoxVolumeFilestoreRef+type BoxVolumeFilestoreRef struct {+ // Filestore instance logical name selected from the API configuration+ Instance string `json:"instance"`+ AdditionalProperties map[string]interface{}+}++type _BoxVolumeFilestoreRef BoxVolumeFilestoreRef++// NewBoxVolumeFilestoreRef instantiates a new BoxVolumeFilestoreRef object+// This constructor will assign default values to properties that have it defined,+// and makes sure properties required by API are set, but the set of arguments+// will change when the set of required properties is changed+func NewBoxVolumeFilestoreRef(instance string) *BoxVolumeFilestoreRef {+ this := BoxVolumeFilestoreRef{}+ this.Instance = instance+ return &this+}++// NewBoxVolumeFilestoreRefWithDefaults instantiates a new BoxVolumeFilestoreRef object+// This constructor will only assign default values to properties that have it defined,+// but it doesn't guarantee that properties required by API are set+func NewBoxVolumeFilestoreRefWithDefaults() *BoxVolumeFilestoreRef {+ this := BoxVolumeFilestoreRef{}+ return &this+}++// GetInstance returns the Instance field value+func (o *BoxVolumeFilestoreRef) GetInstance() string {+ if o == nil {+ var ret string+ return ret+ }++ return o.Instance+}++// GetInstanceOk returns a tuple with the Instance field value+// and a boolean to check if the value has been set.+func (o *BoxVolumeFilestoreRef) GetInstanceOk() (*string, bool) {+ if o == nil {+ return nil, false+ }+ return &o.Instance, true+}++// SetInstance sets field value+func (o *BoxVolumeFilestoreRef) SetInstance(v string) {+ o.Instance = v+}++func (o BoxVolumeFilestoreRef) MarshalJSON() ([]byte, error) {+ toSerialize,err := o.ToMap()+ if err != nil {+ return []byte{}, err+ }+ return json.Marshal(toSerialize)+}++func (o BoxVolumeFilestoreRef) ToMap() (map[string]interface{}, error) {+ toSerialize := map[string]interface{}{}+ toSerialize["instance"] = o.Instance++ for key, value := range o.AdditionalProperties {+ toSerialize[key] = value+ }++ return toSerialize, nil+}++func (o *BoxVolumeFilestoreRef) UnmarshalJSON(data []byte) (err error) {+ // This validates that all required properties are included in the JSON object+ // by unmarshalling the object into a generic map with string keys and checking+ // that every required field exists as a key in the generic map.+ requiredProperties := []string{+ "instance",+ }++ allProperties := make(map[string]interface{})++ err = json.Unmarshal(data, &allProperties)++ if err != nil {+ return err;+ }++ for _, requiredProperty := range(requiredProperties) {+ if _, exists := allProperties[requiredProperty]; !exists {+ return fmt.Errorf("no value given for required property %v", requiredProperty)+ }+ }++ varBoxVolumeFilestoreRef := _BoxVolumeFilestoreRef{}++ err = json.Unmarshal(data, &varBoxVolumeFilestoreRef)++ if err != nil {+ return err+ }++ *o = BoxVolumeFilestoreRef(varBoxVolumeFilestoreRef)++ additionalProperties := make(map[string]interface{})++ if err = json.Unmarshal(data, &additionalProperties); err == nil {+ delete(additionalProperties, "instance")+ o.AdditionalProperties = additionalProperties+ }++ return err+}++type NullableBoxVolumeFilestoreRef struct {+ value *BoxVolumeFilestoreRef+ isSet bool+}++func (v NullableBoxVolumeFilestoreRef) Get() *BoxVolumeFilestoreRef {+ return v.value+}++func (v *NullableBoxVolumeFilestoreRef) Set(val *BoxVolumeFilestoreRef) {+ v.value = val+ v.isSet = true+}++func (v NullableBoxVolumeFilestoreRef) IsSet() bool {+ return v.isSet+}++func (v *NullableBoxVolumeFilestoreRef) Unset() {+ v.value = nil+ v.isSet = false+}++func NewNullableBoxVolumeFilestoreRef(val *BoxVolumeFilestoreRef) *NullableBoxVolumeFilestoreRef {+ return &NullableBoxVolumeFilestoreRef{value: val, isSet: true}+}++func (v NullableBoxVolumeFilestoreRef) MarshalJSON() ([]byte, error) {+ return json.Marshal(v.value)+}++func (v *NullableBoxVolumeFilestoreRef) UnmarshalJSON(src []byte) error {+ v.isSet = true+ return json.Unmarshal(src, &v.value)+}++diff --git a/apps/libs/api-client-go/model_create_volume.go b/apps/libs/api-client-go/model_create_volume.goindex 7bf66309f..941c797db 100644--- a/apps/libs/api-client-go/model_create_volume.go+++ b/apps/libs/api-client-go/model_create_volume.go@@ -21,6 +21,10 @@ var _ MappedNullable = &CreateVolume{}// CreateVolume struct for CreateVolumetype CreateVolume struct {Name *string `json:"name,omitempty"`+ // The storage class of the volume; defaults to standard+ StorageBackend *string `json:"storageBackend,omitempty"`+ // The Filestore instance the volume stores its data on; filestore volumes only. Omit to assign from configured instances.+ Instance *string `json:"instance,omitempty"`AdditionalProperties map[string]interface{}}@@ -75,6 +79,70 @@ func (o *CreateVolume) SetName(v string) {o.Name = &v}+// GetStorageBackend returns the StorageBackend field value if set, zero value otherwise.+func (o *CreateVolume) GetStorageBackend() string {+ if o == nil || IsNil(o.StorageBackend) {+ var ret string+ return ret+ }+ return *o.StorageBackend+}++// GetStorageBackendOk returns a tuple with the StorageBackend field value if set, nil otherwise+// and a boolean to check if the value has been set.+func (o *CreateVolume) GetStorageBackendOk() (*string, bool) {+ if o == nil || IsNil(o.StorageBackend) {+ return nil, false+ }+ return o.StorageBackend, true+}++// HasStorageBackend returns a boolean if a field has been set.+func (o *CreateVolume) HasStorageBackend() bool {+ if o != nil && !IsNil(o.StorageBackend) {+ return true+ }++ return false+}++// SetStorageBackend gets a reference to the given string and assigns it to the StorageBackend field.+func (o *CreateVolume) SetStorageBackend(v string) {+ o.StorageBackend = &v+}++// GetInstance returns the Instance field value if set, zero value otherwise.+func (o *CreateVolume) GetInstance() string {+ if o == nil || IsNil(o.Instance) {+ var ret string+ return ret+ }+ return *o.Instance+}++// GetInstanceOk returns a tuple with the Instance field value if set, nil otherwise+// and a boolean to check if the value has been set.+func (o *CreateVolume) GetInstanceOk() (*string, bool) {+ if o == nil || IsNil(o.Instance) {+ return nil, false+ }+ return o.Instance, true+}++// HasInstance returns a boolean if a field has been set.+func (o *CreateVolume) HasInstance() bool {+ if o != nil && !IsNil(o.Instance) {+ return true+ }++ return false+}++// SetInstance gets a reference to the given string and assigns it to the Instance field.+func (o *CreateVolume) SetInstance(v string) {+ o.Instance = &v+}+func (o CreateVolume) MarshalJSON() ([]byte, error) {toSerialize,err := o.ToMap()if err != nil {@@ -88,6 +156,12 @@ func (o CreateVolume) ToMap() (map[string]interface{}, error) {if !IsNil(o.Name) {toSerialize["name"] = o.Name}+ if !IsNil(o.StorageBackend) {+ toSerialize["storageBackend"] = o.StorageBackend+ }+ if !IsNil(o.Instance) {+ toSerialize["instance"] = o.Instance+ }for key, value := range o.AdditionalProperties {toSerialize[key] = value@@ -111,6 +185,8 @@ func (o *CreateVolume) UnmarshalJSON(data []byte) (err error) {if err = json.Unmarshal(data, &additionalProperties); err == nil {delete(additionalProperties, "name")+ delete(additionalProperties, "storageBackend")+ delete(additionalProperties, "instance")o.AdditionalProperties = additionalProperties}diff --git a/apps/libs/api-client-go/model_volume_dto.go b/apps/libs/api-client-go/model_volume_dto.goindex ea2e09e63..c936ea7da 100644--- a/apps/libs/api-client-go/model_volume_dto.go+++ b/apps/libs/api-client-go/model_volume_dto.go@@ -29,6 +29,10 @@ type VolumeDto struct {OrganizationId string `json:"organizationId"`// Volume stateState VolumeState `json:"state"`+ // The storage class of the volume+ StorageBackend string `json:"storageBackend"`+ // Filestore instance name; filestore volumes only+ Instance *string `json:"instance,omitempty"`// Creation timestampCreatedAt string `json:"createdAt"`// Last update timestamp@@ -46,12 +50,13 @@ type _VolumeDto VolumeDto// This constructor will assign default values to properties that have it defined,// and makes sure properties required by API are set, but the set of arguments// will change when the set of required properties is changed-func NewVolumeDto(id string, name string, organizationId string, state VolumeState, createdAt string, updatedAt string, errorReason NullableString) *VolumeDto {+func NewVolumeDto(id string, name string, organizationId string, state VolumeState, storageBackend string, createdAt string, updatedAt string, errorReason NullableString) *VolumeDto {this := VolumeDto{}this.Id = idthis.Name = namethis.OrganizationId = organizationIdthis.State = state+ this.StorageBackend = storageBackendthis.CreatedAt = createdAtthis.UpdatedAt = updatedAtthis.ErrorReason = errorReason@@ -162,6 +167,62 @@ func (o *VolumeDto) SetState(v VolumeState) {o.State = v}+// GetStorageBackend returns the StorageBackend field value+func (o *VolumeDto) GetStorageBackend() string {+ if o == nil {+ var ret string+ return ret+ }++ return o.StorageBackend+}++// GetStorageBackendOk returns a tuple with the StorageBackend field value+// and a boolean to check if the value has been set.+func (o *VolumeDto) GetStorageBackendOk() (*string, bool) {+ if o == nil {+ return nil, false+ }+ return &o.StorageBackend, true+}++// SetStorageBackend sets field value+func (o *VolumeDto) SetStorageBackend(v string) {+ o.StorageBackend = v+}++// GetInstance returns the Instance field value if set, zero value otherwise.+func (o *VolumeDto) GetInstance() string {+ if o == nil || IsNil(o.Instance) {+ var ret string+ return ret+ }+ return *o.Instance+}++// GetInstanceOk returns a tuple with the Instance field value if set, nil otherwise+// and a boolean to check if the value has been set.+func (o *VolumeDto) GetInstanceOk() (*string, bool) {+ if o == nil || IsNil(o.Instance) {+ return nil, false+ }+ return o.Instance, true+}++// HasInstance returns a boolean if a field has been set.+func (o *VolumeDto) HasInstance() bool {+ if o != nil && !IsNil(o.Instance) {+ return true+ }++ return false+}++// SetInstance gets a reference to the given string and assigns it to the Instance field.+func (o *VolumeDto) SetInstance(v string) {+ o.Instance = &v+}+// GetCreatedAt returns the CreatedAt field valuefunc (o *VolumeDto) GetCreatedAt() string {if o == nil {@@ -292,6 +353,10 @@ func (o VolumeDto) ToMap() (map[string]interface{}, error) {toSerialize["name"] = o.NametoSerialize["organizationId"] = o.OrganizationIdtoSerialize["state"] = o.State+ toSerialize["storageBackend"] = o.StorageBackend+ if !IsNil(o.Instance) {+ toSerialize["instance"] = o.Instance+ }toSerialize["createdAt"] = o.CreatedAttoSerialize["updatedAt"] = o.UpdatedAtif o.LastUsedAt.IsSet() {@@ -315,6 +380,7 @@ func (o *VolumeDto) UnmarshalJSON(data []byte) (err error) {"name","organizationId","state",+ "storageBackend","createdAt","updatedAt","errorReason",@@ -351,6 +417,8 @@ func (o *VolumeDto) UnmarshalJSON(data []byte) (err error) {delete(additionalProperties, "name")delete(additionalProperties, "organizationId")delete(additionalProperties, "state")+ delete(additionalProperties, "storageBackend")+ delete(additionalProperties, "instance")delete(additionalProperties, "createdAt")delete(additionalProperties, "updatedAt")delete(additionalProperties, "lastUsedAt")diff --git a/apps/libs/api-client/src/.openapi-generator/FILES b/apps/libs/api-client/src/.openapi-generator/FILESindex 90a0910b5..00060c97e 100644--- a/apps/libs/api-client/src/.openapi-generator/FILES+++ b/apps/libs/api-client/src/.openapi-generator/FILES@@ -78,6 +78,7 @@ docs/BoxProgress.mddocs/BoxProgressPhase.mddocs/BoxState.mddocs/BoxVolume.md+docs/BoxVolumeFilestoreRef.mddocs/BoxliteConfiguration.mddocs/ConfigApi.mddocs/CpuIncidentListDto.md@@ -230,6 +231,7 @@ models/box-memory-usage-dto.tsmodels/box-progress-phase.tsmodels/box-progress.tsmodels/box-state.ts+models/box-volume-filestore-ref.tsmodels/box-volume.tsmodels/box.tsmodels/boxlite-configuration.tsdiff --git a/apps/libs/api-client/src/docs/BoxVolume.md b/apps/libs/api-client/src/docs/BoxVolume.mdindex 0bd710a11..4260b2ca5 100644--- a/apps/libs/api-client/src/docs/BoxVolume.md+++ b/apps/libs/api-client/src/docs/BoxVolume.md@@ -5,8 +5,9 @@Name | Type | Description | Notes------------ | ------------- | ------------- | --------------**volumeId** | **string** | The ID of the volume | [default to undefined]+**volumeId** | **string** | The ID of the volume (bucket-backed or Filestore-backed) | [default to undefined]**mountPath** | **string** | The mount path for the volume | [default to undefined]+**filestore** | [**BoxVolumeFilestoreRef**](BoxVolumeFilestoreRef.md) | The Filestore instance reference; absent for bucket-backed volumes | [optional] [default to undefined]**subpath** | **string** | Optional subpath within the volume to mount. When specified, only this S3 prefix will be accessible. When omitted, the entire volume is mounted. | [optional] [default to undefined]## Example@@ -17,6 +18,7 @@ import { BoxVolume } from './api';const instance: BoxVolume = {volumeId,mountPath,+ filestore,subpath,};```diff --git a/apps/libs/api-client/src/docs/BoxVolumeFilestoreRef.md b/apps/libs/api-client/src/docs/BoxVolumeFilestoreRef.mdnew file mode 100644index 000000000..bee144900--- /dev/null+++ b/apps/libs/api-client/src/docs/BoxVolumeFilestoreRef.md@@ -0,0 +1,20 @@+# BoxVolumeFilestoreRef+++## Properties++Name | Type | Description | Notes+------------ | ------------- | ------------- | -------------+**instance** | **string** | Filestore instance logical name selected from the API configuration | [default to undefined]++## Example++```typescript+import { BoxVolumeFilestoreRef } from './api';++const instance: BoxVolumeFilestoreRef = {+ instance,+};+```++[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)diff --git a/apps/libs/api-client/src/docs/CreateVolume.md b/apps/libs/api-client/src/docs/CreateVolume.mdindex 70ba90811..4ff870cb2 100644--- a/apps/libs/api-client/src/docs/CreateVolume.md+++ b/apps/libs/api-client/src/docs/CreateVolume.md@@ -6,6 +6,8 @@Name | Type | Description | Notes------------ | ------------- | ------------- | -------------**name** | **string** | | [optional] [default to undefined]+**storageBackend** | **string** | The storage class of the volume; defaults to standard | [optional] [default to undefined]+**instance** | **string** | The Filestore instance the volume stores its data on; filestore volumes only. Omit to assign from configured instances. | [optional] [default to undefined]## Example@@ -14,6 +16,8 @@ import { CreateVolume } from './api';const instance: CreateVolume = {name,+ storageBackend,+ instance,};```diff --git a/apps/libs/api-client/src/docs/VolumeDto.md b/apps/libs/api-client/src/docs/VolumeDto.mdindex 0878e140a..4af237ab0 100644--- a/apps/libs/api-client/src/docs/VolumeDto.md+++ b/apps/libs/api-client/src/docs/VolumeDto.md@@ -9,6 +9,8 @@ Name | Type | Description | Notes**name** | **string** | Volume name | [default to undefined]**organizationId** | **string** | Organization ID | [default to undefined]**state** | [**VolumeState**](VolumeState.md) | Volume state | [default to undefined]+**storageBackend** | **string** | The storage class of the volume | [default to undefined]+**instance** | **string** | Filestore instance name; filestore volumes only | [optional] [default to undefined]**createdAt** | **string** | Creation timestamp | [default to undefined]**updatedAt** | **string** | Last update timestamp | [default to undefined]**lastUsedAt** | **string** | Last used timestamp | [optional] [default to undefined]@@ -24,6 +26,8 @@ const instance: VolumeDto = {name,organizationId,state,+ storageBackend,+ instance,createdAt,updatedAt,lastUsedAt,diff --git a/apps/libs/api-client/src/models/box-volume-filestore-ref.ts b/apps/libs/api-client/src/models/box-volume-filestore-ref.tsnew file mode 100644index 000000000..f1312f083--- /dev/null+++ b/apps/libs/api-client/src/models/box-volume-filestore-ref.ts@@ -0,0 +1,23 @@+/* tslint:disable */+/* eslint-disable */+/**+ * BoxLite+ * BoxLite AI platform API Docs+ *+ * The version of the OpenAPI document: 1.0+ * Contact: [email protected]+ *+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).+ * https://openapi-generator.tech+ * Do not edit the class manually.+ */++++export interface BoxVolumeFilestoreRef {+ /**+ * Filestore instance logical name selected from the API configuration+ */+ 'instance': string;+}+diff --git a/apps/libs/api-client/src/models/box-volume.ts b/apps/libs/api-client/src/models/box-volume.tsindex ee421a7c3..5f3e36c42 100644--- a/apps/libs/api-client/src/models/box-volume.ts+++ b/apps/libs/api-client/src/models/box-volume.ts@@ -13,16 +13,23 @@*/+// May contain unused imports in some cases+// @ts-ignore+import type { BoxVolumeFilestoreRef } from './box-volume-filestore-ref';export interface BoxVolume {/**- * The ID of the volume+ * The ID of the volume (bucket-backed or Filestore-backed)*/'volumeId': string;/*** The mount path for the volume*/'mountPath': string;+ /**+ * The Filestore instance reference; absent for bucket-backed volumes+ */+ 'filestore'?: BoxVolumeFilestoreRef;/*** Optional subpath within the volume to mount. When specified, only this S3 prefix will be accessible. When omitted, the entire volume is mounted.*/diff --git a/apps/libs/api-client/src/models/create-volume.ts b/apps/libs/api-client/src/models/create-volume.tsindex aaf0aca01..917cb5235 100644--- a/apps/libs/api-client/src/models/create-volume.ts+++ b/apps/libs/api-client/src/models/create-volume.ts@@ -16,5 +16,22 @@export interface CreateVolume {'name'?: string;+ /**+ * The storage class of the volume; defaults to standard+ */+ 'storageBackend'?: CreateVolumeStorageBackendEnum;+ /**+ * The Filestore instance the volume stores its data on; filestore volumes only. Omit to assign from configured instances.+ */+ 'instance'?: string;}+export const CreateVolumeStorageBackendEnum = {+ STANDARD: 'standard',+ PERFORMANCE: 'performance',+ UNKNOWN_DEFAULT_OPEN_API: '11184809',+} as const;++export type CreateVolumeStorageBackendEnum = typeof CreateVolumeStorageBackendEnum[keyof typeof CreateVolumeStorageBackendEnum];++diff --git a/apps/libs/api-client/src/models/index.ts b/apps/libs/api-client/src/models/index.tsindex 448d68b12..725ca8b6e 100644--- a/apps/libs/api-client/src/models/index.ts+++ b/apps/libs/api-client/src/models/index.ts@@ -48,6 +48,7 @@ export * from './box-progress';export * from './box-progress-phase';export * from './box-state';export * from './box-volume';+export * from './box-volume-filestore-ref';export * from './boxlite-configuration';export * from './cpu-incident-list-dto';export * from './create-api-key';diff --git a/apps/libs/api-client/src/models/volume-dto.ts b/apps/libs/api-client/src/models/volume-dto.tsindex d7b3dc620..1d77423e2 100644--- a/apps/libs/api-client/src/models/volume-dto.ts+++ b/apps/libs/api-client/src/models/volume-dto.ts@@ -34,6 +34,14 @@ export interface VolumeDto {* Volume state*/'state': VolumeState;+ /**+ * The storage class of the volume+ */+ 'storageBackend': VolumeDtoStorageBackendEnum;+ /**+ * Filestore instance name; filestore volumes only+ */+ 'instance'?: string;/*** Creation timestamp*/@@ -52,5 +60,12 @@ export interface VolumeDto {'errorReason': string | null;}+export const VolumeDtoStorageBackendEnum = {+ STANDARD: 'standard',+ PERFORMANCE: 'performance',+ UNKNOWN_DEFAULT_OPEN_API: '11184809',+} as const;++export type VolumeDtoStorageBackendEnum = typeof VolumeDtoStorageBackendEnum[keyof typeof VolumeDtoStorageBackendEnum];diff --git a/apps/runner/README.md b/apps/runner/README.mdindex 82ebb2c39..c8bae1c2b 100644--- a/apps/runner/README.md+++ b/apps/runner/README.md@@ -561,38 +561,51 @@ the counters maintained in `pkg/common/` (operation counts, etc.).----## GCP Filestore mount engine--The runner's internal volume DTO accepts a Filestore reference alongside the-volume ID and guest mount path:--```json-{- "volumeId": "09f81aef-69a3-488b-b872-e193831549f3",- "mountPath": "/data",- "filestore": {- "instance": "boxlite-filestore-stage",- "server": "10.20.24.2",- "export": "/vol1"- }-}+## GCP Filestore volumes++A box mounts a **Filestore volume** — a Volume row whose data directory lives+on a Filestore NFS instance, created through the volume API with+`storageBackend: "performance"` and an optional `instance` field. It is mounted+by the same `managed_volume` selector as bucket-backed volumes. The reference+carries the instance's **logical name**; the API resolves the address from GCP+Filestore and dispatches it to the runner with the mount, so recreating an+instance under the same name reuses the same logical identity without a change+to historical boxes.++### Instance configuration (API side)++`FILESTORE_INSTANCES` is an environment variable of the **API** deployment —+a JSON object list declaring which GCP Filestore instances a create may+auto-assign to or a mount dispatch may resolve to:++```bash+FILESTORE_INSTANCES='[{"instance":"boxlite-filestore-stage","project_id":"boxlite-dev-project","zone":"us-east4-a"}]'```+Validation runs when the API starts: invalid JSON, a duplicate instance, a name+outside `^[a-z](?:[a-z0-9-]{0,61}[a-z0-9])?$`, or invalid project/zone values refuse to+start the API. Until removed, an unset variable temporarily defaults to+`boxlite-dev-shared` in `boxlite-dev-project`, zone `us-east5-a`; stage deployments+instead default to `boxlite-filestore-stage`, zone `us-east4-a`. An explicit+empty value disables Filestore. A volume create naming an instance outside the+list fails loudly; the runner configures no instances of its own and mounts the+resolved target the dispatch carries.+`instance` is the logical mount identity, while `server` and `export` identifythe NFS target. The runner validates all three on every reference beforeper-call mount deduplication, requires one target per instance within a request,-and rejects Filestore `subpath` instead of silently ignoring it. Public Volume-provisioning and control-plane admission are outside this runner-only slice.+and rejects Filestore `subpath` instead of silently ignoring it.-### Mount and record lifecycle+### How it mounts- One NFSv4.1 mount per instance is shared by every box referencing it. Therunner creates it on demand and reclaims it when no box record references it.An existing mount is reused only after `findmnt` confirms NFSv4 and the exact`server:export` source; a different target fails with a mount mismatch.- A box binds to `/mnt/boxlite-filestore-<instance>/<volume_id>`. The directory- is named by volume ID, so boxes sharing a volume share data. Destroy removes- the box reference, not the volume data.+ is named by volume ID, so boxes sharing a volume share data. It is created+ with `chmod 0777` — NFS permissions are real, unlike the FUSE backends'+ faked ones.- Per-instance mutexes serialize mount, record, and reclaim decisions. Createrolls back records written before a later volume or final record write fails.After a successful record rollback, it immediately reclaims any resulting@@ -610,8 +623,51 @@ provisioning and control-plane admission are outside this runner-only slice.- Prepare failures return `FILESTORE_VOLUME_PREPARE_FAILED` with box, volume,and instance IDs plus the mount error. Logs do not include box environmentvariables, secrets, authorization headers, or job payloads.--### Troubleshooting and prerequisites+- Destroy unbinds only: the data directory and its data survive, exactly as a+ bucket survives a destroy — reachable again through the volume id. A stopped+ Filestore Box waiting for a restart can be deleted without resolving its+ configured instance; deletion cancels the waiting start intent and proceeds+ with runner cleanup without removing the NFS data.+- Volume removal follows the same async path as bucket volumes — in-use+ refusal, then PENDING_DELETE until the manager lands the row DELETED (the+ name is released by the same `name-deleted` rename). The NFS data+ directory itself is left in place for ops cleanup.++### Runner/API version skew++The runner declares `capabilities: ["filestore"]` in its healthcheck; the API+persists the declaration on the runner row and refuses (loudly, at dispatch)+to hand a filestore volume to a v2 runner that has not declared it. A runner+binary predating capability reporting declares nothing, so during a rolling+upgrade a filestore volume can only land on an upgraded runner. Upgrade order+that keeps filestore creates working: runners first, API second — an upgraded+runner with the old API is idle for filestore (the old API never creates+filestore volumes), while the reverse order would put filestore creates on+runners the API does not yet trust. Before replaying start metadata, an upgraded+runner also checks the Box's persisted mount record. If an old API replica omits+the Filestore reference, Start fails with `FILESTORE_VOLUME_REFERENCE_MISSING`+before trying the object-storage fallback or starting the Box. An unreadable+mount record fails with `FILESTORE_VOLUME_RECORD_UNREADABLE` instead of guessing+that the Box has no Filestore mounts. This guard uses only the local record, not+a GCP lookup or a rollout feature flag. Rolling back+the runner to a binary without Filestore support remains unsupported while+Filestore Boxes exist. The dispatch check re-reads the runner row instead of+trusting an API replica's lookup cache. A rejection logs the Box ID,+runner ID, runner version, declared capabilities and+`FILESTORE_CAPABILITY_MISSING`; the create response carries the reason, Box ID+and `BOX_STATE_TRANSITION_FAILED`, which the Dashboard displays with the HTTP+status. The reason also reports whether the runner row exists, its state,+protocol and binary versions, observed capabilities, last healthcheck time and+age, and confirms that no create job was dispatched. A runner-side prepare+failure adds `FILESTORE_VOLUME_PREPARE_FAILED`,+Box/Volume/instance IDs and, when available, the mount process exit code. API+job-insert failures similarly log `job.create.failed` with the job, runner,+resource and database error code. Final reconciliation failures log+`box.sync.failed` with the Box ID, error name and database code. Both events+omit the raw database error, so logs do not include Box environment variables,+secrets, authorization headers, SQL parameters or job payloads.++### TroubleshootingStart returns Filestore preparation errors, including target mismatches, beforestarting the box, and the `START_BOX` job reports that failure. Object-storage-@@ -622,10 +678,22 @@ empty guest directory; stop it, restore connectivity, and start it again. NFSIf a later request resolves the same logical instance to another server orexport, the runner rejects the target mismatch instead of binding the old share.-Unmount the stale path or reboot the host before retrying. The host needs an NFS-client (`nfs-utils` on RHEL-family or `nfs-common` on Debian-family), util-linux-for `mountpoint` and `findmnt`, NFSv4.1 support, and network access to port 2049-on the Filestore instance.+Unmount the stale path or reboot the host before retrying.++### Ops prerequisites++- Filestore instance: zonal, NFSv4.1, 1 TiB minimum, same VPC as the runner,+ port 2049 open. Capacity exhaustion shows up in the box as ENOSPC.+- Host: NFS client package (`nfs-utils` on RHEL-family, `nfs-common` on+ Debian-family) and util-linux for `mountpoint` and `findmnt`. No autofs; the+ runner mounts explicitly. The cloud boot script+ ([`runner-boot.ts`](../infra/mdeploy/stack/runner-boot.ts)) installs+ `nfs-common` on fresh hosts automatically. GCP deployments also declare the+ package through OS Config, so existing runner hosts converge without SSH or+ a rerun of the boot script.+- **Deploy order: runners before the API.** The capability check refuses an+ old runner before dispatch. An API older than its runners simply dispatches+ no filestore volumes at all, which is harmless.## Background servicesdiff --git a/apps/runner/pkg/boxlite/volumes.go b/apps/runner/pkg/boxlite/volumes.goindex 6e27c2755..f47ab8929 100644--- a/apps/runner/pkg/boxlite/volumes.go+++ b/apps/runner/pkg/boxlite/volumes.go@@ -349,19 +349,42 @@ func isFilestoreVolumePreparationError(err error) bool {return errors.As(err, &target)}+func (c *Client) rejectRecordedFilestoreFallback(boxID string) error {+ record, err := c.readBoxVolumeMountRecord(boxID)+ if err != nil {+ return &filestoreVolumePreparationError{err: fmt.Errorf(+ "FILESTORE_VOLUME_RECORD_UNREADABLE: box %s volume mount record could not be read: %w",+ boxID,+ err,+ )}+ }+ for _, entry := range record.Entries {+ if entry.Backend == volumeBackendFilestore {+ return &filestoreVolumePreparationError{err: fmt.Errorf(+ "FILESTORE_VOLUME_REFERENCE_MISSING: box %s has a recorded Filestore mount but start metadata has no Filestore reference",+ boxID,+ )}+ }+ }+ return nil+}+func (c *Client) ensureVolumeMountsFromMetadata(ctx context.Context, boxID string, metadata map[string]string) error {if metadata == nil {return nil}-volumesJSON, ok := metadata["volumes"]if !ok {return nil}-var volumes []dto.VolumeDTOif err := json.Unmarshal([]byte(volumesJSON), &volumes); err != nil {- return nil+ volumes = nil+ }+ if !hasFilestoreRef(volumes) {+ if err := c.rejectRecordedFilestoreFallback(boxID); err != nil {+ return err+ }}if len(volumes) == 0 {return nildiff --git a/apps/runner/pkg/boxlite/volumes_filestore_test.go b/apps/runner/pkg/boxlite/volumes_filestore_test.goindex e5e7b49c5..b91bf208e 100644--- a/apps/runner/pkg/boxlite/volumes_filestore_test.go+++ b/apps/runner/pkg/boxlite/volumes_filestore_test.go@@ -1451,6 +1451,73 @@ func TestStartReturnsFilestorePreparationFailureBeforeBoxLookup(t *testing.T) {}}+func TestStartRejectsRecordedFilestoreWithoutReference(t *testing.T) {+ useVolumeMountBasePath(t, t.TempDir())+ var nativeCalls atomic.Int32+ c := checkpointRESTClient(t, func(w http.ResponseWriter, _ *http.Request) {+ nativeCalls.Add(1)+ http.Error(w, "native box lookup reached", http.StatusInternalServerError)+ })+ if err := c.recordBoxVolumeMounts(context.Background(), "abc123def456", []volumeMount{{+ rootPath: filepath.Join(getVolumeMountBasePath(), filestoreMountPrefix+"ml-scratch"),+ dataDir: filestoreDataDir(filepath.Join(getVolumeMountBasePath(), filestoreMountPrefix+"ml-scratch"), "vol-a"),+ backend: volumeBackendFilestore,+ filestoreInstance: "ml-scratch",+ }}); err != nil {+ t.Fatalf("recordBoxVolumeMounts failed: %v", err)+ }+ c.testProbeRunner = func(context.Context, string) (bool, error) {+ return false, errors.New("object-storage fallback must not run")+ }+ metadata := map[string]string{+ "volumes": `[{"volumeId":"vol-a","mountPath":"/data"}]`,+ }++ _, err := c.Start(context.Background(), "abc123def456", nil, metadata)+ if err == nil || !strings.Contains(err.Error(), "FILESTORE_VOLUME_REFERENCE_MISSING") {+ t.Fatalf("Start returned %v, want a missing Filestore reference error", err)+ }+ if !isFilestoreVolumePreparationError(err) {+ t.Fatalf("Start returned an untyped error: %v", err)+ }+ if got := nativeCalls.Load(); got != 0 {+ t.Fatalf("Start made %d native box calls after the missing Filestore reference", got)+ }+}++func TestStartRejectsUnreadableVolumeMountRecord(t *testing.T) {+ useVolumeMountBasePath(t, t.TempDir())+ var nativeCalls atomic.Int32+ c := checkpointRESTClient(t, func(w http.ResponseWriter, _ *http.Request) {+ nativeCalls.Add(1)+ http.Error(w, "native box lookup reached", http.StatusInternalServerError)+ })+ boxID := "abc123def456"+ if err := os.MkdirAll(getVolumeMountRecordDir(), 0755); err != nil {+ t.Fatalf("create record directory: %v", err)+ }+ if err := os.WriteFile(filepath.Join(getVolumeMountRecordDir(), boxID+".json"), []byte("not-json"), 0600); err != nil {+ t.Fatalf("write malformed record: %v", err)+ }+ c.testProbeRunner = func(context.Context, string) (bool, error) {+ return false, errors.New("object-storage fallback must not run")+ }+ metadata := map[string]string{+ "volumes": `[{"volumeId":"vol-a","mountPath":"/data"}]`,+ }++ _, err := c.Start(context.Background(), boxID, nil, metadata)+ if err == nil || !strings.Contains(err.Error(), "FILESTORE_VOLUME_RECORD_UNREADABLE") {+ t.Fatalf("Start returned %v, want an unreadable volume record error", err)+ }+ if !isFilestoreVolumePreparationError(err) {+ t.Fatalf("Start returned an untyped error: %v", err)+ }+ if got := nativeCalls.Load(); got != 0 {+ t.Fatalf("Start made %d native box calls after the unreadable volume record", got)+ }+}+func TestStartPreservesObjectStorageMountFallback(t *testing.T) {useVolumeMountBasePath(t, t.TempDir())var nativeCalls atomic.Int32diff --git a/openapi/box.openapi.yaml b/openapi/box.openapi.yamlindex 7244c1862..40ca18489 100644--- a/openapi/box.openapi.yaml+++ b/openapi/box.openapi.yaml@@ -2882,6 +2882,13 @@ components:typed_mounts_enabled:type: booleandescription: Whether create-box accepts the typed `mounts` field.+ object_storage_enabled:+ type: boolean+ description: Whether object-storage volume creation is configured+ example: true+ filestore_enabled:+ type: boolean+ description: Whether at least one Filestore instance is configuredexample: trueidempotency_key_lifetime:type: string@@ -3524,7 +3531,10 @@ components:Legacy managed-volume mount. New requests should use `mounts` with`type=volume`; do not send non-empty `volumes` and `mounts` together.Host bind mounts have no representation here because a REST path would- name the server's filesystem.+ name the server's filesystem. This includes Filestore volumes — a volume+ whose data directory lives on a Filestore NFS instance — which are+ created through the volume endpoints and referenced identically by id+ or name.additionalProperties: falserequired: [managed_volume, guest_path]properties:@@ -3564,6 +3574,13 @@ components:description: User-assigned volume namestate:$ref: "#/components/schemas/VolumeState"+ storage_backend:+ type: string+ enum: [standard, performance]+ description: |+ The cloud storage class of the volume, derived from whether+ `instance` is present. Absent for local directory volumes.+ example: performancecreated_at:type: stringformat: date-time@@ -3580,6 +3597,12 @@ components:description: >Best-effort size. Local directory volumes report null rather than scanthe payload synchronously.+ instance:+ type: string+ description: |+ Filestore-only: the NFS instance holding the volume's data+ directory. Absent for object-storage volumes, whose data lives in+ boxlite-volume-<id>.CreateVolumeRequest:type: object@@ -3594,6 +3617,26 @@ components:pattern: "^[a-zA-Z0-9][a-zA-Z0-9_.-]+$"minLength: 2example: my-data+ storageBackend:+ type: string+ enum: [standard, performance]+ default: standard+ description: |+ The storage class of the volume. `standard` stores data in+ `boxlite-volume-<id>`; `performance` stores it in an NFS data+ directory on the selected or automatically assigned Filestore+ instance. This field, not the presence of `instance`, selects the+ storage class.+ instance:+ type: string+ pattern: "^[a-z](?:[a-z0-9-]{0,61}[a-z0-9])?$"+ description: |+ The Filestore instance the volume's data directory lives on.+ Valid only when storageBackend is performance. When omitted, the+ API assigns an instance by hashing its configured names. The+ instance must exist in GCP and in the API's FILESTORE_INSTANCES+ configuration, checked at create and dispatch time.+ example: boxlite-dev-sharedVolume:type: object@@ -3609,6 +3652,13 @@ components:description: User-assigned volume namestate:$ref: "#/components/schemas/VolumeState"+ storage_backend:+ type: string+ enum: [standard, performance]+ description: |+ The cloud storage class of the volume, derived from whether+ `instance` is present. Absent for local directory volumes.+ example: performancecreated_at:type: stringformat: date-time@@ -3631,6 +3681,12 @@ components:description: >Best-effort size. Local directory volumes report null rather than scanthe payload synchronously.+ instance:+ type: string+ description: |+ Filestore-only: the NFS instance holding the volume's data+ directory. Absent for object-storage volumes, whose data lives in+ boxlite-volume-<id>.ListVolumesResponse:type: objectdiff --git a/src/cli/src/commands/serve/mod.rs b/src/cli/src/commands/serve/mod.rsindex 06131ba77..4653264fb 100644--- a/src/cli/src/commands/serve/mod.rs+++ b/src/cli/src/commands/serve/mod.rs@@ -2558,6 +2558,38 @@ mod tests {);}+ #[test]+ fn local_volume_response_satisfies_openapi_contract() {+ let info = boxlite::runtime::types::VolumeInfo {+ id: "018f6f36-7d28-7b28-a2fa-4b5c6d7e8f90".into(),+ name: "workspace".into(),+ created_at: chrono::Utc::now(),+ size_bytes: None,+ };+ let response = serde_json::to_value(volume_info_to_response(&info)).unwrap();+ let spec: serde_yaml::Value = serde_yaml::from_str(+ &std::fs::read_to_string(concat!(+ env!("CARGO_MANIFEST_DIR"),+ "/../../openapi/box.openapi.yaml"+ ))+ .expect("read openapi spec"),+ )+ .expect("parse openapi spec");++ for schema_name in ["Volume", "VolumeSummary"] {+ let required = spec["components"]["schemas"][schema_name]["required"]+ .as_sequence()+ .unwrap();+ for field in required {+ let field = field.as_str().unwrap();+ assert!(+ response.get(field).is_some(),+ "{schema_name} requires `{field}`, but the local response is {response}"+ );+ }+ }+ }+#[test]fn mount_requests_accept_empty_and_reject_invalid_wire_fields() {for volumes in [None, Some(serde_json::json!([]))] {