Skip to content

An open-source, faster Devin alternative

TypeScript

fix review issues

Brian Reardonef7dbca8de8b
diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.ts
index c7500bb4..ff9c027c 100644
--- a/cloudflare-workers/api-edge/src/index.ts
+++ b/cloudflare-workers/api-edge/src/index.ts
@@ -496,10 +496,14 @@ async function getSandbox(req: Request, env: Env, id: string): Promise<Response>
// when the SDK's API key didn't exist in cell PG (api_keys are global in D1
// now, not mirrored per-cell).
async function proxyToCellSDK(req: Request, env: Env, ctx: ExecutionContext, caller: Caller, id: string): Promise<Response> {
- const row = await env.OPENCOMPUTER_DB.prepare("SELECT cell_id FROM sandboxes_index WHERE id = ?1")
+ const row = await env.OPENCOMPUTER_DB.prepare("SELECT cell_id, org_id FROM sandboxes_index WHERE id = ?1")
.bind(id)
- .first<{ cell_id: string }>();
- if (!row) return json({ error: "sandbox not found" }, 404);
+ .first<{ cell_id: string; org_id: string }>();
+ // Authorization: the sandbox must belong to the caller's org. Without this,
+ // any authenticated org could exec/files/pty/delete/hibernate/wake another
+ // org's sandbox by id (the cell trusts the edge for authz). 404 not 403 so
+ // we don't leak which sandbox ids exist.
+ if (!row || row.org_id !== caller.orgID) return json({ error: "sandbox not found" }, 404);
const cell = await lookupCell(env, row.cell_id);
if (!cell) return json({ error: `cell ${row.cell_id} not registered` }, 503);
diff --git a/cloudflare-workers/events-ingest/src/index.ts b/cloudflare-workers/events-ingest/src/index.ts
index 21dcecfc..25db4425 100644
--- a/cloudflare-workers/events-ingest/src/index.ts
+++ b/cloudflare-workers/events-ingest/src/index.ts
@@ -205,16 +205,20 @@ export default {
// sandbox_checkpoints. CP emits checkpoint_ready after SetCheckpointReady
// (UPSERT all fields) and checkpoint_deleted after DeleteCheckpoint. The
// dashboard cross-cell list + the edge's spawn-from-checkpoint routing
- // both depend on this table being populated.
+ // both depend on this table being populated. golden_hash is write-once:
+ // it pins the checkpoint to its base golden, so the upsert fills a
+ // previously-empty row but never overwrites a set value — changing it
+ // would rebase the delta onto the wrong base and break restore.
const checkpointUpsert = env.OPENCOMPUTER_DB.prepare(
`INSERT INTO checkpoints_index
(id, sandbox_id, org_id, owner_cell_id, s3_url, size_bytes, golden_hash, workspace_size, created_at)
- VALUES (?1, ?2, ?3, ?4, ?5, ?6, '', NULL, ?7)
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, NULL, ?8)
ON CONFLICT(id) DO UPDATE SET
sandbox_id = excluded.sandbox_id,
owner_cell_id = excluded.owner_cell_id,
s3_url = excluded.s3_url,
- size_bytes = excluded.size_bytes`,
+ size_bytes = excluded.size_bytes,
+ golden_hash = CASE WHEN checkpoints_index.golden_hash = '' THEN excluded.golden_hash ELSE checkpoints_index.golden_hash END`,
);
const checkpointDelete = env.OPENCOMPUTER_DB.prepare(
`DELETE FROM checkpoints_index WHERE id = ?1`,
@@ -227,6 +231,7 @@ export default {
rootfs_s3_key?: string;
workspace_s3_key?: string;
size_bytes?: number;
+ golden_hash?: string;
};
if (!p.checkpoint_id) return [];
if (e.type === "checkpoint_deleted") {
@@ -244,6 +249,7 @@ export default {
e.cell_id,
p.rootfs_s3_key ?? "",
p.size_bytes ?? null,
+ p.golden_hash ?? "",
tsSec,
),
];
diff --git a/internal/api/sandbox.go b/internal/api/sandbox.go
index e167b9b5..a3832b6f 100644
--- a/internal/api/sandbox.go
+++ b/internal/api/sandbox.go
@@ -526,6 +526,11 @@ func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg ty
tmpl, err := s.resolveTemplate(ctx, orgID, hasOrg, cfg.Template)
if err != nil {
log.Printf("sandbox: template %q lookup failed: %v", cfg.Template, err)
+ // Don't silently fall back to a blank default sandbox when the caller
+ // explicitly asked for a template — surface the failure.
+ if cfg.Template != "" {
+ return c.JSON(http.StatusBadGateway, map[string]string{"error": "template lookup failed for " + cfg.Template + ": " + err.Error()})
+ }
} else if tmpl != nil {
templateID = &tmpl.ID
log.Printf("sandbox: resolved template %q (type=%s, id=%s)", cfg.Template, tmpl.TemplateType, tmpl.ID)
@@ -534,6 +539,9 @@ func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg ty
templateWorkspaceKey = *tmpl.WorkspaceS3Key
log.Printf("sandbox: using snapshot template drives: rootfs=%s, workspace=%s", templateRootfsKey, templateWorkspaceKey)
}
+ } else if cfg.Template != "" {
+ // Requested a template by name but it didn't resolve (not found).
+ return c.JSON(http.StatusNotFound, map[string]string{"error": "template not found: " + cfg.Template})
}
// Dispatch via persistent gRPC connection.
@@ -2157,10 +2165,18 @@ func (s *Server) createCheckpoint(c echo.Context) error {
// Pre-fix this was hardcoded to 0, leaving size_bytes meaningless.
_ = s.store.SetCheckpointReady(context.Background(), checkpointID, grpcResp.RootfsS3Key, grpcResp.WorkspaceS3Key, grpcResp.SizeBytes)
log.Printf("api: checkpoint %s ready (size=%d bytes)", checkpointID, grpcResp.SizeBytes)
+ golden := ""
+ if session.GoldenVersion != nil {
+ golden = *session.GoldenVersion
+ }
s.publishCheckpointEvent(context.Background(), "checkpoint_ready", checkpointID, sandboxID, orgID, session.WorkerID, map[string]any{
"rootfs_s3_key": grpcResp.RootfsS3Key,
"workspace_s3_key": grpcResp.WorkspaceS3Key,
"size_bytes": grpcResp.SizeBytes,
+ // golden_hash pins the checkpoint to its base golden so D1
+ // checkpoints_index rows created from this event are spawn-routable
+ // (matches what the backfill stores from sandbox_sessions.golden_version).
+ "golden_hash": golden,
})
}()
} else if s.manager != nil {
@@ -2181,10 +2197,15 @@ func (s *Server) createCheckpoint(c echo.Context) error {
}
_ = s.store.SetCheckpointReady(context.Background(), checkpointID, rootfsKey, workspaceKey, sizeBytes)
log.Printf("api: checkpoint %s ready (size=%d bytes)", checkpointID, sizeBytes)
+ golden := ""
+ if session.GoldenVersion != nil {
+ golden = *session.GoldenVersion
+ }
s.publishCheckpointEvent(context.Background(), "checkpoint_ready", checkpointID, sandboxID, orgID, session.WorkerID, map[string]any{
"rootfs_s3_key": rootfsKey,
"workspace_s3_key": workspaceKey,
"size_bytes": sizeBytes,
+ "golden_hash": golden,
})
}()
} else {
diff --git a/internal/worker/redis_event_publisher.go b/internal/worker/redis_event_publisher.go
index 5e22045b..ffdd911f 100644
--- a/internal/worker/redis_event_publisher.go
+++ b/internal/worker/redis_event_publisher.go
@@ -9,7 +9,6 @@ import (
"sync"
"time"
- "github.com/google/uuid"
"github.com/redis/go-redis/v9"
"github.com/opensandbox/opensandbox/internal/sandbox"
)
@@ -206,7 +205,11 @@ func (p *RedisEventPublisher) FlushSandbox(ctx context.Context, sandboxID string
ts = time.Now()
}
envelope := SandboxEventEnvelope{
- ID: uuid.NewString(),
+ // Deterministic id: a re-publish (XADD succeeded but MarkSynced
+ // didn't — crash/timeout) must collide with the prior id so the
+ // downstream D1 `ON CONFLICT(id) DO NOTHING` dedups it. A fresh
+ // UUID per attempt would double-apply (e.g. usage_tick → double debit).
+ ID: fmt.Sprintf("%s:%d", sandboxID, e.ID),
Type: e.Type,
SandboxID: sandboxID,
OrgID: orgID,
@@ -257,7 +260,8 @@ func (p *RedisEventPublisher) flush(ctx context.Context) {
for _, se := range events {
envelope := SandboxEventEnvelope{
- ID: uuid.NewString(),
+ // Deterministic id (see FlushSandbox) so retries dedup downstream.
+ ID: fmt.Sprintf("%s:%d", se.SandboxID, se.Event.ID),
Type: se.Event.Type,
SandboxID: se.SandboxID,
WorkerID: p.workerID,