-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathcoverage_test.go
More file actions
1415 lines (1196 loc) · 38.6 KB
/
Copy pathcoverage_test.go
File metadata and controls
1415 lines (1196 loc) · 38.6 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 workflow
import (
"context"
"fmt"
"log/slog"
"os"
"path/filepath"
"sync"
"testing"
"time"
"github.com/deepnoodle-ai/workflow/internal/require"
)
// --- Patches ---
func TestNewPatch(t *testing.T) {
p := newPatch(patchOptions{Variable: "key", Value: "val", Delete: false})
require.Equal(t, "key", p.Variable())
require.Equal(t, "val", p.Value())
require.False(t, p.Delete())
p2 := newPatch(patchOptions{Variable: "x", Delete: true})
require.True(t, p2.Delete())
require.Nil(t, p2.Value())
}
func TestApplyPatches(t *testing.T) {
state := NewBranchLocalState(nil, map[string]any{"a": 1, "b": 2})
patches := []patch{
newPatch(patchOptions{Variable: "a", Value: 10}),
newPatch(patchOptions{Variable: "b", Delete: true}),
newPatch(patchOptions{Variable: "c", Value: "new"}),
}
applyPatches(state, patches)
v, ok := state.Get("a")
require.True(t, ok)
require.Equal(t, 10, v)
_, ok = state.Get("b")
require.False(t, ok)
v, ok = state.Get("c")
require.True(t, ok)
require.Equal(t, "new", v)
}
// --- BranchLocalState ---
func TestBranchLocalState_Inputs(t *testing.T) {
state := NewBranchLocalState(map[string]any{"z": 1, "a": 2, "m": 3}, nil)
snapshot := state.inputsSnapshot()
require.Equal(t, map[string]any{"z": 1, "a": 2, "m": 3}, snapshot)
}
func TestBranchLocalState_InputsGet(t *testing.T) {
state := NewBranchLocalState(map[string]any{"key": "value"}, nil)
inputs := newInputs(state.inputsSnapshot())
v, ok := inputs.Get("key")
require.True(t, ok)
require.Equal(t, "value", v)
_, ok = inputs.Get("missing")
require.False(t, ok)
}
func TestBranchLocalState_Delete(t *testing.T) {
state := NewBranchLocalState(nil, map[string]any{"a": 1, "b": 2})
state.Delete("a")
_, ok := state.Get("a")
require.False(t, ok)
v, ok := state.Get("b")
require.True(t, ok)
require.Equal(t, 2, v)
}
// --- Context helpers ---
func TestContextGetters(t *testing.T) {
logger := slog.New(slog.NewTextHandler(os.Stdout, nil))
compiler := newTestCompiler()
state := NewBranchLocalState(map[string]any{"input1": "val"}, map[string]any{"var1": 42})
ctx := NewContext(context.Background(), ExecutionContextOptions{
BranchLocalState: state,
Logger: logger,
Compiler: compiler,
BranchID: "branch-1",
StepName: "step-1",
})
require.Equal(t, logger, ctx.Logger())
require.Equal(t, compiler, ctx.Compiler())
require.Equal(t, "branch-1", ctx.BranchID())
require.Equal(t, "step-1", ctx.StepName())
}
func TestWithTimeout(t *testing.T) {
state := NewBranchLocalState(map[string]any{"in": 1}, map[string]any{"v": 2})
parent := NewContext(context.Background(), ExecutionContextOptions{
BranchLocalState: state,
BranchID: "p1",
StepName: "s1",
})
child, cancel := WithTimeout(parent, 5*time.Second)
defer cancel()
require.Equal(t, "p1", child.BranchID())
require.Equal(t, "s1", child.StepName())
// Verify variable access still works
v, ok := child.Get("v")
require.True(t, ok)
require.Equal(t, 2, v)
}
func TestWithTimeout_NonWorkflowContext(t *testing.T) {
// Test the fallback branch when parent is not an executionContext
mockCtx := NewContext(context.Background(), ExecutionContextOptions{})
// WithTimeout with a basic interface should still work
child, cancel := WithTimeout(mockCtx, 5*time.Second)
defer cancel()
require.NotNil(t, child)
}
func TestWithCancel(t *testing.T) {
state := NewBranchLocalState(map[string]any{"in": 1}, map[string]any{"v": 2})
parent := NewContext(context.Background(), ExecutionContextOptions{
BranchLocalState: state,
BranchID: "p1",
StepName: "s1",
})
child, cancel := WithCancel(parent)
defer cancel()
require.Equal(t, "p1", child.BranchID())
require.Equal(t, "s1", child.StepName())
}
func TestWithCancel_NonWorkflowContext(t *testing.T) {
mockCtx := NewContext(context.Background(), ExecutionContextOptions{})
child, cancel := WithCancel(mockCtx)
defer cancel()
require.NotNil(t, child)
}
func TestInputsFromContext(t *testing.T) {
state := NewBranchLocalState(map[string]any{"a": 1, "b": "two"}, nil)
ctx := NewContext(context.Background(), ExecutionContextOptions{
BranchLocalState: state,
})
inputs := ctx.Inputs()
require.Equal(t, map[string]any{"a": 1, "b": "two"}, inputs.ToMap())
require.Equal(t, 2, inputs.Len())
require.Equal(t, []string{"a", "b"}, inputs.Keys())
v, ok := inputs.Get("a")
require.True(t, ok)
require.Equal(t, 1, v)
}
// --- ValidationError ---
func TestValidationError_Error(t *testing.T) {
ve := &ValidationError{
Problems: []ValidationProblem{
{Step: "step1", Message: "unreachable from start step"},
{Message: "workflow-level problem"},
},
}
s := ve.Error()
require.Contains(t, s, "workflow validation failed (2 problems)")
require.Contains(t, s, `step "step1": unreachable from start step`)
require.Contains(t, s, "workflow-level problem")
}
func TestValidationProblem_String(t *testing.T) {
p := ValidationProblem{Step: "my-step", Message: "bad config"}
require.Equal(t, `step "my-step": bad config`, p.String())
p2 := ValidationProblem{Message: "global issue"}
require.Equal(t, "global issue", p2.String())
}
// --- Workflow ---
func TestInput_IsRequired(t *testing.T) {
required := &Input{Name: "name", Type: "string"}
require.True(t, required.IsRequired())
optional := &Input{Name: "name", Type: "string", Default: "default"}
require.False(t, optional.IsRequired())
}
// --- Logger ---
func TestNewJSONLogger(t *testing.T) {
l := NewJSONLogger()
require.NotNil(t, l)
}
// --- FileActivityLogger ---
func TestFileActivityLogger(t *testing.T) {
dir := t.TempDir()
logger := NewFileActivityLogger(dir)
entry := &ActivityLogEntry{
ID: "log-1",
ExecutionID: "exec-1",
Activity: "print",
StepName: "step1",
BranchID: "main",
Parameters: map[string]interface{}{"message": "hello"},
Result: "hello",
StartTime: time.Now(),
Duration: 0.5,
}
// Log an activity
err := logger.LogActivity(context.Background(), entry)
require.NoError(t, err)
// Log another
entry2 := &ActivityLogEntry{
ID: "log-2",
ExecutionID: "exec-1",
Activity: "print",
StepName: "step2",
BranchID: "main",
Parameters: map[string]interface{}{"message": "world"},
Result: "world",
StartTime: time.Now(),
Duration: 0.3,
}
err = logger.LogActivity(context.Background(), entry2)
require.NoError(t, err)
// Read back
entries, err := logger.GetActivityHistory(context.Background(), "exec-1")
require.NoError(t, err)
require.Len(t, entries, 2)
require.Equal(t, "log-1", entries[0].ID)
require.Equal(t, "log-2", entries[1].ID)
// Non-existent execution
_, err = logger.GetActivityHistory(context.Background(), "nonexistent")
require.Error(t, err)
}
func TestFileActivityLogger_Path(t *testing.T) {
logger := NewFileActivityLogger("/tmp/logs")
branch := logger.executionActivityLogPath("exec-123")
require.Equal(t, filepath.Join("/tmp/logs", "exec-123.jsonl"), branch)
}
// --- NullActivityLogger.GetActivityHistory ---
func TestNullActivityLogger_GetActivityHistory(t *testing.T) {
logger := NewNullActivityLogger()
entries, err := logger.GetActivityHistory(context.Background(), "any")
require.NoError(t, err)
require.Nil(t, entries)
}
// --- executionState nested field operations ---
func TestGetNestedField(t *testing.T) {
data := map[string]any{
"user": map[string]any{
"profile": map[string]any{
"name": "alice",
"age": 30,
},
},
"simple": "value",
}
t.Run("simple key", func(t *testing.T) {
v, ok := getNestedField(data, "simple")
require.True(t, ok)
require.Equal(t, "value", v)
})
t.Run("nested key", func(t *testing.T) {
v, ok := getNestedField(data, "user.profile.name")
require.True(t, ok)
require.Equal(t, "alice", v)
})
t.Run("empty branch", func(t *testing.T) {
_, ok := getNestedField(data, "")
require.False(t, ok)
})
t.Run("missing key", func(t *testing.T) {
_, ok := getNestedField(data, "nonexistent")
require.False(t, ok)
})
t.Run("missing nested key", func(t *testing.T) {
_, ok := getNestedField(data, "user.nonexistent")
require.False(t, ok)
})
t.Run("branch through non-map", func(t *testing.T) {
_, ok := getNestedField(data, "simple.sub")
require.False(t, ok)
})
t.Run("empty part in branch", func(t *testing.T) {
_, ok := getNestedField(data, "user..name")
require.False(t, ok)
})
}
func TestSetNestedField(t *testing.T) {
t.Run("simple key", func(t *testing.T) {
data := map[string]any{}
setNestedField(data, "key", "value")
require.Equal(t, "value", data["key"])
})
t.Run("nested key creates intermediate maps", func(t *testing.T) {
data := map[string]any{}
setNestedField(data, "a.b.c", "deep")
require.Equal(t, "deep", data["a"].(map[string]any)["b"].(map[string]any)["c"])
})
t.Run("empty branch is no-op", func(t *testing.T) {
data := map[string]any{}
setNestedField(data, "", "value")
require.Empty(t, data)
})
t.Run("empty part in branch is no-op", func(t *testing.T) {
data := map[string]any{}
setNestedField(data, "a..b", "value")
require.NotContains(t, data, "b")
})
t.Run("overwrites non-map intermediate", func(t *testing.T) {
data := map[string]any{"a": "not a map"}
setNestedField(data, "a.b", "value")
m, ok := data["a"].(map[string]any)
require.True(t, ok)
require.Equal(t, "value", m["b"])
})
t.Run("existing nested map", func(t *testing.T) {
data := map[string]any{
"a": map[string]any{"b": "old"},
}
setNestedField(data, "a.b", "new")
require.Equal(t, "new", data["a"].(map[string]any)["b"])
})
}
// --- executionState ---
func TestExecutionState_NextBranchID(t *testing.T) {
state := newExecutionState("exec-1", "wf", nil)
id1 := state.NextBranchID("main")
id2 := state.NextBranchID("main")
require.Equal(t, "main-1", id1)
require.Equal(t, "main-2", id2)
}
func TestExecutionState_GetWaitingBranchIDs(t *testing.T) {
state := newExecutionState("exec-1", "wf", nil)
state.SetBranchState("branch-1", &BranchState{ID: "branch-1", Status: ExecutionStatusWaiting})
state.SetBranchState("branch-2", &BranchState{ID: "branch-2", Status: ExecutionStatusCompleted})
state.SetBranchState("branch-3", &BranchState{ID: "branch-3", Status: ExecutionStatusWaiting})
waiting := state.GetWaitingBranchIDs()
require.Len(t, waiting, 2)
require.Contains(t, waiting, "branch-1")
require.Contains(t, waiting, "branch-3")
}
func TestExecutionState_IsJoinReady(t *testing.T) {
t.Run("no join state", func(t *testing.T) {
state := newExecutionState("exec-1", "wf", nil)
require.False(t, state.IsJoinReady("step"))
})
t.Run("specific branches all completed", func(t *testing.T) {
state := newExecutionState("exec-1", "wf", nil)
state.SetBranchState("pathA", &BranchState{ID: "pathA", Status: ExecutionStatusCompleted})
state.SetBranchState("pathB", &BranchState{ID: "pathB", Status: ExecutionStatusCompleted})
state.AddBranchToJoin("join-step", "waiter", &JoinConfig{
Branches: []string{"pathA", "pathB"},
}, nil, nil)
require.True(t, state.IsJoinReady("join-step"))
})
t.Run("specific branches not all completed", func(t *testing.T) {
state := newExecutionState("exec-1", "wf", nil)
state.SetBranchState("pathA", &BranchState{ID: "pathA", Status: ExecutionStatusCompleted})
state.SetBranchState("pathB", &BranchState{ID: "pathB", Status: ExecutionStatusRunning})
state.AddBranchToJoin("join-step", "waiter", &JoinConfig{
Branches: []string{"pathA", "pathB"},
}, nil, nil)
require.False(t, state.IsJoinReady("join-step"))
})
t.Run("count-based join ready", func(t *testing.T) {
state := newExecutionState("exec-1", "wf", nil)
state.SetBranchState("p1", &BranchState{ID: "p1", Status: ExecutionStatusCompleted})
state.SetBranchState("p2", &BranchState{ID: "p2", Status: ExecutionStatusCompleted})
state.AddBranchToJoin("join-step", "waiter", &JoinConfig{
Count: 2,
}, nil, nil)
require.True(t, state.IsJoinReady("join-step"))
})
t.Run("count-based join not ready", func(t *testing.T) {
state := newExecutionState("exec-1", "wf", nil)
state.SetBranchState("p1", &BranchState{ID: "p1", Status: ExecutionStatusCompleted})
state.AddBranchToJoin("join-step", "waiter", &JoinConfig{
Count: 2,
}, nil, nil)
require.False(t, state.IsJoinReady("join-step"))
})
t.Run("default join needs 2 completed", func(t *testing.T) {
state := newExecutionState("exec-1", "wf", nil)
state.SetBranchState("p1", &BranchState{ID: "p1", Status: ExecutionStatusCompleted})
state.SetBranchState("p2", &BranchState{ID: "p2", Status: ExecutionStatusCompleted})
state.AddBranchToJoin("join-step", "waiter", &JoinConfig{}, nil, nil)
require.True(t, state.IsJoinReady("join-step"))
})
t.Run("default join with only 1 completed", func(t *testing.T) {
state := newExecutionState("exec-1", "wf", nil)
state.SetBranchState("p1", &BranchState{ID: "p1", Status: ExecutionStatusCompleted})
state.AddBranchToJoin("join-step", "waiter", &JoinConfig{}, nil, nil)
require.False(t, state.IsJoinReady("join-step"))
})
}
// --- MemoryWorkflowRegistry ---
func TestMemoryWorkflowRegistry(t *testing.T) {
reg := NewMemoryWorkflowRegistry()
// Register nil workflow
err := reg.Register(nil)
require.Error(t, err)
require.Contains(t, err.Error(), "workflow cannot be nil")
// Create a valid workflow
wf, err := New(Options{
Name: "test-wf",
Steps: []*Step{{Name: "start", Activity: "print"}},
})
require.NoError(t, err)
// Register it
err = reg.Register(wf)
require.NoError(t, err)
// Get it
got, ok := reg.Get("test-wf")
require.True(t, ok)
require.Equal(t, "test-wf", got.Name())
// Get missing
_, ok = reg.Get("nope")
require.False(t, ok)
// List
names := reg.List()
require.Equal(t, []string{"test-wf"}, names)
}
// --- DefaultChildWorkflowExecutor ---
func TestDefaultChildWorkflowExecutor_RequiresRegistry(t *testing.T) {
_, err := NewDefaultChildWorkflowExecutor(ChildWorkflowExecutorOptions{})
require.Error(t, err)
require.Contains(t, err.Error(), "workflow registry is required")
}
func TestDefaultChildWorkflowExecutor_ExecuteSync(t *testing.T) {
// Create a simple workflow that sets an output
wf, err := New(Options{
Name: "child",
Steps: []*Step{
{Name: "greet", Activity: "greet"},
},
Outputs: []*Output{
{Name: "greeting", Variable: "greeting"},
},
})
require.NoError(t, err)
reg := NewMemoryWorkflowRegistry()
reg.Register(wf)
greetActivity := ActivityFunc("greet", func(ctx Context, params map[string]any) (any, error) {
ctx.Set("greeting", "hello")
return "hello", nil
})
executor, err := NewDefaultChildWorkflowExecutor(ChildWorkflowExecutorOptions{
WorkflowRegistry: reg,
Activities: []Activity{greetActivity},
})
require.NoError(t, err)
result, err := executor.ExecuteSync(context.Background(), &ChildWorkflowSpec{
WorkflowName: "child",
})
require.NoError(t, err)
require.Equal(t, ExecutionStatusCompleted, result.Status)
require.Equal(t, "hello", result.Outputs["greeting"])
}
func TestDefaultChildWorkflowExecutor_ExecuteSyncNotFound(t *testing.T) {
reg := NewMemoryWorkflowRegistry()
executor, err := NewDefaultChildWorkflowExecutor(ChildWorkflowExecutorOptions{
WorkflowRegistry: reg,
})
require.NoError(t, err)
_, err = executor.ExecuteSync(context.Background(), &ChildWorkflowSpec{
WorkflowName: "missing",
})
require.Error(t, err)
require.Contains(t, err.Error(), "not found in registry")
}
func TestDefaultChildWorkflowExecutor_GetResult_NilHandle(t *testing.T) {
reg := NewMemoryWorkflowRegistry()
executor, err := NewDefaultChildWorkflowExecutor(ChildWorkflowExecutorOptions{
WorkflowRegistry: reg,
})
require.NoError(t, err)
_, err = executor.GetResult(context.Background(), nil)
require.Error(t, err)
require.Contains(t, err.Error(), "handle cannot be nil")
}
func TestDefaultChildWorkflowExecutor_GetResult_NotFound(t *testing.T) {
reg := NewMemoryWorkflowRegistry()
executor, err := NewDefaultChildWorkflowExecutor(ChildWorkflowExecutorOptions{
WorkflowRegistry: reg,
})
require.NoError(t, err)
_, err = executor.GetResult(context.Background(), &ChildWorkflowHandle{
ExecutionID: "nonexistent",
})
require.Error(t, err)
require.Contains(t, err.Error(), "not found or has expired")
}
// --- FileCheckpointer ---
func TestFileCheckpointer_DeleteCheckpoint(t *testing.T) {
dir := t.TempDir()
cp, err := NewFileCheckpointer(dir)
require.NoError(t, err)
// Save a checkpoint first
checkpoint := &Checkpoint{
SchemaVersion: CheckpointSchemaVersion,
ID: "cp-1",
ExecutionID: "exec-1",
WorkflowName: "test-wf",
Status: "running",
Inputs: map[string]any{},
Outputs: map[string]any{},
BranchStates: map[string]*BranchState{},
CheckpointAt: time.Now(),
}
err = cp.SaveCheckpoint(context.Background(), checkpoint)
require.NoError(t, err)
// Verify file exists
files, _ := os.ReadDir(filepath.Join(dir, "exec-1"))
require.Greater(t, len(files), 0)
// Delete
err = cp.DeleteCheckpoint(context.Background(), "exec-1")
require.NoError(t, err)
// Verify deleted
_, err = os.Stat(filepath.Join(dir, "exec-1"))
require.True(t, os.IsNotExist(err))
}
func TestFileCheckpointer_ListExecutions(t *testing.T) {
dir := t.TempDir()
cp, err := NewFileCheckpointer(dir)
require.NoError(t, err)
// Save checkpoints for two executions
for _, execID := range []string{"exec-1", "exec-2"} {
checkpoint := &Checkpoint{
SchemaVersion: CheckpointSchemaVersion,
ID: "cp-" + execID,
ExecutionID: execID,
WorkflowName: "test-wf",
Status: "completed",
Inputs: map[string]any{},
Outputs: map[string]any{},
BranchStates: map[string]*BranchState{},
StartTime: time.Now(),
CheckpointAt: time.Now(),
}
err := cp.SaveCheckpoint(context.Background(), checkpoint)
require.NoError(t, err)
}
executions, err := cp.ListExecutions(context.Background())
require.NoError(t, err)
require.Len(t, executions, 2)
}
// --- FencedCheckpointer DeleteCheckpoint ---
func TestFencedCheckpointer_DeleteCheckpoint(t *testing.T) {
dir := t.TempDir()
inner, err := NewFileCheckpointer(dir)
require.NoError(t, err)
fenced := WithFencing(inner, func(ctx context.Context) error {
return nil // fence always valid
})
// Save a checkpoint
checkpoint := &Checkpoint{
SchemaVersion: CheckpointSchemaVersion,
ID: "cp-1",
ExecutionID: "exec-1",
WorkflowName: "test-wf",
Status: "running",
Inputs: map[string]any{},
Outputs: map[string]any{},
BranchStates: map[string]*BranchState{},
CheckpointAt: time.Now(),
}
err = fenced.SaveCheckpoint(context.Background(), checkpoint)
require.NoError(t, err)
err = fenced.DeleteCheckpoint(context.Background(), "exec-1")
require.NoError(t, err)
}
// --- NullCheckpointer DeleteCheckpoint ---
func TestNullCheckpointer_DeleteCheckpoint(t *testing.T) {
cp := NewNullCheckpointer()
err := cp.DeleteCheckpoint(context.Background(), "any")
require.NoError(t, err)
}
// --- BaseExecutionCallbacks ---
func TestBaseExecutionCallbacks(t *testing.T) {
cb := NewBaseExecutionCallbacks()
ctx := context.Background()
// All methods should be no-ops (no panics)
cb.BeforeWorkflowExecution(ctx, &WorkflowExecutionEvent{})
cb.AfterWorkflowExecution(ctx, &WorkflowExecutionEvent{})
cb.BeforeBranchExecution(ctx, &BranchExecutionEvent{})
cb.AfterBranchExecution(ctx, &BranchExecutionEvent{})
cb.BeforeActivityExecution(ctx, &ActivityExecutionEvent{})
cb.AfterActivityExecution(ctx, &ActivityExecutionEvent{})
}
func TestCallbackChain_Add(t *testing.T) {
var calls []string
cb1 := &trackingCallbacks{name: "cb1", calls: &calls}
cb2 := &trackingCallbacks{name: "cb2", calls: &calls}
chain := NewCallbackChain(cb1)
chain.Add(cb2)
ctx := context.Background()
chain.BeforeWorkflowExecution(ctx, &WorkflowExecutionEvent{})
require.Equal(t, []string{"cb1:before-wf", "cb2:before-wf"}, calls)
}
type trackingCallbacks struct {
BaseExecutionCallbacks
name string
calls *[]string
}
func (t *trackingCallbacks) BeforeWorkflowExecution(_ context.Context, _ *WorkflowExecutionEvent) {
*t.calls = append(*t.calls, t.name+":before-wf")
}
// --- executionState additional ---
func TestExecutionState_GenerateBranchID_Duplicate(t *testing.T) {
state := newExecutionState("exec-1", "wf", nil)
state.SetBranchState("my-branch", &BranchState{ID: "my-branch"})
_, err := state.GenerateBranchID("main", "my-branch")
require.Error(t, err)
require.Contains(t, err.Error(), "duplicate branch name")
}
func TestExecutionState_SetError_Nil(t *testing.T) {
state := newExecutionState("exec-1", "wf", nil)
state.SetError(nil)
require.NoError(t, state.GetError())
}
func TestExecutionState_AddBranchToJoin_UpdateExisting(t *testing.T) {
state := newExecutionState("exec-1", "wf", nil)
// First add
state.AddBranchToJoin("step", "branch-1", &JoinConfig{}, nil, nil)
js := state.GetJoinState("step")
require.Equal(t, "branch-1", js.WaitingBranchID)
// Update with different branch
state.AddBranchToJoin("step", "branch-2", &JoinConfig{}, nil, nil)
js = state.GetJoinState("step")
require.Equal(t, "branch-2", js.WaitingBranchID)
}
func TestExecutionState_GetJoinState_Nil(t *testing.T) {
state := newExecutionState("exec-1", "wf", nil)
require.Nil(t, state.GetJoinState("nonexistent"))
}
func TestExecutionState_FromCheckpoint_NilJoinStates(t *testing.T) {
state := newExecutionState("exec-1", "wf", nil)
checkpoint := &Checkpoint{
ExecutionID: "exec-1",
WorkflowName: "wf",
Status: "running",
Inputs: map[string]any{},
Outputs: map[string]any{},
BranchStates: map[string]*BranchState{},
JoinStates: nil, // backward compat
}
state.FromCheckpoint(checkpoint)
require.NotNil(t, state.GetAllJoinStates())
}
// --- Execution with callbacks and step progress ---
func TestExecution_WithCallbacks(t *testing.T) {
var events []string
wf, err := New(Options{
Name: "cb-test",
Steps: []*Step{
{Name: "greet", Activity: "greet"},
},
})
require.NoError(t, err)
greetActivity := ActivityFunc("greet", func(ctx Context, params map[string]any) (any, error) {
return "hello", nil
})
cb := &eventTracker{events: &events}
reg := NewActivityRegistry()
reg.MustRegister(greetActivity)
exec, err := NewExecution(wf, reg,
WithScriptCompiler(newTestCompiler()),
WithExecutionCallbacks(cb),
)
require.NoError(t, err)
_, err = exec.Execute(context.Background())
require.NoError(t, err)
require.Equal(t, ExecutionStatusCompleted, exec.Status())
require.Contains(t, events, "before-wf")
require.Contains(t, events, "after-wf")
require.Contains(t, events, "before-branch")
require.Contains(t, events, "after-branch")
require.Contains(t, events, "before-activity")
require.Contains(t, events, "after-activity")
}
type eventTracker struct {
BaseExecutionCallbacks
events *[]string
}
func (t *eventTracker) BeforeWorkflowExecution(_ context.Context, _ *WorkflowExecutionEvent) {
*t.events = append(*t.events, "before-wf")
}
func (t *eventTracker) AfterWorkflowExecution(_ context.Context, _ *WorkflowExecutionEvent) {
*t.events = append(*t.events, "after-wf")
}
func (t *eventTracker) BeforeBranchExecution(_ context.Context, _ *BranchExecutionEvent) {
*t.events = append(*t.events, "before-branch")
}
func (t *eventTracker) AfterBranchExecution(_ context.Context, _ *BranchExecutionEvent) {
*t.events = append(*t.events, "after-branch")
}
func (t *eventTracker) BeforeActivityExecution(_ context.Context, _ *ActivityExecutionEvent) {
*t.events = append(*t.events, "before-activity")
}
func (t *eventTracker) AfterActivityExecution(_ context.Context, _ *ActivityExecutionEvent) {
*t.events = append(*t.events, "after-activity")
}
// --- Execution with step progress store ---
func TestExecution_WithStepProgressStore(t *testing.T) {
wf, err := New(Options{
Name: "progress-test",
Steps: []*Step{
{Name: "work", Activity: "work"},
},
})
require.NoError(t, err)
workActivity := ActivityFunc("work", func(ctx Context, params map[string]any) (any, error) {
ctx.ReportProgress(ProgressDetail{Message: "halfway", Data: map[string]any{"pct": 50}})
return "done", nil
})
store := &memoryProgressStore{}
reg := NewActivityRegistry()
reg.MustRegister(workActivity)
exec, err := NewExecution(wf, reg,
WithScriptCompiler(newTestCompiler()),
WithStepProgressStore(store),
)
require.NoError(t, err)
_, err = exec.Execute(context.Background())
require.NoError(t, err)
// Poll until async dispatch completes (at least running + completed)
deadline := time.After(2 * time.Second)
for store.Len() < 2 {
select {
case <-deadline:
require.GreaterOrEqual(t, store.Len(), 2, "timed out waiting for step progress updates")
default:
time.Sleep(10 * time.Millisecond)
}
}
require.GreaterOrEqual(t, store.Len(), 2)
}
type memoryProgressStore struct {
mu sync.Mutex
updates []StepProgress
}
func (m *memoryProgressStore) UpdateStepProgress(_ context.Context, _ string, progress StepProgress) error {
m.mu.Lock()
defer m.mu.Unlock()
m.updates = append(m.updates, progress)
return nil
}
func (m *memoryProgressStore) Len() int {
m.mu.Lock()
defer m.mu.Unlock()
return len(m.updates)
}
// --- Execution: context cancellation ---
func TestExecution_ContextCancelled(t *testing.T) {
wf, err := New(Options{
Name: "cancel-test",
Steps: []*Step{
{Name: "slow", Activity: "slow"},
},
})
require.NoError(t, err)
slowActivity := ActivityFunc("slow", func(ctx Context, params map[string]any) (any, error) {
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-time.After(10 * time.Second):
return "done", nil
}
})
reg := NewActivityRegistry()
reg.MustRegister(slowActivity)
exec, err := NewExecution(wf, reg,
WithScriptCompiler(newTestCompiler()),
)
require.NoError(t, err)
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
defer cancel()
result, err := exec.Execute(ctx)
require.NoError(t, err)
require.True(t, result.Failed())
}
// --- Execution.Execute structured result ---
func TestExecution_Execute(t *testing.T) {
wf, err := New(Options{
Name: "execute-test",
Steps: []*Step{
{Name: "step1", Activity: "echo"},
},
Outputs: []*Output{
{Name: "result", Variable: "msg"},
},
})
require.NoError(t, err)
echoActivity := ActivityFunc("echo", func(ctx Context, params map[string]any) (any, error) {
ctx.Set("msg", "hello")
return "hello", nil
})
reg := NewActivityRegistry()
reg.MustRegister(echoActivity)
exec, err := NewExecution(wf, reg,
WithScriptCompiler(newTestCompiler()),
)
require.NoError(t, err)
result, err := exec.Execute(context.Background())
require.NoError(t, err)
require.True(t, result.Completed())
require.False(t, result.Failed())
require.Equal(t, "hello", result.Outputs["result"])
require.NotZero(t, result.Timing.Duration)
}
// --- MemoryWorkflowRegistry: multiple workflows ---
func TestMemoryWorkflowRegistry_Multiple(t *testing.T) {
reg := NewMemoryWorkflowRegistry()
wf1, _ := New(Options{Name: "a", Steps: []*Step{{Name: "s", Activity: "x"}}})
wf2, _ := New(Options{Name: "b", Steps: []*Step{{Name: "s", Activity: "x"}}})
require.NoError(t, reg.Register(wf1))
require.NoError(t, reg.Register(wf2))
require.Len(t, reg.List(), 2)
}
// --- DefaultChildWorkflowExecutor: ExecuteAsync and GetResult ---
func TestDefaultChildWorkflowExecutor_AsyncFlow(t *testing.T) {
wf, err := New(Options{
Name: "async-child",
Steps: []*Step{
{Name: "greet", Activity: "greet"},
},
Outputs: []*Output{
{Name: "msg", Variable: "msg"},
},
})
require.NoError(t, err)
reg := NewMemoryWorkflowRegistry()
reg.Register(wf)
greetActivity := ActivityFunc("greet", func(ctx Context, params map[string]any) (any, error) {
ctx.Set("msg", "async hello")
return "done", nil
})
executor, err := NewDefaultChildWorkflowExecutor(ChildWorkflowExecutorOptions{
WorkflowRegistry: reg,
Activities: []Activity{greetActivity},
})
require.NoError(t, err)
// Use a cancellable context to verify that cancelling the caller does not
// prevent the child workflow from completing.
ctx, cancel := context.WithCancel(context.Background())
handle, err := executor.ExecuteAsync(ctx, &ChildWorkflowSpec{
WorkflowName: "async-child",
})
require.NoError(t, err)
require.NotEmpty(t, handle.ExecutionID)
require.Equal(t, "async-child", handle.WorkflowName)
// Cancel the caller context immediately after launching the async child.
cancel()
// Poll for completion using a fresh context since the original was cancelled.
var result *ChildWorkflowResult
for i := 0; i < 50; i++ {