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


##########
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', ';', 
'|', ' '};

Review Comment:
   We now have `delimiter_string` for multiple-character delimiters, so you may 
want to update this to using an array of strings or string views.



##########
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
+
+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()];

Review Comment:
   I think you can keep this `std::array` as well?



##########
cpp/src/arrow/csv/generate_fuzz_corpus.cc:
##########
@@ -152,6 +158,93 @@ Result<RecordBatchVector> 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<uint8_t>(it - internal::kFuzzCsvDelimiters.begin());
+}
+
+using WriteAndHeaderOptions = std::pair<WriteOptions, internal::FuzzCsvHeader>;
+
+// 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<WriteAndHeaderOptions> SampleVariants() {
+  std::vector<WriteAndHeaderOptions> variants;
+  auto append_variant = [&](std::function<void(WriteOptions&)> write_fn,
+                            std::function<void(internal::FuzzCsvHeader&)> 
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(';'); });

Review Comment:
   How about we have a function or constructor to create a matching 
`FuzzCsvHeader` from a `WriteOptions` object?



##########
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:
   Some of these options are read-side options and shouldn't affect CSV file 
generation, so they don't need to be materialized in the fuzz header.
   
   For example, `block_size` or `use_threads` are immaterial to how Arrow data 
is serialized to CSV. We want to ensure that various block sizes and threading 
setting are exercised in the fuzzer, though, and ideally check that they don't 
change the output of CSV reading.



##########
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};

Review Comment:
   We would actually like to exercise very small blocks (because this stresses 
the chunking logic more), these values are probably too large.



##########
cpp/src/arrow/csv/generate_fuzz_corpus.cc:
##########
@@ -152,6 +158,93 @@ Result<RecordBatchVector> 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<uint8_t>(it - internal::kFuzzCsvDelimiters.begin());
+}
+
+using WriteAndHeaderOptions = std::pair<WriteOptions, internal::FuzzCsvHeader>;
+
+// 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<WriteAndHeaderOptions> SampleVariants() {
+  std::vector<WriteAndHeaderOptions> variants;
+  auto append_variant = [&](std::function<void(WriteOptions&)> write_fn,
+                            std::function<void(internal::FuzzCsvHeader&)> 
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;
+    }

Review Comment:
   Can we error out instead? 



##########
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};

Review Comment:
   Similarly, I think small values make more sense here.



##########
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:
   If we keep `newlines_in_values` in the fuzz header, then I think the 
header-originated value should be used here as well.
   



-- 
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