Skip to content

Implement real-time previews of query results - #115988

Open
alexey-milovidov wants to merge 116 commits into
masterfrom
query-result-previews
Open

alexey-milovidov wants to merge 116 commits into
masterfrom
query-result-previews

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 23, 2026 •

Copy link
Copy Markdown
Member

Closes: #115980

Implements real-time previews of query results. While a long-running query of a simple shape is running, the accumulating processors (aggregation, and top-N sorting) periodically emit a snapshot of the intermediate result. The snapshot is processed by the rest of the query pipeline like ordinary data - so HAVING, projection expressions, ORDER BY, LIMIT, and OFFSET apply to it - and is delivered to the client as a preview that fully replaces the previous one:

  • over the native protocol as a new PreviewData packet (revision 54498), rendered by clickhouse-client (and clickhouse-local) as a live table below the progress bar, redrawn in place with muted colors;
  • over HTTP as preview packets of framing formats, each carrying a complete self-contained document of the output format;
  • in the Web UI, which renders preview packets as a visually muted table that the real result replaces.

The design follows the issue and the lessons of the two previous attempts:

  • Inside the pipeline a preview is an ordinary chunk annotated with a ChunkInfo (QueryResultPreviewInfo), flowing through the same continuation of the query pipeline - no mirrored "partial result" pipeline. Every stateful processor on the way treats it out of band: PartialSortingTransform sorts it standalone (without touching the shared top-K threshold), MergeSortingTransform and MergingSortedTransform pass it along without mixing it into the accumulated state, LimitTransform/OffsetTransform cut it without advancing rows_read, and LimitsCheckingTransform, the query result cache, extremes, and the runtime dataflow statistics skip it entirely, so previews never affect the result, result limits, quotas, or result_rows/result_bytes.
  • Emitters are fail-close: they stay dormant unless QueryPipeline::complete proves that every processor between the emitter and the output format declares supportsQueryResultPreviews and the format can deliver previews to the client. Any unknown stateful processor (LIMIT BY, WITH FILL, joins, INSERT SELECT, ...) keeps them dormant.
  • Stateful operators apply to each preview standalone, because a preview is a complete small intermediate result: DISTINCT deduplicates the preview alone with a fresh set (never touching the accumulated set in either direction), and window functions are computed over the preview alone by a fresh one-shot WindowTransform - so bar(x, 0, max(x) OVER (), 100) draws bars scaled by the maximum of the intermediate result, converging to the final scale.
  • The aggregation snapshot is non-destructive, unlike the previous attempt that hard-coded final = true (Distributed: Bad cast from type DB::ColumnVector<unsigned long> to DB::ColumnAggregateFunction. #55864): the emitting thread deep-copies the aggregate function states (a serialize + deserialize round trip into a snapshot arena) from the per-thread hash tables under per-participant locks, merges them with a dedicated merge-only Aggregator, and finalizes only the copies. Previews are emitted only for the standard final aggregation (never for WithMergeableState stages, TOTALS/ROLLUP/CUBE, grouping sets, overflow rows, in-order, sharded, or spilled aggregation), and only while the state is small: single-level and below the query_result_previews_max_result_rows/query_result_previews_max_result_bytes thresholds. When query_result_previews is enabled, it takes priority over the adaptive aggregation algorithm.
  • A sorting with a small enough LIMIT (at most query_result_previews_max_result_rows) emits its own previews: the accumulated top-N candidates of all the streams are merged and cut to the limit.
  • On the wire a preview travels as a distinct packet type (like Totals/Extremes), never as an in-band Data packet, so a client that does not know previews can never mistake preview rows for the result; the server force-disables the setting for clients below revision 54498. BlockInfo gets an in-memory-only is_preview field (not serialized).
  • The frequency of previews is controlled by query_result_previews_min_interval_ms (default one second), query_result_previews_min_rows, and query_result_previews_min_bytes, checked on every processed block.
  • Distributed queries: query_result_previews is force-disabled for the remote parts (merging per-shard previews on the initiator is future work), and the initiator defensively drops PreviewData packets from shards.

Changelog category (leave one):

  • Experimental Feature

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

Real-time previews of query results (the experimental setting query_result_previews): while a long-running aggregation or top-N sorting is running, the server periodically sends small snapshots of the intermediate result, processed by the rest of the query pipeline like ordinary data. clickhouse-client renders them as a live table below the progress bar, framing formats carry them as preview packets over HTTP, and the Web UI shows them as a muted table that the real result replaces. Closes #115980.

Documentation entry for user-facing changes

  • Documentation is written (the query_result_previews* settings, the preview packet kind in the framing formats documentation, and the PreviewData packet in the native protocol specification)

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

While a long-running query of a simple shape is running, the accumulating
processors (aggregation, and sorting with a small enough `LIMIT`)
periodically emit a snapshot of the intermediate result, annotated as a
preview. The snapshot is processed by the rest of the query pipeline like
ordinary data (`HAVING`, projection expressions, `ORDER BY`, `LIMIT` apply
to it), never affects the result, the limits, the quotas, or the counters,
and each preview fully replaces the previous one. Emitters stay dormant
unless every processor between them and the output format supports preview
chunks and the format can deliver previews.

Previews are delivered over the native protocol as a new `PreviewData`
packet (protocol revision 54493), rendered by `clickhouse-client` and
`clickhouse-local` as a live muted table below the progress bar; over HTTP
as `preview` packets of framing formats, each a self-contained document of
the output format; and the Web UI renders them as a muted table that the
real result replaces.

Enabled by the experimental setting `query_result_previews`, with the
frequency and state-size thresholds in the `query_result_previews_*`
settings.

Closes #115980

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

mintlify Bot commented Aug 23, 2026 •

Copy link
Copy Markdown
Contributor

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

Project Status Preview Updated
ClickHouse-docs 🟢 Ready View Preview Nov 24, 2026, 9:40 AM

@clickhouse-gh

clickhouse-gh Bot commented Aug 23, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ca9b6f9]

Summary: ❌

job_name test_name status info comment
Performance Comparison (arm_release, master_head, 4/6) FAIL Performance dashboard
window_transform #6 FAIL dashboard
window_transform #7 FAIL dashboard
Performance Comparison (arm_release, master_head, 6/6) FAIL Performance dashboard
window_functions_sliding_frames #5 FAIL dashboard
iceberg_suite_s3_synthio_read #21 unstable query history
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

Adds experimental query result previews through aggregation/sorting snapshots, native and framed HTTP packets, and client/Web UI rendering. One native protocol exception path needs correction before merge. The latest Praktika reports show 15,416 passed tests and no failures.

Consumer coverage included native TCP and local connections, framed HTTP formatters, scalar subqueries, gRPC, Prometheus, remote-shard handling, and downstream sorting, merging, distinct, window, expression/filter, limit/offset, squashing, cache and statistics processors. Existing review replies and fixes were checked against the current code.

Findings

❌ Blockers

  • src/Server/TCPHandler.cpp:2115: sendPreviewData buffers a packet envelope and calls NativeWriter::write without the raw/compressed-buffer rollback used by sendData. Serialization can throw while materializing a constant preview column. The outer handler then appends logs/Exception and preserves the connection, leaving the client decoding an unfinished preview instead of receiving the error. A small aggregation preview projecting a large constant string can reach this through MEMORY_LIMIT_EXCEEDED, even when the final HAVING result is empty. Share the guarded packet writer/rollback; close the connection if a partial packet cannot be recovered. This finding is source-traced; no local binary was available.
Tests
  • ⚠️ Add a native regression that forces preview serialization to throw and verifies delivery of a complete exception and safe connection reuse, or deliberate connection closure when recovery is impossible. Existing framed-format error tests do not cover this writer.
Final Verdict

Status: ❌ Block

Preserve packet boundaries on failed native preview serialization and cover the failure path.

alexey-milovidov and others added 3 commits August 23, 2026 17:06
The style check requires the `-WithMemoryTracking` container alternatives
in `src/QueryPipeline`.

Co-Authored-By: Claude Fable 5 <[email protected]>
The `applyColumnColors` pass (bars, heatmaps, categorical colors) now runs
on every preview frame, like it does for the real result and for the
history-restore paths. Numeric bars use the displayed preview values as the
fallback range, since the server extremes are unavailable mid-query, and the
user-selected color modes survive the per-frame table rebuild.

Co-Authored-By: Claude Fable 5 <[email protected]>
Stateful operators apply to each preview standalone, because a preview is a
complete small intermediate result:

- `DISTINCT` deduplicates the preview alone with a fresh set (in both
  `DistinctTransform` and `DistinctSortedStreamTransform`), never touching
  the accumulated set in either direction - the set must not filter preview
  rows, and preview rows must not poison the set and filter real rows out of
  the result.

- Window functions are computed over the preview alone by a fresh one-shot
  `WindowTransform` driven over a single-chunk pipeline, so for example
  `bar(x, 0, max(x) OVER (), 100)` draws bars scaled by the maximum of the
  intermediate result, converging to the final scale as the previews
  converge. The window calculation state of the main stream is not involved.

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread src/Client/ClientBase.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 23, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing ca9b6f9ee with master 583909bc1 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: object file sizes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes ⚠️

1418 object files changed (+1.44 MiB total), 2 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/Aggregator.cpp.o 33.73 MiB 34.22 MiB +502.21 KiB (+1.45%)
src/CMakeFiles/dbms.dir/Processors/Transforms/DistinctTransform.cpp.o 131.78 KiB 283.25 KiB +151.46 KiB (+114.94%)
src/CMakeFiles/dbms.dir/Client/QueryResultPreviewDisplay.cpp.o new 109.31 KiB +109.31 KiB
src/CMakeFiles/dbms.dir/Processors/QueryResultPreview.cpp.o new 83.61 KiB +83.61 KiB
src/CMakeFiles/dbms.dir/Processors/Transforms/WindowTransform.cpp.o 172.43 KiB 240.07 KiB +67.64 KiB (+39.23%)
src/CMakeFiles/dbms.dir/Interpreters/executeQuery.cpp.o 1.19 MiB 1.22 MiB +25.67 KiB (+2.10%)
src/CMakeFiles/dbms.dir/Processors/Transforms/AggregatingTransform.cpp.o 690.10 KiB 714.31 KiB +24.21 KiB (+3.51%)
src/CMakeFiles/dbms.dir/QueryPipeline/QueryPipeline.cpp.o 309.91 KiB 329.44 KiB +19.54 KiB (+6.30%)
src/CMakeFiles/dbms.dir/Processors/Transforms/MergeSortingTransform.cpp.o 673.20 KiB 692.08 KiB +18.88 KiB (+2.80%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

2850 translation units recompiled, 12810 s compile time in total, 2848 of them have a recent master baseline.

Job report

alexey-milovidov and others added 5 commits August 23, 2026 21:43
`CLOCK_MONOTONIC_COARSE` is a Linux extension; `Common/Stopwatch.h` (via
`base/time.h`) provides the fallback for other platforms, fixing the Darwin
builds.

Co-Authored-By: Claude Fable 5 <[email protected]>
A preview round used to deep-copy every aggregate state of every thread
through a `serialize` + `deserialize` round trip into a snapshot arena, turn
the copies into one not-finalized chunk per thread, and only then merge those
chunks with a dedicated merge-only `Aggregator`. The copy is pure overhead:
the round has to merge the per-thread states anyway, and `IAggregateFunction::merge`
only reads the source state, so it can read the live one directly.

The walk now merges each participant into one private `AggregatedDataVariants`
under that participant's lock, and finalizes it into the preview chunk. The
merge-only `Aggregator` is gone with the copies.

The cost of a round matters because it, not `query_result_previews_min_interval_ms`,
is what paces the previews: the emitter runs rounds back to back, and a preview
reaches the client only when a round completes. For

    SELECT AdvEngineID, count(), uniq(UserID), uniq(*) AS u FROM hits
    GROUP BY ALL ORDER BY count() DESC LIMIT 100

over 100 million rows with `max_threads = 64`, where two `uniq` states per key
per thread saturate at 65536 elements, the first preview used to appear after
4.6 to 11.5 seconds; it now appears after 2.8 to 3.9 seconds, and a query that
emitted 6 previews emits 11. Sampling `system.stack_trace` over the running
query shows the remaining time of a round is no longer the state copy (62% of
the samples before, gone now) but waiting for the participants' locks (24%
before, 68% now), each held for a whole `executeOnBlock`.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The `query_result_previews_max_result_bytes` threshold was compared with the
bytes used by the aggregation arenas, which is almost nothing for the states
that make a preview expensive: a `uniq`, a `uniqExact` or a `groupArray` keeps
its data in containers of its own and leaves only a few dozen bytes per state
in the arena. For

    SELECT AdvEngineID, count(), uniq(UserID), uniq(*) FROM hits GROUP BY ALL

with 64 threads the arenas hold 0.1 MiB while the states hold 106 MiB, so the
threshold never fired and every round merged 106 MiB.

The threshold is now compared with `Aggregator::getStateMemoryUsage` - the
aggregation's own memory tracker, the one that also decides when to spill to
disk, so it accounts for everything the states allocate wherever they allocate
it. Since the measure is now two orders of magnitude larger for such queries,
the default goes from 1 MiB to 64 MiB, which is about half a second of merging
in the worst case measured.

The row threshold had the mirror-image problem: it added up the keys of every
thread, so it really limited the keys per thread to
`query_result_previews_max_result_rows / max_threads` - an aggregation of 1000
keys over 64 threads was already over the default. It now counts the keys of
the merged snapshot, which is what the preview actually contains, with a
per-participant check before the merge so that a participant that is over the
threshold on its own settles it without doing the work.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Both sides added to `DistinctTransform`: master the `DeduplicationAbandonController`
that gives up deduplicating mostly-unique input, and the constant-NULL-key
short-circuit; this branch the standalone deduplication of preview chunks.

In `transform` the abandon check goes first - abandoned deduplication passes
every chunk through, and a preview deduplicated while the result is not would
not match the result - and the preview branch goes before the constant-NULL-key
short-circuit, which stops the input and so must never be reached by a preview.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
alexey-milovidov and others added 4 commits August 27, 2026 00:17
`src/Common/LicenseChecker.cpp`, `src/Common/LicenseChecker.h` and the editor
backup files `src/Core/Settings.cpp_`, `src/AggregateFunctions/SingleValueData.cpp_`,
`src/AggregateFunctions/SingleValueData.h_` were added by mistake and are
unrelated to query result previews. The stale `LicenseChecker.cpp` also broke the
style check, because it references a `license_key` server setting that does not
exist here.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…opping it

`clickhouse-gh` pointed out two ways a stale preview could stay in front of the
user, both because an empty preview was silently dropped instead of replacing
the previous one:

- `FilterTransform` inherits `ISimpleTransform(..., skip_empty_chunks = true)`,
  so a preview that `HAVING` filters down to zero rows was swallowed and the
  previous preview stayed as the last one the client saw. The transform now
  gives such a preview the columns of the output header, so the empty preview
  is delivered.
- A framing format wrote nothing for a payload with no bytes, which for a
  format like `JSONCompactEachRow` is exactly what an empty preview serializes
  to, so the `preview` packet never reached the client. An empty payload of the
  `Preview` kind is now emitted as an empty packet.
- `ClientBase::onPreviewData` renders an empty preview by erasing the painted
  region and forgetting the cached lines, and previews are ignored (and no
  longer repainted by `onProfileEvents`) once the real output has started - the
  second finding: the flush callback cleared the painted region but kept the
  cached lines, so a later `ProfileEvents` packet could repaint a stale preview
  below the progress bar.

The framing test covers a preview emptied by `HAVING`.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Comment thread src/Processors/LimitTransform.cpp Resolved
Comment thread src/Processors/LimitTransform.cpp Resolved
Comment thread src/Processors/OffsetTransform.cpp Resolved
Comment thread src/Client/ClientBase.cpp Resolved
…, keep the client preview state in sync

- `LIMIT ... WITH TIES` no longer declares support for query result previews: the tie boundary is
  decided by the rows that follow the limit in the real result, which a preview does not have, so
  the fail-close activation keeps the emitters dormant for such a pipeline.
- `LimitTransform` and `OffsetTransform` forward an emptied preview instead of dropping it: an
  empty preview is a preview state of its own that tells the client to clear the previous rows.
- `WindowTransform` re-emits an empty preview computed by the standalone window pipeline instead
  of returning early.
- `ClientBase::onPreviewData` keeps updating the cached preview while the progress table is
  toggled on, and only skips the repaint, so toggling the table back off cannot resurrect a
  preview from before the toggle.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Addressed the five findings of the AI review (see the per-thread replies) and fixed the flaky 05037_query_result_previews_framing.

The flake was in the the state-size threshold in bytes stops previews step: its query used ORDER BY k LIMIT 3, and a sorting with a limit is a preview emitter of its own whose state (the top-N candidates after the partial sort) stays far below any byte threshold, so it kept emitting previews after the aggregation had correctly stopped - the assertion therefore depended on timing. The step now uses a query with no sorting (SELECT number % 4 AS k, uniqExact(number) AS u FROM numbers(2000000) GROUP BY k), where the aggregation is the only emitter and its state is unambiguously above 1 KiB and below 1 GiB; the two runs are compared as sets since there is no ORDER BY.

Verified locally against a server built from this branch: 05037_query_result_previews_framing passes, and 05038_query_result_previews_correctness fails only on its remote('127.0.0.{1,2}') step, which cannot connect on a local server that does not listen on port 9000.

Comment thread src/Client/ClientBase.cpp Resolved
# Conflicts:
#	src/Processors/QueryPlan/AggregatingStep.cpp
… queries, do not erase the progress table

Two findings of the AI review:

- `query_result_previews` is initiator-only, but only the per-shard `Settings`
  packet was cleared: a forwarded query *text* keeping
  `SETTINGS query_result_previews = 1` could re-enable preview emission on the
  shards, whose `PreviewData` packets the initiator drops anyway, and the sibling
  `query_result_previews_*` thresholds were forwarded as well (an older shard in a
  rolling upgrade rejects them with `UNKNOWN_SETTING`). The reset now lives in
  `stripInitiatorOnlySettings` and covers the whole setting family, and the names
  are listed in `initiator_only_setting_names`, so
  `stripInitiatorOnlySettingsFromQuery` removes them from the forwarded query text
  too. `DDLLogEntry` strips them for the same reason.

- An empty preview arriving while the progress table is toggled on called
  `clearPreviewOutput`, which sends `\r` and `CLEAR_TO_END_OF_SCREEN` and erased
  the progress table out from under the user when a preview had been painted
  before the toggle. While the table owns that band of the terminal the empty
  preview is now a state-only reset.

New test `05054_query_result_previews_not_forwarded` runs a `remote(...)` query
with previews enabled by the query context and by an inline `SETTINGS` clause and
asserts, via `system.query_log`, that the secondary queries carry neither any
`query_result_previews*` setting nor a query text mentioning one.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (the branch was ~1100 commits behind; one conflict in AggregatingStep.cpp, where master removed the sharded-aggregation branch of adaptive_rejection - the preview clause is kept on top of the new shape) and addressed both Majors of the AI review in bfa94c711bbc:

  • The preview settings are initiator-only, but only the per-shard Settings packet was cleared. The reset now lives in stripInitiatorOnlySettings and covers the whole family (query_result_previews and the five query_result_previews_* thresholds), and the names are listed in initiator_only_setting_names, so stripInitiatorOnlySettingsFromQuery also removes them from a forwarded query text. DDLLogEntry strips them as well, for the same rolling-upgrade (UNKNOWN_SETTING) reason.
  • An empty preview received while the progress table is toggled on no longer erases the terminal band the table owns; it is a state-only reset now.

Also added the requested distributed test, 05054_query_result_previews_not_forwarded: a remote(...) query with previews enabled by the query context and by an inline SETTINGS clause, asserting through system.query_log that the secondary queries carry neither a query_result_previews* setting nor a query text mentioning one.

Verified locally against a server built from this branch: 05037_query_result_previews_framing, 05038_query_result_previews_correctness and the new 05054_query_result_previews_not_forwarded all pass (this time on a server listening on the default port, so the remote('127.0.0.{1,2}') steps run for real).

The two red integration shards on the previous commit (amd_asan_ubsan, db disk, old analyzer, 5/6 and 6/6) failed at the job level (Timeout / ERROR) with no individual test failures; the fresh run on the merged commit will show whether anything real is left.

alexey-milovidov and others added 2 commits November 6, 2026 17:00
Resolve conflicts: master took protocol revision 54496 for
`PROFILE_EVENTS_IN_SECONDARY_INSERT`, so `QUERY_RESULT_PREVIEWS` moves to
54497 and `DBMS_TCP_PROTOCOL_VERSION` is bumped to 54497; the native protocol
spec is updated accordingly. Keep both `sendPreviewData` and
`shouldSendProfileEvents` in `TCPHandler`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Master changed `WindowTransform` to take `VectorWithMemoryTracking<WindowFunctionDescription>`,
so the copy of the functions kept for previews must use the same type.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	src/Processors/Transforms/WindowTransform.cpp
#	src/Processors/Transforms/WindowTransform.h
alexey-milovidov and others added 2 commits November 11, 2026 02:56
`AggregateWindowFunctionRecalculate` evaluates a whole batch without checking
cancellation, and with a moving frame it re-adds the whole frame on each row, so
cancelling a query (or the one-shot transform computing a query result preview)
waited for the entire block, e.g. 65536 rows of `quantileExact` over 50000-row
frames. Now the row walk estimates the rows the aggregate functions add to their
states and evaluates the batch once it exceeds about a million rows, so the
per-row cancellation check runs between the batches. Frames with an unbounded
start add only the rows the frame end advanced by and keep full batches.

This addresses the review comment on `WindowTransform.cpp` and the
`05449_query_result_previews_window_cancellation` timeouts in the flaky check:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=115988&sha=60ab092f5c484e56b301de92e910d59d19ebb7c1&name_0=PR&name_1=Stateless%20tests%20%28amd_asan_ubsan%2C%20flaky%20check%29
#115988

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 2 commits November 12, 2026 12:29
# Conflicts:
#	src/Processors/Transforms/WindowTransform.cpp
`AggregateState` charged only the rows added to the state, so a run of
finalizations that add few rows each never reached a cancellation check:
the growing prefix of a moving frame (the first 50001 frames of
`quantileExact(c) OVER (ORDER BY k ROWS BETWEEN 50000 PRECEDING AND CURRENT ROW)`
add one row each but select over up to 50001 rows), or any frame with
`UNBOUNDED PRECEDING`. `KILL QUERY` then waited for the whole batch, which
made `05449_query_result_previews_window_cancellation` run for more than
180 s in the flaky check.

`insertResultInto` now also charges the number of rows in the state, capped
at 1/64 of the budget per call, so cheap finalizations of large frames
(e.g. `sum`) check the time limit at most once per 64 rows. Locally, with
the reproduction from the review, `KILL QUERY ... SYNC` returns in about
0.11 s both during the prefix and with `UNBOUNDED PRECEDING`.

Addresses the review: #115988 (comment)
CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=115988&sha=6cd5ef1012c2736e25fd4040ece931e9e8a6609f&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20flaky%20check%29

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	src/Interpreters/Aggregator.h
#	src/Processors/QueryPlan/SortingStep.h
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master in 0ddb54d. Resolved two additive conflicts by keeping both sides: the declarations in Aggregator.h (the preview snapshot methods plus master's singleLevelPartitionChunkEndsForFanOut) and the includes in SortingStep.h. The merged tree builds, and the PR's stateless tests pass locally.

Red checks on cb8949e:

  • La Casa Del Dolor (amd_tsan): a data race on session_timezone in the client. onTimezoneUpdate writes it on the main thread while the INSERT ... VALUES parsing pipeline reads it in DateLUT::instance. This race already exists on master (the TimezoneUpdate handling during INSERT predates this PR), and Apply the server's TimezoneUpdate before clickhouse-client parses the data of input() and RETURNING #131177 fixes it. That fix is now included through this merge.
  • Performance Comparison (arm_release, ...): all shards stopped before running any tests: test selection unavailable: GitHub API 403 Client Error: rate limit exceeded. This is an infrastructure failure, and a fresh run should clear it.

alexey-milovidov and others added 2 commits November 18, 2026 09:58
Master took protocol revision 54497 for
`DBMS_MIN_REVISION_WITH_CURRENT_AGGREGATION_VARIANT_SELECTION_METHOD`, so
`DBMS_MIN_REVISION_WITH_QUERY_RESULT_PREVIEWS` and `DBMS_TCP_PROTOCOL_VERSION`
move to 54498 (protocol docs updated accordingly).

`IMergingTransformBase::prepareInitializeInputs` was refactored on master into
`tryInitializeInput`; the query result preview interception moved there.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…int` after merging master

Master changed `AggregatedDataVariants::init` to take an optional `SizeHint`
instead of a plain number of keys.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master in a18c43d:

  • master took protocol revision 54497 for DBMS_MIN_REVISION_WITH_CURRENT_AGGREGATION_VARIANT_SELECTION_METHOD, so DBMS_MIN_REVISION_WITH_QUERY_RESULT_PREVIEWS and DBMS_TCP_PROTOCOL_VERSION are now 54498. The protocol docs and the PR description are updated to match.
  • master split IMergingTransformBase::prepareInitializeInputs out into tryInitializeInput, so the preview interception now lives there.
  • UserDefinedExecutableFunctionFactory.cpp / TCPHandler.h: kept master's [[nodiscard]] annotations and added the PR's hasObservableSideEffects / sendPreviewData.
  • ead8200: adapted the preview snapshot to the new AggregatedDataVariants::SizeHint argument of init.

The clickhouse binary builds. The preview stateless tests pass locally, except those that need the CI test config (system.query_log, the executable UDF).

# Conflicts:
#	src/Interpreters/DDLTask.cpp
#	src/WindowFunctions/Aggregate/AggregateState.cpp
alexey-milovidov and others added 2 commits November 24, 2026 09:01
Conflicts:
- `ClusterProxy/executeQuery.cpp`: kept both additions to `initiator_only_setting_names`.
- `WindowFunctions/Aggregate`: master moved `evaluate` of `AggregateWindowFunctionPrefix` and
  `AggregateWindowFunctionRecalculate` into the class definitions and replaced `makeTimeLimitCheck`
  with `makeCancellationCheck`. Took master's structure and re-applied the `frame_rows` argument
  of `AggregateState::insertResultInto`, which charges finalizations to the cancellation budget.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
The `settings_changes_history` style check failed: master is at 26.12 now, and the six
`query_result_previews*` settings still had their history record under 26.11.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=115988&sha=e2060de60e11bd0230bf4f868a5bf94a2a644cce&name_0=PR&name_1=Style%20check
#115988

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

Copy link
Copy Markdown
Member Author

🕵 Merged master in 1f012c3 and fixed the Style check red in ca9b6f9.

  • Conflicts in src/WindowFunctions/Aggregate: master moved evaluate of AggregateWindowFunctionPrefix and AggregateWindowFunctionRecalculate into the class definitions and replaced makeTimeLimitCheck with makeCancellationCheck. I took the structure from master and re-applied the frame_rows argument of AggregateState::insertResultInto, which charges finalizations to the cancellation budget.
  • ClusterProxy/executeQuery.cpp: kept both additions to initiator_only_setting_names (the preview settings and distributed_group_by_top_k).
  • settings_changes_history: master is at 26.12 now, so the history records of the six query_result_previews* settings moved from 26.11 to 26.12.

Verification: every translation unit changed by this PR compiles against the merged tree (Aggregator.cpp was checked with -fsyntax-only). I did not link clickhouse or run the stateless tests locally this time, so the tests are verified by CI only.

Comment thread src/Server/TCPHandler.cpp
writeVarUInt(Protocol::Server::PreviewData, *out);
writeStringBinary("", *out);

state.block_out->write(block);

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.

[Blocker] Preserve native packet boundaries when preview serialization throws

NativeWriter::write can throw after the PreviewData envelope and part of the block have been buffered. For example, NativeWriter::writeData materializes ColumnConst columns; a large constant string projected over a small aggregation preview can raise MEMORY_LIMIT_EXCEEDED there. This writer omits the rollback of both out and state.maybe_compressed_out that sendData performs for exactly this failure.

The outer handler then sends logs/the Exception packet on the same connection and preserves it. The client is still decoding the unfinished preview, so it reads those bytes as block data or waits for missing bytes instead of receiving the exception.

A source-traced triggering query on a preview-capable native connection is:

SELECT repeat('x', 1048576), c
FROM
(
    SELECT number % 1000 AS k, count() AS c
    FROM numbers(10000000)
    GROUP BY k
    HAVING c < 1000
)
SETTINGS max_threads = 1, max_block_size = 65536,
    group_by_two_level_threshold = 0,
    group_by_two_level_threshold_bytes = 0,
    query_result_previews = 1,
    query_result_previews_min_interval_ms = 0,
    max_memory_usage = 268435456;

The first preview has 1000 rows, so native serialization expands the constant to about 1 GiB; the final result is empty. I could not execute this query in this job because no binary is available.

Please share sendData's guarded packet-writing/rollback logic with this path, and add a native regression that forces a serialization exception and verifies that the client receives a complete exception rather than a truncated preview. If a partial packet has already been flushed, terminate the connection instead of appending another packet.

This branch was successfully deployed

1 active deployment
staging - docs — ca9b6f9e Deployed Nov 24, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. pr-experimental Experimental Feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Real-time previews of query results

2 participants