Skip to content

EXPLAIN SYNTAX: return a single record (default on) - #110479

Merged
alexey-milovidov merged 74 commits into
masterfrom
explain-syntax-single-record
Aug 18, 2026
Merged

alexey-milovidov merged 74 commits into
masterfrom
explain-syntax-single-record

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jul 15, 2026 •

Copy link
Copy Markdown
Member

Closes: #80410
Related: #107925

Changelog category (leave one):

  • Backward Incompatible Change

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

EXPLAIN SYNTAX now returns the reformatted query as a single String record (with embedded newlines) instead of one record per line, so its output is a recoverable single row that is directly usable (for example, SELECT count() FROM (EXPLAIN SYNTAX ...) returns 1). This is controlled by the new single_record option, which defaults to 1; set single_record = 0 to restore the historical one-record-per-line output. Other EXPLAIN kinds (PLAN/PIPELINE/AST) keep their per-line tree output.

Description

Per the discussion on #80410, EXPLAIN SYNTAX is a reformatted, copy-pasteable query, so returning the whole query as a single record is far more usable than splitting it across N rows.

This is done in two commits:

  1. Add a single_record option to EXPLAIN SYNTAX, off by default (no behavior change). The single-record code path already existed (used by EXPLAIN PLAN JSON output); this wires it to the new option for the SYNTAX kind and renames the internal single_line flag to single_record.
  2. Flip the default to single_record = 1. This is backward-incompatible: existing EXPLAIN SYNTAX consumers now see one row instead of N. The oneline option still controls physical-line rendering (default 0, i.e. embedded newlines).

The affected stateless .reference files (including .oldanalyzer.reference variants) were regenerated for the new default. The optimize_syntax_fuse_functions docstring example was switched from FORMAT TSV to FORMAT TSVRaw so its multi-line output stays literal now that the single record carries the embedded newlines.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Workflow [PR]
Sync PR [sync-upstream/pr/110479]

alexey-milovidov and others added 2 commits July 14, 2026 23:30
Add a single_record option to EXPLAIN SYNTAX. When set, the reformatted
query is returned as one multi-line record instead of one record per line.

Off by default, so the existing row-per-line output (and all reference
files that consume it) is unchanged. See issue #80410.

The single-record code path already existed (used by EXPLAIN PLAN json);
this wires it to the new option for the SYNTAX kind and renames the flag
single_line -> single_record, since the SYNTAX buffer is multi-line but
one record. Other EXPLAIN kinds keep one row per line.

Closes #80410

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Make single_record on by default, so EXPLAIN SYNTAX returns the reformatted
query as a single multi-line record instead of one record per line. Set
single_record = 0 to restore the historical row-per-line output.

This is a backward-incompatible change: existing EXPLAIN SYNTAX consumers now
see one row instead of N (the whole reformatted query, with embedded newlines).
The oneline option still controls physical-line rendering and defaults to 0.

Regenerated the affected stateless .reference and .oldanalyzer.reference files
for the new default. Switched the optimize_syntax_fuse_functions docstring
example from FORMAT TSV to FORMAT TSVRaw so its multi-line output stays literal
now that the single record carries the embedded newlines.

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

mintlify Bot commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated (UTC)
ClickHouse-docs 🟢 Ready View Preview Jul 15, 2026, 1:29 AM

…le-record

# Conflicts:
#	tests/queries/0_stateless/02226_analyzer_or_like_combine.oldanalyzer.reference
#	tests/queries/0_stateless/02226_analyzer_or_like_combine.reference
… master

The merge of master brought in the reworked `optimize_or_like_chain`
(#94517), which changed the semantic content of this test. Regenerate
both reference files from the merged binary so the `EXPLAIN SYNTAX`
results are single records with embedded newlines, matching the new
`single_record = 1` default. Verified with clickhouse-test against a
local server: `02226_analyzer_or_like_combine` passes with both the new
and the old analyzer.
@clickhouse-gh

clickhouse-gh Bot commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [287bfc5]

Summary: ✅


AI Review

Summary

This PR changes EXPLAIN SYNTAX to return a single multiline String row by default, adds the single_record / explain_syntax_single_record compatibility and override surfaces, updates the documented behavior, and wires the new surface into the fuzzers. I did not find any remaining correctness, compatibility, or coverage gaps in the current diff after checking the code and the prior review threads.

Final Verdict

✅ Approve

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.90% 86.80% -0.10%
Functions 92.00% 92.00% +0.00%
Branches 79.30% 79.20% -0.10%

Changed lines: Changed C/C++ lines covered: 61/73 (83.56%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-backward-incompatible Pull request with backwards incompatible changes label Jul 15, 2026
The single_record default was hardcoded to true inside the local
QuerySyntaxSettings struct in InterpreterExplainQuery.cpp, so it never
consulted `compatibility`. Old clients that rely on `compatibility`
(rather than editing every EXPLAIN SYNTAX query by hand) would silently
start seeing a single row after upgrading, with no way to opt back into
the pre-26.7 output.

Add a proper `explain_syntax_single_record` setting (mirroring
`explain_query_plan_default`, used the same way for EXPLAIN PLAN),
register it in SettingsChangesHistory.cpp for 26.7, and feed it into
checkAndGetSettings() as the default before any explicit
`single_record = ...` option in the EXPLAIN statement overrides it.
Setting `compatibility` to any version older than 26.7 now restores the
historical row-per-line output, same as for `explain_query_plan_default`.

Addresses review feedback on PR #110479 (single_record couldn't be
reverted via compatibility).
…e_record default

This test's EXPLAIN SYNTAX run_query_tree_passes=1 calls were still
checked in with the pre-26.7 row-per-line output; it was added to
master after the single_record default flip landed on this branch and
was missed by the earlier reference regeneration pass, so CI failed
with a result-differs-with-reference diff on the two EXPLAIN SYNTAX
statements (amd_debug/tsan/asan_ubsan parallel, arm_binary parallel).
alexey-milovidov and others added 2 commits July 16, 2026 16:19
…NTAX output

The AI review and clickhouse-gh[bot] requested a focused regression test for
the upgrade-safe legacy path: the new `explain_syntax_single_record` default
must be restorable via `compatibility`, not only via the `EXPLAIN`-local
`single_record` option that 04517 already covered.

Add to 04517_explain_syntax_single_record.sql:
- SET compatibility = '26.6' (predates the setting) then assert
  count() > 1 from EXPLAIN SYNTAX, proving the pre-26.7 one-record-per-line
  output is restored for old clients that rely on compatibility.
- Assert the EXPLAIN-local single_record = 1 option still wins over
  compatibility when explicitly set.

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

Copy link
Copy Markdown
Member Author

CI failures on e8d2b666 are all unrelated to this PR:

Merged master (clean, no conflicts — verified the EXPLAIN ANALYZE reintroduction #110668 integrates correctly with the reworked checkAndGetSettings; 04517, 04312_explain_analyze, 03759, 02226 all pass locally against the merged binary) and pushed 992b9c64458 for a fresh CI run.

@clickhouse-gh

clickhouse-gh Bot commented Jul 16, 2026

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [992b9c6]

@groeneai

Copy link
Copy Markdown
Collaborator

@alexey-milovidov the Block structure mismatch in JoinStep: [__table3.number, __table3.number] ... different number of columns failure (#110673, STID 0993-386d) already has a fix in flight: #109114 "Fix Block structure mismatch in JoinStep for decorrelated correlated subquery with duplicate column name".

That PR was opened directly off STID 0993-386d (it cites this exact STID and the same duplicate-column JoinStep signature). Root cause: a correlated subquery decorrelated into a join whose source relation carries a column name more than once, e.g.

WITH t AS (SELECT number, * FROM numbers(3))
SELECT *, (SELECT t.number WHERE t.number >= 0) FROM t
SETTINGS correlated_subqueries_default_join_kind = 'right';

The [__table3.number, __table3.number] header in this CI failure is the duplicated-column left side that #109114 fixes. #109114 is open and awaiting review, so nothing further is needed on this PR.

alexey-milovidov and others added 2 commits July 17, 2026 05:10
…ocs example

After this PR flips `EXPLAIN SYNTAX` to return a single `String` record with
embedded newlines by default, the `optimize_syntax_fuse_functions` example on the
autogenerated `docs/reference/settings/session-settings.mdx` page still used
`FORMAT TSV`, which escapes the embedded line breaks as `\n` and no longer renders
the multi-line query shown in the result block. Switch it to `FORMAT TSVRaw` to
match the already-updated `optimize_syntax_fuse_functions` source doc in
`src/Core/Settings.cpp` and the actual output.

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

Copy link
Copy Markdown
Collaborator

Investigated. This recurrence is the non-clonable-source carrier of the 0250-* bucket, and it already has an open fix: #114849 ("Preserve non-clonable sources for deferred set builds"). No new PR needed from me.

The failing query, from fatal.log (query_id 8cb265e3-875f-45b9-9225-399ff6d7c921):

SELECT count() FROM test_2.t_local
WHERE x IN (SELECT x FROM merge('test_2', '') WHERE x < 3)

An AST-fuzzer draw off 04545_analyzer_with_cte_over_distributed.sql, with that test's t_dist fuzzed into merge('test_2', '').

Root cause: ReadFromMerge declares no clone() override, so it inherits IQueryPlanStep::clone, which throws NOT_IMPLEMENTED. FutureSetFromSubquery::buildOrderedSetInplace therefore fails its plan-preserving clone and takes the destructive fallback, consuming source during speculative index analysis. If that speculative pipeline stops without reaching Set::finishInsert, nothing is left for DelayedCreatingSetsStep to build from, and the main pipeline reaches FunctionIn (src/Functions/in.cpp:116) with an unready set.

I confirmed the carrier with an index-pruning discriminator rather than a failure injection, since it distinguishes the destructive path from the preserving one directly:

CREATE TABLE t_local (x UInt64) ENGINE = MergeTree ORDER BY x SETTINGS index_granularity = 8;
INSERT INTO t_local SELECT number FROM numbers(800);

-- clonable source (control)
SELECT trimLeft(explain) FROM (EXPLAIN indexes = 1
  SELECT count() FROM t_local WHERE x IN (SELECT x FROM t_local WHERE x < 3))
WHERE explain ILIKE '%Granules%';

-- non-clonable source
SELECT trimLeft(explain) FROM (EXPLAIN indexes = 1
  SELECT count() FROM t_local WHERE x IN (SELECT x FROM merge(currentDatabase(), '^t_local$') WHERE x < 3))
WHERE explain ILIKE '%Granules%';

On master both report Granules: 1/100, i.e. the merge() source is built in place and destructively. With #114849 applied the control still prunes to 1/100 while the merge() case becomes 100/100: the speculative build is skipped and the source is preserved for the deferred build. That is the behaviour change #114849 describes, and it closes the window this abort comes from.

#114983 ("Report the real error when an in-place IN-set build destroys its source") is the complementary diagnostics change for the shapes that stay destructive, notably GLOBAL IN with an external table.

The Stress test (arm_asan_ubsan) red on a9570909a is unrelated to this PR.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate these unrelated CI failures and provide fixes in separate PRs (or link existing work here):

@groeneai

Copy link
Copy Markdown
Collaborator

Investigated both. They are unrelated to each other and to this PR.

(a) 04513_prewhere_statistics_cost_ordering, MEMORY_LIMIT_EXCEEDED

The runner's own minimizer already named the culprits in the report diagnostics (16/16 failed with them, 66/66 passed without randomization):

--index_granularity_bytes 136878 --min_bytes_for_full_part_storage 282646584
--text_index_posting_list_codec bitpacking --map_serialization_version with_buckets
--map_serialization_version_for_zero_level_parts with_buckets --max_buckets_in_map 64
--map_buckets_strategy constant --map_buckets_min_avg_size 1

The 241 is raised while prefetching the Map column h, in AsynchronousBoundedReadBuffer::prefetch reached from SerializationMap::enumerateStreams through MergeTreeReaderWide::prefetchForAllColumns, which allocates one buffer per substream. The failing run combines bucketed Map serialization at 64 buckets with index_granularity = 35425, so both the substream count and the per-buffer size are far above default. I have not measured which of the two dominates, so I am claiming no more than that stack.

No open PR touches this test, and the only earlier hits are #110695's own flaky-check rounds, so this is the first hit on a PR that does not own it. Not covered by #114150: this test sets optimize_functions_to_subcolumns = 0, so the rewrite that PR gates is not in play, though its finding that bucketed Map serialization is imperfect looks related.

A fix is in progress and I will link the PR here. Intended shape is a per-setting -- Random settings limits: clamp on the specific offenders, not a blanket no-random-merge-tree-settings.

(b) Stateless tests (amd_tsan, flaky check), reported as Server died

The server did not die. It logged continuously through the window and shut down cleanly (Application: Child process exited normally with code 0), with no <Fatal>, no Received signal, no sanitizer record and an empty dmesg.

What happened: the hung check failed (Hung check failed: server is not responding), so clickhouse-test exited with STOP_TESTING_EXIT_CODE (2). functional_tests_results.py has that code in ABORTED_RUN_EXIT_CODES and unconditionally appends a Server died FAIL leaf, so a hung check is reported as a death.

From the artifacts: Failed: 0, Passed: 3872; CurrentMetric_Query rises 6 to 29 across the window and never drains; CurrentMetric_MemoryTracking stays flat near 0.25 GiB; 10 SELECT 1 /*liveness check*/ probes reach the planner and never return, dying with Broken pipe only when teardown closed their sockets.

Two separate defects, neither owned yet:

This leaf alone, with zero real test failures, is 27 hits across 12 PRs and 0 on master for this check in 30 days.

@groeneai

Copy link
Copy Markdown
Collaborator

(a) 04513_prewhere_statistics_cost_ordering 241: measured, and the reader-side half is already in flight as #114072

I promised a per-setting clamp here. Measurement moved the fix, and it turned out to overlap work
I already have open, so I am not opening a second PR for it.

I pulled query_log.tsv.zst from the report and measured all 659 completions of the failing
query (28 failed, 631 passed):

failed (241) passed
RemoteFSPrefetches 3003 min / 3169 mean / 3391 max 12 min / 183 mean / 2597 max
memory_usage 4.66 GiB in all 28 3.24 GiB max
allow_prefetched_read_pool_for_remote_filesystem 0 in all 28 0 in all 631

The chain: map_buckets_min_avg_size is randomized to 1 (default 32), which disables the
small-map guard in SerializationMap::calculateNumberOfBuckets, so a 2-key map takes
constant/max_buckets_in_map and gets 64 buckets instead of 1.
SerializationMap::enumerateStreams then emits a nested Array(Tuple(K, V)) per bucket, about
194 substreams for column h, and MergeTreeReaderWide::prefetchForColumn issues one prefetch,
each with its own read buffer, per substream. 4.66 GiB / 1.64 MiB is 2910 buffers; 3003 to 3391
were issued.

filesystem_prefetches_limit does not stop it because
MergeTreeReaderWide::prefetchForAllColumns compares it against the column count (2), not the
prefetch count. That specific defect is what my open #114072 fixes: it counts the prefetches
actually issued and stops at the limit, at both issuance sites. It is not merged, so it was not in
this build.

One thing #114072 does not cover, and I would rather flag it than quietly widen that PR: its bound
is per reader. This run left filesystem_prefetches_limit at the default 200, one reader
enumerates only ~194 substreams, and the 3169 prefetches are ~16 concurrent readers. So at the
default limit the bound never engages here; it engages only when the limit is randomized below
~194. Admission is per reader, exhaustion is query-wide. The plain ReadPool also has no
filesystem_prefetch_max_memory_usage budget at all (only MergeTreePrefetchedReadPool reads
that setting), and the run above never constructed the prefetched pool.

Closing that gap needs a policy decision I do not want to make unilaterally, since each option is
user-visible:

  1. Shared query-level admission, all-or-nothing. Preserves the contract
    03394_filesystem_prefetches_limit.reference pins (10 columns at limit 5 records 0
    prefetches, not 5), but a wide-Map reader can then be denied prefetching entirely under a
    shared budget.
  2. Shared query-level admission, partial. Bounds memory smoothly, changes that tested contract.
  3. Memory-based admission for the plain ReadPool, giving it the budget concept it currently
    lacks.

There is no shared cross-reader prefetch state today to extend: MergeTreeReaderSettings is
copied per reader, so any of these is new plumbing.

If you would rather not touch the reader for this at all, the cheap alternative is a one-line
test clamp, -- Random settings limits: map_buckets_min_avg_size=(32, None), which restores the
documented small-map guard and neutralizes the whole randomized set the minimizer reported. I did
not take it on its own because it leaves the memory blow-up reachable with non-default MergeTree
settings.

Happy to implement whichever of 1-3 you prefer. Note map_serialization_version defaults to
basic and map_buckets_min_avg_size to 32, so a 2-key map gets one bucket by default; reaching
this needs non-default settings, which is why I have not filed it as a separate bug.

# Conflicts:
#	tests/queries/0_stateless/04032_and_comparison_filter_optimization_2.reference
@groeneai

Copy link
Copy Markdown
Collaborator

Root-caused the (b) half above, the Stateless tests (amd_tsan, flaky check) stall where queries were planned and never executed: #115030.

The hung check's verdict was true. SystemLogQueue::push appends to a std::vector<LogElement> while holding the queue mutex, so crossing capacity reallocates inside the critical section, and libc++ relocates with std::move_if_noexcept, which deep-copies every element when the type is not nothrow-move-constructible. QueryLogElement was not, because Poco::Net::SocketAddress declared copy operations only and its copy heap-allocates a SocketAddressImpl; ClientInfo carries three of those. On this run that held the query_log mutex for 177 of 181 seconds with 31 threads blocked in the same push, including all 10 liveness probes, which is why the probe never got an answer.

The measurement came from the job's own trace_log.tsv symbolized against the exact CI binary, so no new diagnostics were needed. One reallocation of 8192 elements goes from 32769 allocations to 1.

One mechanism proven on one artifact, not a claim about every Server died report. The mislabel half is separate and still tracked.

@groeneai

Copy link
Copy Markdown
Collaborator

Fixing PR for the mislabel half of (b): #115080.

One correction to what I wrote above. I said I would extend #112952; I did not. That PR gates
its new branch on runner_exit_code in KILLED_BY_SIGNAL_EXIT_CODES and on s.failed == 0, so
exit code 2 deliberately falls through to the old branch. #115080 is a successor instead: it adds
HUNG_CHECK_EXIT_CODE = 5 and a Server liveness check failed leaf, so a failed probe stops
being reported as a death at all. The two PRs touch the same region of
functional_tests_results.py, so whichever merges second needs a rebase.

The stall half is unchanged and still open: the server accepted and authenticated queries without
executing them for about 3.5 minutes. That is a real defect and I am working it separately, not
covered by #115080, which only stops the harness from calling it a death.

@clickhouse-gh

clickhouse-gh Bot commented Aug 18, 2026

Copy link
Copy Markdown
Contributor

Dear @Fgrtue, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is just a purity/presentation thing, not a big deal.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 18, 2026
Merged via the queue into master with commit e16cba0 Aug 18, 2026
181 checks passed
@alexey-milovidov
alexey-milovidov deleted the explain-syntax-single-record branch August 18, 2026 19:35
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 18, 2026
alexey-milovidov added a commit that referenced this pull request Aug 20, 2026
`EXPLAIN SYNTAX` now returns the formatted query as a single record (#110479,
merged into `master` on 2026-08-18), so the dump appears as one `TSV` row with
escaped newlines instead of one row per line. Only the reference of
`04823_explain_syntax_nested_view_throwing_table_function_legacy` was still in
the old shape; verified locally that the test passes with the updated one.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-backward-incompatible Pull request with backwards incompatible changes 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.

EXPLAIN SYNTAX should return a single multi-line record instead of many single-line records

5 participants