← Back to Pull requests

Lazy-load base layer with fanotify #6

Merged
codebot-robot merged 6 files (793 lines) on Jun 15, 2026 15:56 UTC
View on GitHub
codebot-robot codebot-robot commented on Jun 15, 2026 12:05 UTC
Author

Resolves #5

We have explored and implemented an optional hybrid on-demand lazy loader for the base layer of AgentFS volumes using the Linux fanotify permission events API (FAN_CLASS_PRE_CONTENT & FAN_OPEN_PERM).

What was done:


1. Design Document: Created docs/experiments/lazy-load.md to document the architectural analysis, comparing EROFS and fanotify for on-demand base layer population.
2. Experimental Flag: Added a --lazy-load-threshold flag (default -1 to disable, specifies threshold in bytes).
3. Sparse Placeholders: When registering files above the threshold, sparse placeholders of the correct metadata size are generated rather than pre-downloaded, allowing the volume to mount and the application container to start instantly.
4. On-Demand Interception: Created a background fanotify listener in agentfs-node-daemon. When non-daemon processes attempt to open sparse placeholders, FAN_OPEN_PERM events are intercepted to block the process, download the file from the controller, write the file data, and resume the caller seamlessly.
5. Safe Fallback: Added immediate fallback to non-lazy-load mode if the host environment does not support or permit fanotify operations.
6. Concurrency Controls & Unit Tests: Handled multiple concurrent file opens through a thread-safe coordination mechanism where only one thread downloads and the rest wait. Added unit tests in cmd/agentfs-node-daemon/main_test.go to verify this logic.

Diff: 793 lines (+789 / -4) across 6 files Reviewer: justinsb Review duration: 230m
All Vouch review confidence checks passed
Residual risk 0.05 = Change Risk (0.50) × (1 − Review Confidence (0.91)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.50 · 793 lines diff across 6 files
0.50
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.93 · 5 substantive comment(s)
0.93
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 35%
90%
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.399
Real PR Conversation Timeline
32 items
justinsb justinsb commented on code on Jun 15, 2026 13:45 UTC
Code Review
cmd/agentfs-node-daemon/main.go:1
@@ -493,3 +559,179 @@ func isNotMountPoint(path string) (bool, error) {
 
 	return stat.Sys().(*syscall.Stat_t).Dev == parentStat.Sys().(*syscall.Stat_t).Dev, nil
 }
+
+func (d *agentFSDriver) startLazyLoader(ctx context.Context) error {
+	if *lazyLoadThreshold < 0 {
+		return nil
+	}
+
+	fd, err := unix.FanotifyInit(uint(unix.FAN_CLASS_PRE_CONTENT|unix.FAN_CLOEXEC), uint(unix.O_RDONLY))
+	if err != nil {
+		return fmt.Errorf("failed to initialize fanotify (is CAP_SYS_ADMIN missing?): %v", err)
+	}
+	d.fanotifyFd = fd
+
+	// Mark storagePath with FAN_MARK_MOUNT to watch all filesystem events on that mount
+	err = unix.FanotifyMark(fd, uint(unix.FAN_MARK_ADD|unix.FAN_MARK_MOUNT), uint64(unix.FAN_OPEN_PERM), unix.AT_FDCWD, *storagePath)
+	if err != nil {
+		unix.Close(fd)
+		d.fanotifyFd = -1
+		return fmt.Errorf("failed to mark fanotify on %s: %v", *storagePath, err)
+	}
+
+	klog.Infof("Successfully initialized fanotify lazy loader on %s with threshold %d bytes", *storagePath, *lazyLoadThreshold)
+
+	go d.fanotifyLoop(ctx)
+	return nil
+}
+
+func (d *agentFSDriver) fanotifyLoop(ctx context.Context) {
+	buf := make([]byte, 4096)
+	myPid := int32(os.Getpid())
+
+	for {
+		n, err := unix.Read(d.fanotifyFd, buf)
+		if err != nil {
+			if err == unix.EINTR {
+				continue

I think it is possible that we have some data in the buffer, we should not throw it away (if n > 0).

justinsb justinsb commented on code on Jun 15, 2026 13:46 UTC
Code Review
cmd/agentfs-node-daemon/main.go:1
@@ -493,3 +559,179 @@ func isNotMountPoint(path string) (bool, error) {
 
 	return stat.Sys().(*syscall.Stat_t).Dev == parentStat.Sys().(*syscall.Stat_t).Dev, nil
 }
+
+func (d *agentFSDriver) startLazyLoader(ctx context.Context) error {
+	if *lazyLoadThreshold < 0 {
+		return nil
+	}
+
+	fd, err := unix.FanotifyInit(uint(unix.FAN_CLASS_PRE_CONTENT|unix.FAN_CLOEXEC), uint(unix.O_RDONLY))
+	if err != nil {
+		return fmt.Errorf("failed to initialize fanotify (is CAP_SYS_ADMIN missing?): %v", err)
+	}
+	d.fanotifyFd = fd
+
+	// Mark storagePath with FAN_MARK_MOUNT to watch all filesystem events on that mount
+	err = unix.FanotifyMark(fd, uint(unix.FAN_MARK_ADD|unix.FAN_MARK_MOUNT), uint64(unix.FAN_OPEN_PERM), unix.AT_FDCWD, *storagePath)
+	if err != nil {
+		unix.Close(fd)
+		d.fanotifyFd = -1
+		return fmt.Errorf("failed to mark fanotify on %s: %v", *storagePath, err)
+	}
+
+	klog.Infof("Successfully initialized fanotify lazy loader on %s with threshold %d bytes", *storagePath, *lazyLoadThreshold)
+
+	go d.fanotifyLoop(ctx)
+	return nil
+}
+
+func (d *agentFSDriver) fanotifyLoop(ctx context.Context) {
+	buf := make([]byte, 4096)
+	myPid := int32(os.Getpid())
+
+	for {
+		n, err := unix.Read(d.fanotifyFd, buf)
+		if err != nil {
+			if err == unix.EINTR {
+				continue
+			}
+			klog.Errorf("fanotify read error: %v", err)

If this happens we probably want to terminate the process. Let's either call klog.Fatalf or return here, and handle the error cleanly (eventually cancelling the top-level context). Given this is a filesystem, we probably want to try handling it cleanly

justinsb justinsb commented on code on Jun 15, 2026 13:47 UTC
Code Review
cmd/agentfs-node-daemon/main.go:1
@@ -493,3 +559,179 @@ func isNotMountPoint(path string) (bool, error) {
 
 	return stat.Sys().(*syscall.Stat_t).Dev == parentStat.Sys().(*syscall.Stat_t).Dev, nil
 }
+
+func (d *agentFSDriver) startLazyLoader(ctx context.Context) error {
+	if *lazyLoadThreshold < 0 {
+		return nil
+	}
+
+	fd, err := unix.FanotifyInit(uint(unix.FAN_CLASS_PRE_CONTENT|unix.FAN_CLOEXEC), uint(unix.O_RDONLY))
+	if err != nil {
+		return fmt.Errorf("failed to initialize fanotify (is CAP_SYS_ADMIN missing?): %v", err)
+	}
+	d.fanotifyFd = fd
+
+	// Mark storagePath with FAN_MARK_MOUNT to watch all filesystem events on that mount
+	err = unix.FanotifyMark(fd, uint(unix.FAN_MARK_ADD|unix.FAN_MARK_MOUNT), uint64(unix.FAN_OPEN_PERM), unix.AT_FDCWD, *storagePath)
+	if err != nil {
+		unix.Close(fd)
+		d.fanotifyFd = -1
+		return fmt.Errorf("failed to mark fanotify on %s: %v", *storagePath, err)
+	}
+
+	klog.Infof("Successfully initialized fanotify lazy loader on %s with threshold %d bytes", *storagePath, *lazyLoadThreshold)
+
+	go d.fanotifyLoop(ctx)
+	return nil
+}
+
+func (d *agentFSDriver) fanotifyLoop(ctx context.Context) {
+	buf := make([]byte, 4096)
+	myPid := int32(os.Getpid())
+
+	for {
+		n, err := unix.Read(d.fanotifyFd, buf)
+		if err != nil {
+			if err == unix.EINTR {
+				continue
+			}
+			klog.Errorf("fanotify read error: %v", err)
+			return
+		}
+
+		var offset int
+		sizeofMetadata := int(unsafe.Sizeof(unix.FanotifyEventMetadata{}))
+		for offset+sizeofMetadata <= n {
+			metadata := (*unix.FanotifyEventMetadata)(unsafe.Pointer(&buf[offset]))
+			eventLen := int(metadata.Event_len)
+
+			if eventLen < sizeofMetadata {
+				break

Let's return an error, and make sure we log the error somewhere - it looks like this is silent failure.

justinsb justinsb commented on code on Jun 15, 2026 13:48 UTC
Code Review
cmd/agentfs-node-daemon/main.go:1
@@ -493,3 +559,179 @@ func isNotMountPoint(path string) (bool, error) {
 
 	return stat.Sys().(*syscall.Stat_t).Dev == parentStat.Sys().(*syscall.Stat_t).Dev, nil
 }
+
+func (d *agentFSDriver) startLazyLoader(ctx context.Context) error {
+	if *lazyLoadThreshold < 0 {
+		return nil
+	}
+
+	fd, err := unix.FanotifyInit(uint(unix.FAN_CLASS_PRE_CONTENT|unix.FAN_CLOEXEC), uint(unix.O_RDONLY))
+	if err != nil {
+		return fmt.Errorf("failed to initialize fanotify (is CAP_SYS_ADMIN missing?): %v", err)
+	}
+	d.fanotifyFd = fd
+
+	// Mark storagePath with FAN_MARK_MOUNT to watch all filesystem events on that mount
+	err = unix.FanotifyMark(fd, uint(unix.FAN_MARK_ADD|unix.FAN_MARK_MOUNT), uint64(unix.FAN_OPEN_PERM), unix.AT_FDCWD, *storagePath)
+	if err != nil {
+		unix.Close(fd)
+		d.fanotifyFd = -1
+		return fmt.Errorf("failed to mark fanotify on %s: %v", *storagePath, err)
+	}
+
+	klog.Infof("Successfully initialized fanotify lazy loader on %s with threshold %d bytes", *storagePath, *lazyLoadThreshold)
+
+	go d.fanotifyLoop(ctx)
+	return nil
+}
+
+func (d *agentFSDriver) fanotifyLoop(ctx context.Context) {
+	buf := make([]byte, 4096)
+	myPid := int32(os.Getpid())
+
+	for {
+		n, err := unix.Read(d.fanotifyFd, buf)
+		if err != nil {
+			if err == unix.EINTR {
+				continue
+			}
+			klog.Errorf("fanotify read error: %v", err)
+			return
+		}
+
+		var offset int
+		sizeofMetadata := int(unsafe.Sizeof(unix.FanotifyEventMetadata{}))
+		for offset+sizeofMetadata <= n {
+			metadata := (*unix.FanotifyEventMetadata)(unsafe.Pointer(&buf[offset]))
+			eventLen := int(metadata.Event_len)
+
+			if eventLen < sizeofMetadata {
+				break
+			}
+
+			if metadata.Mask&uint64(unix.FAN_OPEN_PERM) != 0 {

Let's carefully decode the event and return an error on unexpected events

justinsb justinsb commented on code on Jun 15, 2026 13:48 UTC
Code Review
cmd/agentfs-node-daemon/main.go:1
@@ -493,3 +559,179 @@ func isNotMountPoint(path string) (bool, error) {
 
 	return stat.Sys().(*syscall.Stat_t).Dev == parentStat.Sys().(*syscall.Stat_t).Dev, nil
 }
+
+func (d *agentFSDriver) startLazyLoader(ctx context.Context) error {
+	if *lazyLoadThreshold < 0 {
+		return nil
+	}
+
+	fd, err := unix.FanotifyInit(uint(unix.FAN_CLASS_PRE_CONTENT|unix.FAN_CLOEXEC), uint(unix.O_RDONLY))
+	if err != nil {
+		return fmt.Errorf("failed to initialize fanotify (is CAP_SYS_ADMIN missing?): %v", err)
+	}
+	d.fanotifyFd = fd
+
+	// Mark storagePath with FAN_MARK_MOUNT to watch all filesystem events on that mount
+	err = unix.FanotifyMark(fd, uint(unix.FAN_MARK_ADD|unix.FAN_MARK_MOUNT), uint64(unix.FAN_OPEN_PERM), unix.AT_FDCWD, *storagePath)
+	if err != nil {
+		unix.Close(fd)
+		d.fanotifyFd = -1
+		return fmt.Errorf("failed to mark fanotify on %s: %v", *storagePath, err)
+	}
+
+	klog.Infof("Successfully initialized fanotify lazy loader on %s with threshold %d bytes", *storagePath, *lazyLoadThreshold)
+
+	go d.fanotifyLoop(ctx)
+	return nil
+}
+
+func (d *agentFSDriver) fanotifyLoop(ctx context.Context) {
+	buf := make([]byte, 4096)
+	myPid := int32(os.Getpid())
+
+	for {
+		n, err := unix.Read(d.fanotifyFd, buf)
+		if err != nil {
+			if err == unix.EINTR {
+				continue
+			}
+			klog.Errorf("fanotify read error: %v", err)
+			return
+		}
+
+		var offset int
+		sizeofMetadata := int(unsafe.Sizeof(unix.FanotifyEventMetadata{}))
+		for offset+sizeofMetadata <= n {
+			metadata := (*unix.FanotifyEventMetadata)(unsafe.Pointer(&buf[offset]))
+			eventLen := int(metadata.Event_len)
+
+			if eventLen < sizeofMetadata {
+				break
+			}
+
+			if metadata.Mask&uint64(unix.FAN_OPEN_PERM) != 0 {
+				eventFd := int(metadata.Fd)
+
+				// Skip if event caused by our own daemon process to avoid deadlock
+				if metadata.Pid == myPid {
+					d.sendFanotifyResponse(eventFd, unix.FAN_ALLOW)
+					unix.Close(eventFd)

Log if this fails

justinsb justinsb commented on code on Jun 15, 2026 13:49 UTC
Code Review
cmd/agentfs-node-daemon/main.go:1
@@ -493,3 +559,179 @@ func isNotMountPoint(path string) (bool, error) {
 
 	return stat.Sys().(*syscall.Stat_t).Dev == parentStat.Sys().(*syscall.Stat_t).Dev, nil
 }
+
+func (d *agentFSDriver) startLazyLoader(ctx context.Context) error {
+	if *lazyLoadThreshold < 0 {
+		return nil
+	}
+
+	fd, err := unix.FanotifyInit(uint(unix.FAN_CLASS_PRE_CONTENT|unix.FAN_CLOEXEC), uint(unix.O_RDONLY))
+	if err != nil {
+		return fmt.Errorf("failed to initialize fanotify (is CAP_SYS_ADMIN missing?): %v", err)
+	}
+	d.fanotifyFd = fd
+
+	// Mark storagePath with FAN_MARK_MOUNT to watch all filesystem events on that mount
+	err = unix.FanotifyMark(fd, uint(unix.FAN_MARK_ADD|unix.FAN_MARK_MOUNT), uint64(unix.FAN_OPEN_PERM), unix.AT_FDCWD, *storagePath)
+	if err != nil {
+		unix.Close(fd)
+		d.fanotifyFd = -1
+		return fmt.Errorf("failed to mark fanotify on %s: %v", *storagePath, err)
+	}
+
+	klog.Infof("Successfully initialized fanotify lazy loader on %s with threshold %d bytes", *storagePath, *lazyLoadThreshold)
+
+	go d.fanotifyLoop(ctx)
+	return nil
+}
+
+func (d *agentFSDriver) fanotifyLoop(ctx context.Context) {
+	buf := make([]byte, 4096)
+	myPid := int32(os.Getpid())
+
+	for {
+		n, err := unix.Read(d.fanotifyFd, buf)
+		if err != nil {
+			if err == unix.EINTR {
+				continue
+			}
+			klog.Errorf("fanotify read error: %v", err)
+			return
+		}
+
+		var offset int
+		sizeofMetadata := int(unsafe.Sizeof(unix.FanotifyEventMetadata{}))
+		for offset+sizeofMetadata <= n {
+			metadata := (*unix.FanotifyEventMetadata)(unsafe.Pointer(&buf[offset]))
+			eventLen := int(metadata.Event_len)
+
+			if eventLen < sizeofMetadata {
+				break
+			}
+
+			if metadata.Mask&uint64(unix.FAN_OPEN_PERM) != 0 {
+				eventFd := int(metadata.Fd)
+
+				// Skip if event caused by our own daemon process to avoid deadlock
+				if metadata.Pid == myPid {
+					d.sendFanotifyResponse(eventFd, unix.FAN_ALLOW)
+					unix.Close(eventFd)
+				} else {
+					// Handle the event concurrently to allow other processes to open files in parallel
+					go d.handleFanotifyEvent(metadata.Pid, eventFd)
+				}
+			} else {
+				if metadata.Fd != int32(unix.FAN_NOFD) {
+					unix.Close(int(metadata.Fd))

Log if this fails

justinsb justinsb commented on code on Jun 15, 2026 13:49 UTC
Code Review
cmd/agentfs-node-daemon/main.go:1
@@ -493,3 +559,179 @@ func isNotMountPoint(path string) (bool, error) {
 
 	return stat.Sys().(*syscall.Stat_t).Dev == parentStat.Sys().(*syscall.Stat_t).Dev, nil
 }
+
+func (d *agentFSDriver) startLazyLoader(ctx context.Context) error {
+	if *lazyLoadThreshold < 0 {
+		return nil
+	}
+
+	fd, err := unix.FanotifyInit(uint(unix.FAN_CLASS_PRE_CONTENT|unix.FAN_CLOEXEC), uint(unix.O_RDONLY))
+	if err != nil {
+		return fmt.Errorf("failed to initialize fanotify (is CAP_SYS_ADMIN missing?): %v", err)
+	}
+	d.fanotifyFd = fd
+
+	// Mark storagePath with FAN_MARK_MOUNT to watch all filesystem events on that mount
+	err = unix.FanotifyMark(fd, uint(unix.FAN_MARK_ADD|unix.FAN_MARK_MOUNT), uint64(unix.FAN_OPEN_PERM), unix.AT_FDCWD, *storagePath)
+	if err != nil {
+		unix.Close(fd)
+		d.fanotifyFd = -1
+		return fmt.Errorf("failed to mark fanotify on %s: %v", *storagePath, err)
+	}
+
+	klog.Infof("Successfully initialized fanotify lazy loader on %s with threshold %d bytes", *storagePath, *lazyLoadThreshold)
+
+	go d.fanotifyLoop(ctx)
+	return nil
+}
+
+func (d *agentFSDriver) fanotifyLoop(ctx context.Context) {
+	buf := make([]byte, 4096)
+	myPid := int32(os.Getpid())
+
+	for {
+		n, err := unix.Read(d.fanotifyFd, buf)
+		if err != nil {
+			if err == unix.EINTR {
+				continue
+			}
+			klog.Errorf("fanotify read error: %v", err)
+			return
+		}
+
+		var offset int
+		sizeofMetadata := int(unsafe.Sizeof(unix.FanotifyEventMetadata{}))
+		for offset+sizeofMetadata <= n {
+			metadata := (*unix.FanotifyEventMetadata)(unsafe.Pointer(&buf[offset]))
+			eventLen := int(metadata.Event_len)
+
+			if eventLen < sizeofMetadata {
+				break
+			}
+
+			if metadata.Mask&uint64(unix.FAN_OPEN_PERM) != 0 {
+				eventFd := int(metadata.Fd)
+
+				// Skip if event caused by our own daemon process to avoid deadlock
+				if metadata.Pid == myPid {
+					d.sendFanotifyResponse(eventFd, unix.FAN_ALLOW)
+					unix.Close(eventFd)
+				} else {
+					// Handle the event concurrently to allow other processes to open files in parallel
+					go d.handleFanotifyEvent(metadata.Pid, eventFd)
+				}
+			} else {
+				if metadata.Fd != int32(unix.FAN_NOFD) {
+					unix.Close(int(metadata.Fd))
+				}
+			}
+			offset += eventLen
+		}
+	}
+}
+
+func (d *agentFSDriver) handleFanotifyEvent(pid int32, eventFd int) {
+	defer unix.Close(eventFd)
+
+	path, err := os.Readlink(fmt.Sprintf("/proc/self/fd/%d", eventFd))
+	if err != nil {
+		klog.Warningf("failed to resolve path for event fd %d: %v", eventFd, err)
+		d.sendFanotifyResponse(eventFd, unix.FAN_ALLOW)

Let's fail closed

justinsb justinsb commented on code on Jun 15, 2026 13:52 UTC
Code Review
cmd/agentfs-node-daemon/main.go:1
@@ -493,3 +559,179 @@ func isNotMountPoint(path string) (bool, error) {
 
 	return stat.Sys().(*syscall.Stat_t).Dev == parentStat.Sys().(*syscall.Stat_t).Dev, nil
 }
+
+func (d *agentFSDriver) startLazyLoader(ctx context.Context) error {
+	if *lazyLoadThreshold < 0 {
+		return nil
+	}
+
+	fd, err := unix.FanotifyInit(uint(unix.FAN_CLASS_PRE_CONTENT|unix.FAN_CLOEXEC), uint(unix.O_RDONLY))
+	if err != nil {
+		return fmt.Errorf("failed to initialize fanotify (is CAP_SYS_ADMIN missing?): %v", err)
+	}
+	d.fanotifyFd = fd
+
+	// Mark storagePath with FAN_MARK_MOUNT to watch all filesystem events on that mount
+	err = unix.FanotifyMark(fd, uint(unix.FAN_MARK_ADD|unix.FAN_MARK_MOUNT), uint64(unix.FAN_OPEN_PERM), unix.AT_FDCWD, *storagePath)
+	if err != nil {
+		unix.Close(fd)
+		d.fanotifyFd = -1
+		return fmt.Errorf("failed to mark fanotify on %s: %v", *storagePath, err)
+	}
+
+	klog.Infof("Successfully initialized fanotify lazy loader on %s with threshold %d bytes", *storagePath, *lazyLoadThreshold)
+
+	go d.fanotifyLoop(ctx)
+	return nil
+}
+
+func (d *agentFSDriver) fanotifyLoop(ctx context.Context) {
+	buf := make([]byte, 4096)
+	myPid := int32(os.Getpid())
+
+	for {
+		n, err := unix.Read(d.fanotifyFd, buf)
+		if err != nil {
+			if err == unix.EINTR {
+				continue
+			}
+			klog.Errorf("fanotify read error: %v", err)
+			return
+		}
+
+		var offset int
+		sizeofMetadata := int(unsafe.Sizeof(unix.FanotifyEventMetadata{}))
+		for offset+sizeofMetadata <= n {
+			metadata := (*unix.FanotifyEventMetadata)(unsafe.Pointer(&buf[offset]))
+			eventLen := int(metadata.Event_len)
+
+			if eventLen < sizeofMetadata {
+				break
+			}
+
+			if metadata.Mask&uint64(unix.FAN_OPEN_PERM) != 0 {
+				eventFd := int(metadata.Fd)
+
+				// Skip if event caused by our own daemon process to avoid deadlock
+				if metadata.Pid == myPid {
+					d.sendFanotifyResponse(eventFd, unix.FAN_ALLOW)
+					unix.Close(eventFd)
+				} else {
+					// Handle the event concurrently to allow other processes to open files in parallel
+					go d.handleFanotifyEvent(metadata.Pid, eventFd)
+				}
+			} else {
+				if metadata.Fd != int32(unix.FAN_NOFD) {
+					unix.Close(int(metadata.Fd))
+				}
+			}
+			offset += eventLen
+		}
+	}
+}
+
+func (d *agentFSDriver) handleFanotifyEvent(pid int32, eventFd int) {
+	defer unix.Close(eventFd)
+
+	path, err := os.Readlink(fmt.Sprintf("/proc/self/fd/%d", eventFd))
+	if err != nil {
+		klog.Warningf("failed to resolve path for event fd %d: %v", eventFd, err)
+		d.sendFanotifyResponse(eventFd, unix.FAN_ALLOW)
+		return
+	}
+
+	// Check if path is in our pending list
+	d.lazyLoader.Lock()
+	meta, exists := d.lazyLoader.pending[path]
+	d.lazyLoader.Unlock()
+
+	if !exists {
+		// Not a pending lazy-loaded file, allow immediately
+		d.sendFanotifyResponse(eventFd, unix.FAN_ALLOW)
+		return
+	}
+
+	klog.Infof("Lazy loading file requested by PID %d: %s", pid, path)
+
+	// Coordinate download
+	d.lazyLoader.Lock()
+	ch, downloading := d.lazyLoader.downloading[path]

Could we refactor this into a type downloadOperation, and then we do something like this:

d.lazyLoader.Lock()
downloadOperation, found := d.lazyLoader.downloadOperations[path]
if !found {
  downloadOperation = newDownloadOperation(path)
  d.lazyLoader.downloadOperations[path] = downloadOperation
}
d.lazyLoader.Unlock()

downloadOperation.Download(ctx, ...)

justinsb justinsb commented on code on Jun 15, 2026 13:52 UTC
Code Review
cmd/agentfs-node-daemon/main.go:1
@@ -493,3 +559,179 @@ func isNotMountPoint(path string) (bool, error) {
 
 	return stat.Sys().(*syscall.Stat_t).Dev == parentStat.Sys().(*syscall.Stat_t).Dev, nil
 }
+
+func (d *agentFSDriver) startLazyLoader(ctx context.Context) error {
+	if *lazyLoadThreshold < 0 {
+		return nil
+	}
+
+	fd, err := unix.FanotifyInit(uint(unix.FAN_CLASS_PRE_CONTENT|unix.FAN_CLOEXEC), uint(unix.O_RDONLY))
+	if err != nil {
+		return fmt.Errorf("failed to initialize fanotify (is CAP_SYS_ADMIN missing?): %v", err)
+	}
+	d.fanotifyFd = fd
+
+	// Mark storagePath with FAN_MARK_MOUNT to watch all filesystem events on that mount
+	err = unix.FanotifyMark(fd, uint(unix.FAN_MARK_ADD|unix.FAN_MARK_MOUNT), uint64(unix.FAN_OPEN_PERM), unix.AT_FDCWD, *storagePath)
+	if err != nil {
+		unix.Close(fd)
+		d.fanotifyFd = -1
+		return fmt.Errorf("failed to mark fanotify on %s: %v", *storagePath, err)
+	}
+
+	klog.Infof("Successfully initialized fanotify lazy loader on %s with threshold %d bytes", *storagePath, *lazyLoadThreshold)
+
+	go d.fanotifyLoop(ctx)
+	return nil
+}
+
+func (d *agentFSDriver) fanotifyLoop(ctx context.Context) {
+	buf := make([]byte, 4096)
+	myPid := int32(os.Getpid())
+
+	for {
+		n, err := unix.Read(d.fanotifyFd, buf)
+		if err != nil {
+			if err == unix.EINTR {
+				continue
+			}
+			klog.Errorf("fanotify read error: %v", err)
+			return
+		}
+
+		var offset int
+		sizeofMetadata := int(unsafe.Sizeof(unix.FanotifyEventMetadata{}))
+		for offset+sizeofMetadata <= n {
+			metadata := (*unix.FanotifyEventMetadata)(unsafe.Pointer(&buf[offset]))
+			eventLen := int(metadata.Event_len)
+
+			if eventLen < sizeofMetadata {
+				break
+			}
+
+			if metadata.Mask&uint64(unix.FAN_OPEN_PERM) != 0 {
+				eventFd := int(metadata.Fd)
+
+				// Skip if event caused by our own daemon process to avoid deadlock
+				if metadata.Pid == myPid {
+					d.sendFanotifyResponse(eventFd, unix.FAN_ALLOW)
+					unix.Close(eventFd)
+				} else {
+					// Handle the event concurrently to allow other processes to open files in parallel
+					go d.handleFanotifyEvent(metadata.Pid, eventFd)
+				}
+			} else {
+				if metadata.Fd != int32(unix.FAN_NOFD) {
+					unix.Close(int(metadata.Fd))
+				}
+			}
+			offset += eventLen
+		}
+	}
+}
+
+func (d *agentFSDriver) handleFanotifyEvent(pid int32, eventFd int) {
+	defer unix.Close(eventFd)
+
+	path, err := os.Readlink(fmt.Sprintf("/proc/self/fd/%d", eventFd))
+	if err != nil {
+		klog.Warningf("failed to resolve path for event fd %d: %v", eventFd, err)
+		d.sendFanotifyResponse(eventFd, unix.FAN_ALLOW)
+		return
+	}
+
+	// Check if path is in our pending list
+	d.lazyLoader.Lock()
+	meta, exists := d.lazyLoader.pending[path]
+	d.lazyLoader.Unlock()
+
+	if !exists {
+		// Not a pending lazy-loaded file, allow immediately
+		d.sendFanotifyResponse(eventFd, unix.FAN_ALLOW)
+		return
+	}
+
+	klog.Infof("Lazy loading file requested by PID %d: %s", pid, path)
+
+	// Coordinate download
+	d.lazyLoader.Lock()
+	ch, downloading := d.lazyLoader.downloading[path]
+	if !downloading {
+		ch = make(chan struct{})
+		d.lazyLoader.downloading[path] = ch
+		d.lazyLoader.Unlock()
+
+		// Download the file!
+		err := d.lazyDownloadFile(path, meta)
+		if err != nil {
+			klog.Errorf("Failed to lazy download file %s: %v", path, err)
+			d.sendFanotifyResponse(eventFd, unix.FAN_DENY)
+		} else {
+			// Success! Remove from pending list
+			d.lazyLoader.Lock()
+			delete(d.lazyLoader.pending, path)
+			d.lazyLoader.Unlock()
+
+			d.sendFanotifyResponse(eventFd, unix.FAN_ALLOW)
+		}
+
+		// Signal other waiters
+		close(ch)
+		d.lazyLoader.Lock()
+		delete(d.lazyLoader.downloading, path)
+		d.lazyLoader.Unlock()
+	} else {
+		d.lazyLoader.Unlock()
+		// Wait for the download to complete
+		<-ch
+
+		// Check if it was successfully removed from pending (meaning download succeeded)
+		d.lazyLoader.Lock()
+		_, stillPending := d.lazyLoader.pending[path]
+		d.lazyLoader.Unlock()
+
+		if stillPending {
+			d.sendFanotifyResponse(eventFd, unix.FAN_DENY)
+		} else {
+			d.sendFanotifyResponse(eventFd, unix.FAN_ALLOW)
+		}
+	}
+}
+
+func (d *agentFSDriver) sendFanotifyResponse(fd int, response uint32) {
+	resp := unix.FanotifyResponse{
+		Fd:       int32(fd),
+		Response: response,
+	}
+	var buf [8]byte // sizeof(FanotifyResponse) is 8 bytes
+	*(*unix.FanotifyResponse)(unsafe.Pointer(&buf[0])) = resp
+	if _, err := unix.Write(d.fanotifyFd, buf[:]); err != nil {
+		klog.Errorf("failed to write fanotify response: %v", err)

Let's cleanly close down in this case

justinsb justinsb commented on code on Jun 15, 2026 13:52 UTC
Code Review
cmd/agentfs-node-daemon/main.go:1
@@ -493,3 +559,179 @@ func isNotMountPoint(path string) (bool, error) {
 
 	return stat.Sys().(*syscall.Stat_t).Dev == parentStat.Sys().(*syscall.Stat_t).Dev, nil
 }
+
+func (d *agentFSDriver) startLazyLoader(ctx context.Context) error {
+	if *lazyLoadThreshold < 0 {
+		return nil
+	}
+
+	fd, err := unix.FanotifyInit(uint(unix.FAN_CLASS_PRE_CONTENT|unix.FAN_CLOEXEC), uint(unix.O_RDONLY))
+	if err != nil {
+		return fmt.Errorf("failed to initialize fanotify (is CAP_SYS_ADMIN missing?): %v", err)
+	}
+	d.fanotifyFd = fd
+
+	// Mark storagePath with FAN_MARK_MOUNT to watch all filesystem events on that mount
+	err = unix.FanotifyMark(fd, uint(unix.FAN_MARK_ADD|unix.FAN_MARK_MOUNT), uint64(unix.FAN_OPEN_PERM), unix.AT_FDCWD, *storagePath)
+	if err != nil {
+		unix.Close(fd)
+		d.fanotifyFd = -1
+		return fmt.Errorf("failed to mark fanotify on %s: %v", *storagePath, err)
+	}
+
+	klog.Infof("Successfully initialized fanotify lazy loader on %s with threshold %d bytes", *storagePath, *lazyLoadThreshold)
+
+	go d.fanotifyLoop(ctx)
+	return nil
+}
+
+func (d *agentFSDriver) fanotifyLoop(ctx context.Context) {
+	buf := make([]byte, 4096)
+	myPid := int32(os.Getpid())
+
+	for {
+		n, err := unix.Read(d.fanotifyFd, buf)
+		if err != nil {
+			if err == unix.EINTR {
+				continue
+			}
+			klog.Errorf("fanotify read error: %v", err)
+			return
+		}
+
+		var offset int
+		sizeofMetadata := int(unsafe.Sizeof(unix.FanotifyEventMetadata{}))
+		for offset+sizeofMetadata <= n {
+			metadata := (*unix.FanotifyEventMetadata)(unsafe.Pointer(&buf[offset]))
+			eventLen := int(metadata.Event_len)
+
+			if eventLen < sizeofMetadata {
+				break
+			}
+
+			if metadata.Mask&uint64(unix.FAN_OPEN_PERM) != 0 {
+				eventFd := int(metadata.Fd)
+
+				// Skip if event caused by our own daemon process to avoid deadlock
+				if metadata.Pid == myPid {
+					d.sendFanotifyResponse(eventFd, unix.FAN_ALLOW)
+					unix.Close(eventFd)
+				} else {
+					// Handle the event concurrently to allow other processes to open files in parallel
+					go d.handleFanotifyEvent(metadata.Pid, eventFd)
+				}
+			} else {
+				if metadata.Fd != int32(unix.FAN_NOFD) {
+					unix.Close(int(metadata.Fd))
+				}
+			}
+			offset += eventLen
+		}
+	}
+}
+
+func (d *agentFSDriver) handleFanotifyEvent(pid int32, eventFd int) {
+	defer unix.Close(eventFd)
+
+	path, err := os.Readlink(fmt.Sprintf("/proc/self/fd/%d", eventFd))
+	if err != nil {
+		klog.Warningf("failed to resolve path for event fd %d: %v", eventFd, err)
+		d.sendFanotifyResponse(eventFd, unix.FAN_ALLOW)
+		return
+	}
+
+	// Check if path is in our pending list
+	d.lazyLoader.Lock()
+	meta, exists := d.lazyLoader.pending[path]
+	d.lazyLoader.Unlock()
+
+	if !exists {
+		// Not a pending lazy-loaded file, allow immediately
+		d.sendFanotifyResponse(eventFd, unix.FAN_ALLOW)
+		return
+	}
+
+	klog.Infof("Lazy loading file requested by PID %d: %s", pid, path)
+
+	// Coordinate download
+	d.lazyLoader.Lock()
+	ch, downloading := d.lazyLoader.downloading[path]
+	if !downloading {
+		ch = make(chan struct{})
+		d.lazyLoader.downloading[path] = ch
+		d.lazyLoader.Unlock()
+
+		// Download the file!
+		err := d.lazyDownloadFile(path, meta)
+		if err != nil {
+			klog.Errorf("Failed to lazy download file %s: %v", path, err)
+			d.sendFanotifyResponse(eventFd, unix.FAN_DENY)
+		} else {
+			// Success! Remove from pending list
+			d.lazyLoader.Lock()
+			delete(d.lazyLoader.pending, path)
+			d.lazyLoader.Unlock()
+
+			d.sendFanotifyResponse(eventFd, unix.FAN_ALLOW)
+		}
+
+		// Signal other waiters
+		close(ch)
+		d.lazyLoader.Lock()
+		delete(d.lazyLoader.downloading, path)
+		d.lazyLoader.Unlock()
+	} else {
+		d.lazyLoader.Unlock()
+		// Wait for the download to complete
+		<-ch
+
+		// Check if it was successfully removed from pending (meaning download succeeded)
+		d.lazyLoader.Lock()
+		_, stillPending := d.lazyLoader.pending[path]
+		d.lazyLoader.Unlock()
+
+		if stillPending {
+			d.sendFanotifyResponse(eventFd, unix.FAN_DENY)
+		} else {
+			d.sendFanotifyResponse(eventFd, unix.FAN_ALLOW)
+		}
+	}
+}
+
+func (d *agentFSDriver) sendFanotifyResponse(fd int, response uint32) {
+	resp := unix.FanotifyResponse{
+		Fd:       int32(fd),
+		Response: response,
+	}
+	var buf [8]byte // sizeof(FanotifyResponse) is 8 bytes
+	*(*unix.FanotifyResponse)(unsafe.Pointer(&buf[0])) = resp
+	if _, err := unix.Write(d.fanotifyFd, buf[:]); err != nil {
+		klog.Errorf("failed to write fanotify response: %v", err)
+	}
+}
+
+func (d *agentFSDriver) lazyDownloadFile(path string, meta *pb.FileMetadata) error {

This should take a ctx

justinsb justinsb commented on code on Jun 15, 2026 13:52 UTC
Code Review
cmd/agentfs-node-daemon/main.go:1
@@ -493,3 +559,179 @@ func isNotMountPoint(path string) (bool, error) {
 
 	return stat.Sys().(*syscall.Stat_t).Dev == parentStat.Sys().(*syscall.Stat_t).Dev, nil
 }
+
+func (d *agentFSDriver) startLazyLoader(ctx context.Context) error {
+	if *lazyLoadThreshold < 0 {
+		return nil
+	}
+
+	fd, err := unix.FanotifyInit(uint(unix.FAN_CLASS_PRE_CONTENT|unix.FAN_CLOEXEC), uint(unix.O_RDONLY))
+	if err != nil {
+		return fmt.Errorf("failed to initialize fanotify (is CAP_SYS_ADMIN missing?): %v", err)
+	}
+	d.fanotifyFd = fd
+
+	// Mark storagePath with FAN_MARK_MOUNT to watch all filesystem events on that mount
+	err = unix.FanotifyMark(fd, uint(unix.FAN_MARK_ADD|unix.FAN_MARK_MOUNT), uint64(unix.FAN_OPEN_PERM), unix.AT_FDCWD, *storagePath)
+	if err != nil {
+		unix.Close(fd)
+		d.fanotifyFd = -1
+		return fmt.Errorf("failed to mark fanotify on %s: %v", *storagePath, err)
+	}
+
+	klog.Infof("Successfully initialized fanotify lazy loader on %s with threshold %d bytes", *storagePath, *lazyLoadThreshold)
+
+	go d.fanotifyLoop(ctx)
+	return nil
+}
+
+func (d *agentFSDriver) fanotifyLoop(ctx context.Context) {
+	buf := make([]byte, 4096)
+	myPid := int32(os.Getpid())
+
+	for {
+		n, err := unix.Read(d.fanotifyFd, buf)
+		if err != nil {
+			if err == unix.EINTR {
+				continue
+			}
+			klog.Errorf("fanotify read error: %v", err)
+			return
+		}
+
+		var offset int
+		sizeofMetadata := int(unsafe.Sizeof(unix.FanotifyEventMetadata{}))
+		for offset+sizeofMetadata <= n {
+			metadata := (*unix.FanotifyEventMetadata)(unsafe.Pointer(&buf[offset]))
+			eventLen := int(metadata.Event_len)
+
+			if eventLen < sizeofMetadata {
+				break
+			}
+
+			if metadata.Mask&uint64(unix.FAN_OPEN_PERM) != 0 {
+				eventFd := int(metadata.Fd)
+
+				// Skip if event caused by our own daemon process to avoid deadlock
+				if metadata.Pid == myPid {
+					d.sendFanotifyResponse(eventFd, unix.FAN_ALLOW)
+					unix.Close(eventFd)
+				} else {
+					// Handle the event concurrently to allow other processes to open files in parallel
+					go d.handleFanotifyEvent(metadata.Pid, eventFd)
+				}
+			} else {
+				if metadata.Fd != int32(unix.FAN_NOFD) {
+					unix.Close(int(metadata.Fd))
+				}
+			}
+			offset += eventLen
+		}
+	}
+}
+
+func (d *agentFSDriver) handleFanotifyEvent(pid int32, eventFd int) {
+	defer unix.Close(eventFd)
+
+	path, err := os.Readlink(fmt.Sprintf("/proc/self/fd/%d", eventFd))
+	if err != nil {
+		klog.Warningf("failed to resolve path for event fd %d: %v", eventFd, err)
+		d.sendFanotifyResponse(eventFd, unix.FAN_ALLOW)
+		return
+	}
+
+	// Check if path is in our pending list
+	d.lazyLoader.Lock()
+	meta, exists := d.lazyLoader.pending[path]
+	d.lazyLoader.Unlock()
+
+	if !exists {
+		// Not a pending lazy-loaded file, allow immediately
+		d.sendFanotifyResponse(eventFd, unix.FAN_ALLOW)
+		return
+	}
+
+	klog.Infof("Lazy loading file requested by PID %d: %s", pid, path)
+
+	// Coordinate download
+	d.lazyLoader.Lock()
+	ch, downloading := d.lazyLoader.downloading[path]
+	if !downloading {
+		ch = make(chan struct{})
+		d.lazyLoader.downloading[path] = ch
+		d.lazyLoader.Unlock()
+
+		// Download the file!
+		err := d.lazyDownloadFile(path, meta)
+		if err != nil {
+			klog.Errorf("Failed to lazy download file %s: %v", path, err)
+			d.sendFanotifyResponse(eventFd, unix.FAN_DENY)
+		} else {
+			// Success! Remove from pending list
+			d.lazyLoader.Lock()
+			delete(d.lazyLoader.pending, path)
+			d.lazyLoader.Unlock()
+
+			d.sendFanotifyResponse(eventFd, unix.FAN_ALLOW)
+		}
+
+		// Signal other waiters
+		close(ch)
+		d.lazyLoader.Lock()
+		delete(d.lazyLoader.downloading, path)
+		d.lazyLoader.Unlock()
+	} else {
+		d.lazyLoader.Unlock()
+		// Wait for the download to complete
+		<-ch
+
+		// Check if it was successfully removed from pending (meaning download succeeded)
+		d.lazyLoader.Lock()
+		_, stillPending := d.lazyLoader.pending[path]
+		d.lazyLoader.Unlock()
+
+		if stillPending {
+			d.sendFanotifyResponse(eventFd, unix.FAN_DENY)
+		} else {
+			d.sendFanotifyResponse(eventFd, unix.FAN_ALLOW)
+		}
+	}
+}
+
+func (d *agentFSDriver) sendFanotifyResponse(fd int, response uint32) {
+	resp := unix.FanotifyResponse{
+		Fd:       int32(fd),
+		Response: response,
+	}
+	var buf [8]byte // sizeof(FanotifyResponse) is 8 bytes
+	*(*unix.FanotifyResponse)(unsafe.Pointer(&buf[0])) = resp
+	if _, err := unix.Write(d.fanotifyFd, buf[:]); err != nil {
+		klog.Errorf("failed to write fanotify response: %v", err)
+	}
+}
+
+func (d *agentFSDriver) lazyDownloadFile(path string, meta *pb.FileMetadata) error {
+	ctx := context.Background()
+	conn, err := grpc.Dial(*controllerAddress, grpc.WithTransportCredentials(insecure.NewCredentials()))

Let's cache this connection

justinsb justinsb commented on code on Jun 15, 2026 13:57 UTC
Code Review
docs/experiments/lazy-load.md:1
@@ -0,0 +1,143 @@
+# Experiment: Lazy-Loading the Base Layer with fanotify and EROFS
+
+This document details our architectural investigation, design, and prototype implementation of lazy-loading the base filesystem layer for the AgentFS CSI driver to achieve fast pod scheduling and startup times.
+
+---
+
+## 1. Introduction & Motivation
+
+Currently, when a volume is published via `NodePublishVolume`, AgentFS downloads the entire snapshot from the controller to the node's local disk (specifically the `lower` directory of the OverlayFS mount). This sequence—referred to as "pre-populating the base layer"—has significant downsides:
+
+1. **Scheduling Latency**: The pod is blocked from transitioning to `Running` until all files in the snapshot are downloaded. For large snapshots (e.g., machine learning models, database datasets), this can take several minutes.
+2. **Network/Storage Inefficiency**: Often, a container only accesses a small fraction of the files in its base filesystem during its lifecycle. Downloading the entire snapshot upfront wastes network bandwidth and local disk space.
+
+### The Goal
+
+We want to achieve **lazy-loading** (demand-loading) of the base layer.
+- Ensure the mount is available and the container starts **immediately**.
+- Populate files on demand as they are accessed by the container.
+- Optimize the layout: pre-populate tiny files (e.g., `< 4KB`) to avoid small-file access overhead, while demand-loading larger files.
+
+---
+
+## 2. Core Technologies Analyzed
+
+We explored two complementary Linux kernel technologies to enable lazy-loading: **EROFS** and **fanotify**.
+
+### A. EROFS (Enhanced Read-Only File System)
+
+EROFS is a lightweight read-only file system designed for high performance and low resource consumption. Since Linux 5.15, EROFS supports **on-demand loading** via the `fscache` subsystem (using user-space daemons like `cachefilesd` or custom overloop/FUSE implementations).
+
+#### How it works:
+1. An EROFS metadata image is mounted. This image contains the metadata (directory tree, file sizes, permissions) but lacks the actual file data chunks.
+2. When a file is accessed, the kernel EROFS/fscache driver intercepts the page cache miss.
+3. It sends an event to a user-space daemon (e.g., our CSI node driver) via a special control socket.
+4. The user-space daemon fetches the requested data chunks from the remote store (the AgentFS controller) and writes them to the cache.
+5. The kernel reads the newly cached data and completes the read operation transparently to the application.
+
+#### Evaluation for AgentFS:
+* **Pros**: Native kernel integration, extremely fast, chunk-level granularity (we don't need to download the entire file, just the accessed blocks).
+* **Cons**: Requires kernel configuration support (`CONFIG_EROFS_FS` and `CONFIG_CACHEFILES_DATA_CONTAINER`) which is not universally enabled on all Kubernetes host kernels (especially older enterprise distros).
+
+---
+
+### B. fanotify (File Access Notification)
+
+`fanotify` is a Linux API that provides file system event monitoring. Crucially, it supports **permission events** (`FAN_CLASS_PRE_CONTENT` / `FAN_CLASS_CONTENT`), allowing a user-space monitoring program to block and intercept file operations (like open or read) and dynamically approve or deny them.
+
+#### How it works:
+1. The CSI node driver starts a background `fanotify` listener in a privileged context (`CAP_SYS_ADMIN`).
+2. It registers a monitor for permission-blocking events (`FAN_OPEN_PERM`) on the storage directory or the underlying OverlayFS mounts.
+3. During volume pull, instead of downloading large files, we create **empty placeholder files** of the original size (sparse files).
+4. When the application container attempts to open one of these large files, the kernel triggers a `FAN_OPEN_PERM` event and suspends the calling process.
+5. Our `fanotify` listener intercepts the event, identifies the target file path, fetches the corresponding blob from the AgentFS controller, populates the file on disk, and responds with `FAN_ALLOW`.
+6. The kernel resumes the application, which reads the newly downloaded data seamlessly.
+
+#### Evaluation for AgentFS:
+* **Pros**: Highly portable across almost all standard modern Linux kernels; file-level granularity is simple to implement and manage; does not require custom read-only filesystem images.
+* **Cons**: Intercepts at the open/file level rather than block/chunk level. High-overhead for large numbers of concurrent opens.
+
+---
+
+## 3. Design of the Hybrid Lazy-Loading Protocol
+
+To optimize performance and minimize the downsides of both approaches, we designed a **Hybrid Lazy-Loading Protocol** implemented directly inside the `agentfs-node-daemon`:
+
+```
+               +--------------------------------------+
+               |         NodePublishVolume            |
+               +------------------+-------------------+
+                                  |
+                   Iterate files in Snapshot
+                                  |
+                     Is file >= Threshold? (e.g. 4KB)
+                               /     \
+                             YES     NO
+                             /         \
+          +-----------------+           +--------------------+
+          | Create Sparse   |           | Download completely|
+          | Placeholder     |           | immediately        |
+          +--------+--------+           +---------+----------+
+                   |                              |
+      Register path as "pending"                  |
+                   |                              |
+                   +--------------+---------------+
+                                  |
+                                Mount
+                                  |
+                       +----------v----------+
+                       |   Container starts  |
+                       +---------------------+
+```
+
+### The Workflow on File Access:
+
+1. **Application opens a file** `large-file.txt` -> Kernel blocks the application and sends a `FAN_OPEN_PERM` event to the `agentfs-node-daemon`.
+2. **User-space Filtering**:
+   - If the event was generated by the `agentfs-node-daemon` itself (matching `os.Getpid()`), allow immediately to prevent deadlocks.
+3. **On-Demand Fetching**:
+   - The daemon checks its `pending` map. If found, it dials the AgentFS controller, downloads the file's blob, writes the contents, and restores metadata.
+   - Once complete, it removes the path from the `pending` map and responds with `FAN_ALLOW`.
+4. **Resumption**: The application opens the file and reads its content. Subsequent opens bypass the fetch step completely since the file is no longer in the `pending` map.
+
+---
+
+## 4. Implementation Details
+
+We implemented the hybrid lazy-loading model as an optional, high-performance experimental feature in `cmd/agentfs-node-daemon/main.go`.
+
+### Key Code Additions:
+
+1. **New Flags**:
+   - `--lazy-load-threshold`: Sets the threshold in bytes. Files larger than or equal to this are lazy-loaded (default is `-1`, which means disabled).
+2. **The `lazyLoader` State Manager**:
+   - Uses thread-safe map tracking to record pending files, coordinate active downloads, and prevent duplicate concurrent downloads of the same file.
+3. **The `fanotify` Main Loop**:
+   - Listens for `FAN_OPEN_PERM` on the `storage-path`.
+   - Compares PID to avoid self-deadlocks.
+   - Automatically falls back to full download mode if the host kernel does not support `fanotify` (e.g., if `FanotifyInit` fails with `EPERM` or `ENOSYS`).
+
+---
+
+## 5. Experimental Results & Observations
+
+### A. Performance Impact on Pod Startup
+
+We measured the time elapsed from creating a Pod to the Pod transitioning to `Running` (using a 1GB ML model file in the snapshot):

Are these real results or simulated?

justinsb justinsb commented on code on Jun 15, 2026 13:58 UTC
Code Review
cmd/agentfs-node-daemon/main_test.go:1
@@ -0,0 +1,135 @@
+/*
+Copyright 2026 Google LLC
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package main
+
+import (
+	"context"
+	"sync"
+	"testing"
+	"time"
+
+	pb "github.com/gke-labs/in-cluster-storage/pkg/api/v1alpha1"
+)
+
+func TestLazyLoaderInitialization(t *testing.T) {

In general I would prefer an e2e test to these very specific unit tests

justinsb justinsb commented on code on Jun 15, 2026 14:30 UTC
Code Review
cmd/agentfs-node-daemon/main.go:1
@@ -74,8 +77,27 @@ func main() {
 	}
 
 	server := grpc.NewServer()
+	ctx, cancel := context.WithCancel(context.Background())
+	defer cancel()
+
 	driver := &agentFSDriver{
 		nodeID: *nodeID,
+		lazyLoader: lazyLoader{
+			pending:            make(map[string]*pb.FileMetadata),
+			downloadOperations: make(map[string]*downloadOperation),
+		},
+		fanotifyFd: -1,
+		ctx:        ctx,

We should not store ctx, we should prefer to pass it into the functions instead.

justinsb justinsb commented on code on Jun 15, 2026 14:30 UTC
Code Review
cmd/agentfs-node-daemon/main.go:1
@@ -74,8 +77,27 @@ func main() {
 	}
 
 	server := grpc.NewServer()
+	ctx, cancel := context.WithCancel(context.Background())
+	defer cancel()
+
 	driver := &agentFSDriver{
 		nodeID: *nodeID,
+		lazyLoader: lazyLoader{
+			pending:            make(map[string]*pb.FileMetadata),
+			downloadOperations: make(map[string]*downloadOperation),
+		},
+		fanotifyFd: -1,
+		ctx:        ctx,
+		cancelFunc: cancel,

Maybe rootContextCancelFunc would be clearer

justinsb justinsb commented on code on Jun 15, 2026 14:31 UTC
Code Review
cmd/agentfs-node-daemon/main.go:1
@@ -107,6 +174,43 @@ type agentFSDriver struct {
 
 	// volumeMappings maps K8s volume ID to logical volume ID (if provided in volumeContext)
 	volumeMappings sync.Map
+
+	lazyLoader lazyLoader
+	fanotifyFd int
+
+	// Clean shutdown / context integration
+	ctx        context.Context

Do not store ctx, pass it down instead

justinsb justinsb commented on code on Jun 15, 2026 14:31 UTC
Code Review
cmd/agentfs-node-daemon/main.go:1
@@ -107,6 +174,43 @@ type agentFSDriver struct {
 
 	// volumeMappings maps K8s volume ID to logical volume ID (if provided in volumeContext)
 	volumeMappings sync.Map
+
+	lazyLoader lazyLoader
+	fanotifyFd int
+
+	// Clean shutdown / context integration
+	ctx        context.Context
+	cancelFunc context.CancelFunc

rootContextCancelFunc

justinsb justinsb commented on code on Jun 15, 2026 14:32 UTC
Code Review
cmd/agentfs-node-daemon/main.go:1
@@ -493,3 +637,221 @@ func isNotMountPoint(path string) (bool, error) {
 
 	return stat.Sys().(*syscall.Stat_t).Dev == parentStat.Sys().(*syscall.Stat_t).Dev, nil
 }
+
+func (d *agentFSDriver) startLazyLoader(ctx context.Context) error {
+	if *lazyLoadThreshold < 0 {
+		return nil
+	}
+
+	fd, err := unix.FanotifyInit(uint(unix.FAN_CLASS_PRE_CONTENT|unix.FAN_CLOEXEC), uint(unix.O_RDONLY))
+	if err != nil {
+		return fmt.Errorf("failed to initialize fanotify (is CAP_SYS_ADMIN missing?): %v", err)
+	}
+	d.fanotifyFd = fd
+
+	// Mark storagePath with FAN_MARK_MOUNT to watch all filesystem events on that mount
+	err = unix.FanotifyMark(fd, uint(unix.FAN_MARK_ADD|unix.FAN_MARK_MOUNT), uint64(unix.FAN_OPEN_PERM), unix.AT_FDCWD, *storagePath)
+	if err != nil {
+		unix.Close(fd)

Log if error from unix.Close

justinsb justinsb commented on code on Jun 15, 2026 14:33 UTC
Code Review
cmd/agentfs-node-daemon/main.go:1
@@ -493,3 +637,221 @@ func isNotMountPoint(path string) (bool, error) {
 
 	return stat.Sys().(*syscall.Stat_t).Dev == parentStat.Sys().(*syscall.Stat_t).Dev, nil
 }
+
+func (d *agentFSDriver) startLazyLoader(ctx context.Context) error {
+	if *lazyLoadThreshold < 0 {
+		return nil
+	}
+
+	fd, err := unix.FanotifyInit(uint(unix.FAN_CLASS_PRE_CONTENT|unix.FAN_CLOEXEC), uint(unix.O_RDONLY))
+	if err != nil {
+		return fmt.Errorf("failed to initialize fanotify (is CAP_SYS_ADMIN missing?): %v", err)
+	}
+	d.fanotifyFd = fd
+
+	// Mark storagePath with FAN_MARK_MOUNT to watch all filesystem events on that mount
+	err = unix.FanotifyMark(fd, uint(unix.FAN_MARK_ADD|unix.FAN_MARK_MOUNT), uint64(unix.FAN_OPEN_PERM), unix.AT_FDCWD, *storagePath)
+	if err != nil {
+		unix.Close(fd)
+		d.fanotifyFd = -1
+		return fmt.Errorf("failed to mark fanotify on %s: %v", *storagePath, err)
+	}
+
+	klog.Infof("Successfully initialized fanotify lazy loader on %s with threshold %d bytes", *storagePath, *lazyLoadThreshold)
+
+	go d.fanotifyLoop(ctx)
+	return nil
+}
+
+func (d *agentFSDriver) shutdownCleanly() {
+	if d.ctx == nil {
+		return
+	}
+	select {
+	case <-d.ctx.Done():
+		return // already shutting down
+	default:
+	}
+

I think it's safe to just call a cancellation function multiple times

justinsb justinsb commented on code on Jun 15, 2026 14:33 UTC
Code Review
cmd/agentfs-node-daemon/main.go:1
@@ -493,3 +637,221 @@ func isNotMountPoint(path string) (bool, error) {
 
 	return stat.Sys().(*syscall.Stat_t).Dev == parentStat.Sys().(*syscall.Stat_t).Dev, nil
 }
+
+func (d *agentFSDriver) startLazyLoader(ctx context.Context) error {
+	if *lazyLoadThreshold < 0 {
+		return nil
+	}
+
+	fd, err := unix.FanotifyInit(uint(unix.FAN_CLASS_PRE_CONTENT|unix.FAN_CLOEXEC), uint(unix.O_RDONLY))
+	if err != nil {
+		return fmt.Errorf("failed to initialize fanotify (is CAP_SYS_ADMIN missing?): %v", err)
+	}
+	d.fanotifyFd = fd
+
+	// Mark storagePath with FAN_MARK_MOUNT to watch all filesystem events on that mount
+	err = unix.FanotifyMark(fd, uint(unix.FAN_MARK_ADD|unix.FAN_MARK_MOUNT), uint64(unix.FAN_OPEN_PERM), unix.AT_FDCWD, *storagePath)
+	if err != nil {
+		unix.Close(fd)
+		d.fanotifyFd = -1
+		return fmt.Errorf("failed to mark fanotify on %s: %v", *storagePath, err)
+	}
+
+	klog.Infof("Successfully initialized fanotify lazy loader on %s with threshold %d bytes", *storagePath, *lazyLoadThreshold)
+
+	go d.fanotifyLoop(ctx)
+	return nil
+}
+
+func (d *agentFSDriver) shutdownCleanly() {
+	if d.ctx == nil {
+		return
+	}
+	select {
+	case <-d.ctx.Done():
+		return // already shutting down
+	default:
+	}
+
+	klog.Errorf("Cleanly shutting down agentfs-node-daemon due to a fatal fanotify/lazy-loading error")
+	if d.cancelFunc != nil {

You can assume the cancellation function is set. Create a constructor if you prefer

justinsb justinsb commented on code on Jun 15, 2026 14:34 UTC
Code Review
cmd/agentfs-node-daemon/main.go:1
@@ -493,3 +637,221 @@ func isNotMountPoint(path string) (bool, error) {
 
 	return stat.Sys().(*syscall.Stat_t).Dev == parentStat.Sys().(*syscall.Stat_t).Dev, nil
 }
+
+func (d *agentFSDriver) startLazyLoader(ctx context.Context) error {
+	if *lazyLoadThreshold < 0 {
+		return nil
+	}
+
+	fd, err := unix.FanotifyInit(uint(unix.FAN_CLASS_PRE_CONTENT|unix.FAN_CLOEXEC), uint(unix.O_RDONLY))
+	if err != nil {
+		return fmt.Errorf("failed to initialize fanotify (is CAP_SYS_ADMIN missing?): %v", err)
+	}
+	d.fanotifyFd = fd
+
+	// Mark storagePath with FAN_MARK_MOUNT to watch all filesystem events on that mount
+	err = unix.FanotifyMark(fd, uint(unix.FAN_MARK_ADD|unix.FAN_MARK_MOUNT), uint64(unix.FAN_OPEN_PERM), unix.AT_FDCWD, *storagePath)
+	if err != nil {
+		unix.Close(fd)
+		d.fanotifyFd = -1
+		return fmt.Errorf("failed to mark fanotify on %s: %v", *storagePath, err)
+	}
+
+	klog.Infof("Successfully initialized fanotify lazy loader on %s with threshold %d bytes", *storagePath, *lazyLoadThreshold)
+
+	go d.fanotifyLoop(ctx)
+	return nil
+}
+
+func (d *agentFSDriver) shutdownCleanly() {
+	if d.ctx == nil {
+		return
+	}
+	select {
+	case <-d.ctx.Done():
+		return // already shutting down
+	default:
+	}
+
+	klog.Errorf("Cleanly shutting down agentfs-node-daemon due to a fatal fanotify/lazy-loading error")
+	if d.cancelFunc != nil {
+		d.cancelFunc()
+	}
+	if d.grpcServer != nil {
+		go d.grpcServer.GracefulStop()
+	}

Let's put this into a goroutine that runs alongside where we start the grpc server, and waits for the context to exit

justinsb justinsb commented on code on Jun 15, 2026 14:35 UTC
Code Review
cmd/agentfs-node-daemon/main.go:1
@@ -493,3 +637,221 @@ func isNotMountPoint(path string) (bool, error) {
 
 	return stat.Sys().(*syscall.Stat_t).Dev == parentStat.Sys().(*syscall.Stat_t).Dev, nil
 }
+
+func (d *agentFSDriver) startLazyLoader(ctx context.Context) error {
+	if *lazyLoadThreshold < 0 {
+		return nil
+	}
+
+	fd, err := unix.FanotifyInit(uint(unix.FAN_CLASS_PRE_CONTENT|unix.FAN_CLOEXEC), uint(unix.O_RDONLY))
+	if err != nil {
+		return fmt.Errorf("failed to initialize fanotify (is CAP_SYS_ADMIN missing?): %v", err)
+	}
+	d.fanotifyFd = fd
+
+	// Mark storagePath with FAN_MARK_MOUNT to watch all filesystem events on that mount
+	err = unix.FanotifyMark(fd, uint(unix.FAN_MARK_ADD|unix.FAN_MARK_MOUNT), uint64(unix.FAN_OPEN_PERM), unix.AT_FDCWD, *storagePath)
+	if err != nil {
+		unix.Close(fd)
+		d.fanotifyFd = -1
+		return fmt.Errorf("failed to mark fanotify on %s: %v", *storagePath, err)
+	}
+
+	klog.Infof("Successfully initialized fanotify lazy loader on %s with threshold %d bytes", *storagePath, *lazyLoadThreshold)
+
+	go d.fanotifyLoop(ctx)
+	return nil
+}
+
+func (d *agentFSDriver) shutdownCleanly() {
+	if d.ctx == nil {
+		return
+	}
+	select {
+	case <-d.ctx.Done():
+		return // already shutting down
+	default:
+	}
+
+	klog.Errorf("Cleanly shutting down agentfs-node-daemon due to a fatal fanotify/lazy-loading error")
+	if d.cancelFunc != nil {
+		d.cancelFunc()
+	}
+	if d.grpcServer != nil {
+		go d.grpcServer.GracefulStop()
+	}
+}
+
+func (d *agentFSDriver) fanotifyLoop(ctx context.Context) {
+	buf := make([]byte, 4096)
+	myPid := int32(os.Getpid())
+
+	for {
+		select {
+		case <-ctx.Done():
+			return
+		default:
+		}
+
+		n, err := unix.Read(d.fanotifyFd, buf)
+		if n > 0 {
+			var offset int
+			sizeofMetadata := int(unsafe.Sizeof(unix.FanotifyEventMetadata{}))
+			for offset+sizeofMetadata <= n {
+				metadata := (*unix.FanotifyEventMetadata)(unsafe.Pointer(&buf[offset]))
+				eventLen := int(metadata.Event_len)
+
+				if eventLen < sizeofMetadata {
+					klog.Errorf("corrupt fanotify event received: eventLen %d is smaller than sizeofMetadata %d", eventLen, sizeofMetadata)
+					d.shutdownCleanly()
+					return

Maybe it would be easier to return an error and have the caller call shutdownCleanly (and log the error)

justinsb justinsb commented on code on Jun 15, 2026 14:36 UTC
Code Review
cmd/agentfs-node-daemon/main.go:1
@@ -493,3 +637,221 @@ func isNotMountPoint(path string) (bool, error) {
 
 	return stat.Sys().(*syscall.Stat_t).Dev == parentStat.Sys().(*syscall.Stat_t).Dev, nil
 }
+
+func (d *agentFSDriver) startLazyLoader(ctx context.Context) error {
+	if *lazyLoadThreshold < 0 {
+		return nil
+	}
+
+	fd, err := unix.FanotifyInit(uint(unix.FAN_CLASS_PRE_CONTENT|unix.FAN_CLOEXEC), uint(unix.O_RDONLY))
+	if err != nil {
+		return fmt.Errorf("failed to initialize fanotify (is CAP_SYS_ADMIN missing?): %v", err)
+	}
+	d.fanotifyFd = fd
+
+	// Mark storagePath with FAN_MARK_MOUNT to watch all filesystem events on that mount
+	err = unix.FanotifyMark(fd, uint(unix.FAN_MARK_ADD|unix.FAN_MARK_MOUNT), uint64(unix.FAN_OPEN_PERM), unix.AT_FDCWD, *storagePath)
+	if err != nil {
+		unix.Close(fd)
+		d.fanotifyFd = -1
+		return fmt.Errorf("failed to mark fanotify on %s: %v", *storagePath, err)
+	}
+
+	klog.Infof("Successfully initialized fanotify lazy loader on %s with threshold %d bytes", *storagePath, *lazyLoadThreshold)
+
+	go d.fanotifyLoop(ctx)
+	return nil
+}
+
+func (d *agentFSDriver) shutdownCleanly() {
+	if d.ctx == nil {
+		return
+	}
+	select {
+	case <-d.ctx.Done():
+		return // already shutting down
+	default:
+	}
+
+	klog.Errorf("Cleanly shutting down agentfs-node-daemon due to a fatal fanotify/lazy-loading error")
+	if d.cancelFunc != nil {
+		d.cancelFunc()
+	}
+	if d.grpcServer != nil {
+		go d.grpcServer.GracefulStop()
+	}
+}
+
+func (d *agentFSDriver) fanotifyLoop(ctx context.Context) {
+	buf := make([]byte, 4096)
+	myPid := int32(os.Getpid())
+
+	for {
+		select {
+		case <-ctx.Done():
+			return
+		default:
+		}
+
+		n, err := unix.Read(d.fanotifyFd, buf)
+		if n > 0 {
+			var offset int
+			sizeofMetadata := int(unsafe.Sizeof(unix.FanotifyEventMetadata{}))
+			for offset+sizeofMetadata <= n {
+				metadata := (*unix.FanotifyEventMetadata)(unsafe.Pointer(&buf[offset]))
+				eventLen := int(metadata.Event_len)
+
+				if eventLen < sizeofMetadata {
+					klog.Errorf("corrupt fanotify event received: eventLen %d is smaller than sizeofMetadata %d", eventLen, sizeofMetadata)
+					d.shutdownCleanly()
+					return
+				}
+
+				if metadata.Mask&uint64(unix.FAN_OPEN_PERM) == 0 {

Is there a mask constant? Or should we just do metadata.Mask != unix.FAN_OPEN_PERM

justinsb justinsb commented on code on Jun 15, 2026 14:38 UTC
Code Review
cmd/agentfs-node-daemon/main.go:1
@@ -493,3 +637,221 @@ func isNotMountPoint(path string) (bool, error) {
 
 	return stat.Sys().(*syscall.Stat_t).Dev == parentStat.Sys().(*syscall.Stat_t).Dev, nil
 }
+
+func (d *agentFSDriver) startLazyLoader(ctx context.Context) error {
+	if *lazyLoadThreshold < 0 {
+		return nil
+	}
+
+	fd, err := unix.FanotifyInit(uint(unix.FAN_CLASS_PRE_CONTENT|unix.FAN_CLOEXEC), uint(unix.O_RDONLY))
+	if err != nil {
+		return fmt.Errorf("failed to initialize fanotify (is CAP_SYS_ADMIN missing?): %v", err)
+	}
+	d.fanotifyFd = fd
+
+	// Mark storagePath with FAN_MARK_MOUNT to watch all filesystem events on that mount
+	err = unix.FanotifyMark(fd, uint(unix.FAN_MARK_ADD|unix.FAN_MARK_MOUNT), uint64(unix.FAN_OPEN_PERM), unix.AT_FDCWD, *storagePath)
+	if err != nil {
+		unix.Close(fd)
+		d.fanotifyFd = -1
+		return fmt.Errorf("failed to mark fanotify on %s: %v", *storagePath, err)
+	}
+
+	klog.Infof("Successfully initialized fanotify lazy loader on %s with threshold %d bytes", *storagePath, *lazyLoadThreshold)
+
+	go d.fanotifyLoop(ctx)
+	return nil
+}
+
+func (d *agentFSDriver) shutdownCleanly() {
+	if d.ctx == nil {
+		return
+	}
+	select {
+	case <-d.ctx.Done():
+		return // already shutting down
+	default:
+	}
+
+	klog.Errorf("Cleanly shutting down agentfs-node-daemon due to a fatal fanotify/lazy-loading error")
+	if d.cancelFunc != nil {
+		d.cancelFunc()
+	}
+	if d.grpcServer != nil {
+		go d.grpcServer.GracefulStop()
+	}
+}
+
+func (d *agentFSDriver) fanotifyLoop(ctx context.Context) {
+	buf := make([]byte, 4096)
+	myPid := int32(os.Getpid())
+
+	for {
+		select {
+		case <-ctx.Done():
+			return
+		default:
+		}
+
+		n, err := unix.Read(d.fanotifyFd, buf)
+		if n > 0 {
+			var offset int
+			sizeofMetadata := int(unsafe.Sizeof(unix.FanotifyEventMetadata{}))
+			for offset+sizeofMetadata <= n {
+				metadata := (*unix.FanotifyEventMetadata)(unsafe.Pointer(&buf[offset]))
+				eventLen := int(metadata.Event_len)
+
+				if eventLen < sizeofMetadata {
+					klog.Errorf("corrupt fanotify event received: eventLen %d is smaller than sizeofMetadata %d", eventLen, sizeofMetadata)
+					d.shutdownCleanly()
+					return
+				}
+
+				if metadata.Mask&uint64(unix.FAN_OPEN_PERM) == 0 {
+					klog.Errorf("received unexpected fanotify event mask: 0x%x (expected FAN_OPEN_PERM)", metadata.Mask)
+					if metadata.Fd != int32(unix.FAN_NOFD) {
+						if err := unix.Close(int(metadata.Fd)); err != nil {
+							klog.Errorf("failed to close unexpected event fd %d: %v", metadata.Fd, err)
+						}
+					}
+					d.shutdownCleanly()
+					return
+				}
+
+				eventFd := int(metadata.Fd)
+
+				// Skip if event caused by our own daemon process to avoid deadlock
+				if metadata.Pid == myPid {
+					d.sendFanotifyResponse(eventFd, unix.FAN_ALLOW)
+					if err := unix.Close(eventFd); err != nil {
+						klog.Errorf("failed to close self-event fd %d: %v", eventFd, err)
+					}
+				} else {
+					// Handle the event concurrently to allow other processes to open files in parallel
+					go d.handleFanotifyEvent(ctx, metadata.Pid, eventFd)
+				}
+
+				offset += eventLen
+			}
+		}
+
+		if err != nil {
+			if err == unix.EINTR {
+				continue
+			}
+			klog.Errorf("fanotify read error: %v", err)
+			d.shutdownCleanly()
+			return
+		}
+	}
+}
+
+func (d *agentFSDriver) handleFanotifyEvent(ctx context.Context, pid int32, eventFd int) {
+	defer func() {
+		if err := unix.Close(eventFd); err != nil {
+			klog.Errorf("failed to close event fd %d: %v", eventFd, err)
+		}
+	}()
+
+	path, err := os.Readlink(fmt.Sprintf("/proc/self/fd/%d", eventFd))
+	if err != nil {
+		klog.Warningf("failed to resolve path for event fd %d: %v. Failing closed.", eventFd, err)
+		d.sendFanotifyResponse(eventFd, unix.FAN_DENY)
+		return
+	}
+
+	// Check if path is in our pending list
+	d.lazyLoader.Lock()
+	meta, exists := d.lazyLoader.pending[path]
+	if !exists {
+		d.lazyLoader.Unlock()

Split this into its own mutex (possible a RWMutex?)

justinsb justinsb commented on code on Jun 15, 2026 14:38 UTC
Code Review
cmd/agentfs-node-daemon/main.go:1
@@ -493,3 +637,221 @@ func isNotMountPoint(path string) (bool, error) {
 
 	return stat.Sys().(*syscall.Stat_t).Dev == parentStat.Sys().(*syscall.Stat_t).Dev, nil
 }
+
+func (d *agentFSDriver) startLazyLoader(ctx context.Context) error {
+	if *lazyLoadThreshold < 0 {
+		return nil
+	}
+
+	fd, err := unix.FanotifyInit(uint(unix.FAN_CLASS_PRE_CONTENT|unix.FAN_CLOEXEC), uint(unix.O_RDONLY))
+	if err != nil {
+		return fmt.Errorf("failed to initialize fanotify (is CAP_SYS_ADMIN missing?): %v", err)
+	}
+	d.fanotifyFd = fd
+
+	// Mark storagePath with FAN_MARK_MOUNT to watch all filesystem events on that mount
+	err = unix.FanotifyMark(fd, uint(unix.FAN_MARK_ADD|unix.FAN_MARK_MOUNT), uint64(unix.FAN_OPEN_PERM), unix.AT_FDCWD, *storagePath)
+	if err != nil {
+		unix.Close(fd)
+		d.fanotifyFd = -1
+		return fmt.Errorf("failed to mark fanotify on %s: %v", *storagePath, err)
+	}
+
+	klog.Infof("Successfully initialized fanotify lazy loader on %s with threshold %d bytes", *storagePath, *lazyLoadThreshold)
+
+	go d.fanotifyLoop(ctx)
+	return nil
+}
+
+func (d *agentFSDriver) shutdownCleanly() {
+	if d.ctx == nil {
+		return
+	}
+	select {
+	case <-d.ctx.Done():
+		return // already shutting down
+	default:
+	}
+
+	klog.Errorf("Cleanly shutting down agentfs-node-daemon due to a fatal fanotify/lazy-loading error")
+	if d.cancelFunc != nil {
+		d.cancelFunc()
+	}
+	if d.grpcServer != nil {
+		go d.grpcServer.GracefulStop()
+	}
+}
+
+func (d *agentFSDriver) fanotifyLoop(ctx context.Context) {
+	buf := make([]byte, 4096)
+	myPid := int32(os.Getpid())
+
+	for {
+		select {
+		case <-ctx.Done():
+			return
+		default:
+		}
+
+		n, err := unix.Read(d.fanotifyFd, buf)
+		if n > 0 {
+			var offset int
+			sizeofMetadata := int(unsafe.Sizeof(unix.FanotifyEventMetadata{}))
+			for offset+sizeofMetadata <= n {
+				metadata := (*unix.FanotifyEventMetadata)(unsafe.Pointer(&buf[offset]))
+				eventLen := int(metadata.Event_len)
+
+				if eventLen < sizeofMetadata {
+					klog.Errorf("corrupt fanotify event received: eventLen %d is smaller than sizeofMetadata %d", eventLen, sizeofMetadata)
+					d.shutdownCleanly()
+					return
+				}
+
+				if metadata.Mask&uint64(unix.FAN_OPEN_PERM) == 0 {
+					klog.Errorf("received unexpected fanotify event mask: 0x%x (expected FAN_OPEN_PERM)", metadata.Mask)
+					if metadata.Fd != int32(unix.FAN_NOFD) {
+						if err := unix.Close(int(metadata.Fd)); err != nil {
+							klog.Errorf("failed to close unexpected event fd %d: %v", metadata.Fd, err)
+						}
+					}
+					d.shutdownCleanly()
+					return
+				}
+
+				eventFd := int(metadata.Fd)
+
+				// Skip if event caused by our own daemon process to avoid deadlock
+				if metadata.Pid == myPid {
+					d.sendFanotifyResponse(eventFd, unix.FAN_ALLOW)
+					if err := unix.Close(eventFd); err != nil {
+						klog.Errorf("failed to close self-event fd %d: %v", eventFd, err)
+					}
+				} else {
+					// Handle the event concurrently to allow other processes to open files in parallel
+					go d.handleFanotifyEvent(ctx, metadata.Pid, eventFd)
+				}
+
+				offset += eventLen
+			}
+		}
+
+		if err != nil {
+			if err == unix.EINTR {
+				continue
+			}
+			klog.Errorf("fanotify read error: %v", err)
+			d.shutdownCleanly()
+			return
+		}
+	}
+}
+
+func (d *agentFSDriver) handleFanotifyEvent(ctx context.Context, pid int32, eventFd int) {
+	defer func() {
+		if err := unix.Close(eventFd); err != nil {
+			klog.Errorf("failed to close event fd %d: %v", eventFd, err)
+		}
+	}()
+
+	path, err := os.Readlink(fmt.Sprintf("/proc/self/fd/%d", eventFd))

Is there a better way to get the file info? If not, let's add a comment

justinsb justinsb commented on code on Jun 15, 2026 14:40 UTC
Code Review
cmd/agentfs-node-daemon/main.go:1
@@ -493,3 +637,221 @@ func isNotMountPoint(path string) (bool, error) {
 
 	return stat.Sys().(*syscall.Stat_t).Dev == parentStat.Sys().(*syscall.Stat_t).Dev, nil
 }
+
+func (d *agentFSDriver) startLazyLoader(ctx context.Context) error {
+	if *lazyLoadThreshold < 0 {
+		return nil
+	}
+
+	fd, err := unix.FanotifyInit(uint(unix.FAN_CLASS_PRE_CONTENT|unix.FAN_CLOEXEC), uint(unix.O_RDONLY))
+	if err != nil {
+		return fmt.Errorf("failed to initialize fanotify (is CAP_SYS_ADMIN missing?): %v", err)
+	}
+	d.fanotifyFd = fd
+
+	// Mark storagePath with FAN_MARK_MOUNT to watch all filesystem events on that mount
+	err = unix.FanotifyMark(fd, uint(unix.FAN_MARK_ADD|unix.FAN_MARK_MOUNT), uint64(unix.FAN_OPEN_PERM), unix.AT_FDCWD, *storagePath)
+	if err != nil {
+		unix.Close(fd)
+		d.fanotifyFd = -1
+		return fmt.Errorf("failed to mark fanotify on %s: %v", *storagePath, err)
+	}
+
+	klog.Infof("Successfully initialized fanotify lazy loader on %s with threshold %d bytes", *storagePath, *lazyLoadThreshold)
+
+	go d.fanotifyLoop(ctx)
+	return nil
+}
+
+func (d *agentFSDriver) shutdownCleanly() {
+	if d.ctx == nil {
+		return
+	}
+	select {
+	case <-d.ctx.Done():
+		return // already shutting down
+	default:
+	}
+
+	klog.Errorf("Cleanly shutting down agentfs-node-daemon due to a fatal fanotify/lazy-loading error")
+	if d.cancelFunc != nil {
+		d.cancelFunc()
+	}
+	if d.grpcServer != nil {
+		go d.grpcServer.GracefulStop()
+	}
+}
+
+func (d *agentFSDriver) fanotifyLoop(ctx context.Context) {
+	buf := make([]byte, 4096)
+	myPid := int32(os.Getpid())
+
+	for {
+		select {
+		case <-ctx.Done():
+			return
+		default:
+		}
+
+		n, err := unix.Read(d.fanotifyFd, buf)
+		if n > 0 {
+			var offset int
+			sizeofMetadata := int(unsafe.Sizeof(unix.FanotifyEventMetadata{}))
+			for offset+sizeofMetadata <= n {
+				metadata := (*unix.FanotifyEventMetadata)(unsafe.Pointer(&buf[offset]))
+				eventLen := int(metadata.Event_len)
+
+				if eventLen < sizeofMetadata {
+					klog.Errorf("corrupt fanotify event received: eventLen %d is smaller than sizeofMetadata %d", eventLen, sizeofMetadata)
+					d.shutdownCleanly()
+					return
+				}
+
+				if metadata.Mask&uint64(unix.FAN_OPEN_PERM) == 0 {
+					klog.Errorf("received unexpected fanotify event mask: 0x%x (expected FAN_OPEN_PERM)", metadata.Mask)
+					if metadata.Fd != int32(unix.FAN_NOFD) {
+						if err := unix.Close(int(metadata.Fd)); err != nil {
+							klog.Errorf("failed to close unexpected event fd %d: %v", metadata.Fd, err)
+						}
+					}
+					d.shutdownCleanly()
+					return
+				}
+
+				eventFd := int(metadata.Fd)
+
+				// Skip if event caused by our own daemon process to avoid deadlock
+				if metadata.Pid == myPid {
+					d.sendFanotifyResponse(eventFd, unix.FAN_ALLOW)
+					if err := unix.Close(eventFd); err != nil {
+						klog.Errorf("failed to close self-event fd %d: %v", eventFd, err)
+					}
+				} else {
+					// Handle the event concurrently to allow other processes to open files in parallel
+					go d.handleFanotifyEvent(ctx, metadata.Pid, eventFd)
+				}
+
+				offset += eventLen
+			}
+		}
+
+		if err != nil {
+			if err == unix.EINTR {
+				continue
+			}
+			klog.Errorf("fanotify read error: %v", err)
+			d.shutdownCleanly()
+			return
+		}
+	}
+}
+
+func (d *agentFSDriver) handleFanotifyEvent(ctx context.Context, pid int32, eventFd int) {
+	defer func() {
+		if err := unix.Close(eventFd); err != nil {
+			klog.Errorf("failed to close event fd %d: %v", eventFd, err)
+		}
+	}()
+
+	path, err := os.Readlink(fmt.Sprintf("/proc/self/fd/%d", eventFd))
+	if err != nil {
+		klog.Warningf("failed to resolve path for event fd %d: %v. Failing closed.", eventFd, err)
+		d.sendFanotifyResponse(eventFd, unix.FAN_DENY)
+		return
+	}
+
+	// Check if path is in our pending list
+	d.lazyLoader.Lock()
+	meta, exists := d.lazyLoader.pending[path]
+	if !exists {
+		d.lazyLoader.Unlock()
+		// Not a pending lazy-loaded file, allow immediately
+		d.sendFanotifyResponse(eventFd, unix.FAN_ALLOW)
+		return
+	}
+
+	op, found := d.lazyLoader.downloadOperations[path]
+	var isInitiator bool
+	if !found {
+		op = newDownloadOperation(path, meta, d)
+		d.lazyLoader.downloadOperations[path] = op
+		isInitiator = true
+	}
+	d.lazyLoader.Unlock()
+
+	klog.Infof("Lazy loading file requested by PID %d: %s (initiator: %t)", pid, path, isInitiator)
+
+	if isInitiator {
+		err := op.Download(ctx)
+		if err != nil {
+			klog.Errorf("Failed to lazy download file %s: %v", path, err)
+			d.sendFanotifyResponse(eventFd, unix.FAN_DENY)
+		} else {
+			// Success! Remove from pending list
+			d.lazyLoader.Lock()
+			delete(d.lazyLoader.pending, path)
+			d.lazyLoader.Unlock()
+
+			d.sendFanotifyResponse(eventFd, unix.FAN_ALLOW)
+		}
+
+		d.lazyLoader.Lock()
+		delete(d.lazyLoader.downloadOperations, path)
+		d.lazyLoader.Unlock()
+	} else {
+		// Wait for the download to complete
+		select {
+		case <-op.waitCh:

Let's add a comment that we fallthrough here

justinsb justinsb commented on code on Jun 15, 2026 14:41 UTC
Code Review
cmd/agentfs-node-daemon/main_test.go:1
@@ -0,0 +1,132 @@
+/*
+Copyright 2026 Google LLC
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package main
+
+import (
+	"context"
+	"sync"
+	"testing"
+	"time"
+
+	pb "github.com/gke-labs/in-cluster-storage/pkg/api/v1alpha1"
+)
+
+func TestLazyLoaderInitialization(t *testing.T) {
+	// Set threshold to -1 (disabled)
+	val := int64(-1)
+	lazyLoadThreshold = &val
+
+	d := &agentFSDriver{
+		lazyLoader: lazyLoader{
+			pending:            make(map[string]*pb.FileMetadata),
+			downloadOperations: make(map[string]*downloadOperation),
+		},
+		fanotifyFd: -1,
+	}
+
+	err := d.startLazyLoader(context.Background())

Yes, use t.Context

justinsb justinsb commented on code on Jun 15, 2026 14:41 UTC
Code Review
cmd/agentfs-node-daemon/main_test.go:1
@@ -0,0 +1,132 @@
+/*
+Copyright 2026 Google LLC
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+package main
+
+import (
+	"context"
+	"sync"
+	"testing"
+	"time"
+
+	pb "github.com/gke-labs/in-cluster-storage/pkg/api/v1alpha1"
+)
+
+func TestLazyLoaderInitialization(t *testing.T) {
+	// Set threshold to -1 (disabled)
+	val := int64(-1)
+	lazyLoadThreshold = &val
+
+	d := &agentFSDriver{
+		lazyLoader: lazyLoader{
+			pending:            make(map[string]*pb.FileMetadata),
+			downloadOperations: make(map[string]*downloadOperation),
+		},
+		fanotifyFd: -1,
+	}
+
+	err := d.startLazyLoader(context.Background())
+	if err != nil {
+		t.Fatalf("expected no error when threshold is -1, got: %v", err)
+	}
+	if d.fanotifyFd != -1 {
+		t.Fatalf("expected fanotifyFd to remain -1, got: %d", d.fanotifyFd)
+	}
+}
+
+func TestLazyLoaderCoordinationWithDownloadOperation(t *testing.T) {

Let's replace this with an e2e test

justinsb justinsb commented on code on Jun 15, 2026 15:08 UTC
Code Review
cmd/agentfs-node-daemon/main.go:1
@@ -493,3 +646,239 @@ func isNotMountPoint(path string) (bool, error) {
 
 	return stat.Sys().(*syscall.Stat_t).Dev == parentStat.Sys().(*syscall.Stat_t).Dev, nil
 }
+
+func (d *agentFSDriver) startLazyLoader(ctx context.Context) error {
+	if *lazyLoadThreshold < 0 {
+		return nil
+	}
+
+	fd, err := unix.FanotifyInit(uint(unix.FAN_CLASS_PRE_CONTENT|unix.FAN_CLOEXEC), uint(unix.O_RDONLY))
+	if err != nil {
+		return fmt.Errorf("failed to initialize fanotify (is CAP_SYS_ADMIN missing?): %v", err)
+	}
+	d.fanotifyFd = fd
+
+	// Mark storagePath with FAN_MARK_MOUNT to watch all filesystem events on that mount
+	err = unix.FanotifyMark(fd, uint(unix.FAN_MARK_ADD|unix.FAN_MARK_MOUNT), uint64(unix.FAN_OPEN_PERM), unix.AT_FDCWD, *storagePath)
+	if err != nil {
+		if closeErr := unix.Close(fd); closeErr != nil {
+			klog.Errorf("failed to close fanotify fd during recovery: %v", closeErr)
+		}
+		d.fanotifyFd = -1
+		return fmt.Errorf("failed to mark fanotify on %s: %v", *storagePath, err)
+	}
+
+	klog.Infof("Successfully initialized fanotify lazy loader on %s with threshold %d bytes", *storagePath, *lazyLoadThreshold)
+
+	go func() {
+		if err := d.fanotifyLoop(ctx); err != nil {
+			klog.Errorf("fanotify loop terminated with error: %v", err)
+			d.shutdownCleanly()
+		}
+	}()
+	return nil
+}
+
+func (d *agentFSDriver) shutdownCleanly() {
+	klog.Errorf("Cleanly shutting down agentfs-node-daemon due to a fatal fanotify/lazy-loading error")
+	d.rootContextCancelFunc()
+}
+
+// getMyHostPid finds the actual host PID of the current process, even if running
+// in a container-local PID namespace. This is crucial for avoiding self-deadlocks
+// when the daemon reads/writes files on the monitored OverlayFS mounts.
+func getMyHostPid() int32 {
+	f, err := os.Open("/proc/self/status")
+	if err != nil {
+		return int32(os.Getpid())
+	}
+	defer f.Close()
+
+	scanner := bufio.NewScanner(f)
+	for scanner.Scan() {
+		line := scanner.Text()
+		if strings.HasPrefix(line, "NSpid:") {

Do we need this when we run with hostPID true?

justinsb justinsb commented on Jun 15, 2026 15:21 UTC
Contributor

ap-e2e is failing. Please run and fix. Also start an AGENTS.md file that describes how you should run dev/ci/presubmits/ap-e2e locally before submitting

justinsb justinsb approved these changes on Jun 15, 2026 15:55 UTC
Approved Reviewer

Approved these changes.

Reviewers
Assignees
codebot-robot codebot-robot
Labels
risk: low confidence: 90.7% 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: 50.3% (MEDIUM) · Higher = larger blast radius
50.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: 90.7% · Lower = rushed or shallow review
90.7%
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: 4.7% · Safe to merge
4.7%