Skip to content

Reject input() referenced more than once via CTE inlining - #106682

Merged
CheSema merged 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-input-twice-cte-106672
Jun 12, 2026
Merged

CheSema merged 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-input-twice-cte-106672

Conversation

@groeneai

@groeneai groeneai commented Jun 7, 2026 •

Copy link
Copy Markdown
Collaborator

A non-MATERIALIZED CTE that wraps input() and is referenced from multiple places (e.g. two sibling CTEs that are CROSS JOINed) gets inlined by the analyzer into multiple ReadFromInput plan steps over the same singleton StorageInput. The first initializePipeline consumed the pipe; the second hit LOGICAL_ERROR 'Trying to read from input() twice.', which aborts the server in debug builds.

The AST-level guard in ASTInsertQuery::tryFindInputFunction only sees the original AST before CTE inlining, so it cannot catch this pattern. Reject the second readImpl add at the storage level with a clean INVALID_USAGE_OF_INPUT exception.

Closes: #106672

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

Fix exception 'Trying to read from input() twice.' raised when the table function input is wrapped in a non-MATERIALIZED CTE that is referenced from more than one place in the query. The query is now rejected with a clean INVALID_USAGE_OF_INPUT error at planning time. input is a one-shot client stream and can only be consumed by a single source in the query plan.

Version info

  • Merged into: 26.6.1.713
  • Backported to: 26.5.3.34, 26.4.5.40

A non-MATERIALIZED CTE that wraps `input()` and is referenced from
multiple places (e.g. two sibling CTEs that are CROSS JOINed) gets
inlined by the analyzer into multiple `ReadFromInput` plan steps over
the same singleton `StorageInput`. The first `initializePipeline`
consumed the pipe; the second hit `LOGICAL_ERROR 'Trying to read from
input() twice.'`, which aborted the server in debug builds.

The AST-level guard in `ASTInsertQuery::tryFindInputFunction` only sees
the original AST before CTE inlining, so it could not catch this
pattern. Reject the second `readImpl` add at the storage level with a
clean `INVALID_USAGE_OF_INPUT` exception.

Closes: ClickHouse#106672
@groeneai

groeneai commented Jun 7, 2026

Copy link
Copy Markdown
Collaborator Author

cc @nikitamikhaylov @vitlibar — could you review this? Reject the second readImpl add on StorageInput with INVALID_USAGE_OF_INPUT so analyzer-time CTE inlining of input() no longer surfaces as LOGICAL_ERROR (#106672).

@groeneai

groeneai commented Jun 7, 2026

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. The exact reproducer from issue #106672 (CREATE TABLE + INSERT ... WITH data AS (SELECT * FROM input(...)), first_ref AS (...), second_ref AS (...) SELECT ... CROSS JOIN ...) deterministically aborts the local debug server with LOGICAL_ERROR 'Trying to read from input() twice.' on every invocation against unpatched master (verified locally on 26.6.1.1).
b Root cause explained? The analyzer clones a non-MATERIALIZED CTE QueryNode at every reference (QueryAnalyzer.cpp:3061). When the CTE wraps input(), both clones resolve to the same singleton StorageInput (cached in Context::table_function_results by tree hash), so two separate ReadFromInput plan steps over the same storage are added. The first initializePipeline consumes the pipe; the second hits was_pipe_used==true and throws LOGICAL_ERROR (StorageInput.cpp:136). The AST-level guard ASTInsertQuery::tryFindInputFunction runs on the original AST before CTE inlining, so it sees only one input() and lets the query through.
c Fix matches root cause? Yes. The structural invariant of StorageInput is "one Storage = one read", so the right place to enforce it is at StorageInput::readImpl — the moment a second ReadFromInput step would be added to the plan. Reject with INVALID_USAGE_OF_INPUT (the same code already used at line 133 for "input stream is not initialized"), which surfaces as a clean user-facing error at planning time instead of a debug-build server abort at pipeline build time.
d Test intent preserved / new tests added? New regression test tests/queries/0_stateless/04323_input_twice_cte_106672.sh covers four cases: (1) the issue's CROSS-JOIN reproducer is rejected with INVALID_USAGE_OF_INPUT, (2) single CTE reference still inserts, (3) direct input() without CTE still inserts, (4) server stays alive after the rejected query. No existing tests modified or weakened.
e Both directions demonstrated? Yes. Without the fix, the reproducer aborts the server (LOGICAL_ERROR); the test would fail because --- server alive step would not run AND the grep in step 1 would match LOGICAL_ERROR not INVALID_USAGE_OF_INPUT. With the fix applied and rebuilt, the test passes (diff ... reference exits 0). Verified locally.
f Fix is general, not a narrow patch? Yes. The new was_read_added guard catches every multi-reference path that produces multiple ReadFromInput steps over the same StorageInput — including non-MATERIALIZED CTE inlining (the issue's CROSS-JOIN pattern), CTE inlining via UNION ALL, and any future analyzer rewrite that duplicates references to the same input(). It is not a guard against the specific symptom (the two CTE clones); it is a structural one-shot enforcement at the storage level, matching the underlying invariant that the input() HTTP body / TCP stream physically can only be read once. The pre-existing was_pipe_used check at pipeline-build time is left intact as a deeper safety net.

Session id: cron:clickhouse-ci-task-worker:20260607-154500

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

clickhouse-gh Bot commented Jun 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9e9bbe8]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_debug, parallel) FAIL
Server died FAIL cidb
Logical error: Virtual row boundary violated in MergingSortedAlgorithm for input A on sort column 'B' C: the virtual row announced D but the source then produced E, which would mis-order the merge (STID: 2651-3359) FAIL cidb
Integration tests (amd_tsan, 2/6) FAIL
test_storage_delta_disks/test.py::test_single_log_file[False-1-s3] FAIL cidb
test_storage_delta_disks/test.py::test_single_log_file[False-0-s3] FAIL cidb
test_storage_delta_disks/test.py::test_single_log_file[False-1-local] FAIL cidb
test_storage_delta_disks/test.py::test_single_log_file[False-0-azure] FAIL cidb
test_storage_delta_disks/test.py::test_single_log_file[True-1-s3] FAIL cidb
test_storage_delta_disks/test.py::test_single_log_file[True-0-s3] FAIL cidb
test_storage_delta_disks/test.py::test_single_log_file[True-1-local] FAIL cidb
test_storage_delta_disks/test.py::test_single_log_file[True-0-azure] FAIL cidb

AI Review

Summary

This PR turns duplicate consumption of the one-shot input stream after CTE inlining into a user-facing INVALID_USAGE_OF_INPUT exception, and the final version applies the guard to both the HTTP shared-pipe path and callback-backed clients such as clickhouse-local. The added focused tests cover the original multi-reference CTE failure, allowed single-read cases, and the MATERIALIZED CTE workaround. I did not find remaining correctness, safety, or metadata issues that need inline comments.

Final Verdict

Status: ✅ Approve

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

Copy link
Copy Markdown
Member

@groeneai Maybe suggest using the MATERIALIZED CTE instead?

Per @nikitamikhaylov suggestion on PR ClickHouse#106682: extend the
`INVALID_USAGE_OF_INPUT` thrown from `StorageInput::readImpl` to actively
guide users toward the `MATERIALIZED` CTE workaround.

The hint also notes that `enable_materialized_cte = 1` is required:
without that setting, `MATERIALIZED` is treated as just a hint by the
analyzer and the CTE is still inlined into multiple plan sources.

The new test case in `04323_input_twice_cte_106672.sh` verifies that the
workaround actually works end-to-end (a CROSS JOIN of two child CTEs both
reading from a MATERIALIZED parent CTE that wraps `input` succeeds).

Related: ClickHouse#106682

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

groeneai commented Jun 7, 2026

Copy link
Copy Markdown
Collaborator Author

@nikitamikhaylov Thanks — done in 5ea4f5e.

While verifying the suggestion locally, I found that wrapping input in MATERIALIZED is not enough on its own: the enable_materialized_cte setting is false by default, so the analyzer (QueryAnalyzer.cpp:1325) ignores the MATERIALIZED keyword and inlines the CTE anyway, and you still hit the same multi-ReadFromInput situation. The hint therefore mentions both:

SETTINGS enable_materialized_cte = 1
WITH cte AS MATERIALIZED (SELECT ... FROM input(...)) ...

The new test step --- MATERIALIZED CTE workaround with enable_materialized_cte=1: allowed in 04323_input_twice_cte_106672.sh confirms the workaround actually succeeds end-to-end.

Session id: cron:clickhouse-ci-task-worker:20260607-165800

The previous commit (5ea4f5e) added an early was_read_added guard in
StorageInput::readImpl to reject the second readImpl call for non-MATERIALIZED
CTE inlining. That check fired in legitimate cases too: the existing test
02915_input_table_function_in_subquery uses the shape

  INSERT INTO ... SELECT t FROM <view-with-aggregation>
   WHERE toUnixTimestamp64Milli(t) IN (SELECT timestamp FROM input(...))

over HTTP. The IN-subquery + aggregating-view planning calls readImpl twice on
the singleton StorageInput (one of which is a planner artifact whose pipeline
is never actually initialized), so the early readImpl guard rejected the query.

Move the rejection back to ReadFromInput::initializePipeline, where the
existing was_pipe_used flag truthfully detects the second pipeline read
(only the actually-executed plan steps init their pipeline). Keep the
helpful MATERIALIZED CTE / enable_materialized_cte hint message and the
INVALID_USAGE_OF_INPUT error code (replacing the old LOGICAL_ERROR that
aborted the server in debug builds).

After this:
  - 04323_input_twice_cte_106672: still rejected at run time with
    INVALID_USAGE_OF_INPUT and the MATERIALIZED CTE hint, server stays alive.
  - 02915_input_table_function_in_subquery: passes again.

Closes: ClickHouse#106672

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

groeneai commented Jun 7, 2026

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? YES. Pre-fix: INSERT INTO t WITH data AS (SELECT * FROM input(...)), first AS (SELECT id FROM data), second AS (SELECT name FROM data) SELECT f.id, s.name FROM first f CROSS JOIN second s over HTTP triggers LOGICAL_ERROR 'Trying to read from input() twice.' and aborts the debug-build server every time. The 02915 regression introduced by the prior commit was also deterministic: the IN-subquery+aggregating-view shape from 02915_input_table_function_in_subquery.sh always fired the over-eager readImpl guard.
b Root cause explained? Two separate problems. (1) Original issue #106672: a non-MATERIALIZED CTE that wraps input and is referenced more than once is inlined by the analyzer into multiple ReadFromInput plan steps over the singleton StorageInput. The first initializePipeline consumes storage.pipe; the second hits was_pipe_used and threw LOGICAL_ERROR, aborting the server. (2) Regression introduced by the previous commit: the was_read_added guard added to readImpl was too aggressive: readImpl is also called on harmless plan-time paths (e.g. an IN-subquery over a view with aggregation) where only one of the two ReadFromInput plan steps is actually wired into the executed pipeline. Rejecting the second readImpl falsely rejected those queries.
c Fix matches root cause? YES. The check now lives at the only place where a real second pipeline read happens: ReadFromInput::initializePipeline. The pre-existing was_pipe_used flag truthfully detects a second pipeline init (only the actually-executed plan steps init their pipeline; planner artifacts never reach this path). The check now throws INVALID_USAGE_OF_INPUT instead of LOGICAL_ERROR, with the helpful MATERIALIZED CTE / enable_materialized_cte hint message. The over-eager readImpl guard is removed entirely.
d Test intent preserved / new tests added? YES. (i) 02915_input_table_function_in_subquery is now passing again (it was passing before this PR; the prior commit broke it; this commit restores it). (ii) 04323_input_twice_cte_106672 still rejects the two-CTE-refs CROSS JOIN shape with the same error class (INVALID_USAGE_OF_INPUT) and same end-to-end behavior (server stays alive, --- final rows and --- server alive blocks unchanged). (iii) The 04323 regression test from the prior commit is unchanged and still proves the original issue #106672 is fixed.
e Both directions demonstrated? YES. Verified locally on a fresh debug build: pre-fix (HEAD before this commit) on the 04323 reproducer crashes the server with LOGICAL_ERROR and Connection refused afterwards; with this fix the same query produces a clean INVALID_USAGE_OF_INPUT and the server stays alive (SELECT 1 succeeds). For the 02915 regression: pre-fix (HEAD before this commit) the IN-subquery+aggregating-view INSERT fails with the over-eager INVALID_USAGE_OF_INPUT; with this fix the same query succeeds and count() advances as expected.
f Fix is general, not a narrow patch? YES. The fix addresses the root cause (the was_pipe_used check at initializePipeline is the single choke-point where a real second pipeline read manifests) and removes a defensive symptom guard at readImpl that was masking the real semantics and causing collateral damage. It does not silence the LOGICAL_ERROR in readImpl (no such guard exists anymore); it converts the existing LOGICAL_ERROR at initializePipeline into a user-facing exception with an actionable hint. The TCP-path harmless duplicate-readImpl shape (each readImpl makes its own StorageInputSource reading from the shared client callback) is now correctly NOT rejected at plan time.

Session id: cron:clickhouse-ci-task-worker:20260607-180100

@groeneai

groeneai commented Jun 7, 2026

Copy link
Copy Markdown
Collaborator Author

The previous commit broke 02915_input_table_function_in_subquery (a Fast test failure on the PR CI). Pushed fix-up commit 6950e45df51f that restores 02915 while keeping the original #106672 fix and the MATERIALIZED CTE hint.

The over-eager was_read_added guard at StorageInput::readImpl rejected harmless duplicate readImpl calls (e.g. the IN-subquery over an aggregating view shape used by 02915). The actual second-pipeline-read manifests at ReadFromInput::initializePipeline via the pre-existing was_pipe_used flag, which only fires for plan steps actually wired into the executed pipeline. Moved the check there and converted the old LOGICAL_ERROR 'Trying to read from input() twice.' into the user-facing INVALID_USAGE_OF_INPUT with the MATERIALIZED CTE / enable_materialized_cte hint.

Verified locally on debug build:

  • 04323 reproducer (two-CTE-refs CROSS JOIN over HTTP) → clean INVALID_USAGE_OF_INPUT, server stays alive.
  • 02915 (INSERT-SELECT IN(input()) over aggregating view, HTTP) → succeeds, no error, server alive.
  • 04323 single-CTE-ref / direct input() / MATERIALIZED CTE workaround paths → all still pass with the same reference output.

Comment thread src/Storages/StorageInput.cpp Resolved
The previous guard at `ReadFromInput::initializePipeline` only fired in the
HTTP branch, after the `if (!pipe.empty()) return;` early exit. The TCP, gRPC
and `clickhouse-local` paths take that early exit because `readImpl` builds a
fresh `StorageInputSource` pipe per call site when `getInputBlocksReaderCallback`
is set. Two `ReadFromInput` plan steps over the same `StorageInput` singleton
therefore attached two sources to the same client-driven block reader and one
of them silently observed EOF, dropping rows from the INSERT instead of
raising `INVALID_USAGE_OF_INPUT`.

Move the one-shot check to the top of `initializePipeline` so it runs before
either branch and set `was_pipe_used` in the callback branch as well.

Adds a `clickhouse-local` regression test (`04324_input_twice_cte_106672_local.sh`)
asserting `INVALID_USAGE_OF_INPUT` is raised on the multi-CTE-ref shape and that
single-ref / direct-`input` shapes still work.

Verified locally on debug build: 50/50 random runs of `04324`. The new test
fails on the parent commit (HEAD before this change) and passes with this
change. Companion test `04323` (HTTP) and the existing `02915` callback-path
test both still pass.

Addresses clickhouse-gh[bot] review on PR ClickHouse#106682:
ClickHouse#106682 (review)

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

groeneai commented Jun 7, 2026

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (callback-path follow-up commit 9c6cda9e631a)

# Question Answer
a Deterministic repro? Yes. clickhouse-local --path <dir> --query "INSERT INTO dst WITH data AS (SELECT * FROM input('id UInt64, name String')), first_ref AS (SELECT id FROM data), second_ref AS (SELECT name FROM data) SELECT f.id, s.name FROM first_ref f CROSS JOIN second_ref s FORMAT JSONEachRow" <<< $'{"id":1,"name":"a"}\n{"id":2,"name":"b"}\n{"id":3,"name":"c"}'. Without the new commit: zero rows inserted, no error. With the new commit: Code: 477. INVALID_USAGE_OF_INPUT.
b Root cause explained? ReadFromInput::initializePipeline checked storage.was_pipe_used only inside the HTTP branch, after the if (!pipe.empty()) return; early exit. StorageInput::readImpl builds a fresh StorageInputSource pipe per call site whenever getInputBlocksReaderCallback is set (TCP, gRPC, clickhouse-local), so the callback path always took the early exit and the guard never ran. Two ReadFromInput plan steps from a non-MATERIALIZED CTE both attached sources to the same singleton client-driven block reader, the executor handed all rows to the first one, and the second saw EOF, dropping the join silently.
c Fix matches root cause? Yes. The was_pipe_used check is now the first statement of initializePipeline, applied uniformly to both the callback-backed and HTTP branches, and was_pipe_used is set in both branches after pipeline.init. The earliest second initialization throws INVALID_USAGE_OF_INPUT regardless of which branch handled the first one.
d Test intent preserved / new tests added? New stateless test 04324_input_twice_cte_106672_local.sh covers the callback path via clickhouse-local. Existing 04323_input_twice_cte_106672.sh (HTTP) and 02915_input_table_function_in_subquery.sh (single-ref input inside an IN-subquery) still pass and remain untouched.
e Both directions demonstrated? Yes. Built the parent commit 6950e45df51f and ran the new test: 04324 FAILS (no INVALID_USAGE_OF_INPUT is raised, output drops to 6 lines). Built this commit 9c6cda9e631a and reran: 04324 PASSES. 50/50 random-settings runs of 04324 pass with the fix.
f Fix is general, not a narrow patch? Yes. The single guard at the top of initializePipeline covers HTTP, TCP, gRPC and clickhouse-local because all of them go through the same step. There is no symmetric path that re-instantiates StorageInput to consider; the storage is a per-query singleton cached by AST hash in Context::executeTableFunction. The was_pipe_initialized flag remains the HTTP-specific signal that setPipe ran, and stays unchanged.

Session id: cron:clickhouse-ci-task-worker:20260607-191800

@groeneai

groeneai commented Jun 7, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks, you were right. Reproduced the silent-EOF case locally with clickhouse-local: a multi-row INSERT with a two-ref CTE over input produced zero rows on the parent commit 6950e45df51f, no error, just one source consuming the stream and the other seeing EOF.

Pushed 9c6cda9e631a:

  • Moved the was_pipe_used check to the top of ReadFromInput::initializePipeline, before the if (!pipe.empty()) return; early exit, so it applies uniformly to the callback-backed path (TCP, gRPC, clickhouse-local) and the HTTP shared-pipe path.
  • Set was_pipe_used in the callback branch as well, so the second ReadFromInput plan step throws INVALID_USAGE_OF_INPUT instead of attaching another source to the same client-driven block reader.
  • Added stateless test 04324_input_twice_cte_106672_local.sh that exercises the multi-CTE-ref shape via clickhouse-local. It fails on the parent commit (no error raised, rows dropped) and passes on this commit. 50/50 random-settings runs locally on debug.

Pre-PR validation gate posted as a separate comment.

CI failure on PR ClickHouse#106682 commit 9c6cda9:
Stateless tests (amd_llvm_coverage, old analyzer, s3 storage,
DatabaseReplicated, WasmEdge, parallel) -> 04323_input_twice_cte_106672 Q4.

Q4 verifies that the MATERIALIZED CTE workaround (recommended in our new
INVALID_USAGE_OF_INPUT error message) actually works. enable_materialized_cte
is honored only by the new analyzer; on the old-analyzer lane MATERIALIZED is
treated as a no-op and the CTE is still inlined, so our one-shot guard fires
and the workaround appears not to work. Pin enable_analyzer=1 in Q4's
query-level SETTINGS so the workaround can actually run on every lane,
including the old-analyzer one.

CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=106682&sha=9c6cda9e631a25d222c5655cfe7020c5a897d34c
PR: ClickHouse#106682

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

groeneai commented Jun 8, 2026

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

Fix-up commit: 9e9bbe8 (tests/queries/0_stateless/04323_input_twice_cte_106672.sh).

# Question Answer
a Deterministic repro? Yes. Curl Q4 against local debug build with ?enable_analyzer=0 URL parameter (which mimics the failing old analyzer lane) and the prior-Q4 SETTINGS clause (enable_materialized_cte = 1 only): server replies Code: 477 INVALID_USAGE_OF_INPUT every time. With the fix-up Q4 SETTINGS (enable_analyzer = 1, enable_materialized_cte = 1): succeeds every time.
b Root cause explained? enable_materialized_cte is honored only by the new analyzer (src/Analyzer/Resolve/QueryAnalyzer.cpp:1325). On the failing CI lane (Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DatabaseReplicated, WasmEdge, parallel)) the runner forces enable_analyzer = 0 at session level. The old analyzer treats MATERIALIZED as a parser hint and still inlines the CTE twice, so our one-shot guard at the top of ReadFromInput::initializePipeline fires and Q4 receives INVALID_USAGE_OF_INPUT instead of demonstrating the workaround. Q4 is meant to verify the workaround in the error message, so it must run on the new analyzer.
c Fix matches root cause? Yes. Pin enable_analyzer = 1 together with the existing enable_materialized_cte = 1 in Q4's query-level SETTINGS clause. Query-level SETTINGS take priority over session-level ones, so the workaround query runs on the new analyzer regardless of which lane the runner picked. The other test steps (Q1 rejection, Q2 single ref, Q3 direct input) deliberately stay analyzer-agnostic.
d Test intent preserved? Yes. Q4 still demonstrates the recommended workaround end-to-end (data is materialized once, two CTE refs read from the temporary, INSERT succeeds). The reference output is unchanged. The other Qs are unchanged and continue to exercise both analyzers.
e Both directions demonstrated? Yes. Without the fix-up, Q4 errors with INVALID_USAGE_OF_INPUT under enable_analyzer=0; with the fix-up Q4 succeeds. Verified via the deterministic curl repro above and via 50/50 --no-random-settings runs of the test. 04324_input_twice_cte_106672_local.sh and 02915_input_table_function_in_subquery continue to pass (5/5 runs each).
f Fix is general, not a narrow patch? N/A — this is a test-side pin to make the workaround deterministic on every analyzer lane. The behavioral fix (one-shot guard at the top of ReadFromInput::initializePipeline covering both HTTP and callback paths) was already applied earlier in this PR (commits 6950e45df51, 9c6cda9e631) and is not changed here.

Session id: cron:clickhouse-ci-task-worker:20260608-062900

@groeneai

groeneai commented Jun 8, 2026

Copy link
Copy Markdown
Collaborator Author

CI ledger update — covered SHA: 9e9bbe8

Addressed the PR-caused failure on commit 9c6cda9e631:

  • Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DatabaseReplicated, WasmEdge, parallel) — 04323_input_twice_cte_106672 Q4 (the MATERIALIZED CTE workaround verification).

Cause: enable_materialized_cte is honored only by the new analyzer. On the old analyzer lane the runner forces enable_analyzer = 0 at session level; the old analyzer ignores MATERIALIZED (it's a hint, not a parser-level keyword for it) and re-inlines the CTE, so our new INVALID_USAGE_OF_INPUT correctly fires and Q4 fails to demonstrate the workaround.

Fix-up: pin enable_analyzer = 1 alongside enable_materialized_cte = 1 in Q4's query-level SETTINGS so the workaround can actually run. Query-level SETTINGS take priority over runner-injected session settings.

Other failure on the SHA — AST fuzzer (arm_asan_ubsan) STID 2508-3fad — is not PR-caused (unrelated or_argument_nodes.size() > 1 chronic; only one hit in 90 days, none in this PR's diff scope), tracked separately.

Pre-PR validation gate (a–f) posted in the previous comment.

@clickhouse-gh

clickhouse-gh Bot commented Jun 8, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.50% 84.60% +0.10%
Functions 92.30% 92.30% +0.00%
Branches 77.20% 77.20% +0.00%

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

Full report · Diff report

@groeneai

groeneai commented Jun 8, 2026

Copy link
Copy Markdown
Collaborator Author

CI ledger update — covered SHA: 9e9bbe8 (post-CI)

CI on commit `9e9bbe83bbb` has now fully finished (Finish Workflow=pass). Two failures, both NOT PR-caused:

job failure classification disposition
`Integration tests (amd_tsan, 2/6)` `test_storage_delta_disks::test_single_log_file` × 8 parametrizations — all timed out starting node `node_with_disabled_delta_kernel` (cluster.start() timeout, the test bodies never ran) infra/chronic, single-run cluster-startup timeout This PR only touches `src/Storages/StorageInput.cpp` and adds two stateless test files; no Delta / disk / docker / cluster code is changed. CIDB 30d cross-PR: only 2 unrelated PRs hit it (#105056, #106682); the larger cluster-counts on #105165=95 / #102017=67 are own-test sightings (those PRs modify `test_storage_delta_disks/test.py`). 0 master hits. Sibling-tracker task created for monitoring.
`Stateless tests (amd_debug, parallel)` `Logical error: Virtual row boundary violated in MergingSortedAlgorithm` (STID 2651-3359) on sort column `__table1.timestamp` DESC trunk-bug (currently on master and 28+ unrelated PRs in 30d, last master hit today 11:25:58 UTC) Already tracked under umbrella STID 2651-3359 with fix PR #106664 in flight. The failing path is `MergingSortedAlgorithm::checkVirtualRowBoundary` — entirely unrelated to StorageInput. Cross-link in our umbrella task.

Both failures predate this PR and are tracked elsewhere. The PR diff (StorageInput.cpp + 04323_/04324_ tests) cannot affect either failing path.

CI is fully GREEN for everything in this PR's diff scope. Awaiting human review.

@CheSema CheSema self-assigned this Jun 8, 2026
@CheSema
CheSema added this pull request to the merge queue Jun 12, 2026
Merged via the queue into ClickHouse:master with commit cdd9b77 Jun 12, 2026
163 of 166 checks passed
@clickgapai

clickgapai commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor

Found via ClickGap automated review. Please close or comment if this is incorrect or needs adjustment.

TL;DR

Reject input() referenced more than once via CTE inlining

ClickGap verified: reproduced it with the script below on 26.5; tested 5 version(s) — 4 affected, 1 clean (see Affects); confirmed it predates the oldest available release (pre-existing).

Reproduction

Shell reproducer — run against a local ClickHouse build (bash <script> <clickhouse-binary>); requires the referenced test fixtures from the repo.

A non-MATERIALIZED CTE that wraps input() and is referenced more than once (here two sibling CTEs that are CROSS JOINed) gets inlined by the analyzer into two ReadFromInput plan steps over the same singleton StorageInput. Since input() is a one-shot client stream that cannot be read twice, this either fails with LOGICAL_ERROR 'Trying to read from input() twice.' or silently drops the inserted rows. It should instead be rejected cleanly at planning time with INVALID_USAGE_OF_INPUT.

CREATE TABLE dst (id UInt64, name String) ENGINE = MergeTree() ORDER BY id;

-- pipe one row of data into input() via stdin:
echo '{"id":1,"name":"a"}' | clickhouse-client --query "
    INSERT INTO dst
    SETTINGS enable_analyzer = 1
    WITH data AS (SELECT * FROM input('id UInt64, name String')),
         first_ref  AS (SELECT id   FROM data),
         second_ref AS (SELECT name FROM data)
    SELECT f.id, s.name FROM first_ref f CROSS JOIN second_ref s
    FORMAT JSONEachRow
"

-- Pre-fix: LOGICAL_ERROR 'Trying to read from input() twice.' (or the INSERT silently
-- succeeds inserting 0 rows). Post-fix: rejected with INVALID_USAGE_OF_INPUT.

Bisect

  • Present since at least v25.4.13.22 — reproduces on every release line tested down to there; the introducer predates the oldest release with a downloadable binary, so a single commit isn't pinnable from release binaries (not a recent regression).

Affects

  • ✓ Fix is on master — this PR's change fixes the bug on master. Branches below still have the bug and need the backport.
  • Reproduces on: 26.5, 26.4, 26.3, 25.8
  • Does NOT reproduce on: master
  • Backport needed: 26.5, 26.4, 26.3, 25.8

Suggested next step

The fix has landed on master; the affected release branches above still need the backport.

Component: comp-special-table-engines
Severity: P2

cc fix PR author: @groeneai
cc fix PR reviewer: @CheSema


ClickGap · Finding: phase_d_pr106682

@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 12, 2026
@robot-clickhouse robot-clickhouse added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Jun 15, 2026
robot-clickhouse-ci-1 added a commit that referenced this pull request Jun 15, 2026
Cherry pick #106682 to 26.3: Reject input() referenced more than once via CTE inlining
robot-clickhouse added a commit that referenced this pull request Jun 15, 2026
robot-clickhouse-ci-1 added a commit that referenced this pull request Jun 15, 2026
Cherry pick #106682 to 26.4: Reject input() referenced more than once via CTE inlining
robot-clickhouse added a commit that referenced this pull request Jun 15, 2026
robot-clickhouse-ci-1 added a commit that referenced this pull request Jun 15, 2026
Cherry pick #106682 to 26.5: Reject input() referenced more than once via CTE inlining
robot-clickhouse added a commit that referenced this pull request Jun 15, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Jun 15, 2026
fm4v added a commit that referenced this pull request Jun 16, 2026
Backport #106682 to 26.4: Reject input() referenced more than once via CTE inlining
fm4v added a commit that referenced this pull request Jun 16, 2026
Backport #106682 to 26.5: Reject input() referenced more than once via CTE inlining
jegathees02 pushed a commit to jegathees02/ClickHouse that referenced this pull request Aug 28, 2026
tryExtractCommonExpressions in the LogicalExpressionOptimizer pass
assumed every or() function node has at least two arguments and asserted
it with chassert(or_argument_nodes.size() > 1), aborting the server in
debug/sanitizer builds.

A single-argument or() can be resolved when its only argument has the
Nothing type: IFunctionOverloadResolver::getReturnTypeWithoutLowCardinality
short-circuits to Nothing for any Nothing-typed argument before the
function's own getReturnTypeImpl runs, so the "at least 2 arguments"
check in FunctionAnyArityLogical is skipped. An empty ARRAY JOIN makes a
column Nothing-typed, e.g.

  SELECT t1.c0 FROM t1 AS tx LEFT ARRAY JOIN [] AS a0
  LEFT JOIN t1 ON or(a0 = t1.c0);

produces a single-argument or() in the JOIN ON expression, which tripped
the assert. Common-expression extraction across disjuncts is meaningless
with fewer than two disjuncts, so return without optimizing instead of
asserting. The single-argument or() then falls through to normal JOIN ON
validation, which rejects it with a clear error where appropriate.

Found by the AST fuzzer (STID 2508-3fad), reproduced on two unrelated PRs
(ClickHouse#106981 AST fuzzer amd_debug, ClickHouse#106682 AST fuzzer arm_asan_ubsan).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…6682

Backport ClickHouse#106682 to 26.4: Reject input() referenced more than once via CTE inlining
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
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-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.2-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Logical error: 'Trying to read from input() twice.'.

7 participants