From 91edce7eac37632273fae4870f55e36485da7d9c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Salavisa?= Date: Sat, 2 May 2026 08:47:04 +0100 Subject: [PATCH] fix(lifecycle): prevent orphaned agent subprocesses from concurrent execution creates (#768) --- .../agent/lifecycle/execution_store.go | 26 ++- .../agent/lifecycle/execution_store_test.go | 80 ++++++++++ .../agent/lifecycle/manager_execution.go | 148 +++++++++++++----- .../agent/lifecycle/manager_execution_test.go | 146 ++++++++++++++--- .../agent/lifecycle/manager_launch.go | 15 +- .../agent/lifecycle/manager_launch_test.go | 75 +++++++++ .../agent/lifecycle/manager_lifecycle.go | 16 +- 7 files changed, 445 insertions(+), 61 deletions(-) create mode 100644 apps/backend/internal/agent/lifecycle/execution_store_test.go diff --git a/apps/backend/internal/agent/lifecycle/execution_store.go b/apps/backend/internal/agent/lifecycle/execution_store.go index 600b30a76d..90418fb12e 100644 --- a/apps/backend/internal/agent/lifecycle/execution_store.go +++ b/apps/backend/internal/agent/lifecycle/execution_store.go @@ -4,6 +4,7 @@ package lifecycle import ( "errors" + "fmt" "sync" v1 "github.com/kandev/kandev/pkg/api/v1" @@ -12,6 +13,14 @@ import ( // ErrExecutionNotFound is returned when an execution doesn't exist in the store. var ErrExecutionNotFound = errors.New("execution not found") +// ErrExecutionAlreadyExistsForSession is returned by Add when the session +// already maps to a different execution. The previous behavior was to silently +// overwrite the bySession index, which orphaned the prior execution: the +// agentctl/subprocess kept running but was unreachable via GetBySessionID, so +// nothing ever cleaned it up. Callers must Remove the prior execution before +// adding a replacement. +var ErrExecutionAlreadyExistsForSession = errors.New("execution already exists for session") + // ExecutionStore provides thread-safe storage and retrieval of agent executions. // It maintains three indexes for efficient lookup by execution ID, session ID, and container ID. type ExecutionStore struct { @@ -33,14 +42,26 @@ func NewExecutionStore() *ExecutionStore { // Add adds an agent execution to all tracking maps. // The execution must have a valid ID. SessionID and ContainerID are optional // but will be indexed if present. -func (s *ExecutionStore) Add(execution *AgentExecution) { +// +// Returns ErrExecutionAlreadyExistsForSession if the session is already mapped +// to a different execution. Callers must explicitly Remove the prior execution +// before adding a replacement — otherwise the prior subprocess is orphaned. +func (s *ExecutionStore) Add(execution *AgentExecution) error { if execution == nil || execution.ID == "" { - return + return fmt.Errorf("execution and execution.ID are required") } s.mu.Lock() defer s.mu.Unlock() + if execution.SessionID != "" { + if existingID, exists := s.bySession[execution.SessionID]; exists && existingID != execution.ID { + return fmt.Errorf("%w: session=%s existing=%s new=%s", + ErrExecutionAlreadyExistsForSession, + execution.SessionID, existingID, execution.ID) + } + } + s.executions[execution.ID] = execution if execution.SessionID != "" { @@ -50,6 +71,7 @@ func (s *ExecutionStore) Add(execution *AgentExecution) { if execution.ContainerID != "" { s.byContainer[execution.ContainerID] = execution.ID } + return nil } // Remove removes an agent execution from all tracking maps. diff --git a/apps/backend/internal/agent/lifecycle/execution_store_test.go b/apps/backend/internal/agent/lifecycle/execution_store_test.go new file mode 100644 index 0000000000..ae9434d2ac --- /dev/null +++ b/apps/backend/internal/agent/lifecycle/execution_store_test.go @@ -0,0 +1,80 @@ +package lifecycle + +import ( + "errors" + "testing" +) + +// TestExecutionStore_AddRejectsDuplicateSession is the regression test for the +// process-leak bug where two paths created executions for the same session +// concurrently and Add silently overwrote the bySession index, orphaning the +// first execution's agent subprocess. +func TestExecutionStore_AddRejectsDuplicateSession(t *testing.T) { + store := NewExecutionStore() + + first := &AgentExecution{ID: "exec-1", SessionID: "session-1"} + if err := store.Add(first); err != nil { + t.Fatalf("first Add: unexpected error: %v", err) + } + + second := &AgentExecution{ID: "exec-2", SessionID: "session-1"} + err := store.Add(second) + if !errors.Is(err, ErrExecutionAlreadyExistsForSession) { + t.Fatalf("second Add: want ErrExecutionAlreadyExistsForSession, got %v", err) + } + + got, ok := store.GetBySessionID("session-1") + if !ok { + t.Fatalf("GetBySessionID: not found") + } + if got.ID != "exec-1" { + t.Errorf("bySession index: want exec-1, got %s (overwrite was supposed to be rejected)", got.ID) + } + // Second execution must not be in the executions map either — otherwise + // it'd live as an unreachable orphan. + if _, ok := store.Get("exec-2"); ok { + t.Errorf("Get(exec-2): rejected execution must not be tracked") + } +} + +func TestExecutionStore_AddSameExecutionTwiceIsIdempotent(t *testing.T) { + store := NewExecutionStore() + + exec := &AgentExecution{ID: "exec-1", SessionID: "session-1"} + if err := store.Add(exec); err != nil { + t.Fatalf("first Add: %v", err) + } + if err := store.Add(exec); err != nil { + t.Errorf("re-adding the SAME execution must be a no-op, got %v", err) + } +} + +func TestExecutionStore_AddReplaceAfterRemove(t *testing.T) { + store := NewExecutionStore() + + first := &AgentExecution{ID: "exec-1", SessionID: "session-1"} + if err := store.Add(first); err != nil { + t.Fatalf("first Add: %v", err) + } + store.Remove("exec-1") + + second := &AgentExecution{ID: "exec-2", SessionID: "session-1"} + if err := store.Add(second); err != nil { + t.Errorf("Add after Remove must succeed, got %v", err) + } + got, _ := store.GetBySessionID("session-1") + if got == nil || got.ID != "exec-2" { + t.Errorf("after Remove+Add: want exec-2, got %v", got) + } +} + +func TestExecutionStore_AddNoSessionIDAlwaysSucceeds(t *testing.T) { + store := NewExecutionStore() + + if err := store.Add(&AgentExecution{ID: "exec-a"}); err != nil { + t.Errorf("Add without SessionID: %v", err) + } + if err := store.Add(&AgentExecution{ID: "exec-b"}); err != nil { + t.Errorf("Add without SessionID (second): %v", err) + } +} diff --git a/apps/backend/internal/agent/lifecycle/manager_execution.go b/apps/backend/internal/agent/lifecycle/manager_execution.go index 96f5cf6d78..beeae5be49 100644 --- a/apps/backend/internal/agent/lifecycle/manager_execution.go +++ b/apps/backend/internal/agent/lifecycle/manager_execution.go @@ -35,13 +35,11 @@ func (m *Manager) GetOrEnsureExecution(ctx context.Context, sessionID string) (* return execution, nil } - // Slow path: create on-demand, deduplicated by singleflight + // Slow path: create on-demand, deduplicated by sessionID-keyed singleflight. + // Use ensureWorkspaceExecutionLocked (not EnsureWorkspaceExecutionForSession) + // to avoid recursing into the same singleflight slot we already hold. v, err, _ := m.ensureExecutionGroup.Do(sessionID, func() (interface{}, error) { - // Double-check after acquiring singleflight slot - if execution, exists := m.executionStore.GetBySessionID(sessionID); exists { - return execution, nil - } - return m.EnsureWorkspaceExecutionForSession(ctx, "", sessionID) + return m.ensureWorkspaceExecutionLocked(ctx, "", sessionID) }) if err != nil { return nil, err @@ -51,6 +49,14 @@ func (m *Manager) GetOrEnsureExecution(ctx context.Context, sessionID string) (* // GetOrEnsureExecutionForEnvironment returns an execution for a task environment, // creating one on-demand from the workspace info provider when needed. +// +// Important: this MUST share the session-keyed singleflight bucket with +// GetOrEnsureExecution(sessionID) and EnsureWorkspaceExecutionForSession. +// A previous version keyed by `"env:" + envID`, which let a concurrent +// session-keyed call race past it (each path observed "no execution" for its +// own key, both called createExecution, both ExecutionStore.Add, the second +// silently overwrote the bySession index, and the first execution's +// agent subprocess was orphaned). See `ErrExecutionAlreadyExistsForSession`. func (m *Manager) GetOrEnsureExecutionForEnvironment(ctx context.Context, taskEnvironmentID string) (*AgentExecution, error) { if taskEnvironmentID == "" { return nil, fmt.Errorf("task_environment_id is required") @@ -60,32 +66,38 @@ func (m *Manager) GetOrEnsureExecutionForEnvironment(ctx context.Context, taskEn return execution, nil } - groupKey := "env:" + taskEnvironmentID - v, err, _ := m.ensureExecutionGroup.Do(groupKey, func() (interface{}, error) { - if execution, exists := m.executionStore.GetByTaskEnvironmentID(taskEnvironmentID); exists { + if m.workspaceInfoProvider == nil { + return nil, fmt.Errorf("workspace info provider not configured") + } + info, err := m.workspaceInfoProvider.GetWorkspaceInfoForEnvironment(ctx, taskEnvironmentID) + if err != nil { + return nil, fmt.Errorf("failed to get workspace info for environment %s: %w", taskEnvironmentID, err) + } + if info == nil { + return nil, fmt.Errorf("task environment %s not found", taskEnvironmentID) + } + if info.TaskEnvironmentID == "" { + return nil, fmt.Errorf("task environment %s has no task_environment_id", taskEnvironmentID) + } + if info.TaskEnvironmentID != taskEnvironmentID { + return nil, fmt.Errorf("workspace info resolved environment %s, want %s", info.TaskEnvironmentID, taskEnvironmentID) + } + if info.WorkspacePath == "" { + return nil, fmt.Errorf("%w: task environment %s has no workspace path yet", ErrSessionWorkspaceNotReady, taskEnvironmentID) + } + if info.SessionID == "" { + return nil, fmt.Errorf("task environment %s has no task session", taskEnvironmentID) + } + + // Share the sessionID-keyed bucket so we deduplicate against any concurrent + // GetOrEnsureExecution(sessionID) / EnsureWorkspaceExecutionForSession for + // the same session. + v, err, _ := m.ensureExecutionGroup.Do(info.SessionID, func() (interface{}, error) { + if execution, exists := m.executionStore.GetBySessionID(info.SessionID); exists { return execution, nil } - if m.workspaceInfoProvider == nil { - return nil, fmt.Errorf("workspace info provider not configured") - } - info, err := m.workspaceInfoProvider.GetWorkspaceInfoForEnvironment(ctx, taskEnvironmentID) - if err != nil { - return nil, fmt.Errorf("failed to get workspace info for environment %s: %w", taskEnvironmentID, err) - } - if info == nil { - return nil, fmt.Errorf("task environment %s not found", taskEnvironmentID) - } - if info.TaskEnvironmentID == "" { - return nil, fmt.Errorf("task environment %s has no task_environment_id", taskEnvironmentID) - } - if info.TaskEnvironmentID != taskEnvironmentID { - return nil, fmt.Errorf("workspace info resolved environment %s, want %s", info.TaskEnvironmentID, taskEnvironmentID) - } - if info.WorkspacePath == "" { - return nil, fmt.Errorf("%w: task environment %s has no workspace path yet", ErrSessionWorkspaceNotReady, taskEnvironmentID) - } - if info.SessionID == "" { - return nil, fmt.Errorf("task environment %s has no task session", taskEnvironmentID) + if execution, exists := m.executionStore.GetByTaskEnvironmentID(taskEnvironmentID); exists { + return execution, nil } return m.createExecution(ctx, info.TaskID, info) }) @@ -99,13 +111,40 @@ func (m *Manager) GetOrEnsureExecutionForEnvironment(ctx context.Context, taskEn // This is used when the frontend provides a session ID (e.g., from URL path /task/[id]/[sessionId]). // If an execution already exists for the session, it returns it. Otherwise, it creates a new execution // using the session's workspace configuration from the database. +// +// Concurrent calls (including from GetOrEnsureExecution and +// GetOrEnsureExecutionForEnvironment) are deduplicated via the same +// sessionID-keyed singleflight bucket so they cannot race past their +// individual check-then-act guards and create duplicate executions. func (m *Manager) EnsureWorkspaceExecutionForSession(ctx context.Context, taskID, sessionID string) (*AgentExecution, error) { - // Check if execution already exists + if sessionID == "" { + return nil, fmt.Errorf("session_id is required") + } + + // Fast path: execution already in memory + if execution, exists := m.executionStore.GetBySessionID(sessionID); exists { + return execution, nil + } + + v, err, _ := m.ensureExecutionGroup.Do(sessionID, func() (interface{}, error) { + return m.ensureWorkspaceExecutionLocked(ctx, taskID, sessionID) + }) + if err != nil { + return nil, err + } + return v.(*AgentExecution), nil +} + +// ensureWorkspaceExecutionLocked is the body of EnsureWorkspaceExecutionForSession +// run inside the sessionID-keyed singleflight bucket. Callers other than +// EnsureWorkspaceExecutionForSession must already hold the singleflight slot. +func (m *Manager) ensureWorkspaceExecutionLocked(ctx context.Context, taskID, sessionID string) (*AgentExecution, error) { + // Double-check after acquiring the slot — a peer in the same group may have + // finished while we were waiting. if execution, exists := m.executionStore.GetBySessionID(sessionID); exists { return execution, nil } - // Need to create a new execution - get workspace info for the specific session if m.workspaceInfoProvider == nil { return nil, fmt.Errorf("workspace info provider not configured") } @@ -114,6 +153,9 @@ func (m *Manager) EnsureWorkspaceExecutionForSession(ctx context.Context, taskID if err != nil { return nil, fmt.Errorf("failed to get workspace info for session %s: %w", sessionID, err) } + if info == nil { + return nil, fmt.Errorf("session %s not found", sessionID) + } // Resolve taskID from provider when caller doesn't have it (e.g., GetOrEnsureExecution) if taskID == "" { @@ -346,9 +388,6 @@ func (m *Manager) createExecution(ctx context.Context, taskID string, info *Work execution := runtimeInstance.ToAgentExecution(req) execution.RuntimeName = string(rt.Name()) - // Persist agentctl auth token from handshake (Docker/remote executors) - m.persistAuthToken(ctx, runtimeInstance, execution) - // Set the ACP session ID for session resumption if info.ACPSessionID != "" { execution.ACPSessionID = info.ACPSessionID @@ -363,7 +402,23 @@ func (m *Manager) createExecution(ctx context.Context, taskID string, info *Work execution.agentctl.SetTraceContext(execution.SessionTraceContext()) } - m.executionStore.Add(execution) + if addErr := m.executionStore.Add(execution); addErr != nil { + // Lost a race: another path created an execution for this session + // between our check and our Add. Roll back the runtime instance we + // just spawned (otherwise its subprocess is orphaned) and return the + // winner so the caller observes a single execution per session. + if errors.Is(addErr, ErrExecutionAlreadyExistsForSession) { + m.rollbackRacedExecution(ctx, rt, runtimeInstance, execution) + if existing, ok := m.executionStore.GetBySessionID(info.SessionID); ok { + return existing, nil + } + } + return nil, fmt.Errorf("failed to register execution: %w", addErr) + } + + // Persist agentctl auth token only after the execution is tracked, so a + // race-lost rollback never leaves an orphaned secret in the store. + m.persistAuthToken(ctx, runtimeInstance, execution) go m.pollOneRemoteStatus(context.Background(), execution) go m.waitForAgentctlReady(execution) @@ -377,6 +432,27 @@ func (m *Manager) createExecution(ctx context.Context, taskID string, info *Work return execution, nil } +// rollbackRacedExecution tears down an execution that lost a session-conflict +// race in the store. Without this the runtime instance (agentctl + agent +// subprocess if any) keeps running with no tracking entry, and no cleanup path +// will ever find it. +func (m *Manager) rollbackRacedExecution(ctx context.Context, rt ExecutorBackend, runtimeInstance *ExecutorInstance, execution *AgentExecution) { + m.logger.Warn("rolling back duplicate execution after session-conflict race", + zap.String("execution_id", execution.ID), + zap.String("session_id", execution.SessionID)) + if rt != nil && runtimeInstance != nil { + if stopErr := rt.StopInstance(ctx, runtimeInstance, false); stopErr != nil { + m.logger.Warn("failed to stop raced runtime instance during rollback", + zap.String("execution_id", execution.ID), + zap.Error(stopErr)) + } + } + if execution.agentctl != nil { + execution.agentctl.Close() + } + execution.EndSessionSpan() +} + // MetadataKeyAuthTokenSecret is the metadata key for the encrypted agentctl auth token secret ID. const MetadataKeyAuthTokenSecret = "env_secret_id_AGENTCTL_AUTH_TOKEN" diff --git a/apps/backend/internal/agent/lifecycle/manager_execution_test.go b/apps/backend/internal/agent/lifecycle/manager_execution_test.go index 6e0a73a032..35763d7da0 100644 --- a/apps/backend/internal/agent/lifecycle/manager_execution_test.go +++ b/apps/backend/internal/agent/lifecycle/manager_execution_test.go @@ -8,6 +8,7 @@ import ( "net/http" "net/http/httptest" "net/url" + "runtime" "strconv" "sync" "sync/atomic" @@ -360,38 +361,43 @@ func TestGetOrEnsureExecutionForEnvironment(t *testing.T) { }, }, }) - backend.delay = 50 * time.Millisecond + backend.entered = make(chan struct{}, 1) + backend.barrier = make(chan struct{}) - var wg sync.WaitGroup - errs := make(chan error, 2) - ids := make(chan string, 2) + type result struct { + id string + err error + } + results := make(chan result, 2) for range 2 { - wg.Add(1) go func() { - defer wg.Done() execution, err := mgr.GetOrEnsureExecutionForEnvironment(context.Background(), "env-new") if err != nil { - errs <- err + results <- result{"", err} return } - ids <- execution.ID + results <- result{execution.ID, nil} }() } - wg.Wait() - close(errs) - close(ids) - for err := range errs { - t.Fatalf("GetOrEnsureExecutionForEnvironment returned error: %v", err) + select { + case <-backend.entered: + case <-time.After(2 * time.Second): + t.Fatal("timed out waiting for CreateInstance to start") } + runtime.Gosched() + close(backend.barrier) + var firstID string - for id := range ids { - if firstID == "" { - firstID = id - continue + for range 2 { + r := <-results + if r.err != nil { + t.Fatalf("GetOrEnsureExecutionForEnvironment returned error: %v", r.err) } - if id != firstID { - t.Errorf("execution ID = %q, want %q", id, firstID) + if firstID == "" { + firstID = r.id + } else if r.id != firstID { + t.Errorf("execution ID = %q, want %q (singleflight must return same execution)", r.id, firstID) } } if backend.createCount.Load() != 1 { @@ -544,11 +550,29 @@ type createInstanceExecutor struct { MockExecutor client *agentctl.Client createCount atomic.Int32 + stopCount atomic.Int32 delay time.Duration + // Barrier-based deterministic synchronization for race tests. + // Set entered (buffered 1) to receive a signal when CreateInstance begins. + // Set barrier (unbuffered, closed to release) to block until the test is ready. + entered chan struct{} + barrier chan struct{} } func (e *createInstanceExecutor) CreateInstance(ctx context.Context, req *ExecutorCreateRequest) (*ExecutorInstance, error) { - if e.delay > 0 { + if e.entered != nil { + select { + case e.entered <- struct{}{}: + default: + } + } + if e.barrier != nil { + select { + case <-ctx.Done(): + return nil, ctx.Err() + case <-e.barrier: + } + } else if e.delay > 0 { select { case <-ctx.Done(): return nil, ctx.Err() @@ -566,6 +590,11 @@ func (e *createInstanceExecutor) CreateInstance(ctx context.Context, req *Execut }, nil } +func (e *createInstanceExecutor) StopInstance(ctx context.Context, instance *ExecutorInstance, force bool) error { + e.stopCount.Add(1) + return nil +} + func newEnvironmentExecutionTestManager(t *testing.T, provider WorkspaceInfoProvider) (*Manager, *createInstanceExecutor) { t.Helper() log := newTestLogger() @@ -665,3 +694,80 @@ func (p *slowWorkspaceInfoProvider) GetWorkspaceInfoForEnvironment(_ context.Con } return p.info, nil } + +// TestGetOrEnsureExecution_DedupAcrossEnvAndSessionPaths is the regression +// test for the orphaned-claude-acp leak introduced by PR #758, which +// keyed GetOrEnsureExecutionForEnvironment by `"env:" + envID` instead of +// the sessionID. Two concurrent paths for the same session each saw +// "no execution exists" for their own key, both called createExecution, +// and ExecutionStore.Add silently overwrote the bySession index — orphaning +// the first execution's claude-agent-acp subprocess. +// +// After the fix, both paths share the sessionID-keyed singleflight bucket, +// so concurrent callers must observe the same execution and CreateInstance +// must be invoked exactly once. +func TestGetOrEnsureExecution_DedupAcrossEnvAndSessionPaths(t *testing.T) { + mgr, backend := newEnvironmentExecutionTestManager(t, &mockWorkspaceInfoProvider{ + infos: map[string]*WorkspaceInfo{ + "session-1": { + TaskID: "task-1", + SessionID: "session-1", + TaskEnvironmentID: "env-1", + WorkspacePath: "/workspace/task-1", + AgentID: "auggie", + }, + }, + envInfos: map[string]*WorkspaceInfo{ + "env-1": { + TaskID: "task-1", + SessionID: "session-1", + TaskEnvironmentID: "env-1", + WorkspacePath: "/workspace/task-1", + AgentID: "auggie", + }, + }, + }) + // Use a barrier channel so that the test is deterministic: CreateInstance + // blocks until we explicitly release it, giving the env-path goroutine + // time to join the same singleflight flight before we let it complete. + backend.entered = make(chan struct{}, 1) + backend.barrier = make(chan struct{}) + + type result struct { + exec *AgentExecution + err error + } + results := make(chan result, 2) + + go func() { + exec, err := mgr.GetOrEnsureExecution(context.Background(), "session-1") + results <- result{exec, err} + }() + go func() { + exec, err := mgr.GetOrEnsureExecutionForEnvironment(context.Background(), "env-1") + results <- result{exec, err} + }() + + // Wait for the singleflight winner to enter CreateInstance, then yield so + // the other goroutine can join the same flight before we release the barrier. + select { + case <-backend.entered: + case <-time.After(2 * time.Second): + t.Fatal("timed out waiting for CreateInstance to start") + } + runtime.Gosched() + close(backend.barrier) + + r1 := <-results + r2 := <-results + if r1.err != nil || r2.err != nil { + t.Fatalf("unexpected errors: %v / %v", r1.err, r2.err) + } + if r1.exec.ID != r2.exec.ID { + t.Errorf("execution IDs differ: session-path=%s env-path=%s — duplicate executions created (the leak bug)", + r1.exec.ID, r2.exec.ID) + } + if got := backend.createCount.Load(); got != 1 { + t.Errorf("CreateInstance called %d times, want 1 (singleflight should deduplicate)", got) + } +} diff --git a/apps/backend/internal/agent/lifecycle/manager_launch.go b/apps/backend/internal/agent/lifecycle/manager_launch.go index d76eb09133..4613a2c525 100644 --- a/apps/backend/internal/agent/lifecycle/manager_launch.go +++ b/apps/backend/internal/agent/lifecycle/manager_launch.go @@ -2,6 +2,7 @@ package lifecycle import ( "context" + "errors" "fmt" "os" "os/exec" @@ -535,8 +536,18 @@ func (m *Manager) Launch(ctx context.Context, req *LaunchRequest) (*AgentExecuti execution.AgentCommand = cmds.initial execution.ContinueCommand = cmds.continue_ - // 8. Track the execution - m.executionStore.Add(execution) + // 8. Track the execution. If we lost a session-conflict race (another path + // added an execution for this session between our check at step 3 and now), + // roll back the runtime instance we just spawned and surface the same + // "already running" error the step-3 check would have produced — otherwise + // the runtime + agent subprocess would be orphaned. + if addErr := m.executionStore.Add(execution); addErr != nil { + if errors.Is(addErr, ErrExecutionAlreadyExistsForSession) { + m.rollbackRacedExecution(ctx, rt, execInstance, execution) + return nil, fmt.Errorf("session %q already has an agent running (race resolved during register)", req.SessionID) + } + return nil, fmt.Errorf("failed to register execution: %w", addErr) + } go m.pollOneRemoteStatus(context.Background(), execution) // 9. Publish agent.started event diff --git a/apps/backend/internal/agent/lifecycle/manager_launch_test.go b/apps/backend/internal/agent/lifecycle/manager_launch_test.go index f4509715f5..d35568dc9c 100644 --- a/apps/backend/internal/agent/lifecycle/manager_launch_test.go +++ b/apps/backend/internal/agent/lifecycle/manager_launch_test.go @@ -4,12 +4,15 @@ import ( "context" "strings" "testing" + "time" "github.com/stretchr/testify/require" "github.com/kandev/kandev/internal/agent/agents" "github.com/kandev/kandev/internal/agent/executor" settingsmodels "github.com/kandev/kandev/internal/agent/settings/models" + agentctl "github.com/kandev/kandev/internal/agentctl/client" + "github.com/kandev/kandev/internal/common/logger" ) // resumeTestAgent is a minimal agent with a BuildCommand that respects the @@ -203,3 +206,75 @@ func TestLaunchResolveWorkspacePath_NonEphemeralSkipsQuickChatDir(t *testing.T) workspacePath, _, _, _ := mgr.launchResolveWorkspacePath(context.Background(), req) require.Empty(t, workspacePath, "non-ephemeral task without repo should NOT get a quick-chat workspace") } + +// TestLaunch_RaceRollback exercises the race window between the step-3 duplicate +// session pre-check and the step-8 executionStore.Add in Launch. A barrier inside +// CreateInstance keeps the goroutine in the race window; the test injects a +// conflicting execution into the store and then releases the barrier. Launch must +// roll back the runtime instance it created (StopInstance called once) and return +// a "race resolved during register" error instead of leaking an orphaned subprocess. +func TestLaunch_RaceRollback(t *testing.T) { + log, _ := logger.NewLogger(logger.LoggingConfig{Level: "error", Format: "json"}) + execRegistry := NewExecutorRegistry(log) + + entered := make(chan struct{}, 1) + barrier := make(chan struct{}) + backend := &createInstanceExecutor{ + MockExecutor: MockExecutor{name: executor.NameStandalone}, + client: (*agentctl.Client)(nil), + entered: entered, + barrier: barrier, + } + execRegistry.Register(backend) + + mgr := NewManager( + newTestRegistry(), &MockEventBus{}, execRegistry, + &MockCredentialsManager{}, &MockProfileResolver{}, nil, + ExecutorFallbackWarn, "", log, + ) + mgr.dataDir = t.TempDir() + t.Cleanup(func() { close(mgr.stopCh) }) + + req := &LaunchRequest{ + TaskID: "task-1", + SessionID: "session-race", + AgentProfileID: "profile-1", + IsEphemeral: true, // gives Launch a workspace path without a real repo + } + + errCh := make(chan error, 1) + go func() { + _, err := mgr.Launch(context.Background(), req) + errCh <- err + }() + + // Wait for CreateInstance to begin (the goroutine is now past the step-3 + // pre-check and inside the race window). + select { + case <-entered: + case <-time.After(5 * time.Second): + t.Fatal("timed out waiting for CreateInstance to start") + } + + // Inject a conflicting execution for the same session. + _ = mgr.executionStore.Add(&AgentExecution{ + ID: "exec-injected", + SessionID: "session-race", + TaskID: "task-1", + }) + + // Release CreateInstance — Launch will now proceed to Add and discover + // the conflict, triggering rollbackRacedExecution. + close(barrier) + + err := <-errCh + if err == nil { + t.Fatal("expected error from race rollback, got nil") + } + if !strings.Contains(err.Error(), "race resolved during register") { + t.Errorf("unexpected error message: %v", err) + } + if got := backend.stopCount.Load(); got != 1 { + t.Errorf("StopInstance called %d times, want 1 (runtime instance must be stopped on rollback)", got) + } +} diff --git a/apps/backend/internal/agent/lifecycle/manager_lifecycle.go b/apps/backend/internal/agent/lifecycle/manager_lifecycle.go index 079aca54cf..4cf4a11b99 100644 --- a/apps/backend/internal/agent/lifecycle/manager_lifecycle.go +++ b/apps/backend/internal/agent/lifecycle/manager_lifecycle.go @@ -76,7 +76,21 @@ func (m *Manager) Start(ctx context.Context) error { execution.SessionTraceContext(), execution.TaskID, execution.SessionID, execution.ID, ) - m.executionStore.Add(execution) + if err := m.executionStore.Add(execution); err != nil { + // Should not happen at startup — duplicate sessions in the recovery + // list signal a DB consistency issue, not a normal race. Log loudly + // and skip; the first one to land wins. + m.logger.Error("skipping duplicate execution during recovery", + zap.String("execution_id", execution.ID), + zap.String("session_id", execution.SessionID), + zap.Error(err)) + if execution.agentctl != nil { + execution.agentctl.Close() + } + execution.EndSessionSpan() + initSpan.End() + continue + } // Reconnect to workspace streams (shell, git, file changes) in background // This is needed so shell.input, git status, etc. work after backend restart