Skip to content

perf(promql): Parallelize flushing samples and recentsamples tables on insert. - #123144

Open
JTCunning wants to merge 21 commits into
ClickHouse:masterfrom
JTCunning:jtcunning/timeseries-parallel-inner-writes
Open

JTCunning wants to merge 21 commits into
ClickHouse:masterfrom
JTCunning:jtcunning/timeseries-parallel-inner-writes

Conversation

@JTCunning

@JTCunning JTCunning commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

An async insert flush of a TimeSeries table writes the tags table, the samples table, and the recent samples table one after another. The flush is one block. The pod still has free CPU during that wait.

TimeSeriesSink finishes the tags insert and the time ranges insert for each input block. It writes samples and recent samples together when the block fits one insert block, the recent target is a MergeTree table, and every row maps to one partition of that table. The samples write finishes first. A Buffer, Distributed, or Memory recent target waits until that finish. A block that spans several partitions of the recent target waits too. A recent target with a dependent materialized view waits too, because that view commits inside the recent pipeline. A samples failure leaves no recent-only rows. The tags pipeline and the time ranges pipeline are created when the block is pushed. When the insert carries an insert_deduplication_token, each input block uses <token>_<block index>. When it does not, each block uses a SipHash of that block plus the block index. A retry repeats the same identity. InterpreterInsertQuery, StorageTimeSeries, and the MergeTree sinks stay unchanged.

The tags pipeline uses a synchronous PushingPipelineExecutor. Squashing stays on for that pipeline. For one block, the tags write runs inside finish. A successful return starts the other two writes. A tags failure does not start the samples write.

The samples pipeline and the recent samples pipeline use PushingAsyncPipelineExecutor when the inner pipeline has more than one thread. report_read_progress is false. Both pipelines squash. Their minimum block sizes are 0. A normal block then passes through on each push. use_strict_insert_block_limits still splits a block at max_insert_block_size. A block that must split finishes the samples write before the recent samples write starts.

The metric families pipeline stays synchronous. The inner inserts still come from InterpreterInsertQuery. The memory-capped max_threads limit and use_concurrency_control stay in force. max_threads = 1 keeps the samples write and the recent samples write synchronous.

consume returns only after the samples write succeeds. A dependent materialized view on the TimeSeries table does not receive a failed chunk. Each input block is written before the next block starts.

Test 05296_time_series_parallel_flush uses the current TimeSeries table version. It covers the writes, a samples failure, a partitioned recent target, a default column, a view on the recent target, and a strict block-limit split. Test 05297_time_series_parallel_inner_flush checks that the samples write and the recent samples write overlap. Test 05402_time_series_multiblock_memory inserts eight blocks of 100000 samples under a 50 MB limit. Test 05403_time_series_insert_deduplication inserts three one-row blocks with one token, three identical blocks without a token, and a retry after a samples constraint failure.

One insert of 1000000 samples for 100000 series in one block, with max_threads = 8, ran eight times on the merge base 324e8a3a164 and on d725e8adb80, and the table shows the median of the last seven runs. Client time is query_duration_ms. CPU time is ProfileEvents['OSCPUVirtualTimeMicroseconds'].

Client time CPU time
Before 410.0 ms 411.1 ms
After 345.0 ms 493.9 ms

Changelog category (leave one):

  • Experimental Feature

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

Parallelize TimeSeries inner table flushes.


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

Each inner table commits when its own flush returns.

Measured on a release build with `async_insert = 0`:

- One row with a 1 s failpoint sleep in each inner flush:
  3.09 s at `max_threads = 1`, 1.12 s at `max_threads = 8`.
- 100k series and 500k samples with `INSERT SELECT`:
  0.56 s at `max_threads = 1`, 0.41 s at `max_threads = 8`.

The gain is bounded by the slowest inner table.
The tags table commits first.
A failed flush drops the other uncommitted parts.
`StorageTimeSeries::write` runs the same chain.
An insert into a materialized view uses that chain.
…block.

The gate sits in front of the storage sink.
A constraint failure on a block keeps that block out of the inner tables.
Each sink writes its temp part, then waits until every earlier target has committed that block.
A tags sink exception leaves that block out of samples and recent samples.
A samples sink exception leaves that block out of recent samples.
…arly.

`prepare` can return Async, and the wait can finish before `schedule`.
`schedule` returns the wait descriptor and signals it.
Tests that arm a server fail point now carry the `no-fasttest` tag.
…thread limits

`TimeSeriesWriteSink::consume` pushes a clone of the input chunk into the inner chain. `SinkToStorage::onConsume` forwards the original chunk to dependent materialized views, so a view on the TimeSeries table receives the inserted rows.

`StorageTimeSeries::write` sizes the inner chain with the memory-capped `max_insert_threads` value and `use_concurrency_control`, the same limits that `InterpreterInsertQuery` applies. `QueryPipeline(Chain)` now copies the concurrency control flag of the chain.

Test `05296_time_series_parallel_samples_writes` adds a materialized view that reads from the TimeSeries table.
The TimeSeries write chain no longer changes the MergeTree sinks. `MergeTreeSink` commits a block when it consumes the next block or finishes, and `SinkToStorage` emits a consumed chunk on its output port after `consume` returns. `TimeSeriesCommitGate` connects to the tags chain output and counts committed tags rows as the rows seen minus the last chunk. It holds the samples and recent samples chunks of a block until the tags rows that block depends on are committed, and releases everything when the tags chain finishes. Samples and recent samples are written in parallel after that. Metric families are not gated.

`TimeSeriesSplitTransform` attaches the cumulative tags row count to each gated chunk. The gate keeps two chunks per lane so the split can hand the next block to the tags chain. A tags table with dependent views has no row signal, so the gate releases at finish only.

`StorageTimeSeries::write` runs the chain on a nested executor with the memory-capped `max_threads` ceiling and `use_concurrency_control`, and pushes a clone so dependent views receive the rows. The `MergeTreeSink`, `ReplicatedMergeTreeSink`, `SinkToStorage`, `ExceptionKeepingTransform`, `QueryPipeline`, `FailPoint`, and `InsertDependenciesBuilder` changes are reverted.

Tests replace the failpoints. `05297_time_series_parallel_inner_flush` uses `sleepEachRow` in CHECK constraints. `05299_time_series_sink_commit_order` uses `max_partitions_per_insert_block` to make a target sink throw inside `consume`.
Move the parallel inner writes into the TimeSeries storage engine and
revert the changes in `InterpreterInsertQuery` and `StorageTimeSeries`.
`TimeSeriesWriteChain` is removed.

`TimeSeriesSink` keeps one pipeline per target table. The tags pipeline
runs on a synchronous `PushingPipelineExecutor` with
`max_insert_threads = 1`, so a push returns after the tags sink consumed
the previous block. The samples, recent samples, and metric families
pipelines run on `PushingAsyncPipelineExecutor` when the inner pipeline
has more than one thread, so these tables are written in parallel. The
inner pipelines use `no_squash`, because the insert into the TimeSeries
table already squashes blocks and a second squashing held every block
until the pipeline finished.

A samples block is delayed until its tags block is committed. The tags
block of push `k` is committed once push `k + 2` returned or the tags
pipeline finished, because a MergeTree sink commits a block when it
consumes the next one.
@JTCunning JTCunning added the can be tested Allows running workflows for external contributors label Sep 30, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [478b774]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_asan_ubsan, flaky check) FAIL
05403_time_series_insert_deduplication FAIL cidb
05403_time_series_insert_deduplication FAIL cidb
05403_time_series_insert_deduplication FAIL cidb
05403_time_series_insert_deduplication FAIL cidb
05296_time_series_parallel_flush FAIL cidb
05296_time_series_parallel_flush FAIL cidb
05296_time_series_parallel_flush FAIL cidb
05296_time_series_parallel_flush FAIL cidb
05296_time_series_parallel_flush FAIL cidb
05296_time_series_parallel_flush FAIL cidb
1 more test cases not shown
Stateless tests (amd_tsan, flaky check) FAIL
05403_time_series_insert_deduplication FAIL cidb
05403_time_series_insert_deduplication FAIL cidb
05403_time_series_insert_deduplication FAIL cidb
05403_time_series_insert_deduplication FAIL cidb
05403_time_series_insert_deduplication FAIL cidb
05403_time_series_insert_deduplication FAIL cidb
05403_time_series_insert_deduplication FAIL cidb
05403_time_series_insert_deduplication FAIL cidb
05403_time_series_insert_deduplication FAIL cidb
05403_time_series_insert_deduplication FAIL cidb
10 more test cases not shown
Stateless tests (amd_msan, flaky check) FAIL
05403_time_series_insert_deduplication FAIL cidb
05403_time_series_insert_deduplication FAIL cidb
05403_time_series_insert_deduplication FAIL cidb
05403_time_series_insert_deduplication FAIL cidb
05296_time_series_parallel_flush FAIL cidb
05403_time_series_insert_deduplication FAIL cidb
05296_time_series_parallel_flush FAIL cidb
05296_time_series_parallel_flush FAIL cidb
05296_time_series_parallel_flush FAIL cidb
05403_time_series_insert_deduplication FAIL cidb
4 more test cases not shown
Stateless tests (amd_debug, flaky check) FAIL
05296_time_series_parallel_flush FAIL cidb
05296_time_series_parallel_flush FAIL cidb
05403_time_series_insert_deduplication FAIL cidb
05403_time_series_insert_deduplication FAIL cidb
05296_time_series_parallel_flush FAIL cidb
Too many test failures FAIL cidb
Stateless tests (amd_binary, flaky check) FAIL
05403_time_series_insert_deduplication FAIL cidb
05403_time_series_insert_deduplication FAIL cidb
05403_time_series_insert_deduplication FAIL cidb
05296_time_series_parallel_flush FAIL cidb
05296_time_series_parallel_flush FAIL cidb
Too many test failures FAIL cidb
Stateless tests (amd_debug, parallel) FAIL
Server liveness check failed FAIL cidb
Logical error: 'Inconsistent AST formatting: the original AST: (STID: 1941-1bfa) FAIL cidb
Fast test (arm_darwin) DROPPED
Build (amd_darwin) DROPPED
Build (arm_darwin) DROPPED
Build (arm_v80compat) DROPPED

AI Review

Summary

The PR overlaps the samples and recent-samples writes while preserving their commit order, using new inner pipelines for each input block. ⚠️ Request changes: rebuilding those pipelines repeats insert admission checks against parts written by the same outer insert, introducing mid-insert failures.

Findings

⚠️ Majors

  • src/Storages/TimeSeries/TimeSeriesSink.cpp:1380: Each new target pipeline constructs a new MergeTreeSink, repeating delayInsertOrThrowIfNeeded with allow_throw = true. Later blocks can therefore fail with TOO_MANY_PARTS because of earlier blocks from the same insert. The previous persistent sink checked before writing and disabled hard rejection on subsequent blocks. This also affects the recreated tags, time-ranges, and recent-samples pipelines. Reproduced on the current Fast Test binary: with parts_to_throw_insert = 2 and background merges prevented, an insert of three one-row blocks into an initially empty samples target commits [0,1], then rejects block 3; a persistent MergeTree control under identical limits commits [0,1,2]. Preserve insert-scoped admission checks and add a multi-block regression crossing the threshold.
Final Verdict

Status: ⚠️ Request changes. Preserve the outer insert's part-count admission across inner pipeline recreation and cover it with a focused regression test.

@clickhouse-gh clickhouse-gh Bot added the pr-experimental Experimental Feature label Sep 30, 2026
Comment thread src/Storages/StorageTimeSeries.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-promql PromQL / time-series subsystem: TimeSeries storage engine, PromQL parser, PromQL-to-SQL converter... label Sep 30, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 478b774d7 with master da712df1b (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.

Object file sizes

4 object files changed (+38.83 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/TimeSeries/TimeSeriesSink.cpp.o 425.13 KiB 463.95 KiB +38.82 KiB (+9.13%)

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

Compile time of recompiled translation units

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

Job report

Comment thread src/Storages/StorageTimeSeries.cpp Resolved
arc1999 pushed a commit to arc1999/ClickHouse that referenced this pull request Oct 9, 2026
`parts stay far below the block count` failed twice in `Stateless tests
(arm_binary, parallel)` (PRs ClickHouse#123144 and ClickHouse#122138) and cannot tell the
defect from a thread that was descheduled.

The baseline spill decision reads query-wide memory. A frozen thread that
gets no CPU while the others thaw and finish the stream keeps its frozen
table and staged records resident (20.5-25 MiB measured), so the thawed
threads spill one part per block with the residue release in place. Under
the SIGPROF half of the CI thread fuzzer (P=0.02, up to 2 s) the fixed
engine writes 61-62 parts and prints exactly the CI line.

The line is also vacuous. Without the release (master before ClickHouse#117326, or
the release block deleted) scenario 1 writes 53-58 parts, under the bound
of 60, so the line passes on the defect. It became so when the rows were
cut from 3M to 1M (499b6e7, bce9bf4) while the thaw point stayed
at 524288 staged records, about 52 blocks before the end of the stream.

The release stays covered by `residue released` and by scenario 4's
`released with live states`: both read 0 on the two defect binaries in
every run and 1 on the fixed engine in every run.

Measured with clickhouse-local (amd_binary of master a2e4282 unless
noted):
- new test: identical to the reference on the debug, ASan and amd_binary
  builds; clickhouse-test --test-runs 50 -j 50 on debug: 50/50 OK;
  thread fuzzer P=0.1/100 ms and P=0.02/2 s, 400 runs each: 0 diffs.
  The current test on the same rig: 1/800 (`parts stay far below the
  block count 0`).
- defect binaries: the new test fails 6/6 on the two counter lines; the
  current parts line passes 6/6.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`TimeSeriesSink` pushes tags on a synchronous `PushingPipelineExecutor`.
It keeps each samples block until that pipeline finishes.
It then writes the samples table and the recent samples table together.

Those two pipelines use `PushingAsyncPipelineExecutor` when the inner pipeline has more than one thread.
They set `no_squash`.
The TimeSeries insert already squashed the block.
A second squash holds the block until `finish`.

The metric families pipeline stays synchronous.
A tags failure does not start the samples write.
This change removes `05298_time_series_multiblock_insert` and `05299_time_series_sink_commit_order`.
Those tests covered a per-block delay that this change does not keep.
@JTCunning JTCunning changed the title perf(promql): Flush TimeSeries inner tables together on the insert executor. Finish the TimeSeries tags insert, then write samples and recent samples together. Oct 14, 2026
@JTCunning JTCunning changed the title Finish the TimeSeries tags insert, then write samples and recent samples together. perf(promql): Parallelize flushing samples and recentsamples tables on insert. Oct 14, 2026
The samples pipeline and the recent samples pipeline squash again.
Both minimum block sizes on those pipelines are 0.
A normal block then passes through on each push.
`use_strict_insert_block_limits` still splits a block at `max_insert_block_size`.
The TimeSeries insert already applied the user minimum block size.
Finish the tags write and the time ranges write for the block, then write samples. A samples failure leaves no recent-only rows. A dependent view does not receive that block.
A Buffer recent target publishes a block inside consume. A multi-partition MergeTree recent target can flush an earlier partition inside one consume. Those targets receive the block only after samples finish. A samples failure then leaves no recent-only rows. The memory test inserts eight blocks of 100000 samples under a 40 MB limit.
A lazily loaded target is reached through `StorageTableProxy`. A direct `typeid_cast` to `MergeTreeData` fails on that proxy, and `isMergeTree` is not forwarded. `castStorage` with `DeferredTable::Load` reaches the engine behind the proxy.

Report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=123144&sha=55b7d1bed88b857123119803df9c2b77191cf7a0&name_0=PR&name_1=Style%20check
`TimeSeriesSink` resolves the recent samples target with `castStorage`
and evaluates the partition key of that table over the samples block.
The recent write runs together with the samples write only when the
target is a `MergeTree` table and every row maps to one partition. A
`MergeTreeSink` holds one delayed part until `finish`, so the recent
write cannot commit before the samples write finishes. A `Buffer`,
`Distributed`, or `Memory` target and a block that spans several
partitions wait for the samples write.

The check no longer calls `splitBlockIntoParts`, so a recent target
with an extra default column accepts the three-column samples block.
It no longer reads `max_insert_delayed_streams_for_parallel_write`.

Test `05401_time_series_samples_commit_boundary` covers a default
column on the recent target, a two-date block with a delayed stream
limit of 6, and a `Distributed` recent target. Test
`05297_time_series_parallel_inner_flush` partitions the recent target.
`TimeSeriesSink` builds new target pipelines for each input block. Each
pipeline starts its `AddDeduplicationInfoTransform` block number at
zero. With one `insert_deduplication_token` for the whole insert, the
second and later blocks got the identity of the first block, and a
deduplicating target dropped them.

The sink now counts non-empty input blocks. When the insert carries a
token, every target pipeline of block N uses the token `<token>_N`.
Distinct blocks get distinct identities, and a retry of the same insert
repeats the same tokens. An insert without a token is unchanged.

Test `05403_time_series_deduplication_token` inserts three one-row
blocks with one token into `MergeTree` targets with
`non_replicated_deduplication_window`, repeats the insert, and inserts
with a second token.
`TimeSeriesSink` builds a new tags pipeline and a new time ranges
pipeline when it pushes a block, after the input block index advances.
It no longer builds those pipelines in the constructor, where the index
is still zero. A retry that skips cached tags therefore stamps the new
block with that block's index, not with the first block's token.

When `insert_deduplication_token` is empty, each per-block pipeline
uses a SipHash of the block plus the input block index. Each pipeline
starts its block counter at zero, so identical blocks in one insert
would otherwise share one hash. A non-empty user token is still
`<token>_<index>`. The metric families pipeline stays one pipeline and
keeps an empty token.

Test `05404_time_series_tokenless_block_dedup` inserts three identical
blocks, then a different row, then retries the first insert. Test
`05405_time_series_dedup_partial_retry` fails a samples constraint and
retries the same token.
…as dependent views

`TimeSeriesSink::writeSamplesAndRecent` overlaps the samples flush and the recent samples flush when the block is one MergeTree partition. A materialized view on the recent samples target runs inside that pipeline and commits during `consume`, so a failed samples flush left rows in the view target.

The overlap now also requires that the recent samples target has no dependent views. With a view, the sink finishes the samples flush before it pushes to recent samples.

Test `05406_time_series_recent_view_commit_barrier` inserts a sample that a delayed samples constraint rejects, with a view on the recent target that writes to a `Buffer` table, and checks that the view target has no rows.
@JTCunning

Copy link
Copy Markdown
Contributor Author
Screenshot 2026-10-15 at 8 48 12 PM I am collapsing the test cases down into larger files, @clickhouse-gh, if you deny this PR I will be very unhappy.

`05296_time_series_parallel_flush` holds the write checks, the samples-failure checks, the dependent-view check, and the strict block-limit check. `05403_time_series_insert_deduplication` holds the token check, the tokenless check, and the partial-retry check. `05297_time_series_parallel_inner_flush` stays a shell test because it reads `query_log`. `05402_time_series_multiblock_memory` stays separate because it skips sanitizer builds.
@clickhouse-gh

clickhouse-gh Bot commented Oct 16, 2026

Copy link
Copy Markdown
Contributor

PromQL Compliance Report

Baseline: S3 master 218a3b73d

Suite Baseline Current Delta
Prometheus compliance 100.00% 100.00% +0.00%
Extended support (upstream engine tests) 93.17% 93.17% +0.00%
Suite Passed Failed Unsupported
Prometheus compliance 539 -> 539 (+0) 0 -> 0 (+0) 0 -> 0 (+0)
Extended support (upstream engine tests) 682 -> 682 (+0) 16 -> 16 (+0) 34 -> 34 (+0)

Extended support (upstream engine tests): native-histogram exclusions: 149; excluded assertions: 248; upstream 3da2514eff5c.

Note: Prometheus compliance score is unchanged vs baseline.

Uploaded compliance JSON for this PR commit

@JTCunning
JTCunning marked this pull request as ready for review October 16, 2026 14:34
@vitlibar vitlibar self-assigned this Nov 2, 2026
…s-parallel-inner-writes

Keep the samples flush and the recent samples flush overlapped after the bucketed samples change.
Pin the flush tests to TimeSeries version 8 so they keep one sample per row and external targets.
The checks use the generated inner tables. A bucket holds the samples of one series, so the strict insert counts bucket rows.
const bool fits_one_block = fits(samples_block) && (!recent_samples_block || fits(*recent_samples_block));

auto samples = createTargetPipeline(
ViewTarget::Samples, samples_pipeline_header, /* parallel= */ true, /* delay_commit= */ false, &samples_block);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[P2] Keep part-count admission checks scoped to the outer insert

Recreating the target pipeline for every input block also constructs a new MergeTreeSink each time. Its constructor calls delayInsertOrThrowIfNeeded with allow_throw = true, so later blocks count parts committed by earlier blocks of this same insert. The previous persistent sink checked before writing and used allow_throw = false for subsequent blocks. An insert admitted just below parts_to_throw_insert can now fail part-way through on its own output; the recreated tags, time-ranges, and recent-samples pipelines have the same problem.

Reproduced on this head's Fast Test binary with an empty TimeSeries table, recent samples disabled, and the samples engine configured with parts_to_delay_insert = 0, parts_to_throw_insert = 2, and max_bytes_to_merge_at_max_space_in_pool = 1. Inserting three series from numbers(3) with max_threads = 1, max_block_size = 1, max_insert_block_size = 1, min_insert_block_size_rows = 1, and min_insert_block_size_bytes = 0 commits sample values [0,1], then throws TOO_MANY_PARTS on block 3. A persistent MergeTree sink under the same limits accepts [0,1,2].

Preserve insert-scoped part-count admission when rebuilding these pipelines, and add a focused multi-block regression that crosses the threshold during one insert.

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

can be tested Allows running workflows for external contributors comp-promql PromQL / time-series subsystem: TimeSeries storage engine, PromQL parser, PromQL-to-SQL converter... pr-experimental Experimental Feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants