Secure, Fast, and Extensible Sandbox runtime for AI agents.
fix(execd): add EXECD_SSE_LEGACY_COMPAT to omit exit_code from SSE events for old SDKs (#2472)
epha4fefd81b9c68
diff --git a/components/execd/pkg/flag/flags.go b/components/execd/pkg/flag/flags.goindex 41bea5957..b95083236 100644--- a/components/execd/pkg/flag/flags.go+++ b/components/execd/pkg/flag/flags.go@@ -55,4 +55,14 @@ var (// disabled, /internal/init is still accepted and becomes authoritative on apply,// preserving legacy behavior for control planes that never call it.RuntimeInit bool++ // SseLegacyCompat omits the exit_code field from execution_complete and+ // error SSE events so that clients whose EventNode schemas predate the+ // field never observe an unknown key. Successful foreground commands+ // carry no information in the field (it is a constant 0; failures are+ // reported via the error event), and newer SDKs already infer 0 from a+ // complete event without exit_code, so enabling this is lossless for+ // successful commands. Enable it while legacy SDK versions are still+ // deployed; turn it off once the fleet has upgraded.+ SseLegacyCompat bool)diff --git a/components/execd/pkg/flag/parser.go b/components/execd/pkg/flag/parser.goindex 795146003..10985e7d1 100644--- a/components/execd/pkg/flag/parser.go+++ b/components/execd/pkg/flag/parser.go@@ -33,6 +33,7 @@ const (jupyterIdlePollIntervalEnv = "EXECD_JUPYTER_IDLE_POLL_INTERVAL"isolationConfigEnv = "EXECD_ISOLATION_CONFIG"runtimeInitEnv = "EXECD_RUNTIME_INIT"+ sseLegacyCompatEnv = "EXECD_SSE_LEGACY_COMPAT")// InitFlags registers CLI flags and env overrides.@@ -46,6 +47,7 @@ func InitFlags() {InitMode = falseLifecycleStartupStatusFile = ""RuntimeInit = false+ SseLegacyCompat = false// First, set default values from environment variablesif jupyterFromEnv := os.Getenv(jupyterHostEnv); jupyterFromEnv != "" {@@ -112,6 +114,14 @@ func InitFlags() {}flag.BoolVar(&RuntimeInit, "runtime-init", RuntimeInit, "Gate preStart and the entrypoint on POST /internal/init; until then only /ping, /ready, and /internal/init are served")+ if sseLegacyCompatFromEnv := os.Getenv(sseLegacyCompatEnv); sseLegacyCompatFromEnv != "" {+ enabled, err := strconv.ParseBool(sseLegacyCompatFromEnv)+ if err != nil {+ stdlog.Panicf("Invalid %s=%s: must be a boolean value", sseLegacyCompatEnv, sseLegacyCompatFromEnv)+ }+ SseLegacyCompat = enabled+ }+// Parse flags - these will override environment variables if providedflag.Parse()if JupyterIdlePollInterval <= 0 {diff --git a/components/execd/pkg/flag/parser_test.go b/components/execd/pkg/flag/parser_test.goindex 03bf3bf5b..513e17462 100644--- a/components/execd/pkg/flag/parser_test.go+++ b/components/execd/pkg/flag/parser_test.go@@ -87,3 +87,35 @@ func TestInitFlagsDefaultsGracefulShutdownTimeout(t *testing.T) {require.Equal(t, 200*time.Millisecond, ApiGracefulShutdownTimeout)}++func TestInitFlagsDefaultsSseLegacyCompat(t *testing.T) {+ previousArgs := os.Args+ previousCommandLine := flag.CommandLine+ flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ContinueOnError)+ os.Args = []string{previousArgs[0]}+ t.Cleanup(func() {+ os.Args = previousArgs+ flag.CommandLine = previousCommandLine+ })+ t.Setenv(sseLegacyCompatEnv, "")++ InitFlags()++ require.False(t, SseLegacyCompat)+}++func TestInitFlagsSseLegacyCompatFromEnv(t *testing.T) {+ previousArgs := os.Args+ previousCommandLine := flag.CommandLine+ flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ContinueOnError)+ os.Args = []string{previousArgs[0]}+ t.Cleanup(func() {+ os.Args = previousArgs+ flag.CommandLine = previousCommandLine+ })+ t.Setenv(sseLegacyCompatEnv, "true")++ InitFlags()++ require.True(t, SseLegacyCompat)+}diff --git a/components/execd/pkg/web/controller/sse.go b/components/execd/pkg/web/controller/sse.goindex d678b9ed2..4d9a0d711 100644--- a/components/execd/pkg/web/controller/sse.go+++ b/components/execd/pkg/web/controller/sse.go@@ -24,6 +24,7 @@ import ("github.com/alibaba/opensandbox/internal/safego""k8s.io/apimachinery/pkg/util/wait"+ "github.com/alibaba/opensandbox/execd/pkg/flag""github.com/alibaba/opensandbox/execd/pkg/jupyter/execute""github.com/alibaba/opensandbox/execd/pkg/log""github.com/alibaba/opensandbox/execd/pkg/runtime"@@ -138,11 +139,11 @@ func (c *CodeInterpretingController) setServerEventsHandler(ctx context.Context)return}- event := model.ServerStreamEvent{+ event := sseLegacyCompatEvent(model.ServerStreamEvent{Type: model.StreamEventTypeError,Error: err,Timestamp: time.Now().UnixMilli(),- }+ })payload := event.ToJSON()c.writeSingleEvent("OnExecuteError", payload, true, event.Summary())},@@ -212,13 +213,33 @@ func (c *CodeInterpretingController) respondRunError(hooks runtime.ExecuteResult})}+// sseLegacyCompatEvent drops the exit_code field (top level and inside the+// error payload) when --sse-legacy-compat is enabled. SDKs whose EventNode+// schema predates the field treat unknown keys as a compatibility hazard, and+// successful foreground commands carry no information in exit_code anyway+// (it is a constant 0; failures are reported via the error event). Newer SDKs+// infer 0 from a complete event without exit_code, so this is lossless for+// successful commands.+func sseLegacyCompatEvent(event model.ServerStreamEvent) model.ServerStreamEvent {+ if !flag.SseLegacyCompat {+ return event+ }+ event.ExitCode = nil+ if event.Error != nil {+ shallowCopy := *event.Error+ shallowCopy.ExitCode = nil+ event.Error = &shallowCopy+ }+ return event+}+func (c *CodeInterpretingController) writeExecutionComplete(executionTime time.Duration, exitCode *int) {- event := model.ServerStreamEvent{+ event := sseLegacyCompatEvent(model.ServerStreamEvent{Type: model.StreamEventTypeComplete,ExecutionTime: executionTime.Milliseconds(),ExitCode: exitCode,Timestamp: time.Now().UnixMilli(),- }+ })c.writeSingleEvent("OnExecuteComplete", event.ToJSON(), true, event.Summary())}diff --git a/components/execd/pkg/web/controller/sse_test.go b/components/execd/pkg/web/controller/sse_test.gonew file mode 100644index 000000000..88e08d5b5--- /dev/null+++ b/components/execd/pkg/web/controller/sse_test.go@@ -0,0 +1,106 @@+// Copyright 2026 The OpenSandbox Authors+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.++package controller++import (+ "testing"+ "time"++ "github.com/alibaba/opensandbox/execd/pkg/flag"+ "github.com/alibaba/opensandbox/execd/pkg/jupyter/execute"+ "github.com/alibaba/opensandbox/execd/pkg/web/model"+ "github.com/stretchr/testify/require"+)++func configureSseLegacyCompat(t *testing.T, enabled bool) {+ t.Helper()+ previous := flag.SseLegacyCompat+ flag.SseLegacyCompat = enabled+ t.Cleanup(func() {+ flag.SseLegacyCompat = previous+ })+}++func TestSseLegacyCompatDisabledKeepsExitCode(t *testing.T) {+ configureSseLegacyCompat(t, false)++ exitCode := 0+ complete := sseLegacyCompatEvent(model.ServerStreamEvent{+ Type: model.StreamEventTypeComplete,+ ExecutionTime: time.Second.Milliseconds(),+ ExitCode: &exitCode,+ Timestamp: time.Now().UnixMilli(),+ })++ require.Contains(t, string(complete.ToJSON()), `"exit_code":0`)+}++func TestSseLegacyCompatDropsExitCodeFromCompleteEvent(t *testing.T) {+ configureSseLegacyCompat(t, true)++ exitCode := 0+ complete := sseLegacyCompatEvent(model.ServerStreamEvent{+ Type: model.StreamEventTypeComplete,+ ExecutionTime: time.Second.Milliseconds(),+ ExitCode: &exitCode,+ Timestamp: time.Now().UnixMilli(),+ })++ require.NotContains(t, string(complete.ToJSON()), "exit_code")+ require.NotZero(t, complete.ExecutionTime)+ require.NotZero(t, complete.Timestamp)+}++func TestSseLegacyCompatDropsExitCodeFromErrorEvent(t *testing.T) {+ configureSseLegacyCompat(t, true)++ exitCode := 3+ original := &execute.ErrorOutput{+ EName: "CommandExecError",+ EValue: "3",+ Traceback: []string{"exit status 3"},+ ExitCode: &exitCode,+ }+ errored := sseLegacyCompatEvent(model.ServerStreamEvent{+ Type: model.StreamEventTypeError,+ Error: original,+ Timestamp: time.Now().UnixMilli(),+ })++ payload := string(errored.ToJSON())+ require.Contains(t, payload, `"ename":"CommandExecError"`)+ require.Contains(t, payload, `"evalue":"3"`)+ require.NotContains(t, payload, "exit_code")++ require.NotNil(t, original.ExitCode, "input ErrorOutput must not be mutated")+}++func TestSseLegacyCompatKeepsErrorExitCodeWhenDisabled(t *testing.T) {+ configureSseLegacyCompat(t, false)++ exitCode := 3+ errored := sseLegacyCompatEvent(model.ServerStreamEvent{+ Type: model.StreamEventTypeError,+ Error: &execute.ErrorOutput{+ EName: "CommandExecError",+ EValue: "3",+ Traceback: []string{"exit status 3"},+ ExitCode: &exitCode,+ },+ Timestamp: time.Now().UnixMilli(),+ })++ require.Contains(t, string(errored.ToJSON()), `"exit_code":3`)+}diff --git a/docs/architecture/data-plane/execd.md b/docs/architecture/data-plane/execd.mdindex ef7efd20a..b8dddceca 100644--- a/docs/architecture/data-plane/execd.md+++ b/docs/architecture/data-plane/execd.md@@ -60,6 +60,10 @@ Foreground `stdout` and `stderr` event text preserves the command's line endingsA successful foreground `POST /command` ends with `execution_complete` carrying `exit_code: 0`. This optional field is omitted from background startup acknowledgements and code execution events; absence is not an exit status. Non-zero command exits retain `error.exit_code` on the `error` event. Older execd versions omit the successful exit code, so clients may retain their existing foreground-only completion inference. A stream that ends before a terminal event does not establish success.+::: warning Legacy SDK compatibility+SDKs built before `sandbox-api 1.0.18` do not know the `exit_code` key, and when a consumer classpath resolves an incompatible kotlinx-serialization runtime, decoding the unknown key crashes with `AbstractMethodError` — the command finishes inside the sandbox but the client call never returns and logs nothing. Setting `EXECD_SSE_LEGACY_COMPAT=true` makes execd omit the field from both events for such fleets; successful commands lose nothing because the value is a constant 0 and newer SDKs infer it. The long-term fix is upgrading the sandbox SDK to a build that shades its serialization runtime (`sandbox-api` 1.0.18 or newer), which removes the dependency-conflict hazard for every field added in the future.+:::+Bash-session runs stream one merged `stdout` event stream (session stderr is merged into it) with the same line-ending contract: event text preserves `\n`, `\r`, or `\r\n`, and concatenating event text reconstructs the run's output. Blank lines are preserved as events containing only the line ending, and the final event may be an unterminated fragment. A line longer than 16 MiB is split across several events, and only the last of them ends with the line ending.Sessions use Bash when the image provides it and fall back to POSIX `sh` on minimal images — commands sent to a fallback session must be `sh`-compatible. Windows sandboxes are supported (environment names are case-insensitive; batch files require shell syntax).