Repository navigation
Implement real-time previews of query results - #115988
alexey-milovidov wants to merge 116 commits into
Conversation
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]>
|
Preview deployment for your docs. Learn more about Mintlify Previews.
|
|
Workflow [PR], commit [ca9b6f9] Summary: ❌
AI ReviewSummaryAdds 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
Tests
Final VerdictStatus: ❌ Block Preserve packet boundaries on failed native preview serialization and cover the failure path. |
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]>
Build profile diff (arm_release)Comparing Binary sizes
The official master build is compiled with Object file sizes
|
| 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.
`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]>
…y-result-previews
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]>
`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]>
…, 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.
|
🕵 Addressed the five findings of the AI review (see the per-thread replies) and fixed the flaky The flake was in the Verified locally against a server built from this branch: |
# 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.
|
🕵 Merged
Also added the requested distributed test, Verified locally against a server built from this branch: The two red integration shards on the previous commit ( |
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
# Conflicts: # src/Processors/Formats/IOutputFormat.h
Fixes the style check: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=115988&sha=00d1dde12d35bd816fe39f5d72aea81cfedb9328&name_0=PR&name_1=Style%20check PR: #115988 Co-Authored-By: Claude Opus 5.5 <[email protected]>
`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]>
# 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
|
🕵 Merged Red checks on cb8949e:
|
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]>
|
🕵 Merged
The |
# Conflicts: # src/Interpreters/DDLTask.cpp # src/WindowFunctions/Aggregate/AggregateState.cpp
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]>
|
🕵 Merged
Verification: every translation unit changed by this PR compiles against the merged tree ( |
| writeVarUInt(Protocol::Server::PreviewData, *out); | ||
| writeStringBinary("", *out); | ||
|
|
||
| state.block_out->write(block); |
There was a problem hiding this comment.
[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.
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, andOFFSETapply to it - and is delivered to the client as a preview that fully replaces the previous one:PreviewDatapacket (revision54498), rendered byclickhouse-client(andclickhouse-local) as a live table below the progress bar, redrawn in place with muted colors;previewpackets of framing formats, each carrying a complete self-contained document of the output format;previewpackets as a visually muted table that the real result replaces.The design follows the issue and the lessons of the two previous attempts:
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:PartialSortingTransformsorts it standalone (without touching the shared top-K threshold),MergeSortingTransformandMergingSortedTransformpass it along without mixing it into the accumulated state,LimitTransform/OffsetTransformcut it without advancingrows_read, andLimitsCheckingTransform, the query result cache, extremes, and the runtime dataflow statistics skip it entirely, so previews never affect the result, result limits, quotas, orresult_rows/result_bytes.QueryPipeline::completeproves that every processor between the emitter and the output format declaressupportsQueryResultPreviewsand the format can deliver previews to the client. Any unknown stateful processor (LIMIT BY,WITH FILL, joins,INSERT SELECT, ...) keeps them dormant.DISTINCTdeduplicates 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-shotWindowTransform- sobar(x, 0, max(x) OVER (), 100)draws bars scaled by the maximum of the intermediate result, converging to the final scale.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-onlyAggregator, and finalizes only the copies. Previews are emitted only for the standard final aggregation (never forWithMergeableStatestages,TOTALS/ROLLUP/CUBE, grouping sets, overflow rows, in-order, sharded, or spilled aggregation), and only while the state is small: single-level and below thequery_result_previews_max_result_rows/query_result_previews_max_result_bytesthresholds. Whenquery_result_previewsis enabled, it takes priority over the adaptive aggregation algorithm.LIMIT(at mostquery_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.Totals/Extremes), never as an in-bandDatapacket, 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 revision54498.BlockInfogets an in-memory-onlyis_previewfield (not serialized).query_result_previews_min_interval_ms(default one second),query_result_previews_min_rows, andquery_result_previews_min_bytes, checked on every processed block.query_result_previewsis force-disabled for the remote parts (merging per-shard previews on the initiator is future work), and the initiator defensively dropsPreviewDatapackets from shards.Changelog category (leave one):
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-clientrenders them as a live table below the progress bar, framing formats carry them aspreviewpackets 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
query_result_previews*settings, thepreviewpacket kind in the framing formats documentation, and thePreviewDatapacket in the native protocol specification)Workflow [PR]
Sync PR [sync-upstream/pr/115988]