Skip to content

Keep sparse columns when an async INSERT ... SELECT falls back to a synchronous insert - #129574

Merged
Felixoid merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-async-insert-select-fallback-keeps-sparse
Nov 16, 2026
Merged

Felixoid merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-async-insert-select-fallback-keeps-sparse

Conversation

@groeneai

@groeneai groeneai commented Nov 5, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #128472
Related: #111663

Changelog category (leave one):

  • Performance Improvement

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

Lower memory usage of an INSERT ... SELECT with async_insert = 1 whose result has several blocks: the synchronous insert it falls back to now keeps sparse columns instead of converting the whole insert block to full columns (about 6 times less memory for a wide table with sparse columns).

Description

03237_insert_sparse_columns_mem fails in the AsyncInsert job with min_chunk_bytes_for_parallel_parsing = 171302 (job): its second INSERT ... SELECT FROM file(...) reports 10165446 written bytes instead of about 340000.

Under async_insert = 1, AsyncInsertQueueTransform holds the first block of an INSERT ... SELECT in case it is the only one. It held a materialized copy (const, sparse and replicated columns converted to full). When a second block arrives, that copy is replayed into the synchronous fallback, so the first block is counted at full size and Squashing then materializes every chunk of the squashed block, because their structures differ. With that chunk size the first parsed segment is 4953 rows, small enough to be held.

The transform now holds the original chunk and materializes a copy only when the block is diverted to the queue. A block too large after materialization falls back with the original chunks. The kill and timeout guard now runs before both exits.

Validation (debug build, server with async_insert = 1): the second insert of 03237 writes 10165446 bytes with a 71.88 MiB peak before the fix, and 342374 bytes with a 12.41 MiB peak after it. The new test 04633_async_insert_select_fallback_keeps_sparse fails on master and passes with the fix, in 50 randomized runs plain and 50 with async_insert = 1; the other 04633_async_insert* tests pass.


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

Version info

  • Merged into: 26.11.1.2453-master (included in 26.11 and later)

groeneai and others added 2 commits November 5, 2026 17:37
…ynchronous insert

AsyncInsertQueueTransform held a materialized copy of the first block of an
INSERT ... SELECT under async_insert (const, sparse and replicated columns
converted to full). When a second block arrived, that copy was replayed into
the synchronous fallback pipeline, so CountingTransform counted the first block
at full size and Squashing, seeing chunks of different structures, materialized
every chunk of the squashed block. For a wide table with sparse columns this
wrote a full part and used about 6 times more memory.

This is what fails 03237_insert_sparse_columns_mem in the AsyncInsert job with
min_chunk_bytes_for_parallel_parsing = 171302: the first parsed segment is 4953
rows, small enough to be held, and the second insert reports 10165446 written
bytes instead of about 340000.

Hold the original chunk and materialize a copy only when the block is diverted
to the queue. A block whose materialized size exceeds async_insert_max_data_size
now falls back with the original chunks at the end of input, after the existing
kill / timeout / cancel guard, which therefore covers both exits of a held
block. The replay part of disqualify() is split out as fallBack().

The new test compares the bytes written by the async fallback with a plain
synchronous INSERT ... SELECT of the same blocks. Its source table pins
index_granularity: a granule of 20000 rows or more is read as one block, which
the queue route diverts instead of falling back.

Related: ClickHouse#128472

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…t assert its route

The previous commit moved materializeBlockInplace in getRemaining below the
kill / timeout / cancel guard, so an O(block) expansion ran between the last
check and the write. Materialize first and keep the guard right before both
writes (the divert to the queue and the fallback of a block that is too large
after materialization), as it was before. The rejected materialized copy is now
released before the fallback runs.

The test now also fails when its evidence is missing: it requires both
query_log rows and the text_log line showing that the async query took the
queue route and fell back there (async_insert_select_as_async_insert = 0 gives
0 for that line).

Related: ClickHouse#128472

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

groeneai commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 4 findings over 1 full pass, 1 fix round and 1 delta recheck).

# Sev Finding Verdict Evidence / action
1 ❌ The held block was materialized after the kill/timeout guard, so a kill during the expansion could still queue it (getRemaining) AGREE, fixed @ ebc8e52 Materialize first, then the guard, then both exits
2 ⚠️ The rejected materialized copy stayed alive while the fallback ran AGREE, fixed @ ebc8e52 block.clear() before fallBack()
3 ⚠️ The test could pass without its query_log rows or without taking the queue route AGREE, fixed @ ebc8e52 Presence columns plus the text_log route line for the async query; async_insert_select_as_async_insert = 0 gives 0 there
4 ⚠️ Under a break timeout the held block is now expanded before the guard and then discarded DISAGREE Master materialized every held first chunk on arrival, before any guard, so this costs no more than before; bounded by async_insert_max_data_size; nothing is written (04633_async_insert_select_break_writes_nothing)

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding. Also disagreed in round 1: an absolute sparse-size bound in the new test (sparsity of the sync route is covered by 03531_insert_removing_sparse_transform and 03237) and a case for a block that is too large only after materialization (estimateMaterializedBytes never undershoots for const, sparse, replicated or tuple columns, so no SQL input reaches it).

Session id: cron:clickhouse-review-slot-8:20261105-182600

@groeneai

groeneai commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. On a server with async_insert = 1, 03237's second INSERT ... SELECT FROM file(...) with min_chunk_bytes_for_parallel_parsing = 171302 writes 10165446 bytes on master (the CI number), every run. The new test fails on master every run (also 20/20 randomized).
b Root cause explained? AsyncInsertQueueTransform held a materialized copy of the first block. A second block makes it replay that copy into the synchronous fallback, so the first block is counted full and Squashing materializes the whole squashed block because the chunk structures differ.
c Fix matches root cause? Yes. The held chunk stays the original; a copy is materialized only when the block is diverted to the queue. No test bound or setting changed.
d Test intent preserved / new tests added? 03237 is unchanged and its bound holds again. New 04633_async_insert_select_fallback_keeps_sparse checks that the async fallback writes the same bytes as a synchronous insert of the same blocks, and asserts its own evidence: the text_log line proving the query took the queue route and fell back, and both query_log rows being present.
e Both directions demonstrated? New test: last line 1 1 0 on master, 1 1 1 with the fix, the route line 1 on both (deterministic; master 20/20 FAIL randomized, fix 50/50 plain and 50/50 with async_insert = 1). With async_insert_select_as_async_insert = 0 the route line is 0. 03237 replay: 10165446 bytes, 71.88 MiB peak on master vs 342374 bytes, 12.41 MiB with the fix.
f Fix is general across code paths? Every exit of the transform was checked: the oversized first block, the held block, a second block, zero-row chunks, the divert, the late size check (now falls back with the original chunks) and the empty result. The held block is materialized first and the kill and timeout guard then runs right before both of its writes. Other async insert routes do not use this transform.
g Fix generalizes across inputs (params/datatypes/wrappers)? Sparse, replicated and const columns all go through the same materialization, so all of them now reach the fallback as a synchronous insert delivers them. LowCardinality is not affected by it.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, default or format change; only a debug log line loses its estimated value.
i Invariants and contracts preserved? The fallback receives the SELECT's chunks unchanged and in arrival order, with their chunk infos. A held block is written only for a SELECT that completed. The divert path materializes once, as before.

Session id: cron:clickhouse-impl-slot-41:20261105-180700

@groeneai

groeneai commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator Author

cc @Felixoid @jkartseva, could you review this and add the can be tested label so CI runs? AsyncInsertQueueTransform held a materialized copy of the first block and replayed it into the synchronous fallback when a second block arrived, so squashing turned the whole insert block from sparse to full columns; it now holds the original chunk and materializes only the block it diverts to the queue.

@clickhouse-gh

clickhouse-gh Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ebc8e52]

Summary: ✅


AI Review

Summary

The change preserves the original INSERT ... SELECT chunks during synchronous fallback and materializes only the candidate for the asynchronous queue. No actionable findings at ebc8e52247ae5c0e9229b66786caebb7e98852b4. The focused regression passed in Fast test, alongside eight other async insert-select tests. The reported before/after peak memory of 71.88 MiB versus 12.41 MiB supports the performance claim. Consumers traced: PushingAsyncPipelineExecutor and ResizeProcessor move chunks unchanged; ShrinkColumnsTransform and CountingTransform use column interfaces; AddDeduplicationInfoTransform retains columns for lazy hashing; PlanSquashingTransform and ApplySquashingTransform preserve compatible representations and materialize incompatible ones; ConvertingTransform applies the existing conversion/default actions; the storage sink chain removes replicated columns and removes sparse columns for engines without sparse support. The queue still receives a materialized block.

Missing context / blind spots
  • ⚠️ Broader stateless and sanitizer CI results are still pending. No local build or tests were run; completed results from those jobs would extend the available runtime coverage.
Final Verdict

Status: ✅ Approve. No changes requested.

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements can be tested Allows running workflows for external contributors comp-async-insert Asynchronous INSERT buffering/queueing and flush semantics. labels Nov 5, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

✅ No significant changes.

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.

Compile time of recompiled translation units

8 translation units recompiled, 23 s compile time in total, 8 of them have a recent master baseline.

Job report

@Felixoid
Felixoid added this pull request to the merge queue Nov 16, 2026
Merged via the queue into ClickHouse:master with commit f0ee6ba Nov 16, 2026
367 of 368 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 16, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-async-insert Asynchronous INSERT buffering/queueing and flush semantics. pr-performance Pull request with some performance improvements 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.

3 participants