Skip to content

Metrics for tracking insertions via materialized view - #110391

Open
UberDever wants to merge 20 commits into
ClickHouse:masterfrom
UberDever:uberdever/feature/insertion-metrics-mv-clickhouse2
Open

UberDever wants to merge 20 commits into
ClickHouse:masterfrom
UberDever:uberdever/feature/insertion-metrics-mv-clickhouse2

Conversation

@UberDever

@UberDever UberDever commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

Changelog category:

  • New Feature

Changelog entry:

Added metrics DirectInsertedRows, DirectInsertedBytes, MaterializedViewInsertedRows, and MaterializedViewInsertedBytes.
...

Documentation entry for user-facing changes:

I think there are none user-facing changes.

At a minimum, the following information should be added (but add more as needed).

  • Motivation: Why is this function, table engine, etc. useful to ClickHouse users?

Sometimes people need to track table's changes via matirialized view.

  • Example use: A query or command.

I used this to check is materialized view metrics work:

CREATE DATABASE IF NOT EXISTS test;

DROP TABLE IF EXISTS test.random_events;

CREATE TABLE test.random_events
(
    id UUID,
    user_id UInt64,
    event_type LowCardinality(String),
    amount Float64,
    is_success UInt8,
    event_time DateTime,
    payload String
)
ENGINE = MergeTree
ORDER BY (event_time, user_id);

INSERT INTO test.random_events
SELECT
    generateUUIDv4(),
    rand64() % 1000000,
    arrayElement(['click', 'view', 'purchase', 'login', 'logout'], 1 + rand() % 5),
    round(randCanonical() * 1000, 2),
    rand() % 2,
    now() - toIntervalSecond(rand() % 86400),
    concat('random_payload_', toString(rand64()))
FROM numbers(1000);
CREATE TABLE test.random_events_hourly_stats
(
    event_type  LowCardinality(String),
    event_hour  DateTime,
    total_amount    Float64,
    success_count   UInt64,
    fail_count      UInt64,
    event_count     UInt64
)
ENGINE = SummingMergeTree
ORDER BY (event_type, event_hour);

CREATE MATERIALIZED VIEW test.mv_hourly_stats
TO test.random_events_hourly_stats
AS
SELECT
    event_type,
    toStartOfHour(event_time)   AS event_hour,
    sum(amount)                 AS total_amount,
    countIf(is_success = 1)     AS success_count,
    countIf(is_success = 0)     AS fail_count,
    count()                     AS event_count
FROM test.random_events
GROUP BY event_type, event_hour;


-- Backfill hourly stats
INSERT INTO test.random_events_hourly_stats
SELECT
    event_type,
    toStartOfHour(event_time)   AS event_hour,
    sum(amount)                 AS total_amount,
    countIf(is_success = 1)     AS success_count,
    countIf(is_success = 0)     AS fail_count,
    count()                     AS event_count
FROM test.random_events
GROUP BY event_type, event_hour;


-- Testing results
SELECT *
FROM test.random_events_hourly_stats
ORDER BY event_hour DESC, event_type
LIMIT 20;

Kinda optional stage:

INSERT INTO test.random_events
SELECT
    generateUUIDv4(),
    rand64() % 1000000,
    arrayElement(['click', 'view', 'purchase', 'login', 'logout'], 1 + rand() % 5),
    round(randCanonical() * 1000, 2),
    rand() % 2,
    now() - toIntervalSecond(rand() % 86400),
    concat('random_payload_', toString(rand64()))
FROM numbers(1000000);

Checking metrics:

SELECT
    event,
    value
FROM system.events
WHERE (event ILIKE '%InsertedRows') OR (event ILIKE '%InsertedBytes')
ORDER BY event;

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

EilRoviSoft and others added 3 commits July 14, 2026 12:53
…x 02310 grep

Remove the unused CountingTransform::setInsertSource setter since
InsertSource is fixed at construction time.

Replace the non-deterministic test 04141 (which measured deltas of global
system.events counters affected by concurrent queries) with a deterministic
test 04538 that reads per-query ProfileEvents from system.query_log isolated
by current_database. It checks that DirectInsertedRows/DirectInsertedBytes
count only the top-level INSERT, while
MaterializedViewInsertedRows/MaterializedViewInsertedBytes count the rows a
materialized view writes into its target table, and that the two together add
up to InsertedRows/InsertedBytes.

Fix 02310_profile_events_insert broken by the new Direct/MaterializedView
insert events: the new event names contain 'InsertedRows' as a substring, so
the test's grep matched them too. Anchor the match with a word boundary
(grep -oP '\bInsertedRows: .*') so only the standalone InsertedRows event
matches.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=104076&sha=550d496a5a63f6bd77c8fef819c247837f5bb10a&name_0=PR&name_1=Fast%20test
@UberDever

Copy link
Copy Markdown
Contributor Author

@alexey-milovidov Hello! Could you please close #104076 in favor of this PR?

Adapt follow-ups from ClickHouse#104076:

- `d1fa10396c4` (2026-08-04, Alexey Milovidov): document that
  `DirectInsertedRows` and `DirectInsertedBytes` include internal writes
  through `InterpreterInsertQuery`.
- `e0e5528f208` (2026-07-26, Alexey Milovidov): make window-view coverage
  non-vacuous by asserting that a window view is not an insert dependency,
  then verify direct-only metric attribution.
- `bccfb2938a7` (2026-07-19, Alexey Milovidov): preserve local optional
  insert-source classification, which already prevents window views from
  incrementing materialized-view counters.
@tavplubix tavplubix added the can be tested Allows running workflows for external contributors label Aug 10, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [41f984c]

Summary: ❌

job_name test_name status info comment
Integration tests (amd_msan, targeted) FAIL
test_storage_s3_queue/test_parallel_inserts.py::test_parallel_inserts_with_failures[1-exclusive] FAIL cidb

AI Review

Summary

Adds DirectInsertedRows, DirectInsertedBytes, MaterializedViewInsertedRows, and MaterializedViewInsertedBytes to attribute insert activity by pipeline source, preserving attribution through same-query forwarding and resetting it for separate Distributed inserts. Reviewed head 41f984c50a97f6205255da61585a9afa3a9a32b4 and all prior discussion. The four previous findings are addressed in the current code. All four new regression tests passed in the current head's Fast test report. No blocker or major findings remain.

PR Metadata

New Feature matches this additive change. The required changelog entry names the new metrics, but its trailing ... placeholder would also be collected into the published entry. Suggested replacement:

Added DirectInsertedRows, DirectInsertedBytes, MaterializedViewInsertedRows, and MaterializedViewInsertedBytes profile events to distinguish direct insert pipeline activity from materialized-view insert activity.

Findings

💡 Nits

  • PR description, changelog entry: remove the trailing ... placeholder; use the replacement above.
Final Verdict

Status: ✅ Approve. Only the changelog cleanup above is suggested.

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Aug 10, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 41f984c50 with master c5a04df72 (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.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.94, programs/clickhouse-keeper ×1.14 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 7.5 s 17.9 s +10.9 s (+155%)
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 4.0 s 8.9 s +5.2 s (+139%)
Compile time of recompiled translation units

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

Median compile-time ratio to the baselines is ×1.05 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +501.1 s (+6%) in total before that adjustment.

Symbol sizes
Binary Symbol Master PR Δ
programs/clickhouse ProfileEvents::global_counters_storage 14.31 MiB 14.38 MiB +64.00 KiB (+0.44%)
programs/clickhouse-keeper ProfileEvents::global_counters_storage 14.31 MiB 14.38 MiB +64.00 KiB (+0.44%)

Job report

Comment thread src/Interpreters/Context.cpp Resolved
Comment thread src/Common/ProfileEvents.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-materialized-view Materialized views: insert-triggered MV pipeline, insert dependencies, deduplication. label Sep 4, 2026
Carry insert-source classification to the relocated CountingTransform sites in InterpreterInsertQuery.

Related: ClickHouse#110391
@maxknv maxknv added the external Author is not a member of the ClickHouse organization label Nov 2, 2026
Check inline values with dependent materialized views, table-function destinations, and refreshable APPEND writes without changing pipeline-hop attribution.

Related: ClickHouse#104076
The refresh context selects the database of its view, so filter the query log by that database as required by stateless test style checks.

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-materialized-view Materialized views: insert-triggered MV pipeline, insert dependencies, deduplication. external Author is not a member of the ClickHouse organization pr-feature Pull request with new product feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants