Repository navigation
Reject input() referenced more than once via CTE inlining - #106682
Conversation
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
|
cc @nikitamikhaylov @vitlibar — could you review this? Reject the second |
Pre-PR validation gate
Session id: cron:clickhouse-ci-task-worker:20260607-154500 |
|
Workflow [PR], commit [9e9bbe8] Summary: ❌
AI ReviewSummaryThis PR turns duplicate consumption of the one-shot Final VerdictStatus: ✅ Approve |
|
@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]>
|
@nikitamikhaylov Thanks — done in 5ea4f5e. While verifying the suggestion locally, I found that wrapping The new test step 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]>
Pre-PR validation gate
Session id: cron:clickhouse-ci-task-worker:20260607-180100 |
|
The previous commit broke The over-eager Verified locally on debug build:
|
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]>
Pre-PR validation gate (callback-path follow-up commit
|
| # | 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
|
Thanks, you were right. Reproduced the silent-EOF case locally with Pushed
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]>
Pre-PR validation gateFix-up commit: 9e9bbe8 (
Session id: cron:clickhouse-ci-task-worker:20260608-062900 |
CI ledger update — covered SHA: 9e9bbe8Addressed the PR-caused failure on commit
Cause: Fix-up: pin Other failure on the SHA — Pre-PR validation gate (a–f) posted in the previous comment. |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered by tests: 13/14 (92.86%) | Lost baseline coverage: none · Uncovered code |
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:
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. |
cdd9b77
|
Found via ClickGap automated review. Please close or comment if this is incorrect or needs adjustment. TL;DRReject input() referenced more than once via CTE inlining ClickGap verified: reproduced it with the script below on ReproductionShell reproducer — run against a local ClickHouse build ( 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
Affects
Suggested next stepThe fix has landed on master; the affected release branches above still need the backport. Component: cc fix PR author: @groeneai ClickGap · Finding: |
Cherry pick #106682 to 26.3: Reject input() referenced more than once via CTE inlining
Cherry pick #106682 to 26.4: Reject input() referenced more than once via CTE inlining
Cherry pick #106682 to 26.5: Reject input() referenced more than once via CTE inlining
Backport #106682 to 26.4: Reject input() referenced more than once via CTE inlining
Backport #106682 to 26.5: Reject input() referenced more than once via CTE inlining
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]>
…an once via CTE inlining
…6682 Backport ClickHouse#106682 to 26.4: Reject input() referenced more than once via CTE inlining
…an once via CTE inlining
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 multipleReadFromInputplan steps over the same singletonStorageInput. The firstinitializePipelineconsumed the pipe; the second hitLOGICAL_ERROR 'Trying to read from input() twice.', which aborts the server in debug builds.The AST-level guard in
ASTInsertQuery::tryFindInputFunctiononly sees the original AST before CTE inlining, so it cannot catch this pattern. Reject the secondreadImpladd at the storage level with a cleanINVALID_USAGE_OF_INPUTexception.Closes: #106672
Changelog category (leave one):
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 functioninputis wrapped in a non-MATERIALIZED CTE that is referenced from more than one place in the query. The query is now rejected with a cleanINVALID_USAGE_OF_INPUTerror at planning time.inputis a one-shot client stream and can only be consumed by a single source in the query plan.Version info
26.6.1.71326.5.3.34,26.4.5.40