prodigy 0.4.4

Turn ad-hoc Claude sessions into reproducible development pipelines with parallel AI agents
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
//! Event writer implementations for different output targets

use super::EventRecord;
use anyhow::{Context, Result};
use async_trait::async_trait;
use serde_json;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use tokio::fs::{self, File, OpenOptions};
use tokio::io::{AsyncWriteExt, BufWriter};
use tokio::sync::Mutex;
use tracing::{debug, info};

/// Trait for writing events to various destinations
#[async_trait]
pub trait EventWriter: Send + Sync {
    /// Write a batch of events
    async fn write(&self, events: &[EventRecord]) -> Result<()>;

    /// Flush any buffered data
    async fn flush(&self) -> Result<()>;

    /// Clone the writer
    fn clone(&self) -> Box<dyn EventWriter>;
}

/// File-based event writer in JSONL format
pub struct JsonlEventWriter {
    file_path: PathBuf,
    writer: Arc<Mutex<Option<BufWriter<File>>>>,
    rotation_size: u64,
    current_size: Arc<Mutex<u64>>,
}

impl JsonlEventWriter {
    /// Create a new JSONL event writer
    pub async fn new(file_path: PathBuf) -> Result<Self> {
        // Create parent directory if it doesn't exist
        if let Some(parent) = file_path.parent() {
            fs::create_dir_all(parent)
                .await
                .context("Failed to create event directory")?;
        }

        // Open file for appending
        let file = OpenOptions::new()
            .create(true)
            .append(true)
            .open(&file_path)
            .await
            .context("Failed to open event file")?;

        let metadata = file.metadata().await?;
        let current_size = metadata.len();

        let writer = BufWriter::new(file);

        Ok(Self {
            file_path,
            writer: Arc::new(Mutex::new(Some(writer))),
            rotation_size: 100 * 1024 * 1024, // 100MB
            current_size: Arc::new(Mutex::new(current_size)),
        })
    }

    /// Create a writer with custom rotation size
    pub async fn with_rotation(file_path: PathBuf, rotation_size: u64) -> Result<Self> {
        let mut writer = Self::new(file_path).await?;
        writer.rotation_size = rotation_size;
        Ok(writer)
    }

    /// Rotate the log file if needed
    async fn rotate_if_needed(&self) -> Result<()> {
        let current_size = *self.current_size.lock().await;

        if current_size >= self.rotation_size {
            let mut writer_guard = self.writer.lock().await;

            // Close current file
            if let Some(mut writer) = writer_guard.take() {
                writer.flush().await?;
            }

            // Create rotation filename
            let timestamp = chrono::Utc::now().format("%Y%m%d_%H%M%S");
            let rotation_path = self
                .file_path
                .with_extension(format!("{}.jsonl.gz", timestamp));

            // Compress and move old file
            self.compress_and_move(&rotation_path).await?;

            // Open new file
            let file = OpenOptions::new()
                .create(true)
                .truncate(true)
                .write(true)
                .open(&self.file_path)
                .await?;

            *writer_guard = Some(BufWriter::new(file));

            // Reset size counter
            let mut size_guard = self.current_size.lock().await;
            *size_guard = 0;

            info!("Rotated event log to {:?}", rotation_path);
        }

        Ok(())
    }

    /// Compress and move file for rotation
    async fn compress_and_move(&self, target: &Path) -> Result<()> {
        // For now, just rename the file
        // In production, we'd use flate2 or similar for actual compression
        let backup_path = self.file_path.with_extension("jsonl.bak");
        fs::rename(&self.file_path, &backup_path)
            .await
            .context("Failed to rotate event file")?;

        // TODO: Implement actual compression
        fs::rename(&backup_path, target)
            .await
            .context("Failed to move rotated file")?;

        Ok(())
    }
}

/// Serialize events to JSONL format
///
/// Pure function that converts events to (line_string, byte_count) tuples.
/// Returns error if serialization fails.
fn serialize_events_to_jsonl(events: &[EventRecord]) -> Result<Vec<(String, usize)>> {
    events
        .iter()
        .map(|event| {
            let json = serde_json::to_string(event)?;
            let line = format!("{}\n", json);
            let byte_count = line.len();
            Ok((line, byte_count))
        })
        .collect()
}

/// Update size counter with additional bytes
///
/// Async function that updates the size counter in a thread-safe manner.
async fn update_size_counter(current: &Mutex<u64>, additional: u64) {
    let mut size_guard = current.lock().await;
    *size_guard += additional;
}

/// Write serialized events to a buffered writer
///
/// Returns total bytes written or error if write fails.
async fn write_serialized_events(
    writer: &mut BufWriter<File>,
    serialized: &[(String, usize)],
) -> Result<u64> {
    let mut total_bytes = 0u64;

    for (line, byte_count) in serialized {
        let bytes = line.as_bytes();
        writer
            .write_all(bytes)
            .await
            .context("Failed to write event to file")?;
        total_bytes += *byte_count as u64;
    }

    Ok(total_bytes)
}

#[async_trait]
impl EventWriter for JsonlEventWriter {
    async fn write(&self, events: &[EventRecord]) -> Result<()> {
        self.rotate_if_needed().await?;

        // Serialize events to JSONL format
        let serialized = serialize_events_to_jsonl(events)?;

        let mut writer_guard = self.writer.lock().await;
        if let Some(writer) = writer_guard.as_mut() {
            // Write serialized events and get total bytes written
            let total_bytes = write_serialized_events(writer, &serialized).await?;

            // Update size counter
            update_size_counter(&self.current_size, total_bytes).await;

            debug!("Wrote {} events ({} bytes)", events.len(), total_bytes);
        }

        Ok(())
    }

    async fn flush(&self) -> Result<()> {
        let mut writer_guard = self.writer.lock().await;
        if let Some(writer) = writer_guard.as_mut() {
            writer.flush().await?;
        }
        Ok(())
    }

    fn clone(&self) -> Box<dyn EventWriter> {
        Box::new(Self {
            file_path: self.file_path.clone(),
            writer: Arc::clone(&self.writer),
            rotation_size: self.rotation_size,
            current_size: Arc::clone(&self.current_size),
        })
    }
}

/// Generic file event writer that delegates to specific format writers
pub struct FileEventWriter {
    base_path: PathBuf,
    job_id: String,
    writer: Box<dyn EventWriter>,
}

impl FileEventWriter {
    /// Create a new file event writer for a specific job
    pub async fn new(base_path: PathBuf, job_id: String) -> Result<Self> {
        let event_dir = base_path.join("events").join(&job_id);
        fs::create_dir_all(&event_dir)
            .await
            .context("Failed to create job event directory")?;

        let timestamp = chrono::Utc::now().format("%Y%m%d_%H%M%S");
        let file_path = event_dir.join(format!("events-{}.jsonl", timestamp));

        let writer = Box::new(JsonlEventWriter::new(file_path).await?);

        Ok(Self {
            base_path,
            job_id,
            writer,
        })
    }

    /// Create an index file for quick event lookup
    pub async fn create_index(&self) -> Result<()> {
        let _index_path = self
            .base_path
            .join("events")
            .join(&self.job_id)
            .join("index.json");

        // TODO: Implement index creation
        debug!("Index creation not yet implemented");

        Ok(())
    }
}

#[async_trait]
impl EventWriter for FileEventWriter {
    async fn write(&self, events: &[EventRecord]) -> Result<()> {
        self.writer.write(events).await
    }

    async fn flush(&self) -> Result<()> {
        self.writer.flush().await
    }

    fn clone(&self) -> Box<dyn EventWriter> {
        Box::new(Self {
            base_path: self.base_path.clone(),
            job_id: self.job_id.clone(),
            writer: self.writer.clone(),
        })
    }
}

/// Stdout event writer for debugging
#[allow(dead_code)]
pub struct StdoutEventWriter;

#[async_trait]
impl EventWriter for StdoutEventWriter {
    async fn write(&self, events: &[EventRecord]) -> Result<()> {
        for event in events {
            let json = serde_json::to_string_pretty(event)?;
            println!("{}", json);
        }
        Ok(())
    }

    async fn flush(&self) -> Result<()> {
        // Stdout is auto-flushed
        Ok(())
    }

    fn clone(&self) -> Box<dyn EventWriter> {
        Box::new(StdoutEventWriter)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cook::execution::events::MapReduceEvent;
    use crate::cook::execution::mapreduce::MapReduceConfig;

    use tempfile::TempDir;
    use uuid::Uuid;

    #[tokio::test]
    async fn test_jsonl_writer() {
        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("events.jsonl");

        let writer = JsonlEventWriter::new(file_path.clone()).await.unwrap();

        let event = EventRecord {
            id: Uuid::new_v4(),
            timestamp: chrono::Utc::now(),
            correlation_id: "test-correlation".to_string(),
            event: MapReduceEvent::JobStarted {
                job_id: "test-job".to_string(),
                config: MapReduceConfig {
                    agent_timeout_secs: None,
                    continue_on_failure: false,
                    batch_size: None,
                    enable_checkpoints: true,
                    input: "test.json".to_string(),
                    json_path: "$.items".to_string(),
                    max_parallel: 5,
                    max_items: None,
                    offset: None,
                },
                total_items: 10,
                timestamp: chrono::Utc::now(),
            },
            metadata: Default::default(),
        };

        writer.write(&[event]).await.unwrap();
        writer.flush().await.unwrap();

        // Verify file was written
        assert!(file_path.exists());
        let content = tokio::fs::read_to_string(&file_path).await.unwrap();
        assert!(content.contains("test-job"));
    }

    #[tokio::test]
    async fn test_write_empty_events() {
        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("events.jsonl");

        let writer = JsonlEventWriter::new(file_path.clone()).await.unwrap();

        // Writing empty events should succeed without error
        writer.write(&[]).await.unwrap();
        writer.flush().await.unwrap();

        // File should exist but be empty (or only have initial content)
        assert!(file_path.exists());
    }

    #[tokio::test]
    async fn test_write_multiple_events() {
        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("events.jsonl");

        let writer = JsonlEventWriter::new(file_path.clone()).await.unwrap();

        let events: Vec<EventRecord> = (0..3)
            .map(|i| EventRecord {
                id: Uuid::new_v4(),
                timestamp: chrono::Utc::now(),
                correlation_id: format!("test-correlation-{}", i),
                event: MapReduceEvent::JobStarted {
                    job_id: format!("test-job-{}", i),
                    config: MapReduceConfig {
                        agent_timeout_secs: None,
                        continue_on_failure: false,
                        batch_size: None,
                        enable_checkpoints: true,
                        input: "test.json".to_string(),
                        json_path: "$.items".to_string(),
                        max_parallel: 5,
                        max_items: None,
                        offset: None,
                    },
                    total_items: 10,
                    timestamp: chrono::Utc::now(),
                },
                metadata: Default::default(),
            })
            .collect();

        writer.write(&events).await.unwrap();
        writer.flush().await.unwrap();

        // Verify all events were written
        let content = tokio::fs::read_to_string(&file_path).await.unwrap();
        let lines: Vec<&str> = content.lines().collect();
        assert_eq!(lines.len(), 3);
        assert!(content.contains("test-job-0"));
        assert!(content.contains("test-job-1"));
        assert!(content.contains("test-job-2"));
    }

    #[tokio::test]
    async fn test_size_tracking_across_writes() {
        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("events.jsonl");

        let writer = JsonlEventWriter::new(file_path.clone()).await.unwrap();

        let event = EventRecord {
            id: Uuid::new_v4(),
            timestamp: chrono::Utc::now(),
            correlation_id: "test-correlation".to_string(),
            event: MapReduceEvent::JobStarted {
                job_id: "test-job".to_string(),
                config: MapReduceConfig {
                    agent_timeout_secs: None,
                    continue_on_failure: false,
                    batch_size: None,
                    enable_checkpoints: true,
                    input: "test.json".to_string(),
                    json_path: "$.items".to_string(),
                    max_parallel: 5,
                    max_items: None,
                    offset: None,
                },
                total_items: 10,
                timestamp: chrono::Utc::now(),
            },
            metadata: Default::default(),
        };

        // Write same event multiple times
        writer.write(std::slice::from_ref(&event)).await.unwrap();
        writer.write(std::slice::from_ref(&event)).await.unwrap();
        writer.flush().await.unwrap();

        // Verify size tracking - should accumulate across writes
        let size = *writer.current_size.lock().await;
        assert!(size > 0, "Size should be tracked across writes");

        // Verify file content
        let content = tokio::fs::read_to_string(&file_path).await.unwrap();
        let lines: Vec<&str> = content.lines().collect();
        assert_eq!(lines.len(), 2);
    }

    #[test]
    fn test_serialize_single_event() {
        let event = EventRecord {
            id: Uuid::new_v4(),
            timestamp: chrono::Utc::now(),
            correlation_id: "test-correlation".to_string(),
            event: MapReduceEvent::JobStarted {
                job_id: "test-job".to_string(),
                config: MapReduceConfig {
                    agent_timeout_secs: None,
                    continue_on_failure: false,
                    batch_size: None,
                    enable_checkpoints: true,
                    input: "test.json".to_string(),
                    json_path: "$.items".to_string(),
                    max_parallel: 5,
                    max_items: None,
                    offset: None,
                },
                total_items: 10,
                timestamp: chrono::Utc::now(),
            },
            metadata: Default::default(),
        };

        let result = serialize_events_to_jsonl(&[event]).unwrap();
        assert_eq!(result.len(), 1);

        let (line, byte_count) = &result[0];
        assert!(line.contains("test-job"));
        assert!(line.ends_with('\n'));
        assert_eq!(*byte_count, line.len());
    }

    #[test]
    fn test_serialize_multiple_events() {
        let events: Vec<EventRecord> = (0..3)
            .map(|i| EventRecord {
                id: Uuid::new_v4(),
                timestamp: chrono::Utc::now(),
                correlation_id: format!("test-correlation-{}", i),
                event: MapReduceEvent::JobStarted {
                    job_id: format!("test-job-{}", i),
                    config: MapReduceConfig {
                        agent_timeout_secs: None,
                        continue_on_failure: false,
                        batch_size: None,
                        enable_checkpoints: true,
                        input: "test.json".to_string(),
                        json_path: "$.items".to_string(),
                        max_parallel: 5,
                        max_items: None,
                        offset: None,
                    },
                    total_items: 10,
                    timestamp: chrono::Utc::now(),
                },
                metadata: Default::default(),
            })
            .collect();

        let result = serialize_events_to_jsonl(&events).unwrap();
        assert_eq!(result.len(), 3);

        for (i, (line, byte_count)) in result.iter().enumerate() {
            assert!(line.contains(&format!("test-job-{}", i)));
            assert!(line.ends_with('\n'));
            assert_eq!(*byte_count, line.len());
        }
    }

    #[test]
    fn test_serialize_empty_events() {
        let result = serialize_events_to_jsonl(&[]).unwrap();
        assert_eq!(result.len(), 0);
    }

    #[test]
    fn test_serialize_event_with_special_characters() {
        let event = EventRecord {
            id: Uuid::new_v4(),
            timestamp: chrono::Utc::now(),
            correlation_id: "test-with-\"quotes\"-and-\\backslash".to_string(),
            event: MapReduceEvent::JobStarted {
                job_id: "test-job".to_string(),
                config: MapReduceConfig {
                    agent_timeout_secs: None,
                    continue_on_failure: false,
                    batch_size: None,
                    enable_checkpoints: true,
                    input: "test.json".to_string(),
                    json_path: "$.items".to_string(),
                    max_parallel: 5,
                    max_items: None,
                    offset: None,
                },
                total_items: 10,
                timestamp: chrono::Utc::now(),
            },
            metadata: Default::default(),
        };

        let result = serialize_events_to_jsonl(&[event]).unwrap();
        assert_eq!(result.len(), 1);

        let (line, byte_count) = &result[0];
        // JSON should escape special characters
        assert!(line.contains(r#"\"quotes\""#));
        assert!(line.contains(r"\\backslash"));
        assert_eq!(*byte_count, line.len());
    }

    #[tokio::test]
    async fn test_update_size_counter_initial() {
        let counter = Mutex::new(0u64);
        update_size_counter(&counter, 100).await;

        let value = *counter.lock().await;
        assert_eq!(value, 100);
    }

    #[tokio::test]
    async fn test_update_size_counter_multiple() {
        let counter = Mutex::new(50u64);
        update_size_counter(&counter, 100).await;
        update_size_counter(&counter, 200).await;

        let value = *counter.lock().await;
        assert_eq!(value, 350);
    }

    #[tokio::test]
    async fn test_write_serialized_events_to_file() {
        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("test-write.jsonl");

        let file = OpenOptions::new()
            .create(true)
            .write(true)
            .truncate(true)
            .open(&file_path)
            .await
            .unwrap();
        let mut writer = BufWriter::new(file);

        let serialized = vec![
            ("first line\n".to_string(), 11),
            ("second line\n".to_string(), 12),
        ];

        let total_bytes = write_serialized_events(&mut writer, &serialized)
            .await
            .unwrap();

        writer.flush().await.unwrap();

        assert_eq!(total_bytes, 23);

        let content = tokio::fs::read_to_string(&file_path).await.unwrap();
        assert_eq!(content, "first line\nsecond line\n");
    }

    #[tokio::test]
    async fn test_write_serialized_events_byte_accuracy() {
        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("test-bytes.jsonl");

        let file = OpenOptions::new()
            .create(true)
            .write(true)
            .truncate(true)
            .open(&file_path)
            .await
            .unwrap();
        let mut writer = BufWriter::new(file);

        let serialized = vec![("test\n".to_string(), 5), ("data\n".to_string(), 5)];

        let total_bytes = write_serialized_events(&mut writer, &serialized)
            .await
            .unwrap();

        writer.flush().await.unwrap();

        assert_eq!(total_bytes, 10);

        let metadata = tokio::fs::metadata(&file_path).await.unwrap();
        assert_eq!(metadata.len(), 10);
    }

    #[tokio::test]
    async fn test_write_serialized_events_empty() {
        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("test-empty.jsonl");

        let file = OpenOptions::new()
            .create(true)
            .write(true)
            .truncate(true)
            .open(&file_path)
            .await
            .unwrap();
        let mut writer = BufWriter::new(file);

        let serialized: Vec<(String, usize)> = vec![];

        let total_bytes = write_serialized_events(&mut writer, &serialized)
            .await
            .unwrap();

        writer.flush().await.unwrap();

        assert_eq!(total_bytes, 0);

        let metadata = tokio::fs::metadata(&file_path).await.unwrap();
        assert_eq!(metadata.len(), 0);
    }

    #[tokio::test]
    async fn test_write_with_none_writer() {
        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("test-none.jsonl");

        let writer = JsonlEventWriter::new(file_path.clone()).await.unwrap();

        // Simulate closed writer by taking the writer out
        {
            let mut writer_guard = writer.writer.lock().await;
            *writer_guard = None;
        }

        let event = EventRecord {
            id: Uuid::new_v4(),
            timestamp: chrono::Utc::now(),
            correlation_id: "test-correlation".to_string(),
            event: MapReduceEvent::JobStarted {
                job_id: "test-job".to_string(),
                config: MapReduceConfig {
                    agent_timeout_secs: None,
                    continue_on_failure: false,
                    batch_size: None,
                    enable_checkpoints: true,
                    input: "test.json".to_string(),
                    json_path: "$.items".to_string(),
                    max_parallel: 5,
                    max_items: None,
                    offset: None,
                },
                total_items: 10,
                timestamp: chrono::Utc::now(),
            },
            metadata: Default::default(),
        };

        // Should succeed without error even if writer is None
        writer.write(&[event]).await.unwrap();
    }

    #[tokio::test]
    async fn test_write_large_batch() {
        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("test-large.jsonl");

        let writer = JsonlEventWriter::new(file_path.clone()).await.unwrap();

        // Create a large batch of events
        let events: Vec<EventRecord> = (0..100)
            .map(|i| EventRecord {
                id: Uuid::new_v4(),
                timestamp: chrono::Utc::now(),
                correlation_id: format!("correlation-{}", i),
                event: MapReduceEvent::JobStarted {
                    job_id: format!("job-{}", i),
                    config: MapReduceConfig {
                        agent_timeout_secs: None,
                        continue_on_failure: false,
                        batch_size: None,
                        enable_checkpoints: true,
                        input: "test.json".to_string(),
                        json_path: "$.items".to_string(),
                        max_parallel: 5,
                        max_items: None,
                        offset: None,
                    },
                    total_items: 10,
                    timestamp: chrono::Utc::now(),
                },
                metadata: Default::default(),
            })
            .collect();

        writer.write(&events).await.unwrap();
        writer.flush().await.unwrap();

        // Verify all events were written
        let content = tokio::fs::read_to_string(&file_path).await.unwrap();
        let lines: Vec<&str> = content.lines().collect();
        assert_eq!(lines.len(), 100);
    }

    #[tokio::test]
    async fn test_consecutive_writes_accumulate() {
        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("test-consecutive.jsonl");

        let writer = JsonlEventWriter::new(file_path.clone()).await.unwrap();

        let create_event = |i: usize| EventRecord {
            id: Uuid::new_v4(),
            timestamp: chrono::Utc::now(),
            correlation_id: format!("correlation-{}", i),
            event: MapReduceEvent::JobStarted {
                job_id: format!("job-{}", i),
                config: MapReduceConfig {
                    agent_timeout_secs: None,
                    continue_on_failure: false,
                    batch_size: None,
                    enable_checkpoints: true,
                    input: "test.json".to_string(),
                    json_path: "$.items".to_string(),
                    max_parallel: 5,
                    max_items: None,
                    offset: None,
                },
                total_items: 10,
                timestamp: chrono::Utc::now(),
            },
            metadata: Default::default(),
        };

        // Write in multiple batches
        for batch in 0..5 {
            let events: Vec<EventRecord> = (0..10).map(|i| create_event(batch * 10 + i)).collect();
            writer.write(&events).await.unwrap();
        }

        writer.flush().await.unwrap();

        // Verify all events were written and accumulated
        let content = tokio::fs::read_to_string(&file_path).await.unwrap();
        let lines: Vec<&str> = content.lines().collect();
        assert_eq!(lines.len(), 50);

        // Verify size counter accumulated
        let size = *writer.current_size.lock().await;
        assert!(size > 0);
    }

    #[tokio::test]
    async fn test_jsonl_writer_write_single_event() {
        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("events.jsonl");

        let writer = JsonlEventWriter::new(file_path.clone()).await.unwrap();

        let event = EventRecord {
            id: Uuid::new_v4(),
            timestamp: chrono::Utc::now(),
            correlation_id: "test-correlation".to_string(),
            event: MapReduceEvent::JobStarted {
                job_id: "test-job".to_string(),
                config: MapReduceConfig {
                    agent_timeout_secs: None,
                    continue_on_failure: false,
                    batch_size: None,
                    enable_checkpoints: true,
                    input: "test.json".to_string(),
                    json_path: "$.items".to_string(),
                    max_parallel: 5,
                    max_items: None,
                    offset: None,
                },
                total_items: 10,
                timestamp: chrono::Utc::now(),
            },
            metadata: Default::default(),
        };

        writer.write(&[event]).await.unwrap();
        writer.flush().await.unwrap();

        let content = tokio::fs::read_to_string(&file_path).await.unwrap();
        assert!(content.contains("test-job"));

        let size = *writer.current_size.lock().await;
        assert!(size > 0);
    }

    #[tokio::test]
    async fn test_jsonl_writer_write_empty_array() {
        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("events.jsonl");

        let writer = JsonlEventWriter::new(file_path.clone()).await.unwrap();

        writer.write(&[]).await.unwrap();
        writer.flush().await.unwrap();

        let content = tokio::fs::read_to_string(&file_path).await.unwrap();
        assert_eq!(content.len(), 0);

        let size = *writer.current_size.lock().await;
        assert_eq!(size, 0);
    }

    #[tokio::test]
    async fn test_jsonl_writer_write_batch_events() {
        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("events.jsonl");

        let writer = JsonlEventWriter::new(file_path.clone()).await.unwrap();

        let events: Vec<EventRecord> = (0..10)
            .map(|i| EventRecord {
                id: Uuid::new_v4(),
                timestamp: chrono::Utc::now(),
                correlation_id: format!("correlation-{}", i),
                event: MapReduceEvent::JobStarted {
                    job_id: format!("job-{}", i),
                    config: MapReduceConfig {
                        agent_timeout_secs: None,
                        continue_on_failure: false,
                        batch_size: None,
                        enable_checkpoints: true,
                        input: "test.json".to_string(),
                        json_path: "$.items".to_string(),
                        max_parallel: 5,
                        max_items: None,
                        offset: None,
                    },
                    total_items: 10,
                    timestamp: chrono::Utc::now(),
                },
                metadata: Default::default(),
            })
            .collect();

        writer.write(&events).await.unwrap();
        writer.flush().await.unwrap();

        let content = tokio::fs::read_to_string(&file_path).await.unwrap();
        let lines: Vec<&str> = content.lines().collect();
        assert_eq!(lines.len(), 10);

        let size = *writer.current_size.lock().await;
        assert!(size > 0);
    }

    #[tokio::test]
    async fn test_jsonl_writer_rotation_on_write() {
        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("events.jsonl");

        let writer = JsonlEventWriter::with_rotation(file_path.clone(), 500)
            .await
            .unwrap();

        let events: Vec<EventRecord> = (0..10)
            .map(|i| EventRecord {
                id: Uuid::new_v4(),
                timestamp: chrono::Utc::now(),
                correlation_id: format!("test-correlation-{}", i),
                event: MapReduceEvent::JobStarted {
                    job_id: format!("test-job-{}", i),
                    config: MapReduceConfig {
                        agent_timeout_secs: None,
                        continue_on_failure: false,
                        batch_size: None,
                        enable_checkpoints: true,
                        input: "test.json".to_string(),
                        json_path: "$.items".to_string(),
                        max_parallel: 5,
                        max_items: None,
                        offset: None,
                    },
                    total_items: 10,
                    timestamp: chrono::Utc::now(),
                },
                metadata: Default::default(),
            })
            .collect();

        writer.write(&events).await.unwrap();
        writer.flush().await.unwrap();

        let size_before_rotation = *writer.current_size.lock().await;
        assert!(size_before_rotation >= 500);

        let small_event = EventRecord {
            id: Uuid::new_v4(),
            timestamp: chrono::Utc::now(),
            correlation_id: "small".to_string(),
            event: MapReduceEvent::JobStarted {
                job_id: "small".to_string(),
                config: MapReduceConfig {
                    agent_timeout_secs: None,
                    continue_on_failure: false,
                    batch_size: None,
                    enable_checkpoints: true,
                    input: "test.json".to_string(),
                    json_path: "$.items".to_string(),
                    max_parallel: 5,
                    max_items: None,
                    offset: None,
                },
                total_items: 10,
                timestamp: chrono::Utc::now(),
            },
            metadata: Default::default(),
        };

        writer.write(&[small_event]).await.unwrap();
        writer.flush().await.unwrap();

        let size_after_rotation = *writer.current_size.lock().await;
        assert!(size_after_rotation < 500);
    }

    #[tokio::test]
    async fn test_jsonl_writer_write_after_close() {
        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("events.jsonl");

        let writer = JsonlEventWriter::new(file_path.clone()).await.unwrap();

        {
            let mut writer_guard = writer.writer.lock().await;
            *writer_guard = None;
        }

        let event = EventRecord {
            id: Uuid::new_v4(),
            timestamp: chrono::Utc::now(),
            correlation_id: "test".to_string(),
            event: MapReduceEvent::JobStarted {
                job_id: "test".to_string(),
                config: MapReduceConfig {
                    agent_timeout_secs: None,
                    continue_on_failure: false,
                    batch_size: None,
                    enable_checkpoints: true,
                    input: "test.json".to_string(),
                    json_path: "$.items".to_string(),
                    max_parallel: 5,
                    max_items: None,
                    offset: None,
                },
                total_items: 10,
                timestamp: chrono::Utc::now(),
            },
            metadata: Default::default(),
        };

        let result = writer.write(&[event]).await;
        assert!(result.is_ok());
    }
}