Skip to content

Fix FORMAT not applying to EXPLAIN INSERT SELECT output with SETTINGS or Values - #106686

Merged
alexey-milovidov merged 14 commits into
masterfrom
fix/explain-insert-format-settings-values
Jun 20, 2026
Merged

alexey-milovidov merged 14 commits into
masterfrom
fix/explain-insert-format-settings-values

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jun 7, 2026 •

Copy link
Copy Markdown
Member

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

Make FORMAT apply to the EXPLAIN output of EXPLAIN ... INSERT ... SELECT ... FORMAT ... also when SETTINGS precede the FORMAT or the output format is Values. Follow-up to #101772.

Documentation entry for user-facing changes

  • Documentation is written (no docs needed)

Follow-up to #101772, addressing two unresolved review comments left by the review bot after merge.

EXPLAIN ... INSERT ... SELECT ... FORMAT ... rewinds the trailing FORMAT so it applies to the EXPLAIN output instead of being consumed by the inner INSERT. The rewind was guarded by !insert_query->settings_ast and insert_query->format != "Values", and both guards were too broad:

  • !settings_ast also skipped the rewind for SETTINGS written before the FORMAT (and for settings pushed down from the inner SELECT), so EXPLAIN SYNTAX INSERT INTO FUNCTION null('x UInt64') SELECT 1 SETTINGS max_threads = 1 FORMAT JSONEachRow left FORMAT JSONEachRow on the INSERT.
  • format != "Values" excluded the valid Values output format, even though insert_query->select already rules out the INSERT ... VALUES data path, so EXPLAIN SYNTAX INSERT INTO FUNCTION null('x UInt64') SELECT 1 FORMAT Values never applied FORMAT Values to the EXPLAIN output.

The settings_ast guard existed because the blind --pos; --pos; rewind is only correct when the FORMAT clause is the last thing the INSERT parser consumed — which is not true when SETTINGS follow the FORMAT (allow_settings_after_format_in_insert). Instead of guarding on settings_ast, the rewind now verifies that the two trailing tokens are exactly FORMAT <name>. This keeps the SETTINGS-before-FORMAT and FORMAT Values cases working while still leaving the FORMAT on the INSERT for the SETTINGS-after-FORMAT, FROM INFILE, input, and explicit double-FORMAT forms.

Added stateless test 04321_explain_insert_format_settings_values.

Related: #101772
Related: #67321

Version info

  • Merged into: 26.6.1.1078

Follow-up to #101772. The FORMAT rewind that makes `FORMAT` apply to the
`EXPLAIN` output of `EXPLAIN ... INSERT ... SELECT ... FORMAT ...` was guarded
by `!insert_query->settings_ast` and `insert_query->format != "Values"`. Both
guards were too broad:

- `!settings_ast` also skipped the rewind for `SETTINGS` written before the
  `FORMAT` (and for settings pushed down from the inner `SELECT` by
  `InsertQuerySettingsPushDownVisitor`), so `EXPLAIN SYNTAX INSERT INTO FUNCTION
  null('x UInt64') SELECT 1 SETTINGS max_threads = 1 FORMAT JSONEachRow` left
  `FORMAT JSONEachRow` on the `INSERT` instead of applying it to the `EXPLAIN`
  output.
- `format != "Values"` excluded the valid `Values` output format even though
  `insert_query->select` already rules out the `INSERT ... VALUES` data path, so
  `EXPLAIN SYNTAX INSERT INTO FUNCTION null('x UInt64') SELECT 1 FORMAT Values`
  never applied `FORMAT Values` to the `EXPLAIN` output.

The original `settings_ast` guard existed because the blind `--pos; --pos;`
rewind is only correct when the `FORMAT` clause is the last thing the `INSERT`
parser consumed, which is not true when `SETTINGS` follow the `FORMAT`
(`allow_settings_after_format_in_insert`). Instead of guarding on `settings_ast`,
verify that the two trailing tokens are exactly `FORMAT <name>` before rewinding.
This keeps `SETTINGS`/`FORMAT`-after-`SETTINGS` and `FORMAT Values` working while
still leaving the `FORMAT` on the `INSERT` for the `SETTINGS`-after-`FORMAT`,
`FROM INFILE`, `input`, and explicit double-`FORMAT` forms.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8db77b4]

Summary: ✅


AI Review

Summary

This PR fixes EXPLAIN ... INSERT ... SELECT ... FORMAT ... so the trailing FORMAT is applied to the EXPLAIN output for the SETTINGS-before-FORMAT and Values cases, while preserving input-data formats for FROM INFILE, input, and explicit double-FORMAT forms. The current code addresses the prior child-order and roundtrip review threads, and I did not find remaining correctness issues in the changed parser paths.

Missing context / blind spots
  • ⚠️ Full CI was still pending when reviewed, and this checkout has no local build directory to run the new parser/stateless tests. Passing Fast test and the relevant bugfix validation/parser tests would close this.
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
Comment thread src/Parsers/ParserExplainQuery.cpp Resolved
@Fgrtue Fgrtue self-assigned this Jun 8, 2026
alexey-milovidov and others added 3 commits June 9, 2026 01:30
…hout input()

`ParserInsertQuery` extracted inline insert data following the `FORMAT` clause
whenever a format was present and the data did not come `FROM INFILE`. But an
`INSERT ... SELECT` has no inline data -- the rows come from the `SELECT` -- unless
the `SELECT` reads them through the `input` table function. For a plain
`INSERT ... SELECT ... FORMAT <name>` the parser still looked for inline data and
raised `You have excessive ';' symbol before data for INSERT.` on the common
semicolon-terminated form, e.g.

    EXPLAIN SYNTAX INSERT INTO FUNCTION null('x UInt64') SELECT 1 FORMAT Values;

Guard the inline-data extraction with a check that the `SELECT` actually uses the
`input` table function. The `input` and inline-data (`VALUES`, `FORMAT <name>`
without a `SELECT`) paths are unchanged and still validate the trailing data.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
… roundtrip

The previous follow-up made the FORMAT-to-EXPLAIN-output rewind depend on whether
the two trailing tokens the INSERT consumed were exactly `FORMAT <name>`. That is
not stable across a formatting roundtrip: `ASTInsertQuery::formatImpl` always emits
`SETTINGS` before the `SELECT` and the INSERT `FORMAT` last, so a query written with
`SETTINGS` after the `FORMAT` (allow_settings_after_format_in_insert) re-parses into
the `SETTINGS`-before form, flipping a position-dependent decision and tripping the
`Inconsistent AST formatting` assertion found by the AST fuzzer for

    EXPLAIN SYNTAX INSERT INTO FUNCTION null('x UInt64') SELECT 1 FORMAT JSONEachRow SETTINGS max_threads = 1

Decide based only on the INSERT shape (a `SELECT` source, no `FROM INFILE`, no
`input` table function, no explicit second `FORMAT`), which is invariant under
formatting, and move the `FORMAT` to the EXPLAIN output by setting the output format
on the EXPLAIN query directly instead of rewinding `pos`. The `pos` rewind only
worked when `FORMAT <name>` was the last consumed token; setting the output format
directly is correct regardless of where `SETTINGS` are written.

The test now also covers the SETTINGS-after-FORMAT, double-FORMAT, trailing-semicolon
and roundtrip-stability cases.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread src/Parsers/ParserExplainQuery.cpp Resolved

@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.

The implementation looks good. Added two nits and one suggestion about the test.

Comment thread src/Parsers/ParserExplainQuery.cpp Resolved
Comment thread src/Parsers/ParserExplainQuery.cpp Resolved
alexey-milovidov and others added 2 commits June 10, 2026 14:19
Address the review: the moved output `FORMAT` of `EXPLAIN ... INSERT ... SELECT ... FORMAT ...`
was added to the children of `ASTExplainQuery` before `setExplainedQuery`, so the children were
`[format, insert]` while `ASTExplainQuery::clone` cloned only `children[0]` as the explained
query: clones contained the format node twice and aliased the original explained query.

Attach the moved `FORMAT` through `IAST::set` after `setExplainedQuery`, and make
`ASTExplainQuery::clone` clone the named children (`query`, `ast_settings`, `table_function`,
`table_override`) explicitly instead of assuming their order. The order assumption was already
wrong before this PR for `EXPLAIN SETTINGS ... SELECT ...`, where the EXPLAIN settings are the
first child and the clone aliased the original explained query.

Also remove redundant comments pointed out in the review.

Co-Authored-By: Claude Fable 5 <[email protected]>
Address the review: the test only checked the output format wrapper (e.g. the leading
`{"explain"` of `JSONEachRow`) but not the body of the `EXPLAIN` output. Print the full
`EXPLAIN SYNTAX` output for every case, so the reference also verifies that the `FORMAT`
clause is gone from the `INSERT` body (or kept on it for the double-`FORMAT` form).

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

Copy link
Copy Markdown
Member Author

Addressed all review comments:

  • 786827e620f: the moved FORMAT is now attached after setExplainedQuery, so the explained query stays the first child of ASTExplainQuery; additionally ASTExplainQuery::clone now clones its named children explicitly instead of assuming children[0] is the explained query (that assumption was already wrong for EXPLAIN SETTINGS ... SELECT ... before this PR). Also removed the redundant comments.
  • 15a5421142b: test 04321 now prints the full EXPLAIN SYNTAX output for every case, so the reference verifies the body of the EXPLAIN output (the FORMAT clause is gone from the INSERT body, or kept on it for the double-FORMAT form), not just the output format wrapper.

Verified locally: rebuilt and ran 04321_explain_insert_format_settings_values, 04309_explain_insert_format, 02504_explain_ast_insert, 03904_explain_format_null, 04039_explain_union_settings_formatting_roundtrip, 04050_explain_ast_insert_with_output_options, 04057_explain_except_ast_formatting — all pass.

The only red check, BuzzHouse (amd_debug), is the known issue (exact STID match) — the fuzzed query is a plain SELECT with a lambda-alias tupleElement formatting roundtrip problem, no EXPLAIN/INSERT involved:
Related: #105396

Comment thread src/Parsers/ParserExplainQuery.cpp Resolved
Address review: when `EXPLAIN INSERT ... SELECT ... FORMAT <fmt>` is followed
by `INTO OUTFILE`, `ParserExplainQuery` attaches the moved `FORMAT` child to the
explained query before `ParserQueryWithOutput` parses `INTO OUTFILE`, so the
children end up ordered `[query, format, out_file]`. A re-parse of the formatted
query (the formatter always emits `INTO OUTFILE` before `FORMAT`) yields
`[query, out_file, format]`, so `out_ast->getTreeHash` differs from the
re-parsed AST and the debug-only "Inconsistent AST formatting" check trips.

Generalize the previous `FORMAT`/`SETTINGS` swap into a full canonicalization of
the output-option children (`INTO OUTFILE`, `COMPRESSION`, `LEVEL`, `FORMAT`,
`SETTINGS`) into the fixed order used by `ASTQueryWithOutput::formatImpl`, so the
tree hash is stable across a formatting roundtrip regardless of the original
clause order or of which parser attached the child.

Extend `04321_explain_insert_format_settings_values` with the `INTO OUTFILE`
case, which executes the query so the `#ifndef NDEBUG` consistency check runs.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Comment thread src/Parsers/ParserQueryWithOutput.cpp Resolved
The previous commit canonicalized the output-option child order
(`INTO OUTFILE`, `COMPRESSION`, `FORMAT`, `SETTINGS`) only in the parser, to
match the order `ASTQueryWithOutput::formatImpl` writes them. But
`ASTQueryWithOutput::cloneOutputOptions` still appended children in a different
order (`out_file`, `format_ast`, `settings_ast`, `compression`,
`compression_level`). So a clone of a query that has both an outfile
`COMPRESSION` and a trailing `FORMAT`/`SETTINGS`, e.g.
`SELECT 1 INTO OUTFILE 'x' COMPRESSION 'gz' FORMAT JSONEachRow`, produced a
different child order — and therefore a different `getTreeHash` — than a freshly
parsed or roundtripped AST.

Make the canonical order a single source of truth, `output_option_members`, and
use it from both the parser canonicalization and `cloneOutputOptions`, with a
comment tying it to `formatImpl`. Add a focused gtest asserting that the parsed
AST, its clone, and a format+reparse roundtrip all share the same tree hash for
`INTO OUTFILE ... COMPRESSION ... FORMAT`/`SETTINGS` (and the bare
`FORMAT`/`SETTINGS`) cases.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread src/Parsers/ASTExplainQuery.h Resolved
Comment thread src/Parsers/ASTQueryWithOutput.h Resolved
alexey-milovidov and others added 5 commits June 19, 2026 06:55
`ParserExplainQuery` parses the EXPLAIN-level settings before the explained
query, so `EXPLAIN header = 1 SELECT 1` is parsed with
`children = [ast_settings, query]`. The clone re-added `query` before
`ast_settings`, giving the clone a different child order and therefore a
different `getTreeHash` than a freshly parsed AST (the hash includes children
in order).

Re-add `ast_settings` before `query` in `clone` so that the clone matches the
parser order.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`ASTExecuteAsQuery` also derives from `ASTQueryWithOutput`, but it is parsed
outside `ParserQueryWithOutput`: `ParserExecuteAsQuery` hoists the output
options (`INTO OUTFILE`, `COMPRESSION`, `FORMAT`, `SETTINGS`) from the subquery
to the outer query. It appended them to `children` before the subquery and in
the parsing order (`out_file`, `format_ast`, `compression`, ...), while
`ASTExecuteAsQuery::clone` appends the subquery first and then the output
options in the canonical `output_option_members` order. A parsed
`EXECUTE AS u SELECT 1 INTO OUTFILE 'x' COMPRESSION 'gz' FORMAT JSONEachRow` and
its clone therefore had a different child order and a different `getTreeHash`.

Assign the hoisted fields without appending to `children`, then append the
subquery and the output options through `output_option_members`, so the parsed
AST matches its clone.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ility

Extend `gtest_Parser` with two cases asserting that the clone and the
format+reparse roundtrip both reproduce the same `getTreeHash` as a freshly
parsed AST, for `EXPLAIN` with EXPLAIN-level settings and for `EXECUTE AS` with
output options.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…comment

The EXPLAIN-level settings are written inline without the `SETTINGS` keyword
(e.g. `EXPLAIN header = 1 SELECT 1`); the `EXPLAIN SETTINGS ...` form is a
syntax error. Fix the example in the comment accordingly.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Addressed the AI Review Request changes verdict (both Major findings about clone/parse child-order and tree-hash stability), merged master, and pushed a1db794564c..8db77b4facb.

Changes

  • 9557fe98847 ASTExplainQuery::clone: re-add ast_settings before query, matching the order ParserExplainQuery produces (EXPLAIN-level settings are parsed before the explained query). The clone of e.g. EXPLAIN header = 1 SELECT 1 now keeps children = [ast_settings, query] and has the same getTreeHash as a freshly parsed AST. (8db77b4facb fixes the example in the comment — EXPLAIN SETTINGS ... SELECT is a syntax error; the inline EXPLAIN header = 1 SELECT 1 form is what carries EXPLAIN-level settings.)
  • f9bb383a4d4 ParserExecuteAsQuery: when hoisting the subquery output options to the outer EXECUTE AS, append the subquery first and then the output options through output_option_members, so a parsed EXECUTE AS u SELECT 1 INTO OUTFILE 'x' COMPRESSION 'gz' FORMAT JSONEachRow and its clone share the same child order and getTreeHash.
  • 45d63a1cb9f tests: two gtest_Parser cases asserting clone + format/reparse tree-hash equality for EXPLAIN with EXPLAIN-level settings and for EXECUTE AS with output options. Verified the test queries parse and are format-roundtrip-stable via clickhouse format; the tree-hash assertions run in gtest_Parser in CI.

master was merged (the PR files were untouched by master, so the merge is conflict-free).

Prior CI reds (on a1db794564c) — both unrelated, pre-existing flakes

  • AST fuzzer (amd_debug, targeted, old_compatibility) — Logical error: Trying to get name of not a column: A (STID: 2310-3993). The stack is TableFunctionExplain -> InterpreterExplainQuery -> numbers(...) const-expr evaluation; not related to this parser change. CIDB shows this STID on 8 different days across ~10 unrelated PRs and on master (pull_request_number = 0 on 2026-06-15; e.g. PRs 99508, 104396, 106215, 107554, 107430, 107134, 97452): a master-wide fuzzer-found logical error.

    @groeneai, this looks like a genuine latent logical error reproducible on master (not caused by this PR) — could you investigate Trying to get name of not a column: A (STID: 2310-3993) and track/fix it in a separate PR?

  • Stateless tests (arm_asan_ubsan, azure, parallel) / 03927_autopr_input_bytes_estimation_prewhere_filter — MEMORY_LIMIT_EXCEEDED (current RSS 53.88 GiB on the runner) while reading test.hits; an environmental/resource flake, unrelated to EXPLAIN parsing (this test also failed 3× on unrelated PR 103706).

CI is re-running on the merged HEAD.

@groeneai

Copy link
Copy Markdown
Collaborator

@alexey-milovidov Investigated. Trying to get name of not a column: A (STID: 2310-3993) is the same root cause as the multiIf-matcher-in-table-function-argument bug, now fixed and merged in #106647 (a0b506e271, merged 2026-06-19 07:46 UTC; Closes #97988, #43199, #100323). No separate PR is needed.

Every CIDB instance of this STID, including the one on this PR (report) and on master (report), is numbers(...multiIf(*, ...)...) (or numbers_mt/remote/format/viewExplain) where the * matcher sits inside a table-function argument. The EXPLAIN/TableFunctionExplain is only the outer wrapper around numbers(...); the crashing inner expression is the matcher-in-argument that #106647 fixes (snapshot the multiIf cond_node so resolveExpressionNode no longer rebinds the matcher into an unprintable ExpressionList).

Verified locally on a debug build, both directions:

So #106686 was not the cause, and master is fixed as of a0b506e271. STID 2310-3993 should stop appearing on runs based on master at/after that commit.

(session cron:clickhouse-worker-slot-0:20260619-073500)

@clickhouse-gh

clickhouse-gh Bot commented Jun 19, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.20% 85.20% +0.00%
Functions 92.60% 92.60% +0.00%
Branches 77.50% 77.50% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 122/126 (96.83%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 1 line(s) · Uncovered code

Full report · Diff report

@alexey-milovidov
alexey-milovidov merged commit ac03059 into master Jun 20, 2026
165 of 166 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix/explain-insert-format-settings-values branch June 20, 2026 16:13
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

4 participants