hello-stephen commented on code in PR #71397:
URL: https://github.com/apache/doris/pull/71397#discussion_r4793654483


##########
be/src/core/data_type_serde/data_type_datev2_serde.cpp:
##########
@@ -99,7 +117,7 @@ class DateV2ParquetConsumer final : public 
ParquetFixedValueConsumer {
         _data.resize(old_size + num_values);
         for (size_t row = 0; row < num_values; ++row) {
             DateV2Value<DateV2ValueType> value;
-            const auto status = decode_parquet_date(
+            const auto status = decode_epoch_days(

Review Comment:
   [P2] Keep shredded Variant DATEs on the Gregorian calendar
   
   A Parquet VARIANT with a shredded DATE of `0000-02-28` carries `-719470`. 
This decoder now materializes February 28, then `VariantColumnReader` passes it 
to `with_variant_typed_scalar`. That helper still subtracts the MySQL epoch day 
number, producing `-719469`. When Doris renders the reconstructed Variant, 
`format_json_date` interprets that ordinal as `0000-02-29`. The base's decode 
and re-encode offsets canceled on this path. Use the shared Gregorian 
conversion in the DATE branches that emit Variant values and test a shredded 
DATE against the same value in unshredded Variant encoding. [Parquet Variant 
shredding 
specification](https://github.com/apache/parquet-format/blob/master/VariantShredding.md#shredded-value-types)



##########
be/src/format_v2/orc/orc_reader.cpp:
##########
@@ -2960,6 +3133,26 @@ Status OrcReader::get_aggregate_result(const 
format::FileAggregateRequest& reque
                 return Status::NotSupported("Missing ORC stripe statistics for 
stripe {}",
                                             stripe_index);
             }
+            // COUNT skips decoding even for complex arguments. Every DATE 
leaf must be safe,
+            // including an unrepresentable day inside otherwise valid bounds, 
to preserve errors.
+            for (const auto column_id : date_column_ids) {
+                // Schema IDs can outlive truncated stripe statistics; the SDK 
lookup is unchecked.
+                if (column_id >= stripe_statistics->getNumberOfColumns()) {
+                    return Status::NotSupported("Missing ORC DATE statistics 
for COUNT");
+                }
+                const auto* date_statistics = dynamic_cast<const 
::orc::DateColumnStatistics*>(
+                        stripe_statistics->getColumnStatistics(column_id));
+                if (date_statistics == nullptr ||
+                    (date_statistics->getNumberOfValues() != 0 &&

Review Comment:
   [P2] Require a real all-NULL proof for ORC DATE COUNT
   
   The SDK returns zero when a column statistic omits its optional value count, 
as the file-level DATE check notes above. For a non-NULL struct `s` with an 
unrepresentable DATE child, the stripe can retain that child's DATE bounds 
while omitting its count. This guard ignores the bounds and returns the 
struct's non-NULL count. Materializing the same struct returns a DATE 
conversion error. Validate present DATE bounds regardless of the count, and 
fall back to reading values when there is no reliable all-NULL proof. Add an 
omitted-count case alongside the truncated-statistics fixture.



##########
be/src/format_v2/orc/orc_reader.cpp:
##########
@@ -2260,7 +2398,8 @@ Status OrcReader::_select_stripe_ranges_by_statistics() {
     uint64_t previous = range_first;
     for (size_t idx = 1; idx < selected_stripes.size(); ++idx) {
         const auto stripe_index = selected_stripes[idx];
-        if (stripe_index == previous + 1) {
+        if (stripe_index == previous + 1 &&
+            unsafe_date_stripes.contains(stripe_index) == 
unsafe_date_stripes.contains(previous)) {

Review Comment:
   [P3] Bound ORC reader setup across alternating DATE ranges
   
   Use a single split and an `id` predicate that can be pushed into ORC and 
matches every stripe. Alternate stripes containing `0000-02-28` and 
`0000-03-01` with stripes containing modern dates. All rows are representable, 
but the early stripes' bounds straddle the leap-day gap. This condition splits 
the scan at every stripe, and each SDK RowReader visits the whole stripe 
directory. The base used one reader for the contiguous range, so setup grows 
from linear to quadratic in the number of stripes. Bound reader creation while 
retaining DATE validation and cover the alternating layout with the ORC 
stripe-visit counter.



##########
tools/legacy_date_migration/migrate_legacy_dates.py:
##########
@@ -0,0 +1,205 @@
+#!/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':
+        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
+
+    # 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
+    # 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')
+    return reader, schema
+
+
+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 = _open_source(source, file_format)
+    chunks = (reader.read_stripe(i) for i in range(reader.nstripes)) if 
file_format == 'orc' else (
+        reader.iter_batches(batch_size=65536))
+    if destination.exists():
+        raise FileExistsError(destination)
+    # Publish with an exclusive hard link only after the writer succeeds, 
including its footer.
+    # An existence check alone races with another writer and could overwrite 
its output.
+    temporary = tempfile.NamedTemporaryFile(prefix='.legacy-date-', 
dir=destination.parent,
+                                           delete=False)
+    temporary_path = Path(temporary.name)
+    try:
+        with temporary:
+            writer = (orc.ORCWriter(temporary) if file_format == 'orc'

Review Comment:
   [P2] Preserve ORC CHAR values during DATE migration
   
   Doris exports a `CHAR(4)` value such as `x` as padded ORC CHAR and trims the 
padding when it reads that physical type. PyArrow 23 reads the padded bytes 
into Arrow UTF-8 and writes UTF-8 as ORC STRING, where Doris keeps the spaces. 
A confirmed legacy export with DATE and CHAR can migrate successfully and 
change `LENGTH(c)` from 1 to 4. Preserve the logical CHAR value or reject such 
files before publication, and cover a legacy ORC file containing physical CHAR. 
[Arrow ORC 
adapter](https://github.com/apache/arrow/blob/apache-arrow-23.0.0/cpp/src/arrow/adapters/orc/util.cc)



##########
be/src/format_v2/parquet/parquet_statistics.cpp:
##########
@@ -1084,6 +1084,15 @@ ParquetColumnStatistics 
ParquetStatisticsUtils::TransformColumnStatistics(
                                            ? &statistics->max_value
                                            : (statistics->__isset.max ? 
&statistics->max : nullptr);
 
+    if (!has_not_null && 
remove_nullable(column_schema.type)->get_primitive_type() == TYPE_DATEV2 &&

Review Comment:
   [P2] Check partial DATE bounds before sanitizing the footer
   
   The callers for COUNT, cache eligibility, and footer pruning call 
`sanitize_native_footer_statistics` first. It clears an unpaired `min_value` or 
legacy `min`, so this check never sees that evidence. A one-row nullable DATE 
with an unrepresentable ordinal, only a footer lower bound, and `null_count = 
num_values` still passes as all NULL. The levels-only COUNT can return 1, while 
a strict value scan reports a conversion error. Check the contradiction on the 
original statistics and add a reader test with only one bound. The direct 
`TransformColumnStatistics` unit test skips sanitization.



##########
tools/legacy_date_migration/migrate_legacy_dates.py:
##########
@@ -0,0 +1,205 @@
+#!/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':
+        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
+
+    # 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
+    # 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')
+    return reader, schema
+
+
+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 = _open_source(source, file_format)
+    chunks = (reader.read_stripe(i) for i in range(reader.nstripes)) if 
file_format == 'orc' else (
+        reader.iter_batches(batch_size=65536))
+    if destination.exists():
+        raise FileExistsError(destination)
+    # Publish with an exclusive hard link only after the writer succeeds, 
including its footer.
+    # An existence check alone races with another writer and could overwrite 
its output.
+    temporary = tempfile.NamedTemporaryFile(prefix='.legacy-date-', 
dir=destination.parent,
+                                           delete=False)
+    temporary_path = Path(temporary.name)
+    try:
+        with temporary:
+            writer = (orc.ORCWriter(temporary) if file_format == 'orc'
+                      else parquet.ParquetWriter(temporary, schema))

Review Comment:
   [P2] Preserve the INT96 timezone contract during migration
   
   The default PyArrow writer converts these INT96 columns to UTC-adjusted 
INT64 TIMESTAMP because the stored Doris Arrow schema carries the export 
timezone. The Doris reader applies `hive.parquet.time-zone` only to physical 
INT96. Take the Asia/Shanghai export and America/Los_Angeles read session from 
`test_doris_int96_round_trip.groovy`, and add a legacy DATE column. The 
original file returns `1970-01-01 08:00:00.654321` with the override. The 
migrated TVF infers TIMESTAMPTZ, and casting it to DATETIMEV2 in that session 
gives `1969-12-31 16:00:00.654321`. Preserve the INT96 read semantics or reject 
affected inputs before publication, and test a Doris read with a different 
session timezone. [PyArrow writer 
options](https://github.com/apache/arrow/blob/apache-arrow-24.0.0/python/pyarrow/parquet/core.py#L984-L1013)
 ยท [Timestamp 
mapping](https://github.com/apache/arrow/blob/apache-arrow-24.0.0/cpp/src/parquet/arrow/schema.cc#L160-L205)



##########
be/src/core/data_type_serde/data_type_datev2_serde.cpp:
##########
@@ -285,15 +301,10 @@ Status 
DataTypeDateV2SerDe::read_column_from_arrow(IColumn& column, const arrow:
             const uint8_t* raw_byte_ptr = base_ptr + value_i * element_size;
             auto date_value = unaligned_load<int32_t>(raw_byte_ptr);
 
-            // Arrow allows any int32 day, Doris DATE only day numbers 
1..DATE_MAX_DAYNR
-            // (0000-01-01..9999-12-31). For example, 2932897 is 10000-01-01: 
its day number
-            // 3652425 makes get_date_from_daynr() fail, and ignoring that 
result used to append
-            // a non-null 0000-00-00. Add in 64 bits so INT32_MAX cannot 
overflow, and reject
-            // the value like the DATE64 branch above.
-            const int64_t daynr = static_cast<int64_t>(date_value) + 
date_threshold;
             DateV2Value<DateV2ValueType> v;
-            if (daynr <= 0 || daynr > DATE_MAX_DAYNR ||
-                !v.get_date_from_daynr(static_cast<uint64_t>(daynr))) {
+            // Gregorian year zero has a leap day Doris cannot represent; 
ordinary day-number
+            // addition would also shift January and February by one day.
+            if (const auto status = decode_epoch_days(date_value, &v); 
!status.ok()) {

Review Comment:
   [P2] Handle year-zero DATEs across mixed-version Remote Doris connections
   
   `RemoteDorisFileReader::_materialize_arrow_column` uses this decoder for 
Arrow Flight results from another Doris cluster. A pre-fix remote BE writes 
`0000-01-01` as `-719527`, so an upgraded consumer silently returns 
`0000-01-02`. The same cluster pair reports a conversion error for remote 
`0000-02-28`. The file migration guide cannot repair a live stream. Provide a 
version-aware transport path for Doris-to-Doris DATEs, or detect and document 
the unsupported mixed-version pairing so it cannot silently return shifted 
dates.



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

Reply via email to