Skip to content

An open-source, faster Devin alternative

TypeScript

stale cache invalidation, s3 synchronous

Brian Reardond4a4017d59dd
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> {