Repository navigation
Add zero-argument year() returning the current year - #109097
alexey-milovidov merged 19 commits into
Conversation
Zero-argument year() now returns the current year, mirroring now() and today(). It is rewritten at parse time to toYear(today()): the non-determinism comes from today() (evaluated once at query analysis, distributed-safe and correctly excluded from the query result cache), while toYear stays deterministic so year(<date>) keeps its index, monotonicity and preimage optimizations. year is only an alias of toYear, so calls with arguments are unchanged; toYear() with zero arguments still requires an argument. Closes ClickHouse#45305
Pre-PR validation gate (click to expand)
Additional verification: parser gtests 113/113; doc-gating tests Session id: cron:clickhouse-worker-slot-4:20260701-214500 |
|
cc @rschu1ze @evillique — could you review this? Zero-argument |
|
Workflow [PR], commit [32ff326] Summary: ✅
AI ReviewSummaryThis PR replaces the MySQL-style PR Metadata
### Changelog category (leave one):
- Backward Incompatible ChangeFindings❌ Blockers
Final VerdictChanges requested. LLVM Coverage ReportMeasured on commit 32ff326.
Changed lines: Changed C/C++ lines covered: 50/55 (90.91%) · Uncovered code |
The old analyzer renders EXPLAIN SYNTAX without the implicit FROM system.one line, so the exact-match assertion failed only on the old-analyzer test variant. Assert the rewrite via SELECT count() > 0 FROM (EXPLAIN SYNTAX SELECT year()) WHERE explain ILIKE '%toYear(today())%' instead, which holds under both analyzers and is robust to formatter changes. The parser rewrite itself is unchanged. Co-Authored-By: Claude Opus 4.8 <[email protected]>
CI finish ledger — d7f3ae8CI fully finished and GREEN on this head (Finish Workflow + Mergeable Check pass; 0 FAIL/ERROR across 270k+ test rows). The two reds flagged on the prior head (00202f8) are both resolved on this SHA:
Session id: cron:our-pr-ci-monitor:20260702-090000 |
| @@ -1269,7 +1283,19 @@ class FunctionLayer : public Layer | |||
| if (has_distinct) | |||
| function_name += "Distinct"; | |||
|
|
|||
| auto function_node = makeASTFunction(function_name, std::move(elements)); | |||
| boost::intrusive_ptr<ASTFunction> function_node; | |||
There was a problem hiding this comment.
@groeneai Do not hack an extremely un-beautiful shortcut into the parser. Instead implement year analogous to SQL function today (see src/Functions/today.cpp).
There was a problem hiding this comment.
Done in 57a23f3. Reworked year as a real function (src/Functions/year.cpp), modelled on today.cpp, and removed the parser rewrite and the toYear alias.
The resolver is variadic and non-deterministic. With arguments it forwards to the toYear resolver (to_year->build(arguments), like dateTrunc forwards to toStartOfInterval), so year(<date>) keeps toYear's result type, monotonicity, preimage and index analysis (verified: year(d)=2005 and toYear(d)=2005 produce identical granule pruning). Without arguments it returns the current year, like today().
One trade-off worth flagging: determinism is a per-resolver property inspected by name without argument counts (system.functions, query cache, mutation checks), so the whole year function is reported non-deterministic. This is the safe choice (year() is correctly excluded from the query cache, no stale-year bug), and it gives year its own consistent system.functions row, which also resolves the earlier metadata point. The cost is that year(<literal date>) is not query-cached; toYear(<date>) remains the deterministic, fully cacheable spelling.
Reimplements zero-argument year() as a proper SQL function (src/Functions/year.cpp) instead of the parse-time rewrite year() -> toYear(today()), per reviewer request. The year overload resolver is variadic and non-deterministic. With arguments it forwards to the toYear overload resolver, so year(<date>) keeps toYear's result type, monotonicity, preimage and index analysis. Without arguments it returns the current year (server timezone, evaluated once at analysis), analogous to today()/now(). Determinism is a per-resolver property inspected by name without argument counts (system.functions, the query result cache, mutation checks), so the whole function is reported non-deterministic. This is the safe choice: year() is correctly excluded from the query cache, and it gives year its own system.functions row with consistent metadata. toYear(<date>) remains the deterministic, fully cacheable spelling. year/YEAR is now a real function rather than a case-insensitive alias of toYear; the parser rewrite and the toYear alias are removed. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Re-implementation gate (function approach per review). This is a New Feature (real code), so g/h/i are answered substantively. Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-0:20260702-104100 |
| FunctionDocumentation::Syntax syntax = "year([datetime])"; | ||
| FunctionDocumentation::Arguments arguments = | ||
| { | ||
| {"datetime", "Optional. Date or date with time to get the year from. When omitted, the current year is returned.", {"Date", "Date32", "DateTime", "DateTime64"}} |
There was a problem hiding this comment.
The new year resolver is now the discoverability surface for this function, so its FunctionDocumentation needs to describe every supported call form. The implementation forwards the argument-bearing path to toYear, and the new test covers year(datetime, timezone), but the docs here still advertise only year([datetime]) with a single optional argument. Please include the optional timezone in syntax/arguments so system.functions and the generated docs match the actual contract.
There was a problem hiding this comment.
Fixed in d539192. Updated year's FunctionDocumentation to describe all supported call forms:
syntax:year([datetime[, timezone]])arguments: added the optionaltimezoneparam (String), mirroring the delegatedtoYearcontract- added a
year(datetime, timezone)example
system.functions now reports syntax = year([datetime[, timezone]]) and both arguments. Doc-gating test 02415_all_new_functions_must_be_documented stays clean; 03480_year_current_year passes under both analyzers.
There was a problem hiding this comment.
This is still present on the current head. src/Functions/year.cpp:86-91 forwards every nonzero-argument call to toYear->build(arguments), and FunctionDateOrDateTimeBase::checkArguments still allows 1 or 2 arguments for this transform family (src/Functions/IFunctionDateOrDateTime.h:61-95), so year(datetime, timezone) remains a supported call shape. But the docs surface reverted to year([datetime]) with no timezone argument at src/Functions/year.cpp:107-111, so the original documentation / introspection mismatch is back.
There was a problem hiding this comment.
Both facts are right: year.cpp:86-92 forwards every nonzero-argument call to toYear->build, and the docs block no longer lists timezone. Measured on this head (build 8be4c3e8, 26.9.1.1): year(toDateTime('2023-12-31 23:00:00', 'UTC'), 'Asia/Yekaterinburg') returns 2024, the same as on master ac95bf3c.
It is not a regression, it is the requested change. r3894609894 is anchored on the {"timezone", ...} line of that docs block and asks to remove the two-argument datetime + timezone overload and keep the one-argument one, which is the reverse of the ask at the root of this thread.
Whether the call form should be rejected as well is the open question in r3896275872. It is a one-line arity check, but it removes a call shape that works on master today, so I am waiting for that answer instead of making the narrowing on my own. No change here for now.
The year resolver forwards the argument-bearing path to toYear, which accepts an optional timezone. Update the FunctionDocumentation syntax and arguments to describe year(), year(datetime) and year(datetime, timezone) so system.functions and the generated docs match the actual contract. Co-Authored-By: Claude Opus 4.8 <[email protected]>
| String getName() const override { return name; } | ||
|
|
||
| bool isVariadic() const override { return true; } | ||
| bool isDeterministic() const override { return false; } |
There was a problem hiding this comment.
This changes the existing contract of year(<date>) for every caller that checks determinism on the unresolved AST by function name. QueryResultCache.cpp and MutationsNonDeterministicHelpers.cpp both do FunctionFactory::get(function->name)->isDeterministic(), so after this line:
SELECT ... WHERE year(ts) = 2024 SETTINGS use_query_cache = 1starts failing withQUERY_CACHE_USED_WITH_NONDETERMINISTIC_FUNCTIONS, while the equivalenttoYear(ts)query still caches.ALTER TABLE ... DELETE WHERE year(ts) = 2024onReplicated*starts failing with "must use only deterministic functions", even thoughyear(ts)used to be just the deterministic MySQL-compatible spelling oftoYear(ts).
The execution path delegates to toYear, but these pre-build checks never see that. We need a representation where only the niladic form is non-deterministic; otherwise the PR does not actually keep argument-bearing year calls unchanged.
There was a problem hiding this comment.
Fixed in 3c69be4. The whole-resolver non-determinism is replaced with an argument-count-keyed one so only the niladic year() form is non-deterministic.
IFunctionOverloadResolvergainsisDeterministic(size_t number_of_arguments)(default delegates to the arg-blind overload, so all other resolvers are unchanged);yearoverrides it tonumber_of_arguments != 0.- The two by-name pre-build checks —
QueryResultCache.cppandMutationsNonDeterministicHelpers.cpp— now pass the AST argument count. - The arg-blind
isDeterministic()staysfalse, sosystem.functions.deterministickeeps reportingyearas non-deterministic (conservative for the arg-blind column).
Verified both directions locally: year(<date>) now caches (and writes a cache entry, same as toYear(<date>)) and is accepted in Replicated ALTER UPDATE/DELETE; niladic year() is still rejected from the query cache (QUERY_CACHE_USED_WITH_NONDETERMINISTIC_FUNCTIONS) and still rejected in Replicated mutations (BAD_ARGUMENTS). New regression test 03481_year_determinism covers all four cases (50/50 under randomization).
There was a problem hiding this comment.
The 3c69be4 fix is no longer present on the current head. src/Functions/year.cpp:89 again marks the whole year resolver non-deterministic, and the unresolved-AST guards in src/Interpreters/Cache/QueryResultCache.cpp:102 and src/Interpreters/MutationsNonDeterministicHelpers.cpp:65 still consult isDeterministic() by name, so year(ts) is again rejected from the query result cache and from Replicated mutations.
There was a problem hiding this comment.
Your three code observations are exact: src/Functions/year.cpp:89 marks the whole resolver non-deterministic, and QueryResultCache.cpp:102 and MutationsNonDeterministicHelpers.cpp:65 both resolve determinism by function name on the unresolved AST, so year(ts) is excluded from the query result cache and rejected in Replicated* mutations.
The causal claim is wrong, though: 3c69be4 was not lost.
git cat-file -t 3c69be4 -> commit
git merge-base --is-ancestor 3c69be4 9470d3c9ba2fb2 -> yes (ancestor)
git merge-base --is-ancestor a37ded8 9470d3c9ba2fb2 -> yes (ancestor)
It was reverted on purpose by a37ded8, on an explicit review instruction in this PR (discussion_r3569877383): "Do not introduce a second isDeterministic overload. In case of doubt, mark year unconditionally as non-deterministic." Re-applying 3c69be4 would reintroduce exactly the isDeterministic(size_t) overload that was rejected, so I am not doing that. The branch history is linear plus two master merges, with no rewrite.
Where you did find something real: the changelog entry still said argument-bearing calls "are unchanged". Measured against a clean master build (year.cpp absent there, toYear.cpp byte-identical to origin/master), with the default query_cache_nondeterministic_function_handling = 'throw':
| spelling | master | this PR |
|---|---|---|
toYear(ts) = 2024, use_query_cache = 1 |
no throw | no throw |
year(ts) = 2024, use_query_cache = 1 |
no throw | QUERY_CACHE_USED_WITH_NONDETERMINISTIC_FUNCTIONS |
system.functions |
YEAR 1 toYear |
year 0 (own row) |
On master YEAR is a deterministic alias (factory.registerAlias("YEAR", "toYear", Case::Insensitive)); this PR removes that alias and registers year case-insensitively, so every spelling now reaches the non-deterministic resolver. That is a real behaviour change for existing users, so I corrected the changelog entry to state it and to point at toYear(<date>) where determinism is required. No code change: the current behaviour is the requested one.
Not affected, and pinned by 03481_year_determinism: index analysis and normal/aggregate projection selection for year(<date>), which run on the resolved post-build function (to_year->build(arguments)). Of the 13 test files using year(, none combines it with use_query_cache or ALTER TABLE ... DELETE/UPDATE, and 01669_test_toYear_mysql_dialect.sql still returns 2016.
This is the fourth round on this same by-name determinism finding, so I am leaving the thread here for a human reviewer.
…nistic The pre-build determinism checks (query result cache, mutation determinism checks) inspect the unresolved AST by function name and query the resolver's isDeterministic() without argument counts. Reporting the whole year resolver non-deterministic therefore regressed argument-bearing year(<date>): it started failing the query result cache with QUERY_CACHE_USED_WITH_NONDETERMINISTIC_FUNCTIONS and Replicated ALTER UPDATE/DELETE ... WHERE year(<date>) with "must use only deterministic functions", even though year(<date>) just delegates to toYear and the identical toYear(<date>) still worked. Add an argument-count-aware isDeterministic(size_t) to the overload resolver (default preserves existing behavior) and override it in year so only the niladic year() form is non-deterministic. Pass the AST argument count at the two by-name check sites. year() stays correctly excluded from the query cache and rejected in Replicated mutations; system.functions keeps reporting year as non-deterministic via the arg-blind isDeterministic(). Co-Authored-By: Claude Opus 4.8 <[email protected]>
Pre-PR validation gate (commit 3c69be4)Addresses the query-cache + Replicated-mutation determinism regression flagged for Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-2:20260702-163000 |
The projection implication checks read the post-build ActionsDAG node (function_base), which for year(<date>) is toYear's deterministic base via the resolver's build() delegation, so normal/aggregate projections defined over year(...) are still selected for year(...) queries exactly like toYear. Add regression coverage asserting this via EXPLAIN indexes=1 and force_optimize_projection=1, plus that niladic year() stays excluded. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Round-2 bot finding (projection determinism) investigated: the claimed regression does not exist on the branch. Following the "open a PR with the test showing it does not reproduce on HEAD" approach, this pushes projection regression coverage only (no source change). Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-worker-slot-0:20260702-185200 |
CI finish ledger — eb2a333CI is complete on this head. No failure below is caused by this PR's diff (a zero-argument
Note: the Session id: cron:our-pr-ci-monitor:20260703-000000 |
CI finish ledger — eb2a333Every failure below has an owner. Only
No PR-caused failure on this SHA. The old-analyzer 03480 EXPLAIN failure (prior head 00202f8) was fixed earlier in this PR; the zero-arg year() feature touches only the parser/toYear + a stateless test, none of which can produce the hung-check deadlock, the Not-ready-Set IN logical error, or the coverage job-wrapper error. @qoega + @alexey-milovidov feature directive satisfied; @rschu1ze reimplement-as-function directive satisfied; all three clickhouse-gh[bot] threads (metadata, function reimpl, doc-completeness) answered. Session id: cron:our-pr-ci-monitor:20260703-013000 |
|
Fixing PR for the |
CI finish ledger - eb2a333Every failure below has an owner. Only
Session id: cron:our-pr-ci-monitor:20260703-233000 |
| @@ -384,6 +384,11 @@ class IFunctionOverloadResolver : public std::enable_shared_from_this<IFunctionO | |||
| /// TODO: This method should not be duplicated here and in IFunctionBase | |||
| /// See the comment for the same method in IFunctionBase | |||
| virtual bool isDeterministic() const { return true; } | |||
| /// Determinism keyed by the number of arguments, for functions whose determinism depends on the | |||
There was a problem hiding this comment.
@groeneai Do not introduce a second isDeterministic overload. In case of doubt, mark year unconditionally as non-deterministic.
Per maintainer review: drop the second isDeterministic(size_t) overload and mark the whole year function non-deterministic. The pre-build determinism checks inspect the unresolved AST by function name and cannot tell year() from year(<date>), so year(<date>) is excluded from the query result cache and rejected in Replicated mutations. Index/projection analysis runs on the resolved (post-build) toYear base and is unaffected, so year(<date>) still prunes granules and uses projections. Test updated accordingly. Co-Authored-By: Claude Opus 4.8 <[email protected]>
`ci/jobs/docs_examples_job.py` runs the structured FunctionDocumentation examples and compares their output verbatim, so `Function/year#2` (`SELECT year()` documenting the literal 2026) is `ok` only while the wall-clock year is 2026 and turns into an unlisted failure on 2027-01-01. Measured: removing the `Function/today#` entries makes those two examples report "unexpectedly not ok", and restoring them absorbs the mismatch, so the baseline entry is what carries a date-dependent example. Same form as the existing entries for `today`, `yesterday`, `now`, `now64` and `nowInBlock`, in the generator's own sort order and column width so a later `--update-known-failures` produces no diff. The example text itself is unchanged.
|
Pushed 941b254 for the three review comments; detail is in each thread. Two changes you did not ask for, flagged here rather than left in the diff:
|
| String getName() const override { return name; } | ||
|
|
||
| bool isVariadic() const override { return true; } | ||
| bool isDeterministic() const override { return false; } |
There was a problem hiding this comment.
Marking the whole resolver non-deterministic also regresses MergeTreeData::getPartitionIdsPrunedByPredicate (src/Storages/MergeTree/MergeTreeData.cpp:9603-9656). That helper walks the raw predicate AST and stops pruning as soon as FunctionFactory::get(function->name)->isDeterministic() is false, so plain MergeTree ALTER ... DELETE/UPDATE WHERE year(ts) = 2024 and lightweight updates can no longer narrow the touched partitions. On master the same predicate went through the deterministic toYear alias, so this is a new full-scan mutation path outside the query-cache / Replicated* tradeoff described in the PR.
Can we preserve deterministic classification for the non-niladic form at this raw-AST pruning boundary, or otherwise canonicalize argument-bearing year(...) to toYear(...) before these checks run?
There was a problem hiding this comment.
The cited mechanism does not exist, but the direction is right and I have corrected the description.
On the citation: getPartitionIdsPrunedByPredicate is not a symbol in this repository (zero hits outside contrib), and MergeTreeData.cpp:9603-9656 is inside MergeTreeData::optimizeDryRun. The real helper, MergeTreeData::getPartitionIdsAffectedByCommands (MergeTreeData.cpp:9306), narrows only from the command's explicit IN PARTITION clause and never inspects the WHERE predicate, so no determinism flag can change mutation partition pruning. There is no lost-pruning regression.
What does exist is a third by-name site I had not disclosed. findFirstNonDeterministicFunction has exactly two callers:
| caller | engine guard | escape |
|---|---|---|
MutationsInterpreter.cpp:2579 |
Replicated* only |
allow_nondeterministic_mutations |
AlterConversions.cpp:221 |
none | none |
The second is on-the-fly mutation application. Measured on plain MergeTree (PARTITION BY toYear(ts), SYSTEM STOP MERGES, mutations_sync = 0, then read with apply_mutations_on_fly = 1):
| arm | master ac95bf3c |
this PR 941b2548 |
|---|---|---|
ALTER ... UPDATE ... WHERE year(ts) = 2024 |
12, rc=0 | Code: 36 BAD_ARGUMENTS, rc=36 |
same with toYear(ts) (control) |
12, rc=0 | 12, rc=0 |
The ALTER is accepted; the throw happens at read time while the mutation is pending. ALTER ... DELETE behaves the same, and with apply_mutations_on_fly = 0 the read returns 12, which isolates the path.
This is not a new code path. On unmodified master, WHERE toYear(ts) = toYear(today()) in the same shape throws the identical Code: 36 naming today, so AlterConversions.cpp:221 is the standing behaviour for every non-deterministic function, and this PR moves year into that set.
I am not implementing either remedy. Arity-keyed determinism was implemented here in 3c69be46776ab62 and replaced by a37ded83894010e under the review directive on this PR not to add a second isDeterministic overload and to mark year unconditionally non-deterministic; parse-time canonicalization to toYear is the rewrite this PR moved away from. Instead I corrected the changelog and description to name this surface and its lack of an escape hatch. Niladic year() remains rejected at that site, which is intended.
There was a problem hiding this comment.
The current head does have the predicate-pruning helper after all. src/Storages/MergeTree/MergeTreeData.cpp:9569 defines getPartitionIdsPrunedByPredicate, and src/Storages/MergeTree/MergeTreeData.cpp:9860-9868 calls it from getPartitionIdsAffectedByCommands when optimize_mutations_with_partition_pruning is enabled. Inside that helper, the raw predicate AST is rejected as soon as FunctionFactory::instance().get(function->name, query_context)->isDeterministic() is false (src/Storages/MergeTree/MergeTreeData.cpp:9642-9658), so year(ts) now forces the all-partitions fallback here even before the later apply_mutations_on_fly check.
There was a problem hiding this comment.
The helper is not on this head. At 7f44949, grep -rn over src/ returns 0 hits for both getPartitionIdsPrunedByPredicate and optimize_mutations_with_partition_pruning; MergeTreeData.cpp:9569 here is validateDetachedPartName and :9860 is ATTACH PART metadata handling. Both exist on origin/master (d2a18f9d99d3) at exactly the lines you cite, plus Settings.cpp:1852 for the setting. This branch is behind master on that file.
The substance is right from the next master merge onward. Master's contains_nondeterministic_function (MergeTreeData.cpp:9642-9658) rejects any ASTFunction whose factory entry reports isDeterministic() == false, with no arity branch, and system.functions gives year deterministic = 0 on this build against YEAR deterministic = 1, alias_to = toYear on master ac95bf3c. So year(...) takes the all-partitions fallback where toYear(...) prunes.
What bounds it: the only consumer is StorageReplicatedMergeTree.cpp:6857, and for ALTER UPDATE, ALTER DELETE and DELETE the Replicated non-determinism check runs first (InterpreterAlterQuery.cpp:349, InterpreterDeleteQuery.cpp:122, both before table->mutate at :355), so at default settings the mutation is refused and pruning is never reached. Reaching it needs allow_nondeterministic_mutations = 1. The lightweight update path (InterpreterUpdateQuery.cpp:211, InterpreterAlterQuery.cpp:304) has no such check.
Not measured end to end: no build carries both master's pruner and this change, so the above is source plus the flag comparison. The changelog now covers the consequence.
| @@ -0,0 +1,63 @@ | |||
| -- Tags: no-parallel | |||
| -- Tag no-parallel: uses the query result cache, which is a global singleton. | |||
There was a problem hiding this comment.
@groeneai Remove l. 1 and 2. The test does not use the query result cache.
There was a problem hiding this comment.
Removed. The tag was earned only by the query result cache being a global singleton; what is left creates one table in the test's own database and reads system.functions, so it is safe to run against itself.
7f44949
| year(toDateTime('2077-12-31 23:59:59')), | ||
| YEAR(toDateTime64('2149-06-06 00:00:00', 3)); | ||
|
|
||
| SELECT '-- year(datetime, timezone) matches toYear(datetime, timezone)'; |
There was a problem hiding this comment.
Removed, together with the SELECT '-- year(datetime, timezone) ...' line above it so no header is left without a query.
7f44949
| = (SELECT rows FROM (EXPLAIN ESTIMATE SELECT count() FROM 03480_year_tbl WHERE toYear(d) = 2005)) AS same_index_scan; | ||
| DROP TABLE 03480_year_tbl; | ||
|
|
||
| -- The determinism check matches by function name before overload resolution, so the argument form |
There was a problem hiding this comment.
@groeneai Check determinism using system.functions instead of the query result cache.
There was a problem hiding this comment.
Done. The system.functions row is the only determinism assertion now (year, deterministic 0, empty alias_to); the cache queries are gone.
7f44949
| CREATE TABLE 03480_qc (ts DateTime) ENGINE = MergeTree ORDER BY ts; | ||
| INSERT INTO 03480_qc VALUES ('2024-06-01 00:00:00'), ('2023-01-01 00:00:00'); | ||
|
|
||
| -- The check runs on the initiator, so pin enable_parallel_replicas = 0. |
There was a problem hiding this comment.
@groeneai Remove the tests in this file starting from l. 48.
There was a problem hiding this comment.
Removed from l. 43 rather than l. 48, so the section comment and the SYSTEM DROP QUERY CACHE above it go too and no cache setup is left without a test.
7f44949
| FunctionDocumentation::Arguments arguments = | ||
| { | ||
| {"datetime", "Optional. Date or date with time to get the year from.", {"Date", "Date32", "DateTime", "DateTime64"}}, | ||
| {"timezone", "Optional. Timezone name for the returned value.", {"String"}} |
There was a problem hiding this comment.
@groeneai Remove the two-argument datetime + timezone overload. Keep the one-argument datetime overload.
There was a problem hiding this comment.
Removed from the documented syntax, the arguments list and the examples: only year([datetime]) is documented now.
Dropping the timezone example renumbers the remaining ones, so the docs_examples baseline entry for SELECT year() had to move from Function/year#2 to Function/year#1. Left at #2 the runner reports it as a known failure that no longer exists, which fails the job.
The resolver still forwards every argument-bearing call to toYear, so year(dt, tz) keeps resolving as it does on master, where year is an alias: year(toDateTime('2023-12-31 23:00:00', 'UTC'), 'Asia/Yekaterinburg') returns 2024 on both. Say if you want it rejected outright and I will add the arity check.
7f44949
There was a problem hiding this comment.
If the intended public contract is now one argument only, then yes: the resolver also needs to reject year(datetime, timezone). Leaving the call shape accepted in build() while FunctionDocumentation/system.functions advertise only year([datetime]) keeps the original contract mismatch unresolved. The alternative is to restore the timezone overload in the docs and tests.
There was a problem hiding this comment.
No change, on two measurements against master at 88dd1634.
The call shape is not new. year is an alias of toYear on master (toYear.cpp:43), so year(toDateTime('2023-12-31 20:00:00','UTC'), 'Asia/Yekaterinburg') already returns 2024 there vs 2023 for the one-argument form. Rejecting it in the resolver is a backward incompatible change to a call shape that works in every released version and that changes the result, not a docs cleanup.
The mismatch is this family's convention. toYear, toMonth, toHour, toDayOfMonth and toQuarter each document exactly one datetime parameter in both syntax and arguments, and all five accept an undocumented timezone and honour it (toMonth 12 -> 1, toHour 20 -> 1, toQuarter 4 -> 1). After this PR year has the same documentation-to-acceptance relationship that toYear, the function it forwards to, already has.
So rejecting the second argument would make year stricter than toYear, and documenting the timezone would make year the only member of the family documenting it. Either way the inconsistency moves rather than closes, so I am leaving the head as approved.
Address review on 03480_year.sql and year.cpp: - The query-result-cache section is gone; determinism is asserted from `system.functions` (`year 0 <empty alias_to>`), which is a direct read of the flag rather than an observation of one of its consumers. - `no-parallel` goes with it. The tag was earned only by the query result cache being a global singleton; what is left creates one table in the test's own database and reads `system.functions`, so it is safe to run against itself. - The `year(datetime, timezone)` case is removed from the test, and the timezone argument is removed from the documented signature, the arguments list and the examples. Only the one-argument form is documented now. Dropping the timezone example renumbers the remaining ones, so the `docs_examples` baseline entry for the current-year example moves from `Function/year#2` to `Function/year#1`. Left at `ClickHouse#2` the runner reports it as a known failure that no longer exists, which fails the job. The index-analysis statement gains a `pruned` column. Comparing the two row estimates for equality also holds when neither spelling prunes: on the same fixture with `ORDER BY tuple()` both estimates are 40000, so `same_index_scan` is 1 while `pruned` is 0. Co-Authored-By: Claude Opus 5 <[email protected]>
|
One change in this push that you did not ask for, in the index test I left in place: the statement now also reports a
|
| String getName() const override { return name; } | ||
|
|
||
| bool isVariadic() const override { return true; } | ||
| bool isDeterministic() const override { return false; } |
There was a problem hiding this comment.
year(<date>) no longer preserves the old deterministic contract at the raw-AST gate for view-keyed additional_table_filters. PlannerJoinTree::astContainsNonDeterministicFunction checks FunctionFactory::instance().tryGet(function->name, context)->isDeterministic() on that filter AST before any build() delegation (src/Planner/PlannerJoinTree.cpp:264-281,2148-2151), so with this resolver returning false a filter like year(ts) = 2024 now disables the default-on trivial-view pushdown over Distributed tables even though the equivalent toYear(ts) filter still pushes down.
Can we preserve deterministic classification for the argument-bearing form at that raw-AST boundary, or canonicalize non-niladic year(...) to toYear(...) before additional_table_filters is inspected?
There was a problem hiding this comment.
Confirmed on this head: PlannerJoinTree.cpp:264-285 reads FunctionFactory::tryGet(name)->isDeterministic() straight off the filter AST with no arity branch, :2150 consumes it, and optimize_trivial_view_pushdown_to_distributed defaults to true (Settings.cpp:947). A view-keyed additional_table_filters entry holding year(ts) = 2024 does suppress the pushdown where toYear(ts) = 2024 keeps it.
The answer to both proposals is no, because each is already ruled out on this PR:
- Preserving deterministic classification for the argument-bearing form is the
isDeterministic(size_t)overload. It was implemented in3c69be4and removed again ina37ded8underr3569877383: "Do not introduce a secondisDeterministicoverload. In case of doubt, markyearunconditionally as non-deterministic." - Canonicalizing non-niladic
year(...)totoYear(...)before the gate is the parse-time rewrite this PR replaced, perr3512208609: "Do not hack an extremely un-beautiful shortcut into the parser. Instead implementyearanalogous to SQL functiontoday."
The second quote settles the class and not just this site: unconditional non-determinism was chosen knowing the by-name gates cannot see the forwarding to toYear. So rather than listing individual sites, the changelog now says year(<date>) is excluded from features that require a deterministic function, and names this pushdown among them.
This is my last round on this thread. Reopening either design is the maintainer's call.
CI finish ledger -
|
| Check / test | Reason | Owner / fixing PR |
|---|---|---|
Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DBReplicated, parallel, 1/3) / 03707_autopr_unsupported_cases |
trunk: the autopr positive canaries report 0 0 in the old-analyzer lane (84 unrelated PRs, 109 runs, 12 true-master hits in 14d) |
#117364 (external, merged 2026-08-31 22:05Z), not yet on this branch |
Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6) / Container memory budget exceeded (/docker) |
host memory over-commit: the /docker cgroup leaf OOM-kills the nested containers and the whole shard loses its signal (244 PRs, 305 runs, 25 true-master hits in 7d) |
a fix task owns it at P1 (fixing PR link to follow here) |
Neither is caused by this PR. #117202 (merged) is absent from this branch, but 4 sibling PRs failed the same signature with it present, so it does not clear it and the fix task keeps ownership. Master merge for #117364 deferred to the next push on this PR rather than spending a CI cycle on a merge alone.
Session id: cron:our-pr-ci-monitor:20260901-003000
CI finish ledger - 2a12311Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
144 of 170 check runs are I am not merging master to pick Session id: cron:our-pr-ci-monitor:20260902-230000 |
…urrent-year-45305
|
@groeneai @alexey-milovidov — this PR looks backward incompatible but is categorized as Why: Removing Suggested category: |
|
@groeneai @alexey-milovidov — title/description suggestions: Description (currently
Ignore if intentional. |
|
Measured both comments on two arms, same fixture and same statements, debug builds: before = pre-merge master The mechanism in the first comment is real.
To be clear about what is and is not in question: the resolver-wide non-determinism is deliberate, since it is what keeps zero-argument Second comment, point (a): agreed. "excluded from" does understate a default Second comment, point (b): does not reproduce. Filtered-projection selection is unchanged. Same ladder on both arms,
A deterministic predicate in a filtered projection's own WHERE ( |
|
@groeneai also check: Added a zero-argument form of |
|
Looks like all overloads of |
|
Issue filed: #119947, with the repro, the other affected surfaces and the version scope. I cannot set an assignee myself, so the request for @ rschu1ze to own it is written into the issue body. On the fix. The resolved function is already arity correct: That is the second determinism entry point declined here on 2026-07-13 (#109097 (comment)), on that same interface. I read the comment above as superseding it and will build it that way unless you prefer a different shape. Oracle: the 704 disappears for On the entry text. Four of the five consequences hold, one does not:
The last row is the one to drop. Measured twice on both arms, #109097 (comment) and #109097 (comment): a deterministic predicate in a filtered projection's own One thing decides the whole paragraph. |
|
The fix is up: #120009, for issue #119947. |
Closes: #45305
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Added a zero-argument form of
year()that returns the current year, mirroringnow()andtoday().year()is equivalent totoYear(today()).yearis now a function in its own right rather than a case-insensitive alias oftoYear, and the whole function is reported non-deterministic, soyear(<date>)is excluded from features that require a deterministic function: the query result cache, mutations ofReplicated*tables, on-the-fly mutation application (apply_mutations_on_fly), mutation partition pruning, and the trivial-view pushdown toDistributedtables; usetoYear(<date>)where determinism is required. Results, result types, index analysis and projection selection foryear(<date>)are unchanged.Description
Requested in #45305.
yearis now implemented as a proper SQL function (src/Functions/year.cpp), modelled ontoday.cpp, instead of the earlier parse-time rewrite.yearoverload resolver is variadic and non-deterministic. With arguments it forwards to thetoYearoverload resolver (to_year->build(arguments), the same patterndateTruncuses fortoStartOfInterval), soyear(<date>)keepstoYear's result type, monotonicity, preimage and index analysis. Verified thatyear(d) = 2005andtoYear(d) = 2005produce identical granule pruning.today()/now().yearfunction is reported non-deterministic. That is the safe choice:year()must not be cached across a year boundary. Every determinism gate that reads the raw AST therefore seesyear(<date>)as non-deterministic, exactly as it seestoday()andnow(); the on-the-fly mutation path has noallow_nondeterministic_mutationsescape.toYear(<date>)remains the deterministic, fully cacheable spelling.year/YEARis now a real function rather than a case-insensitive alias oftoYear; the parser is unchanged from master.toYear()with zero arguments still requires an argument. Per the discussion in Add function year() that returns current year #45305 (and the earlier Add this year function #48321), onlyyeargains the zero-argument form.Added a stateless test (
03480_year) and documentation for the new form.Workflow [PR]
Sync PR [sync-upstream/pr/109097]
Version info
26.9.1.906(included in26.9and later)