← Back to Pull requests

feat: Explore storing EROFS layers #16

Merged
codebot-robot merged 7 files (742 lines) on Jun 20, 2026 12:23 UTC
View on GitHub
codebot-robot codebot-robot commented on Jun 19, 2026 02:15 UTC
Author

Please review this Pull Request to explore storing volume snapshots as EROFS layers.

It implements a mode where we download EROFS snapshots as a sequence of layers and stack them using OverlayFS, write changed files in the upper-level overlay to a new EROFS layer when unpublishing, and validate layers with the native Go Fsck.

Fixes #13

Diff: 742 lines (+708 / -34) across 7 files Reviewer: justinsb Review duration: 2047m
All Vouch review confidence checks passed
Residual risk 0.07 = Change Risk (0.51) × (1 − Review Confidence (0.87)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.51 · 742 lines diff across 7 files
0.51
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.86 · 5 substantive comment(s)
0.86
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 35%
87%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.396
Real PR Conversation Timeline
18 items
justinsb justinsb commented on code on Jun 19, 2026 02:18 UTC
Code Review
cmd/agentfs-node-daemon/main.go:1
@@ -416,6 +443,15 @@ func (d *agentFSDriver) NodeUnpublishVolume(ctx context.Context, req *csi.NodeUn
 	delete(d.lazyLoader.mounts, targetPath)
 	d.lazyLoader.mountsMu.Unlock()
 
+	volumeDir := filepath.Join(*storagePath, k8sVolumeID)
+
+	// Push snapshot to controller if EROFS layers mode is enabled (must be done before targetPath is unmounted)

Can we expand this comment? I would have assumed that we would want to unmount and then snapshot the upperdir (which becomes a lowerdir in future?)

justinsb justinsb commented on code on Jun 19, 2026 02:21 UTC
Code Review
cmd/agentfs-node-daemon/main.go:1
@@ -579,6 +668,120 @@ func (d *agentFSDriver) pullSnapshot(ctx context.Context, volumeID, sourcePath s
 	return nil
 }
 
+func (d *agentFSDriver) pushErofsLayersSnapshot(ctx context.Context, volumeID, volumeDir, targetPath string) error {
+	conn, err := d.getControllerConn()
+	if err != nil {
+		return err
+	}
+
+	client := pb.NewAgentFSControllerClient(conn)
+
+	// Fetch latest snapshot from the controller to get existing layers
+	resp, err := client.GetLatestSnapshot(ctx, &pb.GetLatestSnapshotRequest{VolumeId: volumeID})
+	if err != nil {
+		return fmt.Errorf("failed to get latest snapshot: %v", err)
+	}
+
+	var existingLayers []string
+	if resp != nil && resp.Snapshot != nil {
+		existingLayers = resp.Snapshot.ErofsLayers
+		if len(existingLayers) == 0 && resp.Snapshot.ErofsSha256 != "" {
+			existingLayers = []string{resp.Snapshot.ErofsSha256}
+		}
+	}
+
+	upperPath := filepath.Join(volumeDir, "upper")
+
+	// Check if upper/ directory is empty (no changes)
+	isEmpty := true
+	if _, err := os.Stat(upperPath); err == nil {
+		entries, err := os.ReadDir(upperPath)
+		if err == nil && len(entries) > 0 {
+			isEmpty = false
+		}
+	}
+
+	if isEmpty {
+		klog.Infof("Upper directory %s is empty, no new EROFS layer to create/push", upperPath)
+		return nil
+	}
+
+	// Check if we should combine/flatten layers
+	shouldCombine := len(existingLayers) >= 2

Let's add a comment about whether the 2 is a hard limit (e.g. overlayfs is limited to 2/3 layers) vs a heuristic

justinsb justinsb commented on code on Jun 19, 2026 02:21 UTC
Code Review
cmd/agentfs-node-daemon/main_test.go:1
@@ -80,3 +84,57 @@ func TestLazyLoaderCoordinationWithDownloadOperation(t *testing.T) {
 	}
 	d.lazyLoader.downloadMu.Unlock()
 }
+
+func TestErofsLayersLowerdirOption(t *testing.T) {

Let's test this using an e2e test instead of a unit test

justinsb justinsb commented on code on Jun 20, 2026 10:38 UTC
Code Review
cmd/agentfs-node-daemon/main.go:1
@@ -318,13 +322,36 @@ func (d *agentFSDriver) NodePublishVolume(ctx context.Context, req *csi.NodePubl
 	}
 
 	// Mount overlayfs to target path
-	opts := fmt.Sprintf("lowerdir=%s,upperdir=%s,workdir=%s", lowerPath, upperPath, workPath)
+	var lowerdirOpt string
+	if d.enableEROFSLayers {
+		var layers []string
+		for i := 0; ; i++ {
+			p := filepath.Join(volumeDir, fmt.Sprintf("layer-%d", i))
+			if _, err := os.Stat(p); err != nil {

We should check that the error is indeed IsNotFound; any error other than IsNotFound should be returned as an error

justinsb justinsb commented on code on Jun 20, 2026 10:38 UTC
Code Review
cmd/agentfs-node-daemon/main.go:1
@@ -318,13 +322,36 @@ func (d *agentFSDriver) NodePublishVolume(ctx context.Context, req *csi.NodePubl
 	}
 
 	// Mount overlayfs to target path
-	opts := fmt.Sprintf("lowerdir=%s,upperdir=%s,workdir=%s", lowerPath, upperPath, workPath)
+	var lowerdirOpt string
+	if d.enableEROFSLayers {
+		var layers []string
+		for i := 0; ; i++ {
+			p := filepath.Join(volumeDir, fmt.Sprintf("layer-%d", i))
+			if _, err := os.Stat(p); err != nil {
+				break
+			}
+			layers = append(layers, p)
+		}
+		if len(layers) > 0 {
+			var revLayers []string
+			for i := len(layers) - 1; i >= 0; i-- {
+				revLayers = append(revLayers, layers[i])
+			}

Is this slices.Reverse ?

justinsb justinsb commented on code on Jun 20, 2026 10:44 UTC
Code Review
cmd/agentfs-node-daemon/main.go:1
@@ -579,6 +672,125 @@ func (d *agentFSDriver) pullSnapshot(ctx context.Context, volumeID, sourcePath s
 	return nil
 }
 
+func (d *agentFSDriver) pushErofsLayersSnapshot(ctx context.Context, volumeID, volumeDir, targetPath string) error {
+	conn, err := d.getControllerConn()
+	if err != nil {
+		return err
+	}
+
+	client := pb.NewAgentFSControllerClient(conn)
+
+	// Fetch latest snapshot from the controller to get existing layers
+	resp, err := client.GetLatestSnapshot(ctx, &pb.GetLatestSnapshotRequest{VolumeId: volumeID})
+	if err != nil {
+		return fmt.Errorf("failed to get latest snapshot: %v", err)
+	}

Let's just store the volume information as a proto file on disk, perhaps in the directory where we are building all the layers and layer mounts. This should let us detect when e.g. we're trying to upload a new version of the disk, but someone else has also uploaded one ("optimistic concurrency")

justinsb justinsb commented on code on Jun 20, 2026 10:44 UTC
Code Review
cmd/agentfs-node-daemon/main.go:1
@@ -485,6 +542,42 @@ func (d *agentFSDriver) pullSnapshot(ctx context.Context, volumeID, sourcePath s
 		return nil
 	}
 
+	if d.enableEROFSLayers {
+		layers := resp.Snapshot.ErofsLayers
+		if len(layers) == 0 && resp.Snapshot.ErofsSha256 != "" {
+			layers = []string{resp.Snapshot.ErofsSha256}
+		}
+
+		volumeDir := filepath.Dir(sourcePath)
+
+		if len(layers) == 0 {
+			klog.Infof("No EROFS layers for volume %s, using empty lower path", volumeID)
+			return nil
+		}
+
+		for i, layerSha := range layers {
+			imagePath := filepath.Join(volumeDir, fmt.Sprintf("erofs-%s.img", layerSha))

If two volumes have the same read-only EROFS layer, we want to download it once and store it once.

justinsb justinsb commented on code on Jun 20, 2026 10:45 UTC
Code Review
cmd/agentfs-node-daemon/main.go:1
@@ -579,6 +672,125 @@ func (d *agentFSDriver) pullSnapshot(ctx context.Context, volumeID, sourcePath s
 	return nil
 }
 
+func (d *agentFSDriver) pushErofsLayersSnapshot(ctx context.Context, volumeID, volumeDir, targetPath string) error {
+	conn, err := d.getControllerConn()
+	if err != nil {
+		return err
+	}
+
+	client := pb.NewAgentFSControllerClient(conn)
+
+	// Fetch latest snapshot from the controller to get existing layers
+	resp, err := client.GetLatestSnapshot(ctx, &pb.GetLatestSnapshotRequest{VolumeId: volumeID})
+	if err != nil {
+		return fmt.Errorf("failed to get latest snapshot: %v", err)
+	}
+
+	var existingLayers []string
+	if resp != nil && resp.Snapshot != nil {
+		existingLayers = resp.Snapshot.ErofsLayers
+		if len(existingLayers) == 0 && resp.Snapshot.ErofsSha256 != "" {
+			existingLayers = []string{resp.Snapshot.ErofsSha256}
+		}

Do we need ErofsSha256? It feels redundant with ErofsLayers (and we have to do this little dance every time)

justinsb justinsb commented on code on Jun 20, 2026 10:45 UTC
Code Review
cmd/agentfs-node-daemon/main.go:1
@@ -579,6 +672,125 @@ func (d *agentFSDriver) pullSnapshot(ctx context.Context, volumeID, sourcePath s
 	return nil
 }
 
+func (d *agentFSDriver) pushErofsLayersSnapshot(ctx context.Context, volumeID, volumeDir, targetPath string) error {
+	conn, err := d.getControllerConn()
+	if err != nil {
+		return err
+	}
+
+	client := pb.NewAgentFSControllerClient(conn)
+
+	// Fetch latest snapshot from the controller to get existing layers
+	resp, err := client.GetLatestSnapshot(ctx, &pb.GetLatestSnapshotRequest{VolumeId: volumeID})
+	if err != nil {
+		return fmt.Errorf("failed to get latest snapshot: %v", err)
+	}
+
+	var existingLayers []string
+	if resp != nil && resp.Snapshot != nil {
+		existingLayers = resp.Snapshot.ErofsLayers
+		if len(existingLayers) == 0 && resp.Snapshot.ErofsSha256 != "" {
+			existingLayers = []string{resp.Snapshot.ErofsSha256}
+		}
+	}
+
+	upperPath := filepath.Join(volumeDir, "upper")
+
+	// Check if upper/ directory is empty (no changes)
+	isEmpty := true

Nit: isUpperLayerEmpty

justinsb justinsb commented on Jun 20, 2026 10:47 UTC
Contributor

OK really great stuff, some proposed tweaks

justinsb justinsb commented on code on Jun 20, 2026 10:59 UTC
Code Review
cmd/agentfs-node-daemon/main.go:1
@@ -416,6 +445,19 @@ func (d *agentFSDriver) NodeUnpublishVolume(ctx context.Context, req *csi.NodeUn
 	delete(d.lazyLoader.mounts, targetPath)
 	d.lazyLoader.mountsMu.Unlock()
 
+	volumeDir := filepath.Join(*storagePath, k8sVolumeID)
+
+	// Push snapshot to controller if EROFS layers mode is enabled.
+	// This must be done before targetPath is unmounted because when we combine or flatten layers,
+	// we compile the entire merged targetPath (active union/view of all layers) into a single,
+	// consolidated EROFS image. If the targetPath is unmounted first, we would lose this unified
+	// view and would be unable to perform client-side layer flattening/compilation.
+	if d.enableEROFSLayers {
+		if err := d.pushErofsLayersSnapshot(ctx, logicalVolumeID, volumeDir, targetPath); err != nil {
+			klog.Errorf("failed to push EROFS layers snapshot for volume %s (logical: %s): %v", k8sVolumeID, logicalVolumeID, err)

I think we have to return this error, we have to retry here or there will be silent data loss

justinsb justinsb commented on code on Jun 20, 2026 11:00 UTC
Code Review
cmd/agentfs-node-daemon/main.go:1
@@ -434,34 +476,51 @@ func (d *agentFSDriver) NodeUnpublishVolume(ctx context.Context, req *csi.NodeUn
 		}
 	}
 
-	// Push snapshot to controller
-	volumeDir := filepath.Join(*storagePath, k8sVolumeID)
-	if err := d.pushSnapshot(ctx, logicalVolumeID, volumeDir); err != nil {
-		klog.Errorf("failed to push snapshot for volume %s (logical: %s): %v", k8sVolumeID, logicalVolumeID, err)
-	} else {
-		// Clean up lazyLoader pending entries for this volume
-		d.lazyLoader.pendingMu.Lock()
-		for path := range d.lazyLoader.pending {
-			if strings.HasPrefix(path, volumeDir) {
-				delete(d.lazyLoader.pending, path)
+	// Try to unmount any EROFS layer mounts if we are in EROFS layers mode
+	if d.enableEROFSLayers {
+		layerDirs, _ := filepath.Glob(filepath.Join(volumeDir, "layer-*"))
+		for _, ld := range layerDirs {
+			if err := syscall.Unmount(ld, 0); err != nil {
+				klog.Warningf("failed to unmount EROFS layer mount %s: %v", ld, err)
 			}
 		}
-		d.lazyLoader.pendingMu.Unlock()
+	}
 
-		d.lazyLoader.downloadMu.Lock()
-		for path := range d.lazyLoader.downloadOperations {
-			if strings.HasPrefix(path, volumeDir) {
-				delete(d.lazyLoader.downloadOperations, path)
-			}
+	if !d.enableEROFSLayers {
+		// Push snapshot to controller (classic/standard mode)
+		if err := d.pushSnapshot(ctx, logicalVolumeID, volumeDir); err != nil {
+			klog.Errorf("failed to push snapshot for volume %s (logical: %s): %v", k8sVolumeID, logicalVolumeID, err)

Same here, we need to return the error to force a retry, otherwise there will be silent data loss

justinsb justinsb commented on code on Jun 20, 2026 11:00 UTC
Code Review
cmd/agentfs-node-daemon/main.go:1
@@ -485,6 +544,82 @@ func (d *agentFSDriver) pullSnapshot(ctx context.Context, volumeID, sourcePath s
 		return nil
 	}
 
+	if d.enableEROFSLayers {
+		volumeDir := filepath.Dir(sourcePath)
+
+		// Save the latest snapshot metadata as snapshot.pb inside volumeDir on disk.
+		// This enables offline/cached state access and facilitates optimistic concurrency checks.
+		snapshotPBPath := filepath.Join(volumeDir, "snapshot.pb")
+		snapshotData, err := proto.Marshal(resp.Snapshot)
+		if err != nil {
+			return fmt.Errorf("failed to marshal snapshot metadata: %v", err)
+		}
+		if err := os.WriteFile(snapshotPBPath, snapshotData, 0644); err != nil {
+			return fmt.Errorf("failed to write snapshot metadata to %s: %v", snapshotPBPath, err)
+		}

Can we always save the snapshot.pb, even without erofs?

justinsb justinsb commented on code on Jun 20, 2026 11:01 UTC
Code Review
cmd/agentfs-node-daemon/main.go:1
@@ -579,6 +714,163 @@ func (d *agentFSDriver) pullSnapshot(ctx context.Context, volumeID, sourcePath s
 	return nil
 }
 
+func (d *agentFSDriver) pushErofsLayersSnapshot(ctx context.Context, volumeID, volumeDir, targetPath string) error {
+	conn, err := d.getControllerConn()
+	if err != nil {
+		return err
+	}
+
+	client := pb.NewAgentFSControllerClient(conn)
+
+	// Load the volume snapshot information from the local snapshot.pb file on disk
+	snapshotPBPath := filepath.Join(volumeDir, "snapshot.pb")
+	var localSnapshot pb.SnapshotMetadata
+	hasLocalSnapshot := false
+	if data, err := os.ReadFile(snapshotPBPath); err == nil {
+		if err := proto.Unmarshal(data, &localSnapshot); err == nil {
+			hasLocalSnapshot = true
+		} else {
+			klog.Warningf("failed to unmarshal local snapshot metadata from %s: %v", snapshotPBPath, err)

This should be an error that we return

justinsb justinsb approved these changes on Jun 20, 2026 11:10 UTC
Approved Reviewer

Approved these changes.

justinsb justinsb commented on Jun 20, 2026 11:27 UTC
Contributor

So I'm assuming something is going wrong in our e2e test with our unmount:

    e2e_test.go:439: Waiting for pod layers-pod-1 to be ready in namespace default
    e2e_test.go:439: Pod layers-pod-1 phase: Pending, ready: false
    e2e_test.go:439: Pod layers-pod-1 phase: Pending, ready: false
    e2e_test.go:439: Pod layers-pod-1 phase: Running, ready: true
    e2e_test.go:439: Pod layers-pod-1 is ready (phase: Running)
    e2e_test.go:444: Deleting Pod 1 to trigger layer 1 upload
panic: test timed out after 20m0s
	running tests:
		TestEROFSLayersE2E (14m53s)

Let's put a relatively short timeout on pod deletion (1 minute), and let's dump logs and the pod status etc if we hit the timeout. Create a function to dump logs in the harness, as we'll want to extend this in future (e.g. to write to an ARTIFACTS dir etc)

justinsb justinsb approved these changes on Jun 20, 2026 11:38 UTC
Approved Reviewer

Approved these changes.

Reviewers
Assignees
codebot-robot codebot-robot
Labels
risk: low confidence: 87.3% reviewed
Vouch Risk Breakdown
AI-powered review risk analysis
Change Risk
Change Risk · Model 1 (XGBoost)
Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
Score: 51.3% (MEDIUM) · Higher = larger blast radius
51.3%
Review Confidence
Review Confidence · Models 2 & 3
Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
Score: 87.3% · Lower = rushed or shallow review
87.3%
Residual Risk
Residual Risk · Core Equation
Residual = Change × (1 − Confidence)
Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
Score: 6.5% · Safe to merge
6.5%