summaryrefslogtreecommitdiff
path: root/internal/storage/db_test.go
blob: 78cb1e14178b4621a40b05c315afea82c291fc03 (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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
package storage

import (
	"fmt"
	"path/filepath"
	"testing"
	"time"

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

func testDB(t *testing.T) *DB {
	t.Helper()
	dbPath := filepath.Join(t.TempDir(), "test.db")
	db, err := Open(dbPath)
	if err != nil {
		t.Fatalf("opening db: %v", err)
	}
	t.Cleanup(func() { db.Close() })
	return db
}

func TestOpen_CreatesSchema(t *testing.T) {
	db := testDB(t)
	// Should be able to query tasks table.
	_, err := db.ListTasks(TaskFilter{})
	if err != nil {
		t.Fatalf("querying tasks: %v", err)
	}
}

func TestCreateTask_AndGetTask(t *testing.T) {
	db := testDB(t)
	now := time.Now().UTC().Truncate(time.Second)

	tk := &task.Task{
		ID:          "task-1",
		Name:        "Test Task",
		Description: "A test",
		Claude: task.ClaudeConfig{
			Model:        "sonnet",
			Instructions: "do it",
			WorkingDir:   "/tmp",
			MaxBudgetUSD: 2.5,
		},
		Priority:  task.PriorityHigh,
		Tags:      []string{"test", "alpha"},
		DependsOn: []string{},
		Retry:     task.RetryConfig{MaxAttempts: 3, Backoff: "exponential"},
		State:     task.StatePending,
		CreatedAt: now,
		UpdatedAt: now,
	}
	tk.Timeout.Duration = 10 * time.Minute

	if err := db.CreateTask(tk); err != nil {
		t.Fatalf("creating task: %v", err)
	}

	got, err := db.GetTask("task-1")
	if err != nil {
		t.Fatalf("getting task: %v", err)
	}
	if got.Name != "Test Task" {
		t.Errorf("name: want 'Test Task', got %q", got.Name)
	}
	if got.Claude.Model != "sonnet" {
		t.Errorf("model: want 'sonnet', got %q", got.Claude.Model)
	}
	if got.Claude.MaxBudgetUSD != 2.5 {
		t.Errorf("budget: want 2.5, got %f", got.Claude.MaxBudgetUSD)
	}
	if got.Priority != task.PriorityHigh {
		t.Errorf("priority: want 'high', got %q", got.Priority)
	}
	if got.Timeout.Duration != 10*time.Minute {
		t.Errorf("timeout: want 10m, got %v", got.Timeout.Duration)
	}
	if got.Retry.MaxAttempts != 3 {
		t.Errorf("retry: want 3, got %d", got.Retry.MaxAttempts)
	}
	if len(got.Tags) != 2 || got.Tags[0] != "test" {
		t.Errorf("tags: want [test alpha], got %v", got.Tags)
	}
	if got.State != task.StatePending {
		t.Errorf("state: want PENDING, got %v", got.State)
	}
}

func TestUpdateTaskState(t *testing.T) {
	db := testDB(t)
	now := time.Now().UTC()
	tk := &task.Task{
		ID:        "task-2",
		Name:      "Stateful",
		Claude:    task.ClaudeConfig{Instructions: "test"},
		Priority:  task.PriorityNormal,
		Retry:     task.RetryConfig{MaxAttempts: 1, Backoff: "linear"},
		Tags:      []string{},
		DependsOn: []string{},
		State:     task.StatePending,
		CreatedAt: now,
		UpdatedAt: now,
	}
	if err := db.CreateTask(tk); err != nil {
		t.Fatal(err)
	}

	if err := db.UpdateTaskState("task-2", task.StateQueued); err != nil {
		t.Fatalf("updating state: %v", err)
	}
	got, _ := db.GetTask("task-2")
	if got.State != task.StateQueued {
		t.Errorf("state: want QUEUED, got %v", got.State)
	}
}

func TestUpdateTaskState_NotFound(t *testing.T) {
	db := testDB(t)
	err := db.UpdateTaskState("nonexistent", task.StateQueued)
	if err == nil {
		t.Fatal("expected error for nonexistent task")
	}
}

func TestListTasks_FilterByState(t *testing.T) {
	db := testDB(t)
	now := time.Now().UTC()

	for i, state := range []task.State{task.StatePending, task.StatePending, task.StateRunning} {
		tk := &task.Task{
			ID: fmt.Sprintf("t-%d", i), Name: fmt.Sprintf("Task %d", i),
			Claude: task.ClaudeConfig{Instructions: "x"}, Priority: task.PriorityNormal,
			Retry: task.RetryConfig{MaxAttempts: 1, Backoff: "linear"},
			Tags: []string{}, DependsOn: []string{},
			State: state, CreatedAt: now, UpdatedAt: now,
		}
		if err := db.CreateTask(tk); err != nil {
			t.Fatal(err)
		}
	}

	pending, err := db.ListTasks(TaskFilter{State: task.StatePending})
	if err != nil {
		t.Fatal(err)
	}
	if len(pending) != 2 {
		t.Errorf("want 2 pending, got %d", len(pending))
	}

	running, err := db.ListTasks(TaskFilter{State: task.StateRunning})
	if err != nil {
		t.Fatal(err)
	}
	if len(running) != 1 {
		t.Errorf("want 1 running, got %d", len(running))
	}
}

func TestListTasks_WithLimit(t *testing.T) {
	db := testDB(t)
	now := time.Now().UTC()
	for i := 0; i < 5; i++ {
		tk := &task.Task{
			ID: fmt.Sprintf("lt-%d", i), Name: fmt.Sprintf("T%d", i),
			Claude: task.ClaudeConfig{Instructions: "x"}, Priority: task.PriorityNormal,
			Retry: task.RetryConfig{MaxAttempts: 1, Backoff: "linear"},
			Tags: []string{}, DependsOn: []string{},
			State: task.StatePending, CreatedAt: now.Add(time.Duration(i) * time.Second), UpdatedAt: now,
		}
		db.CreateTask(tk)
	}

	tasks, err := db.ListTasks(TaskFilter{Limit: 3})
	if err != nil {
		t.Fatal(err)
	}
	if len(tasks) != 3 {
		t.Errorf("want 3, got %d", len(tasks))
	}
}

func TestCreateExecution_AndGet(t *testing.T) {
	db := testDB(t)
	now := time.Now().UTC().Truncate(time.Second)

	// Need a task first.
	tk := &task.Task{
		ID: "etask", Name: "E", Claude: task.ClaudeConfig{Instructions: "x"},
		Priority: task.PriorityNormal, Retry: task.RetryConfig{MaxAttempts: 1, Backoff: "linear"},
		Tags: []string{}, DependsOn: []string{},
		State: task.StatePending, CreatedAt: now, UpdatedAt: now,
	}
	db.CreateTask(tk)

	exec := &Execution{
		ID:         "exec-1",
		TaskID:     "etask",
		StartTime:  now,
		EndTime:    now.Add(5 * time.Minute),
		ExitCode:   0,
		Status:     "COMPLETED",
		StdoutPath: "/tmp/stdout.log",
		StderrPath: "/tmp/stderr.log",
		CostUSD:    0.42,
	}
	if err := db.CreateExecution(exec); err != nil {
		t.Fatalf("creating execution: %v", err)
	}

	got, err := db.GetExecution("exec-1")
	if err != nil {
		t.Fatalf("getting execution: %v", err)
	}
	if got.Status != "COMPLETED" {
		t.Errorf("status: want COMPLETED, got %q", got.Status)
	}
	if got.CostUSD != 0.42 {
		t.Errorf("cost: want 0.42, got %f", got.CostUSD)
	}
	if got.ExitCode != 0 {
		t.Errorf("exit code: want 0, got %d", got.ExitCode)
	}
}

func TestListExecutions(t *testing.T) {
	db := testDB(t)
	now := time.Now().UTC()
	tk := &task.Task{
		ID: "ltask", Name: "L", Claude: task.ClaudeConfig{Instructions: "x"},
		Priority: task.PriorityNormal, Retry: task.RetryConfig{MaxAttempts: 1, Backoff: "linear"},
		Tags: []string{}, DependsOn: []string{},
		State: task.StatePending, CreatedAt: now, UpdatedAt: now,
	}
	db.CreateTask(tk)

	for i := 0; i < 3; i++ {
		db.CreateExecution(&Execution{
			ID: fmt.Sprintf("le-%d", i), TaskID: "ltask",
			StartTime: now.Add(time.Duration(i) * time.Minute), EndTime: now.Add(time.Duration(i+1) * time.Minute),
			Status: "COMPLETED",
		})
	}

	execs, err := db.ListExecutions("ltask")
	if err != nil {
		t.Fatal(err)
	}
	if len(execs) != 3 {
		t.Errorf("want 3, got %d", len(execs))
	}
}

func TestUpdateExecution(t *testing.T) {
	db := testDB(t)
	now := time.Now().UTC()
	tk := &task.Task{
		ID: "utask", Name: "U", Claude: task.ClaudeConfig{Instructions: "x"},
		Priority: task.PriorityNormal, Retry: task.RetryConfig{MaxAttempts: 1, Backoff: "linear"},
		Tags: []string{}, DependsOn: []string{},
		State: task.StatePending, CreatedAt: now, UpdatedAt: now,
	}
	db.CreateTask(tk)

	exec := &Execution{
		ID: "ue-1", TaskID: "utask", StartTime: now, EndTime: now, Status: "RUNNING",
	}
	db.CreateExecution(exec)

	exec.Status = "FAILED"
	exec.ExitCode = 1
	exec.ErrorMsg = "something broke"
	exec.EndTime = now.Add(2 * time.Minute)
	if err := db.UpdateExecution(exec); err != nil {
		t.Fatal(err)
	}

	got, _ := db.GetExecution("ue-1")
	if got.Status != "FAILED" {
		t.Errorf("status: want FAILED, got %q", got.Status)
	}
	if got.ErrorMsg != "something broke" {
		t.Errorf("error: want 'something broke', got %q", got.ErrorMsg)
	}
}