Skip to content

Fix null AST in remote() named-collection database override - #108271

Merged
Algunenano merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-tablefunctionfactory-null-deref-ubsan
Jun 23, 2026
Merged

Algunenano merged 1 commit into
ClickHouse:masterfrom
groeneai:fix-tablefunctionfactory-null-deref-ubsan

Conversation

@groeneai

@groeneai groeneai commented Jun 23, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #107189

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed a possible crash (null pointer dereference) when the database/db override of a named collection passed to remote()/remoteSecure() is not a constant database name, e.g. remote(nc, database = (SELECT 1)). The query now fails with a clear error instead of crashing.

Description

remote()/remoteSecure() with a named collection accepts a database/db override, e.g. remote(nc, database = ...). TableFunctionRemote::parseArguments stored that override expression directly as the remote table function without checking it is an ASTFunction, unlike the positional signature remote('addr', table_function()) which validates the node and otherwise treats it as a database name.

So remote(nc, database = (SELECT 1)) stored a non-function node as the table function. When the shard is local it reached TableFunctionFactory::get(), where ast_function->as<ASTFunction>() returns nullptr and table_function->name dereferenced it: UBSan reported a member access within a null pointer, and a release build would read from a null base pointer. This is reachable from plain SQL, no fuzzer needed.

UBSan report (Stress test (arm_ubsan)):

src/TableFunctions/TableFunctionFactory.cpp:45:39: runtime error: member access within null pointer of type 'const DB::ASTFunction'

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=107189&sha=ee127aeb85205b0eec364f557f260bf3e1e6ab38&name_0=PR&name_1=Stress%20test%20%28arm_ubsan%29

Fix: the database/db override is now handled like the positional argument. A table function is stored as the remote table function; anything else is evaluated as a constant database name, so a non-constant or wrong-typed expression fails at argument-parsing time (before any connection) with a clean error and the server stays up. TableFunctionFactory::get() can no longer receive a non-ASTFunction node from this path or from the analyzer's TableFunctionNode::toAST(), so the guard there is now an internal invariant and throws LOGICAL_ERROR.

A stateless test (04408_remote_named_collection_database_override) reproduces the bug from SQL and replaces the previous unit test.

Version info

  • Merged into: 26.6.1.1168

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. unit_tests_dbms --gtest_filter="TableFunctionFactory.RejectsNonFunctionAST" aborts on every run without the fix (exit 134 / SIGABRT in the debug build; the reported "member access within null pointer of type const DB::ASTFunction" under UBSan). A SQL reproducer is not possible: the parser never emits a non-ASTFunction in the table-function position, only the server-side query fuzzer does, so the malformed AST is built directly in the unit test.
b Root cause explained? Yes. The query fuzzer places a non-function node (e.g. a literal) in a table-function position. TableFunctionFactory::get() does ast_function->as<ASTFunction>() (pointer cast), which returns nullptr, then dereferences table_function->name unconditionally -> undefined behaviour (null member access).
c Fix matches root cause? Yes. A null check is added immediately after the cast, throwing UNEXPECTED_AST_STRUCTURE (the code sibling table functions TableFunctionFilesystem/TableFunctionExplain use for a wrong AST node), so the null is never dereferenced. It is a normal user error, so it does not trip the stress-test crash/LOGICAL_ERROR detection.
d Test intent preserved / new tests added? New unit test added (src/TableFunctions/tests/gtest_table_function_factory.cpp) covering a literal and an identifier passed into get(), asserting code() == UNEXPECTED_AST_STRUCTURE. No existing test weakened.
e Both directions demonstrated? Yes. Without the fix the test aborts (SIGABRT/UBSan); with the fix it passes ([ OK ]), same binary tree, verified by reverting only the source guard and rebuilding.
f Fix is general, not a narrow patch? Yes. get() is the single entry point taking an untyped ASTPtr (legacy/non-analyzer path: InterpreterDescribeQuery, Context::executeTableFunction, DatabaseS3/HDFS/Filesystem). parseArguments() overrides that deref function->arguments are reached only through get() (after this check) or through the analyzer at QueryAnalyzer.cpp:4603, where the AST comes from TableFunctionNode::toAST() and is always an ASTFunction. Guarding the chokepoint covers every reachable path; no sibling fix needed. The fix is at the layer where the implicit contract is actually violated, not a symptom guard.

Session id: cron:clickhouse-worker-slot-2:20260623-090200

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @Algunenano @rschu1ze — could you review this? It adds a missing null check in TableFunctionFactory::get(): the pointer cast as<ASTFunction>() returns nullptr for a fuzzer-supplied non-function node and the old code dereferenced table_function->name (UBSan null member access in Stress test (arm_ubsan)). The fix throws UNEXPECTED_AST_STRUCTURE at the cast site, matching sibling table functions.

@Algunenano Algunenano self-assigned this Jun 23, 2026
@Algunenano Algunenano added the can be tested Allows running workflows for external contributors label Jun 23, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 23, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b09d93f]

Summary: ❌

job_name test_name status info comment
Stress test (amd_msan) FAIL
Hung check failed, possible deadlock found FAIL cidb, issue ISSUE EXISTS

AI Review

Summary

This PR fixes the user-reachable path where a named-collection database/db override for remote/remoteSecure could store a non-ASTFunction as the remote table function and later hit a null dereference in TableFunctionFactory::get. The current code validates that override at the source, keeps real table functions supported, turns the factory check into an internal LOGICAL_ERROR, and adds a focused SQL regression test. I did not find any remaining review findings.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 23, 2026
remote()/remoteSecure() with a named collection accepts a database/db override,
e.g. remote(nc, database = ...). TableFunctionRemote::parseArguments stored that
override expression directly as the remote table function without checking it is an
ASTFunction, unlike the positional signature remote('addr', table_function()) which
validates the node and otherwise treats it as a database name.

So remote(nc, database = (SELECT 1)) stored a non-function node as the table function.
When the shard is local it reached TableFunctionFactory::get(), where
ast_function->as<ASTFunction>() returns nullptr and table_function->name dereferenced
it: UBSan reported a member access within a null pointer, and a release build read from
a null base pointer. This is reachable from plain SQL, no fuzzer needed.

The override is now handled like the positional argument: a table function is stored as
the remote table function, anything else is evaluated as a constant database name. A
non-constant or wrong-typed expression now fails at argument-parsing time (before any
connection) with a clean error and the server stays up.

TableFunctionFactory::get() can no longer receive a non-ASTFunction node from this path
or from the analyzer's TableFunctionNode::toAST(), so the guard there is now an internal
invariant and throws LOGICAL_ERROR instead of UNEXPECTED_AST_STRUCTURE.

The gtest is replaced by a stateless test that reproduces the bug from SQL.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai
groeneai force-pushed the fix-tablefunctionfactory-null-deref-ubsan branch from 2337b57 to b09d93f Compare June 23, 2026 12:38
@groeneai groeneai changed the title Fix UBSan null pointer dereference in TableFunctionFactory::get Fix null AST in remote() named-collection database override Jun 23, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. SELECT * FROM remote(nc, database = (SELECT 1)) against a local shard. On the pre-fix code it reaches TableFunctionFactory::get() with a non-ASTFunction node (UBSan null member access / null deref in release).
b Root cause explained? The named-collection database/db override in TableFunctionRemote::parseArguments was stored directly as remote_table_function_ptr with no type check, unlike the positional path which validates as<ASTFunction>() && isTableFunctionName(). A subquery/non-function expression therefore flowed to get(), where ast_function->as<ASTFunction>() is nullptr and table_function->name dereferences it.
c Fix matches root cause? Yes. The override is validated at its origin in TableFunctionRemote: a table function is stored as the remote table function, anything else is evaluated as a constant database name. The bad node never reaches get(). The factory guard is then a pure internal invariant (LOGICAL_ERROR).
d Test intent preserved / new tests added? Replaced the gtest with stateless 04408_remote_named_collection_database_override, which reproduces the bug from SQL (asserts BAD_GET for database/db = (SELECT 1) / = 1, and that the server stays responsive).
e Both directions demonstrated? Yes. Local debug build: without the TableFunctionRemote change the query throws the factory LOGICAL_ERROR (test's BAD_GET assertion fails); with it the query fails at parse time with BAD_GET and the test passes 5/5.
f Fix is general, not a narrow patch? Yes. The fix is at the source (where the bad AST originates), not a guard at the crash site. Both override keys (database, db) are covered, and behavior now matches the positional path: identifiers (db = system), string-returning functions (database = concat('sys','tem')) and table functions (database = numbers(1)) all resolve correctly; only non-constant/wrong-typed expressions are rejected.

Session id: cron:clickhouse-worker-slot-1:20260623-113800

@clickhouse-gh

clickhouse-gh Bot commented Jun 23, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.30% 85.30% +0.00%
Functions 92.50% 92.50% +0.00%
Branches 77.50% 77.60% +0.10%

Changed lines: Changed C/C++ lines covered by tests: 13/14 (92.86%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@Algunenano
Algunenano enabled auto-merge June 23, 2026 17:11
@Algunenano
Algunenano added this pull request to the merge queue Jun 23, 2026
Merged via the queue into ClickHouse:master with commit 253757e Jun 23, 2026
165 of 167 checks passed
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI on b09d93f9920a finished. Functional, integration, build and unit checks pass. One red check is not caused by this PR:

@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 23, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…actory-null-deref-ubsan

Fix null AST in remote() named-collection database override
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 pr-bugfix Pull request with bugfix, not backported by default 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.

3 participants