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
50 changes: 47 additions & 3 deletions cpp/src/arrow/json/chunked_builder.cc
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@

#include "arrow/json/chunked_builder.h"

#include <algorithm>
#include <mutex>
#include <optional>
#include <string>
#include <unordered_map>
#include <utility>
Expand All @@ -26,6 +28,7 @@
#include "arrow/array.h"
#include "arrow/buffer.h"
#include "arrow/json/converter.h"
#include "arrow/json/parser.h"
#include "arrow/table.h"
#include "arrow/util/checked_cast.h"
#include "arrow/util/logging_internal.h"
Expand All @@ -45,6 +48,29 @@ Status MakeChunkedArrayBuilder(const std::shared_ptr<TaskGroup>& task_group,
bool allow_promotion,
std::shared_ptr<ChunkedArrayBuilder>* out);

// The parser checks JSON kinds only inside one block. Each field it emits carries the
// kind it saw, which is how a builder spots a kind change between blocks.
std::optional<Kind::type> TaggedKind(const Field& field) {
const auto& tag = field.metadata();
if (tag == nullptr || tag->FindKey("json_kind") == -1) {
return std::nullopt;
}
return Kind::FromTag(tag);
}

// With threads any block can reach a builder first, so the message names the two kinds
// in a fixed order rather than guess which one came first in the file.
Status MixedKindsError(Kind::type kind, const Field& field, const Array& other) {
auto other_kind = TaggedKind(field);
if (!other_kind) {
return Status::Invalid("JSON parse error: Column mixes ", Kind::Name(kind), " and ",
*other.type(), " values across blocks");
}
auto [first, second] = std::minmax(kind, *other_kind);
return Status::Invalid("JSON parse error: Column mixes ", Kind::Name(first), " and ",
Kind::Name(second), " values across blocks");
}

class NonNestedChunkedArrayBuilder : public ChunkedArrayBuilder {
public:
NonNestedChunkedArrayBuilder(const std::shared_ptr<TaskGroup>& task_group,
Expand Down Expand Up @@ -135,6 +161,15 @@ class InferringChunkedArrayBuilder
std::shared_ptr<Array> converted;

lock.unlock();
// Promotion stays inside one kind (int64 to double, timestamp to string), so a
// different kind is an error rather than a reason to promote.
Kind::type expected;
RETURN_NOT_OK(Kind::ForType(*converter->out_type(), &expected));
auto actual = TaggedKind(*unconverted_field);
if (expected != Kind::kNull && unconverted->type_id() != Type::NA && actual &&
*actual != expected) {
return MixedKindsError(expected, *unconverted_field, *unconverted);
}
Status st = converter->Convert(unconverted, &converted);
lock.lock();

Expand Down Expand Up @@ -204,7 +239,7 @@ class ChunkedListArrayBuilder : public ChunkedArrayBuilder {
return Status::OK();
}

void Insert(int64_t block_index, const std::shared_ptr<Field>&,
void Insert(int64_t block_index, const std::shared_ptr<Field>& unconverted_field,
const std::shared_ptr<Array>& unconverted) override {
std::unique_lock<std::mutex> lock(mutex_);

Expand All @@ -221,7 +256,11 @@ class ChunkedListArrayBuilder : public ChunkedArrayBuilder {
return;
}

DCHECK_EQ(unconverted->type_id(), Type::LIST);
if (unconverted->type_id() != Type::LIST) {
auto st = MixedKindsError(Kind::kArray, *unconverted_field, *unconverted);
task_group_->Append([st] { return st; });
return;
}
const auto& list_array = checked_cast<const ListArray&>(*unconverted);

null_bitmap_chunks_[block_index] = unconverted->null_bitmap();
Expand Down Expand Up @@ -288,7 +327,7 @@ class ChunkedStructArrayBuilder : public ChunkedArrayBuilder {
}
}

void Insert(int64_t block_index, const std::shared_ptr<Field>&,
void Insert(int64_t block_index, const std::shared_ptr<Field>& unconverted_field,
const std::shared_ptr<Array>& unconverted) override {
std::unique_lock<std::mutex> lock(mutex_);

Expand All @@ -315,6 +354,11 @@ class ChunkedStructArrayBuilder : public ChunkedArrayBuilder {
return;
}

if (unconverted->type_id() != Type::STRUCT) {
auto st = MixedKindsError(Kind::kObject, *unconverted_field, *unconverted);
task_group_->Append([st] { return st; });
return;
}
const auto& struct_array = checked_cast<const StructArray&>(*unconverted);
if (promotion_graph_ == nullptr) {
// If unexpected fields are ignored or result in an error then all parsers will emit
Expand Down
9 changes: 9 additions & 0 deletions cpp/src/arrow/json/converter.cc
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,9 @@ class NumericConverter : public PrimitiveConverter {
if (in->type_id() == Type::NA) {
return MakeArrayOfNull(out_type_, in->length(), pool_).Value(out);
}
if (in->type_id() != Type::DICTIONARY) {
return GenericConversionError(*out_type_, " from ", *in->type());
}
const auto& dict_array = GetDictionaryArray(in);

using Builder = typename TypeTraits<T>::BuilderType;
Expand Down Expand Up @@ -160,6 +163,9 @@ class DecimalConverter : public PrimitiveConverter {
if (in->type_id() == Type::NA) {
return MakeArrayOfNull(out_type_, in->length(), pool_).Value(out);
}
if (in->type_id() != Type::DICTIONARY) {
return GenericConversionError(*out_type_, " from ", *in->type());
}
const auto& dict_array = GetDictionaryArray(in);

using Builder = typename TypeTraits<T>::BuilderType;
Expand Down Expand Up @@ -239,6 +245,9 @@ class BinaryConverter : public PrimitiveConverter {
if (in->type_id() == Type::NA) {
return MakeArrayOfNull(out_type_, in->length(), pool_).Value(out);
}
if (in->type_id() != Type::DICTIONARY) {
return GenericConversionError(*out_type_, " from ", *in->type());
}
const auto& dict_array = GetDictionaryArray(in);

using Builder = typename TypeTraits<T>::BuilderType;
Expand Down
182 changes: 182 additions & 0 deletions cpp/src/arrow/json/reader_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
// specific language governing permissions and limitations
// under the License.

#include <algorithm>
#include <string>
#include <utility>
#include <vector>
Expand Down Expand Up @@ -1048,5 +1049,186 @@ TEST(ReaderTest, FailOnMalformedNumbers) {
}
}

// GH-55833: a read split into blocks must behave like a single-block read.
struct BlockCase {
std::string name;
std::vector<std::string> rows;
bool is_error;
};

void PrintTo(const BlockCase& block_case, std::ostream* os) { *os << block_case.name; }

static Result<std::shared_ptr<Table>> ReadRows(std::vector<std::string> rows,
bool one_row_per_block,
ReadOptions read_options) {
size_t width = 0;
for (const auto& row : rows) {
width = std::max(width, row.size());
}
// Equal line lengths put exactly one row in every block.
std::string json;
for (auto& row : rows) {
row.resize(width, ' ');
json += row + "\n";
}
if (one_row_per_block) {
read_options.block_size = static_cast<int32_t>(width + 1);
}
return ReadToTable(std::move(json), read_options, ParseOptions::Defaults());
}

static void AssertSplitMatchesSingleBlock(const std::vector<std::string>& rows,
bool is_error, bool use_threads = false) {
auto read_options = ReadOptions::Defaults();
read_options.use_threads = use_threads;
auto whole = ReadRows(rows, false, read_options);
auto split = ReadRows(rows, true, read_options);

if (is_error) {
ASSERT_RAISES(Invalid, whole);
ASSERT_RAISES(Invalid, split);
// Checking the text rules out an unrelated Invalid, such as a garbage size from a
// bad cast.
ASSERT_THAT(split.status().message(), ::testing::HasSubstr("values across blocks"));
} else {
ASSERT_OK(whole);
ASSERT_OK(split);
ASSERT_OK((*split)->ValidateFull());
ASSERT_EQ((*split)->column(0)->num_chunks(), static_cast<int>(rows.size()));
AssertTablesEqual(**whole, **split, /*same_chunk_layout=*/false);
}
}

class BlockBoundaryTest : public ::testing::TestWithParam<BlockCase> {};

TEST_P(BlockBoundaryTest, SplitMatchesSingleBlock) {
AssertSplitMatchesSingleBlock(GetParam().rows, GetParam().is_error);
}

static std::string BlockCaseName(const ::testing::TestParamInfo<BlockCase>& info) {
return info.param.name;
}

// A list or object that changes to another kind, or the other way round.
static std::vector<BlockCase> ContainerKindChanges() {
const std::vector<std::pair<std::string, std::string>> containers = {
{"list", "[1]"}, {"object", R"({"x":1})"}};
const std::vector<std::pair<std::string, std::string>> scalars = {
{"bool", "true"}, {"number", "1"}, {"string", R"("a")"}};
std::vector<BlockCase> cases = {
{"list_then_object", {R"({"c":[1]})", R"({"c":{"x":1}})"}, true},
{"object_then_list", {R"({"c":{"x":1}})", R"({"c":[1]})"}, true},
// A date is read as a timestamp first, which is retried as a string on failure.
{"timestamp_then_object", {R"({"c":"2020-01-01"})", R"({"c":{"x":1}})"}, true}};
for (const auto& [container, container_value] : containers) {
for (const auto& [scalar, scalar_value] : scalars) {
const std::string container_row = R"({"c":)" + container_value + "}";
const std::string scalar_row = R"({"c":)" + scalar_value + "}";
cases.push_back({container + "_then_" + scalar, {container_row, scalar_row}, true});
cases.push_back({scalar + "_then_" + container, {scalar_row, container_row}, true});
}
}
return cases;
}

INSTANTIATE_TEST_SUITE_P(ContainerKindChanges, BlockBoundaryTest,
::testing::ValuesIn(ContainerKindChanges()), BlockCaseName);

// Numbers and strings reach the builders as the same array type, so only the JSON kind
// tells them apart.
static std::vector<BlockCase> ScalarKindChanges() {
return {{"string_then_number", {R"({"c":"a"})", R"({"c":1})"}, true},
{"number_then_numeric_string", {R"({"c":1})", R"({"c":"123"})"}, true},
{"number_then_nan_string", {R"({"c":1})", R"({"c":"nan"})"}, true},
{"timestamp_then_number", {R"({"c":"2020-01-01"})", R"({"c":1})"}, true},
{"number_then_bool", {R"({"c":1})", R"({"c":true})"}, true},
{"list_item_number_then_string", {R"({"c":[1]})", R"({"c":["2"]})"}, true}};
}

INSTANTIATE_TEST_SUITE_P(ScalarKindChanges, BlockBoundaryTest,
::testing::ValuesIn(ScalarKindChanges()), BlockCaseName);

INSTANTIATE_TEST_SUITE_P(
NestedConflicts, BlockBoundaryTest,
::testing::Values(
BlockCase{
"list_item_number_then_object", {R"({"c":[1]})", R"({"c":[{"x":1}]})"}, true},
BlockCase{
"list_item_object_then_number", {R"({"c":[{"x":1}]})", R"({"c":[1]})"}, true},
BlockCase{"list_of_lists_then_list", {R"({"c":[[1]]})", R"({"c":[1]})"}, true},
BlockCase{"field_number_then_object",
{R"({"c":{"x":1}})", R"({"c":{"x":{"y":1}}})"},
true},
BlockCase{"field_object_then_number",
{R"({"c":{"x":{"y":1}}})", R"({"c":{"x":1}})"},
true},
BlockCase{
"field_list_then_number", {R"({"c":{"x":[1]}})", R"({"c":{"x":1}})"}, true}),
BlockCaseName);

static std::vector<std::string> ObjectsThenNumber() {
std::vector<std::string> rows(20, R"({"c":{"x":1}})");
rows.push_back(R"({"c":1})");
return rows;
}

INSTANTIATE_TEST_SUITE_P(
ManyBlocks, BlockBoundaryTest,
::testing::Values(BlockCase{"null_between_conflict",
{R"({"c":1})", R"({"c":null})", R"({"c":{"x":1}})"},
true},
BlockCase{"conflict_after_many_blocks", ObjectsThenNumber(), true},
BlockCase{"valid_blocks_after_conflict",
{R"({"c":{"x":1}})", R"({"c":1})", R"({"c":{"x":2}})"},
true},
BlockCase{"valid_list_blocks_after_conflict",
{R"({"c":[1]})", R"({"c":1})", R"({"c":[2]})"},
true}),
BlockCaseName);

TEST(BlockBoundaryReaderTest, ConflictWithThreads) {
// Threads decide which block builds the column first, so repeat every case.
for (const auto& cases : {ContainerKindChanges(), ScalarKindChanges()}) {
for (const auto& block_case : cases) {
SCOPED_TRACE(block_case.name);
for (int i = 0; i < 20; ++i) {
ASSERT_NO_FATAL_FAILURE(AssertSplitMatchesSingleBlock(
block_case.rows, /*is_error=*/true, /*use_threads=*/true));
}
}
}
}

TEST(BlockBoundaryReaderTest, ErrorNamesKindsInFixedOrder) {
auto read_options = ReadOptions::Defaults();
read_options.use_threads = true;
const std::string object_row = R"({"c":{"x":1}})";
const std::string number_row = R"({"c":1})";
for (int i = 0; i < 20; ++i) {
for (const auto& rows : {std::vector<std::string>{object_row, number_row},
std::vector<std::string>{number_row, object_row}}) {
EXPECT_RAISES_WITH_MESSAGE_THAT(
Invalid,
::testing::HasSubstr("Column mixes number and object values across blocks"),
ReadRows(rows, /*one_row_per_block=*/true, read_options));
}
}
}

// Reads that must keep working, including promotion within one JSON kind.
INSTANTIATE_TEST_SUITE_P(
ValidInput, BlockBoundaryTest,
::testing::Values(
BlockCase{"int_then_float", {R"({"c":1})", R"({"c":2.5})"}, false},
BlockCase{
"timestamp_then_text", {R"({"c":"2020-01-01"})", R"({"c":"a"})"}, false},
BlockCase{"list_then_list", {R"({"c":[1]})", R"({"c":[2]})"}, false},
BlockCase{"object_then_object", {R"({"c":{"x":1}})", R"({"c":{"x":2}})"}, false},
BlockCase{"list_then_null", {R"({"c":[1]})", R"({"c":null})"}, false},
BlockCase{"object_then_null", {R"({"c":{"x":1}})", R"({"c":null})"}, false},
BlockCase{
"different_object_keys", {R"({"c":{"x":1}})", R"({"c":{"y":2}})"}, false}),
BlockCaseName);

} // namespace json
} // namespace arrow