duroxide 0.1.27

Durable code execution framework for Rust
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
//! Comprehensive tests for the management interface including metrics
#![allow(clippy::unwrap_used)]
#![allow(clippy::clone_on_ref_ptr)]
#![allow(clippy::expect_used)]

use duroxide::providers::sqlite::SqliteProvider;
use duroxide::runtime::registry::ActivityRegistry;
use duroxide::runtime::{self, RuntimeOptions};
use duroxide::{ActivityContext, Client, OrchestrationContext, OrchestrationRegistry};
use std::sync::Arc;
use std::time::Duration;

mod common;

// Helper to create fast-polling runtime for management tests (timing-sensitive)
fn fast_runtime_options() -> RuntimeOptions {
    RuntimeOptions {
        dispatcher_min_poll_interval: Duration::from_millis(50),
        ..Default::default()
    }
}

/// Test: Basic capability discovery
#[tokio::test]
async fn test_capability_discovery() {
    let store = Arc::new(SqliteProvider::new("sqlite::memory:", None).await.unwrap());
    let client = Client::new(store.clone());

    // Test capability discovery
    assert!(client.has_management_capability());

    // Test management methods work
    let instances = client.list_all_instances().await.unwrap();
    assert!(instances.is_empty());

    let metrics = client.get_system_metrics().await.unwrap();
    assert_eq!(metrics.total_instances, 0);
    assert_eq!(metrics.total_executions, 0);
    assert_eq!(metrics.running_instances, 0);
    assert_eq!(metrics.completed_instances, 0);
    assert_eq!(metrics.failed_instances, 0);
    assert_eq!(metrics.total_events, 0);

    let queues = client.get_queue_depths().await.unwrap();
    assert_eq!(queues.orchestrator_queue, 0);
    assert_eq!(queues.worker_queue, 0);
    assert_eq!(queues.timer_queue, 0);
}

/// Test: Management features with workflow
#[tokio::test]
async fn test_management_features_with_workflow() {
    let store = Arc::new(SqliteProvider::new("sqlite::memory:", None).await.unwrap());
    let client = Client::new(store.clone());

    // Set up runtime with orchestrations
    let orchestrations = OrchestrationRegistry::builder()
        .register(
            "TestOrchestration",
            |_ctx: OrchestrationContext, _input: String| async move { Ok("completed".to_string()) },
        )
        .build();

    let _rt =
        runtime::Runtime::start_with_store(store.clone(), ActivityRegistry::builder().build(), orchestrations).await;

    // Start an orchestration
    client
        .start_orchestration("test-instance", "TestOrchestration", "{}")
        .await
        .unwrap();

    // Wait for completion (with timeout)
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
    loop {
        let completed = client.list_instances_by_status("Completed").await.unwrap();
        if completed.contains(&"test-instance".to_string()) {
            break;
        }
        if std::time::Instant::now() > deadline {
            panic!("Timed out waiting for orchestration to complete");
        }
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
    }

    // Check management features
    assert!(client.has_management_capability());

    let instances = client.list_all_instances().await.unwrap();
    assert_eq!(instances.len(), 1);
    assert_eq!(instances[0], "test-instance");

    let info = client.get_instance_info("test-instance").await.unwrap();
    assert_eq!(info.instance_id, "test-instance");
    assert_eq!(info.orchestration_name, "TestOrchestration");
    assert_eq!(info.orchestration_version, "1.0.0");
    assert_eq!(info.current_execution_id, 1);

    let executions = client.list_executions("test-instance").await.unwrap();
    assert_eq!(executions.len(), 1);
    assert_eq!(executions[0], 1);

    let metrics = client.get_system_metrics().await.unwrap();
    assert_eq!(metrics.total_instances, 1);
    assert_eq!(metrics.total_executions, 1);
}

/// Test: Instance discovery and listing
#[tokio::test]
async fn test_instance_discovery() {
    let (store, _temp_dir) = common::create_sqlite_store_disk().await;
    let client = Client::new(store.clone());

    // Initially empty
    let instances = client.list_all_instances().await.unwrap();
    assert!(instances.is_empty());

    // Start some orchestrations
    let activities = ActivityRegistry::builder()
        .register("TestActivity", |_ctx: ActivityContext, input: String| async move {
            Ok(format!("Processed: {input}"))
        })
        .build();

    let orchestrations = OrchestrationRegistry::builder()
        .register(
            "TestOrchestration",
            |ctx: OrchestrationContext, input: String| async move {
                let result = ctx.schedule_activity("TestActivity", input).await?;
                Ok(result)
            },
        )
        .build();

    let _rt =
        runtime::Runtime::start_with_options(store.clone(), activities, orchestrations, fast_runtime_options()).await;

    // Start multiple orchestrations
    client
        .start_orchestration("instance-1", "TestOrchestration", "input-1")
        .await
        .unwrap();
    client
        .start_orchestration("instance-2", "TestOrchestration", "input-2")
        .await
        .unwrap();
    client
        .start_orchestration("instance-3", "TestOrchestration", "input-3")
        .await
        .unwrap();

    // Wait for all orchestrations to complete (with timeout)
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
    loop {
        let completed = client.list_instances_by_status("Completed").await.unwrap();
        if completed.len() >= 3 {
            break;
        }
        if std::time::Instant::now() > deadline {
            panic!(
                "Timed out waiting for orchestrations to complete. Completed: {}",
                completed.len()
            );
        }
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
    }

    // List instances
    let instances = client.list_all_instances().await.unwrap();
    assert_eq!(instances.len(), 3);
    assert!(instances.contains(&"instance-1".to_string()));
    assert!(instances.contains(&"instance-2".to_string()));
    assert!(instances.contains(&"instance-3".to_string()));

    // Test status filtering
    let completed = client.list_instances_by_status("Completed").await.unwrap();
    assert_eq!(completed.len(), 3);

    let running = client.list_instances_by_status("Running").await.unwrap();
    assert_eq!(running.len(), 0);
}

/// Test: Instance information retrieval
#[tokio::test]
async fn test_instance_info() {
    let (store, _temp_dir) = common::create_sqlite_store_disk().await;
    let client = Client::new(store.clone());

    let activities = ActivityRegistry::builder()
        .register("TestActivity", |_ctx: ActivityContext, input: String| async move {
            Ok(format!("Processed: {input}"))
        })
        .build();

    let orchestrations = OrchestrationRegistry::builder()
        .register(
            "TestOrchestration",
            |ctx: OrchestrationContext, input: String| async move {
                let result = ctx.schedule_activity("TestActivity", input).await?;
                Ok(result)
            },
        )
        .build();

    let _rt =
        runtime::Runtime::start_with_options(store.clone(), activities, orchestrations, fast_runtime_options()).await;

    // Start orchestration
    client
        .start_orchestration("test-instance", "TestOrchestration", "test-input")
        .await
        .unwrap();

    // Wait for completion (with timeout)
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
    loop {
        let completed = client.list_instances_by_status("Completed").await.unwrap();
        if completed.contains(&"test-instance".to_string()) {
            break;
        }
        if std::time::Instant::now() > deadline {
            panic!("Timed out waiting for orchestration to complete");
        }
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
    }

    // Get instance info
    let info = client.get_instance_info("test-instance").await.unwrap();
    assert_eq!(info.instance_id, "test-instance");
    assert_eq!(info.orchestration_name, "TestOrchestration");
    assert_eq!(info.orchestration_version, "1.0.0");
    assert_eq!(info.current_execution_id, 1);
    assert_eq!(info.status, "Completed");
    assert!(info.output.is_some());
    // Note: created_at and updated_at may be 0 if not properly set by SQLite
    // This is a known limitation - timestamps are stored as strings but read as i64

    // Test non-existent instance
    let result = client.get_instance_info("nonexistent").await;
    assert!(result.is_err());
    assert!(result.unwrap_err().to_string().contains("not found"));
}

/// Test: Execution information and history
#[tokio::test]
async fn test_execution_info() {
    let (store, _temp_dir) = common::create_sqlite_store_disk().await;
    let client = Client::new(store.clone());

    let activities = ActivityRegistry::builder()
        .register("TestActivity", |_ctx: ActivityContext, input: String| async move {
            Ok(format!("Processed: {input}"))
        })
        .build();

    let orchestrations = OrchestrationRegistry::builder()
        .register(
            "TestOrchestration",
            |ctx: OrchestrationContext, input: String| async move {
                let result = ctx.schedule_activity("TestActivity", input).await?;
                Ok(result)
            },
        )
        .build();

    let _rt =
        runtime::Runtime::start_with_options(store.clone(), activities, orchestrations, fast_runtime_options()).await;

    // Start orchestration
    client
        .start_orchestration("test-exec", "TestOrchestration", "test-input")
        .await
        .unwrap();

    // Wait for completion (with timeout)
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
    loop {
        let completed = client.list_instances_by_status("Completed").await.unwrap();
        if completed.contains(&"test-exec".to_string()) {
            break;
        }
        if std::time::Instant::now() > deadline {
            panic!("Timed out waiting for orchestration to complete");
        }
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
    }

    // List executions
    let executions = client.list_executions("test-exec").await.unwrap();
    assert_eq!(executions.len(), 1);
    assert_eq!(executions[0], 1);

    // Get execution info
    let exec_info = client.get_execution_info("test-exec", 1).await.unwrap();
    assert_eq!(exec_info.execution_id, 1);
    assert_eq!(exec_info.status, "Completed");
    assert!(exec_info.output.is_some());
    // Note: started_at and completed_at may be 0 if not properly set by SQLite
    // This is a known limitation - timestamps are stored as strings but read as i64
    assert!(exec_info.event_count > 0);

    // Read execution history
    let history = client.read_execution_history("test-exec", 1).await.unwrap();
    assert!(!history.is_empty());

    // Should contain at least OrchestrationStarted and OrchestrationCompleted events
    let has_started = history
        .iter()
        .any(|e| matches!(&e.kind, duroxide::EventKind::OrchestrationStarted { .. }));
    let has_completed = history
        .iter()
        .any(|e| matches!(&e.kind, duroxide::EventKind::OrchestrationCompleted { .. }));
    assert!(has_started);
    assert!(has_completed);

    // Test non-existent execution
    let result = client.get_execution_info("test-exec", 999).await;
    assert!(result.is_err());
}

/// Test: Multi-execution support (ContinueAsNew)
#[tokio::test]
async fn test_multi_execution_support() {
    let (store, _temp_dir) = common::create_sqlite_store_disk().await;
    let client = Client::new(store.clone());

    let orchestrations = OrchestrationRegistry::builder()
        .register(
            "ContinueAsNewTest",
            |ctx: OrchestrationContext, count_str: String| async move {
                let count: u32 = count_str.parse().unwrap_or(0);
                if count < 3 {
                    return ctx.continue_as_new((count + 1).to_string()).await;
                } else {
                    Ok(format!("Final: {count}"))
                }
            },
        )
        .build();

    let _rt =
        runtime::Runtime::start_with_store(store.clone(), ActivityRegistry::builder().build(), orchestrations).await;

    // Start orchestration that will ContinueAsNew
    client
        .start_orchestration("test-continue", "ContinueAsNewTest", "0")
        .await
        .unwrap();

    // Wait for completion using wait_for_orchestration instead of sleep
    match client
        .wait_for_orchestration("test-continue", std::time::Duration::from_secs(5))
        .await
    {
        Ok(status) => println!("Orchestration completed with status: {status:?}"),
        Err(e) => println!("Orchestration failed: {e:?}"),
    }

    // Add a small delay to ensure all processing is complete
    tokio::time::sleep(std::time::Duration::from_millis(100)).await;

    // ContinueAsNew creates separate execution records now
    let executions = client.list_executions("test-continue").await.unwrap();

    // Should have exactly 4 executions: exec_id=1 (count=0→1), exec_id=2 (count=1→2),
    // exec_id=3 (count=2→3), exec_id=4 (count=3, completes)
    assert_eq!(executions.len(), 4);
    assert_eq!(executions, vec![1, 2, 3, 4]);

    // Get info for each execution
    for exec_id in &executions {
        let exec_info = client.get_execution_info("test-continue", *exec_id).await.unwrap();
        assert_eq!(exec_info.execution_id, *exec_id);

        // First 3 executions should be ContinuedAsNew, last one should be Completed
        if *exec_id == 4 {
            assert_eq!(exec_info.status, "Completed");
        } else {
            assert_eq!(exec_info.status, "ContinuedAsNew");
        }
    }

    // Instance info should show the latest execution
    let instance_info = client.get_instance_info("test-continue").await.unwrap();
    assert_eq!(instance_info.current_execution_id, 4); // Should be 4 (the final execution)
    assert_eq!(instance_info.status, "Completed"); // Instance status is Completed
}

/// Test: System metrics
#[tokio::test]
async fn test_system_metrics() {
    let (store, _temp_dir) = common::create_sqlite_store_disk().await;
    let client = Client::new(store.clone());

    let activities = ActivityRegistry::builder()
        .register("TestActivity", |_ctx: ActivityContext, input: String| async move {
            Ok(format!("Processed: {input}"))
        })
        .register("FailingActivity", |_ctx: ActivityContext, _input: String| async move {
            Err("Intentional failure".to_string())
        })
        .build();

    let orchestrations = OrchestrationRegistry::builder()
        .register(
            "SuccessOrchestration",
            |ctx: OrchestrationContext, input: String| async move {
                let result = ctx.schedule_activity("TestActivity", input).await?;
                Ok(result)
            },
        )
        .register(
            "FailureOrchestration",
            |ctx: OrchestrationContext, input: String| async move {
                let _result = ctx.schedule_activity("FailingActivity", input).await?;
                Ok("Should not reach here".to_string())
            },
        )
        .register(
            "RunningOrchestration",
            |ctx: OrchestrationContext, _input: String| async move {
                // Wait for external event (never comes)
                let _event = ctx.schedule_wait("NeverComes").await;
                Ok("Should not reach here".to_string())
            },
        )
        .build();

    let _rt =
        runtime::Runtime::start_with_options(store.clone(), activities, orchestrations, fast_runtime_options()).await;

    // Start orchestrations with different outcomes
    client
        .start_orchestration("success-1", "SuccessOrchestration", "input-1")
        .await
        .unwrap();
    client
        .start_orchestration("success-2", "SuccessOrchestration", "input-2")
        .await
        .unwrap();
    client
        .start_orchestration("failure-1", "FailureOrchestration", "input-1")
        .await
        .unwrap();
    client
        .start_orchestration("running-1", "RunningOrchestration", "input-1")
        .await
        .unwrap();

    // Wait for processing
    tokio::time::sleep(std::time::Duration::from_millis(5000)).await;

    // Get system metrics
    let metrics = client.get_system_metrics().await.unwrap();

    assert_eq!(metrics.total_instances, 4);
    assert_eq!(metrics.total_executions, 4);
    assert_eq!(metrics.running_instances, 1); // running-1
    assert_eq!(metrics.completed_instances, 2); // success-1, success-2
    assert_eq!(metrics.failed_instances, 1); // failure-1
    assert!(metrics.total_events > 0);

    // Test status filtering
    let completed = client.list_instances_by_status("Completed").await.unwrap();
    assert_eq!(completed.len(), 2);
    assert!(completed.contains(&"success-1".to_string()));
    assert!(completed.contains(&"success-2".to_string()));

    let failed = client.list_instances_by_status("Failed").await.unwrap();
    assert_eq!(failed.len(), 1);
    assert!(failed.contains(&"failure-1".to_string()));

    let running = client.list_instances_by_status("Running").await.unwrap();
    assert_eq!(running.len(), 1);
    assert!(running.contains(&"running-1".to_string()));
}

/// Test: Queue depths
#[tokio::test]
async fn test_queue_depths() {
    let (store, _temp_dir) = common::create_sqlite_store_disk().await;
    let client = Client::new(store.clone());

    let activities = ActivityRegistry::builder()
        .register("SlowActivity", |_ctx: ActivityContext, _input: String| async move {
            // Simulate slow activity
            tokio::time::sleep(std::time::Duration::from_millis(500)).await;
            Ok("Slow result".to_string())
        })
        .build();

    let orchestrations = OrchestrationRegistry::builder()
        .register(
            "QueueTestOrchestration",
            |ctx: OrchestrationContext, input: String| async move {
                let result = ctx.schedule_activity("SlowActivity", input).await?;
                Ok(result)
            },
        )
        .build();

    let _rt =
        runtime::Runtime::start_with_options(store.clone(), activities, orchestrations, fast_runtime_options()).await;

    // Start multiple orchestrations quickly
    for i in 1..=5 {
        client
            .start_orchestration(
                &format!("queue-test-{i}"),
                "QueueTestOrchestration",
                &format!("input-{i}"),
            )
            .await
            .unwrap();
    }

    // Check queue depths immediately (should have pending work)
    let _queues = client.get_queue_depths().await.unwrap();

    // Should have some pending work in queues (counts are always >= 0)
    // Note: Queue depths are always non-negative, so these assertions are redundant

    // Wait for completion
    tokio::time::sleep(std::time::Duration::from_secs(2)).await;

    // Check queue depths after completion (should be empty or minimal)
    let queues_after = client.get_queue_depths().await.unwrap();
    // Note: Some queues may still have items due to timing, so we just check they're reasonable
    assert!(queues_after.orchestrator_queue <= 1);
    assert!(queues_after.worker_queue <= 1);
    assert!(queues_after.timer_queue <= 1);
}

/// Test: Error handling for non-existent instances
#[tokio::test]
async fn test_error_handling() {
    let (store, _temp_dir) = common::create_sqlite_store_disk().await;
    let client = Client::new(store.clone());

    // Test all management methods with non-existent instance
    let result = client.get_instance_info("nonexistent").await;
    assert!(result.is_err());
    assert!(result.unwrap_err().to_string().contains("not found"));

    let result = client.get_execution_info("nonexistent", 1).await;
    assert!(result.is_err());
    assert!(result.unwrap_err().to_string().contains("not found"));

    let result = client.read_execution_history("nonexistent", 1).await;
    assert!(result.is_ok());
    assert!(result.unwrap().is_empty());

    let executions = client.list_executions("nonexistent").await.unwrap();
    assert!(executions.is_empty());

    // Test status filtering with non-existent status
    let result = client.list_instances_by_status("NonExistentStatus").await;
    assert!(result.is_ok());
    assert!(result.unwrap().is_empty());
}

/// Test: Management interface with complex workflow
#[tokio::test]
async fn test_complex_workflow_management() {
    let (store, _temp_dir) = common::create_sqlite_store_disk().await;
    let client = Client::new(store.clone());

    let activities = ActivityRegistry::builder()
        .register("ProcessOrder", |_ctx: ActivityContext, order: String| async move {
            Ok(format!("Processed order: {order}"))
        })
        .register("SendEmail", |_ctx: ActivityContext, email: String| async move {
            Ok(format!("Sent email: {email}"))
        })
        .register("UpdateInventory", |_ctx: ActivityContext, item: String| async move {
            Ok(format!("Updated inventory for: {item}"))
        })
        .build();

    let orchestrations = OrchestrationRegistry::builder()
        .register(
            "OrderProcessing",
            |ctx: OrchestrationContext, order: String| async move {
                // Process order
                let result = ctx.schedule_activity("ProcessOrder", order.clone()).await?;

                // Send confirmation email
                let _email = ctx
                    .schedule_activity("SendEmail", format!("Order processed: {result}"))
                    .await?;

                // Update inventory
                let _inventory = ctx.schedule_activity("UpdateInventory", order).await?;

                Ok(result)
            },
        )
        .build();

    let _rt =
        runtime::Runtime::start_with_options(store.clone(), activities, orchestrations, fast_runtime_options()).await;

    // Start multiple order processing workflows
    let orders = vec!["order-1", "order-2", "order-3", "order-4", "order-5"];
    for order in &orders {
        client
            .start_orchestration(*order, "OrderProcessing", *order)
            .await
            .unwrap();
    }

    // Wait for all orchestrations to complete (with timeout)
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
    loop {
        let completed = client.list_instances_by_status("Completed").await.unwrap();
        if completed.len() >= 5 {
            break;
        }
        if std::time::Instant::now() > deadline {
            panic!(
                "Timed out waiting for orchestrations to complete. Completed: {}",
                completed.len()
            );
        }
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
    }

    // Verify all orders completed
    let instances = client.list_all_instances().await.unwrap();
    assert_eq!(instances.len(), 5);

    let completed = client.list_instances_by_status("Completed").await.unwrap();
    assert_eq!(completed.len(), 5);

    // Verify system metrics
    let metrics = client.get_system_metrics().await.unwrap();
    assert_eq!(metrics.total_instances, 5);
    assert_eq!(metrics.total_executions, 5);
    assert_eq!(metrics.completed_instances, 5);
    assert_eq!(metrics.failed_instances, 0);
    assert_eq!(metrics.running_instances, 0);
    assert!(metrics.total_events > 0);

    // Verify each instance details
    for order in &orders {
        let info = client.get_instance_info(order).await.unwrap();
        assert_eq!(info.instance_id, *order);
        assert_eq!(info.orchestration_name, "OrderProcessing");
        assert_eq!(info.status, "Completed");
        assert!(info.output.is_some());

        let executions = client.list_executions(order).await.unwrap();
        assert_eq!(executions.len(), 1);
        assert_eq!(executions[0], 1);

        let exec_info = client.get_execution_info(order, 1).await.unwrap();
        assert_eq!(exec_info.execution_id, 1);
        assert_eq!(exec_info.status, "Completed");
        // Note: completed_at may be None due to SQLite timestamp handling
        assert!(exec_info.event_count > 0);

        let history = client.read_execution_history(order, 1).await.unwrap();
        assert!(!history.is_empty());

        // Should contain OrchestrationStarted, ActivityCompleted, and OrchestrationCompleted events
        let has_started = history
            .iter()
            .any(|e| matches!(&e.kind, duroxide::EventKind::OrchestrationStarted { .. }));
        let has_completed = history
            .iter()
            .any(|e| matches!(&e.kind, duroxide::EventKind::OrchestrationCompleted { .. }));
        let has_activity = history
            .iter()
            .any(|e| matches!(&e.kind, duroxide::EventKind::ActivityCompleted { .. }));

        assert!(has_started);
        assert!(has_completed);
        assert!(has_activity);
    }

    // Verify queue depths are empty
    let queues = client.get_queue_depths().await.unwrap();
    assert_eq!(queues.orchestrator_queue, 0);
    assert_eq!(queues.worker_queue, 0);
    assert_eq!(queues.timer_queue, 0);
}

// ============================================================================
// Coverage improvement tests (moved from coverage_improvement_tests.rs)
// ============================================================================

/// Test: Management API with unknown instance ID returns appropriate errors
#[tokio::test]
async fn test_management_unknown_instance_errors() {
    use duroxide::Event;
    use duroxide::providers::management::{ExecutionInfo, InstanceInfo};
    use duroxide::providers::{Provider, ProviderError};

    let store = Arc::new(SqliteProvider::new_in_memory().await.unwrap());
    let mgmt = store.as_management_capability().unwrap();

    // get_instance_info should return error for unknown instance
    let result: Result<InstanceInfo, ProviderError> = mgmt.get_instance_info("unknown-instance").await;
    assert!(result.is_err());
    let err = result.unwrap_err();
    assert!(
        err.message.contains("not found"),
        "Expected 'not found' error, got: {err}"
    );

    // get_execution_info should return error for unknown instance
    let result: Result<ExecutionInfo, ProviderError> = mgmt.get_execution_info("unknown-instance", 1).await;
    assert!(result.is_err());
    let err = result.unwrap_err();
    assert!(
        err.message.contains("not found"),
        "Expected 'not found' error, got: {err}"
    );

    // list_executions should return empty for unknown instance
    let result: Result<Vec<u64>, ProviderError> = mgmt.list_executions("unknown-instance").await;
    assert!(result.is_ok());
    assert!(result.unwrap().is_empty());

    // read_history_with_execution_id should return empty for unknown instance
    let result: Result<Vec<Event>, ProviderError> = mgmt.read_history_with_execution_id("unknown-instance", 1).await;
    assert!(result.is_ok());
    assert!(result.unwrap().is_empty());

    // latest_execution_id returns Ok(1) for unknown instance (per design, default to exec 1)
    let result: Result<u64, ProviderError> = mgmt.latest_execution_id("unknown-instance").await;
    assert!(result.is_ok());
    assert_eq!(result.unwrap(), 1);
}

/// Test: Management API read_execution for specific execution
#[tokio::test]
async fn test_management_read_execution_specific() {
    let (store, _temp_dir) = common::create_sqlite_store_disk().await;
    let client = Client::new(store.clone());
    let mgmt = store.as_management_capability().unwrap();

    let orchestrations = OrchestrationRegistry::builder()
        .register(
            "ContinueTest",
            |ctx: OrchestrationContext, count_str: String| async move {
                let count: u32 = count_str.parse().unwrap_or(0);
                if count < 2 {
                    ctx.continue_as_new((count + 1).to_string()).await
                } else {
                    Ok(format!("Final: {count}"))
                }
            },
        )
        .build();

    let _rt =
        runtime::Runtime::start_with_store(store.clone(), ActivityRegistry::builder().build(), orchestrations).await;

    client
        .start_orchestration("read-exec-test", "ContinueTest", "0")
        .await
        .unwrap();

    // Wait for completion
    client
        .wait_for_orchestration("read-exec-test", Duration::from_secs(5))
        .await
        .unwrap();

    // Read each execution's history separately
    let executions = mgmt.list_executions("read-exec-test").await.unwrap();
    assert!(executions.len() >= 2, "Should have at least 2 executions");

    for exec_id in &executions {
        let history = mgmt
            .read_history_with_execution_id("read-exec-test", *exec_id)
            .await
            .unwrap();
        assert!(!history.is_empty(), "Execution {exec_id} should have history");

        // First event should be OrchestrationStarted
        let first_event = &history[0];
        assert!(
            matches!(&first_event.kind, duroxide::EventKind::OrchestrationStarted { .. }),
            "First event should be OrchestrationStarted"
        );
    }

    // Verify latest_execution_id
    let latest = mgmt.latest_execution_id("read-exec-test").await.unwrap();
    assert_eq!(latest, *executions.last().unwrap());
}

/// Test: Management API get_instance_tree with hierarchy
#[tokio::test]
async fn test_management_get_instance_tree() {
    let (store, _temp_dir) = common::create_sqlite_store_disk().await;
    let client = Client::new(store.clone());
    let mgmt = store.as_management_capability().unwrap();

    let activities = ActivityRegistry::builder()
        .register("SimpleActivity", |_ctx: ActivityContext, input: String| async move {
            Ok(format!("Processed: {input}"))
        })
        .build();

    let orchestrations = OrchestrationRegistry::builder()
        .register("Parent", |ctx: OrchestrationContext, _input: String| async move {
            // Spawn child sub-orchestrations
            let child1 = ctx.schedule_sub_orchestration_with_id("Child", "child-1", "input1".to_string());
            let child2 = ctx.schedule_sub_orchestration_with_id("Child", "child-2", "input2".to_string());
            let results = ctx.join(vec![child1, child2]).await;
            Ok(format!("Children: {:?}", results))
        })
        .register("Child", |ctx: OrchestrationContext, input: String| async move {
            let result = ctx.schedule_activity("SimpleActivity", input).await?;
            Ok(result)
        })
        .build();

    let _rt = runtime::Runtime::start_with_options(
        store.clone(),
        activities,
        orchestrations,
        RuntimeOptions {
            dispatcher_min_poll_interval: Duration::from_millis(50),
            ..Default::default()
        },
    )
    .await;

    client.start_orchestration("parent-1", "Parent", "start").await.unwrap();

    // Wait for completion
    client
        .wait_for_orchestration("parent-1", Duration::from_secs(10))
        .await
        .unwrap();

    // Get instance tree
    let tree = mgmt.get_instance_tree("parent-1").await.unwrap();
    assert_eq!(tree.root_id, "parent-1");
    assert!(
        tree.size() >= 3,
        "Tree should have parent + 2 children, got: {}",
        tree.size()
    );
    assert!(tree.all_ids.contains(&"parent-1".to_string()));
    assert!(tree.all_ids.contains(&"child-1".to_string()));
    assert!(tree.all_ids.contains(&"child-2".to_string()));
    assert!(!tree.is_root_only());
}

/// Test: Management list_instances_by_status with all status types
#[tokio::test]
async fn test_management_all_status_types() {
    let (store, _temp_dir) = common::create_sqlite_store_disk().await;
    let client = Client::new(store.clone());
    let mgmt = store.as_management_capability().unwrap();

    let activities = ActivityRegistry::builder()
        .register(
            "OkActivity",
            |_ctx: ActivityContext, input: String| async move { Ok(input) },
        )
        .register("FailActivity", |_ctx: ActivityContext, _: String| async move {
            Err("Intentional failure".to_string())
        })
        .build();

    let orchestrations = OrchestrationRegistry::builder()
        .register("Completed", |ctx: OrchestrationContext, input: String| async move {
            ctx.schedule_activity("OkActivity", input).await
        })
        .register("Failed", |ctx: OrchestrationContext, input: String| async move {
            ctx.schedule_activity("FailActivity", input).await
        })
        .register(
            "ContinuedAsNew",
            |ctx: OrchestrationContext, input: String| async move {
                let count: u32 = input.parse().unwrap_or(0);
                if count < 1 {
                    ctx.continue_as_new((count + 1).to_string()).await
                } else {
                    Ok("done".to_string())
                }
            },
        )
        .register("Running", |ctx: OrchestrationContext, _: String| async move {
            // Wait for external event that never comes
            let _event = ctx.schedule_wait("NeverComes").await;
            Ok("done".to_string())
        })
        .build();

    let _rt = runtime::Runtime::start_with_options(
        store.clone(),
        activities,
        orchestrations,
        RuntimeOptions {
            dispatcher_min_poll_interval: Duration::from_millis(50),
            ..Default::default()
        },
    )
    .await;

    // Start orchestrations of each type
    client
        .start_orchestration("inst-completed", "Completed", "test")
        .await
        .unwrap();
    client
        .start_orchestration("inst-failed", "Failed", "test")
        .await
        .unwrap();
    client
        .start_orchestration("inst-continued", "ContinuedAsNew", "0")
        .await
        .unwrap();
    client
        .start_orchestration("inst-running", "Running", "test")
        .await
        .unwrap();

    // Wait for terminal ones to complete
    tokio::time::sleep(Duration::from_secs(2)).await;

    // Test each status filter
    let completed = mgmt.list_instances_by_status("Completed").await.unwrap();
    assert!(
        completed.contains(&"inst-completed".to_string()) || completed.contains(&"inst-continued".to_string()),
        "Should have completed instances"
    );

    let failed = mgmt.list_instances_by_status("Failed").await.unwrap();
    assert!(
        failed.contains(&"inst-failed".to_string()),
        "Should have failed instances"
    );

    let running = mgmt.list_instances_by_status("Running").await.unwrap();
    assert!(
        running.contains(&"inst-running".to_string()),
        "Should have running instances"
    );

    // Test unknown status returns empty
    let unknown = mgmt.list_instances_by_status("UnknownStatus").await.unwrap();
    assert!(unknown.is_empty(), "Unknown status should return empty list");
}

// ═══════════════════════════════════════════════════════════════════════════════
// Orchestration stats (Client::get_orchestration_stats)
// ═══════════════════════════════════════════════════════════════════════════════

/// Client::get_orchestration_stats returns stats after orchestration completes.
#[tokio::test]
async fn client_get_orchestration_stats_after_completion() {
    let store = Arc::new(SqliteProvider::new_in_memory().await.unwrap());
    let activities = ActivityRegistry::builder().build();
    let orchestrations = OrchestrationRegistry::builder()
        .register("StatsOrch", |ctx: OrchestrationContext, _: String| async move {
            ctx.set_kv_value("user_key", "user_value");
            Ok("done".to_string())
        })
        .build();

    let rt = runtime::Runtime::start_with_store(store.clone(), activities, orchestrations).await;
    let client = Client::new(store.clone());
    client
        .start_orchestration("inst-stats-1", "StatsOrch", "")
        .await
        .unwrap();
    client
        .wait_for_orchestration("inst-stats-1", Duration::from_secs(5))
        .await
        .unwrap();

    let stats = client
        .get_orchestration_stats("inst-stats-1")
        .await
        .unwrap()
        .expect("stats should be present after completion");
    assert!(stats.history_event_count > 0, "should have history events");
    assert_eq!(stats.kv_user_key_count, 1, "one user key was set");
    assert!(stats.kv_total_value_bytes > 0, "user value bytes should be non-zero");

    rt.shutdown(None).await;
}

/// Client::get_orchestration_stats returns None for non-existent instance.
#[tokio::test]
async fn client_get_orchestration_stats_nonexistent() {
    let store = Arc::new(SqliteProvider::new_in_memory().await.unwrap());
    let client = Client::new(store);
    let stats = client.get_orchestration_stats("no-such-instance").await.unwrap();
    assert!(stats.is_none());
}

/// Stats reflect accurate KV metrics across multiple keys.
#[tokio::test]
async fn client_orchestration_stats_kv_metrics_accuracy() {
    let store = Arc::new(SqliteProvider::new_in_memory().await.unwrap());
    let activities = ActivityRegistry::builder().build();
    let orchestrations = OrchestrationRegistry::builder()
        .register("MultiKV", |ctx: OrchestrationContext, _: String| async move {
            ctx.set_kv_value("k1", "aaa"); // 3 bytes
            ctx.set_kv_value("k2", "bbbbb"); // 5 bytes
            ctx.set_kv_value("k3", "cc"); // 2 bytes
            Ok("done".to_string())
        })
        .build();

    let rt = runtime::Runtime::start_with_store(store.clone(), activities, orchestrations).await;
    let client = Client::new(store.clone());
    client
        .start_orchestration("inst-multi-kv", "MultiKV", "")
        .await
        .unwrap();
    client
        .wait_for_orchestration("inst-multi-kv", Duration::from_secs(5))
        .await
        .unwrap();

    let stats = client
        .get_orchestration_stats("inst-multi-kv")
        .await
        .unwrap()
        .expect("stats should exist");
    assert_eq!(stats.kv_user_key_count, 3);
    assert_eq!(stats.kv_total_value_bytes, 10); // 3 + 5 + 2

    rt.shutdown(None).await;
}

/// Stats report accurate history_size_bytes for large histories (>256 KB).
#[tokio::test]
async fn client_orchestration_stats_large_history_size() {
    let store = Arc::new(SqliteProvider::new_in_memory().await.unwrap());
    let activities = ActivityRegistry::builder()
        .register("BigResult", |_ctx: ActivityContext, input: String| async move {
            let n: usize = input.parse().unwrap_or(0);
            // Each activity returns ~64 KB × n of data
            Ok("X".repeat(64 * 1024 * n))
        })
        .build();
    let orchestrations = OrchestrationRegistry::builder()
        .register("BigHistory", |ctx: OrchestrationContext, _: String| async move {
            // 4 activities with results of 64KB, 128KB, 192KB, 256KB
            for i in 1..=4u32 {
                ctx.schedule_activity("BigResult", i.to_string()).await?;
            }
            Ok("done".to_string())
        })
        .build();

    let rt = runtime::Runtime::start_with_store(store.clone(), activities, orchestrations).await;
    let client = Client::new(store.clone());
    client.start_orchestration("big-hist", "BigHistory", "").await.unwrap();
    client
        .wait_for_orchestration("big-hist", Duration::from_secs(10))
        .await
        .unwrap();

    let stats = client
        .get_orchestration_stats("big-hist")
        .await
        .unwrap()
        .expect("stats should exist");

    // 4 activities: Scheduled+Completed each = 8 events, plus Started + Completed = 10
    assert_eq!(stats.history_event_count, 10);
    // Payload: activity results are 64KB, 128KB, 192KB, 256KB = 640KB total in results alone
    // Plus JSON serialization overhead, input strings, event metadata
    assert!(
        stats.history_size_bytes > 256 * 1024,
        "history should be >256 KB, got {} bytes",
        stats.history_size_bytes,
    );
    assert!(
        stats.history_size_bytes < 1024 * 1024,
        "history should be <1 MB, got {} bytes",
        stats.history_size_bytes,
    );

    rt.shutdown(None).await;
}

/// Stats report accurate kv_total_value_bytes for large KV values.
#[tokio::test]
async fn client_orchestration_stats_large_kv_values() {
    let store = Arc::new(SqliteProvider::new_in_memory().await.unwrap());
    let activities = ActivityRegistry::builder().build();
    let orchestrations = OrchestrationRegistry::builder()
        .register("BigKV", |ctx: OrchestrationContext, _: String| async move {
            // 4 keys × 16 KB each = 64 KB total
            for i in 0..4 {
                ctx.set_kv_value(format!("big_{i}"), "Y".repeat(16 * 1024));
            }
            Ok("done".to_string())
        })
        .build();

    let rt = runtime::Runtime::start_with_store(store.clone(), activities, orchestrations).await;
    let client = Client::new(store.clone());
    client.start_orchestration("big-kv", "BigKV", "").await.unwrap();
    client
        .wait_for_orchestration("big-kv", Duration::from_secs(5))
        .await
        .unwrap();

    let stats = client
        .get_orchestration_stats("big-kv")
        .await
        .unwrap()
        .expect("stats should exist");

    assert_eq!(stats.kv_user_key_count, 4);
    assert_eq!(stats.kv_total_value_bytes, 4 * 16 * 1024); // exact: 65536

    rt.shutdown(None).await;
}

/// Stats report zero queue_pending_count for a fresh orchestration (no carry-forward).
#[tokio::test]
async fn client_orchestration_stats_no_carry_forward() {
    let store = Arc::new(SqliteProvider::new_in_memory().await.unwrap());
    let activities = ActivityRegistry::builder().build();
    let orchestrations = OrchestrationRegistry::builder()
        .register("Simple", |_ctx: OrchestrationContext, _: String| async move {
            Ok("done".to_string())
        })
        .build();

    let rt = runtime::Runtime::start_with_store(store.clone(), activities, orchestrations).await;
    let client = Client::new(store.clone());
    client.start_orchestration("no-cf", "Simple", "").await.unwrap();
    client
        .wait_for_orchestration("no-cf", Duration::from_secs(5))
        .await
        .unwrap();

    let stats = client
        .get_orchestration_stats("no-cf")
        .await
        .unwrap()
        .expect("stats should exist");
    assert_eq!(stats.queue_pending_count, 0);

    rt.shutdown(None).await;
}

/// After ContinueAsNew, stats reflect the current (latest) execution only.
#[tokio::test]
async fn client_orchestration_stats_after_continue_as_new() {
    let store = Arc::new(SqliteProvider::new_in_memory().await.unwrap());
    let activities = ActivityRegistry::builder()
        .register("Noop", |_ctx: ActivityContext, _: String| async move {
            Ok("ok".to_string())
        })
        .build();
    let orchestrations = OrchestrationRegistry::builder()
        .register("CANStats", |ctx: OrchestrationContext, input: String| async move {
            let n: u32 = input.parse().unwrap_or(0);
            ctx.set_kv_value("iter", n.to_string());
            if n < 2 {
                // Activity creates a yield point so CAN sees history
                ctx.schedule_activity("Noop", "").await?;
                ctx.continue_as_new((n + 1).to_string()).await
            } else {
                Ok(format!("done:{n}"))
            }
        })
        .build();

    let rt = runtime::Runtime::start_with_store(store.clone(), activities, orchestrations).await;
    let client = Client::new(store.clone());
    client.start_orchestration("can-stats", "CANStats", "0").await.unwrap();
    client
        .wait_for_orchestration("can-stats", Duration::from_secs(10))
        .await
        .unwrap();

    let stats = client
        .get_orchestration_stats("can-stats")
        .await
        .unwrap()
        .expect("stats should exist after CAN completion");

    // History events should be from the CURRENT (final) execution only,
    // not accumulated across all executions. Final execution just does
    // set_kv + Ok("done:2") = OrchestrationStarted + OrchestrationCompleted.
    assert!(
        stats.history_event_count >= 2,
        "should have at least Started + Completed, got {}",
        stats.history_event_count,
    );
    // Should NOT have the full history from all 3 executions
    assert!(
        stats.history_event_count <= 5,
        "should only count current execution events, got {}",
        stats.history_event_count,
    );

    // KV: "iter" key from the final execution (kv_store is instance-scoped, persists across CAN)
    assert!(stats.kv_user_key_count >= 1, "should have at least 1 KV key");

    rt.shutdown(None).await;
}