-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathquery_test.go
More file actions
1225 lines (1005 loc) · 33.3 KB
/
query_test.go
File metadata and controls
1225 lines (1005 loc) · 33.3 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
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package codexsdk
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"runtime"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/stretchr/testify/require"
"github.com/ethpandaops/codex-agent-sdk-go/internal/config"
)
const msgTypeControlRequest = "control_request"
func TestQueryCLINotFound(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
for _, err := range Query(ctx, Text("test"),
WithCliPath("/nonexistent/path/to/claude"),
) {
if err == nil {
t.Fatal("Expected error when CLI not found")
}
if _, ok := errors.AsType[*CLINotFoundError](err); !ok {
t.Errorf("Expected CLINotFoundError, got: %v", err)
}
break
}
}
func TestQueryWithNoOptions(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// This should work if claude is in PATH
// If not, it should return CLINotFoundError or ProcessError
for _, err := range Query(ctx, Text("test")) {
_, isCLINotFound := errors.AsType[*CLINotFoundError](err)
_, isProcessError := errors.AsType[*ProcessError](err)
if err != nil && !isCLINotFound && !isProcessError {
t.Errorf("Unexpected error type: %v", err)
}
break
}
}
// TestQuery_WithOptions tests Query with full CodexAgentOptions configuration.
func TestQuery_WithOptions(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
for _, err := range Query(ctx, Text("test"),
WithSystemPrompt("You are a helpful assistant."),
WithModel("claude-sonnet-4-5-20250514"),
WithPermissionMode("bypassPermissions"),
WithEnv(map[string]string{"TEST_VAR": "test_value"}),
WithConfig(map[string]string{"model": "gpt-5.4"}),
WithOutputFormat(map[string]any{
"type": "json_schema",
"schema": map[string]any{
"type": "object",
"properties": map[string]any{
"answer": map[string]any{"type": "string"},
},
"required": []string{"answer"},
},
}),
) {
// Either succeeds or returns CLINotFoundError or ProcessError (CLI issues)
_, isCLINotFound := errors.AsType[*CLINotFoundError](err)
_, isProcessError := errors.AsType[*ProcessError](err)
if err != nil && !isCLINotFound && !isProcessError {
t.Errorf("Unexpected error type with full options: %v", err)
}
break
}
}
// TestQuery_WithCwd tests Query with a custom working directory.
func TestQuery_WithCwd(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// Create a temporary directory
tmpDir, err := os.MkdirTemp("", "claude-sdk-test-cwd-*")
require.NoError(t, err)
defer os.RemoveAll(tmpDir)
// Resolve to absolute path
absPath, err := filepath.Abs(tmpDir)
require.NoError(t, err)
for _, err := range Query(ctx, Text("test"),
WithCwd(absPath),
WithPermissionMode("bypassPermissions"),
) {
// Either succeeds or returns CLINotFoundError or ProcessError (CLI issues)
_, isCLINotFound := errors.AsType[*CLINotFoundError](err)
_, isProcessError := errors.AsType[*ProcessError](err)
if err != nil && !isCLINotFound && !isProcessError {
t.Errorf("Unexpected error type with Cwd option: %v", err)
}
break
}
}
// TestQuery_WithEnv tests Query with custom environment variables.
func TestQuery_WithEnv(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
for _, err := range Query(ctx, Text("test"),
WithPermissionMode("bypassPermissions"),
WithEnv(map[string]string{
"CLAUDE_SDK_TEST_VAR": "test_value_123",
"ANOTHER_VAR": "another_value",
}),
) {
// Either succeeds or returns CLINotFoundError or ProcessError (CLI issues)
_, isCLINotFound := errors.AsType[*CLINotFoundError](err)
_, isProcessError := errors.AsType[*ProcessError](err)
if err != nil && !isCLINotFound && !isProcessError {
t.Errorf("Unexpected error type with Env option: %v", err)
}
break
}
}
// TestQuery_WithSystemPromptPreset tests Query option handling for system prompt presets.
func TestQuery_WithSystemPromptPreset(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
for _, err := range Query(ctx, Text("test"),
WithSystemPromptPreset(&SystemPromptPreset{
Type: "preset",
Preset: "claude_code",
Append: new("\nAdditional instructions."),
}),
WithPermissionMode("bypassPermissions"),
) {
// Either succeeds or returns CLINotFoundError or ProcessError (CLI issues)
_, isCLINotFound := errors.AsType[*CLINotFoundError](err)
_, isProcessError := errors.AsType[*ProcessError](err)
if err != nil && !isCLINotFound && !isProcessError {
t.Errorf("Unexpected error type with SystemPromptPreset option: %v", err)
}
break
}
}
// TestQuery_WithOutputFormat tests Query with structured output format.
func TestQuery_WithOutputFormat(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
for _, err := range Query(ctx, Text("test"),
WithOutputFormat(map[string]any{
"type": "json_schema",
"schema": map[string]any{
"type": "object",
"properties": map[string]any{
"answer": map[string]any{
"type": "string",
},
},
"required": []string{"answer"},
},
}),
WithPermissionMode("bypassPermissions"),
) {
// Either succeeds or returns CLINotFoundError or ProcessError (CLI issues)
_, isCLINotFound := errors.AsType[*CLINotFoundError](err)
_, isProcessError := errors.AsType[*ProcessError](err)
if err != nil && !isCLINotFound && !isProcessError {
t.Errorf("Unexpected error type with OutputFormat option: %v", err)
}
break
}
}
// TestQuery_WithResume tests Query with session resume option.
func TestQuery_WithResume(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
for _, err := range Query(ctx, Text("test"),
WithResume("nonexistent-session-id"),
WithPermissionMode("bypassPermissions"),
) {
// May fail due to invalid session, but should not be unexpected error type
_, isCLINotFound := errors.AsType[*CLINotFoundError](err)
_, isProcessError := errors.AsType[*ProcessError](err)
if err != nil && !isCLINotFound && !isProcessError {
t.Logf("Error with Resume option (may be expected): %v", err)
}
break
}
}
// TestQuery_WithExtraArgs tests Query with extra CLI arguments.
func TestQuery_WithExtraArgs(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
for _, err := range Query(ctx, Text("test"),
WithExtraArgs(map[string]*string{
"verbose": new(""), // Boolean flag with empty value
}),
WithPermissionMode("bypassPermissions"),
) {
// Either succeeds or returns CLINotFoundError or ProcessError (CLI issues)
_, isCLINotFound := errors.AsType[*CLINotFoundError](err)
_, isProcessError := errors.AsType[*ProcessError](err)
if err != nil && !isCLINotFound && !isProcessError {
t.Errorf("Unexpected error type with ExtraArgs option: %v", err)
}
break
}
}
// TestQuery_CanUseToolWithPermissionPromptToolName tests that Query yields
// an error when both CanUseTool and PermissionPromptToolName are set.
func TestQuery_CanUseToolWithPermissionPromptToolName(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
for _, err := range Query(ctx, Text("test"),
WithCanUseTool(func(
_ context.Context,
_ string,
_ map[string]any,
_ *ToolPermissionContext,
) (PermissionResult, error) {
return &PermissionResultAllow{Behavior: "allow"}, nil
}),
WithPermissionPromptToolName("custom"),
WithPermissionMode("bypassPermissions"),
) {
require.Error(t, err)
require.Contains(t, err.Error(), "can_use_tool callback cannot be used with permission_prompt_tool_name")
break
}
}
// TestQuery_CanUseToolAutoConfiguresPermissionPrompt tests that Query
// automatically sets PermissionPromptToolName to "stdio" when CanUseTool is set.
func TestQuery_CanUseToolAutoConfiguresPermissionPrompt(t *testing.T) {
options := &CodexAgentOptions{
CanUseTool: func(
_ context.Context,
_ string,
_ map[string]any,
_ *ToolPermissionContext,
) (PermissionResult, error) {
return &PermissionResultAllow{Behavior: "allow"}, nil
},
PermissionMode: "bypassPermissions",
}
// Call validateAndConfigureOptions directly to test the auto-configuration
err := validateAndConfigureOptions(options)
require.NoError(t, err)
require.Equal(t, "stdio", options.PermissionPromptToolName)
}
// TestQueryStream_CanUseToolWithPermissionPromptToolName tests that QueryStream
// yields an error when both CanUseTool and PermissionPromptToolName are set.
func TestQueryStream_CanUseToolWithPermissionPromptToolName(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
messages := MessagesFromSlice([]StreamingMessage{
NewUserMessage(Text("test")),
})
for _, err := range QueryStream(ctx, messages,
WithCanUseTool(func(
_ context.Context,
_ string,
_ map[string]any,
_ *ToolPermissionContext,
) (PermissionResult, error) {
return &PermissionResultAllow{Behavior: "allow"}, nil
}),
WithPermissionPromptToolName("custom"),
WithPermissionMode("bypassPermissions"),
) {
require.Error(t, err)
require.Contains(t, err.Error(), "can_use_tool callback cannot be used with permission_prompt_tool_name")
break
}
}
// dummyCanUseTool is a helper for tests that returns allow.
func dummyCanUseTool(
_ context.Context,
_ string,
_ map[string]any,
_ *ToolPermissionContext,
) (PermissionResult, error) {
return &PermissionResultAllow{Behavior: "allow"}, nil
}
// TestValidateAndConfigureOptions tests the validation helper function.
func TestValidateAndConfigureOptions(t *testing.T) {
tests := []struct {
name string
options *CodexAgentOptions
wantErr bool
errContains string
checkFunc func(t *testing.T, opts *CodexAgentOptions)
}{
{
name: "nil CanUseTool does not modify PermissionPromptToolName",
options: &CodexAgentOptions{},
wantErr: false,
checkFunc: func(t *testing.T, opts *CodexAgentOptions) {
t.Helper()
require.Empty(t, opts.PermissionPromptToolName)
},
},
{
name: "CanUseTool without PermissionPromptToolName sets stdio",
options: &CodexAgentOptions{
CanUseTool: dummyCanUseTool,
},
wantErr: false,
checkFunc: func(t *testing.T, opts *CodexAgentOptions) {
t.Helper()
require.Equal(t, "stdio", opts.PermissionPromptToolName)
},
},
{
name: "CanUseTool with PermissionPromptToolName returns error",
options: &CodexAgentOptions{
CanUseTool: dummyCanUseTool,
PermissionPromptToolName: "custom",
},
wantErr: true,
errContains: "can_use_tool callback cannot be used with permission_prompt_tool_name",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := validateAndConfigureOptions(tt.options)
if tt.wantErr {
require.Error(t, err)
require.Contains(t, err.Error(), tt.errContains)
} else {
require.NoError(t, err)
if tt.checkFunc != nil {
tt.checkFunc(t, tt.options)
}
}
})
}
}
func TestRequiresAppServerQuery(t *testing.T) {
tests := []struct {
name string
options *CodexAgentOptions
want bool
}{
{name: "default options", options: &CodexAgentOptions{}, want: false},
{name: "exec-compatible option stays exec", options: &CodexAgentOptions{Model: "gpt-5.4"}, want: false},
{name: "system prompt requires app-server", options: &CodexAgentOptions{SystemPrompt: "be concise"}, want: true},
{name: "resume requires app-server", options: &CodexAgentOptions{Resume: "thread_1"}, want: true},
{name: "fork requires app-server", options: &CodexAgentOptions{ForkSession: true}, want: true},
{name: "continue requires app-server", options: &CodexAgentOptions{ContinueConversation: true}, want: true},
{name: "output format requires app-server", options: &CodexAgentOptions{OutputFormat: map[string]any{"type": "json_schema"}}, want: true},
{
name: "sdk mcp server requires app-server",
options: &CodexAgentOptions{
MCPServers: map[string]MCPServerConfig{
"sdk": &MCPSdkServerConfig{Type: MCPServerTypeSDK, Name: "sdk"},
},
},
want: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
require.Equal(t, tt.want, config.SelectQueryBackend(tt.options) == config.QueryBackendAppServer)
})
}
}
func TestQuery_FailFastUnsupportedOptions(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
tests := []struct {
name string
opts []Option
contains string
}{
{
name: "continue without resume unsupported",
opts: []Option{
WithContinueConversation(true),
},
contains: "requires WithResume",
},
{
name: "permission prompt custom tool unsupported",
opts: []Option{
WithPermissionPromptToolName("custom"),
},
contains: "PermissionPromptToolName",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
for _, err := range Query(ctx, Text("test"), tt.opts...) {
require.Error(t, err)
require.ErrorIs(t, err, ErrUnsupportedOption)
require.Contains(t, err.Error(), tt.contains)
return
}
t.Fatal("expected fail-fast error")
})
}
}
func TestBuildInitialUserMessage(t *testing.T) {
t.Run("text-only prompt", func(t *testing.T) {
msg := buildInitialUserMessage(Text("hello"), &CodexAgentOptions{})
require.Equal(t, "user", msg["type"])
messageData, ok := msg["message"].(map[string]any)
require.True(t, ok)
require.Equal(t, Text("hello"), messageData["content"])
})
t.Run("prompt with images", func(t *testing.T) {
msg := buildInitialUserMessage(Text("look at this"), &CodexAgentOptions{
Images: []string{"/tmp/a.png", "/tmp/b.png"},
})
messageData, ok := msg["message"].(map[string]any)
require.True(t, ok)
content, ok := messageData["content"].(UserMessageContent)
require.True(t, ok)
blocks := content.Blocks()
require.Len(t, blocks, 3)
require.Equal(t, "text", blocks[0].BlockType())
imageA, ok := blocks[1].(*InputLocalImageBlock)
require.True(t, ok)
require.Equal(t, "/tmp/a.png", imageA.Path)
imageB, ok := blocks[2].(*InputLocalImageBlock)
require.True(t, ok)
require.Equal(t, "/tmp/b.png", imageB.Path)
})
}
// =============================================================================
// Mid-Operation Context Cancellation Tests
// =============================================================================
// TestQuery_ContextCancelMidIteration tests that Query respects context
// cancellation during message iteration.
func TestQuery_ContextCancelMidIteration(t *testing.T) {
t.Run("context timeout during iteration", func(t *testing.T) {
// Create a context with very short timeout
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
defer cancel()
var gotError error
var iterationCount int
for _, err := range Query(ctx, Text("test"),
WithCliPath("/nonexistent/path/to/claude"),
) {
iterationCount++
if err != nil {
gotError = err
break
}
}
// Should get either CLI not found (fast path) or context deadline exceeded
require.Error(t, gotError)
_, isCLINotFound := errors.AsType[*CLINotFoundError](gotError)
isContextErr := gotError == context.DeadlineExceeded ||
gotError == context.Canceled
require.True(t, isCLINotFound || isContextErr,
"Expected CLINotFoundError or context error, got: %v", gotError)
t.Logf("Iterations: %d, Error type: %T", iterationCount, gotError)
})
t.Run("context cancel before iteration starts", func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
cancel() // Cancel immediately
var gotError error
for _, err := range Query(ctx, Text("test")) {
if err != nil {
gotError = err
break
}
}
// Should get an error (either context canceled or CLI not found)
require.Error(t, gotError)
})
}
// TestQueryStream_ContextCancelMidIteration tests that QueryStream respects
// context cancellation during message iteration.
func TestQueryStream_ContextCancelMidIteration(t *testing.T) {
t.Run("context timeout during streaming iteration", func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
defer cancel()
messages := MessagesFromSlice([]StreamingMessage{
NewUserMessage(Text("test message")),
})
var gotError error
for _, err := range QueryStream(ctx, messages,
WithCliPath("/nonexistent/path/to/claude"),
) {
if err != nil {
gotError = err
break
}
}
// Should get either CLI not found or context error
require.Error(t, gotError)
_, isCLINotFound := errors.AsType[*CLINotFoundError](gotError)
isContextErr := gotError == context.DeadlineExceeded ||
gotError == context.Canceled
require.True(t, isCLINotFound || isContextErr,
"Expected CLINotFoundError or context error, got: %v", gotError)
})
}
// =============================================================================
// Early Iteration Exit Goroutine Leak Tests
// =============================================================================
// TestQuery_EarlyExitDoesNotLeakGoroutines tests that breaking out of the
// iterator early doesn't leak goroutines.
func TestQuery_EarlyExitDoesNotLeakGoroutines(t *testing.T) {
before := runtime.NumGoroutine()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// Break out of iteration immediately
for _, err := range Query(ctx, Text("test"),
WithCliPath("/nonexistent/path/to/claude"),
) {
// Break immediately regardless of error
_ = err
break
}
// Allow goroutines to settle
time.Sleep(200 * time.Millisecond)
after := runtime.NumGoroutine()
// Should not have leaked goroutines (allow +2 for GC fluctuation)
require.LessOrEqual(t, after, before+2,
"goroutine leak detected: before=%d, after=%d", before, after)
}
// TestQueryStream_EarlyExitDoesNotBlockInputStreamer tests that early exit
// with MCP/hooks configuration doesn't block the input streamer goroutine.
func TestQueryStream_EarlyExitDoesNotBlockInputStreamer(t *testing.T) {
before := runtime.NumGoroutine()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
messages := MessagesFromSlice([]StreamingMessage{
NewUserMessage(Text("test")),
})
// Break out immediately
for _, err := range QueryStream(ctx, messages,
WithCliPath("/nonexistent/path/to/claude"),
) {
_ = err
break
}
// Allow goroutines to settle - should NOT take 60 seconds
time.Sleep(200 * time.Millisecond)
after := runtime.NumGoroutine()
require.LessOrEqual(t, after, before+2,
"goroutine leak detected - input streamer may be blocked")
}
// TestQueryStream_DeferOrderingDoesNotDeadlock verifies that the defer ordering
// in QueryStream correctly closes resultReceived BEFORE wg.Wait() to prevent
// deadlock when the main loop exits early while streamInputMessages is blocked.
//
// This test specifically targets Issue #1: Potential goroutine leak in error paths.
// The bug was that defer statements were in wrong order (LIFO):
// - defer close(resultReceived) registered FIRST, executes SECOND
// - defer wg.Wait() registered SECOND, executes FIRST
//
// This caused wg.Wait() to block before close(resultReceived) could unblock
// the streamInputMessages goroutine, relying on 60s timeout to recover.
func TestQueryStream_DeferOrderingDoesNotDeadlock(t *testing.T) {
before := runtime.NumGoroutine()
// Use a context with short timeout to force early exit
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
// Create a slow message iterator that will be interrupted
slowMessages := func(yield func(StreamingMessage) bool) {
// First message goes through
if !yield(NewUserMessage(Text("first"))) {
return
}
// Simulate slow producer - will be interrupted by context
select {
case <-ctx.Done():
return
case <-time.After(5 * time.Second):
yield(NewUserMessage(Text("second")))
}
}
start := time.Now()
// Run QueryStream - should exit quickly when context times out
for _, err := range QueryStream(ctx, slowMessages,
WithCliPath("/nonexistent/path/to/claude"),
WithMCPServers(map[string]MCPServerConfig{
"test": &MCPStdioServerConfig{Command: "echo", Args: []string{"test"}},
}), // Enable MCP to trigger resultReceived channel usage
) {
_ = err
break
}
elapsed := time.Since(start)
// Should complete quickly (context timeout + cleanup), NOT wait for
// the 60s streamCloseTimeout. Allow 2 seconds for cleanup overhead.
require.Less(t, elapsed, 2*time.Second,
"QueryStream took too long (%v) - possible deadlock due to defer ordering", elapsed)
// Allow goroutines to settle
time.Sleep(200 * time.Millisecond)
after := runtime.NumGoroutine()
require.LessOrEqual(t, after, before+2,
"goroutine leak detected: before=%d, after=%d", before, after)
}
// =============================================================================
// Bug Detection Tests - These tests are designed to FAIL with current buggy code
// and PASS after the bugs are fixed.
// =============================================================================
// =============================================================================
// Errgroup Error Propagation Tests
// =============================================================================
// failingTransport is a mock transport that fails on SendMessage after N calls.
type failingTransport struct {
mu sync.Mutex
sendCallCount atomic.Int32
failAfter int32 // Fail after this many SendMessage calls
msgChan chan map[string]any
errChan chan error
closed bool
}
func newFailingTransport(failAfter int32) *failingTransport {
return &failingTransport{
failAfter: failAfter,
msgChan: make(chan map[string]any, 10),
errChan: make(chan error, 1),
}
}
func (f *failingTransport) Start(_ context.Context) error {
return nil
}
func (f *failingTransport) ReadMessages(_ context.Context) (<-chan map[string]any, <-chan error) {
return f.msgChan, f.errChan
}
func (f *failingTransport) SendMessage(_ context.Context, data []byte) error {
count := f.sendCallCount.Add(1)
if count > f.failAfter {
return errors.New("simulated transport send failure")
}
// Parse the message to check if it's a control_request that needs a response.
var msg map[string]any
if err := json.Unmarshal(data, &msg); err == nil {
if msgType, ok := msg["type"].(string); ok && msgType == msgTypeControlRequest {
if requestID, ok := msg["request_id"].(string); ok {
// Send a success response asynchronously.
go func() {
f.msgChan <- map[string]any{
"type": "control_response",
"response": map[string]any{
"subtype": "success",
"request_id": requestID,
"response": map[string]any{},
},
}
}()
}
}
}
return nil
}
func (f *failingTransport) Close() error {
f.mu.Lock()
defer f.mu.Unlock()
if !f.closed {
f.closed = true
close(f.msgChan)
close(f.errChan)
}
return nil
}
func (f *failingTransport) IsReady() bool {
return true
}
func (f *failingTransport) EndInput() error {
return nil
}
// Compile-time check that failingTransport implements config.Transport.
var _ config.Transport = (*failingTransport)(nil)
// stickyResultTransport emits a ResultMessage after input is closed but keeps
// the transport open until Close() or context cancellation. This characterizes
// Query behavior when a final result arrives before transport EOF.
type stickyResultTransport struct {
mu sync.Mutex
msgChan chan map[string]any
errChan chan error
ready chan struct{}
msg map[string]any
started bool
closed bool
}
func newStickyResultTransport(msg map[string]any) *stickyResultTransport {
return &stickyResultTransport{
msgChan: make(chan map[string]any, 16),
errChan: make(chan error, 1),
ready: make(chan struct{}),
msg: msg,
}
}
func (s *stickyResultTransport) Start(_ context.Context) error {
s.mu.Lock()
if s.started {
s.mu.Unlock()
return nil
}
s.started = true
msg := s.msg
s.mu.Unlock()
go func() {
<-s.ready
s.msgChan <- msg
}()
return nil
}
func (s *stickyResultTransport) ReadMessages(_ context.Context) (<-chan map[string]any, <-chan error) {
return s.msgChan, s.errChan
}
func (s *stickyResultTransport) SendMessage(_ context.Context, data []byte) error {
var msg map[string]any
if err := json.Unmarshal(data, &msg); err != nil {
return nil
}
msgType, _ := msg["type"].(string)
if msgType != msgTypeControlRequest {
s.release()
return nil
}
requestID, _ := msg["request_id"].(string)
request, _ := msg["request"].(map[string]any)
subtype, _ := request["subtype"].(string)
payload := map[string]any{}
if subtype == "initialize" {
payload = map[string]any{
"protocol_version": "1.0",
"server_info": map[string]any{
"name": "test-server",
"version": "1.0.0",
},
}
}
s.mu.Lock()
defer s.mu.Unlock()
if s.closed {
return nil
}
s.msgChan <- map[string]any{
"type": "control_response",
"response": map[string]any{
"request_id": requestID,
"subtype": "success",
"response": payload,
},
}
return nil
}
func (s *stickyResultTransport) Close() error {
s.mu.Lock()
defer s.mu.Unlock()
if s.closed {
return nil
}
s.closed = true
close(s.msgChan)
close(s.errChan)
return nil
}
func (s *stickyResultTransport) IsReady() bool {
s.mu.Lock()
defer s.mu.Unlock()
return s.started && !s.closed
}
func (s *stickyResultTransport) EndInput() error {
s.release()
return nil
}
func (s *stickyResultTransport) release() {
select {
case <-s.ready:
default:
close(s.ready)
}
}
var _ config.Transport = (*stickyResultTransport)(nil)
// resultMessageTransport is a mock transport that successfully initializes and
// emits a ResultMessage while keeping channels open. This verifies that
// QueryStream stops at ResultMessage instead of waiting for context cancellation.
type resultMessageTransport struct {
mu sync.Mutex
msgChan chan map[string]any
errChan chan error
sentResult atomic.Bool
closed bool
}
func newResultMessageTransport() *resultMessageTransport {
return &resultMessageTransport{
msgChan: make(chan map[string]any, 16),
errChan: make(chan error, 1),
}
}
func (t *resultMessageTransport) Start(_ context.Context) error {
return nil
}
func (t *resultMessageTransport) ReadMessages(_ context.Context) (<-chan map[string]any, <-chan error) {
return t.msgChan, t.errChan
}
func (t *resultMessageTransport) SendMessage(_ context.Context, data []byte) error {
var msg map[string]any
if err := json.Unmarshal(data, &msg); err != nil {
return err
}
if msgType, ok := msg["type"].(string); ok && msgType == msgTypeControlRequest {
requestID, _ := msg["request_id"].(string)
if requestID == "" {
return nil
}
go func() {
t.msgChan <- map[string]any{
"type": "control_response",
"response": map[string]any{
"subtype": "success",
"request_id": requestID,
"response": map[string]any{},
},
}
}()
return nil
}
if t.sentResult.CompareAndSwap(false, true) {
go func() {
t.msgChan <- map[string]any{
"type": "result",
"subtype": "success",
"is_error": false,
"session_id": "session-test",
}
}()