Skip to content

Avoid copying data for the NONE compression codec when writing - #108096

Open
alexey-milovidov wants to merge 54 commits into
masterfrom
add-none-codec-zero-copy-write
Open

alexey-milovidov wants to merge 54 commits into
masterfrom
add-none-codec-zero-copy-write

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jun 22, 2026 •

Copy link
Copy Markdown
Member

Avoid copying data for the NONE compression 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 a CompressedWriteBuffer exclusively 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; nextImpl only fills in the header and checksum in place, with no payload copy. 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 the same zero-copy buffer-aliasing technique that HashingWriteBuffer already 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 one plain_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: their marks_file has a small fixed-size buffer (4096 bytes), so the direct path would clamp NONE-coded mark blocks to it instead of the configured marks_compress_block_size; the regression test 04539_marks_compression_codec_none_block_size covers 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 NONE data directly into the destination column via readBig, so no change is needed there.

Performance evidence

Measured with two clickhouse binaries 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 CompressedWriteBuffer with the NONE codec into a discarding sink (no disk), 1 MiB blocks and output buffer, toggling only out_buffer_is_exclusive:

out_buffer_is_exclusive throughput
false (old copy path) ~8.5–9.2 GB/s
true (zero-copy path) ~13.6–14.0 GB/s
speedup ~1.5–1.6x

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). 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 scans CODEC(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 changed NONE block layout, and tracks NONE read 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):

  • Performance Improvement

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 NONE codec by writing the data directly into the output buffer.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

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

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]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c576378]

Summary: ❌

job_name test_name status info comment
Stress test (amd_tsan) FAIL
Hung check failed, possible deadlock found FAIL cidb, issue
Stress test (arm_tsan) ERROR

AI Review

Summary

This PR removes the extra payload copy on CODEC(NONE) writes by letting CompressedWriteBuffer alias an exclusive downstream buffer, with regression coverage for wide-part data, primary-key streams, and temporary files. After reconciling the existing review threads against the current head and reading the changed code paths, I did not find any remaining correctness, compatibility, or performance blockers in the diff.

Final Verdict

✅ No actionable findings.

LLVM Coverage Report

Measured on commit c576378.

Metric Baseline Current Δ
Lines 88.80% 88.80% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.20% 81.20% +0.00%

Changed lines: Changed C/C++ lines covered: 256/256 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Jun 22, 2026
@alexey-milovidov

alexey-milovidov commented Jun 22, 2026 •

Copy link
Copy Markdown
Member Author

If you are wondering why it is needed. For two reasons:

  • optimize columns that will explicitly use NONE, such as vector embeddings;
  • for a possible future optimization, when incompressible data will back off to NONE. While both ZSTD and LZ4 are naturally degenerate to fast path on incompressible data, it is still less efficient.

@alexey-milovidov
alexey-milovidov requested a review from rienath June 22, 2026 04:09
@clickhouse-gh

clickhouse-gh Bot commented Jun 22, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 40 queries analysed

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.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 34 not_sure 1138 1210 +6.3% 0.0232 cpu: This PR only changes the NONE-codec write path (block layout, buffer sizing); a ClickBench Q34 SELECT scan does not exercise it, so the +6.3% is run-to-run variance.

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
  • StressHouse run: 8bfe0850-16ce-4920-9b9d-b5fe6919ef57
  • MIRAI run: e4a11461-0a83-444b-bca1-f1584be016d1
  • PR check IDs:
    • clickbench_91662_1788910370
    • clickbench_91668_1788910370
    • clickbench_91674_1788910370
    • tpch_adapted_1_official_91685_1788910370
    • tpch_adapted_1_official_91719_1788910370
    • tpch_adapted_1_official_91733_1788910370

alexey-milovidov and others added 4 commits June 28, 2026 22:07
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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Refreshed this PR by merging the latest master (147 commits, clean — master did not touch any of the PR's files, and mariadb-connector-c was re-synced for the local build). Verified that the six production translation units this change touches (CompressedWriteBuffer, ICompressionCodec, TemporaryDataOnDisk, MergeTreeDataPartWriterCompact, MergeTreeDataPartWriterOnDisk, MergeTreeWriterStream) compile cleanly against the new master.

The three CI reds on the previous commit are all pre-existing, master-wide flakes unrelated to this change (which only affects the CODEC(NONE) write path):

@groeneai, please take a look at the two stress-test failures (the wait_for UBSan overflow and the empty-part dropPartition logical error) and provide fixes in separate PRs if they are not already tracked.

@groeneai

Copy link
Copy Markdown
Collaborator

@alexey-milovidov disposition of the two stress flakes, both unrelated to the CODEC(NONE) write path:

1) wait_for UBSan signed-integer-overflow (duration.h:93, ms * 1000000 overflows long long inside ConcurrentBoundedQueue<Chunk>::popImpl's wait_for; this run: 15483011758670014 * 1000000). Already fixed by our open PR #106961, which clamps the timeout via saturatedMilliseconds() in both pushImpl/popImpl (and the other unbounded-ms wait sites). It is under review, so no new PR is needed; the #108096 hit and the #107743 / #107582 / master hits are all the same site.
Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108096&sha=c0f4dc662c4948c22fcf8ed4b7be8cb64b5e20ae&name_0=PR&name_1=Stress%20test%20%28arm_asan_ubsan%29

2) 03008_alter_partition empty-part dropPartition LOGICAL_ERROR ("New empty part is about to materialize but the directory already exist"; aborts under debug/sanitizer). Confirmed on master too (arm_ubsan, sha dd89f87, same day). Deterministically reproduced today. Root cause: a partition covering-op (DROP/DETACH/MOVE/REPLACE PARTITION) builds an empty covering part via createEmptyPart (physical tmp_empty_<name> dir); renameTempPartAndReplaceUnlocked(rename_in_transaction=true) flips the part to PreActive with is_temp=false but defers the physical rename to transaction.renameParts(). If the op fails in between (in CI: a CANNOT_SCHEDULE_TASK fault during the s3_plain_rewritable metadata commit), rollback does not remove the tmp_empty_<name> dir, because removeIfNeeded early-returns once is_temp==false. A later covering-op on the same source part re-derives the same getNewName(level+1) and the exists() check throws. A separate PR with a failpoint-based regression test is being prepared and will be linked here.
Report (master): https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=dd89f87010a4d59d6278b02d3030683e29940c9f&name_0=MasterCI&name_1=Stress%20test%20%28arm_ubsan%29

@groeneai

Copy link
Copy Markdown
Collaborator

Fixing PR for the 03008_alter_partition empty-part dropPartition LOGICAL_ERROR (item 2 above, STID 3202-2fe9): #108879. It reclaims the stale tmp_empty_<part> directory in createEmptyPart() instead of aborting, with a deterministic failpoint-based regression test.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Status (continue-pr, 2026-06-30): No code changes needed — branch unchanged at 59241e72030, AI Review ✅ Approve, 0 unresolved review threads. The two remaining reds are both confirmed unrelated to this PR (NONE-codec zero-copy write):

  • Stress test (amd_tsan) — "Hung check failed, possible deadlock found". The hung check fired in run_0, where the server-side AST fuzzer hit 04319_base58_respects_time_limit — that test's own comment documents this exact symptom (base58 quadratic blowup blocking the connection handler and triggering the hung check). run_0 has zero compression/write-path frames; the blocked thread reported is pure analyzer (QueryTreePassManager::run → InterpreterSelectQueryAnalyzer → executeQuery). Known flake, tracked in Hung check failed, possible deadlock found #107941 (the CI comment itself links it). Reran the failed public job.

  • CH Inc sync — tests failed in sync PR ClickHouse/clickhouse-private#61727. All 5 failures are private-only Cloud features / infra, none touching the compression write path:

    • Unit DistributedFileCacheTest.TemporaryFileInDistributedCacheFailsFastAfterConnectionLoss (distributed cache)
    • Integration test_distributed_cache/test.py::test_idle_client_ttl (716 passed, 1 failed)
    • Integration test_refreshable_mv_no_multi_read/test.py::test_refreshable_mv_attach_without_multi_read (692 passed, 1 failed; recurring flake)
    • Stress (SharedCatalog, meta in keeper) 00234_disjunctive_equality_chains_optimization → We tried to commit part, but ZooKeeper is unavailable / Connection refused (localhost:9000) (Keeper infra)
    • Stress (meta in keeper) → Connection refused (localhost:9000) (server-start infra)

    The PR's own gtest passed: [ OK ] CompressedWriteBufferNone.RoundTripVariousSizes; the lone CompressedWriteBuffer string in the private stress logs is just the changed_files banner. Reran the failed private sync jobs.

No re-merge: the branch is 96 commits behind, but merge-base 68024785a70 is from 06-29 23:39Z (< 1 day) and neither red is fixable by merging master.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Status (continue-pr, 2026-06-30, 2nd pass): No code changes needed. Branch unchanged at 59241e72030; public CI fully green (151 passed, 0 failed), AI Review ✅ Approve, Cloud Performance Report verdict no_change, 0 unresolved review threads, MERGEABLE.

The sole non-green check is CH Inc sync (tests failed, sync PR ClickHouse/clickhouse-private#61727). I inspected the failed jobs from the latest sync run (28415380898, finished 20:02Z) individually — all three are the same private-only Cloud / infra flakes, none touching the CODEC(NONE) write path:

  • Unit tests (asan_ubsan) — [ FAILED ] DistributedFileCacheTest.TemporaryFileInDistributedCacheFailsFastAfterConnectionLoss (distributed cache, private Cloud).
  • Integration tests (amd_asan_ubsan, db disk, old analyzer, 5/7) — test_refreshable_mv_no_multi_read/test.py::test_refreshable_mv_attach_without_multi_read (refreshable MV, private Cloud; 692 passed / 1 failed — recurring flake).
  • Stress test (arm_asan_ubsan, SharedCatalog, meta in keeper) — Code: 210. Connection refused (localhost:9000) during the server-start health probe (server-start infra). The only CompressedWriteBuffer string in that log is the changed_files banner, not an error.

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 68024785a70 is from 06-29 23:39Z (< 1 day old), it is MERGEABLE with no conflicts, and none of these private flakes are fixable by merging master.

Confirmed no docs/en/interfaces/specs/NativeFormat.md update is needed: the frame layout (checksum + method 0x02 + sizes + body) is byte-identical, the Native wire path (network protocol buffer) is intentionally left off the zero-copy path, and the spec already documents that a block is a stream of one or more frames bounded by the buffer size — so the slightly different on-disk NONE block chunking is within the already-specified behavior.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Status (continue-pr, 2026-07-01): No code changes needed. Branch unchanged at 59241e72030; public CI fully green (151 passed, 0 failed, 19 skipped), AI Review ✅ Approve, Cloud Performance Report no_change, 0 unresolved review threads, MERGEABLE. Confirmed the diff is unchanged in scope (6 production TUs + gtest_compressed_write_buffer_none.cpp + codec_none_read.xml, +270/-13) and no NativeFormat.md update is needed (frame layout byte-identical; the Native network-protocol buffer is intentionally left off the zero-copy path).

The sole non-green check remains CH Inc sync (tests failed, sync PR ClickHouse/clickhouse-private#61727). I inspected the private run 28415380898 directly:

  • Its last rerun re-flaked on the same two private-only Cloud/infra failures — [ FAILED ] DistributedFileCacheTest.TemporaryFileInDistributedCacheFailsFastAfterConnectionLoss (distributed-cache fault-injection test, Injected continueRequest failure in DistributedCache::Client::Request::continueRequest) and the Stress test (arm_asan_ubsan, SharedCatalog, meta in keeper) Code: 210. Connection refused (localhost:9000) server-start infra probe. The lone CompressedWriteBuffer/codec strings in those logs are the changed_files banner, not errors — none of these touch the CODEC(NONE) write path.
  • The run was also stuck: one job (Integration tests (amd_asan_ubsan, db disk, old analyzer, 5/7)) had been orphaned in queued since 06-30 21:29Z (~1 day), so the run never completed and gh run rerun --failed was rejected with "This workflow is already running". That orphaned job is why the sync never turned green after the earlier reruns.

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 68024785a70 is from 06-29 23:39Z (< 1 week old), it is MERGEABLE with no conflicts, and none of these private flakes are fixable by merging master.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Status (continue-pr, 2026-07-01, 2nd pass): re-merged master to spawn a fresh sync run.

Public CI was fully green (151 passed, 0 failed, 19 skipped), AI Review ✅ Approve, Cloud Performance no_change, 0 unresolved review threads, MERGEABLE. The sole non-green check remained CH Inc sync (FAILURE, sync PR ClickHouse/clickhouse-private#61727).

Unlike the prior passes, I did not just rerun the sync — because its run (28415380898) was genuinely wedged, not merely flaky:

  • The Integration tests (amd_asan_ubsan, db disk, old analyzer, 5/7) job had been orphaned in queued since 06-30 21:29Z (re-queued again to 07-01 01:16Z on the last rerun), so the overall run never left queued for ~3+ hours.
  • gh run rerun --failed reruns jobs in the same run, so it kept re-orphaning that job and re-flaking the same two private-only Cloud/infra tests (DistributedFileCacheTest.TemporaryFileInDistributedCacheFailsFastAfterConnectionLoss; Stress test (arm_asan_ubsan, SharedCatalog) → Code: 210. Connection refused (localhost:9000) server-start probe). Rerunning could not converge.

Only a new commit spawns a fresh, non-wedged sync run, so I:

  1. Cancelled the wedged run 28415380898 (freeing the orphaned integration job).
  2. Merged the latest master into the branch (59241e72030 → 27d90150fd9).

The merge is clean and low-risk: master left all of the PR's files untouched (verified per-file over the 636-commit range) and there were no conflicts. The net diff is unchanged in scope (10 files, +270/-13: the six production TUs, gtest_compressed_write_buffer_none.cpp, codec_none_read.xml). I rebuilt the six production TUs (CompressedWriteBuffer, ICompressionCodec, TemporaryDataOnDisk, MergeTreeDataPartWriterCompact, MergeTreeDataPartWriterOnDisk, MergeTreeWriterStream) against the merged master — all compile cleanly with no warnings.

Fresh public CI and a fresh sync run are now starting on 27d90150fd9.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

AI Review ✅ Approve, Cloud Performance Report no_change, 0 unresolved review threads, MERGEABLE. Confirmed the diff is unchanged in scope (6 production TUs + gtest_compressed_write_buffer_none.cpp + codec_none_read.xml, +270/-13), 100% of changed lines covered, and re-verified the zero-copy arithmetic (16-byte checksum + 9-byte header reserved window; checksum over [header, header+9+size); out.position() advances by exactly prefix + size).

The sole non-green check is CH Inc sync (tests failed, sync PR ClickHouse/clickhouse-private#61727). This is a fresh failure from the sync run 28497170506 that completed at 11:44Z (after the last triage at 04:45Z). Unlike the earlier run I cancelled, this one was not wedged — it ran to completion, so gh run rerun --failed works. I inspected all four failed jobs; every one is a known flake unrelated to the CODEC(NONE) write path:

  • Unit tests (asan_ubsan) — [ FAILED ] DistributedFileCacheTest.TemporaryFileInDistributedCacheFailsFastAfterConnectionLoss (distributed-cache fault-injection test, private Cloud; 0 public-master failures because it is private-only).
  • Stateless tests (amd_asan_ubsan, distributed cache, meta in keeper, s3 storage, parallel, 2/2) — 03911_fractional_limit_offset_distributed_large failed once with Code: 102. Unexpected packet from server 127.0.0.2:9000 (expected TablesStatusResponse, got ProfileInfo) — the master-wide pooled-connection desync, being fixed by Fix flaky distributed query "Unexpected packet from server (expected TablesStatusResponse, got ProfileInfo)" #108854. All 23 reruns passed in the same job ("The failure is not reproducible").
  • Integration tests (amd_asan_ubsan, db disk, old analyzer, 2/7) — test_backup_restore_on_cluster/test_cancel_backup.py::test_long_disconnection_stops_backup (AssertionError; backup-cancellation flake, 2 master failures on 06-14/06-18).
  • Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/7) — test_refreshable_mv_no_multi_read/test.py::test_refreshable_mv_attach_without_multi_read (AssertionError; recurring refreshable-MV flake Disable aggregation-by-partitions optimisation with parallel replicas #62697, 6 master failures on 06-30).

None touch the compression write path — the only CompressedWriteBuffer/codec strings in those logs are the changed_files banner, not errors. Reran the four failed sync jobs (no re-merge: merge-base d584c4a28ff is from 04:14Z today, MERGEABLE, clean per merge-tree, and none of these flakes are fixable by merging master).

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Status (continue-pr, 2026-07-01): No code changes needed. Head 27d90150fd9; public CI fully green (151 passed, 0 failed, 19 skipped), AI Review ✅ Approve, Cloud Performance Report no_change, 100% of changed lines covered, 0 unresolved review threads, MERGEABLE. Merge-base d584c4a28ff is from 04:14Z today (< 1 day) and master left all of this PR's files untouched, so no re-merge.

The sole non-green check is CH Inc sync (sync PR ClickHouse/clickhouse-private#61727). Its structural blocker is Unit tests (asan_ubsan) → [ FAILED ] DistributedFileCacheTest.TemporaryFileInDistributedCacheFailsFastAfterConnectionLoss (C++ exception ... "Injected continueRequest failure"), a private-only Cloud distributed-cache fault-injection test unrelated to the CODEC(NONE) write path this PR changes.

Two things worth recording:

  • This unit-test job runs 1/1 attempt (no in-job retry), and it has re-flaked on every job-level rerun (latest 13:32Z), so the sync will not go green by rerunning the current run — the DistributedFileCacheTest job reproduces the injected-failure exception each time.
  • It already has a dedicated open fix: ClickHouse/clickhouse-private#62567 ("Fix flaky DistributedFileCacheTest.TemporaryFileInDistributedCacheFailsFastAfterConnectionLoss"), which fixes a brittle expectation in the test body and explicitly lists this sync PR #61727 as related. So CH Inc sync is blocked on #62567 landing (or this public-green PR can be merged on its own CI).

The remaining sync failures triaged earlier are the same known flakes, none touching the compression write path: integration test_backup_restore_on_cluster/test_cancel_backup.py::test_long_disconnection_stops_backup and test_refreshable_mv_no_multi_read (#62697), and the TablesStatusResponse pooled-connection desync being fixed by #108854 (all 23 reruns of 03911_fractional_limit_offset_distributed_large passed).

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Status (continue-pr, 2026-07-02): No code changes needed. Head 27d90150fd9; public CI fully green (151 passed, 0 failed, 19 skipped), AI Review ✅ Approve, Cloud Performance Report no_change, 100% of changed lines covered (122/122), 0 unresolved review threads, MERGEABLE. Merge-base is 2026-07-01 04:14Z (~1.3 days, well under a week) and master left all of this PR's files untouched, so no re-merge.

The sole non-green check remains CH Inc sync (sync PR ClickHouse/clickhouse-private#61727, run 28497170506). Since the last triage (07-01 16:46Z) the sync re-ran to completion — not wedged — with two failing jobs, both confirmed private-only Cloud flakes unrelated to the CODEC(NONE) write path this PR changes:

  • Unit tests (asan_ubsan) → DistributedFileCacheTest.TemporaryFileInDistributedCacheFailsFastAfterConnectionLoss (distributed-cache fault-injection, Injected continueRequest failure). Its dedicated fix ClickHouse/clickhouse-private#62567 is still open (unmerged, last touched 06-29), and the job runs 1/1 attempt with no in-job retry, so it re-flakes on every rerun — the sync cannot go green by rerunning until #62567 lands.
  • Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/7) → test_refreshable_mv_no_multi_read/test.py::test_refreshable_mv_attach_without_multi_read (AssertionError: assert 'Disabled' in 'Scheduled\t\n') — the recurring refreshable-MV / multi-read Cloud flake noted on 06-30 (696 passed / 1 failed), not a regression.

Neither failing test exercises compression. No re-merge (merge-base < 1 week, clean, PR files untouched by master) and no rerun (would re-hit the deterministic DistributedFileCacheTest flake). The PR is merge-ready pending #62567 landing to unblock the sync, or a maintainer merge-override, since both sync failures are confirmed private-only Cloud flakes.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

I verified this against the current head (c9b90e2) and it is correct — flagging so it is not dismissed as an AI false positive, and confirming the exact mechanism:

  • The zero-copy window in CompressedWriteBuffer::resetWorkingBuffer is std::min(out.available() - COMPRESSED_BLOCK_PREFIX_SIZE, adaptive_buffer_max_size). Because HashingWriteBuffer reuses the nested buffer as its own working buffer (working_buffer = out.buffer()), out.available() for the marks compressor is bounded by the 4096-byte marks_file buffer, not by marks_compress_block_size.
  • Both MergeTreeWriterStream and MergeTreeDataPartWriterCompact open marks_file with a hard-coded 4096 and pass out_buffer_is_exclusive = true, so with marks_compression_codec = 'NONE' each mark frame is clamped to ~4071 bytes instead of marks_compress_block_size (default 65536) — ~16x more .mrk* frames/checksums. Before this PR the owned-buffer path streamed a full ~64 KiB block across many marks_file flushes, so this is a real behavior change for that setting.
  • The data, primary-index, and temporary-data paths are not affected: their nested buffers are already sized to max_compress_block_size, so the window is block_size - 25 (negligible). Only the marks path has the small-buffer mismatch, and only for the non-default marks_compression_codec = 'NONE' (default is ZSTD(3)).

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:

  1. Turn out_buffer_is_exclusive back off for the two marks writers — simplest, keeps all the data-path gains, and marks are tiny so the retained copy is negligible; or
  2. Grow the marks output buffer to marks_compress_block_size where the NONE fast-path is wanted.

Either way I'd add the requested regression test exercising marks_compression_codec = 'NONE' with a marks_compress_block_size larger than 4096. Let me know which direction you want.

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)
@alexey-milovidov

Copy link
Copy Markdown
Member Author

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 master and added the regression test 04539_marks_compression_codec_none_block_size covering marks_compression_codec = 'NONE' with marks_compress_block_size larger (and smaller) than the 4096-byte marks file buffer, for both wide and compact parts.

Option 2 (growing the marks file buffer to marks_compress_block_size to extend the zero-copy path to marks) remains possible as a follow-up if desired — the new test would keep it honest.

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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Pushed bec3085edcd: sped up the regression test 04539_marks_compression_codec_none_block_size.

The private sync run 29210026960 surfaced that 04539 was flagged Test runs too long (~195–230 s per run) in the Stateless tests (flaky check) job — the test inserted 20000 rows into four MergeTree tables with index_granularity = 1, and the per-granule overhead is prohibitive under sanitizers + the s3/distributed-cache configuration. (The public amd_debug flaky check did not catch this because its server failed to start — unrelated infra flake.)

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 marks_bytes comparison and its red-without-the-fix behavior are preserved — while bringing a single run to ~0.7 s locally. Verified via clickhouse local that the output matches the reference.

The remaining reds are known unrelated flakes: Stress test (×4) = the JoinStep block-structure-mismatch #109215, and CH Inc sync = the private-only DistributedFileCacheTest.TemporaryFileInDistributedCacheFailsFastAfterConnectionLoss flake (open fix: clickhouse-private#62567).

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @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 (HTTPHandler vs QueryPipelineEx), so this is not a stable reproducer for the CODEC(NONE) write path. The rerun completed 317 fast tests with zero individual test failures before the liveness abort; the original completed 1,052. Both cores are uploaded encrypted and the job output contains no stack.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108096&sha=9f682d8679214bc3af1bcdac4cde7a16bedfe5ab&name_0=PR&name_1=Fast%20test
Related: #113059
Related: #115080

@groeneai

Copy link
Copy Markdown
Collaborator

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:

3.0. inlined from src/IO/WriteBuffer.h:142: DB::WriteBuffer::checkBeforeWrite()
3. src/Interpreters/TemporaryDataOnDisk.cpp:418: DB::TemporaryDataBuffer::preNext()
4. src/IO/WriteBuffer.h:52: DB::WriteBuffer::next()
Address: NULL pointer. Access: read.

The core file name is the crashing thread's name (core.%e), not the bug, so HTTPHandler vs QueryPipelineEx is only the entry path:

sha core entry path query
b24081b2854f HTTPHandler readRaw():486 -> read():481 -> HTTPHandler::Output::pushDelayedResults():1962 SELECT * FROM system.zeros LIMIT 100
9f682d8679214 QueryPipelineEx TemporaryBlockStreamHolder::finishWriting():575 -> AggregatingTransform::initGenerate():1469 argMaxIf/uniq GROUP BY (01576_if_null_external_aggregation)
0fdd526e17d5 QueryPipelineEx same, :1471 max_bytes_before_external_group_by = 1 (02418_do_not_return_empty_blocks_from_ConvertingAggregatedToChunksTransform)

Mechanism (line numbers at 0fdd526e17d5). WriteBuffer::next() now calls preNext() at WriteBuffer.h:52, before the if (!offset()) return; early-out at :60. TemporaryDataBuffer::preNext() at TemporaryDataOnDisk.cpp:417-419 dereferences out_compressed_buf with no null check, unlike nextImpl():423 and finalizeImpl():449, which both guard on it. finalizeImpl():457-458 calls releaseHolder() (which resets the guard's impl) and then reset(), so any next() after finalize dereferences null.

A post-finalize next() is reachable and normal. In the HTTPHandler arm, pushDelayedResults finalizes the cascade at HTTPHandler.cpp:1951 and then calls read() at :1962; that reaches finishWriting(), whose std::call_once body at :468 calls next(). Frame 5 of that core is exactly that body. Before this PR the same call was a harmless no-op, because offset() was 0 and next() returned at :47. call_once guards the body, not the newly added pre-body hook.

Why there is no test attribution. The server dies asynchronously, the runner's liveness probe then gets ConnectionRefusedError [Errno 111], and StopTesting (exit code 2) relabels the run Server died with no per-test row. The differing per-test counts (241, 950, 430 passed) just reflect where external aggregation or a delayed HTTP result happened to land. That is the reporting artifact I am fixing in #115080 and #113059; neither fixes this crash.

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 preNext() call after the if (!offset()) return; early-out in WriteBuffer::next() would also restore the pre-PR semantics for a nothing-to-flush next(). Happy to send either as a PR against this branch if you prefer.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108096&sha=0fdd526e17d55f319352b9ec554c5c7f7ef0927a&name_0=PR&name_1=Fast%20test

@rienath rienath left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Done — preNext is gone, exactly as suggested.

CompressedWriteBuffer::nextImpl now derives the frame from the window itself, working_buffer.begin() - COMPRESSED_BLOCK_PREFIX_SIZE, writes the checksum and the header there with raw stores, and then assigns out.position() = pos — the same idiom as HashingWriteBuffer / CascadeWriteBuffer / ForkWriteBuffer. The raw stores also remove the buffered writeBinaryLittleEndian calls that could flush out between the payload and its checksum. Exclusivity is documented on declareOutBufferExclusive and backed by chassert(out.position() == frame_begin), so a violation is caught during writing in CI the way checksums catch it during reading. expected_out_position / expected_out_flush_count and the unit tests for the removed runtime check are deleted, and WriteBuffer.h, HashingWriteBuffer.h and TemporaryDataOnDisk.h are back to untouched — no abstraction leak left.

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:

  • HashingWriteBuffer::getHash calls next, and the primary-index checksums are collected after index_source_hashing_stream, index_compressor_stream and index_file_hashing_stream are all 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 — every INSERT into a table with primary_key_compression_codec = 'NONE' failed (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. That is the Fast test Server died on the previous head (02418_do_not_return_empty_blocks_from_ConvertingAggregatedToChunksTransform).

Both reproduce on the previous head and pass now, together with the CompressedWriteBufferNone and FileCacheTest.TemporaryData* unit tests and 04539/04540/04541/04630.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @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 HTTPHandler arm you found, pushDelayedResults finalizing the cascade and then calling read() → finishWriting() → next(), is a third reproducer I had not seen; it is covered too, since the hook is now gone entirely rather than guarded.

I went with the stronger of the two options you offered plus @rienath's suggestion: preNext / checkBeforeWrite is removed from WriteBuffer, HashingWriteBuffer and TemporaryDataBuffer altogether, and CompressedWriteBuffer::nextImpl derives the frame from the window itself instead of remembering out's position. No post-finalize hook remains to be reached, so all three arms are fixed at the root. Pushed in adc3a58d8778.

Nothing needed on your side; #115080 and #113059 remain worth having for the missing test attribution.

@groeneai

Copy link
Copy Markdown
Collaborator

Correction to my 2026-07-17 comment here: the stress artifacts were never inaccessible, and nothing is needed from you. The 403 was my own path error. Artifact keys use the normalized task name, so stress_test_amd_debug/clickhouse-server.err.log.zst returns 200 where the display form Stress_test__amd_debug_/... returns 403. I have the failing run's log and its randomized settings.

On the ask itself: still no fix for this arm. #107586 is merged, but it corrected intDiv monotonicity in FunctionBinaryArithmetic.h and left the begin > end block alone, so the assertion is live in both MergeTreeSetIndex::checkInRange overloads on master today. Neither of my open PRs in that file, #112231 and #113965, touches it either. I will link the fix here when it opens.

Two findings that change the shape of that fix:

  • 3252-3a4a and 3252-4616 are one defect, not two. MergeTreeDataSelectExecutor dispatches on use_lightweight_primary_key_index_analysis, and the dense and sparse checkInRange overloads each carry their own copy of the begin > end throw. The sub-STID only records which overload ran.
  • The cause named in the TODO above that throw cannot apply to this trigger. It blames applyMonotonicFunctionsChainToRange applying nonmonotonic functions so that left > right, but t_04493_plain is ORDER BY (flag, id), two plain columns, so isKeyPossiblyWrappedByMonotonicFunctionsImpl matches the bare name and leaves the functions chain empty, and applyMonotonicFunctionsChainToRange then returns the range unmodified. A fix written against the TODO would miss this arm. Issue Multiple functions report inaccurate monotonicity information #90461, whose closure that TODO waits on, is also already closed while both copies still fire.

Query-level reproduction stays negative across the recovered settings, with EXPLAIN indexes = 1 confirming the probe does reach __lazy_final_set and generic exclusion search. So the remaining candidate is a hyperrectangle that is already inverted on arrival, which KeyCondition::checkInRange only chasserts. I am driving MergeTreeSetIndex::checkInRange directly through the existing gtest_merge_tree_set_index harness, where such a range can be constructed and no SQL fixture reaches it.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Status on head 6da17e5a (2026-08-24 master merge): AI Review ✅ ("no remaining correctness, safety, or contract issues"), changed-line coverage 230/230 (100%), cloud benchmark verdict improvement (ClickBench Q17 −46.4%), CH Inc sync green, 0 unresolved review threads, MERGEABLE.

All three remaining reds are AST fuzzer jobs, and all three are unrelated to this change:

  1. AST fuzzer (amd_debug, targeted) — Logical error: 'Too large size (9223372036854775934) passed to allocator' (STID 1367-1ab3), thrown from SerializationNumber<Int8>::deserializeBinaryBulk ← MergeTreeDataPartWriterWide::validateColumnOfFixedSize. The fuzzed table it aborts on is marks_none_wide_small__fuzz_45, created with index_granularity = 9223372036854775807; the debug-only mark validation then tries to read back one granule of that size, i.e. the allocation request is simply index_granularity and has nothing to do with the codec or with the zero-copy write path. Same signature on ~15 unrelated pull requests since 2026-06-26 (e.g. Reject malformed Arrow Flight Basic credentials #115347, where the fuzzed setting is index_granularity = 9223372036854775806 and the same abort occurs on a plain Int8 table; Do not hold the DDL guard during TRUNCATE of a replicated table #114672, Fix count distinct rewrite safety #81944, Perf: bulk insert repeated LowCardinality values #115020, Improve canceling queries in nested expression functions in FilterTransform #112705). No open issue exists for this signature yet.
    @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108096&sha=6da17e5afe0414b421fa716ba8c0f950fdc4652f&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29 and provide a fix in a separate PR (the debug mark validation in MergeTreeDataPartWriterWide::validateColumnOfFixedSize should not allocate a granule-sized buffer unconditionally). If a fix is already in progress, please link it here.

  2. AST fuzzer (amd_debug) — Logical error: 'Shard number is greater than shard count: shard_num=4 shard_count=1 cluster=parallel_replicas' (STID 5066-457d) on a SELECT DISTINCT … LIMIT 2147483646, 65536. Parallel-replicas shard bookkeeping; nothing in this diff. Recurs on master itself (8 hits, latest 2026-08-25) and on many unrelated pull requests (Do not use task-based parallel replicas for a recursive CTE or a correlated subquery enabled by a nested SETTINGS clause #115916, Fix lost index analysis when parallel replicas estimation is enabled in a subquery #116529, Add server setting additional_memory_tracking_per_thread #104965, Perform the Too many parts check once per INSERT query #113045, …). Tracked variant: Logical error: Shard number is greater than shard count: shard_num=A shard_count=B cluster=C (STID: 5066-564d) #101325 (the exact sub-STID was closed as Logical error: Shard number is greater than shard count: shard_num=A shard_count=B cluster=C (STID: 5066-457d) #101490 but is clearly live again).

  3. AST fuzzer (arm_asan_ubsan) — Logical error: 'Invalid number of columns in chunk pushed to OutputPort. Expected 0, found 1' (STID 2270-3258) on a remoteSecure(...) + window-function query. Already auto-labelled with the open issue Logical error: Invalid number of columns in chunk pushed to OutputPort. Expected A, found B (STID: 2270-3258) #114611; recurs across ~15 unrelated pull requests and on master.

Since fuzzer aborts depend on the randomly generated statements, I re-ran the three failed jobs; no code change was needed. No master re-merge either: the merge base is from 2026-08-24 and none of the three failures has a fix on master that a merge would pull in.

Remaining gates: @rienath's re-review (the 2026-08-20 CHANGES_REQUESTED points were implemented in adc3a58d — preNext was dropped and the frame position is now derived from working_buffer.begin() - COMPRESSED_BLOCK_PREFIX_SIZE with a chassert) and a human merge.

@groeneai

Copy link
Copy Markdown
Collaborator

Item 1 is already fixed on master: #108650, merged 2026-08-25 02:37Z (d2856332b6eb9e5c9f28e80f675e062e10c6fa30). It is the change you describe. The three deserializeBinaryBulk sites in validateColumnOfFixedSize now go through a helper that fills the column in bounded batches of 2^20 rows instead of resizing it to the untrusted per-mark granularity, so the allocation no longer scales with index_granularity. The regression test pins a non-adaptive wide part with index_granularity above 2^63, the same shape as marks_none_wide_small__fuzz_45.

Your head predates it, so the red is expected here: the merge base of 6da17e5a and d2856332 is 80ad8a50 from 2026-08-24 01:18Z, and the fix is not an ancestor of your head. A master re-merge is what clears this line; your call. The last sighting of 1367-1ab3 in CIDB anywhere is that same 2026-08-24 07:15Z run, with nothing since the fix landed, although at roughly one hit every two days across all pull requests 44 hours is not yet conclusive.

#108650 does not close the huge-index_granularity family, though. #116428 is open for a read-path defect with the same trigger: an index_granularity near 2^64 overflows the ceil-division in MergeTreeIndexGranularityConstant::fixFromRowsCount, the only data mark is reclassified as final, and the part then reads as empty. INSERT succeeds and count() reports the rows while sum() returns 0, so that one is wrong results in release builds rather than a debug-only abort. My fix for it is in flight at #116528.

@groeneai

Copy link
Copy Markdown
Collaborator

The fix for 3252-3a4a is open: #116608.

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 04493 lazy-FINAL query in that report is not what aborted. The failing run's own log carries the fuzzed one, WHERE intDiv(a, -9223372036854775807) GLOBAL NOT IN (10) over t_intdiv_mono__fuzz_44 with a Decimal(5, 4) and ORDER BY a, from my own 04340_intdiv_variable_constant_monotonicity. So this is not a separate cause in the lazy-FINAL set build, and my "the cause named in the TODO cannot apply to this trigger" reading was wrong for the same reason: a monotonic functions chain is exactly what makes left > right here.

intDiv and divide with a Decimal dividend compute in the decimal's own native signed width and cast the constant divisor into it. For Decimal(5, 4) that width is Int32, so intDiv(a, -9223372036854775807) divides by 1 and increases, while getMonotonicityForRange took the direction from the untruncated literal and reported decreasing. The Decimal guard already there tested the divisor, which is the wrong operand for this shape.

The release builds are affected too, without the assertion: a range atom reaches no chassert at all, so on Decimal(5, 4) data holding 0..9, WHERE intDiv(a, -9223372036854775807) > 4 returned 0 rows where 5 match.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master into the branch: head is now 0c26d107ab97 (merge base moves from 80ad8a50 2026-08-24 to 6ea4e96d 2026-08-28).

@groeneai — this pulls in #108650, so the 1367-1ab3 Too large size … passed to allocator line in validateColumnOfFixedSize is now covered on this head as you suggested. The rerun of the previous head had already come back clean: all 163 checks pass, 15 skipped, CH Inc sync green, and 0 unresolved review threads.

The merge was clean apart from nothing — git diff origin/master --stat lists exactly the 21 files this PR owns. I rebuilt the affected translation units locally (CompressedWriteBuffer.cpp, ICompressionCodec.cpp, TemporaryDataOnDisk.cpp, MergeTreeDataPartWriterCompact.cpp, MergeTreeDataPartWriterOnDisk.cpp, MergeTreeWriterStream.cpp) — all compile.

@rienath, the points from your 2026-08-20 review are implemented (the preNext hook is gone; the frame is derived from working_buffer.begin() - COMPRESSED_BLOCK_PREFIX_SIZE with a chassert guarding the invariant, plus the .xml performance tests). Could you take another look and clear the CHANGES_REQUESTED when you are happy with it?

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.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pushed 4ef75115668a: the AI Review Request changes verdict is addressed, and master is merged again (merge base moves from 6ea4e96d 2026-08-28 to db94cef6 2026-08-31; clean, git diff origin/master --stat lists exactly the 21 files this PR owns).

The Major finding is fixed in aaacac17fec2. The window-relative frame check in CompressedWriteBuffer::nextImpl was a chassert, so outside debug and sanitizer builds an exclusivity violation was silent. It is now an unconditional throw Exception(LOGICAL_ERROR, ...). It covers the wrapper paths too — compressed_hashing, index_source_hashing_stream and TemporaryDataBuffer all reach the compressor through out.next() — and it runs before the header and the checksum are stored and before out.position() is advanced, so a foreign write or flush is never finished as a well-formed frame with a matching checksum. A throw out of nextImpl cancels the whole buffer chain, so the contract fails closed. The preNext hook is not reintroduced (it segfaulted three production paths); nothing outside CompressedWriteBuffer is touched. The ViolatedExclusivityIsDetected unit test is restored, skipped in debug and sanitizer builds where LOGICAL_ERROR aborts. Verified locally: CompressedWriteBuffer.cpp and gtest_compressed_write_buffer_none.cpp both compile.

The one red on 0c26d107ab97 is unrelated and already has a fix in flight. Stress test (arm_debug) — Logical error: 'Equal values are not contiguous within the range assumed to be sorted' (STID 2508-3ce9), aborting in DistinctSortedStreamTransform::transform at DistinctSortedStreamTransform.cpp:184 via ColumnNullable::getEqualRangeEndAssumeSorted. The aborting query is a fuzzed SELECT count() FROM (SELECT DISTINCT s FROM dist_distinct__fuzz_4 ORDER BY ALL ASC LIMIT 100) SETTINGS optimize_distinct_in_order = 1, i.e. an AST-fuzzer mutation of 04870_distinct_merge_over_distributed — DISTINCT-in-order over a Merge/Distributed fixture whose column type the fuzzer retyped. This PR changes neither DISTINCT processing nor sorting, and the engine defect is old and master-wide.

Related: #113242 (the engine defect, still open)
Related: #115839 (pins ast_fuzzer_runs = 0 in 04870, which is what stops this signature from firing on unrelated pull requests; still open, so the red is expected here until it merges)

@rienath, your 2026-08-20 points remain implemented (the preNext hook is gone, the frame is derived from working_buffer.begin() - COMPRESSED_BLOCK_PREFIX_SIZE, and the invariant is now enforced in release builds as well). Could you take another look and clear the CHANGES_REQUESTED when you are happy with it?

@rienath rienath left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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?

@abashkeev abashkeev added the comp-codecs Compression/encoding codecs (LZ4/ZSTD/etc.), archive formats (tar/zip/7z), codec selection and IO... label Sep 4, 2026
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.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pushed c576378aedcd: the AI Review Request changes Major is answered with a fix where it pointed at a real defect, and master is merged again (merge base db94cef6 2026-08-31 → ca3603d1 2026-09-08; single base, conflict-free, exactly the 21 files this pull request owns).

Fix. The in-place frame guard in CompressedWriteBuffer::nextImpl compared only out.position() with the start of the frame. A foreign write that fills the output buffer and flushes it leaves the position back at the buffer start, which is exactly where the frame begins in the common case, so that violation passed the check and a block of wrong bytes would have been committed with a matching checksum. out.count() is now recorded when the frame is reserved and compared too, so any foreign write to out — flushed or not — is detected and the whole chain is canceled. New unit test ViolatedExclusivityIsDetectedAfterForeignFlush; it fails without the count comparison.

Not changed: the preNext hook in WriteBuffer is still not coming back (it segfaulted HashingWriteBuffer::getHash, TemporaryDataBuffer after out_compressed_buf was released, and HTTPHandler::Output::pushDelayedResults), so the window between a contract-violating memcpy through a wrapper's cached alias and the check remains. That window is the same single-writer invariant plain_hashing already relies on for plain_file today; the reasoning is in #108096 (comment).

Reds on the previous head were both unrelated infrastructure: Integration tests (amd_asan_ubsan, db disk, old analyzer, 5/6 and 6/6) failed only with Container memory budget exceeded (/docker), the fleet-wide runner memory guard, with no test failures of their own. CH Inc sync will be re-evaluated on the new head.

Verified locally (RelWithDebInfo): unit_tests_dbms builds, all 7 CompressedWriteBufferNone tests and the rest of the compression suite pass (195 passed, 0 failed).

@rienath, your 2026-08-20 points remain implemented and nothing outside CompressedWriteBuffer is touched. Could you take another look and clear the CHANGES_REQUESTED when you are happy with it?

@rienath

rienath commented Sep 9, 2026

Copy link
Copy Markdown
Member

#108096 (review) remains unanswered. We should not merge master and push commits until it is

@rienath rienath added the hold Skip for auto-updating. label Sep 9, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 9, 2026

Copy link
Copy Markdown
Contributor

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.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-codecs Compression/encoding codecs (LZ4/ZSTD/etc.), archive formats (tar/zip/7z), codec selection and IO... hold Skip for auto-updating. pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants