dataprof-json 0.10.0

JSON and JSONL scanning support for dataprof
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
use std::collections::{HashMap, HashSet};
use std::io::BufRead;
use std::path::Path;

pub use dataprof_core::JsonErrorPolicy;
use dataprof_core::{
    ColumnProfile, DataProfilerError, DataSource, ExecutionMetadata, FileFormat, QualityDimension,
    SemanticHints, TruncationReason,
};
use dataprof_runtime::{
    ProfileReport, ReportAssembler, StreamingColumnCollection, profile_builder,
};
use serde::Deserialize;
use serde_json::Value;

/// JSON/JSONL format hint.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum JsonFormat {
    /// Standard JSON array of objects (`[{...}, {...}]`).
    JsonArray,
    /// JSON Lines — one JSON object per line.
    Jsonl,
}

/// Configuration for JSON/JSONL parsing and scanning.
#[derive(Debug, Clone, Default)]
pub struct JsonParserConfig {
    /// Force a specific format (None = auto-detect from content).
    pub format: Option<JsonFormat>,
    /// Maximum rows to process (None = all rows).
    pub max_rows: Option<usize>,
    /// How to react to a malformed record (default: skip).
    pub error_policy: JsonErrorPolicy,
}

impl JsonParserConfig {
    /// Set the maximum number of rows to process.
    pub fn with_max_rows(mut self, max_rows: usize) -> Self {
        self.max_rows = Some(max_rows);
        self
    }

    /// Set how malformed records are handled.
    pub fn with_error_policy(mut self, policy: JsonErrorPolicy) -> Self {
        self.error_policy = policy;
        self
    }

    /// Force JSONL format.
    pub fn jsonl() -> Self {
        Self {
            format: Some(JsonFormat::Jsonl),
            ..Default::default()
        }
    }

    /// Force JSON array format.
    pub fn json_array() -> Self {
        Self {
            format: Some(JsonFormat::JsonArray),
            ..Default::default()
        }
    }
}

/// Borrowed JSON object callback payload.
pub type JsonObject = serde_json::Map<String, Value>;

/// Summary of a JSON/JSONL scan.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct JsonScanSummary {
    pub rows_read: usize,
    pub malformed_lines: usize,
    pub format: FileFormat,
    /// The scan stopped at `max_rows` while records still remained. A source
    /// holding exactly `max_rows` records was read in full, so this stays false.
    pub truncated: bool,
}

/// Scan JSON or JSONL input and invoke `on_object` for each object record.
///
/// - **JSONL**: scans one top-level JSON value at a time from the reader.
/// - **JSON array**: streams array elements without buffering the entire input.
pub fn scan_json_from_reader<R, F>(
    mut reader: R,
    config: &JsonParserConfig,
    mut on_object: F,
) -> Result<JsonScanSummary, DataProfilerError>
where
    R: BufRead,
    F: FnMut(&JsonObject),
{
    let format = match config.format {
        Some(JsonFormat::JsonArray) => FileFormat::Json,
        Some(JsonFormat::Jsonl) => FileFormat::Jsonl,
        None => match consume_leading_whitespace(&mut reader)? {
            Some(b'[') => FileFormat::Json,
            _ => FileFormat::Jsonl,
        },
    };

    let mut rows_read = 0;
    let mut malformed_lines = 0;
    let mut truncated = false;

    match format {
        FileFormat::Jsonl => loop {
            if let Some(max) = config.max_rows
                && rows_read >= max
            {
                // Reaching the cap is not truncation unless a record actually
                // remains: a file with exactly `max_rows` rows was read in full.
                truncated = consume_leading_whitespace(&mut reader)?.is_some();
                break;
            }

            // `serde_json` classifies both a clean end of input and an
            // incomplete trailing value as `Category::Eof`. Check whether a
            // non-whitespace value actually starts here so only the former is
            // treated as normal exhaustion.
            if consume_leading_whitespace(&mut reader)?.is_none() {
                break;
            }

            let mut deserializer = serde_json::Deserializer::from_reader(&mut reader);
            let value: Value = match Value::deserialize(&mut deserializer) {
                Ok(v) => v,
                Err(err) => {
                    if config.error_policy == JsonErrorPolicy::Strict {
                        return Err(malformed_record_error(&err));
                    }
                    malformed_lines += 1;
                    if err.classify() == serde_json::error::Category::Eof {
                        break;
                    }
                    skip_to_next_line(&mut reader)?;
                    continue;
                }
            };

            if let Value::Object(ref obj) = value {
                on_object(obj);
                rows_read += 1;
            }
        },
        FileFormat::Json => {
            let mut found_array = false;
            loop {
                let mut consume = 0;
                {
                    let buf = reader.fill_buf().map_err(DataProfilerError::from)?;
                    if buf.is_empty() {
                        break;
                    }
                    for &byte in buf {
                        consume += 1;
                        if byte == b'[' {
                            found_array = true;
                            break;
                        } else if !byte.is_ascii_whitespace() {
                            break;
                        }
                    }
                }
                reader.consume(consume);
                if found_array || consume == 0 {
                    break;
                }
            }

            if !found_array {
                if config.format.is_some() {
                    return Err(DataProfilerError::JsonParsingError {
                        message: "Expected JSON array (starts with '[') but input does not match"
                            .to_string(),
                    });
                }
            } else {
                let mut expect_value = true;
                let mut allow_end = true;
                let mut array_closed = false;
                let mut drain_remainder = false;

                loop {
                    let Some(next) = consume_leading_whitespace(&mut reader)? else {
                        if config.error_policy == JsonErrorPolicy::Strict {
                            return Err(malformed_array_error(
                                "unexpected end of input before closing ']'",
                            ));
                        }
                        malformed_lines += 1;
                        drain_remainder = true;
                        break;
                    };

                    if expect_value {
                        if next == b']' {
                            if !allow_end {
                                if config.error_policy == JsonErrorPolicy::Strict {
                                    return Err(malformed_array_error(
                                        "trailing comma before closing ']'",
                                    ));
                                }
                                malformed_lines += 1;
                                drain_remainder = true;
                                break;
                            }
                            reader.consume(1);
                            array_closed = true;
                            break;
                        }

                        if let Some(max) = config.max_rows
                            && rows_read >= max
                        {
                            // A value remains unread. Do not validate the unread
                            // suffix of an intentionally bounded scan.
                            truncated = true;
                            break;
                        }

                        if next == b',' {
                            if config.error_policy == JsonErrorPolicy::Strict {
                                return Err(malformed_array_error(
                                    "unexpected comma where an array value was required",
                                ));
                            }
                            malformed_lines += 1;
                            drain_remainder = true;
                            break;
                        }

                        let mut deserializer = serde_json::Deserializer::from_reader(&mut reader);
                        match Value::deserialize(&mut deserializer) {
                            Ok(Value::Object(obj)) => {
                                on_object(&obj);
                                rows_read += 1;
                            }
                            Ok(_) => {}
                            Err(err) => {
                                if config.error_policy == JsonErrorPolicy::Strict {
                                    return Err(malformed_record_error(&err));
                                }
                                malformed_lines += 1;
                                drain_remainder = true;
                                break;
                            }
                        }
                        expect_value = false;
                    } else {
                        match next {
                            b',' => {
                                reader.consume(1);
                                expect_value = true;
                                allow_end = false;
                            }
                            b']' => {
                                reader.consume(1);
                                array_closed = true;
                                break;
                            }
                            _ => {
                                if config.error_policy == JsonErrorPolicy::Strict {
                                    return Err(malformed_array_error(
                                        "expected ',' or ']' after an array value",
                                    ));
                                }
                                malformed_lines += 1;
                                drain_remainder = true;
                                break;
                            }
                        }
                    }
                }

                if drain_remainder {
                    drain_to_end(&mut reader)?;
                } else if array_closed && consume_leading_whitespace(&mut reader)?.is_some() {
                    if config.error_policy == JsonErrorPolicy::Strict {
                        return Err(malformed_array_error(
                            "non-whitespace content follows the closing ']'",
                        ));
                    }
                    malformed_lines += 1;
                    drain_to_end(&mut reader)?;
                }
            }
        }
        _ => unreachable!("json scanner only returns json or jsonl formats"),
    }

    Ok(JsonScanSummary {
        rows_read,
        malformed_lines,
        format,
        truncated,
    })
}

/// Build a strict-mode parse error from a serde failure. The serde message
/// carries line/column context but never the record contents, so it is safe to
/// surface directly.
fn malformed_record_error(err: &serde_json::Error) -> DataProfilerError {
    DataProfilerError::JsonParsingError {
        message: format!("malformed JSON record: {err}"),
    }
}

fn malformed_array_error(message: &str) -> DataProfilerError {
    DataProfilerError::JsonParsingError {
        message: format!("malformed JSON array: {message}"),
    }
}

fn drain_to_end<R: BufRead>(reader: &mut R) -> Result<(), DataProfilerError> {
    loop {
        let available = reader.fill_buf().map_err(DataProfilerError::from)?.len();
        if available == 0 {
            return Ok(());
        }
        reader.consume(available);
    }
}

fn consume_leading_whitespace<R: BufRead>(reader: &mut R) -> Result<Option<u8>, DataProfilerError> {
    loop {
        let mut bytes_to_consume = 0;
        let first_non_whitespace = {
            let buf = reader.fill_buf().map_err(DataProfilerError::from)?;
            if buf.is_empty() {
                return Ok(None);
            }

            let first_non_whitespace = buf.iter().find(|byte| !byte.is_ascii_whitespace()).copied();
            if first_non_whitespace.is_none() {
                bytes_to_consume = buf.len();
            }
            first_non_whitespace
        };

        if first_non_whitespace.is_some() {
            return Ok(first_non_whitespace);
        }

        reader.consume(bytes_to_consume);
    }
}

fn skip_to_next_line<R: BufRead>(reader: &mut R) -> Result<(), DataProfilerError> {
    let mut discarded = Vec::new();
    reader
        .read_until(b'\n', &mut discarded)
        .map_err(DataProfilerError::from)?;
    Ok(())
}

/// Convert a JSON [`Value`] to a flat string for column storage.
fn json_value_to_string(value: &Value) -> String {
    match value {
        Value::Null => String::new(),
        Value::Bool(boolean) => boolean.to_string(),
        Value::Number(number) => number.to_string(),
        Value::String(string) => string.to_string(),
        // decode-audit: impossible — serializing an in-memory Value back to a
        // string cannot fail; a panic here beats folding "" (= null) into stats.
        Value::Array(_) | Value::Object(_) => {
            serde_json::to_string(value).expect("re-serializing a parsed JSON value cannot fail")
        }
    }
}

/// Feed a JSON object's fields into a [`StreamingColumnCollection`].
fn feed_json_object(
    obj: &JsonObject,
    prior_rows: usize,
    known_columns: &mut Vec<String>,
    known_columns_set: &mut HashSet<String>,
    column_stats: &mut StreamingColumnCollection,
) {
    for key in obj.keys() {
        if known_columns_set.insert(key.clone()) {
            known_columns.push(key.clone());
            column_stats.init_column_with_missing(key, prior_rows);
        }
    }

    let values: Vec<String> = known_columns
        .iter()
        .map(|column| {
            // decode-audit: no-data — a key absent from this object is a
            // missing field, and "" is the profiler's textual null.
            obj.get(column)
                .map(json_value_to_string)
                .unwrap_or_default()
        })
        .collect();

    column_stats.process_record(known_columns, values);
}

/// Analyze JSON/JSONL data from a buffered reader using streaming statistics.
///
/// Returns `(column_profiles, streaming_stats, rows_read, malformed_lines, detected_format)`.
pub fn analyze_json_from_reader<R: BufRead>(
    reader: R,
    config: &JsonParserConfig,
) -> Result<
    (
        Vec<ColumnProfile>,
        StreamingColumnCollection,
        usize,
        usize,
        FileFormat,
    ),
    DataProfilerError,
> {
    analyze_json_from_reader_with_hints(reader, config, &SemanticHints::default())
}

pub fn analyze_json_from_reader_with_hints<R: BufRead>(
    reader: R,
    config: &JsonParserConfig,
    semantic_hints: &SemanticHints,
) -> Result<
    (
        Vec<ColumnProfile>,
        StreamingColumnCollection,
        usize,
        usize,
        FileFormat,
    ),
    DataProfilerError,
> {
    let (profiles, stats, rows_read, malformed_lines, format, _truncated) =
        analyze_json_from_reader_full(reader, config, semantic_hints)?;
    Ok((profiles, stats, rows_read, malformed_lines, format))
}

/// As [`analyze_json_from_reader_with_hints`], but also reports whether the scan
/// stopped early. Kept private so the public tuple stays stable.
#[allow(clippy::type_complexity)]
fn analyze_json_from_reader_full<R: BufRead>(
    reader: R,
    config: &JsonParserConfig,
    semantic_hints: &SemanticHints,
) -> Result<
    (
        Vec<ColumnProfile>,
        StreamingColumnCollection,
        usize,
        usize,
        FileFormat,
        bool,
    ),
    DataProfilerError,
> {
    let mut column_stats = StreamingColumnCollection::new().with_semantic_hints(semantic_hints);
    let mut known_columns = Vec::new();
    let mut known_columns_set = HashSet::new();
    let mut rows_seen = 0;

    let summary = scan_json_from_reader(reader, config, |obj| {
        feed_json_object(
            obj,
            rows_seen,
            &mut known_columns,
            &mut known_columns_set,
            &mut column_stats,
        );
        rows_seen += 1;
    })?;

    let profiles = profile_builder::profiles_from_streaming_with_hints(
        &column_stats,
        false,
        false,
        None,
        semantic_hints,
    );

    Ok((
        profiles,
        column_stats,
        summary.rows_read,
        summary.malformed_lines,
        summary.format,
        summary.truncated,
    ))
}

/// Analyze a JSON or JSONL file, returning a full [`ProfileReport`].
pub fn analyze_json_file(
    file_path: &Path,
    config: &JsonParserConfig,
) -> Result<ProfileReport, DataProfilerError> {
    analyze_json_file_with_dimensions(file_path, config, None)
}

/// Like [`analyze_json_file`] but only computes the requested quality dimensions.
pub fn analyze_json_file_with_dimensions(
    file_path: &Path,
    config: &JsonParserConfig,
    quality_dimensions: Option<&[QualityDimension]>,
) -> Result<ProfileReport, DataProfilerError> {
    analyze_json_file_with_dimensions_and_hints(
        file_path,
        config,
        quality_dimensions,
        &SemanticHints::default(),
    )
}

pub fn analyze_json_file_with_dimensions_and_hints(
    file_path: &Path,
    config: &JsonParserConfig,
    quality_dimensions: Option<&[QualityDimension]>,
    semantic_hints: &SemanticHints,
) -> Result<ProfileReport, DataProfilerError> {
    let metadata = std::fs::metadata(file_path).map_err(|error| map_io_error(file_path, error))?;
    let start = std::time::Instant::now();

    let file = std::fs::File::open(file_path).map_err(|error| map_io_error(file_path, error))?;
    let buf_reader = std::io::BufReader::new(file);

    let (column_profiles, column_stats, rows_read, malformed_lines, format, truncated) =
        analyze_json_from_reader_full(buf_reader, config, semantic_hints)?;

    let file_source = DataSource::File {
        path: file_path.display().to_string(),
        format,
        size_bytes: metadata.len(),
        modified_at: None,
        parquet_metadata: None,
    };

    if rows_read == 0 {
        if malformed_lines > 0 {
            return Err(DataProfilerError::JsonParsingError {
                message: "No valid JSON records found in file (malformed JSON encountered)"
                    .to_string(),
            });
        }
        let mut assembler = ReportAssembler::new(
            file_source,
            ExecutionMetadata::new(0, 0, start.elapsed().as_millis()).with_engine("json"),
        )
        .columns(column_profiles)
        .with_quality_data(HashMap::new());
        if let Some(dimensions) = quality_dimensions {
            assembler = assembler.with_requested_dimensions(dimensions.to_vec());
        }
        return Ok(assembler.build());
    }

    let sample_columns = profile_builder::quality_check_samples(&column_stats);
    let scan_time_ms = start.elapsed().as_millis();
    let num_columns = column_profiles.len();

    let mut execution = ExecutionMetadata::new(rows_read, num_columns, scan_time_ms)
        .with_engine("json")
        // Tolerant scans surface skipped malformed records here so callers can
        // tell a partial profile from a clean one.
        .with_error_count(malformed_lines);
    // `truncated` is set only when a record still remained at the cap, so a source
    // holding exactly `max_rows` records is reported as fully read, not cut short.
    if truncated && let Some(max) = config.max_rows {
        execution = execution.with_truncation(TruncationReason::MaxRows(max as u64));
    }

    let mut assembler = ReportAssembler::new(file_source, execution)
        .columns(column_profiles)
        .with_quality_data(sample_columns)
        .with_row_duplicates(column_stats.row_duplicate_summary())
        .with_exact_value_hint_bindings(column_stats.semantic_hint_bindings())
        .with_semantic_hints(semantic_hints.clone());
    if let Some(dimensions) = quality_dimensions {
        assembler = assembler.with_requested_dimensions(dimensions.to_vec());
    }
    Ok(assembler.build())
}

fn map_io_error(file_path: &Path, error: std::io::Error) -> DataProfilerError {
    if error.kind() == std::io::ErrorKind::NotFound {
        DataProfilerError::FileNotFound {
            path: file_path.display().to_string(),
        }
    } else {
        DataProfilerError::from(error)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::{Cursor, Write};
    use tempfile::NamedTempFile;

    fn write_file(content: &str) -> NamedTempFile {
        let mut file = NamedTempFile::new().unwrap();
        write!(file, "{}", content).unwrap();
        file.flush().unwrap();
        file
    }

    #[test]
    fn test_scan_jsonl_detects_format_and_rows() {
        let data = b"{\"x\":1}\n{\"x\":2}\n{\"x\":3}\n";
        let mut rows = 0;

        let summary = scan_json_from_reader(
            Cursor::new(data.as_ref()),
            &JsonParserConfig::default(),
            |_| {
                rows += 1;
            },
        )
        .unwrap();

        assert_eq!(summary.format, FileFormat::Jsonl);
        assert_eq!(summary.rows_read, 3);
        assert_eq!(summary.malformed_lines, 0);
        assert_eq!(rows, 3);
    }

    #[test]
    fn test_scan_json_array_detects_format_and_rows() {
        let data = br#"[{"name":"Alice"},{"name":"Bob"}]"#;
        let mut keys = Vec::new();

        let summary = scan_json_from_reader(
            Cursor::new(data.as_ref()),
            &JsonParserConfig::default(),
            |obj| keys.push(obj.keys().cloned().collect::<Vec<_>>()),
        )
        .unwrap();

        assert_eq!(summary.format, FileFormat::Json);
        assert_eq!(summary.rows_read, 2);
        assert_eq!(keys.len(), 2);
        assert_eq!(keys[0], vec!["name".to_string()]);
    }

    #[test]
    fn test_json_array_container_grammar_obeys_error_policy() {
        let cases = [
            (br#"[{"x":1}"#.as_ref(), 1, "missing closing bracket"),
            (br#"[{"x":1},"#.as_ref(), 1, "comma followed by EOF"),
            (br#"[{"x":1} {"x":2}]"#.as_ref(), 1, "missing comma"),
            (br#"[{"x":1},,{"x":2}]"#.as_ref(), 1, "doubled comma"),
            (br#"[,{"x":1}]"#.as_ref(), 0, "leading comma"),
            (br#"[{"x":1},]"#.as_ref(), 1, "trailing comma"),
            (br#"[{"x":1}] trailing"#.as_ref(), 1, "trailing content"),
            (
                br#"[{"x":1}][{"x":2}]"#.as_ref(),
                1,
                "second top-level value",
            ),
        ];

        for (data, expected_rows, case) in cases {
            let skip = JsonParserConfig::json_array();
            let summary =
                scan_json_from_reader(Cursor::new(data), &skip, |_| {}).expect("tolerant scan");
            assert_eq!(summary.rows_read, expected_rows, "{case}");
            assert_eq!(summary.malformed_lines, 1, "{case}");

            let strict = JsonParserConfig::json_array().with_error_policy(JsonErrorPolicy::Strict);
            let err = scan_json_from_reader(Cursor::new(data), &strict, |_| {})
                .expect_err("strict mode must reject invalid array grammar");
            assert!(
                err.to_string()
                    .to_lowercase()
                    .contains("malformed json array"),
                "{case}: {err}"
            );
        }
    }

    #[test]
    fn test_json_array_max_rows_does_not_validate_unread_values() {
        let data = br#"[{"x":1},not-valid-json"#;
        let config = JsonParserConfig::json_array().with_max_rows(1);
        let summary = scan_json_from_reader(Cursor::new(data.as_ref()), &config, |_| {}).unwrap();

        assert_eq!(summary.rows_read, 1);
        assert_eq!(summary.malformed_lines, 0);
        assert!(summary.truncated);
    }

    #[test]
    fn test_scan_respects_max_rows() {
        let data = b"{\"x\":1}\n{\"x\":2}\n{\"x\":3}\n{\"x\":4}\n";
        let config = JsonParserConfig::default().with_max_rows(2);
        let mut rows = 0;

        let summary =
            scan_json_from_reader(Cursor::new(data.as_ref()), &config, |_| rows += 1).unwrap();

        assert_eq!(summary.rows_read, 2);
        assert_eq!(rows, 2);
    }

    #[test]
    fn test_scan_skips_malformed_jsonl_lines() {
        let data = b"{\"x\":1}\n{\"x\":,bad}\n{\"x\":3}\n";
        let mut rows = 0;

        let summary = scan_json_from_reader(
            Cursor::new(data.as_ref()),
            &JsonParserConfig::jsonl(),
            |_| {
                rows += 1;
            },
        )
        .unwrap();

        assert_eq!(summary.format, FileFormat::Jsonl);
        assert_eq!(summary.rows_read, 2);
        assert_eq!(summary.malformed_lines, 1);
        assert_eq!(rows, 2);
    }

    #[test]
    fn test_scan_pretty_printed_root_object_is_one_jsonl_row() {
        let data = br#"{
    "type": "FeatureCollection",
    "features": [
        {"id": 1},
        {"id": 2}
  ]
}"#;
        let mut object_field_counts = Vec::new();

        let summary = scan_json_from_reader(
            Cursor::new(data.as_ref()),
            &JsonParserConfig::default(),
            |obj| object_field_counts.push(obj.len()),
        )
        .unwrap();

        assert_eq!(summary.format, FileFormat::Jsonl);
        assert_eq!(summary.rows_read, 1);
        assert_eq!(summary.malformed_lines, 0);
        assert_eq!(object_field_counts, vec![2]);
    }

    #[test]
    fn test_forced_json_array_requires_opening_bracket() {
        let data = br#"{"x":1}"#;
        let err = scan_json_from_reader(
            Cursor::new(data.as_ref()),
            &JsonParserConfig::json_array(),
            |_| {},
        )
        .expect_err("forced json array should reject non-array input");

        assert!(err.to_string().contains("Expected JSON array"));
    }

    #[test]
    fn test_analyze_json_from_reader_jsonl_streaming() {
        let data = b"{\"x\":1,\"y\":\"a\"}\n{\"x\":2,\"y\":\"b\"}\n{\"x\":3,\"y\":\"c\"}\n";
        let cursor = Cursor::new(data.as_ref());
        let config = JsonParserConfig::default();

        let (profiles, _stats, rows, _malformed, format) =
            analyze_json_from_reader(cursor, &config).unwrap();
        assert_eq!(format, FileFormat::Jsonl);
        assert_eq!(rows, 3);
        assert_eq!(profiles.len(), 2);
    }

    #[test]
    fn test_analyze_json_from_reader_json_array() {
        let data = br#"[{"name":"Alice","age":25},{"name":"Bob","age":30}]"#;
        let cursor = Cursor::new(data.as_ref());
        let config = JsonParserConfig::default();

        let (profiles, _stats, rows, _malformed, format) =
            analyze_json_from_reader(cursor, &config).unwrap();
        assert_eq!(format, FileFormat::Json);
        assert_eq!(rows, 2);
        assert_eq!(profiles.len(), 2);
    }

    #[test]
    fn test_analyze_json_from_reader_max_rows() {
        let data = b"{\"x\":1}\n{\"x\":2}\n{\"x\":3}\n{\"x\":4}\n{\"x\":5}\n";
        let cursor = Cursor::new(data.as_ref());
        let config = JsonParserConfig::default().with_max_rows(3);

        let (_profiles, _stats, rows, _malformed, _format) =
            analyze_json_from_reader(cursor, &config).unwrap();
        assert_eq!(rows, 3);
    }

    #[test]
    fn test_analyze_json_from_reader_missing_fields() {
        let data = b"{\"a\":1,\"b\":2}\n{\"a\":3}\n";
        let cursor = Cursor::new(data.as_ref());
        let config = JsonParserConfig::jsonl();

        let (profiles, _stats, rows, _malformed, _format) =
            analyze_json_from_reader(cursor, &config).unwrap();
        assert_eq!(rows, 2);

        let col_b = profiles.iter().find(|profile| profile.name == "b").unwrap();
        assert_eq!(col_b.total_count, 2);
    }

    #[test]
    fn test_analyze_json_file_quality_report() {
        let file = write_file(r#"[{"x":1},{"x":2}]"#);
        let config = JsonParserConfig::default();
        let report = analyze_json_file(file.path(), &config).unwrap();

        assert_eq!(report.execution.rows_processed, 2);
        assert_eq!(report.column_profiles.len(), 1);
        assert!(report.quality_score().unwrap() >= 0.0);
    }

    #[test]
    fn test_jsonl_skips_malformed_lines() {
        let data = b"{\"x\":1}\n{\"x\":,malformed}\n{\"x\":3}\n";
        let cursor = Cursor::new(data.as_ref());
        let config = JsonParserConfig::jsonl();

        let (profiles, _stats, rows, _malformed, format) =
            analyze_json_from_reader(cursor, &config).unwrap();
        assert_eq!(format, FileFormat::Jsonl);
        assert_eq!(rows, 2);
        assert_eq!(profiles[0].total_count, 2);
    }

    #[test]
    fn test_strict_policy_errors_on_malformed_jsonl() {
        // Malformed in first / middle / last position all abort under Strict.
        for data in [
            b"not-json\n{\"x\":1}\n{\"x\":2}\n".as_ref(),
            b"{\"x\":1}\nnot-json\n{\"x\":2}\n".as_ref(),
            b"{\"x\":1}\n{\"x\":2}\nnot-json\n".as_ref(),
        ] {
            let config = JsonParserConfig::jsonl().with_error_policy(JsonErrorPolicy::Strict);
            let err = scan_json_from_reader(Cursor::new(data), &config, |_| {})
                .expect_err("strict mode must reject malformed records");
            let message = err.to_string().to_lowercase();
            assert!(message.contains("malformed json record"), "got: {message}");
            // The offending record text must never be echoed back.
            assert!(
                !err.to_string().contains("not-json"),
                "leaked record: {err}"
            );
        }
    }

    #[test]
    fn test_tolerant_policy_counts_skipped_records() {
        let data = b"{\"x\":1}\nnot-json\n{\"x\":2}\n";
        let config = JsonParserConfig::jsonl(); // default Skip
        let summary = scan_json_from_reader(Cursor::new(data.as_ref()), &config, |_| {}).unwrap();
        assert_eq!(summary.rows_read, 2);
        assert_eq!(summary.malformed_lines, 1);
    }

    #[test]
    fn test_blank_lines_are_not_counted_as_malformed() {
        let data = b"{\"x\":1}\n\n   \n{\"x\":2}\n";
        for policy in [JsonErrorPolicy::Skip, JsonErrorPolicy::Strict] {
            let config = JsonParserConfig::jsonl().with_error_policy(policy);
            let summary =
                scan_json_from_reader(Cursor::new(data.as_ref()), &config, |_| {}).unwrap();
            assert_eq!(summary.rows_read, 2, "policy {policy:?}");
            assert_eq!(summary.malformed_lines, 0, "policy {policy:?}");
        }
    }

    #[test]
    fn test_truncated_final_record_obeys_error_policy() {
        let data = b"{\"x\":1}\n{\"x\":2";

        let skip = JsonParserConfig::jsonl().with_error_policy(JsonErrorPolicy::Skip);
        let summary = scan_json_from_reader(Cursor::new(data.as_ref()), &skip, |_| {}).unwrap();
        assert_eq!(summary.rows_read, 1);
        assert_eq!(summary.malformed_lines, 1);

        let strict = JsonParserConfig::jsonl().with_error_policy(JsonErrorPolicy::Strict);
        let err = scan_json_from_reader(Cursor::new(data.as_ref()), &strict, |_| {})
            .expect_err("strict mode must reject an incomplete trailing record");
        assert!(
            err.to_string()
                .to_lowercase()
                .contains("malformed json record")
        );
    }

    #[test]
    fn test_all_malformed_file_fails() {
        let file = write_file("not-json\nalso-bad\n");
        let config = JsonParserConfig::jsonl();
        let err = analyze_json_file(file.path(), &config)
            .expect_err("a file with no valid records must fail");
        let message = err.to_string().to_lowercase();
        assert!(message.contains("no valid json records"), "got: {message}");
    }

    #[test]
    fn test_tolerant_file_reports_error_count() {
        let file = write_file("{\"x\":1}\nnot-json\n{\"x\":2}\n");
        let config = JsonParserConfig::jsonl();
        let report = analyze_json_file(file.path(), &config).unwrap();
        assert_eq!(report.execution.rows_processed, 2);
        assert_eq!(report.execution.error_count, 1);
    }

    #[test]
    fn test_strict_file_errors_on_malformed() {
        let file = write_file("{\"x\":1}\nnot-json\n{\"x\":2}\n");
        let config = JsonParserConfig::jsonl().with_error_policy(JsonErrorPolicy::Strict);
        let err = analyze_json_file(file.path(), &config)
            .expect_err("strict mode must reject the malformed record");
        assert!(
            err.to_string()
                .to_lowercase()
                .contains("malformed json record")
        );
    }

    #[test]
    fn test_analyze_json_with_large_leading_whitespace() {
        let data = format!("{}[{{\"x\":1}}]", " ".repeat(10_000));
        let cursor = Cursor::new(data.into_bytes());
        let config = JsonParserConfig::default();

        let (_profiles, _stats, rows, malformed, format) =
            analyze_json_from_reader(cursor, &config).unwrap();
        assert_eq!(format, FileFormat::Json);
        assert_eq!(rows, 1);
        assert_eq!(malformed, 0);
    }

    #[test]
    fn test_analyze_json_array() {
        let json = write_file(r#"[{"name":"Alice","age":25},{"name":"Bob","age":30}]"#);
        let config = JsonParserConfig::default();
        let report = analyze_json_file(json.path(), &config).unwrap();
        let profiles = &report.column_profiles;

        assert_eq!(profiles.len(), 2);
        let names: Vec<&str> = profiles
            .iter()
            .map(|profile| profile.name.as_str())
            .collect();
        assert!(names.contains(&"name"));
        assert!(names.contains(&"age"));

        let age = profiles
            .iter()
            .find(|profile| profile.name == "age")
            .unwrap();
        assert_eq!(age.total_count, 2);
        assert_eq!(age.null_count, 0);
    }

    #[test]
    fn test_analyze_jsonl() {
        let jsonl = write_file("{\"x\":1}\n{\"x\":2}\n{\"x\":3}\n");
        let config = JsonParserConfig::default();
        let report = analyze_json_file(jsonl.path(), &config).unwrap();
        let profiles = &report.column_profiles;

        assert_eq!(profiles.len(), 1);
        assert_eq!(profiles[0].name, "x");
        assert_eq!(profiles[0].total_count, 3);
    }

    #[test]
    fn test_analyze_json_with_nulls() {
        let json = write_file(r#"[{"a":"hello","b":1},{"a":null,"b":2},{"a":"world","b":null}]"#);
        let config = JsonParserConfig::default();
        let report = analyze_json_file(json.path(), &config).unwrap();
        let profiles = &report.column_profiles;

        let col_a = profiles.iter().find(|profile| profile.name == "a").unwrap();
        assert_eq!(col_a.null_count, 1);

        let col_b = profiles.iter().find(|profile| profile.name == "b").unwrap();
        assert_eq!(col_b.null_count, 1);
    }

    #[test]
    fn test_analyze_json_with_missing_fields() {
        let json = write_file(r#"[{"a":1,"b":2},{"a":3}]"#);
        let config = JsonParserConfig::default();
        let report = analyze_json_file(json.path(), &config).unwrap();
        let profiles = &report.column_profiles;

        let col_b = profiles.iter().find(|profile| profile.name == "b").unwrap();
        assert_eq!(col_b.total_count, 2);
    }

    #[test]
    fn test_analyze_json_backfills_columns_discovered_after_first_row() {
        let json = write_file(r#"[{"a":1},{"a":2,"b":3}]"#);
        let config = JsonParserConfig::default();
        let report = analyze_json_file(json.path(), &config).unwrap();
        let col_b = report
            .column_profiles
            .iter()
            .find(|profile| profile.name == "b")
            .unwrap();

        assert_eq!(col_b.total_count, 2);
        assert_eq!(col_b.null_count, 1);
        assert_eq!(col_b.unique_count, Some(1));
    }

    #[test]
    fn test_analyze_json_empty_array() {
        let json = write_file("[]");
        let config = JsonParserConfig::default();
        let report = analyze_json_file(json.path(), &config).unwrap();
        assert!(report.column_profiles.is_empty());
        // An empty dataset has nothing to assess: no score is fabricated.
        assert_eq!(report.quality_score(), None);
    }

    #[test]
    fn test_analyze_json_malformed_returns_error() {
        let json = write_file("this is entirely invalid json");
        let config = JsonParserConfig::default();
        let err = analyze_json_file(json.path(), &config)
            .expect_err("malformed JSON should return an error");

        let message = err.to_string().to_lowercase();
        assert!(message.contains("malformed") && message.contains("json"));
    }

    #[test]
    fn test_analyze_json_file_detects_format() {
        let json_array = write_file(r#"[{"x":1}]"#);
        let config = JsonParserConfig::default();
        let report = analyze_json_file(json_array.path(), &config).unwrap();
        assert!(matches!(
            report.data_source,
            DataSource::File {
                format: FileFormat::Json,
                ..
            }
        ));

        let jsonl = write_file("{\"x\":1}\n{\"x\":2}\n");
        let report = analyze_json_file(jsonl.path(), &config).unwrap();
        assert!(matches!(
            report.data_source,
            DataSource::File {
                format: FileFormat::Jsonl,
                ..
            }
        ));
    }

    #[test]
    fn test_analyze_json_file_empty() {
        let json = write_file("");
        let config = JsonParserConfig::default();
        let report = analyze_json_file(json.path(), &config).unwrap();
        assert_eq!(report.execution.rows_processed, 0);
        assert!(report.column_profiles.is_empty());
    }

    #[test]
    fn test_analyze_json_boolean_and_nested() {
        let json =
            write_file(r#"[{"flag":true,"nested":{"a":1}},{"flag":false,"nested":{"b":2}}]"#);
        let config = JsonParserConfig::default();
        let report = analyze_json_file(json.path(), &config).unwrap();
        let profiles = &report.column_profiles;

        let flag = profiles
            .iter()
            .find(|profile| profile.name == "flag")
            .unwrap();
        assert_eq!(flag.total_count, 2);

        let nested = profiles
            .iter()
            .find(|profile| profile.name == "nested")
            .unwrap();
        assert_eq!(nested.total_count, 2);
    }

    #[test]
    fn test_single_root_object_compact_yields_one_row() {
        let data = br#"{"type":"FeatureCollection","features":[1,2,3]}"#;
        let cursor = Cursor::new(data.as_ref());
        let config = JsonParserConfig::default();

        let (profiles, _stats, rows, malformed, _format) =
            analyze_json_from_reader(cursor, &config).unwrap();
        assert_eq!(rows, 1);
        assert_eq!(malformed, 0);
        assert_eq!(profiles.len(), 2);

        let names: Vec<&str> = profiles
            .iter()
            .map(|profile| profile.name.as_str())
            .collect();
        assert!(names.contains(&"type"));
        assert!(names.contains(&"features"));
    }

    #[test]
    fn test_jsonl_multi_object_still_works() {
        let data = b"{\"x\":1}\n{\"x\":2}\n{\"x\":3}\n";
        let cursor = Cursor::new(data.as_ref());
        let config = JsonParserConfig::default();

        let (_profiles, _stats, rows, _malformed, format) =
            analyze_json_from_reader(cursor, &config).unwrap();
        assert_eq!(format, FileFormat::Jsonl);
        assert_eq!(rows, 3);
    }

    #[test]
    fn test_single_root_object_via_analyze_json_file() {
        let file = write_file(r#"{"type":"FeatureCollection","features":[{"id":1},{"id":2}]}"#);
        let config = JsonParserConfig::default();
        let report = analyze_json_file(file.path(), &config).unwrap();

        assert_eq!(report.execution.rows_processed, 1);
        assert_eq!(report.column_profiles.len(), 2);
    }

    #[test]
    fn test_single_root_object_pretty_printed_yields_one_row() {
        let data = br#"{
  "type": "FeatureCollection",
  "features": [
    {"id": 1},
    {"id": 2}
  ]
}"#;
        let cursor = Cursor::new(data.as_ref());
        let config = JsonParserConfig::default();

        let (profiles, _stats, rows, malformed, format) =
            analyze_json_from_reader(cursor, &config).unwrap();
        assert_eq!(format, FileFormat::Jsonl);
        assert_eq!(rows, 1);
        assert_eq!(malformed, 0);
        assert_eq!(profiles.len(), 2);
    }

    #[test]
    fn test_single_root_object_pretty_printed_via_analyze_json_file() {
        let file = write_file(
            "{\n  \"type\": \"FeatureCollection\",\n  \"features\": [\n    {\"id\": 1},\n    {\"id\": 2}\n  ]\n}\n",
        );
        let config = JsonParserConfig::default();
        let report = analyze_json_file(file.path(), &config).unwrap();

        assert_eq!(report.execution.rows_processed, 1);
        assert_eq!(report.column_profiles.len(), 2);
    }
}