Skip to content

Secure, Fast, and Extensible Sandbox runtime for AI agents.

fix(execd): write an isolated run's script while reading its output

Maohaob814b2bf2417
diff --git a/components/execd/pkg/runtime/isolated_session_ctrl.go b/components/execd/pkg/runtime/isolated_session_ctrl.go
index 54417b303..021363ef9 100644
--- a/components/execd/pkg/runtime/isolated_session_ctrl.go
+++ b/components/execd/pkg/runtime/isolated_session_ctrl.go
@@ -713,11 +713,22 @@ func (r *IsolatedRunner) RunInIsolatedSession(ctx context.Context, id string, co
}
}()
- if _, err := io.WriteString(stdin, script.String()); err != nil {
- return fmt.Errorf("write stdin: %w", err)
- }
+ // The shell runs the script as it reads it, so write it while stdout is
+ // read: a command that fills the stdout pipe before the shell has read the
+ // rest of a large script would otherwise block both sides.
+ written := make(chan error, 1)
+ go func() {
+ _, err := io.WriteString(stdin, script.String())
+ written <- err
+ }()
exitCode, err := scanUntilMarker(ctx, stdout, runMarker, onStdout)
+ // Scanning stops at the marker, which the shell reads last, or when the
+ // shell exits, so the write has returned by then and cannot spill into the
+ // next run.
+ if writeErr := <-written; writeErr != nil && ctx.Err() == nil {
+ return fmt.Errorf("write stdin: %w", writeErr)
+ }
if err != nil {
return err
}
diff --git a/components/execd/pkg/runtime/isolated_session_test.go b/components/execd/pkg/runtime/isolated_session_test.go
index e9175d355..6b20209d9 100644
--- a/components/execd/pkg/runtime/isolated_session_test.go
+++ b/components/execd/pkg/runtime/isolated_session_test.go
@@ -677,6 +677,35 @@ func TestRunInIsolatedSession_MultiLine(t *testing.T) {
}
}
+// The shell runs the script while it reads it, so a script larger than the
+// stdin pipe whose early commands print more than the stdout pipe holds must
+// still complete.
+func TestRunInIsolatedSession_LargeScriptWithEarlyOutput(t *testing.T) {
+ runner := newTestRunner(t)
+
+ id, err := runner.CreateIsolatedSession(&IsolatedSessionOptions{
+ WorkspacePath: t.TempDir(),
+ WorkspaceMode: "rw",
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer runner.DeleteIsolatedSession(id)
+
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+
+ var lines int
+ code := "seq 1 100000\n#" + strings.Repeat("x", 150*1024) + "\necho done"
+ err = runner.RunInIsolatedSession(ctx, id, code, nil, func(string) { lines++ })
+ if err != nil {
+ t.Fatalf("RunInIsolatedSession: %v", err)
+ }
+ if lines != 100001 {
+ t.Fatalf("got %d output lines, want 100001", lines)
+ }
+}
+
func TestRunInIsolatedSession_EnvPersistence(t *testing.T) {
runner := newTestRunner(t)