summaryrefslogtreecommitdiff
path: root/internal/executor/executor_test.go
blob: acce95b5f1506ca28249360bf178336fe152b8ed (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
package executor

import (
	"context"
	"fmt"
	"log/slog"
	"os"
	"path/filepath"
	"sync"
	"testing"
	"time"

	"github.com/claudomator/claudomator/internal/storage"
	"github.com/claudomator/claudomator/internal/task"
)

// mockRunner implements Runner for testing.
type mockRunner struct {
	mu       sync.Mutex
	calls    int
	delay    time.Duration
	err      error
	exitCode int
}

func (m *mockRunner) Run(ctx context.Context, t *task.Task, e *storage.Execution) error {
	m.mu.Lock()
	m.calls++
	m.mu.Unlock()

	if m.delay > 0 {
		select {
		case <-time.After(m.delay):
		case <-ctx.Done():
			return ctx.Err()
		}
	}
	if m.err != nil {
		e.ExitCode = m.exitCode
		return m.err
	}
	return nil
}

func (m *mockRunner) callCount() int {
	m.mu.Lock()
	defer m.mu.Unlock()
	return m.calls
}

func testStore(t *testing.T) *storage.DB {
	t.Helper()
	dbPath := filepath.Join(t.TempDir(), "test.db")
	db, err := storage.Open(dbPath)
	if err != nil {
		t.Fatal(err)
	}
	t.Cleanup(func() { db.Close() })
	return db
}

func makeTask(id string) *task.Task {
	now := time.Now().UTC()
	return &task.Task{
		ID: id, Name: "Test " + id,
		Claude:    task.ClaudeConfig{Instructions: "test"},
		Priority:  task.PriorityNormal,
		Retry:     task.RetryConfig{MaxAttempts: 1, Backoff: "linear"},
		Tags:      []string{},
		DependsOn: []string{},
		State:     task.StateQueued,
		CreatedAt: now, UpdatedAt: now,
	}
}

func TestPool_Submit_Success(t *testing.T) {
	store := testStore(t)
	runner := &mockRunner{}
	logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))
	pool := NewPool(2, runner, store, logger)

	tk := makeTask("ps-1")
	store.CreateTask(tk)

	if err := pool.Submit(context.Background(), tk); err != nil {
		t.Fatalf("submit: %v", err)
	}

	result := <-pool.Results()
	if result.Err != nil {
		t.Errorf("expected no error, got: %v", result.Err)
	}
	if result.Execution.Status != "COMPLETED" {
		t.Errorf("status: want COMPLETED, got %q", result.Execution.Status)
	}

	// Verify task state in DB.
	got, _ := store.GetTask("ps-1")
	if got.State != task.StateCompleted {
		t.Errorf("task state: want COMPLETED, got %v", got.State)
	}
}

func TestPool_Submit_Failure(t *testing.T) {
	store := testStore(t)
	runner := &mockRunner{err: fmt.Errorf("boom"), exitCode: 1}
	logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))
	pool := NewPool(2, runner, store, logger)

	tk := makeTask("pf-1")
	store.CreateTask(tk)
	pool.Submit(context.Background(), tk)

	result := <-pool.Results()
	if result.Err == nil {
		t.Fatal("expected error")
	}
	if result.Execution.Status != "FAILED" {
		t.Errorf("status: want FAILED, got %q", result.Execution.Status)
	}
}

func TestPool_Submit_Timeout(t *testing.T) {
	store := testStore(t)
	runner := &mockRunner{delay: 5 * time.Second}
	logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))
	pool := NewPool(2, runner, store, logger)

	tk := makeTask("pt-1")
	tk.Timeout.Duration = 50 * time.Millisecond
	store.CreateTask(tk)
	pool.Submit(context.Background(), tk)

	result := <-pool.Results()
	if result.Execution.Status != "TIMED_OUT" {
		t.Errorf("status: want TIMED_OUT, got %q", result.Execution.Status)
	}
}

func TestPool_Submit_Cancellation(t *testing.T) {
	store := testStore(t)
	runner := &mockRunner{delay: 5 * time.Second}
	logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))
	pool := NewPool(2, runner, store, logger)

	ctx, cancel := context.WithCancel(context.Background())
	tk := makeTask("pc-1")
	store.CreateTask(tk)
	pool.Submit(ctx, tk)

	time.Sleep(20 * time.Millisecond)
	cancel()

	result := <-pool.Results()
	if result.Execution.Status != "CANCELLED" {
		t.Errorf("status: want CANCELLED, got %q", result.Execution.Status)
	}
}

func TestPool_AtCapacity(t *testing.T) {
	store := testStore(t)
	runner := &mockRunner{delay: time.Second}
	logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))
	pool := NewPool(1, runner, store, logger)

	tk1 := makeTask("cap-1")
	store.CreateTask(tk1)
	pool.Submit(context.Background(), tk1)

	// Pool is at capacity, second submit should fail.
	time.Sleep(10 * time.Millisecond) // let goroutine start
	tk2 := makeTask("cap-2")
	store.CreateTask(tk2)
	err := pool.Submit(context.Background(), tk2)
	if err == nil {
		t.Fatal("expected capacity error")
	}

	<-pool.Results() // drain
}

func TestPool_ConcurrentExecution(t *testing.T) {
	store := testStore(t)
	runner := &mockRunner{delay: 50 * time.Millisecond}
	logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))
	pool := NewPool(3, runner, store, logger)

	for i := 0; i < 3; i++ {
		tk := makeTask(fmt.Sprintf("cc-%d", i))
		store.CreateTask(tk)
		if err := pool.Submit(context.Background(), tk); err != nil {
			t.Fatalf("submit %d: %v", i, err)
		}
	}

	for i := 0; i < 3; i++ {
		result := <-pool.Results()
		if result.Execution.Status != "COMPLETED" {
			t.Errorf("task %s: want COMPLETED, got %q", result.TaskID, result.Execution.Status)
		}
	}

	if runner.callCount() != 3 {
		t.Errorf("calls: want 3, got %d", runner.callCount())
	}
}