hello-stephen commented on code in PR #71397:
URL: https://github.com/apache/doris/pull/71397#discussion_r4796034423
##########
be/src/format_v2/parquet/reader/variant_column_reader.cpp:
##########
@@ -167,6 +167,12 @@ uint8_t integer_width(const ParquetColumnSchema& schema,
PrimitiveType type) {
void append_typed_scalar(const ParquetColumnSchema& schema, const IColumn&
column, size_t row,
VariantBatchBuilder::Row& builder) {
+ // DATE identity cannot pass through DATEV2: its calendar excludes
Gregorian 0000-02-29.
+ if (schema.type_descriptor.is_variant_date) {
+ builder.add_scalar(
Review Comment:
[P2] Preserve year-zero Variant DATE types when loading into Doris
A shredded Parquet object with `v['d'] = DATE '0000-01-01'` now reaches a
query as a Variant DATE. When the same object is inserted into a native VARIANT
table through the V2 writer, `VariantShredder` hands the leaf to
`VariantPathBuilder`. Its range check still excludes all of year zero, so it
infers JSONB and writes the DATE as a string. Reading the stored path back
loses the DATE tag, which is observable through `variant_type(v['d'])`. Use the
shared Gregorian inverse in both the path builder’s range test and its DATE
materialization, and test a load and readback of a nested year-zero leaf.
[Variant path type
inference](https://github.com/apache/doris/blob/d76640f5059014ff230a7f40d79f592738c229f0/be/src/storage/segment/variant/v2/variant_path_builder.cpp#L264-L269)
· [JSONB DATE
conversion](https://github.com/apache/doris/blob/d76640f5059014ff230a7f40d79f592738c229f0/be/src/exprs/function/parse/variant_jsonb_parse.cpp#L399-L401)
##########
be/src/format/arrow/arrow_row_batch.cpp:
##########
@@ -54,6 +54,22 @@
namespace doris {
+namespace {
+
+std::shared_ptr<arrow::Schema> doris_arrow_schema(
+ std::vector<std::shared_ptr<arrow::Field>> fields) {
+ const bool has_dates = std::ranges::any_of(
+ fields, [](const auto& field) { return
arrow_type_contains_date(*field->type()); });
+ // Legacy Flight strips field metadata; keep DATE provenance on the
enclosing schema
+ // so upgraded Remote Doris consumers can distinguish live year-zero
encodings.
+ auto metadata = has_dates ?
arrow::key_value_metadata({ARROW_DORIS_DATE_ENCODING_KEY},
Review Comment:
[P2] Keep parallel DATE results available during BE upgrades
With `enable_parallel_result_sink` and an ordinary unprepared query
returning DATE from both a pre-fix and a corrected BE, only the corrected
endpoint has this schema marker.
`FlightSqlConnectProcessor.fetchArrowFlightSchema()` compares those schemas
with `Schema.equals()`, which includes custom metadata, so GetFlightInfo fails
before returning any tickets. This also affects a query whose dates are all
modern. Negotiate a consistent schema contract for the result endpoints or
route the query to compatible BEs during the rollout. The guide currently calls
out the local mixed-version restriction for prepared queries only. [Arrow Java
19 schema
equality](https://github.com/apache/arrow-java/blob/v19.0.0/vector/src/main/java/org/apache/arrow/vector/types/pojo/Schema.java#L256-L263)
##########
tools/legacy_date_migration/migrate_legacy_dates.py:
##########
@@ -0,0 +1,231 @@
+#!/usr/bin/env python3
+# 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.
+
+"""Rewrite confirmed legacy Doris DATE32 files into proleptic Gregorian
encoding."""
+
+import argparse
+import base64
+import os
+import tempfile
+from pathlib import Path
+
+import pyarrow as pa
+import pyarrow.compute as pc
+import pyarrow.orc as orc
+import pyarrow.parquet as parquet
+
+
+def convert_array(array, visible=None):
+ """Preserve Arrow structure and nulls while correcting legacy DATE32
ordinals."""
+ data_type = array.type
+ visible = array.is_valid() if visible is None else pc.and_(visible,
array.is_valid())
+ if pa.types.is_date32(data_type):
+ # Children beneath a null container have no date value, regardless of
their payload.
+ days = pc.if_else(visible, array.cast(pa.int32()), pa.scalar(None,
pa.int32()))
+ bounds = pc.min_max(days).as_py()
+ if bounds['min'] is not None and (
+ bounds['min'] < -719527 or bounds['max'] > 2932896):
+ raise ValueError('DATE value outside the legacy Doris range')
+ # The old MySQL-calendar encoder is one day ahead only before March of
year zero.
+ early = pc.and_(pc.greater_equal(days, -719527), pc.less_equal(days,
-719469))
+ return pc.if_else(early, pc.subtract(days, pa.scalar(1, pa.int32())),
days).cast(pa.date32())
+ if pa.types.is_struct(data_type):
+ return pa.StructArray.from_arrays(
+ [convert_array(array.field(i), visible) for i in
range(data_type.num_fields)],
+ fields=list(data_type), mask=array.is_null())
+ if pa.types.is_list(data_type) or pa.types.is_large_list(data_type):
+ start, end = array.offsets[0].as_py(), array.offsets[-1].as_py()
+ raw_values = array.values.slice(start, end - start)
+ offsets = pc.subtract(array.offsets, start)
+ parents =
pc.list_parent_indices(pa.LargeListArray.from_arrays(offsets, raw_values))
+ values = convert_array(raw_values, pc.take(visible, parents))
+ constructor = pa.LargeListArray if pa.types.is_large_list(data_type)
else pa.ListArray
+ return constructor.from_arrays(offsets, values, type=data_type,
mask=array.is_null())
+ if pa.types.is_fixed_size_list(data_type):
+ size = data_type.list_size
+ raw_values = array.values.slice(array.offset * size, len(array) * size)
+ parents =
pc.list_parent_indices(pa.FixedSizeListArray.from_arrays(raw_values, size))
+ values = convert_array(raw_values, pc.take(visible, parents))
+ return pa.FixedSizeListArray.from_arrays(values, type=data_type,
mask=array.is_null())
+ if pa.types.is_map(data_type):
+ start, end = array.offsets[0].as_py(), array.offsets[-1].as_py()
+ offsets = pc.subtract(array.offsets, start)
+ keys = array.keys.slice(start, end - start)
+ parents =
pc.list_parent_indices(pa.LargeListArray.from_arrays(offsets, keys))
+ child_visible = pc.take(visible, parents)
+ converted_keys = convert_array(keys, child_visible)
+ if pa.types.is_date32(keys.type):
+ # Arrow requires non-null map keys even in an unreachable null map
slot.
+ converted_keys = pc.fill_null(converted_keys, pa.scalar(0,
pa.date32()))
+ return pa.MapArray.from_arrays(
+ offsets,
+ converted_keys,
+ convert_array(array.items.slice(start, end - start),
child_visible),
+ type=data_type, mask=array.is_null())
+ if pa.types.is_dictionary(data_type):
+ used = pc.unique(pc.filter(array.indices, visible)).cast(pa.int64())
+ dictionary_visible = pc.is_in(pa.array(range(len(array.dictionary)),
type=pa.int64()),
+ value_set=used)
+ return pa.DictionaryArray.from_arrays(
+ array.indices, convert_array(array.dictionary, dictionary_visible),
+ ordered=data_type.ordered)
+ if pa.types.is_union(data_type) or isinstance(data_type, pa.ExtensionType):
+ raise ValueError('Unsupported Arrow type; refusing a potentially
partial migration: '
+ + str(data_type))
+ return array
+
+
+def convert_table(table):
+ """Convert all DATE32 fields, including nested fields and all chunks."""
+ columns = [pa.chunked_array([convert_array(chunk) for chunk in
column.chunks],
+ type=column.type) for column in table.columns]
+ return pa.Table.from_arrays(columns, schema=table.schema)
+
+
+def _leaves(data_type):
+ if pa.types.is_dictionary(data_type):
+ yield from _leaves(data_type.value_type)
+ elif data_type.num_fields:
+ for index in range(data_type.num_fields):
+ yield from _leaves(data_type.field(index).type)
+ else:
+ yield data_type
+
+
+def _open_source(source, file_format):
+ if file_format == 'orc':
+ import pyorc
+ # Arrow exposes physical CHAR as UTF8, then writes STRING. Doris trims
only CHAR,
+ # so padded CHAR(4) 'x' would change from length 1 to 4 after that
round trip.
+ def has_char(data_type):
+ if data_type.kind == pyorc.TypeKind.CHAR:
+ return True
+ if data_type.kind == pyorc.TypeKind.STRUCT:
+ return any(has_char(child) for child in
data_type.fields.values())
+ if data_type.kind == pyorc.TypeKind.LIST:
+ return has_char(data_type.type)
+ if data_type.kind == pyorc.TypeKind.MAP:
+ return has_char(data_type.key) or has_char(data_type.value)
+ if data_type.kind == pyorc.TypeKind.UNION:
+ return any(has_char(child) for child in data_type.cont_types)
+ return False
+
+ with source.open('rb') as stream:
+ if has_char(pyorc.Reader(stream).schema):
+ raise ValueError('ORC CHAR columns cannot be migrated safely
with PyArrow')
+ reader = orc.ORCFile(source)
+ # PyArrow materializes ORC timestamps as int64 nanoseconds: 1600-01-01
already
+ # wraps before convert_table can inspect it. No reader option selects
a wider unit.
+ if any(pa.types.is_timestamp(leaf) for field in reader.schema
+ for leaf in _leaves(field.type)):
+ raise ValueError('ORC timestamp columns cannot be migrated safely
with PyArrow')
+ return reader, reader.schema, False
+
+ # The default INT96 -> nanoseconds conversion wraps valid Doris DATETIME
values
+ # outside 1677..2262. Microseconds cover the whole Doris DATE/DATETIME
year range.
+ reader = parquet.ParquetFile(source, coerce_int96_timestamp_unit='us')
+ int96 = [i for i in range(len(reader.schema))
+ if reader.schema.column(i).physical_type == 'INT96']
+ if not int96:
+ return reader, reader.schema_arrow, False
+ # INT96 itself carries no precision. Doris exports store the original
Arrow schema;
+ # require its microsecond-or-coarser contract instead of truncating
nanosecond input.
+ metadata = reader.metadata.metadata or {}
+ if b'ARROW:schema' not in metadata:
+ raise ValueError('INT96 migration requires a stored Arrow timestamp
schema')
+ schema =
pa.ipc.read_schema(pa.BufferReader(base64.b64decode(metadata[b'ARROW:schema'])))
+ leaves = [leaf for field in schema for leaf in _leaves(field.type)]
+ if len(leaves) != len(reader.schema) or any(
+ not pa.types.is_timestamp(leaves[i]) or leaves[i].unit not in
('s', 'ms', 'us')
+ for i in int96):
+ raise ValueError('INT96 migration requires stored
microsecond-or-coarser timestamps')
+ # PyArrow selects INT96 for every timestamp at file level. Applying that
option to a
+ # mixed INT96/INT64 file would change the other columns'
timezone/precision contract.
+ if any(pa.types.is_timestamp(leaf) and i not in int96 for i, leaf in
enumerate(leaves)):
+ raise ValueError('Mixed INT96 and INT64 timestamp columns cannot be
migrated safely')
+ return reader, schema, True
+
+
+def migrate(source, destination, file_format, confirmed_legacy=False):
+ """Write a new file; source provenance must be confirmed by the caller."""
+ if not confirmed_legacy:
+ raise ValueError('Explicit confirmation of legacy Doris DATE encoding
is required')
+ source, destination = Path(source), Path(destination)
+ if source.resolve() == destination.resolve():
+ raise ValueError('Source and destination must be different files')
+ if file_format not in ('orc', 'parquet'):
+ raise ValueError('Format must be orc or parquet')
+ # Convert one stripe/batch at a time to avoid loading the whole data file
into memory.
+ reader, schema, use_int96 = _open_source(source, file_format)
+ chunks = (reader.read_stripe(i) for i in range(reader.nstripes)) if
file_format == 'orc' else (
Review Comment:
[P3] Validate ORC DATE ordinals before PyArrow narrows them
A corrupt ORC file can carry an oversized DATE value in the SDK’s 64-bit
batch. PyArrow narrows it to a 32-bit ordinal while reading the stripe. For
example, 4294967296 becomes 0, passes `convert_array()` and is published as
1970-01-01. The native Doris decoder rejects the original ordinal and the
migration guide promises out-of-range rejection. Validate the raw ORC ordinals
before the Arrow conversion, or document the limit of the corruption check.
[PyArrow DATE
dispatch](https://github.com/apache/arrow/blob/apache-arrow-24.0.0/cpp/src/arrow/adapters/orc/util.cc#L335-L339)
· [PyArrow
narrowing](https://github.com/apache/arrow/blob/apache-arrow-24.0.0/cpp/src/arrow/adapters/orc/util.cc#L138-L156)
--
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]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]