Skip to content

Fix server crash on lazy remote source with unbuilt materialized CTE - #108547

Merged
alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-remote-cte-null-logger-segfault
Jun 30, 2026
Merged

alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:fix-remote-cte-null-logger-segfault

Conversation

@groeneai

@groeneai groeneai commented Jun 25, 2026 •

Copy link
Copy Markdown
Collaborator

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 server crash (segmentation fault) that could occur when a distributed query referenced a not-yet-materialized MATERIALIZED CTE as an external table and the remote source was created lazily (delayed source). The crash was a null Logger dereference inside RemoteQueryExecutor::sendExternalTables().

Description

Found by the CI stress test Stress test (amd_tsan) (STID 4231-40cb). CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108457&sha=2216167c4c60044d1adc8e09d6a8cb9993f47504&name_0=PR&name_1=Stress%20test%20%28amd_tsan%29

Symptom. A distributed query over cluster()/remote() that references an unbuilt MATERIALIZED CTE crashed the server inside an async fiber:

Address: 0x38. Access: read. Address not mapped to object.
Poco::Logger::is(int) const                                       (Logger.h:393, reads atomic _level on a null this)
DB::RemoteQueryExecutor::sendExternalTables()                     (RemoteQueryExecutor.cpp, the "Skipping sending CTE ..." LOG_DEBUG)
DB::RemoteQueryExecutor::sendQueryUnlocked(...)
DB::RemoteQueryExecutorReadContext::Task::run(...)
DB::AsyncTaskExecutor::Routine::operator()(...)
Fiber::RoutineImpl<...>                                            (async fiber machinery)

The fault address 0x38 is a small fixed member offset, i.e. a null-pointer + member-offset read (not a stack-overflow guard page, not a heap use-after-free).

Root cause. RemoteQueryExecutor::log is a LoggerPtr that defaults to null and is only set optionally via setLogger(). Every RemoteQueryExecutor construction site in ReadFromRemote.cpp calls setLogger(log) right after the constructor except the lazy/delayed-source path in ReadFromRemote::addLazyPipe, which forgot it. That lazy path still passes the external tables (which can include a not-yet-built materialized CTE) to the executor, so sendExternalTables() enters the unbuilt-CTE skip branch and logs through the null logger, crashing. The crash is rare because it requires the delayed-source path and the CTE-materialization race that leaves the CTE unbuilt at send time (only seen under stress with failpoints injected).

Fix.

  1. ReadFromRemote::addLazyPipe now calls remote_query_executor->setLogger(log), matching the other three construction sites in the same file. This is the real omission.
  2. The log statement in RemoteQueryExecutor::sendExternalTables() is made null-safe with the file's existing idiom (log ? log : getLogger("RemoteQueryExecutor"), already used at three other sites in the same file), as defense-in-depth so any future construction path that forgets setLogger cannot crash here.

Test. Added 04365_materialized_cte_delayed_remote_null_logger, which forces the lazy remote source via the use_delayed_remote_source failpoint and runs a distributed query referencing a materialized CTE. The test deterministically exercises the skip-CTE branch (verified via server logs) and crashes the server without the fix; it passes with the fix.

Version info

  • Merged into: 26.7.1.298 (included in 26.7 and later)

A distributed query over cluster()/remote() that references a not-yet-built
MATERIALIZED CTE as an external table could crash the server with a null
Logger dereference inside RemoteQueryExecutor::sendExternalTables(), reached
through the async fiber that runs the remote read.

RemoteQueryExecutor::log is a LoggerPtr that defaults to null and is set
optionally via setLogger(). Every RemoteQueryExecutor construction site in
ReadFromRemote.cpp calls setLogger(log) right after the constructor except the
lazy/delayed-source path in ReadFromRemote::addLazyPipe, which forgot it. That
path still forwards the external tables (which may include an unbuilt
materialized CTE), so sendExternalTables() enters the unbuilt-CTE skip branch
and logs through the null logger, dereferencing it (Poco::Logger::is reading
the atomic _level on a null this -> SIGSEGV at address 0x38).

Fix:
- ReadFromRemote::addLazyPipe now calls setLogger(log), matching the three
  other construction sites in the same file (the real omission).
- The log statement in sendExternalTables() is made null-safe with the file's
  existing idiom (log ? log : getLogger("RemoteQueryExecutor")), already used
  at three other sites in the same file, as defense-in-depth.

Found by the CI stress test Stress test (amd_tsan) (STID 4231-40cb). Added a
regression test that forces the lazy remote source via the
use_delayed_remote_source failpoint and runs a distributed query referencing a
materialized CTE; it crashes without the fix and passes with it.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Debug build, server on a 2-shard self-cluster: SET enable_analyzer=1, enable_materialized_cte=1; SYSTEM ENABLE FAILPOINT use_delayed_remote_source; then a distributed cluster()/remote() query referencing a MATERIALIZED CTE via two correlated IN subqueries. Crashes the server on the unfixed binary every run; the skip-CTE branch fires every run (verified in server log).
b Root cause explained? Yes. RemoteQueryExecutor::log is a LoggerPtr defaulting to null, set optionally via setLogger(). ReadFromRemote::addLazyPipe (lazy/delayed-source path) builds the executor but, unlike the other 3 sites in the same file, never calls setLogger(). It still forwards external tables (which may hold an unbuilt materialized CTE), so sendExternalTables() enters the unbuilt-CTE branch and LOG_DEBUG(log, ...) dereferences the null logger (Poco::Logger::is reads atomic _level on null this -> SIGSEGV, fault addr 0x38 = small fixed member offset).
c Fix matches root cause? Yes. Primary fix adds the missing setLogger(log) on the lazy path (the actual omission). Defensive fix makes the log site null-safe using the file's existing log ? log : getLogger(...) idiom.
d Test intent preserved / new tests added? New regression test 04365_materialized_cte_delayed_remote_null_logger added. It forces the lazy path via use_delayed_remote_source and exercises the unbuilt-CTE branch; crashes the unfixed server, passes on the fixed server.
e Both directions demonstrated? Yes. Unfixed binary: regression test crashes the server with the exact CI stack (Poco::Logger::is -> sendExternalTables -> fiber, addr 0x38). Fixed binary: 10/10 test-runs pass (skip-CTE branch fires 120x across runs, now with a valid logger), server stays up.
f Fix is general across code paths? Yes. Audited all 13 RemoteQueryExecutor construction sites: only the lazy ReadFromRemote::addLazyPipe path passed non-empty external tables AND omitted setLogger. StorageDistributed (1213/1338) and ClickHouseDictionarySource pass empty external tables (can't reach the branch); all other ReadFromRemote/executeQuery/InterpreterInsertQuery/IStorageCluster/distributedIndexAnalysis sites already call setLogger. The defensive guard additionally covers the lone unguarded log deref in sendExternalTables.
g Fix generalizes across inputs? N/A (null-pointer guard + missing-initialization fix; no datatype/wrapper/parameter dimension). The defensive guard is unconditional regardless of CTE name, type, or query shape.
h Backward compatible? Yes. No setting, format, or behavior change; logging output is unchanged when log is already set. Pure crash fix.
i Invariants and contracts preserved? Yes. setLogger(log) only assigns the optional logger member (no lifetime/ownership change); the lazy callback already captures other ReadFromRemote members by value, and log is added the same way. The log ? log : getLogger(...) idiom is already used at three sites in the same file. The external-tables-forwarding semantics of the lazy path are untouched.

Session id: cron:clickhouse-worker-slot-1:20260625-200100

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @novikd @KochetovNicolai — could you review this? It fixes a null-logger SIGSEGV in RemoteQueryExecutor::sendExternalTables(): ReadFromRemote::addLazyPipe (the lazy/delayed-source path) builds the executor without calling setLogger() like the other three sites do, yet still forwards external tables, so the unbuilt-materialized-CTE skip branch logs through a null logger. @novikd, this is in the CTE-materialization-vs-parallel-replicas path you added (cbbfbef).

@nikitamikhaylov nikitamikhaylov added the can be tested Allows running workflows for external contributors label Jun 25, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b943c31]

Summary: ✅


AI Review

Summary

This PR fixes a null Logger dereference in lazy RemoteQueryExecutor construction for delayed remote sources with unbuilt MATERIALIZED CTE external tables. The current code sets a non-null default logger, preserves the caller-specific logger on the lazy ReadFromRemote path, and adds a focused stateless regression test. I found no current code correctness issue that warrants a new inline review comment.

PR Metadata
  • The selected Changelog category is Bug Fix, but the template has Critical Bug Fix (crash, data loss, RBAC) for server crashes. Use this replacement:
- Critical Bug Fix (crash, data loss, RBAC)
  • The changelog entry itself is specific and user-readable.
  • The longer PR description still describes the earlier per-site defensive-guard approach, while the current code now uses LoggerPtr log = getLogger("RemoteQueryExecutor") and removes those guards. Please refresh the Root cause / Fix text so future readers do not have to reconstruct the final approach from comments.
Final Verdict

Status: ⚠️ Request changes

Minimum required action: update the changelog category to Critical Bug Fix (crash, data loss, RBAC) and refresh the stale PR-description fix text.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 25, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 641aa36

Every failure below has an owner: a fixing PR (ours 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. PR diff is ReadFromRemote.cpp + RemoteQueryExecutor.cpp (null-logger fix) + a regression test, so none of these are PR-caused.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug, targeted) / "Block structure mismatch in stream" (STID 0993-2cc2) chronic AST fuzzer trunk bug (24 PRs / 0 master / 30d; family 79 PRs / 6 master) #94517 (external, open)
Upgrade check (amd_release) / "Error message in clickhouse-server.log" chronic background-mutation CANNOT_PARSE_TEXT noise (49 PRs / 0 master / 30d; not in RemoteQueryExecutor path) a fix task is created (investigating at full effort, fixing-PR link to follow here)
PR / Mergeable Check aggregator rollup reflects the above
CH Inc sync — CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260626-010000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Upgrade check (amd_release) server.log MutatePlainMergeTreeTask CANNOT_PARSE_TEXT noise created: #108563

@Ergus Ergus left a comment

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.

The fix works, but it is adding unneeded complexity.

Rather than chasing individual call sites with three different idioms (log ? log : getLogger(...), bare log, and if (log))
Isn't it better and simpler to default the member to a non-null logger so the null state cannot exist?

// RemoteQueryExecutor.h:326
LoggerPtr log = getLogger("RemoteQueryExecutor");

@Ergus Ergus left a comment

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.

Either make log non-null by default as recomended before or guard all other sites too.

-- stayed null. RemoteQueryExecutor::sendExternalTables() then logged "Skipping sending CTE ..."
-- on the unbuilt-CTE branch through that null logger, dereferencing it inside an async fiber
-- (Poco::Logger::is -> SIGSEGV). The fix sets the logger on the lazy path and the log site is
-- defensively guarded like its siblings in the same file.

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 defensive half of the PR doesn't match its own stated goal because lines 170/175 remain an unguarded null-log deref reachable via ClickHouseDictionarySource.

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.

Right, the per-site guard left those unguarded. The non-null default member (b8448f7) covers the ClickHouseDictionarySource path and the connection-failure log sites too, so this is no longer a partial fix.

Per review: instead of guarding individual log sites with three different
idioms (log ? log : getLogger(...), bare log, and if (log)), default the
member to a non-null logger so the null state cannot exist. This also covers
the connection-failure log sites and the ClickHouseDictionarySource
construction path, which the per-site guard missed. setLogger() still lets
callers override with a StorageDistributed-prefixed logger for attribution;
no caller passes null, so the non-null invariant holds.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Done, went with the non-null default you suggested (b8448f7):

  • RemoteQueryExecutor.h: LoggerPtr log = getLogger("RemoteQueryExecutor"); so the null state cannot exist.
  • Dropped the three idioms in RemoteQueryExecutor.cpp (log ? log : getLogger(...) x3 and the if (log) guard) back to bare log.

This also covers the two sites you flagged: the connection-failure LOG_DEBUG(log, ...) calls and the ClickHouseDictionarySource construction path (which builds a RemoteQueryExecutor without setLogger), both of which the per-site guard missed.

Audited all 13 construction sites and every setLogger caller: none pass null, so the non-null invariant holds. Kept setLogger(my_log) on the ReadFromRemote::addLazyPipe lazy path so its log lines keep the StorageDistributed (cluster) prefix like its three siblings.

Re-ran 04365 on the rebuilt binary: 20/20 pass (10 deterministic + 10 randomized), server stays up. The unfixed binary still crashes with the same Address: 0x38 / Poco::Logger::is -> sendExternalTables fiber stack.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Ledger update for the Upgrade check (amd_release) server.log MutatePlainMergeTreeTask CANNOT_PARSE_TEXT (Cannot parse string 'x' as UInt64) line on this PR:

The fixing PR is now #108651 (alexey-milovidov-approved), which suppresses the whole benign issue-#39174 background-mutation class by error CLASS. The earlier-linked #108563 has been closed as superseded by #108651. The exact Cannot parse string 'x' as UInt64 literal is additionally already on master via #107985. This line is owned/fixed; no further action needed on this PR.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — b8448f7

Every failure below has an owner: a fixing PR (ours or external). CI was fully finished on this head (Finish Workflow success, 0 checks pending, >20 min ingest buffer).

Check / test Reason Owner / fixing PR
Stateless tests (all 11 shards) / 02354_vector_search_rescoring master regression (Code 44 ILLEGAL_COLUMN _distance; introduced by #105591, deterministic across all shards, 0 relation to this PR's null-logger diff) #108812 (merged 14:13 UTC, revert of #105591) — merged master @ b943c31 to pick it up
Stress test (arm_release) / Received signal 6 (STID 3721-41da) crash: abort in SingleValueDataString::setIfSmaller ← Aggregator::executeWithoutKeyImpl (min/max-over-String aggregate; chronic trunk bug, 3 unrelated PRs / 0 master / 30d; unrelated to this PR's RemoteQueryExecutor diff) #104350 (ours, open) — the group_by_use_nulls SingleValueDataString family (issue #91119)
CH Inc sync private fork-sync mirror CH Inc sync (private, not actionable by us)

Merged current master into the branch (HEAD now b943c31) to pick up the #108812 revert, which clears the 02354 line; CI re-runs on the fresh head.

Session id: cron:our-pr-ci-monitor:20260629-163000

@clickhouse-gh

clickhouse-gh Bot commented Jun 29, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.40% 85.40% +0.00%
Functions 92.60% 92.70% +0.10%
Branches 77.60% 77.60% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 23/25 (92.00%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — b943c31

CI fully finished on this SHA (Finish Workflow + Mergeable Check SUCCESS; 0 checks queued/in_progress; >20-min ingestion buffer). This is the master-merge re-trigger SHA: the earlier 02354_vector_search_rescoring all-shards failures (the #105591 master regression) are gone now that revert #108812 is on-branch, and the chronic SingleValueDataString stress crash did not recur. No CI failures remain on this commit.

Check / test Reason Owner / fixing PR
(no failures on this SHA) - -
CH Inc sync - CH Inc sync (private, not actionable by us)

PR-caused gate: zero. The null-logger fix (RemoteQueryExecutor::log non-null default per @Ergus + the lazy-path setLogger + 04365 regression test) is green everywhere.

Session id: cron:our-pr-ci-monitor:20260629-203000

@alexey-milovidov alexey-milovidov left a comment

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.

Now Ok.

@alexey-milovidov alexey-milovidov self-assigned this Jun 30, 2026
@alexey-milovidov
alexey-milovidov merged commit 82f6e60 into ClickHouse:master Jun 30, 2026
173 of 174 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 30, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…l-logger-segfault

Fix server crash on lazy remote source with unbuilt materialized CTE
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.

5 participants