Skip to content

An open-source, faster Devin alternative

TypeScript

stale cache invalidation, s3 synchronous (#120)

Brian Reardon7242c253d09f
diff --git a/.github/workflows/deploy-worker.yml b/.github/workflows/deploy-worker.yml
index 727768d0..51f5c05f 100644
--- a/.github/workflows/deploy-worker.yml
+++ b/.github/workflows/deploy-worker.yml
@@ -130,33 +130,63 @@ jobs:
sudo rm -f \"\$IMAGES_DIR/default.ext4\"
sudo bash deploy/ec2/build-rootfs-docker.sh /usr/local/bin/osb-agent \"\$IMAGES_DIR\" default
- # Patch rootfs with kernel modules for virtio-mem support
+ # Ensure generic kernel + modules are installed for virtio-mem.
+ # Azure VMs ship with the azure kernel which lacks virtio_mem.
+ # The generic kernel provides it.
+ if ! ls -d /lib/modules/*-generic >/dev/null 2>&1; then
+ echo \"No generic kernel found — installing for virtio-mem support...\"
+ sudo DEBIAN_FRONTEND=noninteractive apt-get update -qq
+ sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq linux-image-generic 2>&1 | tail -3
+ fi
+
+ # Determine guest kernel version
GUEST_KVER=\"\"
if [ -f /opt/opensandbox/guest-kernel-version ]; then
GUEST_KVER=\$(cat /opt/opensandbox/guest-kernel-version)
elif ls -d /lib/modules/*-generic >/dev/null 2>&1; then
GUEST_KVER=\$(ls -d /lib/modules/*-generic | sort -V | tail -1 | xargs basename)
fi
- if [ -n \"\$GUEST_KVER\" ] && [ -d \"/lib/modules/\$GUEST_KVER\" ]; then
- echo \"Patching rootfs with kernel modules for \$GUEST_KVER...\"
- MNTDIR=\$(mktemp -d)
- sudo mount -o loop \"\$IMAGES_DIR/default.ext4\" \"\$MNTDIR\"
- sudo rm -rf \"\$MNTDIR/lib/modules\"/*
- sudo cp -a \"/lib/modules/\$GUEST_KVER\" \"\$MNTDIR/lib/modules/\"
- sudo depmod -b \"\$MNTDIR\" \"\$GUEST_KVER\" 2>/dev/null || true
- # Create insmod symlink (busybox applet) if missing
- if [ -f \"\$MNTDIR/bin/busybox\" ] && [ ! -e \"\$MNTDIR/sbin/insmod\" ]; then
- sudo ln -sf /bin/busybox \"\$MNTDIR/sbin/insmod\"
- fi
- # Create modprobe symlink if missing
- if [ -f \"\$MNTDIR/bin/busybox\" ] && [ ! -e \"\$MNTDIR/sbin/modprobe\" ]; then
- sudo ln -sf /bin/busybox \"\$MNTDIR/sbin/modprobe\"
+
+ if [ -z \"\$GUEST_KVER\" ]; then
+ echo \"ERROR: Failed to find generic kernel — virtio-mem will not work\"
+ exit 1
+ fi
+
+ # Patch rootfs with kernel modules
+ echo \"Patching rootfs with kernel modules for \$GUEST_KVER...\"
+ MNTDIR=\$(mktemp -d)
+ sudo mount -o loop \"\$IMAGES_DIR/default.ext4\" \"\$MNTDIR\"
+ sudo rm -rf \"\$MNTDIR/lib/modules\"/*
+ sudo cp -a \"/lib/modules/\$GUEST_KVER\" \"\$MNTDIR/lib/modules/\"
+ sudo depmod -b \"\$MNTDIR\" \"\$GUEST_KVER\" 2>/dev/null || true
+ if [ -f \"\$MNTDIR/bin/busybox\" ] && [ ! -e \"\$MNTDIR/sbin/insmod\" ]; then
+ sudo ln -sf /bin/busybox \"\$MNTDIR/sbin/insmod\"
+ fi
+ if [ -f \"\$MNTDIR/bin/busybox\" ] && [ ! -e \"\$MNTDIR/sbin/modprobe\" ]; then
+ sudo ln -sf /bin/busybox \"\$MNTDIR/sbin/modprobe\"
+ fi
+ sudo umount \"\$MNTDIR\"
+ rmdir \"\$MNTDIR\"
+ echo \"Rootfs patched with kernel modules for \$GUEST_KVER\"
+
+ # Update guest kernel binary to match modules version.
+ # Without this, the VM boots with an old kernel that can't load
+ # the modules (e.g., virtio_mem won't load).
+ CURRENT_KVER=\"\"
+ if [ -f /opt/opensandbox/vmlinux ]; then
+ CURRENT_KVER=\$(file /opt/opensandbox/vmlinux 2>/dev/null | grep -oE '[0-9]+\\.[0-9]+\\.[0-9]+-[0-9]+-generic' || true)
+ fi
+ if [ \"\$CURRENT_KVER\" != \"\$GUEST_KVER\" ]; then
+ if [ -f \"/boot/vmlinuz-\$GUEST_KVER\" ]; then
+ echo \"Updating guest kernel: \$CURRENT_KVER → \$GUEST_KVER\"
+ sudo cp /opt/opensandbox/vmlinux /opt/opensandbox/vmlinux.bak 2>/dev/null || true
+ sudo cp \"/boot/vmlinuz-\$GUEST_KVER\" /opt/opensandbox/vmlinux
+ else
+ echo \"ERROR: /boot/vmlinuz-\$GUEST_KVER not found — kernel/module mismatch will break virtio-mem\"
+ exit 1
fi
- sudo umount \"\$MNTDIR\"
- rmdir \"\$MNTDIR\"
- echo \"Rootfs patched with kernel modules for \$GUEST_KVER\"
else
- echo \"WARNING: No guest kernel modules found for virtio-mem\"
+ echo \"Guest kernel already at \$GUEST_KVER\"
fi
# Delete golden snapshot so it rebuilds with new agent
diff --git a/internal/api/image_builder.go b/internal/api/image_builder.go
index 4c34e621..e5a38ec0 100644
--- a/internal/api/image_builder.go
+++ b/internal/api/image_builder.go
@@ -213,13 +213,37 @@ func (s *Server) resolveImageManifest(ctx context.Context, orgID uuid.UUID, mani
if s.store != nil {
cached, err := s.store.GetImageCacheByHash(ctx, orgID, contentHash)
if err == nil && cached.Status == "ready" && cached.CheckpointID != nil {
- // Cache hit — update last_used_at and return
- _ = s.store.TouchImageCacheUsage(ctx, cached.ID)
- log.Printf("image-builder: cache hit for hash %s (checkpoint=%s)", contentHash[:12], cached.CheckpointID)
- if logFn != nil {
- logFn(0, "cache_hit", fmt.Sprintf("Image found in cache (hash=%s)", contentHash[:12]))
+ // Cache hit — verify the checkpoint's S3 data still exists.
+ // Stale entries (from dead workers or failed uploads) would cause
+ // every fork to fail until the cache entry is cleared.
+ cp, cpErr := s.store.GetCheckpoint(ctx, *cached.CheckpointID)
+ if cpErr != nil || cp.RootfsS3Key == nil {
+ log.Printf("image-builder: cache hit for hash %s but checkpoint %s is invalid, rebuilding",
+ contentHash[:12], cached.CheckpointID)
+ _ = s.store.DeleteImageCache(ctx, orgID, cached.ID)
+ } else if s.checkpointStore != nil {
+ if exists, _ := s.checkpointStore.Exists(ctx, *cp.RootfsS3Key); !exists {
+ log.Printf("image-builder: cache hit for hash %s but S3 object missing for checkpoint %s, rebuilding",
+ contentHash[:12], cached.CheckpointID)
+ _ = s.store.DeleteImageCache(ctx, orgID, cached.ID)
+ } else {
+ // Cache hit is valid
+ _ = s.store.TouchImageCacheUsage(ctx, cached.ID)
+ log.Printf("image-builder: cache hit for hash %s (checkpoint=%s)", contentHash[:12], cached.CheckpointID)
+ if logFn != nil {
+ logFn(0, "cache_hit", fmt.Sprintf("Image found in cache (hash=%s)", contentHash[:12]))
+ }
+ return *cached.CheckpointID, nil
+ }
+ } else {
+ // No checkpoint store — trust the cache
+ _ = s.store.TouchImageCacheUsage(ctx, cached.ID)
+ log.Printf("image-builder: cache hit for hash %s (checkpoint=%s)", contentHash[:12], cached.CheckpointID)
+ if logFn != nil {
+ logFn(0, "cache_hit", fmt.Sprintf("Image found in cache (hash=%s)", contentHash[:12]))
+ }
+ return *cached.CheckpointID, nil
}
- return *cached.CheckpointID, nil
}
if err == nil && cached.Status == "building" {
// Another request is building this same image — wait for it
diff --git a/internal/qemu/manager.go b/internal/qemu/manager.go
index 91fac014..cd8f1bb1 100644
--- a/internal/qemu/manager.go
+++ b/internal/qemu/manager.go
@@ -1957,6 +1957,33 @@ func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointID
log.Printf("qemu: checkpoint %s: cache saved (%dms)", checkpointID, time.Since(t0).Milliseconds())
+ // Upload checkpoint to S3 synchronously so cross-worker forks can download it.
+ // Without this, forks routed to a different worker fail with "checkpoint not found in S3".
+ if checkpointStore != nil {
+ t1 := time.Now()
+ for _, upload := range []struct {
+ key string
+ file string
+ }{
+ {rootfsKey, filepath.Join(cacheDir, "rootfs.qcow2")},
+ {workspaceKey, filepath.Join(cacheDir, "workspace.qcow2")},
+ } {
+ // Create tar.zst archive of the single file
+ archivePath := upload.file + ".tar.zst"
+ if err := createArchive(archivePath, cacheDir, []string{filepath.Base(upload.file)}); err != nil {
+ log.Printf("qemu: checkpoint %s: archive %s failed: %v", checkpointID, filepath.Base(upload.file), err)
+ continue
+ }
+ uploadCtx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
+ if _, err := checkpointStore.Upload(uploadCtx, upload.key, archivePath); err != nil {
+ log.Printf("qemu: checkpoint %s: S3 upload %s failed: %v", checkpointID, upload.key, err)
+ }
+ cancel()
+ os.Remove(archivePath)
+ }
+ log.Printf("qemu: checkpoint %s: S3 upload complete (%dms)", checkpointID, time.Since(t1).Milliseconds())
+ }
+
if onReady != nil {
onReady()
}
diff --git a/internal/storage/s3.go b/internal/storage/s3.go
index 0486b453..0fcdea01 100644
--- a/internal/storage/s3.go
+++ b/internal/storage/s3.go
@@ -97,6 +97,15 @@ func (s *CheckpointStore) CacheHit(key string) bool {
// Upload uploads a checkpoint archive from a local file to S3.
// If caching is enabled, the file is also copied into the local NVMe cache.
+// Exists checks whether an object exists in S3/blob storage.
+func (s *CheckpointStore) Exists(ctx context.Context, key string) (bool, error) {
+ _, err := s.blob.Head(ctx, s.bucket, key)
+ if err != nil {
+ return false, err
+ }
+ return true, nil
+}
+
func (s *CheckpointStore) Upload(ctx context.Context, key, localPath string) (int64, error) {
f, err := os.Open(localPath)
if err != nil {
diff --git a/sdks/python/opencomputer/sandbox.py b/sdks/python/opencomputer/sandbox.py
index 3313b132..ee3adf3f 100644
--- a/sdks/python/opencomputer/sandbox.py
+++ b/sdks/python/opencomputer/sandbox.py
@@ -187,9 +187,8 @@ class Sandbox:
@property
def _ops_client(self) -> httpx.AsyncClient:
- """Return the client for data operations (direct worker if available, else CP)."""
- if self._data_client is not None:
- return self._data_client
+ """Return the client for data operations. Always goes through the CP,
+ which handles readiness waiting and proxies to workers."""
return self._client
async def kill(self) -> None:
diff --git a/sdks/typescript/src/sandbox.ts b/sdks/typescript/src/sandbox.ts
index cc9badce..5aec9300 100644
--- a/sdks/typescript/src/sandbox.ts
+++ b/sdks/typescript/src/sandbox.ts
@@ -104,16 +104,12 @@ export class Sandbox {
this.token = data.token || "";
this._sandboxDomain = data.sandboxDomain || "";
- // Use direct worker URL for data operations if available
- const opsUrl = this.connectUrl || apiUrl;
- const opsKey = this.connectUrl ? "" : apiKey;
- const opsToken = this.connectUrl ? this.token : "";
-
- this.agent = new Agent(opsUrl, opsKey, this.sandboxId, opsToken);
- this.files = new Filesystem(opsUrl, opsKey, this.sandboxId, opsToken);
- this.exec = new Exec(opsUrl, opsKey, this.sandboxId, opsToken);
+ // Always route through the CP — it handles readiness waiting and proxies to workers.
+ this.agent = new Agent(apiUrl, apiKey, this.sandboxId, "");
+ this.files = new Filesystem(apiUrl, apiKey, this.sandboxId, "");
+ this.exec = new Exec(apiUrl, apiKey, this.sandboxId, "");
this.commands = this.exec; // backwards-compatible alias
- this.pty = new Pty(opsUrl, opsKey, this.sandboxId, opsToken);
+ this.pty = new Pty(apiUrl, apiKey, this.sandboxId, "");
}
get status(): string {
@@ -259,29 +255,20 @@ export class Sandbox {
this.connectUrl = data.connectURL || "";
this.token = data.token || "";
- // Rebuild ops clients with new worker connection
- const opsUrl = this.connectUrl || this.apiUrl;
- const opsKey = this.connectUrl ? "" : this.apiKey;
- const opsToken = this.connectUrl ? this.token : "";
-
- (this as any).agent = new Agent(opsUrl, opsKey, this.sandboxId, opsToken);
- (this as any).files = new Filesystem(opsUrl, opsKey, this.sandboxId, opsToken);
- (this as any).exec = new Exec(opsUrl, opsKey, this.sandboxId, opsToken);
- (this as any).pty = new Pty(opsUrl, opsKey, this.sandboxId, opsToken);
+ // Always route through the CP
+ (this as any).agent = new Agent(this.apiUrl, this.apiKey, this.sandboxId, "");
+ (this as any).files = new Filesystem(this.apiUrl, this.apiKey, this.sandboxId, "");
+ (this as any).exec = new Exec(this.apiUrl, this.apiKey, this.sandboxId, "");
+ (this as any).pty = new Pty(this.apiUrl, this.apiKey, this.sandboxId, "");
}
async setTimeout(timeout: number): Promise<void> {
- // Route to worker directly (like commands/files/pty) — the control plane
- // rejects this call in server mode.
- const url = this.connectUrl || this.apiUrl;
const headers: Record<string, string> = { "Content-Type": "application/json" };
- if (this.connectUrl && this.token) {
- headers["Authorization"] = `Bearer ${this.token}`;
- } else if (this.apiKey) {
+ if (this.apiKey) {
headers["X-API-Key"] = this.apiKey;
}
- const resp = await fetch(`${url}/sandboxes/${this.sandboxId}/timeout`, {
+ const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/timeout`, {
method: "POST",
headers,
body: JSON.stringify({ timeout }),
@@ -343,13 +330,12 @@ export class Sandbox {
this.connectUrl = data.connectURL || "";
this.token = data.token || "";
- const opsUrl = this.connectUrl || this.apiUrl;
- const opsKey = this.connectUrl ? "" : this.apiKey;
- const opsToken = this.connectUrl ? this.token : "";
- (this as any).agent = new Agent(opsUrl, opsKey, this.sandboxId, opsToken);
- (this as any).files = new Filesystem(opsUrl, opsKey, this.sandboxId, opsToken);
- (this as any).exec = new Exec(opsUrl, opsKey, this.sandboxId, opsToken);
- (this as any).pty = new Pty(opsUrl, opsKey, this.sandboxId, opsToken);
+
+ // Always route through the CP
+ (this as any).agent = new Agent(this.apiUrl, this.apiKey, this.sandboxId, "");
+ (this as any).files = new Filesystem(this.apiUrl, this.apiKey, this.sandboxId, "");
+ (this as any).exec = new Exec(this.apiUrl, this.apiKey, this.sandboxId, "");
+ (this as any).pty = new Pty(this.apiUrl, this.apiKey, this.sandboxId, "");
}
static async createFromCheckpoint(checkpointId: string, opts: Pick<SandboxOpts, "apiKey" | "apiUrl" | "timeout"> = {}): Promise<Sandbox> {