Skip to content

Prune ORC row groups by predicates on a monotonic function of a column - #128505

Open
groeneai wants to merge 8 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-112577-native-orc-monotonic-chain
Open

groeneai wants to merge 8 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-112577-native-orc-monotonic-chain

Conversation

@groeneai

@groeneai groeneai commented Nov 1, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #112577

Changelog category (leave one):

  • Performance Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

ORC filter pushdown now skips row groups for predicates on a monotonic function of an integer column, including a named tuple element, such as toUInt64(id) = 555555, id + 1 = 555556, intDiv(id, 10) = 55555, -id = -555555 or id + 1 IN (...), which previously read the whole file. Closes #112577.

Description

An ORC search argument compares a stored column with a literal, so buildORCSearchArgumentImpl turns every atom with a monotonic function chain into "unknown" and such predicates pruned nothing, while Parquet pruned them. Results were correct; only the pruning was lost. Inverting the chain into a leaf on the bare column is unsound (non-injective intDiv, decreasing -id, lossy casts), so the chain is evaluated forward, as in the Parquet reader.

ORC::RowReaderOptions gets a row_group_filter, which RowReader::pickRowGroups combines with the search argument's decision for each row group. NativeORCBlockInputFormat builds it only when the key condition has a monotonic chain: KeyCondition::checkInHyperrectangle over the row index min/max. Ranges are built only for BYTE/SHORT/INT/LONG columns, including named tuple elements, resolved and type-checked as in the search argument (the type check moved into isSameTypeAsInORCFile); a row group with NULLs is not bounded (ifNull or transform_null_in can match a NULL) unless input_format_null_as_default reads them as the column default. A struct field has no value in the rows where the struct is NULL, so its statistics are used only in row groups where no enclosing struct is NULL.

The search argument and the filter find a tuple element by its subcolumn's element path: with t Tuple(`x.y` Int64, x Tuple(y Int64)) over a file storing x first, the search argument bound t.x.y to x's field y and pruned matching row groups, also on 26.10.

@ PedroTadim picked this hook on the issue. Stripe statistics are unused: ClickHouse writes a stripe per 64 MiB.

Validation: on the issue's file (1M ordered rows), master reads all 1,000,000 rows for every chain predicate; the fix reads 10,000, with equal results either way. The new test fails on master in its pruning and dotted-element lines; removing the NULL, default or enclosing-struct handling makes it return wrong counts (the last on a committed fixture).

🤖 Generated with Claude Code


Workflow [PR]
Sync PR [sync-upstream/pr/128505]

groeneai and others added 3 commits November 1, 2026 15:33
An ORC search argument leaf compares a stored column with a literal, so
`buildORCSearchArgumentImpl` turns every key condition atom with a monotonic
function chain (`toUInt64(id) = 555555`, `id + 1 = 555556`, `intDiv(id, 10) = 55555`,
`-id = -555555`, `id + 1 IN (...)`) into `YES_NO_NULL`, and a predicate made only of
such atoms read the whole file, while the Parquet reader prunes it. Inverting the
chain into a leaf on the bare column is where pruning turns unsound (non-injective
`intDiv`, decreasing `-id`, lossy casts), so the chain is evaluated forward instead.

`ORC::RowReaderOptions::row_group_filter` is consulted by `RowReader::pickRowGroups`
for the row groups the search argument keeps, inside the backward loop, before the
run-end markers of `next_skipped_rows` are written (zeroing an entry afterwards would
leave the previous marker spanning the skipped group). `NativeORCBlockInputFormat`
builds it only when `KeyCondition::hasMonotonicFunctionsChain`, as
`KeyCondition::checkInHyperrectangle` over the row index statistics the reader has
already loaded, the same evaluation the Parquet reader uses. Only key columns used by
the condition get a range, and only `BYTE`/`SHORT`/`INT`/`LONG` columns that pass the
search argument's own resolver and type check, moved into `isSameTypeAsInORCFile` so
the two cannot drift. NULL handling follows `adjustRangeFromIndexIfNeeded`: a NULL
extends the range to an infinity, or with `input_format_null_as_default` on a
non-Nullable column to the column default. Missing `has_null` or bounds, or
`min > max`, give the whole universe.

File and stripe statistics are not extended: the ClickHouse writer cuts a stripe every
64 MiB of data, so row groups are the granularity that matters.

This is the shape @ PedroTadim picked on ClickHouse#112577 (a hook in the ORC reader); since
ClickHouse#127690 the reader is in-tree, so no submodule change is needed.

Closes ClickHouse#112577

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`buildORCRowGroupFilter` looked key names up in the reader header only, so a
named tuple element (`t.x`, which the header carries as its parent `t`) never
got a range, while the search argument resolves it with `findHeaderTypesByPath`.
Keys are now resolved the same way, with the same result type for the type check
and the same declared type for the `input_format_null_as_default` value.

A STRUCT field has no value in the rows where the struct is NULL (no PRESENT
entry is written for them), and the reader returns NULL or the default there,
but a writer need not count those rows in the field's `has_null`. So a field's
statistics are used only in row groups where every enclosing struct has
`has_null == false`. This covers tuple elements and a flat dotted `s.x`
structure, which resolves into the struct as well.

The test becomes a shell test so it can read a committed ORC file whose writer
leaves those rows out of the field's statistics (made once with a patched
ClickHouse writer, not committed). It adds pruning lines for a NULL-bearing row
group and for the `input_format_null_as_default` range, and reads tuple-element
pruning from `query_log`, because `indexHint` does not keep the subcolumn
rewrite.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop the ORCRowGroupFilterColumn and ancestors comments, shorten the buildORCRowGroupFilter comment to one line.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

groeneai commented Nov 1, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex) plus my own review; 4 findings over two rounds.

# Sev Finding Verdict Evidence / action
1 ❌ Monotonic predicates on named tuple elements did not prune: keys were looked up in the flat header only AGREE, fixed @ 2285db6 keys resolved with findHeaderTypesByPath, as in the search argument
2 ⚠️ A struct field's statistics bounded rows where the struct is NULL, although the field has no value there AGREE, fixed @ 2285db6 used only in row groups where no enclosing struct is NULL; test on a committed file whose writer leaves those rows out of the field's has_null
3 ⚠️ The NULL and input_format_null_as_default lines checked results only AGREE, fixed @ 2285db6 two rows-read lines for NULL-bearing row groups
4 ❌ Non-Nullable column with input_format_null_as_default = 0: a pruned row group holding a NULL no longer raises CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN DISAGREE the search argument already skips that row group for a bare id = X (NO_NULL is not needed, ORC/SearchArgument.cpp), and Parquet's min/max pruning maps NULL to -inf the same way (adjustRangeFromIndexIfNeeded); every returned row matches

Not changed here: the search argument's own t.x IS NULL leaf reads the field's has_null, so it has the exposure of row 2 on such a file (same on master); filters on columns with a DEFAULT expression are handled by #127108.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-review-slot-11:20261101-163800

@groeneai

groeneai commented Nov 1, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The issue's 1M-row file (row index stride 10000) with count() under indexHint: master reads 1,000,000 rows for every chain predicate, id = 555555 reads 10,000. For a tuple element, WHERE t.x + 1 = 100001 reads 200,000 of 200,000 rows on master and 10,000 with the fix.
b Root cause explained? An ORC search argument leaf compares a stored column with a literal, so buildORCSearchArgumentImpl makes every chain atom "unknown"; the reader's only row-group decision, RowReader::pickRowGroups, used the search argument alone and never reached KeyCondition, which evaluates chains forward from min/max.
c Fix matches root cause? Yes. The missing evaluator is added at the row-group decision, through KeyCondition::checkInHyperrectangle (the Parquet path) over statistics already loaded; keys are resolved with the search argument's own findHeaderTypesByPath.
d Test intent preserved / new tests added? New shell test 05495_orc_filter_pushdown_monotonic_chain: pruning, result equality with and without pushdown, NULL and input_format_null_as_default arms with pruning lines, tuple elements, and a 914-byte ORC file whose writer leaves NULL-struct rows out of the field's statistics. No existing test changed.
e Both directions demonstrated? Yes. Master fails exactly in the 16 pruning lines, the fix passes 50/50 randomized parallel runs; dropping the wiring, the NULL widening, the default inclusion, the tuple-path resolution or the enclosing-struct rule, widening every NULL-bearing row group, or folding after the loop each reddens only its own lines.
f Fix is general across code paths? The IN set bail is covered by the same filter, and tuple elements resolve as in the search argument. This is the only reader site building a search argument (Iceberg and DeltaLake ORC files go through it). Stripe statistics are not used, since ClickHouse writes a stripe per 64 MiB.
g Fix generalizes across inputs (params/datatypes/wrappers)? Checked Int8/Int16/Int32/Int64, Nullable, LowCardinality, LowCardinality(Nullable), non-Nullable header with input_format_null_as_default, AND/OR/NOT and IN; tuple elements inferred, explicit, two levels deep, under a NULL inner struct, and a flat dotted `t.x` structure; results equal to master. Unsigned headers and non-integer kinds keep the current behaviour.
h Backward compatible? (maintainer-approved exception only) Yes. No setting or format change; a query without a chain builds no filter and reads as before.
i Invariants and contracts preserved? A row group is skipped only if no row the reader returns can match: same column resolution and type checks as the search argument, NULL handling as in the Parquet reader, a struct field's range only where no enclosing struct is NULL, missing statistics mean "unknown", and the decision is combined before the run-end markers of next_skipped_rows are written.

Session id: cron:clickhouse-impl-slot-5:20261101-160800

@groeneai

groeneai commented Nov 1, 2026

Copy link
Copy Markdown
Collaborator Author

cc @alexey-milovidov @al13n321, could you review this and add the can be tested label so CI runs? The native ORC reader now skips row groups for predicates with a monotonic function chain over an integer column, using KeyCondition::checkInHyperrectangle over the row index min/max as the Parquet reader does, through a new RowReaderOptions::row_group_filter combined with the search argument in RowReader::pickRowGroups.

@clickhouse-gh

clickhouse-gh Bot commented Nov 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f21ec3d]

Summary: ✅


AI Review

Summary

The PR adds ORC row-group pruning for monotonic function chains over integer columns and named tuple elements. Reviewed commit f21ec3dcf96986f6bdcf76bf0b7586a22baa3a6c, including the current code, full diff, and all prior discussion. The earlier NULL-substitution and dotted-tuple-field findings are addressed. No new actionable findings; no inline comments posted.

Missing context / blind spots
  • ⚠️ No local ClickHouse binary or build directory was available, so tests were not run locally. Runtime evidence comes from the PR's recorded before/after measurements and regression results; a current-head stateless run would independently confirm them.
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Nov 1, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-formats Input/output formats (CSV/JSON/Parquet/ORC/Arrow/Protobuf/etc.). label Nov 1, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Nov 1, 2026
The row group filter put a NULL at negative infinity, as the Parquet
reader does. A KeyCondition chain does not respect that position:
`ifNull` and `coalesce` report themselves monotonic whenever the upper
bound is not NULL and leave the infinite bound untouched, and a
`transform_null_in` set sorts its NULL elsewhere. So with one NULL and
9,999 values of -1 in a row group, `toFloat64(ifNull(id, toInt64(42))) = 42`,
`ifNull(id, toInt64(42)) IN (42, 43)` and, with `transform_null_in = 1`,
`intDiv(id, 10) IN (NULL, 5)` pruned the group and returned 0 rows
instead of 1 (the same with `allow_key_condition_coalesce_rewrite = 0`
for `ifNull(id, toInt64(42)) = 42` and `coalesce`).

Moving the NULL to positive infinity is not enough either, since a
decreasing link such as `-id` before `ifNull` moves it back. A row group
with NULLs read as NULL is now not bounded by that column. With
`input_format_null_as_default` the NULL is read as the column default,
a real value, and the range is still extended to it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Nov 1, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing f21ec3dcf with master f63ca4f78 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

4 object files changed (+57.70 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/Formats/Impl/NativeORCBlockInputFormat.cpp.o 1.17 MiB 1.22 MiB +54.12 KiB (+4.52%)

711 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

13 translation units recompiled, 77 s compile time in total, 13 of them have a recent master baseline.

Job report

`traverseDownORCTypeByName` binds a dotted predicate column to the first field
whose name is a prefix, in file order. An element name can contain a dot, so for
`t Tuple(`x.y` Int64, x Tuple(y Int64))` read from a file that stores `x` before
`x.y`, the predicate column `t.x.y` (the element `x.y`) was bound to the field
`y` of `x`, and its statistics pruned row groups that match. Both the search
argument (`t.x.y = 7`, also on 26.10) and the row group filter (`t.x.y + 1 = 8`)
returned 0 rows with the pushdown and 2000 without.

Resolve a tuple element through the substreams path of its subcolumn, with the
same struct field lookup that selects the fields the reader reads.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

groeneai commented Nov 2, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 0de896a

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stress test (arm_release) / Logical error: Cannot write to canceled buffer (STID: 4158-3eef) not from this PR (its diff changes only the native ORC reader and its test): the embedded client's ClientBase::resetOutput finalizes a FORMAT JSON output into a buffer that a failed flush already canceled (JSONRowOutputFormat::writeSuffix); the same signature failed on master 7 times and on 20+ other PRs in the last 30 days #126142 (mine, open)
Mergeable Check, PR praktika rollups of the row above #126142 (the owner of the row above)

05495_orc_filter_pushdown_monotonic_chain passes on this head, including all five flaky check jobs. CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261102-033003

@PedroTadim

Copy link
Copy Markdown
Member

@alexey-milovidov should you review this?

groeneai and others added 3 commits November 18, 2026 14:53
`src/Processors/Formats` is now linted for `std::` containers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…row index

Since d201b1c (count row groups without overflow) `pickRowGroups` reads all
row groups unless a leaf of the search argument has a row index. A predicate on a
monotonic function of a column has no leaf, so the row group filter was never
called and 05495 read every row again. The filter now also counts, with the same
bound on the number of row groups: an index with at least that many entries.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@snelheidai

Copy link
Copy Markdown

@groeneai, the row-group filter here only takes BYTE/SHORT/INT/LONG columns, so date and time bucketing, probably the most common chain, still reads every row group: toDate(ts) = …, toStartOfHour(ts) = …, toStartOfMonth(d) = …, toMonday(d) = …, toYear(d) = … on ORC TIMESTAMP and DATE columns. Inferred ORC columns are Nullable, so the preimage rewrite does not turn toYear/toYYYYMM into a plain range either. Building the same Range from date_statistics and timestamp_statistics makes these prune like d = … already does. Could you take the patch below into this PR, or into a follow-up if you prefer to keep this one as is?

50M-row ORC file sorted by time (2023-01-01 to 2024-12-30, 10,000-row row groups, 478 MB), SELECT count(), sum(value), sum(length(url)) FROM file(…) WHERE …. Server query_duration_ms, median of 10 paired hot runs on x86 (32 vCPU, Release build): this PR's diff on master c25f02d vs the same plus the patch below.

WHERE Rows read This PR + patch Change (95% CI)
toDate(ts) = '2024-03-15' 50M → 80K 1909 ms 36 ms −98.0% (−98.2, −97.8)
toStartOfHour(ts) = '2024-03-15 10:00:00' 50M → 10K 1918 ms 31 ms −98.4% (−98.4, −98.3)
toYYYYMM(ts) = 202403 50M → 2.1M 1908 ms 120 ms −93.7% (−93.8, −93.6)
toStartOfMonth(d) = '2024-03-01' 50M → 2.1M 1623 ms 104 ms −93.6% (−93.7, −93.5)
toMonday(d) = '2024-03-11' 50M → 490K 1638 ms 52 ms −96.8% (−96.9, −96.8)
toYear(d) = 2023 50M → 25M 1613 ms 855 ms −46.8% (−47.7, −45.9)
d = '2024-03-15' (search argument) 80K 14 ms 14 ms +1.6% (−3.8, +7.2)
id + 1 = 12345679 (this PR's case) 10K 40 ms 41 ms +1.7% (−0.5, +4.0)
toYear(d) >= 2023 (nothing to skip) 50M 1630 ms 1653 ms +1.3% (+0.1, +2.5)
no WHERE 50M 1402 ms 1401 ms +0.1% (−1.0, +1.2)

The toYear(d) >= 2023 row is the cost of evaluating the chain for every row group when nothing can be skipped, about 5 µs for each of the 5,000 row groups.

The TIMESTAMP bounds follow PredicateLeaf::evaluatePredicateMinMax: UTC milliseconds plus the stored sub-millisecond nanoseconds. As for the search argument, they are used only when the writer and reader time zones are UTC and the writer is ORC-135 or later. The reader passes that to the filter as a second argument computed with areTimestampsShifted, so the UTC-alias fix in #132657 would apply here as well. Near the epoch the upper bound is widened to +1 s, because timestamps between −1 and 0 s are not read back as written by every writer. DATE bounds outside the Date32 range are not used, since such days are not read as stored.

Results were identical with input_format_orc_filter_push_down on and off in 109 predicate and setting combinations, 97 of which prune. They cover pre-1970 timestamps with sub-millisecond parts, NULLs, three session time zones, a non-UTC reader time zone, input_format_null_as_default and declared types. 05495 passes with 16 added DATE/TIMESTAMP lines, as do 02892, 05214–05217 and 05629.

Patch on top of f21ec3d (+138/−13)
diff --git a/src/Processors/Formats/Impl/NativeORCBlockInputFormat.cpp b/src/Processors/Formats/Impl/NativeORCBlockInputFormat.cpp
index 962d8331b494..73846e2651f1 100644
--- a/src/Processors/Formats/Impl/NativeORCBlockInputFormat.cpp
+++ b/src/Processors/Formats/Impl/NativeORCBlockInputFormat.cpp
@@ -1093,6 +1093,7 @@ struct ORCRowGroupFilterColumn
 {
     size_t key_column;
     UInt64 orc_column_id;
+    ORC::TypeKind kind;
     /// What the reader returns for NULL when it is not NULL (`input_format_null_as_default`).
     std::optional<Field> null_value;
     VectorWithMemoryTracking<UInt64> ancestors;
@@ -1124,14 +1125,74 @@ static VectorWithMemoryTracking<UInt64> getORCAncestorColumnIds(const ORC::Type
     return ancestors;
 }
 
-static Range getRangeFromORCStatistics(const ORC::Proto::ColumnStatistics & stats, const ORCRowGroupFilterColumn & column)
+/// The minimum and the maximum of the non-NULL values of a row group, as the reader returns them.
+static std::optional<std::pair<Field, Field>> getORCStatisticsBounds(
+    const ORC::Proto::ColumnStatistics & stats, ORC::TypeKind kind, bool timestamps_comparable)
+{
+    switch (kind)
+    {
+        case ORC::TypeKind::BYTE:
+        case ORC::TypeKind::SHORT:
+        case ORC::TypeKind::INT:
+        case ORC::TypeKind::LONG:
+        {
+            const auto & ints = stats.int_statistics;
+            if (!ints || !ints->minimum || !ints->maximum || *ints->minimum > *ints->maximum)
+                return {};
+            return std::pair{Field(*ints->minimum), Field(*ints->maximum)};
+        }
+        case ORC::TypeKind::DATE:
+        {
+            /// A day outside the range of `Date32` is not read as it is (`date_time_overflow_behavior`).
+            const auto & dates = stats.date_statistics;
+            if (!dates || !dates->minimum || !dates->maximum || *dates->minimum > *dates->maximum
+                || *dates->minimum < DATE_LUT_MIN_EXTEND_DAY_NUM || *dates->maximum > DATE_LUT_MAX_EXTEND_DAY_NUM)
+                return {};
+            return std::pair{Field(static_cast<Int64>(*dates->minimum)), Field(static_cast<Int64>(*dates->maximum))};
+        }
+        case ORC::TypeKind::TIMESTAMP:
+        {
+            /// The UTC milliseconds and the sub-millisecond nanoseconds plus one, as in `PredicateLeaf::evaluatePredicateMinMax`.
+            const auto & ts = stats.timestamp_statistics;
+            auto valid_nanos = [](const std::optional<UInt64> & nanos) { return !nanos || (*nanos >= 1 && *nanos <= 1'000'000); };
+            if (!timestamps_comparable || !ts || !ts->minimum_utc || !ts->maximum_utc || !valid_nanos(ts->minimum_nanos)
+                || !valid_nanos(ts->maximum_nanos))
+                return {};
+            /// The values are read as `DateTime64(9)`, which a nanosecond count out of Int64 does not fit.
+            constexpr Int64 max_abs_millis = std::numeric_limits<Int64>::max() / 1'000'000 - 2;
+            const Int64 min_millis = *ts->minimum_utc;
+            const Int64 max_millis = *ts->maximum_utc;
+            if (min_millis < -max_abs_millis || max_millis > max_abs_millis || min_millis > max_millis)
+                return {};
+            Int64 min_nanos = min_millis * 1'000'000 + (ts->minimum_nanos ? static_cast<Int64>(*ts->minimum_nanos) - 1 : 0);
+            Int64 max_nanos = max_millis * 1'000'000 + (ts->maximum_nanos ? static_cast<Int64>(*ts->maximum_nanos) - 1 : 999'999);
+            /// The writers round the negative milliseconds differently, so widen the bounds by one.
+            if (min_millis < 0)
+                min_nanos -= 1'000'000;
+            if (max_millis < 0)
+                max_nanos += 1'000'000;
+            /// A timestamp between -1 and 0 seconds is not read as it was written: some writers store the epoch,
+            /// the Java one the value plus one second, while the statistics can keep the written value.
+            if (min_nanos < 0 && max_nanos > -1'000'000'000)
+                max_nanos = std::max<Int64>(max_nanos, 1'000'000'000);
+            return std::pair{Field(DecimalField<DateTime64>(DateTime64(min_nanos), 9)), Field(DecimalField<DateTime64>(DateTime64(max_nanos), 9))};
+        }
+        default:
+            return {};
+    }
+}
+
+static Range getRangeFromORCStatistics(
+    const ORC::Proto::ColumnStatistics & stats, const ORCRowGroupFilterColumn & column, bool timestamps_comparable)
 {
     /// Some writers omit `has_null`; without bounds (no non-NULL values) nothing is known either.
     /// A NULL read as NULL has no position in a Range that every chain and set respects (`ifNull`, `transform_null_in`).
-    if (!stats.has_null || (*stats.has_null && !column.null_value) || !stats.int_statistics || !stats.int_statistics->minimum
-        || !stats.int_statistics->maximum || *stats.int_statistics->minimum > *stats.int_statistics->maximum)
+    if (!stats.has_null || (*stats.has_null && !column.null_value))
+        return Range::createWholeUniverse();
+    auto bounds = getORCStatisticsBounds(stats, column.kind, timestamps_comparable);
+    if (!bounds)
         return Range::createWholeUniverse();
-    Range range(Field(*stats.int_statistics->minimum), true, Field(*stats.int_statistics->maximum), true);
+    Range range(std::move(bounds->first), true, std::move(bounds->second), true);
     if (*stats.has_null)
     {
         if (accurateLess(*column.null_value, range.left))
@@ -1179,7 +1240,8 @@ static ORC::RowGroupFilter buildORCRowGroupFilter(
             continue;
 
         const auto kind = orc_type->getKind();
-        if (kind != ORC::TypeKind::BYTE && kind != ORC::TypeKind::SHORT && kind != ORC::TypeKind::INT && kind != ORC::TypeKind::LONG)
+        if (kind != ORC::TypeKind::BYTE && kind != ORC::TypeKind::SHORT && kind != ORC::TypeKind::INT && kind != ORC::TypeKind::LONG
+            && kind != ORC::TypeKind::DATE && kind != ORC::TypeKind::TIMESTAMP)
             continue;
 
         if (!isSameTypeAsInORCFile(column_types->result_type, *orc_type, format_settings))
@@ -1193,12 +1255,13 @@ static ORC::RowGroupFilter buildORCRowGroupFilter(
             default_column->insertDefault();
             null_value = (*default_column)[0];
         }
-        columns.push_back({key_column, orc_type->getColumnId(), std::move(null_value), getORCAncestorColumnIds(schema, *orc_type)});
+        columns.push_back({key_column, orc_type->getColumnId(), kind, std::move(null_value), getORCAncestorColumnIds(schema, *orc_type)});
     }
     if (columns.empty())
         return {};
 
-    return [key_condition, key_types, columns](const std::function<const ORC::Proto::ColumnStatistics *(UInt64)> & get_statistics)
+    return [key_condition, key_types, columns](
+               const std::function<const ORC::Proto::ColumnStatistics *(UInt64)> & get_statistics, bool timestamps_comparable)
     {
         Hyperrectangle hyperrectangle(key_types.size(), Range::createWholeUniverse());
         for (const auto & column : columns)
@@ -1214,7 +1277,7 @@ static ORC::RowGroupFilter buildORCRowGroupFilter(
                     return ancestor && ancestor->has_null == false;
                 }))
                 continue;
-            hyperrectangle[column.key_column] = getRangeFromORCStatistics(*stats, column);
+            hyperrectangle[column.key_column] = getRangeFromORCStatistics(*stats, column, timestamps_comparable);
         }
         return key_condition->checkInHyperrectangle(hyperrectangle, key_types).can_be_true;
     };
diff --git a/src/Processors/Formats/Impl/ORC/Reader.cpp b/src/Processors/Formats/Impl/ORC/Reader.cpp
index 5c9e3fbb5245..47d2db5fdb5d 100644
--- a/src/Processors/Formats/Impl/ORC/Reader.cpp
+++ b/src/Processors/Formats/Impl/ORC/Reader.cpp
@@ -629,6 +629,8 @@ void RowReader::pickRowGroups()
     VectorWithMemoryTracking<TruthValue> values(leaves.size(), TruthValue::YES_NO_NULL);
     const UInt32 writer_version = reader.getPostScript().writer_version;
     const Proto::ColumnStatistics empty_statistics;
+    const bool timestamps_comparable = options.row_group_filter && writer_version >= WRITER_VERSION_ORC_135
+        && !areTimestampsShifted(stripe_streams->getWriterTimezone());
 
     UInt64 next_skipped_group = groups;
     for (UInt64 group = groups; group > 0;)
@@ -663,7 +665,7 @@ void RowReader::pickRowGroups()
                 if (it == row_indexes.end() || group >= it->second.entry.size() || !it->second.entry[group].statistics)
                     return nullptr;
                 return &*it->second.entry[group].statistics;
-            });
+            }, timestamps_comparable);
         if (!needed)
         {
             next_skipped_rows[group] = 0;
diff --git a/src/Processors/Formats/Impl/ORC/Reader.h b/src/Processors/Formats/Impl/ORC/Reader.h
index ca95668c9c25..2a4cdc41cf24 100644
--- a/src/Processors/Formats/Impl/ORC/Reader.h
+++ b/src/Processors/Formats/Impl/ORC/Reader.h
@@ -40,7 +40,9 @@ struct ReaderOptions
     UInt64 range_size_limit = 32 * 1024 * 1024;
 };
 
-using RowGroupFilter = std::function<bool(const std::function<const Proto::ColumnStatistics *(UInt64)> &)>;
+/// The second argument is false if the TIMESTAMP statistics are not the UTC instants that are read
+/// (a local writer or reader time zone, or a writer before ORC-135), as in `PredicateLeaf::evaluate`.
+using RowGroupFilter = std::function<bool(const std::function<const Proto::ColumnStatistics *(UInt64)> &, bool)>;
 
 struct RowReaderOptions
 {
diff --git a/src/Processors/Formats/Impl/ORC/SearchArgument.cpp b/src/Processors/Formats/Impl/ORC/SearchArgument.cpp
index 0eb52cc862a5..9ff16a5db4ce 100644
--- a/src/Processors/Formats/Impl/ORC/SearchArgument.cpp
+++ b/src/Processors/Formats/Impl/ORC/SearchArgument.cpp
@@ -379,9 +379,6 @@ VectorWithMemoryTracking<T> literalsTo(const VectorWithMemoryTracking<Literal> &
     return result;
 }
 
-/// From the reference implementation: the writer version that fixed the timestamp statistics.
-constexpr UInt32 WRITER_VERSION_ORC_135 = 6;
-
 }
 
 TruthValue PredicateLeaf::evaluatePredicateMinMax(const Proto::ColumnStatistics & stats) const
diff --git a/src/Processors/Formats/Impl/ORC/SearchArgument.h b/src/Processors/Formats/Impl/ORC/SearchArgument.h
index 3e11d14047fa..2c8e68f8a946 100644
--- a/src/Processors/Formats/Impl/ORC/SearchArgument.h
+++ b/src/Processors/Formats/Impl/ORC/SearchArgument.h
@@ -13,6 +13,9 @@
 namespace DB::ORC
 {
 
+/// From the reference implementation: the writer version that fixed the timestamp statistics.
+inline constexpr UInt32 WRITER_VERSION_ORC_135 = 6;
+
 /// The possible outcomes of a predicate over a set of rows: whether any row can satisfy it (YES),
 /// fail it (NO), or evaluate it to NULL.
 enum class TruthValue : UInt8
diff --git a/tests/queries/0_stateless/05495_orc_filter_pushdown_monotonic_chain.reference b/tests/queries/0_stateless/05495_orc_filter_pushdown_monotonic_chain.reference
index c1ee5ebc54e2..3ebeed98f4d7 100644
--- a/tests/queries/0_stateless/05495_orc_filter_pushdown_monotonic_chain.reference
+++ b/tests/queries/0_stateless/05495_orc_filter_pushdown_monotonic_chain.reference
@@ -37,6 +37,22 @@ tuple	1	100000
 tuple	1	100000
 dotted	10000
 dotted	10000
+toStartOfMonth	40000
+toYYYYMM	30000
+toMonday	20000
+toDate	20000
+toStartOfHour	10000
+toDate reader time zone	200000
+toDate	10800	1108074600
+toDate	10800	1108074600
+toStartOfMonth	31000	2340484500
+toStartOfMonth	31000	2340484500
+date default	1
+date default pruned	10000
+timestamp default	1
+timestamp default pruned	10000
+epoch	2500	1970-01-01 00:00:00.000000000	1970-01-01 00:00:00.000800000
+epoch	2500	1970-01-01 00:00:00.000000000	1970-01-01 00:00:00.000800000
 tuple	10000
 dotted	10000
 struct nulls	10
diff --git a/tests/queries/0_stateless/05495_orc_filter_pushdown_monotonic_chain.sh b/tests/queries/0_stateless/05495_orc_filter_pushdown_monotonic_chain.sh
index df91a4504e6e..9d0c31f94677 100755
--- a/tests/queries/0_stateless/05495_orc_filter_pushdown_monotonic_chain.sh
+++ b/tests/queries/0_stateless/05495_orc_filter_pushdown_monotonic_chain.sh
@@ -98,6 +98,48 @@ SELECT 'dotted', count() FROM file(currentDatabase() || '_05495_dotted.orc', ORC
 SELECT 'dotted', count() FROM file(currentDatabase() || '_05495_dotted.orc', ORC, 't Tuple(`x.y` Int64, x Tuple(y Int64))')
     WHERE t.x.y = 7 SETTINGS optimize_functions_to_subcolumns = 1;
 
+-- DATE and TIMESTAMP columns: 1000 rows a day and 8 seconds a row.
+SET session_timezone = 'UTC';
+INSERT INTO FUNCTION file(currentDatabase() || '_05495_dt.orc', ORC)
+    SELECT number AS id, toDate32('2020-01-01') + intDiv(number, 1000) AS d,
+        toDateTime64('2020-01-01 00:00:00', 3, 'UTC') + toIntervalSecond(number * 8) AS ts
+    FROM numbers(200000);
+SELECT 'toStartOfMonth', count() FROM file(currentDatabase() || '_05495_dt.orc', ORC) WHERE indexHint(toStartOfMonth(d) = '2020-03-01');
+SELECT 'toYYYYMM', count() FROM file(currentDatabase() || '_05495_dt.orc', ORC) WHERE indexHint(toYYYYMM(d) = 202002);
+SELECT 'toMonday', count() FROM file(currentDatabase() || '_05495_dt.orc', ORC) WHERE indexHint(toMonday(d) = '2020-01-06');
+SELECT 'toDate', count() FROM file(currentDatabase() || '_05495_dt.orc', ORC) WHERE indexHint(toDate(ts) = '2020-01-10');
+SELECT 'toStartOfHour', count() FROM file(currentDatabase() || '_05495_dt.orc', ORC) WHERE indexHint(toStartOfHour(ts) = '2020-01-10 05:00:00');
+SELECT 'toDate reader time zone', count() FROM file(currentDatabase() || '_05495_dt.orc', ORC) WHERE indexHint(toDate(ts) = '2020-01-10')
+    SETTINGS input_format_orc_reader_time_zone_name = 'Asia/Tokyo';
+SELECT 'toDate', count(), sum(id) FROM file(currentDatabase() || '_05495_dt.orc', ORC) WHERE toDate(ts) = '2020-01-10';
+SELECT 'toDate', count(), sum(id) FROM file(currentDatabase() || '_05495_dt.orc', ORC) WHERE toDate(ts) = '2020-01-10'
+    SETTINGS input_format_orc_filter_push_down = 0;
+SELECT 'toStartOfMonth', count(), sum(id) FROM file(currentDatabase() || '_05495_dt.orc', ORC) WHERE toStartOfMonth(d) = '2020-03-01';
+SELECT 'toStartOfMonth', count(), sum(id) FROM file(currentDatabase() || '_05495_dt.orc', ORC) WHERE toStartOfMonth(d) = '2020-03-01'
+    SETTINGS input_format_orc_filter_push_down = 0;
+
+-- A NULL read as the default of a non-Nullable DATE or TIMESTAMP column.
+INSERT INTO FUNCTION file(currentDatabase() || '_05495_dt_null.orc', ORC)
+    SELECT if(number = 15000, NULL, toDate32('2020-01-01') + intDiv(number, 1000))::Nullable(Date32) AS d,
+        if(number = 15000, NULL, toDateTime64('2020-01-01 00:00:00', 9, 'UTC') + toIntervalSecond(number * 8))::Nullable(DateTime64(9, 'UTC')) AS ts
+    FROM numbers(40000);
+SELECT 'date default', count() FROM file(currentDatabase() || '_05495_dt_null.orc', ORC, 'd Date32, ts DateTime64(9)') WHERE toYear(d) = 1970
+    SETTINGS input_format_null_as_default = 1;
+SELECT 'date default pruned', count() FROM file(currentDatabase() || '_05495_dt_null.orc', ORC, 'd Date32, ts DateTime64(9)') WHERE indexHint(toStartOfMonth(d) = '1970-01-01')
+    SETTINGS input_format_null_as_default = 1;
+SELECT 'timestamp default', count() FROM file(currentDatabase() || '_05495_dt_null.orc', ORC, 'd Date32, ts DateTime64(9)') WHERE toDate(ts) = '1970-01-01'
+    SETTINGS input_format_null_as_default = 1;
+SELECT 'timestamp default pruned', count() FROM file(currentDatabase() || '_05495_dt_null.orc', ORC, 'd Date32, ts DateTime64(9)') WHERE indexHint(toDate(ts) = '1970-01-01')
+    SETTINGS input_format_null_as_default = 1;
+
+-- Timestamps around the epoch.
+INSERT INTO FUNCTION file(currentDatabase() || '_05495_epoch.orc', ORC)
+    SELECT toDateTime64('1969-12-31 23:59:58', 6, 'UTC') + toIntervalMicrosecond(number * 400) AS ts FROM numbers(20000)
+    SETTINGS output_format_orc_row_index_stride = 1000;
+SELECT 'epoch', count(), min(ts), max(ts) FROM file(currentDatabase() || '_05495_epoch.orc', ORC) WHERE toUnixTimestamp64Milli(ts) BETWEEN -1 AND 0;
+SELECT 'epoch', count(), min(ts), max(ts) FROM file(currentDatabase() || '_05495_epoch.orc', ORC) WHERE toUnixTimestamp64Milli(ts) BETWEEN -1 AND 0
+    SETTINGS input_format_orc_filter_push_down = 0;
+
 SYSTEM FLUSH LOGS query_log;
 SELECT 'tuple', read_rows FROM system.query_log
     WHERE current_database = currentDatabase() AND log_comment = '05495_tuple' AND type = 'QueryFinish';

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-formats Input/output formats (CSV/JSON/Parquet/ORC/Arrow/Protobuf/etc.). pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Monotonic function chains prevent ORC filter pushdown

4 participants