An open-source, faster Devin alternative
TypeScript
qemu: harden hibernate/checkpoint against rootfs corruption (#238)
Mohamed Habib50627c67de59
diff --git a/internal/agent/stats.go b/internal/agent/stats.goindex a565e7bf..ba22107c 100644--- a/internal/agent/stats.go+++ b/internal/agent/stats.go@@ -58,9 +58,34 @@ func (s *Server) Stats(ctx context.Context, req *pb.StatsRequest) (*pb.StatsResp// Network from /proc/net/devresp.NetInput, resp.NetOutput = readNetStats()+ // Disk usage via statvfs(). The worker uses these to refuse hibernate /+ // checkpoint when rootfs is critically full, before the qcow2 ends up+ // captured in an inconsistent state. Errors silently zero the fields —+ // the worker treats 0/0 as "unknown" and falls back to no pressure gate.+ resp.RootfsUsedBytes, resp.RootfsTotalBytes = diskUsage("/")+ resp.WorkspaceUsedBytes, resp.WorkspaceTotalBytes = diskUsage("/home/sandbox")+return resp, nil}+// diskUsage returns (used, total) in bytes for the filesystem containing path.+// On any error, returns (0, 0) — caller treats that as "unknown".+func diskUsage(path string) (used, total uint64) {+ var st syscall.Statfs_t+ if err := syscall.Statfs(path, &st); err != nil {+ return 0, 0+ }+ bsize := uint64(st.Bsize)+ total = st.Blocks * bsize+ avail := st.Bavail * bsize+ if avail > total {+ // Should never happen on ext4, but guard against underflow if it does.+ return 0, total+ }+ used = total - avail+ return used, total+}+// readMemInfo parses /proc/meminfo for MemTotal and MemAvailable.func readMemInfo() (total, available uint64) {f, err := os.Open("/proc/meminfo")diff --git a/internal/qemu/manager.go b/internal/qemu/manager.goindex 1197782f..4e5293a4 100644--- a/internal/qemu/manager.go+++ b/internal/qemu/manager.go@@ -28,54 +28,152 @@ import ("google.golang.org/grpc/status")+// ErrAgentUnresponsive is returned by quiesceAndCloseAgent when the in-VM agent+// is unreachable. Callers must not proceed to savevm when this fires: capturing+// a snapshot of a guest with un-synced page cache and pending EXT4 journal+// entries produces a qcow2 that won't mount on next cold-boot (inode #2+// metadata-checksum failure → kernel panic loop). Surface a clean error to the+// API caller instead of silently corrupting the rootfs.+var ErrAgentUnresponsive = fmt.Errorf("guest agent unresponsive, refusing to capture potentially-inconsistent snapshot")++// ErrRootfsCritical is returned when the guest's rootfs (/dev/vda) is so full+// that destructive operations could leave it in a corrupted state. dpkg/apt+// mid-rename of system files plus an ENOSPC trip plus a savevm is the path+// that causes EXT4 metadata checksum failure on next cold-mount. Refuse the+// op early; let the caller / customer free space first.+var ErrRootfsCritical = fmt.Errorf("rootfs disk usage too high — refusing destructive operation to prevent corruption")++const (+ // rootfsRefuseThresholdPct: above this, refuse destructive operations.+ rootfsRefuseThresholdPct = 95+ // rootfsWarnThresholdPct: above this, log a warning on the next destructive+ // op so the customer sees it surface in their logs / our telemetry.+ rootfsWarnThresholdPct = 85+)+// prepareAgentForHibernate synchronously syncs the guest filesystems and quiesces-// the virtio-serial listener. Returns when the guest is fully prepared — no sleep-// needed afterward.+// the virtio-serial listener. Returns nil when the guest is fully prepared — no+// sleep needed afterward.+//+// On transport-class errors (Unavailable, Canceled, EOF, "client connection is+// closing") the RPC is retried once after a Redial — matching the pattern used+// by SyncFS / Exec / patchGuestNetwork elsewhere in this file. This handles+// the common transient where the gRPC channel is mid-recycle (e.g. right after+// a heavy Exec just completed). Only after redial+retry also fails do we+// surface ErrAgentUnresponsive.//-// On agents that don't implement the PrepareHibernate RPC (older builds), falls-// back to the legacy Exec("sync; kill -USR1 1") path with a 1s sleep.-func prepareAgentForHibernate(ctx context.Context, agent *AgentClient) {+// An Unimplemented response from PrepareHibernate (older agent builds) is not+// itself a failure — the legacy Exec("sync; kill -USR1 1") fallback is what+// counts. ErrAgentUnresponsive (wrapped) is returned only when neither the+// modern path nor the fallback succeeds, even after redial.+func prepareAgentForHibernate(ctx context.Context, agent *AgentClient) error {if agent == nil {- return+ return nil+ }++ prepareOnce := func() error {+ rpcCtx, cancel := context.WithTimeout(ctx, 10*time.Second)+ defer cancel()+ _, err := agent.PrepareHibernate(rpcCtx, &pb.PrepareHibernateRequest{})+ return err+ }+ err := prepareOnce()+ if err != nil && IsTransportError(err) {+ log.Printf("qemu: PrepareHibernate transport error (%v), redialing", err)+ if rdErr := agent.Redial(); rdErr == nil {+ err = prepareOnce()+ } else {+ log.Printf("qemu: PrepareHibernate redial failed: %v (orig: %v)", rdErr, err)+ }}- rpcCtx, cancel := context.WithTimeout(ctx, 10*time.Second)- defer cancel()- _, err := agent.PrepareHibernate(rpcCtx, &pb.PrepareHibernateRequest{})if err == nil {- return+ return nil}+if st, ok := status.FromError(err); !ok || st.Code() != codes.Unimplemented {log.Printf("qemu: PrepareHibernate RPC failed: %v (falling back to legacy path)", err)}- // Fallback for older agents: sync + SIGUSR1 + sleep.- execCtx, cancel2 := context.WithTimeout(ctx, 10*time.Second)- defer cancel2()- _, _ = agent.Exec(execCtx, &pb.ExecRequest{- Command: "/bin/sh",- Args: []string{"-c", "sync; blockdev --flushbufs /dev/vda 2>/dev/null; blockdev --flushbufs /dev/vdb 2>/dev/null; sync; kill -USR1 1"},- RunAsRoot: true,- })++ execOnce := func() error {+ execCtx, cancel := context.WithTimeout(ctx, 10*time.Second)+ defer cancel()+ _, e := agent.Exec(execCtx, &pb.ExecRequest{+ Command: "/bin/sh",+ Args: []string{"-c", "sync; blockdev --flushbufs /dev/vda 2>/dev/null; blockdev --flushbufs /dev/vdb 2>/dev/null; sync; kill -USR1 1"},+ RunAsRoot: true,+ })+ return e+ }+ fallbackErr := execOnce()+ if fallbackErr != nil && IsTransportError(fallbackErr) {+ log.Printf("qemu: prepareHibernate fallback Exec transport error (%v), redialing", fallbackErr)+ if rdErr := agent.Redial(); rdErr == nil {+ fallbackErr = execOnce()+ } else {+ log.Printf("qemu: prepareHibernate fallback redial failed: %v", rdErr)+ }+ }+ if fallbackErr != nil {+ return fmt.Errorf("%w: PrepareHibernate=%v, fallback Exec=%v", ErrAgentUnresponsive, err, fallbackErr)+ }time.Sleep(1 * time.Second)+ return nil+}++// checkRootfsPressure polls the in-guest agent for filesystem usage and+// returns ErrRootfsCritical if rootfs use% is at or above the refuse threshold.+// Best-effort: returns nil on agent unreachable / older agent that doesn't+// fill the new fields (RootfsTotalBytes==0). In those cases the caller falls+// back to the pre-existing behavior — backward compatible for long-lived+// sandboxes whose in-guest agent predates this change.+//+// Logs a warning when use% crosses rootfsWarnThresholdPct so customers see+// the early signal in their logs even when the op is allowed to proceed.+func (m *Manager) checkRootfsPressure(ctx context.Context, vm *VMInstance) error {+ if vm == nil || vm.agent == nil {+ return nil+ }+ statsCtx, cancel := context.WithTimeout(ctx, 5*time.Second)+ defer cancel()+ resp, err := vm.agent.Stats(statsCtx)+ if err != nil || resp == nil || resp.RootfsTotalBytes == 0 {+ return nil+ }+ pct := int(resp.RootfsUsedBytes * 100 / resp.RootfsTotalBytes)+ if pct >= rootfsRefuseThresholdPct {+ return fmt.Errorf("%w: rootfs at %d%% (refuse threshold %d%%) — free space and retry, or kill and respawn from a checkpoint", ErrRootfsCritical, pct, rootfsRefuseThresholdPct)+ }+ if pct >= rootfsWarnThresholdPct {+ log.Printf("qemu: %s: rootfs at %d%% — destructive operations will be refused at %d%%", vm.ID, pct, rootfsRefuseThresholdPct)+ }+ return nil}// quiesceAndCloseAgent prepares the agent for hibernate, closes the host-side// gRPC client connection, and waits 200ms for the guest's gRPC server to-// process the EOF and re-enter its Accept poll loop. After this returns it is-// safe for the caller to call savevm — the captured snapshot will not have a-// stale virtioSerialConn whose buffered HTTP/2 framer state could corrupt the-// next host's gRPC handshake on fork/restore.+// process the EOF and re-enter its Accept poll loop. After this returns nil it+// is safe for the caller to call savevm — the captured snapshot will not have+// a stale virtioSerialConn whose buffered HTTP/2 framer state could corrupt the+// next host's gRPC handshake on fork/restore, AND the guest filesystem state is+// known-quiesced.//// The 200ms is empirically sufficient for the guest virtio-serial driver to// surface EOF on /dev/virtio-ports/agent → for the gRPC server's Read goroutine// to drop its conn → for onClose to run (active=false). Without this wait the// snapshot can land mid-tear-down and the bug returns.-func quiesceAndCloseAgent(ctx context.Context, agent *AgentClient) {+//+// Returns ErrAgentUnresponsive (wrapped) when the agent cannot be reached for+// the prep step. Callers must abort their savevm path on this error.+func quiesceAndCloseAgent(ctx context.Context, agent *AgentClient) error {if agent == nil {- return+ return nil+ }+ if err := prepareAgentForHibernate(ctx, agent); err != nil {+ return err}- prepareAgentForHibernate(ctx, agent)_ = agent.Close()time.Sleep(200 * time.Millisecond)+ return nil}// Compile-time check that Manager implements sandbox.Manager.@@ -379,6 +477,39 @@ func (m *Manager) reinstallProxyCA(ctx context.Context, sandboxID string, agentlog.Printf("qemu: %s: reinstalled proxy CA on guest", sandboxID)}+// setupAptCacheBindMount redirects /var/cache/apt/archives onto the workspace+// disk via bind-mount, so apt's package-download traffic (commonly 1-3 GB+// during a base build) doesn't compete with the OS for rootfs space.+//+// Idempotent: mountpoint -q short-circuits when the bind is already in place,+// so re-applying on every wake/migrate/golden-create costs nothing. Lives in+// the kernel mount table only — does NOT modify guest /etc/fstab — so it+// re-runs on every resume through this hook. Best-effort: failure is logged+// but doesn't fail the handoff (apt-cache stays on rootfs as before).+//+// Called from: golden-create (inline with the workspace mount block), wake,+// migration. All three paths converge on a guest with /home/sandbox already+// mounted on /dev/vdb.+func (m *Manager) setupAptCacheBindMount(ctx context.Context, sandboxID string, agent *AgentClient) {+ if agent == nil {+ return+ }+ execCtx, cancel := context.WithTimeout(ctx, 5*time.Second)+ defer cancel()+ _, err := agent.Exec(execCtx, &pb.ExecRequest{+ Command: "/bin/sh",+ Args: []string{"-c", strings.Join([]string{+ "mkdir -p /home/sandbox/.osb-apt-cache /var/cache/apt/archives",+ "mountpoint -q /var/cache/apt/archives || mount --bind /home/sandbox/.osb-apt-cache /var/cache/apt/archives",+ }, " && ")},+ RunAsRoot: true,+ })+ if err != nil {+ log.Printf("qemu: %s: apt-cache bind-mount failed: %v (apt cache will live on rootfs)", sandboxID, err)+ return+ }+}+// PrepareGoldenSnapshot boots a temporary VM, waits for the agent, then// hibernates it to create a reusable snapshot. Subsequent Create() calls// restore from this snapshot instead of cold-booting, cutting start time@@ -980,6 +1111,14 @@ func (m *Manager) createFromGolden(ctx context.Context, cfg types.SandboxConfig,// golden workspace. The new sandbox has a DIFFERENT workspace qcow2 on the same// virtio-blk device. Without dropping caches, the kernel uses stale superblock/// journal data → ext4 checksum errors ("Bad message").+ //+ // After /home/sandbox is mounted, redirect /var/cache/apt/archives onto+ // workspace via bind-mount. apt downloads packages there before installing+ // (commonly 1-3 GB during a base build); without the redirect, that traffic+ // lands on the 4 GiB rootfs and can fill it. The bind-mount is idempotent+ // (mountpoint -q short-circuits) and survives only in the running kernel —+ // re-applied on every wake/spawn through this same hook. Failure to bind-+ // mount is non-fatal (apt-cache stays on rootfs, status quo).mountCtx, mountCancel := context.WithTimeout(context.Background(), 10*time.Second)_, mountErr := agentClient.Exec(mountCtx, &pb.ExecRequest{Command: "/bin/sh",@@ -989,6 +1128,8 @@ func (m *Manager) createFromGolden(ctx context.Context, cfg types.SandboxConfig,"mount /dev/vdb /home/sandbox 2>/dev/null || true","resize2fs /dev/vdb 2>/dev/null || true","chown 1000:1000 /home/sandbox",+ "mkdir -p /home/sandbox/.osb-apt-cache /var/cache/apt/archives",+ "mountpoint -q /var/cache/apt/archives || mount --bind /home/sandbox/.osb-apt-cache /var/cache/apt/archives 2>/dev/null || true",}, " && ")},RunAsRoot: true,})@@ -2310,6 +2451,14 @@ func (m *Manager) Hibernate(ctx context.Context, sandboxID string, checkpointStoreturn nil, err}+ // Refuse hibernate if rootfs is critically full. dpkg/apt mid-rename + an+ // unsynced page cache + a savevm produces qcow2 EXT4 metadata corruption+ // that won't cold-mount on the next wake. Cheap pre-flight check; the+ // customer should free space (or kill+respawn from a checkpoint) instead.+ if err := m.checkRootfsPressure(ctx, vm); err != nil {+ return nil, err+ }+if !vm.opMu.TryLock() {return nil, fmt.Errorf("another operation is in progress on sandbox %s — try again shortly", sandboxID)}@@ -2391,6 +2540,12 @@ func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointIDreturn "", "", 0, err}+ // Refuse if rootfs is critically full — same corruption risk as hibernate+ // (dpkg/apt mid-rename + savevm = qcow2 EXT4 metadata broken on next mount).+ if err := m.checkRootfsPressure(ctx, vm); err != nil {+ return "", "", 0, err+ }+// Reject if another destructive operation (checkpoint, hibernate, restore) is in progress.// Without this, rapid-fire checkpoints queue up and the agent gets into a bad state// from overlapping SIGUSR1/reconnect cycles.@@ -2408,8 +2563,15 @@ func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointID// Sync filesystem, quiesce virtio-serial, close host conn, and WAIT for// the guest to process EOF before savevm. Critical for clean snapshot// state — see quiesceAndCloseAgent for the protocol details.+ //+ // If quiesce fails (agent unresponsive), refuse the checkpoint: a savevm+ // against an un-synced guest captures inconsistent qcow2 metadata that+ // becomes unbootable on next cold-mount. See ErrAgentUnresponsive.if vm.agent != nil {- quiesceAndCloseAgent(ctx, vm.agent)+ if err := quiesceAndCloseAgent(ctx, vm.agent); err != nil {+ log.Printf("qemu: CreateCheckpoint %s/%s: refusing savevm — %v", sandboxID, checkpointID, err)+ return "", "", 0, fmt.Errorf("checkpoint %s: %w", sandboxID, err)+ }vm.agent = nil}@@ -2440,10 +2602,24 @@ func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointID// savevm pauses the VM, writes memory+device+disk-delta into every qcow2// drive as an internal snapshot, then resumes. The qcow2 files now carry// the full VM state; no external memory file is needed.+ //+ // Explicit Stop() before savevm halts vCPUs to close the small race where+ // in-flight virtio-blk writes can land in the qcow2 between the agent's+ // `sync` (above) and the start of savevm. We Cont() unconditionally after+ // savevm completes (success or failure) — the sandbox is supposed to keep+ // running post-checkpoint, so we must not leave it in stopped state.snapshotName := "cp-" + checkpointID- if err := vm.qmp.SaveVM(snapshotName); err != nil {+ if stopErr := vm.qmp.Stop(); stopErr != nil {+ os.RemoveAll(stagingDir)+ return "", "", 0, fmt.Errorf("qmp stop before savevm: %w", stopErr)+ }+ saveErr := vm.qmp.SaveVM(snapshotName)+ if contErr := vm.qmp.Cont(); contErr != nil {+ log.Printf("qemu: CreateCheckpoint %s/%s: failed to resume VM after savevm: %v", sandboxID, checkpointID, contErr)+ }+ if saveErr != nil {os.RemoveAll(stagingDir)- return "", "", 0, fmt.Errorf("savevm: %w", err)+ return "", "", 0, fmt.Errorf("savevm: %w", saveErr)}log.Printf("qemu: CreateCheckpoint %s/%s: savevm complete (%dms)", sandboxID, checkpointID, time.Since(t0).Milliseconds())diff --git a/internal/qemu/migration.go b/internal/qemu/migration.goindex 3bc322bc..afb74313 100644--- a/internal/qemu/migration.go+++ b/internal/qemu/migration.go@@ -590,6 +590,12 @@ func (m *Manager) CompleteIncomingMigration(ctx context.Context, sandboxID strin// new content equals the old, so this is a no-op write.m.reinstallProxyCA(ctx, sandboxID, agentClient)+ // Re-apply the apt-cache bind-mount on the destination. Migration carries+ // the loadvm-restored mount table, so this is normally a no-op (mountpoint+ // -q short-circuits), but it covers sandboxes that were migrated before+ // this fix shipped and never had the bind set up.+ m.setupAptCacheBindMount(ctx, sandboxID, agentClient)+// Sync VM memory tracking with actual QEMU state.// After migration, the QEMU process has the source's virtio-mem hotplugged memory,// but the Go struct still has the prep values (virtioMemRequestedMB=0, MemoryMB=baseMem).diff --git a/internal/qemu/snapshot.go b/internal/qemu/snapshot.goindex e2e0b191..2bab77e1 100644--- a/internal/qemu/snapshot.go+++ b/internal/qemu/snapshot.go@@ -69,8 +69,17 @@ func (m *Manager) doHibernate(ctx context.Context, vm *VMInstance, checkpointSto// Step 1: Sync filesystems, quiesce agent, close host conn, and WAIT for// the guest to process EOF before savevm. See quiesceAndCloseAgent.// Don't unmount /workspace — open FDs prevent clean unmount and cause ext4 corruption.+ //+ // If quiesce fails (agent unresponsive), DO NOT proceed to savevm: the+ // captured qcow2 would carry un-synced page cache + pending EXT4 journal+ // entries and become unbootable on the next cold-mount (inode #2 checksum+ // failure → kernel panic loop). Bubble the error up so the API caller+ // gets a clear refusal instead of a silently-corrupted sandbox.if vm.agent != nil {- quiesceAndCloseAgent(ctx, vm.agent)+ if err := quiesceAndCloseAgent(ctx, vm.agent); err != nil {+ log.Printf("qemu: hibernate %s: refusing savevm — %v", vm.ID, err)+ return nil, fmt.Errorf("hibernate %s: %w", vm.ID, err)+ }vm.agent = nil}log.Printf("qemu: hibernate %s: guest sync + unmount done (%dms)", vm.ID, time.Since(t0).Milliseconds())@@ -78,12 +87,23 @@ func (m *Manager) doHibernate(ctx context.Context, vm *VMInstance, checkpointSto// Step 2: savevm — saves memory + device state INTO the qcow2 files.// Same mechanism as CreateCheckpoint. On wake, loadvm restores everything// including running processes, open files, and memory contents.+ //+ // Explicit Stop() before savevm: although savevm internally pauses and+ // resumes the VM, the explicit pause closes the small race where in-flight+ // virtio-blk writes from the guest can still land in the qcow2 between+ // the agent's `sync` and the start of savevm. Halting vCPUs first makes+ // the captured state strictly post-sync. doHibernate proceeds straight+ // to Quit on success, so leaving the VM in stopped state is fine; only+ // the failure path resumes (so we don't leak a wedged paused VM).if vm.qmp == nil {return nil, fmt.Errorf("no QMP client for VM %s", vm.ID)}snapshotName := "hibernate"+ if stopErr := vm.qmp.Stop(); stopErr != nil {+ return nil, fmt.Errorf("qmp stop before savevm: %w", stopErr)+ }if err := vm.qmp.SaveVM(snapshotName); err != nil {- // Try to resume VM so it's not left in a broken paused state+ // Resume so we don't leave the VM wedged paused on the error path.if contErr := vm.qmp.Cont(); contErr != nil {log.Printf("qemu: hibernate %s: failed to resume after savevm failure: %v", vm.ID, contErr)}@@ -552,6 +572,12 @@ func (m *Manager) doWake(ctx context.Context, sandboxID, checkpointKey string, c// worker's proxy presents. Idempotent on same-worker wake.m.reinstallProxyCA(context.Background(), sandboxID, agentClient)+ // Re-apply the apt-cache bind-mount. Idempotent: no-op if already in place+ // (e.g., same-worker wake where the loadvm-restored mount table preserved+ // the bind). On cross-worker wake or sandboxes that pre-date this fix,+ // this is the first chance to set it up.+ m.setupAptCacheBindMount(context.Background(), sandboxID, agentClient)+log.Printf("qemu: wake %s: golden restore complete (port=%d, tap=%s)",sandboxID, hostPort, netCfg.TAPName)diff --git a/proto/agent/agent.pb.go b/proto/agent/agent.pb.goindex 15c37d4c..9e3d004d 100644--- a/proto/agent/agent.pb.go+++ b/proto/agent/agent.pb.go@@ -1,7 +1,7 @@// Code generated by protoc-gen-go. DO NOT EDIT.// versions:// protoc-gen-go v1.36.11-// protoc v5.29.3+// protoc v7.34.0// source: proto/agent/agent.protopackage agent@@ -1268,15 +1268,24 @@ func (*StatsRequest) Descriptor() ([]byte, []int) {}type StatsResponse struct {- state protoimpl.MessageState `protogen:"open.v1"`- CpuPercent float64 `protobuf:"fixed64,1,opt,name=cpu_percent,json=cpuPercent,proto3" json:"cpu_percent,omitempty"`- MemUsage uint64 `protobuf:"varint,2,opt,name=mem_usage,json=memUsage,proto3" json:"mem_usage,omitempty"` // bytes- MemLimit uint64 `protobuf:"varint,3,opt,name=mem_limit,json=memLimit,proto3" json:"mem_limit,omitempty"` // bytes- NetInput uint64 `protobuf:"varint,4,opt,name=net_input,json=netInput,proto3" json:"net_input,omitempty"` // bytes- NetOutput uint64 `protobuf:"varint,5,opt,name=net_output,json=netOutput,proto3" json:"net_output,omitempty"` // bytes- Pids int32 `protobuf:"varint,6,opt,name=pids,proto3" json:"pids,omitempty"`- unknownFields protoimpl.UnknownFields- sizeCache protoimpl.SizeCache+ state protoimpl.MessageState `protogen:"open.v1"`+ CpuPercent float64 `protobuf:"fixed64,1,opt,name=cpu_percent,json=cpuPercent,proto3" json:"cpu_percent,omitempty"`+ MemUsage uint64 `protobuf:"varint,2,opt,name=mem_usage,json=memUsage,proto3" json:"mem_usage,omitempty"` // bytes+ MemLimit uint64 `protobuf:"varint,3,opt,name=mem_limit,json=memLimit,proto3" json:"mem_limit,omitempty"` // bytes+ NetInput uint64 `protobuf:"varint,4,opt,name=net_input,json=netInput,proto3" json:"net_input,omitempty"` // bytes+ NetOutput uint64 `protobuf:"varint,5,opt,name=net_output,json=netOutput,proto3" json:"net_output,omitempty"` // bytes+ Pids int32 `protobuf:"varint,6,opt,name=pids,proto3" json:"pids,omitempty"`+ // Disk usage from statvfs() inside the guest. Used by the worker to refuse+ // destructive ops (hibernate, checkpoint) before the rootfs runs out of+ // space and corrupts. Older agents that don't fill these fields report 0,+ // which the worker treats as "unknown" (no pressure gate, falls back to+ // existing behavior).+ RootfsUsedBytes uint64 `protobuf:"varint,7,opt,name=rootfs_used_bytes,json=rootfsUsedBytes,proto3" json:"rootfs_used_bytes,omitempty"`+ RootfsTotalBytes uint64 `protobuf:"varint,8,opt,name=rootfs_total_bytes,json=rootfsTotalBytes,proto3" json:"rootfs_total_bytes,omitempty"`+ WorkspaceUsedBytes uint64 `protobuf:"varint,9,opt,name=workspace_used_bytes,json=workspaceUsedBytes,proto3" json:"workspace_used_bytes,omitempty"`+ WorkspaceTotalBytes uint64 `protobuf:"varint,10,opt,name=workspace_total_bytes,json=workspaceTotalBytes,proto3" json:"workspace_total_bytes,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache}func (x *StatsResponse) Reset() {@@ -1351,6 +1360,34 @@ func (x *StatsResponse) GetPids() int32 {return 0}+func (x *StatsResponse) GetRootfsUsedBytes() uint64 {+ if x != nil {+ return x.RootfsUsedBytes+ }+ return 0+}++func (x *StatsResponse) GetRootfsTotalBytes() uint64 {+ if x != nil {+ return x.RootfsTotalBytes+ }+ return 0+}++func (x *StatsResponse) GetWorkspaceUsedBytes() uint64 {+ if x != nil {+ return x.WorkspaceUsedBytes+ }+ return 0+}++func (x *StatsResponse) GetWorkspaceTotalBytes() uint64 {+ if x != nil {+ return x.WorkspaceTotalBytes+ }+ return 0+}+type PingRequest struct {state protoimpl.MessageState `protogen:"open.v1"`unknownFields protoimpl.UnknownFields@@ -3113,7 +3150,7 @@ const file_proto_agent_agent_proto_rawDesc = "" +"\x04mode\x18\x04 \x01(\tR\x04mode\x12\x19\n" +"\bmod_time\x18\x05 \x01(\tR\amodTime\x12\x12\n" +"\x04path\x18\x06 \x01(\tR\x04path\"\x0e\n" +- "\fStatsRequest\"\xba\x01\n" ++ "\fStatsRequest\"\xfa\x02\n" +"\rStatsResponse\x12\x1f\n" +"\vcpu_percent\x18\x01 \x01(\x01R\n" +"cpuPercent\x12\x1b\n" +@@ -3122,7 +3159,12 @@ const file_proto_agent_agent_proto_rawDesc = "" +"\tnet_input\x18\x04 \x01(\x04R\bnetInput\x12\x1d\n" +"\n" +"net_output\x18\x05 \x01(\x04R\tnetOutput\x12\x12\n" +- "\x04pids\x18\x06 \x01(\x05R\x04pids\"\r\n" ++ "\x04pids\x18\x06 \x01(\x05R\x04pids\x12*\n" ++ "\x11rootfs_used_bytes\x18\a \x01(\x04R\x0frootfsUsedBytes\x12,\n" ++ "\x12rootfs_total_bytes\x18\b \x01(\x04R\x10rootfsTotalBytes\x120\n" ++ "\x14workspace_used_bytes\x18\t \x01(\x04R\x12workspaceUsedBytes\x122\n" ++ "\x15workspace_total_bytes\x18\n" ++ " \x01(\x04R\x13workspaceTotalBytes\"\r\n" +"\vPingRequest\"O\n" +"\fPingResponse\x12\x18\n" +"\aversion\x18\x01 \x01(\tR\aversion\x12%\n" +diff --git a/proto/agent/agent.proto b/proto/agent/agent.protoindex 99130d67..ef52e45c 100644--- a/proto/agent/agent.proto+++ b/proto/agent/agent.proto@@ -234,6 +234,15 @@ message StatsResponse {uint64 net_input = 4; // bytesuint64 net_output = 5; // bytesint32 pids = 6;+ // Disk usage from statvfs() inside the guest. Used by the worker to refuse+ // destructive ops (hibernate, checkpoint) before the rootfs runs out of+ // space and corrupts. Older agents that don't fill these fields report 0,+ // which the worker treats as "unknown" (no pressure gate, falls back to+ // existing behavior).+ uint64 rootfs_used_bytes = 7;+ uint64 rootfs_total_bytes = 8;+ uint64 workspace_used_bytes = 9;+ uint64 workspace_total_bytes = 10;}// --- Ping ---diff --git a/proto/agent/agent_grpc.pb.go b/proto/agent/agent_grpc.pb.goindex a5396637..ae83f1f0 100644--- a/proto/agent/agent_grpc.pb.go+++ b/proto/agent/agent_grpc.pb.go@@ -1,7 +1,7 @@// Code generated by protoc-gen-go-grpc. DO NOT EDIT.// versions:// - protoc-gen-go-grpc v1.6.1-// - protoc v5.29.3+// - protoc v7.34.0// source: proto/agent/agent.protopackage agentdiff --git a/scripts/qemu-tests/40-corruption-guards.sh b/scripts/qemu-tests/40-corruption-guards.shnew file mode 100755index 00000000..4760d0a6--- /dev/null+++ b/scripts/qemu-tests/40-corruption-guards.sh@@ -0,0 +1,355 @@+#!/usr/bin/env bash+# 40-corruption-guards.sh — Stress the four hibernate/checkpoint corruption+# guards landed in fix/savevm-corruption-guards. Each section asserts the+# guard actually fires under the conditions it's designed to catch.+#+# Sections (set SECTION=<n> to run only one):+# 1. Hibernate refusal when the in-guest agent is unresponsive.+# Suspend the agent with SIGSTOP, issue Hibernate, expect a clean error+# (NOT "guest sync + unmount done (0ms)" followed by a savevm). The+# rootfs.qcow2 mtime on the worker must not change during the attempt.+#+# 2. Checkpoint+fork under sustained I/O.+# Regression test for the explicit Stop/SaveVM/Cont sequence: a busy+# writer thread must not produce a corrupt qcow2 when checkpointed,+# and the forked child must boot cleanly with the checkpointed file+# contents intact.+#+# 3. Apt-cache bind-mount lifecycle.+# Fresh sandbox: /var/cache/apt/archives must be a bind-mount onto+# /home/sandbox/.osb-apt-cache. Across hibernate+wake the bind-mount+# must still be in place. apt-get update writes must land on /dev/vdb,+# not /dev/vda.+#+# 4. Disk-pressure refusal.+# Fill rootfs to >=95%, attempt Hibernate, expect ErrRootfsCritical+# with the actual % surfaced. Free space below threshold and confirm+# the next Hibernate succeeds.+#+# Required env:+# OPENSANDBOX_API_URL (e.g. https://dev.opencomputer.dev)+# OPENSANDBOX_API_KEY+# SSH_KEY path to a key with worker access, optional but+# required for the rootfs.qcow2 mtime assertion in+# section 1 (skipped without it)+#+# Optional:+# ITERATIONS=<n> repeat each section's main loop n times (default 3)+# SECTION=<1|2|3|4> run only one section+# FILL_PCT=<n> section 4 target % (default 96)++set +u+source "$(dirname "$0")/common.sh"++ITERATIONS="${ITERATIONS:-3}"+SECTION="${SECTION:-all}"+FILL_PCT="${FILL_PCT:-96}"+TIMEOUT=180+SANDBOXES=()+PASS=0+FAIL=0+SKIP=0++cleanup() {+ set +u+ for sb in "${SANDBOXES[@]+"${SANDBOXES[@]}"}"; do+ [ -n "$sb" ] && destroy_sandbox "$sb" 2>/dev/null+ done+ set -u+}+trap cleanup EXIT INT TERM++# Helper: parse error message + status from a JSON error response.+err_msg() { python3 -c "import sys,json; d=json.load(sys.stdin); print(d.get('error') or d.get('message') or d)" 2>/dev/null; }++# Helper: read worker-side mtime of a sandbox's rootfs.qcow2 over SSH.+# Returns "skip" if SSH_KEY isn't set or worker host can't be inferred.+worker_rootfs_mtime() {+ local sb="$1"+ [ -z "${SSH_KEY:-}" ] && { echo skip; return; }+ local worker_id worker_host path+ worker_id=$(api "$API_URL/api/sandboxes/$sb" 2>/dev/null | python3 -c "import sys,json; print(json.load(sys.stdin).get('worker_id',''))" 2>/dev/null)+ [ -z "$worker_id" ] && { echo skip; return; }+ # Workers expose their grpc_addr in the workers list — strip port.+ worker_host=$(api "$API_URL/api/workers" 2>/dev/null | python3 -c "+import sys, json+target = '$worker_id'+for w in json.load(sys.stdin):+ if w.get('worker_id') == target:+ addr = w.get('grpc_addr') or w.get('http_addr') or ''+ print(addr.split(':')[0])+ break+" 2>/dev/null)+ [ -z "$worker_host" ] && { echo skip; return; }+ path="/data/sandboxes/sandboxes/$sb/rootfs.qcow2"+ ssh -o StrictHostKeyChecking=no -o ConnectTimeout=5 -i "$SSH_KEY" \+ "azureuser@$worker_host" "stat -c %Y $path 2>/dev/null" 2>/dev/null || echo skip+}++# Helper: freeze the entire VM from the host so the in-guest agent stops+# responding to gRPC. We can't SIGSTOP the agent directly because it runs as+# PID 1 (SIGNAL_UNKILLABLE — the kernel rejects user-space SIGSTOP to init).+# Instead, find the QEMU process for this sandbox on the host and SIGSTOP it.+# Restoring is symmetric (SIGCONT). Requires SSH access to the host (set+# DEV_VM_HOST + SSH_KEY); skips the section if unavailable.+#+# Action: stop|cont+freeze_guest_agent() {+ local sb="$1"+ local action="${2:-stop}"+ local sig="STOP"+ [ "$action" = "cont" ] && sig="CONT"+ if [ -z "${DEV_VM_HOST:-}" ] || [ -z "${SSH_KEY:-}" ]; then+ return 2 # not configured — caller should skip+ fi+ ssh -o StrictHostKeyChecking=no -o ConnectTimeout=5 -i "$SSH_KEY" \+ "${DEV_VM_USER:-azureuser}@$DEV_VM_HOST" \+ "sudo pkill -$sig -f 'qemu.*$sb' 2>/dev/null; sleep 0.5; sudo pgrep -f 'qemu.*$sb' >/dev/null && echo found || echo nopid" 2>/dev/null+}++# ── Section 1: Hibernate refusal on unresponsive agent ────────────────+section1() {+ h "Section 1: Hibernate refusal when guest agent is unresponsive ($ITERATIONS iters)"+ if [ -z "${DEV_VM_HOST:-}" ] || [ -z "${SSH_KEY:-}" ]; then+ skip "Section 1 needs DEV_VM_HOST + SSH_KEY for host-side QEMU SIGSTOP (PID-1 freeze inside guest is blocked by SIGNAL_UNKILLABLE)."+ return+ fi+ for i in $(seq 1 "$ITERATIONS"); do+ SB=$(create_sandbox)+ SANDBOXES+=("$SB")++ # Wait for the QEMU process to be fully up and the agent registered.+ sleep 4++ # SIGSTOP the QEMU process for this sandbox on the host. Freezes the+ # whole VM, including the agent's gRPC server. The host's prepare-+ # hibernate RPC will hit its 10s timeout (PrepareHibernate), then the+ # 10s fallback Exec timeout, then bubble up ErrAgentUnresponsive.+ local freeze_result+ freeze_result=$(freeze_guest_agent "$SB" stop)+ if ! echo "$freeze_result" | grep -q found; then+ skip "iter $i: could not locate QEMU process for $SB on host"+ destroy_sandbox "$SB"+ continue+ fi++ local resp http_status+ resp=$(api -X POST -w '\nHTTP_STATUS:%{http_code}\n' "$API_URL/api/sandboxes/$SB/hibernate" 2>/dev/null)+ http_status=$(echo "$resp" | grep '^HTTP_STATUS:' | cut -d: -f2)++ # ALWAYS resume the QEMU process — even on test failure — so we don't+ # leak frozen VMs in the dev environment.+ freeze_guest_agent "$SB" cont >/dev/null 2>&1++ if [ "$http_status" = "200" ] || [ "$http_status" = "204" ]; then+ fail "iter $i: Hibernate succeeded against frozen VM (expected refusal)"+ elif echo "$resp" | grep -qi "agent unresponsive\|ErrAgentUnresponsive\|guest agent"; then+ pass "iter $i: Hibernate refused with agent-unresponsive error (HTTP $http_status)"+ else+ fail "iter $i: Hibernate failed (HTTP $http_status) but error did not mention agent unresponsiveness"+ echo "$resp" | tail -3 | sed 's/^/ /'+ fi++ destroy_sandbox "$SB"+ done+}++# ── Section 2: Checkpoint+fork under sustained I/O ────────────────────+section2() {+ h "Section 2: Checkpoint+fork under heavy I/O ($ITERATIONS iters)"+ for i in $(seq 1 "$ITERATIONS"); do+ SB=$(create_sandbox)+ SANDBOXES+=("$SB")++ # Start a background writer producing churn into rootfs+workspace.+ # 50 MB/s into rootfs for 30s plus a tight rename loop on workspace.+ exec_run "$SB" "bash" "-c" "+ (dd if=/dev/urandom of=/tmp/churn bs=1M count=200 oflag=direct 2>/dev/null) &+ (for j in \$(seq 1 200); do echo j-\$j > /home/sandbox/.churn.\$j; mv /home/sandbox/.churn.\$j /home/sandbox/.churn-final.\$j; done) &+ sleep 0.5; echo writers-launched+ " >/dev/null++ # Drop a deterministic blob whose hash we'll verify post-fork.+ local blob_hash+ exec_run "$SB" "bash" "-c" "dd if=/dev/urandom of=/home/sandbox/blob.bin bs=1M count=20 2>/dev/null && sync" >/dev/null+ blob_hash=$(exec_stdout "$SB" "bash" "-c" "sha256sum /home/sandbox/blob.bin | cut -d' ' -f1")++ # Take the checkpoint while the writers are still going. The API uses+ # capital-N "Name" on input; response field is "id" (not checkpoint_id).+ local cp_resp cp_id+ cp_resp=$(api -X POST "$API_URL/api/sandboxes/$SB/checkpoints" -d "{\"Name\":\"guard-test-$i\"}" 2>/dev/null)+ cp_id=$(echo "$cp_resp" | python3 -c "import sys,json; print(json.load(sys.stdin).get('id',''))" 2>/dev/null)+ if [ -z "$cp_id" ]; then+ fail "iter $i: checkpoint create failed: $(echo $cp_resp | err_msg)"+ destroy_sandbox "$SB"+ continue+ fi+ pass "iter $i: checkpoint $cp_id created under load"++ # Checkpoint create returns immediately with status=processing; wait+ # for it to finish before forking from it. There is no+ # GET /api/checkpoints/<id> endpoint — we list per-sandbox and filter.+ local waited=0+ local cp_status=""+ while [ "$waited" -lt 90 ]; do+ cp_status=$(CP_ID="$cp_id" api "$API_URL/api/sandboxes/$SB/checkpoints" 2>/dev/null \+ | CP_ID="$cp_id" python3 -c "import sys,json,os+target=os.environ['CP_ID']+for cp in (json.load(sys.stdin) or []):+ if cp.get('id')==target:+ print(cp.get('status','')); break" 2>/dev/null)+ [ "$cp_status" = "ready" ] && break+ [ "$cp_status" = "failed" ] && { fail "iter $i: checkpoint $cp_id failed during processing"; break; }+ sleep 2; waited=$((waited+2))+ done+ if [ "$cp_status" != "ready" ]; then+ fail "iter $i: checkpoint $cp_id never reached ready (last status=$cp_status, waited ${waited}s)"+ destroy_sandbox "$SB"+ continue+ fi++ # Source sandbox should still be running afterward (Cont was issued).+ local status+ status=$(api "$API_URL/api/sandboxes/$SB" 2>/dev/null | python3 -c "import sys,json; print(json.load(sys.stdin).get('status',''))" 2>/dev/null)+ if [ "$status" = "running" ]; then+ pass "iter $i: source sandbox still running post-checkpoint"+ else+ fail "iter $i: source sandbox status=$status after checkpoint (expected running) — Cont may have failed"+ fi++ # Fork from the checkpoint and verify blob hash matches.+ # Endpoint is POST /api/sandboxes/from-checkpoint/<id> (per router.go).+ local fork_resp fork_sb fork_hash+ fork_resp=$(api -X POST "$API_URL/api/sandboxes/from-checkpoint/$cp_id" -d '{}' 2>/dev/null)+ fork_sb=$(echo "$fork_resp" | python3 -c "import sys,json; print(json.load(sys.stdin).get('sandboxID',''))" 2>/dev/null)+ if [ -z "$fork_sb" ]; then+ fail "iter $i: fork from checkpoint failed: $(echo $fork_resp | err_msg)"+ else+ SANDBOXES+=("$fork_sb")+ sleep 3+ fork_hash=$(exec_stdout "$fork_sb" "bash" "-c" "sha256sum /home/sandbox/blob.bin | cut -d' ' -f1")+ if [ "$blob_hash" = "$fork_hash" ]; then+ pass "iter $i: fork blob.bin hash matches source"+ else+ fail "iter $i: fork blob hash MISMATCH (expected $blob_hash, got $fork_hash)"+ fi+ destroy_sandbox "$fork_sb"+ fi+ destroy_sandbox "$SB"+ done+}++# ── Section 3: Apt-cache bind-mount lifecycle ─────────────────────────+section3() {+ h "Section 3: Apt-cache bind-mount survives lifecycle events ($ITERATIONS iters)"+ for i in $(seq 1 "$ITERATIONS"); do+ SB=$(create_sandbox)+ SANDBOXES+=("$SB")++ # Fresh-spawn check.+ local mp_status+ mp_status=$(exec_exit_code "$SB" "bash" "-c" "mountpoint -q /var/cache/apt/archives")+ if [ "$mp_status" = "0" ]; then+ pass "iter $i: bind-mount in place on fresh spawn"+ else+ fail "iter $i: /var/cache/apt/archives is NOT a bind-mount on fresh spawn"+ fi++ # Verify the underlying device is /dev/vdb (workspace), not /dev/vda.+ local mount_dev+ mount_dev=$(exec_stdout "$SB" "bash" "-c" "findmnt -no SOURCE /var/cache/apt/archives 2>/dev/null | head -1")+ if [[ "$mount_dev" == *"vdb"* ]] || [[ "$mount_dev" == *"sandbox/.osb-apt-cache"* ]]; then+ pass "iter $i: bind-mount source is workspace ($mount_dev)"+ else+ fail "iter $i: bind-mount source is unexpected: $mount_dev"+ fi++ # apt-get update writes index files into /var/cache/apt — write a+ # marker file there and verify it actually lands on workspace.+ exec_run "$SB" "bash" "-c" "sudo touch /var/cache/apt/archives/.bind-test-$i" >/dev/null+ local on_workspace+ on_workspace=$(exec_stdout "$SB" "bash" "-c" "[ -f /home/sandbox/.osb-apt-cache/.bind-test-$i ] && echo yes || echo no")+ if [ "$on_workspace" = "yes" ]; then+ pass "iter $i: writes through /var/cache/apt/archives land on /home/sandbox/.osb-apt-cache"+ else+ fail "iter $i: bind-mount is not redirecting writes correctly"+ fi++ # Hibernate + wake. Bind-mount must be re-applied (or survive) on wake.+ api -X POST "$API_URL/api/sandboxes/$SB/hibernate" >/dev/null 2>&1+ sleep 5+ api -X POST "$API_URL/api/sandboxes/$SB/wake" -d '{"timeout":3600}' >/dev/null 2>&1+ sleep 5+ mp_status=$(exec_exit_code "$SB" "bash" "-c" "mountpoint -q /var/cache/apt/archives")+ if [ "$mp_status" = "0" ]; then+ pass "iter $i: bind-mount in place after hibernate+wake"+ else+ fail "iter $i: bind-mount lost after hibernate+wake"+ fi++ destroy_sandbox "$SB"+ done+}++# ── Section 4: Disk-pressure refusal ──────────────────────────────────+section4() {+ h "Section 4: Hibernate/checkpoint refused at >=95% rootfs use ($ITERATIONS iters, fill=$FILL_PCT%)"+ for i in $(seq 1 "$ITERATIONS"); do+ SB=$(create_sandbox)+ SANDBOXES+=("$SB")++ # Fill the rootfs (NOT workspace) to FILL_PCT% using dd (fallocate+ # allocates lazily on this ext4 — sparse files don't show in df). dd+ # writes zeros in 1 MiB blocks with conv=fsync so blocks are really+ # reserved. NB: must be a single line — common.sh's exec_run flattens+ # multi-line args via newline-split, which truncates a multi-line+ # bash -c body to just its first line.+ exec_run "$SB" "bash" "-c" "set -e; B=\$(stat -fc %s /); T=\$(stat -fc %b /); A=\$(stat -fc %a /); TOT=\$((B*T)); USED=\$((TOT-A*B)); TGT=\$((TOT*$FILL_PCT/100)); FILL_MB=\$(( (TGT-USED)/1024/1024 )); [ \$FILL_MB -gt 0 ] && sudo dd if=/dev/zero of=/.fill bs=1M count=\$FILL_MB conv=fsync status=none 2>&1 || true; df -h / | tail -1" >/dev/null++ local pct_used+ pct_used=$(exec_stdout "$SB" "bash" "-c" "df --output=pcent / | tail -1 | tr -dc '0-9'")+ if [ -z "$pct_used" ] || [ "$pct_used" -lt 95 ]; then+ skip "iter $i: rootfs only at ${pct_used:-?}% — fallocate may have failed; can't exercise refusal"+ destroy_sandbox "$SB"+ continue+ fi+ pass "iter $i: rootfs at $pct_used%"++ local resp http_status+ resp=$(api -X POST -w '\nHTTP_STATUS:%{http_code}\n' "$API_URL/api/sandboxes/$SB/hibernate" 2>/dev/null)+ http_status=$(echo "$resp" | grep '^HTTP_STATUS:' | cut -d: -f2)++ if [ "$http_status" = "200" ] || [ "$http_status" = "204" ]; then+ fail "iter $i: Hibernate succeeded against full rootfs at $pct_used% (expected refusal)"+ elif echo "$resp" | grep -qi "rootfs disk usage\|ErrRootfsCritical\|rootfs at"; then+ pass "iter $i: Hibernate refused with disk-pressure error"+ else+ fail "iter $i: Hibernate failed (HTTP $http_status) but error did not mention disk pressure"+ echo "$resp" | tail -3 | sed 's/^/ /'+ fi++ # Free space and confirm Hibernate now succeeds.+ exec_run "$SB" "bash" "-c" "sudo rm -f /.fill && sync" >/dev/null+ sleep 1+ resp=$(api -X POST -w '\nHTTP_STATUS:%{http_code}\n' "$API_URL/api/sandboxes/$SB/hibernate" 2>/dev/null)+ http_status=$(echo "$resp" | grep '^HTTP_STATUS:' | cut -d: -f2)+ if [ "$http_status" = "200" ] || [ "$http_status" = "204" ]; then+ pass "iter $i: Hibernate succeeded after freeing space"+ else+ fail "iter $i: Hibernate still failed after freeing space (HTTP $http_status)"+ fi+ destroy_sandbox "$SB"+ done+}++# ── Dispatch ──────────────────────────────────────────────────────────+case "$SECTION" in+ 1) section1 ;;+ 2) section2 ;;+ 3) section3 ;;+ 4) section4 ;;+ all|"") section1; section2; section3; section4 ;;+ *) echo "unknown SECTION=$SECTION (expected 1|2|3|4|all)"; exit 64 ;;+esac++summary