Skip to content

Let a table with a sequenceNextNode aggregate function column be loaded - #121996

Closed
groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:fix-aggregate-state-attach-without-query-context
Closed

groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:fix-aggregate-state-attach-without-query-context

Conversation

@groeneai

@groeneai groeneai commented Sep 24, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Improvement

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

A table with a column of type AggregateFunction(sequenceNextNode, ...) can now be loaded. Previously such a table could be created with enable_funnel_functions = 1 and then never opened again, because the loader has no query context and the creator read the absent settings as the feature gate being off.

Description

With enable_funnel_functions = 1 a column of type AggregateFunction(sequenceNextNode(...), ...) can be created, and the table can then never be opened again: the load fails UNKNOWN_AGGREGATE_FUNCTION wrapped in ASYNC_LOAD_WAIT_FAILED, its stored data unreachable, and no setting restores access.

Found while censusing the same contract for #121894, whose review asked whether other aggregate functions share it. No related issue.

Root cause. AggregateFunctionFactory::getImpl takes a creator's settings from the current thread's query context and passes nullptr when the thread has none (AggregateFunctionFactory.cpp:258-277). The async load table job is such a thread. The creator guarded with settings == nullptr || !(*settings)[enable_funnel_functions], reading "no settings" as "the gate is off". On a loader thread the gate's value is not merely false but invisible, which is why neither a query-level SET on reopen nor a server-level default helps.

Change. The gate now applies only when a query context exists, the form five sibling creators already use. Having the factory synthesise settings instead would not help: the gate defaults to false, so the column would stay unloadable.

Scope. rank and denseRank were fixed the same way in the first revision and are now dropped, per review: both are window functions, so their state arguably should not be a storable column type at all. WindowTransform.cpp is byte identical to master again and those two column types still fail to load exactly as on master, which is why the category moved from Bug Fix to Improvement.

Validation. 05252_aggregate_state_attach_without_query_context reopens the column across two clickhouse local invocations. It passes 50/50 under randomized settings and fails on a pristine master binary, with an unrelated test green in the same setup. With the gate at its default, sequenceNextNode(...), CAST to the type name and CREATE TABLE are all still refused.

Census: every creator in src/ that reads the const Settings *, and what it does when the pointer is null

Exhaustive grep -rn '(\*settings)\[' src/, plus settings-> across the same surface (no hits). Grouped by guard form.

Guard form Sites On a null pointer
refusing, settings == nullptr || ... 3 throws, so a stored column type naming it cannot be loaded: sequenceNextNode (fixed here), plus rank and denseRank, left alone per review
permissive, if (settings && ...) 5 constructs it: the timeSeries* family (its ~16 creators funnel through one choke point) and uniqExact's parallel-merge choice. Unchanged; this is the precedent
unchecked dereference 1 crashes. createAggregateFunctionFlameGraph, fixed by #121894, so not touched here
outside the creator surface 2 codec choice and a table function

No data type gates on a setting at parse time, and no window_creator registration reads the pointer, so a stored type always resolves through the plain creator this PR changes.

Six input shapes were measured for this arm, each failing to reopen before the change and reopening after it: plain; a LowCardinality(Nullable(String)) argument; the ('backward','tail') parameters; the state nested in Array(...) and in Map(...); MergeTree as well as Memory. Data reachability was measured by writing a state, reopening, and reading it back. Hand-corrupted stored metadata (a bad direction parameter, a truncated argument list) still fails on the loader path after the change, so the fix removes one refusal and no validation.


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

…ry context

A table with a column of type AggregateFunction(sequenceNextNode(...), ...),
AggregateFunction(rank, ...) or AggregateFunction(denseRank, ...) could be
created legally and then never opened again. On 26.9 the reopen fails with
UNKNOWN_AGGREGATE_FUNCTION for the first and NUMBER_OF_ARGUMENTS_DOESNT_MATCH
for the other two, wrapped in ASYNC_LOAD_WAIT_FAILED, and no setting restores
access: neither a query-level SET on the second run nor a server-level default
helps.

AggregateFunctionFactory::getImpl resolves the calling thread's query context
and passes the creator that context's settings, or nullptr when the thread has
none (AggregateFunctionFactory.cpp:258-277). There is no fallback to a global
context: ThreadStatus::tryGetQueryContext is a bare query_context.lock()
(ThreadStatus.cpp:216-219) and the query context is only ever populated by
CurrentThread::attachToGroup, which is what QueryScope::create does. The async
`load table` job runs on such a thread, and attaching a table parses its column
types, so the parse reaches these creators with a null pointer. All three
guarded with `settings == nullptr || !(*settings)[gate]`, reading "no settings"
as "the gate is off". That is why the setting's value cannot help on a loader
thread: the value is not merely false, it is not visible at all.

Applying the gate only when there is a query context is the form five sibling
creators already use (the timeSeries* family, whose creators funnel through one
choke point in AggregateFunctionTimeseriesHelpers.cpp, and uniqExact's
parallel-merge choice), and it is the form PR ClickHouse#121894 applies to the sixth. With
no query context there is no session whose setting could be consulted and no
principal to authorize, and the no-context path is reachable only by parsing a
type name that already exists in metadata, in a part's columns.txt, or in a
query plan a peer already validated. Writing that metadata required passing the
same gate in a query context, so no user-facing refusal is weakened: with both
gates at their defaults, SELECT rank(1) OVER (...), sequenceNextNode(...), CAST
to either type name and CREATE TABLE are all still refused, and the guard stays
the first statement in each creator so every later validation still runs,
including on the loader path.

For rank and denseRank this first shipped in 26.5, so such a table loads on 26.4
and stops loading on 26.5 through 26.9. Those two arms are openable and
droppable after this change but the column can never hold state, because
WindowFunction::serialize throws for a window function used as an aggregate;
sequenceNextNode is an ordinary aggregate function, and its stored data becomes
reachable again.

No setting is added, removed, or has its default changed, so
SettingsChangesHistory.cpp needs no entry.

Related: ClickHouse#121894
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-review-human PR origin: human review feedback on a groeneai PR labels Sep 24, 2026
@groeneai

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

Pre-publication review by an independent model (engine: codex; 1 finding) plus my own cold
review of the resulting code (3 nits).

# Sev Finding Verdict Evidence / action
1 ❌ Stored definitions replayed on a thread that HAS a query context are still refused with the gates at their defaults: short ATTACH TABLE after a DETACH, and first access under SETTINGS lazy_load_tables = 1. Proposed remedy: key the bypass on stored-definition provenance instead DISAGREE Both observations are true and both name a path this diff cannot reach: settings == nullptr || !(*settings)[g] and settings && !(*settings)[g] differ only when the pointer is null, so every session-bearing path is unchanged. Both are also remediable by the setting, which the reviewing model measured itself (gate set in the session, the lazy path returns 0 for all three types); the loader path is the opposite case and is why this PR exists, since there the value is invisible rather than false. Scope measured: lazy_load_tables defaults to false and is a per-database opt-in (src/Databases/DatabaseMetadataDiskSettings.cpp:17), and a short ATTACH is DDL in a session, so needing the setting CREATE needs is the gates' purpose. The remedy would thread a second signal for a fact the null pointer already carries, through every type parse, and would contradict #121894
2 💡 Three nits from my own cold review AGREE 2, DISAGREE 1 Two were in this description and are fixed above, before the code review ran: the changelog entry no longer reads as though the fix caused the defect, and one clause now says why substitute settings from the factory would not work (both gates default to false). The third, the test's fixed temporary directory name, is measured harmless: tests/clickhouse-test gives each run its own CLICKHOUSE_TMP unless --database is passed, and the name carries the test number

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. No source or test file was touched during review.

Session id: cron:clickhouse-review-slot-10:20260924-131900

@groeneai
groeneai requested review from novikd and rschu1ze September 24, 2026 14:00
@clickhouse-gh

clickhouse-gh Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8f49076]

Summary: ✅


AI Review

Summary

This PR fixes the settings == nullptr reload path for AggregateFunction(sequenceNextNode, ...), so startup/background metadata loads no longer reject the stored type just because there is no query context. I did not find any new issues beyond one previously raised concern that still holds: metadata replays that happen on a live query thread are still gated by the caller's session settings, so the advertised "table can now be loaded" contract remains incomplete.

Findings
  • ⚠️ Major: [dismissed by author -- https://github.com/Let a table with a sequenceNextNode aggregate function column be loaded #121996#issuecomment-5815567190] [src/AggregateFunctions/AggregateFunctionSequenceNextNode.cpp:464] The bypass is keyed only to settings == nullptr, but two supported metadata-replay paths still rebuild the table with a non-null query context and therefore keep rejecting the stored type unless the caller repeats enable_funnel_functions = 1: lazy materialization on first access under lazy_load_tables (src/Databases/DatabaseOrdinary.cpp:511-529, src/Storages/StorageTableProxy.h:61-68) and short ATTACH TABLE from stored metadata (src/Interpreters/InterpreterCreateQuery.cpp:1907-1937). That leaves a table created with the setting still unloadable by default in supported lifecycle paths, which contradicts the PR title and changelog entry. Suggested fix: key the bypass off stored-metadata provenance (attach_short_syntax / LoadingStrictnessLevel::ATTACH / recovery-from-metadata context) rather than only a null settings pointer, and add regression coverage for lazy first access plus short ATTACH.
Tests
  • ⚠️ tests/queries/0_stateless/05252_aggregate_state_attach_without_query_context.sh covers only the no-query-context reload path. Add one case that materializes a lazy table on first access and one that uses short ATTACH TABLE after DETACH, both without re-enabling enable_funnel_functions.
Final Verdict

Changes requested.

LLVM Coverage Report

Measured on commit 8f49076.

Metric Baseline Current Δ
Lines 88.20% 88.10% -0.10%
Functions 91.70% 91.70% +0.00%
Branches 79.50% 79.50% +0.00%

Changed lines: Changed C/C++ lines covered: 1/3 (33.33%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 24, 2026
@PedroTadim PedroTadim self-assigned this Sep 24, 2026
@Michicosun

Copy link
Copy Markdown
Member

rank and denseRank are window functions; they should not be stored in the merge tree parts.

$CLICKHOUSE_LOCAL --path "$data_path" --query "
SET enable_funnel_functions = 1, allow_rank_dense_rank_arguments = 1;
CREATE TABLE t_sequence_next_node (c AggregateFunction(sequenceNextNode('forward', 'head'), DateTime, Nullable(String), UInt8)) ENGINE = Memory;
CREATE TABLE t_rank (c AggregateFunction(rank, UInt64)) ENGINE = Memory;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This SELECT 1::AggregateFunction(rank, UInt64) SETTINGS allow_rank_dense_rank_arguments = 1; gives error because it's a window function, so these statements should also fail.

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.

Agreed, and the inconsistency is on master rather than in this PR: with the setting on, that cast fails Code: 36 ... The function 'rank' can only be used as a window function, not as an aggregate function (WindowFunction::fail), while CREATE TABLE t (c AggregateFunction(rank, UInt64)) with the same setting succeeds.

So I dropped the rank and denseRank hunks in 8f49076. These two lines went with them, the test now covers sequenceNextNode only, and WindowTransform.cpp is byte identical to master again.

@clickhouse-gh clickhouse-gh Bot added the comp-aggregate-functions Aggregate function implementations (sum, avg, count, quantile, combinators, etc.). label Sep 24, 2026
Review on this PR objected that rank and denseRank are window functions and
so should not be storable as an aggregate state column type at all, which
makes tolerating a null Settings pointer in their creators the wrong
direction:
ClickHouse#121996 (comment)
ClickHouse#121996 (comment)

Both WindowTransform.cpp hunks are reverted, so that file is byte identical
to master, and the test covers sequenceNextNode only.

Measured after the revert, with allow_rank_dense_rank_arguments = 1: creating
a column of type AggregateFunction(rank, UInt64) or AggregateFunction(denseRank,
UInt64) still succeeds and reopening it still fails with
NUMBER_OF_ARGUMENTS_DOESNT_MATCH, exactly as on master. So the arm is dropped
in behaviour, not only in text.

The changelog category moves from Bug Fix to Improvement. The rank arm carried
the released-stable-regression claim, since that guard first shipped in 26.5
and allow_rank_dense_rank_arguments is tier 0, while the remaining
sequenceNextNode arm is reachable only behind enable_funnel_functions, which is
tier EXPERIMENTAL.

05252_aggregate_state_attach_without_query_context passes 50/50 under
randomized settings with the fix and fails on a pristine master binary; an
unrelated test passes in the same A-side setup as the control.
@groeneai groeneai changed the title Fix a table with a sequenceNextNode, rank or denseRank aggregate function column failing to load Let a table with a sequenceNextNode aggregate function column be loaded Sep 24, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Agreed. I dropped both rank and denseRank hunks in 8f49076: WindowTransform.cpp is byte identical to master again, and this PR now changes only sequenceNextNode, an ordinary aggregate function whose state is serializable. The changelog category moved to Improvement with them, since the released-stable-regression claim was carried by the rank arm (allow_rank_dense_rank_arguments is tier 0, while enable_funnel_functions is tier EXPERIMENTAL).

Measured after the revert: creating a column of type AggregateFunction(rank, UInt64) with allow_rank_dense_rank_arguments = 1 still succeeds and reopening it still fails NUMBER_OF_ARGUMENTS_DOESNT_MATCH, exactly as on master.

That leaves the type creatable and not loadable, which is the state before this PR. Rejecting it at creation instead is a separate change, and the predicate for it already exists: IAggregateFunction::isOnlyWindowFunction(), which AggregateFunctionFactory.cpp:128 already consults under the comment "Pure window functions are not real aggregate functions". The one shape it would newly reject is the zero-argument AggregateFunction(rank), which creates and loads today with no setting. Tell me if you want that as a follow-up.

@clickhouse-gh clickhouse-gh Bot added pr-improvement Pull request with some product improvements and removed pr-bugfix Pull request with bugfix, not backported by default labels Sep 24, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 24, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 8f49076f2 with master 1b5715814 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

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

Job report

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai window functions shouldn't be inside the AggregateFunction type, maybe that should be in another PR.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Acknowledged, I will send that as a separate PR. The predicate is already in tree: IAggregateFunction::isOnlyWindowFunction(), which AggregateFunctionFactory.cpp:128 consults today under "Pure window functions are not real aggregate functions".

One surface I want to get right there, because it is the shape of the bug this PR fixes: the argument-bearing spellings already fail, at creation without allow_rank_dense_rank_arguments and on load with it, so the only spelling that works end to end on master is the zero-argument one. AggregateFunction(rank) and AggregateFunction(denseRank) create and reopen fine today with no setting, on Memory and on MergeTree (measured on 26.10.1.1). A refusal inside the factory would therefore also stop an existing column of that type from attaching, so my plan is to refuse it at creation only, beside the other type gates in InterpreterCreateQuery (validateDataType, already skipped for ATTACH). Tell me if you would rather refuse it everywhere.

I will post the PR in this thread.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Opened #122148 for this: it refuses a pure window function state as a column type where the user declares it (CREATE, AS/OR REPLACE/TEMPORARY, a full-definition ATTACH, and ALTER ADD/MODIFY COLUMN), and leaves a definition this server already stored replaying unscreened, so tables created earlier still attach.

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai this is too permissive. I want to make sure enable_funnel_functions is always enabled before calling the aggregate

@PedroTadim PedroTadim closed this Sep 25, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Understood, and I will not reopen this: skipping the gate when the pointer is null was the wrong direction.

The creator's const Settings * is built only from the query context (AggregateFunctionFactory.cpp:277, query_context ? &query_context->getSettingsRef() : nullptr), and the load table job runs with none, so there it arrives null rather than false. That is why a table created with enable_funnel_functions = 1 cannot be reopened today even with the setting enabled at server level: no value of it reaches the creator on that path.

So enforcing it needs a source for the value outside a query. My default is to resolve the settings from the global context when there is no query context, the way AggregateFunctionGroupFormat.cpp:58 already resolves its own (resolveFormatContext()), so the gate is always evaluated and enable_funnel_functions = 1 in the default profile is what lets such a column load.

Tell me if you would rather the load keep refusing, and I will leave master as it is. Either way it goes in a new PR.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Opened #122204 with the design I described here: where there is no query context the gate now reads enable_funnel_functions from the global context and still refuses when it is off, so it is evaluated rather than skipped.

The boundary that follows from that, stated in the PR body: enable_funnel_functions = 1 in the server's configuration or default profile is what makes such a column loadable, and a session-level SET alone is not enough.

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 25, 2026
DataTypeAggregateFunction's factory creator resolved the named aggregate
function and built the type without asking whether that function is a real
aggregate function, so a WindowFunction subclass could become the type's
function. Such a state has no serialization: WindowFunction::add, mergeImpl,
serialize, deserialize and insertResultInto all call fail(). The column was
therefore accepted everywhere a type name is parsed, and could never hold a
value.

Screen it at the creator with isOnlyWindowFunction(), which already carries
exactly this meaning and is already consulted at AggregateFunctionFactory.cpp
under the comment "Pure window functions are not real aggregate functions".
That is one check at the single place a written AggregateFunction(...) becomes
a type, so CREATE, ALTER, a full-definition ATTACH, CAST and a table
function's structure argument are all covered by it, and nesting is covered
for free because Array/Map/Tuple creators and the state's own argument list
build their children through DataTypeFactory. The storage-level alternative
missed the full-definition ATTACH, missed a table function's structure, and
let Array(AggregateFunction(rank)) through.

Two supporting hunks make the predicate answer for combinators. The base
implementation now forwards one getNestedFunction() hop, which is what 12
singular combinators need, since they override getNestedFunction() and not
isOnlyWindowFunction(). AggregateFunctionTuple has no single nested function
to forward to, so it folds over nested_functions with any_of, matching the two
sibling predicates beside it.

BAD_ARGUMENTS rather than ILLEGAL_COLUMN, because this creator also runs for a
CAST and for a table function's structure, where there is no column; the same
code is what this creator already throws for a malformed function name, what
the sibling SimpleAggregateFunction creator throws to refuse an unsupported
function, and what WindowFunction::fail() throws for this same rule at
runtime.

This is a backward incompatible change, not a bug fix: no released version
returns a wrong answer, loses data or rejects a valid input here. It removes
an input that was accepted, and a table that already stores such a column
stops attaching, because the refusal also fires when stored metadata is
re-parsed. That cost was stated before the site was chosen.

Deliberately out of scope, all three because they do not go through create():
rankState() with zero result groups still mints the type via getStateType(),
so such a table will not reattach; the same type name in an empty result's
Native header is refused by the receiver; and a view stores its query rather
than column types. Gating the constructor would move rankState()'s failure
from execution to analysis.

Related: ClickHouse#121996
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-aggregate-functions Aggregate function implementations (sum, avg, count, quantile, combinators, etc.). groeneai-origin-review-human PR origin: human review feedback on a groeneai PR pr-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants