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


##########
be/src/format_v2/orc/orc_reader.cpp:
##########
@@ -2205,7 +2292,9 @@ Status OrcReader::_select_stripe_ranges_by_statistics() {
     int64_t filtered_bytes = 0;
     for (const auto stripe_index : split_stripes) {
         bool drop = false;
-        if (sarg_needed_stripes[stripe_index - split_stripes.front()] == 0) {
+        // An unsafe DATE must reach decoding, preserving strict errors or 
conversion-generated NULLs.
+        if (!unsafe_date_stripes.contains(stripe_index) &&

Review Comment:
   [P2] Preserve unsafe DATE errors on a condition-cache hit
   
   With condition caching enabled, run `SELECT d FROM orc_file WHERE id > 7` 
against a stripe whose rows all have `id = 0` and whose projected DATE contains 
`-719469`. The new guard keeps the stripe. A lazy scan can reject every row on 
`id` before decoding `d` and publish an all-false granule. An eager scan of the 
same split then reuses that entry because `enable_orc_lazy_materialization` 
does not enter the digest. `_skip_condition_cache_false_granules()` seeks past 
the range, so the warm eager scan succeeds where the cold eager scan reports 
the DATE conversion error. Skip condition-cache seeks for unsafe ranges that 
would otherwise decode DATE values and add cold/warm coverage.



##########
tools/legacy_date_migration/migrate_legacy_dates.py:
##########
@@ -0,0 +1,162 @@
+#!/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 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 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 = orc.ORCFile(source) if file_format == 'orc' else 
parquet.ParquetFile(source)

Review Comment:
   [P1] Preserve wide-range INT96 timestamps during migration
   
   A legacy Doris Parquet OUTFILE export with `enable_int96_timestamps=true` 
can contain a year-zero DATE beside a valid `DATETIMEV2(6)` such as `1600-01-01 
00:00:00`. PyArrow's default INT96 conversion narrows the timestamp to signed 
64-bit nanoseconds and wraps it into a different year. The stored Arrow schema 
does not restore the original unit, so the migration successfully publishes the 
changed timestamp alongside the corrected DATE. Read legacy Doris INT96 at 
microsecond resolution or reject unsafe input before publication. The existing 
round-trip test writes an ordinary INT64 timestamp near 1970, so add a 
wide-range INT96 case. [PyArrow reader 
defaults](https://github.com/apache/arrow/blob/apache-arrow-24.0.0/python/pyarrow/parquet/core.py#L227-L231)
 · [INT96 
conversion](https://github.com/apache/arrow/blob/apache-arrow-24.0.0/cpp/src/parquet/types.h#L666-L685)
 · [Arrow schema 
restoration](https://github.com/apache/arrow/blob/apache-arrow-24.0.0/cpp/src/parquet/arrow/schema.c
 c#L996-L1012)



##########
be/src/format_v2/parquet/parquet_reader.cpp:
##########
@@ -1216,6 +1216,56 @@ Status ParquetReader::get_aggregate_result(const 
format::FileAggregateRequest& r
         }
         const auto& count_projection = request.columns[0].projection;
         const auto& root_schema = projected_root_schema(_state->file_schema, 
count_projection);
+        std::vector<const ParquetColumnSchema*> date_leaves;
+        if (_state->enable_strict_mode ||
+            remove_nullable(root_schema.type)->get_primitive_type() == 
TYPE_DATEV2) {
+            const auto collect_dates = [&](auto&& self, const 
ParquetColumnSchema& schema,
+                                           const format::LocalColumnIndex* 
projection) -> void {
+                if (schema.kind == ParquetColumnSchemaKind::PRIMITIVE) {
+                    if (remove_nullable(schema.type)->get_primitive_type() == 
TYPE_DATEV2) {
+                        date_leaves.push_back(&schema);
+                    }
+                    return;
+                }
+                for (const auto& child : schema.children) {
+                    if (format::is_child_projected(projection, 
child->local_id)) {
+                        self(self, *child,
+                             format::find_child_projection(projection, 
child->local_id));
+                    }
+                }
+            };
+            collect_dates(collect_dates, root_schema, &count_projection);
+        }
+        const auto& footer = _state->file_context.native_metadata->to_thrift();
+        // Older writers can publish incorrect all-NULL counts. They must not 
let COUNT
+        // bypass DATE conversion when the same statistics are distrusted by 
normal reads.
+        const bool null_count_trusted =
+                native::parquet_reader_compat(footer.__isset.created_by ? 
footer.created_by : "")
+                        .null_count_trusted;
+        for (const auto* date_leaf : date_leaves) {
+            // Definition levels count physical NULLs only. DATE conversion 
can add logical NULLs
+            // or raise an error, including for nested children in strict 
mode. Validate every
+            // projected DATE leaf before allowing a levels-only count to 
bypass conversion.
+            for (const auto& row_group_plan : _state->scan_plan->row_groups) {
+                const auto& group = 
_state->file_context.native_metadata->to_thrift()
+                                            
.row_groups[row_group_plan.row_group_id];
+                const auto& chunk = group.columns[date_leaf->leaf_column_id];
+                if (!chunk.__isset.meta_data || 
!chunk.meta_data.__isset.statistics) {
+                    return Status::NotSupported("Parquet DATE COUNT requires 
value validation");
+                }
+                const auto stats = detail::sanitize_native_footer_statistics(
+                        date_leaf->type_descriptor, chunk.meta_data.statistics,
+                        detail::has_supported_type_defined_order(
+                                
_state->file_context.native_metadata->to_thrift(),
+                                date_leaf->leaf_column_id));
+                const auto decoded = 
ParquetStatisticsUtils::TransformColumnStatistics(
+                        *date_leaf, &stats, chunk.meta_data.num_values, 
_state->timezone,
+                        null_count_trusted);
+                if (!decoded.has_min_max && !(decoded.has_null_count && 
!decoded.has_not_null)) {

Review Comment:
   [P2] Reject contradictory all-NULL DATE statistics before COUNT
   
   A one-row required DATE chunk can contain `-719469` with that ordinal in 
both footer bounds and a contradictory `null_count = num_values = 1`. Footer 
validation accepts this combination. `TransformColumnStatistics()` classifies 
it as all NULL and returns before the DATE bounds check, so this gate accepts 
it and the required-column shortcut returns `COUNT(d) = 1`. A strict data scan 
would raise a conversion error. Require all-NULL metadata to agree with the 
DATE bounds and physical nullability before it can bypass conversion.



##########
be/src/core/value/vdatetime_value.h:
##########
@@ -1777,6 +1778,54 @@ inline uint32_t calc_daynr(uint16_t year, uint8_t month, 
uint8_t day) {
     return delsum + y / 4 - y / 100 + y / 400;
 }
 
+// Doris follows MySQL's calendar, in which year 0 is NOT a leap year (see 
`is_leap()`): 0000-02-29
+// does not exist and `calc_daynr()` therefore numbers 0000-01-01 .. 
0000-02-28 one day ahead of the
+// proleptic Gregorian calendar. Arrow `date32`, Parquet/ORC `DATE` and the 
Iceberg spec all define
+// their day ordinal in the proleptic Gregorian calendar, where year 0 IS a 
leap year. The two
+// numberings coincide from 0000-03-01 (daynr 60) onwards, so the whole 
difference is the missing
+// 0000-02-29. Every conversion between a Doris DATE and an external "days 
since 1970-01-01" value

Review Comment:
   [P2] Use the shared Gregorian conversion in `parquet_meta`
   
   For a corrected Parquet file containing only `0000-02-28`, a regular SELECT 
decodes the stored `-719470` as February 28. The public `parquet_meta` TVF 
still routes the footer bounds through `decode_statistics_value()` and 
`Int32ToDate` in `be/src/format/parquet/parquet_column_convert.h`. Its lookup 
uses the old MySQL day-number offset and reports February 27 for both bounds. 
Route metadata DATE conversion through the same checked helper and preserve the 
TVF's hexadecimal fallback for unrepresentable bounds.



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