Skip to content

An open-source, faster Devin alternative

TypeScript

include scripts

Brian Reardon25ea6632495c
diff --git a/cmd/worker/main.go b/cmd/worker/main.go
index 9d9e9824..47191aca 100644
--- a/cmd/worker/main.go
+++ b/cmd/worker/main.go
@@ -1031,6 +1031,7 @@ func runExecRebindQEMU(ctx context.Context, agent *qm.AgentClient, sessionID str
}
go forwardStdin(stdinR, stream)
consumeExecOutput(stream, scrollback, handle)
+ recoverExitAfterDrop(ctx, agent, sessionID, handle)
}
// createExecSessionQEMU creates an exec session using a QEMU agent client.
@@ -1089,6 +1090,40 @@ func runExecStreamQEMU(ctx context.Context, agent *qm.AgentClient, sessionID str
}
go forwardStdin(stdinR, stream)
consumeExecOutput(stream, scrollback, handle)
+ recoverExitAfterDrop(ctx, agent, sessionID, handle)
+}
+
+// recoverExitAfterDrop handles the case where the attach stream ended before
+// the EXIT frame (e.g. the gRPC connection dropped mid-command). The command
+// likely kept running / finished but we never recorded its exit code, which
+// would leave the handle stuck at running forever and the async /result poll
+// never completing. The agent retains exited sessions ~5min, so we re-attach in
+// exit-only mode to recover the real code. Bounded; ignores replayed output
+// (the handle's scrollback already has it) to avoid duplicating it.
+func recoverExitAfterDrop(ctx context.Context, agent *qm.AgentClient, sessionID string, handle *sandbox.ExecSessionHandle) {
+ for attempt := 0; handle.ExitCode == nil && ctx.Err() == nil && attempt < 30; attempt++ {
+ time.Sleep(2 * time.Second)
+ rs, err := agent.ExecSessionAttach(ctx)
+ if err != nil {
+ continue
+ }
+ if err := rs.Send(&agentpb.ExecSessionInput{SessionId: sessionID}); err != nil {
+ continue
+ }
+ for {
+ msg, err := rs.Recv()
+ if err != nil {
+ break
+ }
+ if msg.Type == agentpb.ExecSessionOutput_EXIT {
+ exitCode := int(msg.ExitCode)
+ handle.ExitedAt = time.Now()
+ handle.ExitCode = &exitCode
+ handle.Running = false
+ return
+ }
+ }
+ }
}
// forwardStdin pipes stdin data to a gRPC stream.
diff --git a/internal/agent/server.go b/internal/agent/server.go
index ff6ae641..d7f41648 100644
--- a/internal/agent/server.go
+++ b/internal/agent/server.go
@@ -17,6 +17,7 @@ import (
"github.com/opensandbox/opensandbox/internal/logship"
pb "github.com/opensandbox/opensandbox/proto/agent"
"google.golang.org/grpc"
+ "google.golang.org/grpc/keepalive"
)
const (
@@ -97,6 +98,17 @@ func (s *Server) Serve(lis net.Listener) error {
grpcServer := grpc.NewServer(
grpc.MaxRecvMsgSize(256 * 1024 * 1024), // 256MB for large file transfers
grpc.MaxSendMsgSize(256 * 1024 * 1024),
+ // The worker client pings every 30s with PermitWithoutStream. gRPC's
+ // default server enforcement (MinTime 5m, PermitWithoutStream false)
+ // treats those as too-frequent and, after 2 strikes, sends GOAWAY and
+ // drops the connection — which kills in-flight exec attach streams on
+ // long no-output commands (e.g. `sleep 60`), so the EXIT is never
+ // delivered and the async result poll hangs at running. Permit the
+ // client's cadence.
+ grpc.KeepaliveEnforcementPolicy(keepalive.EnforcementPolicy{
+ MinTime: 10 * time.Second,
+ PermitWithoutStream: true,
+ }),
)
pb.RegisterSandboxAgentServer(grpcServer, s)
diff --git a/scripts/524/confirm.sh b/scripts/524/confirm.sh
new file mode 100755
index 00000000..000701c9
--- /dev/null
+++ b/scripts/524/confirm.sh
@@ -0,0 +1,69 @@
+#!/usr/bin/env bash
+#
+# confirm.sh — verify the 524s are gone against an environment on this change.
+#
+# OSB_API_KEY=osb_xxx OSB_BASE=https://app2.opensandbox.ai ./scripts/524/confirm.sh
+#
+# Every request returns in well under Cloudflare's 100s; long work happens in the
+# background and is polled, so there's no 524 on any path.
+set -uo pipefail
+: "${OSB_API_KEY:?set OSB_API_KEY}"
+: "${OSB_BASE:?set OSB_BASE (e.g. https://app2.opensandbox.ai)}"
+API="$OSB_BASE/api"
+H=(-H "X-API-Key: $OSB_API_KEY" -H "User-Agent: curl/8.0" -H "Content-Type: application/json")
+PASS=0; FAIL=0
+ok(){ echo " PASS: $1"; PASS=$((PASS+1)); }
+no(){ echo " FAIL: $1"; FAIL=$((FAIL+1)); }
+newsb(){ curl -s "${H[@]}" -X POST -d '{}' "$API/sandboxes" | python3 -c 'import sys,json;print(json.load(sys.stdin)["sandboxID"])'; }
+hibernate(){ curl -s "${H[@]}" -X POST "$API/sandboxes/$1/hibernate" >/dev/null
+ until [ "$(curl -s "${H[@]}" "$API/sandboxes/$1" | python3 -c 'import sys,json;print(json.load(sys.stdin).get("status"))')" = hibernated ]; do sleep 2; done; }
+
+run_and_wait(){ # sid cmd -> "exit|stdout|post_secs"
+ local rj; rj=$(curl -s -w '\n%{time_total}' "${H[@]}" -X POST \
+ -d "$(python3 -c 'import json,sys;print(json.dumps({"cmd":"sh","args":["-c",sys.argv[1]]}))' "$2")" \
+ "$API/sandboxes/$1/exec/run")
+ local ps eid; ps=$(echo "$rj"|tail -1); eid=$(echo "$rj"|head -1|python3 -c 'import sys,json;print(json.load(sys.stdin).get("execId",""))')
+ local r; for _ in $(seq 1 300); do r=$(curl -s "${H[@]}" "$API/sandboxes/$1/exec/$eid/result")
+ [ "$(echo "$r"|python3 -c 'import sys,json;print(json.load(sys.stdin)["running"])')" = False ] && break; sleep 0.5; done
+ echo "$r"|python3 -c "import sys,json;r=json.load(sys.stdin);print(f\"{r.get('exitCode')}|{r.get('stdout','')!r}|$ps\")"
+}
+
+echo "=== exec/run: long command, async, no 524 ==="
+SID=$(newsb); echo "sandbox=$SID"
+IFS='|' read -r ec so ps <<<"$(run_and_wait "$SID" 'sleep 60; echo done')"
+echo " POST=${ps}s exit=$ec stdout=$so"
+python3 -c "import sys;sys.exit(0 if float('$ps')<3 else 1)" && ok "POST <3s on a 60s command" || no "POST ${ps}s"
+[ "$ec" = 0 ] && ok "exit 0" || no "exit=$ec"
+
+echo "=== exec/run: fast commands keep their exit code ==="
+IFS='|' read -r ec so ps <<<"$(run_and_wait "$SID" 'echo hi')"; [ "$ec" = 0 ] && ok "echo hi -> 0" || no "echo hi -> $ec"
+IFS='|' read -r ec so ps <<<"$(run_and_wait "$SID" 'echo e>&2; exit 7')"; [ "$ec" = 7 ] && ok "exit 7 kept" || no "got $ec"
+
+echo "=== exec/run: cold (hibernated) returns immediately ==="
+hibernate "$SID"
+T=$(curl -s -o /tmp/c_run -w '%{time_total}' "${H[@]}" -X POST -d '{"cmd":"sh","args":["-c","echo woke"]}' "$API/sandboxes/$SID/exec/run")
+echo " cold POST=${T}s"
+python3 -c "import sys;sys.exit(0 if float('$T')<5 else 1)" && ok "cold exec POST <5s" || no "cold exec POST ${T}s"
+
+echo "=== files: cold returns 503 waking immediately, served on retry ==="
+SID2=$(newsb); curl -s "${H[@]}" -X PUT --data-binary "hello" "$API/sandboxes/$SID2/files?path=/tmp/t" >/dev/null
+hibernate "$SID2"
+T=$(curl -s -o /tmp/c_f -w '%{time_total}' "${H[@]}" "$API/sandboxes/$SID2/files?path=/tmp/t")
+WK=$(python3 -c 'import json;print(json.load(open("/tmp/c_f")).get("waking"))' 2>/dev/null)
+echo " first GET=${T}s waking=$WK"
+python3 -c "import sys;sys.exit(0 if float('$T')<5 and '$WK'=='True' else 1)" && ok "cold files 503 waking <5s" || no "cold files ${T}s waking=$WK"
+for _ in $(seq 1 60); do B=$(curl -s -w '|%{http_code}' "${H[@]}" "$API/sandboxes/$SID2/files?path=/tmp/t")
+ [ "${B##*|}" = 200 ] && break; sleep 2; done
+[ "${B%|*}" = "hello" ] && ok "warm retry served the file" || no "retry body='${B%|*}'"
+
+echo "=== snapshots: non-SSE build is async (building -> ready) ==="
+TS=$(date +%s)
+B=$(curl -s -o /tmp/c_s -w '%{time_total}' "${H[@]}" -X POST \
+ -d "{\"name\":\"confirm-$TS\",\"image\":{\"base\":\"ubuntu\",\"steps\":[{\"type\":\"run\",\"args\":{\"commands\":[\"echo hi\"]}}]}}" "$API/snapshots")
+echo " POST=${B}s status=$(python3 -c 'import json;print(json.load(open("/tmp/c_s")).get("status"))')"
+python3 -c "import sys;sys.exit(0 if float('$B')<5 else 1)" && ok "snapshot POST <5s" || no "snapshot POST ${B}s"
+for _ in $(seq 1 120); do ST=$(curl -s "${H[@]}" "$API/snapshots/confirm-$TS" | python3 -c 'import sys,json;print(json.load(sys.stdin).get("status"))' 2>/dev/null)
+ { [ "$ST" = ready ] || [ "$ST" = failed ]; } && break; sleep 2; done
+[ "$ST" = ready ] && ok "snapshot -> ready" || no "snapshot ended $ST"
+
+echo; echo "========== $PASS passed, $FAIL failed =========="; exit $((FAIL>0))
diff --git a/scripts/524/repro.sh b/scripts/524/repro.sh
new file mode 100755
index 00000000..58136f86
--- /dev/null
+++ b/scripts/524/repro.sh
@@ -0,0 +1,42 @@
+#!/usr/bin/env bash
+#
+# repro.sh — reproduce the Cloudflare 524s this change eliminates.
+#
+# Each case is a SINGLE synchronous request that holds the connection open past
+# Cloudflare's ~100s proxy_read_timeout while the backend works, so the edge
+# 524s the client even though the operation is fine. Run against an environment
+# on the pre-change code:
+#
+# OSB_API_KEY=osb_xxx OSB_BASE=https://app.opencomputer.dev ./scripts/524/repro.sh
+#
+# Expect HTTP 524 (or a 5xx near the ~100s mark) on each path.
+set -uo pipefail
+: "${OSB_API_KEY:?set OSB_API_KEY}"
+: "${OSB_BASE:?set OSB_BASE (e.g. https://app.opencomputer.dev)}"
+API="$OSB_BASE/api"
+H=(-H "X-API-Key: $OSB_API_KEY" -H "User-Agent: curl/8.0" -H "Content-Type: application/json")
+
+new_sandbox() { curl -s "${H[@]}" -X POST -d '{}' "$API/sandboxes" | python3 -c 'import sys,json;print(json.load(sys.stdin)["sandboxID"])'; }
+hibernate() {
+ curl -s "${H[@]}" -X POST "$API/sandboxes/$1/hibernate" >/dev/null
+ until [ "$(curl -s "${H[@]}" "$API/sandboxes/$1" | python3 -c 'import sys,json;print(json.load(sys.stdin).get("status"))')" = hibernated ]; do sleep 2; done
+}
+timed() { curl -s -o /dev/null -w "HTTP %{http_code} in %{time_total}s" "${H[@]}" "$@"; }
+
+echo "### exec/run — the synchronous command holds the connection until it finishes"
+SID=$(new_sandbox); echo "sandbox=$SID"
+echo " $(timed -X POST -d '{"cmd":"sh","args":["-c","sleep 130; echo done"],"timeout":200}' "$API/sandboxes/$SID/exec/run")"
+echo
+
+echo "### snapshots — the synchronous (non-SSE) build holds the connection"
+TS=$(date +%s)
+BODY="{\"name\":\"repro-$TS\",\"image\":{\"base\":\"ubuntu\",\"steps\":[{\"type\":\"run\",\"args\":{\"commands\":[\"sleep 130\"]}}]}}"
+echo " $(timed -X POST -d "$BODY" "$API/snapshots")"
+echo
+
+echo "### files — a large/slow upload holds the connection until the write completes"
+SID2=$(new_sandbox); echo "sandbox=$SID2"
+# Stream the body slowly for >130s so the worker can't return its 204 before
+# Cloudflare's ~100s read timeout. Deterministic regardless of bandwidth.
+( for _ in $(seq 1 130); do head -c 200000 /dev/zero; sleep 1; done ) | \
+ curl -s -o /dev/null -w " HTTP %{http_code} in %{time_total}s\n" "${H[@]}" -T - "$API/sandboxes/$SID2/files?path=/tmp/big"