Skip to content

Streaming Watermarks - #106169

Merged
Michicosun merged 6 commits into
masterfrom
merge_tree_streaming_watermarks
Aug 24, 2026
Merged

Michicosun merged 6 commits into
masterfrom
merge_tree_streaming_watermarks

Conversation

@Michicosun

@Michicosun Michicosun commented May 30, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

This patch extends streaming queries with watermarks.


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

@clickhouse-gh

clickhouse-gh Bot commented May 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7d0c59c]

Summary: ✅


AI Review

Summary

This PR rewrites the MergeTree streaming read path around round-based per-partition pipelines and adds WATERMARK FOR ... AS ... [IDLE TIMEOUT ...], _time_attribute, and _watermark support for FROM ... STREAM. The new structure is much clearer than the old sequential source, but the current branch still has one correctness blocker in multi-stream watermark queries, and several earlier edge-case and performance findings are still present in the current code.

PR Metadata

Changelog category should not be Not for changelog: this is a user-visible addition to the experimental streaming-query surface, so Experimental Feature is the right category. The current changelog entry is also too vague for that category. A concrete replacement would be:

### Changelog category (leave one):
- Experimental Feature

### Changelog entry:
Add experimental `WATERMARK FOR <column> AS <expr> [IDLE TIMEOUT ...]` support to `FROM ... STREAM` queries, including the `_time_attribute` and `_watermark` virtual columns.
Findings

❌ Blockers

  • [src/Processors/QueryPlan/ReadFromMergeTree.cpp:4141] Watermarks are still only calibrated per MergeTreeCommitOrderSource, not per query. groupPartitionsByStreams() can create several independent sources, each with its own ReadState::last_emitted_watermark and idle state, but there is no outer watermark-aware merge after Pipe::unitePipes(...). A concrete trace is: source A advances one assigned partition to watermark 100, source B is still at 10, then a new partition hashes to source B; ReadState::updatePartitionSet() seeds that partition from 10, so rows at watermark 20 are emitted even though they are already late relative to the query-global watermark 100. The fix is to either force watermarked streams through a single MergeTreeCommitOrderSource or add cross-source watermark/idle calibration before exposing parallel query streams.

  • [src/Storages/MergeTree/Streaming/ReadingPlan/buildReadRoundPipeline.cpp:69] validateWatermarkSettings() accepts aliases because it resolves the expression against the full ColumnsDescription, but the read-round rebuild still derives dependencies from metadata->getColumns().getAllPhysical() and later re-resolves the AST against a dummy header built from those physical columns only. A query like ... STREAM WATERMARK FOR ts AS alias_ts therefore passes analysis and then throws when the subplan is built. Keep the analyzed watermark expression, or expand aliases before this point, instead of rebuilding it from a physical-only header.

⚠️ Majors

  • [src/Storages/MergeTree/Streaming/MergeTreeCommitOrderSource.cpp:130] [dismissed by author -- https://github.com/Streaming Watermarks #106169#discussion_r3329386666] filterStreamingVirtualColumns() strips _time_attribute and _watermark from every STREAM read, even when there is no watermark clause. That means a table with a real _watermark or _time_attribute column still analyzes for SELECT _watermark FROM t STREAM, but the inner read drops the physical column and the final projection cannot satisfy the header. Either reserve those names for all STREAM queries up front or only strip them when stream_settings.watermark is set.

  • [src/Storages/MergeTree/Streaming/ReadingPlan/buildReadRoundPipeline.cpp:102] [dismissed by author -- https://github.com/Streaming Watermarks #106169#discussion_r3831698093] Each changed-partition subplan still calls MergeTreeDataSelectExecutor::read(..., /*max_block_numbers_to_read=*/nullptr, ...) against the whole storage_snapshot, and the only partition_id = '<target>' restriction is the downstream FilterStep built by buildPartitionFilter(). That turns one read round into O(changed_partitions × full-table read) work and re-reads unrelated partitions in every subpipeline. Passing a singleton partition restriction into read() is still necessary here.

  • [src/Storages/MergeTree/Streaming/ReadingPlan/buildReadRoundPipeline.cpp:160] [dismissed by author -- https://github.com/Streaming Watermarks #106169#discussion_r3817175871] Plain STREAM reads still lose storage-level filter pushdown even though only STREAM WATERMARK needs the deferred-filter path. makeStreamingSelectQueryInfo() clears the storage read's prewhere_info / filter_actions_dag, and buildPartitionReadingPipeline() reapplies the predicate only as a late FilterStep, so text/skip-index optimization disappears for non-watermarked streams as well. The updated 04235_streaming_queries_text_index_direct_read.sql is now explicitly asserting TextIndexUseHint = 0, which is the regression rather than evidence that the behavior is acceptable.

Tests
  • ⚠️ Add a focused streaming test that forces at least two MergeTreeCommitOrderSource instances (for example via max_threads > 1) and proves that a new partition is seeded from the query-global watermark, not from a per-source local watermark.
  • ⚠️ Add a regression test for WATERMARK FOR ts AS alias_ts so the accepted query form does not regress back into a late plan-build exception.
  • ⚠️ Add a regression test for a physical _watermark / _time_attribute column on STREAM without a watermark clause; that edge case is currently untested.
Final Verdict

Status: ⚠️ Request changes

Minimum required actions:

  1. Make watermark / idle state query-global when groupPartitionsByStreams() produces more than one streaming source, or force watermarked streams to one source.
  2. Fix the alias-handling gap in the watermark expression rebuild path.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.10% 87.00% -0.10%
Functions 91.90% 91.90% +0.00%
Branches 79.40% 79.30% -0.10%

Changed lines: Changed C/C++ lines covered: 745/820 (90.85%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label May 30, 2026
Comment thread src/Analyzer/TableExpressionModifiers.h Resolved
Comment thread src/Analyzer/Utils.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented May 31, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.40% 84.30% -0.10%
Functions 91.40% 91.40% +0.00%
Branches 77.00% 76.90% -0.10%

Changed lines: Changed C/C++ lines covered by tests: 307/1014 (30.28%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 27 line(s) · Uncovered code

Full report · Diff report

@Michicosun

Copy link
Copy Markdown
Member Author

waiting for #106200 to fix problems with metadata snapshot.

@Michicosun
Michicosun force-pushed the merge_tree_streaming_watermarks branch from 8d61b98 to e276925 Compare August 19, 2026 12:13
@clickhouse-gh

clickhouse-gh Bot commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

⚠️ Significant changes: object file sizes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 705.37 MiB 702.44 MiB -2.92 MiB (-0.41%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Object file sizes ⚠️

8 object files changed (+1.57 MiB total), 17 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/MergeTree/Streaming/MergeTreeCommitOrderSource.cpp.o new 257.74 KiB +257.74 KiB
src/CMakeFiles/dbms.dir/Processors/Streaming/CalibrateWatermarksProcessor.cpp.o new 168.03 KiB +168.03 KiB
src/CMakeFiles/dbms.dir/Storages/MergeTree/Streaming/ReadingPlan/StampPartitionWatermarks.cpp.o new 138.09 KiB +138.09 KiB
src/CMakeFiles/dbms.dir/Storages/MergeTree/Streaming/ReadingPlan/buildReadRoundPipeline.cpp.o new 130.29 KiB +130.29 KiB
src/CMakeFiles/dbms.dir/Storages/MergeTree/Streaming/ReadingPlan/StampPartitionCursors.cpp.o new 117.78 KiB +117.78 KiB
src/CMakeFiles/dbms.dir/Storages/MergeTree/Streaming/ReadState.cpp.o new 94.21 KiB +94.21 KiB
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Streaming/CalculateWatermarksStep.cpp.o new 91.90 KiB +91.90 KiB
src/CMakeFiles/dbms.dir/Processors/Streaming/RaiseWatermarksTransform.cpp.o new 89.46 KiB +89.46 KiB
src/CMakeFiles/dbms.dir/Interpreters/Streaming/Utils.cpp.o new 85.67 KiB +85.67 KiB
src/CMakeFiles/dbms.dir/Processors/QueryPlan/Streaming/RaiseWatermarksStep.cpp.o new 80.71 KiB +80.71 KiB
src/CMakeFiles/dbms.dir/Processors/Streaming/Markers.cpp.o new 75.76 KiB +75.76 KiB
src/CMakeFiles/dbms.dir/Processors/Streaming/CalculateWatermarksTransform.cpp.o new 72.79 KiB +72.79 KiB
src/CMakeFiles/dbms.dir/Storages/MergeTree/Streaming/Cursors/CursorUtils.cpp.o new 63.24 KiB +63.24 KiB
src/CMakeFiles/dbms.dir/Storages/MergeTree/Streaming/Cursors/CursorPromoter.cpp.o new 53.58 KiB +53.58 KiB
src/CMakeFiles/dbms.dir/Storages/MergeTree/Streaming/Subscription/MergeTreeBoundsSubscription.cpp.o new 30.99 KiB +30.99 KiB
src/CMakeFiles/dbms.dir/Storages/MergeTree/Streaming/Subscription/SubscriptionEnrichment.cpp.o new 29.73 KiB +29.73 KiB
src/CMakeFiles/dbms.dir/Storages/MergeTree/Streaming/PartitionsClassification.cpp.o new 18.69 KiB +18.69 KiB

743 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

529 translation units recompiled, 4286 s compile time in total, 513 of them have a recent master baseline.

Translation units without a recent master baseline:

  • src/Storages/MergeTree/Streaming/ReadingPlan/buildReadRoundPipeline.cpp: 8.9 s
  • src/Storages/MergeTree/Streaming/MergeTreeCommitOrderSource.cpp: 7.8 s
  • src/Interpreters/Streaming/Utils.cpp: 5.2 s

Job report

@Michicosun
Michicosun force-pushed the merge_tree_streaming_watermarks branch 3 times, most recently from 104d1a3 to 43ee8f3 Compare August 21, 2026 14:35
if (!std::ranges::contains(columns, stream_settings.watermark->column))
columns.push_back(stream_settings.watermark->column);

const auto source_columns = collectWatermarkSourceColumns(stream_settings.watermark->expression, metadata->getColumns().getAllPhysical(), context);

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.

validateWatermarkSettings accepts watermark expressions against storage_snapshot->metadata->getColumns(), which includes aliases, but this rebuild path re-derives watermark dependencies from getAllPhysical() and buildWatermarkActionsDAG later re-analyzes the raw AST against a dummy header built from those physical columns only. A query like ... STREAM WATERMARK FOR ts AS alias_ts therefore passes analysis and then fails when the read round is built because alias_ts is no longer resolvable. Please keep the validated/analyzed watermark expression (or expand aliases before this point) instead of rebuilding it from a physical-only header.

@Michicosun
Michicosun force-pushed the merge_tree_streaming_watermarks branch from 43ee8f3 to a70d142 Compare August 21, 2026 15:25
@Michicosun
Michicosun marked this pull request as ready for review August 22, 2026 09:53
@clickhouse-gh

clickhouse-gh Bot commented Aug 22, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 72f48cf1-f3be-4596-af09-95b0eee5772d
  • MIRAI run: 45b21b8b-57d2-47f1-9799-dc9e3e431078
  • PR check IDs:
    • clickbench_7174_1787429652
    • clickbench_7180_1787429652
    • clickbench_7191_1787429652
    • tpch_adapted_1_official_7203_1787429652
    • tpch_adapted_1_official_7215_1787429652
    • tpch_adapted_1_official_7245_1787429652

@Michicosun
Michicosun added this pull request to the merge queue Aug 23, 2026
@Michicosun
Michicosun removed this pull request from the merge queue due to a manual request Aug 23, 2026
@Michicosun
Michicosun added this pull request to the merge queue Aug 24, 2026
Merged via the queue into master with commit 4525e5f Aug 24, 2026
350 of 351 checks passed
@Michicosun
Michicosun deleted the merge_tree_streaming_watermarks branch August 24, 2026 07:41
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 24, 2026
alexey-milovidov added a commit that referenced this pull request Aug 24, 2026
Edited following .claude/skills/edit-changelog/SKILL.md, by hand on a
workstation: the editing step of the NightlyChangelog job has been failing
its own verification since 2026-08-12, so three raw blocks had accumulated
(47 + 84 + 628 entries).

Of the 759 raw entries, 482 are integrated into the in-progress 26.8 section
and 277 are dropped:

- Section 3: the 300 `NOT FOR CHANGELOG / INSIGNIFICANT` entries are dropped,
  except 41 that describe a user-visible change and are promoted into a real
  category, among them a server abort on a corrupt `ORC` stripe footer
  (#114924), `EXPLAIN ANALYZE` for streaming queries (#112445), `SELECT` from
  `TimeSeries` (#115622), streaming watermarks (#106169), and the
  `clickhouse-local` CORS overrides (#115129).
- Section 2: every revert in the range cancels out inside it, so neither side
  appears. Two are re-applications: #114912 re-applies the
  `accurateCastOrDefault` fix, so #109946 keeps its entry with both links and
  the intervening revert #114911 is gone; #114409 re-applies the PromQL
  streaming plan, recorded on the #113656 entry.
- Section 4: `Build/Testing/Packaging Improvement` keeps the seven entries a
  user, packager or from-source builder notices (musl `getaddrinfo` and
  `sched_getcpu`, signed macOS artifacts, Debian packages for release builds
  only, zstd-compressed Docker layers, `unit_tests_dbms` without the full
  library set, vendored Rust built with optimizations locally) and drops the
  CI plumbing.
- Sections 5 and 6: bare pull request URLs converted to links, settings put
  in backticks, four entries rewritten from developer notes into user-visible
  descriptions, and three moved into `Performance Improvement`.

No entry of a strict-retention category was deleted: the job's own
`verify_edit` passes on this edit.

Not done here, because the release manager does it at release time: the full
significance sort, the aggressive merging of sibling pull requests, and the
`FIXME` release date and presentation links.
@clickgapai

Copy link
Copy Markdown
Contributor

@Michicosun @CheSema — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

pull Bot pushed a commit to sjoerd2025/ClickHouse that referenced this pull request Sep 15, 2026
The test loops its STREAM query 30 times with --max_execution_time=20. That
limit cannot catch anything the test looks for: the test asserts the query
SUCCEEDS (the oracle is throwIf(max(b) >= 5000 OR count() = 0), and the file
carries no serverError expectation), and the read is bounded by
STREAM LIMIT 400 over 10,010 pre-inserted rows, so it terminates on its own.
The limit can therefore only convert a slow-but-correct run into
Code: 159 TIMEOUT_EXCEEDED, which happened once on an unrelated PR (ClickHouse#113400).

What makes an iteration slow: a STREAM read re-runs full per-partition
planning on every snapshot iteration. Measured on this 10-partition table,
a single query logs 3 "Building new snapshot", 10 "Loading statistics",
10 "Moved conditions to PREWHERE" and 11 partition-key prunings while
reading about 1000 rows. That cost is left alone here, since
buildPartitionReadingPlan and buildNextSnapshotReadingPipeline are being
rewritten in ClickHouse#106169.

The sibling 04619_streaming_queries_shared_snapshot_strip_race.sql keeps its
max_execution_time = 2, because there the limit is the oracle
({ serverError TIMEOUT_EXCEEDED }). It is the only other streaming test that
sets the setting and is deliberately untouched.

The limit also never bought headroom: 30 iterations x 20s is a 600s ceiling,
exactly the harness's own --timeout 600. The installed test overlay does not
re-impose max_execution_time: the server default is 0, limits.yaml does not
set it, and the 60 second limits_fast.yaml is linked only under
FAST_TEST==1 && is_fast_build while Fast test passes --no-long and this test
is tagged long. Verified live on the installed stateless overlay:
system.settings reports max_execution_time 0, changed 0, while limits.yaml's
own values read changed 1. limits.yaml does set max_estimated_execution_time:
600, and that path is armed rather than inert, but the guard that reaches it
is a conjunction: the estimate is computed only once a query's own elapsed
time exceeds timeout_before_checking_execution_speed, which limits.yaml
raises to 300s, against a measured server-side 12ms per query
(system.query_log, n=30, min 10ms, max 72ms). It cannot substitute for the
removed cap.

One job adds a further cap on top of that overlay, and it is worth naming
because grep -rn max_execution_time tests/docker_scripts/ finds it. The Stress
test job runs the same install.sh, then configure_limits in
tests/docker_scripts/stress_tests.lib writes max_execution_time 60 into the
default profile, and stress_runner.sh calls that before starting the server
which runs the functional suite. The Stress test job passes neither --no-long
nor --no-parallel-replicas, and both skips are opt-in, so this test does run
there. That cap is looser than the one being removed, not tighter: a client
setting wins over the profile value, so the test's own --max_execution_time=20
was the effective limit there and it becomes 60s. Measured against that
profile: with no client flag system.settings reads 60, with the test's flag it
reads 20. Upgrade check never calls configure_limits, and the fuzzer and
performance profiles that also set the setting do not run clickhouse-test.

Runaway protection stays with the harness, which gives each file
--timeout 600 plus an int(600*1.1)+60 = 720s alarm and reports a hang as
"Timeout!". The flaky check's 180 second slow-test verdict
is gated on "long" not in tags and cannot fire here. This trades a fast false
failure for a slower true one.

Validation: the modified test passes 50/50 randomized and 50/50
non-randomized runs (--long-test-runs-ratio 1.0 is required, since the long
tag otherwise reduces 50 requested runs to 5). Removing the cap does not
measurably slow the test. Two runs of the same 21-test streaming suite on the
same binary give 7.70s with the cap (suite-base.log) and 7.96s without it
(suite-fix2.log). They are separate clickhouse-test invocations 131s apart,
so the comparison rests on a load control rather than on co-scheduling: the
20 unmodified tests in those same two runs move +0.50% in total (27.97s to
28.11s, per-test deltas -0.07s to +0.15s), and both logs carry identical
21-test name sets and the same server sha. The +0.26s difference is
therefore inside this test's own run-to-run spread of 7.46s to 9.47s across
the 50 randomized runs.
system.query_log confirms 30 oracle queries per run with zero timeouts, so
the pass is not a skipped loop. Reverting the ClickHouse#111572 source fix makes the
modified test fail with Code: 10 "Not found column less(b, 5000_UInt16) in
block" while executing MergeTreeCommitOrderSequentialSource, so the
regression oracle is still armed. The whole streaming family is 21/21 on
both arms.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-not-for-changelog This PR should not be mentioned in the changelog pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants