From c7662ab8b40a721819e534941e038e7265f1ef8e Mon Sep 17 00:00:00 2001 From: Arthur Chan Date: Tue, 20 Oct 2026 08:16:34 +0100 Subject: [PATCH 1/5] OSS-Fuzz: Update csv fuzzer and corpora/dict preparation Signed-off-by: Arthur Chan --- .../fuzzing/dicts/arrow-csv-fuzz.dict | 60 ++++++ .../fuzzing/generate_corpuses.sh | 21 ++ cpp/src/arrow/csv/fuzz.cc | 188 ++++++++++++------ cpp/src/arrow/csv/generate_fuzz_corpus.cc | 37 +++- 4 files changed, 237 insertions(+), 69 deletions(-) create mode 100644 cpp/build-support/fuzzing/dicts/arrow-csv-fuzz.dict diff --git a/cpp/build-support/fuzzing/dicts/arrow-csv-fuzz.dict b/cpp/build-support/fuzzing/dicts/arrow-csv-fuzz.dict new file mode 100644 index 000000000000..bbda8108e016 --- /dev/null +++ b/cpp/build-support/fuzzing/dicts/arrow-csv-fuzz.dict @@ -0,0 +1,60 @@ +# Tokens for arrow-csv-fuzz: CSV dialect characters, null/bool spellings, +# numeric edge cases and timestamp formats understood by the Arrow CSV reader. +"," +";" +"\x09" +"|" +" " +"\"" +"'" +"\\" +"\x0d\x0a" +"\x0a" +"\x0d" +"NULL" +"null" +"None" +"N/A" +"n/a" +"NaN" +"nan" +"inf" +"+inf" +"-inf" +"Infinity" +"true" +"false" +"True" +"False" +"TRUE" +"FALSE" +"1" +"0" +"01" +"0.5" +"-0.0" +"-1.25" +"1e10" +"1E+10" +"1.5e-300" +"18446744073709551615" +"-9223372036854775808" +"9223372036854775807" +"2147483648" +"2024-12-31" +"2024-12-31T23:59:59" +"2024-12-31T23:59:59.123456789" +"2024-12-31 23:59:59" +"12/31/2024" +"1970-01-01T00:00:00Z" +"2024-12-31T23:59:59+0100" +"23:59:59" +"12:34:56.789" +"00:00:00" +"a,b" +"\"quoted\"" +"\"with,\"delimiter" +"\"escaped\\\"quote\"" +"\"\"" +"\xc3\xa9" +"\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e" \ No newline at end of file diff --git a/cpp/build-support/fuzzing/generate_corpuses.sh b/cpp/build-support/fuzzing/generate_corpuses.sh index 2d95e110b516..25fa735a51ec 100755 --- a/cpp/build-support/fuzzing/generate_corpuses.sh +++ b/cpp/build-support/fuzzing/generate_corpuses.sh @@ -89,4 +89,25 @@ rm -rf "${CORPUS_DIR}" cp "${ARROW_ROOT}"/testing/data/csv/*.csv "${CORPUS_DIR}" # Add examples from Pandas test suite find "${PANDAS_DIR}/" -name "*.csv" -exec cp --backup=numbered '{}' "${CORPUS_DIR}" \; +# Some Pandas CSV files are exact duplicates of each other under different +# names, and pack_corpus.py fails on duplicate hashes; keep only one copy. +declare -A seen=() +while IFS= read -r -d '' f; do + h=$(sha1sum "$f" | cut -d' ' -f1) + if [[ -n "${seen[$h]}" ]]; then + rm -f "$f" + else + seen[$h]=1 + fi +done < <(find "${CORPUS_DIR}" -maxdepth 1 -type f -print0) + "${ARROW_CPP}/build-support/fuzzing/pack_corpus.py" "${CORPUS_DIR}" "${OUT}/arrow-csv-fuzz_seed_corpus.zip" + +# Fuzz target dictionaries +# +# Dictionaries are shipped under build-support/fuzzing/dicts as +# ".dict" and copied next to the seed corpus zips, so that +# OSS-Fuzz's build script can pick them up like the corpora above. + +find "${ARROW_CPP}/build-support/fuzzing/dicts" -name '*.dict' \ + -exec cp '{}' "${OUT}/" \; diff --git a/cpp/src/arrow/csv/fuzz.cc b/cpp/src/arrow/csv/fuzz.cc index 2219efa2cb59..5c7ce40273ad 100644 --- a/cpp/src/arrow/csv/fuzz.cc +++ b/cpp/src/arrow/csv/fuzz.cc @@ -29,92 +29,160 @@ #include "arrow/util/fuzz_internal.h" #include "arrow/util/macros.h" #include "arrow/util/thread_pool.h" +#include "arrow/util/value_parsing.h" namespace arrow::csv { using ::arrow::internal::GetCpuThreadPool; using ::arrow::io::InputStream; -Status FuzzCsvReader(const uint8_t* data, int64_t size) { - // Since the Fuzz-allocated data is not owned, any task that outlives the TableReader - // may try to read memory that has been deallocated. Hence we wait for all pending - // tasks to end before leaving. - struct TaskGuard { - ~TaskGuard() { GetCpuThreadPool()->WaitForIdle(); } - }; +namespace { - auto io_context = arrow::io::default_io_context(); +// Packed header prefixing the fuzz payload, used to explore the CSV reader's +// option space (see https://github.com/google/oss-fuzz/issues/14437 for why +// fuzz target parameters have to be encoded inside the payload itself). +// +// All option values are total functions of the header bytes, so every possible +// input leads to a well-defined option set. Inputs shorter than the header are +// read with the original hardcoded options, preserving the fuzzer's historical +// behavior on legacy corpus entries. +constexpr int64_t kFuzzHeaderSize = 8; + +struct FuzzCsvOptions { + ReadOptions read; + ParseOptions parse; + ConvertOptions convert; +}; + +FuzzCsvOptions MakeFuzzCsvOptions(const uint8_t* header) { + FuzzCsvOptions opts; + + // --- ParseOptions --- + const char kDelimiters[] = {',', '\t', ';', '|', ' '}; + opts.parse.delimiter = kDelimiters[header[0] % 5]; + opts.parse.quoting = !(header[1] & 1); + opts.parse.quote_char = (header[1] & 2) ? '\'' : '"'; + opts.parse.double_quote = !(header[1] & 4); + opts.parse.escaping = (header[2] & 1); + opts.parse.escape_char = (header[2] & 2) ? '"' : '\\'; + opts.parse.newlines_in_values = (header[4] & 1); + opts.parse.ignore_empty_lines = !(header[4] & 2); + opts.parse.pad_short_rows = (header[4] & 4); + opts.parse.ignore_extra_columns = (header[4] & 8); + + // --- ReadOptions --- + const int32_t kBlockSizes[] = {1024, 4096, 65536, 1 << 20}; + opts.read.block_size = kBlockSizes[(header[3] >> 1) % 4]; + opts.read.use_threads = (header[3] & 1); + opts.read.skip_rows = (header[7] & 1) ? 1 : 0; + opts.read.autogenerate_column_names = (header[7] & 2); + + // --- ConvertOptions --- + opts.convert.strings_can_be_null = (header[5] & 1); + opts.convert.quoted_strings_can_be_null = !(header[5] & 2); + opts.convert.auto_dict_encode = (header[5] & 4); + const int32_t kDictMaxCardinalities[] = {50, 1000, 1000000}; + opts.convert.auto_dict_max_cardinality = kDictMaxCardinalities[(header[5] >> 3) % 3]; + opts.convert.decimal_point = (header[6] & 1) ? ',' : '.'; + opts.convert.check_utf8 = !(header[6] & 2); + if (header[6] & 4) { + opts.convert.timestamp_parsers.push_back(TimestampParser::MakeStrptime("%Y-%m-%d")); + } + if (header[6] & 8) { + opts.convert.timestamp_parsers.push_back(TimestampParser::MakeStrptime("%m/%d/%Y")); + } - auto read_options = ReadOptions::Defaults(); - // Make chunking more likely to exercise chunked reading and optional parallelization. - // Most files in the seed corpus are currently in the 4-10 kB range. - read_options.block_size = 1000; - auto parse_options = ParseOptions::Defaults(); - auto convert_options = ConvertOptions::Defaults(); - convert_options.auto_dict_encode = true; - // This is the default value, but we might want to turn this knob to have a better - // mix of dict-encoded and non-dict-encoded columns when reading. - convert_options.auto_dict_max_cardinality = 50; + return opts; +} - // TODO should we also test non-inferring table read? +Status ReadAllWays(io::IOContext io_context, const FuzzCsvOptions& opts, + std::shared_ptr input) { + Status st; - auto read_table_serial = [=](std::shared_ptr input) mutable -> Status { + // 1. Full table read, single-threaded + { + auto read_options = opts.read; read_options.use_threads = false; - ARROW_ASSIGN_OR_RAISE(auto table_reader, - TableReader::Make(io_context, input, read_options, - parse_options, convert_options)); + ARROW_ASSIGN_OR_RAISE( + auto table_reader, + TableReader::Make(io_context, input, read_options, opts.parse, opts.convert)); ARROW_ASSIGN_OR_RAISE(auto table, table_reader->Read()); - return table->ValidateFull(); - }; + st &= table->ValidateFull(); + } - auto read_table_threaded = [=](std::shared_ptr input) mutable -> Status { + // 2. Full table read, multi-threaded + { + auto read_options = opts.read; read_options.use_threads = true; - ARROW_ASSIGN_OR_RAISE(auto table_reader, - TableReader::Make(io_context, input, read_options, - parse_options, convert_options)); + ARROW_ASSIGN_OR_RAISE( + auto table_reader, + TableReader::Make(io_context, input, read_options, opts.parse, opts.convert)); ARROW_ASSIGN_OR_RAISE(auto table, table_reader->Read()); - return table->ValidateFull(); - }; + st &= table->ValidateFull(); + } - auto read_streaming = [=](std::shared_ptr input) mutable -> Status { + // 3. Streaming (incremental) read + { + auto read_options = opts.read; read_options.use_threads = true; ARROW_ASSIGN_OR_RAISE( - auto reader, StreamingReader::Make(io_context, input, read_options, parse_options, - convert_options)); + auto reader, + StreamingReader::Make(io_context, input, read_options, opts.parse, opts.convert)); ARROW_ASSIGN_OR_RAISE(auto table, reader->ToTable()); - return table->ValidateFull(); - }; + st &= table->ValidateFull(); + } - auto count_rows = [=](std::shared_ptr input) mutable -> Status { - read_options.use_threads = true; - parse_options.newlines_in_values = false; - auto fut = CountRowsAsync(io_context, input, GetCpuThreadPool(), read_options, + // 4. Row counting, with both values for `newlines_in_values` (row counting + // scans rows without conversion, so it exercises parsing on its own) + for (const bool newlines_in_values : {false, true}) { + auto parse_options = opts.parse; + parse_options.newlines_in_values = newlines_in_values; + auto fut = CountRowsAsync(io_context, input, GetCpuThreadPool(), opts.read, parse_options); - return fut.status(); - }; + st &= fut.status(); + } - auto count_rows_allow_newlines = - [=](std::shared_ptr input) mutable -> Status { - read_options.use_threads = true; - parse_options.newlines_in_values = true; - auto fut = CountRowsAsync(io_context, input, GetCpuThreadPool(), read_options, - parse_options); - return fut.status(); + return st; +} + +} // namespace + +Status FuzzCsvReader(const uint8_t* data, int64_t size) { + // Since the Fuzz-allocated data is not owned, any task that outlives the + // TableReader may try to read memory that has been deallocated. Hence we + // wait for all pending tasks to end before leaving. + struct TaskGuard { + ~TaskGuard() { GetCpuThreadPool()->WaitForIdle(); } }; + TaskGuard task_guard; - using ReadFunc = decltype(std::function(read_table_serial)); + auto io_context = arrow::io::default_io_context(); - // Test all reader types regardless of outcome - Status st; - for (auto read_func : {ReadFunc(read_table_serial), ReadFunc(read_table_threaded), - ReadFunc(read_streaming), ReadFunc(count_rows), - ReadFunc(count_rows_allow_newlines)}) { - auto input = - std::make_shared<::arrow::io::BufferReader>(std::make_shared(data, size)); - TaskGuard task_guard; - st &= read_func(input); + FuzzCsvOptions opts; + const uint8_t* payload = data; + int64_t payload_size = size; + if (size >= kFuzzHeaderSize) { + opts = MakeFuzzCsvOptions(data); + payload += kFuzzHeaderSize; + payload_size -= kFuzzHeaderSize; + RETURN_NOT_OK(opts.parse.Validate()); + RETURN_NOT_OK(opts.read.Validate()); + RETURN_NOT_OK(opts.convert.Validate()); + } else { + // Legacy behavior for inputs without a full header: the original + // hardcoded options. Small block sizes make chunking more likely to be + // exercised, as most legacy corpus entries are in the 4-10 kB range. + opts.read = ReadOptions::Defaults(); + opts.read.block_size = 1000; + opts.parse = ParseOptions::Defaults(); + opts.convert = ConvertOptions::Defaults(); + opts.convert.auto_dict_encode = true; + opts.convert.auto_dict_max_cardinality = 50; } - return st; + + return ReadAllWays(io_context, opts, + std::make_shared<::arrow::io::BufferReader>( + std::make_shared(payload, payload_size))); } } // namespace arrow::csv diff --git a/cpp/src/arrow/csv/generate_fuzz_corpus.cc b/cpp/src/arrow/csv/generate_fuzz_corpus.cc index eeba49e87f81..dc369121eb96 100644 --- a/cpp/src/arrow/csv/generate_fuzz_corpus.cc +++ b/cpp/src/arrow/csv/generate_fuzz_corpus.cc @@ -163,18 +163,37 @@ Status DoMain(const std::string& out_dir) { ARROW_ASSIGN_OR_RAISE(auto batches, Batches()); - auto options = WriteOptions::Defaults(); - RETURN_NOT_OK(options.Validate()); + // Generate several dialect variants of each batch, matching the option + // rotations performed by the fuzz target (see csv/fuzz.cc). + std::vector option_variants; + auto append_variant = [&](std::function fn) { + auto options = WriteOptions::Defaults(); + fn(options); + if (options.Validate().ok()) { + option_variants.push_back(std::move(options)); + } + }; + append_variant([](WriteOptions&) {}); + append_variant([](WriteOptions& o) { o.delimiter = ';'; }); + append_variant([](WriteOptions& o) { o.delimiter = '\t'; }); + append_variant([](WriteOptions& o) { o.quoting_style = QuotingStyle::AllValid; }); + append_variant([](WriteOptions& o) { o.include_header = false; }); + // Small batch sizes exercise the writer's chunking and produce files that + // make the reader merge many batches. + append_variant([](WriteOptions& o) { o.batch_size = 7; }); + append_variant([](WriteOptions& o) { o.null_string = "N/A"; }); for (const auto& batch : batches) { RETURN_NOT_OK(batch->ValidateFull()); - ARROW_ASSIGN_OR_RAISE(auto buffer, WriteRecordBatch(batch, options)); - - ARROW_ASSIGN_OR_RAISE(auto sample_fn, dir_fn.Join(sample_name())); - std::cerr << sample_fn.ToString() << std::endl; - ARROW_ASSIGN_OR_RAISE(auto file, io::FileOutputStream::Open(sample_fn.ToString())); - RETURN_NOT_OK(file->Write(buffer)); - RETURN_NOT_OK(file->Close()); + for (const auto& options : option_variants) { + ARROW_ASSIGN_OR_RAISE(auto buffer, WriteRecordBatch(batch, options)); + + ARROW_ASSIGN_OR_RAISE(auto sample_fn, dir_fn.Join(sample_name())); + std::cerr << sample_fn.ToString() << std::endl; + ARROW_ASSIGN_OR_RAISE(auto file, io::FileOutputStream::Open(sample_fn.ToString())); + RETURN_NOT_OK(file->Write(buffer)); + RETURN_NOT_OK(file->Close()); + } } return Status::OK(); } From 787add548a82c3412f3d848689a5d8849f82d935 Mon Sep 17 00:00:00 2001 From: Arthur Chan Date: Fri, 23 Oct 2026 08:47:56 +0100 Subject: [PATCH 2/5] Fix formatting Signed-off-by: Arthur Chan --- cpp/src/arrow/csv/fuzz.cc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cpp/src/arrow/csv/fuzz.cc b/cpp/src/arrow/csv/fuzz.cc index 5c7ce40273ad..beabfc4c8415 100644 --- a/cpp/src/arrow/csv/fuzz.cc +++ b/cpp/src/arrow/csv/fuzz.cc @@ -137,8 +137,8 @@ Status ReadAllWays(io::IOContext io_context, const FuzzCsvOptions& opts, for (const bool newlines_in_values : {false, true}) { auto parse_options = opts.parse; parse_options.newlines_in_values = newlines_in_values; - auto fut = CountRowsAsync(io_context, input, GetCpuThreadPool(), opts.read, - parse_options); + auto fut = + CountRowsAsync(io_context, input, GetCpuThreadPool(), opts.read, parse_options); st &= fut.status(); } From c7da686f3db9dc61fa048b2d1ac913be403ba9a8 Mon Sep 17 00:00:00 2001 From: Arthur Chan Date: Thu, 19 Nov 2026 14:02:41 +0000 Subject: [PATCH 3/5] Address comments Signed-off-by: Arthur Chan --- .../fuzzing/dicts/arrow-csv-fuzz.dict | 6 +- .../fuzzing/generate_corpuses.sh | 16 +- cpp/build-support/fuzzing/pack_corpus.py | 6 +- cpp/src/arrow/csv/fuzz.cc | 190 +++++++++++------- cpp/src/arrow/csv/fuzz_header_internal.h | 172 ++++++++++++++++ cpp/src/arrow/csv/generate_fuzz_corpus.cc | 125 +++++++++--- 6 files changed, 401 insertions(+), 114 deletions(-) create mode 100644 cpp/src/arrow/csv/fuzz_header_internal.h diff --git a/cpp/build-support/fuzzing/dicts/arrow-csv-fuzz.dict b/cpp/build-support/fuzzing/dicts/arrow-csv-fuzz.dict index bbda8108e016..f17d630c896b 100644 --- a/cpp/build-support/fuzzing/dicts/arrow-csv-fuzz.dict +++ b/cpp/build-support/fuzzing/dicts/arrow-csv-fuzz.dict @@ -1,5 +1,9 @@ # Tokens for arrow-csv-fuzz: CSV dialect characters, null/bool spellings, # numeric edge cases and timestamp formats understood by the Arrow CSV reader. +# +# Note that the dictionary only provides hints to the fuzzing engine: inputs +# are not restricted to combinations of these tokens, random mutations are +# still applied on top. "," ";" "\x09" @@ -57,4 +61,4 @@ "\"escaped\\\"quote\"" "\"\"" "\xc3\xa9" -"\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e" \ No newline at end of file +"\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e" diff --git a/cpp/build-support/fuzzing/generate_corpuses.sh b/cpp/build-support/fuzzing/generate_corpuses.sh index 25fa735a51ec..6ca47e0ebcf0 100755 --- a/cpp/build-support/fuzzing/generate_corpuses.sh +++ b/cpp/build-support/fuzzing/generate_corpuses.sh @@ -89,17 +89,8 @@ rm -rf "${CORPUS_DIR}" cp "${ARROW_ROOT}"/testing/data/csv/*.csv "${CORPUS_DIR}" # Add examples from Pandas test suite find "${PANDAS_DIR}/" -name "*.csv" -exec cp --backup=numbered '{}' "${CORPUS_DIR}" \; -# Some Pandas CSV files are exact duplicates of each other under different -# names, and pack_corpus.py fails on duplicate hashes; keep only one copy. -declare -A seen=() -while IFS= read -r -d '' f; do - h=$(sha1sum "$f" | cut -d' ' -f1) - if [[ -n "${seen[$h]}" ]]; then - rm -f "$f" - else - seen[$h]=1 - fi -done < <(find "${CORPUS_DIR}" -maxdepth 1 -type f -print0) +# Note: some of the files above may have duplicate content under different +# names; pack_corpus.py emits a warning and keeps a single copy of them. "${ARROW_CPP}/build-support/fuzzing/pack_corpus.py" "${CORPUS_DIR}" "${OUT}/arrow-csv-fuzz_seed_corpus.zip" @@ -108,6 +99,9 @@ done < <(find "${CORPUS_DIR}" -maxdepth 1 -type f -print0) # Dictionaries are shipped under build-support/fuzzing/dicts as # ".dict" and copied next to the seed corpus zips, so that # OSS-Fuzz's build script can pick them up like the corpora above. +# Note that a dictionary does not restrict the fuzzing engine to generating +# inputs made of these tokens; it is only a set of hints that the fuzzing +# engine may try splicing into the inputs it mutates. find "${ARROW_CPP}/build-support/fuzzing/dicts" -name '*.dict' \ -exec cp '{}' "${OUT}/" \; diff --git a/cpp/build-support/fuzzing/pack_corpus.py b/cpp/build-support/fuzzing/pack_corpus.py index 4480ec514bac..458038b593e8 100755 --- a/cpp/build-support/fuzzing/pack_corpus.py +++ b/cpp/build-support/fuzzing/pack_corpus.py @@ -36,9 +36,9 @@ def process_dir(corpus_dir, zip_output): data = f.read() arcname = hashlib.sha1(data).hexdigest() if arcname in seen_hashes: - raise ValueError( - f"Duplicate hash: {arcname} (in file {child}), " - f"already seen in file {seen_hashes[arcname]}") + print(f" WARNING: {child} has the same content as {seen_hashes[arcname]}, " + "skipping it") + continue print(f" {child} -> {arcname}") zip_output.writestr(str(arcname), data) seen_hashes[arcname] = child diff --git a/cpp/src/arrow/csv/fuzz.cc b/cpp/src/arrow/csv/fuzz.cc index beabfc4c8415..a22061ee8756 100644 --- a/cpp/src/arrow/csv/fuzz.cc +++ b/cpp/src/arrow/csv/fuzz.cc @@ -15,19 +15,22 @@ // specific language governing permissions and limitations // under the License. +#include #include -#include #include -#include +#include +#include #include "arrow/buffer.h" +#include "arrow/compare.h" +#include "arrow/csv/fuzz_header_internal.h" #include "arrow/csv/reader.h" #include "arrow/io/interfaces.h" #include "arrow/io/memory.h" #include "arrow/status.h" #include "arrow/table.h" #include "arrow/util/fuzz_internal.h" -#include "arrow/util/macros.h" +#include "arrow/util/logging.h" #include "arrow/util/thread_pool.h" #include "arrow/util/value_parsing.h" @@ -38,107 +41,144 @@ using ::arrow::io::InputStream; namespace { -// Packed header prefixing the fuzz payload, used to explore the CSV reader's -// option space (see https://github.com/google/oss-fuzz/issues/14437 for why -// fuzz target parameters have to be encoded inside the payload itself). -// -// All option values are total functions of the header bytes, so every possible -// input leads to a well-defined option set. Inputs shorter than the header are -// read with the original hardcoded options, preserving the fuzzer's historical -// behavior on legacy corpus entries. -constexpr int64_t kFuzzHeaderSize = 8; - struct FuzzCsvOptions { ReadOptions read; ParseOptions parse; ConvertOptions convert; }; -FuzzCsvOptions MakeFuzzCsvOptions(const uint8_t* header) { +FuzzCsvOptions MakeFuzzCsvOptions(const internal::FuzzCsvHeader& header) { FuzzCsvOptions opts; // --- ParseOptions --- - const char kDelimiters[] = {',', '\t', ';', '|', ' '}; - opts.parse.delimiter = kDelimiters[header[0] % 5]; - opts.parse.quoting = !(header[1] & 1); - opts.parse.quote_char = (header[1] & 2) ? '\'' : '"'; - opts.parse.double_quote = !(header[1] & 4); - opts.parse.escaping = (header[2] & 1); - opts.parse.escape_char = (header[2] & 2) ? '"' : '\\'; - opts.parse.newlines_in_values = (header[4] & 1); - opts.parse.ignore_empty_lines = !(header[4] & 2); - opts.parse.pad_short_rows = (header[4] & 4); - opts.parse.ignore_extra_columns = (header[4] & 8); + // The "id" fields store an index in the corresponding candidate arrays, + // modulo the array length (see csv/fuzz_header_internal.h). + opts.parse.delimiter = + internal::kFuzzCsvDelimiters[header.parse_1.delimiter_id % + internal::kFuzzCsvDelimiters.size()]; + opts.parse.quoting = header.parse_1.quoting; + opts.parse.quote_char = + internal::kFuzzCsvQuoteChars[header.parse_1.quote_char_id % + internal::kFuzzCsvQuoteChars.size()]; + opts.parse.double_quote = header.parse_1.double_quote; + opts.parse.escaping = header.parse_1.escaping; + opts.parse.escape_char = + internal::kFuzzCsvEscapeChars[header.parse_1.escape_char_id % + internal::kFuzzCsvEscapeChars.size()]; + opts.parse.newlines_in_values = header.parse_2.newlines_in_values; + opts.parse.ignore_empty_lines = header.parse_2.ignore_empty_lines; + opts.parse.pad_short_rows = header.parse_2.pad_short_rows; + opts.parse.ignore_extra_columns = header.parse_2.ignore_extra_columns; // --- ReadOptions --- - const int32_t kBlockSizes[] = {1024, 4096, 65536, 1 << 20}; - opts.read.block_size = kBlockSizes[(header[3] >> 1) % 4]; - opts.read.use_threads = (header[3] & 1); - opts.read.skip_rows = (header[7] & 1) ? 1 : 0; - opts.read.autogenerate_column_names = (header[7] & 2); + opts.read.block_size = + internal::kFuzzCsvBlockSizes[header.read.block_size_id % + internal::kFuzzCsvBlockSizes.size()]; + opts.read.use_threads = header.read.use_threads; + opts.read.skip_rows = header.read.skip_rows; + opts.read.autogenerate_column_names = header.read.autogenerate_column_names; // --- ConvertOptions --- - opts.convert.strings_can_be_null = (header[5] & 1); - opts.convert.quoted_strings_can_be_null = !(header[5] & 2); - opts.convert.auto_dict_encode = (header[5] & 4); - const int32_t kDictMaxCardinalities[] = {50, 1000, 1000000}; - opts.convert.auto_dict_max_cardinality = kDictMaxCardinalities[(header[5] >> 3) % 3]; - opts.convert.decimal_point = (header[6] & 1) ? ',' : '.'; - opts.convert.check_utf8 = !(header[6] & 2); - if (header[6] & 4) { + opts.convert = ConvertOptions::Defaults(); + opts.convert.strings_can_be_null = header.convert_1.strings_can_be_null; + opts.convert.quoted_strings_can_be_null = header.convert_1.quoted_strings_can_be_null; + opts.convert.auto_dict_encode = header.convert_1.auto_dict_encode; + opts.convert.auto_dict_max_cardinality = internal::kFuzzCsvDictMaxCardinalities + [header.convert_1.auto_dict_max_cardinality_id % + internal::kFuzzCsvDictMaxCardinalities.size()]; + opts.convert.decimal_point = header.convert_1.decimal_point_is_comma ? ',' : '.'; + opts.convert.check_utf8 = header.convert_1.check_utf8; + if (header.convert_1.add_strptime_ymd_parser) { opts.convert.timestamp_parsers.push_back(TimestampParser::MakeStrptime("%Y-%m-%d")); } - if (header[6] & 8) { + if (header.convert_2.add_strptime_mdy_parser) { opts.convert.timestamp_parsers.push_back(TimestampParser::MakeStrptime("%m/%d/%Y")); } return opts; } +// Read the payload using several complementary reading strategies. +// Each strategy is given a fresh input stream, as a reader consumes the +// stream that it is passed. Status ReadAllWays(io::IOContext io_context, const FuzzCsvOptions& opts, - std::shared_ptr input) { + std::span payload) { Status st; + auto make_input = [&]() -> std::shared_ptr { + return std::make_shared<::arrow::io::BufferReader>( + std::make_shared(payload.data(), static_cast(payload.size()))); + }; + + // The tables read below are kept around for differential testing. + std::shared_ptr serial_table, threaded_table, streaming_table; + // 1. Full table read, single-threaded - { + auto read_table_serial = [&]() -> Status { auto read_options = opts.read; read_options.use_threads = false; - ARROW_ASSIGN_OR_RAISE( - auto table_reader, - TableReader::Make(io_context, input, read_options, opts.parse, opts.convert)); - ARROW_ASSIGN_OR_RAISE(auto table, table_reader->Read()); - st &= table->ValidateFull(); - } + ARROW_ASSIGN_OR_RAISE(auto table_reader, + TableReader::Make(io_context, make_input(), read_options, + opts.parse, opts.convert)); + ARROW_ASSIGN_OR_RAISE(serial_table, table_reader->Read()); + return serial_table->ValidateFull(); + }; // 2. Full table read, multi-threaded - { + auto read_table_threaded = [&]() -> Status { auto read_options = opts.read; read_options.use_threads = true; - ARROW_ASSIGN_OR_RAISE( - auto table_reader, - TableReader::Make(io_context, input, read_options, opts.parse, opts.convert)); - ARROW_ASSIGN_OR_RAISE(auto table, table_reader->Read()); - st &= table->ValidateFull(); - } + ARROW_ASSIGN_OR_RAISE(auto table_reader, + TableReader::Make(io_context, make_input(), read_options, + opts.parse, opts.convert)); + ARROW_ASSIGN_OR_RAISE(threaded_table, table_reader->Read()); + return threaded_table->ValidateFull(); + }; // 3. Streaming (incremental) read - { + auto read_streaming = [&]() -> Status { auto read_options = opts.read; read_options.use_threads = true; - ARROW_ASSIGN_OR_RAISE( - auto reader, - StreamingReader::Make(io_context, input, read_options, opts.parse, opts.convert)); - ARROW_ASSIGN_OR_RAISE(auto table, reader->ToTable()); - st &= table->ValidateFull(); + ARROW_ASSIGN_OR_RAISE(auto reader, + StreamingReader::Make(io_context, make_input(), read_options, + opts.parse, opts.convert)); + ARROW_ASSIGN_OR_RAISE(streaming_table, reader->ToTable()); + return streaming_table->ValidateFull(); + }; + + // Test all reader types regardless of outcome + st &= read_table_serial(); + st &= read_table_threaded(); + st &= read_streaming(); + + // 4. Differential test: if all three table reads above succeeded, they + // should return equal tables (comparison ignores chunking, and NaN + // values compare equal as they parse deterministically). Any mismatch + // is a reader bug, so abort, like the Parquet encoding fuzzer does. + if (serial_table && threaded_table && streaming_table) { + auto equal_options = EqualOptions{}.nans_equal(true); + if (!serial_table->Equals(*threaded_table, equal_options) || + !serial_table->Equals(*streaming_table, equal_options)) { + std::stringstream ss; + ss << "CSV reader inconsistency detected: the tables returned by the\n" + << "single-threaded, multi-threaded and streaming CSV readers differ.\n" + << " serial schema: " << serial_table->schema()->ToString() << "\n" + << " threaded schema: " << threaded_table->schema()->ToString() << "\n" + << " streaming schema: " << streaming_table->schema()->ToString() << "\n" + << " serial rows: " << serial_table->num_rows() + << ", threaded rows: " << threaded_table->num_rows() + << ", streaming rows: " << streaming_table->num_rows(); + ARROW_CHECK_OK(Status::Invalid(ss.str())); + } } - // 4. Row counting, with both values for `newlines_in_values` (row counting + // 5. Row counting, with both values for `newlines_in_values` (row counting // scans rows without conversion, so it exercises parsing on its own) for (const bool newlines_in_values : {false, true}) { auto parse_options = opts.parse; parse_options.newlines_in_values = newlines_in_values; - auto fut = - CountRowsAsync(io_context, input, GetCpuThreadPool(), opts.read, parse_options); + auto fut = CountRowsAsync(io_context, make_input(), GetCpuThreadPool(), opts.read, + parse_options); st &= fut.status(); } @@ -158,20 +198,22 @@ Status FuzzCsvReader(const uint8_t* data, int64_t size) { auto io_context = arrow::io::default_io_context(); + std::span input(data, static_cast(size)); + std::span payload = input; FuzzCsvOptions opts; - const uint8_t* payload = data; - int64_t payload_size = size; - if (size >= kFuzzHeaderSize) { - opts = MakeFuzzCsvOptions(data); - payload += kFuzzHeaderSize; - payload_size -= kFuzzHeaderSize; + + auto maybe_header = internal::ParseFuzzCsvHeader(input); + if (maybe_header.ok()) { + opts = MakeFuzzCsvOptions(*maybe_header); + payload = input.subspan(internal::kFuzzCsvHeaderSize); RETURN_NOT_OK(opts.parse.Validate()); RETURN_NOT_OK(opts.read.Validate()); RETURN_NOT_OK(opts.convert.Validate()); } else { - // Legacy behavior for inputs without a full header: the original - // hardcoded options. Small block sizes make chunking more likely to be - // exercised, as most legacy corpus entries are in the 4-10 kB range. + // Legacy behavior for inputs that don't start with the expected magic + // (e.g. legacy corpus entries): the original hardcoded options. Small + // block sizes make chunking more likely to be exercised, as most legacy + // corpus entries are in the 4-10 kB range. opts.read = ReadOptions::Defaults(); opts.read.block_size = 1000; opts.parse = ParseOptions::Defaults(); @@ -180,9 +222,7 @@ Status FuzzCsvReader(const uint8_t* data, int64_t size) { opts.convert.auto_dict_max_cardinality = 50; } - return ReadAllWays(io_context, opts, - std::make_shared<::arrow::io::BufferReader>( - std::make_shared(payload, payload_size))); + return ReadAllWays(io_context, opts, payload); } } // namespace arrow::csv diff --git a/cpp/src/arrow/csv/fuzz_header_internal.h b/cpp/src/arrow/csv/fuzz_header_internal.h new file mode 100644 index 000000000000..3831332110d2 --- /dev/null +++ b/cpp/src/arrow/csv/fuzz_header_internal.h @@ -0,0 +1,172 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include +#include +#include + +#include "arrow/result.h" +#include "arrow/status.h" +#include "arrow/util/macros.h" + +namespace arrow::csv::internal { + +// The CSV fuzz target prepends a packed header to the fuzz payload to explore +// the CSV reader's option space (see +// https://github.com/google/oss-fuzz/issues/14437 for why fuzz target +// parameters have to be encoded inside the payload itself). +// +// The header starts with a magic number so that the fuzz target can detect +// whether an input was generated with this scheme. If the magic number +// matches, the header is parsed and the rest of the payload is read with the +// corresponding options. Otherwise (e.g. for legacy corpus entries), the +// whole input is read with the fuzzer's historical hardcoded options. + +constexpr auto kFuzzCsvHeaderSize = 16; + +inline constexpr std::array kFuzzCsvMagic = {'A', 'R', 'R', 'O', + 'W', 'C', 'S', 'V'}; + +// Candidate values for the options encoded in FuzzCsvHeader below. The +// corresponding option fields store an index in these arrays (modulo the +// array length, so that all header values lead to a well-defined option set). +inline constexpr std::array kFuzzCsvDelimiters = {',', '\t', ';', '|', ' '}; +inline constexpr std::array kFuzzCsvQuoteChars = {'"', '\''}; +inline constexpr std::array kFuzzCsvEscapeChars = {'\\', '"'}; +inline constexpr std::array kFuzzCsvBlockSizes = {1024, 4096, 65536, 1 << 20}; +inline constexpr std::array kFuzzCsvDictMaxCardinalities = {50, 1000, + 1000000}; + +// NOTE: The option bit-fields are grouped into dedicated packed structures +// of one byte each (verified by the static_asserts below), so that the +// layout is unambiguous. +ARROW_PACKED_START(struct, FuzzCsvParseGroup1) { + // Index (modulo length) in kFuzzCsvDelimiters + uint8_t delimiter_id : 3; + uint8_t quoting : 1; + // Index in kFuzzCsvQuoteChars + uint8_t quote_char_id : 1; + uint8_t double_quote : 1; + uint8_t escaping : 1; + // Index in kFuzzCsvEscapeChars + uint8_t escape_char_id : 1; +}; +ARROW_PACKED_END + +ARROW_PACKED_START(struct, FuzzCsvParseGroup2) { + uint8_t newlines_in_values : 1; + uint8_t ignore_empty_lines : 1; + uint8_t pad_short_rows : 1; + uint8_t ignore_extra_columns : 1; + uint8_t reserved_1 : 4; +}; +ARROW_PACKED_END + +ARROW_PACKED_START(struct, FuzzCsvReadGroup) { + // Index (modulo length) in kFuzzCsvBlockSizes + uint8_t block_size_id : 2; + uint8_t use_threads : 1; + // 0 or 1 + uint8_t skip_rows : 1; + uint8_t autogenerate_column_names : 1; + uint8_t reserved_2 : 3; +}; +ARROW_PACKED_END + +ARROW_PACKED_START(struct, FuzzCsvConvertGroup1) { + uint8_t strings_can_be_null : 1; + uint8_t quoted_strings_can_be_null : 1; + uint8_t auto_dict_encode : 1; + // Index (modulo length) in kFuzzCsvDictMaxCardinalities + uint8_t auto_dict_max_cardinality_id : 2; + // 0: '.', 1: ',' + uint8_t decimal_point_is_comma : 1; + uint8_t check_utf8 : 1; + // Add a strptime timestamp parser with the "%Y-%m-%d" format + uint8_t add_strptime_ymd_parser : 1; +}; +ARROW_PACKED_END + +ARROW_PACKED_START(struct, FuzzCsvConvertGroup2) { + // Add a strptime timestamp parser with the "%m/%d/%Y" format + uint8_t add_strptime_mdy_parser : 1; + uint8_t reserved_3 : 7; +}; +ARROW_PACKED_END + +static_assert(sizeof(FuzzCsvParseGroup1) == 1, "FuzzCsvParseGroup1 not packed"); +static_assert(sizeof(FuzzCsvParseGroup2) == 1, "FuzzCsvParseGroup2 not packed"); +static_assert(sizeof(FuzzCsvReadGroup) == 1, "FuzzCsvReadGroup not packed"); +static_assert(sizeof(FuzzCsvConvertGroup1) == 1, "FuzzCsvConvertGroup1 not packed"); +static_assert(sizeof(FuzzCsvConvertGroup2) == 1, "FuzzCsvConvertGroup2 not packed"); + +ARROW_PACKED_START(struct, FuzzCsvHeader) { + char magic[kFuzzCsvMagic.size()]; + FuzzCsvParseGroup1 parse_1; + FuzzCsvParseGroup2 parse_2; + FuzzCsvReadGroup read; + FuzzCsvConvertGroup1 convert_1; + FuzzCsvConvertGroup2 convert_2; + // Unused bytes, should be zero + std::array reserved; +}; +ARROW_PACKED_END + +static_assert(sizeof(FuzzCsvHeader) == kFuzzCsvHeaderSize, + "FuzzCsvHeader not packed to the expected size"); + +// Fill in the magic number in `header` (all serialized headers should start +// with it). +inline void SetFuzzCsvMagic(FuzzCsvHeader& header) { + std::memcpy(header.magic, kFuzzCsvMagic.data(), kFuzzCsvMagic.size()); +} + +// Serialize the header, for prepending to a fuzz payload (e.g. when +// generating seed corpus files). +inline std::string SerializeFuzzCsvHeader(const FuzzCsvHeader& header) { + return std::string(reinterpret_cast(&header), kFuzzCsvHeaderSize); +} + +// Parse and validate the header at the beginning of `payload`. +// Status::Invalid is returned if the payload is too small, or if it doesn't +// start with the expected magic and padding (e.g. for a legacy input). +inline Result ParseFuzzCsvHeader(std::span payload) { + auto invalid_payload = [] { + return Status::Invalid("Invalid CSV fuzz payload header"); + }; + + if (payload.size() < kFuzzCsvHeaderSize) { + return invalid_payload(); + } + FuzzCsvHeader header; + std::memcpy(&header, payload.data(), kFuzzCsvHeaderSize); + // We are strict in what we accept because we don't want the fuzzer to + // explore pointless variations. + if (std::memcmp(header.magic, kFuzzCsvMagic.data(), kFuzzCsvMagic.size()) != 0 || + header.parse_2.reserved_1 != 0 || header.read.reserved_2 != 0 || + header.convert_2.reserved_3 != 0 || + header.reserved != decltype(header.reserved){}) { + return invalid_payload(); + } + return header; +} + +} // namespace arrow::csv::internal \ No newline at end of file diff --git a/cpp/src/arrow/csv/generate_fuzz_corpus.cc b/cpp/src/arrow/csv/generate_fuzz_corpus.cc index dc369121eb96..f78af07572b0 100644 --- a/cpp/src/arrow/csv/generate_fuzz_corpus.cc +++ b/cpp/src/arrow/csv/generate_fuzz_corpus.cc @@ -15,20 +15,26 @@ // specific language governing permissions and limitations // under the License. -// A command line executable that generates a bunch of valid IPC files -// containing example record batches. Those are used as fuzzing seeds -// to make fuzzing more efficient. +// A command line executable that generates a bunch of valid CSV files +// containing example record batches. Each file is prefixed with a serialized +// CSV fuzz header (see csv/fuzz_header_internal.h) encoding the reader +// options matching the dialect used for writing. Those are used as fuzzing +// seeds to make fuzzing more efficient. +#include +#include #include #include #include #include #include +#include #include #include "arrow/array.h" #include "arrow/array/util.h" #include "arrow/compute/cast.h" +#include "arrow/csv/fuzz_header_internal.h" #include "arrow/csv/options.h" #include "arrow/csv/writer.h" #include "arrow/io/file.h" @@ -152,6 +158,93 @@ Result Batches() { return batches; } +namespace { + +// Default fuzz header values, matching the default CSV reader options +// (see ParseOptions, ReadOptions and ConvertOptions in csv/options.h). +internal::FuzzCsvHeader MakeDefaultFuzzCsvHeader() { + internal::FuzzCsvHeader header{}; + internal::SetFuzzCsvMagic(header); + // --- ParseOptions defaults --- + header.parse_1.delimiter_id = 0; // ',' + header.parse_1.quoting = 1; + header.parse_1.quote_char_id = 0; // '"' + header.parse_1.double_quote = 1; + header.parse_1.escaping = 0; + header.parse_1.escape_char_id = 0; // '\\' + header.parse_2.newlines_in_values = 0; + header.parse_2.ignore_empty_lines = 1; + header.parse_2.pad_short_rows = 0; + header.parse_2.ignore_extra_columns = 0; + // --- ReadOptions defaults --- + header.read.block_size_id = 3; // 1 << 20 (the default block size) + header.read.use_threads = 1; + header.read.skip_rows = 0; + header.read.autogenerate_column_names = 0; + // --- ConvertOptions defaults --- + header.convert_1.strings_can_be_null = 0; + header.convert_1.quoted_strings_can_be_null = 1; + header.convert_1.auto_dict_encode = 0; + header.convert_1.auto_dict_max_cardinality_id = 0; // 50 + header.convert_1.decimal_point_is_comma = 0; // '.' + header.convert_1.check_utf8 = 1; + return header; +} + +// Index of `delimiter` in the candidate delimiters of the fuzz header +uint8_t FuzzDelimiterId(char delimiter) { + auto it = std::find(internal::kFuzzCsvDelimiters.begin(), + internal::kFuzzCsvDelimiters.end(), delimiter); + return static_cast(it - internal::kFuzzCsvDelimiters.begin()); +} + +using WriteAndHeaderOptions = std::pair; + +// Generate several dialect variants of each batch, matching the option +// rotations performed by the fuzz target (see csv/fuzz.cc). For each +// variant, also compute the fuzz header encoding the reader options that +// match the writing dialect. +std::vector SampleVariants() { + std::vector variants; + auto append_variant = [&](std::function write_fn, + std::function header_fn) { + auto write_options = WriteOptions::Defaults(); + write_fn(write_options); + auto validation_st = write_options.Validate(); + if (!validation_st.ok()) { + std::cerr << "Skipping invalid write options: " << validation_st.ToString() + << std::endl; + return; + } + auto header = MakeDefaultFuzzCsvHeader(); + header_fn(header); + variants.emplace_back(std::move(write_options), std::move(header)); + }; + // Default dialect + append_variant([](WriteOptions&) {}, [](internal::FuzzCsvHeader&) {}); + // Alternate delimiters + append_variant( + [](WriteOptions& o) { o.delimiter = ';'; }, + [](internal::FuzzCsvHeader& h) { h.parse_1.delimiter_id = FuzzDelimiterId(';'); }); + append_variant( + [](WriteOptions& o) { o.delimiter = '\t'; }, + [](internal::FuzzCsvHeader& h) { h.parse_1.delimiter_id = FuzzDelimiterId('\t'); }); + // Quote all values (the writer uses '"' as the quoting character) + append_variant([](WriteOptions& o) { o.quoting_style = QuotingStyle::AllValid; }, + [](internal::FuzzCsvHeader&) {}); + // No header row, and let the reader autogenerate column names + append_variant( + [](WriteOptions& o) { o.include_header = false; }, + [](internal::FuzzCsvHeader& h) { h.read.autogenerate_column_names = 1; }); + // Write nulls as "N/A", and let the reader parse them as nulls + // ("N/A" is one of the default null spellings in ConvertOptions) + append_variant([](WriteOptions& o) { o.null_string = "N/A"; }, + [](internal::FuzzCsvHeader& h) { h.convert_1.strings_can_be_null = 1; }); + return variants; +} + +} // namespace + Status DoMain(const std::string& out_dir) { ARROW_ASSIGN_OR_RAISE(auto dir_fn, PlatformFilename::FromString(out_dir)); RETURN_NOT_OK(CreateDir(dir_fn)); @@ -162,35 +255,19 @@ Status DoMain(const std::string& out_dir) { }; ARROW_ASSIGN_OR_RAISE(auto batches, Batches()); - - // Generate several dialect variants of each batch, matching the option - // rotations performed by the fuzz target (see csv/fuzz.cc). - std::vector option_variants; - auto append_variant = [&](std::function fn) { - auto options = WriteOptions::Defaults(); - fn(options); - if (options.Validate().ok()) { - option_variants.push_back(std::move(options)); - } - }; - append_variant([](WriteOptions&) {}); - append_variant([](WriteOptions& o) { o.delimiter = ';'; }); - append_variant([](WriteOptions& o) { o.delimiter = '\t'; }); - append_variant([](WriteOptions& o) { o.quoting_style = QuotingStyle::AllValid; }); - append_variant([](WriteOptions& o) { o.include_header = false; }); - // Small batch sizes exercise the writer's chunking and produce files that - // make the reader merge many batches. - append_variant([](WriteOptions& o) { o.batch_size = 7; }); - append_variant([](WriteOptions& o) { o.null_string = "N/A"; }); + const auto option_variants = SampleVariants(); for (const auto& batch : batches) { RETURN_NOT_OK(batch->ValidateFull()); - for (const auto& options : option_variants) { + for (const auto& [options, header] : option_variants) { ARROW_ASSIGN_OR_RAISE(auto buffer, WriteRecordBatch(batch, options)); + const std::string header_str = internal::SerializeFuzzCsvHeader(header); ARROW_ASSIGN_OR_RAISE(auto sample_fn, dir_fn.Join(sample_name())); std::cerr << sample_fn.ToString() << std::endl; ARROW_ASSIGN_OR_RAISE(auto file, io::FileOutputStream::Open(sample_fn.ToString())); + RETURN_NOT_OK( + file->Write(header_str.data(), static_cast(header_str.size()))); RETURN_NOT_OK(file->Write(buffer)); RETURN_NOT_OK(file->Close()); } From e7d0cf71fab518a72d5e5ee29d05b6394b5f0db5 Mon Sep 17 00:00:00 2001 From: Arthur Chan Date: Tue, 24 Nov 2026 10:43:24 +0000 Subject: [PATCH 4/5] Address comments Signed-off-by: Arthur Chan --- cpp/src/arrow/csv/fuzz.cc | 30 ++++++----- cpp/src/arrow/csv/fuzz_header_internal.h | 16 +++--- cpp/src/arrow/csv/generate_fuzz_corpus.cc | 63 +++++++++++++---------- 3 files changed, 60 insertions(+), 49 deletions(-) diff --git a/cpp/src/arrow/csv/fuzz.cc b/cpp/src/arrow/csv/fuzz.cc index a22061ee8756..5b26bd14e1da 100644 --- a/cpp/src/arrow/csv/fuzz.cc +++ b/cpp/src/arrow/csv/fuzz.cc @@ -53,9 +53,9 @@ FuzzCsvOptions MakeFuzzCsvOptions(const internal::FuzzCsvHeader& header) { // --- ParseOptions --- // The "id" fields store an index in the corresponding candidate arrays, // modulo the array length (see csv/fuzz_header_internal.h). - opts.parse.delimiter = - internal::kFuzzCsvDelimiters[header.parse_1.delimiter_id % - internal::kFuzzCsvDelimiters.size()]; + opts.parse.delimiter_string = + std::string(internal::kFuzzCsvDelimiters[header.parse_1.delimiter_id % + internal::kFuzzCsvDelimiters.size()]); opts.parse.quoting = header.parse_1.quoting; opts.parse.quote_char = internal::kFuzzCsvQuoteChars[header.parse_1.quote_char_id % @@ -71,10 +71,9 @@ FuzzCsvOptions MakeFuzzCsvOptions(const internal::FuzzCsvHeader& header) { opts.parse.ignore_extra_columns = header.parse_2.ignore_extra_columns; // --- ReadOptions --- - opts.read.block_size = - internal::kFuzzCsvBlockSizes[header.read.block_size_id % - internal::kFuzzCsvBlockSizes.size()]; - opts.read.use_threads = header.read.use_threads; + // Block size and threading are deliberately not encoded in the header: + // they are read-side knobs that do not affect the CSV bytes being read, + // and the target varies them itself in ReadAllWays() below. opts.read.skip_rows = header.read.skip_rows; opts.read.autogenerate_column_names = header.read.autogenerate_column_names; @@ -113,10 +112,13 @@ Status ReadAllWays(io::IOContext io_context, const FuzzCsvOptions& opts, // The tables read below are kept around for differential testing. std::shared_ptr
serial_table, threaded_table, streaming_table; - // 1. Full table read, single-threaded + // 1. Full table read, single-threaded, with a small block size: chunking + // is stressed harder, and the differential test below checks that the + // block size and threading settings do not change the parsed output. auto read_table_serial = [&]() -> Status { auto read_options = opts.read; read_options.use_threads = false; + read_options.block_size = 64; ARROW_ASSIGN_OR_RAISE(auto table_reader, TableReader::Make(io_context, make_input(), read_options, opts.parse, opts.convert)); @@ -124,10 +126,11 @@ Status ReadAllWays(io::IOContext io_context, const FuzzCsvOptions& opts, return serial_table->ValidateFull(); }; - // 2. Full table read, multi-threaded + // 2. Full table read, multi-threaded, with a larger block size auto read_table_threaded = [&]() -> Status { auto read_options = opts.read; read_options.use_threads = true; + read_options.block_size = 16384; ARROW_ASSIGN_OR_RAISE(auto table_reader, TableReader::Make(io_context, make_input(), read_options, opts.parse, opts.convert)); @@ -172,9 +175,12 @@ Status ReadAllWays(io::IOContext io_context, const FuzzCsvOptions& opts, } } - // 5. Row counting, with both values for `newlines_in_values` (row counting - // scans rows without conversion, so it exercises parsing on its own) - for (const bool newlines_in_values : {false, true}) { + // 5. Row counting, with the header's newlines_in_values value and its + // opposite (row counting scans rows without conversion, so it + // exercises parsing on its own) + const bool header_newlines_in_values = opts.parse.newlines_in_values; + for (const bool newlines_in_values : + {header_newlines_in_values, !header_newlines_in_values}) { auto parse_options = opts.parse; parse_options.newlines_in_values = newlines_in_values; auto fut = CountRowsAsync(io_context, make_input(), GetCpuThreadPool(), opts.read, diff --git a/cpp/src/arrow/csv/fuzz_header_internal.h b/cpp/src/arrow/csv/fuzz_header_internal.h index 3831332110d2..9076880a9218 100644 --- a/cpp/src/arrow/csv/fuzz_header_internal.h +++ b/cpp/src/arrow/csv/fuzz_header_internal.h @@ -48,12 +48,13 @@ inline constexpr std::array kFuzzCsvMagic = {'A', 'R', 'R', 'O', // Candidate values for the options encoded in FuzzCsvHeader below. The // corresponding option fields store an index in these arrays (modulo the // array length, so that all header values lead to a well-defined option set). -inline constexpr std::array kFuzzCsvDelimiters = {',', '\t', ';', '|', ' '}; +inline constexpr std::array kFuzzCsvDelimiters = { + ",", "\t", ";", "|", " ", "@@"}; inline constexpr std::array kFuzzCsvQuoteChars = {'"', '\''}; inline constexpr std::array kFuzzCsvEscapeChars = {'\\', '"'}; -inline constexpr std::array kFuzzCsvBlockSizes = {1024, 4096, 65536, 1 << 20}; -inline constexpr std::array kFuzzCsvDictMaxCardinalities = {50, 1000, - 1000000}; +// Small cardinality thresholds exercise dictionary truncation and fallback +// more often than large ones. +inline constexpr std::array kFuzzCsvDictMaxCardinalities = {5, 20, 100}; // NOTE: The option bit-fields are grouped into dedicated packed structures // of one byte each (verified by the static_asserts below), so that the @@ -81,13 +82,10 @@ ARROW_PACKED_START(struct, FuzzCsvParseGroup2) { ARROW_PACKED_END ARROW_PACKED_START(struct, FuzzCsvReadGroup) { - // Index (modulo length) in kFuzzCsvBlockSizes - uint8_t block_size_id : 2; - uint8_t use_threads : 1; // 0 or 1 uint8_t skip_rows : 1; uint8_t autogenerate_column_names : 1; - uint8_t reserved_2 : 3; + uint8_t reserved_2 : 6; }; ARROW_PACKED_END @@ -169,4 +167,4 @@ inline Result ParseFuzzCsvHeader(std::span payload return header; } -} // namespace arrow::csv::internal \ No newline at end of file +} // namespace arrow::csv::internal diff --git a/cpp/src/arrow/csv/generate_fuzz_corpus.cc b/cpp/src/arrow/csv/generate_fuzz_corpus.cc index f78af07572b0..8845fddd9043 100644 --- a/cpp/src/arrow/csv/generate_fuzz_corpus.cc +++ b/cpp/src/arrow/csv/generate_fuzz_corpus.cc @@ -38,6 +38,7 @@ #include "arrow/csv/options.h" #include "arrow/csv/writer.h" #include "arrow/io/file.h" +#include "arrow/util/logging.h" #include "arrow/io/memory.h" #include "arrow/ipc/writer.h" #include "arrow/json/from_string.h" @@ -177,8 +178,8 @@ internal::FuzzCsvHeader MakeDefaultFuzzCsvHeader() { header.parse_2.pad_short_rows = 0; header.parse_2.ignore_extra_columns = 0; // --- ReadOptions defaults --- - header.read.block_size_id = 3; // 1 << 20 (the default block size) - header.read.use_threads = 1; + // Block size and threading are not part of the header: they do not affect + // the CSV bytes and the fuzz target varies them itself. header.read.skip_rows = 0; header.read.autogenerate_column_names = 0; // --- ConvertOptions defaults --- @@ -192,11 +193,30 @@ internal::FuzzCsvHeader MakeDefaultFuzzCsvHeader() { } // Index of `delimiter` in the candidate delimiters of the fuzz header -uint8_t FuzzDelimiterId(char delimiter) { +uint8_t FuzzDelimiterId(std::string_view delimiter) { auto it = std::find(internal::kFuzzCsvDelimiters.begin(), internal::kFuzzCsvDelimiters.end(), delimiter); return static_cast(it - internal::kFuzzCsvDelimiters.begin()); } +// Build the fuzz header for a set of write options: the parse and convert +// fields mirror the dialect that the writer will produce, and the read-side +// fields keep their defaults (block size and threading are varied by the +// fuzz target itself). +internal::FuzzCsvHeader MakeFuzzCsvHeaderFromWriteOptions( + const WriteOptions& o) { + internal::FuzzCsvHeader header = MakeDefaultFuzzCsvHeader(); + header.parse_1.delimiter_id = FuzzDelimiterId(std::string(1, o.delimiter)); + if (!o.include_header) { + // No header row was written, so the reader must autogenerate the + // column names it will read back. + header.read.autogenerate_column_names = 1; + } + if (!o.null_string.empty()) { + // The reader must parse the written null spelling as nulls. + header.convert_1.strings_can_be_null = 1; + } + return header; +} using WriteAndHeaderOptions = std::pair; @@ -206,40 +226,27 @@ using WriteAndHeaderOptions = std::pair; // match the writing dialect. std::vector SampleVariants() { std::vector variants; - auto append_variant = [&](std::function write_fn, - std::function header_fn) { + auto append_variant = [&](std::function write_fn) { auto write_options = WriteOptions::Defaults(); write_fn(write_options); - auto validation_st = write_options.Validate(); - if (!validation_st.ok()) { - std::cerr << "Skipping invalid write options: " << validation_st.ToString() - << std::endl; - return; - } - auto header = MakeDefaultFuzzCsvHeader(); - header_fn(header); - variants.emplace_back(std::move(write_options), std::move(header)); + // An invalid set of write options is a bug in this generator, not + // something to skip silently. + ARROW_CHECK_OK(write_options.Validate()); + variants.emplace_back(std::move(write_options), + MakeFuzzCsvHeaderFromWriteOptions(write_options)); }; // Default dialect - append_variant([](WriteOptions&) {}, [](internal::FuzzCsvHeader&) {}); + append_variant([](WriteOptions&) {}); // Alternate delimiters - append_variant( - [](WriteOptions& o) { o.delimiter = ';'; }, - [](internal::FuzzCsvHeader& h) { h.parse_1.delimiter_id = FuzzDelimiterId(';'); }); - append_variant( - [](WriteOptions& o) { o.delimiter = '\t'; }, - [](internal::FuzzCsvHeader& h) { h.parse_1.delimiter_id = FuzzDelimiterId('\t'); }); + append_variant([](WriteOptions& o) { o.delimiter = ';'; }); + append_variant([](WriteOptions& o) { o.delimiter = '\t'; }); // Quote all values (the writer uses '"' as the quoting character) - append_variant([](WriteOptions& o) { o.quoting_style = QuotingStyle::AllValid; }, - [](internal::FuzzCsvHeader&) {}); + append_variant([](WriteOptions& o) { o.quoting_style = QuotingStyle::AllValid; }); // No header row, and let the reader autogenerate column names - append_variant( - [](WriteOptions& o) { o.include_header = false; }, - [](internal::FuzzCsvHeader& h) { h.read.autogenerate_column_names = 1; }); + append_variant([](WriteOptions& o) { o.include_header = false; }); // Write nulls as "N/A", and let the reader parse them as nulls // ("N/A" is one of the default null spellings in ConvertOptions) - append_variant([](WriteOptions& o) { o.null_string = "N/A"; }, - [](internal::FuzzCsvHeader& h) { h.convert_1.strings_can_be_null = 1; }); + append_variant([](WriteOptions& o) { o.null_string = "N/A"; }); return variants; } From 18258d5230f8467c43c273ccb9e0470b85e7e28c Mon Sep 17 00:00:00 2001 From: Arthur Chan Date: Tue, 24 Nov 2026 11:10:00 +0000 Subject: [PATCH 5/5] Address more comments Signed-off-by: Arthur Chan --- cpp/build-support/fuzzing/pack_corpus.py | 2 +- cpp/src/arrow/csv/fuzz.cc | 20 ++++++++++++++++---- cpp/src/arrow/csv/fuzz_header_internal.h | 7 +++++-- cpp/src/arrow/csv/generate_fuzz_corpus.cc | 13 +++++++++++-- 4 files changed, 33 insertions(+), 9 deletions(-) diff --git a/cpp/build-support/fuzzing/pack_corpus.py b/cpp/build-support/fuzzing/pack_corpus.py index 458038b593e8..0adb5d4e2b46 100755 --- a/cpp/build-support/fuzzing/pack_corpus.py +++ b/cpp/build-support/fuzzing/pack_corpus.py @@ -37,7 +37,7 @@ def process_dir(corpus_dir, zip_output): arcname = hashlib.sha1(data).hexdigest() if arcname in seen_hashes: print(f" WARNING: {child} has the same content as {seen_hashes[arcname]}, " - "skipping it") + "skipping it", file=sys.stderr) continue print(f" {child} -> {arcname}") zip_output.writestr(str(arcname), data) diff --git a/cpp/src/arrow/csv/fuzz.cc b/cpp/src/arrow/csv/fuzz.cc index 5b26bd14e1da..4029c5b2fb07 100644 --- a/cpp/src/arrow/csv/fuzz.cc +++ b/cpp/src/arrow/csv/fuzz.cc @@ -49,13 +49,18 @@ struct FuzzCsvOptions { FuzzCsvOptions MakeFuzzCsvOptions(const internal::FuzzCsvHeader& header) { FuzzCsvOptions opts; + // Start from the documented defaults and override the fields driven by the + // fuzz header, so that options added in the future keep their default + // values here. + opts.parse = ParseOptions::Defaults(); + opts.read = ReadOptions::Defaults(); // --- ParseOptions --- // The "id" fields store an index in the corresponding candidate arrays, // modulo the array length (see csv/fuzz_header_internal.h). - opts.parse.delimiter_string = - std::string(internal::kFuzzCsvDelimiters[header.parse_1.delimiter_id % - internal::kFuzzCsvDelimiters.size()]); + opts.parse.delimiter = + internal::kFuzzCsvDelimiters[header.parse_1.delimiter_id % + internal::kFuzzCsvDelimiters.size()][0]; opts.parse.quoting = header.parse_1.quoting; opts.parse.quote_char = internal::kFuzzCsvQuoteChars[header.parse_1.quote_char_id % @@ -158,7 +163,14 @@ Status ReadAllWays(io::IOContext io_context, const FuzzCsvOptions& opts, // should return equal tables (comparison ignores chunking, and NaN // values compare equal as they parse deterministically). Any mismatch // is a reader bug, so abort, like the Parquet encoding fuzzer does. - if (serial_table && threaded_table && streaming_table) { + // With automatic dictionary encoding enabled, though, different block + // sizes and threading can produce different dictionary representations + // (or dictionary-versus-string schemas) of the same values, and + // Table::Equals compares dictionaries rather than decoded values - so + // the cross-mode assertion only applies when dictionary encoding is + // disabled. + if (serial_table && threaded_table && streaming_table && + !opts.convert.auto_dict_encode) { auto equal_options = EqualOptions{}.nans_equal(true); if (!serial_table->Equals(*threaded_table, equal_options) || !serial_table->Equals(*streaming_table, equal_options)) { diff --git a/cpp/src/arrow/csv/fuzz_header_internal.h b/cpp/src/arrow/csv/fuzz_header_internal.h index 9076880a9218..c3750452ad01 100644 --- a/cpp/src/arrow/csv/fuzz_header_internal.h +++ b/cpp/src/arrow/csv/fuzz_header_internal.h @@ -48,8 +48,11 @@ inline constexpr std::array kFuzzCsvMagic = {'A', 'R', 'R', 'O', // Candidate values for the options encoded in FuzzCsvHeader below. The // corresponding option fields store an index in these arrays (modulo the // array length, so that all header values lead to a well-defined option set). -inline constexpr std::array kFuzzCsvDelimiters = { - ",", "\t", ";", "|", " ", "@@"}; +// Single-character delimiters only: ParseOptions::delimiter_string (which +// supports multi-character delimiters) is not available on this branch yet, +// so multi-character candidates can be added after rebasing onto it. +inline constexpr std::array kFuzzCsvDelimiters = { + ",", "\t", ";", "|", " "}; inline constexpr std::array kFuzzCsvQuoteChars = {'"', '\''}; inline constexpr std::array kFuzzCsvEscapeChars = {'\\', '"'}; // Small cardinality thresholds exercise dictionary truncation and fallback diff --git a/cpp/src/arrow/csv/generate_fuzz_corpus.cc b/cpp/src/arrow/csv/generate_fuzz_corpus.cc index 8845fddd9043..33a55612f43f 100644 --- a/cpp/src/arrow/csv/generate_fuzz_corpus.cc +++ b/cpp/src/arrow/csv/generate_fuzz_corpus.cc @@ -196,6 +196,13 @@ internal::FuzzCsvHeader MakeDefaultFuzzCsvHeader() { uint8_t FuzzDelimiterId(std::string_view delimiter) { auto it = std::find(internal::kFuzzCsvDelimiters.begin(), internal::kFuzzCsvDelimiters.end(), delimiter); + // An unknown delimiter would silently desync the fuzz header from the + // written dialect (the id maps modulo the array length), so treat it as + // the generator bug it is. + if (it == internal::kFuzzCsvDelimiters.end()) { + ARROW_CHECK_OK(Status::Invalid("Delimiter missing from kFuzzCsvDelimiters: ", + std::string(delimiter))); + } return static_cast(it - internal::kFuzzCsvDelimiters.begin()); } // Build the fuzz header for a set of write options: the parse and convert @@ -232,8 +239,10 @@ std::vector SampleVariants() { // An invalid set of write options is a bug in this generator, not // something to skip silently. ARROW_CHECK_OK(write_options.Validate()); - variants.emplace_back(std::move(write_options), - MakeFuzzCsvHeaderFromWriteOptions(write_options)); + // Build the header before moving the options: argument evaluation order + // is unspecified, so moving first could read from a moved-from object. + auto header = MakeFuzzCsvHeaderFromWriteOptions(write_options); + variants.emplace_back(std::move(write_options), std::move(header)); }; // Default dialect append_variant([](WriteOptions&) {});