cloacina 0.3.2

A Rust library for resilient task execution and orchestration.
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
/*
 *  Copyright 2025-2026 Colliery Software
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

use async_trait::async_trait;
use cloacina::executor::PipelineExecutor;
use cloacina::runner::{DefaultRunner, DefaultRunnerConfig};
use cloacina::*;
use serde_json::Value;
use std::sync::Arc;
use std::time::Duration;
use tokio::time;

use crate::fixtures::get_or_init_fixture;

// Simple task for workflow construction
#[derive(Debug)]
struct WorkflowTask {
    id: String,
    dependencies: Vec<TaskNamespace>,
}

impl WorkflowTask {
    fn new(id: &str, deps: Vec<&str>) -> Self {
        Self {
            id: id.to_string(),
            dependencies: deps
                .into_iter()
                .map(|s| TaskNamespace::from_string(s).unwrap())
                .collect(),
        }
    }
}

#[async_trait]
impl Task for WorkflowTask {
    async fn execute(
        &self,
        context: Context<serde_json::Value>,
    ) -> Result<Context<serde_json::Value>, TaskError> {
        Ok(context) // No-op for workflow building
    }

    fn id(&self) -> &str {
        &self.id
    }

    fn dependencies(&self) -> &[TaskNamespace] {
        &self.dependencies
    }
}

#[task(
    id = "test_task",
    dependencies = []
)]
async fn test_task(context: &mut Context<Value>) -> Result<(), TaskError> {
    // Add test output to the context
    context.insert("result", Value::String("success".to_string()))?;
    Ok(())
}

#[task(
    id = "producer_task",
    dependencies = []
)]
async fn producer_task(context: &mut Context<Value>) -> Result<(), TaskError> {
    // Add shared data to the context
    context.insert("shared_data", Value::String("important_value".to_string()))?;
    Ok(())
}

#[task(
    id = "consumer_task",
    dependencies = ["producer_task"]
)]
async fn consumer_task(context: &mut Context<Value>) -> Result<(), TaskError> {
    // With pre-inject pattern, dependency data is already in context
    if let Some(value) = context.get("shared_data") {
        // Add a derived value to show dependency was loaded
        context.insert(
            "derived_from_shared_data",
            Value::String(format!("Processed: {}", value)),
        )?;
    } else {
        return Err(TaskError::Unknown {
            task_id: "consumer_task".to_string(),
            message: "Dependency key 'shared_data' not found".to_string(),
        });
    }

    Ok(())
}

#[task(
    id = "timeout_task_test",
    dependencies = [],
    retry_attempts = 1
)]
async fn timeout_task_test(_context: &mut Context<Value>) -> Result<(), TaskError> {
    // Sleep longer than the timeout
    time::sleep(Duration::from_secs(10)).await;
    Ok(())
}

#[tokio::test]
async fn test_task_executor_basic_execution() {
    let fixture = get_or_init_fixture().await;
    let mut fixture = fixture.lock().unwrap_or_else(|e| e.into_inner());

    // Reset the database to ensure a clean state
    fixture.reset_database().await;
    fixture.initialize().await;

    let database_url = fixture.get_database_url();
    let database = fixture.get_database();

    // Create workflow using the #[task] function
    let workflow = Workflow::builder("test_pipeline_basic")
        .description("Test pipeline for executor")
        .add_task(Arc::new(WorkflowTask::new("test_task", vec![])))
        .unwrap()
        .build()
        .unwrap();

    // Register task with correct namespace in global registry
    let namespace = TaskNamespace::new(
        workflow.tenant(),
        workflow.package(),
        workflow.name(),
        "test_task",
    );
    register_task_constructor(namespace, || Arc::new(test_task_task()));

    // Register workflow in global registry for scheduler to find
    register_workflow_constructor("test_pipeline_basic".to_string(), {
        let workflow = workflow.clone();
        move || workflow.clone()
    });

    // Create runner with proper schema isolation
    let schema = fixture.get_schema();
    let runner = DefaultRunner::builder()
        .database_url(&database_url)
        .schema(&schema)
        .build()
        .await
        .unwrap();

    // Schedule workflow execution
    let mut input_context = Context::new();
    input_context
        .insert("test_data", Value::String("test_value".to_string()))
        .unwrap();
    let execution = runner
        .execute_async("test_pipeline_basic", input_context)
        .await
        .unwrap();
    let pipeline_id = execution.execution_id;

    // Give time for scheduler loop and dispatcher to process
    time::sleep(Duration::from_millis(500)).await;

    // Check that task was executed
    let dal = cloacina::dal::DAL::new(database.clone());
    let task_executions = dal
        .task_execution()
        .get_all_tasks_for_pipeline(UniversalUuid(pipeline_id))
        .await
        .unwrap();

    // Verify task execution
    assert_eq!(task_executions.len(), 1);
    let task = &task_executions[0];
    assert_eq!(task.status, "Completed");
    let expected_task_name = format!(
        "{}::{}::{}::test_task",
        workflow.tenant(),
        workflow.package(),
        workflow.name()
    );
    assert_eq!(task.task_name, expected_task_name);

    // Clean up
    runner.shutdown().await.unwrap();
}

#[tokio::test]
async fn test_task_executor_dependency_loading() {
    let fixture = get_or_init_fixture().await;
    let mut fixture = fixture.lock().unwrap_or_else(|e| e.into_inner());

    fixture.reset_database().await;
    fixture.initialize().await;

    let database_url = fixture.get_database_url();
    let database = fixture.get_database();

    // Create workflow with dependencies using the #[task] functions
    let workflow_name = format!(
        "dependency_pipeline_test_{}",
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    );

    // Create namespaces for dependencies
    let producer_ns = TaskNamespace::new("public", "embedded", &workflow_name, "producer_task");

    let workflow = Workflow::builder(&workflow_name)
        .description("Test pipeline with dependencies")
        .add_task(Arc::new(producer_task_task()))
        .unwrap()
        .add_task(Arc::new(
            consumer_task_task().with_dependencies(vec![producer_ns.clone()]),
        ))
        .unwrap()
        .build()
        .unwrap();

    // Register tasks with correct namespaces in global registry
    let namespace1 = TaskNamespace::new(
        workflow.tenant(),
        workflow.package(),
        workflow.name(),
        "producer_task",
    );
    register_task_constructor(namespace1, || Arc::new(producer_task_task()));

    let namespace2 = TaskNamespace::new(
        workflow.tenant(),
        workflow.package(),
        workflow.name(),
        "consumer_task",
    );
    let producer_ns_for_closure = producer_ns.clone();
    register_task_constructor(namespace2, move || {
        Arc::new(consumer_task_task().with_dependencies(vec![producer_ns_for_closure.clone()]))
    });

    // Register workflow in global registry for scheduler to find
    register_workflow_constructor(workflow.name().to_string(), {
        let workflow = workflow.clone();
        move || workflow.clone()
    });

    // Create runner with proper schema isolation
    let schema = fixture.get_schema();
    let runner = DefaultRunner::builder()
        .database_url(&database_url)
        .schema(&schema)
        .build()
        .await
        .unwrap();

    // Schedule workflow execution
    let mut input_context = Context::new();
    input_context
        .insert("initial_data", Value::String("test_value".to_string()))
        .unwrap();
    let execution = runner
        .execute_async(&workflow_name, input_context)
        .await
        .unwrap();
    let pipeline_id = execution.execution_id;

    // Give time for both tasks to execute
    time::sleep(Duration::from_secs(2)).await;

    // Check that consumer task successfully loaded dependency data
    let dal = cloacina::dal::DAL::new(database.clone());
    let consumer_namespace = cloacina::TaskNamespace::new(
        workflow.tenant(),
        workflow.package(),
        workflow.name(),
        "consumer_task",
    );
    let consumer_metadata = dal
        .task_execution_metadata()
        .get_by_pipeline_and_task(UniversalUuid(pipeline_id), &consumer_namespace)
        .await
        .unwrap();

    // Verify the consumer processed the dependency data
    let context_data: std::collections::HashMap<String, Value> =
        if let Some(context_id) = consumer_metadata.context_id {
            let context = dal
                .context()
                .read::<serde_json::Value>(context_id)
                .await
                .unwrap();
            context.data().clone()
        } else {
            std::collections::HashMap::new()
        };

    assert!(
        context_data.contains_key("derived_from_shared_data"),
        "Consumer task should have processed dependency data"
    );

    if let Some(derived_value) = context_data.get("derived_from_shared_data") {
        assert_eq!(
            derived_value,
            &Value::String("Processed: \"important_value\"".to_string()),
            "Derived value should contain processed dependency data"
        );
    }

    // Cleanup
    runner.shutdown().await.unwrap();
}

#[tokio::test]
async fn test_task_executor_timeout_handling() {
    let fixture = get_or_init_fixture().await;
    let mut fixture = fixture.lock().unwrap_or_else(|e| e.into_inner());

    fixture.reset_database().await;
    fixture.initialize().await;

    let database_url = fixture.get_database_url();
    let database = fixture.get_database();

    // Create workflow with timeout task
    let workflow_name = format!(
        "timeout_pipeline_test_{}",
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    );
    let workflow = Workflow::builder(&workflow_name)
        .description("Test pipeline with timeout")
        .add_task(Arc::new(WorkflowTask::new("timeout_task_test", vec![])))
        .unwrap()
        .build()
        .unwrap();

    // Register task with correct namespace in global registry
    let namespace = TaskNamespace::new(
        workflow.tenant(),
        workflow.package(),
        workflow.name(),
        "timeout_task_test",
    );
    register_task_constructor(namespace, || Arc::new(timeout_task_test_task()));

    // Register workflow in global registry for scheduler to find
    register_workflow_constructor(workflow.name().to_string(), {
        let workflow = workflow.clone();
        move || workflow.clone()
    });

    // Create runner with short timeout and proper schema isolation
    let config = DefaultRunnerConfig::builder()
        .task_timeout(Duration::from_millis(500))
        .build();
    let schema = fixture.get_schema();
    let runner = DefaultRunner::builder()
        .database_url(&database_url)
        .schema(&schema)
        .with_config(config)
        .build()
        .await
        .unwrap();

    // Schedule workflow execution
    let mut input_context = Context::new();
    input_context
        .insert("test_data", Value::String("timeout_test".to_string()))
        .unwrap();
    let execution = runner
        .execute_async(&workflow_name, input_context)
        .await
        .unwrap();
    let pipeline_id = execution.execution_id;

    // Give time for timeout to occur
    time::sleep(Duration::from_secs(2)).await;

    // Check that task failed due to timeout
    let dal = cloacina::dal::DAL::new(database.clone());
    let full_task_name = format!(
        "{}::{}::{}::timeout_task_test",
        workflow.tenant(),
        workflow.package(),
        workflow.name()
    );
    let task_status = dal
        .task_execution()
        .get_task_status(UniversalUuid(pipeline_id), &full_task_name)
        .await
        .unwrap();

    assert_eq!(
        task_status, "Failed",
        "Task should have failed due to timeout"
    );

    // Cleanup
    runner.shutdown().await.unwrap();
}

#[task(
    id = "unified_task_test",
    dependencies = []
)]
async fn unified_task_test(context: &mut Context<Value>) -> Result<(), TaskError> {
    // Add test output to the context
    context.insert("result", Value::String("unified_success".to_string()))?;
    Ok(())
}

#[tokio::test]
async fn test_default_runner_execution() {
    let fixture = get_or_init_fixture().await;
    let mut fixture = fixture.lock().unwrap_or_else(|e| e.into_inner());

    fixture.reset_database().await;
    fixture.initialize().await;

    let database_url = fixture.get_database_url();
    let database = fixture.get_database();

    // Create workflow using the #[task] function
    let workflow = Workflow::builder("unified_pipeline_test")
        .description("Test pipeline for unified mode")
        .add_task(Arc::new(WorkflowTask::new("unified_task_test", vec![])))
        .unwrap()
        .build()
        .unwrap();

    // Register task with correct namespace in global registry
    let namespace = TaskNamespace::new(
        workflow.tenant(),
        workflow.package(),
        workflow.name(),
        "unified_task_test",
    );
    register_task_constructor(namespace, || Arc::new(unified_task_test_task()));

    // Register workflow in global registry for scheduler to find
    register_workflow_constructor(workflow.name().to_string(), {
        let workflow = workflow.clone();
        move || workflow.clone()
    });

    // Create runner with proper schema isolation
    let schema = fixture.get_schema();
    let runner = DefaultRunner::builder()
        .database_url(&database_url)
        .schema(&schema)
        .build()
        .await
        .unwrap();

    // Schedule a workflow execution
    let mut input_context = Context::new();
    input_context
        .insert("engine_test", Value::String("unified_mode".to_string()))
        .unwrap();
    let execution = runner
        .execute_async("unified_pipeline_test", input_context)
        .await
        .unwrap();
    let pipeline_id = execution.execution_id;

    // Give time for execution
    time::sleep(Duration::from_secs(1)).await;

    // Check that task was processed
    let dal = cloacina::dal::DAL::new(database.clone());
    let task_namespace = cloacina::TaskNamespace::new(
        workflow.tenant(),
        workflow.package(),
        workflow.name(),
        "unified_task_test",
    );
    let task_metadata = dal
        .task_execution_metadata()
        .get_by_pipeline_and_task(UniversalUuid(pipeline_id), &task_namespace)
        .await;

    // If the task was executed, metadata should exist
    match task_metadata {
        Ok(metadata) => {
            if let Some(context_id) = metadata.context_id {
                let context = dal
                    .context()
                    .read::<serde_json::Value>(context_id)
                    .await
                    .unwrap();
                let context_data = context.data();
                assert!(
                    context_data.contains_key("result"),
                    "Task output should be present"
                );
            } else {
                // Task completed but produced no output
                println!("Task completed but produced no output context");
            }
        }
        Err(_) => {
            // Task might still be in progress or failed - check execution status
            let full_task_name = format!(
                "{}::{}::{}::unified_task_test",
                workflow.tenant(),
                workflow.package(),
                workflow.name()
            );
            let task_status = dal
                .task_execution()
                .get_task_status(UniversalUuid(pipeline_id), &full_task_name)
                .await
                .unwrap();
            assert_ne!(task_status, "Pending", "Task should have been processed");
        }
    }

    // Cleanup
    runner.shutdown().await.unwrap();
}

#[task(
    id = "initial_context_task_test",
    dependencies = []
)]
async fn initial_context_task_test(context: &mut Context<Value>) -> Result<(), TaskError> {
    // Verify we can access the initial context data
    let initial_value = context
        .get("initial_data")
        .ok_or_else(|| TaskError::ValidationFailed {
            message: "No initial_data found in context".to_string(),
        })?;

    // Add a processed value to show the task ran
    context.insert(
        "processed_initial",
        Value::String(format!("Processed: {}", initial_value)),
    )?;

    Ok(())
}

#[tokio::test]
async fn test_task_executor_context_loading_no_dependencies() {
    let fixture = get_or_init_fixture().await;
    let mut fixture = fixture.lock().unwrap_or_else(|e| e.into_inner());

    fixture.reset_database().await;
    fixture.initialize().await;

    let database_url = fixture.get_database_url();
    let database = fixture.get_database();

    // Create workflow using the #[task] function with unique name
    let workflow_name = format!(
        "initial_context_pipeline_test_{}",
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    );
    let workflow = Workflow::builder(&workflow_name)
        .description("Test pipeline for initial context loading")
        .add_task(Arc::new(WorkflowTask::new(
            "initial_context_task_test",
            vec![],
        )))
        .unwrap()
        .build()
        .unwrap();

    // Register task with correct namespace in global registry
    let namespace = TaskNamespace::new(
        workflow.tenant(),
        workflow.package(),
        workflow.name(),
        "initial_context_task_test",
    );
    register_task_constructor(namespace, || Arc::new(initial_context_task_test_task()));

    // Register workflow in global registry for scheduler to find
    register_workflow_constructor(workflow.name().to_string(), {
        let workflow = workflow.clone();
        move || workflow.clone()
    });

    // Create runner with proper schema isolation
    let schema = fixture.get_schema();
    let runner = DefaultRunner::builder()
        .database_url(&database_url)
        .schema(&schema)
        .build()
        .await
        .unwrap();

    // Schedule workflow execution with initial context
    let mut input_context = Context::new();
    input_context
        .insert("initial_data", Value::String("hello_world".to_string()))
        .unwrap();
    input_context
        .insert("config_value", Value::Number(serde_json::Number::from(42)))
        .unwrap();
    let execution = runner
        .execute_async(&workflow_name, input_context)
        .await
        .unwrap();
    let pipeline_id = execution.execution_id;

    // Give time for execution
    time::sleep(Duration::from_secs(1)).await;

    // Verify the task successfully processed the initial context
    let dal = cloacina::dal::DAL::new(database.clone());
    let full_task_name = format!(
        "{}::{}::{}::initial_context_task_test",
        workflow.tenant(),
        workflow.package(),
        workflow.name()
    );
    let task_status = dal
        .task_execution()
        .get_task_status(UniversalUuid(pipeline_id), &full_task_name)
        .await
        .unwrap();
    assert_eq!(
        task_status, "Completed",
        "Task should have completed successfully"
    );

    // Check the output context contains processed data
    let task_namespace = cloacina::TaskNamespace::new(
        workflow.tenant(),
        workflow.package(),
        workflow.name(),
        "initial_context_task_test",
    );
    let task_metadata = dal
        .task_execution_metadata()
        .get_by_pipeline_and_task(UniversalUuid(pipeline_id), &task_namespace)
        .await
        .unwrap();

    if let Some(context_id) = task_metadata.context_id {
        let context = dal
            .context()
            .read::<serde_json::Value>(context_id)
            .await
            .unwrap();
        let context_data = context.data();

        assert!(
            context_data.contains_key("processed_initial"),
            "Task should have processed initial context data"
        );
        assert!(
            context_data.contains_key("config_value"),
            "Initial context should be preserved"
        );

        if let Some(processed) = context_data.get("processed_initial") {
            assert_eq!(
                processed,
                &Value::String("Processed: \"hello_world\"".to_string())
            );
        }
    } else {
        panic!("Task should have produced output context");
    }

    // Cleanup
    runner.shutdown().await.unwrap();
}

#[task(
    id = "producer_context_task",
    dependencies = []
)]
async fn producer_context_task(context: &mut Context<Value>) -> Result<(), TaskError> {
    // Should have access to initial context
    let initial_value = context
        .get("seed_value")
        .ok_or_else(|| TaskError::ValidationFailed {
            message: "No seed_value found in context".to_string(),
        })?;

    // Produce some data
    context.insert(
        "produced_data",
        Value::String(format!("Produced from: {}", initial_value)),
    )?;

    Ok(())
}

#[task(
    id = "consumer_context_task",
    dependencies = ["producer_context_task"]
)]
async fn consumer_context_task(context: &mut Context<Value>) -> Result<(), TaskError> {
    // Should have access to dependency context data (not initial context directly)
    let produced_data =
        context
            .get("produced_data")
            .ok_or_else(|| TaskError::ValidationFailed {
                message: "No produced_data found in context from dependency".to_string(),
            })?;

    // Should also have initial context merged in
    let seed_value = context
        .get("seed_value")
        .ok_or_else(|| TaskError::ValidationFailed {
            message: "No seed_value found in context".to_string(),
        })?;

    // Process the data
    context.insert(
        "final_result",
        Value::String(format!("Final: {} + {}", produced_data, seed_value)),
    )?;

    Ok(())
}

#[tokio::test]
async fn test_task_executor_context_loading_with_dependencies() {
    let fixture = get_or_init_fixture().await;
    let mut fixture = fixture.lock().unwrap_or_else(|e| e.into_inner());

    fixture.reset_database().await;
    fixture.initialize().await;

    let database_url = fixture.get_database_url();
    let database = fixture.get_database();

    // Create workflow with dependency chain using the #[task] functions
    let workflow_name = format!(
        "dependency_context_pipeline_test_{}",
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    );

    // Create namespaces for dependencies
    let producer_ns = TaskNamespace::new(
        "public",
        "embedded",
        &workflow_name,
        "producer_context_task",
    );

    let workflow = Workflow::builder(&workflow_name)
        .description("Test pipeline for dependency context loading")
        .add_task(Arc::new(producer_context_task_task()))
        .unwrap()
        .add_task(Arc::new(
            consumer_context_task_task().with_dependencies(vec![producer_ns.clone()]),
        ))
        .unwrap()
        .build()
        .unwrap();

    // Register tasks with correct namespaces and dependencies in global registry
    let namespace1 = TaskNamespace::new(
        workflow.tenant(),
        workflow.package(),
        workflow.name(),
        "producer_context_task",
    );
    register_task_constructor(namespace1, || Arc::new(producer_context_task_task()));

    let namespace2 = TaskNamespace::new(
        workflow.tenant(),
        workflow.package(),
        workflow.name(),
        "consumer_context_task",
    );
    let producer_ns_for_closure = producer_ns.clone();
    register_task_constructor(namespace2, move || {
        Arc::new(
            consumer_context_task_task().with_dependencies(vec![producer_ns_for_closure.clone()]),
        )
    });

    // Register workflow in global registry for scheduler to find
    register_workflow_constructor(workflow.name().to_string(), {
        let workflow = workflow.clone();
        move || workflow.clone()
    });

    // Create runner with proper schema isolation
    let schema = fixture.get_schema();
    let runner = DefaultRunner::builder()
        .database_url(&database_url)
        .schema(&schema)
        .build()
        .await
        .unwrap();

    // Schedule workflow execution with initial context
    let mut input_context = Context::new();
    input_context
        .insert("seed_value", Value::String("initial_seed".to_string()))
        .unwrap();
    let execution = runner
        .execute_async(&workflow_name, input_context)
        .await
        .unwrap();
    let pipeline_id = execution.execution_id;

    // Give time for both tasks to execute
    time::sleep(Duration::from_secs(2)).await;

    // Verify both tasks completed
    let dal = cloacina::dal::DAL::new(database.clone());
    let producer_full_name = format!(
        "{}::{}::{}::producer_context_task",
        workflow.tenant(),
        workflow.package(),
        workflow.name()
    );
    let consumer_full_name = format!(
        "{}::{}::{}::consumer_context_task",
        workflow.tenant(),
        workflow.package(),
        workflow.name()
    );
    let producer_status = dal
        .task_execution()
        .get_task_status(UniversalUuid(pipeline_id), &producer_full_name)
        .await
        .unwrap();
    let consumer_status = dal
        .task_execution()
        .get_task_status(UniversalUuid(pipeline_id), &consumer_full_name)
        .await
        .unwrap();

    assert_eq!(
        producer_status, "Completed",
        "Producer task should have completed"
    );
    assert_eq!(
        consumer_status, "Completed",
        "Consumer task should have completed"
    );

    // Check the consumer's output context
    let consumer_namespace = cloacina::TaskNamespace::new(
        workflow.tenant(),
        workflow.package(),
        workflow.name(),
        "consumer_context_task",
    );
    let consumer_metadata = dal
        .task_execution_metadata()
        .get_by_pipeline_and_task(UniversalUuid(pipeline_id), &consumer_namespace)
        .await
        .unwrap();

    if let Some(context_id) = consumer_metadata.context_id {
        let context = dal
            .context()
            .read::<serde_json::Value>(context_id)
            .await
            .unwrap();
        let context_data = context.data();

        assert!(
            context_data.contains_key("final_result"),
            "Consumer should have produced final result"
        );
        assert!(
            context_data.contains_key("produced_data"),
            "Consumer should have access to producer data"
        );
        assert!(
            context_data.contains_key("seed_value"),
            "Consumer should have access to initial context"
        );

        if let Some(final_result) = context_data.get("final_result") {
            assert_eq!(
                final_result,
                &Value::String(
                    "Final: \"Produced from: \\\"initial_seed\\\"\" + \"initial_seed\"".to_string()
                )
            );
        }
    } else {
        panic!("Consumer task should have produced output context");
    }

    // Cleanup
    runner.shutdown().await.unwrap();
}