-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathworker_test.go
More file actions
769 lines (691 loc) · 22.4 KB
/
Copy pathworker_test.go
File metadata and controls
769 lines (691 loc) · 22.4 KB
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
package worker
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/gorilla/websocket"
"github.com/warpdotdev/oz-agent-worker/internal/metrics"
"github.com/warpdotdev/oz-agent-worker/internal/types"
"go.opentelemetry.io/otel/trace"
)
type shutdownRecordingBackend struct {
shutdownCalled bool
shutdownCtxErr error
}
func (b *shutdownRecordingBackend) ExecuteTask(context.Context, *TaskParams) error {
return nil
}
func (b *shutdownRecordingBackend) Shutdown(ctx context.Context) {
b.shutdownCalled = true
b.shutdownCtxErr = ctx.Err()
}
func (b *shutdownRecordingBackend) PreservesTasksOnShutdown() bool {
return false
}
type preservingShutdownRecordingBackend struct {
shutdownRecordingBackend
}
func (b *preservingShutdownRecordingBackend) PreservesTasksOnShutdown() bool {
return true
}
type recordingBackend struct {
err error
}
func (b *recordingBackend) ExecuteTask(context.Context, *TaskParams) error {
return b.err
}
func (b *recordingBackend) Shutdown(context.Context) {}
func (b *recordingBackend) PreservesTasksOnShutdown() bool {
return false
}
func TestTaskFailureLabels(t *testing.T) {
tests := []struct {
name string
err error
wantPhase string
wantReason string
}{
{
name: "deadline exceeded",
err: context.DeadlineExceeded,
wantPhase: metrics.TaskFailurePhaseBackend,
wantReason: metrics.TaskFailureReasonTaskTimeout,
},
{
name: "canceled",
err: context.Canceled,
wantPhase: metrics.TaskFailurePhaseBackend,
wantReason: metrics.TaskFailureReasonTaskCancelled,
},
{
name: "wrapped backend failure",
err: fmt.Errorf("wrapped: %w", newBackendFailure(
metrics.TaskFailurePhaseBackend,
metrics.TaskFailureReasonImagePull,
errors.New("pull failed"),
)),
wantPhase: metrics.TaskFailurePhaseBackend,
wantReason: metrics.TaskFailureReasonImagePull,
},
{
name: "unknown error",
err: errors.New("boom"),
wantPhase: metrics.TaskFailurePhaseBackend,
wantReason: metrics.TaskFailureReasonUnknown,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
phase, reason := taskFailureLabels(tt.err)
if phase != tt.wantPhase || reason != tt.wantReason {
t.Fatalf("taskFailureLabels() = (%q, %q), want (%q, %q)", phase, reason, tt.wantPhase, tt.wantReason)
}
})
}
}
func TestExecuteTaskReportsTaskCancelledOnUserCancellation(t *testing.T) {
taskCtx, taskCancel := context.WithCancel(context.Background())
taskCancel()
w := &Worker{
ctx: context.Background(),
config: Config{},
sendChan: make(chan []byte, 1),
activeTasks: map[string]activeTask{"task-1": {
cancel: func() {},
cancellationSource: taskCancellationSourceUser,
}},
backend: &recordingBackend{err: context.Canceled},
}
w.executeTask(taskCtx, func() {}, trace.SpanFromContext(taskCtx), &types.TaskAssignmentMessage{
TaskID: "task-1",
Task: &types.Task{ID: "task-1", Title: "test task"},
}, time.Now())
msg := readWebSocketMessage(t, w.sendChan)
if msg.Type != types.MessageTypeTaskCompleted {
t.Fatalf("message type = %q, want %q", msg.Type, types.MessageTypeTaskCompleted)
}
var completed types.TaskCompletedMessage
if err := json.Unmarshal(msg.Data, &completed); err != nil {
t.Fatalf("failed to unmarshal task completed message: %v", err)
}
if completed.TaskID != "task-1" {
t.Errorf("task ID = %q, want %q", completed.TaskID, "task-1")
}
if completed.TaskState == nil || *completed.TaskState != types.TaskStateCancelled {
t.Fatalf("task state = %v, want %q", completed.TaskState, types.TaskStateCancelled)
}
if completed.Message != "Task cancelled by user request." {
t.Errorf("message = %q, want %q", completed.Message, "Task cancelled by user request.")
}
if _, ok := w.activeTasks["task-1"]; ok {
t.Fatal("task should be removed from active tasks")
}
}
func TestExecuteTaskDoesNotReportTaskCancelledOnBackendCancellationError(t *testing.T) {
w := &Worker{
ctx: context.Background(),
config: Config{},
sendChan: make(chan []byte, 1),
activeTasks: map[string]activeTask{"task-1": {cancel: func() {}}},
backend: &recordingBackend{err: fmt.Errorf("backend request failed: %w", context.Canceled)},
}
w.executeTask(context.Background(), func() {}, trace.SpanFromContext(context.Background()), &types.TaskAssignmentMessage{
TaskID: "task-1",
Task: &types.Task{ID: "task-1", Title: "test task"},
}, time.Now())
msg := readWebSocketMessage(t, w.sendChan)
if msg.Type != types.MessageTypeTaskFailed {
t.Fatalf("message type = %q, want %q", msg.Type, types.MessageTypeTaskFailed)
}
}
func TestHandleMessageCancelsActiveTask(t *testing.T) {
taskCtx, taskCancel := context.WithCancel(context.Background())
defer taskCancel()
w := &Worker{
ctx: context.Background(),
sendChan: make(chan []byte, 1),
activeTasks: map[string]activeTask{
"task-1": {
ctx: taskCtx,
cancel: taskCancel,
},
},
}
data, err := json.Marshal(types.TaskCancellationMessage{TaskID: "task-1"})
if err != nil {
t.Fatalf("failed to marshal cancellation message: %v", err)
}
message, err := json.Marshal(types.WebSocketMessage{
Type: types.MessageTypeTaskCancellation,
Data: data,
})
if err != nil {
t.Fatalf("failed to marshal websocket message: %v", err)
}
w.handleMessage(message)
if taskCtx.Err() != context.Canceled {
t.Fatalf("task context error = %v, want %v", taskCtx.Err(), context.Canceled)
}
if task := w.activeTasks["task-1"]; task.cancellationSource != taskCancellationSourceUser {
t.Fatalf("task cancellation source = %q, want %q", task.cancellationSource, taskCancellationSourceUser)
}
}
func TestExecuteTaskReportsTaskCompletedOnSuccess(t *testing.T) {
w := &Worker{
ctx: context.Background(),
config: Config{},
sendChan: make(chan []byte, 1),
activeTasks: map[string]activeTask{"task-1": {cancel: func() {}}},
backend: &recordingBackend{},
}
w.executeTask(context.Background(), func() {}, trace.SpanFromContext(context.Background()), &types.TaskAssignmentMessage{
TaskID: "task-1",
Task: &types.Task{ID: "task-1", Title: "test task"},
}, time.Now())
msg := readWebSocketMessage(t, w.sendChan)
if msg.Type != types.MessageTypeTaskCompleted {
t.Fatalf("message type = %q, want %q", msg.Type, types.MessageTypeTaskCompleted)
}
var completed types.TaskCompletedMessage
if err := json.Unmarshal(msg.Data, &completed); err != nil {
t.Fatalf("failed to unmarshal task completed message: %v", err)
}
if completed.TaskID != "task-1" {
t.Errorf("task ID = %q, want %q", completed.TaskID, "task-1")
}
if completed.Message != "Task completed successfully" {
t.Errorf("message = %q, want %q", completed.Message, "Task completed successfully")
}
if _, ok := w.activeTasks["task-1"]; ok {
t.Fatal("task should be removed from active tasks")
}
}
func TestExecuteTaskReportsTaskFailedOnBackendError(t *testing.T) {
w := &Worker{
ctx: context.Background(),
config: Config{},
sendChan: make(chan []byte, 1),
activeTasks: map[string]activeTask{"task-1": {cancel: func() {}}},
backend: &recordingBackend{err: errors.New("boom")},
}
w.executeTask(context.Background(), func() {}, trace.SpanFromContext(context.Background()), &types.TaskAssignmentMessage{
TaskID: "task-1",
Task: &types.Task{ID: "task-1", Title: "test task"},
}, time.Now())
msg := readWebSocketMessage(t, w.sendChan)
if msg.Type != types.MessageTypeTaskFailed {
t.Fatalf("message type = %q, want %q", msg.Type, types.MessageTypeTaskFailed)
}
var failed types.TaskFailedMessage
if err := json.Unmarshal(msg.Data, &failed); err != nil {
t.Fatalf("failed to unmarshal task failed message: %v", err)
}
if failed.TaskID != "task-1" {
t.Errorf("task ID = %q, want %q", failed.TaskID, "task-1")
}
if failed.Message != "Failed to execute task: boom" {
t.Errorf("message = %q, want %q", failed.Message, "Failed to execute task: boom")
}
if _, ok := w.activeTasks["task-1"]; ok {
t.Fatal("task should be removed from active tasks")
}
}
func TestExecuteTaskReportsUserFriendlyMessageOnDeadlineExceeded(t *testing.T) {
w := &Worker{
ctx: context.Background(),
config: Config{},
sendChan: make(chan []byte, 1),
activeTasks: map[string]activeTask{"task-1": {cancel: func() {}}},
backend: &recordingBackend{err: context.DeadlineExceeded},
}
w.executeTask(context.Background(), func() {}, trace.SpanFromContext(context.Background()), &types.TaskAssignmentMessage{
TaskID: "task-1",
Task: &types.Task{ID: "task-1", Title: "test task"},
}, time.Now())
msg := readWebSocketMessage(t, w.sendChan)
if msg.Type != types.MessageTypeTaskFailed {
t.Fatalf("message type = %q, want %q", msg.Type, types.MessageTypeTaskFailed)
}
var failed types.TaskFailedMessage
if err := json.Unmarshal(msg.Data, &failed); err != nil {
t.Fatalf("failed to unmarshal task failed message: %v", err)
}
want := "The task exceeded its maximum allowed execution time and was terminated. Consider breaking the task into smaller steps or increasing the timeout."
if failed.Message != want {
t.Errorf("message = %q, want %q", failed.Message, want)
}
}
func TestUserFacingTaskError(t *testing.T) {
tests := []struct {
name string
err error
want string
}{
{
name: "context canceled",
err: context.Canceled,
want: "The task was interrupted due to an infrastructure issue (context canceled). This is typically transient — please try again.",
},
{
name: "wrapped context canceled",
err: fmt.Errorf("exec failed: %w", context.Canceled),
want: "The task was interrupted due to an infrastructure issue (context canceled). This is typically transient — please try again.",
},
{
name: "deadline exceeded",
err: context.DeadlineExceeded,
want: "The task exceeded its maximum allowed execution time and was terminated. Consider breaking the task into smaller steps or increasing the timeout.",
},
{
name: "generic error",
err: errors.New("boom"),
want: "Failed to execute task: boom",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := userFacingTaskError(tt.err)
if got != tt.want {
t.Errorf("userFacingTaskError() = %q, want %q", got, tt.want)
}
})
}
}
func readWebSocketMessage(t *testing.T, messages <-chan []byte) types.WebSocketMessage {
t.Helper()
select {
case msgBytes := <-messages:
var msg types.WebSocketMessage
if err := json.Unmarshal(msgBytes, &msg); err != nil {
t.Fatalf("failed to unmarshal websocket message: %v", err)
}
return msg
default:
t.Fatal("expected websocket message")
}
return types.WebSocketMessage{}
}
// TestRunHeartbeatAndWritesAreConcurrencySafe is a regression test for the
// "concurrent write to websocket connection" panic: the heartbeat loop used
// to send pings via WriteMessage, racing writeLoop's data writes on the same
// connection and crashing the whole worker process (taking the metrics
// exporter down with it). It floods the send channel while heartbeats fire
// every millisecond; before the fix this panicked within the test window.
func TestRunHeartbeatAndWritesAreConcurrencySafe(t *testing.T) {
upgrader := websocket.Upgrader{}
var messagesReceived, pingsReceived atomic.Int64
serverConnClosed := make(chan struct{})
srv := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(rw, r, nil)
if err != nil {
t.Errorf("failed to upgrade connection: %v", err)
return
}
defer close(serverConnClosed)
defer conn.Close()
conn.SetPingHandler(func(string) error {
pingsReceived.Add(1)
return nil
})
for {
if _, _, err := conn.ReadMessage(); err != nil {
return
}
messagesReceived.Add(1)
}
}))
defer srv.Close()
wsURL := "ws" + strings.TrimPrefix(srv.URL, "http")
conn, resp, err := websocket.DefaultDialer.Dial(wsURL, nil)
if err != nil {
t.Fatalf("failed to dial test server: %v", err)
}
if resp != nil && resp.Body != nil {
resp.Body.Close()
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
w := &Worker{
config: Config{},
conn: conn,
ctx: ctx,
cancel: cancel,
sendChan: make(chan []byte, 256),
activeTasks: make(map[string]activeTask),
heartbeatInterval: time.Millisecond,
}
runDone := make(chan struct{})
go func() {
w.run()
close(runDone)
}()
// Flood data writes while heartbeats fire so the two write paths overlap
// constantly for the duration of the test window.
message := []byte(`{"type":"task_claimed","data":{"task_id":"task-1"}}`)
deadline := time.After(500 * time.Millisecond)
flood:
for {
select {
case <-deadline:
break flood
case w.sendChan <- message:
}
}
// Tear down: cancelling the context stops writeLoop/heartbeatLoop, and
// closing the connection unblocks readLoop so run() returns.
cancel()
conn.Close()
select {
case <-runDone:
case <-time.After(5 * time.Second):
t.Fatal("run() did not return after context cancellation and connection close")
}
select {
case <-serverConnClosed:
case <-time.After(5 * time.Second):
t.Fatal("server connection was not closed")
}
if messagesReceived.Load() == 0 {
t.Error("expected the server to receive data messages")
}
if pingsReceived.Load() == 0 {
t.Error("expected the server to receive heartbeat pings")
}
}
func TestDefaultImageForTask(t *testing.T) {
newWorker := func(defaultImage string) *Worker {
ctx := context.Background()
var k8sConfig *KubernetesBackendConfig
if defaultImage != "" {
k8sConfig = &KubernetesBackendConfig{DefaultImage: defaultImage}
}
return &Worker{
ctx: ctx,
config: Config{
Kubernetes: k8sConfig,
},
}
}
envID := "env-123"
t.Run("server-provided image wins over default_image", func(t *testing.T) {
w := newWorker("my-registry.io/default:v1")
got := w.defaultImageForTask("server-image:latest", &types.Task{})
if got != "server-image:latest" {
t.Errorf("got %q, want %q", got, "server-image:latest")
}
})
t.Run("default_image used when server image empty", func(t *testing.T) {
w := newWorker("my-registry.io/default:v1")
got := w.defaultImageForTask("", &types.Task{})
if got != "my-registry.io/default:v1" {
t.Errorf("got %q, want %q", got, "my-registry.io/default:v1")
}
})
t.Run("hardcoded fallback when no default_image configured", func(t *testing.T) {
w := newWorker("")
got := w.defaultImageForTask("", &types.Task{})
if got != "ubuntu:22.04" {
t.Errorf("got %q, want %q", got, "ubuntu:22.04")
}
})
t.Run("hardcoded fallback when kubernetes config nil", func(t *testing.T) {
w := &Worker{
ctx: context.Background(),
config: Config{},
}
got := w.defaultImageForTask("", &types.Task{})
if got != "ubuntu:22.04" {
t.Errorf("got %q, want %q", got, "ubuntu:22.04")
}
})
t.Run("hardcoded fallback with environment ID logs warning", func(t *testing.T) {
w := newWorker("")
task := &types.Task{
AgentConfigSnapshot: &types.AmbientAgentConfig{
EnvironmentID: &envID,
},
}
got := w.defaultImageForTask("", task)
if got != "ubuntu:22.04" {
t.Errorf("got %q, want %q", got, "ubuntu:22.04")
}
})
}
func TestPrepareTaskParamsSidecarImageOverride(t *testing.T) {
newWorker := func(sidecarImage string) *Worker {
ctx := context.Background()
var k8sConfig *KubernetesBackendConfig
if sidecarImage != "" {
k8sConfig = &KubernetesBackendConfig{SidecarImage: sidecarImage}
} else {
k8sConfig = &KubernetesBackendConfig{}
}
return &Worker{
ctx: ctx,
config: Config{
Kubernetes: k8sConfig,
},
}
}
t.Run("config sidecar_image overrides server-provided image", func(t *testing.T) {
w := newWorker("my-registry.io/warpdotdev/warp-agent:latest")
params := w.prepareTaskParams(&types.TaskAssignmentMessage{
TaskID: "task-1",
Task: &types.Task{ID: "task-1"},
SidecarImage: "docker.io/warpdotdev/warp-agent:latest",
})
if len(params.Sidecars) == 0 {
t.Fatal("expected at least one sidecar")
}
if params.Sidecars[0].Image != "my-registry.io/warpdotdev/warp-agent:latest" {
t.Errorf("sidecar image = %q, want %q", params.Sidecars[0].Image, "my-registry.io/warpdotdev/warp-agent:latest")
}
})
t.Run("server-provided image used when config sidecar_image empty", func(t *testing.T) {
w := newWorker("")
params := w.prepareTaskParams(&types.TaskAssignmentMessage{
TaskID: "task-1",
Task: &types.Task{ID: "task-1"},
SidecarImage: "docker.io/warpdotdev/warp-agent:latest",
})
if len(params.Sidecars) == 0 {
t.Fatal("expected at least one sidecar")
}
if params.Sidecars[0].Image != "docker.io/warpdotdev/warp-agent:latest" {
t.Errorf("sidecar image = %q, want %q", params.Sidecars[0].Image, "docker.io/warpdotdev/warp-agent:latest")
}
})
t.Run("no sidecar when server provides empty sidecar image", func(t *testing.T) {
w := newWorker("my-registry.io/warpdotdev/warp-agent:latest")
params := w.prepareTaskParams(&types.TaskAssignmentMessage{
TaskID: "task-1",
Task: &types.Task{ID: "task-1"},
SidecarImage: "",
})
if len(params.Sidecars) != 0 {
t.Errorf("expected no sidecars when server sidecar image is empty, got %d", len(params.Sidecars))
}
})
}
func TestPrepareTaskParamsTeamShareConditional(t *testing.T) {
newWorker := func() *Worker {
return &Worker{
ctx: context.Background(),
config: Config{
ServerRootURL: "https://app.warp.dev",
Kubernetes: &KubernetesBackendConfig{},
},
}
}
containsShareTeamEdit := func(args []string) bool {
for i, arg := range args {
if arg == "--share" && i+1 < len(args) && args[i+1] == "team:edit" {
return true
}
}
return false
}
t.Run("includes --share team:edit for team-owned task", func(t *testing.T) {
w := newWorker()
params := w.prepareTaskParams(&types.TaskAssignmentMessage{
TaskID: "task-1",
Task: &types.Task{
ID: "task-1",
Owner: &types.TaskOwner{Type: "TEAM", Id: 42},
},
})
if !containsShareTeamEdit(params.BaseArgs) {
t.Fatalf("expected --share team:edit in args for team-owned task, got %v", params.BaseArgs)
}
})
t.Run("omits --share team:edit for user-owned task", func(t *testing.T) {
w := newWorker()
params := w.prepareTaskParams(&types.TaskAssignmentMessage{
TaskID: "task-2",
Task: &types.Task{
ID: "task-2",
Owner: &types.TaskOwner{Type: "USER", Id: 99},
},
})
if containsShareTeamEdit(params.BaseArgs) {
t.Fatalf("did not expect --share team:edit in args for user-owned task, got %v", params.BaseArgs)
}
})
t.Run("omits --share team:edit when owner is nil", func(t *testing.T) {
w := newWorker()
params := w.prepareTaskParams(&types.TaskAssignmentMessage{
TaskID: "task-3",
Task: &types.Task{
ID: "task-3",
},
})
if containsShareTeamEdit(params.BaseArgs) {
t.Fatalf("did not expect --share team:edit in args when owner is nil, got %v", params.BaseArgs)
}
})
}
func TestPrepareTaskParamsIncludesServerRootURLForHarnessSupport(t *testing.T) {
w := &Worker{
ctx: context.Background(),
config: Config{
ServerRootURL: "https://staging.example.com",
Kubernetes: &KubernetesBackendConfig{},
},
}
params := w.prepareTaskParams(&types.TaskAssignmentMessage{
TaskID: "task-1",
Task: &types.Task{ID: "task-1"},
})
want := warpServerRootURLEnv + "=https://staging.example.com"
for _, entry := range params.EnvVars {
if entry == want {
return
}
}
t.Fatalf("expected %s in env vars, got %v", want, params.EnvVars)
}
func TestPrepareTaskParamsAdditionalOzArgs(t *testing.T) {
newWorker := func() *Worker {
return &Worker{
ctx: context.Background(),
config: Config{
ServerRootURL: "https://app.warp.dev",
Kubernetes: &KubernetesBackendConfig{},
},
}
}
containsSkipInitialTurn := func(args []string) bool {
for _, arg := range args {
if arg == "--skip-initial-turn" {
return true
}
}
return false
}
t.Run("forwards server supplemental oz args", func(t *testing.T) {
w := newWorker()
params := w.prepareTaskParams(&types.TaskAssignmentMessage{
TaskID: "task-skip",
Task: &types.Task{ID: "task-skip"},
AdditionalOzArgs: []string{"--skip-initial-turn"},
})
if !containsSkipInitialTurn(params.BaseArgs) {
t.Fatalf("expected --skip-initial-turn in args, got %v", params.BaseArgs)
}
})
t.Run("does not add omitted supplemental oz args", func(t *testing.T) {
w := newWorker()
params := w.prepareTaskParams(&types.TaskAssignmentMessage{
TaskID: "task-no-skip",
Task: &types.Task{ID: "task-no-skip"},
})
if containsSkipInitialTurn(params.BaseArgs) {
t.Fatalf("did not expect --skip-initial-turn in args, got %v", params.BaseArgs)
}
})
}
func TestWorkerShutdownUsesFreshContextForBackendCleanup(t *testing.T) {
workerCtx, cancel := context.WithCancel(context.Background())
backend := &shutdownRecordingBackend{}
w := &Worker{
ctx: workerCtx,
cancel: cancel,
activeTasks: make(map[string]activeTask),
backend: backend,
}
w.Shutdown()
if !backend.shutdownCalled {
t.Fatal("expected backend shutdown to be called")
}
if backend.shutdownCtxErr != nil {
t.Fatalf("expected backend shutdown context to be active, got %v", backend.shutdownCtxErr)
}
}
func TestWorkerShutdownPreservesActiveTasksForPreservingBackend(t *testing.T) {
workerCtx, cancel := context.WithCancel(context.Background())
backend := &preservingShutdownRecordingBackend{}
cancelledTask := false
w := &Worker{
ctx: workerCtx,
cancel: cancel,
activeTasks: map[string]activeTask{
"task-1": {cancel: func() {
cancelledTask = true
}},
},
backend: backend,
}
w.Shutdown()
if cancelledTask {
t.Fatal("expected active task to be preserved, but cancel function was called")
}
if !backend.shutdownCalled {
t.Fatal("expected backend shutdown to be called")
}
}
func TestHandleTaskAssignmentDoesNotStartTaskAfterShutdownDuringClaim(t *testing.T) {
workerCtx, cancel := context.WithCancel(context.Background())
cancel()
w := &Worker{
ctx: workerCtx,
cancel: cancel,
config: Config{},
sendChan: make(chan []byte, 1),
activeTasks: make(map[string]activeTask),
backend: &preservingShutdownRecordingBackend{},
}
w.handleTaskAssignment(&types.TaskAssignmentMessage{
TaskID: "task-1",
Task: &types.Task{ID: "task-1", Title: "test task"},
})
if len(w.activeTasks) != 0 {
t.Fatalf("expected no active tasks to start after shutdown during claim, got %d", len(w.activeTasks))
}
}