mirror of
https://github.com/BaaRai/ARTEX.git
synced 2026-12-03 13:11:05 +00:00
Merge pull request #828 from renaesop/codex/sandbox-cancel-pause-fix
fix(sandbox): preserve run cancellation and persist failure pauses
This commit is contained in:
commit
cc4e536a32
11 changed files with 315 additions and 11 deletions
|
|
@ -31,6 +31,8 @@ var (
|
|||
"The user paused the task via the task control API (POST /api/tasks/{id}/control, action=pause). This Planner/Worker run was actively cancelled; running intents return to frontier(open) and are re-claimed and executed from scratch after the task resumes")
|
||||
AbortPausedByOrchestrator = cause("paused_by_orchestrator", "The orchestrating agent paused the task",
|
||||
"The orchestrating agent called the pause_task tool to pause this task. This Planner/Worker run was actively cancelled; running intents return to frontier(open) and are executed again after resuming")
|
||||
AbortSandboxUnavailable = cause("sandbox_unavailable", "The sandbox runner is unavailable",
|
||||
"The required sandbox runner or Docker backend is unavailable. The task was paused without local execution fallback; running intents return to frontier(open) and can run again after the operator resumes the task")
|
||||
AbortTaskDeleted = cause("task_deleted", "The task was deleted",
|
||||
"The task is being deleted (DELETE /api/tasks/{id}); the deletion barrier has cancelled the task's running Planner, Worker, and main agent; this run's results will not be used")
|
||||
AbortPausedOnReload = cause("paused_on_reload", "Restored the paused state on startup",
|
||||
|
|
|
|||
|
|
@ -87,6 +87,9 @@ func containerWorkdir(taskDir, workingDir string) string {
|
|||
// In ARTEX_SANDBOX=required mode it fails closed (no local fallback) and notifies
|
||||
// OnUnavailable when the runner cannot be reached so the engine pauses the task.
|
||||
func ExecInSandbox(ctx context.Context, argv []string, workingDir string, timeoutMS int, env []string) (sandbox.ExecResponse, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return sandbox.ExecResponse{}, err
|
||||
}
|
||||
ex := activeSandboxExecutor.Load()
|
||||
if ex == nil || ex.Mode != sandbox.ModeRequired {
|
||||
return sandbox.ExecResponse{}, errors.New("sandbox executor not in required mode")
|
||||
|
|
@ -111,7 +114,9 @@ func ExecInSandbox(ctx context.Context, argv []string, workingDir string, timeou
|
|||
ScopeCIDRs: info.ScopeCIDRs,
|
||||
}
|
||||
resp, err := ex.Runner.Exec(ctx, info.TaskID, req)
|
||||
if err != nil && sandbox.IsUnavailable(err) && ex.OnUnavailable != nil {
|
||||
// A run deadline or task cancellation says nothing about runner health.
|
||||
// Keep this guard even for runner implementations that wrap cancellation.
|
||||
if err != nil && ctx.Err() == nil && sandbox.IsUnavailable(err) && ex.OnUnavailable != nil {
|
||||
ex.OnUnavailable(info.TaskID, err)
|
||||
}
|
||||
return resp, err
|
||||
|
|
|
|||
|
|
@ -139,7 +139,7 @@ func TestTerminalTextNonAbortReasons(t *testing.T) {
|
|||
|
||||
func TestAbortCausesAreWellFormed(t *testing.T) {
|
||||
all := []*AbortCause{
|
||||
AbortPausedByUser, AbortPausedByOrchestrator, AbortTaskDeleted, AbortPausedOnReload,
|
||||
AbortPausedByUser, AbortPausedByOrchestrator, AbortSandboxUnavailable, AbortTaskDeleted, AbortPausedOnReload,
|
||||
AbortGoalMet, AbortSettleDrainTimeout, AbortKilledByPlanner, AbortWorkPausedByUser,
|
||||
AbortWorkCancelledByUser, AbortWorkClaimLost, AbortWorkFinished, AbortPausedRaceGuard,
|
||||
AbortChatStoppedByUser, AbortChatPausedWithTask, AbortChatTurnFinished,
|
||||
|
|
|
|||
|
|
@ -59,6 +59,9 @@ func (c *Client) doJSON(ctx context.Context, method, path string, reqBody, out a
|
|||
}
|
||||
resp, err := c.http.Do(req)
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return fmt.Errorf("runner request canceled: %w", ctx.Err())
|
||||
}
|
||||
return fmt.Errorf("%w: %v", ErrRunnerUnavailable, err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
|
@ -66,6 +69,9 @@ func (c *Client) doJSON(ctx context.Context, method, path string, reqBody, out a
|
|||
// Cap error/JSON reads to 4 MiB (ExecResponse carries <= 2 MiB of stdout+stderr + JSON overhead).
|
||||
respRaw, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return fmt.Errorf("runner response canceled: %w", ctx.Err())
|
||||
}
|
||||
return fmt.Errorf("%w: read response: %v", ErrRunnerUnavailable, err)
|
||||
}
|
||||
if resp.StatusCode >= 400 {
|
||||
|
|
|
|||
80
sandbox/client_cancel_test.go
Normal file
80
sandbox/client_cancel_test.go
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
package sandbox
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestClientCancellationIsNotRunnerUnavailable(t *testing.T) {
|
||||
for _, stage := range []string{"headers", "body"} {
|
||||
for _, reason := range []string{"cancel", "deadline"} {
|
||||
t.Run(stage+"/"+reason, func(t *testing.T) {
|
||||
entered := make(chan struct{})
|
||||
release := make(chan struct{})
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = io.Copy(io.Discard, r.Body)
|
||||
if stage == "body" {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.(http.Flusher).Flush()
|
||||
}
|
||||
close(entered)
|
||||
<-release
|
||||
}))
|
||||
defer srv.Close()
|
||||
defer close(release)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
|
||||
defer cancel()
|
||||
want := context.DeadlineExceeded
|
||||
if reason == "cancel" {
|
||||
want = context.Canceled
|
||||
go func() {
|
||||
select {
|
||||
case <-entered:
|
||||
cancel()
|
||||
case <-ctx.Done():
|
||||
}
|
||||
}()
|
||||
}
|
||||
_, err := NewClient(srv.URL, "").Exec(ctx, "1", ExecRequest{Argv: []string{"true"}})
|
||||
if !errors.Is(err, want) || IsUnavailable(err) {
|
||||
t.Fatalf("Exec error = %v, want %v without unavailability", err, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type cancelTestTransport func(*http.Request) (*http.Response, error)
|
||||
|
||||
func (f cancelTestTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
|
||||
|
||||
type failedRunnerBody struct{}
|
||||
|
||||
func (failedRunnerBody) Read([]byte) (int, error) { return 0, io.ErrUnexpectedEOF }
|
||||
func (failedRunnerBody) Close() error { return nil }
|
||||
|
||||
func TestClientLiveContextFailuresRemainUnavailable(t *testing.T) {
|
||||
for _, stage := range []string{"transport", "body", "http"} {
|
||||
t.Run(stage, func(t *testing.T) {
|
||||
c := NewClient("http://runner.invalid", "")
|
||||
c.http.Transport = cancelTestTransport(func(*http.Request) (*http.Response, error) {
|
||||
if stage == "transport" {
|
||||
return nil, context.DeadlineExceeded
|
||||
}
|
||||
if stage == "body" {
|
||||
return &http.Response{StatusCode: 200, Body: failedRunnerBody{}}, nil
|
||||
}
|
||||
return &http.Response{StatusCode: 503, Body: http.NoBody}, nil
|
||||
})
|
||||
_, err := c.Exec(context.Background(), "1", ExecRequest{Argv: []string{"true"}})
|
||||
if !IsUnavailable(err) {
|
||||
t.Fatalf("Exec error = %v, want unavailability", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -1722,7 +1722,7 @@ func taskExecutionPaused(cause error) bool {
|
|||
}
|
||||
switch abort.Code {
|
||||
case "paused_by_user", "paused_by_orchestrator", "paused_on_reload", "paused_race_guard",
|
||||
"queued_for_admission", "llm_unavailable_queued", "task_deleted":
|
||||
"queued_for_admission", "llm_unavailable_queued", "sandbox_unavailable", "task_deleted":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
|
|
|
|||
|
|
@ -150,7 +150,10 @@ func (s *Server) admitTaskWhen(t *Task, mode string, requirePaused, blockTimeout
|
|||
if isTerminalStatus(lifecycle.Status) {
|
||||
return false, fmt.Errorf("a terminal task cannot be resumed")
|
||||
}
|
||||
if !lifecycle.Paused {
|
||||
// Older sandbox failures (or a failed pause write) can leave only the
|
||||
// Engine paused. Allow explicit recovery, but never treat the FIFO
|
||||
// admission barrier as an operator-resumable pause.
|
||||
if !lifecycle.Paused && (!s.engine.IsPaused(t.ID) || lifecycle.Queued) {
|
||||
return false, fmt.Errorf("only a paused task can be resumed")
|
||||
}
|
||||
mode = s.resumeAdmissionMode(t)
|
||||
|
|
|
|||
|
|
@ -22,6 +22,19 @@ type SandboxClient interface {
|
|||
Delete(ctx context.Context, taskID string) (sandbox.DeleteResponse, error)
|
||||
}
|
||||
|
||||
// pauseTaskForSandboxFailure shares the task-control transition so runtime, UI
|
||||
// and persisted pause state agree. Deletion/terminal guards still apply.
|
||||
func (s *Server) pauseTaskForSandboxFailure(taskID string, runnerErr error) {
|
||||
task, ok := s.m.Task(taskID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
log.Printf("[sandbox] runner unavailable for task %s (%v): pausing task (no local fallback)", taskID, runnerErr)
|
||||
if _, err := s.applyTaskControlWithCause(task, "pause", agent.AbortSandboxUnavailable); err != nil {
|
||||
log.Printf("[sandbox] task %s pause: %v", taskID, err)
|
||||
}
|
||||
}
|
||||
|
||||
// WithSandbox configures the panel's sandbox execution mode ("required" or "off")
|
||||
// and its artex-runner client (CONTRACT.md §6).
|
||||
func WithSandbox(client SandboxClient, mode string) Option {
|
||||
|
|
|
|||
192
server/sandbox_pause_test.go
Normal file
192
server/sandbox_pause_test.go
Normal file
|
|
@ -0,0 +1,192 @@
|
|||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/Autumn-27/artex/agent"
|
||||
"github.com/Autumn-27/artex/db"
|
||||
"github.com/Autumn-27/artex/sandbox"
|
||||
)
|
||||
|
||||
func TestSandboxCanceledRunDoesNotPauseTask(t *testing.T) {
|
||||
prev := agent.CurrentSandboxExecutor()
|
||||
t.Cleanup(func() { agent.SetSandboxExecutor(prev) })
|
||||
for _, before := range []bool{false, true} {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
calls := 0
|
||||
stub := &stubSandboxClient{execFn: func(context.Context, string, sandbox.ExecRequest) (sandbox.ExecResponse, error) {
|
||||
calls++
|
||||
cancel()
|
||||
return sandbox.ExecResponse{}, sandbox.ErrRunnerUnavailable
|
||||
}}
|
||||
agent.SetSandboxExecutor(&agent.SandboxExecutor{Mode: sandbox.ModeRequired, Runner: stub, OnUnavailable: func(string, error) { t.Error("canceled run paused task") }})
|
||||
if before {
|
||||
cancel()
|
||||
}
|
||||
ctx = agent.WithSandboxRunInfo(ctx, agent.SandboxRunInfo{TaskID: "1"})
|
||||
if _, err := agent.ExecInSandbox(ctx, []string{"true"}, "", 1000, nil); err == nil {
|
||||
t.Fatal("cancellation returned success")
|
||||
}
|
||||
if before && calls != 0 {
|
||||
t.Fatal("already canceled run reached runner")
|
||||
}
|
||||
cancel()
|
||||
}
|
||||
}
|
||||
|
||||
func newSandboxPauseTestTask(t *testing.T) (*Manager, *Server, *Task) {
|
||||
t.Helper()
|
||||
m, err := NewManager(t.TempDir(), "")
|
||||
if err != nil {
|
||||
db.SkipPGUnavailable(t, err)
|
||||
}
|
||||
t.Cleanup(func() { m.Close() })
|
||||
task, err := m.CreateTask("sandbox pause regression", "test lifecycle only", nil, 0, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tid := mustTaskID(t, task.ID)
|
||||
t.Cleanup(func() {
|
||||
// A failure test closes the manager connection. Cleanup uses its own handle.
|
||||
dsn, _, err := db.DSN()
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
pg, err := db.Open(dsn)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
defer pg.Close()
|
||||
if err := pg.DeleteTask(tid); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
})
|
||||
return m, newAdmissionTestServer(m, nil), task
|
||||
}
|
||||
|
||||
func TestSandboxFailurePersistsPauseAndCanResume(t *testing.T) {
|
||||
m, s, task := newSandboxPauseTestTask(t)
|
||||
defer restoreConcurrencySetting(t, m)()
|
||||
if err := m.SetConcurrency(false, defaultConcurrencyLimit); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx := s.engine.execContextFor(context.Background(), task.ID)
|
||||
s.pauseTaskForSandboxFailure(task.ID, sandbox.ErrRunnerUnavailable)
|
||||
if !task.lifecycleSnapshot().Paused || !s.engine.IsPaused(task.ID) {
|
||||
t.Fatal("pause not reflected in lifecycle and engine")
|
||||
}
|
||||
stored, err := m.pg.GetTask(mustTaskID(t, task.ID))
|
||||
if err != nil || stored == nil || !stored.Paused || stored.Queued {
|
||||
t.Fatalf("persisted pause=%+v err=%v", stored, err)
|
||||
}
|
||||
if !errors.Is(context.Cause(ctx), agent.AbortSandboxUnavailable) || !taskExecutionPaused(context.Cause(ctx)) {
|
||||
t.Fatalf("wrong cause: %v", context.Cause(ctx))
|
||||
}
|
||||
if _, err := s.applyTaskControl(task, "resume"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if task.lifecycleSnapshot().Paused || s.engine.IsPaused(task.ID) {
|
||||
t.Fatal("resume left task paused")
|
||||
}
|
||||
stored, err = m.pg.GetTask(mustTaskID(t, task.ID))
|
||||
if err != nil || stored == nil || stored.Paused {
|
||||
t.Fatalf("resume not persisted: %+v %v", stored, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSandboxFailureStaysPausedWhenPersistenceFails(t *testing.T) {
|
||||
m, s, task := newSandboxPauseTestTask(t)
|
||||
ctx := s.engine.execContextFor(context.Background(), task.ID)
|
||||
chat, cancel := context.WithCancelCause(context.Background())
|
||||
defer cancel(context.Canceled)
|
||||
s.chatCancel[task.ID] = cancel
|
||||
if err := m.pg.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.pauseTaskForSandboxFailure(task.ID, sandbox.ErrDockerUnavailable)
|
||||
if !s.engine.IsPaused(task.ID) || !errors.Is(context.Cause(ctx), agent.AbortSandboxUnavailable) {
|
||||
t.Fatal("failed persistence lifted safety pause")
|
||||
}
|
||||
if !errors.Is(context.Cause(chat), agent.AbortSandboxUnavailable) {
|
||||
t.Fatal("main chat still active after safety pause")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSandboxLegacyPauseCanResumeButQueueCannot(t *testing.T) {
|
||||
for _, queued := range []bool{false, true} {
|
||||
name := "legacy"
|
||||
if queued {
|
||||
name = "queue"
|
||||
}
|
||||
t.Run(name, func(t *testing.T) {
|
||||
m, s, task := newSandboxPauseTestTask(t)
|
||||
defer restoreConcurrencySetting(t, m)()
|
||||
if err := m.SetConcurrency(false, defaultConcurrencyLimit); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if queued {
|
||||
if err := m.EnqueueTask(task.ID, "bootstrap"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
s.engine.Pause(task.ID, agent.AbortSandboxUnavailable)
|
||||
_, err := s.applyTaskControl(task, "resume")
|
||||
if queued {
|
||||
if err == nil || !s.engine.IsPaused(task.ID) || !task.lifecycleSnapshot().Queued {
|
||||
t.Fatal("resume bypassed queue barrier")
|
||||
}
|
||||
} else if err != nil || s.engine.IsPaused(task.ID) {
|
||||
t.Fatalf("legacy resume failed: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSandboxFailureHonorsExistingControlBarriers(t *testing.T) {
|
||||
for _, state := range []string{"paused", "terminal", "deleting", "queued"} {
|
||||
t.Run(state, func(t *testing.T) {
|
||||
m, s, task := newSandboxPauseTestTask(t)
|
||||
ctx := s.engine.execContextFor(context.Background(), task.ID)
|
||||
switch state {
|
||||
case "paused":
|
||||
if _, err := s.applyTaskControl(task, "pause"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
case "terminal":
|
||||
if err := m.SetTaskStatus(task.ID, "done"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
case "deleting":
|
||||
s.engine.BeginDelete(task.ID)
|
||||
case "queued":
|
||||
if err := m.EnqueueTask(task.ID, "bootstrap"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.engine.Pause(task.ID, agent.AbortPausedRaceGuard)
|
||||
}
|
||||
s.pauseTaskForSandboxFailure(task.ID, sandbox.ErrRunnerUnavailable)
|
||||
switch state {
|
||||
case "paused":
|
||||
if !errors.Is(context.Cause(ctx), agent.AbortPausedByUser) {
|
||||
t.Fatal("user pause cause replaced")
|
||||
}
|
||||
case "terminal":
|
||||
if s.engine.IsPaused(task.ID) || task.lifecycleSnapshot().Paused {
|
||||
t.Fatal("terminal task paused")
|
||||
}
|
||||
case "deleting":
|
||||
if !errors.Is(context.Cause(ctx), agent.AbortTaskDeleted) || task.lifecycleSnapshot().Paused {
|
||||
t.Fatal("deletion barrier changed")
|
||||
}
|
||||
case "queued":
|
||||
if !task.lifecycleSnapshot().Paused || task.lifecycleSnapshot().Queued {
|
||||
t.Fatal("safety pause did not dequeue task")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -225,12 +225,9 @@ func New(ctx context.Context, m *Manager, skillDir string, dataDir string, keyDi
|
|||
s.engine.SetSandbox(s.sandboxClient, s.sandboxMode, dataDir)
|
||||
if s.sandboxMode != "" {
|
||||
agent.SetSandboxExecutor(&agent.SandboxExecutor{
|
||||
Mode: s.sandboxMode,
|
||||
Runner: s.sandboxClient,
|
||||
OnUnavailable: func(taskID string, err error) {
|
||||
log.Printf("[sandbox] runner unavailable for task %s (%v): pausing task (no local fallback)", taskID, err)
|
||||
s.engine.Pause(taskID, agent.AbortPausedByOrchestrator)
|
||||
},
|
||||
Mode: s.sandboxMode,
|
||||
Runner: s.sandboxClient,
|
||||
OnUnavailable: s.pauseTaskForSandboxFailure,
|
||||
})
|
||||
}
|
||||
s.initSetupToken()
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ package server
|
|||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
|
|
@ -124,9 +125,14 @@ func (s *Server) applyTaskControlWithCause(t *Task, action string, pauseCause er
|
|||
}
|
||||
s.engine.Pause(t.ID, pauseCause)
|
||||
if err := s.m.ApplyTaskPause(t.ID); err != nil {
|
||||
if !wasEnginePaused && !wasQueued {
|
||||
// A safety pause must remain fail-closed if persistence fails. The
|
||||
// operator can retry pause or explicitly resume after recovery.
|
||||
if !wasEnginePaused && !wasQueued && !errors.Is(pauseCause, agent.AbortSandboxUnavailable) {
|
||||
s.engine.Resume(t)
|
||||
}
|
||||
if errors.Is(pauseCause, agent.AbortSandboxUnavailable) {
|
||||
s.cancelTaskChat(t.ID, pauseCause)
|
||||
}
|
||||
return out, err
|
||||
}
|
||||
// Main Agent is independently cancellable. Only cancel its current turn
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue