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


##########
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:
   Fixed in 2192e2e162. Migration retains physical INT96 as well as checked 
timestamp precision, preserving Doris type inference and hive.parquet.time-zone 
behavior. Mixed INT96/INT64 timestamp files are rejected before publication 
because the writer option applies to every timestamp. Python regressions pass, 
and an actual Doris read with the Shanghai override and Los Angeles session 
returns 1970-01-01 08:00:00.654321 both before and after migration.



##########
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:
   Fixed in 2192e2e162. Variant-owned DATE leaves retain raw Gregorian INT32 
days and are reconstructed with DATE identity, including 0000-02-29 without a 
DATEV2 intermediate. Ordinary typed DATE emission also uses the shared 
Gregorian mapping. Differential tests cover hardcoded raw days and JSON for 
shredded/unshredded values, full/partial projections, plain/dictionary 
encodings, and annotated/table-format override schemas. Numeric metadata 
comparisons are disabled for this raw DATE representation.



##########
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:
   Fixed in 2192e2e162. All Doris Arrow schema producers now publish 
doris.date.encoding=proleptic-gregorian-v1; FE Prepare/GetSchema advertise the 
same contract. A corrected Remote Doris consumer rejects ambiguous unmarked 
year-zero values and unknown markers before materialization, while skipping 
NULL-hidden children and unrequested columns. Malformed child offsets are 
rejected before inspection. Reader, schema/IPC and FE tests pass; actual Flight 
SQL and prepared-query regressions pass. The guide declares consumer-first 
upgrades, coordinated FE/BE completion for prepared DATE queries, and the 
unsupported reverse pairing. A real two-version cluster deployment was not run.



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