dataprof-csv 0.14.0

CSV parsing and profiling 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
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
use csv::ReaderBuilder;
use std::io::Read;
use std::path::Path;

use dataprof_core::{
    AnalysisOptions, ColumnProfile, CsvSourceMetadata, DataProfilerError, DataSource,
    DelimiterDetection, ExecutionMetadata, FileFormat, TruncationReason,
};
use dataprof_runtime::{
    ProfileReport, ReportAssembler, StreamingColumnCollection, profile_builder,
};

mod encoding;
mod memmap_reader;
mod quote_state;
#[doc(hidden)]
pub mod row_count;

pub use encoding::{EncodingDiagnostic, diagnose_non_utf8};
pub use memmap_reader::MemoryMappedCsvReader;
pub use quote_state::{QuoteOutcome, QuoteTrackingReader, unterminated_quote_error};

/// Configuration for CSV parsing and analysis.
///
/// Replaces the 7 separate `analyze_csv_*` functions with a single config struct.
/// Supports both file-based and reader-based (streaming) entry points.
#[derive(Debug, Clone)]
pub struct CsvParserConfig {
    /// Allow ragged rows (flexible field counts).
    pub flexible: bool,
    /// Custom delimiter (None = comma).
    pub delimiter: Option<u8>,
    /// Quote character, used for delimiter detection and parsing.
    pub quote_char: u8,
    /// Trim whitespace from fields.
    pub trim_whitespace: bool,
    /// Whether the first row contains column headers.
    /// When `false`, columns are named `column_0`, `column_1`, etc.
    pub has_header: bool,
    /// Maximum rows to process (None = all rows).
    pub max_rows: Option<usize>,
}

impl Default for CsvParserConfig {
    fn default() -> Self {
        Self {
            flexible: true,
            delimiter: None,
            quote_char: b'"',
            trim_whitespace: false,
            has_header: true,
            max_rows: None,
        }
    }
}

impl CsvParserConfig {
    /// Create a strict config that rejects ragged rows.
    pub fn strict() -> Self {
        Self {
            flexible: false,
            ..Default::default()
        }
    }

    /// Set the delimiter.
    pub fn with_delimiter(mut self, delimiter: u8) -> Self {
        self.delimiter = Some(delimiter);
        self
    }

    /// Set whether the first row contains column headers.
    pub fn has_header(mut self, yes: bool) -> Self {
        self.has_header = yes;
        self
    }

    /// Set maximum number of rows to evaluate.
    pub fn max_rows(mut self, max: Option<usize>) -> Self {
        self.max_rows = max;
        self
    }
}

/// Count the fields in a record for a given delimiter, respecting quoted
/// sections, and how many of them at the end are empty.
///
/// Returns `(fields, trailing_empty)`. A field is empty when it decodes to
/// nothing, as the readers decode it: nothing stands between its delimiters,
/// or it is a quoted empty string `""`. Judging the raw text instead counted
/// `""` as content, and a row ending in `;""` disagreed with its header
/// (#1102).
///
/// A quote opens a quoted section only at the start of a field, as in the
/// readers and [`split_sample_records`]. Opening one at any quote hid every
/// delimiter after `id"x`, and a `id"x;value` header was read as one column.
fn count_fields(line: &[u8], delimiter: u8, quote: u8) -> (usize, usize) {
    let decodes_empty = |field: &[u8]| field.is_empty() || field == [quote, quote];
    let mut fields = 1;
    let mut trailing_empty = 0;
    let mut field_start = 0;
    let mut in_quotes = false;
    let mut bytes = line.iter().copied().enumerate().peekable();
    while let Some((index, byte)) = bytes.next() {
        if byte == quote && in_quotes {
            if bytes.peek().map(|&(_, next)| next) == Some(quote) {
                bytes.next();
            } else {
                in_quotes = false;
            }
        } else if byte == quote && index == field_start {
            in_quotes = true;
        } else if byte == delimiter && !in_quotes {
            trailing_empty = if decodes_empty(&line[field_start..index]) {
                trailing_empty + 1
            } else {
                0
            };
            fields += 1;
            field_start = index + 1;
        }
    }
    trailing_empty = if decodes_empty(&line[field_start..]) {
        trailing_empty + 1
    } else {
        0
    };
    (fields, trailing_empty)
}

/// Whether a record reads at the header's width without losing or inventing a
/// value: it has exactly that many fields, or more whose extras are all empty,
/// so cutting it to the header drops nothing (#1096).
fn agrees_with_header(fields: usize, trailing_empty: usize, header_fields: usize) -> bool {
    fields == header_fields || (fields > header_fields && fields - trailing_empty <= header_fields)
}

/// Split raw CSV sample text into logical records, honoring quoted sections
/// so an embedded newline inside quotes does not start a new record.
///
/// A record ends at LF, CRLF or a lone CR outside quotes, as in the readers.
/// Splitting on LF alone read a CR-only file as one header record (#1097).
///
/// As in the readers, a quote opens a quoted section only at the start of a
/// field, here a record start or right after `delimiter`; anywhere else it is
/// a literal character. Opening one at any quote read a header such as
/// `id;height"in;note` as never ending. Taking any candidate as a field
/// boundary did the same to `id,height;"in` read with comma (#1172 review),
/// so each candidate splits the text by its own rule.
///
/// The returned flag is true when the final record was not terminated by a
/// newline outside quotes — i.e. the text ends mid-record (or exactly at a
/// record's end with no trailing newline, which a caller sampling a fixed
/// byte budget cannot distinguish from a cut).
fn split_sample_records(bytes: &[u8], delimiter: u8, quote: u8) -> (Vec<&[u8]>, bool) {
    let mut records = Vec::new();
    let mut in_quotes = false;
    let mut start = 0usize;
    let mut i = 0usize;
    while i < bytes.len() {
        match bytes[i] {
            byte if byte == quote && in_quotes => {
                if bytes.get(i + 1) == Some(&quote) {
                    i += 1; // escaped quote inside a quoted section
                } else {
                    in_quotes = false;
                }
            }
            // The reader skips leading record terminators before opening a
            // field, even if the configured quote is itself CR or LF.
            byte if byte == quote
                && (i == start || bytes[i - 1] == delimiter)
                && !(i == start && matches!(byte, b'\r' | b'\n')) =>
            {
                in_quotes = true;
            }
            b'\n' if !in_quotes => {
                let end = if i > start && bytes[i - 1] == b'\r' {
                    i - 1
                } else {
                    i
                };
                records.push(&bytes[start..end]);
                start = i + 1;
            }
            b'\r' if !in_quotes && bytes.get(i + 1) != Some(&b'\n') => {
                records.push(&bytes[start..i]);
                start = i + 1;
            }
            _ => {}
        }
        i += 1;
    }
    let last_unterminated = start < bytes.len();
    if last_unterminated {
        let mut end = bytes.len();
        while end > start && bytes[end - 1] == b'\r' {
            end -= 1;
        }
        records.push(&bytes[start..end]);
    }
    (records, last_unterminated)
}

/// Delimiters detection chooses between, in the order that breaks a tie.
const CANDIDATES: [u8; 4] = *b",;\t|";

/// Bytes delimiter detection reads when the header record ends within them.
const DETECTION_SAMPLE_BYTES: usize = 4096;

/// Most bytes delimiter detection reads to see the whole header record.
const MAX_HEADER_SAMPLE_BYTES: usize = 1 << 20;

/// The bytes of a detection head. A UTF-8 BOM marks the encoding, as in the
/// readers, and is no part of the first record: left in, a BOM followed by a
/// blank line was scored as a one-field header and outvoted the real one.
/// Keep quote bytes intact: a configured non-ASCII byte may delimit fields
/// whose decoded contents are valid UTF-8.
fn head_bytes(head: &[u8]) -> &[u8] {
    head.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(head)
}

/// Preserve detection's whitespace rule without decoding its CSV syntax.
fn record_is_blank(record: &[u8]) -> bool {
    String::from_utf8_lossy(record).trim().is_empty()
}

/// Whether `head`, the start of a source, holds its header record up to the
/// newline that ends it, as every candidate splits it. The readers take the
/// first non-blank record as the header.
fn header_is_complete(head: &[u8], quote: u8) -> bool {
    let head = head_bytes(head);
    CANDIDATES.iter().all(|&delimiter| {
        let (records, last_unterminated) = split_sample_records(head, delimiter, quote);
        records
            .iter()
            .position(|record| !record_is_blank(record))
            .is_some_and(|index| index + 1 < records.len() || !last_unterminated)
    })
}

/// Read the head of a source that delimiter detection scores: 4 KB, or more
/// when the header record runs past that, doubling up to 1 MiB. Each read
/// takes one byte past its target, so the returned flag says for certain
/// whether the head was cut before the end of the source.
///
/// A fixed 4 KB window scored the start of a longer header as the whole of
/// it; no candidate split the fragment, and the file was read as one column
/// with no error (#1098).
fn read_detection_head<R: Read>(reader: &mut R, quote: u8) -> std::io::Result<(Vec<u8>, bool)> {
    let mut head = Vec::new();
    let mut target = DETECTION_SAMPLE_BYTES;
    loop {
        let wanted = (target + 1 - head.len()) as u64;
        reader.by_ref().take(wanted).read_to_end(&mut head)?;
        let cut = head.len() > target;
        if !cut || target == MAX_HEADER_SAMPLE_BYTES || header_is_complete(&head, quote) {
            return Ok((head, cut));
        }
        target = (target * 2).min(MAX_HEADER_SAMPLE_BYTES);
    }
}

const HEADER_TOO_LONG: &str = "The first 1 MiB of the CSV source holds no complete header record, so its delimiter could not be detected.";
const HEADER_TOO_LONG_HINT: &str = "Set the delimiter explicitly (csv_delimiter on Profiler or dataprof.profile) to read this file.";

/// Detect the delimiter of a source and return it with the bytes read to
/// detect it, so a caller that cannot rewind the source can chain them back
/// in front of the rest.
///
/// Detection reads 4 KB, or up to 1 MiB when the header record is longer. A
/// source with no complete header in its first 1 MiB is an error, never a
/// guess. Quoted fields use the default double-quote character.
pub fn detect_delimiter_with_head<R: Read>(
    reader: &mut R,
) -> Result<(u8, Vec<u8>), DataProfilerError> {
    let (detection, head) = detect_delimiter_detailed_with_head(reader)?;
    Ok((detection_byte(&detection), head))
}

/// [`detect_delimiter_with_head`], returning what detection saw with the
/// delimiter it chose: the header's field count and a candidate that read the
/// sampled records as well, so a report can say when the choice was not
/// clear (#1100).
pub fn detect_delimiter_detailed_with_head<R: Read>(
    reader: &mut R,
) -> Result<(DelimiterDetection, Vec<u8>), DataProfilerError> {
    detect_delimiter_with_quote(reader, b'"')
}

/// Use the reader's quote grammar throughout sampling and scoring.
fn detect_delimiter_with_quote<R: Read>(
    reader: &mut R,
    quote: u8,
) -> Result<(DelimiterDetection, Vec<u8>), DataProfilerError> {
    let (head, cut) = read_detection_head(reader, quote)?;
    match score_head(&head, cut, quote) {
        Some(detection) => Ok((detection, head)),
        None => Err(DataProfilerError::csv_structure(
            HEADER_TOO_LONG,
            HEADER_TOO_LONG_HINT,
        )),
    }
}

/// [`detect_delimiter`], returning what detection saw with the delimiter it
/// chose (see [`detect_delimiter_detailed_with_head`]).
pub fn detect_delimiter_detailed<R: Read>(mut reader: R) -> std::io::Result<DelimiterDetection> {
    let (head, cut) = read_detection_head(&mut reader, b'"')?;
    score_head(&head, cut, b'"').ok_or_else(|| {
        std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            format!("{HEADER_TOO_LONG} {HEADER_TOO_LONG_HINT}"),
        )
    })
}

/// The delimiter byte of a detection. Detection only ever chooses one of
/// the ASCII candidates, so the recorded character is that byte.
pub fn detection_byte(detection: &DelimiterDetection) -> u8 {
    detection.delimiter.as_bytes()[0]
}

/// Detect the most likely CSV delimiter by sampling 4 KB of data, or more
/// when the header record is longer (see [`detect_delimiter_with_head`]).
///
/// The sample is split into logical records with double-quote handling, so quoted
/// fields containing embedded newlines or delimiter characters do not skew
/// detection. Tests comma, semicolon, tab, and pipe over the first 5 non-blank
/// records, measured against the first one, the header: it sets the column
/// count, and the readers cut or pad a wider or narrower record to it, or
/// reject it under strict parsing. A delimiter that splits the header always
/// beats one that does not; then more records agreeing with the header win,
/// then more records at exactly the header's width, then a wider header, and
/// comma wins a tie. A record agrees when it reads at the header's width
/// without losing a value: the same field count, or extra fields that are all
/// empty, as an exporter's trailing delimiter leaves.
///
/// Judging by the data rows alone let a delimiter that never occurs in the
/// header win, and the readers then cut every row back to its first field: a
/// one-column file of `123|456` keys was profiled as `123` with fabricated
/// duplicates (#1092).
///
/// A source with no complete header record in its first 1 MiB is an
/// `InvalidData` error.
pub fn detect_delimiter<R: Read>(reader: R) -> std::io::Result<u8> {
    detect_delimiter_detailed(reader).map(|detection| detection_byte(&detection))
}

/// Score the candidate delimiters over a detection head, or `None` when the
/// head was cut before any candidate saw a whole header record.
///
/// A runner-up is a candidate that also splits the header and has as many
/// records agreeing with it. Exact width and header width still pick between
/// the two, but they do not make the reading clear: `id;amount,EUR` with rows
/// `1;10,50;` reads at two fields with either comma or semicolon (#1100).
fn score_head(head: &[u8], cut: bool, quote: u8) -> Option<DelimiterDetection> {
    let head = head_bytes(head);
    // (splits the header into >1 field, records agreeing with the header,
    //  records at exactly the header's width, header field count) — compared
    //  lexicographically, first wins ties. Exact width only breaks a tie: a
    //  candidate that reads every record as it stands beats one that needs
    //  trailing empty fields cut to agree.
    let mut scores: Vec<((bool, usize, usize, usize), u8)> = Vec::new();
    // The scored records of each candidate, in the order of `scores`.
    let mut sampled: Vec<Vec<&[u8]>> = Vec::new();

    for delimiter in CANDIDATES {
        let (mut records, last_unterminated) = split_sample_records(head, delimiter, quote);
        // A head cut mid-record ends in a fragment; never score it. A head
        // ending on a clean newline keeps all its records.
        if cut && last_unterminated {
            records.pop();
        }
        // Blank records carry no delimiter signal: a header followed by
        // trailing blank lines must not outvote the true delimiter with
        // single-field "records" (gh #559).
        let scored: Vec<&[u8]> = records
            .into_iter()
            .filter(|record| !record_is_blank(record))
            .take(5)
            .collect();
        let Some((header, rows)) = scored.split_first() else {
            // A cut head with no whole header has nothing to score for this
            // candidate: its header is the fragment, or lies past the head.
            // A whole source with no header is blank to every candidate.
            if cut {
                continue;
            }
            return Some(DelimiterDetection::new(b',', 0, None));
        };

        let (header_fields, _) = count_fields(header, delimiter, quote);
        let (mut agreeing, mut exact) = (1, 1);
        for record in rows {
            let (fields, trailing_empty) = count_fields(record, delimiter, quote);
            if agrees_with_header(fields, trailing_empty, header_fields) {
                agreeing += 1;
            }
            if fields == header_fields {
                exact += 1;
            }
        }

        scores.push((
            (header_fields > 1, agreeing, exact, header_fields),
            delimiter,
        ));
        sampled.push(scored);
    }

    // The highest score wins, and the earlier candidate a tie.
    let pick = |candidates: &mut dyn Iterator<Item = ((bool, usize, usize, usize), u8)>| {
        candidates.fold(
            None,
            |best: Option<((bool, usize, usize, usize), u8)>, entry| match best {
                Some(held) if entry.0 <= held.0 => Some(held),
                _ => Some(entry),
            },
        )
    };
    let (score, delimiter) = pick(&mut scores.iter().copied())?;
    let (splits, agreeing, _, header_fields) = score;
    let runner_up = pick(
        &mut scores.iter().copied().filter(|&(other, other_delimiter)| {
            splits && other_delimiter != delimiter && other.0 && other.1 == agreeing
        }),
    )
    .map(|(_, other_delimiter)| other_delimiter);
    let unlisted = if splits {
        None
    } else {
        scores
            .iter()
            .position(|&(_, candidate)| candidate == delimiter)
            .and_then(|index| unlisted_delimiter(&sampled[index], quote))
    };
    Some(
        DelimiterDetection::new(delimiter, header_fields, runner_up)
            .with_unlisted_delimiter(unlisted),
    )
}

/// Punctuation that can delimit a file detection does not try: ASCII
/// punctuation except the candidates and `.`, `-` and `_`, which
/// sit inside single values (`first.last`, `2024-01-02`, `event_0`).
/// The active quote character is excluded when scoring these bytes.
const UNLISTED_DELIMITERS: &[u8] = b"!\"#$%&'()*+/:<=>?@[\\]^`{}~";

/// A character outside the candidates that reads the sampled records as a
/// table when no candidate splits the header: it occurs outside quotes in the
/// header, and as often in every sampled record. `None` without a data record
/// to compare, and for an ordinary one-column file, where nothing does.
///
/// `id^amount` over `1^10` is read as one column; this names `^` so the
/// finding can say which delimiter to set (#1100).
fn unlisted_delimiter(records: &[&[u8]], quote: u8) -> Option<u8> {
    let (header, rows) = records.split_first()?;
    if rows.is_empty() {
        return None;
    }
    UNLISTED_DELIMITERS.iter().copied().find(|&byte| {
        if byte == quote {
            return false;
        }
        let occurrences = |record: &[u8]| count_fields(record, byte, quote).0 - 1;
        let in_header = occurrences(header);
        in_header > 0 && rows.iter().all(|row| occurrences(row) == in_header)
    })
}

/// Detect the most likely CSV delimiter from a file path.
pub fn detect_delimiter_from_path(path: &Path) -> std::io::Result<u8> {
    let file = std::fs::File::open(path)?;
    detect_delimiter(std::io::BufReader::new(file))
}

/// Analyze CSV data from any `Read` source using streaming statistics.
///
/// This is the primary generic entry point for both file-based and stream-based
/// CSV profiling. Data is processed incrementally through [`StreamingColumnCollection`]
/// with bounded memory, rather than accumulating all rows in a `HashMap`.
///
/// Returns `(column_profiles, streaming_stats, rows_read)`.
pub fn analyze_csv_from_reader<R: Read>(
    reader: R,
    config: &CsvParserConfig,
) -> Result<
    (
        Vec<ColumnProfile>,
        StreamingColumnCollection,
        usize,
        Vec<String>,
    ),
    DataProfilerError,
> {
    let scan = scan_csv(reader, config)?;
    let profiles = profile_builder::profiles_from_streaming(&scan.column_stats, false, false, None);

    Ok((
        profiles,
        scan.column_stats,
        scan.rows_read,
        scan.header_names,
    ))
}

/// What one pass over CSV input read, and how much of the input that was.
struct CsvScan {
    column_stats: StreamingColumnCollection,
    header_names: Vec<String>,
    rows_read: usize,
    /// Records whose field count differs from the header's, padded or cut to
    /// the header width before profiling.
    ragged_rows: usize,
    /// Set when `max_rows` stopped the pass with records left in the input.
    truncation: Option<TruncationReason>,
    /// The delimiter the pass split records on and how it was chosen.
    csv_metadata: CsvSourceMetadata,
}

fn scan_csv<R: Read>(reader: R, config: &CsvParserConfig) -> Result<CsvScan, DataProfilerError> {
    let mut csv_builder = ReaderBuilder::new();
    csv_builder.has_headers(config.has_header);
    csv_builder.flexible(config.flexible);
    csv_builder.quote(config.quote_char);
    if config.trim_whitespace {
        csv_builder.trim(csv::Trim::All);
    }
    // The byte is kept as it was given: the metadata holds it as a character,
    // and a configured byte above 0x7F would not read back as itself.
    let (boxed_reader, csv_metadata, delimiter): (Box<dyn std::io::Read + '_>, _, _) = match config
        .delimiter
    {
        Some(delimiter) => (
            Box::new(reader),
            CsvSourceMetadata::configured(delimiter),
            delimiter,
        ),
        None => {
            let mut reader = reader;
            let (detection, head) = detect_delimiter_with_quote(&mut reader, config.quote_char)?;
            let delimiter = detection_byte(&detection);
            (
                Box::new(std::io::Cursor::new(head).chain(reader)),
                CsvSourceMetadata::detected(detection),
                delimiter,
            )
        }
    };
    csv_builder.delimiter(delimiter);

    let mut csv_reader = csv_builder.from_reader(boxed_reader);

    let header_names: Vec<String> = if config.has_header {
        let headers = csv_reader.headers()?;
        let names: Vec<String> = headers.iter().map(|header| header.to_string()).collect();
        // Reject duplicate headers before profiling: process_record keys on name,
        // so a repeat would merge two source columns into one inflated profile.
        dataprof_core::validate_unique_column_names(&names, "CSV header")?;
        names
    } else {
        let headers = csv_reader.headers()?;
        (0..headers.len())
            .map(|index| format!("column_{index}"))
            .collect()
    };

    let mut column_stats = StreamingColumnCollection::new();
    // A header declares the columns even when no data records follow it.
    column_stats.init_columns(&header_names);
    let mut rows_read = 0;
    let mut ragged_rows = 0;
    let mut truncation = None;

    for result in csv_reader.records() {
        if let Some(max_rows) = config.max_rows
            && rows_read >= max_rows
        {
            // A record past the cap means the cap, not the end of the input,
            // stopped the pass. That record is neither profiled nor judged.
            truncation = Some(TruncationReason::MaxRows(max_rows as u64));
            break;
        }

        let record = result?;
        let mut values: Vec<String> = record.iter().map(|value| value.to_string()).collect();

        let header_len = header_names.len();
        if values.len() != header_len {
            ragged_rows += 1;
        }
        if values.len() < header_len {
            values.resize(header_len, String::new());
        } else if values.len() > header_len {
            values.truncate(header_len);
        }

        column_stats.process_record(&header_names, values);
        rows_read += 1;
    }

    Ok(CsvScan {
        column_stats,
        header_names,
        rows_read,
        ragged_rows,
        truncation,
        csv_metadata,
    })
}

/// Analyze a CSV file, returning a full [`ProfileReport`].
///
/// Opens the file, reads it as [`analyze_csv_from_reader`] does, and wraps the
/// result with file metadata, ISO 8000/25012 data quality metrics, and the
/// scan's own record: how many rows were ragged, and whether `max_rows` left
/// rows unread.
pub fn analyze_csv_file(
    file_path: &Path,
    config: &CsvParserConfig,
) -> Result<ProfileReport, DataProfilerError> {
    let metadata = std::fs::metadata(file_path).map_err(|error| map_io_error(file_path, error))?;
    dataprof_core::binary_input::reject_binary_input(file_path)?;
    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 scan = scan_csv(buf_reader, config)?;
    let column_stats = &scan.column_stats;
    let column_profiles =
        profile_builder::profiles_from_streaming(column_stats, false, false, None);

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

    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(scan.rows_read, num_columns, scan_time_ms)
        .with_engine("csv")
        .with_ragged_row_count(scan.ragged_rows);
    if let Some(reason) = scan.truncation {
        execution = execution.with_truncation(reason);
    }

    // This path takes no analysis options: it profiles with the defaults,
    // so it records them rather than leaving its settings unknown.
    Ok(ReportAssembler::new(file_source, execution)
        .with_analysis_options(&AnalysisOptions::default())
        .columns(column_profiles)
        .with_quality_data(sample_columns)
        .with_row_duplicates(column_stats.row_duplicate_summary())
        .with_row_completeness(column_stats.row_completeness_summary())
        .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 dataprof_core::DataType;
    use std::io::{Cursor, Write};
    use tempfile::NamedTempFile;

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

    #[test]
    fn test_analyze_csv_from_reader_basic() {
        let data = b"name,age\nAlice,25\nBob,30\n";
        let cursor = Cursor::new(data.as_ref());
        let config = CsvParserConfig::default();

        let (profiles, _stats, rows, _) = analyze_csv_from_reader(cursor, &config).unwrap();
        assert_eq!(rows, 2);
        assert_eq!(profiles.len(), 2);

        let age = profiles
            .iter()
            .find(|profile| profile.name == "age")
            .unwrap();
        assert_eq!(age.total_count, 2);
        assert_eq!(age.data_type, DataType::Integer);
    }

    #[test]
    fn test_analyze_csv_from_reader_with_max_rows() {
        let data = b"val\n1\n2\n3\n4\n5\n";
        let cursor = Cursor::new(data.as_ref());
        let config = CsvParserConfig::default().max_rows(Some(3));

        let (_profiles, _stats, rows, _) = analyze_csv_from_reader(cursor, &config).unwrap();
        assert_eq!(rows, 3);
    }

    #[test]
    fn test_analyze_csv_from_reader_strict_rejects_ragged() {
        let data = b"a,b\n1,2\n3,4,5\n";
        let cursor = Cursor::new(data.as_ref());
        let config = CsvParserConfig::strict();

        assert!(analyze_csv_from_reader(cursor, &config).is_err());
    }

    #[test]
    fn test_analyze_csv_from_reader_flexible_handles_ragged() {
        let data = b"a,b\n1,2\n3,4,5\n6\n";
        let cursor = Cursor::new(data.as_ref());
        let config = CsvParserConfig::default();

        let (profiles, _stats, rows, _) = analyze_csv_from_reader(cursor, &config).unwrap();
        assert_eq!(rows, 3);
        assert!(!profiles.is_empty());
    }

    #[test]
    fn test_analyze_csv_from_reader_custom_delimiter() {
        let data = b"a;b\n1;2\n3;4\n";
        let cursor = Cursor::new(data.as_ref());
        let config = CsvParserConfig::default().with_delimiter(b';');

        let (profiles, _stats, rows, _) = analyze_csv_from_reader(cursor, &config).unwrap();
        assert_eq!(rows, 2);
        assert_eq!(profiles.len(), 2);
    }

    #[test]
    fn test_analyze_csv_file_returns_quality_report() {
        let csv = write_csv("x,y\n1,a\n2,b\n3,c\n");
        let config = CsvParserConfig::default();
        let report = analyze_csv_file(csv.path(), &config).unwrap();

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

    #[test]
    fn test_csv_auto_detects_delimiter_from_reader() {
        let data = b"name;age\nAlice;25\nBob;30\n";
        let cursor = Cursor::new(data.as_ref());
        let config = CsvParserConfig::default();

        let (profiles, _stats, rows, _) = analyze_csv_from_reader(cursor, &config).unwrap();
        assert_eq!(rows, 2);
        assert_eq!(profiles.len(), 2);

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

    #[test]
    fn test_analyze_csv_basic() {
        let csv = write_csv("name,age\nAlice,25\nBob,30\n");
        let config = CsvParserConfig::default();
        let report = analyze_csv_file(csv.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_csv_with_nulls() {
        let csv = write_csv("name,age,email\nAlice,25,a@b.com\nBob,,\nCharlie,30,c@d.com\n");
        let config = CsvParserConfig::default();
        let report = analyze_csv_file(csv.path(), &config).unwrap();
        let profiles = &report.column_profiles;

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

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

    #[test]
    fn test_analyze_csv_file_returns_quality_report_legacy() {
        let csv = write_csv("x,y\n1,a\n2,b\n3,c\n");
        let config = CsvParserConfig::default();
        let report = analyze_csv_file(csv.path(), &config).unwrap();

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

    #[test]
    fn test_analyze_csv_file_header_only_preserves_declared_columns() {
        let csv = write_csv("name,age\n");
        let config = CsvParserConfig::default();
        let report = analyze_csv_file(csv.path(), &config).unwrap();

        assert_eq!(
            report
                .column_profiles
                .iter()
                .map(|column| (column.name.as_str(), column.data_type.clone()))
                .collect::<Vec<_>>(),
            vec![("name", DataType::String), ("age", DataType::String)]
        );
        assert_eq!(report.execution.rows_processed, 0);
        assert!(report.quality.is_some());
    }

    #[test]
    fn test_analyze_csv_file_empty_file_has_no_columns() {
        let csv = write_csv("");
        let config = CsvParserConfig::default();
        let report = analyze_csv_file(csv.path(), &config).unwrap();

        assert!(report.column_profiles.is_empty());
        assert_eq!(report.execution.rows_processed, 0);
        assert_eq!(report.execution.columns_detected, 0);
        assert_eq!(
            report.quality_status,
            dataprof_runtime::QualityAnalysisStatus::Computed
        );
        assert!(report.quality.is_some());
        assert!(report.quality_score().is_none());
    }

    #[test]
    fn test_analyze_csv_with_max_rows_small_file() {
        let csv = write_csv("val\n1\n2\n3\n4\n5\n");
        let config = CsvParserConfig::default();
        let report = analyze_csv_file(csv.path(), &config).unwrap();

        assert_eq!(report.execution.rows_processed, 5);
        assert_eq!(report.execution.columns_detected, 1);
        assert!((report.execution.sampling_ratio.unwrap_or(1.0) - 1.0).abs() < 0.01);
    }

    #[test]
    fn a_row_cap_that_leaves_rows_unread_is_a_truncation() {
        let csv = write_csv("val\n1\n2\n3\n4\n5\n");
        let config = CsvParserConfig::default().max_rows(Some(2));
        let report = analyze_csv_file(csv.path(), &config).unwrap();

        assert_eq!(report.execution.rows_processed, 2);
        assert!(!report.execution.source_exhausted);
        assert_eq!(
            report.execution.truncation_reason,
            Some(TruncationReason::MaxRows(2))
        );
    }

    #[test]
    fn a_row_cap_at_the_last_row_is_a_complete_scan() {
        let csv = write_csv("val\n1\n2\n");
        let config = CsvParserConfig::default().max_rows(Some(2));
        let report = analyze_csv_file(csv.path(), &config).unwrap();

        assert_eq!(report.execution.rows_processed, 2);
        assert!(report.execution.source_exhausted);
        assert_eq!(report.execution.truncation_reason, None);
    }

    #[test]
    fn short_and_long_rows_are_counted_as_ragged() {
        let csv = write_csv("a,b,c\n1,2,3\n4,5\n6,7,8,9\n10,11,12\n");
        let report = analyze_csv_file(csv.path(), &CsvParserConfig::default()).unwrap();

        assert_eq!(report.execution.rows_processed, 4);
        assert_eq!(report.execution.ragged_row_count, 2);
    }

    #[test]
    fn a_ragged_row_past_the_row_cap_is_not_counted() {
        let csv = write_csv("a,b,c\n1,2,3\n4,5\n");
        let config = CsvParserConfig::default().max_rows(Some(1));
        let report = analyze_csv_file(csv.path(), &config).unwrap();

        assert_eq!(report.execution.ragged_row_count, 0);
        assert_eq!(
            report.execution.truncation_reason,
            Some(TruncationReason::MaxRows(1))
        );
    }

    #[test]
    fn test_analyze_csv_numeric_types_detected() {
        let csv = write_csv("int_col,float_col,str_col\n1,1.5,hello\n2,2.5,world\n3,3.5,foo\n");
        let config = CsvParserConfig::default();
        let report = analyze_csv_file(csv.path(), &config).unwrap();
        let profiles = &report.column_profiles;

        let int_col = profiles
            .iter()
            .find(|profile| profile.name == "int_col")
            .unwrap();
        assert!(matches!(int_col.data_type, DataType::Integer));

        let float_col = profiles
            .iter()
            .find(|profile| profile.name == "float_col")
            .unwrap();
        assert!(matches!(float_col.data_type, DataType::Float));

        let str_col = profiles
            .iter()
            .find(|profile| profile.name == "str_col")
            .unwrap();
        assert!(matches!(str_col.data_type, DataType::String));
    }

    #[test]
    fn test_analyze_csv_strict_rejects_ragged_rows() {
        let csv = write_csv("a,b\n1,2\n3,4,5\n");
        let config = CsvParserConfig::strict();
        assert!(analyze_csv_file(csv.path(), &config).is_err());
    }

    #[test]
    fn test_analyze_csv_file_handles_ragged_rows() {
        let csv = write_csv("a,b\n1,2\n3,4,5\n6\n");
        let config = CsvParserConfig::default();
        let report = analyze_csv_file(csv.path(), &config).unwrap();
        assert!(!report.column_profiles.is_empty());
    }

    #[test]
    fn test_analyze_csv_with_quality_metrics() {
        let csv = write_csv(
            "name,age\n\
             Alice,25\nBob,\nCharlie,30\nDave,\nEve,28\n\
             Frank,\nGrace,35\nHeidi,40\nIvan,\nJudy,22\n",
        );
        let config = CsvParserConfig::default();
        let report = analyze_csv_file(csv.path(), &config).unwrap();

        let age = report
            .column_profiles
            .iter()
            .find(|profile| profile.name == "age")
            .unwrap();
        assert_eq!(age.null_count, 4);
        assert_eq!(age.total_count, 10);
        assert!(report.quality_score().unwrap() >= 0.0);
    }

    /// What detection records beside the delimiter it picks (#1100): a
    /// runner-up only on a structural tie, and an unlisted delimiter only when
    /// it splits the header and every sampled record alike.
    #[test]
    fn detection_records_a_tie_and_an_unlisted_delimiter_only_when_present() {
        // (case, source, delimiter, header fields, runner-up, unlisted)
        type Case<'a> = (
            &'a str,
            &'a [u8],
            &'a str,
            usize,
            Option<&'a str>,
            Option<&'a str>,
        );
        let cases: [Case; 9] = [
            (
                "tie",
                b"id;amount,EUR\n1;10,50;\n2;20,75;\n",
                ",",
                2,
                Some(";"),
                None,
            ),
            ("clear comma", b"a,b,c\n1,2,3\n4,5,6\n", ",", 3, None, None),
            (
                "clear semicolon",
                b"a;b\n1,5;2\n3,5;4\n",
                ";",
                2,
                None,
                None,
            ),
            (
                "unlisted caret",
                b"id^amount\n1^10\n2^20\n",
                ",",
                1,
                None,
                Some("^"),
            ),
            ("one column", b"value\n1\n2\n", ",", 1, None, None),
            (
                "dot inside values",
                b"name.first\njohn.doe\njane.roe\n",
                ",",
                1,
                None,
                None,
            ),
            ("header lacks it", b"ratio\n1/2\n3/4\n", ",", 1, None, None),
            ("a record lacks it", b"a:b\n1:2\n3\n", ",", 1, None, None),
            ("header only", b"a^b\n", ",", 1, None, None),
        ];
        let mut wrong = Vec::new();
        for (case, data, delimiter, header_fields, runner_up, unlisted) in cases {
            let detection = detect_delimiter_detailed(Cursor::new(data)).unwrap();
            let seen = (
                detection.delimiter.as_str(),
                detection.header_fields,
                detection.runner_up.as_deref(),
                detection.unlisted_delimiter.as_deref(),
            );
            if seen != (delimiter, header_fields, runner_up, unlisted) {
                wrong.push(format!("{case}: {seen:?}"));
            }
        }
        assert!(wrong.is_empty(), "{}", wrong.join("\n"));
    }

    #[test]
    fn test_detect_delimiter_comma() {
        let data = b"name,age,city\nAlice,25,NYC\nBob,30,London\n";
        assert_eq!(detect_delimiter(Cursor::new(data.as_ref())).unwrap(), b',');
    }

    #[test]
    fn test_detect_delimiter_semicolon() {
        let data = b"name;age;city\nAlice;25;NYC\nBob;30;London\n";
        assert_eq!(detect_delimiter(Cursor::new(data.as_ref())).unwrap(), b';');
    }

    #[test]
    fn test_detect_delimiter_pipe() {
        let data = b"name|age|city\nAlice|25|NYC\nBob|30|London\n";
        assert_eq!(detect_delimiter(Cursor::new(data.as_ref())).unwrap(), b'|');
    }

    #[test]
    fn test_detect_delimiter_tab() {
        let data = b"name\tage\tcity\nAlice\t25\tNYC\nBob\t30\tLondon\n";
        assert_eq!(detect_delimiter(Cursor::new(data.as_ref())).unwrap(), b'\t');
    }

    #[test]
    fn test_detect_delimiter_from_path_semicolon() {
        let csv = write_csv("id;name;salary\n1;Alice;50000\n2;Bob;60000\n");
        assert_eq!(detect_delimiter_from_path(csv.path()).unwrap(), b';');
    }

    #[test]
    fn test_detect_delimiter_blank_records_do_not_outvote_header() {
        // A header-only file with trailing blank lines: the blank records are
        // single-field for every candidate, so counting them made `;` win on
        // perfect consistency and collapse the whole header into one column
        // (gh #559).
        let data = b"name,age\n\n\n";
        assert_eq!(detect_delimiter(Cursor::new(data.as_ref())).unwrap(), b',');

        let semicolon = b"name;age\n\n";
        assert_eq!(
            detect_delimiter(Cursor::new(semicolon.as_ref())).unwrap(),
            b';'
        );
    }

    #[test]
    fn test_detect_delimiter_quoted_fields() {
        let data = b"name;desc;val\n\"hello;world\";foo;1\nbar;baz;2\n";
        assert_eq!(detect_delimiter(Cursor::new(data.as_ref())).unwrap(), b';');
    }

    #[test]
    fn test_detect_delimiter_quoted_embedded_newline() {
        // A quoted cell containing a newline must not break record splitting:
        // before the quote-aware sniffer this file was detected as semicolon
        // (zero occurrences, "perfectly consistent" single-field records) and
        // profiled as a single column named "id,comment".
        let data = b"id,comment\n1,\"line one\nline two\"\n2,\"normal\"\n3,\"has \"\"quotes\"\" inside\"\n";
        assert_eq!(detect_delimiter(Cursor::new(data.as_ref())).unwrap(), b',');
    }

    #[test]
    fn test_detect_delimiter_absent_candidate_never_beats_real_one() {
        // One ragged record makes comma imperfect (consistency 3/4); an absent
        // delimiter is uniformly single-field (4/4) and must still lose.
        let data = b"a,b,c\n1,2,3\nragged line without delimiters\n4,5,6\n";
        assert_eq!(detect_delimiter(Cursor::new(data.as_ref())).unwrap(), b',');
    }

    #[test]
    fn test_detect_delimiter_single_column_falls_back_to_comma() {
        let data = b"value\n1\n2\n3\n";
        assert_eq!(detect_delimiter(Cursor::new(data.as_ref())).unwrap(), b',');
    }

    #[test]
    fn test_detect_delimiter_two_column_semicolon_with_commas_in_text() {
        // Free text containing commas must not outvote the true delimiter.
        let data = b"id;note\n1;hello, world\n2;foo, bar, baz\n3;plain\n";
        assert_eq!(detect_delimiter(Cursor::new(data.as_ref())).unwrap(), b';');
    }

    #[test]
    fn test_detect_delimiter_never_splits_rows_the_header_does_not() {
        // Pipe splits both data rows and not the header; the readers cut rows
        // to the header's width, so choosing it kept only `123` (gh #1092).
        let data = b"key\n123|456\n123|789\n";
        assert_eq!(detect_delimiter(Cursor::new(data.as_ref())).unwrap(), b',');
    }

    #[test]
    fn test_detect_delimiter_header_split_beats_uniform_rows() {
        // A trailing delimiter on every data row: comma splits the header,
        // which no other candidate does.
        let data = b"a,b\n1,2,\n3,4,\n";
        assert_eq!(detect_delimiter(Cursor::new(data.as_ref())).unwrap(), b',');
    }

    #[test]
    fn test_detect_delimiter_trailing_empty_fields_still_agree() {
        // Semicolon rows carry a trailing empty field, comma occurs inside the
        // header name and a decimal. Counting the empty extras against
        // semicolon let comma win and invent a null column (gh #1096).
        let data = b"id;amount,EUR\n1;10,50;\n2;20;\n";
        assert_eq!(detect_delimiter(Cursor::new(data.as_ref())).unwrap(), b';');
    }

    #[test]
    fn test_detect_delimiter_quoted_empty_trailing_field_still_agrees() {
        // `""` decodes to an empty field in every reader; judged on its raw
        // text it counted as content and comma won again (gh #1102).
        let data = b"id;amount,EUR\n1;10,50;\"\"\n2;20;\"\"\n";
        assert_eq!(detect_delimiter(Cursor::new(data.as_ref())).unwrap(), b';');
    }

    #[test]
    fn test_detect_delimiter_exact_width_beats_cut_trailing_fields() {
        // Both candidates split the header and keep every value; semicolon
        // reads each row as it stands, comma only after cutting an empty
        // trailing field. Comma won the tie and renamed the columns.
        let data = b"id,part;value\nx;y,z,\nu;v,w,\n";
        assert_eq!(detect_delimiter(Cursor::new(data.as_ref())).unwrap(), b';');
    }

    #[test]
    fn test_detect_delimiter_skips_a_utf8_bom() {
        // A BOM then a blank line: the BOM alone was scored as a one-field
        // header, and comma won over the real semicolon header.
        let data = b"\xEF\xBB\xBF\nid;value\n1;2\n3;4\n";
        assert_eq!(detect_delimiter(Cursor::new(data.as_ref())).unwrap(), b';');
        let no_blank = b"\xEF\xBB\xBFid;value\n1;2\n";
        assert_eq!(
            detect_delimiter(Cursor::new(no_blank.as_ref())).unwrap(),
            b';'
        );
    }

    #[test]
    fn test_detect_delimiter_lone_cr_ends_a_record() {
        // CR-only line endings: read as one header record, pipe split it and
        // won, and the keys were cut to `123` (gh #1097).
        let data = b"key\r123|456\r123|789\r";
        assert_eq!(detect_delimiter(Cursor::new(data.as_ref())).unwrap(), b',');
        let semicolon = b"id;value\r1;10\r2;20\r";
        assert_eq!(
            detect_delimiter(Cursor::new(semicolon.as_ref())).unwrap(),
            b';'
        );
    }

    #[test]
    fn test_count_fields_reports_trailing_empty_fields() {
        assert_eq!(count_fields(b"1;10,50;", b';', b'"'), (3, 1));
        assert_eq!(count_fields(b"a;;", b';', b'"'), (3, 2));
        assert_eq!(count_fields(b"a;\"\"", b';', b'"'), (2, 1));
        assert_eq!(count_fields(b"a;\"\"\"\"", b';', b'"'), (2, 0));
        assert_eq!(count_fields(b"a; ", b';', b'"'), (2, 0));
        assert_eq!(count_fields(b"a;b", b';', b'"'), (2, 0));
        assert_eq!(count_fields(b"\"x;y\";", b';', b'"'), (2, 1));
    }

    #[test]
    fn test_split_sample_records_quote_aware() {
        let (records, last_unterminated) =
            split_sample_records(b"a,b\r\n1,\"x\ny\"\n2,z\n", b',', b'"');
        assert_eq!(records, ["a,b", "1,\"x\ny\"", "2,z"].map(str::as_bytes));
        assert!(!last_unterminated);

        let (records, last_unterminated) =
            split_sample_records(b"a,b\n1,\"cut mid-fie", b',', b'"');
        assert_eq!(records, ["a,b", "1,\"cut mid-fie"].map(str::as_bytes));
        assert!(last_unterminated);

        let (records, last_unterminated) =
            split_sample_records(b"a,b\r1,\"x\ry\"\r2,z\r", b',', b'"');
        assert_eq!(records, ["a,b", "1,\"x\ry\"", "2,z"].map(str::as_bytes));
        assert!(!last_unterminated);

        let (records, _) = split_sample_records(b"a\rb\r\nc\n", b',', b'"');
        assert_eq!(records, ["a", "b", "c"].map(str::as_bytes));
    }

    #[test]
    fn test_detect_delimiter_full_sample_ending_on_record_boundary() {
        // Exactly 4096 bytes ending with a clean newline: the final record is
        // complete and must be scored, not dropped as a fragment.
        let mut data = Vec::from(&b"a;b;c\n"[..]);
        while data.len() < 4090 {
            data.extend_from_slice(b"1;2;3\n");
        }
        while data.len() < 4095 {
            data.push(b'#');
        }
        data.push(b'\n');
        assert_eq!(data.len(), 4096);
        assert_eq!(
            detect_delimiter(Cursor::new(data.as_slice())).unwrap(),
            b';'
        );
    }

    #[test]
    fn test_detect_delimiter_reads_past_the_sample_to_end_the_header() {
        // #1098: the first `;` is past byte 4096, so a 4 KB sample held a
        // fragment of the header that no candidate split.
        let issue = format!("\"{}\";value\n1;10\n2;20\n", "x".repeat(4094));
        assert_eq!(
            detect_delimiter(Cursor::new(issue.as_bytes())).unwrap(),
            b';'
        );

        // A header record ending exactly at the 4 KB boundary needs no more
        // than the one byte read past it.
        let mut exact = "a".repeat(4093).into_bytes();
        exact.extend_from_slice(b";b\n1;2\n");
        let mut reader = Cursor::new(exact.as_slice());
        let (delimiter, head) = detect_delimiter_with_head(&mut reader).unwrap();
        assert_eq!((delimiter, head.len()), (b';', 4097));
    }

    #[test]
    fn test_detect_delimiter_with_head_returns_every_byte_it_read() {
        let data = format!("{};value\n1;2\n", "a".repeat(20_000));
        let mut reader = Cursor::new(data.as_bytes());
        let (delimiter, head) = detect_delimiter_with_head(&mut reader).unwrap();
        assert_eq!(delimiter, b';');
        assert_eq!(head.len(), 32_768.min(data.len()));
        let mut rest = Vec::new();
        reader.read_to_end(&mut rest).unwrap();
        assert_eq!([head, rest].concat(), data.as_bytes());
    }

    #[test]
    fn test_detect_delimiter_refuses_a_header_past_the_bound() {
        let data = format!("{};value\n1;2\n", "h".repeat(MAX_HEADER_SAMPLE_BYTES));
        let error = detect_delimiter(Cursor::new(data.as_bytes())).unwrap_err();
        assert_eq!(error.kind(), std::io::ErrorKind::InvalidData);
        assert!(error.to_string().contains("csv_delimiter"), "{error}");
        let error = detect_delimiter_with_head(&mut Cursor::new(data.as_bytes())).unwrap_err();
        assert!(matches!(error, DataProfilerError::CsvParsingError { .. }));

        // A whole source no longer than the bound is never refused.
        let short = "h".repeat(MAX_HEADER_SAMPLE_BYTES);
        assert_eq!(
            detect_delimiter(Cursor::new(short.as_bytes())).unwrap(),
            b','
        );
    }

    #[test]
    fn test_detect_delimiter_quote_rule_is_per_candidate() {
        // #1172 review: with any candidate taken as a field boundary, the quote
        // after `;` in a comma header (and after `,` in a semicolon one) opened
        // a quoted section, and a short header past a 1 MiB source was refused.
        for (header, row, expected) in [
            (&b"id,height;\"in\n"[..], &b"1,5\n"[..], b','),
            (&b"id;a;b,\"c\n"[..], &b"1;2;3\n"[..], b';'),
        ] {
            let mut data = header.to_vec();
            while data.len() <= MAX_HEADER_SAMPLE_BYTES {
                data.extend_from_slice(row);
            }
            assert_eq!(
                detect_delimiter(Cursor::new(data.as_slice())).unwrap(),
                expected,
                "{}",
                String::from_utf8_lossy(header)
            );
        }
    }

    #[test]
    fn test_detect_delimiter_refuses_a_head_of_blank_records() {
        // #1172 review: a 1 MiB head of blank lines has not reached the header
        // yet, and guessing comma read `id;value` as one column.
        let mut data = vec![b'\n'; MAX_HEADER_SAMPLE_BYTES + 1];
        data.extend_from_slice(b"id;value\n1;2\n");
        assert!(detect_delimiter(Cursor::new(data.as_slice())).is_err());

        // A whole source that is blank still reads as comma.
        let blank = vec![b'\n'; 10];
        assert_eq!(
            detect_delimiter(Cursor::new(blank.as_slice())).unwrap(),
            b','
        );
    }

    #[test]
    fn test_detect_delimiter_mid_field_quote_is_literal() {
        // The readers take a quote inside a field as a literal, so the header
        // ends at its newline. Taken as opening a quote, it never ended, and a
        // source past the 1 MiB bound was refused.
        let mut data = b"id;height\"in;note\n".to_vec();
        while data.len() <= MAX_HEADER_SAMPLE_BYTES {
            data.extend_from_slice(b"1;5;x\n");
        }
        assert_eq!(
            detect_delimiter(Cursor::new(data.as_slice())).unwrap(),
            b';'
        );

        let (records, last_unterminated) =
            split_sample_records(b"a;b\"c;d\n1;\"x\ny\";2\n", b';', b'"');
        assert_eq!(records, ["a;b\"c;d", "1;\"x\ny\";2"].map(str::as_bytes));
        assert!(!last_unterminated);

        // Field counting follows the same rule: the readers split `id"x;value`
        // into two fields, and a header no candidate split fell back to comma.
        assert_eq!(count_fields(b"id\"x;value", b';', b'"'), (2, 0));
        assert_eq!(count_fields(b"\"a;\"\"b\";c", b';', b'"'), (2, 0));
        assert_eq!(
            detect_delimiter(Cursor::new(&b"id\"x;value\n1;2\n3;4\n"[..])).unwrap(),
            b';'
        );
    }
}