Unified Workspace Block Volume Lifecycle Management via /volumes API
此内容尚不支持你的语言。
- Source:
docs/enhancements/0030-unified-workspace-block-volumes/README.md- Status:
provisional- Area:
storage- Milestone:
v0.8.0
| Stage | Status | Created | Updated | Owning Area |
|---|---|---|---|---|
alpha |
provisional |
2026-11-21 |
2026-11-22 |
storage (gateway, controller, runtime, sdk) |
Tracking Issue: #146 (Milestone 0.8.0)
Table of Contents
Section titled “Table of Contents”- Release Signoff Checklist
- Summary
- Motivation
- Proposal
- Design Details
- Production Readiness Review Questionnaire (PRR)
- Implementation History
- Drawbacks
- Alternatives
Release Signoff Checklist
Section titled “Release Signoff Checklist”- Enhancement design documented in
docs/enhancements/0030-unified-workspace-block-volumes/ -
POST /volumes(type: "shared" | "block") and volume metadata extension (sizeBytes,legacyVolumeKey, PVC binding) specified in OpenAPI (api/openapi/cubepod-v1.yaml) and implemented inpkg/volume+pkg/gateway -
VolumeMount.Type("shared" | "block"inPodBoxSpec.VolumeMounts) andKubeClient.GetPVC/KubeClient.ListPVCs/ atomic PVC attach-lease CAS implemented inapi/v1alpha1&pkg/controllerwithout coupling/workspaceto/rootfs-upper(AGENTS.md Invariant 1) - Single-writer exclusivity (
409 Conflictwhen attached to a non-Terminated PodBox) & CSIVolumeSnapshotCoW Fork behavior verified - Legacy
/workspacedata migration implemented & verified: zero-copy in-place adoption (activePodBoxauto-adoption +cubepod volume migrate-legacyCLI/Job + optional CSIVolumeSnapshotclone) with pre/post-upgrade data integrity checks - Anonymous
/workspaceWarmPool claim (< 50ms) preserved unchanged - Dual-runtime behavior implemented and tested across Production Kubernetes (
Kata + CSI Block) and Local Development (Docker + Loopback ext4) - Statechart / TLC check run for
PodBox/ block volume attach-detach lifecycle transitions (AGENTS.md) - Deployed & soak-verified in test/staging environment (
v0.8.0) before graduating tov1.0.0GA
Summary
Section titled “Summary”CEP-0030 extends CubePod’s control-plane /volumes API (POST / GET / DELETE /volumes) to support exclusive persistent /workspace block volumes (type: "block") alongside existing shared RWX filesystem volumes (type: "shared", the default).
Today, users who want a sandbox /workspace to persist across DELETE /sandboxes -> POST /sandboxes cycles must pass an implicit extension.volumeKey string when creating a sandbox, which creates a <sanitized>-workspace-pvc without any list, inspect, quota, tenant-ownership, or delete REST API. CEP-0030 brings persistent /workspace block storage under the /volumes lifecycle while keeping the underlying storage engines separate: /workspace block volumes continue using volumeMode: Block (VolumeDevices -> /dev/cubepod-workspace), podd-init ensure_ext4, and CSI VolumeSnapshot CoW Forks, while shared volumes keep their RWX subPath + /volumecontent semantics.
Motivation
Section titled “Motivation”CubePod currently manages two independent persistent storage paths with an awkward user-facing gap:
- Shared Volumes (
/volumes, CEP-0025 & CEP-0026): Full CRUD (POST/GET/DELETE /volumes), tenant isolation viaX-API-KEYandtenants.json, quota enforcement, and/volumecontent/{id}/...HTTP file APIs, backed by a cluster-wide sharedReadWriteManyPVC (cubepod-volumes) mounted into guests viavirtiofsd+VolumeMounts. - Workspace Block Volumes (
extension.volumeKey, CEP-0003 & CEP-0022): PassingvolumeKeyonPOST /sandboxescreates an exclusiveReadWriteOncevolumeMode: BlockPVC (<sanitized>-workspace-pvc) and keeps it alive when the sandbox is deleted (spec.VolumeKey != ""inpkg/controller/reconciler.go). However:- Operators and SDK users have no REST API to pre-provision, list (
GET /volumes), inspect, quota-limit, rotate ownership, or explicitly delete (DELETE /volumes/{id}) avolumeKeyPVC. volumeKeyhas noX-API-KEYtenant isolation boundary equivalent topkg/volume.Store(SanitizeVolumeKeyhashes raw keys globally).
- Operators and SDK users have no REST API to pre-provision, list (
At the same time, /workspace cannot simply be collapsed into the RWX /volumes data-plane implementation:
- Raw
BlockCSI (volumeMode: Blockwith Kata QEMU direct block attach) avoidsvirtiofsdoverhead and enables CSIVolumeSnapshotCoW Fork, where parent and child sandboxes diverge on independent writable/workspaceclones. - Anonymous sandboxes (without persistent volumes) rely on pre-created, pre-attached
workspace-pvcs in PodWarmPool for< 50msclaims. cubepod-gatewaycannot safely mount userext4block devices directly onto the gateway Pod to serve/volumecontent.
- Unified Control-Plane API: Allow users to create, list, inspect, rotate keys for, and delete persistent block
/workspacevolumes through/volumes(type: "block"). - Preserve Raw Block Semantics: Mount
type: "block"volumes exclusively at/workspaceusingVolumeDevices(/dev/cubepod-workspace) +podd-initensure_ext4on Kubernetes Kata, and loopbackext4image / bind mount on local Docker. - Preserve CSI
VolumeSnapshotCoW Fork: Forking a sandbox with atype: "block"/workspacevolume MUST clone a new writable block PVC (never multi-attaching an RWO PVC or mutating the parent volume). - Preserve WarmPool Fast Path: Sandboxes created without
volumeMounts//workspaceblock mount continue claiming pre-warmedPodWarmPoolreplicas sub-50ms. - Enforce Single-Writer Exclusivity & Tenant Isolation: Bind block volumes to
pkg/volume.Storetenant ownership (X-API-KEY/tenants.json) and reject attaching atype: "block"volume that is already attached to an active (non-Terminated) sandbox, or deleting an attached volume, with409 Conflict.
Non-Goals
Section titled “Non-Goals”- Gateway
/volumecontent/{id}/...fortype: "block"volumes: Offline HTTP file read/write viacubepod-gatewayremains exclusive totype: "shared"RWX volumes. Gateway MUST return400 Bad Request(viawriteContentError, where the OpenAPIError.codefield is the string"400") when/volumecontentis called on atype: "block"volume; file I/O on a block workspace uses the running sandbox’s/filesAPI. - Mounting
type: "block"volumes at arbitrary paths (e.g./mnt/data) in Alpha: Alpha restrictstype: "block"mounts strictly topath: "/workspace"(replacing the anonymous sandboxworkspace-pvcon thatPodBox). Arbitrary multi-block device mounting is deferred. - Converting anonymous
PodWarmPoolsandboxes to RWX: Ephemeral sandboxes keep per-sandbox blockworkspace-pvcs.
Proposal
Section titled “Proposal”User Stories
Section titled “User Stories”- As an agent developer, I want to create a persistent workspace via
POST /volumes({"name": "repo-ws", "type": "block", "size": "20Gi"}), attach it to a sandbox viaPOST /sandboxes("volumeMounts": [{"name": "repo-ws", "path": "/workspace"}]), delete the sandbox when idle, re-attach"repo-ws"to a newer template/image sandbox later, and eventually delete it viaDELETE /volumes/{volumeID}when the project is archived. - As a platform operator, I want tenant storage quotas,
GET /volumesinventory,POST /volumes/rotate-key, and409 Conflictdelete/attach guards to cover both shared RWX datasets and persistent block workspaces under one/volumescontrol surface. - As an SDK consumer forking a workspace, when I call
POST /sandboxes/{id}/forkon a sandbox whose/workspaceis backed by"repo-ws", I expect the child sandbox to get an independent CoW CSI snapshot clone of/workspacewithout mutating"repo-ws"or stalling inMulti-Attach.
Notes / Constraints / Caveats
Section titled “Notes / Constraints / Caveats”- Dual-Runtime Behavior:
- Production Kubernetes (
Kata + CSI Block):- Creating a
type: "block"volume viaPOST /volumesrecords metadata inpkg/volume.Store(type: "block", deterministicpvcName: "vol-<volumeID>") and synchronously provisions aReadWriteOncevolumeMode: BlockPersistentVolumeClaim(vol-<volumeID>) viacontroller.KubeClient().EnsurePVCusing the configured blockStorageClass. IfEnsurePVCfails, Gateway MUST roll back thepkg/volume.Storerecord and return an error (never returning201 Createdwith a dangling metadata record). - No RWX dependency for block volumes:
isKubeVolumeMountsUnsupported()MUST be split by volume type so clusters withoutSharedPVCName(single-tenant or pure-block CSI clusters with no RWX StorageClass) still allowtype: "block"/volumesCRUD and/workspacemounts, while gating onlytype: "shared"mounts onSharedPVCName. - When
POST /sandboxesrequestsvolumeMounts: [{name, path: "/workspace"}]backed by atype: "block"volume, Gateway validates single-writer exclusivity (via K8s atomic PVC attach-lease CAS +volume.Store), attaches the existingvol-<volumeID>(or adopted legacy PVC) claim as the Pod’sworkspace-volume(VolumeDevices -> /dev/cubepod-workspace) instead of allocating a fresh<boxName>-workspace-pvc, and skipsPodWarmPoolclaiming. podd-initrequires zero changes for the block path: it already formats/fscks/dev/cubepod-workspace(ensure_ext4) and mounts it at<merged>/workspacewhile keepingrootfs-upperstrictly isolated (AGENTS.md Invariant 1).- On
DELETE /sandboxes/{id}(including?deleteVolumes=true):cubepod-controller(Reconciler.DeleteBox) deletes the Pod and ephemeralrootfs-pvc, and always preserves managed block workspace PVCs (both canonicalvol-<volumeID>and in-place adopted legacy PVCs); lifecycle deletion is exclusively controlled byDELETE /volumes/{id}. Local Docker mode similarly skipsos.RemoveAllon managed block volume directories during sandbox deletion.
- Creating a
- Local Development (
Docker + Loopback ext4):- Creating a
type: "block"volume allocates a sparseext4image file<volumesDir>/<volumeID>/workspace.img(or loopback device / isolated host workspace dir when running host-loopback Docker), formatted on first sandbox attach. - Mounting at
/workspaceattaches<volumeID>exclusively to at most one running sandbox (enforcing single-writer409 Conflictparity with K8s RWO).
- Creating a
- Production Kubernetes (
- Pause / Resume with Attached Block Volume:
- When a sandbox with an attached
type: "block"volume at/workspaceisPaused(DesiredState: "Paused"), its compute Pod is deleted (releasing the CSI RWO node attachment while keeping the sandbox-to-volume lease inmounts.json/PodBox.Spec). Resuming (DesiredState: "Running") re-attachesvol-<volumeID>to the new Pod. - Because a
Pausedsandbox still owns that/workspacestate, another sandbox CANNOT mount the sametype: "block"volume concurrently (409 Conflict); the owner sandbox must be deleted (DELETE /sandboxes/{id}) to release the block volume for reuse.
- When a sandbox with an attached
Risks and Mitigations
Section titled “Risks and Mitigations”| Risk | Impact | Mitigation |
|---|---|---|
Concurrent attachment of a type: "block" RWO PVC to two sandboxes (including across HA Gateway replicas without cross-node flock, or delayed in-flight UpsertPodBox) |
K8s Multi-Attach error stalling Pod startup or ext4 corruption |
Local/single-replica mode enforces uniqueness under pkg/volume.Store lock; Kubernetes HA mode acquires an atomic K8s API lease before UpsertPodBox via resourceVersion-guarded CAS setting metadata.annotations["cubepod.io/attached-sandbox"] and metadata.annotations["cubepod.io/attached-at"] (requiring no extra Helm RBAC beyond existing persistentvolumeclaims verbs), enforcing an AttachLeaseGracePeriod (e.g. 30s) before reclaiming NotFound leases. As defense in depth, cubepod-controller performs a fencing check before starting/resuming any Pod and transitions the PodBox to Failed (WorkspaceVolumeLeaseLost) if the PVC is missing or its lease no longer matches boxName. Contention returns 409 Conflict immediately. |
Controller mistakenly deletes a managed block PVC on DELETE /sandboxes/{id} (including ?deleteVolumes=true or after controller restart when !hasSpec) |
Permanent loss of user /workspace data |
Reconciler.DeleteBox MUST never delete a PVC when spec.VolumeMounts contains a type: "block" entry for /workspace, even if deleteVolumes == true. When !hasSpec (cache miss after restart), DeleteBox MUST fall back to GetPodBox and/or inspect the target PVC’s app.kubernetes.io/managed-by=cubepod-volumes label (covering both vol-* and Mode 1 in-place adopted <sanitized>-workspace-pvc claims) before ever calling DeletePVC. |
ForkFrom reuses parent’s RWO vol-<volumeID> or inherits parent’s block mount lease |
CSI multi-attach deadlock + shared corruption | For ForkFrom, BuildBlockPVCsWithOptions still uses WorkspaceSnapshotName / DataSourcePVC pointing to the parent’s WorkspacePVCName to create an ephemeral per-fork <childID>-workspace-pvc; volume.Store.CopyMounts (called by copySandboxVolumeMounts) MUST copy only type: "shared" mounts and skip type: "block" so the child does NOT inherit vol-<volumeID> ownership in mounts.json or PVC attach leases. |
Unclean Pod kill leaves dirty ext4 journal on vol-<volumeID> |
Mount failure on next sandbox attach | podd-init already runs e2fsck -p via ensure_ext4 prior to mounting /dev/cubepod-workspace cleanly before pivot_root(2). |
User attempts /volumecontent/{id}/... against type: "block" volume |
Confusion or unintended host mount exposure | Volume metadata explicitly stores type; /volumecontent/* handlers reject type == "block" upfront with 400 Bad Request (writeContentError, JSON code: "400", "content API is only supported for shared volumes"). |
Design Details
Section titled “Design Details”API / CRD / Wire Changes
Section titled “API / CRD / Wire Changes”1. OpenAPI / REST Wire (api/openapi/cubepod-v1.yaml, pkg/gateway/volumes.go)
Section titled “1. OpenAPI / REST Wire (api/openapi/cubepod-v1.yaml, pkg/gateway/volumes.go)”POST /volumes(CreateVolumeRequest):{"name": "repo-workspace","type": "block","size": "20Gi"}type(optional, enum["shared", "block"], default"shared"):"shared": RWX shared filesystem volume (existing E2B 2.64.0 behavior,/volumecontentsupported). Specifyingsizeontype: "shared"returns400 Bad Request."block": Exclusive RWO block volume (sizedefaults to template/cluster default20Gi; must be a valid positive Kubernetes resource quantity within cluster min/max bounds, e.g.1Gi..1Ti, otherwise400 Bad Request). On Kubernetes,EnsurePVCruns synchronously duringPOST /volumes; provisioning failure rolls back thevolume.Storerecord and returns an error. For tenant byte quotas,type: "block"volumes account their declaredsizeBytesagainstMaxBytesPerTenant(alongsidesharedfile bytes) at creation time.tokenmay be omitted or issued only for schema compatibility while/volumecontentrejectstype == "block"with400 Bad Request.
GET /volumes&GET /volumes/{volumeID}: Include"type": "shared" | "block"and optional"size": "20Gi"in responses (backwards-compatible additive JSON fields).DELETE /volumes/{volumeID}:- Rejects with
409 Conflictif mounted inmounts.json(after evicting any stale entry whose ownerPodBoxisTerminated/FailedorNotFoundpastAttachLeaseGracePeriod), if the target PVC carries a livecubepod.io/attached-sandboxlease, or if any non-Terminated/non-FailedPodBoxreferences the volume inspec.VolumeMounts. deleteVolumePVCMUST NOT hard-requirepvcName == "vol-" + volumeIDfortype: "block"volumes (so Mode 1 in-place adopted<sanitized>-workspace-pvcclaims do not leak). Instead, fortype: "block", it verifiespvcName != sharedPVCAND verifies viaGetPVCthat the PVC carrieslabels["cubepod.io/volume-id"] == volumeIDandlabels["app.kubernetes.io/managed-by"] == "cubepod-volumes"before callingDeletePVC.
- Rejects with
POST /sandboxes(volumeMountssemantics):- Existing validation in
api/v1alpha1.ValidVolumeContainerPathreserves/workspacefortype: "shared"volumes. - When a requested mount references a
type: "block"volume:pathMUST equal"/workspace"(400 Bad Requestotherwise).- At most one
type: "block"volume may be mounted per sandbox (400 Bad Requestotherwise). - Specifying both
extension.volumeKeyand atype: "block"mount at/workspacein the same request returns400 Bad Request. - If already attached to any sandbox in
mounts.json, an active (non-Terminated)PodBoxCR, or the PVC’s atomiccubepod.io/attached-sandboxlease, return409 Conflict. - Coexists seamlessly with
type: "shared"mounts on other paths (e.g./mnt/datasets), and works on pure-block clusters withoutSharedPVCName.
extension.volumeKeyremains supported as legacy/implicit shorthand duringv0.8.x(with deprecation notice inv0.8.0docs ifBlockWorkspaceVolumesis promoted).
- Existing validation in
2. CRD (api/v1alpha1/types.go, deploy/helm/cubepod/crds/cubepod.io_podboxes.yaml)
Section titled “2. CRD (api/v1alpha1/types.go, deploy/helm/cubepod/crds/cubepod.io_podboxes.yaml)”Keep the CRD unified with the REST API by extending the existing VolumeMount struct in PodBoxSpec.VolumeMounts with an optional Type field (no separate WorkspaceVolume field needed):
type VolumeMount struct { VolumeID string `json:"volumeID"` // Type is "shared" (default when omitted) for RWX filesystem mounts, // or "block" for exclusive RWO raw-block mounts (restricted to path "/workspace" in v0.8.0). Type string `json:"type,omitempty"` PVCName string `json:"pvcName"` // SubPath is used only for "shared" volumes. SubPath string `json:"subPath,omitempty"` Path string `json:"path"`}- When
spec.VolumeMountscontains atype: "block"mount (withpath: "/workspace"):WorkspacePVCNamereturns that mount’sPVCName(e.g.vol-<volumeID>or an adopted legacy PVC name) and maps it toVolumeDevices(/dev/cubepod-workspace), never to containerVolumeMounts+subPath.reconciler.ensurePodBoxPVCsensures/verifies the referenced PVC (vol-<volumeID>or adopted legacy PVC) exists (EnsurePVCis idempotent), andReconciler.DeleteBox/ failed cold-create rollback NEVER delete it (even whendeleteVolumes=true).- Controller Fencing Check: Before creating or recreating the compute Pod (
Provisioning -> RunningandPaused -> Running),cubepod-controllerreads the target PVC viaGetPVCand verifies that the PVC exists andpvc.Annotations["cubepod.io/attached-sandbox"] == boxName. If the PVC is missing or owned by a different sandbox (e.g. a delayedUpsertPodBoxarrived after the attach grace period expired), the controller MUST NOT start the Pod and instead transitions thePodBoxtoFailed(Reason:WorkspaceVolumeLeaseLost). - Entries with
type == ""ortype == "shared"continue to be mounted as RWX filesystemVolumeMounts+subPath(non-/workspace), preserving clean data-plane separation betweenVolumeDevicesandVolumeMounts. OnPOST /sandboxes/{id}/fork, the childPodBoxinherits onlysharedentries fromspec.VolumeMounts(nevertype: "block"), andcopySandboxVolumeMounts(volume.Store.CopyMounts) similarly copies onlytype: "shared"mounts.
State Machine & Data Flow
Section titled “State Machine & Data Flow”flowchart TD
Create["POST /volumes {name, type: 'block', size}"] -->|"Create metadata + RWO Block PVC"| VolPVC["PVC: vol-<id> (volumeMode: Block, state: Available)"]
VolPVC -->|"POST /sandboxes (volumeMounts: [{path: '/workspace'}])"| Check{"Attached to another sandbox?"}
Check -->|"Yes"| Conflict["409 Conflict"]
Check -->|"No"| Attach["Commit mount + PVC lease CAS + PodBox.spec.volumeMounts (type: block, path: /workspace)"]
Attach -->|"Kata Pod starts"| Init["podd-init: ensure_ext4(/dev/cubepod-workspace) -> mount at /workspace"]
Init -->|"POST /sandboxes/{id}/fork"| Fork["CSI VolumeSnapshot -> new child <childID>-workspace-pvc"]
Init -->|"DELETE /sandboxes/{id}"| Detach["Delete Pod + rootfs-pvc; release mount -> vol-<id> Available"]
VolPVC -->|"DELETE /volumes/{id}"| DelCheck{"Active mount or PodBox ref?"}
DelCheck -->|"Yes"| DelConflict["409 Conflict"]
DelCheck -->|"No"| Purge["Delete PVC vol-<id> + metadata"]Legacy /workspace Data Migration Strategy
Section titled “Legacy /workspace Data Migration Strategy”Production and staging clusters currently running v0.7.x (and earlier 0.x releases) already hold user data inside existing /workspace PVCs and local loopback directories. Upgrading to v0.8.0 and graduating to v1.0.0 MUST NOT lose, overwrite, or orphan this data.
Inventory of Legacy /workspace Assets in Deployed Clusters
Section titled “Inventory of Legacy /workspace Assets in Deployed Clusters”- Active Anonymous Sandboxes (
spec.VolumeKey == ""):- Ephemeral
/workspacePVCs named<boxName>-workspace-pvc(labelspod.cubeplex.ai/box=<boxName>,pod.cubeplex.ai/vol-type=workspace). - Kept intact as-is;
spec.VolumeMountshas notype: "block"entry, soWorkspacePVCNameresolves<boxName>-workspace-pvcidentically across upgrade and rolling restarts.
- Ephemeral
- Active Sandboxes with
spec.VolumeKey != ""(RunningorPaused):- Persistent
/workspacePVCs named<SanitizeVolumeKey(volumeKey)>-workspace-pvc. - The
PodBoxCR carriesannotations["cubepod.io/volume-key"]andannotations["cubepod.io/owner-tenant"](pkg/gateway/sandboxes.go).
- Persistent
- Retained Orphaned Legacy
VolumeKeyPVCs (Sandbox Already Deleted in<= v0.7.x):- When a sandbox created with
volumeKeywas deleted prior tov0.8.0,Reconciler.DeleteBoxintentionally retained<sanitized>-workspace-pvceven though thePodBoxCR was deleted. - Only the Kubernetes
PersistentVolumeClaim(pod.cubeplex.ai/vol-type=workspace) remains;owner-tenantis absent on the PVC itself because pre-v0.8.0BuildBlockPVCsWithOptionsdid not copy tenant annotations onto the PVC.
- When a sandbox created with
- Local Development (
Docker + Loopback ext4):- Existing directories or sparse images under
<workspaceBaseDir>associated with prior sandboxes /volumeKeyworkloads.
- Existing directories or sparse images under
Two Migration Modes (Lossless by Design)
Section titled “Two Migration Modes (Lossless by Design)”Because pkg/volume.Store (meta.json) and VolumeMount.PVCName (type: "block") store an explicit pvcName string rather than requiring pvcName == "vol-" + volumeID, migration supports Zero-Copy In-Place Adoption as the primary path and optional CSI Snapshot Clone:
-
Mode 1 — Zero-Copy In-Place Adoption (Default, Zero Downtime):
- Why zero-copy: Kubernetes does not allow renaming an existing
PersistentVolumeClaim(metadata.nameis immutable). Instead,volume.StorerecordspvcName: "<legacy-pvc-name>"(e.g.<sanitized>-workspace-pvc),type: "block",size(read from PVCspec.resources.requests.storage), and optionallegacyVolumeKeyinmeta.json. - Data safety invariant: Existing ext4 blocks on the CSI volume are untouched. When a new sandbox attaches the adopted volume,
podd-initensure_ext4detects the existing validext4superblock (blkid/dumpe2fscheck) and skips formatting, running onlye2fsck -pbefore mounting at/workspace. - Automatic Adoption for Active
PodBoxes (syncFromKube):- On
cubepod-gatewayboot and periodic resync, for anyPodBoxwhosespec.VolumeKey != ""and has notype: "block"entry inspec.VolumeMounts, and whoseannotations["cubepod.io/owner-tenant"]is present, Gateway automatically registers a deterministictype: "block"entry involume.Storeunder thatowner-tenanthash referencingstatus.WorkspacePVCNameand patchescubepod.io/volume-idandapp.kubernetes.io/managed-by=cubepod-volumeslabels onto that PVC (idempotent; skips if already registered and labeled). - Subsequent
GET /volumescalls immediately show the volume;POST /sandboxeswith eithervolumeMounts: [{name, path: "/workspace"}]OR legacyextension.volumeKeyresolves to the exact samevolume.Storelock, preventing concurrent multi-attach (409 Conflict).
- On
- Idempotent Migration CLI / Upgrade Job (
cubepod volume migrate-legacy):- Covers already-deleted sandboxes’ retained PVCs (Scenario 3 above) and local workspace directories (Scenario 4), as well as pre-populating entries cleanly during the
v0.8.0test/production rollout:- Lists PVCs in
controller.workloadNamespacewith labelpod.cubeplex.ai/vol-type=workspaceviaKubeClient.ListPVCs(skipping WarmPool standby PVCs*-warm-*, active ephemeral<podBox>-workspace-pvcwithoutVolumeKey, and already-managedvol-*PVCs). - Resolves tenant ownership in strict precedence order:
- Active
PodBoxannotation (cubepod.io/owner-tenant+cubepod.io/volume-key); - Operator-supplied
--owner-map <file.json>(mappingpvcNameorvolumeKey->tenantIDorapiKey); - Explicit
--default-api-key(only when operator explicitly passes it for single-tenant staging/legacy clusters; never auto-assigned to arbitrary callers without authorization).
- Active
- Writes
meta.json(type: "block",pvcName: pvc.Name,pvcNamespace) atomically under.store.lockflockand patches non-breaking tracking labels/annotations onto the migrated PVC (cubepod.io/volume-id,app.kubernetes.io/managed-by=cubepod-volumes).
- Lists PVCs in
- Covers already-deleted sandboxes’ retained PVCs (Scenario 3 above) and local workspace directories (Scenario 4), as well as pre-populating entries cleanly during the
- Lazy Claim Compatibility for Legacy
extension.volumeKeyCallers:- During
v0.8.0, if a client callsPOST /sandboxeswithextension.volumeKey = Kand that volume was not yet pre-migrated:- Gateway checks whether PVC
<SanitizeVolumeKey(K)>-workspace-pvcalready exists viaKubeClient.GetPVC. - Because knowledge of the exact raw string
K(which maps deterministically viaSanitizeVolumeKey) served as the caller credential in<= v0.7.x, if the PVC exists and has no active ownerPodBoxbelonging to a differentowner-tenant, Gateway adopts it under the caller’s tenant on attach (patchingcubepod.io/volume-idandapp.kubernetes.io/managed-by=cubepod-volumeslabels onto the PVC) and adds atype: "block"entry (path: "/workspace") toPodBoxSpec.VolumeMounts. If an activePodBoxwith a differentcubepod.io/owner-tenantowns that PVC, Gateway rejects the request with409 Conflict/403 Forbidden. - Multi-tenant security note: For already-deleted sandboxes whose legacy
volumeKeywas a predictable string (e.g."default"or"workspace"), lazy claiming is first-come-first-served. Multi-tenant clusters SHOULD runcubepod volume migrate-legacy --owner-mapbefore openingv0.8.0traffic and may disable lazy claiming of unmigrated PVCs via--allow-lazy-legacy-volume-claim=false(Helmvolumes.allowLazyLegacyClaim).
- Gateway checks whether PVC
- During
- Why zero-copy: Kubernetes does not allow renaming an existing
-
Mode 2 — Optional CSI Snapshot Clone Migration (
--clone-to-canonical):- Available in
cubepod volume migrate-legacy --clone-to-canonicalwhen an operator wants canonicalvol-<volumeID>PVC names and independent backup before retiring legacy PVCs. - Creates a CSI
VolumeSnapshotof the legacy PVC (WaitVolumeSnapshotReady), creates a newvol-<volumeID>PVC withDataSourceSnapshot, verifiesBoundstatus, and retains the original<sanitized>-workspace-pvcuntouched until the operator manually removes it after validation.
- Available in
Boundary Conditions & Failure Recovery
Section titled “Boundary Conditions & Failure Recovery”- Gateway Crash Between
CommitMounts/ PVC Lease Acquisition andUpsertPodBox: When acquiring a PVC lease, Gateway writes bothmetadata.annotations["cubepod.io/attached-sandbox"] = sandboxIDandmetadata.annotations["cubepod.io/attached-at"] = <RFC3339>. On startup (ConfigureVolumes) and periodic resync (syncFromKube),pkg/gatewaybuilds theactivesandbox set strictly from non-Terminated/non-FailedPodBoxCRs and reconcilesmounts.jsonand stale PVC leases viaReconcileMounts. ANotFoundowner lease is only treated as orphaned and cleared oncenow - attached-at > AttachLeaseGracePeriod(default30s, strictly greater than theUpsertPodBoxrequest timeout) so in-flight sandbox creates are never preempted prematurely. - Asynchronous Reaper Expiration (
ReapIdle->PausedTTLSeconds): Whencubepod-controllerReapIdletransitions aPausedPodBoxwith atype: "block"mount inspec.VolumeMountstoTerminatedwithout going throughDELETE /sandboxes/{id}, it MUST clearmetadata.annotations["cubepod.io/attached-sandbox"](andcubepod.io/attached-at) on the referenced PVC only if the value matches thatPodBoxname. As a defense-in-depth guard, wheneverPOST /sandboxesorDELETE /volumes/{id}observes a non-emptycubepod.io/attached-sandbox: <oldID>(or stalemounts.jsonentry) whoseGetPodBox(<oldID>)returnsPhase == Terminated/Failed, or returnsNotFoundandnow - attached-at > AttachLeaseGracePeriod, Gateway evicts the stalemounts.jsonentry immediately and reclaims/clears the PVC lease viaresourceVersionCAS. - Two Concurrent
POST /sandboxesRequests Claiming the SameblockVolume:- In local / single-replica mode,
Store.CommitMountscheckstype == "block"uniqueness atomically under the store mutex +.store.lockflock. - In Kubernetes multi-replica HA mode, Gateway acquires an atomic K8s API lease on the target PVC (
metadata.annotations["cubepod.io/attached-sandbox"] = sandboxID,cubepod.io/attached-at = nowviaresourceVersionCAS update) before callingUpsertPodBox, eliminating theListPodBoxes->UpsertPodBoxTOCTOU window even when the shared volume-store filesystem does not provide reliable cross-nodeflock(e.g. NFS). Exactly one caller succeeds; the loser receives409 Conflict. IfUpsertPodBoxsubsequently fails, Gateway releases the PVC lease andmounts.jsonentry before returning an error. Even if a severely delayedUpsertPodBoxarrives afterAttachLeaseGracePeriod, the controller’s PVC lease fencing check guarantees the delayedPodBoxtransitions toFailed(WorkspaceVolumeLeaseLost) without ever starting a second Pod.
- In local / single-replica mode,
VolumeMode: FilesystemFallback Clusters: When template/clustervolumeModeisFilesystem(e.g. Kind E2E without raw block CSI),vol-<volumeID>is created withvolumeMode: Filesystem(AccessModes: ["ReadWriteOnce"]) and mounted at/workspaceinstead ofVolumeDevices, preserving identical single-writer API semantics.
Test Plan
Section titled “Test Plan”-
Unit Tests (Go,
-race):pkg/volume/store_test.go: Creatingtype: "block"volumes, declaredsizeBytestenant quota checks, rejection of concurrent block mounts (ErrInUse->409),CopyMountsskippingtype: "block"while preservingtype: "shared", and cleanup after unmount.pkg/controller/manifests_test.go:BuildBlockPVCsWithOptionsandBuildPodManifestwith atype: "block"entry inspec.VolumeMounts(vol-<id>mapped to/dev/cubepod-workspace, never mounted as containerVolumeMounts+subPath, no<boxName>-workspace-pvcleak, CSI snapshot fork pointing tovol-<id>).pkg/controller/reconciler_test.go: State-machine verification ensuringDeleteBox(includingdeleteVolumes=trueand!hasSpeccache-miss fallback) and rollback do NOT deletevol-<id>or adopted managed legacy PVCs, controller fencing check rejects Pod start/resume withFailed(WorkspaceVolumeLeaseLost) when PVC lease does not matchboxName,ReapIdleclears PVC attach lease onPausedTTLSecondsexpiration, andForkFromcreates a separate cloned PVC for the child without inheritingtype: "block"entries inspec.VolumeMounts.pkg/gateway/volumes_test.go: Full API tests forPOST /volumes(type: "block",sizevalidation,EnsurePVCfailure rollback, pure-block cluster withoutSharedPVCName),/volumecontentrejection (400string code),POST /sandboxesmounting at/workspace, non-/workspacepath andvolumeKey+volumeMountsconflict rejection (400),409concurrent mount rejection (including K8s PVC CAS contention),DELETE /volumes/{id}409while mounted (ignoringTerminatedPodBoxes) ->204after sandbox delete (including label-verified deletion of Mode 1 adopted legacy PVCs),POST /sandboxes/{id}/forkindependence, and legacy/workspacePVC auto-adoption / lazyvolumeKeybridging / cross-tenant guard.cmd/cubepod/migration CLI tests: Idempotentcubepod volume migrate-legacyexecution against Memory/fake K8s PVCs and local workspace directories,--owner-mapresolution, and--clone-to-canonicalsnapshot flow.
-
State Machine Verification (
AGENTS.md):- Run
/statechart(TLA+/TLC model check) coveringAvailable -> Attached -> Paused (Pod deleted, volume leased) -> Running -> Detached -> DeletedandForkFromsnapshot clone invariants before implementation PRs merge.
- Run
-
Integration / E2E Tests:
make test-e2e: Local Docker / loopbackext4persistence across sandbox delete -> recreate via/volumes(type: "block").make test-k8s-e2e: Live Kata + Longhorn V2 Block CSI test: create block volume -> attach at/workspace-> write data -> delete sandbox -> create new sandbox with same block volume -> verify data intact -> fork sandbox -> mutate child/workspaceand verify parent block volume untouched -> delete both sandboxes -> delete block volume.
-
Release & Staging Verification Plan (
v0.8.0-> Test Cluster ->v1.0.0GA):- Before
v1.0.0GA, deployv0.8.0into the staging/test Kubernetes cluster that contains representativev0.7.xlegacy/workspacePVCs (activeRunning,Paused, and deleted-sandbox retained<sanitized>-workspace-pvcclaims):- Record SHA-256 checksums of sentinel files inside legacy
/workspacePVCs; - Upgrade control plane (
cubepod-controller,cubepod-gateway, CRD) in place tov0.8.0and confirm existingPodBoxes remain healthy without unintended Pod restarts; - Run
cubepod volume migrate-legacy(and test lazyvolumeKeyadoption +type: "block"mounts); - Verify
GET /volumeslists the migrated block volumes, re-attaching at/workspacepreserves exact sentinel file checksums (ensure_ext4skips formatting), concurrent attach returns409 Conflict, CSIVolumeSnapshotfork isolates writes from the parent block volume, andDELETE /volumes/{id}cleanly reclaims the PVC once unmounted.
- Record SHA-256 checksums of sentinel files inside legacy
- Before
Graduation Criteria
Section titled “Graduation Criteria”- Release Scope (
v0.8.0— Complete Production-Launchable Feature Set + Test Environment Rollout):- All runtime, API, CRD, Helm, SDK (Python/TS/Go), monitoring, statechart (
/statechart), and legacy/workspacemigration capabilities implemented and passing automated unit/E2E suites (make test,make test-e2e,make test-k8s-e2e). - Deployed to staging/test Kubernetes environment and verified end-to-end, including in-place
v0.7.x -> v0.8.0upgrade and legacy/workspacedata migration without data loss.
- All runtime, API, CRD, Helm, SDK (Python/TS/Go), monitoring, statechart (
- GA / Formal Production Release (
v1.0.0):- Staging/test deployment soak complete with zero data-loss or multi-attach incidents;
BlockWorkspaceVolumesenabled by default (true);extension.volumeKeydocumented as legacy compatibility alias (or switched to auto-adopt bridge) with zero breaking data migration gaps for existing users.
- Staging/test deployment soak complete with zero data-loss or multi-attach incidents;
Upgrade / Downgrade Strategy
Section titled “Upgrade / Downgrade Strategy”CreateVolumeRequest.Typedefaults to"shared"when omitted; all existing/volumesclients behave identically without changes.VolumeMount.Typeis optional (omitempty, defaulting to"shared"); existingPodBoxCRs (includingspec.VolumeMounts,spec.VolumeKey, and anonymous/WarmPool sandboxes) continue operating seamlessly without Pod recreation.- In-place adopted legacy PVCs keep their original
<sanitized>-workspace-pvcclaim names; if an operator rolls back fromv0.8.0tov0.7.x, legacyextension.volumeKeycallers continue resolving those exact PVCs without data loss. (--clone-to-canonicalalso preserves the original PVC until manually deleted.) - Disabling
BlockWorkspaceVolumesrejects newPOST /volumes(type: "block") requests with501 Not Implementedwhile existing sandboxes continue running.
Production Readiness Review Questionnaire (PRR)
Section titled “Production Readiness Review Questionnaire (PRR)”- Feature Enablement and Rollback: Gated by
--feature-gate=BlockWorkspaceVolumes=true|false(featureGates.blockWorkspaceVolumesin Helm). Disabling prevents creating newblockvolumes without deleting existingvol-*PVCs or interrupting running pods. - Rollout, Upgrade and Rollback Planning: Gateway restarts reconcile active
mounts.jsonleases againstPodBoxCRs in Kubernetes; rolling upgrades do not detach running PodVolumeDevices. - Monitoring Requirements:
cubepod_block_volumes_total(gauge): active managedtype: "block"volumes across tenants.cubepod_block_volume_attach_conflicts_total(counter): rejected concurrent attach/delete409 Conflictevents.
- Dependencies: Kubernetes CSI driver supporting
volumeMode: BlockandVolumeSnapshot(e.g., Longhorn V2 or OpenEBS LVM-LocalPV) for Kata Block + CoW Fork;FilesystemRWO fallback when clustervolumeModeisFilesystem. - Scalability: Each
type: "block"volume corresponds 1:1 to a Kubernetes PVC (vol-<volumeID>) bounded by tenant volume count & byte quotas (MaxVolumesPerTenant,MaxBytesPerTenant). - Troubleshooting: Check
PodBox.spec.volumeMounts(entries withtype: block),kubectl get pvc vol-<volumeID>(andcubepod.io/attached-sandbox/cubepod.io/attached-atannotations),mounts.jsonactive owner sandbox ID, andcubepod_block_volume_attach_conflicts_totalfor409contention.
Implementation History
Section titled “Implementation History”- 2026-11-21: Drafted CEP-0030 (
provisional,alpha) targetingv0.8.0alongside GitHub Issue #146. - 2026-11-22: Addressed PR #147 review findings and ran TLC
/statechartmodel check (160 states, 0 invariant violations): hardenedReconciler.DeleteBox(deleteVolumes=true&!hasSpecprotection), specified K8s atomic PVC attach-lease CAS (cubepod.io/attached-sandbox+cubepod.io/attached-atgrace period) + controller-side fencing (WorkspaceVolumeLeaseLost) +ReapIdlelease release and stalemounts.jsoneviction, aligneddeleteVolumePVCfor Mode 1 adopted PVCs, clarifiedEnsurePVCrollback,CopyMountsblock filtering,sizequota/validation rules, and multi-tenant lazy claim guardrails.
Drawbacks
Section titled “Drawbacks”- Exposing two volume types (
sharedvsblock) on/volumesintroduces capability asymmetry: callers must understand thatblockvolumes are single-writer,/workspace-only, and do not support/volumecontentoffline file uploads. - Multi-replica Gateway HA requires both shared storage for
pkg/volume.Storemetadata (meta.json/tenants.json, whereas single-replica pure-block clusters can use an RWO PVC) and atomic K8s PVCcubepod.io/attached-sandboxresourceVersionCAS arbitration before Pod creation starts.
Alternatives
Section titled “Alternatives”- Migrate
/workspaceto Shared RWX Filesystem (/volumes): Rejected because RWX POSIX (virtiofsd) sacrifices raw block VM I/O performance, breaks CSIVolumeSnapshotCoW Fork isolation (forks would share and overwrite the parent’s/workspace), and requires an RWX StorageClass even on single-tenant block clusters. - Proxy
/volumecontenttotype: "block"via Ephemeral Helper Pods: Deferred (not needed for Alpha). Mounting an RWO block device into an on-demand helper Pod when no sandbox is running adds seconds of CSI attach/format latency and Pod GC complexity;/filesinside the running sandbox suffices for block workspace I/O. - Keep
extension.volumeKeySeparate Forever: Rejected because users lack/volumesCRUD (GET,DELETE), tenant API-key isolation, and unified quota accounting for persistent/workspacePVCs.