cortex-ai 0.1.9

An asynchronous flow-based processing framework for building flexible data pipelines with conditional branching and error handling
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
use crate::helpers::{
    init_tracing, EmptySource, ErrorProcessor, ErrorSource, PassthroughProcessor, SkipProcessor,
    SkipSource, StreamErrorSource, TestSource,
};
use cortex_ai::Flow;
use flume::bounded;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tracing::info;

#[cfg(test)]
mod flow_tests {
    use cortex_ai::{flow::types::SourceOutput, FlowComponent, FlowError, FlowFuture, Source};
    use flume::Receiver;

    use super::*;
    use crate::helpers::{run_flow_with_timeout, TestCondition};

    // Move struct definitions to the top
    struct MultiSource {
        rx: Receiver<Result<String, FlowError>>,
        feedback: flume::Sender<Result<String, FlowError>>,
    }

    impl FlowComponent for MultiSource {
        type Input = ();
        type Output = String;
        type Error = FlowError;
    }

    impl Source for MultiSource {
        fn stream(&self) -> FlowFuture<'_, SourceOutput<Self::Output, Self::Error>, Self::Error> {
            let rx = self.rx.clone();
            let feedback = self.feedback.clone();
            Box::pin(async move {
                Ok(SourceOutput {
                    receiver: rx,
                    feedback,
                })
            })
        }
    }

    #[tokio::test]
    async fn it_should_error_when_source_not_set() {
        init_tracing();
        info!("Starting source not set test");
        // Given
        let flow = Flow::<String, FlowError, String>::new();
        let (_, shutdown_rx) = tokio::sync::broadcast::channel(1);

        // When
        let result = flow.run_stream(shutdown_rx).await;

        // Then
        assert!(result.is_err());
        assert_eq!(
            result.unwrap_err().to_string(),
            "Flow error: No source configured"
        );
    }

    #[tokio::test]
    async fn it_should_handle_source_stream_error() {
        init_tracing();
        info!("Starting source stream error test");
        // Given
        let flow = Flow::<String, FlowError, String>::new().source(StreamErrorSource);
        let (_, shutdown_rx) = tokio::sync::broadcast::channel(1);

        // When
        let result = flow.run_stream(shutdown_rx).await;

        // Then
        assert!(result.is_err());
        assert_eq!(
            result.unwrap_err().to_string(),
            "Source error: Stream initialization error"
        );
    }

    #[tokio::test]
    async fn it_should_handle_processor_error() {
        init_tracing();
        info!("Starting processor error test");
        // Given
        let (feedback_tx, _) = bounded::<Result<String, FlowError>>(1);
        let flow = Flow::<String, FlowError, String>::new()
            .source(TestSource {
                data: "test_input".to_string(),
                feedback: feedback_tx,
            })
            .process(ErrorProcessor);

        // When
        let result = run_flow_with_timeout(flow, Duration::from_millis(100)).await;

        // Then
        assert!(result.is_err());
        assert_eq!(
            result.unwrap_err().to_string(),
            "Process error: Processing failed"
        );
    }

    #[tokio::test]
    async fn it_should_handle_empty_source() {
        init_tracing();
        info!("Starting empty source test");
        // Given
        let flow = Flow::<String, FlowError, String>::new().source(EmptySource);
        let (_, shutdown_rx) = tokio::sync::broadcast::channel(1);

        // When
        let result = flow.run_stream(shutdown_rx).await;

        // Then
        assert!(result.is_ok());
        assert_eq!(result.unwrap().len(), 0);
    }

    #[tokio::test]
    async fn it_should_create_flow_using_default() {
        init_tracing();
        info!("Starting flow using default test");
        // Given
        let flow = Flow::<String, FlowError, String>::default();

        // When
        let (_, shutdown_rx) = tokio::sync::broadcast::channel(1);
        let result = flow.run_stream(shutdown_rx).await;

        // Then
        assert!(result.is_err());
        assert_eq!(
            result.unwrap_err().to_string(),
            "Flow error: No source configured"
        );
    }

    #[tokio::test]
    async fn it_should_send_error_feedback_for_source_errors() {
        init_tracing();
        info!("Starting send error feedback for source errors test");
        // Given
        let (feedback_tx, feedback_rx) = bounded::<Result<String, FlowError>>(1);
        let feedback_results = Arc::new(Mutex::new(Vec::<Result<String, FlowError>>::new()));
        let feedback_results_clone = feedback_results.clone();

        // Spawn a task to collect feedback
        tokio::spawn(async move {
            while let Ok(result) = feedback_rx.recv_async().await {
                let mut results = feedback_results_clone.lock().unwrap();
                results.push(result);
            }
        });

        let flow: Flow<String, FlowError, String> = Flow::new()
            .source(ErrorSource {
                feedback: feedback_tx,
            })
            .process(PassthroughProcessor);

        // When
        let result = run_flow_with_timeout(flow, Duration::from_millis(100)).await;

        // Then
        assert!(result.is_err());
        assert_eq!(
            result.unwrap_err().to_string(),
            "Source error: Source error"
        );

        // Wait a bit for feedback processing
        tokio::time::sleep(Duration::from_millis(50)).await;

        let feedback_results = feedback_results.lock().unwrap();
        assert_eq!(feedback_results.len(), 1);
        assert!(matches!(
            &feedback_results[0],
            Err(e) if e.to_string() == "Source error: Source error"
        ));
        drop(feedback_results);
    }

    #[tokio::test]
    async fn it_should_handle_skipped_items() {
        init_tracing();
        info!("Starting handle skipped items test");
        // Given
        let (feedback_tx, feedback_rx) = bounded::<Result<String, FlowError>>(1);
        let feedback_results = Arc::new(Mutex::new(Vec::<Result<String, FlowError>>::new()));
        let feedback_results_clone = feedback_results.clone();

        // Spawn a task to collect feedback
        tokio::spawn(async move {
            while let Ok(result) = feedback_rx.recv_async().await {
                let mut results = feedback_results_clone.lock().unwrap();
                results.push(result);
            }
        });

        let flow: Flow<String, FlowError, String> = Flow::new()
            .source(SkipSource {
                feedback: feedback_tx,
            })
            .process(SkipProcessor);

        // When
        let result = run_flow_with_timeout(flow, Duration::from_millis(100)).await;

        // Then
        assert!(result.is_ok());
        let results = result.unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0], "skipped");

        // Wait a bit for feedback processing
        tokio::time::sleep(Duration::from_millis(50)).await;

        let feedback_results = feedback_results.lock().unwrap();
        assert_eq!(feedback_results.len(), 1);
        assert!(matches!(
            &feedback_results[0],
            Ok(msg) if msg == "skipped"
        ));
        drop(feedback_results);
    }

    #[tokio::test]
    async fn it_should_set_source() {
        init_tracing();
        info!("Starting set source test");
        // Given
        let (feedback_tx, _) = bounded::<Result<String, FlowError>>(1);
        let flow = Flow::<String, FlowError, String>::new();

        // When
        let flow = flow.source(TestSource {
            data: "test".to_string(),
            feedback: feedback_tx,
        });

        // Then
        let (_, shutdown_rx) = tokio::sync::broadcast::channel(1);
        let result = flow.run_stream(shutdown_rx).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn it_should_handle_source_item_error() {
        init_tracing();
        info!("Starting handle source item error test");
        // Given
        let (feedback_tx, feedback_rx) = bounded::<Result<String, FlowError>>(1);
        let feedback_results = Arc::new(Mutex::new(Vec::<Result<String, FlowError>>::new()));
        let feedback_results_clone = feedback_results.clone();

        tokio::spawn(async move {
            while let Ok(result) = feedback_rx.recv_async().await {
                let mut results = feedback_results_clone.lock().unwrap();
                results.push(result);
            }
        });

        let flow: Flow<String, FlowError, String> = Flow::new()
            .source(ErrorSource {
                feedback: feedback_tx,
            })
            .process(PassthroughProcessor);

        // When
        let result = run_flow_with_timeout(flow, Duration::from_millis(100)).await;

        // Then
        assert!(result.is_err());
        let feedback_results = feedback_results.lock().unwrap();
        assert_eq!(feedback_results.len(), 1);
        assert!(matches!(
            &feedback_results[0],
            Err(e) if e.to_string() == "Source error: Source error"
        ));
        drop(feedback_results);
    }

    #[tokio::test]
    async fn it_should_return_empty_vec_when_no_items_processed() {
        init_tracing();
        info!("Starting return empty vec when no items processed test");
        // Given
        let flow: Flow<String, FlowError, String> = Flow::new().source(EmptySource);

        // When
        let result = run_flow_with_timeout(flow, Duration::from_millis(100)).await;

        // Then
        assert!(result.is_ok());
        assert!(result.unwrap().is_empty());
    }

    #[tokio::test]
    async fn it_should_add_processor_to_stages() {
        init_tracing();
        info!("Starting add processor to stages test");
        // Given
        let (feedback_tx, _) = bounded::<Result<String, FlowError>>(1);
        let flow = Flow::<String, FlowError, String>::new()
            .source(TestSource {
                data: "test".to_string(),
                feedback: feedback_tx,
            })
            .process(PassthroughProcessor);

        // When
        let result = run_flow_with_timeout(flow, Duration::from_millis(100)).await;

        // Then
        assert!(result.is_ok());
        let results = result.unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0], "test"); // PassthroughProcessor doesn't modify the input
    }

    #[tokio::test]
    async fn it_should_preserve_source_after_setting() {
        init_tracing();
        info!("Starting preserve source after setting test");
        // Given
        let (feedback_tx, _) = bounded::<Result<String, FlowError>>(1);
        let source_data = "test".to_string();
        let flow = Flow::<String, FlowError, String>::new().source(TestSource {
            data: source_data.clone(),
            feedback: feedback_tx,
        });

        // When
        let result = run_flow_with_timeout(flow, Duration::from_millis(100)).await;

        // Then
        assert!(result.is_ok());
        let results = result.unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0], source_data); // Verify source data is preserved
    }

    #[tokio::test]
    async fn it_should_handle_source_item_with_feedback() {
        init_tracing();
        info!("Starting handle source item with feedback test");
        // Given
        let (feedback_tx, feedback_rx) = bounded::<Result<String, FlowError>>(1);
        let feedback_results = Arc::new(Mutex::new(Vec::<Result<String, FlowError>>::new()));
        let feedback_results_clone = feedback_results.clone();

        tokio::spawn(async move {
            while let Ok(result) = feedback_rx.recv_async().await {
                let mut results = feedback_results_clone.lock().unwrap();
                results.push(result);
            }
        });

        let test_data = "test_data".to_string();
        let flow: Flow<String, FlowError, String> = Flow::new()
            .source(TestSource {
                data: test_data.clone(),
                feedback: feedback_tx, // Pass feedback channel to TestSource
            })
            .process(PassthroughProcessor);

        // When
        let result = run_flow_with_timeout(flow, Duration::from_millis(100)).await;

        // Then
        assert!(result.is_ok());
        let results = result.unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0], test_data); // Verify data is processed and not skipped

        // Wait a bit for feedback processing
        tokio::time::sleep(Duration::from_millis(50)).await;

        let feedback_results = feedback_results.lock().unwrap();
        assert_eq!(feedback_results.len(), 1);
        assert!(matches!(
            &feedback_results[0],
            Ok(data) if data == &test_data
        ));
        drop(feedback_results);
    }

    #[tokio::test]
    async fn it_should_process_multiple_items() {
        init_tracing();
        info!("Starting process multiple items test");
        // Given
        let (tx, rx) = bounded(2);
        let (feedback_tx, _) = bounded(2);

        tx.send(Ok("item1".to_string())).unwrap();
        tx.send(Ok("item2".to_string())).unwrap();
        drop(tx);

        let flow: Flow<String, FlowError, String> = Flow::new()
            .source(MultiSource {
                rx,
                feedback: feedback_tx,
            })
            .process(PassthroughProcessor);

        // When
        let result = run_flow_with_timeout(flow, Duration::from_millis(100)).await;

        // Then
        assert!(result.is_ok());
        let results = result.unwrap();
        assert_eq!(results.len(), 2); // Verify multiple items are processed
        assert_eq!(results, vec!["item1".to_string(), "item2".to_string()]);
    }

    #[tokio::test]
    async fn it_should_show_tracing_metrics() {
        // Set up tracing with a more detailed configuration
        let subscriber = tracing_subscriber::fmt()
            .with_env_filter("cortex_ai=info,test=info")
            .with_thread_ids(true)
            .with_thread_names(true)
            .with_file(true)
            .with_line_number(true)
            .with_target(true)
            .with_span_events(tracing_subscriber::fmt::format::FmtSpan::FULL) // Show enter/exit of spans
            .try_init();

        if subscriber.is_err() {
            println!("Warning: tracing already initialized");
        }

        // Run a flow with all components to generate tracing data
        let (feedback_tx, _) = bounded::<Result<String, FlowError>>(1);
        let test_condition = TestCondition; // Create instance first
        let flow = Flow::new()
            .source(TestSource {
                data: "test_data".to_string(),
                feedback: feedback_tx,
            })
            .process(PassthroughProcessor)
            .when(test_condition) // Use the instance
            .process(PassthroughProcessor)
            .otherwise()
            .process(PassthroughProcessor)
            .end();

        let result = run_flow_with_timeout(flow, Duration::from_millis(100)).await;
        assert!(result.is_ok());
    }
}