Repository navigation
Fix a server crash when the flameGraph aggregate function is constructed without a query context - #121894
Conversation
AggregateFunctionFactory takes the settings it hands to a creator from the current thread's query context (AggregateFunctionFactory.cpp:269-277) and passes a null pointer when the thread has no query context. createAggregateFunctionFlameGraph read that pointer unconditionally on its first line, so constructing the function from a context-less thread dereferenced address 0 and crashed the server with SIGSEGV. The AST fuzzer reached it on master through the distributed-query client read path: CancellationChecker, a BackgroundSchedulePool task with no query context, timed out a distributed query, and RemoteQueryExecutorReadContext::cancelBefore() drained the pending packet on the cancelling thread. Fibers switch stacks but not threads and CurrentThread is thread-local, so the PacketReceiver fiber saw the pool's context-less ThreadStatus while NativeReader::read() parsed the block header's AggregateFunction(flameGraph, ...) column type. The pointer is nullable by construction, so the creator now honours that. The check is permissive rather than fail-closed because a null pointer means the construction belongs to no user query: allow_introspection_functions is a per-query user setting, and with no principal there is nothing to authorize. Refusing instead would fail NativeReader::read() inside a drain loop whose whole purpose is to leave the connection synchronised (and whose exception AsyncTaskExecutor::Routine swallows), and would leave a stored table of that type unattachable, since the attach is where the type name is parsed. Where a query context exists nothing changes: with allow_introspection_functions = 0, naming the function in a SELECT, CREATE TABLE, CAST or format schema still returns FUNCTION_NOT_ALLOWED, and 04114_aggregate_function_flamegraph.sql asserts that identically with and without this change. A construction on a context-less thread (the drain above, or attaching a stored table) now succeeds instead of crashing, which grants no new capability: such a column can only be created by a statement that passed the check, and reading an existing one already behaved this way on master. A census of every creator that dereferences the pointer found this to be the only unguarded one, so the fix is single-site: sequenceNextNode, uniqExact, the four TimeSeries sites, rank and denseRank all null-check it already. Two regression tests, complementary. 05243_flamegraph_attach_without_query_context covers the user-facing route: one clickhouse-local process creates the table and a second one attaches it, which parses the column type on a thread that has no query context. The gtest pins the factory-level invariant, which no single statement isolates deterministically: the drain above needs a cancellation to land while such a block header is in flight; it runs on a plain std::thread, which never gets a ThreadStatus, and asserts that precondition so the oracle cannot go vacuous.
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex). Five gate rounds on this branch,
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-9:20260924-031200 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-4:20260924-014900 |
|
Workflow [PR], commit [83e8470] Summary: ✅
AI ReviewSummaryThis PR fixes the Missing context / blind spots
Final Verdict✅ No review findings in the current diff. No inline comments were posted. LLVM Coverage ReportMeasured on commit 83e8470.
Changed lines: Changed C/C++ lines covered: 3/3 (100.00%) · Uncovered code |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units7 translation units recompiled, 7 s compile time in total, 7 of them have a recent master baseline. |
CI finish ledger - 373f91aEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
All 176 check-runs completed (134 pass, 39 not selected, 3 red), Session id: cron:our-pr-ci-monitor:20260924-090214 |
| if (!(*settings)[Setting::allow_introspection_functions]) | ||
| /// The factory passes null when there is no query context to take settings from, and with no | ||
| /// principal there is nothing to authorize. | ||
| if (settings && !(*settings)[Setting::allow_introspection_functions]) |
There was a problem hiding this comment.
@groeneai there could be other aggregates with the same issue? Can you investigate?
There was a problem hiding this comment.
Investigated. I censused every function in src/ whose signature takes a const Settings *, which is the entire creator and window-creator surface, and classified what each does with the pointer:
| Group | Sites | On a null pointer |
|---|---|---|
| parameter left unnamed | 126 | cannot read it |
| named, never dereferenced | 33 | only forwards it |
dereferenced, checked, permissive (if (settings && ...)) |
6 | constructs the function: the timeSeries* family, uniqExact's parallel-merge choice, and flameGraph with this PR |
dereferenced, checked, refusing (settings == nullptr || ...) |
3 | throws: sequenceNextNode (AggregateFunctionSequenceNextNode.cpp:463), rank and denseRank (WindowTransform.cpp:3101, :3178) |
| dereferenced unchecked | 1 | crashes: flameGraph, fixed here |
| dereferenced outside the creator surface | 4 | connection handshake, tracing, codec choice |
Negative control: the same census run against the pre-fix file reports createAggregateFunctionFlameGraph as an unchecked dereference, so it is able to fail.
So no other aggregate function has this crash. The three refusing creators do have a problem of their own, which I measured on this build: a table created legally cannot be loaded back, and neither a query-level SET nor a server-level default helps, because the loading thread has no settings at all.
$ clickhouse local --path d -q "SET enable_funnel_functions = 1; CREATE TABLE t (c AggregateFunction(sequenceNextNode('forward', 'head'), DateTime, Nullable(String), UInt8)) ENGINE = Memory"
$ clickhouse local --path d -q "SELECT count() FROM t"
Code: 63. DB::Exception: Aggregate function sequenceNextNode is experimental. Set `enable_funnel_functions` setting to enable it: Cannot attach table `default`.`t` from metadata file [...] (UNKNOWN_AGGREGATE_FUNCTION)
AggregateFunction(rank, UInt64) behaves the same way with allow_rank_dense_rank_arguments = 1, failing to load with NUMBER_OF_ARGUMENTS_DOESNT_MATCH. Both are pre-existing and are a policy change rather than a crash fix, so I kept this PR to the crash and will send them separately. Tell me if you would rather have them here.
There was a problem hiding this comment.
Opened #121996 for the three refusing sites from that census (sequenceNextNode, rank, denseRank), using the same permissive shape as this PR.
| @@ -0,0 +1,57 @@ | |||
| #include <gtest/gtest.h> | |||
There was a problem hiding this comment.
@groeneai remove the gtest, we already have the shell one
There was a problem hiding this comment.
Removed in 8e6250d. 05243_flamegraph_attach_without_query_context is now the only regression test, and it still reproduces the crash without the src/ change.
The stateless test 05243_flamegraph_attach_without_query_context already reproduces the crash end to end, so the gtest only restated it at a lower level. Requested in review. A census of every function in src/ taking a `const Settings *` (172 sites: 126 leave the parameter unnamed, 33 name it without reading it, 13 dereference it and all 13 null-check first) confirms the flameGraph creator was the only unguarded dereference, so the fix stays single-site.
CI finish ledger - 8e6250dEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
All 172 check-runs completed (128 pass, 39 not selected, 5 red), last completion 17:02:40Z, and CIDB Session id: cron:our-pr-ci-monitor:20260924-173442 |
CI finish ledger - aa6a7b0Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260924-210057 |
Backport #121894 to 26.9: Fix a server crash when the flameGraph aggregate function is constructed without a query context
Backport #121894 to 26.8: Fix a server crash when the flameGraph aggregate function is constructed without a query context
Backport #121894 to 26.7: Fix a server crash when the flameGraph aggregate function is constructed without a query context
Backport #121894 to 26.3: Fix a server crash when the flameGraph aggregate function is constructed without a query context
…Graph aggregate function is constructed without a query context
…Graph aggregate function is constructed without a query context
…Graph aggregate function is constructed without a query context
…Graph aggregate function is constructed without a query context
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a server crash when the
flameGraphaggregate function was constructed on a thread without a query context, for example while attaching a stored table whose column type namesAggregateFunction(flameGraph, ...).Description
On v26.8 and v26.9, attaching a stored table whose column type names
AggregateFunction(flameGraph, ...)crashes the process with SIGSEGV before any query runs.Found by the AST fuzzer on master: AST fuzzer (amd_release, oracle) at
5a72ff95, a bystander commit. No related issue.Root cause.
AggregateFunctionFactory::getImpltakes a creator's settings from the current thread's query context and passesnullptrwhen the thread has none (AggregateFunctionFactory.cpp:269-277).createAggregateFunctionFlameGraphread that pointer unconditionally, so the privilege check itself was the faulting instruction.How it was reached.
CancellationChecker(aBackgroundSchedulePooltask, no query context) timed out a distributed query, andRemoteQueryExecutorReadContext::cancelBefore()drained the packet on the cancelling thread. Fibers switch stacks, not threads, andCurrentThreadis thread-local, so thePacketReceiverfiber ran context-less whileNativeReader::read()parsed a block header naming such a column.Change. The creator honours the nullability. Permissive rather than fail-closed: with no query context there is no principal to authorize, and fail-closed would instead fail
NativeReader::read()inside a drain loop meant to resynchronise the connection.Other aggregate functions. Censused mechanically, table below: this was the only creator that read the pointer without checking it.
Validation.
05243_flamegraph_attach_without_query_contextreproduces the crash with twoclickhouse-localinvocations and was verified to fail without thesrc/change. Where a context exists nothing changes: withallow_introspection_functions = 0,SELECT,CREATE TABLE,CAST,format()and the combinator forms all still returnFUNCTION_NOT_ALLOWED, and all fourflameGraphtests pass 40/40 under randomized settings.Census: what every
const Settings *reader insrc/does when the pointer is nullEvery function in
src/whose signature takes aconst Settings *, which is the whole creator and window-creator surface, grouped by what it does with the pointer.if (settings && ...))timeSeries*family,uniqExact's parallel-merge choice, and nowflameGraphsettings == nullptr || ...)sequenceNextNode,rank,denseRankflameGraph, fixed hereNegative control: the same census run against the pre-fix file reports
createAggregateFunctionFlameGraphas an unchecked dereference, so it can fail.The three refusing creators make a table whose column type names them fail to load, measured on this build; that is pre-existing, orthogonal to the crash, and not touched here.
Workflow [PR]
Sync PR [sync-upstream/pr/121894]
Version info
26.10.1.674-master(included in26.10and later)26.9.2.40,26.8.11.54,26.7.14.52,26.3.33.158