Repository navigation
Conversation
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]>
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.
Not changed here: the search argument's own Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-11:20261101-163800 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-5:20261101-160800 |
|
cc @alexey-milovidov @al13n321, could you review this and add the |
|
Workflow [PR], commit [f21ec3d] Summary: ✅
AI ReviewSummaryThe PR adds Missing context / blind spots
Final VerdictStatus: ✅ Approve |
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]>
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes4 object files changed (+57.70 KiB total), 0 added.
711 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units13 translation units recompiled, 77 s compile time in total, 13 of them have a recent master baseline. |
`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]>
CI finish ledger - 0de896aEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20261102-033003 |
|
@alexey-milovidov should you review this? |
…-native-orc-monotonic-chain
`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]>
|
@groeneai, the row-group filter here only takes 50M-row ORC file sorted by time (2023-01-01 to 2024-12-30, 10,000-row row groups, 478 MB),
The The Results were identical with 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'; |
Closes: #112577
Changelog category (leave one):
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 = -555555orid + 1 IN (...), which previously read the whole file. Closes #112577.Description
An ORC search argument compares a stored column with a literal, so
buildORCSearchArgumentImplturns 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-injectiveintDiv, decreasing-id, lossy casts), so the chain is evaluated forward, as in the Parquet reader.ORC::RowReaderOptionsgets arow_group_filter, whichRowReader::pickRowGroupscombines with the search argument's decision for each row group.NativeORCBlockInputFormatbuilds it only when the key condition has a monotonic chain:KeyCondition::checkInHyperrectangleover the row index min/max. Ranges are built only forBYTE/SHORT/INT/LONGcolumns, including named tuple elements, resolved and type-checked as in the search argument (the type check moved intoisSameTypeAsInORCFile); a row group with NULLs is not bounded (ifNullortransform_null_incan match a NULL) unlessinput_format_null_as_defaultreads 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 storingxfirst, the search argument boundt.x.ytox's fieldyand 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]