arthurscchan commented on code in PR #54912:
URL: https://github.com/apache/arrow/pull/54912#discussion_r4678813228


##########
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 <array>
+#include <cstdint>
+#include <cstring>
+#include <span>
+#include <string>
+
+#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<char, 8> 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<char, 5> kFuzzCsvDelimiters = {',', '\t', ';', 
'|', ' '};
+inline constexpr std::array<char, 2> kFuzzCsvQuoteChars = {'"', '\''};
+inline constexpr std::array<char, 2> kFuzzCsvEscapeChars = {'\\', '"'};
+inline constexpr std::array<int32_t, 4> kFuzzCsvBlockSizes = {1024, 4096, 
65536, 1 << 20};
+inline constexpr std::array<int32_t, 3> 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

Review Comment:
   Removed.



##########
cpp/src/arrow/csv/fuzz.cc:
##########
@@ -15,106 +15,214 @@
 // 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;
+
+  // --- 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.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 ---
+  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 = 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
+  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,
-                                            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
+  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,
-                                            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.
+  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()));
+    }
+  }
 
-  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 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}) {

Review Comment:
   Fixed.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to