Skip to content

Add monotonic toStartOf*Extended, toLastDayOf*Extended, toMondayExtended, and toRelative*NumExtended datetime functions for primary key and partition expressions - #108002

Closed
nihalzp wants to merge 15 commits into
ClickHouse:masterfrom
nihalzp:extended-datetime-functions
Closed

nihalzp wants to merge 15 commits into
ClickHouse:masterfrom
nihalzp:extended-datetime-functions

Conversation

@nihalzp

@nihalzp nihalzp commented Jun 19, 2026 •

Copy link
Copy Markdown
Member

Related: #105244, #101814

The base functions wrongly tell that they are always monotonic but they are not for some input types and can give wrong results when column contains extreme values or even some cases pre-epoch values. This PR creates the Extended versions of these base function that guarantee that the functions will always be monotonic across all four input types: Date, DateTime, Date32, DateTime64. For example:

DROP TABLE IF EXISTS test;
CREATE TABLE test (d Nullable(Date32))
ENGINE = MergeTree PARTITION BY toRelativeDayNum(assumeNotNull(d)) ORDER BY tuple() SETTINGS allow_nullable_key = 1;

INSERT INTO test VALUES ('1969-12-31');
INSERT INTO test VALUES ('2024-01-20');
INSERT INTO test VALUES ('2024-01-30');
INSERT INTO test VALUES ('2024-02-20');

SELECT count() FROM test WHERE d <= '2024-01-25'; -- returns 1 (incorrect)

SELECT count() FROM test WHERE d <= '2024-01-25' SETTINGS use_partition_pruning = 0; -- returns 2 (correct)

EXPLAIN indexes = 1 SELECT count() FROM test WHERE d <= '2024-01-25';

Additionally, enable_extended_results_for_datetime_functions does not cover all the cases; the setting only widens when the input type is Date32 or DateTime64 but does not when input is Date.

Changelog category (leave one):

  • New Feature

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

Add always-monotonic *Extended variants of the datetime functions: toStartOfDayExtended, toStartOfHourExtended, toStartOfMinuteExtended, toStartOfFiveMinutesExtended, toStartOfTenMinutesExtended, toStartOfFifteenMinutesExtended, toMondayExtended, toStartOfWeekExtended, toStartOfMonthExtended, toStartOfQuarterExtended, toStartOfYearExtended, toLastDayOfMonthExtended, toLastDayOfWeekExtended, toRelativeWeekNumExtended, toRelativeDayNumExtended, toRelativeHourNumExtended, toRelativeMinuteNumExtended, and toRelativeSecondNumExtended. Each returns a wide-enough result type (Date32, DateTime64, or Int64) so that, unlike the corresponding base function, the result does not wrap for arguments outside the Date/DateTime range and stays monotonic over the whole input range. This makes them the recommended choice in primary key and partition key expressions, where the primary index can then prune data correctly, independent of the enable_extended_results_for_datetime_functions setting.

@clickhouse-gh

clickhouse-gh Bot commented Jun 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [906e935]

Summary: ❌

job_name test_name status info comment
Fast test FAIL
04261_to_start_of_extended_date32_family_pk_condition FAIL cidb
Docs check DROPPED
Fast test (arm_darwin) DROPPED
Build (amd_debug) DROPPED
Build (amd_asan_ubsan) DROPPED
Build (amd_tsan) DROPPED
Build (amd_msan) DROPPED
Build (amd_binary) DROPPED
Build (arm_debug) DROPPED
Build (arm_asan_ubsan) DROPPED

AI Review

Summary

This PR adds always-on Extended datetime/relative-number functions and wires them through the existing datetime transform templates, source-level function docs, and stateless coverage for primary-key pruning. The core approach looks consistent, but I found one stateless test syntax issue and one user-facing return-type documentation mismatch that should be fixed before merge.

Missing context / blind spots
  • ⚠️ The linked Praktika report currently contains zero test results, and there is no local ClickHouse binary/build directory available here, so I could not validate the new stateless tests by execution. A passing stateless run after the test syntax fix would close this gap.
Findings

⚠️ Majors

  • [tests/queries/0_stateless/04261_to_start_of_extended_date32_family_pk_condition.sql:44] The query uses two SETTINGS clauses in one SELECT, so the stateless test will fail before it checks force_primary_key. Use a single settings list: SETTINGS optimize_use_implicit_projections = 0, force_primary_key = 1.

💡 Nits

  • [src/Functions/toLastDayOfMonth.cpp:54] The docs say Date input returns Date, but the implementation sets widen_date_input = true, so Date input returns Date32. Update this sentence to include Date in the Date32 case; the same correction is needed for toLastDayOfWeekExtended.
Tests
  • ⚠️ The new test suite evidence is insufficient until 04261_to_start_of_extended_date32_family_pk_condition.sql parses and the Praktika/stateless run reports results.
Final Verdict

Status: ⚠️ Request changes

Minimum required actions: fix the duplicate SETTINGS clause in the stateless test and correct the Date return-type documentation for the round-up Extended variants.

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Jun 19, 2026
INSERT INTO t_d32_post_2149 VALUES ('2150-01-15'), ('2200-06-15'), ('2299-12-31');

SELECT trimLeft(explain) FROM (EXPLAIN indexes = 1 SELECT count() FROM t_d32_post_2149 WHERE toStartOfYearExtended(d) >= toDate32('2150-01-01') SETTINGS optimize_use_implicit_projections = 0) WHERE explain LIKE '%Condition%' OR explain LIKE '%Parts%' OR explain LIKE '%Granules%' OR explain LIKE '%Keys%' OR explain LIKE '%Search Algorithm%' OR explain LIKE '%Min-Max%' OR explain LIKE '%Partition%' OR explain LIKE '%PrimaryKey%';
SELECT count() FROM t_d32_post_2149 WHERE toStartOfYearExtended(d) >= toDate32('2150-01-01') SETTINGS optimize_use_implicit_projections = 0 SETTINGS force_primary_key = 1;

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.

This query has two SETTINGS clauses in the same SELECT. The parser expects a single settings list, so this stateless test will fail before it reaches the force_primary_key check. Please combine them:

SETTINGS optimize_use_implicit_projections = 0, force_primary_key = 1

FunctionDocumentation::Description description = R"(
Same as [`toLastDayOfMonth`](#toLastDayOfMonth), but the result is monotonic across the entire range of every supported argument type, regardless of the [`enable_extended_results_for_datetime_functions`](/operations/settings/settings#enable_extended_results_for_datetime_functions) setting.

The result type is widened only as far as is needed to represent the result without wrapping. The function returns [`Date32`](/sql-reference/data-types/date32) for `Date32` and `DateTime64` arguments, and `Date` for `Date` and `DateTime` arguments.

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.

The implementation widens Date input for this Extended variant (widen_date_input = true), so toLastDayOfMonthExtended(toDate('2149-06-06')) returns Date32, not Date. This source documentation publishes the wrong return-type contract; please include Date in the Date32 case. The same correction is needed for toLastDayOfWeekExtended.

@nihalzp

nihalzp commented Jul 14, 2026

Copy link
Copy Markdown
Member Author

The problem of fixing incorrect query result is already handled by some bugfix PRs. This PR can be revisited if needed.

@nihalzp nihalzp closed this Jul 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-feature Pull request with new product feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant