kelora 1.5.0

A command-line log analysis tool with embedded Rhai scripting
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
mod common;
use common::*;
use std::io::Write;
use std::path::Path;
use std::process::{Command, Stdio};
use tempfile::NamedTempFile;

#[test]
fn test_explicit_stdin_with_dash() {
    let input = r#"{"level": "info", "message": "test1"}
{"level": "error", "message": "test2"}
{"level": "info", "message": "test3"}"#;

    let (stdout, _stderr, exit_code) = run_kelora_with_input(&["-f", "json", "-"], input);

    assert_eq!(exit_code, 0);
    assert!(stdout.contains("test1"));
    assert!(stdout.contains("test2"));
    assert!(stdout.contains("test3"));
}

#[test]
fn test_missing_file_reports_name() {
    let missing = "tests/data/file_should_not_exist_12345.log";
    assert!(
        !Path::new(missing).exists(),
        "Test assumes missing file does not exist"
    );

    let (_stdout, stderr, exit_code) = run_kelora_with_files(&["-f", "json"], &[missing]);

    assert_ne!(exit_code, 0, "Should fail when file is missing");
    assert!(
        stderr.contains(missing),
        "stderr should mention missing filename: {}",
        stderr
    );
}

#[test]
fn test_quoted_glob_reports_shell_expansion_hint() {
    let (_stdout, stderr, exit_code) =
        run_kelora_with_files(&["-f", "json"], &["examples/*.jsonl"]);

    assert_ne!(
        exit_code, 0,
        "quoted glob should fail as a literal missing file"
    );
    assert!(
        stderr.contains("Shell glob patterns must be expanded by the shell"),
        "stderr should explain quoted glob behavior: {}",
        stderr
    );
}

#[test]
fn test_missing_file_is_in_error_summary() {
    let mut temp_file = NamedTempFile::new().expect("Failed to create temp file");
    writeln!(temp_file, "ok").expect("Failed to write temp file");

    let missing = "tests/data/file_should_not_exist_98765.log";
    assert!(
        !Path::new(missing).exists(),
        "Test assumes missing file does not exist"
    );

    let (_stdout, stderr, exit_code) = run_kelora_with_files(
        &["-f", "line"],
        &[temp_file.path().to_str().unwrap(), missing],
    );

    assert_ne!(exit_code, 0, "Should fail when file is missing");
    assert!(
        stderr.contains("file failed to open"),
        "Error summary should mention failed file open: {}",
        stderr
    );
    assert!(
        stderr.contains(missing),
        "Error summary should include missing filename: {}",
        stderr
    );
}

#[test]
fn test_stdin_mixed_with_files() {
    // Create a temporary file
    let mut temp_file = NamedTempFile::new().expect("Failed to create temp file");
    temp_file
        .write_all(b"{\"level\": \"debug\", \"message\": \"from file\"}\n")
        .expect("Failed to write to temp file");

    let stdin_input = r#"{"level": "info", "message": "from stdin"}"#;

    // Test file first, then stdin
    // Use CARGO_BIN_EXE_kelora env var set by cargo during test runs
    // This works correctly for regular builds, coverage builds, and custom target dirs
    let mut cmd = Command::new(env!("CARGO_BIN_EXE_kelora"))
        .env("LLVM_PROFILE_FILE", "/dev/null") // Disable profraw generation for subprocesses
        .args(["-f", "json", temp_file.path().to_str().unwrap(), "-"])
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("Failed to start kelora");

    if let Some(stdin) = cmd.stdin.as_mut() {
        stdin
            .write_all(stdin_input.as_bytes())
            .expect("Failed to write to stdin");
    }

    let output = cmd.wait_with_output().expect("Failed to read output");
    let stdout = String::from_utf8_lossy(&output.stdout).to_string();
    let exit_code = output.status.code().unwrap_or(-1);

    assert_eq!(exit_code, 0);
    assert!(stdout.contains("from file"));
    assert!(stdout.contains("from stdin"));
}

#[test]
fn test_multiple_stdin_rejected() {
    let (stdout, stderr, exit_code) = run_kelora_with_input(&["-f", "json", "-", "-"], "test");

    assert_ne!(exit_code, 0);
    assert!(stderr.contains("stdin (\"-\") can only be specified once"));
    assert!(stdout.is_empty());
}

#[test]
fn test_stdin_large_input_performance() {
    // Generate 1000 log entries to test performance
    let mut large_input = String::new();
    for i in 1..=1000 {
        large_input.push_str(&format!(
            "{{\"user\":\"user{}\",\"status\":{},\"message\":\"Message {}\",\"id\":{}}}\n",
            i,
            200 + (i % 300),
            i,
            i
        ));
    }

    let start_time = std::time::Instant::now();
    let (stdout, _, exit_code) = run_kelora_with_input(
        &[
            "-f",
            "json",
            "--filter",
            "e.status >= 400",
            "--exec",
            "track_count(\"errors\");",
            "--end",
            "print(`Errors: ${metrics[\"errors\"]}`);",
        ],
        &large_input,
    );
    let duration = start_time.elapsed();

    assert_eq!(
        exit_code, 0,
        "kelora should handle large input successfully"
    );
    assert!(
        stdout.contains("Errors:"),
        "Should count errors in large dataset"
    );

    // Performance check: should process 1000 lines in reasonable time
    assert!(
        duration.as_millis() < 5000,
        "Should process 1000 lines in less than 5 seconds, took {}ms",
        duration.as_millis()
    );
}

#[test]
fn test_filename_tracking_json_sequential() {
    // Test filename tracking with JSON format in sequential mode
    let mut temp_file1 = NamedTempFile::new().expect("Failed to create temp file");
    let mut temp_file2 = NamedTempFile::new().expect("Failed to create temp file");

    temp_file1
        .write_all(b"{\"message\": \"test1\"}\n")
        .expect("Failed to write to temp file");
    temp_file2
        .write_all(b"{\"message\": \"test2\"}\n")
        .expect("Failed to write to temp file");

    let (stdout, _stderr, exit_code) = run_kelora_with_files(
        &[
            "-f",
            "json",
            "--exec",
            "print(\"File: \" + meta.filename + \", Message: \" + e.message)",
        ],
        &[
            temp_file1.path().to_str().unwrap(),
            temp_file2.path().to_str().unwrap(),
        ],
    );

    assert_eq!(exit_code, 0, "Should exit successfully");
    assert!(
        stdout.contains("File: ") && stdout.contains("Message: test1"),
        "Should show filename and message for file1: {}",
        stdout
    );
    assert!(
        stdout.contains("File: ") && stdout.contains("Message: test2"),
        "Should show filename and message for file2: {}",
        stdout
    );
}

#[test]
fn test_filename_tracking_json_parallel() {
    // Test filename tracking with JSON format in parallel mode
    let mut temp_file1 = NamedTempFile::new().expect("Failed to create temp file");
    let mut temp_file2 = NamedTempFile::new().expect("Failed to create temp file");

    temp_file1
        .write_all(b"{\"message\": \"test1\"}\n")
        .expect("Failed to write to temp file");
    temp_file2
        .write_all(b"{\"message\": \"test2\"}\n")
        .expect("Failed to write to temp file");

    let (stdout, _stderr, exit_code) = run_kelora_with_files(
        &[
            "-f",
            "json",
            "--parallel",
            "--exec",
            "print(\"File: \" + meta.filename + \", Message: \" + e.message)",
        ],
        &[
            temp_file1.path().to_str().unwrap(),
            temp_file2.path().to_str().unwrap(),
        ],
    );

    assert_eq!(exit_code, 0, "Should exit successfully");
    assert!(
        stdout.contains("File: ") && stdout.contains("Message: test1"),
        "Should show filename and message for file1: {}",
        stdout
    );
    assert!(
        stdout.contains("File: ") && stdout.contains("Message: test2"),
        "Should show filename and message for file2: {}",
        stdout
    );
}

#[test]
fn test_filename_tracking_line_format() {
    // Test filename tracking with line format
    let mut temp_file1 = NamedTempFile::new().expect("Failed to create temp file");
    let mut temp_file2 = NamedTempFile::new().expect("Failed to create temp file");

    temp_file1
        .write_all(b"line from file1\n")
        .expect("Failed to write to temp file");
    temp_file2
        .write_all(b"line from file2\n")
        .expect("Failed to write to temp file");

    let (stdout, _stderr, exit_code) = run_kelora_with_files(
        &[
            "-f",
            "line",
            "--exec",
            "print(\"File: \" + meta.filename + \", Line: \" + line)",
        ],
        &[
            temp_file1.path().to_str().unwrap(),
            temp_file2.path().to_str().unwrap(),
        ],
    );

    assert_eq!(exit_code, 0, "Should exit successfully");
    assert!(
        stdout.contains("File: ") && stdout.contains("Line: line from file1"),
        "Should show filename and content for file1: {}",
        stdout
    );
    assert!(
        stdout.contains("File: ") && stdout.contains("Line: line from file2"),
        "Should show filename and content for file2: {}",
        stdout
    );
}

#[test]
fn test_filename_tracking_with_file_order() {
    // Test filename tracking with file ordering
    let mut temp_file1 = NamedTempFile::new().expect("Failed to create temp file");
    let mut temp_file2 = NamedTempFile::new().expect("Failed to create temp file");

    temp_file1
        .write_all(b"first\n")
        .expect("Failed to write to temp file");
    temp_file2
        .write_all(b"second\n")
        .expect("Failed to write to temp file");

    let (stdout, _stderr, exit_code) = run_kelora_with_files(
        &[
            "-f",
            "line",
            "--file-order",
            "name",
            "--exec",
            "print(\"Processing: \" + meta.filename + \" -> \" + line)",
        ],
        &[
            temp_file1.path().to_str().unwrap(),
            temp_file2.path().to_str().unwrap(),
        ],
    );

    assert_eq!(exit_code, 0, "Should exit successfully");
    assert!(
        stdout.contains("Processing: ") && stdout.contains("first"),
        "Should process first file: {}",
        stdout
    );
    assert!(
        stdout.contains("Processing: ") && stdout.contains("second"),
        "Should process second file: {}",
        stdout
    );
}

#[test]
fn test_no_input_with_begin_only() {
    // Test --no-input with only --begin stage
    let (stdout, _stderr, exit_code) =
        run_kelora(&["--no-input", "--begin", "print(\"Hello, World!\")"]);

    assert_eq!(exit_code, 0, "Should exit successfully");
    assert!(
        stdout.contains("Hello, World!"),
        "Should execute begin stage: {}",
        stdout
    );
}

#[test]
fn test_no_input_with_begin_and_end() {
    // Test --no-input with both --begin and --end stages
    let (stdout, _stderr, exit_code) = run_kelora(&[
        "--no-input",
        "--begin",
        "conf.counter = 0; for i in 0..5 { conf.counter += i; }",
        "--end",
        "print(`Sum: ${conf.counter}`)",
    ]);

    assert_eq!(exit_code, 0, "Should exit successfully");
    assert!(
        stdout.contains("Sum: 10"),
        "Should execute begin and end stages: {}",
        stdout
    );
}

#[test]
fn test_no_input_conflicts_with_files() {
    // Test that --no-input conflicts with file arguments
    let mut temp_file = NamedTempFile::new().expect("Failed to create temp file");
    temp_file
        .write_all(b"test\n")
        .expect("Failed to write to temp file");

    let (stdout, stderr, exit_code) =
        run_kelora_with_files(&["--no-input"], &[temp_file.path().to_str().unwrap()]);

    assert_ne!(exit_code, 0, "Should fail with error");
    assert!(
        stderr.contains("--no-input cannot be used with input files"),
        "Should show conflict error: {}",
        stderr
    );
    assert!(
        stderr.contains("Remove --no-input to read files"),
        "Should explain how to resolve the conflict: {}",
        stderr
    );
    assert!(stdout.is_empty());
}

#[test]
fn test_no_input_with_metrics() {
    // Test --no-input with metrics tracking in begin/end stages
    let (stdout, _stderr, exit_code) = run_kelora(&[
        "--no-input",
        "--begin",
        "for i in 0..10 { track_count(\"iterations\"); }",
        "--end",
        "print(`Total iterations: ${metrics[\"iterations\"]}`)",
    ]);

    assert_eq!(exit_code, 0, "Should exit successfully");
    assert!(
        stdout.contains("Total iterations: 10"),
        "Should track metrics across stages: {}",
        stdout
    );
}

#[test]
fn test_no_input_sequential_mode() {
    // Test --no-input in sequential mode (default)
    let (stdout, _stderr, exit_code) =
        run_kelora(&["--no-input", "--begin", "print(\"Sequential mode\")"]);

    assert_eq!(exit_code, 0, "Should work in sequential mode");
    assert!(stdout.contains("Sequential mode"));
}

#[test]
fn test_no_input_parallel_mode() {
    // Test --no-input with --parallel
    let (stdout, _stderr, exit_code) = run_kelora(&[
        "--no-input",
        "--parallel",
        "--begin",
        "print(\"Parallel mode\")",
    ]);

    assert_eq!(exit_code, 0, "Should work in parallel mode");
    assert!(stdout.contains("Parallel mode"));
}

#[test]
fn test_merge_sorted_merges_files_chronologically() {
    let mut temp_file1 = NamedTempFile::new().expect("Failed to create temp file");
    let mut temp_file2 = NamedTempFile::new().expect("Failed to create temp file");

    temp_file1
        .write_all(
            b"{\"ts\":\"2025-01-01T00:00:02Z\",\"msg\":\"b\"}\n{\"ts\":\"2025-01-01T00:00:04Z\",\"msg\":\"d\"}\n",
        )
        .expect("Failed to write to temp file");
    temp_file2
        .write_all(
            b"{\"ts\":\"2025-01-01T00:00:01Z\",\"msg\":\"a\"}\n{\"ts\":\"2025-01-01T00:00:03Z\",\"msg\":\"c\"}\n",
        )
        .expect("Failed to write to temp file");

    let (stdout, _stderr, exit_code) = run_kelora_with_files(
        &["-f", "json", "-F", "json", "--merge-sorted"],
        &[
            temp_file1.path().to_str().unwrap(),
            temp_file2.path().to_str().unwrap(),
        ],
    );

    assert_eq!(exit_code, 0, "Should merge files successfully");
    let messages: Vec<String> = stdout
        .lines()
        .map(|line| {
            serde_json::from_str::<serde_json::Value>(line)
                .expect("Output line should be JSON")
                .get("msg")
                .and_then(|v| v.as_str())
                .unwrap_or_default()
                .to_string()
        })
        .collect();
    assert_eq!(messages, vec!["a", "b", "c", "d"]);
}

#[test]
fn test_merge_sorted_auto_detects_standard_timestamp_field_names() {
    let mut temp_file1 = NamedTempFile::new().expect("Failed to create temp file");
    let mut temp_file2 = NamedTempFile::new().expect("Failed to create temp file");

    temp_file1
        .write_all(
            b"{\"timestamp\":\"2025-01-01T00:00:02Z\",\"msg\":\"b\"}\n{\"timestamp\":\"2025-01-01T00:00:04Z\",\"msg\":\"d\"}\n",
        )
        .expect("Failed to write to temp file");
    temp_file2
        .write_all(
            b"{\"timestamp\":\"2025-01-01T00:00:01Z\",\"msg\":\"a\"}\n{\"timestamp\":\"2025-01-01T00:00:03Z\",\"msg\":\"c\"}\n",
        )
        .expect("Failed to write to temp file");

    let (stdout, _stderr, exit_code) = run_kelora_with_files(
        &["-f", "json", "-F", "json", "--merge-sorted"],
        &[
            temp_file1.path().to_str().unwrap(),
            temp_file2.path().to_str().unwrap(),
        ],
    );

    assert_eq!(exit_code, 0, "Should merge files successfully");
    let messages: Vec<String> = stdout
        .lines()
        .map(|line| {
            serde_json::from_str::<serde_json::Value>(line)
                .expect("Output line should be JSON")
                .get("msg")
                .and_then(|v| v.as_str())
                .unwrap_or_default()
                .to_string()
        })
        .collect();
    assert_eq!(messages, vec!["a", "b", "c", "d"]);
}

#[test]
fn test_merge_sorted_rejects_parallel_mode() {
    let (stdout, stderr, exit_code) = run_kelora(&["-f", "json", "--parallel", "--merge-sorted"]);
    assert_ne!(exit_code, 0, "Expected validation error");
    assert!(
        stderr.contains("--merge-sorted is not supported with --parallel"),
        "Unexpected error message: {}",
        stderr
    );
    assert!(stdout.is_empty());
}

#[test]
fn test_merge_sorted_supports_logfmt() {
    let mut temp_file1 = NamedTempFile::new().expect("Failed to create temp file");
    let mut temp_file2 = NamedTempFile::new().expect("Failed to create temp file");

    temp_file1
        .write_all(b"ts=2025-01-01T00:00:02Z msg=b\n")
        .expect("Failed to write to temp file");
    temp_file2
        .write_all(b"ts=2025-01-01T00:00:01Z msg=a\n")
        .expect("Failed to write to temp file");

    let (stdout, _stderr, exit_code) = run_kelora_with_files(
        &["-f", "logfmt", "-F", "json", "--merge-sorted"],
        &[
            temp_file1.path().to_str().unwrap(),
            temp_file2.path().to_str().unwrap(),
        ],
    );

    assert_eq!(exit_code, 0, "Should merge logfmt inputs successfully");
    let messages: Vec<String> = stdout
        .lines()
        .map(|line| {
            serde_json::from_str::<serde_json::Value>(line)
                .expect("Output line should be JSON")
                .get("msg")
                .and_then(|v| v.as_str())
                .unwrap_or_default()
                .to_string()
        })
        .collect();
    assert_eq!(messages, vec!["a", "b"]);
}

#[test]
fn test_merge_sorted_rejects_csv_for_now() {
    let mut temp_file1 = NamedTempFile::new().expect("Failed to create temp file");
    let mut temp_file2 = NamedTempFile::new().expect("Failed to create temp file");

    temp_file1
        .write_all(b"ts,msg\n2025-01-01T00:00:02Z,b\n")
        .expect("Failed to write to temp file");
    temp_file2
        .write_all(b"ts,msg\n2025-01-01T00:00:01Z,a\n")
        .expect("Failed to write to temp file");

    let (stdout, _stderr, exit_code) = run_kelora_with_files(
        &["-f", "csv", "-F", "json", "--merge-sorted"],
        &[
            temp_file1.path().to_str().unwrap(),
            temp_file2.path().to_str().unwrap(),
        ],
    );

    assert_ne!(exit_code, 0, "CSV merge should be rejected for now");
    assert!(
        stdout.is_empty(),
        "No events should be emitted for unsupported format"
    );
}

#[test]
fn test_merge_sorted_assumes_each_file_is_already_sorted() {
    let mut temp_file1 = NamedTempFile::new().expect("Failed to create temp file");
    let mut temp_file2 = NamedTempFile::new().expect("Failed to create temp file");

    temp_file1
        .write_all(
            b"{\"ts\":\"2025-01-01T00:00:04Z\",\"msg\":\"d\"}\n{\"ts\":\"2025-01-01T00:00:01Z\",\"msg\":\"a\"}\n",
        )
        .expect("Failed to write to temp file");
    temp_file2
        .write_all(
            b"{\"ts\":\"2025-01-01T00:00:02Z\",\"msg\":\"b\"}\n{\"ts\":\"2025-01-01T00:00:03Z\",\"msg\":\"c\"}\n",
        )
        .expect("Failed to write to temp file");

    let (stdout, _stderr, exit_code) = run_kelora_with_files(
        &["-f", "json", "-F", "json", "--merge-sorted"],
        &[
            temp_file1.path().to_str().unwrap(),
            temp_file2.path().to_str().unwrap(),
        ],
    );

    assert_ne!(
        exit_code, 0,
        "merge-sorted should fail when an input file is not timestamp-sorted"
    );
    let messages: Vec<String> = stdout
        .lines()
        .map(|line| {
            serde_json::from_str::<serde_json::Value>(line)
                .expect("Output line should be JSON")
                .get("msg")
                .and_then(|v| v.as_str())
                .unwrap_or_default()
                .to_string()
        })
        .collect();
    assert_eq!(messages, vec!["b", "c", "d"]);
}

#[test]
fn test_merge_sorted_missing_timestamps_fail_immediately_in_streaming_mode() {
    let mut temp_file1 = NamedTempFile::new().expect("Failed to create temp file");
    let mut temp_file2 = NamedTempFile::new().expect("Failed to create temp file");

    temp_file1
        .write_all(
            b"{\"ts\":\"2025-01-01T00:00:02Z\",\"msg\":\"b\"}\n{\"msg\":\"missing\"}\n{\"ts\":\"2025-01-01T00:00:04Z\",\"msg\":\"d\"}\n",
        )
        .expect("Failed to write to temp file");
    temp_file2
        .write_all(
            b"{\"ts\":\"2025-01-01T00:00:01Z\",\"msg\":\"a\"}\n{\"ts\":\"2025-01-01T00:00:03Z\",\"msg\":\"c\"}\n",
        )
        .expect("Failed to write to temp file");

    let (stdout, stderr, exit_code) = run_kelora_with_files(
        &["-f", "json", "-F", "json", "--merge-sorted"],
        &[
            temp_file1.path().to_str().unwrap(),
            temp_file2.path().to_str().unwrap(),
        ],
    );

    assert_ne!(
        exit_code, 0,
        "merge-sorted should fail when a later event is missing a timestamp"
    );
    let messages: Vec<String> = stdout
        .lines()
        .map(|line| {
            serde_json::from_str::<serde_json::Value>(line)
                .expect("Output line should be JSON")
                .get("msg")
                .and_then(|v| v.as_str())
                .unwrap_or_default()
                .to_string()
        })
        .collect();
    assert_eq!(messages, vec!["a", "b"]);
    assert!(
        stderr.contains("--merge-sorted requires a timestamp for every event"),
        "Expected immediate merge failure, got: {}",
        stderr
    );
}

#[test]
fn test_merge_sorted_missing_timestamps_fail_in_strict_mode() {
    let mut temp_file1 = NamedTempFile::new().expect("Failed to create temp file");
    let mut temp_file2 = NamedTempFile::new().expect("Failed to create temp file");

    temp_file1
        .write_all(
            b"{\"ts\":\"2025-01-01T00:00:02Z\",\"msg\":\"b\"}\n{\"msg\":\"missing\"}\n{\"ts\":\"2025-01-01T00:00:04Z\",\"msg\":\"d\"}\n",
        )
        .expect("Failed to write to temp file");
    temp_file2
        .write_all(b"{\"ts\":\"2025-01-01T00:00:01Z\",\"msg\":\"a\"}\n")
        .expect("Failed to write to temp file");

    let (stdout, stderr, exit_code) = run_kelora_with_files(
        &["-f", "json", "-F", "json", "--merge-sorted", "--strict"],
        &[
            temp_file1.path().to_str().unwrap(),
            temp_file2.path().to_str().unwrap(),
        ],
    );

    assert_ne!(
        exit_code, 0,
        "Strict mode should fail on missing timestamps"
    );
    assert!(stdout.contains("\"msg\":\"a\""));
    assert!(stdout.contains("\"msg\":\"b\""));
    assert!(
        stderr.contains("--merge-sorted requires a timestamp for every event"),
        "Expected strict-mode failure to mention missing timestamp, got: {}",
        stderr
    );
    assert!(
        stderr.contains("--ts-field"),
        "Expected strict-mode failure to suggest --ts-field override, got: {}",
        stderr
    );
}

#[test]
fn test_merge_sorted_fails_fast_on_disordered_events() {
    let mut temp_file1 = NamedTempFile::new().expect("Failed to create temp file");
    let mut temp_file2 = NamedTempFile::new().expect("Failed to create temp file");

    temp_file1
        .write_all(
            b"{\"ts\":\"2025-01-01T00:00:04Z\",\"msg\":\"d\"}\n{\"ts\":\"2025-01-01T00:00:01Z\",\"msg\":\"a\"}\n",
        )
        .expect("Failed to write to temp file");
    temp_file2
        .write_all(
            b"{\"ts\":\"2025-01-01T00:00:02Z\",\"msg\":\"b\"}\n{\"ts\":\"2025-01-01T00:00:03Z\",\"msg\":\"c\"}\n",
        )
        .expect("Failed to write to temp file");

    let (stdout, stderr, exit_code) = run_kelora_with_files(
        &["-f", "json", "-F", "json", "--merge-sorted"],
        &[
            temp_file1.path().to_str().unwrap(),
            temp_file2.path().to_str().unwrap(),
        ],
    );

    assert_ne!(
        exit_code, 0,
        "merge-sorted should fail when an input file is not timestamp-sorted"
    );
    let messages: Vec<String> = stdout
        .lines()
        .map(|line| {
            serde_json::from_str::<serde_json::Value>(line)
                .expect("Output line should be JSON")
                .get("msg")
                .and_then(|v| v.as_str())
                .unwrap_or_default()
                .to_string()
        })
        .collect();
    assert_eq!(messages, vec!["b", "c", "d"]);
    assert!(
        stderr.contains("input is not sorted by timestamp"),
        "Expected disordered-input failure, got: {}",
        stderr
    );
    assert!(
        stderr.contains("earlier than the previous event"),
        "Expected disordered-input details, got: {}",
        stderr
    );
}

#[test]
fn test_merge_sorted_disordered_events_fail_in_strict_mode() {
    let mut temp_file1 = NamedTempFile::new().expect("Failed to create temp file");
    let mut temp_file2 = NamedTempFile::new().expect("Failed to create temp file");

    temp_file1
        .write_all(
            b"{\"ts\":\"2025-01-01T00:00:04Z\",\"msg\":\"d\"}\n{\"ts\":\"2025-01-01T00:00:01Z\",\"msg\":\"a\"}\n",
        )
        .expect("Failed to write to temp file");
    temp_file2
        .write_all(
            b"{\"ts\":\"2025-01-01T00:00:02Z\",\"msg\":\"b\"}\n{\"ts\":\"2025-01-01T00:00:03Z\",\"msg\":\"c\"}\n",
        )
        .expect("Failed to write to temp file");

    let (stdout, stderr, exit_code) = run_kelora_with_files(
        &["-f", "json", "-F", "json", "--merge-sorted", "--strict"],
        &[
            temp_file1.path().to_str().unwrap(),
            temp_file2.path().to_str().unwrap(),
        ],
    );

    assert_ne!(exit_code, 0, "Strict mode should fail on disordered input");
    assert!(stdout.contains("\"msg\":\"b\""));
    assert!(stdout.contains("\"msg\":\"c\""));
    assert!(stdout.contains("\"msg\":\"d\""));
    assert!(!stdout.contains("\"msg\":\"a\""));
    assert!(
        stderr.contains("input is not sorted by timestamp"),
        "Expected strict-mode failure to mention disordered input, got: {}",
        stderr
    );
    assert!(
        stderr.contains("earlier than the previous event"),
        "Expected strict-mode failure to mention disordered input, got: {}",
        stderr
    );
}

#[test]
fn test_merge_sorted_fails_before_output_when_file_has_no_initial_mergeable_event() {
    let mut temp_file1 = NamedTempFile::new().expect("Failed to create temp file");
    let mut temp_file2 = NamedTempFile::new().expect("Failed to create temp file");

    temp_file1
        .write_all(b"{\"msg\":\"missing\"}\n")
        .expect("Failed to write to temp file");
    temp_file2
        .write_all(b"{\"ts\":\"2025-01-01T00:00:01Z\",\"msg\":\"a\"}\n")
        .expect("Failed to write to temp file");

    let (stdout, stderr, exit_code) = run_kelora_with_files(
        &["-f", "json", "-F", "json", "--merge-sorted"],
        &[
            temp_file1.path().to_str().unwrap(),
            temp_file2.path().to_str().unwrap(),
        ],
    );

    assert_ne!(exit_code, 0, "merge-sorted should fail during priming");
    assert!(
        stdout.is_empty(),
        "priming failures should happen before output"
    );
    assert!(
        stderr.contains("--merge-sorted requires a timestamp for every event"),
        "Expected priming failure to mention missing timestamp, got: {}",
        stderr
    );
}