Repository navigation
[fix](be) Reject Arrow timestamps outside the DATETIMEV2 and TIMESTAMPTZ ranges - #69697
Conversation
…PTZ ranges ### What problem does this PR solve? Issue Number: None Related PR: apache#69581 Problem Summary: An Arrow timestamp whose civil year is outside 0000..9999 was read as a different value. `DataTypeDateTimeV2SerDe::read_column_from_arrow` converted each value with `DateV2Value::from_unixtime()`, which passes the cctz year to `unchecked_set_time(uint16_t year, ...)` without a check, and nothing checked the result. So timestamp(us) 2005980768000000000 (65537-01-01 00:00:00) read as a non-null 0001-01-01 00:00:00, the years 10000..65535 were stored as DATETIMEV2 values outside its range, and years before 0000 wrapped as well. The TIMESTAMPTZ Arrow path converts through the same `from_unixtime()` and called `is_valid_date()` only after packing, which a year wrapped back into 0000..9999 passes. ADBC, Arrow stream load, paimon-rust and remote Doris reads all decode Arrow timestamps through these SerDes, nested leaves included. apache#69581's review found it for Lance. DATETIMEV2 now converts to civil time in the value's time zone and rejects a year outside 0000..9999 before packing, as the ORC path does since apache#68516 (`orc_timestamp_to_datetime()`); a zoned timestamp is checked after the shift to the session time zone. TIMESTAMPTZ, which is stored in UTC, checks the instant against 0000-01-01 00:00:00 UTC .. 9999-12-31 23:59:59.999999 UTC before converting, so its check after packing can no longer fail and becomes a DCHECK; the message now names the 0000-9999 range it enforces, as `is_valid_date()` already accepted year 0. Both fail the read with DataQualityError. NULL slots are still skipped before conversion. The Parquet INT64 and INT96 timestamp paths validate the UTC range before packing (`parquet_timestamp_micros()`, `parquet_int96_timestamp_micros()`), so they could not wrap and behave as before. Arrow reads into DATE and DATETIME (v1) use `VecDateTimeValue::from_unixtime()`, which has the same unchecked narrowing; those deprecated types are not changed here. ### Release note Reading an Arrow timestamp whose year is outside 0000..9999 into DATETIMEV2 or TIMESTAMPTZ (ADBC, Arrow stream load, paimon-rust, remote Doris) now fails instead of returning a different date. ### Check List (For Author) - Test: Unit Test - New `DataTypeDateTimeV2SerDeTest.RejectsArrowTimestampsOutsideDateTimeV2Range` (the last and first instants of the range pass; 10000-01-01, 65537-01-01 and the last microsecond of year -1 fail; a zoned value is checked at +08:00), `RejectsNestedArrowTimestampOutsideDateTimeV2Range` (an ARRAY leaf) and `DataTypeTimeStampTzSerDeTest.RejectsArrowTimestampsOutsideTimestampTzRange`. - With the previous DATETIMEV2 code, both DATETIMEV2 tests fail (10000-01-01 and 65537-01-01 read without an error); with the previous TIMESTAMPTZ code, 65537-01-01 reads as a valid value and the TIMESTAMPTZ test fails. - The two SerDe suites and the Arrow and Parquet SerDe suites pass on macOS arm64 (ASAN), run on a tree that also carries apache#69581, whose Lance reader suites pass with it (279 tests in all). - Behavior changed: Yes. See the release note. - Does this need documentation: No Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Thank you for your contribution to Apache Doris. Please clearly describe your PR:
|
|
run buildall |
|
/review |
There was a problem hiding this comment.
Static review of head 3f336d2294cb9d06ba42e055d08ae2b99cb4d673: two verified P2 correctness regressions are recorded inline. The year checks prevent the intended wraparound, but NULL complex ancestors and Doris' year-zero calendar rule need handling before the change is correct. No existing inline findings were present; there are no existing P0/P1 comments to carry forward. No additional user focus was supplied.
Critical checkpoint conclusions:
- Goal and proof: the added unit cases exercise year 10000/65537/-1 rejection, supported endpoints, a session-zone upper boundary, and a visible ARRAY timestamp leaf. They miss both reported regressions.
- Scope and reuse: the two production changes are small and focused and follow the ORC pre-narrowing pattern; no unrelated code or interfaces were added.
- Concurrency and locking: conversion runs synchronously on caller-owned mutable columns; no new shared mutable state, threads, locks, or lock ordering.
- Lifecycle and initialization: added values are local or constexpr; the existing function-local UTC object has no new cross-TU dependency, ownership cycle, or resource lifetime.
- Configuration: no settings added or changed; existing Arrow input validation does not combine ancestor validity.
- Compatibility: packed column and storage layouts, function interfaces, and rolling-upgrade protocols are unchanged. External-input validation changes as intended, with the two inline exceptions requiring correction.
- Thrift/protobuf IDs: no generated definitions changed.
- Parallel paths: both timestamp types and their nullable/ARRAY/MAP/STRUCT delegates were traced. ORC already checks the civil year; Parquet INT64/INT96 validates its 0001..9999 range before the shared TIMESTAMPTZ helper. Legacy DATE/DATETIME narrowing and unrelated precision behavior predate this PR.
- Conditional checks: the new branches document concrete wraparound examples. The removed calendar-validation branch cannot safely become DCHECK because year bounds do not prove Doris calendar validity.
- Test coverage: existing tests add ordinary Arrow units, negative fractions, scaling, direct leaf NULL payloads, and timezone-naive behavior. Add year-zero February 29 and NULL-ancestor cases; no end-to-end test for these cases is present.
- Test results: no generated result files changed; new expected scalar values/error messages match the inspected logic. Builds, tests, sanitizers, benchmarks, formatting checks, and runtime validation were not run under this static-only contract.
- Observability: the new DataQualityError messages carry epoch/type context; no new metrics or per-row logging is needed for these local checks.
- Transactions and persistence: no transaction, visible-version, delete-bitmap, EditLog, replay, or master-failover code changed.
- Data mutation and atomicity: only transient destination columns are appended. Reader Status propagation and scanner publication prevent partially converted failed batches from becoming output; no separate persistence or cleanup defect was found.
- FE/BE propagation: no new variables or metadata cross the boundary.
- Performance: constant work per value; DATETIMEV2 retains one cctz conversion, with no new large allocations, copies, repeated scans, or row-wise COW detachment. No additional static performance issue was found.
- Other BE obligations: allocation-aware column storage and mutable ownership remain unchanged. Test-only header additions introduce no hub-header, template-instantiation, unity .cpp inclusion, or new libc API concern; final ELF compatibility was not executed.
All four changed files, candidate dispositions, and both initial risk areas were covered. The calendar invariant failure and NULL-ancestor failure are separate findings; repeated instances were deduplicated. There are no unresolved static review questions. Validation remains limited to source inspection.
Review converged after 3 round(s).
| "Decoded TIMESTAMPTZ is outside the Doris 0001-9999 range: micros={}", | ||
| timestamp_micros); | ||
| } | ||
| DCHECK(timestamp_tz.is_valid_date()); |
There was a problem hiding this comment.
[P2] Keep the runtime calendar-validity check for TIMESTAMPTZ
The new epoch interval does not imply is_valid_date(). Arrow timestamp(MICRO) value -62162121600000000 is UTC 0000-02-29 00:00:00 and passes these bounds. cctz's Gregorian leap-year rule accepts year-zero February 29, whereas Doris is_leap(0) in util/time_lut.h explicitly returns false, so the resulting value fails DateV2Value::is_valid_date(). Previously this input returned DataQualityError; now it aborts a DCHECK-enabled BE or appends an invalid TIMESTAMPTZ when DCHECK is disabled (UTC formatting can then emit only +00:00). Keep the new pre-narrowing bounds check, retain a runtime validity failure after conversion, and add this leap-day input to the unit test.
There was a problem hiding this comment.
Fixed in 6c1fd8f. The range check before packing stays, and append_timestamptz_from_utc_epoch_micros checks is_valid_date() at run time again after packing instead of the DCHECK, so -62162121600000000 (0000-02-29 UTC) fails with Decoded TIMESTAMPTZ is not a valid Doris date, as it did on master. The DATETIMEV2 Arrow path checked only the civil year and stored that date as an invalid DATETIMEV2 (it did so before this PR too); it now checks is_valid_date() after packing as well. RejectsArrowTimestampsOutsideTimestampTzRange and RejectsArrowTimestampsOutsideDateTimeV2Range read the leap day and expect DataQualityError; both fail when the new checks skip that value. orc_timestamp_to_datetime() has the same year-only check and is left to a change of its own.
| // as orc_timestamp_to_datetime() does for ORC. | ||
| const auto civil = cctz::convert( | ||
| cctz::time_point<cctz::seconds>(cctz::seconds(seconds)), real_ctz); | ||
| if (civil.year() < 0 || civil.year() > 9999) { |
There was a problem hiding this comment.
[P2] Mask NULL ancestors before validating nested timestamp leaves
A valid nullable Arrow STRUCT can have parent validity [false, true] and a non-null timestamp(MICRO) child containing [2005980768000000000, 0]; its logical rows are [NULL, {ts:1970-01-01}]. Arrow specifies independent parent/child validity. DataTypeNullableSerDe copies the parent bitmap, then DataTypeStructSerDe passes field(i) unchanged, so the leaf's IsNull(0) is false and this new check rejects the hidden year-65537 payload. The previous conversion's wrapped year was hidden by the NULL parent, so this batch succeeded. The same regression affects the new TIMESTAMPTZ check and NULL LIST parents with arbitrary nonempty child spans. Normalization leaves ordinary struct/list timestamp arrays unchanged, and stream-load/ADBC callers propagate the error, failing a read whose visible timestamps are valid. Carry ancestor validity or skip/default children of NULL parents before applying either check, and add mixed NULL/non-NULL parent coverage.
There was a problem hiding this comment.
Agreed on the mechanism. The fix is the NULL-parent masking in #69581 rather than a second copy here: df95b41 (mask_arrow_children_hidden_by_null_parents) masks the child slots of NULL list, map and struct rows in the shared nested SerDes before any leaf SerDe reads them, so the leaf checks of this PR never see a hidden payload, for every Arrow caller. ArrowParentNullsTest there covers mixed NULL / non-NULL parents and child offsets.
I checked your example on a tree with both PRs: a STRUCT with rows [NULL, {ts: 0}] whose NULL row carries 2005980768000000000, and a LIST [NULL, [0]] whose NULL row spans that value, both read two rows with row 0 NULL. With the masking taken out, the STRUCT case fails with Arrow timestamp 2005980768000000000 of type timestamp[us] is outside the DATETIMEV2 range. This PR will be merged after #69581, so master does not carry the regression in between; the description now says so. When this PR is rebased onto #69581, I will add your STRUCT and LIST cases here as a test.
There was a problem hiding this comment.
Follow-up on the STRUCT and LIST cases promised above. This PR was merged on 2026-11-03, before #69581, so the cases went into #69581 instead, which was merged on 2026-11-06 as 0d1ae9e: DataTypeDateTimeV2SerDeTest.IgnoresArrowTimestampsHiddenByNullParents in be/test/core/data_type_serde/data_type_serde_datetime_v2_test.cpp. For both DATETIMEV2 and TIMESTAMPTZ, it hides 65537-01-01 (2005980768000000000) under the NULL row of a LIST, a FIXED_SIZE_LIST, a MAP value and a STRUCT. The NULL row reads as NULL and the visible rows keep their values, while the same value in a visible row still fails with the range error. Returning the child unmasked from mask_arrow_children_hidden_by_null_parents fails the test, and dropping only the STRUCT mask fails it at the STRUCT case.
A correction to my reply above: master did carry the regression between the two merges, from 2026-11-03 to 2026-11-06. In that window, a batch whose NULL list, map or struct row hid an out-of-range timestamp failed with DataQualityError instead of being read. It raised an error and did not return wrong values.
TPC-H: Total hot run time: 28575 ms |
TPC-DS: Total hot run time: 151836 ms |
ClickBench: Total hot run time: 24.41 s |
BE UT Coverage ReportIncrement line coverage Increment coverage report
|
BE Regression && UT Coverage ReportIncrement line coverage Increment coverage report
|
### What problem does this PR solve? Issue Number: None Related PR: apache#69697 Problem Summary: The range check added before packing an Arrow timestamp does not make every instant inside the range a Doris date. cctz counts year 0 as a leap year and Doris does not (is_leap(0) in util/time_lut.h is false), so timestamp(us) -62162121600000000, 0000-02-29 00:00:00 UTC, is inside 0000-01-01Z..9999-12-31Z but packs into a value that is_valid_date() rejects. For TIMESTAMPTZ this PR had turned the runtime is_valid_date() check after packing into a DCHECK, so that input aborted an ASAN or debug BE and appended an invalid TIMESTAMPTZ in a release build, where master returns DataQualityError. The DATETIMEV2 Arrow path checks only the civil year, so the same date at the session time zone was stored as an invalid DATETIMEV2, as it was before this PR. Both paths now check is_valid_date() at run time after packing and return DataQualityError for such a value. The ORC path (orc_timestamp_to_datetime) has the same year-only check and is not changed here. ### Release note None ### Check List (For Author) - Test: Unit Test - BE UT RejectsArrowTimestampsOutsideTimestampTzRange and RejectsArrowTimestampsOutsideDateTimeV2Range read -62162121600000000 and expect DataQualityError; both fail when the new checks skip that value. The serde, Arrow round-trip, nested serde and Lance reader suites (168 tests) pass. - Behavior changed: Yes. An Arrow timestamp on 0000-02-29 is rejected instead of being stored as an invalid date. - Does this need documentation: No Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
/review |
There was a problem hiding this comment.
Static review of head 6c1fd8f8ab037fba68da24861bb618d5d3cdab9a found no new valuable correctness issue beyond the existing inline context.
I reviewed both production SerDes changes and both added test files against the authoritative diff, then traced the Arrow, nullable/nested, Parquet, decoded-value, and ORC paths. The DATETIMEV2 civil-year check, TIMESTAMPTZ epoch bounds, year-zero calendar validation, negative-time normalization, timezone boundary, scale carry, and caller error/null-on-failure behavior are internally consistent. The added branches document their wraparound cases; no new hub-header, COW, template-instantiation, unity, Thrift/protobuf, locking, lifecycle, or performance concern was found.
Existing inline P2 comment 4390157295 (year-zero calendar validity) is addressed in this head and was not reposted. Existing inline P2 comment 4390157310 (hidden timestamp payloads beneath NULL LIST/STRUCT/MAP ancestors) is already-known context and remains dependent on the separate #69581 masking change; it was not duplicated. Neither is a P0/P1 ID, so existing_blocking_comment_ids is empty. The user focus file contains no additional focus.
Validation was static only under the review contract: no builds, tests, sanitizers, benchmarks, formatting checks, service startup, or runtime validation were executed. git diff --check was clean.
Review delivery is separate from convergence. The final main-agent sweep found no accepted new finding and covered all four changed paths and all ledger dispositions. Convergence is false because the unchanged-byte independent final-review confirmations for rounds 2 and 3 could not be obtained after repeated runner interruptions; the verified review is still delivered at the bounded round limit.
Review did not converge after 3 rounds. This automated review cannot pass the review check.
At the three-round cap, the main static sweep verified all changed paths, existing-thread dispositions, and no new finding, but the required unchanged-byte final reviewer confirmations were lost to repeated runner interruptions/model-capacity exits. The existing P2 NULL-ancestor thread is known context and was not duplicated; no additional unverified candidate remains.
|
run buildall |
TPC-H: Total hot run time: 28596 ms |
TPC-DS: Total hot run time: 152030 ms |
ClickBench: Total hot run time: 24.42 s |
|
/review |
|
Codex automated review failed and did not complete. Error: Selected model is at capacity. Please try a different model. Please inspect the workflow logs and rerun the review after the underlying issue is resolved. |
|
/review |
There was a problem hiding this comment.
Reviewed all four changed files and the related Arrow callers, nested SerDes, date packing/rounding, and shared Parquet consumers at head 6c1fd8f8ab037fba68da24861bb618d5d3cdab9a. No new nonduplicate findings.
The existing NULL-ancestor finding still applies to this exact head: nullable parent bitmaps are copied without masking child arrays, so a hidden out-of-range timestamp can fail an otherwise valid batch. The author explicitly requires #69581 to merge first; it was still open/unmerged when checked. Preserve that prerequisite and revalidate after rebasing, including the promised mixed-NULL STRUCT/LIST cases. I have not verified the author's combined-tree runtime results. This is already reported and is not reposted.
The existing calendar-validity finding is fixed: TIMESTAMPTZ retains a runtime is_valid_date() failure after packing, and both readers have year-zero February 29 negative tests. Both existing findings are P2; there are no independently confirmed existing P0/P1 comments to list as blockers.
| Required checkpoint | Conclusion |
|---|---|
| Goal and correctness | Range checks precede narrowing and prevent year 65537 from wrapping to year 1. Calendar checks reject 0000-02-29. The known NULL-parent prerequisite above remains applicable. |
| Scope and clarity | Focused changes to two reader implementations and two unit-test files; concrete failure examples explain the checks. |
| Concurrency and locks | No new threads, shared mutation, locks, or lock ordering. Conversion uses caller-owned mutable columns. |
| Lifecycle and initialization | New values/constants are local or constexpr; the existing UTC static is unchanged. No new ownership or cross-TU initialization dependency. |
| Configuration | No configuration changes. |
| Compatibility | No function signature, packed representation, storage/block format or rolling-upgrade protocol changes. No new libc API/dependency; final ELF/GLIBC requirements were not measured. |
| Thrift/protobuf | No definition changes. |
| Parallel paths | All Arrow units use the checks. TIMESTAMPTZ's shared Parquet callers already enforce a narrower 0001..9999 interval, preserving their accepted values. ORC's existing civil-year check and legacy DATE/DATETIME paths were compared; their pre-existing differences are unchanged. |
| Conditional checks and errors | Conditions have reachable out-of-domain examples and explanatory comments. Runtime calendar validity remains essential inside the epoch interval. Callers propagate non-OK Status. |
| Test coverage | New unit cases cover accepted endpoints, adjacent invalid epochs, year-wrap, year-zero leap day, a session-zone boundary and a visible ARRAY leaf. Existing tests cover units, negative fractions, direct NULL leaves and rounding. New tests omit mixed-NULL STRUCT/LIST parents and range-edge cases for every unit; no end-to-end execution was performed. |
| Test results | Expected epoch literals and formatted values were reviewed. No golden results changed. Tests were inspected, not run. |
| Observability | Conversion errors identify the source timestamp and type or microsecond value; existing Status propagation is sufficient for these deterministic failures. |
| Transactions and persistence | No transaction, EditLog, failover or persistence changes. |
| Data writes and atomicity | Changes affect decoding; errors abort the read rather than publish a successful partial batch. Parquet strict-error rollback is preserved. No new crash-sensitive resource ownership. |
| FE/BE variable propagation | No new variables or transmitted metadata. |
| Performance | DATETIMEV2 still performs one civil conversion per visible row; added checks are constant time and add no owning buffers or copies. No benchmark was run. |
| Other core invariants | Column ownership/COW and memory tracking are unchanged; no visibility, version or delete-bitmap changes. No additional independently verified issue. |
No additional user-provided focus was supplied. Static source review is complete; no builds, tests, runtime validation, binary audits or source modifications were performed. The combined #69581 tree and future merge ordering remain outside this exact-head validation.
Converged in 1 review round: both complete-review agents and the separate risk-focused agent returned NO_NEW_VALUABLE_FINDINGS; every changed hunk and risk focus was reviewed, and all candidates were verified as fixed, already covered, or dismissed with evidence. No unresolved new review question remains.
Review converged after 1 round(s).
BE Regression && UT Coverage ReportIncrement line coverage Increment coverage report
|
|
run external |
BE Regression && UT Coverage ReportIncrement line coverage Increment coverage report
|
|
PR approved by anyone and no changes requested. |
|
PR approved by at least one committer and no changes requested. |
…output block ### What problem does this PR solve? Issue Number: None Related PR: apache#69581 Problem Summary: Reproduction: load one large Arrow IPC batch through Arrow stream load with a nested column that has NULL rows. For example, take 2^24 LIST<INT> rows that alternate between [1] and NULL (2^23 child values), read in blocks of 4096 rows. Every block allocates a 1 MiB validity bitmap, zero-fills it and copies the child's validity into it, so the batch allocates 4 GiB and writes 8 GiB from the query's Arrow pool. A STRUCT field costs N^2/B bits per batch the same way. So does a NULL list row whose producer left values in its span. Root cause: `mask_arrow_children_hidden_by_null_parents()` was added earlier in this PR so that element SerDes never decode child values hidden by a NULL list, fixed-size-list, map or struct row. At the first NULL parent row of the requested range, it allocated a bitmap covering the whole child and copied the child's validity, before it looked at that row's child span. A NULL row that owns no slots, as Arrow's list and map builders write it, or only NULL slots, hides nothing but paid the same. `ArrowStreamReader` keeps each IPC batch and hands the SerDes one row range per output block, and the mask is thrown away after each call, so the bitmap was rebuilt for every block. The map SerDe builds one for the keys and one for the items, and the struct SerDe one per field. Since the bitmaps come from ExecEnv's accounted Arrow pool, these temporary allocations also count against the query's memory limit. Fix: 1. `mask_arrow_children_hidden_by_null_parents()` reads a NULL row's child span first and skips the row when the span is empty or has no set validity bit in [offset + begin, offset + end). A child without a validity buffer counts as all valid. The bitmap is allocated at the first row that really hides a valid value. The check, `has_valid_slot()`, is now shared with `mask_unreferenced_slots()`, the slot mask of the Lance path. A NULL row that hides a valid value is still masked, and its bitmap still comes from ExecEnv's Arrow pool. Offsets are still read through the SerDes' unaligned loads, still after their offset validation, and an Arrow Null child is still returned as it is. 2. `ArrowStreamReader::_prepare_arrays()` masks each column of a retained batch once, after the existing normalization and cast. It uses `mask_arrow_descendants_not_visible()` with the reader's accounted pool. The per-block SerDe calls then find nothing left to hide and allocate nothing. If this mask fails, the error names the column the way the per-block errors do. It rejects only offsets that reach outside the child or run backwards at a NULL row. `enable_arrow_input_validation` (on by default) rejected those batches as well, in the block that read them. What remains: a MapArray cannot hold NULL keys, so the per-batch mask leaves the keys alone. A NULL map row that still owns entries therefore costs each block a key bitmap. Arrow's map builder writes NULL map rows without entries. The other Arrow readers (ADBC, remote Doris, Lance, the Arrow block convertor, Python UDTF) read each batch with one SerDe call, so they pay for the mask at most once per batch. paimon-rust reads row ranges of batches about the size of a block. Before: every block of a large nested batch with a NULL row allocated and filled a bitmap the size of the whole child. After: the blocks allocate nothing from the SerDes' pool, and each batch is masked at most once per nested level. In the example above nothing is allocated at all, because the NULL rows own no values. Also covered: the NULL-parent case of the DATETIMEV2 / TIMESTAMPTZ range checks from apache#69697. That PR merged before this one and its tests use visible values only. master, branch-4.1 and branch-4.2 have no parent-null masks (this PR adds them), so nothing needs porting. ### Release note None ### Check List (For Author) - Test: Unit Test - New: `ArrowParentNullsTest.AllocatesNothingForNullRowsThatHideNothing` covers LIST rows that alternate [1] and NULL, read two rows per call; a NULL MAP row without entries (keys and items); and LIST and FIXED_SIZE_LIST NULL rows over NULL slots. Each returns the child itself and allocates nothing from the Doris Arrow pool. A NULL row over valid values next to them is still masked, with one bitmap. - New: `LoadArrowPipeTest.Null{List,FixedSizeList,Map,Struct}BatchReadsInBlocksWithoutPerBlockMasks` read one IPC batch of 64 rows four rows per block through `ArrowStreamReader`, with every fourth row NULL. No block allocates from the pool the SerDes mask with, and every row reads as one SerDe call over the whole batch reads it. - New: `DataTypeDateTimeV2SerDeTest.IgnoresArrowTimestampsHiddenByNullParents` hides 65537-01-01 under a NULL LIST, FIXED_SIZE_LIST, MAP value and STRUCT row, as DATETIMEV2 and as TIMESTAMPTZ. It reads as a NULL element, while the same value in a visible row fails with the range error. - Done: `run-be-ut.sh --run --filter=...` (ASAN, macOS arm64) over 24 suites: `ArrowParentNullsTest`, `LoadArrowPipeTest`, the DATETIMEV2 / TIMESTAMPTZ, Arrow, Arrow validation, array, map and struct SerDe suites, `ArrowColumnToDorisColumnTest`, `ArrowBlockConvertorTest`, `AdbcReaderTest`, `RemoteDorisV2ReaderTest`, `PaimonRustTableReaderTest` and `Lance*`: 328 of 328 pass. clang-format 16 and `check-build-hygiene.sh` pass. - Mutations: allocating at the first NULL row of each call again (B1 off) fails the new `ArrowParentNullsTest` case and the four new `LoadArrowPipeTest` cases; dropping the per-batch mask's result (B2 off) fails the LIST and STRUCT `LoadArrowPipeTest` cases (the reader casts a FIXED_SIZE_LIST to a compacted LIST, and a NULL map row owns no entries, so B1 covers those two); returning the child unmasked fails the new timestamp case, four `ArrowParentNullsTest` cases and `LanceTableReaderTypeTest.IgnoresDate32PayloadHiddenByNullParents`. - Behavior changed: No (the values read are unchanged; only the allocations change) - Does this need documentation: No Co-Authored-By: Claude Opus 5.5 <[email protected]>
### What problem does this PR solve? Issue Number: None Related PR: #65730 #66608 #66805 #66841 #66999 #67005 #67011 #67110 #67268 #67289 #67325 #67650 #67921 #68028 #68335 #68375 #68615 #68690 #68813 #68815 #68707 #68649 Problem Summary: **In short.** This ports the Lance BE read path of branch-4.1 / branch-4.2 to master, in its branch-4.2 form as of `cabcf45c1af`, plus the BE side of three 4.x changes merged after that snapshot: the search filter `prefilter` flag and profile layout (#68813), distance bounds for `vector_search` (#68815), and the split-level index rule of #68707 that #68815 relies on. It gathers the BE parts of the PRs listed above. Master links `liblance_c` but has no Lance reader, so every `FORMAT_LANCE` scan fails today. With this PR the BE reads Lance datasets through FileScannerV2: plain scans, vector search and full-text search, predicate and runtime-filter pushdown, the schema fetch of a local Lance TVF, and the second phase of TopN lazy materialization. The PR is BE only. The FE connector plugin and the regression suites come in separate PRs, so until then nothing on master plans a Lance scan, and the BE unit tests carry the proof. Original authors: @zhangstar333 @Gabriel39 @wangzhaobo957-cloud @Jay-ju @FANNG1 **Background.** Lance shipped in 4.1.4: the Lance catalog, `local()` / `s3()` with `format=lance`, and the `vector_search` / `full_text_search` TVFs. On master the FE side is being rebuilt as a connector plugin (`fe-connector-lance`), and the BE needs the reader from 4.x. The thrift ids are the branch-4.1 / 4.2 ones, including `TExternalSearchRequest.5` (`prefilter`) and `TVectorSearchParams.6/7` (distance bounds) added after the snapshot, so a BE built from master also reads the Lance scan ranges and search requests that a 4.x FE sends during a rolling upgrade. The one exception is `TVectorSearchOptions` 6, branch-4.2's `approx_mode` (#69852, merged into branch-4.2 after the snapshot and not ported): it is reserved in a comment, and a master BE ignores it, so during a rolling upgrade a 4.2 FE that asks for `fast` or `accurate` gets Lance's default (`normal`). **The problem, and what it cost.** | | master today | with this PR | |---|---|---| | A `FORMAT_LANCE` scan | FileScannerV2 has no Lance reader, so the scan fails with "FileScannerV2 does not support file format" | read by `LanceTableReader` in FileScannerV2 | | `fetch_table_schema` for a local Lance TVF | not handled | returns the Arrow schema mapped to Doris types; Null leaves keep `NULL_TYPE` | | The row location of a Lance row in TopN lazy materialization | `GlobalRowLoacationV2` only has a 32-bit row id, but a Lance row id is a 64-bit id within the snapshot | a version 1 layout carries the 64-bit row id; phase two reads the rows with the dataset's `take_rows` | **How this PR fixes it.** - Reader: `be/src/format_v2/lance/*` and `be/src/format_v2/table/lance_reader.*`, as on branch-4.2 except one local renamed for master's `-Wshadow`. The unit tests construct `RuntimeState(TQueryOptions(), globals)`, because master removed the globals-only constructor. - FileScannerV2: the reader dispatch and `_to_file_format` handle `FORMAT_LANCE` / `"lance"`; `FileFormat::LANCE` is added to its two exhaustive switches. Since #69723 every file scan uses FileScannerV2, so nothing else routes Lance scans (on branch-4.2 a Lance query fails with NotSupported when `enable_file_scanner_v2` is off). - Row locations: `ROW_VERSION {FILE_LOCAL_ROW_ID = 0, LANCE_DATASET_ROW_ID = 1}` and a union layout for `GlobalRowLoacationV2`. Version 0 keeps its byte layout, which static asserts pin. `PRequestBlockDesc.row_id` becomes `uint64` (a proto2 varint, so the wire format is compatible). The materialization operator decodes row locations by version, rejects an unknown version or a wrong size, and stamps `row_location_version`. `RowIdStorageReader` validates the counts and the version, range-checks internal row ids against `uint32`, and groups Lance rows by plan node, snapshot version and dataset URI, so each dataset is read with one `take_rows`. Master's segment batching, scan-slot dedup and fetch concurrency stay as they are. - Thrift (`PlanNodes.thrift`): the external search request body (`TVectorElementType`, `TVectorMetric`, `TSearchVector`, `TVectorSearchParams` 1-7, `TFtsCoverageMode`, `TFtsQueryType`, `TFtsMatchOperator`, `TFullTextSearchParams`, `TSearchFilterFormat`, `TSearchFilter`, `TVectorSearchOptions`, `TExternalSearchQuery`), `TExternalSearchRequest` 2-5 and `TLanceFileDesc` 4-6, all with the branch-4.1 / 4.2 ids. The enums spell out their 4.x values. No id is reused. On master, #70075 reserved `TExternalSearchRequest` 2-5 in comments and added 6 (`paimon_options`); this PR replaces those comments with the fields and leaves 6 as it is. `TVectorSearchOptions` 6 is reserved in a comment for branch-4.2's `approx_mode` (#69852). - After the snapshot (one commit each): - #68813: `prefilter` decides whether the TVF search filter runs before (true) or after (unset / false) candidate selection, for vector and full-text search. The profile groups the Lance counters under `LanceTiming`, `LanceIO`, `LanceIndex`, `LanceVectorIndex`, `LanceScalarIndex`, `LanceExecutionPlan`, `LanceScan`, `LanceSearchPlan` and `LanceDataCache`, uses the 4.x counter names, and registers every scan metric before the statistics callback is installed, so the callback, which Lance invokes from its execution streams, never adds counters. #68813's FE tweak that hides `TUnit.NONE` labels in `AggCounter` belongs to the FE port. - #68707 (part): a vector split searches exactly the index segments FE planned for it, and a split without segments is searched flat whatever `use_index` says; a split with segments under `use_index = false` is rejected. 4.x FEs plan segments only when `use_index` allows them. - #68815: `distance_lower_bound` (inclusive) and `distance_upper_bound` (exclusive) are validated (finite FLOAT values, lower < upper at FLOAT precision, single-vector only) and installed with `lance_scanner_set_distance_range()`, which master's pinned lance-c provides. - Review fixes: - A nested array goes to the Doris SerDes without a copy only when it and every descendant start at offset 0 and reference exactly their child ranges. Lance's legacy (v1) decoder can return a struct or list that is tight at its own level over a Boolean child with a bit offset (a batch that starts mid-byte in the bitmap), and the SerDes reject that under Arrow input validation. - A zero-field `STRUCT<>`, which Lance decodes, is reported as an unsupported column at any nesting level, like the other unsupported Lance types. It used to be typed as a STRUCT that `ColumnStruct` cannot hold (its row count comes from its first child). - A Lance Decimal256 field with precision <= 38 is narrowed to Decimal128 by a safe Arrow cast before decoding. Doris types it DECIMAL32/64/128I by precision, and those SerDes read only Decimal128 arrays; the BE used to crash on the first value, also for nested leaves. Only values a reader can see are cast: before a nested leaf is narrowed, every child slot that no visible row references (under a NULL list, fixed-size-list, map or struct row, or outside a sliced parent) is marked NULL, so a hidden value does not fail the cast and a visible value outside the declared precision still does; map keys, which cannot be NULL, stay checked. - FLOAT / DOUBLE `>=` runtime filters stay residual-only. Lance compares floats by totalOrder, so a pushed `x >= c` dropped negative-NaN rows that Doris keeps. - Runtime filters that mention INT64_MIN stay residual-only. The pinned Lance SQL parser reads `-9223372036854775808` as the negation of a magnitude that it parses as i64 first; the overflow turns the literal into a Float64, which the planner cannot coerce to Int64 or Decimal, so a pushed IN, `>=` or `<=` filter on an INT64 or scale-zero decimal column failed planning and the query failed. Every other i64 is still pushed. - The shared Arrow DATE32 decoding (`DataTypeDateV2SerDe::read_column_from_arrow`) rejects days outside 0000-01-01..9999-12-31 instead of returning a non-null `0000-00-00`, skips null slots and adds the epoch in 64 bits: the DATE32 range part of branch-4.1 / 4.2 #68649. It also changes ADBC, Arrow stream load and paimon-rust reads. - Child values hidden by a NULL list, fixed-size-list, map or struct row are not decoded: the array, map and struct SerDes give the element SerDe a validity bitmap that also clears those slots (`mask_arrow_children_hidden_by_null_parents()`). Arrow leaves them unspecified, and Lance's v2.1 miniblock encoding keeps them, so a hidden 10000-01-01 under a NULL fixed-size list used to fail the DATE32 range check above. Visible values are unchanged; this applies to ADBC, Arrow stream load and paimon-rust as well. The masks come from ExecEnv's tracked Arrow pool. A nested Lance array that is compacted before decoding is masked the same way, at every level, before its `ValidateFull()`, so a hidden invalid UTF-8 string, out-of-precision decimal, Date64 or time no longer fails the batch while a visible one still does. Since #69697 the same masks keep hidden DATETIMEV2 / TIMESTAMPTZ values out of its range checks. A mask costs at most one pass per batch: a NULL row that owns no child slots, or only NULL ones, allocates nothing, and Arrow stream load masks each retained IPC batch once (`mask_arrow_descendants_not_visible()`) before it hands row ranges to the SerDes, so its per-block reads allocate nothing. The one per-block mask left is for map keys under a NULL map row that still owns entries, since a MapArray cannot hold NULL keys; Arrow's map builder writes NULL map rows without entries. - Core: `to_protobuf` keeps `NULL_TYPE` for a NULL literal type, so a Null leaf in ARRAY / MAP / STRUCT no longer comes back as BOOLEAN. The nullable serde reads an Arrow Null array as NULLs without touching buffers that the array does not have. - Configs, caches and metrics, with the 4.x names and defaults: | Config | Default | |---|---| | `lance_index_cache_size_bytes` | 10 GiB | | `lance_metadata_cache_size_bytes` | 1 GiB | | `enable_lance_data_cache` | true | | `lance_data_cache_path` | `${DORIS_HOME}/lance_data_cache` | | `lance_data_cache_disk_capacity_bytes` | 100 GiB | | `lance_data_cache_read_block_size_bytes` | 1 MiB | | `lance_io_buffer_size_bytes` (mutable) | 2 GiB | | `lance_batch_readahead` (mutable) | 5 | | `lance_fragment_readahead` (mutable) | 5 | The BE-wide Lance session (index cache, metadata cache and the optional Foyer disk cache) is created by the first Lance scan, so a BE that never reads Lance creates no cache directory. The first six configs take effect after a restart. A negative cache size (and, while the data cache is enabled, a negative disk capacity or read block size) fails the first Lance scan with a message that names the setting, as does any data-cache value lance-c rejects; the rest of the BE keeps serving. Ten `lance_session_*` metrics report the two in-memory caches. With the defaults, the disk tier keeps 51,200 sparse 2 MiB block files open from the first Lance scan on (100 GiB in blocks of twice the read block size), the same as on branch-4.1 / 4.2. Size `lance_data_cache_disk_capacity_bytes` and `lance_data_cache_read_block_size_bytes` against the BE's open-file limit, or set `enable_lance_data_cache = false`. The index and metadata caches live in lance-c memory: they are not charged to a MemTracker or registered with CacheManager, so memory GC, the cache capacity adjustment under memory pressure and `/api/clear_cache/all` do not shrink them, and `enable_lance_data_cache = false` does not turn them off. lance-c has no call to clear, evict or resize them, so size them with the two configs. The disk tier keys blocks by Lance's store prefix (`scheme$bucket` for S3, GCS and OSS, without the endpoint) and the object path (`thirdparty/patches/lance-c-foyer.patch`). Several endpoints that serve the same bucket name and data-file path with different bytes (data files registered under chosen names or replaced in place; Lance's writers use random file names) share entries, also across a BE restart; such a deployment should set `enable_lance_data_cache = false`. Both are as on branch-4.1 / 4.2 and tracked as follow-ups. A Lance scan's native working set, that is the I/O buffered up to `lance_io_buffer_size_bytes` per scanner, the decode readahead and the operators of a search plan such as the top-k of a flat vector search, is allocated inside lance-c and is charged to neither the query nor its workload group. It counts toward the BE process memory only, so memory GC, which ranks queries by tracked memory, does not attribute it to the Lance query. lance-c accepts no memory budget, so on BEs with little memory headroom size `lance_io_buffer_size_bytes`, `lance_batch_readahead` and `lance_fragment_readahead` for the number of concurrent Lance scanners. As on branch-4.1 / 4.2; tracked as a follow-up. - Build: macOS links `-framework IOKit`. This is the first time objects of `liblance_c.a` are pulled into `doris_be`, so the binary and the link time grow. With this PR `util/rle_encoding.h` reaches 231 TUs and `util/threadpool.h` 589, the same as master `315c2e00331` alone (limits 275 and 660 since #69717), and `gen_cpp/internal_service.pb.h` 562 (master alone 559, limit 660); the reach budgets are unchanged. Not included: the Lance index metadata scanner (`LANCE_INDEX_ENTRIES`); the FE side, including the rolling-upgrade guard that keeps Lance lazy materialization off while an old BE could decode a version 1 row location as version 0; the regression suites; the rest of #68707 (searching historical versions, tags and branches, rejecting fragment ids missing from the snapshot, naming the snapshot in errors and the profile). The `InitReaderAvgTime` / `GetBlockAvgTime` profile fix that #67005 carried goes in a separate PR. **Results.** | | master | with this PR | |---|---|---| | A `FORMAT_LANCE` query | fails before reading anything | read by `LanceTableReader` in FileScannerV2 | | A Lance row in the second phase of TopN lazy materialization | cannot be represented | a version 1 row location, read back with `take_rows` | | A row location of an unknown version or size in phase two | decoded as version 0 | rejected with an error | | An Arrow DATE32 day outside 0000-01-01..9999-12-31 (ADBC, Arrow stream load, paimon-rust, Lance) | read as a non-null `0000-00-00` | the read fails with `InvalidArgument` | BE unit tests (ASAN, macOS arm64, against master's pinned lance-c), on the head rebased onto master `378404eeb12`: 1029 cases in 54 suites run, 1027 pass and 2 Parquet microbenchmarks skip by design. They cover the Lance suites (107: `LanceTableReader*` 83, `LanceNestedNullTest` 10, `LanceRuntimeFilterHelperTest` 10, `LanceSessionManagerTest` 4); the row-location protocol (`MaterializationSharedStateTest`, `RowIdStorageReaderTest`, and the new `RowIdFetchRequestValidationTest`: count mismatch, unknown version, a Lance version on an internal mapping, an internal row id of 2^32); `FileScannerV2Test` (28); the ORC and Parquet reader suites (`NewOrcReaderTest`, `NewParquetReaderTest`, `ParquetScanTest` and the other `Parquet*` suites), whose row ids now go through `file_local`; and the Arrow / protobuf / DATE serde suites with the new `ArrowParentNullsTest`, plus the Iceberg and Parquet reader suites that decode Arrow dates. Reverting any of the review fixes, the #68813 flag, the #68707 split rule or the #68815 bounds makes its new tests fail. The sixth review round adds 13 cases (`ArrowParentNullsTest` 10, `LanceTableReaderTypeTest` 3) and extends one; with them the Arrow SerDe, Lance, ADBC and `IcebergV2ReaderTest` suites run 317 cases: 310 pass and the 7 ADBC SQLite cases skip without a local SQLite driver. The ninth review round adds `LanceRuntimeFilterHelperTest.KeepsInt64MinFiltersResidualOnly` and `LanceTableReaderFilterTest.KeepsInt64MinRuntimeFiltersOutOfLanceScanner`: both pass with the 106 Lance cases (`Lance*`) on the branch rebased onto `339e087b11f`, and restoring `parse_int64()` in either check makes exactly these two fail. On the head rebased onto master `315c2e00331`, with the per-block mask fix (`42cf4e3e5d1`), 328 cases in 24 suites pass: the Arrow SerDe and validation suites, `ArrowParentNullsTest` (15), `LoadArrowPipeTest` (47), the DATETIMEV2 / TIMESTAMPTZ SerDe suites, `ArrowColumnToDorisColumnTest`, `ArrowBlockConvertorTest`, `AdbcReaderTest`, `RemoteDorisV2ReaderTest`, `PaimonRustTableReaderTest` and the Lance suites. Allocating at the first NULL row of each call again fails the new `ArrowParentNullsTest` case and the four new `LoadArrowPipeTest` block cases, dropping the per-batch mask fails the LIST and STRUCT block cases, and returning the child unmasked fails the new timestamp case, four `ArrowParentNullsTest` cases and `LanceTableReaderTypeTest.IgnoresDate32PayloadHiddenByNullParents`. ### Release note Add nine `lance_*` BE configs and `lance_session_*` BE metrics. They take effect once the FE can plan Lance scans. Reading an Arrow DATE32 value outside 0000-01-01..9999-12-31 through ADBC, Arrow stream load or paimon-rust now fails instead of returning 0000-00-00. ### Check List (For Author) - Test <!-- At least one of them must be included. --> - [ ] Regression test - [x] Unit Test - `run-be-ut.sh --run --filter=...` with the suites listed under Results: 420 of 420 pass on macOS arm64 (ASAN) on the content before the rebases, and the Lance and Arrow SerDe suites pass again with the nested-offset, zero-field struct, hidden-child, hidden-Decimal256 and compaction-mask fixes (the ADBC SQLite cases skip without a local SQLite driver). Rebased onto master `43f9ceb48d7`: #69668 conflicted in the scanner selection and in `fetch_table_schema`, which now hands every file format to `format::fetch_file_schema()`, so the Lance branch runs ahead of that call; #69646 added a TopN row-group test that reads the version 0 row location fields, which now go through `file_local` (the earlier rebase onto `5caaeb3e3d4` resolved #69614 and #69601 in the scanner selection, the `FileFormat` enum, its test and the reach budget table). The 95 TUs that this PR changes or that master changed since `5caaeb3e3d4` were syntax-checked against the rebased tree with the UT build flags, and CI runs the suites again. Rebased again onto master `8d88f1cc6f7`: the only conflict was the budget table, where #65858 moved the `util/rle_encoding.h` baseline to 828, and the 163 TUs that this PR changes or that master changed since `43f9ceb48d7` pass the same syntax check. Rebased again onto master `339e087b11f`: the only conflict was the budget table again, where #67292 moved the `util/rle_encoding.h` baseline to 834; #69872 added Arrow type checks ahead of the NULL-parent masking in the map and struct readers and merged cleanly. Of the 114 sources that this PR changes or that master changed since `8d88f1cc6f7`, 111 pass the same syntax check. The other three are master's: two new #67292 files under `storage/segment` fail the same way on master alone, since they compile only inside their unity batch, and this PR adds no source to that target; the #69818 benchmark is not in the UT build and includes only `util/simd` headers that this PR does not touch. Reverting any of the review fixes, the #68813 flag, the #68707 split rule or the #68815 bounds makes its new tests fail. Rebased again onto master `378404eeb12`, which removed the legacy file scanner (#69723): the conflicts were in the scanner-selection code and tests that #69723 deleted, so this PR's Lance lines there went with them (including its `LanceQueriesAlwaysUseScannerV2` test), in the profile keys of `materialization_opertor.cpp`, and in the row fetch of `rowid_fetcher.cpp`, whose non-Lance path is now only `FileScannerV2::read_by_rows`; the deleted V1 ORC / Parquet row id tests took this PR's `file_local` rename with them, and the `util/rle_encoding.h` budget commit is dropped because master is no longer near that limit. Of the 100 sources that this PR changes or that master changed since `339e087b11f`, 99 pass the same syntax check; the other, `format_v2/orc/orc_reader.cpp`, fails the same way on master alone. On the rebased head the suites listed under Results run 1029 cases: 1027 pass and 2 microbenchmarks skip. The test-utility fix that `DataTypeDateTimeV2SerDeTest` needed on macOS (#69695) is now on master. Rebased again onto master `315c2e00331`: the only conflict was `TExternalSearchRequest` in `PlanNodes.thrift`, where #70075 had reserved fields 2-5 in comments; the two commits that add the fields replace those comments, and field 6 stays #70075's `paimon_options`. #69717 cut transitive includes from shared headers: of the 160 sources that this PR changes or that master changed since `378404eeb12`, 156 pass the same syntax check; the two `jemalloc_hook` tests have no compile command on macOS, `runtime/memory/jemalloc_hook.cpp` uses glibc aliases that macOS cannot build (#69819), and `format_v2/table_reader.cpp` alone fails the same way on master alone while its unity batch compiles. The full `doris_be_test` builds and links on the rebased head; `ArrowParentNulls*` and `Lance*` (121 cases) pass before the mask fix, and the 328 cases above with it. - `build-support/check-build-hygiene.sh` (on this branch rebased onto master `315c2e00331`), clang-format 16 and `build-support/run-clang-tidy.sh` on the changed files: all pass; on the changed lines clang-tidy (llvm 22) reports only `readability-inconsistent-ifelse-braces` on the `DORIS_CHECK` lines of the masking functions, the macro's expansion that master's existing `DORIS_CHECK`s report too. - [ ] Manual test (add detailed scripts or steps below) - [ ] No need to test or manual test. Explain why: - Behavior changed: - [ ] No. - [x] Yes. `PRequestBlockDesc.row_id` is `uint64`; phase two of TopN lazy materialization rejects row locations of an unknown version or size; `FORMAT_LANCE` scans run on FileScannerV2; an Arrow DATE32 day outside the Doris DATE range fails the read instead of becoming `0000-00-00`. - Does this need documentation? - [x] No. Lance is documented with the FE connector. - [ ] Yes. <!-- Add document PR link here. eg: apache/doris-website#1214 --> ### Check List (For Reviewer who merge this PR) - [ ] Confirm the release note - [ ] Confirm test cases - [ ] Confirm document - [ ] Add branch pick label <!-- Add branch pick label that this PR should merge into --> --------- Co-authored-by: zhangstar333 <[email protected]> Co-authored-by: Gabriel <[email protected]> Co-authored-by: zhaobo wang <[email protected]> Co-authored-by: jay <[email protected]> Co-authored-by: FANNG <[email protected]> Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]> Co-authored-by: zy-kkk <[email protected]>
What problem does this PR solve?
Issue Number: None
Related PR: #69581 #68516
Problem Summary:
In short. An Arrow timestamp whose civil year is outside 0000..9999 is read into DATETIMEV2 or TIMESTAMPTZ as a different, valid-looking value: timestamp(us) 2005980768000000000, which is 65537-01-01, reads as a non-null 0001-01-01. This PR checks the year before the value is narrowed into Doris' 16-bit year field, as the ORC path already does, and fails the read otherwise. The review of #69581 found it on the Lance path; the code is shared by every Arrow reader.
Background.
DataTypeDateTimeV2SerDe::read_column_from_arrowandDataTypeTimeStampTzSerDe::read_column_from_arrowdecode Arrow timestamps for ADBC, Arrow stream load, paimon-rust, remote Doris and, once #69581 lands, Lance, nested leaves included. Both convert epoch seconds withDateV2Value::from_unixtime(), which passes cctz's 64-bit year tounchecked_set_time(uint16_t year, ...)("there's no overflow check since it's hot path"). #68516 added a check before this narrowing to the ORC path (orc_timestamp_to_datetime()).The problem, and what it cost.
In the wrapped cases the read succeeds with a wrong value, and nothing in the result tells the user.
How this PR fixes it.
orc_timestamp_to_datetime(). After packing,is_valid_date()is checked too: cctz counts year 0 as a leap year and Doris does not (is_leap(0)is false), so the civil date 0000-02-29 passes the year check, and before this PR it was stored as an invalid date.append_timestamptz_from_utc_epoch_microschecks the instant against 0000-01-01 00:00:00 UTC .. 9999-12-31 23:59:59.999999 UTC before converting. Its runtimeis_valid_date()check after packing stays, for the same leap day: timestamp(us) -62162121600000000 (0000-02-29 UTC) is inside the range but packs into an invalid value. The range message now says 0000-9999, the rangeis_valid_date()accepts.parquet_timestamp_micros(),parquet_int96_timestamp_micros()), so they could not wrap. Arrow reads into the deprecated DATE / DATETIME (v1) types go throughVecDateTimeValue::from_unixtime()with the same unchecked narrowing; they are left as they are.orc_timestamp_to_datetime()checks only the year, so an ORC timestamp on 0000-02-29 is still stored as an invalid date; it is not changed here.Merge order: after #69581. A NULL STRUCT, LIST or MAP row may hide any child value, an out-of-range timestamp included, because Arrow leaves the payload under a NULL parent unspecified. #69581 masks those child slots in the shared nested SerDes (
mask_arrow_children_hidden_by_null_parents, df95b41) before any leaf SerDe reads them. Without it, the checks here fail a batch whose visible values are valid: a STRUCT with rows[NULL, {ts: 0}]whose NULL row carries 2005980768000000000 reads with DataQualityError on this PR alone, and reads both rows on a tree with both PRs.Results.
Release note
Reading an Arrow timestamp whose year is outside 0000..9999 into DATETIMEV2 or TIMESTAMPTZ (ADBC, Arrow stream load, paimon-rust, remote Doris) now fails instead of returning a different date. So does a DATETIMEV2 read of 0000-02-29, which is not a valid Doris date.
Check List (For Author)
DataTypeDateTimeV2SerDeTest.RejectsArrowTimestampsOutsideDateTimeV2Range,RejectsNestedArrowTimestampOutsideDateTimeV2Range(an ARRAY leaf) andDataTypeTimeStampTzSerDeTest.RejectsArrowTimestampsOutsideTimestampTzRange. With the previous DATETIMEV2 code both DATETIMEV2 tests fail; with the previous TIMESTAMPTZ code 65537-01-01 reads as a valid value and its test fails. The two range tests also read 0000-02-29 and expect DataQualityError; they fail when the checks after packing skip that value.Such reads now fail with DataQualityError instead of returning a wrong date.
Check List (For Reviewer who merge this PR)