fix: retain session failures across recovery surfaces (#3669)
This commit is contained in:
@@ -1432,6 +1432,27 @@ func (a *messageCreatorAdapter) CreateSessionMessage(ctx context.Context, taskID
|
||||
return err
|
||||
}
|
||||
|
||||
// CreateSessionMessageIdempotent persists a lifecycle/status message with a
|
||||
// deterministic ID so a replayed failure event cannot add another transcript
|
||||
// entry for the same failure stamp.
|
||||
func (a *messageCreatorAdapter) CreateSessionMessageIdempotent(
|
||||
ctx context.Context,
|
||||
messageID, taskID, content, agentSessionID, messageType, turnID string,
|
||||
metadata map[string]interface{}, requestsInput bool,
|
||||
) error {
|
||||
_, err := a.svc.CreateMessageIdempotent(ctx, messageID, &taskservice.CreateMessageRequest{
|
||||
TaskSessionID: agentSessionID,
|
||||
TaskID: taskID,
|
||||
TurnID: turnID,
|
||||
Content: content,
|
||||
AuthorType: "agent",
|
||||
Type: messageType,
|
||||
Metadata: metadata,
|
||||
RequestsInput: requestsInput,
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
// CreatePermissionRequestMessage creates a message for a permission request
|
||||
func (a *messageCreatorAdapter) CreatePermissionRequestMessage(ctx context.Context, taskID, sessionID, requestID, pendingID, toolCallID, title, turnID string, options []map[string]interface{}, actionType string, actionDetails map[string]interface{}) (string, error) {
|
||||
metadata := map[string]interface{}{
|
||||
|
||||
@@ -510,6 +510,7 @@ func loadTaskSessionObservations(
|
||||
}
|
||||
if lastError, ok := models.LoadLastAgentError(session.Metadata); ok && !lastError.IsDismissed() {
|
||||
input.ActiveError = &statussummary.ActiveErrorSummary{
|
||||
Scope: models.ErrorScopeSession,
|
||||
SessionID: session.ID,
|
||||
TaskRepositoryID: lastError.TaskRepositoryID,
|
||||
ExecutionID: lastError.ExecutionID,
|
||||
@@ -551,10 +552,13 @@ func loadTaskLaunchErrorObservation(
|
||||
return statussummary.TaskLaunchErrorObservation{
|
||||
Observed: true,
|
||||
Error: &statussummary.ActiveErrorSummary{
|
||||
Scope: models.ErrorScopeTask,
|
||||
SessionID: errorValue.SessionID,
|
||||
TaskRepositoryID: errorValue.TaskRepositoryID,
|
||||
Stamp: errorValue.Stamp(),
|
||||
OccurredAt: errorValue.OccurredAt,
|
||||
Preview: errorValue.Message,
|
||||
Details: errorValue.Details,
|
||||
Category: errorValue.Code,
|
||||
RecoveryActions: errorValue.RecoveryActions,
|
||||
},
|
||||
|
||||
@@ -230,6 +230,20 @@ func (a *testMessageCreatorAdapter) CreateSessionMessage(ctx context.Context, ta
|
||||
return err
|
||||
}
|
||||
|
||||
func (a *testMessageCreatorAdapter) CreateSessionMessageIdempotent(ctx context.Context, messageID, taskID, content, agentSessionID, messageType, turnID string, metadata map[string]interface{}, requestsInput bool) error {
|
||||
_, err := a.svc.CreateMessageIdempotent(ctx, messageID, &taskservice.CreateMessageRequest{
|
||||
TaskSessionID: agentSessionID,
|
||||
TaskID: taskID,
|
||||
TurnID: turnID,
|
||||
Content: content,
|
||||
AuthorType: "agent",
|
||||
Type: messageType,
|
||||
Metadata: metadata,
|
||||
RequestsInput: requestsInput,
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
func (a *testMessageCreatorAdapter) CreatePermissionRequestMessage(ctx context.Context, taskID, sessionID, requestID, pendingID, toolCallID, title, turnID string, options []map[string]interface{}, actionType string, actionDetails map[string]interface{}) (string, error) {
|
||||
metadata := map[string]interface{}{
|
||||
"request_id": requestID,
|
||||
|
||||
@@ -21,6 +21,7 @@ import (
|
||||
"github.com/kandev/kandev/internal/orchestrator/watcher"
|
||||
"github.com/kandev/kandev/internal/task/models"
|
||||
"github.com/kandev/kandev/internal/task/plancomments"
|
||||
"github.com/kandev/kandev/internal/worktree"
|
||||
v1 "github.com/kandev/kandev/pkg/api/v1"
|
||||
)
|
||||
|
||||
@@ -2729,12 +2730,11 @@ func (s *Service) handleRecoverableFailureLockedState(ctx context.Context, data
|
||||
s.completeTurnForSession(ctx, data.SessionID)
|
||||
s.persistLastAgentError(ctx, data)
|
||||
|
||||
// Create a status message with recovery action metadata.
|
||||
// Skipped for office sessions: the office task page renders its
|
||||
// own structured RunErrorEntry sourced from the FAILED session,
|
||||
// and including the legacy ActionMessage would double-show the
|
||||
// red banner (top-level + inside the embedded chat panel).
|
||||
if s.messageCreator != nil && !s.isOfficeSession(ctx, data.SessionID) {
|
||||
// Create a status message with recovery action metadata. Session failures
|
||||
// are chronological transcript entries for every task surface, including
|
||||
// Office sessions. Only the current metadata record owns recovery controls;
|
||||
// the persisted message remains as history after it is retired.
|
||||
if s.messageCreator != nil {
|
||||
s.createRecoveryStatusMessage(ctx, data)
|
||||
}
|
||||
|
||||
@@ -2796,17 +2796,12 @@ func (s *Service) handleRecoverableFailureLockedState(ctx context.Context, data
|
||||
}
|
||||
|
||||
func (s *Service) persistLastAgentError(ctx context.Context, data watcher.AgentEventData) error {
|
||||
errMsg := data.ErrorMessage
|
||||
if errMsg == "" {
|
||||
errMsg = defaultAgentFailedMessage
|
||||
}
|
||||
errMsg := agentFailureMessage(data)
|
||||
details := routingerr.Sanitize(data.FailureDetails)
|
||||
// Keep this metadata until the user dismisses the UI notice locally or a
|
||||
// later recoverable failure replaces it. A successful turn should not erase
|
||||
// the investigation breadcrumb that explains why the task was marked REVIEW.
|
||||
lastErr := models.LastAgentError{
|
||||
Message: errMsg,
|
||||
OccurredAt: time.Now().UTC(),
|
||||
Scope: models.ErrorScopeSession,
|
||||
AgentExecutionID: data.AgentExecutionID,
|
||||
ExecutionID: data.AgentExecutionID,
|
||||
Phase: data.Phase,
|
||||
@@ -2815,7 +2810,7 @@ func (s *Service) persistLastAgentError(ctx context.Context, data watcher.AgentE
|
||||
RemediationURL: providerRemediationURL(data),
|
||||
Code: data.FailureCode,
|
||||
Details: details,
|
||||
StampValue: data.ErrorStamp,
|
||||
StampValue: agentFailureStamp(data),
|
||||
}
|
||||
if err := s.repo.SetSessionMetadataKey(ctx, data.SessionID, models.SessionMetaKeyLastAgentError, lastErr); err != nil {
|
||||
s.logger.Warn("failed to persist last agent error",
|
||||
@@ -2829,6 +2824,7 @@ func (s *Service) persistLastAgentError(ctx context.Context, data watcher.AgentE
|
||||
"task_id": data.TaskID,
|
||||
"session_id": data.SessionID,
|
||||
"active": true,
|
||||
"scope": models.ErrorScopeSession,
|
||||
"message": lastErr.Message,
|
||||
"occurred_at": lastErr.OccurredAt.Format(time.RFC3339Nano),
|
||||
"stamp": lastErr.Stamp(),
|
||||
@@ -2868,39 +2864,160 @@ func (s *Service) persistLastAgentError(ctx context.Context, data watcher.AgentE
|
||||
return nil
|
||||
}
|
||||
|
||||
// clearRecoveredAgentError drops a session's stored agent failure once the agent
|
||||
// completes a turn, and publishes the inactive error event so open clients drop
|
||||
// the red error affordance.
|
||||
//
|
||||
// persistLastAgentError deliberately keeps the record across a successful turn
|
||||
// as an investigation breadcrumb, but nothing ever retired it, so a failure the
|
||||
// agent recovered from weeks ago still read as live: every path that re-derives
|
||||
// task status from session metadata (a status-summary rebuild, a backend
|
||||
// restart, a later session event) put it straight back. The failure also lands
|
||||
// in the transcript as a recovery message, which is where an investigation
|
||||
// actually looks, so the metadata copy is not the durable record.
|
||||
//
|
||||
// Writes JSON null rather than a delete: LoadLastAgentError already treats that
|
||||
// as absent, so no new repository surface is needed.
|
||||
func agentFailureMessage(data watcher.AgentEventData) string {
|
||||
if strings.TrimSpace(data.ErrorMessage) != "" {
|
||||
return data.ErrorMessage
|
||||
}
|
||||
return defaultAgentFailedMessage
|
||||
}
|
||||
|
||||
func agentFailureStamp(data watcher.AgentEventData) string {
|
||||
if stamp := strings.TrimSpace(data.ErrorStamp); stamp != "" {
|
||||
return stamp
|
||||
}
|
||||
return models.StableLaunchErrorStamp(
|
||||
data.TaskID,
|
||||
data.SessionID,
|
||||
data.AgentExecutionID,
|
||||
data.AttemptID,
|
||||
data.FailureCode,
|
||||
agentFailureMessage(data),
|
||||
)
|
||||
}
|
||||
|
||||
// launchFailureIsTaskOwned reports whether the launch producer proved that a
|
||||
// failure affects the task's shared workspace or workflow. Generic launch
|
||||
// errors remain session-owned so a profile-specific startup failure cannot
|
||||
// surface recovery controls on another session.
|
||||
func launchFailureIsTaskOwned(lastError models.LastAgentError, launchErr error) bool {
|
||||
if lastError.Scope == models.ErrorScopeTask {
|
||||
return true
|
||||
}
|
||||
switch lastError.Code {
|
||||
case models.LaunchErrorCategoryBaseBranchMissing,
|
||||
models.LaunchErrorCategoryDefaultBranchUnresolved,
|
||||
models.LaunchErrorCategoryWorkspaceCheckoutFailed,
|
||||
models.LaunchErrorCategoryPRAlreadyClosed:
|
||||
return true
|
||||
case models.LaunchErrorCategoryGenericLaunchFailure:
|
||||
var recoveryErr *worktree.WorktreeRecoveryError
|
||||
return errors.As(launchErr, &recoveryErr)
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// handleLaunchFailed projects shared workspace failures at task scope while
|
||||
// retaining profile-specific startup failures on their originating session.
|
||||
// The executor has already persisted the source session marker when this
|
||||
// callback runs.
|
||||
func (s *Service) handleLaunchFailed(
|
||||
ctx context.Context,
|
||||
taskID, sessionID, _ string,
|
||||
launchErr error,
|
||||
) {
|
||||
session, err := s.repo.GetTaskSession(ctx, sessionID)
|
||||
if err != nil || session == nil {
|
||||
if err != nil {
|
||||
s.logger.Warn("failed to load launch failure session",
|
||||
zap.String("task_id", taskID),
|
||||
zap.String("session_id", sessionID),
|
||||
zap.Error(err))
|
||||
}
|
||||
return
|
||||
}
|
||||
lastError, found := models.LoadLastAgentError(session.Metadata)
|
||||
if !found || lastError.IsDismissed() {
|
||||
return
|
||||
}
|
||||
if !launchFailureIsTaskOwned(lastError, launchErr) {
|
||||
if err := s.persistBootstrapFailureMessage(ctx, taskID, sessionID, session.AgentExecutionID, lastError); err != nil {
|
||||
s.logger.Warn("failed to persist session-owned launch failure history",
|
||||
zap.String("task_id", taskID),
|
||||
zap.String("session_id", sessionID),
|
||||
zap.Error(err))
|
||||
}
|
||||
return
|
||||
}
|
||||
taskError := models.TaskLaunchError{
|
||||
Message: lastError.Message,
|
||||
OccurredAt: lastError.OccurredAt,
|
||||
Scope: models.ErrorScopeTask,
|
||||
SessionID: sessionID,
|
||||
Code: lastError.Code,
|
||||
Details: lastError.Details,
|
||||
RecoveryActions: lastError.RecoveryActions,
|
||||
TaskRepositoryID: lastError.TaskRepositoryID,
|
||||
StampValue: lastError.Stamp(),
|
||||
}
|
||||
if !s.persistTaskLaunchError(ctx, taskID, taskError) {
|
||||
s.logger.Warn("failed to persist task-owned launch error",
|
||||
zap.String("task_id", taskID),
|
||||
zap.String("session_id", sessionID),
|
||||
zap.Error(launchErr))
|
||||
return
|
||||
}
|
||||
s.dismissRecoveredAgentError(ctx, taskID, session, time.Now().UTC())
|
||||
}
|
||||
|
||||
// clearRecoveredAgentError retires the current session error while preserving
|
||||
// its record for transcript hydration and investigation. The inactive event
|
||||
// clears only the live projection; a later failure publishes a new active
|
||||
// stamp and re-arms the controls.
|
||||
func (s *Service) clearRecoveredAgentError(ctx context.Context, taskID string, session *models.TaskSession) {
|
||||
s.dismissRecoveredAgentError(ctx, taskID, session, time.Now().UTC())
|
||||
}
|
||||
|
||||
func (s *Service) dismissRecoveredAgentError(
|
||||
ctx context.Context,
|
||||
taskID string,
|
||||
session *models.TaskSession,
|
||||
dismissedAt time.Time,
|
||||
) {
|
||||
if session == nil || session.ID == "" {
|
||||
return
|
||||
}
|
||||
if _, ok := models.LoadLastAgentError(session.Metadata); !ok {
|
||||
lastErr, ok := models.LoadLastAgentError(session.Metadata)
|
||||
if !ok || lastErr.IsDismissed() {
|
||||
return
|
||||
}
|
||||
if err := s.repo.SetSessionMetadataKey(
|
||||
ctx, session.ID, models.SessionMetaKeyLastAgentError, nil,
|
||||
); err != nil {
|
||||
s.logger.Warn("failed to clear recovered agent error",
|
||||
lastErr.DismissedAt = &dismissedAt
|
||||
recoveryRepo := s.taskLaunchRecoveryRepo
|
||||
if recoveryRepo == nil {
|
||||
var ok bool
|
||||
recoveryRepo, ok = s.repo.(taskLaunchRecoveryRepository)
|
||||
if !ok {
|
||||
s.logger.Warn("cannot retire recovered agent error without stamp-CAS repository",
|
||||
zap.String("task_id", taskID),
|
||||
zap.String("session_id", session.ID))
|
||||
return
|
||||
}
|
||||
}
|
||||
stored, err := recoveryRepo.SetSessionMetadataKeyIfStamp(
|
||||
ctx,
|
||||
session.ID,
|
||||
models.SessionMetaKeyLastAgentError,
|
||||
lastErr.Stamp(),
|
||||
lastErr,
|
||||
)
|
||||
if err != nil {
|
||||
s.logger.Warn("failed to retire recovered agent error",
|
||||
zap.String("task_id", taskID),
|
||||
zap.String("session_id", session.ID),
|
||||
zap.Error(err))
|
||||
return
|
||||
}
|
||||
if !stored {
|
||||
// A successor failure won the metadata race. Do not overwrite the
|
||||
// caller's snapshot or publish an inactive event for the old stamp.
|
||||
return
|
||||
}
|
||||
// Keep the in-memory copy in step: the session-state publish below reads
|
||||
// its `session_metadata` straight off this object.
|
||||
delete(session.Metadata, models.SessionMetaKeyLastAgentError)
|
||||
if session.Metadata == nil {
|
||||
session.Metadata = make(map[string]interface{})
|
||||
}
|
||||
session.Metadata[models.SessionMetaKeyLastAgentError] = lastErr
|
||||
if s.eventBus == nil {
|
||||
return
|
||||
}
|
||||
@@ -2910,6 +3027,8 @@ func (s *Service) clearRecoveredAgentError(ctx context.Context, taskID string, s
|
||||
map[string]interface{}{
|
||||
"task_id": taskID,
|
||||
"session_id": session.ID,
|
||||
"scope": models.ErrorScopeSession,
|
||||
"stamp": lastErr.Stamp(),
|
||||
"active": false,
|
||||
},
|
||||
)); err != nil {
|
||||
@@ -2942,6 +3061,9 @@ func (s *Service) markRecoveryResolved(ctx context.Context, sessionID string, se
|
||||
session.Metadata = make(map[string]interface{})
|
||||
}
|
||||
session.Metadata[models.SessionMetaKeyRecoveryResolvedAt] = resolvedAtValue
|
||||
if session.TaskID != "" {
|
||||
s.dismissRecoveredAgentError(ctx, session.TaskID, session, resolvedAt)
|
||||
}
|
||||
return &resolvedAt
|
||||
}
|
||||
|
||||
@@ -2956,13 +3078,16 @@ func providerRemediationURL(data watcher.AgentEventData) string {
|
||||
return data.ProviderError.RemediationURL
|
||||
}
|
||||
|
||||
// createRecoveryStatusMessage builds and persists the ActionMessage shown
|
||||
// in the kanban chat surface after a recoverable agent failure. Must only
|
||||
// be called for non-office sessions (office sessions render their own error UI).
|
||||
func (s *Service) createRecoveryStatusMessage(ctx context.Context, data watcher.AgentEventData) {
|
||||
// createRecoveryStatusMessage builds and persists the ActionMessage shown in
|
||||
// the session transcript after a recoverable agent failure. Its stable message
|
||||
// identity keeps retries and bootstrap failures idempotent.
|
||||
func (s *Service) createRecoveryStatusMessage(ctx context.Context, data watcher.AgentEventData) error {
|
||||
if s.messageCreator == nil {
|
||||
return fmt.Errorf("recovery status message creator is unavailable")
|
||||
}
|
||||
authErr := isAuthError(data.ErrorMessage)
|
||||
resumeCorrupted := routingerr.IsResumeCorrupted(data.ErrorMessage)
|
||||
displayMsg := data.ErrorMessage
|
||||
displayMsg := agentFailureMessage(data)
|
||||
if authErr {
|
||||
if readable := extractReadableAuthError(data.ErrorMessage); readable != "" {
|
||||
displayMsg = readable
|
||||
@@ -2974,6 +3099,9 @@ func (s *Service) createRecoveryStatusMessage(ctx context.Context, data watcher.
|
||||
// session instead of dumping the raw 400.
|
||||
classified := classifyKanbanFailure(data)
|
||||
statusMsg := fmt.Sprintf("Agent encountered an error: %s", displayMsg)
|
||||
if data.Phase == models.LaunchErrorPhaseBootstrap {
|
||||
statusMsg = fmt.Sprintf("Agent startup failed: %s", displayMsg)
|
||||
}
|
||||
if resumeCorrupted {
|
||||
statusMsg = "This agent session can't be resumed — its saved reasoning state is corrupted. Start a fresh session to continue."
|
||||
} else if routingerr.Decide(routingerr.ContextKanban, classified, time.Now().UTC()) == routingerr.DecisionShortRetry {
|
||||
@@ -2985,6 +3113,8 @@ func (s *Service) createRecoveryStatusMessage(ctx context.Context, data watcher.
|
||||
meta := map[string]interface{}{
|
||||
"variant": "error",
|
||||
"recovery_actions": true,
|
||||
"scope": models.ErrorScopeSession,
|
||||
"error_stamp": agentFailureStamp(data),
|
||||
"session_id": data.SessionID,
|
||||
"task_id": data.TaskID,
|
||||
"has_resume_token": hasResumeToken,
|
||||
@@ -2998,6 +3128,11 @@ func (s *Service) createRecoveryStatusMessage(ctx context.Context, data watcher.
|
||||
meta["error_output"] = details
|
||||
}
|
||||
}
|
||||
if data.Phase == models.LaunchErrorPhaseBootstrap {
|
||||
if details := routingerr.Sanitize(data.FailureDetails); details != "" {
|
||||
meta["error_output"] = details
|
||||
}
|
||||
}
|
||||
// The validated remediation URL is carried independently of quota
|
||||
// classification so the generic recoverable card can still show the link.
|
||||
if remediationURL := providerRemediationURL(data); remediationURL != "" {
|
||||
@@ -3028,8 +3163,22 @@ func (s *Service) createRecoveryStatusMessage(ctx context.Context, data watcher.
|
||||
meta["actions"] = buildRecoveryActions(data.TaskID, data.SessionID, hasResumeToken, authErr, resumeCorrupted)
|
||||
}
|
||||
|
||||
if err := s.messageCreator.CreateSessionMessage(
|
||||
return s.persistRecoveryStatusMessage(ctx, data, statusMsg, meta)
|
||||
}
|
||||
|
||||
func (s *Service) persistRecoveryStatusMessage(
|
||||
ctx context.Context,
|
||||
data watcher.AgentEventData,
|
||||
statusMsg string,
|
||||
meta map[string]interface{},
|
||||
) error {
|
||||
messageID := uuid.NewSHA1(
|
||||
uuid.NameSpaceOID,
|
||||
[]byte("session-recovery:"+data.SessionID+":"+agentFailureStamp(data)),
|
||||
)
|
||||
if err := s.messageCreator.CreateSessionMessageIdempotent(
|
||||
ctx,
|
||||
messageID.String(),
|
||||
data.TaskID,
|
||||
statusMsg,
|
||||
data.SessionID,
|
||||
@@ -3041,7 +3190,9 @@ func (s *Service) createRecoveryStatusMessage(ctx context.Context, data watcher.
|
||||
s.logger.Warn("failed to create recovery status message",
|
||||
zap.String("task_id", data.TaskID),
|
||||
zap.Error(err))
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// applyProviderQuotaMetadata promotes only a validated OpenCode terminal
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"go.uber.org/zap"
|
||||
"go.uber.org/zap/zapcore"
|
||||
"go.uber.org/zap/zaptest/observer"
|
||||
@@ -408,6 +409,45 @@ func TestDispatchKanbanAgentErrorTrigger_OfficeAndLoadFailureGuards(t *testing.T
|
||||
})
|
||||
}
|
||||
|
||||
func TestHandleRecoverableFailurePersistsOfficeSessionHistory(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
repo := setupTestRepo(t)
|
||||
now := time.Now().UTC()
|
||||
requireNoError(t, repo.CreateWorkspace(ctx, &models.Workspace{ID: "ws1", Name: "Test", CreatedAt: now, UpdatedAt: now}))
|
||||
requireNoError(t, repo.CreateWorkflow(ctx, &models.Workflow{ID: "wf1", WorkspaceID: "ws1", Name: "WF", CreatedAt: now, UpdatedAt: now}))
|
||||
requireNoError(t, repo.CreateTask(ctx, &models.Task{
|
||||
ID: "office-history-task", WorkspaceID: "ws1", WorkflowID: "wf1", WorkflowStepID: "step1",
|
||||
ProjectID: "proj1", Title: "Office task", State: v1.TaskStateInProgress, CreatedAt: now, UpdatedAt: now,
|
||||
}))
|
||||
requireNoError(t, repo.CreateTaskSession(ctx, &models.TaskSession{
|
||||
ID: "office-history-session", TaskID: "office-history-task", State: models.TaskSessionStateRunning,
|
||||
StartedAt: now, UpdatedAt: now,
|
||||
}))
|
||||
|
||||
svc, _ := newAgentErrorTestService(t, repo, newMockStepGetter(), nil)
|
||||
messages := &mockMessageCreator{}
|
||||
svc.messageCreator = messages
|
||||
svc.handleRecoverableFailureLocked(ctx, watcher.AgentEventData{
|
||||
TaskID: "office-history-task",
|
||||
SessionID: "office-history-session",
|
||||
AgentExecutionID: "office-history-execution",
|
||||
ErrorMessage: "The Office agent could not start.",
|
||||
FailureCode: models.LaunchErrorCategoryGenericLaunchFailure,
|
||||
Phase: models.LaunchErrorPhaseBootstrap,
|
||||
AttemptID: "office-history-attempt",
|
||||
ErrorStamp: "office-history-failure",
|
||||
})
|
||||
|
||||
require.Len(t, messages.sessionMessages, 1, "Office failures must have one chronological session entry")
|
||||
require.Equal(t, models.ErrorScopeSession, messages.sessionMessages[0].metadata["scope"])
|
||||
require.Equal(t, "office-history-failure", messages.sessionMessages[0].metadata["error_stamp"])
|
||||
require.Equal(t, true, messages.sessionMessages[0].metadata["recovery_actions"])
|
||||
|
||||
session, err := repo.GetTaskSession(ctx, "office-history-session")
|
||||
requireNoError(t, err)
|
||||
require.Equal(t, models.TaskSessionStateFailed, session.State)
|
||||
}
|
||||
|
||||
type agentErrorTaskLoadErrorRepo struct {
|
||||
sessionExecutorStore
|
||||
err error
|
||||
|
||||
@@ -860,6 +860,14 @@ func TestHandleAgentBootReady_DoesNotTriggerOnTurnComplete(t *testing.T) {
|
||||
}); err != nil {
|
||||
t.Fatalf("create session: %v", err)
|
||||
}
|
||||
if err := repo.SetSessionMetadataKey(ctx, sessionID, models.SessionMetaKeyLastAgentError, models.LastAgentError{
|
||||
Message: "saved session failed before recovery",
|
||||
OccurredAt: now,
|
||||
Scope: models.ErrorScopeSession,
|
||||
StampValue: "saved-session-failure",
|
||||
}); err != nil {
|
||||
t.Fatalf("set saved session failure: %v", err)
|
||||
}
|
||||
|
||||
taskRepo := newMockTaskRepo()
|
||||
taskRepo.tasks["task-1"] = &v1.Task{
|
||||
@@ -915,6 +923,10 @@ func TestHandleAgentBootReady_DoesNotTriggerOnTurnComplete(t *testing.T) {
|
||||
if _, err := time.Parse(time.RFC3339Nano, resolvedAt); err != nil {
|
||||
t.Fatalf("recovery resolution timestamp %q is invalid: %v", resolvedAt, err)
|
||||
}
|
||||
lastError, ok := models.LoadLastAgentError(finalSess.Metadata)
|
||||
if !ok || !lastError.IsDismissed() {
|
||||
t.Fatalf("last agent error = %#v, want dismissed historical error", lastError)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1373,7 +1373,9 @@ func (s *Service) transitionBootstrapFailure(
|
||||
|
||||
committer, ok := s.repo.(bootstrapFailureCommitter)
|
||||
if !ok {
|
||||
return s.transitionTaskSessionState(ctx, taskID, sessionID, models.TaskSessionStateFailed, errorValue.Message, nil)
|
||||
return false, expectedState, fmt.Errorf(
|
||||
"bootstrap failure requires an execution-fenced repository commit",
|
||||
)
|
||||
}
|
||||
changed, updatedAt, err := committer.CommitBootstrapFailureIfCurrentExecution(
|
||||
ctx,
|
||||
@@ -1389,11 +1391,12 @@ func (s *Service) transitionBootstrapFailure(
|
||||
}
|
||||
refreshed, err := s.repo.GetTaskSession(ctx, sessionID)
|
||||
if err != nil {
|
||||
return false, models.TaskSessionStateFailed, fmt.Errorf("get session after bootstrap failure commit: %w", err)
|
||||
return true, models.TaskSessionStateFailed, fmt.Errorf("get session after bootstrap failure commit: %w", err)
|
||||
}
|
||||
if refreshed == nil {
|
||||
return false, models.TaskSessionStateFailed, fmt.Errorf("get session after bootstrap failure commit: session %q is nil", sessionID)
|
||||
return true, models.TaskSessionStateFailed, fmt.Errorf("get session after bootstrap failure commit: session %q is nil", sessionID)
|
||||
}
|
||||
messageErr := s.persistBootstrapFailureMessage(ctx, taskID, sessionID, agentExecutionID, errorValue)
|
||||
authoritativeUpdatedAt := updatedAt.UTC()
|
||||
s.publishAcceptedTaskSessionState(
|
||||
ctx,
|
||||
@@ -1405,9 +1408,37 @@ func (s *Service) transitionBootstrapFailure(
|
||||
&authoritativeUpdatedAt,
|
||||
refreshed,
|
||||
)
|
||||
if messageErr != nil {
|
||||
return true, models.TaskSessionStateFailed, fmt.Errorf("persist bootstrap failure history: %w", messageErr)
|
||||
}
|
||||
return true, models.TaskSessionStateFailed, nil
|
||||
}
|
||||
|
||||
// persistBootstrapFailureMessage records the accepted bootstrap failure as a
|
||||
// chronological session entry. Its stable message identity makes a retry
|
||||
// after the state commit idempotent.
|
||||
func (s *Service) persistBootstrapFailureMessage(
|
||||
ctx context.Context,
|
||||
taskID, sessionID, agentExecutionID string,
|
||||
errorValue models.LastAgentError,
|
||||
) error {
|
||||
if s.messageCreator == nil {
|
||||
return fmt.Errorf("bootstrap failure message creator is unavailable")
|
||||
}
|
||||
return s.createRecoveryStatusMessage(ctx, watcher.AgentEventData{
|
||||
TaskID: taskID,
|
||||
SessionID: sessionID,
|
||||
AgentExecutionID: agentExecutionID,
|
||||
ErrorMessage: errorValue.Message,
|
||||
FailureCode: errorValue.Code,
|
||||
FailureDetails: errorValue.Details,
|
||||
Phase: errorValue.Phase,
|
||||
AttemptID: errorValue.AttemptID,
|
||||
ErrorStamp: errorValue.Stamp(),
|
||||
Causes: errorValue.Causes,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Service) publishAcceptedTaskSessionState(
|
||||
ctx context.Context,
|
||||
taskID, sessionID string,
|
||||
|
||||
@@ -272,6 +272,25 @@ func (m *serviceBackedMessageCreator) CreateSessionMessage(
|
||||
return err
|
||||
}
|
||||
|
||||
func (m *serviceBackedMessageCreator) CreateSessionMessageIdempotent(
|
||||
ctx context.Context,
|
||||
messageID, taskID, content, sessionID, messageType, turnID string,
|
||||
metadata map[string]interface{},
|
||||
requestsInput bool,
|
||||
) error {
|
||||
_, err := m.svc.CreateMessageIdempotent(ctx, messageID, &taskservice.CreateMessageRequest{
|
||||
TaskSessionID: sessionID,
|
||||
TaskID: taskID,
|
||||
TurnID: turnID,
|
||||
Content: content,
|
||||
AuthorType: "agent",
|
||||
Type: messageType,
|
||||
Metadata: metadata,
|
||||
RequestsInput: requestsInput,
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
func (m *serviceBackedMessageCreator) UpdateToolCallMessage(
|
||||
ctx context.Context,
|
||||
taskID, toolCallID, parentToolCallID, status, result, agentSessionID, title, turnID, msgType string,
|
||||
@@ -2819,9 +2838,8 @@ func TestAutoStartFailureDoesNotMarkTaskWithActiveSession(t *testing.T) {
|
||||
require.False(t, marked, "a late failure must not mark a task with active work")
|
||||
}
|
||||
|
||||
// Nothing else ever retires a stored agent failure, so without this clear every
|
||||
// path that re-derives task status from session metadata resurrects it and the
|
||||
// error icon never goes away.
|
||||
// A recovered failure remains available for transcript history, while this
|
||||
// transition retires it from the live session-error projection.
|
||||
func TestClearRecoveredAgentErrorOnTurnCompletion(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
|
||||
@@ -2846,11 +2864,12 @@ func TestClearRecoveredAgentErrorOnTurnCompletion(t *testing.T) {
|
||||
newService := func(repo *sqliterepo.Repository) (*Service, *recordingEventBus) {
|
||||
eb := &recordingEventBus{}
|
||||
svc := createTestService(repo, newMockStepGetter(), newMockTaskRepo())
|
||||
svc.taskLaunchRecoveryRepo = repo
|
||||
svc.eventBus = eb
|
||||
return svc, eb
|
||||
}
|
||||
|
||||
t.Run("clears the record and publishes it inactive", func(t *testing.T) {
|
||||
t.Run("retires the record and publishes it inactive", func(t *testing.T) {
|
||||
repo := setupTestRepo(t)
|
||||
seedSession(t, repo, "t1", "s1", "step1")
|
||||
seedError(t, repo)
|
||||
@@ -2862,13 +2881,15 @@ func TestClearRecoveredAgentErrorOnTurnCompletion(t *testing.T) {
|
||||
|
||||
stored, err := repo.GetTaskSession(ctx, "s1")
|
||||
require.NoError(t, err)
|
||||
_, ok := models.LoadLastAgentError(stored.Metadata)
|
||||
require.False(t, ok, "a recovered failure must not keep driving the error icon")
|
||||
storedError, ok := models.LoadLastAgentError(stored.Metadata)
|
||||
require.True(t, ok, "a recovered failure remains available as history")
|
||||
require.True(t, storedError.IsDismissed(), "a recovered failure must not remain active")
|
||||
|
||||
// The session-state publish that follows reads session_metadata straight
|
||||
// off this object, so a stale copy would re-arm the icon immediately.
|
||||
_, ok = models.LoadLastAgentError(session.Metadata)
|
||||
require.False(t, ok, "the in-memory copy must be cleared too")
|
||||
memoryError, ok := models.LoadLastAgentError(session.Metadata)
|
||||
require.True(t, ok)
|
||||
require.True(t, memoryError.IsDismissed(), "the in-memory copy must be retired too")
|
||||
|
||||
published := errorEvents(eb)
|
||||
require.Len(t, published, 1, "clients need one event to drop the icon")
|
||||
@@ -2876,6 +2897,7 @@ func TestClearRecoveredAgentErrorOnTurnCompletion(t *testing.T) {
|
||||
require.True(t, ok)
|
||||
require.Equal(t, false, data["active"])
|
||||
require.Equal(t, "s1", data["session_id"])
|
||||
require.Equal(t, models.ErrorScopeSession, data["scope"])
|
||||
})
|
||||
|
||||
t.Run("stays silent when the session has no stored error", func(t *testing.T) {
|
||||
@@ -2890,6 +2912,206 @@ func TestClearRecoveredAgentErrorOnTurnCompletion(t *testing.T) {
|
||||
require.Empty(t, errorEvents(eb),
|
||||
"every later completion must stay silent so turns do not churn the row")
|
||||
})
|
||||
|
||||
t.Run("does not retire a successor failure from a stale snapshot", func(t *testing.T) {
|
||||
repo := setupTestRepo(t)
|
||||
seedSession(t, repo, "t1", "s1", "step1")
|
||||
require.NoError(t, repo.SetSessionMetadataKey(
|
||||
ctx, "s1", models.SessionMetaKeyLastAgentError,
|
||||
models.LastAgentError{
|
||||
Message: "old failure",
|
||||
OccurredAt: time.Date(2026, 8, 20, 9, 0, 0, 0, time.UTC),
|
||||
StampValue: "old-stamp",
|
||||
},
|
||||
))
|
||||
svc, eb := newService(repo)
|
||||
|
||||
snapshot, err := repo.GetTaskSession(ctx, "s1")
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, repo.SetSessionMetadataKey(
|
||||
ctx, "s1", models.SessionMetaKeyLastAgentError,
|
||||
models.LastAgentError{
|
||||
Message: "successor failure",
|
||||
OccurredAt: time.Date(2026, 8, 20, 10, 0, 0, 0, time.UTC),
|
||||
StampValue: "successor-stamp",
|
||||
},
|
||||
))
|
||||
|
||||
require.NotNil(t, svc.markRecoveryResolved(ctx, "s1", snapshot))
|
||||
|
||||
stored, err := repo.GetTaskSession(ctx, "s1")
|
||||
require.NoError(t, err)
|
||||
storedError, ok := models.LoadLastAgentError(stored.Metadata)
|
||||
require.True(t, ok)
|
||||
require.Equal(t, "successor-stamp", storedError.Stamp())
|
||||
require.False(t, storedError.IsDismissed())
|
||||
snapshotError, ok := models.LoadLastAgentError(snapshot.Metadata)
|
||||
require.True(t, ok)
|
||||
require.Equal(t, "old-stamp", snapshotError.Stamp())
|
||||
require.False(t, snapshotError.IsDismissed())
|
||||
require.Empty(t, errorEvents(eb), "a stale retirement must not hide the successor")
|
||||
})
|
||||
}
|
||||
|
||||
func TestTransitionBootstrapFailurePersistsSessionHistory(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
repo := setupTestRepo(t)
|
||||
seedSession(t, repo, "bootstrap-history-task", "bootstrap-history-session", "step1")
|
||||
session, err := repo.GetTaskSession(ctx, "bootstrap-history-session")
|
||||
require.NoError(t, err)
|
||||
session.State = models.TaskSessionStateStarting
|
||||
require.NoError(t, repo.UpdateTaskSession(ctx, session))
|
||||
seedExecutorRunning(t, repo, "bootstrap-history-session", "bootstrap-history-task", "exec-1")
|
||||
|
||||
svc := createTestService(repo, newMockStepGetter(), newMockTaskRepo())
|
||||
svc.taskLaunchRecoveryRepo = repo
|
||||
svc.messageCreator = newServiceBackedMessageCreator(repo)
|
||||
startupFailure := &lifecycle.BootstrapFailure{
|
||||
Operation: models.AgentErrorCauseOperationResume,
|
||||
Code: models.AgentErrorCauseCodePermissionDenied,
|
||||
Detail: "The saved session could not be loaded.",
|
||||
Cause: errors.New("provider timeout with private token=secret"),
|
||||
}
|
||||
// The ordinary non-auth startup path returns false so the executor owns the
|
||||
// terminal admission. The transition below is that accepted boundary.
|
||||
require.False(t, svc.handleAgentStartFailed(
|
||||
ctx,
|
||||
"bootstrap-history-task",
|
||||
"bootstrap-history-session",
|
||||
"exec-1",
|
||||
startupFailure,
|
||||
false,
|
||||
))
|
||||
failure := models.LastAgentError{
|
||||
Message: "The agent could not start.",
|
||||
OccurredAt: time.Date(2026, 9, 14, 10, 0, 0, 0, time.UTC),
|
||||
Scope: models.ErrorScopeSession,
|
||||
AgentExecutionID: "exec-1",
|
||||
ExecutionID: "exec-1",
|
||||
Phase: models.LaunchErrorPhaseBootstrap,
|
||||
AttemptID: "attempt-1",
|
||||
Code: models.LaunchErrorCategoryGenericLaunchFailure,
|
||||
Details: "operation=agent_bootstrap; cause=the provider did not respond",
|
||||
StampValue: "bootstrap-failure-1",
|
||||
}
|
||||
|
||||
changed, state, err := svc.transitionBootstrapFailure(
|
||||
ctx,
|
||||
"bootstrap-history-task",
|
||||
"bootstrap-history-session",
|
||||
"exec-1",
|
||||
models.TaskSessionStateStarting,
|
||||
"",
|
||||
failure,
|
||||
)
|
||||
require.NoError(t, err)
|
||||
require.True(t, changed)
|
||||
require.Equal(t, models.TaskSessionStateFailed, state)
|
||||
|
||||
messages, err := repo.ListMessages(ctx, "bootstrap-history-session")
|
||||
require.NoError(t, err)
|
||||
require.Len(t, messages, 1, "accepted bootstrap failure must create one transcript entry")
|
||||
require.Equal(t, models.MessageTypeStatus, messages[0].Type)
|
||||
require.Equal(t, "bootstrap-failure-1", messages[0].Metadata["error_stamp"])
|
||||
require.Equal(t, true, messages[0].Metadata["recovery_actions"])
|
||||
require.Equal(t, failure.Details, messages[0].Metadata["error_output"])
|
||||
require.Equal(t, "Agent startup failed: The agent could not start.", messages[0].Content)
|
||||
|
||||
reloaded, err := repo.GetTaskSession(ctx, "bootstrap-history-session")
|
||||
require.NoError(t, err)
|
||||
resolvedAt := svc.markRecoveryResolved(ctx, reloaded.ID, reloaded)
|
||||
require.NotNil(t, resolvedAt)
|
||||
|
||||
afterRecovery, err := repo.GetTaskSession(ctx, "bootstrap-history-session")
|
||||
require.NoError(t, err)
|
||||
retainedError, ok := models.LoadLastAgentError(afterRecovery.Metadata)
|
||||
require.True(t, ok)
|
||||
require.True(t, retainedError.IsDismissed())
|
||||
retainedMessages, err := repo.ListMessages(ctx, "bootstrap-history-session")
|
||||
require.NoError(t, err)
|
||||
require.Len(t, retainedMessages, 1, "recovery retirement must retain the chronological entry")
|
||||
}
|
||||
|
||||
type failOnceBootstrapMessageCreator struct {
|
||||
*serviceBackedMessageCreator
|
||||
err error
|
||||
}
|
||||
|
||||
func (m *failOnceBootstrapMessageCreator) CreateSessionMessageIdempotent(
|
||||
ctx context.Context,
|
||||
messageID, taskID, content, sessionID, messageType, turnID string,
|
||||
metadata map[string]interface{}, requestsInput bool,
|
||||
) error {
|
||||
if m.err != nil {
|
||||
err := m.err
|
||||
m.err = nil
|
||||
return err
|
||||
}
|
||||
return m.serviceBackedMessageCreator.CreateSessionMessageIdempotent(
|
||||
ctx,
|
||||
messageID,
|
||||
taskID,
|
||||
content,
|
||||
sessionID,
|
||||
messageType,
|
||||
turnID,
|
||||
metadata,
|
||||
requestsInput,
|
||||
)
|
||||
}
|
||||
|
||||
func TestTransitionBootstrapFailureReturnsRepairableHistoryError(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
repo := setupTestRepo(t)
|
||||
seedSession(t, repo, "bootstrap-repair-task", "bootstrap-repair-session", "step1")
|
||||
session, err := repo.GetTaskSession(ctx, "bootstrap-repair-session")
|
||||
require.NoError(t, err)
|
||||
session.State = models.TaskSessionStateStarting
|
||||
require.NoError(t, repo.UpdateTaskSession(ctx, session))
|
||||
seedExecutorRunning(t, repo, "bootstrap-repair-session", "bootstrap-repair-task", "exec-repair")
|
||||
|
||||
svc := createTestService(repo, newMockStepGetter(), newMockTaskRepo())
|
||||
creator := &failOnceBootstrapMessageCreator{
|
||||
serviceBackedMessageCreator: newServiceBackedMessageCreator(repo),
|
||||
err: errors.New("transcript temporarily unavailable"),
|
||||
}
|
||||
svc.messageCreator = creator
|
||||
failure := models.LastAgentError{
|
||||
Message: "The agent could not start.",
|
||||
OccurredAt: time.Date(2026, 9, 14, 11, 0, 0, 0, time.UTC),
|
||||
Scope: models.ErrorScopeSession,
|
||||
AgentExecutionID: "exec-repair",
|
||||
ExecutionID: "exec-repair",
|
||||
Phase: models.LaunchErrorPhaseBootstrap,
|
||||
AttemptID: "exec-repair",
|
||||
Code: models.LaunchErrorCategoryGenericLaunchFailure,
|
||||
Details: "operation=agent_bootstrap; cause=provider unavailable",
|
||||
StampValue: "bootstrap-repair-failure",
|
||||
}
|
||||
|
||||
changed, state, err := svc.transitionBootstrapFailure(
|
||||
ctx,
|
||||
"bootstrap-repair-task",
|
||||
"bootstrap-repair-session",
|
||||
"exec-repair",
|
||||
models.TaskSessionStateStarting,
|
||||
"",
|
||||
failure,
|
||||
)
|
||||
require.Error(t, err)
|
||||
require.True(t, changed, "the state admission succeeded even though history needed repair")
|
||||
require.Equal(t, models.TaskSessionStateFailed, state)
|
||||
messages, err := repo.ListMessages(ctx, "bootstrap-repair-session")
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, messages)
|
||||
|
||||
require.NoError(t, svc.persistBootstrapFailureMessage(
|
||||
ctx, "bootstrap-repair-task", "bootstrap-repair-session", "exec-repair", failure,
|
||||
))
|
||||
messages, err = repo.ListMessages(ctx, "bootstrap-repair-session")
|
||||
require.NoError(t, err)
|
||||
require.Len(t, messages, 1, "the bounded repair must restore the accepted failure entry")
|
||||
require.Equal(t, "bootstrap-repair-failure", messages[0].Metadata["error_stamp"])
|
||||
}
|
||||
|
||||
func TestSetSessionStartingRejectsTerminalSession(t *testing.T) {
|
||||
|
||||
@@ -111,23 +111,6 @@ type sessionMetadataKeyStateSetter interface {
|
||||
) (bool, error)
|
||||
}
|
||||
|
||||
// sessionMetadataErrorCASWriter is the optional persistence seam for
|
||||
// execution-scoped bootstrap errors. Production repositories implement both
|
||||
// operations atomically; legacy test stores can fall back to the ordinary
|
||||
// metadata setter after the executor's current-execution fence.
|
||||
type sessionMetadataErrorCASWriter interface {
|
||||
SetSessionMetadataKeyIfAbsent(
|
||||
ctx context.Context,
|
||||
sessionID, key string,
|
||||
value interface{},
|
||||
) (bool, error)
|
||||
SetSessionMetadataKeyIfStamp(
|
||||
ctx context.Context,
|
||||
sessionID, key, expectedStamp string,
|
||||
value interface{},
|
||||
) (bool, error)
|
||||
}
|
||||
|
||||
// bootstrapFailureCommitter is the atomic repository boundary for an
|
||||
// asynchronous process-start failure. The expected state and error stamp are
|
||||
// captured immediately before the commit; the repository must also require
|
||||
@@ -831,6 +814,16 @@ type BootstrapFailureTransitionFunc func(
|
||||
errorValue models.LastAgentError,
|
||||
) (changed bool, finalState models.TaskSessionState, err error)
|
||||
|
||||
// BootstrapFailureMessageRepairFunc retries the idempotent transcript write
|
||||
// after the state admission has already succeeded. The repair is deliberately
|
||||
// separate from the state commit so a transient message-store failure cannot
|
||||
// make an accepted bootstrap failure disappear from session history.
|
||||
type BootstrapFailureMessageRepairFunc func(
|
||||
ctx context.Context,
|
||||
taskID, sessionID, agentExecutionID string,
|
||||
errorValue models.LastAgentError,
|
||||
) error
|
||||
|
||||
// SessionStartingFunc is called when the executor has prepared/resumed an
|
||||
// execution and needs to mark the session STARTING while preserving other
|
||||
// session-row updates such as metadata. expectedState is the state observed
|
||||
@@ -983,6 +976,9 @@ type Executor struct {
|
||||
// typed error, FAILED state, and corresponding publication as one ownership
|
||||
// decision.
|
||||
onBootstrapFailureTransition BootstrapFailureTransitionFunc
|
||||
// Retry hook for the chronological transcript entry when the state commit
|
||||
// succeeds but the first idempotent message write fails.
|
||||
onBootstrapFailureMessageRepair BootstrapFailureMessageRepairFunc
|
||||
|
||||
// Callback for STARTING writes that carry full session-row changes. Set by
|
||||
// the orchestrator so launch/resume/model-switch transitions serialize with
|
||||
@@ -1304,6 +1300,12 @@ func (e *Executor) SetOnBootstrapFailureTransition(fn BootstrapFailureTransition
|
||||
e.onBootstrapFailureTransition = fn
|
||||
}
|
||||
|
||||
// SetOnBootstrapFailureMessageRepair wires the bounded repair hook for a
|
||||
// bootstrap failure whose session admission already succeeded.
|
||||
func (e *Executor) SetOnBootstrapFailureMessageRepair(fn BootstrapFailureMessageRepairFunc) {
|
||||
e.onBootstrapFailureMessageRepair = fn
|
||||
}
|
||||
|
||||
// SetOnSessionStarting sets a callback for full session-row STARTING updates.
|
||||
func (e *Executor) SetOnSessionStarting(fn SessionStartingFunc) {
|
||||
e.onSessionStarting = fn
|
||||
|
||||
@@ -285,6 +285,17 @@ func (e *Executor) handleAgentProcessStartFailure(
|
||||
zap.String("session_id", sessionID),
|
||||
zap.String("agent_execution_id", agentExecutionID),
|
||||
zap.Error(transitionErr))
|
||||
if changed && finalState == models.TaskSessionStateFailed && e.onBootstrapFailureMessageRepair != nil {
|
||||
if repairErr := e.onBootstrapFailureMessageRepair(
|
||||
ctx, taskID, sessionID, agentExecutionID, errorValue,
|
||||
); repairErr != nil {
|
||||
e.logger.Warn("failed to repair bootstrap failure history",
|
||||
zap.String("task_id", taskID),
|
||||
zap.String("session_id", sessionID),
|
||||
zap.String("agent_execution_id", agentExecutionID),
|
||||
zap.Error(repairErr))
|
||||
}
|
||||
}
|
||||
} else if !changed {
|
||||
// An ownership or compare-and-set miss means a newer execution won the
|
||||
// race. Do not
|
||||
|
||||
+72
@@ -170,6 +170,9 @@ func TestBuildLastAgentErrorSanitizesRepositoryPreparationDetails(t *testing.T)
|
||||
if !strings.Contains(errorValue.Details, "repo-back") || !strings.Contains(errorValue.Details, "backend") {
|
||||
t.Fatalf("launch details = %q, want repository identity", errorValue.Details)
|
||||
}
|
||||
if errorValue.Phase != models.LaunchErrorPhaseBootstrap {
|
||||
t.Fatalf("launch phase = %q, want bootstrap", errorValue.Phase)
|
||||
}
|
||||
if strings.Contains(errorValue.Details, "ghp_abcdefghijklmnopqrstuvwxyz1234567890AB") ||
|
||||
strings.Contains(errorValue.Details, "user:") {
|
||||
t.Fatalf("launch details exposed credential-bearing URL: %q", errorValue.Details)
|
||||
@@ -235,6 +238,27 @@ func TestBootstrapFailureProjection(t *testing.T) {
|
||||
exec.SetOnSessionStateChange(func(ctx context.Context, _, sessionID string, state models.TaskSessionState, message string) error {
|
||||
return repo.UpdateTaskSessionState(ctx, sessionID, state, message)
|
||||
})
|
||||
exec.SetOnBootstrapFailureTransition(func(
|
||||
ctx context.Context,
|
||||
taskID, sessionID, _ string,
|
||||
_ models.TaskSessionState,
|
||||
_ string,
|
||||
errorValue models.LastAgentError,
|
||||
) (bool, models.TaskSessionState, error) {
|
||||
changed, _, err := repo.CommitBootstrapFailureIfCurrentExecution(
|
||||
ctx,
|
||||
taskID,
|
||||
sessionID,
|
||||
"exec-1",
|
||||
models.TaskSessionStateStarting,
|
||||
"",
|
||||
errorValue,
|
||||
)
|
||||
if err != nil || !changed {
|
||||
return changed, models.TaskSessionStateStarting, err
|
||||
}
|
||||
return true, models.TaskSessionStateFailed, nil
|
||||
})
|
||||
|
||||
exec.runAgentProcessAsync(
|
||||
context.Background(), "task-1", "session-1", "exec-1",
|
||||
@@ -273,6 +297,54 @@ func TestBootstrapFailureProjection(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestBootstrapFailureHistoryRepairRunsAfterAcceptedCommitError(t *testing.T) {
|
||||
repo := newMockRepository()
|
||||
repo.sessions["session-repair"] = &models.TaskSession{
|
||||
ID: "session-repair",
|
||||
TaskID: "task-repair",
|
||||
State: models.TaskSessionStateStarting,
|
||||
AgentExecutionID: "exec-repair",
|
||||
}
|
||||
repo.tasks["task-repair"] = &models.Task{ID: "task-repair", State: v1.TaskStateReview}
|
||||
exec := newTestExecutor(t, &mockAgentManager{}, repo)
|
||||
var repairCalls int
|
||||
exec.SetOnBootstrapFailureTransition(func(
|
||||
context.Context,
|
||||
string,
|
||||
string,
|
||||
string,
|
||||
models.TaskSessionState,
|
||||
string,
|
||||
models.LastAgentError,
|
||||
) (bool, models.TaskSessionState, error) {
|
||||
return true, models.TaskSessionStateFailed, errors.New("transcript write failed after admission")
|
||||
})
|
||||
exec.SetOnBootstrapFailureMessageRepair(func(
|
||||
context.Context,
|
||||
string,
|
||||
string,
|
||||
string,
|
||||
models.LastAgentError,
|
||||
) error {
|
||||
repairCalls++
|
||||
return nil
|
||||
})
|
||||
|
||||
exec.handleAgentProcessStartFailure(
|
||||
context.Background(),
|
||||
"task-repair",
|
||||
"session-repair",
|
||||
"exec-repair",
|
||||
errors.New("agent process failed to start"),
|
||||
false,
|
||||
false,
|
||||
)
|
||||
|
||||
if repairCalls != 1 {
|
||||
t.Fatalf("bootstrap history repair calls = %d, want 1", repairCalls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBootstrapFailureSuccessorFence(t *testing.T) {
|
||||
repo := newMockRepository()
|
||||
successor := models.LastAgentError{
|
||||
|
||||
@@ -544,6 +544,45 @@ func (m *mockRepository) UpdateTaskSessionStateIfCurrent(
|
||||
return true, now, nil
|
||||
}
|
||||
|
||||
// CommitBootstrapFailureIfCurrentExecution mirrors the production admission
|
||||
// boundary for executor tests. The fake has no separate executor table, so the
|
||||
// session's execution identity is the equivalent ownership fence.
|
||||
func (m *mockRepository) CommitBootstrapFailureIfCurrentExecution(
|
||||
_ context.Context,
|
||||
taskID, sessionID, agentExecutionID string,
|
||||
expectedState models.TaskSessionState,
|
||||
expectedStamp string,
|
||||
errorValue models.LastAgentError,
|
||||
) (bool, time.Time, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
session, ok := m.sessions[sessionID]
|
||||
if !ok || session == nil || (session.TaskID != "" && session.TaskID != taskID) || session.State != expectedState {
|
||||
return false, time.Time{}, nil
|
||||
}
|
||||
if agentExecutionID != "" && session.AgentExecutionID != "" && session.AgentExecutionID != agentExecutionID {
|
||||
return false, time.Time{}, nil
|
||||
}
|
||||
current, hasCurrent := models.LoadLastAgentError(session.Metadata)
|
||||
if expectedStamp == "" {
|
||||
if hasCurrent {
|
||||
return false, time.Time{}, nil
|
||||
}
|
||||
} else if !hasCurrent || current.Stamp() != expectedStamp {
|
||||
return false, time.Time{}, nil
|
||||
}
|
||||
if session.Metadata == nil {
|
||||
session.Metadata = make(map[string]interface{})
|
||||
}
|
||||
session.Metadata[models.SessionMetaKeyLastAgentError] = errorValue
|
||||
now := time.Now().UTC()
|
||||
session.State = models.TaskSessionStateFailed
|
||||
session.ErrorMessage = errorValue.Message
|
||||
session.CompletedAt = &now
|
||||
session.UpdatedAt = now
|
||||
return true, now, nil
|
||||
}
|
||||
|
||||
func (m *mockRepository) UpdateTaskSessionIfCurrentStateRemovingMetadataKeys(
|
||||
ctx context.Context,
|
||||
session *models.TaskSession,
|
||||
|
||||
@@ -2135,6 +2135,27 @@ func TestRunAgentProcessAsync_CleansUpOnStartFailure(t *testing.T) {
|
||||
exec.SetOnSessionStateChange(func(ctx context.Context, taskID, sessionID string, state models.TaskSessionState, errorMessage string) error {
|
||||
return repo.UpdateTaskSessionState(ctx, sessionID, state, errorMessage)
|
||||
})
|
||||
exec.SetOnBootstrapFailureTransition(func(
|
||||
ctx context.Context,
|
||||
taskID, sessionID, _ string,
|
||||
_ models.TaskSessionState,
|
||||
_ string,
|
||||
errorValue models.LastAgentError,
|
||||
) (bool, models.TaskSessionState, error) {
|
||||
changed, _, err := repo.CommitBootstrapFailureIfCurrentExecution(
|
||||
ctx,
|
||||
taskID,
|
||||
sessionID,
|
||||
"exec-456",
|
||||
models.TaskSessionStateStarting,
|
||||
"",
|
||||
errorValue,
|
||||
)
|
||||
if err != nil || !changed {
|
||||
return changed, models.TaskSessionStateStarting, err
|
||||
}
|
||||
return true, models.TaskSessionStateFailed, nil
|
||||
})
|
||||
exec.SetOnTaskStateChange(func(ctx context.Context, taskID string, state v1.TaskState) error {
|
||||
return repo.UpdateTaskState(ctx, taskID, state)
|
||||
})
|
||||
@@ -2310,6 +2331,15 @@ func TestHandleAgentProcessStartFailure_CancellationDuringCallbackStopsUnclaimed
|
||||
transitionCalls.Add(1)
|
||||
return false, models.TaskSessionStateCancelled, nil
|
||||
})
|
||||
exec.SetOnBootstrapFailureTransition(func(
|
||||
ctx context.Context,
|
||||
taskID, sessionID, _ string,
|
||||
_ models.TaskSessionState,
|
||||
_ string,
|
||||
errorValue models.LastAgentError,
|
||||
) (bool, models.TaskSessionState, error) {
|
||||
return exec.transitionSessionState(ctx, taskID, sessionID, models.TaskSessionStateFailed, errorValue.Message)
|
||||
})
|
||||
exec.SetOnExecutionCleanupClaim(func(sessionID, executionID string) bool {
|
||||
if sessionID != "session-123" || executionID != "exec-456" {
|
||||
t.Fatalf("cleanup claim = (%q, %q), want (session-123, exec-456)", sessionID, executionID)
|
||||
@@ -2654,6 +2684,30 @@ func newRunAgentProcessAsyncFailureFixture(t *testing.T) *runAgentProcessAsyncFa
|
||||
}
|
||||
return repo.UpdateTaskSessionState(ctx, sessionID, state, errorMessage)
|
||||
})
|
||||
f.exec.SetOnBootstrapFailureTransition(func(
|
||||
ctx context.Context,
|
||||
taskID, sessionID, _ string,
|
||||
_ models.TaskSessionState,
|
||||
_ string,
|
||||
errorValue models.LastAgentError,
|
||||
) (bool, models.TaskSessionState, error) {
|
||||
changed, _, err := repo.CommitBootstrapFailureIfCurrentExecution(
|
||||
ctx,
|
||||
taskID,
|
||||
sessionID,
|
||||
"exec-456",
|
||||
models.TaskSessionStateStarting,
|
||||
"",
|
||||
errorValue,
|
||||
)
|
||||
if changed {
|
||||
f.sessionFailedSeen = true
|
||||
}
|
||||
if err != nil || !changed {
|
||||
return changed, models.TaskSessionStateStarting, err
|
||||
}
|
||||
return true, models.TaskSessionStateFailed, nil
|
||||
})
|
||||
f.exec.SetOnAgentStartFailed(func(ctx context.Context, taskID, sessionID, agentExecutionID string, err error, fromResume bool) bool {
|
||||
f.startFailedCalls++
|
||||
f.lastFromResume = fromResume
|
||||
|
||||
@@ -102,6 +102,8 @@ func (e *Executor) buildLastAgentError(
|
||||
return models.LastAgentError{
|
||||
Message: classification.message,
|
||||
OccurredAt: occurredAt,
|
||||
Scope: models.ErrorScopeSession,
|
||||
Phase: models.LaunchErrorPhaseBootstrap,
|
||||
Code: classification.code,
|
||||
Details: details,
|
||||
RecoveryActions: func() []string {
|
||||
@@ -167,6 +169,7 @@ func (e *Executor) buildBootstrapLastAgentError(
|
||||
return models.LastAgentError{
|
||||
Message: classification.message,
|
||||
OccurredAt: occurredAt,
|
||||
Scope: models.ErrorScopeSession,
|
||||
AgentExecutionID: agentExecutionID,
|
||||
ExecutionID: agentExecutionID,
|
||||
Phase: models.LaunchErrorPhaseBootstrap,
|
||||
@@ -306,8 +309,8 @@ func (e *Executor) bootstrapFailureExpectation(
|
||||
|
||||
// commitBootstrapFailure commits the correlated failure projection and the
|
||||
// FAILED transition through the atomic orchestrator callback or repository
|
||||
// capability. Legacy test stores retain the older CAS plus state-transition
|
||||
// fallback, but the production SQL repository uses the guarded commit.
|
||||
// capability. Stores without an execution-fenced commit fail closed so a
|
||||
// bootstrap failure cannot overwrite a successor execution.
|
||||
func (e *Executor) commitBootstrapFailure(
|
||||
ctx context.Context,
|
||||
taskID, sessionID, agentExecutionID string,
|
||||
@@ -352,43 +355,7 @@ func (e *Executor) commitBootstrapFailure(
|
||||
return true, models.TaskSessionStateFailed, nil
|
||||
}
|
||||
|
||||
// Legacy stores cannot atomically fence the executor row and session write.
|
||||
// Keep their existing behavior for focused test doubles and older adapters;
|
||||
// the production repository always takes the guarded path above.
|
||||
writer, supportsCAS := e.repo.(sessionMetadataErrorCASWriter)
|
||||
var persisted bool
|
||||
if supportsCAS {
|
||||
if expectedStamp != "" {
|
||||
persisted, err = writer.SetSessionMetadataKeyIfStamp(
|
||||
ctx,
|
||||
sessionID,
|
||||
models.SessionMetaKeyLastAgentError,
|
||||
expectedStamp,
|
||||
errorValue,
|
||||
)
|
||||
} else {
|
||||
persisted, err = writer.SetSessionMetadataKeyIfAbsent(
|
||||
ctx,
|
||||
sessionID,
|
||||
models.SessionMetaKeyLastAgentError,
|
||||
errorValue,
|
||||
)
|
||||
}
|
||||
} else {
|
||||
err = e.repo.SetSessionMetadataKey(
|
||||
ctx, sessionID, models.SessionMetaKeyLastAgentError, errorValue,
|
||||
)
|
||||
persisted = err == nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, session.State, err
|
||||
}
|
||||
if !persisted {
|
||||
return false, session.State, nil
|
||||
}
|
||||
|
||||
changed, finalState, err := e.transitionSessionState(
|
||||
ctx, taskID, sessionID, models.TaskSessionStateFailed, errorValue.Message,
|
||||
return false, session.State, fmt.Errorf(
|
||||
"bootstrap failure requires an execution-fenced repository commit",
|
||||
)
|
||||
return changed, finalState, err
|
||||
}
|
||||
|
||||
@@ -8,6 +8,8 @@ import (
|
||||
|
||||
"github.com/kandev/kandev/internal/agentctl/types/streams"
|
||||
"github.com/kandev/kandev/internal/orchestrator/watcher"
|
||||
"github.com/kandev/kandev/internal/task/models"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// thinkingBlocks400 is the resume-corrupted signature surfaced by the
|
||||
@@ -77,18 +79,28 @@ func TestCreateRecoveryStatusMessage_ManagedRuntimeNpmUsesOneRetryAction(t *test
|
||||
mc := &mockMessageCreator{}
|
||||
svc.messageCreator = mc
|
||||
|
||||
svc.createRecoveryStatusMessage(ctx, watcher.AgentEventData{
|
||||
require.NoError(t, svc.createRecoveryStatusMessage(ctx, watcher.AgentEventData{
|
||||
TaskID: "t-npm",
|
||||
SessionID: "s-npm",
|
||||
ErrorMessage: "managed npm runtime failed to prepare",
|
||||
FailureCode: "managed_runtime_npm_resolution",
|
||||
FailureDetails: "npm error code ETARGET\nnpm error notarget No matching version found",
|
||||
})
|
||||
}))
|
||||
require.NoError(t, svc.createRecoveryStatusMessage(ctx, watcher.AgentEventData{
|
||||
TaskID: "t-npm",
|
||||
SessionID: "s-npm",
|
||||
ErrorMessage: "managed npm runtime failed to prepare",
|
||||
FailureCode: "managed_runtime_npm_resolution",
|
||||
FailureDetails: "npm error code ETARGET\nnpm error notarget No matching version found",
|
||||
}))
|
||||
|
||||
if len(mc.sessionMessages) != 1 {
|
||||
t.Fatalf("expected one recovery message, got %d", len(mc.sessionMessages))
|
||||
}
|
||||
meta := mc.sessionMessages[0].metadata
|
||||
if meta["scope"] != models.ErrorScopeSession || meta["error_stamp"] == "" {
|
||||
t.Fatalf("recovery identity = %#v", meta)
|
||||
}
|
||||
if meta["failure_kind"] != "managed_runtime_npm_resolution" {
|
||||
t.Fatalf("failure_kind = %#v", meta["failure_kind"])
|
||||
}
|
||||
@@ -120,11 +132,11 @@ func TestCreateRecoveryStatusMessage_ResumeCorrupted(t *testing.T) {
|
||||
mc := &mockMessageCreator{}
|
||||
svc.messageCreator = mc
|
||||
|
||||
svc.createRecoveryStatusMessage(ctx, watcher.AgentEventData{
|
||||
require.NoError(t, svc.createRecoveryStatusMessage(ctx, watcher.AgentEventData{
|
||||
TaskID: "t1",
|
||||
SessionID: "s1",
|
||||
ErrorMessage: thinkingBlocks400,
|
||||
})
|
||||
}))
|
||||
|
||||
if len(mc.sessionMessages) != 1 {
|
||||
t.Fatalf("expected 1 session message, got %d", len(mc.sessionMessages))
|
||||
@@ -147,12 +159,12 @@ func TestCreateRecoveryStatusMessage_TransientExhaustionUsesSafeReason(t *testin
|
||||
mc := &mockMessageCreator{}
|
||||
svc.messageCreator = mc
|
||||
|
||||
svc.createRecoveryStatusMessage(ctx, watcher.AgentEventData{
|
||||
require.NoError(t, svc.createRecoveryStatusMessage(ctx, watcher.AgentEventData{
|
||||
TaskID: "t-capacity",
|
||||
SessionID: "s-capacity",
|
||||
AgentID: "codex-acp",
|
||||
ErrorMessage: "Selected model is at capacity. Please try a different model.",
|
||||
})
|
||||
}))
|
||||
|
||||
if len(mc.sessionMessages) != 1 {
|
||||
t.Fatalf("expected 1 session message, got %d", len(mc.sessionMessages))
|
||||
@@ -177,7 +189,7 @@ func TestCreateRecoveryStatusMessage_OpenCodeQuotaCarriesSafeMetadata(t *testing
|
||||
resetAt := time.Date(2026, 8, 2, 19, 34, 44, 0, time.UTC)
|
||||
const wantURL = "https://opencode.ai/workspace/wrk_01KQM7K5CYT715264YKKFB17ZY/go"
|
||||
|
||||
svc.createRecoveryStatusMessage(ctx, watcher.AgentEventData{
|
||||
require.NoError(t, svc.createRecoveryStatusMessage(ctx, watcher.AgentEventData{
|
||||
TaskID: "t-quota",
|
||||
SessionID: "s-quota",
|
||||
AgentID: "opencode-acp",
|
||||
@@ -191,7 +203,7 @@ func TestCreateRecoveryStatusMessage_OpenCodeQuotaCarriesSafeMetadata(t *testing
|
||||
OccurredAt: time.Date(2026, 8, 2, 15, 15, 44, 0, time.UTC),
|
||||
ResetAt: &resetAt,
|
||||
},
|
||||
})
|
||||
}))
|
||||
|
||||
if len(mc.sessionMessages) != 1 {
|
||||
t.Fatalf("expected 1 session message, got %d", len(mc.sessionMessages))
|
||||
@@ -226,7 +238,7 @@ func TestCreateRecoveryStatusMessage_GenericFailureCarriesRemediationURL(t *test
|
||||
|
||||
// A structured ACP-sourced diagnostic is not quota-classified, but the
|
||||
// validated link still reaches the generic recoverable card.
|
||||
svc.createRecoveryStatusMessage(ctx, watcher.AgentEventData{
|
||||
require.NoError(t, svc.createRecoveryStatusMessage(ctx, watcher.AgentEventData{
|
||||
TaskID: "t-generic",
|
||||
SessionID: "s-generic",
|
||||
AgentID: "opencode-acp",
|
||||
@@ -237,7 +249,7 @@ func TestCreateRecoveryStatusMessage_GenericFailureCarriesRemediationURL(t *test
|
||||
RemediationURL: wantURL,
|
||||
OccurredAt: time.Date(2026, 8, 2, 15, 15, 44, 0, time.UTC),
|
||||
},
|
||||
})
|
||||
}))
|
||||
|
||||
if len(mc.sessionMessages) != 1 {
|
||||
t.Fatalf("expected 1 session message, got %d", len(mc.sessionMessages))
|
||||
@@ -279,12 +291,12 @@ func TestProviderRemediationURLRejectsInvalidDiagnostics(t *testing.T) {
|
||||
}},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
svc.createRecoveryStatusMessage(ctx, watcher.AgentEventData{
|
||||
require.NoError(t, svc.createRecoveryStatusMessage(ctx, watcher.AgentEventData{
|
||||
TaskID: "t-none",
|
||||
SessionID: "s-none",
|
||||
ErrorMessage: "provider failed",
|
||||
ProviderError: tt.providerErr,
|
||||
})
|
||||
}))
|
||||
if len(mc.sessionMessages) == 0 {
|
||||
t.Fatal("expected a session message")
|
||||
}
|
||||
@@ -292,6 +304,7 @@ func TestProviderRemediationURLRejectsInvalidDiagnostics(t *testing.T) {
|
||||
t.Fatalf("remediation_url = %#v, want absent", url)
|
||||
}
|
||||
mc.sessionMessages = nil
|
||||
mc.idempotentSessionMessages = nil
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -124,6 +124,7 @@ type MessageCreator interface {
|
||||
// parentToolCallID is the parent Task tool call ID for subagent nesting (empty for top-level).
|
||||
UpdateToolCallMessage(ctx context.Context, taskID, toolCallID, parentToolCallID, status, result, agentSessionID, title, turnID, msgType string, normalized *streams.NormalizedPayload) error
|
||||
CreateSessionMessage(ctx context.Context, taskID, content, agentSessionID, messageType, turnID string, metadata map[string]interface{}, requestsInput bool) error
|
||||
CreateSessionMessageIdempotent(ctx context.Context, messageID, taskID, content, agentSessionID, messageType, turnID string, metadata map[string]interface{}, requestsInput bool) error
|
||||
CreatePermissionRequestMessage(ctx context.Context, taskID, sessionID, requestID, pendingID, toolCallID, title, turnID string, options []map[string]interface{}, actionType string, actionDetails map[string]interface{}) (string, error)
|
||||
UpdatePermissionMessage(ctx context.Context, taskID, sessionID, requestID, pendingID string, status models.PermissionStatus) error
|
||||
ClaimPermissionResolution(ctx context.Context, request models.PermissionResolutionClaimRequest) (*models.PermissionResolutionClaimResult, error)
|
||||
@@ -1707,6 +1708,7 @@ func NewService(
|
||||
})
|
||||
exec.SetOnSessionStateTransition(s.transitionTaskSessionState)
|
||||
exec.SetOnBootstrapFailureTransition(s.transitionBootstrapFailure)
|
||||
exec.SetOnBootstrapFailureMessageRepair(s.persistBootstrapFailureMessage)
|
||||
exec.SetOnSessionStarting(func(
|
||||
ctx context.Context,
|
||||
taskID string,
|
||||
@@ -1728,6 +1730,7 @@ func NewService(
|
||||
ctx, taskID, session, expectedState, promoteTask, allowCompletedResume,
|
||||
)
|
||||
})
|
||||
exec.SetOnLaunchFailed(s.handleLaunchFailed)
|
||||
exec.SetOnExecutionCleanupClaim(s.claimForcedExecutionCleanup)
|
||||
exec.SetOnExecutionStopOwnerRegistration(s.RegisterExecutionStopOwner)
|
||||
exec.SetOnTaskReviewStateReconcile(func(ctx context.Context, taskID, completedSessionID string) {
|
||||
|
||||
@@ -196,6 +196,7 @@ func (s *Service) shouldSkipTerminalPRAutoStart(
|
||||
errorValue := models.TaskLaunchError{
|
||||
Message: terminalPRLaunchMessage,
|
||||
OccurredAt: time.Now().UTC(),
|
||||
Scope: models.ErrorScopeTask,
|
||||
Code: models.LaunchErrorCategoryPRAlreadyClosed,
|
||||
RecoveryActions: terminalPRRecoveryActions(ctx, s.workflowStepGetter, task.WorkflowStepID),
|
||||
TaskRepositoryID: taskPRLaunchErrorRepositoryID(matches),
|
||||
|
||||
@@ -12,7 +12,6 @@ import (
|
||||
"github.com/kandev/kandev/internal/agent/runtime/routingerr"
|
||||
"github.com/kandev/kandev/internal/task/models"
|
||||
taskservice "github.com/kandev/kandev/internal/task/service"
|
||||
"github.com/kandev/kandev/internal/task/statussummary"
|
||||
wfmodels "github.com/kandev/kandev/internal/workflow/models"
|
||||
"github.com/kandev/kandev/internal/worktree"
|
||||
v1 "github.com/kandev/kandev/pkg/api/v1"
|
||||
@@ -65,7 +64,14 @@ type taskLaunchRecoveryRepository interface {
|
||||
UpdateRepositoryDefaultBranch(context.Context, string, string, string) error
|
||||
SetSessionMetadataKeyIfStamp(context.Context, string, string, string, interface{}) (bool, error)
|
||||
SetTaskMetadataKeyIfStamp(context.Context, string, string, string, interface{}) (bool, error)
|
||||
RemoveSessionMetadataKeyIfStamp(context.Context, string, string, string) (bool, error)
|
||||
}
|
||||
|
||||
type taskLaunchRecoveryEnvironmentReader interface {
|
||||
GetTaskEnvironmentByTaskID(context.Context, string) (*models.TaskEnvironment, error)
|
||||
}
|
||||
|
||||
type taskLaunchRecoveryEnvironmentResetter interface {
|
||||
ResetTaskEnvironment(context.Context, string, taskservice.ResetOptions) error
|
||||
}
|
||||
|
||||
type taskLaunchRecoverySource struct {
|
||||
@@ -216,72 +222,35 @@ func (s *Service) verifyCurrentTaskLaunchRecoverySource(
|
||||
ctx context.Context,
|
||||
source *taskLaunchRecoverySource,
|
||||
) error {
|
||||
current, err := s.loadAuthoritativeTaskLaunchRecoveryError(ctx, source.task.ID)
|
||||
if source.sessionOwned {
|
||||
currentSession, err := s.repo.GetTaskSession(ctx, source.session.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if currentSession == nil {
|
||||
return ErrTaskLaunchRecoveryStale
|
||||
}
|
||||
current, found := models.LoadLastAgentError(currentSession.Metadata)
|
||||
if !found || current.IsDismissed() || !current.MatchesStamp(source.errorStamp) {
|
||||
return ErrTaskLaunchRecoveryStale
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
currentTask, err := s.repo.GetTask(ctx, source.task.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if current == nil || current.SessionID != source.sessionID() || current.Stamp != source.errorStamp {
|
||||
if currentTask == nil {
|
||||
return ErrTaskLaunchRecoveryStale
|
||||
}
|
||||
current, found := models.LoadTaskLaunchError(currentTask.Metadata)
|
||||
if !found || !current.MatchesStamp(source.errorStamp) {
|
||||
return ErrTaskLaunchRecoveryStale
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) loadAuthoritativeTaskLaunchRecoveryError(
|
||||
ctx context.Context,
|
||||
taskID string,
|
||||
) (*statussummary.ActiveErrorSummary, error) {
|
||||
task, err := s.repo.GetTask(ctx, taskID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if task == nil {
|
||||
return nil, fmt.Errorf("task %q was not found", taskID)
|
||||
}
|
||||
sessions, err := s.repo.ListTaskSessions(ctx, taskID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
input := statussummary.RebuildInput{Now: time.Now().UTC()}
|
||||
for _, session := range sessions {
|
||||
if session == nil {
|
||||
continue
|
||||
}
|
||||
lastError, found := models.LoadLastAgentError(session.Metadata)
|
||||
if !found || lastError.IsDismissed() {
|
||||
continue
|
||||
}
|
||||
input.Sessions = append(input.Sessions, statussummary.RebuildSession{
|
||||
ID: session.ID,
|
||||
ActiveError: &statussummary.ActiveErrorSummary{
|
||||
SessionID: session.ID,
|
||||
TaskRepositoryID: lastError.TaskRepositoryID,
|
||||
ExecutionID: lastError.ExecutionID,
|
||||
AttemptID: lastError.AttemptID,
|
||||
Phase: lastError.Phase,
|
||||
Stamp: lastError.Stamp(),
|
||||
OccurredAt: lastError.OccurredAt,
|
||||
Preview: lastError.Message,
|
||||
Details: lastError.Details,
|
||||
Category: lastError.Code,
|
||||
RecoveryActions: lastError.RecoveryActions,
|
||||
Causes: lastError.Causes,
|
||||
},
|
||||
})
|
||||
}
|
||||
if launchError, found := models.LoadTaskLaunchError(task.Metadata); found {
|
||||
input.TaskError = &statussummary.ActiveErrorSummary{
|
||||
TaskRepositoryID: launchError.TaskRepositoryID,
|
||||
Stamp: launchError.Stamp(),
|
||||
OccurredAt: launchError.OccurredAt,
|
||||
Preview: launchError.Message,
|
||||
Details: launchError.Details,
|
||||
Category: launchError.Code,
|
||||
RecoveryActions: launchError.RecoveryActions,
|
||||
}
|
||||
}
|
||||
return statussummary.BuildFromAuthoritative(input).ActiveError, nil
|
||||
}
|
||||
|
||||
func (s *Service) loadSessionTaskLaunchRecoverySource(
|
||||
ctx context.Context,
|
||||
req *TaskLaunchRecoveryRequest,
|
||||
@@ -298,7 +267,7 @@ func (s *Service) loadSessionTaskLaunchRecoverySource(
|
||||
return nil, fmt.Errorf("session does not belong to task")
|
||||
}
|
||||
lastError, found := models.LoadLastAgentError(session.Metadata)
|
||||
if !found {
|
||||
if !found || lastError.IsDismissed() {
|
||||
return nil, fmt.Errorf("session has no active launch error")
|
||||
}
|
||||
if !lastError.MatchesStamp(req.ErrorStamp) {
|
||||
@@ -354,13 +323,6 @@ func (source *taskLaunchRecoverySource) taskRepositoryID() string {
|
||||
return source.taskError.TaskRepositoryID
|
||||
}
|
||||
|
||||
func (source *taskLaunchRecoverySource) sessionID() string {
|
||||
if source.sessionOwned && source.session != nil {
|
||||
return source.session.ID
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (source *taskLaunchRecoverySource) recoveryActions() []string {
|
||||
if source.sessionOwned {
|
||||
return source.sessionError.RecoveryActions
|
||||
@@ -492,6 +454,7 @@ func (s *Service) recordSessionUnresolvedDefault(
|
||||
value := models.LastAgentError{
|
||||
Message: message,
|
||||
OccurredAt: time.Now().UTC(),
|
||||
Scope: models.ErrorScopeSession,
|
||||
Code: models.LaunchErrorCategoryDefaultBranchUnresolved,
|
||||
Details: details,
|
||||
RecoveryActions: []string{models.RecoveryActionPickBaseBranch},
|
||||
@@ -530,6 +493,7 @@ func (s *Service) recordTaskUnresolvedDefault(
|
||||
value := models.TaskLaunchError{
|
||||
Message: message,
|
||||
OccurredAt: time.Now().UTC(),
|
||||
Scope: models.ErrorScopeTask,
|
||||
Code: models.LaunchErrorCategoryDefaultBranchUnresolved,
|
||||
Details: details,
|
||||
RecoveryActions: []string{models.RecoveryActionPickBaseBranch},
|
||||
@@ -564,8 +528,13 @@ func (s *Service) relaunchRecoveredTask(ctx context.Context, req *TaskLaunchReco
|
||||
}
|
||||
return response.SessionID, nil
|
||||
}
|
||||
if err := s.resetFailedTaskEnvironmentForRecovery(ctx, req.TaskID); err != nil {
|
||||
return "", err
|
||||
}
|
||||
agentProfileID, _ := s.resolveTaskAgentProfile(ctx, source.task)
|
||||
response, err := s.LaunchSession(ctx, &LaunchSessionRequest{
|
||||
TaskID: req.TaskID,
|
||||
AgentProfileID: agentProfileID,
|
||||
Intent: IntentStart,
|
||||
WorkflowStepID: source.task.WorkflowStepID,
|
||||
})
|
||||
@@ -578,6 +547,29 @@ func (s *Service) relaunchRecoveredTask(ctx context.Context, req *TaskLaunchReco
|
||||
return response.SessionID, nil
|
||||
}
|
||||
|
||||
// resetFailedTaskEnvironmentForRecovery removes the unusable environment left
|
||||
// by a failed first materialization. Ready environments remain attached so a
|
||||
// task-scoped launch error from a later session does not destroy a usable
|
||||
// workspace before retrying.
|
||||
func (s *Service) resetFailedTaskEnvironmentForRecovery(ctx context.Context, taskID string) error {
|
||||
reader, canRead := s.taskLaunchRecoveryTasks.(taskLaunchRecoveryEnvironmentReader)
|
||||
resetter, canReset := s.taskLaunchRecoveryTasks.(taskLaunchRecoveryEnvironmentResetter)
|
||||
if !canRead || !canReset {
|
||||
return nil
|
||||
}
|
||||
environment, err := reader.GetTaskEnvironmentByTaskID(ctx, taskID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("load failed task environment before recovery: %w", err)
|
||||
}
|
||||
if environment == nil || environment.Status != models.TaskEnvironmentStatusFailed {
|
||||
return nil
|
||||
}
|
||||
if err := resetter.ResetTaskEnvironment(ctx, taskID, taskservice.ResetOptions{}); err != nil {
|
||||
return fmt.Errorf("reset failed task environment before recovery: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) markTaskLaunchReviewDone(ctx context.Context, req *TaskLaunchRecoveryRequest, source *taskLaunchRecoverySource) error {
|
||||
if s.taskLaunchRecoveryTasks == nil || s.githubService == nil || s.workflowStepGetter == nil {
|
||||
return fmt.Errorf("review completion recovery is unavailable")
|
||||
@@ -634,8 +626,31 @@ func (s *Service) clearTaskLaunchRecoverySource(ctx context.Context, source *tas
|
||||
if s.taskLaunchRecoveryRepo == nil {
|
||||
return fmt.Errorf("session launch-error compare-and-clear is unavailable")
|
||||
}
|
||||
_, err := s.taskLaunchRecoveryRepo.RemoveSessionMetadataKeyIfStamp(ctx, source.session.ID, models.SessionMetaKeyLastAgentError, source.errorStamp)
|
||||
return err
|
||||
retired := source.sessionError
|
||||
dismissedAt := time.Now().UTC()
|
||||
retired.DismissedAt = &dismissedAt
|
||||
stored, err := s.taskLaunchRecoveryRepo.SetSessionMetadataKeyIfStamp(
|
||||
ctx,
|
||||
source.session.ID,
|
||||
models.SessionMetaKeyLastAgentError,
|
||||
source.errorStamp,
|
||||
retired,
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !stored {
|
||||
return ErrTaskLaunchRecoveryStale
|
||||
}
|
||||
if s.eventBus != nil {
|
||||
if err := s.publishTaskSessionErrorEvent(ctx, source.task.ID, source.session.ID, false, &retired); err != nil {
|
||||
s.logger.Warn("failed to publish retired task session error",
|
||||
zap.String("task_id", source.task.ID),
|
||||
zap.String("session_id", source.session.ID),
|
||||
zap.Error(err))
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
s.clearTaskLaunchErrorIfStamp(ctx, source.task.ID, source.errorStamp)
|
||||
return nil
|
||||
|
||||
@@ -8,6 +8,8 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/kandev/kandev/internal/events"
|
||||
"github.com/kandev/kandev/internal/events/bus"
|
||||
"github.com/kandev/kandev/internal/github"
|
||||
"github.com/kandev/kandev/internal/task/models"
|
||||
sqliterepo "github.com/kandev/kandev/internal/task/repository/sqlite"
|
||||
@@ -24,6 +26,21 @@ type taskLaunchRecoveryServiceFake struct {
|
||||
moved []taskservice.MoveTaskOptions
|
||||
moveErr error
|
||||
moveTaskIDs []string
|
||||
environment *models.TaskEnvironment
|
||||
resetErr error
|
||||
resetCalls int
|
||||
}
|
||||
|
||||
type failingTaskSessionErrorBus struct {
|
||||
bus.EventBus
|
||||
err error
|
||||
}
|
||||
|
||||
func (b failingTaskSessionErrorBus) Publish(ctx context.Context, subject string, event *bus.Event) error {
|
||||
if subject == events.TaskSessionErrorChanged {
|
||||
return b.err
|
||||
}
|
||||
return b.EventBus.Publish(ctx, subject, event)
|
||||
}
|
||||
|
||||
func (f *taskLaunchRecoveryServiceFake) UpdateRepositoryBaseBranch(_ context.Context, req taskservice.UpdateRepositoryBaseBranchRequest) (*models.TaskRepository, error) {
|
||||
@@ -44,6 +61,46 @@ func (f *taskLaunchRecoveryServiceFake) MoveTaskWithOptions(_ context.Context, t
|
||||
return &taskservice.MoveTaskResult{Task: &models.Task{ID: taskID, WorkflowID: workflowID, WorkflowStepID: workflowStepID, Position: position}}, nil
|
||||
}
|
||||
|
||||
func (f *taskLaunchRecoveryServiceFake) GetTaskEnvironmentByTaskID(context.Context, string) (*models.TaskEnvironment, error) {
|
||||
return f.environment, nil
|
||||
}
|
||||
|
||||
func (f *taskLaunchRecoveryServiceFake) ResetTaskEnvironment(context.Context, string, taskservice.ResetOptions) error {
|
||||
f.resetCalls++
|
||||
return f.resetErr
|
||||
}
|
||||
|
||||
func TestResetFailedTaskEnvironmentForRecoveryOnlyResetsFailedEnvironment(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
status models.TaskEnvironmentStatus
|
||||
wantCalls int
|
||||
wantErr bool
|
||||
resetError error
|
||||
}{
|
||||
{name: "no environment", wantCalls: 0},
|
||||
{name: "ready environment", status: models.TaskEnvironmentStatusReady, wantCalls: 0},
|
||||
{name: "failed environment", status: models.TaskEnvironmentStatusFailed, wantCalls: 1},
|
||||
{name: "reset failure", status: models.TaskEnvironmentStatusFailed, wantCalls: 1, wantErr: true, resetError: errors.New("reset failed")},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
fake := &taskLaunchRecoveryServiceFake{resetErr: tc.resetError}
|
||||
if tc.status != "" {
|
||||
fake.environment = &models.TaskEnvironment{ID: "env-1", Status: tc.status}
|
||||
}
|
||||
svc := &Service{taskLaunchRecoveryTasks: fake}
|
||||
|
||||
err := svc.resetFailedTaskEnvironmentForRecovery(context.Background(), "task-1")
|
||||
if (err != nil) != tc.wantErr {
|
||||
t.Fatalf("resetFailedTaskEnvironmentForRecovery error = %v, want error = %t", err, tc.wantErr)
|
||||
}
|
||||
if fake.resetCalls != tc.wantCalls {
|
||||
t.Fatalf("reset calls = %d, want %d", fake.resetCalls, tc.wantCalls)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type taskLaunchRecoveryWorktreeFake struct {
|
||||
branch string
|
||||
err error
|
||||
@@ -132,6 +189,166 @@ func recoveryFixtureService(t *testing.T, repo *sqliterepo.Repository, fake *tas
|
||||
return svc
|
||||
}
|
||||
|
||||
func TestHandleLaunchFailedProjectsTaskErrorAndRetiresSessionMarker(t *testing.T) {
|
||||
repo := setupTestRepo(t)
|
||||
seedSession(t, repo, "task-launch-failure", "session-launch-failure", "step1")
|
||||
now := time.Now().UTC()
|
||||
lastError := models.LastAgentError{
|
||||
Message: "The selected base branch is not available.",
|
||||
OccurredAt: now,
|
||||
Scope: models.ErrorScopeSession,
|
||||
Code: models.LaunchErrorCategoryBaseBranchMissing,
|
||||
Details: "base branch is missing",
|
||||
RecoveryActions: []string{models.RecoveryActionRetryDefault, models.RecoveryActionPickBaseBranch},
|
||||
TaskRepositoryID: "task-repository-launch-failure",
|
||||
StampValue: "launch-failure-stamp",
|
||||
}
|
||||
if err := repo.SetSessionMetadataKey(context.Background(), "session-launch-failure", models.SessionMetaKeyLastAgentError, lastError); err != nil {
|
||||
t.Fatalf("SetSessionMetadataKey: %v", err)
|
||||
}
|
||||
|
||||
svc := createTestService(repo, newMockStepGetter(), newMockTaskRepo())
|
||||
svc.handleLaunchFailed(context.Background(), "task-launch-failure", "session-launch-failure", "repo-1", errors.New("workspace preparation failed"))
|
||||
|
||||
task, err := repo.GetTask(context.Background(), "task-launch-failure")
|
||||
if err != nil {
|
||||
t.Fatalf("GetTask: %v", err)
|
||||
}
|
||||
taskError, ok := models.LoadTaskLaunchError(task.Metadata)
|
||||
if !ok {
|
||||
t.Fatal("task launch error was not persisted")
|
||||
}
|
||||
if taskError.Scope != models.ErrorScopeTask || taskError.SessionID != "session-launch-failure" {
|
||||
t.Fatalf("task launch error ownership = %#v, want task scope with source session", taskError)
|
||||
}
|
||||
if taskError.Stamp() != lastError.Stamp() {
|
||||
t.Fatalf("task launch error stamp = %q, want %q", taskError.Stamp(), lastError.Stamp())
|
||||
}
|
||||
|
||||
session, err := repo.GetTaskSession(context.Background(), "session-launch-failure")
|
||||
if err != nil {
|
||||
t.Fatalf("GetTaskSession: %v", err)
|
||||
}
|
||||
retired, ok := models.LoadLastAgentError(session.Metadata)
|
||||
if !ok || !retired.IsDismissed() {
|
||||
t.Fatalf("session launch error = %#v, want a dismissed correlation marker", retired)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleLaunchFailedKeepsProfileSpecificFailureOnSession(t *testing.T) {
|
||||
repo := setupTestRepo(t)
|
||||
const (
|
||||
taskID = "task-session-owned-launch-failure"
|
||||
sessionID = "session-session-owned-launch-failure"
|
||||
)
|
||||
seedSession(t, repo, taskID, sessionID, "step1")
|
||||
session, err := repo.GetTaskSession(context.Background(), sessionID)
|
||||
if err != nil {
|
||||
t.Fatalf("GetTaskSession: %v", err)
|
||||
}
|
||||
session.AgentProfileID = "profile-specific"
|
||||
if err := repo.UpdateTaskSession(context.Background(), session); err != nil {
|
||||
t.Fatalf("UpdateTaskSession: %v", err)
|
||||
}
|
||||
lastError := models.LastAgentError{
|
||||
Message: "The agent could not start.",
|
||||
OccurredAt: time.Date(2026, 9, 14, 10, 30, 0, 0, time.UTC),
|
||||
Scope: models.ErrorScopeSession,
|
||||
Code: models.LaunchErrorCategoryGenericLaunchFailure,
|
||||
Details: "profile environment could not be resolved",
|
||||
RecoveryActions: []string{models.RecoveryActionRetryLaunch},
|
||||
StampValue: "profile-specific-launch-failure",
|
||||
}
|
||||
if err := repo.SetSessionMetadataKey(
|
||||
context.Background(), sessionID, models.SessionMetaKeyLastAgentError, lastError,
|
||||
); err != nil {
|
||||
t.Fatalf("SetSessionMetadataKey: %v", err)
|
||||
}
|
||||
|
||||
svc := createTestService(repo, newMockStepGetter(), newMockTaskRepo())
|
||||
messages := &mockMessageCreator{}
|
||||
svc.messageCreator = messages
|
||||
svc.handleLaunchFailed(
|
||||
context.Background(), taskID, sessionID, "repo-1", errors.New("profile env resolution failed"),
|
||||
)
|
||||
|
||||
task, err := repo.GetTask(context.Background(), taskID)
|
||||
if err != nil {
|
||||
t.Fatalf("GetTask: %v", err)
|
||||
}
|
||||
if _, found := models.LoadTaskLaunchError(task.Metadata); found {
|
||||
t.Fatal("profile-specific launch failure was incorrectly promoted to task scope")
|
||||
}
|
||||
updated, err := repo.GetTaskSession(context.Background(), sessionID)
|
||||
if err != nil {
|
||||
t.Fatalf("GetTaskSession after launch failure: %v", err)
|
||||
}
|
||||
retained, found := models.LoadLastAgentError(updated.Metadata)
|
||||
if !found || retained.IsDismissed() || retained.Stamp() != lastError.Stamp() {
|
||||
t.Fatalf("session launch error = %#v, want active profile-specific marker", retained)
|
||||
}
|
||||
if updated.AgentProfileID != "profile-specific" {
|
||||
t.Fatalf("session profile = %q, want profile-specific", updated.AgentProfileID)
|
||||
}
|
||||
if len(messages.sessionMessages) != 1 {
|
||||
t.Fatalf("session recovery messages = %d, want 1", len(messages.sessionMessages))
|
||||
}
|
||||
if messages.sessionMessages[0].metadata["scope"] != models.ErrorScopeSession {
|
||||
t.Fatalf("recovery message scope = %#v, want session", messages.sessionMessages[0].metadata["scope"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestClearTaskLaunchRecoverySourceSucceedsWhenRetirementPublishFails(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
const (
|
||||
taskID = "task-session-error-publish"
|
||||
sessionID = "session-error-publish"
|
||||
)
|
||||
repo := setupTestRepo(t)
|
||||
seedSession(t, repo, taskID, sessionID, "step1")
|
||||
lastError := models.LastAgentError{
|
||||
Message: "The agent could not start.",
|
||||
OccurredAt: time.Date(2026, 9, 14, 11, 0, 0, 0, time.UTC),
|
||||
Scope: models.ErrorScopeSession,
|
||||
StampValue: "session-error-publish-stamp",
|
||||
}
|
||||
if err := repo.SetSessionMetadataKey(ctx, sessionID, models.SessionMetaKeyLastAgentError, lastError); err != nil {
|
||||
t.Fatalf("SetSessionMetadataKey: %v", err)
|
||||
}
|
||||
task, err := repo.GetTask(ctx, taskID)
|
||||
if err != nil {
|
||||
t.Fatalf("GetTask: %v", err)
|
||||
}
|
||||
session, err := repo.GetTaskSession(ctx, sessionID)
|
||||
if err != nil {
|
||||
t.Fatalf("GetTaskSession: %v", err)
|
||||
}
|
||||
baseBus := bus.NewMemoryEventBus(testLogger())
|
||||
t.Cleanup(func() { baseBus.Close() })
|
||||
svc := createTestService(repo, newMockStepGetter(), newMockTaskRepo())
|
||||
svc.taskLaunchRecoveryRepo = repo
|
||||
svc.eventBus = failingTaskSessionErrorBus{EventBus: baseBus, err: errors.New("event bus unavailable")}
|
||||
|
||||
err = svc.clearTaskLaunchRecoverySource(ctx, &taskLaunchRecoverySource{
|
||||
task: task,
|
||||
session: session,
|
||||
sessionError: lastError,
|
||||
sessionOwned: true,
|
||||
errorStamp: lastError.Stamp(),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("clearTaskLaunchRecoverySource: %v", err)
|
||||
}
|
||||
updated, err := repo.GetTaskSession(ctx, sessionID)
|
||||
if err != nil {
|
||||
t.Fatalf("reload session: %v", err)
|
||||
}
|
||||
retired, found := models.LoadLastAgentError(updated.Metadata)
|
||||
if !found || !retired.IsDismissed() {
|
||||
t.Fatalf("retired session error = %#v, want dismissed metadata", retired)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecoverTaskLaunchRejectsStaleStampBeforeMutation(t *testing.T) {
|
||||
repo := setupTestRepo(t)
|
||||
seedTaskLaunchRecoveryFixture(t, repo, "task-stale", "task-repo-stale", models.RecoveryActionPickBaseBranch)
|
||||
@@ -150,7 +367,7 @@ func TestRecoverTaskLaunchRejectsStaleStampBeforeMutation(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecoverTaskLaunchRejectsOlderSessionErrorWhenTaskErrorIsNewer(t *testing.T) {
|
||||
func TestRecoverTaskLaunchValidatesSessionErrorIndependentlyOfTaskError(t *testing.T) {
|
||||
repo := setupTestRepo(t)
|
||||
const taskID = "task-newer-task-error"
|
||||
const taskRepositoryID = "task-repo-newer-task-error"
|
||||
@@ -169,6 +386,7 @@ func TestRecoverTaskLaunchRejectsOlderSessionErrorWhenTaskErrorIsNewer(t *testin
|
||||
if err := repo.SetSessionMetadataKey(context.Background(), "session-older-error", models.SessionMetaKeyLastAgentError, models.LastAgentError{
|
||||
Message: "older session launch error",
|
||||
OccurredAt: now.Add(-time.Hour),
|
||||
Scope: models.ErrorScopeSession,
|
||||
Code: models.LaunchErrorCategoryBaseBranchMissing,
|
||||
RecoveryActions: []string{models.RecoveryActionPickBaseBranch},
|
||||
TaskRepositoryID: taskRepositoryID,
|
||||
@@ -179,15 +397,26 @@ func TestRecoverTaskLaunchRejectsOlderSessionErrorWhenTaskErrorIsNewer(t *testin
|
||||
|
||||
fake := &taskLaunchRecoveryServiceFake{branches: []taskservice.Branch{{Name: "main", Type: "remote"}}}
|
||||
svc := recoveryFixtureService(t, repo, fake)
|
||||
_, err := svc.RecoverTaskLaunch(context.Background(), &TaskLaunchRecoveryRequest{
|
||||
req := &TaskLaunchRecoveryRequest{
|
||||
TaskID: taskID, SessionID: "session-older-error", TaskRepositoryID: taskRepositoryID,
|
||||
Action: models.RecoveryActionPickBaseBranch, BaseBranch: "main", ErrorStamp: "older-session-stamp",
|
||||
})
|
||||
if !errors.Is(err, ErrTaskLaunchRecoveryStale) {
|
||||
t.Fatalf("RecoverTaskLaunch error = %v, want stale error", err)
|
||||
}
|
||||
source, err := svc.loadTaskLaunchRecoverySource(context.Background(), req)
|
||||
if err != nil {
|
||||
t.Fatalf("loadTaskLaunchRecoverySource: %v", err)
|
||||
}
|
||||
if err := svc.verifyCurrentTaskLaunchRecoverySource(context.Background(), source); err != nil {
|
||||
t.Fatalf("verifyCurrentTaskLaunchRecoverySource: %v", err)
|
||||
}
|
||||
if len(fake.updated) != 0 {
|
||||
t.Fatalf("older session recovery updated repositories: %#v", fake.updated)
|
||||
t.Fatalf("validation updated repositories: %#v", fake.updated)
|
||||
}
|
||||
task, err := repo.GetTask(context.Background(), taskID)
|
||||
if err != nil {
|
||||
t.Fatalf("GetTask: %v", err)
|
||||
}
|
||||
if taskError, ok := models.LoadTaskLaunchError(task.Metadata); !ok || taskError.Stamp() != "recovery-stamp" {
|
||||
t.Fatalf("task error = %#v, want independent task error", taskError)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4714,26 +4714,27 @@ func TestIssue1884_StepProfileSignalGateStaysInTaskMode(t *testing.T) {
|
||||
// mockMessageCreator implements MessageCreator for testing.
|
||||
// Only CreateUserMessage is tracked; all other methods are no-op stubs.
|
||||
type mockMessageCreator struct {
|
||||
mu sync.Mutex
|
||||
userMessages []mockUserMessage
|
||||
sessionMessages []mockSessionMessage
|
||||
sessionMessageAttempts int
|
||||
sessionMessageDone chan struct{}
|
||||
sessionMessageOnce sync.Once
|
||||
sessionMessageErr error
|
||||
agentMessages []mockAgentMessage
|
||||
agentMessageWrites int
|
||||
agentStreamWrites int
|
||||
agentStreamTexts []string
|
||||
thinkingWrites int
|
||||
toolCallWrites int
|
||||
toolUpdateWrites int
|
||||
userMessageErr error
|
||||
idempotentUserMessages map[string]struct{}
|
||||
permissionClaimFn func(context.Context, models.PermissionResolutionClaimRequest) (*models.PermissionResolutionClaimResult, error)
|
||||
permissionFinishFn func(context.Context, models.PermissionResolutionFinalizeRequest) (*models.PermissionResolutionFinalizeResult, error)
|
||||
permissionAuditFn func(context.Context, string, string, string, string) (*models.PermissionResolutionAudit, error)
|
||||
permissionUpdateFn func(context.Context, string, string, string, string, models.PermissionStatus) error
|
||||
mu sync.Mutex
|
||||
userMessages []mockUserMessage
|
||||
sessionMessages []mockSessionMessage
|
||||
sessionMessageAttempts int
|
||||
sessionMessageDone chan struct{}
|
||||
sessionMessageOnce sync.Once
|
||||
sessionMessageErr error
|
||||
idempotentSessionMessages map[string]struct{}
|
||||
agentMessages []mockAgentMessage
|
||||
agentMessageWrites int
|
||||
agentStreamWrites int
|
||||
agentStreamTexts []string
|
||||
thinkingWrites int
|
||||
toolCallWrites int
|
||||
toolUpdateWrites int
|
||||
userMessageErr error
|
||||
idempotentUserMessages map[string]struct{}
|
||||
permissionClaimFn func(context.Context, models.PermissionResolutionClaimRequest) (*models.PermissionResolutionClaimResult, error)
|
||||
permissionFinishFn func(context.Context, models.PermissionResolutionFinalizeRequest) (*models.PermissionResolutionFinalizeResult, error)
|
||||
permissionAuditFn func(context.Context, string, string, string, string) (*models.PermissionResolutionAudit, error)
|
||||
permissionUpdateFn func(context.Context, string, string, string, string, models.PermissionStatus) error
|
||||
}
|
||||
|
||||
type mockUserMessage struct {
|
||||
@@ -4818,6 +4819,31 @@ func (m *mockMessageCreator) CreateSessionMessage(_ context.Context, taskID, con
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *mockMessageCreator) CreateSessionMessageIdempotent(_ context.Context, messageID, taskID, content, sessionID, messageType, turnID string, metadata map[string]interface{}, requestsInput bool) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if m.sessionMessageErr != nil {
|
||||
return m.sessionMessageErr
|
||||
}
|
||||
if m.idempotentSessionMessages == nil {
|
||||
m.idempotentSessionMessages = make(map[string]struct{})
|
||||
}
|
||||
if _, exists := m.idempotentSessionMessages[messageID]; exists {
|
||||
return nil
|
||||
}
|
||||
m.idempotentSessionMessages[messageID] = struct{}{}
|
||||
m.sessionMessages = append(m.sessionMessages, mockSessionMessage{
|
||||
taskID: taskID,
|
||||
content: content,
|
||||
sessionID: sessionID,
|
||||
messageType: messageType,
|
||||
turnID: turnID,
|
||||
metadata: metadata,
|
||||
requestsInput: requestsInput,
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *mockMessageCreator) CreatePermissionRequestMessage(context.Context, string, string, string, string, string, string, string, []map[string]interface{}, string, map[string]interface{}) (string, error) {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
@@ -506,7 +506,7 @@ func TestWSAddMessage_ConcurrentInitialBriefStartsOnlyAdmittedCandidate(t *testi
|
||||
}
|
||||
|
||||
require.Eventually(t, func() bool { return len(orch.queueCalls()) == 1 }, time.Second, time.Millisecond)
|
||||
require.Len(t, orch.started, 1)
|
||||
require.Eventually(t, func() bool { return len(orch.started) == 1 }, time.Second, time.Millisecond)
|
||||
require.Len(t, repo.messages, 2)
|
||||
queuedCalls := orch.queueCalls()
|
||||
require.True(t, queuedCalls[0].userMessageRecorded)
|
||||
|
||||
@@ -47,6 +47,12 @@ const (
|
||||
const (
|
||||
LaunchErrorPhaseBootstrap = "bootstrap"
|
||||
|
||||
// Error scopes identify the owner of a failure. Session failures belong in
|
||||
// the session transcript; task failures belong to the task shell and remain
|
||||
// visible while the task changes tabs or sessions.
|
||||
ErrorScopeSession = "session"
|
||||
ErrorScopeTask = "task"
|
||||
|
||||
AgentErrorCauseOperationResume = "resume"
|
||||
AgentErrorCauseOperationRestoreWorkspace = "restore_workspace"
|
||||
|
||||
@@ -138,6 +144,8 @@ func isKnownAgentErrorCauseCode(code string) bool {
|
||||
type TaskLaunchError struct {
|
||||
Message string `json:"message"`
|
||||
OccurredAt time.Time `json:"occurred_at"`
|
||||
Scope string `json:"scope,omitempty"`
|
||||
SessionID string `json:"session_id,omitempty"`
|
||||
Code string `json:"code,omitempty"`
|
||||
Details string `json:"details,omitempty"`
|
||||
RecoveryActions []string `json:"recovery_actions,omitempty"`
|
||||
@@ -210,6 +218,7 @@ func isKnownRecoveryAction(action string) bool {
|
||||
}
|
||||
|
||||
func normalizeLastAgentError(value LastAgentError) LastAgentError {
|
||||
value.Scope = normalizeErrorScope(value.Scope, ErrorScopeSession)
|
||||
value.Message = truncateUTF8Bytes(value.Message, maxLaunchErrorMessageBytes)
|
||||
value.Code = truncateUTF8Bytes(value.Code, maxLaunchErrorCategoryBytes)
|
||||
value.RecoveryActions = NormalizeRecoveryActionsForCategory(value.Code, value.RecoveryActions)
|
||||
@@ -233,8 +242,10 @@ func normalizeLastAgentError(value LastAgentError) LastAgentError {
|
||||
}
|
||||
|
||||
func normalizeTaskLaunchError(value TaskLaunchError) TaskLaunchError {
|
||||
value.Scope = normalizeErrorScope(value.Scope, ErrorScopeTask)
|
||||
value.Message = truncateUTF8Bytes(value.Message, maxLaunchErrorMessageBytes)
|
||||
value.Code = truncateUTF8Bytes(value.Code, maxLaunchErrorCategoryBytes)
|
||||
value.SessionID = truncateUTF8Bytes(value.SessionID, maxLaunchErrorIDBytes)
|
||||
value.RecoveryActions = NormalizeRecoveryActionsForCategory(value.Code, value.RecoveryActions)
|
||||
value.TaskRepositoryID = truncateUTF8Bytes(value.TaskRepositoryID, maxTaskRepositoryIDBytes)
|
||||
value.StampValue = boundedLaunchErrorStamp(value.StampValue)
|
||||
@@ -242,6 +253,17 @@ func normalizeTaskLaunchError(value TaskLaunchError) TaskLaunchError {
|
||||
return value
|
||||
}
|
||||
|
||||
func normalizeErrorScope(value, fallback string) string {
|
||||
switch strings.TrimSpace(value) {
|
||||
case ErrorScopeSession:
|
||||
return ErrorScopeSession
|
||||
case ErrorScopeTask:
|
||||
return ErrorScopeTask
|
||||
default:
|
||||
return fallback
|
||||
}
|
||||
}
|
||||
|
||||
// LoadTaskLaunchError reads and validates the task-owned launch error.
|
||||
func LoadTaskLaunchError(metadata map[string]interface{}) (TaskLaunchError, bool) {
|
||||
if metadata == nil {
|
||||
|
||||
@@ -735,6 +735,7 @@ const SessionMetaKeyLastAgentError = "last_agent_error"
|
||||
type LastAgentError struct {
|
||||
Message string `json:"message"`
|
||||
OccurredAt time.Time `json:"occurred_at"`
|
||||
Scope string `json:"scope,omitempty"`
|
||||
AgentExecutionID string `json:"agent_execution_id,omitempty"`
|
||||
ExecutionID string `json:"execution_id,omitempty"`
|
||||
Phase string `json:"phase,omitempty"`
|
||||
|
||||
@@ -606,6 +606,7 @@ func (s *Service) rebuildInput(
|
||||
var activeError *statussummary.ActiveErrorSummary
|
||||
if lastError, ok := models.LoadLastAgentError(session.Metadata); ok && !lastError.IsDismissed() {
|
||||
activeError = &statussummary.ActiveErrorSummary{
|
||||
Scope: models.ErrorScopeSession,
|
||||
SessionID: session.ID,
|
||||
TaskRepositoryID: lastError.TaskRepositoryID,
|
||||
ExecutionID: lastError.ExecutionID,
|
||||
@@ -655,10 +656,13 @@ func taskLaunchErrorSummary(task *models.Task) *statussummary.ActiveErrorSummary
|
||||
return nil
|
||||
}
|
||||
return &statussummary.ActiveErrorSummary{
|
||||
Scope: models.ErrorScopeTask,
|
||||
SessionID: errorValue.SessionID,
|
||||
TaskRepositoryID: errorValue.TaskRepositoryID,
|
||||
Stamp: errorValue.Stamp(),
|
||||
OccurredAt: errorValue.OccurredAt,
|
||||
Preview: errorValue.Message,
|
||||
Details: errorValue.Details,
|
||||
Category: errorValue.Code,
|
||||
RecoveryActions: errorValue.RecoveryActions,
|
||||
}
|
||||
|
||||
@@ -45,6 +45,7 @@ type TaskStatusSummary struct {
|
||||
ActiveSubagentCount int `json:"active_subagent_count,omitempty"`
|
||||
PendingAction string `json:"pending_action,omitempty"`
|
||||
ActiveError *ActiveErrorSummary `json:"active_error,omitempty"`
|
||||
TaskError *ActiveErrorSummary `json:"task_error,omitempty"`
|
||||
Git *GitSummary `json:"git,omitempty"`
|
||||
PullRequest *PullRequestSummary `json:"pull_request,omitempty"`
|
||||
// QueuedPromptCount is the number of prompts currently en-queued for the
|
||||
@@ -60,6 +61,7 @@ type PrimarySessionSummary struct {
|
||||
}
|
||||
|
||||
type ActiveErrorSummary struct {
|
||||
Scope string `json:"scope,omitempty"`
|
||||
SessionID string `json:"session_id,omitempty"`
|
||||
TaskRepositoryID string `json:"task_repository_id,omitempty"`
|
||||
ExecutionID string `json:"execution_id,omitempty"`
|
||||
@@ -136,6 +138,9 @@ func (s TaskStatusSummary) Validate() error {
|
||||
if err := validateActiveError(s.ActiveError); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := validateActiveError(s.TaskError); err != nil {
|
||||
return err
|
||||
}
|
||||
return validatePullRequest(s.PullRequest)
|
||||
}
|
||||
|
||||
@@ -158,6 +163,7 @@ func validateActiveError(activeError *ActiveErrorSummary) error {
|
||||
value string
|
||||
limit int
|
||||
}{
|
||||
{"active error scope", activeError.Scope, maxActiveErrorCategoryBytes},
|
||||
{"active error session id", activeError.SessionID, maxSessionIDBytes},
|
||||
{"active error task repository id", activeError.TaskRepositoryID, maxTaskRepositoryIDBytes},
|
||||
{"active error execution id", activeError.ExecutionID, maxSessionIDBytes},
|
||||
@@ -168,6 +174,9 @@ func validateActiveError(activeError *ActiveErrorSummary) error {
|
||||
{"active error details", activeError.Details, MaxActiveErrorDetailsBytes},
|
||||
{"active error category", activeError.Category, maxActiveErrorCategoryBytes},
|
||||
}
|
||||
if activeError.Scope != "" && activeError.Scope != models.ErrorScopeSession && activeError.Scope != models.ErrorScopeTask {
|
||||
return fmt.Errorf("active error has unknown scope")
|
||||
}
|
||||
for _, field := range fields {
|
||||
if err := validateUTF8Bytes(field.name, field.value, field.limit); err != nil {
|
||||
return err
|
||||
@@ -239,6 +248,7 @@ func (s TaskStatusSummary) SemanticJSON() ([]byte, error) {
|
||||
ActiveSubagentCount: s.ActiveSubagentCount,
|
||||
PendingAction: s.PendingAction,
|
||||
ActiveError: s.ActiveError,
|
||||
TaskError: s.TaskError,
|
||||
Git: s.Git,
|
||||
PullRequest: s.PullRequest,
|
||||
QueuedPromptCount: s.QueuedPromptCount,
|
||||
@@ -252,6 +262,7 @@ type semanticPayload struct {
|
||||
ActiveSubagentCount int `json:"active_subagent_count,omitempty"`
|
||||
PendingAction string `json:"pending_action,omitempty"`
|
||||
ActiveError *ActiveErrorSummary `json:"active_error,omitempty"`
|
||||
TaskError *ActiveErrorSummary `json:"task_error,omitempty"`
|
||||
Git *GitSummary `json:"git,omitempty"`
|
||||
PullRequest *PullRequestSummary `json:"pull_request,omitempty"`
|
||||
QueuedPromptCount int `json:"queued_prompt_count,omitempty"`
|
||||
|
||||
@@ -69,6 +69,11 @@ func TestTaskStatusSummarySemanticJSONIsBoundedAndOmitsTransportMetadata(t *test
|
||||
Stamp: "error-1",
|
||||
Preview: "safe preview",
|
||||
},
|
||||
TaskError: &ActiveErrorSummary{
|
||||
Scope: models.ErrorScopeTask,
|
||||
Stamp: "task-error-1",
|
||||
Preview: "safe task preview",
|
||||
},
|
||||
Git: &GitSummary{ChangedFiles: 2, Additions: 3},
|
||||
}
|
||||
payload, err := summary.SemanticJSON()
|
||||
@@ -85,6 +90,9 @@ func TestTaskStatusSummarySemanticJSONIsBoundedAndOmitsTransportMetadata(t *test
|
||||
if !summary.SemanticEqual(decoded) {
|
||||
t.Fatalf("semantic round trip changed value: %#v", decoded)
|
||||
}
|
||||
if decoded.TaskError == nil || decoded.TaskError.Scope != models.ErrorScopeTask {
|
||||
t.Fatalf("task error missing from semantic payload: %#v", decoded.TaskError)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskStatusSummaryQueuedPromptCountRoundTripsThroughSemanticJSON(t *testing.T) {
|
||||
@@ -173,6 +181,9 @@ func TestTaskStatusSummaryProjectsTaskOwnedErrorFields(t *testing.T) {
|
||||
if got.ActiveError.Category != "pr_already_closed" {
|
||||
t.Fatalf("active error category = %q", got.ActiveError.Category)
|
||||
}
|
||||
if got.TaskError == nil || got.TaskError.Scope != models.ErrorScopeTask {
|
||||
t.Fatalf("task error = %+v, want independent task projection", got.TaskError)
|
||||
}
|
||||
wantActions := []string{"mark_review_done"}
|
||||
if !reflect.DeepEqual(got.ActiveError.RecoveryActions, wantActions) {
|
||||
t.Fatalf("active error actions = %#v, want %#v", got.ActiveError.RecoveryActions, wantActions)
|
||||
|
||||
@@ -2,6 +2,8 @@ package statussummary
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/kandev/kandev/internal/task/models"
|
||||
)
|
||||
|
||||
func deriveSummary(state *projectionState) TaskStatusSummary {
|
||||
@@ -12,6 +14,7 @@ func deriveSummary(state *projectionState) TaskStatusSummary {
|
||||
ActiveSubagentCount: activeSubagentCount,
|
||||
PendingAction: derivePendingAction(state),
|
||||
ActiveError: deriveActiveError(state),
|
||||
TaskError: cloneActiveError(state.taskError),
|
||||
Git: deriveGitSummary(state),
|
||||
PullRequest: derivePullRequestSummary(state),
|
||||
QueuedPromptCount: state.queuedCount,
|
||||
@@ -19,6 +22,16 @@ func deriveSummary(state *projectionState) TaskStatusSummary {
|
||||
}
|
||||
}
|
||||
|
||||
func cloneActiveError(value *ActiveErrorSummary) *ActiveErrorSummary {
|
||||
if value == nil {
|
||||
return nil
|
||||
}
|
||||
copy := *value
|
||||
copy.RecoveryActions = append([]string(nil), value.RecoveryActions...)
|
||||
copy.Causes = append([]models.AgentErrorCause(nil), value.Causes...)
|
||||
return ©
|
||||
}
|
||||
|
||||
func deriveSessionFields(state *projectionState) (*PrimarySessionSummary, string, int) {
|
||||
var primary *sessionObservation
|
||||
activities := make([]string, 0, len(state.sessions))
|
||||
@@ -90,7 +103,7 @@ func derivePendingAction(state *projectionState) string {
|
||||
func deriveActiveError(state *projectionState) *ActiveErrorSummary {
|
||||
var active *ActiveErrorSummary
|
||||
if !state.errorsObserved && state.current != nil && state.current.ActiveError != nil &&
|
||||
(!state.taskErrorObserved || state.current.ActiveError.SessionID != "") {
|
||||
(!state.taskErrorObserved || activeErrorScope(state.current.ActiveError) == models.ErrorScopeSession) {
|
||||
copy := *state.current.ActiveError
|
||||
active = ©
|
||||
}
|
||||
@@ -108,6 +121,18 @@ func deriveActiveError(state *projectionState) *ActiveErrorSummary {
|
||||
return active
|
||||
}
|
||||
|
||||
// activeErrorScope routes explicit ownership first. Older summaries omitted
|
||||
// scope, so their session-id inference remains the compatibility fallback.
|
||||
func activeErrorScope(value *ActiveErrorSummary) string {
|
||||
if value != nil && (value.Scope == models.ErrorScopeSession || value.Scope == models.ErrorScopeTask) {
|
||||
return value.Scope
|
||||
}
|
||||
if value != nil && value.SessionID != "" {
|
||||
return models.ErrorScopeSession
|
||||
}
|
||||
return models.ErrorScopeTask
|
||||
}
|
||||
|
||||
func newerActiveError(candidate, current *ActiveErrorSummary) bool {
|
||||
if candidate == nil {
|
||||
return false
|
||||
|
||||
@@ -330,12 +330,18 @@ func applySummaryBaseline(state *projectionState, summary *TaskStatusSummary) {
|
||||
isPrimary: true,
|
||||
}
|
||||
}
|
||||
if summary.TaskError != nil {
|
||||
copy := *summary.TaskError
|
||||
copy.RecoveryActions = normalizeRecoveryActionsForCategory(copy.Category, copy.RecoveryActions)
|
||||
state.taskError = ©
|
||||
}
|
||||
if summary.ActiveError != nil {
|
||||
copy := *summary.ActiveError
|
||||
copy.RecoveryActions = normalizeRecoveryActionsForCategory(copy.Category, copy.RecoveryActions)
|
||||
if copy.SessionID != "" {
|
||||
scope := activeErrorScope(©)
|
||||
if scope == models.ErrorScopeSession && copy.SessionID != "" {
|
||||
state.errors[copy.SessionID] = ©
|
||||
} else {
|
||||
} else if scope == models.ErrorScopeTask && summary.TaskError == nil {
|
||||
state.taskError = ©
|
||||
}
|
||||
}
|
||||
|
||||
@@ -182,6 +182,7 @@ func errorFromMap(now time.Time, sessionID string, data map[string]interface{})
|
||||
phase = ""
|
||||
}
|
||||
return &ActiveErrorSummary{
|
||||
Scope: normalizeErrorScope(stringField(data, "scope"), sessionID != ""),
|
||||
SessionID: truncateString(sessionID, maxSessionIDBytes),
|
||||
TaskRepositoryID: truncateString(stringField(data, "task_repository_id"), maxTaskRepositoryIDBytes),
|
||||
ExecutionID: truncateString(firstString(data, "execution_id", "agent_execution_id"), maxSessionIDBytes),
|
||||
@@ -201,7 +202,7 @@ func errorEqual(a, b *ActiveErrorSummary) bool {
|
||||
if a == nil || b == nil {
|
||||
return a == b
|
||||
}
|
||||
return a.SessionID == b.SessionID && a.TaskRepositoryID == b.TaskRepositoryID &&
|
||||
return a.Scope == b.Scope && a.SessionID == b.SessionID && a.TaskRepositoryID == b.TaskRepositoryID &&
|
||||
a.ExecutionID == b.ExecutionID && a.AttemptID == b.AttemptID && a.Phase == b.Phase &&
|
||||
a.Stamp == b.Stamp && a.OccurredAt.Equal(b.OccurredAt) &&
|
||||
a.Preview == b.Preview && a.Details == b.Details && a.Category == b.Category &&
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
|
||||
"github.com/kandev/kandev/internal/events"
|
||||
"github.com/kandev/kandev/internal/events/bus"
|
||||
"github.com/kandev/kandev/internal/task/models"
|
||||
)
|
||||
|
||||
func taskErrorProjector(t *testing.T, store *projectorTestStore, loader TaskLaunchErrorLoader) *Projector {
|
||||
@@ -47,14 +48,17 @@ func TestProjectorProjectsTaskOwnedLaunchErrorWithoutSession(t *testing.T) {
|
||||
t.Fatalf("project task error: %v", err)
|
||||
}
|
||||
got := store.summary("task-1")
|
||||
if got == nil || got.ActiveError == nil {
|
||||
t.Fatalf("summary = %+v, want task-owned active error", got)
|
||||
if got == nil || got.TaskError == nil {
|
||||
t.Fatalf("summary = %+v, want task-owned error projection", got)
|
||||
}
|
||||
if got.ActiveError.SessionID != "" || got.ActiveError.TaskRepositoryID != "task-repository-1" {
|
||||
t.Fatalf("active error identity = %+v", got.ActiveError)
|
||||
if got.TaskError.Scope != "task" || got.TaskError.SessionID != "" || got.TaskError.TaskRepositoryID != "task-repository-1" {
|
||||
t.Fatalf("task error identity = %+v", got.TaskError)
|
||||
}
|
||||
if len(got.ActiveError.RecoveryActions) != 1 || got.ActiveError.RecoveryActions[0] != "mark_review_done" {
|
||||
t.Fatalf("active error actions = %#v", got.ActiveError.RecoveryActions)
|
||||
if len(got.TaskError.RecoveryActions) != 1 || got.TaskError.RecoveryActions[0] != "mark_review_done" {
|
||||
t.Fatalf("task error actions = %#v", got.TaskError.RecoveryActions)
|
||||
}
|
||||
if got.ActiveError == nil || got.ActiveError.Scope != "task" {
|
||||
t.Fatalf("active error compatibility projection = %+v", got.ActiveError)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -123,3 +127,60 @@ func TestProjectorRefreshesTaskLaunchErrorRemoval(t *testing.T) {
|
||||
t.Fatalf("summary after task error removal = %+v, want no active error", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProjectorClearsTaskScopedErrorWithOriginatingSessionAfterTaskMetadataRemoval(t *testing.T) {
|
||||
store := newProjectorTestStore()
|
||||
originatingSession := "session-origin"
|
||||
storedError := &ActiveErrorSummary{
|
||||
Scope: models.ErrorScopeTask,
|
||||
SessionID: originatingSession,
|
||||
Stamp: "task-error-1",
|
||||
OccurredAt: time.Date(2026, 8, 19, 19, 0, 0, 0, time.UTC),
|
||||
Preview: "task error",
|
||||
}
|
||||
store.rows["task-1"] = &StoredTaskStatusSummary{
|
||||
TaskID: "task-1",
|
||||
WorkspaceID: "workspace-1",
|
||||
Summary: TaskStatusSummary{
|
||||
Revision: 1,
|
||||
ActiveError: storedError,
|
||||
TaskError: storedError,
|
||||
},
|
||||
}
|
||||
active := true
|
||||
projector := taskErrorProjector(t, store, func(context.Context, string) (TaskLaunchErrorObservation, error) {
|
||||
if !active {
|
||||
return TaskLaunchErrorObservation{Observed: true}, nil
|
||||
}
|
||||
return TaskLaunchErrorObservation{
|
||||
Observed: true,
|
||||
Error: storedError,
|
||||
}, nil
|
||||
})
|
||||
|
||||
event := func() *bus.Event {
|
||||
return bus.NewEvent(events.TaskUpdated, "test", map[string]interface{}{
|
||||
"task_id": "task-1",
|
||||
"workspace_id": "workspace-1",
|
||||
})
|
||||
}
|
||||
if err := projector.HandleEvent(context.Background(), event()); err != nil {
|
||||
t.Fatalf("restore task error: %v", err)
|
||||
}
|
||||
got := store.summary("task-1")
|
||||
if got == nil || got.TaskError == nil || got.ActiveError == nil {
|
||||
t.Fatalf("summary after restore = %+v, want task error in both projections", got)
|
||||
}
|
||||
if got.TaskError.Scope != models.ErrorScopeTask || got.TaskError.SessionID != originatingSession {
|
||||
t.Fatalf("restored task error = %+v, want explicit task scope", got.TaskError)
|
||||
}
|
||||
|
||||
active = false
|
||||
if err := projector.HandleEvent(context.Background(), event()); err != nil {
|
||||
t.Fatalf("clear task error: %v", err)
|
||||
}
|
||||
got = store.summary("task-1")
|
||||
if got == nil || got.TaskError != nil || got.ActiveError != nil {
|
||||
t.Fatalf("summary after task metadata removal = %+v, want both errors cleared", got)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -140,6 +140,7 @@ func normalizeRebuildError(input *ActiveErrorSummary, now time.Time) *ActiveErro
|
||||
copy.OccurredAt = now.UTC()
|
||||
}
|
||||
copy.Preview = truncateString(copy.Preview, MaxActiveErrorPreviewBytes)
|
||||
copy.Scope = normalizeErrorScope(copy.Scope, copy.SessionID != "")
|
||||
copy.SessionID = truncateString(copy.SessionID, maxSessionIDBytes)
|
||||
copy.TaskRepositoryID = truncateString(copy.TaskRepositoryID, maxTaskRepositoryIDBytes)
|
||||
copy.ExecutionID = truncateString(copy.ExecutionID, maxSessionIDBytes)
|
||||
@@ -157,3 +158,13 @@ func normalizeRebuildError(input *ActiveErrorSummary, now time.Time) *ActiveErro
|
||||
copy.Stamp = truncateString(copy.Stamp, maxActiveErrorStampBytes)
|
||||
return ©
|
||||
}
|
||||
|
||||
func normalizeErrorScope(scope string, sessionOwned bool) string {
|
||||
if scope == models.ErrorScopeSession || scope == models.ErrorScopeTask {
|
||||
return scope
|
||||
}
|
||||
if sessionOwned {
|
||||
return models.ErrorScopeSession
|
||||
}
|
||||
return models.ErrorScopeTask
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user