Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 64 additions & 0 deletions cpp/build-support/fuzzing/dicts/arrow-csv-fuzz.dict
Original file line number Diff line number Diff line change
@@ -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.
Comment thread
arthurscchan marked this conversation as resolved.
Resolved
#
# 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"
15 changes: 15 additions & 0 deletions cpp/build-support/fuzzing/generate_corpuses.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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
# "<FUZZ TARGET>.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}/" \;
6 changes: 3 additions & 3 deletions cpp/build-support/fuzzing/pack_corpus.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
250 changes: 188 additions & 62 deletions cpp/src/arrow/csv/fuzz.cc
Original file line number Diff line number Diff line change
Expand Up @@ -15,106 +15,232 @@
// specific language governing permissions and limitations
// under the License.

#include <array>
#include <cstdint>
#include <functional>
#include <memory>
#include <optional>
#include <span>
#include <sstream>

#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;
Comment thread
arthurscchan marked this conversation as resolved.
Resolved

// --- 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<const uint8_t> payload) {
Status st;

auto make_input = [&]() -> std::shared_ptr<InputStream> {
return std::make_shared<::arrow::io::BufferReader>(
std::make_shared<Buffer>(payload.data(), static_cast<int64_t>(payload.size())));
};

// TODO should we also test non-inferring table read?
// The tables read below are kept around for differential testing.
std::shared_ptr<Table> serial_table, threaded_table, streaming_table;

auto read_table_serial = [=](std::shared_ptr<InputStream> 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<InputStream> 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<InputStream> 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<InputStream> 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()));
}
}
Comment thread
arthurscchan marked this conversation as resolved.
Resolved

auto count_rows_allow_newlines =
[=](std::shared_ptr<InputStream> 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<Buffer>(data, size));
TaskGuard task_guard;
st &= read_func(input);
std::span<const uint8_t> input(data, static_cast<size_t>(size));
std::span<const uint8_t> 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
Expand Down
Loading