Skip to content

Do not evaluate timestamp on rows that a preceding condition excludes - #132120

Merged
PedroTadim merged 2 commits into
ClickHouse:masterfrom
groeneai:timestamp-short-circuit-guard
Nov 20, 2026
Merged

PedroTadim merged 2 commits into
ClickHouse:masterfrom
groeneai:timestamp-short-circuit-guard

Conversation

@groeneai

@groeneai groeneai commented Nov 16, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #129178

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

Fixed timestamp throwing CANNOT_PARSE_DATETIME for rows that a preceding condition excludes, in if, multiIf, AND/OR, PREWHERE (also a WHERE moved to PREWHERE) and sum(if(...)). timestamp is now evaluated lazily behind such conditions, like toDateTime64.

Description

On 26.10.3.7 (also 26.3, 26.8 and master), SELECT if(s != 'x', timestamp(s), NULL) FROM (SELECT arrayJoin(['x', '2025-01-01']) AS s) fails with CANNOT_PARSE_DATETIME, although the condition excludes the only row that cannot be parsed. With default settings the same happens with multiIf, AND/OR, a WHERE moved to PREWHERE, an explicit PREWHERE, sum(if(...)), and for the second argument. toDateTime64(s, 6) works in all of these.

Root cause. timestamp parses every row and throws on a value it cannot parse, but returned false from isSuitableForShortCircuitArgumentsExecution. Lazy execution of if/multiIf/and/or, the PREWHERE read-step split, the PREWHERE condition order and the sumIf rewrite all read this flag, so they ran timestamp on every row. The String-parsing siblings (parseDateTime, makeDate, the toDateTime64 conversions) return true.

Change. Return true, and also describe canThrowIfKnown as true, as repeat does. Expressions with timestamp behind such a condition now run lazily, as with toDateTime64.

Other functions also report false while throwing on row values (for example toModifiedJulianDay, IPv4StringToNum, toBool); there is no can-throw oracle in the tree yet (see the TODO on canThrow in IFunctionAdaptors.h), so each needs the same change. This PR only fixes timestamp.

Tests. New 05814_timestamp_short_circuit fails on master in each of its 12 guarded cases and passed 50 randomized runs with the fix. Found while answering a review comment on #129178.


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

Version info

  • Merged into: 26.12.1.29-master (included in 26.12 and later)

groeneai and others added 2 commits November 16, 2026 19:49
`timestamp(expr[, expr_time])` parses its arguments row by row and throws
`CANNOT_PARSE_DATETIME` (or `ATTEMPT_TO_READ_AFTER_EOF` for an empty time) on
a value it cannot parse, but `isSuitableForShortCircuitArgumentsExecution`
returned `false`. Every mechanism that keeps a function behind the condition
in front of it reads that predicate: `findLazyExecutedNodes` (`if`, `multiIf`,
`and`, `or`), the PREWHERE read-step splitter, the PREWHERE condition order in
`MergeTreeWhereOptimizer`, and the `sum(if(...))` -> `sumIf` rewrite. So with
default settings these failed although the condition excludes the only
unparsable row:

    SELECT if(s != 'x', timestamp(s), NULL) FROM (SELECT arrayJoin(['x', '2025-01-01']) AS s);
    SELECT payload FROM u WHERE s != 'invaliddatetime' AND timestamp(s) > '2020-01-01';

The String-parsing siblings (`parseDateTime`, `parseTimeDelta`, `makeDate`,
`toDateTime64` and the other String conversions) already return `true`,
which is why `toDateTime64(s, 6)` works in exactly the same queries.

Return `true`, and also describe `canThrowIfKnown` as `true`, the way
`repeat` does: today `canThrow` falls back to the same predicate, so this
changes nothing by itself, but keeps the answer right when that fallback
becomes conservative (the TODO in `IFunctionAdaptors.h`).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Shorten the canThrowIfKnown comment in timestamp.cpp to the function's property.

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

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

Pre-publication review by an independent model (engine: codex; 1 finding), plus my own cold review (0 findings).

# Sev Finding Verdict Evidence / action
1 ⚠️ The test stays green if the sumIf rewrite or the WHERE-to-PREWHERE move silently declines; add EXPLAIN route assertions (05814_timestamp_short_circuit.sql) DISAGREE A declined route gives the correct answer, so it hides nothing. A route that is taken and runs timestamp on excluded rows reddens each case: on master all 12 guarded cases fail one by one, the WHERE cases inside the PREWHERE read step (FUNCTION timestamp(s : 0)) and the rewrite case through sumIf. The explicit PREWHERE case does not depend on the move. Plan-shape assertions would pin internals this PR does not change.

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

Session id: cron:clickhouse-review-self-slot-58:20261116-195400

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT if(s != 'x', timestamp(s), NULL) FROM (SELECT arrayJoin(['x', '2025-01-01']) AS s) fails with CANNOT_PARSE_DATETIME every time on master, default settings. The new test fails 20/20 randomized runs on the base binary.
b Root cause explained? timestamp throws on a row it cannot parse but returned false from isSuitableForShortCircuitArgumentsExecution. Lazy execution (if/multiIf/and/or), the PREWHERE step split, the PREWHERE condition order and the sumIf rewrite read only this flag, so timestamp ran on the rows the condition excludes.
c Fix matches root cause? Yes. The function now reports the property every consumer reads (as parseDateTime, makeDate and the toDateTime64 conversions do). No consumer changed, no guard added.
d Test intent preserved / new tests added? New 05814_timestamp_short_circuit: if, multiIf, AND, OR, the second argument, sum(if(...)) with the rewrite on and off, WHERE moved to PREWHERE (multiple and single read steps), explicit PREWHERE, LowCardinality and Nullable columns, plus two negative controls. No existing test changed.
e Both directions demonstrated? Yes. Base binary: 12/12 guarded cases fail (Code 41, Code 32 for the second argument). Fixed binary: 12/12 answer, controls still throw; 50/50 randomized runs pass.
f Fix is general across code paths? All consumers read the one flag, so all are fixed by it. Other functions with the same defect (for example toModifiedJulianDay, IPv4StringToNum, toBool) are separate code; there is no can-throw oracle to fix them at once yet (TODO on canThrow in IFunctionAdaptors.h).
g Fix generalizes across inputs (params/datatypes/wrappers)? The flag is unconditional. Checked String, LowCardinality(String), Nullable(String) with NULL rows, LowCardinality(Nullable(String)), a WHERE excluding every row, and both arguments. FixedString and empty values do not throw on master, so they cannot discriminate.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or default change. Only the evaluation strategy of expressions with timestamp changes (lazy instead of eager), as for toDateTime64. Existing timestamp and short-circuit tests give the same results.
i Invariants and contracts preserved? Yes. canThrow falls back to this flag, so the canThrowIfKnown override changes nothing by itself; canThrow is now true, the correct answer for a function that throws. and/or argument reordering can only lose a reordering, never move a throwing argument ahead.

Session id: cron:clickhouse-impl-self-slot-57:20261116-192800

@clickhouse-gh

clickhouse-gh Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a1729f8]

Summary: ✅


AI Review

Summary

timestamp now supports lazy argument evaluation and explicitly reports that it can throw, preserving guards in conditional expressions, aggregate rewrites, and PREWHERE. No actionable findings at a1729f85735a3aeb01cf4454dc18a1a3c384d524. The focused 05814_timestamp_short_circuit regression and existing 02834_timestamp_function test both passed in Fast test.

Missing context / blind spots
  • ⚠️ Automated base-versus-head bugfix validation did not run: Finish Workflow reports its validation jobs were dropped after Config Workflow. Rerunning those jobs would close this CI validation gap; the new regression passed on the PR head.
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default can be tested Allows running workflows for external contributors comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... labels Nov 16, 2026

@clickhouse-gh clickhouse-gh Bot left a comment

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.

AI review approves this commit, see the AI Review comment.

@clickhouse-gh

clickhouse-gh Bot commented Nov 16, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing a1729f857 with master f6bdd226e (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.

Compile time of recompiled translation units

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

Job report

Comment thread src/Functions/timestamp.cpp Resolved
@PedroTadim
PedroTadim added this pull request to the merge queue Nov 20, 2026
Merged via the queue into ClickHouse:master with commit cec9a0c Nov 20, 2026
568 of 572 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 20, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@groeneai @PedroTadim — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 21, 2026
Since ClickHouse#132120 `timestamp` no longer stops the split of an AND chain in
`FilterStep`, so in `WHERE timestamp(d, t) > x AND d = c` the equality is
filtered first and `optimize_constant_columns_after_filter` passes `d` to
`timestamp` as a constant. Master throws ILLEGAL_COLUMN for both argument
positions; this PR returns the rows. The queries pin the four settings
that path needs (switching any one of them off makes master pass), since
`query_plan_merge_filters` is randomized by the runner.

Closes ClickHouse#133331

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants