Skip to content

Partition pruning fix with date transforms - #103447

Closed
scanhex12 wants to merge 2 commits into
ClickHouse:masterfrom
scanhex12:fix_partition_pruning_iceberg
Closed

scanhex12 wants to merge 2 commits into
ClickHouse:masterfrom
scanhex12:fix_partition_pruning_iceberg

Conversation

@scanhex12

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Partition pruning fix with date transforms. This closes #103433

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

@clickhouse-gh

clickhouse-gh Bot commented Apr 23, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0843bf4]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_tsan, parallel, 1/2) FAIL
00175_obfuscator_schema_inference FAIL cidb
Unit tests (asan_ubsan) FAIL

AI Review

Summary

This PR tries to make Iceberg manifest pruning understand filters such as toDate(ts) = toDate('2024-01-10') by rewriting selected date/time functions to the internal Iceberg partition transforms. The direction is reasonable, but the current rewrite is too broad and not semantics-preserving: it can exclude files that contain matching rows and can make valid queries fail during pruning.

PR Metadata
  • 💡 The Bug Fix category is correct, but the changelog entry is too vague for the user-facing change. Suggested replacement: "Fixed Iceberg partition pruning for filters using date transforms such as toDate, toStartOfHour, and toYear on timestamp partition columns."
Findings

❌ Blockers

  • [src/Storages/ObjectStorage/DataLakes/Iceberg/ManifestFilesPruning.cpp:153] The rewrite is applied under any binary function, including range comparisons, but toStartOfHour(x) < c is not equivalent to toRelativeHourNum(x) < toRelativeHourNum(c) unless c is already aligned to an hour boundary. For example, toStartOfHour(ts) < toDateTime('2024-01-10 10:30:00') should keep rows from 10:00:00 through 10:59:59, while the rewritten predicate drops that hour. That lets KeyCondition prune manifests containing matching rows. Restrict the rewrite to equality, or derive correct half-open ranges for non-aligned constants before enabling range pruning.
  • [src/Storages/ObjectStorage/DataLakes/Iceberg/ManifestFilesPruning.cpp:64] The replacement transforms are not monotonic-equivalent over the full Iceberg temporal domain. Iceberg date maps to Date32 and timestamp maps to DateTime64, so pre-1970 values are valid, but the standard toRelativeDayNum / toRelativeHourNum paths used here wrap through unsigned representations for historical values. Range predicates can therefore invert ordering around the Unix epoch and prune files with matching rows. Either skip these substitutions for domains that can include pre-1970 values or use a signed transform whose monotonicity is proven against the Iceberg transform.
  • [src/Storages/ObjectStorage/DataLakes/Iceberg/ManifestFilesPruning.cpp:100] accepts_const_type allows any numeric RHS for toYear, but safeGet<UInt64> only works when the folded literal is exactly UInt64, and the subtraction has no bounds checks. Valid filters such as toYear(ts) = toInt32(2022) can fail with an exception when use_iceberg_partition_pruning is enabled. Convert through a type-aware path and validate the year range before subtracting 1970.

⚠️ Majors

  • [src/Storages/ObjectStorage/DataLakes/Iceberg/ManifestFilesPruning.cpp:140] The source function is replaced before checking that the argument type is accepted by the target function. toDate accepts inputs such as String, while toRelativeDayNum does not, so a valid filter on a string column can throw while building pruning conditions. Check the argument type before substitution and leave unsupported shapes unchanged.
  • [src/Storages/ObjectStorage/DataLakes/Iceberg/ManifestFilesPruning.cpp:144] Mutating only node.function_base leaves the ActionsDAG node internally inconsistent: result_type, the prepared executable, and any folded constant metadata still describe the original function. Even where KeyCondition reclones parts of the DAG today, this relies on implementation details and can feed stale types into analysis. Rebuild the node through ActionsDAG::addFunction or a dedicated DAG rewrite that updates the full node consistently.
Tests
  • ⚠️ The added tests only cover post-1970 equality predicates with aligned constants and happy-path literal types. Please add focused regressions for non-aligned range predicates, pre-1970 Date32 / DateTime64 values, non-UInt64 numeric RHS for toYear, and unsupported argument types such as toDate over String.
Final Verdict

Status: ❌ Block

Minimum required actions: make the rewrite predicate-aware and type-safe, prove or avoid temporal range rewrites where monotonicity does not hold, rebuild ActionsDAG nodes consistently, and add regression tests for the edge cases above.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Apr 23, 2026
[](const DataTypePtr & t) { return isNumber(t); },
[](ActionsDAG & dag, const ActionsDAG::Node * sibling, const ContextPtr &) -> const ActionsDAG::Node *
{
auto year_val = (*sibling->column)[0].safeGet<UInt64>();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

accepts_const_type allows any numeric constant, but safeGet<UInt64>() only works when the folded literal is exactly UInt64.

For example, toYear(ts) = toInt32(2022) (or any signed/float numeric literal after typing) reaches this branch and throws BAD_GET while building pruning conditions, turning a valid query into an exception when use_iceberg_partition_pruning=1.

Please either restrict the accepted RHS types to ones you can safely extract here, or convert via a type-aware path (e.g. cast the constant to an integer type first and validate bounds) before subtracting 1970.

@antonio2368 antonio2368 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems like a really tricky thing to do. We should probably have more tests with as many edge cases as possible.
AI should be good in finding those edge cases.

std::function<const ActionsDAG::Node *(ActionsDAG &, const ActionsDAG::Node *, const ContextPtr &)> convert_const;
};

static std::vector<FunctionSubstitutionEntry> buildSubstitutionTable(const ContextPtr & context)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Something AI found:
This rewrite is not safe for range pruning on Iceberg historical temporal values. Iceberg date is imported as Date32, and timestamp / timestamptz are imported as DateTime64 (SchemaProcessor.cpp:301-308), so pre-1970 values are valid input for manifest pruning. But the replacement functions used here are the standard unsigned relative transforms: toRelativeDayNum is registered as UInt32 and its standard Date32 path casts through UInt16, while toRelativeHourNum is registered as UInt32 and its standard historical paths cast through unsigned values (toRelativeDayNum.cpp:10, toRelativeHourNum.cpp:10, DateTimeTransforms.h:2188-2204, 2220-2240).

That does not preserve ordering across the Unix epoch. For example:

SELECT
    toDate32('1969-12-31') AS d1,
    toDate32('1970-01-01') AS d2,
    toRelativeDayNum(d1) AS r1,
    toRelativeDayNum(d2) AS r2,
    r1 < r2 AS relative_order_ok;

returns r1 = 65535, r2 = 0, and relative_order_ok = 0. Similarly, toRelativeHourNum(toDateTime64('1969-12-31 23:00:00', 0, 'UTC')) is greater than the value for 1970-01-01 00:00:00.

So a range predicate over toDate / toStartOfHour can be converted into a predicate whose ordering is different from the original one, and KeyCondition can then prune a manifest that actually contains matching rows. Equality for post-1970 happy paths is not enough to justify using these substitutions for ranges.

Please either skip these substitutions when the source domain can include pre-1970 Date32 / DateTime64, or use a signed/extended transform and only enable range rewrites after proving the replacement is monotonic-equivalent for the source and constant domains.

return &dag.addFunction(func_base, {const_node}, const_node->result_name);
};

entries.push_back({"toDate", "toRelativeDayNum",

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

toDate accepts strings, while toRelativeDayNum doesn't. You should probably check argument types before transforming.
Potentially same is true for other parts.

[](const DataTypePtr & t) { return isNumber(t); },
[](ActionsDAG & dag, const ActionsDAG::Node * sibling, const ContextPtr &) -> const ActionsDAG::Node *
{
auto year_val = (*sibling->column)[0].safeGet<UInt64>();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What gh reviewer said is true. You probably need to restrict it more.


std::unordered_map<const ActionsDAG::Node *, size_t> substituted_nodes;

for (auto & node : const_cast<ActionsDAG::Nodes &>(dag.getNodes()))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure if this is okay. I think you need to use ActionsDAG::addFunction.


for (auto & node : const_cast<ActionsDAG::Nodes &>(dag.getNodes()))
{
if (node.type != ActionsDAG::ActionType::FUNCTION || node.children.size() != 2)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems a bit scary, what if it's not comparison operator? Even for comparison operators there can be strange edge cases:
WHERE toStartOfHour(ts) < toDateTime('2024-01-10 10:30:00') becomes toRelativeHourNum(ts) < toRelativeHourNum('2024-01-10 10:30:00') which would exclude some values that it didn't exclude before.

@clickhouse-gh

clickhouse-gh Bot commented Jun 3, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.40% 84.50% +0.10%
Functions 92.40% 92.40% +0.00%
Branches 77.00% 77.00% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 37/85 (43.53%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@clickhouse-gh

clickhouse-gh Bot commented Jun 30, 2026

Copy link
Copy Markdown
Contributor

Dear @antonio2368, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@abashkeev abashkeev added the comp-datalake Data lake table formats (Iceberg/Delta/Hudi) integration. label Sep 4, 2026
@scanhex12

Copy link
Copy Markdown
Member Author

I'll close this PR and continue working here as this PR is too old: #118606

@scanhex12 scanhex12 closed this Sep 7, 2026
scanhex12 added a commit that referenced this pull request Sep 7, 2026
#103447 rewrote the filter itself,
substituting `toDate` with `toRelativeDayNum` and recomputing the constant, and
the review named two ways that loses rows: a constant that is not aligned to the
transform's granularity (`toStartOfHour(ts) < '... 10:30:00'` must keep the
10:00 hour, the rewrite dropped it) and a value before 1970, where the unsigned
relative transforms invert the ordering (`toRelativeDayNum('1969-12-31')` is
`65535` while `1970-01-01` is `0`).

Deriving the source range from the partition value leaves the predicate alone,
so both are decided by `KeyCondition` over an exact range instead of by an
equivalence that has to be proven. Test them: a non-aligned constant on the
hour, day and month transforms, and a table whose `days` and `years` partition
values are negative.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@clickhouse-gh clickhouse-gh Bot added comp-iceberg Apache Iceberg tables: reading and writing Iceberg metadata (snapshots, manifests, schema evoluti... and removed comp-datalake Data lake table formats (Iceberg/Delta/Hudi) integration. labels Nov 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-iceberg Apache Iceberg tables: reading and writing Iceberg metadata (snapshots, manifests, schema evoluti... pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Iceberg Partition Pruning not properly working with toDate function

4 participants