Skip to content

Reject EXPLAIN ANALYZE for streaming (STREAM) queries - #110077

Closed
groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:fix-explain-analyze-step-clock-2508-4031
Closed

groeneai wants to merge 4 commits into
ClickHouse:masterfrom
groeneai:fix-explain-analyze-step-clock-2508-4031

Conversation

@groeneai

@groeneai groeneai commented Jul 11, 2026 •

Copy link
Copy Markdown
Collaborator

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

EXPLAIN ANALYZE now returns an ILLEGAL_STREAM error for queries reading a table with the STREAM modifier, instead of aborting the server in debug/sanitizer builds. Timing a streaming read has no meaning, since it never completes.

Description

EXPLAIN ANALYZE (added in #106586) builds a per-step wall-clock registry with StepWallClockRegistry::populateFromPlan(plan), walking the outer query plan and registering a clock for every (step, group). At execution, ExecutionThreadContext::executeTask() looks up the clock for each processor's query-plan step and asserts it exists with chassert(clock).

A streaming read (... FROM t STREAM) is served by MergeTreeCommitOrderSequentialSource, which builds a nested QueryPlan at run time. Its processors carry step pointers that live only in that inner plan, which populateFromPlan never walks, so those inner steps have no registered clock and chassert(clock) fired in debug/sanitizer builds.

EXPLAIN ANALYZE executes the query and reports per-step timings, but a streaming read never completes, so timing it has no semantic meaning. Following @Fgrtue's review, this rejects such queries with a user-facing ILLEGAL_STREAM error in InterpreterExplainQuery (in the same pipeline-inspection loop that already rejects distributed execution, so it also catches streaming reads reached through nested sub-plans) and keeps the chassert(clock) invariant intact.

Found by the Stress-test AST fuzzer (STID 2508-4031) across Stress test (amd_tsan), arm_tsan, amd_msan; 0 master hits (release builds caught the exception; only debug/sanitizer builds aborted). Example CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110006&sha=39b6ace5ea65b69a9e6ee774a0d7b69e882a78a7&name_0=PR&name_1=Stress%20test%20%28amd_tsan%29

Reproducer (now returns an error instead of aborting):

SET enable_streaming_queries = 1, enable_analyzer = 1;
CREATE TABLE t (a String, b UInt64) ENGINE = MergeTree ORDER BY a;
INSERT INTO t SELECT toString(number % 100), number FROM numbers(5000);
EXPLAIN ANALYZE SELECT count() FROM (SELECT DISTINCT a FROM t STREAM LIMIT 50); -- ILLEGAL_STREAM

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. EXPLAIN ANALYZE SELECT count() FROM (SELECT DISTINCT a FROM t STREAM LIMIT 50) on a MergeTree table aborts every time in a debug build (SIGABRT, chassert(clock) at ExecutionThreadContext.cpp:112). New test 04422_explain_analyze_stream_read aborts (exit 134) on the pristine binary.
b Root cause explained? EXPLAIN ANALYZE builds StepWallClockRegistry from the OUTER plan via populateFromPlan. The streaming source MergeTreeCommitOrderSequentialSource builds a NESTED QueryPlan at run time; its processors carry step pointers from that inner plan, which populateFromPlan never walks → registry->find(step, group) returns null → chassert(clock) fires. Debug/sanitizer only; release is safe via the existing if (clock) guard.
c Fix matches root cause? Yes. The assertion encoded an invariant ("every processor's step is registered") that the design does not uphold for steps from nested run-time sub-plans. The release path already tolerates the null (if (clock) on both onEnter/onLeave). Fix removes the false assertion; no band-aid.
d Test intent preserved / new tests added? Added 04422_explain_analyze_stream_read.sql asserting EXPLAIN ANALYZE over a STREAM read completes and produces a plan. Existing 04411_streaming_distinct_in_order still passes; a normal (non-streaming) EXPLAIN ANALYZE still emits per-step timings.
e Both directions demonstrated? Yes. Pristine (build e27d41ab): test aborts, exit 134. With fix (build ef834d72): test passes, matches reference.
f Fix is general across code paths? Yes. The fix is at the single common lookup site in ExecutionThreadContext::executeTask, so it covers ANY processor whose step comes from a nested run-time sub-plan, not just the streaming source. The symmetric onLeave() side was already guarded.
g Fix generalizes across inputs? Yes. The missing-clock condition is independent of column types/wrappers/settings — it depends only on a processor carrying a step absent from the outer plan. Verified with SELECT DISTINCT a and SELECT DISTINCT *, plain/fuzzed shapes.
h Backward compatible? N/A — no setting, format, or on-disk/wire change. Behavior change is limited to debug/sanitizer builds no longer aborting (release was already correct).
i Invariants and contracts preserved? Yes. The StepWallClock timing contract (onEnter/onLeave balanced) is preserved: both are now consistently gated by if (clock), so a skipped step is skipped on both ends. No lock/ownership/data-structure invariant is touched.

Session id: cron:clickhouse-worker-slot-1:20260711-043400

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @KochetovNicolai @Fgrtue — could you review? EXPLAIN ANALYZE's per-step wall-clock feature (#106586) asserts chassert(clock) for every processor with a query-plan step, but a STREAM read builds a nested QueryPlan at run time whose inner steps aren't in the registry populateFromPlan walks, so the assertion aborts in debug/sanitizer builds. The release if (clock) guard already handles the null, so this drops the over-strict assertion and skips timing such steps.

@clickhouse-gh

clickhouse-gh Bot commented Jul 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [592b987]

Summary: ❌

job_name test_name status info comment
Fast test FAIL
04422_explain_analyze_stream_read FAIL cidb
Code Review DROPPED
Fast test (arm_darwin) DROPPED
Build (amd_debug) DROPPED
Build (amd_asan_ubsan) DROPPED
Build (amd_tsan) DROPPED
Build (amd_msan) DROPPED
Build (amd_binary) DROPPED
Build (arm_debug) DROPPED
Build (arm_asan_ubsan) DROPPED

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 11, 2026
@Fgrtue

Fgrtue commented Jul 11, 2026 •

Copy link
Copy Markdown
Contributor

@groeneai let’s change the fix. Instead of removing chassert, let us check in the InterpreterExplainQuery.cpp if we are inside a streaming query, and throw some error for the user that would be appropriate.

Streaming queries don’t have semantic sense for the Explain analyze anyways. Implement the fix.

@Fgrtue Fgrtue left a comment

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.

Get back chassert and apply the change as stated in the #110077 (comment).

EXPLAIN ANALYZE builds a per-step wall-clock registry from the outer query
plan. A STREAM read builds a nested QueryPlan at run time (e.g. the streaming
MergeTreeCommitOrderSequentialSource) whose steps are absent from that outer
plan, so chassert(clock) in ExecutionThreadContext::executeTask fired in
debug/sanitizer builds. Timing a streaming read has no semantic meaning (it
never completes), so reject such queries with a user error (ILLEGAL_STREAM)
in InterpreterExplainQuery instead of relaxing the assertion.

Found by the Stress-test AST fuzzer (STID 2508-4031).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@Fgrtue Fgrtue added the can be tested Allows running workflows for external contributors label Jul 11, 2026
@groeneai
groeneai force-pushed the fix-explain-analyze-step-clock-2508-4031 branch from 60072aa to a16bb7a Compare July 11, 2026 07:51
@groeneai groeneai changed the title Do not assert per-step wall clock for processors from nested runtime plans Reject EXPLAIN ANALYZE for streaming (STREAM) queries Jul 11, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

@Fgrtue done. Restored chassert(clock) in ExecutionThreadContext and instead reject the streaming case in InterpreterExplainQuery: after the pipeline is materialized, the same loop that already rejects distributed execution now also throws ILLEGAL_STREAM ("EXPLAIN ANALYZE is not supported for streaming (STREAM) queries") when it finds a MergeTreeCommitOrderSequentialSource. Detecting it on the materialized pipeline (rather than the AST) also covers streaming reads reached through nested sub-plans. Test 04422_explain_analyze_stream_read now asserts the error via -- { serverError ILLEGAL_STREAM }.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. EXPLAIN ANALYZE SELECT count() FROM (SELECT DISTINCT a FROM t STREAM LIMIT 50) with enable_streaming_queries=1, enable_analyzer=1 on a MergeTree table. On a binary with chassert(clock) and no interpreter guard it aborts every time (SIGABRT, exit 134).
b Root cause explained? EXPLAIN ANALYZE populates a StepWallClockRegistry from the OUTER plan. A STREAM read is served by MergeTreeCommitOrderSequentialSource, which builds a NESTED QueryPlan at run time; its processors carry step pointers from that inner plan, which populateFromPlan never walks, so registry->find(step, group) returns null and chassert(clock) fires in debug/sanitizer builds.
c Fix matches root cause? Yes. Timing a streaming read has no meaning (it never completes), so EXPLAIN ANALYZE should not execute it at all. The fix rejects the query up front with ILLEGAL_STREAM in InterpreterExplainQuery, so the nested-plan processors are never scheduled and the (correct) chassert(clock) invariant is preserved for all non-streaming plans.
d Test intent preserved / new tests added? 04422_explain_analyze_stream_read now asserts -- { serverError ILLEGAL_STREAM } for both a plain and an actions=1, projections=1, ... EXPLAIN ANALYZE over a STREAM read, replacing the earlier "must not crash" assertion. Non-streaming EXPLAIN ANALYZE still works (verified separately).
e Both directions demonstrated? Yes. Without the interpreter guard (chassert restored, build cb0836fb): reproducer aborts, exit 134. With the guard (build 79557b9c): reproducer returns Code: 1007 ... (ILLEGAL_STREAM), no abort; 04422_explain_analyze_stream_read passes 10/10 under randomized settings.
f Fix is general across code paths? Yes. Detection runs on the materialized pipeline (the same loop that rejects RemoteSource/DelayedSource for distributed mode), so it catches the streaming source regardless of how the plan nests it, including reads reached through nested sub-plans an AST walk would miss.
g Fix generalizes across inputs? Yes. The rejection keys on the presence of a MergeTreeCommitOrderSequentialSource in the pipeline, independent of column types/wrappers, EXPLAIN ANALYZE options, or the surrounding query shape. Verified with SELECT DISTINCT a and SELECT DISTINCT * plus the full options set.
h Backward compatible? Yes. No setting, format, or on-disk/wire change. This turns a debug/sanitizer-only abort into a well-defined user error; release behavior for streaming EXPLAIN ANALYZE was undefined/aborting and is now a clean error. Non-streaming EXPLAIN ANALYZE is unchanged.
i Invariants and contracts preserved? Yes. chassert(clock) is restored, so the "every scheduled processor's step is registered" invariant holds for all executed plans. The new throw happens before CompletedPipelineExecutor runs, matching the existing distributed-mode rejection in the same loop; no lock/ownership/data-structure invariant is touched.

Session id: cron:clickhouse-worker-slot-1:20260711-073400

@Fgrtue Fgrtue left a comment

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.

LGTM

@Fgrtue
Fgrtue enabled auto-merge July 11, 2026 07:53
/// A STREAM read builds a nested QueryPlan at run time whose steps are not part of the outer
/// plan the per-step wall-clock registry is populated from. Timing such a query has no
/// semantic meaning (a streaming read never completes), so reject it rather than execute it.
if (dynamic_cast<const MergeTreeCommitOrderSequentialSource *>(proc_ptr))

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 blanket ILLEGAL_STREAM check is broader than the bug it fixes. The original failure is a debug/sanitizer-only chassert(clock) when the streaming source injects a runtime sub-pipeline whose processors keep inner-plan step pointers, but this branch now rejects all STREAM queries in release builds too.

That is a real behavior regression for bounded streaming queries that already complete from storage today. tests/queries/0_stateless/04411_streaming_distinct_in_order.sql:29-32 explicitly covers SELECT ... STREAM LIMIT 50, and the reference is 50 / 50, so EXPLAIN ANALYZE is not dealing only with never-ending queries here.

If we want to preserve the chassert(clock) invariant, the fix needs to repair step attribution for the runtime-added processors instead of banning STREAM outright. There is already precedent for this pattern in LazyReadReplacingFinalSource::work, which retags its dynamically built processors with inheritQueryPlanStepFromParent(*this, getQueryPlanStepGroup()) before exposing them to the executor.

@groeneai

Copy link
Copy Markdown
Collaborator Author

@Fgrtue the automated review flagged a regression risk in the reject-all approach you asked for, and I want your call before finalizing since it touches the direction of the fix.

Findings after checking the code:

  1. Release builds are already safe. ExecutionThreadContext::executeTask has chassert(clock) immediately followed by if (clock), so a null clock only aborts in debug/sanitizer builds; release silently skips timing for the unattributed step.

  2. Bounded streaming EXPLAIN ANALYZE completes today. 04411_streaming_distinct_in_order.sql shows ... STREAM LIMIT 50 returns from storage (50/50), not a never-ending query. So the blanket ILLEGAL_STREAM reject in this PR turns a query that works in release into a user error.

  3. There is a precedented alternative that keeps chassert(clock) AND keeps STREAM working: repair step attribution for the runtime sub-pipeline. MergeTreeCommitOrderSequentialSource::updatePipeline() detaches its dynamically built sub-pipeline (Pipe::detachProcessors, then update.to_add) without retagging. LazyReadReplacingFinalSource::work() handles the same situation by calling proc->inheritQueryPlanStepFromParent(*this, getQueryPlanStepGroup()) on each detached processor before exposing it. Adding that one loop before update.to_add = std::move(sub_processors) makes the inner processors inherit the source's plan step, so the registry lookup succeeds and the invariant holds.

Which do you want?

  • (a) Reject-all (current PR): simplest, but bounded STREAM LIMIT N EXPLAIN ANALYZE that works in release today starts throwing.
  • (b) Retag via inheritQueryPlanStepFromParent: restore chassert(clock), drop the interpreter reject, keep STREAM working; test 04422 goes back to asserting success.

Your call since you own this pivot. I will implement whichever you pick.

@clickhouse-gh

clickhouse-gh Bot commented Jul 11, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 49.30% 85.80% +36.50%
Functions 63.90% 92.70% +28.80%
Branches 38.10% 77.90% +39.80%

Changed lines: Changed C/C++ lines covered: 5/7 (71.43%) · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Jul 11, 2026 •

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — a16bb7a

Every failure below has an owner (a fixing PR). This PR's diff is ExecutionThreadContext.cpp + two new stateless test files only; none of the failures are in a code path it touches (not PR-caused).

Check / test Reason Owner / fixing PR
Integration tests (amd_msan, 7/8) / test_replicated_database::test_replicated_table_structure_alter flaky (9 master + 15+ unrelated PRs in 30d; newly surfaced 2026-07-10) #110030 (ours, open)
Upgrade check (amd_release) / Error message in clickhouse-server.log — DatabasePostgreSQL::getTablesIterator Code 614 Connection to 192.0.2.1:5432 failed (RFC-5737 fixture host left by 04210_show_remote_databases_in_system_tables) benign leftover-fixture error leak #109350 (ours, open)
Config Workflow / Finish Workflow / Mergeable Check / PR rollup of the above owned via the two rows above
CH Inc sync pass CH Inc sync (private, not actionable)

Session id: cron:our-pr-ci-monitor:20260711-130000

@clickhouse-gh clickhouse-gh Bot added pr-not-for-changelog This PR should not be mentioned in the changelog and removed pr-bugfix Pull request with bugfix, not backported by default labels Jul 11, 2026
Comment on lines +1210 to +1214

/// A STREAM read builds a nested QueryPlan at run time whose steps are not part of the outer
/// plan the per-step wall-clock registry is populated from. Timing such a query has no
/// semantic meaning (a streaming read never completes), so reject it rather than execute it.
if (dynamic_cast<const MergeTreeCommitOrderSequentialSource *>(proc_ptr))

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.

IMO, checking the pipeline is a bug-prone approach; it is better to rewrite this into a logical plan validation. For streaming queries, for example, we need to check that all sources do not have streaming table expression modifiers.

@Fgrtue wdyt?

@groeneai do nothing regarding this comment.

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.

I think a rare person knows a proper fix better than you @Michicosun. It makes sense to do this fix in #110164 since it reintroduces the feature

pull Bot pushed a commit to Spencerx/ClickHouse that referenced this pull request Jul 12, 2026
This reverts the `EXPLAIN ANALYZE` feature added in
ClickHouse#106586 (merge commit
918a0d3), a revert of that merge with `-m 1`.

It removes the query-executor instrumentation (`StepWallClock`,
`StepWallClockRegistry`, `AnalyzePlanStats`, per-step wall-clock and per-port
data accounting on `IProcessor`, per-stage processor grouping on
`SortingStep`/`AggregatingStep`/`JoinStep`), the `ANALYZE` keyword and its
handling in `ParserExplainQuery`/`InterpreterExplainQuery`,
`StreamLocalLimits::forQueryResult`, and the associated tests and
documentation.

There are no merged follow-up pull requests to revert. The only follow-up,
ClickHouse#110077 ("Reject EXPLAIN ANALYZE
for streaming (STREAM) queries"), is still open and not part of `master`.

The single revert conflict, in
`tests/queries/0_stateless/03269_explain_unique_ids.reference`, was resolved to
keep the unrelated node-id renumbering introduced later by "Fix Not-ready Set
exception by making in-place set build non-destructive" (5583c9a) while
reverting only the `EXPLAIN ANALYZE` step-id change.

Co-Authored-By: Claude Fable 5 <[email protected]>
@Fgrtue

Fgrtue commented Jul 13, 2026

Copy link
Copy Markdown
Contributor

Closed in favor of #110164 that reintroduces the feature with a fix

@Fgrtue Fgrtue closed this Jul 13, 2026
auto-merge was automatically disabled July 13, 2026 06:59

Pull request was closed

zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
This reverts the `EXPLAIN ANALYZE` feature added in
ClickHouse#106586 (merge commit
918a0d3), a revert of that merge with `-m 1`.

It removes the query-executor instrumentation (`StepWallClock`,
`StepWallClockRegistry`, `AnalyzePlanStats`, per-step wall-clock and per-port
data accounting on `IProcessor`, per-stage processor grouping on
`SortingStep`/`AggregatingStep`/`JoinStep`), the `ANALYZE` keyword and its
handling in `ParserExplainQuery`/`InterpreterExplainQuery`,
`StreamLocalLimits::forQueryResult`, and the associated tests and
documentation.

There are no merged follow-up pull requests to revert. The only follow-up,
ClickHouse#110077 ("Reject EXPLAIN ANALYZE
for streaming (STREAM) queries"), is still open and not part of `master`.

The single revert conflict, in
`tests/queries/0_stateless/03269_explain_unique_ids.reference`, was resolved to
keep the unrelated node-id renumbering introduced later by "Fix Not-ready Set
exception by making in-place set build non-destructive" (5583c9a) while
reverting only the `EXPLAIN ANALYZE` step-id change.

Co-Authored-By: Claude Fable 5 <[email protected]>
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-not-for-changelog This PR should not be mentioned in the changelog

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants