fix(lifecycle): preserve typed error chain across launch prepare failure (#2783)

Co-authored-by: Carlos Florencio <carlosmflorencio@gmail.com>
This commit is contained in:
WaleWangPW
2026-08-19 05:43:45 +08:00
committed by GitHub
parent 8e33bc9881
commit 9c5888abc8
6 changed files with 257 additions and 2 deletions
@@ -176,8 +176,26 @@ type EnvPrepareResult struct {
// Worktrees is the per-repository outcome list when the preparer ran in
// multi-repo mode. Empty for single-repo or repo-less results.
Worktrees []RepoWorktreeResult `json:"worktrees,omitempty"`
// Error carries the underlying typed error chain when Success is false.
// Populated alongside ErrorMessage so that callers wrapping the result
// can use %w to preserve errors.Is/errors.As reachability for sentinels
// like worktree.ErrBranchCheckedOut. ErrorMessage remains the canonical
// human-readable string; Error is the typed chain for programmatic use.
Error error `json:"-"`
}
// prepareResultError keeps the display message separate from the typed cause.
// The display message can be sanitized while errors.Is/errors.As still reach
// the original cause through Unwrap.
type prepareResultError struct {
message string
cause error
}
func (e *prepareResultError) Error() string { return e.message }
func (e *prepareResultError) Unwrap() error { return e.cause }
// PrepareProgressCallback is called when a preparation step changes status.
type PrepareProgressCallback func(step PrepareStep, stepIndex int, totalSteps int)
@@ -2,6 +2,7 @@ package lifecycle
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
@@ -76,14 +77,15 @@ func (p *WorktreePreparer) Prepare(ctx context.Context, req *EnvPrepareRequest,
// Step 1: Validate repository path
steps, ok := p.validateWorktreeRequest(req, stepIdx, totalSteps, onProgress, steps)
if !ok {
return &EnvPrepareResult{Success: false, Steps: steps, ErrorMessage: steps[len(steps)-1].Error, Duration: time.Since(start)}, nil
msg := steps[len(steps)-1].Error
return &EnvPrepareResult{Success: false, Steps: steps, ErrorMessage: msg, Error: errors.New(msg), Duration: time.Since(start)}, nil
}
stepIdx++
// Steps 2 (and optional sync): Create worktree (with optional pre-sync).
wt, steps, stepIdx, err := p.createWorktreeWithSync(ctx, req, stepIdx, totalSteps, onProgress, steps)
if err != nil {
return &EnvPrepareResult{Success: false, Steps: steps, ErrorMessage: err.Error(), Duration: time.Since(start)}, nil
return &EnvPrepareResult{Success: false, Steps: steps, ErrorMessage: err.Error(), Error: err, Duration: time.Since(start)}, nil
}
if len(wt.CopiedFiles) > 0 || len(wt.CopyFilesWarnings) > 0 {
@@ -368,6 +370,7 @@ func (p *WorktreePreparer) prepareMultiRepo(
Success: false,
Steps: steps,
ErrorMessage: step.Error,
Error: errors.New(step.Error),
Duration: time.Since(start),
}, nil
}
@@ -403,6 +406,7 @@ func (p *WorktreePreparer) prepareMultiRepo(
Success: false,
Steps: steps,
ErrorMessage: err.Error(),
Error: err,
Duration: time.Since(start),
}, nil
}
@@ -46,6 +46,9 @@ func TestWorktreePreparer_ValidateRepository_FailsOnNonGitPath(t *testing.T) {
if res.Success {
t.Fatal("expected prepare to fail for a repository path with no .git directory")
}
if res.Error == nil {
t.Fatal("expected failed prepare result to retain its error cause")
}
if !strings.Contains(res.ErrorMessage, "not a git repository") {
t.Errorf("ErrorMessage = %q, want it to mention the path is not a git repository", res.ErrorMessage)
}
@@ -87,6 +90,9 @@ func TestWorktreePreparer_MultiRepo_ValidateRepository_FailsOnNonGitPath(t *test
if res.Success {
t.Fatal("expected prepare to fail when the secondary repo path has no .git directory")
}
if res.Error == nil {
t.Fatal("expected failed multi-repo result to retain its error cause")
}
if !strings.Contains(res.ErrorMessage, "not a git repository") {
t.Errorf("ErrorMessage = %q, want it to mention the path is not a git repository", res.ErrorMessage)
}
@@ -277,6 +277,9 @@ func TestWorktreePreparer_MultiRepo_RollbackOnPartialFailure(t *testing.T) {
if res.ErrorMessage == "" {
t.Error("expected non-empty error message")
}
if res.Error == nil {
t.Error("expected failed multi-repo result to retain its error cause")
}
// Rollback: no worktrees should remain in the store after partial failure.
all, err := mgr.GetAllByTaskID(context.Background(), "task-multi-fail")
@@ -895,6 +895,7 @@ func (m *Manager) runEnvironmentPreparerWithProgress(
return &EnvPrepareResult{
Success: false,
ErrorMessage: err.Error(),
Error: err,
}
}
@@ -985,6 +986,20 @@ func (m *Manager) launchApplyPrepareResult(
ErrorMessage: result.ErrorMessage,
Steps: result.Steps,
})
// Prefer the typed chain on result.Error so errors.Is/errors.As reach
// the underlying sentinel (worktree.ErrBranchCheckedOut, etc.). Fall
// back to the textual ErrorMessage when the preparer did not supply a
// typed error. The formatted message is identical in both cases.
if result.Error != nil {
displayMessage := result.ErrorMessage
if displayMessage == "" {
displayMessage = result.Error.Error()
}
return fmt.Errorf("environment preparation failed: %w", &prepareResultError{
message: displayMessage,
cause: result.Error,
})
}
return fmt.Errorf("environment preparation failed: %s", result.ErrorMessage)
}
if result.WorkspacePath != "" {
@@ -0,0 +1,209 @@
package lifecycle
import (
"context"
"errors"
"testing"
"github.com/stretchr/testify/require"
"github.com/kandev/kandev/internal/worktree"
)
// errorChainPreparer is an EnvironmentPreparer that returns a failed
// EnvPrepareResult carrying a typed error chain. The orchestrator and any
// other consumer downstream of launchApplyPrepareResult must still be able
// to reach the underlying sentinel via errors.Is.
type errorChainPreparer struct {
err error
}
func (p *errorChainPreparer) Name() string { return "error-chain" }
func (p *errorChainPreparer) Prepare(_ context.Context, _ *EnvPrepareRequest, _ PrepareProgressCallback) (*EnvPrepareResult, error) {
return &EnvPrepareResult{
Success: false,
ErrorMessage: p.err.Error(),
Error: p.err,
Steps: []PrepareStep{{Name: "Create worktree", Status: PrepareStepFailed, Error: p.err.Error()}},
}, nil
}
type directErrorPreparer struct {
err error
}
func (p *directErrorPreparer) Name() string { return "direct-error" }
func (p *directErrorPreparer) Prepare(_ context.Context, _ *EnvPrepareRequest, _ PrepareProgressCallback) (*EnvPrepareResult, error) {
return nil, p.err
}
// newErrorChainTestManager builds a Manager just rich enough to call
// launchApplyPrepareResult. Only the eventPublisher field is exercised.
func newErrorChainTestManager(t *testing.T) *Manager {
t.Helper()
mgr, _ := createTestManagerWithTracking()
return mgr
}
func TestLaunchApplyPrepareResult_PreservesTypedChainViaWorktreeSentinel(t *testing.T) {
mgr := newErrorChainTestManager(t)
cleanupManagerStopCh(t, mgr)
// ClassifyGitError wraps with %w so the typed sentinel is at the head of
// the chain — exactly the path that previously lost identity when
// env_preparer_worktree flattened the error into ErrorMessage.
underlying := worktree.ClassifyGitError(
"fatal: 'feature/foo' is already checked out at '/tmp/repo/.git/worktrees/other'",
nil,
)
var workspacePath, mainRepoGitDir, worktreeID, worktreeBranch string
err := mgr.launchApplyPrepareResult(
&LaunchRequest{TaskID: "task-1", SessionID: "session-1"},
&EnvPrepareResult{
Success: false,
ErrorMessage: underlying.Error(),
Error: underlying,
},
&workspacePath, &mainRepoGitDir, &worktreeID, &worktreeBranch,
)
require.Error(t, err)
if !errors.Is(err, worktree.ErrBranchCheckedOut) {
t.Fatalf("errors.Is(err, worktree.ErrBranchCheckedOut) = false; err = %v", err)
}
// The formatted message must remain byte-compatible with the prior
// %s-based wrap: "environment preparation failed: <underlying.Error()>".
// This protects downstream consumers that grep ErrorMessage / log output
// for the well-known prefix.
require.Contains(t, err.Error(), "environment preparation failed: branch is already checked out in another worktree")
}
func TestLaunchApplyPrepareResult_FallsBackToErrorMessageWhenErrorNil(t *testing.T) {
mgr := newErrorChainTestManager(t)
cleanupManagerStopCh(t, mgr)
var workspacePath, mainRepoGitDir, worktreeID, worktreeBranch string
err := mgr.launchApplyPrepareResult(
&LaunchRequest{TaskID: "task-2", SessionID: "session-2"},
&EnvPrepareResult{
Success: false,
ErrorMessage: "no repository path provided",
// Error intentionally nil — mirrors the validate-step failure
// path where no typed sentinel exists.
},
&workspacePath, &mainRepoGitDir, &worktreeID, &worktreeBranch,
)
require.Error(t, err)
require.Equal(t, "environment preparation failed: no repository path provided", err.Error())
}
func TestLaunchApplyPrepareResult_UsesDisplayMessageAndPreservesCause(t *testing.T) {
mgr := newErrorChainTestManager(t)
cleanupManagerStopCh(t, mgr)
cause := errors.New("raw cause contains internal detail")
var workspacePath, mainRepoGitDir, worktreeID, worktreeBranch string
err := mgr.launchApplyPrepareResult(
&LaunchRequest{TaskID: "task-2b", SessionID: "session-2b"},
&EnvPrepareResult{
Success: false,
ErrorMessage: "safe display message",
Error: cause,
},
&workspacePath, &mainRepoGitDir, &worktreeID, &worktreeBranch,
)
require.Error(t, err)
require.Equal(t, "environment preparation failed: safe display message", err.Error())
require.ErrorIs(t, err, cause)
}
func TestRunEnvironmentPreparerWithProgress_PropagatesTypedErrorChain(t *testing.T) {
mgr := newErrorChainTestManager(t)
cleanupManagerStopCh(t, mgr)
registry := NewPreparerRegistry(mgr.logger)
registry.Register("worktree", &errorChainPreparer{
err: worktree.ClassifyGitError(
"fatal: 'feature/bar' is already used by worktree at '/tmp/repo/.git/worktrees/other'",
nil,
),
})
mgr.preparerRegistry = registry
result := mgr.runEnvironmentPreparerWithProgress(
context.Background(),
&LaunchRequest{
TaskID: "task-3",
SessionID: "session-3",
ExecutorType: "worktree",
RepositoryPath: "/tmp/repo",
},
"",
func(PrepareStep, int, int) {},
)
require.NotNil(t, result)
require.False(t, result.Success)
require.NotNil(t, result.Error)
require.True(t, errors.Is(result.Error, worktree.ErrBranchCheckedOut),
"preparer Error must carry the worktree.ErrBranchCheckedOut sentinel")
// Drive the wrapper too — together these prove the typed sentinel
// survives end-to-end.
var workspacePath, mainRepoGitDir, worktreeID, worktreeBranch string
wrapped := mgr.launchApplyPrepareResult(
&LaunchRequest{TaskID: "task-3", SessionID: "session-3"},
result,
&workspacePath, &mainRepoGitDir, &worktreeID, &worktreeBranch,
)
require.Error(t, wrapped)
require.True(t, errors.Is(wrapped, worktree.ErrBranchCheckedOut),
"wrapped launch error must still expose worktree.ErrBranchCheckedOut")
}
func TestRunEnvironmentPreparerWithProgress_PreservesDirectErrorChain(t *testing.T) {
mgr := newErrorChainTestManager(t)
cleanupManagerStopCh(t, mgr)
registry := NewPreparerRegistry(mgr.logger)
registry.Register("worktree", &directErrorPreparer{
err: worktree.ClassifyGitError(
"fatal: 'feature/direct' is already used by worktree at '/tmp/repo/.git/worktrees/other'",
nil,
),
})
mgr.preparerRegistry = registry
result := mgr.runEnvironmentPreparerWithProgress(
context.Background(),
&LaunchRequest{
TaskID: "task-4",
SessionID: "session-4",
ExecutorType: "worktree",
RepositoryPath: "/tmp/repo",
},
"",
func(PrepareStep, int, int) {},
)
require.NotNil(t, result)
require.False(t, result.Success)
require.ErrorIs(t, result.Error, worktree.ErrBranchCheckedOut)
}
func TestWorktreePreparerMultiRepoFailureCarriesError(t *testing.T) {
preparer := NewWorktreePreparer(nil, newTestLocalLogger())
result, err := preparer.Prepare(context.Background(), &EnvPrepareRequest{
Repositories: []RepoPrepareSpec{
{RepositoryID: "repo-a", RepositoryPath: "/tmp/repo-a"},
{RepositoryID: "repo-b", RepositoryPath: "/tmp/repo-b"},
},
}, nil)
require.NoError(t, err)
require.NotNil(t, result)
require.False(t, result.Success)
require.Error(t, result.Error)
}