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..f17d630c896b --- /dev/null +++ b/cpp/build-support/fuzzing/dicts/arrow-csv-fuzz.dict @@ -0,0 +1,64 @@ +# 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" +"|" +" " +"\"" +"'" +"\\" +"\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" diff --git a/cpp/build-support/fuzzing/generate_corpuses.sh b/cpp/build-support/fuzzing/generate_corpuses.sh index 2d95e110b516..6ca47e0ebcf0 100755 --- a/cpp/build-support/fuzzing/generate_corpuses.sh +++ b/cpp/build-support/fuzzing/generate_corpuses.sh @@ -89,4 +89,19 @@ 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}" \; +# 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" + +# 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. +# 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..0adb5d4e2b46 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", file=sys.stderr) + 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 2219efa2cb59..4029c5b2fb07 100644 --- a/cpp/src/arrow/csv/fuzz.cc +++ b/cpp/src/arrow/csv/fuzz.cc @@ -15,106 +15,232 @@ // 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" 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 { + +struct FuzzCsvOptions { + ReadOptions read; + ParseOptions parse; + ConvertOptions convert; +}; + +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 = + 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 % + 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 --- + // 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; + + // --- ConvertOptions --- + 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.convert_2.add_strptime_mdy_parser) { + opts.convert.timestamp_parsers.push_back(TimestampParser::MakeStrptime("%m/%d/%Y")); + } - auto io_context = arrow::io::default_io_context(); + return opts; +} - 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; +// 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::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()))); + }; - // TODO should we also test non-inferring table read? + // The tables read below are kept around for differential testing. + std::shared_ptr serial_table, threaded_table, streaming_table; - auto read_table_serial = [=](std::shared_ptr input) mutable -> Status { + // 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, input, read_options, - parse_options, convert_options)); - ARROW_ASSIGN_OR_RAISE(auto table, table_reader->Read()); - return table->ValidateFull(); + 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(); }; - auto read_table_threaded = [=](std::shared_ptr input) mutable -> Status { + // 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, input, read_options, - parse_options, convert_options)); - ARROW_ASSIGN_OR_RAISE(auto table, table_reader->Read()); - return table->ValidateFull(); + 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(); }; - auto read_streaming = [=](std::shared_ptr input) mutable -> Status { + // 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, parse_options, - convert_options)); - ARROW_ASSIGN_OR_RAISE(auto table, reader->ToTable()); - return 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(); }; - 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, - parse_options); - return fut.status(); - }; + // 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. + // 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)) { + 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())); + } + } - 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, + // 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, parse_options); - return fut.status(); + st &= 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); + std::span input(data, static_cast(size)); + std::span payload = input; + FuzzCsvOptions opts; + + 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 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(); + opts.convert = ConvertOptions::Defaults(); + opts.convert.auto_dict_encode = true; + opts.convert.auto_dict_max_cardinality = 50; } - return st; + + 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..c3750452ad01 --- /dev/null +++ b/cpp/src/arrow/csv/fuzz_header_internal.h @@ -0,0 +1,173 @@ +// 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). +// 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 +// 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 +// 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) { + // 0 or 1 + uint8_t skip_rows : 1; + uint8_t autogenerate_column_names : 1; + uint8_t reserved_2 : 6; +}; +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 diff --git a/cpp/src/arrow/csv/generate_fuzz_corpus.cc b/cpp/src/arrow/csv/generate_fuzz_corpus.cc index eeba49e87f81..33a55612f43f 100644 --- a/cpp/src/arrow/csv/generate_fuzz_corpus.cc +++ b/cpp/src/arrow/csv/generate_fuzz_corpus.cc @@ -15,23 +15,30 @@ // 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" +#include "arrow/util/logging.h" #include "arrow/io/memory.h" #include "arrow/ipc/writer.h" #include "arrow/json/from_string.h" @@ -152,6 +159,108 @@ 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 --- + // 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 --- + 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(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 +// 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; + +// 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) { + auto write_options = WriteOptions::Defaults(); + write_fn(write_options); + // An invalid set of write options is a bug in this generator, not + // something to skip silently. + ARROW_CHECK_OK(write_options.Validate()); + // 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&) {}); + // Alternate delimiters + 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; }); + // No header row, and let the reader autogenerate column names + 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"; }); + 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,19 +271,22 @@ Status DoMain(const std::string& out_dir) { }; ARROW_ASSIGN_OR_RAISE(auto batches, Batches()); - - auto options = WriteOptions::Defaults(); - RETURN_NOT_OK(options.Validate()); + const auto option_variants = SampleVariants(); for (const auto& batch : batches) { RETURN_NOT_OK(batch->ValidateFull()); - ARROW_ASSIGN_OR_RAISE(auto buffer, WriteRecordBatch(batch, options)); + 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(buffer)); - RETURN_NOT_OK(file->Close()); + 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()); + } } return Status::OK(); }