The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
feat(filestore): add runner NFS mounts and capability reporting (#2722)
Lhfcws0a708588ff40
diff --git a/apps/api/src/box/controllers/runner.controller.privilege.spec.ts b/apps/api/src/box/controllers/runner.controller.privilege.spec.tsindex 03f6a10cd..0fe3920c3 100644--- a/apps/api/src/box/controllers/runner.controller.privilege.spec.ts+++ b/apps/api/src/box/controllers/runner.controller.privilege.spec.ts@@ -31,4 +31,26 @@ describe('RunnerController privilege heartbeat', () => {)},)++ it('forwards reported capabilities to health persistence', async () => {+ const updateRunnerHealth = jest.fn().mockResolvedValue(undefined)+ const controller = Object.create(RunnerController.prototype) as RunnerController+ Object.assign(controller, { runnerService: { updateRunnerHealth } })+ const report = Object.assign(new RunnerHealthcheckDto(), { appVersion: 'dev', capabilities: ['filestore'] })++ await controller.runnerHealthcheck({ runnerId: 'runner-1' } as any, report)++ expect(updateRunnerHealth).toHaveBeenCalledWith(+ 'runner-1',+ undefined,+ undefined,+ undefined,+ undefined,+ undefined,+ 'dev',+ undefined,+ { nestedVirtualizationEnabled: undefined, capabilities: ['filestore'] },+ undefined,+ )+ })})diff --git a/apps/api/src/box/controllers/runner.controller.ts b/apps/api/src/box/controllers/runner.controller.tsindex 2af70e3d9..a0749a641 100644--- a/apps/api/src/box/controllers/runner.controller.ts+++ b/apps/api/src/box/controllers/runner.controller.ts@@ -340,6 +340,7 @@ export class RunnerController {healthcheck.supportsPrivileged,{nestedVirtualizationEnabled: healthcheck.nestedVirtualizationEnabled,+ capabilities: healthcheck.capabilities,},healthcheck.dataDiskRef,)diff --git a/apps/api/src/box/dto/runner-health.dto.ts b/apps/api/src/box/dto/runner-health.dto.tsindex 99b2b254f..0b8d49537 100644--- a/apps/api/src/box/dto/runner-health.dto.ts+++ b/apps/api/src/box/dto/runner-health.dto.ts@@ -169,6 +169,17 @@ export class RunnerHealthcheckDto {@IsBoolean()supportsPrivileged?: boolean+ @ApiPropertyOptional({+ description:+ 'Capabilities the runner binary supports (e.g. "filestore"). Absent from runners predating capability reporting, which the API treats as supporting none of them',+ type: [String],+ example: ['filestore'],+ })+ @ValidateIf((_object, value) => value !== undefined)+ @IsArray()+ @IsString({ each: true })+ capabilities?: string[]+@ApiPropertyOptional({description: 'Runner metrics',type: RunnerHealthMetricsDto,diff --git a/apps/api/src/box/entities/runner.entity.ts b/apps/api/src/box/entities/runner.entity.tsindex 821a62398..8a61c1fe9 100644--- a/apps/api/src/box/entities/runner.entity.ts+++ b/apps/api/src/box/entities/runner.entity.ts@@ -153,6 +153,23 @@ export class Runner {@Column({ default: false })nestedVirtualizationEnabled: boolean+ /**+ * Capabilities the runner binary declared in its latest healthcheck, e.g.+ * `['filestore']`. This exists primarily for backward compatibility during+ * rolling upgrades: null when the binary predates capability reporting, and+ * dispatch then treats the runner as supporting nothing beyond the base+ * protocol, so a pre-filestore v2 runner cannot be handed a filestore+ * volume by mistake. Kept as a jsonb array rather than per-capability+ * boolean columns so new capabilities can be added without a schema+ * migration.+ */+ @Column({+ type: 'jsonb',+ nullable: true,+ default: null,+ })+ capabilities: string[] | null+@Column({nullable: true,type: 'timestamp with time zone',diff --git a/apps/api/src/box/services/runner.service.capabilities.spec.ts b/apps/api/src/box/services/runner.service.capabilities.spec.tsnew file mode 100644index 000000000..b8ffbb9f2--- /dev/null+++ b/apps/api/src/box/services/runner.service.capabilities.spec.ts@@ -0,0 +1,77 @@+/*+ * Copyright 2026 BoxLite AI+ * SPDX-License-Identifier: AGPL-3.0+ */++import { validateSync } from 'class-validator'+import { RunnerService } from './runner.service'+import { RunnerHealthcheckDto } from '../dto/runner-health.dto'+import { RunnerState } from '../enums/runner-state.enum'++describe('Runner capability declarations', () => {+ it.each([[undefined], [['filestore']], [[]]] as [string[] | undefined][])(+ 'persists declaration %p verbatim, absent as null',+ async (capabilities) => {+ const service = Object.create(RunnerService.prototype) as RunnerService+ const write = jest.fn().mockResolvedValue(true)+ Object.assign(service, {+ logger: { debug: jest.fn() },+ findOne: jest.fn().mockResolvedValue({ id: 'runner', state: RunnerState.READY }),+ updateRunnerUnlessDecommissioned: write,+ eventEmitter: { emit: jest.fn() },+ })+ await service.updateRunnerHealth('runner', undefined, undefined, undefined, undefined, undefined, 'dev', false, {+ capabilities,+ })+ expect((service as any).logger.debug).toHaveBeenCalledWith(+ expect.objectContaining({+ event: 'runner.health.persisted',+ runnerId: 'runner',+ appVersion: 'dev',+ capabilities: capabilities ?? [],+ infoFailed: false,+ }),+ 'Runner health persisted',+ )+ expect(write).toHaveBeenCalledWith(+ 'runner',+ expect.objectContaining({+ capabilities: capabilities ?? null,+ }),+ )+ },+ )++ it('does not replace capabilities after an info-read failure', async () => {+ const service = Object.create(RunnerService.prototype) as RunnerService+ const write = jest.fn().mockResolvedValue(true)+ Object.assign(service, {+ logger: { debug: jest.fn() },+ findOne: jest.fn().mockResolvedValue({ id: 'runner', state: RunnerState.READY }),+ updateRunnerUnlessDecommissioned: write,+ eventEmitter: { emit: jest.fn() },+ })+ await service.updateRunnerHealth(+ 'runner',+ undefined,+ undefined,+ undefined,+ undefined,+ undefined,+ undefined,+ undefined,+ { infoFailed: true, capabilities: ['filestore'] },+ )+ expect(write.mock.calls[0][1]).not.toHaveProperty('capabilities')+ })++ it.each([null, 'filestore', 1, ['filestore', 1]])('rejects invalid capabilities %p on the heartbeat boundary', (value) => {+ const dto = Object.assign(new RunnerHealthcheckDto(), {+ appVersion: 'dev',+ capabilities: value,+ })+ expect(validateSync(dto).map((error) => error.property)).toEqual(+ expect.arrayContaining(['capabilities']),+ )+ })+})diff --git a/apps/api/src/box/services/runner.service.ts b/apps/api/src/box/services/runner.service.tsindex 8e61dd7f3..b6b31b9a1 100644--- a/apps/api/src/box/services/runner.service.ts+++ b/apps/api/src/box/services/runner.service.ts@@ -375,6 +375,7 @@ export class RunnerService {signal?: AbortSignalinfoFailed?: booleannestedVirtualizationEnabled?: boolean+ capabilities?: string[]},dataDiskRef?: RunnerDataDiskRef,): Promise<void> {@@ -399,6 +400,11 @@ export class RunnerService {if (!context?.infoFailed) {updateData.supportsPrivileged = supportsPrivileged === trueupdateData.nestedVirtualizationEnabled = context?.nestedVirtualizationEnabled === true+ // The binary's own declaration, not accumulated state: a runner that+ // stops reporting a capability (downgrade, or a binary predating the+ // field) loses it on the next heartbeat, so dispatch can never trust a+ // capability the running binary no longer has.+ updateData.capabilities = context?.capabilities ?? null}if (domain) {@@ -485,7 +491,16 @@ export class RunnerService {if (!(await this.updateRunnerUnlessDecommissioned(runnerId, updateData))) {return}- this.logger.debug(`Updated health for runner ${runnerId}`)+ this.logger.debug(+ {+ event: 'runner.health.persisted',+ runnerId,+ appVersion: appVersion ?? runner.appVersion,+ capabilities: context?.capabilities ?? [],+ infoFailed: context?.infoFailed === true,+ },+ 'Runner health persisted',+ )this.eventEmitter.emit(RunnerEvents.STATE_UPDATED,diff --git a/apps/api/src/migrations/pre-deploy/1794960000000-add-runner-capabilities-migration.ts b/apps/api/src/migrations/pre-deploy/1794960000000-add-runner-capabilities-migration.tsnew file mode 100644index 000000000..b0d7031dc--- /dev/null+++ b/apps/api/src/migrations/pre-deploy/1794960000000-add-runner-capabilities-migration.ts@@ -0,0 +1,16 @@+import { MigrationInterface, QueryRunner } from 'typeorm'++export class AddRunnerCapabilities1794960000000 implements MigrationInterface {+ name = 'AddRunnerCapabilities1794960000000'++ public async up(queryRunner: QueryRunner): Promise<void> {+ // NULL for every existing runner: runners declare their capabilities in+ // the healthcheck, so the column fills as the fleet upgrades, and+ // dispatch treats a runner without the declaration as incapable.+ await queryRunner.query(`ALTER TABLE "runner" ADD "capabilities" jsonb`)+ }++ public async down(queryRunner: QueryRunner): Promise<void> {+ await queryRunner.query(`ALTER TABLE "runner" DROP COLUMN "capabilities"`)+ }+}diff --git a/apps/libs/api-client-go/api/openapi.yaml b/apps/libs/api-client-go/api/openapi.yamlindex 55b41253d..517f8680d 100644--- a/apps/libs/api-client-go/api/openapi.yaml+++ b/apps/libs/api-client-go/api/openapi.yaml@@ -6917,6 +6917,8 @@ components:example:nestedVirtualizationEnabled: truesupportsPrivileged: true+ capabilities:+ - filestoremetrics: ""serviceHealth:- serviceName: runner@@ -6937,6 +6939,15 @@ components:supportsPrivileged:description: Runner preserves the guest privileged creation optiontype: boolean+ capabilities:+ description: "Capabilities the runner binary supports (e.g. \"filestore\"\+ ). Absent from runners predating capability reporting, which the API treats\+ \ as supporting none of them"+ example:+ - filestore+ items:+ type: string+ type: arraymetrics:allOf:- $ref: "#/components/schemas/RunnerHealthMetrics"diff --git a/apps/libs/api-client-go/model_runner_healthcheck.go b/apps/libs/api-client-go/model_runner_healthcheck.goindex 0fd1d64ba..b50bb4164 100644--- a/apps/libs/api-client-go/model_runner_healthcheck.go+++ b/apps/libs/api-client-go/model_runner_healthcheck.go@@ -25,6 +25,8 @@ type RunnerHealthcheck struct {NestedVirtualizationEnabled *bool `json:"nestedVirtualizationEnabled,omitempty"`// Runner preserves the guest privileged creation optionSupportsPrivileged *bool `json:"supportsPrivileged,omitempty"`+ // Capabilities the runner binary supports (e.g. \"filestore\"). Absent from runners predating capability reporting, which the API treats as supporting none of them+ Capabilities []string `json:"capabilities,omitempty"`// Runner metricsMetrics *RunnerHealthMetrics `json:"metrics,omitempty"`// Health status of individual services on the runner@@ -126,6 +128,38 @@ func (o *RunnerHealthcheck) SetSupportsPrivileged(v bool) {o.SupportsPrivileged = &v}+// GetCapabilities returns the Capabilities field value if set, zero value otherwise.+func (o *RunnerHealthcheck) GetCapabilities() []string {+ if o == nil || IsNil(o.Capabilities) {+ var ret []string+ return ret+ }+ return o.Capabilities+}++// GetCapabilitiesOk returns a tuple with the Capabilities field value if set, nil otherwise+// and a boolean to check if the value has been set.+func (o *RunnerHealthcheck) GetCapabilitiesOk() ([]string, bool) {+ if o == nil || IsNil(o.Capabilities) {+ return nil, false+ }+ return o.Capabilities, true+}++// HasCapabilities returns a boolean if a field has been set.+func (o *RunnerHealthcheck) HasCapabilities() bool {+ if o != nil && !IsNil(o.Capabilities) {+ return true+ }++ return false+}++// SetCapabilities gets a reference to the given []string and assigns it to the Capabilities field.+func (o *RunnerHealthcheck) SetCapabilities(v []string) {+ o.Capabilities = v+}+// GetMetrics returns the Metrics field value if set, zero value otherwise.func (o *RunnerHealthcheck) GetMetrics() RunnerHealthMetrics {if o == nil || IsNil(o.Metrics) {@@ -358,6 +392,9 @@ func (o RunnerHealthcheck) ToMap() (map[string]interface{}, error) {if !IsNil(o.SupportsPrivileged) {toSerialize["supportsPrivileged"] = o.SupportsPrivileged}+ if !IsNil(o.Capabilities) {+ toSerialize["capabilities"] = o.Capabilities+ }if !IsNil(o.Metrics) {toSerialize["metrics"] = o.Metrics}@@ -422,6 +459,7 @@ func (o *RunnerHealthcheck) UnmarshalJSON(data []byte) (err error) {if err = json.Unmarshal(data, &additionalProperties); err == nil {delete(additionalProperties, "nestedVirtualizationEnabled")delete(additionalProperties, "supportsPrivileged")+ delete(additionalProperties, "capabilities")delete(additionalProperties, "metrics")delete(additionalProperties, "serviceHealth")delete(additionalProperties, "dataDiskRef")diff --git a/apps/libs/api-client/src/docs/RunnerHealthcheck.md b/apps/libs/api-client/src/docs/RunnerHealthcheck.mdindex b4113c7ff..5a005f1ad 100644--- a/apps/libs/api-client/src/docs/RunnerHealthcheck.md+++ b/apps/libs/api-client/src/docs/RunnerHealthcheck.md@@ -7,6 +7,7 @@ Name | Type | Description | Notes------------ | ------------- | ------------- | -------------**nestedVirtualizationEnabled** | **boolean** | Runner runtime authorizes nested virtualization | [optional] [default to undefined]**supportsPrivileged** | **boolean** | Runner preserves the guest privileged creation option | [optional] [default to undefined]+**capabilities** | **Array<string>** | Capabilities the runner binary supports (e.g. \"filestore\"). Absent from runners predating capability reporting, which the API treats as supporting none of them | [optional] [default to undefined]**metrics** | [**RunnerHealthMetrics**](RunnerHealthMetrics.md) | Runner metrics | [optional] [default to undefined]**serviceHealth** | [**Array<RunnerServiceHealth>**](RunnerServiceHealth.md) | Health status of individual services on the runner | [optional] [default to undefined]**dataDiskRef** | [**RunnerDataDiskRef**](RunnerDataDiskRef.md) | Cloud identity of the runner data disk; absent when the runner has none (AWS or local) | [optional] [default to undefined]@@ -23,6 +24,7 @@ import { RunnerHealthcheck } from './api';const instance: RunnerHealthcheck = {nestedVirtualizationEnabled,supportsPrivileged,+ capabilities,metrics,serviceHealth,dataDiskRef,diff --git a/apps/libs/api-client/src/models/runner-healthcheck.ts b/apps/libs/api-client/src/models/runner-healthcheck.tsindex 3aba4897b..afce29bdb 100644--- a/apps/libs/api-client/src/models/runner-healthcheck.ts+++ b/apps/libs/api-client/src/models/runner-healthcheck.ts@@ -32,6 +32,10 @@ export interface RunnerHealthcheck {* Runner preserves the guest privileged creation option*/'supportsPrivileged'?: boolean;+ /**+ * Capabilities the runner binary supports (e.g. \"filestore\"). Absent from runners predating capability reporting, which the API treats as supporting none of them+ */+ 'capabilities'?: Array<string>;/*** Runner metrics*/diff --git a/apps/runner/README.md b/apps/runner/README.mdindex af2e5c4ef..82ebb2c39 100644--- a/apps/runner/README.md+++ b/apps/runner/README.md@@ -561,6 +561,72 @@ 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"+ }+}+```++`instance` is the logical mount identity, while `server` and `export` identify+the NFS target. The runner validates all three on every reference before+per-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.++### Mount and record lifecycle++- One NFSv4.1 mount per instance is shared by every box referencing it. The+ runner 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.+- Per-instance mutexes serialize mount, record, and reclaim decisions. Create+ rolls back records written before a later volume or final record write fails.+ After a successful record rollback, it immediately reclaims any resulting+ unreferenced Filestore mounts, independently of scheduled cleanup and its+ dry-run mode. A record rollback failure skips reclaim because references+ cannot be verified. New mounts create the empty record directory before+ starting the mount command. If Create exits while mounting or directory+ preparation is still running, completion triggers reference-aware reclaim+ after the pending marker clears. Rollback reclaim uses a bounded context+ detached from caller cancellation. Existing mounts with no records retain the+ missing-records guard. Reclaim rechecks references and pending operations+ under the instance lock instead of stating a potentially unreachable NFS root+ for a recency check; start replay retains existing entries until replacements+ are durable.+- Prepare failures return `FILESTORE_VOLUME_PREPARE_FAILED` with box, volume,+ and instance IDs plus the mount error. Logs do not include box environment+ variables, secrets, authorization headers, or job payloads.++### Troubleshooting and prerequisites++Start returns Filestore preparation errors, including target mismatches, before+starting the box, and the `START_BOX` job reports that failure. Object-storage-+only boxes retain the existing fallback: mount replay failures are logged and+Start proceeds, so a box started while object storage is unreachable can show an+empty guest directory; stop it, restore connectivity, and start it again. NFS+`hard` mounts block I/O while the network is down.++If a later request resolves the same logical instance to another server or+export, 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.+## Background services### Box state syncdiff --git a/apps/runner/pkg/api/docs/docs.go b/apps/runner/pkg/api/docs/docs.goindex 20dcaadb0..3bfe4e58d 100644--- a/apps/runner/pkg/api/docs/docs.go+++ b/apps/runner/pkg/api/docs/docs.go@@ -996,6 +996,27 @@ const docTemplate = `{}}},+ "dto.FilestoreRef": {+ "type": "object",+ "required": [+ "instance",+ "server",+ "export"+ ],+ "properties": {+ "instance": {+ "type": "string"+ },+ "server": {+ "description": "NFS server address resolved by the API",+ "type": "string"+ },+ "export": {+ "description": "NFS export path on the server",+ "type": "string"+ }+ }+ },"dto.SecretDTO": {"type": "object","required": [@@ -1030,6 +1051,9 @@ const docTemplate = `{"dto.VolumeDTO": {"type": "object","properties": {+ "filestore": {+ "$ref": "#/definitions/dto.FilestoreRef"+ },"mountPath": {"type": "string"},diff --git a/apps/runner/pkg/api/docs/swagger.json b/apps/runner/pkg/api/docs/swagger.jsonindex 6ffe54cb4..ab257b763 100644--- a/apps/runner/pkg/api/docs/swagger.json+++ b/apps/runner/pkg/api/docs/swagger.json@@ -925,6 +925,23 @@}}},+ "dto.FilestoreRef": {+ "type": "object",+ "required": ["instance", "server", "export"],+ "properties": {+ "instance": {+ "type": "string"+ },+ "server": {+ "description": "NFS server address resolved by the API",+ "type": "string"+ },+ "export": {+ "description": "NFS export path on the server",+ "type": "string"+ }+ }+ },"dto.SecretDTO": {"type": "object","required": ["headers", "name", "value"],@@ -955,6 +972,9 @@"dto.VolumeDTO": {"type": "object","properties": {+ "filestore": {+ "$ref": "#/definitions/dto.FilestoreRef"+ },"mountPath": {"type": "string"},diff --git a/apps/runner/pkg/api/docs/swagger.yaml b/apps/runner/pkg/api/docs/swagger.yamlindex c221873bc..c9a3be496 100644--- a/apps/runner/pkg/api/docs/swagger.yaml+++ b/apps/runner/pkg/api/docs/swagger.yaml@@ -272,6 +272,21 @@ definitions:outboundEnabled:type: booleantype: object+ dto.FilestoreRef:+ properties:+ instance:+ type: string+ server:+ description: NFS server address resolved by the API+ type: string+ export:+ description: NFS export path on the server+ type: string+ required:+ - instance+ - server+ - export+ type: objectdto.SecretDTO:properties:headers:@@ -295,6 +310,8 @@ definitions:type: objectdto.VolumeDTO:properties:+ filestore:+ $ref: '#/definitions/dto.FilestoreRef'mountPath:type: stringsubpath:diff --git a/apps/runner/pkg/api/dto/volume.go b/apps/runner/pkg/api/dto/volume.goindex d84c6b90b..2b5665453 100644--- a/apps/runner/pkg/api/dto/volume.go+++ b/apps/runner/pkg/api/dto/volume.go@@ -8,4 +8,27 @@ type VolumeDTO struct {VolumeId string `json:"volumeId"`MountPath string `json:"mountPath"`Subpath *string `json:"subpath,omitempty"`+ // Filestore, when set, switches this volume to a GCP Filestore NFS mount.+ // VolumeId always carries the volume's global id and names the NFS data+ // directory; Filestore only changes the mount backend, the two fields are+ // always sent together for a filestore volume.+ Filestore *FilestoreRef `json:"filestore,omitempty"`+}++// FilestoreRef dispatches one filestore volume mount. Instance is the volume+// row's logical instance name — it keys the mount root+// (/mnt/boxlite-filestore-<name>) and the mount record, and it is the only+// piece the public API request or the persisted Volume row ever carries.+// Server and Export are resolved by the API from GCP and travel inside the+// internal dispatch DTO and the box's persisted volume metadata; the runner+// consumes them as given. Every create, Start, and recovery dispatch resolves+// the instance's current address before sending this reference.+type FilestoreRef struct {+ Instance string `json:"instance"`+ // Server and Export name the NFS target the API resolved for Instance.+ // Dispatch omits neither: an empty one is a dispatch bug and fails the+ // mount loudly rather than mounting the wrong target.+ Server string `json:"server"`+ // Export is the NFS export path on Server (Filestore's default is /vol1).+ Export string `json:"export"`}diff --git a/apps/runner/pkg/boxlite/client.go b/apps/runner/pkg/boxlite/client.goindex 5c8e55588..b8cae2418 100644--- a/apps/runner/pkg/boxlite/client.go+++ b/apps/runner/pkg/boxlite/client.go@@ -12,6 +12,7 @@ import ("io""log/slog""os"+ "os/exec""os/user""path/filepath""slices"@@ -52,11 +53,27 @@ type Client struct {awsAccessKeyId stringawsSecretAccessKey stringvolumeBackend string- volumeMutexes map[string]*sync.Mutex- volumeMutexesMutex sync.Mutex- volumeCleanupMutex sync.Mutex- lastVolumeCleanup time.Time- volumeCleanup volumeCleanupConfig+ // testMountRunner and testProbeRunner are the test seams for the NFS mount path:+ // the concurrency test counts mount commands without a real server, and+ // the readiness probe reads a host binary (mountpoint) a dev machine may+ // not have. nil means the real exec runs — every production path lands+ // there because NewClient sets neither.+ testMountRunner func(*exec.Cmd) error+ testProbeRunner func(context.Context, string) (bool, error)+ // writeRecordSeam replaces the box volume mount record write when set —+ // the same posture as testMountRunner replacing the mount exec: a test uses+ // it to fail one specific record write without touching the filesystem.+ // nil means the real write runs — every production path lands there+ // because NewClient sets none of the seams.+ writeRecordSeam func(ctx context.Context, boxID string, record boxVolumeMountRecord) error+ prepareRunner func(dataDir string) error+ clearPublishedRunner func() error+ volumeMutexes map[string]*sync.Mutex+ volumePending map[string]int+ volumeMutexesMutex sync.Mutex+ volumeCleanupMutex sync.Mutex+ lastVolumeCleanup time.Time+ volumeCleanup volumeCleanupConfignestedVirtualizationAllowed bool@@ -461,6 +478,18 @@ func (c *Client) Create(ctx context.Context, boxDto dto.CreateBoxDTO) (string, sif err := validateRecreatableSecrets(boxDto.Secrets); err != nil {return "", "", err}++ // Also before any side effect: the box id becomes part of filesystem+ // paths — volume mount records ({id}.json) and the runtime's own box+ // name. The control plane mints ids from+ // [0-9A-Za-z]{12}, which cannot carry separators or '..', but this+ // boundary must not lean on that: a traversal-shaped id is rejected+ // before any mount or record work runs. The literal Contains checks stay+ // inline so static analysis sees the validation on every path.+ if strings.ContainsAny(boxDto.Id, "/\\") || strings.Contains(boxDto.Id, "..") {+ return "", "", fmt.Errorf("invalid box id %q: must not contain path separators or '..'", boxDto.Id)+ }+operation, err := c.checkpointOperations().Lock(ctx, boxDto.Id)if err != nil {return "", "", err@@ -552,8 +581,24 @@ func (c *Client) Create(ctx context.Context, boxDto dto.CreateBoxDTO) (string, sopts = append(opts, boxlite.WithAdvancedOptions(advanced))}- volumeMounts, err := c.getVolumeMounts(ctx, boxDto.Volumes)+ var priorVolumeRecord *boxVolumeMountRecord+ if hasFilestoreRef(boxDto.Volumes) {+ priorVolumeRecord, err = c.readBoxVolumeMountRecord(boxDto.Id)+ if err != nil {+ return "", "", fmt.Errorf("failed to read existing volume mount record: %w", err)+ }+ }++ volumeMounts, err := c.getVolumeMounts(ctx, boxDto.Id, boxDto.Volumes)if err != nil {+ // A filestore volume earlier in the list may already have written its+ // record entry inside the instance critical section. The failed create+ // must not leave it behind: no box ever exists to destroy, so the+ // dangling entry would count a reference forever and keep the NFS+ // mount from reclaiming.+ if hasFilestoreRef(boxDto.Volumes) {+ c.rollbackVolumeMountRecord(ctx, boxDto.Id, boxDto.Volumes, priorVolumeRecord)+ }return "", "", err}for _, vol := range volumeMounts {@@ -564,6 +609,13 @@ func (c *Client) Create(ctx context.Context, boxDto dto.CreateBoxDTO) (string, sif len(volumeMounts) > 0 {if err := c.recordBoxVolumeMounts(ctx, boxDto.Id, volumeMounts); err != nil {+ // The final write failed after earlier volumes already published+ // their entries in-lock. Same rule as the getVolumeMounts path:+ // no box will exist to destroy, so the dangling entries must not+ // survive.+ if hasFilestoreRef(boxDto.Volumes) {+ c.rollbackVolumeMountRecord(ctx, boxDto.Id, boxDto.Volumes, priorVolumeRecord)+ }return "", "", err}}@@ -573,9 +625,7 @@ func (c *Client) Create(ctx context.Context, boxDto dto.CreateBoxDTO) (string, sif len(volumeMounts) > 0 {cleanupCtx, cancel := cleanupContext(ctx)defer cancel()- if cleanupErr := c.removeBoxVolumeMountRecord(cleanupCtx, boxDto.Id); cleanupErr != nil {- c.logger.WarnContext(cleanupCtx, "failed to remove cancelled box volume mount record", "box", boxDto.Id, "error", cleanupErr)- }+ c.rollbackVolumeMountRecord(cleanupCtx, boxDto.Id, boxDto.Volumes, priorVolumeRecord)}return "", "", err}@@ -593,6 +643,9 @@ func (c *Client) Create(ctx context.Context, boxDto dto.CreateBoxDTO) (string, s// now exists locally and the job can proceed, so it is discarded.id, err := c.nativeBoxID(boxDto.Id)if err != nil {+ if len(volumeMounts) > 0 && hasFilestoreRef(boxDto.Volumes) {+ c.rollbackVolumeMountRecord(ctx, boxDto.Id, boxDto.Volumes, priorVolumeRecord)+ }return "", "", err}var bx *boxlite.Box@@ -600,16 +653,21 @@ func (c *Client) Create(ctx context.Context, boxDto dto.CreateBoxDTO) (string, sbx, err = c.runtime.Get(ctx, id)}if bx == nil && (err == nil || boxlite.IsNotFound(err)) {- if err := operation.ClearPublished(); err != nil {+ clearPublished := operation.ClearPublished+ if c.clearPublishedRunner != nil {+ clearPublished = c.clearPublishedRunner+ }+ if err := clearPublished(); err != nil {+ if len(volumeMounts) > 0 && hasFilestoreRef(boxDto.Volumes) {+ c.rollbackVolumeMountRecord(ctx, boxDto.Id, boxDto.Volumes, priorVolumeRecord)+ }return "", "", err}bx, _, err = c.runtime.GetOrCreate(ctx, boxDto.Image, opts...)}if err != nil {if len(volumeMounts) > 0 {- if cleanupErr := c.removeBoxVolumeMountRecord(ctx, boxDto.Id); cleanupErr != nil {- c.logger.WarnContext(ctx, "failed to remove box volume mount record after create failure", "box", boxDto.Id, "error", cleanupErr)- }+ c.rollbackVolumeMountRecord(ctx, boxDto.Id, boxDto.Volumes, priorVolumeRecord)}return "", "", fmt.Errorf("failed to create box: %w", err)}@@ -688,6 +746,13 @@ func (c *Client) recordPulledImage(ctx context.Context, boxId string, bx boxInfo// Start starts a stopped box and returns the runtime version.func (c *Client) Start(ctx context.Context, boxId string, authToken *string, metadata map[string]string) (string, error) {+ // Same boundary check as Create: Start replays the volume mount record+ // write from metadata and looks the box up by name, so a+ // traversal-shaped id is rejected before any of that runs.+ if strings.ContainsAny(boxId, "/\\") || strings.Contains(boxId, "..") {+ return "", fmt.Errorf("invalid box id %q: must not contain path separators or '..'", boxId)+ }+operation, err := c.lockCheckpointTarget(ctx, boxId)if err != nil {return "", err@@ -695,7 +760,10 @@ func (c *Client) Start(ctx context.Context, boxId string, authToken *string, metdefer operation.Close()ctx = context.WithoutCancel(ctx)if err := c.ensureVolumeMountsFromMetadata(ctx, boxId, metadata); err != nil {- c.logger.ErrorContext(ctx, "failed to ensure volume FUSE mounts", "error", err)+ if isFilestoreVolumePreparationError(err) {+ return "", err+ }+ c.logger.ErrorContext(ctx, "failed to ensure volume mounts", "box", boxId, "error", err)}bx, err := c.getOrFetchBox(ctx, boxId)@@ -733,6 +801,13 @@ func (c *Client) Stop(ctx context.Context, boxId string, force bool) error {// Destroy removes a box entirely.func (c *Client) Destroy(ctx context.Context, boxId string) error {+ // Same boundary check as Create/Start: the runtime removal and the+ // volume mount record paths below all key off boxId, so a+ // traversal-shaped id is rejected before any of them runs.+ if strings.ContainsAny(boxId, "/\\") || strings.Contains(boxId, "..") {+ return fmt.Errorf("invalid box id %q: must not contain path separators or '..'", boxId)+ }+operation, err := c.checkpointOperations().Lock(ctx, boxId)if err != nil {return err@@ -754,8 +829,15 @@ func (c *Client) Destroy(ctx context.Context, boxId string) error {}}- if err := c.removeBoxVolumeMountRecord(ctx, boxId); err != nil {- c.logger.WarnContext(ctx, "failed to remove box volume mount record", "box", boxId, "error", err)+ // The record deletion takes each referenced instance's mutex so it cannot+ // interleave with an in-flight reclaim decision for those instances+ // (design §4.5.3); the orphan cleanup that follows reclaims their mounts.+ instances, readErr := c.readFilestoreInstancesFromRecord(boxId)+ if readErr != nil {+ c.logger.WarnContext(ctx, "failed to read box volume mount record", "box", boxId, "error", readErr)+ }+ if cleanupErr := c.removeBoxVolumeMountRecordLocked(ctx, boxId, instances); cleanupErr != nil {+ c.logger.WarnContext(ctx, "failed to remove box volume mount record", "box", boxId, "error", cleanupErr)}c.CleanupOrphanedVolumeMounts(ctx)diff --git a/apps/runner/pkg/boxlite/client_box_id_guard_test.go b/apps/runner/pkg/boxlite/client_box_id_guard_test.gonew file mode 100644index 000000000..dc77b91e7--- /dev/null+++ b/apps/runner/pkg/boxlite/client_box_id_guard_test.go@@ -0,0 +1,86 @@+// Copyright 2026 BoxLite AI+// SPDX-License-Identifier: AGPL-3.0++package boxlite++import (+ "context"+ "strings"+ "testing"++ "github.com/boxlite-ai/runner/pkg/api/dto"+)++// The box id becomes part of filesystem paths: volume mount records+// ({id}.json) and the runtime's own box name. These tests pin the boundary+// guards on Create/Start/Destroy —+// a traversal-shaped id is rejected before any mount or record work runs.+//+// createDtoWithBadVolumeId carries a filestore volume whose volume id is+// traversal-shaped: once an id passes the guard, getVolumeMounts fails with+// the volume-id guard error instead, which is what distinguishes "the guard+// rejected it" from "the call got into mount work".+func createDtoWithBadVolumeId(id string) dto.CreateBoxDTO {+ outbound := true+ return dto.CreateBoxDTO{+ Id: id,+ OutboundEnabled: &outbound,+ Volumes: []dto.VolumeDTO{+ // A traversal-shaped volume id: the volume-id guard fails it after+ // the box-id guard admits the id.+ {VolumeId: "../escape", Filestore: &dto.FilestoreRef{Instance: "ml", Server: "10.0.0.7", Export: "/vol1"}},+ },+ }+}++func TestCreateRejectsTraversalShapedBoxId(t *testing.T) {+ c := testClient(t)++ for _, id := range []string{"bad/id", "bad\\id", "../etc", "box..id"} {+ _, _, err := c.Create(context.Background(), createDtoWithBadVolumeId(id))+ if err == nil {+ t.Fatalf("Create with id %q: expected the box id guard to reject it, got nil", id)+ }+ if !strings.Contains(err.Error(), "invalid box id") {+ t.Fatalf("Create with id %q: expected the box id guard error, got %q", id, err)+ }+ if strings.Contains(err.Error(), "invalid filestore volume id") {+ t.Fatalf("Create with id %q: reached volume mount work (volume id guard) although the box-id guard should have rejected it", id)+ }+ }+}++func TestCreateAdmitsWellFormedBoxId(t *testing.T) {+ // The rollback on getVolumeMounts failure removes the box's record file,+ // which resolves the mount base path — without the override that reaches+ // the config package global, which no test initializes. The override keeps+ // the test hermetic; the guard assertions below are untouched.+ useVolumeMountBasePath(t, t.TempDir())+ c := testClient(t)+ c.homeDir = t.TempDir()++ // A well-formed box id passes the guard, so the failure must come from+ // the later mount work — here the volume-id guard. That contrast is what+ // proves the guard is what rejected the ids above.+ _, _, err := c.Create(context.Background(), createDtoWithBadVolumeId("abc123def456"))+ if err == nil {+ t.Fatal("expected the volume-id guard error once the guard admits the id, got nil")+ }+ if !strings.Contains(err.Error(), "invalid filestore volume id") {+ t.Fatalf("expected the volume-id guard error after the guard admitted the id, got %q", err)+ }+}++func TestStartAndDestroyRejectTraversalShapedBoxId(t *testing.T) {+ c := testClient(t)++ _, startErr := c.Start(context.Background(), "../esc", nil, nil)+ if startErr == nil || !strings.Contains(startErr.Error(), "invalid box id") {+ t.Fatalf("Start with traversal id: expected the box id guard error, got %v", startErr)+ }++ destroyErr := c.Destroy(context.Background(), "bad/id")+ if destroyErr == nil || !strings.Contains(destroyErr.Error(), "invalid box id") {+ t.Fatalf("Destroy with traversal id: expected the box id guard error, got %v", destroyErr)+ }+}diff --git a/apps/runner/pkg/boxlite/volumes.go b/apps/runner/pkg/boxlite/volumes.goindex 3d28ebfe1..6e27c2755 100644--- a/apps/runner/pkg/boxlite/volumes.go+++ b/apps/runner/pkg/boxlite/volumes.go@@ -13,6 +13,7 @@ import ("os""os/exec""path/filepath"+ "regexp""strings""sync""time"@@ -23,8 +24,11 @@ import ()const volumeMountPrefix = "boxlite-volume-"+const filestoreMountPrefix = "boxlite-filestore-"const volumeMountRecordDir = ".boxlite-volume-mounts"+var filestoreInstanceNamePattern = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,62}$`)+// How long a mount command may run before it is killed. The request context// cannot serve as this bound: Create is handed an undeadlined gin request// context, and gcsfuse retries an unreachable bucket forever, so without an@@ -51,26 +55,120 @@ type volumeMount struct {hostPath stringmountPath stringrootPath string+ // backend labels what mounts rootPath; "s3"/"gcs" for object storage, and+ // "filestore" for an NFS mount. Records keep the label for humans and for+ // debugging; the reclaimer keys off rootPath regardless of backend.+ backend string+ // filestore-only fields. dataDir is the box's own directory inside the NFS+ // export — the bind source for this volume and the thing that survives a+ // destroy (destroy unbinds, never deletes data).+ dataDir string+ filestoreInstance string+}++// boxVolumeMountEntry is one volume of one box in the box's mount record.+// The reclaimer counts a mount root as referenced when ANY entry names it, so+// a box mixing an object-storage volume and a filestore volume (allowed) lands+// as two entries with different backends in one record.+type boxVolumeMountEntry struct {+ Backend string `json:"backend"`+ RootPath string `json:"rootPath"`+ FilestoreInstance string `json:"filestoreInstance,omitempty"`+ // DataDir is filestore-only: the box's own directory inside the NFS+ // export, kept for troubleshooting. The reclaimer counts rootPath, never+ // dataDir — destroy leaves the data behind by design.+ DataDir string `json:"dataDir,omitempty"`}type boxVolumeMountRecord struct {- BoxID string `json:"boxId"`- Paths []string `json:"paths"`+ BoxID string `json:"boxId"`+ Entries []boxVolumeMountEntry `json:"entries"`++ // Paths is the legacy record shape ({boxId, paths}). Records still carry+ // it for one release cycle so a runner binary rolled back to the+ // pre-entries version keeps seeing the references (its reader ignores+ // entries and would otherwise count zero references and reclaim live+ // mounts). entries and paths hold the same deduped rootPath set; new+ // readers fold both shapes and the reclaimer's map dedups the overlap.+ // Remove the field and the double-write once rolling back to a+ // pre-entries binary is no longer possible.+ Paths []string `json:"paths,omitempty"`+}++// UnmarshalJSON folds the legacy bare-paths shape into entries, so every+// reader sees one shape. A record from before filestore has no backend field:+// those paths are object-storage mounts by definition (filestore did not+// exist), and the backend label is inert for reading anyway — the reclaimer+// keys off rootPath.+func (r *boxVolumeMountRecord) UnmarshalJSON(data []byte) error {+ type recordAlias struct {+ BoxID string `json:"boxId"`+ Paths []string `json:"paths"`+ Entries []boxVolumeMountEntry `json:"entries"`+ }+ var alias recordAlias+ if err := json.Unmarshal(data, &alias); err != nil {+ return err+ }++ r.BoxID = alias.BoxID+ for _, path := range alias.Paths {+ r.Entries = append(r.Entries, boxVolumeMountEntry{Backend: volumeBackendS3, RootPath: path})+ }+ r.Entries = append(r.Entries, alias.Entries...)+ return nil}+// volumeMountBasePathOverride lets a test point every volume mount path —+// mount roots, data dirs, record files — at a temp dir. Empty in production,+// where the environment decides between /mnt and /tmp. Same test-replacement+// pattern as client.go's currentUser.+var volumeMountBasePathOverride string+func getVolumeMountBasePath() string {+ if volumeMountBasePathOverride != "" {+ return volumeMountBasePathOverride+ }if config.GetEnvironment() == "development" {return "/tmp"}return "/mnt"}-func (c *Client) getVolumeMounts(ctx context.Context, volumes []dto.VolumeDTO) ([]volumeMount, error) {+func (c *Client) getVolumeMounts(ctx context.Context, boxID string, volumes []dto.VolumeDTO) ([]volumeMount, error) {volumeMounts := make([]volumeMount, 0, len(volumes))fuseMountedVolumes := make(map[string]bool)+ // Per-call dedup remembers the verified target so two volumes on one+ // Filestore instance cannot silently select different shares.+ filestoreEnsured := make(map[string]string)for _, vol := range volumes {+ if vol.Filestore != nil {+ mount, err := c.filestoreVolumeMount(ctx, boxID, vol, filestoreEnsured)+ if err != nil {+ attrs := []any{+ "code", "FILESTORE_VOLUME_PREPARE_FAILED",+ "boxId", boxID,+ "volumeId", vol.VolumeId,+ "instance", vol.Filestore.Instance,+ "mountPath", vol.MountPath,+ "error", err,+ }+ var exitError *exec.ExitError+ if errors.As(err, &exitError) {+ attrs = append(attrs, "exitCode", exitError.ExitCode())+ }+ c.logger.ErrorContext(ctx, "Failed to prepare Filestore volume", attrs...)+ return nil, fmt.Errorf(+ "FILESTORE_VOLUME_PREPARE_FAILED: failed to prepare filestore volume %s on instance %s for box %s: %w",+ vol.VolumeId, vol.Filestore.Instance, boxID, err,+ )+ }+ volumeMounts = append(volumeMounts, mount)+ continue+ }+volumeIdPrefixed := fmt.Sprintf("%s%s", volumeMountPrefix, vol.VolumeId)baseMountPath := filepath.Join(getVolumeMountBasePath(), volumeIdPrefixed)@@ -104,12 +202,153 @@ func (c *Client) getVolumeMounts(ctx context.Context, volumes []dto.VolumeDTO) (hostPath: bindSource,mountPath: vol.MountPath,rootPath: baseMountPath,+ backend: c.volumeBackend,})}return volumeMounts, nil}+// filestoreVolumeMount prepares one filestore volume reference for binding:+// under the instance's mutex it ensures the NFS mount exists (once per call),+// creates the volume's data directory and writes the referencing record. The data directory is named by the volume's+// id, not the box's: boxes sharing a volume share the directory (the+// bucket-alignment contract), and a destroyed box's data stays reachable by+// mounting the volume into a new box. `ensured` records the verified target+// for each instance prepared within this call.+//+// Holding the lock across the whole sequence is what makes the reclaim's+// in-lock record rescan sound: reclaim counts references from records under+// the same per-instance mutex, so a mount cannot be reclaimed in the window+// between "usable" and "referenced" (design §4.5).+func (c *Client) filestoreVolumeMount(ctx context.Context, boxID string, vol dto.VolumeDTO, ensured map[string]string) (volumeMount, error) {+ // The volume id names a data directory under the instance's mount root.+ // The control plane mints uuids, which cannot carry separators or '..',+ // but this boundary must not lean on that — the same posture as the box+ // id guard in client.go: a traversal-shaped or empty id is rejected+ // before any path is derived. An empty id is refused outright because+ // filestoreDataDir(root, "") would name the mount root itself, putting+ // every volume of the instance behind one box's bind mount.+ if vol.VolumeId == "" || vol.VolumeId == "." || strings.ContainsAny(vol.VolumeId, "/\\") || strings.Contains(vol.VolumeId, "..") {+ return volumeMount{}, fmt.Errorf(+ "invalid filestore volume id %q: must be a bare identifier without path separators or '..'",+ vol.VolumeId,+ )+ }+ ref := vol.Filestore+ if !filestoreInstanceNamePattern.MatchString(ref.Instance) {+ return volumeMount{}, fmt.Errorf("invalid filestore instance %q: must match %s", ref.Instance, filestoreInstanceNamePattern)+ }+ if err := validateFilestoreTarget(ref); err != nil {+ return volumeMount{}, err+ }+ if vol.Subpath != nil && *vol.Subpath != "" {+ return volumeMount{}, fmt.Errorf("subpath is not supported for filestore volumes")+ }++ rootPath := filepath.Join(getVolumeMountBasePath(), filestoreMountPrefix+ref.Instance)++ mountKey := filestoreMountPrefix + ref.Instance+ mutex := c.volumeMutexFor(mountKey)+ mutex.Lock()+ defer mutex.Unlock()+ if err := c.checkVolumeOperation(mountKey); err != nil {+ return volumeMount{}, err+ }++ target := filestoreTarget(ref)+ if ensuredTarget, ok := ensured[ref.Instance]; ok {+ if ensuredTarget != target {+ return volumeMount{}, fmt.Errorf("conflicting filestore target for instance %s: request already verified %q, reference requests %q", ref.Instance, ensuredTarget, target)+ }+ } else {+ if err := c.ensureFilestoreMounted(ctx, ref, rootPath, mountKey); err != nil {+ return volumeMount{}, err+ }+ ensured[ref.Instance] = target+ }++ dataDir := filestoreDataDir(rootPath, vol.VolumeId)++ // NFS permissions are real (unlike the FUSE backends' --dir-mode+ // fakes), so the directory needs an explicit chmod after mkdir — plain+ // MkdirAll is masked by umask, and 0777 matches the posture the FUSE+ // backends reach for with --dir-mode 0777.+ prepare := c.prepareRunner+ if prepare == nil {+ prepare = func(dataDir string) error {+ if err := os.MkdirAll(dataDir, 0777); err != nil {+ return fmt.Errorf("failed to create filestore data directory %s: %s", dataDir, err)+ }+ if err := os.Chmod(dataDir, 0777); err != nil {+ return fmt.Errorf("failed to chmod filestore data directory %s: %s", dataDir, err)+ }+ return nil+ }+ }+ prepareCtx, cancelPrepare := context.WithTimeout(ctx, volumeProbeTimeout)+ defer cancelPrepare()+ if _, err := c.runBoundedVolumeOperation(prepareCtx, mountKey, func() error { return prepare(dataDir) }, func() {+ c.reclaimFilestoreMount(context.Background(), rootPath)+ }); err != nil {+ return volumeMount{}, err+ }++ mount := volumeMount{+ hostPath: dataDir,+ mountPath: vol.MountPath,+ rootPath: rootPath,+ backend: volumeBackendFilestore,+ dataDir: dataDir,+ filestoreInstance: ref.Instance,+ }++ // The referencing record is written inside the same critical section —+ // this is what design §4.5.2 pins: reclaim rescans records under this+ // instance's mutex, so the reference must become visible while the mount+ // is still protected. The entry is merged into the record instead of+ // replacing it: the record stays authoritative for a running box, and an+ // in-lock replacement would publish just the processed prefix — a+ // Start whose later volume failed would leave the record truncated while+ // the box kept every mount, handing the orphan reclaimer live references.+ if err := c.mergeBoxVolumeMountRecord(ctx, boxID, []volumeMount{mount}); err != nil {+ return volumeMount{}, err+ }++ return mount, nil+}++func filestoreTarget(ref *dto.FilestoreRef) string {+ return ref.Server + ":" + ref.Export+}++// filestoreDataDir derives the volume's data directory inside an instance's+// NFS export: {mount root}/{volume_id}. Volumes are shared resources — boxes+// mounting the same volume land in the same directory, and a destroyed box's+// data stays reachable through the volume id.+func filestoreDataDir(rootPath string, volumeId string) string {+ return filepath.Join(rootPath, volumeId)+}++type filestoreVolumePreparationError struct {+ err error+}++func (e *filestoreVolumePreparationError) Error() string { return e.err.Error() }+func (e *filestoreVolumePreparationError) Unwrap() error { return e.err }++func classifyVolumeMetadataError(volumes []dto.VolumeDTO, err error) error {+ if hasFilestoreRef(volumes) {+ return &filestoreVolumePreparationError{err: err}+ }+ return err+}++func isFilestoreVolumePreparationError(err error) bool {+ var target *filestoreVolumePreparationError+ return errors.As(err, &target)+}+func (c *Client) ensureVolumeMountsFromMetadata(ctx context.Context, boxID string, metadata map[string]string) error {if metadata == nil {return nil@@ -128,27 +367,23 @@ func (c *Client) ensureVolumeMountsFromMetadata(ctx context.Context, boxID strinreturn nil}- volumeMounts, err := c.getVolumeMounts(ctx, volumes)+ volumeMounts, err := c.getVolumeMounts(ctx, boxID, volumes)if err != nil {- return err+ return classifyVolumeMetadataError(volumes, err)}- return c.recordBoxVolumeMounts(ctx, boxID, volumeMounts)+ if err := c.recordBoxVolumeMounts(ctx, boxID, volumeMounts); err != nil {+ return classifyVolumeMetadataError(volumes, err)+ }+ return nil}func (c *Client) ensureVolumeFuseMounted(ctx context.Context, volumeId string, mountPath string) error {- c.volumeMutexesMutex.Lock()- volumeMutex, exists := c.volumeMutexes[volumeId]- if !exists {- volumeMutex = &sync.Mutex{}- c.volumeMutexes[volumeId] = volumeMutex- }- c.volumeMutexesMutex.Unlock()-+ volumeMutex := c.volumeMutexFor(volumeId)volumeMutex.Lock()defer volumeMutex.Unlock()- mounted, err := c.isDirectoryMounted(ctx, mountPath)+ mounted, err := c.probeMounted(ctx, mountPath)if err != nil {// Guessing here is what makes a stale mount look absent: we would mount// over it, then treat the directory as pre-existing and tear it down.@@ -186,6 +421,145 @@ func (c *Client) ensureVolumeFuseMounted(ctx context.Context, volumeId string, mreturn nil}+func validateFilestoreTarget(ref *dto.FilestoreRef) error {+ if ref.Server == "" || ref.Export == "" {+ return fmt.Errorf("filestore %s requires both server and export", ref.Instance)+ }+ return nil+}++// ensureFilestoreMounted is the NFS twin of ensureVolumeFuseMounted, with two+// deliberate differences. No systemd-run scope: NFS is a kernel mount with no+// daemon, so there is nothing that dies with the runner service's cgroup. And+// no backend flag — the protocol is pinned to NFSv4.1 (the only version the+// Zonal/Regional tiers serve), hard, on the kernel defaults for timeo/retrans.+// Everything else is the same contract: the is-mounted probe, the 90s mount+// timeout (a hard mount to an unreachable server retries forever in the+// foreground — the timeout is what ends it), the readiness wait, and the+// failure cleanup. Unlike its FUSE twin it takes no lock of its own: the+// caller holds the instance mutex so that probing, mounting, preparing the+// data directory and writing the referencing record form ONE critical section+// against reclaim (design §4.5).+func (c *Client) ensureFilestoreMounted(ctx context.Context, ref *dto.FilestoreRef, mountRoot string, mountKey string) error {+ if err := validateFilestoreTarget(ref); err != nil {+ return err+ }++ mounted, err := c.probeMounted(ctx, mountRoot)+ if err != nil {+ // Same reasoning as the FUSE twin: guessing here is what makes a stale+ // mount look absent, and mounting over a live NFS mount wedges both.+ return fmt.Errorf("cannot determine whether filestore %s is already mounted: %w", ref.Instance, err)+ }+ if mounted {+ if err := verifyFilestoreMountTarget(ctx, ref, mountRoot); err != nil {+ return err+ }+ c.logger.DebugContext(ctx, "filestore already mounted", "instance", ref.Instance, "mountRoot", mountRoot)+ return nil+ }++ _, statErr := os.Stat(mountRoot)+ dirExisted := statErr == nil++ if err = os.MkdirAll(mountRoot, 0755); err != nil {+ return fmt.Errorf("failed to create filestore mount root %s: %s", mountRoot, err)+ }++ // Establish the ownership boundary before the mount starts. If the caller+ // times out, late completion can prove this mount unreferenced and reclaim it;+ // existing mounts return above without weakening the missing-records guard.+ recordDir := getVolumeMountRecordDir()+ if err = os.MkdirAll(recordDir, 0755); err != nil {+ c.cleanUpFailedMount(ctx, mountRoot, dirExisted)+ return fmt.Errorf("failed to create volume mount record directory %s: %w", recordDir, err)+ }++ c.logger.InfoContext(ctx, "mounting filestore instance", "instance", ref.Instance, "server", ref.Server, "export", ref.Export, "mountRoot", mountRoot)++ mountCtx, cancelMount := context.WithTimeout(ctx, volumeMountTimeout)+ defer cancelMount()++ cmd := c.getNfsMountCmd(mountCtx, ref, mountRoot)+ pending, mountErr := c.runMount(mountCtx, mountKey, cmd, mountRoot)+ if mountErr != nil {+ if !pending {+ c.cleanUpFailedMount(ctx, mountRoot, dirExisted)+ }+ return fmt.Errorf("failed to mount filestore %s to %s: %w", ref.Instance, mountRoot, mountErr)+ }++ if err = c.waitForMountReady(ctx, mountRoot); err != nil {+ c.cleanUpFailedMount(ctx, mountRoot, dirExisted)+ return fmt.Errorf("mount %s not ready after mounting: %s", mountRoot, err)+ }++ c.logger.InfoContext(ctx, "mounted filestore instance", "instance", ref.Instance, "mountRoot", mountRoot)+ return nil+}++func verifyFilestoreMountTarget(ctx context.Context, ref *dto.FilestoreRef, mountRoot string) error {+ probeCtx, cancel := context.WithTimeout(ctx, volumeProbeTimeout)+ defer cancel()++ expected := filestoreTarget(ref)+ output, err := exec.CommandContext(+ probeCtx,+ "findmnt",+ "--noheadings",+ "--nofsroot",+ "--raw",+ "--mountpoint", mountRoot,+ "--types", "nfs4",+ "--output", "SOURCE",+ ).Output()+ if err != nil {+ return fmt.Errorf("cannot verify existing filestore %s mount at %s as NFSv4 with source %s: %w", ref.Instance, mountRoot, expected, err)+ }+ actual := strings.TrimSpace(string(output))+ if actual != expected {+ return fmt.Errorf("filestore %s mount target mismatch at %s: mounted source %q, requested source %q", ref.Instance, mountRoot, actual, expected)+ }+ return nil+}++// nfsMountArgs builds the argv for one mount(8) invocation: NFSv4.1 and hard,+// with kernel defaults for timeo/retrans. A pure function so a test can pin+// the argv — the protocol and retry posture are design-pinned and are the+// contract with the API's Filestore discovery.+func nfsMountArgs(ref *dto.FilestoreRef, path string) []string {+ opts := "vers=4.1,hard"+ return []string{"-t", "nfs", "-o", opts, filestoreTarget(ref), path}+}++// getNfsMountCmd wraps nfsMountArgs in the command to run. No systemd-run+// scope here, unlike the FUSE backends: NFS is a kernel mount with no daemon,+// so nothing dies with the runner service's cgroup and the plain+// context-bound exec is the whole story. Output goes to the same log writers+// the FUSE mounts use, so a failing mount shows up in the runner's logs.+func (c *Client) getNfsMountCmd(ctx context.Context, ref *dto.FilestoreRef, path string) *exec.Cmd {+ cmd := exec.CommandContext(ctx, "mount", nfsMountArgs(ref, path)...)+ cmd.Env = os.Environ()+ cmd.Stderr = io.Writer(&log.ErrorLogWriter{})+ cmd.Stdout = io.Writer(&log.InfoLogWriter{})+ return cmd+}++// runMount supervises the command so an unkillable process cannot park the+// caller after the deadline. The pending marker prevents a retry or reclaim+// from treating that process as finished before Wait returns. Once an abandoned+// mount finishes, reference-aware reclaim runs with that marker cleared.+func (c *Client) runMount(ctx context.Context, mountKey string, cmd *exec.Cmd, mountRoot string) (bool, error) {+ return c.runBoundedVolumeOperation(ctx, mountKey, func() error {+ if c.testMountRunner != nil {+ return c.testMountRunner(cmd)+ }+ return cmd.Run()+ }, func() {+ c.reclaimFilestoreMount(context.Background(), mountRoot)+ })+}+// mountProbeCmd and umountCmd exist as separate builders so a test can assert// the commands are context-bound. Running them cannot show that: mountpoint// and umount fail on an ordinary directory whatever the context says.@@ -297,6 +671,91 @@ func (c *Client) umountPath(ctx context.Context, path string) error {return umountCmd(umountCtx, path).Run()}+// probeMounted answers whether path is a mountpoint, through the injectable+// probe when a test installed one. The mount seam alone cannot make the+// concurrency test decidable on every host: the readiness wait reads a host+// binary (`mountpoint`), which a dev machine may not have. Production keeps+// the real probe — NewClient sets neither seam.+func (c *Client) probeMounted(ctx context.Context, path string) (bool, error) {+ if c.testProbeRunner != nil {+ return c.testProbeRunner(ctx, path)+ }+ return c.isDirectoryMounted(ctx, path)+}++func (c *Client) checkVolumeOperation(key string) error {+ c.volumeMutexesMutex.Lock()+ defer c.volumeMutexesMutex.Unlock()+ if c.volumePending[key] > 0 {+ return fmt.Errorf("previous volume operation for %s is still in flight", key)+ }+ return nil+}++// trackLateVolumeOperation keeps an instance marked busy until the underlying+// syscall or process has actually finished, even after its caller timed out.+func (c *Client) trackLateVolumeOperation(key string, done <-chan error, onComplete func()) {+ c.volumeMutexesMutex.Lock()+ if c.volumePending == nil {+ c.volumePending = make(map[string]int)+ }+ c.volumePending[key]+++ c.volumeMutexesMutex.Unlock()++ go func() {+ err := <-done+ c.volumeMutexesMutex.Lock()+ c.volumePending[key]--+ if c.volumePending[key] == 0 {+ delete(c.volumePending, key)+ }+ c.volumeMutexesMutex.Unlock()+ if err != nil {+ c.logger.WarnContext(context.Background(), "late volume operation failed", "key", key, "error", err)+ }+ if onComplete != nil {+ onComplete()+ }+ }()+}++// runBoundedVolumeOperation returns on context completion while retaining an+// instance-level pending marker until the operation itself finishes.+func (c *Client) runBoundedVolumeOperation(ctx context.Context, key string, operation func() error, onLateCompletion func()) (bool, error) {+ done := make(chan error, 1)+ go func() {+ done <- operation()+ }()++ select {+ case err := <-done:+ return false, err+ case <-ctx.Done():+ c.trackLateVolumeOperation(key, done, onLateCompletion)+ return true, ctx.Err()+ }+}++// volumeMutexFor returns the per-key mutex for a mount key, creating it on+// first use. The key was the volume id for object storage; it generalizes to+// the prefixed instance name for filestore, so one instance's ensure-mount,+// reclaim decision and in-lock record rescan all serialize on one lock.+func (c *Client) volumeMutexFor(key string) *sync.Mutex {+ c.volumeMutexesMutex.Lock()+ defer c.volumeMutexesMutex.Unlock()+ // Tests construct Clients without the map; lazily create it so every+ // lock-taking path is safe on any Client. NewClient still initializes it.+ if c.volumeMutexes == nil {+ c.volumeMutexes = make(map[string]*sync.Mutex)+ }+ volumeMutex, exists := c.volumeMutexes[key]+ if !exists {+ volumeMutex = &sync.Mutex{}+ c.volumeMutexes[key] = volumeMutex+ }+ return volumeMutex+}+// readable answers whether the mountpoint can be listed, without inheriting a// hang if it cannot. os.Stat and os.ReadDir are uninterruptible on a FUSE mount// whose daemon has attached and then wedged — exactly the state this readiness@@ -342,7 +801,7 @@ func (c *Client) waitForMountReady(ctx context.Context, path string) error {defer cancel()for attempt := 1; ; attempt++ {- mounted, err := c.isDirectoryMounted(readyCtx, path)+ mounted, err := c.probeMounted(readyCtx, path)if err != nil {return notReadyError(ctx, readyCtx)}@@ -375,6 +834,10 @@ func (c *Client) waitForMountReady(ctx context.Context, path string) error {const (volumeBackendS3 = "s3"volumeBackendGCS = "gcs"+ // filestore is not selectable by VOLUME_STORAGE_BACKEND — that flag+ // chooses the bucket backend, and a Filestore mount is chosen per volume+ // reference instead. The label only ever appears in mount records.+ volumeBackendFilestore = "filestore")// The permission bits both mounts present. Paired with allow_other, they are@@ -498,24 +961,161 @@ func (c *Client) wrapMountCmd(ctx context.Context, spec mountSpec) *exec.Cmd {return cmd}-func (c *Client) recordBoxVolumeMounts(ctx context.Context, boxID string, mounts []volumeMount) error {+// readBoxVolumeMountRecord reads a box's record from disk. A missing record is+// not an error: it means no create or replay ever wrote one for the box, which+// is the empty record — a caller merging into it starts from nothing rather+// than failing the merge.+//+// Parsed through a neutral alias rather than the record's own UnmarshalJSON.+// That reader folds the legacy paths into entries unconditionally, and a+// read-modify-write cycle through it (the merge) would copy the folded+// duplicates back into the file's entries on every write — the record would+// grow by its paths count per merge. The two shapes are distinguished instead:+// a record with entries carries its content in entries (paths is the derived+// legacy mirror every writer emits alongside them), and only a pre-entries+// record keeps its references in paths, folded here into s3 entries exactly as+// the compat reader folds them.+func (c *Client) readBoxVolumeMountRecord(boxID string) (*boxVolumeMountRecord, error) {+ path := filepath.Join(getVolumeMountRecordDir(), boxID+".json")+ data, err := os.ReadFile(path)+ if err != nil {+ if os.IsNotExist(err) {+ return &boxVolumeMountRecord{BoxID: boxID}, nil+ }+ return nil, err+ }++ var alias struct {+ BoxID string `json:"boxId"`+ Paths []string `json:"paths"`+ Entries []boxVolumeMountEntry `json:"entries"`+ }+ if err := json.Unmarshal(data, &alias); err != nil {+ return nil, err+ }++ record := &boxVolumeMountRecord{BoxID: alias.BoxID, Entries: alias.Entries}+ if len(alias.Entries) == 0 {+ for _, legacyPath := range alias.Paths {+ record.Entries = append(record.Entries, boxVolumeMountEntry{Backend: volumeBackendS3, RootPath: legacyPath})+ }+ }+ if record.BoxID == "" {+ record.BoxID = boxID+ }+ return record, nil+}++// mergeBoxVolumeMountRecord adds mounts' entries to the box's existing record+// and rewrites it, keeping every entry already on disk. It is the in-lock+// write of filestoreVolumeMount, where an in-lock replacement would publish+// just the processed prefix: a volume list whose later volume fails would+// leave the record truncated while the box kept every mount, handing the+// orphan reclaimer live references. The full rewrite that ends a successful+// volume list (recordBoxVolumeMounts) is what makes the record exact again.+func (c *Client) mergeBoxVolumeMountRecord(ctx context.Context, boxID string, mounts []volumeMount) error {if boxID == "" || len(mounts) == 0 {return nil}- pathsByRoot := make(map[string]struct{})+ record, err := c.readBoxVolumeMountRecord(boxID)+ if err != nil {+ return err+ }++ // boxVolumeMountEntry is comparable, so it keys the seen-set directly: an+ // entry already on disk (or repeated within this call) is kept as-is, not+ // duplicated.+ seen := make(map[boxVolumeMountEntry]bool, len(record.Entries)+len(mounts))+ for _, entry := range record.Entries {+ seen[entry] = true+ }for _, mount := range mounts {- pathsByRoot[normalizeVolumePath(mount.rootPath)] = struct{}{}+ entry := boxVolumeMountEntry{+ Backend: mount.backend,+ RootPath: normalizeVolumePath(mount.rootPath),+ FilestoreInstance: mount.filestoreInstance,+ }+ // dataDir is filestore-only; an empty one stays absent rather than+ // normalized into a meaningless "."+ if mount.dataDir != "" {+ entry.DataDir = normalizeVolumePath(mount.dataDir)+ }+ if !seen[entry] {+ seen[entry] = true+ record.Entries = append(record.Entries, entry)+ }}- paths := make([]string, 0, len(pathsByRoot))- for path := range pathsByRoot {- paths = append(paths, path)+ // paths (legacy) is rebuilt from the merged entries under the same deduped+ // rootPath rule recordBoxVolumeMounts writes, so both record readers keep+ // seeing the same reference set.+ record.Paths = dedupedRootPaths(record.Entries)++ return c.writeBoxVolumeMountRecord(ctx, boxID, *record)+}++func (c *Client) recordBoxVolumeMounts(ctx context.Context, boxID string, mounts []volumeMount) error {+ if boxID == "" || len(mounts) == 0 {+ return nil+ }++ // One entry per declared volume. The reclaimer dedups by rootPath, so a+ // box mounting the same instance twice keeps both data directories on+ // record while counting the mount root once.+ entries := make([]boxVolumeMountEntry, 0, len(mounts))+ for _, mount := range mounts {+ entry := boxVolumeMountEntry{+ Backend: mount.backend,+ RootPath: normalizeVolumePath(mount.rootPath),+ FilestoreInstance: mount.filestoreInstance,+ }+ // dataDir is filestore-only; an empty one stays absent rather than+ // normalized into a meaningless "."+ if mount.dataDir != "" {+ entry.DataDir = normalizeVolumePath(mount.dataDir)+ }+ entries = append(entries, entry)}record := boxVolumeMountRecord{- BoxID: boxID,- Paths: paths,+ BoxID: boxID,+ Entries: entries,+ Paths: dedupedRootPaths(entries),+ }++ return c.writeBoxVolumeMountRecord(ctx, boxID, record)+}++// dedupedRootPaths builds the legacy Paths field from entries: the deduped+// rootPath set, in entry order.+//+// paths is written alongside entries for one release cycle: a runner binary+// rolled back to the pre-entries version reads only Paths, and an entries-only+// record would read as zero references — its cleanup would then reclaim live+// mounts. The deduped rootPath set serves both readers. Stop writing it once a+// rollback to a pre-entries binary is no longer possible (remove this helper+// and the struct's Paths field).+func dedupedRootPaths(entries []boxVolumeMountEntry) []string {+ paths := make([]string, 0, len(entries))+ seenRoot := make(map[string]bool, len(entries))+ for _, entry := range entries {+ if !seenRoot[entry.RootPath] {+ seenRoot[entry.RootPath] = true+ paths = append(paths, entry.RootPath)+ }+ }+ return paths+}++// writeBoxVolumeMountRecord persists one box's record: marshal, ensure the+// record directory, write a uniquely named temp sibling, rename over the+// record. Every writer of a record — the full rewrite and the in-lock merge —+// goes through here, so the seam check sits at the top of this function and+// covers them both.+func (c *Client) writeBoxVolumeMountRecord(ctx context.Context, boxID string, record boxVolumeMountRecord) error {+ if c.writeRecordSeam != nil {+ return c.writeRecordSeam(ctx, boxID, record)}data, err := json.Marshal(record)@@ -529,11 +1129,32 @@ func (c *Client) recordBoxVolumeMounts(ctx context.Context, boxID string, mounts}path := filepath.Join(dir, boxID+".json")- if err := os.WriteFile(path, data, 0644); err != nil {- return fmt.Errorf("failed to write volume mount record %s: %w", path, err)+ // Write to a uniquely named sibling temp file and rename. A reader+ // mid-file (the orphan reclaimer scans every record) must see the old+ // content or the new content, never a torn half of both; rename is atomic+ // on the same filesystem. The unique name keeps two concurrent writers of+ // the same box's record (create replay) from truncating each other's temp+ // file, and it never ends in .json, so the scanner skips it.+ tmp, err := os.CreateTemp(dir, boxID+".json.*.tmp")+ if err != nil {+ return fmt.Errorf("failed to create temp volume mount record in %s: %w", dir, err)+ }+ tmpPath := tmp.Name()+ if _, err := tmp.Write(data); err != nil {+ tmp.Close()+ os.Remove(tmpPath)+ return fmt.Errorf("failed to write volume mount record %s: %w", tmpPath, err)+ }+ if err := tmp.Close(); err != nil {+ os.Remove(tmpPath)+ return fmt.Errorf("failed to close volume mount record %s: %w", tmpPath, err)+ }+ if err := os.Rename(tmpPath, path); err != nil {+ os.Remove(tmpPath)+ return fmt.Errorf("failed to replace volume mount record %s: %w", path, err)}- c.logger.DebugContext(ctx, "recorded box volume mounts", "box", boxID, "paths", paths)+ c.logger.DebugContext(ctx, "recorded box volume mounts", "box", boxID, "entries", len(record.Entries))return nil}@@ -552,6 +1173,131 @@ func (c *Client) removeBoxVolumeMountRecord(ctx context.Context, boxID string) ereturn nil}+// removeBoxVolumeMountRecordLocked deletes a box's record under each+// referenced filestore instance's mutex, in turn. A reclaim decision for an+// instance runs under that instance's lock; deleting the record under the+// same lock means the deletion cannot interleave with an in-flight "is this+// mount referenced?" decision for any of the instances the box used (design+// §4.5.3). The file is deleted once — the call is idempotent for the+// remaining instances. Without filestore instances the plain unlocked delete+// keeps the object-storage behavior exactly as it was.+func (c *Client) removeBoxVolumeMountRecordLocked(ctx context.Context, boxID string, instances []string) error {+ return c.mutateBoxVolumeMountRecordLocked(ctx, boxID, instances, func() error {+ return c.removeBoxVolumeMountRecord(ctx, boxID)+ })+}++func (c *Client) mutateBoxVolumeMountRecordLocked(ctx context.Context, boxID string, instances []string, mutate func() error) error {+ locked := make(map[string]bool, len(instances))+ var firstErr error+ for _, instance := range instances {+ if locked[instance] {+ continue+ }+ locked[instance] = true++ mutex := c.volumeMutexFor(filestoreMountPrefix + instance)+ mutex.Lock()+ err := mutate()+ mutex.Unlock()+ if err != nil && firstErr == nil {+ firstErr = err+ }+ }+ if len(locked) == 0 {+ return mutate()+ }+ return firstErr+}++// hasFilestoreRef answers whether the box declares any Filestore volume.+// Only a filestore volume writes its record entry inside the instance+// critical section -- before the volume list completes -- so it is the only+// kind that can leave a partial record behind a getVolumeMounts failure; an+// object-storage-only list writes its record only after the list succeeds.+func hasFilestoreRef(volumes []dto.VolumeDTO) bool {+ for _, vol := range volumes {+ if vol.Filestore != nil {+ return true+ }+ }+ return false+}++// rollbackVolumeMountRecord removes entries owned by a failed attempt without+// discarding references that an existing box recorded before a replay began.+// After a successful record rollback, it reclaims only the declared Filestore+// roots that remain unreferenced.+func (c *Client) rollbackVolumeMountRecord(ctx context.Context, boxID string, volumes []dto.VolumeDTO, prior *boxVolumeMountRecord) {+ var filestoreInstances []string+ for _, vol := range volumes {+ if vol.Filestore != nil {+ filestoreInstances = append(filestoreInstances, vol.Filestore.Instance)+ }+ }+ if prior != nil {+ for _, entry := range prior.Entries {+ if entry.FilestoreInstance != "" {+ filestoreInstances = append(filestoreInstances, entry.FilestoreInstance)+ }+ }+ }++ err := c.mutateBoxVolumeMountRecordLocked(ctx, boxID, filestoreInstances, func() error {+ if prior == nil || len(prior.Entries) == 0 {+ return c.removeBoxVolumeMountRecord(ctx, boxID)+ }+ restored := *prior+ restored.Paths = dedupedRootPaths(restored.Entries)+ return c.writeBoxVolumeMountRecord(ctx, boxID, restored)+ })+ if err != nil {+ c.logger.WarnContext(ctx, "failed to restore box volume mount record after create failure", "box", boxID, "error", err)+ return+ }++ seen := make(map[string]bool)+ for _, instance := range filestoreInstances {+ if seen[instance] || !filestoreInstanceNamePattern.MatchString(instance) {+ continue+ }+ seen[instance] = true+ root := filepath.Join(getVolumeMountBasePath(), filestoreMountPrefix+instance)+ cleanupCtx, cancel := cleanupContext(ctx)+ c.reclaimFilestoreMount(cleanupCtx, root)+ cancel()+ }+}++// readFilestoreInstancesFromRecord parses a box's record and returns the+// distinct filestore instance names it references. A missing record is not an+// error — the box had no volumes, so there is nothing to lock.+func (c *Client) readFilestoreInstancesFromRecord(boxID string) ([]string, error) {+ path := filepath.Join(getVolumeMountRecordDir(), boxID+".json")+ data, err := os.ReadFile(path)+ if err != nil {+ if os.IsNotExist(err) {+ return nil, nil+ }+ return nil, err+ }++ var record boxVolumeMountRecord+ if err := json.Unmarshal(data, &record); err != nil {+ return nil, err+ }++ seen := make(map[string]bool)+ var instances []string+ for _, entry := range record.Entries {+ if entry.FilestoreInstance != "" && !seen[entry.FilestoreInstance] {+ seen[entry.FilestoreInstance] = true+ instances = append(instances, entry.FilestoreInstance)+ }+ }+ return instances, nil+}+func getVolumeMountRecordDir() string {return filepath.Join(getVolumeMountBasePath(), volumeMountRecordDir)}@@ -570,7 +1316,11 @@ func (c *Client) CleanupOrphanedVolumeMounts(ctx context.Context) {}c.lastVolumeCleanup = time.Now()- mountDirs, err := filepath.Glob(filepath.Join(getVolumeMountBasePath(), volumeMountPrefix+"*"))+ // Both mount families live directly under the base: object-storage bucket+ // mounts (`boxlite-volume-*`) and filestore NFS mounts+ // (`boxlite-filestore-*`). Scanning only one family would leave the other+ // family's orphans on the host forever.+ mountDirs, err := c.globOrphanCandidates()if err != nil || len(mountDirs) == 0 {return}@@ -587,6 +1337,19 @@ func (c *Client) CleanupOrphanedVolumeMounts(ctx context.Context) {if inUse[normalizeVolumePath(dir)] {continue}++ // Filestore uses its instance lock, record rescan and pending marker to+ // guard new mounts. Checking recency first would stat a hard NFS mount,+ // which can block forever when the server is unreachable.+ if strings.HasPrefix(filepath.Base(dir), filestoreMountPrefix) {+ if c.volumeCleanup.dryRun {+ c.logger.InfoContext(ctx, "[DRY-RUN] would clean orphaned volume mount", "path", dir)+ continue+ }+ c.logger.InfoContext(ctx, "cleaning orphaned filestore mount", "path", dir)+ c.reclaimFilestoreMount(ctx, dir)+ continue+ }if c.isRecentlyCreated(dir, c.volumeCleanup.exclusionPeriod) {continue}@@ -594,11 +1357,61 @@ func (c *Client) CleanupOrphanedVolumeMounts(ctx context.Context) {c.logger.InfoContext(ctx, "[DRY-RUN] would clean orphaned volume mount", "path", dir)continue}+c.logger.InfoContext(ctx, "cleaning orphaned volume mount", "path", dir)c.unmountAndRemoveDir(ctx, dir)}}+// globOrphanCandidates lists the mount roots of both volume families.+func (c *Client) globOrphanCandidates() ([]string, error) {+ base := getVolumeMountBasePath()+ var dirs []string+ for _, prefix := range []string{volumeMountPrefix, filestoreMountPrefix} {+ matches, err := filepath.Glob(filepath.Join(base, prefix+"*"))+ if err != nil {+ return nil, err+ }+ dirs = append(dirs, matches...)+ }+ return dirs, nil+}++// reclaimFilestoreMount tears down one instance's NFS mount root after+// re-checking the records under the instance's own mutex. The outer cleanup+// loop decided "orphaned" from a scan that is stale the moment it finishes.+// The rescan alone would not close that window: a create between the outer+// scan and this lock would still have its record unwritten. It closes because+// the other side holds this same lock — filestoreVolumeMount keeps the+// instance mutex across mount + data-dir + record write (design §4.5.2), so a+// reference either predates this lock (the rescan sees it) or can only arrive+// after it is released. A mount that reads unreferenced here is genuinely+// unreferenced.+func (c *Client) reclaimFilestoreMount(ctx context.Context, dir string) {+ mountKey := filepath.Base(dir)+ mutex := c.volumeMutexFor(mountKey)+ mutex.Lock()+ defer mutex.Unlock()+ if err := c.checkVolumeOperation(mountKey); err != nil {+ c.logger.DebugContext(ctx, "skipping filestore reclaim while an operation is in flight", "mountRoot", dir)+ return+ }++ inUse, err := c.getRecordedVolumeMounts()+ if err != nil {+ // The reclaimer only ever acts on what the records prove. A record+ // read that fails proves nothing, so the mount survives this round.+ c.logger.WarnContext(ctx, "skipping filestore reclaim, records unreadable", "path", dir, "error", err)+ return+ }+ if inUse[normalizeVolumePath(dir)] {+ c.logger.InfoContext(ctx, "filestore mount became referenced during cleanup, keeping it", "path", dir)+ return+ }++ c.unmountAndRemoveDir(ctx, dir)+}+func (c *Client) getRecordedVolumeMounts() (map[string]bool, error) {inUse := make(map[string]bool)recordDir := getVolumeMountRecordDir()@@ -626,9 +1439,9 @@ func (c *Client) getRecordedVolumeMounts() (map[string]bool, error) {return nil, err}- for _, path := range record.Paths {- cleanPath := normalizeVolumePath(path)- if strings.HasPrefix(cleanPath, filepath.Join(getVolumeMountBasePath(), volumeMountPrefix)) {+ for _, mountEntry := range record.Entries {+ cleanPath := normalizeVolumePath(mountEntry.RootPath)+ if isOwnedMountPath(cleanPath) {inUse[cleanPath] = true}}@@ -637,15 +1450,34 @@ func (c *Client) getRecordedVolumeMounts() (map[string]bool, error) {return inUse, nil}+// isOwnedMountPath answers whether a path sits under one of the prefixes the+// runner mounts volumes at — object storage (`boxlite-volume-`) and filestore+// (`boxlite-filestore-`). The reclaimer checks this in three places: the+// directory scan, the in-use filter, and the unmount guard. All three must+// accept the same set of paths; a guard that misses filestore roots would+// either reclaim a referenced NFS mount (destroying dataDir visibility) or+// never reclaim an orphaned one.+func isOwnedMountPath(path string) bool {+ base := getVolumeMountBasePath()+ for _, prefix := range []string{+ filepath.Join(base, volumeMountPrefix),+ filepath.Join(base, filestoreMountPrefix),+ } {+ if strings.HasPrefix(path, prefix) {+ return true+ }+ }+ return false+}+func (c *Client) unmountAndRemoveDir(ctx context.Context, path string) {mountBasePath := getVolumeMountBasePath()- volumeMountPath := filepath.Join(mountBasePath, volumeMountPrefix)cleanPath := normalizeVolumePath(path)- if !strings.HasPrefix(cleanPath, volumeMountPath) {+ if !isOwnedMountPath(cleanPath) {return}- mounted, probeErr := c.isDirectoryMounted(ctx, cleanPath)+ mounted, probeErr := c.probeMounted(ctx, cleanPath)if probeErr != nil {// The reclaimer runs again; deleting a path we cannot prove is unmounted// would strand the mount under it.diff --git a/apps/runner/pkg/boxlite/volumes_filestore_test.go b/apps/runner/pkg/boxlite/volumes_filestore_test.gonew file mode 100644index 000000000..e5e7b49c5--- /dev/null+++ b/apps/runner/pkg/boxlite/volumes_filestore_test.go@@ -0,0 +1,1738 @@+// Copyright 2026 BoxLite AI+// SPDX-License-Identifier: AGPL-3.0++package boxlite++import (+ "context"+ "crypto/sha256"+ "encoding/json"+ "errors"+ "fmt"+ "net/http"+ "os"+ "os/exec"+ "path/filepath"+ "reflect"+ "strings"+ "sync"+ "sync/atomic"+ "testing"+ "time"++ "github.com/boxlite-ai/runner/pkg/api/dto"+)++// filestoreTestClient is testClient plus the per-key mutex map. volumeMutexFor+// writes into that map on first use, and the map's zero value is nil — only+// NewClient makes it, so a bare testClient would panic the first time an+// ensure-mount or a reclaim takes the per-instance lock.+func filestoreTestClient(t *testing.T) *Client {+ t.Helper()+ c := testClient(t)+ c.volumeMutexes = make(map[string]*sync.Mutex)+ return c+}++// useVolumeMountBasePath points every volume mount path — mount roots, data+// dirs, record files — at dir for the test. The override is a plain package+// variable rather than an env var, so restoring it is manual; tests in this+// package run sequentially, which is what makes the swap safe.+func useVolumeMountBasePath(t *testing.T, dir string) {+ t.Helper()+ volumeMountBasePathOverride = dir+ t.Cleanup(func() { volumeMountBasePathOverride = "" })+}++// installFakeMountpoint replaces the `mountpoint` binary with a script that+// appends its path argument to a log file and exits with code. The reclaim+// teardown (unmountAndRemoveDir) probes with the real exec path, not the+// testProbeRunner seam, so on a host without util-linux the only host-independent+// way to observe "the probe ran on this path" is to be the binary it runs.+// The log path is handed over through the environment because the probe+// command inherits the process environment.+func installFakeMountpoint(t *testing.T, exitCode int) string {+ t.Helper()++ binDir := t.TempDir()+ logPath := filepath.Join(t.TempDir(), "probes.log")++ script := fmt.Sprintf("#!/bin/sh\nprintf '%%s\\n' \"$1\" >> \"%s\"\nexit %d\n", logPath, exitCode)+ if err := os.WriteFile(filepath.Join(binDir, "mountpoint"), []byte(script), 0755); err != nil {+ t.Fatalf("failed to write fake mountpoint: %v", err)+ }++ t.Setenv("PATH", binDir)+ t.Setenv("FAKE_MOUNTPOINT_LOG", logPath)+ return logPath+}++func installFakeFindmnt(t *testing.T, source string) {+ t.Helper()++ binDir := t.TempDir()+ script := "#!/bin/sh\nprintf '%s\\n' \"$FAKE_FILESTORE_SOURCE\"\n"+ if err := os.WriteFile(filepath.Join(binDir, "findmnt"), []byte(script), 0755); err != nil {+ t.Fatalf("failed to write fake findmnt: %v", err)+ }+ t.Setenv("FAKE_FILESTORE_SOURCE", source)+ t.Setenv("PATH", binDir+string(os.PathListSeparator)+os.Getenv("PATH"))+}++func installFakeUmount(t *testing.T) string {+ t.Helper()++ binDir := t.TempDir()+ logPath := filepath.Join(t.TempDir(), "umounts.log")+ script := fmt.Sprintf("#!/bin/sh\nprintf '%%s\\n' \"$1\" >> \"%s\"\n", logPath)+ if err := os.WriteFile(filepath.Join(binDir, "umount"), []byte(script), 0755); err != nil {+ t.Fatalf("failed to write fake umount: %v", err)+ }+ t.Setenv("PATH", binDir+string(os.PathListSeparator)+os.Getenv("PATH"))+ return logPath+}++// commandLog reads a fake command's log as the ordered list of paths it was+// asked to operate on. A missing log means the command never ran.+func commandLog(t *testing.T, logPath string) []string {+ t.Helper()+ data, err := os.ReadFile(logPath)+ if err != nil {+ return nil+ }+ lines := strings.Split(strings.TrimSpace(string(data)), "\n")+ if len(lines) == 1 && lines[0] == "" {+ return nil+ }+ return lines+}++// The mount options are the contract with GCP Filestore discovery: the+// instance is pinned to NFSv4.1 (the only version the Zonal/Regional tiers+// serve) and hard.+// A quiet change here silently hands boxes a mount the instance cannot serve,+// so the whole argv is pinned, not the parts someone remembered.+func TestNfsMountArgsPinsTheProtocol(t *testing.T) {+ path := "/mnt/boxlite-filestore-ml"++ t.Run("defaults pin vers and hard", func(t *testing.T) {+ ref := &dto.FilestoreRef{Instance: "ml", Server: "10.0.0.7", Export: "/vol1"}+ want := []string{"-t", "nfs", "-o", "vers=4.1,hard", "10.0.0.7:/vol1", path}++ if got := nfsMountArgs(ref, path); !reflect.DeepEqual(got, want) {+ t.Errorf("nfsMountArgs mismatch\n got: %v\nwant: %v", got, want)+ }+ })++}++// An NFS mount is a kernel mount with no daemon, so there is nothing that dies+// with the runner service's cgroup — unlike the FUSE backends, the systemd-run+// scope has nothing to protect and must not be added. The hard option makes a+// mount to an unreachable server retry forever, so the 90s mount timeout is+// the only thing that can end such a mount — and it can only do so if the+// command is built with CommandContext. Asserted through Cmd.Cancel, which+// exec.CommandContext sets and exec.Command leaves nil.+func TestNfsMountCmdIsNotSystemdWrappedAndIsContextBound(t *testing.T) {+ c := testClient(t)+ ref := &dto.FilestoreRef{Instance: "ml", Server: "10.0.0.7", Export: "/vol1"}++ cmd := c.getNfsMountCmd(context.Background(), ref, "/mnt/boxlite-filestore-ml")++ if filepathBase(cmd.Args[0]) != "mount" {+ t.Errorf("nfs mount command = %q, want plain mount with no systemd-run scope", filepathBase(cmd.Args[0]))+ }+ if cmd.Cancel == nil {+ t.Error("nfs mount command is not context-bound; a hard mount to an unreachable server could not be killed")+ }+}++func TestFilestoreMountFailureCarriesBoxAndVolumeContext(t *testing.T) {+ c := filestoreTestClient(t)+ useVolumeMountBasePath(t, t.TempDir())+ c.testProbeRunner = func(context.Context, string) (bool, error) { return false, nil }+ mountErr := exec.Command("/bin/sh", "-c", "exit 32").Run()+ var wantExit *exec.ExitError+ if !errors.As(mountErr, &wantExit) {+ t.Fatalf("test mount command returned %v, want *exec.ExitError", mountErr)+ }+ c.testMountRunner = func(*exec.Cmd) error { return mountErr }++ _, err := c.getVolumeMounts(context.Background(), "box1", []dto.VolumeDTO{{+ VolumeId: "vol1",+ MountPath: "/data",+ Filestore: &dto.FilestoreRef{Instance: "ml-scratch", Server: "10.0.0.7", Export: "/vol1"},+ }})+ if err == nil {+ t.Fatal("expected the mount failure")+ }+ for _, want := range []string{"FILESTORE_VOLUME_PREPARE_FAILED", "box1", "vol1", "ml-scratch", "exit status 32"} {+ if !strings.Contains(err.Error(), want) {+ t.Errorf("mount error %q does not contain %q", err, want)+ }+ }+ var gotExit *exec.ExitError+ if !errors.As(err, &gotExit) || gotExit.ExitCode() != 32 {+ t.Errorf("mount error %v does not preserve exit code 32", err)+ }+}++// The volume id is what makes stop/start keep the data — and what makes+// sharing possible: the same volume derives the same directory whatever box+// mounts it, and a destroyed box's data stays reachable under the volume id.+func TestFilestoreDataDirDerivation(t *testing.T) {+ root := "/mnt/boxlite-filestore-ml"++ if got, want := filestoreDataDir(root, "vol1"), filepath.Join(root, "vol1"); got != want {+ t.Errorf("filestoreDataDir(root, vol1) = %q, want %q", got, want)+ }+ if got, want := filestoreDataDir(root, "vol2"), filepath.Join(root, "vol2"); got != want {+ t.Errorf("filestoreDataDir(root, vol2) = %q, want %q", got, want)+ }+}++// The record is what the orphan reclaimer keys off, so a missing backend label,+// a missing dataDir or a torn file would all silently change what cleanup+// decides is ours to delete. The literal written shape is asserted through a+// neutral struct — both entries and the legacy paths field — because the+// record's own compat UnmarshalJSON folds paths into entries and would blur+// the write into a different shape than the file carries.+func TestRecordBoxVolumeMountsWritesEntries(t *testing.T) {+ ctx := context.Background()+ base := t.TempDir()+ useVolumeMountBasePath(t, base)++ s3Root := filepath.Join(base, "boxlite-volume-abc")+ fsRoot := filepath.Join(base, "boxlite-filestore-ml")+ dataDir := filestoreDataDir(fsRoot, "vol1")++ c := filestoreTestClient(t)+ err := c.recordBoxVolumeMounts(ctx, "box1", []volumeMount{+ {hostPath: s3Root, mountPath: "/data", rootPath: s3Root, backend: volumeBackendS3},+ {hostPath: dataDir, mountPath: "/nfs", rootPath: fsRoot, backend: volumeBackendFilestore, dataDir: dataDir, filestoreInstance: "ml"},+ })+ if err != nil {+ t.Fatalf("recordBoxVolumeMounts failed: %v", err)+ }++ data, err := os.ReadFile(filepath.Join(getVolumeMountRecordDir(), "box1.json"))+ if err != nil {+ t.Fatalf("record file missing: %v", err)+ }+ var written struct {+ BoxID string `json:"boxId"`+ Entries []boxVolumeMountEntry `json:"entries"`+ Paths []string `json:"paths"`+ }+ if err := json.Unmarshal(data, &written); err != nil {+ t.Fatalf("record does not parse: %v", err)+ }++ if written.BoxID != "box1" {+ t.Errorf("record boxId = %q, want box1", written.BoxID)+ }+ want := []boxVolumeMountEntry{+ {Backend: volumeBackendS3, RootPath: s3Root},+ {Backend: volumeBackendFilestore, RootPath: fsRoot, FilestoreInstance: "ml", DataDir: dataDir},+ }+ if len(written.Entries) != len(want) {+ t.Fatalf("record has %d entries\n got: %#v\nwant: %#v", len(written.Entries), written.Entries, want)+ }+ for i := range want {+ if !reflect.DeepEqual(written.Entries[i], want[i]) {+ t.Errorf("entry %d mismatch\n got: %#v\nwant: %#v", i, written.Entries[i], want[i])+ }+ }++ // paths (legacy) is written alongside entries for one release cycle: a+ // runner binary rolled back to the pre-entries version reads only paths,+ // and an entries-only record would read as zero references — its cleanup+ // would then reclaim live mounts. Same rootPath set as the entries carry.+ if wantPaths := []string{s3Root, fsRoot}; !reflect.DeepEqual(written.Paths, wantPaths) {+ t.Errorf("record paths = %v, want %v (the legacy double-write)", written.Paths, wantPaths)+ }++ // Read back through the production reader: the fold turns paths into extra+ // entries alongside the real ones, so the reader sees four entries — but+ // the in-use map keys dedup the overlap, and each rootPath counts exactly+ // once. A fold that double-counted would surface here as len(inUse) > 2.+ inUse, err := c.getRecordedVolumeMounts()+ if err != nil {+ t.Fatalf("getRecordedVolumeMounts failed: %v", err)+ }+ if len(inUse) != 2 || !inUse[s3Root] || !inUse[fsRoot] {+ t.Errorf("in-use mounts = %v, want exactly %q and %q once each", inUse, s3Root, fsRoot)+ }++ // The write is temp file plus rename so a reader mid-file never sees a torn+ // half; the temp name does not end in .json precisely so the record scanner+ // skips it. A leftover .tmp means the rename path was skipped or broken.+ leftovers, err := filepath.Glob(filepath.Join(getVolumeMountRecordDir(), "*.tmp"))+ if err != nil {+ t.Fatalf("glob failed: %v", err)+ }+ if len(leftovers) != 0 {+ t.Errorf("record write left temp files behind: %v", leftovers)+ }+}++// A record written before filestore existed carries bare paths and no backend.+// Every reader must see those as object-storage entries — filestore did not+// exist then, and the reclaimer counts the path regardless — so the legacy+// shape folds, the path stays in use, and nothing the old records referenced+// can be reclaimed.+func TestLegacyRecordReadsAsObjectStorageEntries(t *testing.T) {+ base := t.TempDir()+ useVolumeMountBasePath(t, base)++ recordDir := getVolumeMountRecordDir()+ if err := os.MkdirAll(recordDir, 0755); err != nil {+ t.Fatalf("mkdir record dir: %v", err)+ }+ legacyPath := filepath.Join(base, "boxlite-volume-abc")+ legacy := fmt.Sprintf(`{"boxId":"box-legacy","paths":["%s"]}`, legacyPath)+ if err := os.WriteFile(filepath.Join(recordDir, "box-legacy.json"), []byte(legacy), 0644); err != nil {+ t.Fatalf("write legacy record: %v", err)+ }++ // The fold itself: reading the record through the compat path must label+ // the bare path as an object-storage mount.+ var record boxVolumeMountRecord+ data, err := os.ReadFile(filepath.Join(recordDir, "box-legacy.json"))+ if err != nil {+ t.Fatalf("read legacy record: %v", err)+ }+ if err := json.Unmarshal(data, &record); err != nil {+ t.Fatalf("legacy record does not parse: %v", err)+ }+ if len(record.Entries) != 1 || record.Entries[0].Backend != volumeBackendS3 || record.Entries[0].RootPath != legacyPath {+ t.Errorf("legacy record folded to %#v, want one s3 entry for %q", record.Entries, legacyPath)+ }++ c := filestoreTestClient(t)+ inUse, err := c.getRecordedVolumeMounts()+ if err != nil {+ t.Fatalf("getRecordedVolumeMounts failed: %v", err)+ }+ if !inUse[legacyPath] {+ t.Errorf("the legacy path %q is not counted as in use: %v", legacyPath, inUse)+ }+}++// fakeFilestoreMounts installs the two test seams over the NFS mount path so a+// test can drive it without a real mount. The probe answers from the same map+// the fake mount command fills, which is what makes the readiness wait pass:+// the moment a root is "mounted", every later probe sees it — including the+// next goroutine's is-mounted check. Counting real mounts would need a real+// NFS server; counting through these seams needs none.+type fakeFilestoreMounts struct {+ mounts atomic.Int64+ probes atomic.Int64++ mu sync.Mutex+ mounted map[string]bool+}++func installFakeFilestoreMounts(t *testing.T, c *Client) *fakeFilestoreMounts {+ t.Helper()+ installFakeFindmnt(t, "10.0.0.7:/vol1")+ f := &fakeFilestoreMounts{mounted: make(map[string]bool)}+ c.testMountRunner = func(cmd *exec.Cmd) error {+ f.mounts.Add(1)+ f.mu.Lock()+ defer f.mu.Unlock()+ f.mounted[cmd.Args[len(cmd.Args)-1]] = true+ return nil+ }+ c.testProbeRunner = func(_ context.Context, path string) (bool, error) {+ f.probes.Add(1)+ f.mu.Lock()+ defer f.mu.Unlock()+ return f.mounted[path], nil+ }+ return f+}++// Concurrent preparation of filestore volumes on one instance must run the+// mount command exactly once. The per-instance mutex is taken by+// filestoreVolumeMount (ensureFilestoreMounted no longer locks on its own) and+// held across ensure-mount, data directory and record write, so the goroutines+// serialize and whoever wins mounts and becomes ready before releasing the+// lock — everyone else's probe answers "mounted" and skips. This is the+// design's decidable assertion: a mount command per goroutine (10), or a probe+// that cannot mark the map (so every goroutine mounts), both fail here.+func TestConcurrentGetVolumeMountsRunsFilestoreMountOnce(t *testing.T) {+ ctx := context.Background()+ useVolumeMountBasePath(t, t.TempDir())++ c := filestoreTestClient(t)+ fake := installFakeFilestoreMounts(t, c)++ volumes := []dto.VolumeDTO{{VolumeId: "vol-concurrent", MountPath: "/data", Filestore: &dto.FilestoreRef{Instance: "ml-scratch", Server: "10.0.0.7", Export: "/vol1"}}}++ const goroutines = 10+ errs := make([]error, goroutines)+ var wg sync.WaitGroup+ for i := 0; i < goroutines; i++ {+ wg.Add(1)+ go func(i int) {+ defer wg.Done()+ _, err := c.getVolumeMounts(ctx, "box1", volumes)+ errs[i] = err+ }(i)+ }+ wg.Wait()++ for i, err := range errs {+ if err != nil {+ t.Errorf("goroutine %d: getVolumeMounts failed: %v", i, err)+ }+ }+ if got := fake.mounts.Load(); got != 1 {+ t.Errorf("mount command ran %d times, want exactly once", got)+ }+ if got := fake.probes.Load(); got == 0 {+ t.Error("no probe ever ran, so the skip-after-mount path was never exercised")+ }+}++// getVolumeMounts is the whole filestore preparation for a box's volume list:+// under one instance mutex it mounts the instance once (however many volumes+// reference it), derives each volume's data directory from the declaration+// order, and leaves both the directories and the referencing record behind.+// Every observable here is something a box's first bind mount depends on.+func TestGetVolumeMountsPreparesFilestoreVolumes(t *testing.T) {+ ctx := context.Background()+ base := t.TempDir()+ useVolumeMountBasePath(t, base)++ root := filepath.Join(base, filestoreMountPrefix+"ml-scratch")++ c := filestoreTestClient(t)+ fake := installFakeFilestoreMounts(t, c)++ mounts, err := c.getVolumeMounts(ctx, "box1", []dto.VolumeDTO{+ {VolumeId: "vol-a", MountPath: "/a", Filestore: &dto.FilestoreRef{Instance: "ml-scratch", Server: "10.0.0.7", Export: "/vol1"}},+ {VolumeId: "vol-b", MountPath: "/b", Filestore: &dto.FilestoreRef{Instance: "ml-scratch", Server: "10.0.0.7", Export: "/vol1"}},+ })+ if err != nil {+ t.Fatalf("getVolumeMounts failed: %v", err)+ }++ // Two declared volumes on one instance: two distinct data directories,+ // each named by its volume id, behind one shared mount root, both labeled+ // filestore with the instance that backs them.+ want := []volumeMount{+ {+ hostPath: filestoreDataDir(root, "vol-a"),+ mountPath: "/a",+ rootPath: root,+ backend: volumeBackendFilestore,+ dataDir: filestoreDataDir(root, "vol-a"),+ filestoreInstance: "ml-scratch",+ },+ {+ hostPath: filestoreDataDir(root, "vol-b"),+ mountPath: "/b",+ rootPath: root,+ backend: volumeBackendFilestore,+ dataDir: filestoreDataDir(root, "vol-b"),+ filestoreInstance: "ml-scratch",+ },+ }+ if len(mounts) != len(want) {+ t.Fatalf("getVolumeMounts returned %d mounts\n got: %#v\nwant: %#v", len(mounts), mounts, want)+ }+ for i := range want {+ if !reflect.DeepEqual(mounts[i], want[i]) {+ t.Errorf("mount %d mismatch\n got: %#v\nwant: %#v", i, mounts[i], want[i])+ }+ }++ // The data directories must exist on disk and be world-writable: NFS+ // permissions are real, so the chmod after mkdir is load-bearing, not+ // decoration.+ for _, m := range mounts {+ info, err := os.Stat(m.hostPath)+ if err != nil {+ t.Fatalf("data directory %s missing: %v", m.hostPath, err)+ }+ if got := info.Mode().Perm(); got != 0777 {+ t.Errorf("data directory %s has mode %o, want 0777", m.hostPath, got)+ }+ }++ // Both volumes share the instance's mount root, so the mount command runs+ // once for the pair.+ if got := fake.mounts.Load(); got != 1 {+ t.Errorf("mount command ran %d times, want exactly once for two volumes on one instance", got)+ }++ // The referencing record must already carry both entries — and the legacy+ // paths field must carry both volumes' rootPath alongside them, or a+ // rolled-back runner binary would read the box as referencing nothing and+ // reclaim a live mount. Read through a neutral struct: the record's own+ // UnmarshalJSON folds paths into entries and would blur the count.+ data, err := os.ReadFile(filepath.Join(getVolumeMountRecordDir(), "box1.json"))+ if err != nil {+ t.Fatalf("box volume mount record missing: %v", err)+ }+ var written struct {+ Entries []boxVolumeMountEntry `json:"entries"`+ Paths []string `json:"paths"`+ }+ if err := json.Unmarshal(data, &written); err != nil {+ t.Fatalf("record does not parse: %v", err)+ }+ if len(written.Entries) != 2 {+ t.Errorf("record has %d entries, want 2 (one per declared volume): %#v", len(written.Entries), written.Entries)+ }+ for _, m := range mounts {+ found := false+ for _, p := range written.Paths {+ if p == m.rootPath {+ found = true+ break+ }+ }+ if !found {+ t.Errorf("record paths %v does not contain the rootPath %s of volume %s (legacy double-write missing)", written.Paths, m.rootPath, m.mountPath)+ }+ }+}++// The volume id names the data directory — the bucket-alignment contract:+// two boxes mounting the same volume land in the same directory and share+// data, a destroyed box's directory stays reachable by mounting the volume+// into a new box, and one box declaring the same volume at two guest paths+// binds the same directory twice.+func TestFilestoreVolumesShareTheDirectoryByVolumeId(t *testing.T) {+ ctx := context.Background()+ base := t.TempDir()+ useVolumeMountBasePath(t, base)++ c := filestoreTestClient(t)+ installFakeFilestoreMounts(t, c)++ box1, err := c.getVolumeMounts(ctx, "box1", []dto.VolumeDTO{+ {VolumeId: "vol-shared", MountPath: "/data", Filestore: &dto.FilestoreRef{Instance: "ml-scratch", Server: "10.0.0.7", Export: "/vol1"}},+ })+ if err != nil {+ t.Fatalf("box1 getVolumeMounts failed: %v", err)+ }++ // A second box mounting the same volume derives the same data directory:+ // what makes cross-box sharing (and post-destroy remount) real.+ box2, err := c.getVolumeMounts(ctx, "box2", []dto.VolumeDTO{+ {VolumeId: "vol-shared", MountPath: "/data", Filestore: &dto.FilestoreRef{Instance: "ml-scratch", Server: "10.0.0.7", Export: "/vol1"}},+ })+ if err != nil {+ t.Fatalf("box2 getVolumeMounts failed: %v", err)+ }+ if box1[0].hostPath != box2[0].hostPath {+ t.Fatalf("boxes sharing a volume derived different data directories: %q vs %q", box1[0].hostPath, box2[0].hostPath)+ }++ // One box declaring the same volume twice binds the same directory at+ // both guest paths.+ oneBox, err := c.getVolumeMounts(ctx, "box3", []dto.VolumeDTO{+ {VolumeId: "vol-shared", MountPath: "/x", Filestore: &dto.FilestoreRef{Instance: "ml-scratch", Server: "10.0.0.7", Export: "/vol1"}},+ {VolumeId: "vol-shared", MountPath: "/y", Filestore: &dto.FilestoreRef{Instance: "ml-scratch", Server: "10.0.0.7", Export: "/vol1"}},+ })+ if err != nil {+ t.Fatalf("box3 getVolumeMounts failed: %v", err)+ }+ if oneBox[0].hostPath != oneBox[1].hostPath {+ t.Fatalf("one box declaring a volume twice derived different data directories: %q vs %q", oneBox[0].hostPath, oneBox[1].hostPath)+ }+}++// Design §4.5.2 ordering, pinned end to end: the referencing record is written+// inside filestoreVolumeMount's critical section, so the moment getVolumeMounts+// returns the reference is already visible — there is no window in which a+// reclaim's in-lock rescan could miss it. If the record write ever moved out+// of the lock, the reclaim here would proceed past the rescan to the probe+// (and then the umount), the probe counter would move, and this test would+// fail.+func TestRecordWriteHappensUnderTheInstanceLock(t *testing.T) {+ ctx := context.Background()+ base := t.TempDir()+ useVolumeMountBasePath(t, base)+ probeLogPath := installFakeMountpoint(t, 0)+ root := filepath.Join(base, filestoreMountPrefix+"ml-scratch")+ c := filestoreTestClient(t)+ installFakeFilestoreMounts(t, c)++ recordStarted := make(chan struct{})+ allowRecord := make(chan struct{})+ var seam func(context.Context, string, boxVolumeMountRecord) error+ seam = func(ctx context.Context, boxID string, record boxVolumeMountRecord) error {+ close(recordStarted)+ <-allowRecord+ c.writeRecordSeam = nil+ err := c.writeBoxVolumeMountRecord(ctx, boxID, record)+ c.writeRecordSeam = seam+ return err+ }+ c.writeRecordSeam = seam++ createDone := make(chan error, 1)+ go func() {+ _, err := c.getVolumeMounts(ctx, "box1", []dto.VolumeDTO{+ {VolumeId: "vol1", MountPath: "/data", Filestore: &dto.FilestoreRef{Instance: "ml-scratch", Server: "10.0.0.7", Export: "/vol1"}},+ })+ createDone <- err+ }()+ <-recordStarted++ reclaimDone := make(chan struct{})+ go func() {+ c.reclaimFilestoreMount(ctx, root)+ close(reclaimDone)+ }()+ select {+ case <-reclaimDone:+ t.Error("reclaim completed while the record writer held the instance lock")+ case <-time.After(100 * time.Millisecond):+ }+ if got := commandLog(t, probeLogPath); got != nil {+ t.Errorf("reclaim probed %v before the record write completed", got)+ }++ close(allowRecord)+ if err := <-createDone; err != nil {+ t.Fatalf("getVolumeMounts failed: %v", err)+ }+ <-reclaimDone+ if got := commandLog(t, probeLogPath); got != nil {+ t.Errorf("reclaim probed %v after the record became visible", got)+ }+}++// The outer cleanup scan is stale the moment it finishes: between it and the+// unmount, a Create can mount the instance and write a reference record. The+// in-lock rescan is what closes that window — it must see the reference and+// skip before any probe or umount happens. The probe here is the real exec+// path with a fake `mountpoint` binary: if the rescan were ever removed,+// reclaim would reach the probe (and try to unmount a live mount), the log+// would gain an entry, and this test would fail. With the rescan intact the+// probe is never reached.+func TestReclaimRescansRecordsUnderTheInstanceLock(t *testing.T) {+ ctx := context.Background()+ base := t.TempDir()+ useVolumeMountBasePath(t, base)+ probeLogPath := installFakeMountpoint(t, 0 /* claim mounted */)++ root := filepath.Join(base, "boxlite-filestore-ml")+ if err := os.MkdirAll(root, 0755); err != nil {+ t.Fatalf("mkdir mount root: %v", err)+ }++ // Simulate a create that landed between the outer scan and the reclaim:+ // nothing referenced the root when cleanup decided "orphaned", and by the+ // time the reclaim takes the lock, the record exists.+ c := filestoreTestClient(t)+ if err := c.recordBoxVolumeMounts(ctx, "box-late", []volumeMount{+ {hostPath: filestoreDataDir(root, "vol-late"), mountPath: "/nfs", rootPath: root, backend: volumeBackendFilestore, filestoreInstance: "ml"},+ }); err != nil {+ t.Fatalf("recordBoxVolumeMounts failed: %v", err)+ }++ c.reclaimFilestoreMount(ctx, root)++ if got := commandLog(t, probeLogPath); got != nil {+ t.Errorf("reclaim probed %v; the in-lock rescan must see the reference and skip before any probe or umount", got)+ }+}++// The cleanup scan must cover both mount families and act only on what the+// records prove.+//+// a. A filestore root a record still references survives — and to prove the+//+// loop actually ran and decided rather than aborting early, an orphaned+// object-storage directory planted next to it is reclaimed in the same run.+// The filestore root is never probed; the orphan is.+//+// b. A filestore root no record references is reclaimed: the probe (fake,+//+// answering "not a mountpoint") reports not mounted, the directory is+// empty, and it is removed. The probe log naming the root is what makes+// the removal decidable — it shows the reclaim path was reached, rather+// than the run passing because the directory survived for some other+// reason.+func TestCleanupOrphanedVolumeMountsEndToEnd(t *testing.T) {+ ctx := context.Background()++ t.Run("a referenced filestore mount survives", func(t *testing.T) {+ base := t.TempDir()+ useVolumeMountBasePath(t, base)+ probeLogPath := installFakeMountpoint(t, 1 /* not mounted */)++ root := filepath.Join(base, "boxlite-filestore-ml")+ if err := os.MkdirAll(root, 0755); err != nil {+ t.Fatalf("mkdir mount root: %v", err)+ }++ c := filestoreTestClient(t)+ if err := c.recordBoxVolumeMounts(ctx, "box-a", []volumeMount{+ {hostPath: filestoreDataDir(root, "vol-a"), mountPath: "/nfs", rootPath: root, backend: volumeBackendFilestore, filestoreInstance: "ml"},+ }); err != nil {+ t.Fatalf("recordBoxVolumeMounts failed: %v", err)+ }++ // An unreferenced object-storage directory: if cleanup never entered+ // its loop (a glob or records error aborts silently), this control+ // would survive and the survival of the filestore root would mean+ // nothing. Its removal proves the run decided.+ orphan := filepath.Join(base, "boxlite-volume-orphan")+ if err := os.MkdirAll(orphan, 0755); err != nil {+ t.Fatalf("mkdir orphan: %v", err)+ }++ c.CleanupOrphanedVolumeMounts(ctx)++ if _, err := os.Stat(root); err != nil {+ t.Errorf("the referenced filestore root %s did not survive cleanup: %v", root, err)+ }+ if _, err := os.Stat(orphan); !os.IsNotExist(err) {+ t.Errorf("the orphaned object-storage directory %s was not reclaimed (stat err: %v)", orphan, err)+ }+ if got, want := commandLog(t, probeLogPath), []string{orphan}; !reflect.DeepEqual(got, want) {+ t.Errorf("probe log = %v, want exactly [%s]; the referenced root must not be probed at all", got, orphan)+ }+ })++ t.Run("an orphaned filestore mount is reclaimed", func(t *testing.T) {+ base := t.TempDir()+ useVolumeMountBasePath(t, base)+ probeLogPath := installFakeMountpoint(t, 1 /* not mounted */)++ // getRecordedVolumeMounts refuses to act without the records dir, and+ // cleanup honors that refusal — the dir must exist even when empty.+ if err := os.MkdirAll(getVolumeMountRecordDir(), 0755); err != nil {+ t.Fatalf("mkdir record dir: %v", err)+ }+ root := filepath.Join(base, "boxlite-filestore-ml")+ if err := os.MkdirAll(root, 0755); err != nil {+ t.Fatalf("mkdir mount root: %v", err)+ }++ c := filestoreTestClient(t)+ c.CleanupOrphanedVolumeMounts(ctx)++ if _, err := os.Stat(root); !os.IsNotExist(err) {+ t.Errorf("the orphaned filestore root %s was not reclaimed (stat err: %v)", root, err)+ }+ if got, want := commandLog(t, probeLogPath), []string{root}; !reflect.DeepEqual(got, want) {+ t.Errorf("probe log = %v, want exactly [%s]; the reclaim must have reached the probe on the root", got, root)+ }+ })+}++// The volume id names the data directory under the instance's mount root, so+// the id is path material from the dispatching API's hands. A+// traversal-shaped id would escape the mount root entirely; an empty one+// would name the mount root itself, putting every volume of the instance+// behind one box's bind mount. The control plane mints uuids, but this+// boundary must not lean on that — same posture as the box id guard.+func TestCleanupReclaimsRecentOrphanedFilestoreMount(t *testing.T) {+ useVolumeMountBasePath(t, t.TempDir())+ root := filepath.Join(getVolumeMountBasePath(), filestoreMountPrefix+"ml-scratch")+ if err := os.MkdirAll(root, 0755); err != nil {+ t.Fatal(err)+ }+ if err := os.MkdirAll(getVolumeMountRecordDir(), 0755); err != nil {+ t.Fatal(err)+ }+ c := filestoreTestClient(t)+ c.volumeCleanup = volumeCleanupConfig{exclusionPeriod: time.Hour}+ c.testProbeRunner = func(context.Context, string) (bool, error) { return true, nil }+ umountLogPath := installFakeUmount(t)++ c.CleanupOrphanedVolumeMounts(context.Background())++ if got, want := commandLog(t, umountLogPath), []string{root}; !reflect.DeepEqual(got, want) {+ t.Fatalf("umount log = %v, want %v; instance-lock reclaim must guard the recent mount instead of stating the NFS root", got, want)+ }+}++func TestFilestoreVolumeIdIsPathGuarded(t *testing.T) {+ ctx := context.Background()+ base := t.TempDir()+ useVolumeMountBasePath(t, base)++ c := filestoreTestClient(t)+ fake := installFakeFilestoreMounts(t, c)++ for _, id := range []string{"", ".", "../escape", "a/b", "a\\b", ".."} {+ _, err := c.getVolumeMounts(ctx, "box1", []dto.VolumeDTO{+ {VolumeId: id, MountPath: "/data", Filestore: &dto.FilestoreRef{Instance: "ml-scratch", Server: "10.0.0.7", Export: "/vol1"}},+ })+ if err == nil {+ t.Fatalf("volume id %q: expected the path guard to refuse it, got nil", id)+ }+ if !strings.Contains(err.Error(), "invalid filestore volume id") {+ t.Fatalf("volume id %q: expected the volume id guard error, got %q", id, err)+ }+ }++ // The refusal must precede all mount and directory work: nothing ran.+ if fake.mounts.Load() != 0 {+ t.Errorf("mount command ran %d times; the guard must refuse before any mount work", fake.mounts.Load())+ }+}++func TestFilestoreInstanceIsPathGuarded(t *testing.T) {+ ctx := context.Background()+ base := t.TempDir()+ useVolumeMountBasePath(t, base)++ c := filestoreTestClient(t)+ fake := installFakeFilestoreMounts(t, c)++ for _, instance := range []string{"", "../escape", "a/b", "a\\b", "ML", "-ml", strings.Repeat("a", 64)} {+ _, err := c.getVolumeMounts(ctx, "box1", []dto.VolumeDTO{+ {VolumeId: "vol-1", MountPath: "/data", Filestore: &dto.FilestoreRef{Instance: instance, Server: "10.0.0.7", Export: "/vol1"}},+ })+ if err == nil {+ t.Fatalf("instance %q: expected the path guard to refuse it, got nil", instance)+ }+ if !strings.Contains(err.Error(), "invalid filestore instance") {+ t.Fatalf("instance %q: expected the instance guard error, got %q", instance, err)+ }+ }++ if fake.mounts.Load() != 0 {+ t.Errorf("mount command ran %d times; the guard must refuse before any mount work", fake.mounts.Load())+ }+}++func TestFilestoreVolumeRejectsSubpath(t *testing.T) {+ ctx := context.Background()+ base := t.TempDir()+ useVolumeMountBasePath(t, base)++ c := filestoreTestClient(t)+ fake := installFakeFilestoreMounts(t, c)+ subpath := "nested"++ _, err := c.getVolumeMounts(ctx, "box1", []dto.VolumeDTO{+ {VolumeId: "vol-1", MountPath: "/data", Subpath: &subpath, Filestore: &dto.FilestoreRef{Instance: "ml-scratch", Server: "10.0.0.7", Export: "/vol1"}},+ })+ if err == nil {+ t.Fatal("expected filestore plus subpath to be refused, got nil")+ }+ if !strings.Contains(err.Error(), "subpath is not supported for filestore volumes") {+ t.Fatalf("expected the filestore subpath error, got %q", err)+ }+ if fake.mounts.Load() != 0 {+ t.Errorf("mount command ran %d times; subpath rejection must precede mount work", fake.mounts.Load())+ }+}++func TestCreateReclaimsNewMountWhenPreparationFailsBeforeFirstRecord(t *testing.T) {+ ctx := context.Background()+ base := t.TempDir()+ useVolumeMountBasePath(t, base)+ c := filestoreTestClient(t)+ fake := installFakeFilestoreMounts(t, c)+ umountLogPath := installFakeUmount(t)+ c.prepareRunner = func(string) error { return errors.New("injected prepare failure") }+ root := filepath.Join(base, filestoreMountPrefix+"ml-scratch")+ recordDir := getVolumeMountRecordDir()+ if _, err := os.Stat(recordDir); !os.IsNotExist(err) {+ t.Fatalf("record directory existed before the first mount: %v", err)+ }++ outbound := true+ _, _, err := c.Create(ctx, dto.CreateBoxDTO{+ Id: "abc123def456", OutboundEnabled: &outbound,+ Volumes: []dto.VolumeDTO{{+ VolumeId: "vol-ok", MountPath: "/data", Filestore: &dto.FilestoreRef{Instance: "ml-scratch", Server: "10.0.0.7", Export: "/vol1"},+ }},+ })+ if err == nil || !strings.Contains(err.Error(), "injected prepare failure") {+ t.Fatalf("Create returned %v, want prepare failure", err)+ }+ if got := fake.mounts.Load(); got != 1 {+ t.Fatalf("mount command ran %d times, want one ready mount before preparation", got)+ }+ if got, want := commandLog(t, umountLogPath), []string{root}; !reflect.DeepEqual(got, want) {+ t.Errorf("umount log = %v, want %v; preparation failed before the first record and stranded the new mount", got, want)+ }+ if _, statErr := os.Stat(root); !os.IsNotExist(statErr) {+ t.Errorf("new filestore root survived preparation failure: %v", statErr)+ }+}++// A create that fails partway through its volume list must remove the partial+// record and reclaim the NFS mount when no box references it. A reference from+// another box must keep the mount intact through the same rollback.+func TestCreateRollsBackTheRecordWhenALaterVolumeFails(t *testing.T) {+ ctx := context.Background()+ base := t.TempDir()+ useVolumeMountBasePath(t, base)++ c := filestoreTestClient(t)+ installFakeFilestoreMounts(t, c)+ umountLogPath := installFakeUmount(t)+ root := filepath.Join(base, filestoreMountPrefix+"ml-scratch")+ boxID := "abc123def456"+ outbound := true+ volumes := []dto.VolumeDTO{+ {VolumeId: "vol-ok", MountPath: "/a", Filestore: &dto.FilestoreRef{Instance: "ml-scratch", Server: "10.0.0.7", Export: "/vol1"}},+ {VolumeId: "../escape", MountPath: "/b", Filestore: &dto.FilestoreRef{Instance: "ml-scratch", Server: "10.0.0.7", Export: "/vol1"}},+ }++ _, _, err := c.Create(ctx, dto.CreateBoxDTO{+ Id: boxID,+ OutboundEnabled: &outbound,+ Volumes: volumes,+ })+ if err == nil {+ t.Fatal("expected the volume-id guard failure from the second volume, got nil")+ }+ if !strings.Contains(err.Error(), "invalid filestore volume id") {+ t.Fatalf("expected the volume-id guard error, got %q", err)+ }++ recordPath := filepath.Join(getVolumeMountRecordDir(), boxID+".json")+ if _, statErr := os.Stat(recordPath); !os.IsNotExist(statErr) {+ t.Fatalf("volume mount record survived the failed create: %v", statErr)+ }+ if got, want := commandLog(t, umountLogPath), []string{root}; !reflect.DeepEqual(got, want) {+ t.Errorf("umount log = %v, want %v; the failed create left its unreferenced mount behind", got, want)+ }+ if _, statErr := os.Stat(root); !os.IsNotExist(statErr) {+ t.Errorf("unreferenced filestore root survived the failed create: %v", statErr)+ }++ c = filestoreTestClient(t)+ installFakeFilestoreMounts(t, c)+ umountLogPath = installFakeUmount(t)+ if _, err := c.getVolumeMounts(ctx, "box-other", volumes[:1]); err != nil {+ t.Fatalf("failed to establish another box's mount reference: %v", err)+ }++ _, _, err = c.Create(ctx, dto.CreateBoxDTO{+ Id: boxID,+ OutboundEnabled: &outbound,+ Volumes: volumes,+ })+ if err == nil || !strings.Contains(err.Error(), "invalid filestore volume id") {+ t.Fatalf("Create with an existing reference returned %v, want volume-id failure", err)+ }+ if got := commandLog(t, umountLogPath); got != nil {+ t.Errorf("rollback unmounted %v despite another box's reference", got)+ }+ if _, statErr := os.Stat(root); statErr != nil {+ t.Errorf("filestore root referenced by another box was removed: %v", statErr)+ }+ if _, readErr := c.readBoxVolumeMountRecord("box-other"); readErr != nil {+ t.Errorf("another box's reference did not survive rollback: %v", readErr)+ }+}++// A Start's metadata replay re-prepares the box's volumes while the box's+// record from its create is already on disk. The filestore volume writes its+// entry inside the instance critical section BEFORE the rest of the volume+// list is processed; when a later volume fails there (here: the object-storage+// volume's FUSE ensure), the error propagates and the replay never reaches the+// full record rewrite that ends a successful one. The in-lock write must MERGE+// into the existing record, never replace it: a replacement publishes only the+// processed prefix, the truncated record stops counting the s3 volume's+// reference, and the orphan reclaimer would reclaim a live mount of a box that+// is still running.+func TestStartReplayFailureKeepsExistingRecordEntries(t *testing.T) {+ ctx := context.Background()+ base := t.TempDir()+ useVolumeMountBasePath(t, base)++ c := filestoreTestClient(t)+ installFakeFilestoreMounts(t, c)+ // The filestore root probes mounted (its work is done); the object-storage+ // mount root's probe is the injected failure, so getVolumeMounts dies on+ // the second volume of the list.+ c.testProbeRunner = func(_ context.Context, path string) (bool, error) {+ if strings.Contains(path, volumeMountPrefix) {+ return false, fmt.Errorf("injected fuse ensure failure")+ }+ return true, nil+ }++ fsRoot := filepath.Join(base, filestoreMountPrefix+"ml-scratch")+ s3Root := filepath.Join(base, volumeMountPrefix+"vol-x")+ dataDir := filestoreDataDir(fsRoot, "vol-ok")++ // The box was created earlier and its full record is on disk: one+ // filestore volume, one object-storage volume.+ if err := c.recordBoxVolumeMounts(ctx, "abc123def456", []volumeMount{+ {hostPath: dataDir, mountPath: "/a", rootPath: fsRoot, backend: volumeBackendFilestore, dataDir: dataDir, filestoreInstance: "ml-scratch"},+ {hostPath: s3Root, mountPath: "/b", rootPath: s3Root, backend: volumeBackendS3},+ }); err != nil {+ t.Fatalf("recordBoxVolumeMounts failed: %v", err)+ }++ metadata := map[string]string{+ "volumes": `[{"volumeId":"vol-ok","mountPath":"/a","filestore":{"instance":"ml-scratch","server":"10.0.0.7","export":"/vol1"}},{"volumeId":"vol-x","mountPath":"/b"}]`,+ }+ err := c.ensureVolumeMountsFromMetadata(ctx, "abc123def456", metadata)+ if err == nil {+ t.Fatal("expected the injected fuse ensure failure to propagate out of the replay, got nil")+ }+ if !strings.Contains(err.Error(), "injected fuse ensure failure") {+ t.Fatalf("expected the injected fuse ensure failure, got %q", err)+ }++ // Both entries must still be on record. The pinned failure mode: an+ // in-lock write that REPLACED the record would leave only the filestore+ // entry behind; the truncated record would stop counting the s3+ // reference, and the reclaimer would reclaim a running box's live mount.+ // Presence is asserted (through the folding reader) rather than an exact+ // shape: the reader legitimately re-folds the legacy paths field into+ // extra s3 entries, so the entry count is not the contract here.+ record, err := c.readBoxVolumeMountRecord("abc123def456")+ if err != nil {+ t.Fatalf("readBoxVolumeMountRecord failed: %v", err)+ }+ var haveFilestore, haveS3 bool+ for _, entry := range record.Entries {+ if entry.Backend == volumeBackendFilestore && entry.DataDir == dataDir && entry.FilestoreInstance == "ml-scratch" {+ haveFilestore = true+ }+ if entry.Backend == volumeBackendS3 && entry.RootPath == s3Root {+ haveS3 = true+ }+ }+ if !haveFilestore || !haveS3 {+ t.Errorf("record after the failed replay = %#v; want both the filestore entry (dataDir %s) and the s3 entry (rootPath %s) kept", record.Entries, dataDir, s3Root)+ }+}++// The other half of the replay contract: when every volume's preparation+// succeeds, the replay ends with a full record rewrite, so the record ends up+// exactly matching the metadata — not a merge of the metadata and whatever the+// record happened to carry. The stale filestore entry seeded below must be+// gone after the replay.+func TestStartReplayRewritesTheFullRecord(t *testing.T) {+ ctx := context.Background()+ base := t.TempDir()+ useVolumeMountBasePath(t, base)++ c := filestoreTestClient(t)+ c.volumeBackend = volumeBackendS3+ installFakeFilestoreMounts(t, c)+ // Every probe answers mounted. The object-storage FUSE mount exec runs+ // through cmd.Run, not the testMountRunner seam, so the fake mount marking can+ // never close the loop with the fake probe for it — "already mounted" is+ // the only host-independent way through.+ c.testProbeRunner = func(context.Context, string) (bool, error) { return true, nil }++ fsRoot := filepath.Join(base, filestoreMountPrefix+"ml-scratch")+ s3Root := filepath.Join(base, volumeMountPrefix+"vol-x")++ // A stale entry from the box's earlier life: the full rewrite must drop it.+ if err := c.recordBoxVolumeMounts(ctx, "abc123def456", []volumeMount{+ {hostPath: filestoreDataDir(fsRoot, "vol-gone"), mountPath: "/old", rootPath: fsRoot, backend: volumeBackendFilestore, dataDir: filestoreDataDir(fsRoot, "vol-gone"), filestoreInstance: "ml-scratch"},+ }); err != nil {+ t.Fatalf("recordBoxVolumeMounts failed: %v", err)+ }++ metadata := map[string]string{+ "volumes": `[{"volumeId":"vol-ok","mountPath":"/a","filestore":{"instance":"ml-scratch","server":"10.0.0.7","export":"/vol1"}},{"volumeId":"vol-x","mountPath":"/b"}]`,+ }+ if err := c.ensureVolumeMountsFromMetadata(ctx, "abc123def456", metadata); err != nil {+ t.Fatalf("ensureVolumeMountsFromMetadata failed: %v", err)+ }++ // Asserted through a neutral struct, both entries and the legacy paths+ // field: the record's own compat UnmarshalJSON folds paths into entries+ // and would blur the written shape into a different one than the file+ // carries.+ data, err := os.ReadFile(filepath.Join(getVolumeMountRecordDir(), "abc123def456.json"))+ if err != nil {+ t.Fatalf("record file missing: %v", err)+ }+ var written struct {+ Entries []boxVolumeMountEntry `json:"entries"`+ Paths []string `json:"paths"`+ }+ if err := json.Unmarshal(data, &written); err != nil {+ t.Fatalf("record does not parse: %v", err)+ }+ want := []boxVolumeMountEntry{+ {Backend: volumeBackendFilestore, RootPath: fsRoot, FilestoreInstance: "ml-scratch", DataDir: filestoreDataDir(fsRoot, "vol-ok")},+ {Backend: volumeBackendS3, RootPath: s3Root},+ }+ if !reflect.DeepEqual(written.Entries, want) {+ t.Errorf("record entries after the replay\n got: %#v\nwant: %#v", written.Entries, want)+ }+ if wantPaths := []string{fsRoot, s3Root}; !reflect.DeepEqual(written.Paths, wantPaths) {+ t.Errorf("record paths = %v, want %v", written.Paths, wantPaths)+ }+}++// The final full-list record write of Create can fail after earlier volumes+// already published their entries in-lock (here: the write seam fails exactly+// that write while the in-lock merge write before it lands through the real+// write path). The failed create must remove the record: no box ever exists to+// destroy, so a surviving entry would count a reference forever and keep the+// NFS mount from ever reclaiming. Same rule as the later-volume-failure path+// above, one step later in Create.+func TestCreateRollsBackTheRecordWhenTheFinalWriteFails(t *testing.T) {+ ctx := context.Background()+ base := t.TempDir()+ useVolumeMountBasePath(t, base)++ c := filestoreTestClient(t)+ installFakeFilestoreMounts(t, c)++ // The seam fails exactly the full-list write (Create's second record+ // write); the in-lock merge write before it must land through the real+ // write path, so the seam removes itself for that one call. The write runs+ // under the instance mutex on this goroutine, so the swap races nothing.+ var writes atomic.Int64+ var seam func(context.Context, string, boxVolumeMountRecord) error+ seam = func(ctx context.Context, boxID string, record boxVolumeMountRecord) error {+ if writes.Add(1) == 2 {+ return fmt.Errorf("injected final record write failure")+ }+ c.writeRecordSeam = nil+ err := c.writeBoxVolumeMountRecord(ctx, boxID, record)+ c.writeRecordSeam = seam+ return err+ }+ c.writeRecordSeam = seam++ outbound := true+ _, _, err := c.Create(ctx, dto.CreateBoxDTO{+ Id: "abc123def456",+ OutboundEnabled: &outbound,+ Volumes: []dto.VolumeDTO{+ {VolumeId: "vol-ok", MountPath: "/a", Filestore: &dto.FilestoreRef{Instance: "ml-scratch", Server: "10.0.0.7", Export: "/vol1"}},+ },+ })+ if err == nil {+ t.Fatal("expected the injected final record write failure, got nil")+ }+ if !strings.Contains(err.Error(), "injected final record write failure") {+ t.Fatalf("expected the injected write failure, got %q", err)+ }++ // The volume's entry was already on disk inside its instance critical+ // section when the final write failed. The failed create must remove it.+ recordPath := filepath.Join(getVolumeMountRecordDir(), "abc123def456.json")+ if _, statErr := os.Stat(recordPath); !os.IsNotExist(statErr) {+ t.Fatalf("volume mount record survived the failed create: %v", statErr)+ }+}++func TestFilestoreTargetRequiredWhenAlreadyMounted(t *testing.T) {+ for _, ref := range []*dto.FilestoreRef{+ {Instance: "ml", Export: "/vol1"},+ {Instance: "ml", Server: "10.0.0.7"},+ } {+ c := filestoreTestClient(t)+ c.testProbeRunner = func(context.Context, string) (bool, error) { return true, nil }++ err := c.ensureFilestoreMounted(context.Background(), ref, filepath.Join(t.TempDir(), "mounted"), "boxlite-filestore-ml")+ if err == nil || !strings.Contains(err.Error(), "requires both server and export") {+ t.Fatalf("ensureFilestoreMounted with ref %#v returned %v, want missing-target error", ref, err)+ }+ }+}++func TestFilestoreValidatesTargetForEveryReference(t *testing.T) {+ useVolumeMountBasePath(t, t.TempDir())+ c := filestoreTestClient(t)+ fake := installFakeFilestoreMounts(t, c)++ _, err := c.getVolumeMounts(context.Background(), "box1", []dto.VolumeDTO{+ {VolumeId: "vol-a", MountPath: "/a", Filestore: &dto.FilestoreRef{Instance: "ml-scratch", Server: "10.0.0.7", Export: "/vol1"}},+ {VolumeId: "vol-b", MountPath: "/b", Filestore: &dto.FilestoreRef{Instance: "ml-scratch", Export: "/vol1"}},+ })+ if err == nil || !strings.Contains(err.Error(), "requires both server and export") {+ t.Fatalf("second reference returned %v, want missing-target error", err)+ }+ if got := fake.mounts.Load(); got != 1 {+ t.Fatalf("mount command ran %d times, want only the first valid reference to mount", got)+ }+}++func TestFilestoreRejectsConflictingTargetsWithinRequest(t *testing.T) {+ useVolumeMountBasePath(t, t.TempDir())+ c := filestoreTestClient(t)+ fake := installFakeFilestoreMounts(t, c)++ _, err := c.getVolumeMounts(context.Background(), "box1", []dto.VolumeDTO{+ {VolumeId: "vol-a", MountPath: "/a", Filestore: &dto.FilestoreRef{Instance: "ml-scratch", Server: "10.0.0.7", Export: "/vol1"}},+ {VolumeId: "vol-b", MountPath: "/b", Filestore: &dto.FilestoreRef{Instance: "ml-scratch", Server: "10.0.0.8", Export: "/vol2"}},+ })+ if err == nil || !strings.Contains(err.Error(), "conflicting filestore target") {+ t.Fatalf("conflicting request returned %v, want conflicting-target error", err)+ }+ if got := fake.mounts.Load(); got != 1 {+ t.Fatalf("conflicting request ran %d mount commands, want only the first target to mount", got)+ }+ if _, statErr := os.Stat(filestoreDataDir(filepath.Join(getVolumeMountBasePath(), filestoreMountPrefix+"ml-scratch"), "vol-b")); !os.IsNotExist(statErr) {+ t.Fatalf("conflicting reference prepared its data directory: %v", statErr)+ }+}++func TestFilestoreRejectsReusingDifferentTarget(t *testing.T) {+ useVolumeMountBasePath(t, t.TempDir())+ c := filestoreTestClient(t)+ fake := installFakeFilestoreMounts(t, c)++ first := dto.VolumeDTO{VolumeId: "vol-a", MountPath: "/a", Filestore: &dto.FilestoreRef{Instance: "ml-scratch", Server: "10.0.0.7", Export: "/vol1"}}+ if _, err := c.getVolumeMounts(context.Background(), "box1", []dto.VolumeDTO{first}); err != nil {+ t.Fatalf("first mount failed: %v", err)+ }++ second := dto.VolumeDTO{VolumeId: "vol-b", MountPath: "/b", Filestore: &dto.FilestoreRef{Instance: "ml-scratch", Server: "10.0.0.8", Export: "/vol1"}}+ _, err := c.getVolumeMounts(context.Background(), "box2", []dto.VolumeDTO{second})+ if err == nil || !strings.Contains(err.Error(), "mount target mismatch") {+ t.Fatalf("changed target returned %v, want mount target mismatch", err)+ }+ if got := fake.mounts.Load(); got != 1 {+ t.Fatalf("changed target ran %d mount commands, want reuse without remounting", got)+ }+}++func TestCreateRollbackReclaimsAfterCancellation(t *testing.T) {+ useVolumeMountBasePath(t, t.TempDir())+ c := filestoreTestClient(t)+ fake := installFakeFilestoreMounts(t, c)+ umountLogPath := installFakeUmount(t)+ probe := c.testProbeRunner+ c.testProbeRunner = func(ctx context.Context, path string) (bool, error) {+ if err := ctx.Err(); err != nil {+ return false, err+ }+ return probe(ctx, path)+ }+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ var seam func(context.Context, string, boxVolumeMountRecord) error+ seam = func(ctx context.Context, boxID string, record boxVolumeMountRecord) error {+ c.writeRecordSeam = nil+ err := c.writeBoxVolumeMountRecord(ctx, boxID, record)+ c.writeRecordSeam = seam+ cancel()+ return err+ }+ c.writeRecordSeam = seam+ outbound := true++ _, _, err := c.Create(ctx, dto.CreateBoxDTO{+ Id: "abc123def456", OutboundEnabled: &outbound,+ Volumes: []dto.VolumeDTO{+ {VolumeId: "vol-ok", MountPath: "/a", Filestore: &dto.FilestoreRef{Instance: "ml-scratch", Server: "10.0.0.7", Export: "/vol1"}},+ {VolumeId: "../escape", MountPath: "/b", Filestore: &dto.FilestoreRef{Instance: "ml-scratch", Server: "10.0.0.7", Export: "/vol1"}},+ },+ })+ if err == nil || !strings.Contains(err.Error(), "invalid filestore volume id") {+ t.Fatalf("Create returned %v, want the second volume's guard failure", err)+ }+ root := filepath.Join(getVolumeMountBasePath(), filestoreMountPrefix+"ml-scratch")+ if got, want := commandLog(t, umountLogPath), []string{root}; !reflect.DeepEqual(got, want) {+ t.Fatalf("umount log after cancelled rollback = %v, want %v (mounts=%d)", got, want, fake.mounts.Load())+ }+}++func TestCreateReclaimsMountAfterLatePreparationCompletes(t *testing.T) {+ useVolumeMountBasePath(t, t.TempDir())+ c := filestoreTestClient(t)+ installFakeFilestoreMounts(t, c)+ umountLogPath := installFakeUmount(t)+ started := make(chan struct{})+ release := make(chan struct{})+ c.prepareRunner = func(string) error {+ close(started)+ <-release+ return nil+ }++ ctx, cancel := context.WithCancel(context.Background())+ done := make(chan error, 1)+ outbound := true+ go func() {+ _, _, err := c.Create(ctx, dto.CreateBoxDTO{+ Id: "abc123def456", OutboundEnabled: &outbound,+ Volumes: []dto.VolumeDTO{{+ VolumeId: "vol1", MountPath: "/data", Filestore: &dto.FilestoreRef{Instance: "ml-scratch", Server: "10.0.0.7", Export: "/vol1"},+ }},+ })+ done <- err+ }()+ <-started+ cancel()+ select {+ case err := <-done:+ if err == nil || !strings.Contains(err.Error(), "context canceled") {+ t.Fatalf("cancelled Create returned %v, want context cancellation", err)+ }+ case <-time.After(2 * time.Second):+ t.Fatal("Create did not return after cancellation")+ }++ close(release)+ root := filepath.Join(getVolumeMountBasePath(), filestoreMountPrefix+"ml-scratch")+ deadline := time.Now().Add(12 * time.Second)+ for !reflect.DeepEqual(commandLog(t, umountLogPath), []string{root}) && time.Now().Before(deadline) {+ time.Sleep(10 * time.Millisecond)+ }+ if got, want := commandLog(t, umountLogPath), []string{root}; !reflect.DeepEqual(got, want) {+ t.Fatalf("umount log after late preparation = %v, want %v", got, want)+ }+}++func TestCreateReclaimsLateFirstMountAfterCancellation(t *testing.T) {+ useVolumeMountBasePath(t, t.TempDir())+ c := filestoreTestClient(t)+ fake := installFakeFilestoreMounts(t, c)+ umountLogPath := installFakeUmount(t)+ started := make(chan struct{})+ release := make(chan struct{})+ c.testMountRunner = func(cmd *exec.Cmd) error {+ fake.mounts.Add(1)+ close(started)+ <-release+ fake.mu.Lock()+ fake.mounted[cmd.Args[len(cmd.Args)-1]] = true+ fake.mu.Unlock()+ return nil+ }++ ctx, cancel := context.WithCancel(context.Background())+ done := make(chan error, 1)+ outbound := true+ go func() {+ _, _, err := c.Create(ctx, dto.CreateBoxDTO{+ Id: "abc123def456", OutboundEnabled: &outbound,+ Volumes: []dto.VolumeDTO{{+ VolumeId: "vol1", MountPath: "/data", Filestore: &dto.FilestoreRef{Instance: "ml-scratch", Server: "10.0.0.7", Export: "/vol1"},+ }},+ })+ done <- err+ }()+ <-started+ cancel()+ select {+ case err := <-done:+ if err == nil || !strings.Contains(err.Error(), "context canceled") {+ t.Fatalf("cancelled Create returned %v, want context cancellation", err)+ }+ case <-time.After(2 * time.Second):+ t.Fatal("Create did not return after cancellation")+ }++ close(release)+ root := filepath.Join(getVolumeMountBasePath(), filestoreMountPrefix+"ml-scratch")+ deadline := time.Now().Add(12 * time.Second)+ for !reflect.DeepEqual(commandLog(t, umountLogPath), []string{root}) && time.Now().Before(deadline) {+ time.Sleep(10 * time.Millisecond)+ }+ if got, want := commandLog(t, umountLogPath), []string{root}; !reflect.DeepEqual(got, want) {+ entries, recordErr := os.ReadDir(getVolumeMountRecordDir())+ mounted, probeErr := c.probeMounted(context.Background(), root)+ t.Fatalf("umount log after late mount completion = %v, want %v (pending=%v, records=%v, recordErr=%v, mounted=%v, probeErr=%v, PATH=%s)", got, want, c.checkVolumeOperation(filestoreMountPrefix+"ml-scratch"), entries, recordErr, mounted, probeErr, os.Getenv("PATH"))+ }+}++func TestObjectStorageReplayRepairsMalformedRecord(t *testing.T) {+ useVolumeMountBasePath(t, t.TempDir())+ c := filestoreTestClient(t)+ 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 true, nil }+ c.clearPublishedRunner = func() error { return errors.New("injected stop after record write") }+ var repaired *boxVolumeMountRecord+ var seam func(context.Context, string, boxVolumeMountRecord) error+ seam = func(ctx context.Context, id string, record boxVolumeMountRecord) error {+ repaired = &record+ c.writeRecordSeam = nil+ err := c.writeBoxVolumeMountRecord(ctx, id, record)+ c.writeRecordSeam = seam+ return err+ }+ c.writeRecordSeam = seam++ outbound := true+ _, _, err := c.Create(context.Background(), dto.CreateBoxDTO{+ Id: boxID, OutboundEnabled: &outbound,+ Volumes: []dto.VolumeDTO{{VolumeId: "vol-object", MountPath: "/data"}},+ })+ if err == nil || !strings.Contains(err.Error(), "injected stop after record write") {+ t.Fatalf("object-storage replay returned %v, want the post-record-write error", err)+ }+ if repaired == nil {+ t.Fatal("object-storage replay did not replace the malformed record")+ }+ root := filepath.Join(getVolumeMountBasePath(), volumeMountPrefix+"vol-object")+ if len(repaired.Entries) != 1 || repaired.Entries[0].RootPath != root {+ t.Fatalf("repaired record = %#v, want only the object-storage root %q", repaired.Entries, root)+ }+ persisted, readErr := c.readBoxVolumeMountRecord(boxID)+ if readErr != nil || len(persisted.Entries) != 1 || persisted.Entries[0].RootPath != root {+ t.Fatalf("record after ClearPublished failure = %#v, %v; want the repaired object-storage record to survive", persisted.Entries, readErr)+ }+}++func TestObjectStorageReplayKeepsRecordWhenNativeIDResolutionFails(t *testing.T) {+ useVolumeMountBasePath(t, t.TempDir())+ c := filestoreTestClient(t)+ c.homeDir = t.TempDir()+ c.testProbeRunner = func(context.Context, string) (bool, error) { return true, nil }+ boxID := "abc123def456"+ root := filepath.Join(getVolumeMountBasePath(), volumeMountPrefix+"vol-object")+ if err := c.recordBoxVolumeMounts(context.Background(), boxID, []volumeMount{{+ hostPath: root, mountPath: "/data", rootPath: root, backend: volumeBackendS3,+ }}); err != nil {+ t.Fatal(err)+ }+ journalPath := filepath.Join(c.homeDir, "work", "checkpoint-operations", fmt.Sprintf("%x", sha256.Sum256([]byte(boxID)))+".json")+ var seam func(context.Context, string, boxVolumeMountRecord) error+ seam = func(ctx context.Context, id string, record boxVolumeMountRecord) error {+ c.writeRecordSeam = nil+ err := c.writeBoxVolumeMountRecord(ctx, id, record)+ c.writeRecordSeam = seam+ if err != nil {+ return err+ }+ return os.WriteFile(journalPath, []byte("not-json"), 0600)+ }+ c.writeRecordSeam = seam+ outbound := true++ _, _, err := c.Create(context.Background(), dto.CreateBoxDTO{+ Id: boxID, OutboundEnabled: &outbound,+ Volumes: []dto.VolumeDTO{{VolumeId: "vol-object", MountPath: "/data"}},+ })+ if err == nil {+ t.Fatal("Create succeeded despite the malformed native-ID journal")+ }+ journal, journalErr := os.ReadFile(journalPath)+ if journalErr != nil || string(journal) != "not-json" {+ t.Fatalf("native-ID corruption was not injected at %s: %q, %v; Create error = %v", journalPath, journal, journalErr, err)+ }+ persisted, readErr := c.readBoxVolumeMountRecord(boxID)+ if readErr != nil || len(persisted.Entries) != 1 || persisted.Entries[0].RootPath != root {+ t.Fatalf("record after native-ID failure = %#v, %v; Create error = %v; want the object-storage reference to survive", persisted.Entries, readErr, err)+ }+}++func TestStartReturnsFilestorePreparationFailureBeforeBoxLookup(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)+ })+ c.volumeMutexes = make(map[string]*sync.Mutex)+ installFakeFindmnt(t, "10.0.0.7:/vol1")+ c.testProbeRunner = func(context.Context, string) (bool, error) { return true, nil }+ metadata := map[string]string{+ "volumes": `[{"volumeId":"vol-a","mountPath":"/data","filestore":{"instance":"ml-scratch","server":"10.0.0.8","export":"/vol2"}}]`,+ }++ _, err := c.Start(context.Background(), "abc123def456", nil, metadata)+ if err == nil || !strings.Contains(err.Error(), "mount target mismatch") {+ t.Fatalf("Start returned %v, want the Filestore target mismatch", err)+ }+ if got := nativeCalls.Load(); got != 0 {+ t.Fatalf("Start made %d native box calls after the Filestore failure", got)+ }+}++func TestStartPreservesObjectStorageMountFallback(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)+ })+ c.testProbeRunner = func(context.Context, string) (bool, error) {+ return false, errors.New("injected object-storage preparation failure")+ }+ metadata := map[string]string{+ "volumes": `[{"volumeId":"vol-object","mountPath":"/data"}]`,+ }++ _, err := c.Start(context.Background(), "abc123def456", nil, metadata)+ if err == nil || strings.Contains(err.Error(), "injected object-storage preparation failure") {+ t.Fatalf("Start returned %v, want native lookup after the object-storage fallback", err)+ }+ if got := nativeCalls.Load(); got == 0 {+ t.Fatal("object-storage preparation failure blocked the native box lookup")+ }+}++func TestFilestoreMountTimeoutBlocksRetryUntilCompletion(t *testing.T) {+ useVolumeMountBasePath(t, t.TempDir())+ c := filestoreTestClient(t)+ fake := installFakeFilestoreMounts(t, c)+ started := make(chan struct{})+ release := make(chan struct{})+ c.testMountRunner = func(cmd *exec.Cmd) error {+ fake.mounts.Add(1)+ close(started)+ <-release+ fake.mu.Lock()+ fake.mounted[cmd.Args[len(cmd.Args)-1]] = true+ fake.mu.Unlock()+ return nil+ }++ ctx, cancel := context.WithCancel(context.Background())+ done := make(chan error, 1)+ go func() {+ _, err := c.getVolumeMounts(ctx, "box1", []dto.VolumeDTO{{+ VolumeId: "vol1", MountPath: "/data", Filestore: &dto.FilestoreRef{Instance: "ml-scratch", Server: "10.0.0.7", Export: "/vol1"},+ }})+ done <- err+ }()+ <-started+ cancel()+ select {+ case err := <-done:+ if err == nil || !strings.Contains(err.Error(), "context canceled") {+ t.Fatalf("cancelled mount returned %v, want context cancellation", err)+ }+ case <-time.After(2 * time.Second):+ t.Fatal("mount caller did not return after cancellation")+ }++ _, err := c.getVolumeMounts(context.Background(), "box2", []dto.VolumeDTO{{+ VolumeId: "vol2", MountPath: "/data", Filestore: &dto.FilestoreRef{Instance: "ml-scratch", Server: "10.0.0.7", Export: "/vol1"},+ }})+ if err == nil || !strings.Contains(err.Error(), "still in flight") {+ t.Fatalf("retry while mount was running returned %v, want pending-operation error", err)+ }+ if got := fake.mounts.Load(); got != 1 {+ t.Fatalf("retry started %d mount processes, want only the original", got)+ }++ close(release)+ deadline := time.Now().Add(2 * time.Second)+ for c.checkVolumeOperation("boxlite-filestore-ml-scratch") != nil && time.Now().Before(deadline) {+ time.Sleep(10 * time.Millisecond)+ }+ if err := c.checkVolumeOperation("boxlite-filestore-ml-scratch"); err != nil {+ t.Fatalf("pending marker survived mount completion: %v", err)+ }+ if _, err := c.getVolumeMounts(context.Background(), "box3", []dto.VolumeDTO{{+ VolumeId: "vol3", MountPath: "/data", Filestore: &dto.FilestoreRef{Instance: "ml-scratch", Server: "10.0.0.7", Export: "/vol1"},+ }}); err != nil {+ t.Fatalf("retry after mount completion failed: %v", err)+ }+}++func TestFilestorePreparationTimeoutBlocksRetryUntilCompletion(t *testing.T) {+ useVolumeMountBasePath(t, t.TempDir())+ c := filestoreTestClient(t)+ installFakeFindmnt(t, "10.0.0.7:/vol1")+ c.testProbeRunner = func(context.Context, string) (bool, error) { return true, nil }+ started := make(chan struct{})+ release := make(chan struct{})+ var prepares atomic.Int64+ c.prepareRunner = func(string) error {+ prepares.Add(1)+ close(started)+ <-release+ return nil+ }++ ctx, cancel := context.WithCancel(context.Background())+ done := make(chan error, 1)+ go func() {+ _, err := c.getVolumeMounts(ctx, "box1", []dto.VolumeDTO{{+ VolumeId: "vol1", MountPath: "/data", Filestore: &dto.FilestoreRef{Instance: "ml-scratch", Server: "10.0.0.7", Export: "/vol1"},+ }})+ done <- err+ }()+ <-started+ cancel()+ select {+ case err := <-done:+ if err == nil || !strings.Contains(err.Error(), "context canceled") {+ t.Fatalf("cancelled preparation returned %v, want context cancellation", err)+ }+ case <-time.After(2 * time.Second):+ t.Fatal("preparation caller did not return after cancellation")+ }++ _, err := c.getVolumeMounts(context.Background(), "box2", []dto.VolumeDTO{{+ VolumeId: "vol2", MountPath: "/data", Filestore: &dto.FilestoreRef{Instance: "ml-scratch", Server: "10.0.0.7", Export: "/vol1"},+ }})+ if err == nil || !strings.Contains(err.Error(), "still in flight") {+ t.Fatalf("retry while preparation was running returned %v, want pending-operation error", err)+ }+ if got := prepares.Load(); got != 1 {+ t.Fatalf("retry started %d preparations, want only the original", got)+ }+ close(release)+}++func TestCreateReplayRestoresPriorRecordOnFailure(t *testing.T) {+ ctx := context.Background()+ useVolumeMountBasePath(t, t.TempDir())+ c := filestoreTestClient(t)+ installFakeFilestoreMounts(t, c)+ boxID := "abc123def456"+ root := filepath.Join(getVolumeMountBasePath(), filestoreMountPrefix+"ml-scratch")+ dataDir := filestoreDataDir(root, "vol-ok")+ s3Root := filepath.Join(getVolumeMountBasePath(), volumeMountPrefix+"vol-existing")+ if err := c.recordBoxVolumeMounts(ctx, boxID, []volumeMount{+ {hostPath: dataDir, mountPath: "/a", rootPath: root, backend: volumeBackendFilestore, dataDir: dataDir, filestoreInstance: "ml-scratch"},+ {hostPath: s3Root, mountPath: "/b", rootPath: s3Root, backend: volumeBackendS3},+ }); err != nil {+ t.Fatalf("failed to seed existing record: %v", err)+ }++ outbound := true+ _, _, err := c.Create(ctx, dto.CreateBoxDTO{+ Id: boxID, OutboundEnabled: &outbound,+ Volumes: []dto.VolumeDTO{+ {VolumeId: "vol-ok", MountPath: "/a", Filestore: &dto.FilestoreRef{Instance: "ml-scratch", Server: "10.0.0.7", Export: "/vol1"}},+ {VolumeId: "../escape", MountPath: "/b", Filestore: &dto.FilestoreRef{Instance: "ml-scratch", Server: "10.0.0.7", Export: "/vol1"}},+ },+ })+ if err == nil || !strings.Contains(err.Error(), "invalid filestore volume id") {+ t.Fatalf("replay returned %v, want volume-id failure", err)+ }++ record, readErr := c.readBoxVolumeMountRecord(boxID)+ if readErr != nil {+ t.Fatalf("existing record was not restored: %v", readErr)+ }+ var haveFilestore, haveS3 bool+ for _, entry := range record.Entries {+ if entry.Backend == volumeBackendFilestore && entry.DataDir == dataDir {+ haveFilestore = true+ }+ if entry.Backend == volumeBackendS3 && entry.RootPath == s3Root {+ haveS3 = true+ }+ }+ if !haveFilestore || !haveS3 {+ t.Fatalf("restored record = %#v, want both previous references", record.Entries)+ }+}++func TestCreateReplayDoesNotReclaimWhenRecordRollbackFails(t *testing.T) {+ ctx := context.Background()+ useVolumeMountBasePath(t, t.TempDir())+ c := filestoreTestClient(t)+ installFakeFilestoreMounts(t, c)+ umountLogPath := installFakeUmount(t)+ boxID := "abc123def456"+ root := filepath.Join(getVolumeMountBasePath(), filestoreMountPrefix+"ml-scratch")+ dataDir := filestoreDataDir(root, "vol-ok")+ if err := c.recordBoxVolumeMounts(ctx, boxID, []volumeMount{+ {hostPath: dataDir, mountPath: "/a", rootPath: root, backend: volumeBackendFilestore, dataDir: dataDir, filestoreInstance: "ml-scratch"},+ }); err != nil {+ t.Fatalf("failed to seed existing record: %v", err)+ }++ recordPath := filepath.Join(getVolumeMountRecordDir(), boxID+".json")+ var writes atomic.Int64+ restoreLost := false+ var seam func(context.Context, string, boxVolumeMountRecord) error+ seam = func(ctx context.Context, boxID string, record boxVolumeMountRecord) error {+ if writes.Add(1) == 2 {+ if err := os.Remove(recordPath); err != nil {+ return err+ }+ restoreLost = true+ return errors.New("injected record rollback failure")+ }+ c.writeRecordSeam = nil+ err := c.writeBoxVolumeMountRecord(ctx, boxID, record)+ c.writeRecordSeam = seam+ return err+ }+ c.writeRecordSeam = seam++ outbound := true+ _, _, err := c.Create(ctx, dto.CreateBoxDTO{+ Id: boxID, OutboundEnabled: &outbound,+ Volumes: []dto.VolumeDTO{+ {VolumeId: "vol-ok", MountPath: "/a", Filestore: &dto.FilestoreRef{Instance: "ml-scratch", Server: "10.0.0.7", Export: "/vol1"}},+ {VolumeId: "../escape", MountPath: "/b", Filestore: &dto.FilestoreRef{Instance: "ml-scratch", Server: "10.0.0.7", Export: "/vol1"}},+ },+ })+ if err == nil || !strings.Contains(err.Error(), "invalid filestore volume id") {+ t.Fatalf("replay returned %v, want volume-id failure", err)+ }+ if !restoreLost {+ t.Fatal("test did not reach the lost prior-record rollback failure")+ }+ if got := commandLog(t, umountLogPath); got != nil {+ t.Errorf("record rollback failure allowed umount of %v while references could not be verified", got)+ }+ if _, statErr := os.Stat(root); statErr != nil {+ t.Errorf("active filestore root was removed after record rollback failure: %v", statErr)+ }+}++func TestCreateRollsBackRecordWhenNativeIDResolutionFails(t *testing.T) {+ ctx := context.Background()+ useVolumeMountBasePath(t, t.TempDir())+ c := filestoreTestClient(t)+ c.homeDir = t.TempDir()+ fake := installFakeFilestoreMounts(t, c)+ boxID := "abc123def456"+ journalPath := filepath.Join(c.homeDir, "work", "checkpoint-operations", fmt.Sprintf("%x", sha256.Sum256([]byte(boxID)))+".json")+ c.testMountRunner = func(cmd *exec.Cmd) error {+ fake.mounts.Add(1)+ fake.mu.Lock()+ fake.mounted[cmd.Args[len(cmd.Args)-1]] = true+ fake.mu.Unlock()+ return os.WriteFile(journalPath, []byte("not-json"), 0600)+ }++ outbound := true+ _, _, err := c.Create(ctx, dto.CreateBoxDTO{+ Id: boxID, OutboundEnabled: &outbound,+ Volumes: []dto.VolumeDTO{{+ VolumeId: "vol1", MountPath: "/data", Filestore: &dto.FilestoreRef{Instance: "ml-scratch", Server: "10.0.0.7", Export: "/vol1"},+ }},+ })+ if err == nil {+ t.Fatal("expected native ID resolution to fail on the damaged journal")+ }+ if _, statErr := os.Stat(filepath.Join(getVolumeMountRecordDir(), boxID+".json")); !os.IsNotExist(statErr) {+ t.Fatalf("volume record survived native ID resolution failure: %v", statErr)+ }+}++func TestCreateRollsBackRecordWhenClearPublishedFails(t *testing.T) {+ ctx := context.Background()+ useVolumeMountBasePath(t, t.TempDir())+ c := filestoreTestClient(t)+ c.homeDir = t.TempDir()+ installFakeFilestoreMounts(t, c)+ c.clearPublishedRunner = func() error { return errors.New("injected clear-published failure") }+ boxID := "abc123def456"+ outbound := true++ _, _, err := c.Create(ctx, dto.CreateBoxDTO{+ Id: boxID, OutboundEnabled: &outbound,+ Volumes: []dto.VolumeDTO{{+ VolumeId: "vol1", MountPath: "/data", Filestore: &dto.FilestoreRef{Instance: "ml-scratch", Server: "10.0.0.7", Export: "/vol1"},+ }},+ })+ if err == nil || !strings.Contains(err.Error(), "injected clear-published failure") {+ t.Fatalf("Create returned %v, want clear-published failure", err)+ }+ if _, statErr := os.Stat(filepath.Join(getVolumeMountRecordDir(), boxID+".json")); !os.IsNotExist(statErr) {+ t.Fatalf("volume record survived clear-published failure: %v", statErr)+ }+}diff --git a/apps/runner/pkg/runner/v2/executor/box_test.go b/apps/runner/pkg/runner/v2/executor/box_test.gonew file mode 100644index 000000000..624b007d4--- /dev/null+++ b/apps/runner/pkg/runner/v2/executor/box_test.go@@ -0,0 +1,51 @@+// Copyright 2026 BoxLite AI+// SPDX-License-Identifier: AGPL-3.0++package executor++import (+ "context"+ "encoding/json"+ "errors"+ "strings"+ "testing"++ apiclient "github.com/boxlite-ai/boxlite/libs/api-client-go"+ "github.com/google/uuid"+)++type startErrorBackend struct {+ *fakeBackend+ err error+ metadata map[string]string+}++func (b *startErrorBackend) Start(_ context.Context, _ string, _ *string, metadata map[string]string) (string, error) {+ b.metadata = metadata+ return "", b.err+}++func TestStartBoxJobReportsFilestorePreparationFailure(t *testing.T) {+ h := newHarness(t, nil)+ backend := &startErrorBackend{fakeBackend: h.backend, err: errors.New("filestore ml-scratch mount target mismatch")}+ h.executor.backend = backend+ metadata := map[string]string{+ "volumes": `[{"volumeId":"vol-a","mountPath":"/data","filestore":{"instance":"ml-scratch","server":"10.0.0.8","export":"/vol2"}}]`,+ }+ payload, err := json.Marshal(StartBoxPayload{Metadata: metadata})+ if err != nil {+ t.Fatal(err)+ }+ job := apiclient.NewJob(uuid.NewString(), apiclient.JOBTYPE_START_BOX, apiclient.JOBSTATUS_IN_PROGRESS, "BOX", testBoxId, "2026-11-06T00:00:00Z")+ job.SetPayload(string(payload))++ h.executor.Execute(context.Background(), job)++ report := h.lastReport(t)+ if report.body.Status != apiclient.JOBSTATUS_FAILED || !strings.Contains(report.body.GetErrorMessage(), "mount target mismatch") {+ t.Fatalf("START_BOX status = %#v, want failed with the target mismatch", report.body)+ }+ if backend.metadata["volumes"] != metadata["volumes"] {+ t.Fatalf("Start metadata = %v, want %v", backend.metadata, metadata)+ }+}diff --git a/apps/runner/pkg/runner/v2/healthcheck/healthcheck.go b/apps/runner/pkg/runner/v2/healthcheck/healthcheck.goindex 80614a34d..3937daf33 100644--- a/apps/runner/pkg/runner/v2/healthcheck/healthcheck.go+++ b/apps/runner/pkg/runner/v2/healthcheck/healthcheck.go@@ -117,6 +117,9 @@ func (s *Service) newHealthcheck(nestedVirtualizationEnabled bool) *apiclient.Ruhealthcheck := apiclient.NewRunnerHealthcheck(internal.Version)healthcheck.SetDomain(s.domain)healthcheck.SetSupportsPrivileged(true)+ // The binary's filestore mount support is compiled in, so it is declared+ // unconditionally: an API sees it from the first heartbeat after the upgrade.+ healthcheck.SetCapabilities([]string{"filestore"})healthcheck.SetNestedVirtualizationEnabled(nestedVirtualizationEnabled)proxyUrl := fmt.Sprintf("http://%s:%d", s.domain, s.proxyPort)diff --git a/apps/runner/pkg/runner/v2/healthcheck/healthcheck_contract_test.go b/apps/runner/pkg/runner/v2/healthcheck/healthcheck_contract_test.goindex ca3886e9e..bfed91c8b 100644--- a/apps/runner/pkg/runner/v2/healthcheck/healthcheck_contract_test.go+++ b/apps/runner/pkg/runner/v2/healthcheck/healthcheck_contract_test.go@@ -10,6 +10,35 @@ import (apiclient "github.com/boxlite-ai/boxlite/libs/api-client-go")+func TestHealthcheckCapabilitiesWireContract(t *testing.T) {+ payloads := make(chan map[string]any, 1)+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ var payload map[string]any+ if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {+ t.Error(err)+ w.WriteHeader(http.StatusBadRequest)+ return+ }+ payloads <- payload+ w.WriteHeader(http.StatusNoContent)+ }))+ t.Cleanup(server.Close)+ config := apiclient.NewConfiguration()+ config.Servers = apiclient.ServerConfigurations{{URL: server.URL}}+ client := apiclient.NewAPIClient(config)+ service := &Service{client: client, domain: "runner.test", apiPort: 8080, proxyPort: 8081}+ healthcheck := service.newHealthcheck(false)++ if _, err := client.RunnersAPI.RunnerHealthcheck(context.Background()).RunnerHealthcheck(*healthcheck).Execute(); err != nil {+ t.Fatal(err)+ }+ payload := <-payloads+ got, present := payload["capabilities"].([]any)+ if !present || len(got) != 1 || got[0] != "filestore" {+ t.Fatalf("capabilities = %v (present=%t), want [filestore]; body = %v", got, present, payload)+ }+}+func TestHealthcheckCapabilityWireContract(t *testing.T) {for _, field := range []string{"supportsPrivileged", "nestedVirtualizationEnabled"} {disabled, enabled := false, truediff --git a/docs/contributing/README.md b/docs/contributing/README.mdindex 92e745900..0555ebc9b 100644--- a/docs/contributing/README.md+++ b/docs/contributing/README.md@@ -39,6 +39,8 @@ Dated root-cause analyses and design studies, newest first.- 2026-11-19 · [Trial discovery in Welcome](investigations/2026-11-19-trial-discovery-preview.md): frontend onboarding study, mock boundaries, direct completion and full walkthrough screenshots.- 2026-11-13 · [Runner data-disk performance scaling](investigations/2026-11-13-runner-data-disk-performance-scaling.md): expansion raises provisioned IOPS/throughput proportionally, clipped to the per-disk ceiling; capacity never waits for performance.+- 2026-11-13 · [Filestore lookup prerequisites](investigations/2026-11-13-filestore-lookup-prerequisites.md): automatic Filestore IAM and API prerequisites, cross-project configuration, and diagnostic error preservation.+- 2026-11-13 · [Filestore instance discovery](investigations/2026-11-13-filestore-instance-discovery.md): API-resolved NFS targets, explicit backend selection, and deterministic instance assignment.- 2026-11-11 · [CI resource labels](investigations/2026-11-11-ci-resource-labels.md): job-selected Box resources, quota enforcement and original-operation recovery.- 2026-11-10 · [Desktop left navigation](investigations/2026-11-10-desktop-left-navigation.md): sidebar layout, hover preview and navigation behavior.- 2026-11-10 · [Desktop visual refinement](investigations/2026-11-10-desktop-visual-refinement.md): resource view consistency and desktop review findings.diff --git a/docs/contributing/investigations/2026-11-13-filestore-instance-discovery.md b/docs/contributing/investigations/2026-11-13-filestore-instance-discovery.mdnew file mode 100644index 000000000..b7880c128--- /dev/null+++ b/docs/contributing/investigations/2026-11-13-filestore-instance-discovery.md@@ -0,0 +1,300 @@+**Status:** Accepted++# GCP FileStore instance discovery++## API contract++`storageBackend` is the only field that selects the volume type. `instance` is only an+optional placement hint for Filestore; it never implies a backend.++| Request | Meaning |+| --- | --- |+| `{}` | Create an object-storage volume. |+| `{ "storageBackend": "object_storage" }` | Create an object-storage volume. |+| `{ "storageBackend": "filestore" }` | Create a Filestore volume and assign an instance by hashing the configured names. |+| `{ "storageBackend": "filestore", "instance": "boxlite-dev-shared" }` | Create a Filestore volume on that named instance. |+| `{ "instance": "boxlite-dev-shared" }` | Invalid: a Filestore placement cannot select the backend. |++The accepted values are `object_storage` and `filestore`; `object_storage` is the+default. If `storageBackend` is `object_storage`, `instance` must be absent. If it is+`filestore`, `instance` is optional and must name a real GCP Filestore instance in the+deployment's configured project and location.++## Goal++The API needs only the set of usable Filestore instance names from the environment.+It then discovers the current IP address and NFS export from GCP instead of receiving+those connection details through configuration.++This removes the requirement to duplicate deployment connection data into API+configuration and lets Filestore tests ask for automatic assignment without knowing+which instances a stage has provisioned. The explicit backend also keeps the public+meaning of every request independent of optional-field presence.++## Non-goals++- The API does not create, resize, or delete Filestore instances. Operators provision+ them.+- The API does not create or delete the volume's NFS directory. The runner continues to+ create it under the volume ID at first mount.+- This is not capacity-aware or latency-aware load balancing. It is a deterministic+ early-stage distribution.+- Existing volumes are not moved when the configured instance set changes.++## Decision rationale++The deliberate boundary is **simple enough for the current need**, not "the cheapest+version of a future balancer".++- The current requirement is to spread new Filestore volumes across a small,+ operator-provisioned set and to let tests or operators pin an instance when necessary.+ There is no current workload showing uneven distribution, exhausted shares, or a need+ to compare instances with different capacities.+- Capacity-aware placement would need a definition of which signal governs the decision:+ provisioned size, observed used bytes, inode pressure, throughput, or runner-to-instance+ proximity. It would also need normalizing instances with different tiers and capacities.+ None of those signals, policies, or thresholds is part of the current product need.+- A health-aware or least-loaded selector would be hard to test honestly at this stage.+ It would introduce simulated telemetry that may not match GCP behavior, or extra+ infrastructure whose benefit cannot be measured while there is no observed imbalance.+- A deterministic hash is chosen because it needs no shared state, no coordination between+ API replicas, no background refresh, and no new request-time dependency beyond the+ configured name list. It is easy to test and easy to explain. Its known limitation is+ accepted: it balances new creates, not live demand.+- Existing volumes keep their assigned instance because moving data is a materially larger+ system: it needs copy/cutover semantics, quiescing writers, rollback, and observable+ progress. Inventing that now would not solve a current request.++Revisit this only when there is concrete evidence or a new product requirement: measured+hot spots, instances with materially different capacity or tier, saturation alerts, usage+telemetry that supports a placement policy, or a need to move volumes without operator-run+data copies.++## Runtime flow++`apps/api/src/config/filestore-instances.ts` parses `FILESTORE_INSTANCES` as instance objects.+`FilestoreInstanceResolver` owns deterministic placement and GCP discovery.+`VolumeService.enqueueCreation` selects an explicit name or hashes the sorted list through+that resolver. `BoxService.create` and `BoxStartAction` resolve the current mount target+before each supported create or start dispatch.++The runner receives the resolved `FilestoreRef` and mounts `server:export` with the+pinned NFSv4.1 and hard options. Instance names use the same path-safety grammar on the+runner, and Filestore volumes reject `subpath` rather than silently ignoring it.++## Configuration++The design changes the variable in place instead of adding another compatibility form:++```bash+FILESTORE_INSTANCES='[{"instance":"boxlite-dev-shared","project_id":"boxlite-dev-project","zone":"us-east5-a"}]'+```++`FILESTORE_INSTANCES` is a JSON list. Each entry carries `instance`, `project_id`, and+`zone`, so instances can live in different projects or zones without changing the API+contract again. The runner accepts path-safe instance names matching:++```text+^[a-z0-9][a-z0-9-]{0,62}$+```++The API's `FILESTORE_INSTANCES` validation retains the stricter Filestore naming+rule:++```text+^[a-z](?:[a-z0-9-]{0,61}[a-z0-9])?$+```++Instances are sorted by name before hashing so every API replica makes the same choice.+Each instance carries its own GCP placement, so hash assignment currently balances+instances without considering capacity, region locality, or current utilization.++The API validates each instance, project ID, and zone at startup, but does not call GCP at+startup. An explicit empty `FILESTORE_INSTANCES` remains valid; it only means the deployment+cannot accept a Filestore create. Until the temporary stage rollout is removed, an unset+variable defaults to `boxlite-dev-shared` in `boxlite-dev-project`, zone `us-east5-a`.+Stage deployments default to `boxlite-filestore-stage`, zone `us-east4-a`.++The old comma-separated list plus deployment-wide project/location variables is removed.+Keeping both shapes would make the variable's meaning depend on its first byte, create two+deployment paths, and preserve a form this branch has not shipped. If a deployed stage+already uses the old form, its environment is updated in the same rollout as the API image.++## Instance selection++For `storageBackend: "filestore"`:++1. If the request explicitly supplies `instance`, validate it against the configured+ names and use it.+2. Otherwise parse the configured names, sort them, and hash the request-independent+ value to select one.+3. Store only the selected name in `Volume.instance`.++The initial implementation uses the first 32 bits of the volume ID's SHA-256 digest and+selects `digest % instanceCount`. This uses an ID created for the request, spreads new+creates evenly enough for current use, and is stable across API replicas. It deliberately+does not consider current capacity, available share space, region proximity, or instance+health; the reasons and later triggers are in **Decision rationale**.++If the configured list is empty and no explicit name is supplied, the request fails+before a Volume row is written. If the selected or explicit instance cannot be found in+GCP, the create also fails before a Volume row is written. The response distinguishes:++| Failure | Public status |+| --- | --- |+| No Filestore instance is configured | 503 |+| Explicit instance does not exist | 400 |+| Hash-selected configured instance does not exist | 503 |+| Filestore API authentication or access fails | 503 |+| Filestore API is unavailable | 503 |++An existing Volume keeps its instance name forever in this design. Changing the+environment affects only creates made after that change; it never rebalances existing+data.++## GCP discovery++The API calls the Google Cloud Filestore API directly. It does not shell out to the+`gcloud` CLI. The implementation uses Application Default Credentials, matching the API's+existing Google Cloud access model, and the deployment's service account needs the+Filestore read permission.++For each selected name, the API reads:++```text+projects/{project_id}/locations/{zone}/instances/{instance}+```++The resolver accepts the returned instance only when it can derive exactly one usable+mount target:++- `networks[].ipAddresses` contains exactly one IPv4 address.+- `fileShares[]` contains exactly one share. The export becomes `/${share.name}`.++A zero-share instance fails. An instance with multiple shares or usable addresses also+fails for now. That avoids guessing which share a caller meant. If multi-share instances+become a real requirement, the follow-up should either extend the request with a share+selector or allow the logical instance name to include a share suffix; this design does+not invent that syntax yet.++The mount options stay pinned in the runner: NFSv4.1 and hard. The new name-only+configuration cannot express arbitrary options. If another option is later required, it+should be a separate reviewed contract, not hidden inside an instance-name list.++## Dispatch++`VolumeService.create` stores the assigned or explicit instance name and marks the+Filestore volume `READY` immediately, exactly as the current implementation does. No IP+or export is persisted in the public Volume row or database record.++`BoxService.create` resolves every referenced volume's instance through the resolver+before dispatching. `BoxStartAction` does the same when it rebuilds create or start+metadata. Successful lookups are cached for 60 seconds, so an instance recreated within+that interval can briefly reuse its previous address; a later dispatch refreshes it. A+failed lookup fails the dispatch loudly rather than allowing the runner to discover an+invalid mount.++Public Box responses expose only the logical instance name. The resolved server and+export stay inside dispatch payloads and persisted volume metadata; generated public+clients therefore expose `instance` without those connection details. This corrects the+implementation to match the spec-first contract rather than adding fields to that+contract. Lookup failures retain the same public status but include the configured+instance name, full resource path, GCP status name, and original error message, which the+Dashboard shows when volume creation fails.++The resolver keeps successful responses in memory for 60 seconds, keyed by the full GCP+resource name. This removes duplicate reads while one box create resolves multiple+volumes on the same instance without introducing a shared cache service. Failed lookups+are not cached. The cache is an implementation detail; the database and runner still+store or receive only the name and resolved mount reference respectively.++## Code shape++The expected focused changes are:++- Replace `apps/api/src/config/filestore-instances.ts` with name-list parsing.+- Add a Filestore resolver around the official `@google-cloud/filestore` client.+- Extend `CreateVolumeDto` and the OpenAPI schema with optional `storageBackend`.+- Return the derived `storageBackend` and Filestore-only `instance` in `VolumeDto`.+- Expose `object_storage_enabled` and `filestore_enabled` from `/v1/config`.+- Give the Dashboard a storage-backend selector, list display, and immediate-ready copy for Filestore.+- Use the selector and resolver in `VolumeService.enqueueCreation`.+- Replace direct configuration-array lookups in `BoxService.create` with resolver calls.+- Update focused unit tests, the generated API clients, and `test_filestore.py`.++Discovery adds no runner functionality. Its only runner-side change removes the+per-volume `MountOptions` passthrough so the pinned NFSv4.1+hard options cannot+be overridden; the runner DTO loses that field accordingly, and the `Volume`+database migration predates this design (introduced when Filestore rows became+first-class) and is not part of discovery.++## Test outline++Focused tests cover:++- Name-list parsing, duplicate rejection, and startup validation.+- Deterministic hash assignment across a sorted name list.+- Explicit instance selection, automatic selection, and empty-list errors.+- Mapping of a Filestore API response to a server address and export.+- Rejection of multiple shares, zero shares, and ambiguous addresses.+- Volume create and box dispatch error mapping, including no persisted row on failure.+- `/v1/config` advertising each volume backend only when its configuration is present.+- Dashboard defaulting, disabled options, payload shape, and list rendering.++The Filestore E2E case keeps `FILESTORE_E2E_INSTANCE` as an optional way to pin a named+instance. When omitted, it creates with `storageBackend: "filestore"` and therefore does+not need the API deployment to pre-share its instance list with the test runner.+Whether that default probe should run on a stage is still controlled by the existing E2E+gate, because an available API deployment does not by itself prove that a Filestore+instance was provisioned.++## Operational rollout++Provision the named instances, then run the infrastructure bootstrap and mdeploy so the+Filestore API is enabled and the API service account receives read access. Verify one+explicit-instance create and one automatic-selection create before opening the endpoint+more broadly. Deploying only the API image does not reconcile these prerequisites.+[Filestore lookup prerequisites](2026-11-13-filestore-lookup-prerequisites.md) specifies+how deployment reconciles that read access and the Filestore API, and how lookup failures+retain their GCP cause.++The `1792000000000-volume-instance-column-migration.ts` pre-deploy migration adds the nullable+`volume.instance` column with no backfill and must run before the API rollout. Volumes created by+the current branch contain instance names that this resolver can continue to look up, provided+those names are real GCP instance IDs. If a stored name was only a+local alias and not a GCP instance ID, that row must be corrected before the new dispatch+path ships.++## Dashboard behavior++The Dashboard reads `/v1/config` and keeps backend availability as an operator-visible+capability, not an inferred convention. It offers **ObjectStorage** and **FileStore**,+defaults to object storage, and never asks the user for an instance, NFS server, export,+or mount option.++When Filestore is not configured, its option stays visible but disabled with a concise+configuration note. When object storage is unavailable and Filestore is available, the+Dashboard starts on Filestore. When neither backend is configured, creation is disabled.+Submitting FileStore sends only `{ "name": "...", "storageBackend": "filestore" }`; the+server assigns and resolves the instance. The success copy says the volume was created,+because FileStore volumes are `READY` immediately. The list shows only the backend name,+not the assigned instance; operators can inspect that fact through the API if needed.++## Hardening verification++The focused API suites cover stale-target rediscovery, public-response confidentiality,+validation before GCP calls, dispatch mapping, placement, and lifecycle behavior: 347/347+tests passed. With production changes reverted and only the regression tests retained,+the stale-target, public-response, duplicate-name, and suspended-organization cases all+failed for their original reasons. A test-only constructor adapter preserved the old+signature during that run and was removed before the passing run.++Runner tests prove invalid instance names and Filestore `subpath` are rejected before+mount work. Both failed against the unguarded implementation and passed after the fix.+The complete `pkg/boxlite` package passed afterward. The full runner suite also ran its+unrelated `TestIntegrationExecutionInventoryRecoveryHTTP` case, which failed in+`pkg/api/controllers`; that execution-inventory failure is outside this design.++`make build:apps:api` passed. The detailed lookup-error path has 11/11 resolver tests and+a Dashboard toast regression test proving the GCP status and original message are visible.+No live Filestore instance was mutated for these checks.diff --git a/docs/contributing/investigations/2026-11-13-filestore-lookup-prerequisites.md b/docs/contributing/investigations/2026-11-13-filestore-lookup-prerequisites.mdnew file mode 100644index 000000000..f66e8df67--- /dev/null+++ b/docs/contributing/investigations/2026-11-13-filestore-lookup-prerequisites.md@@ -0,0 +1,252 @@+**Status:** Partially implemented++## TL;DR++Reconcile Filestore discovery prerequisites during deployment, grant the API+`roles/file.viewer` in every configured GCP project, enable the Filestore API in+the stage project, and retain sanitized GCP failure details in API logs without+changing the client error contract.++The resolver diagnostics, effective-configuration, and service-enablement slices+are implemented. The `roles/file.viewer` deployment wiring is tracked separately+in #2731. The default `FILESTORE_INSTANCES` entry is+`boxlite-dev-shared` in `boxlite-dev-project`, zone `us-east5-a`; stage deployments+use `boxlite-filestore-stage`, zone `us-east4-a`.++## Context and evidence++A Filestore volume create currently fails with:++```text+Could not look up Filestore instance 'projects/boxlite-dev-project/locations/us-east5-a/instances/boxlite-dev-shared'+```++`FilestoreInstanceResolver.lookup` emits this message only when `getInstance`+rejects with something other than the recognized `NOT_FOUND` shape. The call+happens before the Volume row is saved and before runner dispatch, so this is+control-plane discovery, not an NFS mount failure.++The current implementation contains a separate correction that accepts both+numeric and string forms of the READY state. That correction addresses an+`is not ready` response after a successful lookup; it does not address this+lookup exception.++Repository evidence exposes three gaps:++| Gap | Current evidence | Consequence |+| -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------- |+| No automatic Filestore IAM grant | The discovery design requires Filestore read access, but neither the GCP API provider nor deployment history declares `roles/file.viewer` or `file.instances.get`. | A stage can advertise Filestore while its API identity receives `PERMISSION_DENIED`. |+| No Filestore API declaration | `apps/infra/bootstrap/gcp.ts` enables the other required Google services but omits `file.googleapis.com`. | A fresh stage can fail at request time with API-disabled or service-unavailable errors. |+| Lost cause | `FilestoreInstanceResolver` catches the GCP error and constructs a new exception without logging it or attaching it as `cause`. | Permission, authentication, API-disabled, and transport failures have the same public symptom. |++This record does not assert which gap caused the observed incident. The live GCP+state was not available during investigation; the design removes all three gaps+and makes any remaining failure identifiable.++## Sources and constraints++- [Filestore IAM roles and permissions](https://cloud.google.com/filestore/docs/iam)+ assigns `file.instances.get` to `roles/file.viewer`. The role is read-only; it+ also permits instance, operation, backup, and snapshot reads, but no writes.+- [Filestore `projects.locations.instances.get`](https://cloud.google.com/filestore/docs/reference/rest/v1/projects.locations.instances/get)+ confirms that discovery calls `file.googleapis.com` and uses the+ cloud-platform OAuth scope.+- [Service Usage](https://cloud.google.com/service-usage/docs/enable-disable)+ makes service enablement a project-level prerequisite and requires+ administrative permission to change it.+- [NestJS exception filters](https://docs.nestjs.com/exception-filters)+ documents that `cause` is not serialized to the client and that built-in+ exceptions are not logged by the default filter. The implementation therefore+ needs both `cause` and an explicit log.+- The existing `ApiCapability` union and per-cloud expansion keep policy out of+ the shared stack. Capability grants are appended, never inserted, because+ their indexes form Pulumi resource names.+- `FILESTORE_INSTANCES` already distinguishes unset, explicit empty, and+ configured entries. Unset currently selects the development default; explicit+ empty disables Filestore. Entries may name different projects.++The implementation must not create, modify, or delete Filestore instances,+change NFS permissions, widen runner IAM, expose credentials or request contexts+to dashboard users, or add a second application-level retry loop.++## Design++### Derive one effective discovery configuration++`apiEnvironmentFrom` already reads `FILESTORE_INSTANCES` while assembling the+API environment. Extend that deployment seam to return both the environment+value and a sorted, deduplicated `filestoreProjects` list.++- On GCP, an unset variable materializes the same default JSON that the API+ currently applies internally. The container and IAM derivation therefore see+ identical effective configuration.+- An explicit empty value produces no projects and no grant.+- A non-empty value is parsed and validated before cloud resources are built.+ Invalid JSON, entries, project IDs, or zones fail deployment with the+ configuration error rather than a later request failure.+- `StackEnvironment` and `StackInputs` carry `filestoreProjects` through both+ the SST and Pulumi composition paths.+- AWS preserves its existing environment behavior but derives no Filestore+ projects or capability. An unset AWS configuration does not acquire the GCP+ default.++The deployment parser should be a small shared deployment function beside+`apiEnvironmentFrom`, not an import from `apps/api/src/config`: infrastructure+must not depend on the API application's Nest configuration module. Contract+tests use the same unset, empty, malformed, and multi-project fixtures on both+sides so the two parsers cannot silently diverge.++### Reconcile read-only IAM through `ApiCapability`++Append one closed-union member:++```text+{ kind: 'read-filestore-instances', projects: string[] }+```++The shared composition root adds it last when the effective project list is+non-empty and the provider supports GCP Filestore discovery. The AWS provider+rejects the capability if composition ever hands it one.++The GCP provider expands the capability into one `gcp.projects.IAMMember` per+project:++```text+project: <configured project>+role: roles/file.viewer+member: serviceAccount:<API runtime service account>+```++Use a deterministic logical name derived from the capability index and project+ID. Existing `granted` handling already includes these resources in `Api.ready`.+The predefined viewer role is preferred over per-project custom roles: it has no+write permissions and avoids additional role lifecycle and deployment resources.++For the stage's own project, the existing deployer permissions are sufficient.+For another project, automatic reconciliation requires that project's+administrator to grant the deployment identity IAM policy-write access first.+Deployment must fail loudly if that prerequisite is absent; it must not attempt+privilege escalation or silently skip the binding. Removing a project from the+effective configuration removes its managed binding on a later apply while+leaving unrelated IAM members intact.++### Enable the API before the runtime depends on it++Add `file.googleapis.com` to `SERVICES` in `apps/infra/bootstrap/gcp.ts`. The+existing bootstrap reconciliation then enables it on a fresh stage project and+does no work when it is already enabled.++An external Filestore project needs a one-time onboarding step before+deployment: enable Service Usage and Filestore, and allow the deployment+identity to manage the API service account's IAM binding. This is an explicit+cross-project trust decision, not something the stage bootstrap should infer.+The normal same-project path, including `boxlite-dev-project`, remains fully+automatic.++The API revision does not need a startup discovery probe. Readiness must not+depend on an operator-provisioned instance being present; configuration+disablement and instance lifecycle remain request-time concerns.++### Preserve diagnostic detail without exposing it++In `FilestoreInstanceResolver`:++- Keep the existing public statuses, including `400` for an explicitly requested+ missing instance and `503` for configured lookup, authentication, permission,+ and transport failures. The public message includes the configured `instanceName`,+ full GCP resource path, GCP status name, and original error message so the dashboard+ can show the actual cause.+- Attach the caught error as `cause` to each new lookup exception.+- On non-`NOT_FOUND` lookup failures, emit one structured error log with event+ name `filestore_lookup_failed`, configured `instanceName`, `resourceName`, lookup+ source, and the GCP error's `code` and `message`.+- Log only these explicit fields rather than serializing request options,+ credentials, headers, or the whole GCP client context.+- Preserve failed-lookup retry behavior: failures are not cached, and the Google+ client retains its own transient retry policy. No additional resolver retry or+ circuit breaker is introduced.++The log lets an operator distinguish at least `PERMISSION_DENIED`,+`UNAUTHENTICATED`, API-disabled responses, `UNAVAILABLE`, and+`DEADLINE_EXCEEDED` without reproducing the dashboard request. `BadRequestError`+accepts an optional Nest exception-options object so the explicit-instance+`NOT_FOUND` branch retains the same cause without changing its public response.++## Alternatives considered++| Alternative | Decision |+| ------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Grant Filestore read manually in each stage | Reject as the primary mechanism: the runtime and deployment would continue to drift. Keep a manual grant only as an emergency recovery action. |+| Grant `roles/file.editor` or project Viewer | Reject: both are broader than discovery requires. `roles/file.viewer` is the predefined read-only Filestore role. |+| Grant only in the stage project | Reject: configured entries can name other projects. Derive grants from the effective project list. |+| Import the API parser into infrastructure | Reject: it couples deployment to the API application's internal configuration module. Use deployment-local parsing with shared contract fixtures. |+| Return the full GCP client context | Reject: it risks credentials and request metadata. Return only the status and original message, with full detail in logs and `cause`. |+| Add resolver retries or a startup probe | Reject for this change: retries already belong to the Google client, and a startup probe would make unrelated API availability depend on instance state. |++## Implementation outline++1. Extend deployment environment parsing and stack inputs with effective+ `filestoreProjects`; add unset, empty, malformed, duplicate-project,+ multi-project, and AWS rejection tests.+2. Append the API capability and implement GCP `roles/file.viewer` bindings;+ verify stable resource names, project selection, API identity, and no grant+ when Filestore is disabled.+3. Add `file.googleapis.com` to bootstrap and test both fresh and+ already-enabled reconciliation.+4. Update the Filestore discovery operational rollout and infrastructure runbook+ with same-project automation and external-project onboarding.++## Verification and rollout++Run focused tests first, then the owning suites:++```bash+make test:apps:infra+make test:apps:api TEST_FILES='filestore-instance.resolver.spec.ts'+```++Infrastructure tests must prove that enabling an existing service is a no-op,+every unique configured project receives exactly one viewer binding, the runner+identity receives none, and inserting this capability does not rename existing+grants.++API tests must cover allowed and denied lookup outcomes at the resolver+interface. Defect proof runs each new regression test with production changes+reverted: IAM/service assertions fail against the undeclared resources, and+logging/cause assertions fail against the discarded error. Restoring the+implementation must make the same tests pass without weakening their assertions.++For the resolver diagnostic slice, reverting both production files while keeping+the tests produced two failures: the generic lookup exception and the+`NOT_FOUND` exception had no `cause`. Restoring the implementation produced 9/9+passing resolver tests, and `make build:apps:api` passed. No live GCP request+was run for this slice.++For the deployment-prerequisite slice, reverting all infrastructure production+changes while retaining the tests produced seven failures: Filestore service+enablement, default and configured project derivation, viewer grants, and final+capability wiring. Restoring the implementation produced 105/105 focused tests,+23/23 bootstrap tests, and 614/614 mdeploy tests, plus a clean mdeploy typecheck.+No live GCP request was run for this slice either.++Roll out infrastructure before or with the API image, then verify against the+real stage. Steps 2 and 3 require the box-runtime slice to enable+`FILESTORE_SUPPORTED` on the stage API; while it is `false`, a create returns+HTTP 501. Defer those steps until that slice is deployed:++1. Confirm `file.googleapis.com` is enabled in the stage project and the API+ runtime service account has `roles/file.viewer` in each configured project.+2. Create one Filestore volume with automatic instance selection and one with an+ explicit `instance`; both must pass discovery and persist the expected+ instance.+3. Run the existing Filestore E2E case with its normal deployment gate,+ including mount, data reuse, and cross-box sharing.+4. Confirm a denied test double leaves the public response unchanged while logs+ retain its GCP code and message. Do not revoke production IAM merely to+ produce a negative E2E result.+5. Confirm transient failure tests still perform a later lookup rather than+ caching the failure.++Completion requires a real successful create against the deployed API. Unit+tests alone do not prove cloud IAM, service enablement, ADC, or network+reachability.