Repository navigation
Avoid copying data for the NONE compression codec when writing - #108096
alexey-milovidov wants to merge 54 commits into
Conversation
For `CODEC(NONE)` the compressed block on disk is byte-identical to the input, so the payload does not need to be copied between the compressor's working buffer and the output buffer. When a `CompressedWriteBuffer` exclusively owns its output buffer, point the working buffer directly into the output buffer, reserving room for the checksum and header in front of the data. The caller then writes the uncompressed data straight to where it will be flushed, and `nextImpl` only fills in the header and the checksum in place, without copying the payload. The header is written by a new `ICompressionCodec::writeHeader` helper factored out of `compress`. When the output buffer is too small, the writer falls back to the previous owned-buffer copy path. This is enabled (`out_buffer_is_exclusive`) only where the compressor is the sole, sequential writer of its output buffer: the wide-part column data and marks streams, the primary index stream, the compact-part marks stream, and the temporary-data buffer. It is intentionally left off where the output buffer is shared and written interleaved - the per-column streams of compact parts (which share one `plain_hashing`) and the network protocol buffer (which is interleaved with raw packet framing) - because there the reserved window could be overwritten by another writer. The read side already decompresses NONE data directly into the destination column via `readBig`, so no change is needed there. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Workflow [PR], commit [c576378] Summary: ❌
AI ReviewSummaryThis PR removes the extra payload copy on Final Verdict✅ No actionable findings. LLVM Coverage ReportMeasured on commit c576378.
Changed lines: Changed C/C++ lines covered: 256/256 (100.00%) · Uncovered code |
|
If you are wondering why it is needed. For two reasons:
|
|
📊 Cloud Performance Report ✅ AI verdict: This is a write-path change: it adds a zero-copy in-place assembly path for CODEC(NONE) compressed blocks and adjusts output-buffer sizing across MergeTree writers, temporary data, and the primary index. The only flagged query, ClickBench Q34, is a read-side SELECT that does not touch the NONE write path and was already borderline (the two tests disagreed, and CPU time was essentially flat at 16.5s base vs 16.6s source). The +6.3% median delta is best read as run-to-run variance rather than a PR effect, so it is downgraded to not_sure. No cross-query pattern is present. clickbenchFlagged queries (1 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🟢 No significant changes Debug info
|
Adds `tests/performance/codec_none_write.xml`, which times an `INSERT` of wide `CODEC(NONE)` `String` columns into a `MergeTree` table. Every column uses `CODEC(NONE)`, so each wide-part column data stream goes through the `out_buffer_is_exclusive` zero-copy path in `CompressedWriteBuffer`, where the data is written straight into the output buffer instead of being copied by `compress`. The insert is single-threaded with deduplication, block squashing and sparse serialization disabled and merges stopped, so the column writes dominate and a regression that stops using the zero-copy path is detectable. This addresses the review request for a focused before/after measurement of the `CODEC(NONE)` write path that also guards against future regressions. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Replaces `tests/performance/codec_none_write.xml` with `tests/performance/codec_none_read.xml`, which reads columns compressed with `CODEC(NONE)` instead of timing an `INSERT`. The timed query is a single-threaded `SELECT` that scans `CODEC(NONE)` columns. Because this PR slightly changes the on-disk block layout of `NONE` blocks (block sizes become bounded by the output buffer, with an occasional shorter block at a buffer boundary), the perf comparison fills the table with each server's own write path (old vs new layout) and then scans it with the identical read code, so the test guards against a read regression from the layout change. It also tracks `NONE` read throughput in general, which matters for incompressible data such as vector embeddings. Measured read time before/after is unchanged (~0.62s vs ~0.61s for 100M rows, single thread), confirming the write-path change is read-neutral. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Refreshed this PR by merging the latest The three CI reds on the previous commit are all pre-existing, master-wide flakes unrelated to this change (which only affects the
@groeneai, please take a look at the two stress-test failures (the |
|
@alexey-milovidov disposition of the two stress flakes, both unrelated to the CODEC(NONE) write path: 1) 2) |
|
Fixing PR for the |
|
Status (continue-pr, 2026-06-30): No code changes needed — branch unchanged at
No re-merge: the branch is 96 commits behind, but merge-base |
|
Status (continue-pr, 2026-06-30, 2nd pass): No code changes needed. Branch unchanged at The sole non-green check is CH Inc sync (
The prior rerun re-flaked on the same three, so I reran the failed sync jobs again (now in progress). No re-merge: the branch's merge-base Confirmed no |
|
Status (continue-pr, 2026-07-01): No code changes needed. Branch unchanged at The sole non-green check remains CH Inc sync (
I cancelled the stuck run to release the orphaned job and re-triggered a clean rerun of the three flaky jobs (now in progress). No re-merge: the branch's merge-base |
|
Status (continue-pr, 2026-07-01, 2nd pass): re-merged Public CI was fully green (151 passed, 0 failed, 19 skipped), AI Review ✅ Approve, Cloud Performance Unlike the prior passes, I did not just rerun the sync — because its run (
Only a new commit spawns a fresh, non-wedged sync run, so I:
The merge is clean and low-risk: Fresh public CI and a fresh sync run are now starting on |
|
AI Review ✅ Approve, Cloud Performance Report The sole non-green check is CH Inc sync (
None touch the compression write path — the only |
|
Status (continue-pr, 2026-07-01): No code changes needed. Head The sole non-green check is Two things worth recording:
The remaining sync failures triaged earlier are the same known flakes, none touching the compression write path: integration |
|
Status (continue-pr, 2026-07-02): No code changes needed. Head The sole non-green check remains
Neither failing test exercises compression. No re-merge (merge-base < 1 week, clean, PR files untouched by |
|
I verified this against the current head (
This is your PR and opting the marks writers into the direct path was a deliberate choice, so I'm not pushing a behavior change unilaterally. Happy to implement whichever you prefer:
Either way I'd add the requested regression test exercising |
The marks file is opened with a small fixed-size buffer (4096 bytes), while `marks_compress_block_size` defaults to 65536. The direct write path bounds each block by the nested buffer's free space, so opting the marks compressors into it clamped NONE-coded mark blocks to ~4071 bytes, multiplying the number of `.mrk*` frames and checksums by about 16x for `marks_compression_codec = 'NONE'`. Turn `out_buffer_is_exclusive` back off for the two marks writers (`MergeTreeWriterStream` and `MergeTreeDataPartWriterCompact`): marks are tiny compared to data, so the retained copy is negligible, and all the data-path, primary-index, and temporary-data gains are kept. Add a regression test that compares marks file sizes between `marks_compress_block_size` = 65536 and 4096 with `marks_compression_codec = 'NONE'`: honoring the block size must produce strictly fewer frames (a smaller file) for both wide and compact parts. Addresses the AI review finding on this PR: #108096 (comment)
|
Follow-up to the option 1 / option 2 question above: went with option 1 (commit 4e103f5) since it is the review's minimum required action and restores the exact pre-PR behavior for marks — the marks compressors no longer use the zero-copy path, while the data, primary-index, and temporary-data paths keep it. Marks are tiny compared to data, so the retained copy there is negligible. Also merged the latest Option 2 (growing the marks file buffer to |
The regression test `04539_marks_compression_codec_none_block_size` inserted 20000 rows into four `MergeTree` tables with `index_granularity = 1`. The per-granule overhead under sanitizers (and with the s3/distributed-cache flaky check configuration) pushed a single run to ~195-230 seconds, which the flaky check flags as `Test runs too long`. 2000 granules already produce ~48 KB of marks per column - a dozen 4096-byte frames but only one or two 65536-byte frames - so the `marks_bytes` comparison that distinguishes the honored `marks_compress_block_size` from the clamped 4096-byte marks-file buffer stays strictly unambiguous. Reducing the row count by 10x brings the run to ~0.7 seconds locally (well under the limit under sanitizers) while keeping the assertion and its red-without-the-fix behavior. Observed in the sync run for the PR: https://github.com/ClickHouse/clickhouse-private/actions/runs/29210026960 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Pushed The private sync run 29210026960 surfaced that Reducing the row count to 2000 keeps the assertion strictly unambiguous — 2000 granules still produce ~48 KB of marks per column (a dozen 4096-byte frames vs. one/two 65536-byte frames), so the The remaining reds are known unrelated flakes: |
|
🕵 @groeneai, please investigate the reproducible Fast-test failure and provide a separate fix if applicable. The original run and its rerun both abort after the hung check with no test attribution, but produce different cores ( Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108096&sha=9f682d8679214bc3af1bcdac4cde7a16bedfe5ab&name_0=PR&name_1=Fast%20test |
|
Investigated. This is not a liveness or infrastructure condition: it is a real SIGSEGV (NULL pointer read) in code this PR adds, and it is present on the current head. The three cores are one defect. All three crash at the same top frames: The core file name is the crashing thread's name (
Mechanism (line numbers at A post-finalize Why there is no test attribution. The server dies asynchronously, the runner's liveness probe then gets On a separate fix: not applicable here. The defect is inside this PR's own diff and does not exist on master, so it belongs in this PR. The minimal change is the guard the siblings already have: void TemporaryDataBuffer::preNext()
{
if (!out_compressed_buf)
return;
out_compressed_buf->checkBeforeWrite();
}Moving the |
There was a problem hiding this comment.
This PR got a little complicated since my last review with abstractions leaking. The preNext causes segfault and I think it can be dropped as the frame location is known relative to the window itself. working_buffer.begin() - COMPRESSED_BLOCK_PREFIX_SIZE, then assign out.position() = pos instead. That's the same idiom other buffers (HashingWriteBuffer, CascadeWriteBuffer, ForkWriteBuffer) use. Exclusivity is documented there, and it can be here too. We can add chassert(out.position() + COMPRESSED_BLOCK_PREFIX_SIZE == working_buffer.begin()) to catch problems during write in CI (checksums do it during read). Also, if we write the header with raw stores, we won't need the position dance
`WriteBuffer::next` called the new `preNext` hook unconditionally, before the `offset()` check, so it also ran for the leftover no-op flushes that happen after a buffer is finalized. Two of them were fatal: * `HashingWriteBuffer::getHash` calls `next`, and the primary-index checksums are collected after `index_source_hashing_stream`, `index_compressor_stream` and `index_file_hashing_stream` have all been finalized. Finalizing the file stream flushes it, so `CompressedWriteBuffer::preNext` then saw a moved `out` and threw `the output buffer declared exclusive was changed by someone else`, breaking every `INSERT` into a table with `primary_key_compression_codec = 'NONE'` whose index does not end exactly on a flush of the underlying file buffer (`04541_none_codec_exact_block_fit`). * `TemporaryBlockStreamHolder::finishWriting` flushes the native writer, and `AggregatingTransform::initGenerate` calls it again for streams `Aggregator::writeToTemporaryFileImpl` already finished. The second flush reached `TemporaryDataBuffer::preNext`, which dereferenced the `out_compressed_buf` that finalization had released — a segmentation fault in external aggregation (`02418_do_not_return_empty_blocks_from_ConvertingAggregatedToChunksTransform`). Nothing may be written after `finalize`, so there is no buffer for the hook to guard: skip it. The check still runs for the real final flush, which `finalizeImpl` performs before `finalized` is set.
… frame The `preNext` / `checkBeforeWrite` hook leaked the zero-copy `NONE` write path into `WriteBuffer`, `HashingWriteBuffer` and `TemporaryDataBuffer`, and it ran for the leftover no-op flushes that follow finalization, which made it fatal twice: * `HashingWriteBuffer::getHash` calls `next`, and the primary-index checksums are collected after `index_source_hashing_stream`, `index_compressor_stream` and `index_file_hashing_stream` have all been finalized. Finalizing the file stream flushes it, so the check saw a moved `out` and threw `the output buffer declared exclusive was changed by someone else`, breaking every `INSERT` into a table with `primary_key_compression_codec = 'NONE'` (`04541_none_codec_exact_block_fit`). * `AggregatingTransform::initGenerate` calls `TemporaryBlockStreamHolder::finishWriting` for streams that `Aggregator::writeToTemporaryFileImpl` already finished. The second flush reached `TemporaryDataBuffer::preNext`, which dereferenced the `out_compressed_buf` that finalization had released — a segmentation fault in external aggregation (`02418_do_not_return_empty_blocks_from_ConvertingAggregatedToChunksTransform`). The frame location does not need to be remembered: it is `working_buffer.begin() - COMPRESSED_BLOCK_PREFIX_SIZE`, so `nextImpl` writes the checksum and the header there with raw stores and then assigns `out.position() = pos`, the idiom `HashingWriteBuffer`, `CascadeWriteBuffer` and `ForkWriteBuffer` already use. Raw stores also remove the buffered writes that could flush `out` between the payload and its checksum. Exclusivity is now a documented contract of `declareOutBufferExclusive`, backed by `chassert(out.position() == frame_begin)`, which catches a violation during writing in CI the way checksums catch it during reading. The unit tests for the removed runtime check are deleted with it.
|
🕵 Done —
You were right that it segfaulted, and it was worse than one crash — the hook ran for the no-op flushes that follow finalization, which broke two unrelated paths:
Both reproduce on the previous head and pass now, together with the |
|
🕵 @groeneai Thank you — your analysis is exactly right, and the three cores being one defect (the crashing thread name is just the entry path) saved a lot of time. The I went with the stronger of the two options you offered plus @rienath's suggestion: Nothing needed on your side; #115080 and #113059 remain worth having for the missing test attribution. |
|
Correction to my 2026-07-17 comment here: the stress artifacts were never inaccessible, and nothing is needed from you. The On the ask itself: still no fix for this arm. #107586 is merged, but it corrected Two findings that change the shape of that fix:
Query-level reproduction stays negative across the recovered settings, with |
|
🕵 Status on head All three remaining reds are AST fuzzer jobs, and all three are unrelated to this change:
Since fuzzer aborts depend on the randomly generated statements, I re-ran the three failed jobs; no code change was needed. No Remaining gates: @rienath's re-review (the 2026-08-20 |
|
Item 1 is already fixed on Your head predates it, so the red is expected here: the merge base of #108650 does not close the huge- |
|
The fix for Correction to my comment above, and to the framing in the note that started this: both were keyed on the wrong query. CI records the pre-fuzz query text against an aborting query id, so the
The release builds are affected too, without the assertion: a range atom reaches no |
|
🕵 Merged @groeneai — this pulls in #108650, so the The merge was clean apart from nothing — @rienath, the points from your 2026-08-20 review are implemented (the |
The window-relative frame check in `CompressedWriteBuffer::nextImpl` was a `chassert`, so outside debug and sanitizer builds an exclusivity violation was silent. That matters because the working buffer of a zero-copy `NONE` block is an alias into `out`, and wrappers such as `HashingWriteBuffer` and `TemporaryDataBuffer` hand that alias further out: a foreign write to or flush of the nested buffer would be finished as a well-formed frame with a matching checksum, i.e. wrong bytes that read back cleanly. The check is now unconditional and throws `LOGICAL_ERROR`. It runs before the header and the checksum are stored and before `out.position()` is advanced, and a throw from `nextImpl` cancels the whole buffer chain, so the contract now fails closed instead of corrupting data. This does not bring back the `preNext` hook: nothing outside `CompressedWriteBuffer` is touched, and no check runs on the no-op flushes that follow finalization. Restores the `ViolatedExclusivityIsDetected` unit test, skipped in debug and sanitizer builds where `LOGICAL_ERROR` aborts the process.
|
🕵 Pushed The Major finding is fixed in The one red on Related: #113242 (the engine defect, still open) @rienath, your 2026-08-20 points remain implemented (the |
rienath
left a comment
There was a problem hiding this comment.
End-to-end INSERT of 8 wide String CODEC(NONE) columns (3M rows, single insert thread, no dedup/squashing/sparse, merges stopped; baseline = exact parent commit; median of interleaved reps): 2.96s → 2.62s (~1.13x, ~13% faster).
I tried the end-to-end INSERT locally and got no speed-up. CI binaries of head vs exact merge-base, 9 reps, same median speed, with the zero-copy path confirmed active. CI's perf test also measures 0%.
Meanwhile declareOutBufferExclusive introduces a cross-component promise. Every future writer to these streams must know about it, it can't be checked at compile time, and the runtime check only fires when the compressor is used. MergeTreeIndexText.cpp already violates it.
For that cost we need a real, reproducible win on a realistic query. Can you demonstrate one?
The in-place `NONE` frame check in `CompressedWriteBuffer::nextImpl` compared only `out.position()` with the start of the frame. A foreign write that filled the output buffer and flushed it leaves the position back at the buffer start, which is exactly where the frame began in the common case, so such a violation passed the check and a frame of wrong bytes was committed with a matching checksum. Record `out.count()` when the frame is reserved and compare it as well: any foreign write to `out`, flushed or not, changes it. Covered by the new `ViolatedExclusivityIsDetectedAfterForeignFlush` unit test.
|
🕵 Pushed Fix. The in-place frame guard in Not changed: the Reds on the previous head were both unrelated infrastructure: Verified locally ( @rienath, your 2026-08-20 points remain implemented and nothing outside |
|
#108096 (review) remains unanswered. We should not merge master and push commits until it is |
|
Dear @rienath, 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. |
Avoid copying data for the
NONEcompression codec when writing.For
CODEC(NONE)the compressed block on disk is byte-identical to the input, so the payload does not need to be copied between the compressor's working buffer and the output buffer. When aCompressedWriteBufferexclusively owns its output buffer, the working buffer is now pointed directly into the output buffer (reserving room for the checksum and header in front of the data), so the caller writes the uncompressed data straight to where it will be flushed;nextImplonly fills in the header and checksum in place, with no payload copy. The header is written by a newICompressionCodec::writeHeaderhelper factored out ofcompress. When the output buffer is too small, the writer falls back to the previous owned-buffer copy path. This is the same zero-copy buffer-aliasing technique thatHashingWriteBufferalready uses.The zero-copy path (
out_buffer_is_exclusive) is enabled only where the compressor is the sole, sequential writer of its output buffer: the wide-part column data streams, the primary-index stream, and the temporary-data buffer. It is intentionally left off where the output buffer is shared and written interleaved — the per-column streams of compact parts (which share oneplain_hashing) and the network protocol buffer (interleaved with raw packet framing) — because there the reserved window could be overwritten by another writer. It is also left off for the marks streams of wide and compact parts: theirmarks_filehas a small fixed-size buffer (4096 bytes), so the direct path would clampNONE-coded mark blocks to it instead of the configuredmarks_compress_block_size; the regression test04539_marks_compression_codec_none_block_sizecovers this.Note: for
NONE, compressed block sizes become bounded by the output buffer size, so the on-disk byte layout can differ slightly from before (an occasional shorter block at buffer boundaries). This is deterministic and does not affect reads.The read side already decompresses
NONEdata directly into the destination column viareadBig, so no change is needed there.Performance evidence
Measured with two
clickhousebinaries built from the same base commit, differing only by this PR (cherry-picked onto the same parent), so the comparison isolates exactly this change.Isolated write-path microbenchmark — 4 GiB through a
CompressedWriteBufferwith theNONEcodec into a discarding sink (no disk), 1 MiB blocks and output buffer, toggling onlyout_buffer_is_exclusive:out_buffer_is_exclusivefalse(old copy path)true(zero-copy path)End-to-end
INSERTof 8 wideString CODEC(NONE)columns (3M rows, single insert thread, no dedup/squashing/sparse, merges stopped; baseline = exact parent commit; median of interleaved reps): 2.96s → 2.62s (~1.13x, ~13% faster). The end-to-end gain is below the disk-free microbenchmark because disk I/O and data generation (equal in both binaries) dominate the rest of the insert.A focused performance test,
tests/performance/codec_none_read.xml, is added. It scansCODEC(NONE)columns, so in the PR-vs-master comparison the table is filled by each side's own write path (old vs new block layout) and then read by the identical read code. This guards against a read regression from the slightly changedNONEblock layout, and tracksNONEread throughput in general (relevant for incompressible data such as vector embeddings). Measured read time is unchanged before/after (~0.62s vs ~0.61s for 100M rows, single thread), confirming the write-path change is read-neutral.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Avoid an extra data copy when writing columns and temporary data compressed with the
NONEcodec by writing the data directly into the output buffer.Documentation entry for user-facing changes
Workflow [PR]
Sync PR [sync-upstream/pr/108096]