Gabriel39 commented on code in PR #71397:
URL: https://github.com/apache/doris/pull/71397#discussion_r4795148086


##########
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:
   Fixed in 2192e2e162. The common ORC DATE proof now requires a positive count 
and explicit representable bounds. COUNT and DATE zone maps cannot treat 
missing/zero counts as an all-NULL proof, and DATE validation SARG includes the 
SDK all-NULL branch. Four fixtures with row-index stride 1000 cover 
zero/omitted counts in single/mixed stripes, scalar/nested COUNT, mixed MIN/MAX 
and eager SARG behavior. All pass. Genuine all-NULL DATE metadata also falls 
back conservatively because the public SDK loses count presence; that tradeoff 
is documented.



##########
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:
   Fixed in 2192e2e162. When DATE sanitization discards the raw bounds, it also 
discards the null-count proof, so normalization cannot manufacture an all-NULL 
column. Reader regressions cover required/nullable columns with complete 
bounds, either single modern or deprecated bound, and missing TYPE_ORDER. COUNT 
declines pushdown and the strict data scan reports DATA_QUALITY_ERROR in every 
contradictory case.



##########
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:
   Fixed in 2192e2e162. ORC physical schemas are inspected with PyORC before 
values are materialized. CHAR at any supported nested position is rejected 
before temporary output/publication; STRING and VARCHAR values are not trimmed. 
Five CHAR shape regressions pass, including MAP keys/values. Actual Doris SQL 
reproduced LENGTH changing from 1 to 4 before the fix; the corrected migration 
publishes no output for that file. The dependency and unsupported-schema limits 
are documented.



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