Skip to content

Metrics for tracking insertions via materialized view - #104076

Open
EilRoviSoft wants to merge 33 commits into
ClickHouse:masterfrom
EilRoviSoft:dev/mdb-43838
Open

EilRoviSoft wants to merge 33 commits into
ClickHouse:masterfrom
EilRoviSoft:dev/mdb-43838

Conversation

@EilRoviSoft

@EilRoviSoft EilRoviSoft commented May 5, 2026 •

Copy link
Copy Markdown

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/104076]

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

Needs a test.

@EilRoviSoft

Copy link
Copy Markdown
Author

Needs a test.

Added for this, I believe it should be correct. Idk if I should include inserts into temp table as a reference value but anyway.

@EilRoviSoft
EilRoviSoft marked this pull request as ready for review May 12, 2026 15:39
alexey-milovidov and others added 4 commits June 29, 2026 05:17
`CountingTransform::InsertSource` is fixed at construction time and the
setter was never called. Drop it to keep the class minimal.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…etrics

The earlier test measured deltas of the global `system.events` counters, which are
affected by any other query running on the server (including background system log
flushes), so it was non-deterministic in the parallel test suite; it was removed
together with the unused setter.

Replace it with a test that reads per-query `ProfileEvents` from `system.query_log`,
isolated by `current_database`, so the values are exact regardless of concurrent
activity. 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`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

I merged the latest master and reworked the test.

The previous test compared deltas of the global system.events counters. Those are server-wide and change with any concurrent query (including background system-log flushes), so the exact values would be non-deterministic in the parallel test suite. The new 04498_direct_and_mv_insert_metrics reads per-query ProfileEvents from system.query_log (isolated by current_database), so the counts are exact regardless of other activity. It verifies that:

  • a plain INSERT into a table without a materialized view counts only DirectInsertedRows/DirectInsertedBytes;
  • an INSERT feeding a materialized view splits into Direct* (the top-level rows) and MaterializedView* (the rows the view writes into its target table);
  • Direct* + MaterializedView* equals InsertedRows/InsertedBytes.

Built with ASan and ran the test locally, including under concurrent inserts from other databases — it passes deterministically.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jul 3, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [dea1eee]

Summary: ❌

job_name test_name status info comment
Performance Comparison (arm_release, master_head, 6/6) FAIL Performance dashboard
Check Results FAIL
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

The PR adds DirectInsertedRows, DirectInsertedBytes, MaterializedViewInsertedRows, and MaterializedViewInsertedBytes, with coverage for ordinary inserts, table functions, chained views, and refreshable views. Reviewed head dea1eeea8f10af35090ccb3c8f921c73210f705d and all prior discussion. Earlier findings are addressed, but remote insert reports double-count the new direct counters, so this change needs correction. The discussion also requests closing this PR in favor of #110391; that consolidation remains a maintainer decision.

Findings

❌ Blockers

  • src/Processors/Transforms/CountingTransform.cpp:38–40: Remote inserts count the same input in DirectInserted* on both sender and receiver. RemoteInserter::processProfileEventsPacket removes the duplicate only from InsertedRows and InsertedBytes, then forwards the new events unchanged. Consequently, inserting three UInt32 rows through remote without materialized views yields combined DirectInsertedRows = 6 versus InsertedRows = 3. usedQuotaProfileEvents charges both snapshots, so quotas on the new direct events are exhausted prematurely. Normalize the duplicate remote DirectInserted* increments using independent subtraction budgets, preserving additional materialized-view writes and correct behavior across multiple hops.
Tests
  • ⚠️ Add a focused stateless remote-insert regression asserting DirectInserted* + MaterializedViewInserted* == Inserted* in client reports or quota usage, including a downstream materialized view. Existing new tests cover local sinks only. The remote-accounting finding is based on tracing the current code; no local binary was available for execution.
Final Verdict

Status: ❌ Block

Normalize remote reports for the new counters and add the focused regression test.

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Jul 3, 2026
Resolve conflicts in CountingTransform and its call sites: master added a
'normalized_query_hash' parameter to 'CountingTransform' while this branch
added an 'InsertSource' parameter. Combined both, keeping the constructor
signature (header, source, quota, normalized_query_hash) and passing
'getNormalizedQueryHash()' at all three construction sites (two Direct in
'InterpreterInsertQuery', one MaterializedView in 'InsertDependenciesBuilder').
…View insert events

The new ProfileEvents 'DirectInsertedRows' and 'MaterializedViewInsertedRows'
contain 'InsertedRows' as a substring, so the test's 'grep -o "InsertedRows: .*"'
matched them too and printed two lines instead of one. Anchor the match with a
word boundary ('grep -oP "\\bInsertedRows: .*"') so only the standalone
'InsertedRows' event matches. The reference is unchanged.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=104076&sha=550d496a5a63f6bd77c8fef819c247837f5bb10a&name_0=PR&name_1=Fast%20test
Comment thread src/Common/ProfileEvents.cpp Resolved
alexey-milovidov and others added 2 commits July 19, 2026 06:55
…serts, narrow event contract

The AI review on ClickHouse#104076 pointed out two problems
with the new Direct/MaterializedView insert profile events:

1. `InsertDependenciesBuilder::createSelect` is shared with `StorageWindowView`, so rows merely
   entering a window view were counted as `MaterializedViewInsertedRows`/`MaterializedViewInsertedBytes`.
   Now the source is chosen from `view_types`: only `MATERIALIZED` views count as materialized view
   inserts; other views (window views) use the new `InsertSource::Other`, which increments only the
   generic `InsertedRows`/`InsertedBytes`. Covered by the new test
   `04612_window_view_insert_source_metrics`.

2. Refreshable materialized view refreshes and explicit `INSERT` queries into a materialized view
   run through `InterpreterInsertQuery` as regular INSERTs and are counted as `DirectInserted*`.
   The event descriptions now state this explicitly instead of promising that every write into a
   materialized view target table lands in `MaterializedViewInserted*`.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=104076&sha=ab72321e4dbee46ab1d09683e4e6e6cecb8a90b1&name_0=PR

Co-Authored-By: Claude Fable 5 <[email protected]>
The AI review pointed out that asserting only
\`MaterializedViewInsertedRows\`/\`MaterializedViewInsertedBytes == 0\` would also
pass if the insert stopped being routed through the dependent window view.

Investigating that showed the window-view branch of
\`InsertDependenciesBuilder::createSelect\` cannot be exercised from SQL today:
a window view registers no view dependency on its source table (unlike a
materialized view, whose source shows up in
\`system.tables.dependencies_table\`), and a direct \`INSERT INTO <window view>\`
fails with \`STD_EXCEPTION\` in \`createPreSink\` - on unmodified master as well,
so this is pre-existing and unrelated to this change.

The test therefore pins both halves of that state explicitly instead of relying
on incidental zeros: the window view is asserted not to be an insert dependency
of its source table, and the tagged INSERT is asserted to attribute all rows and
bytes to the \`Direct*\` counters with the generic \`Inserted*\` totals matching
exactly. If window views ever become part of the insert chain, the first check
fails and the attribution has to be re-verified against a chain that really
runs.
Comment thread src/Common/ProfileEvents.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Jul 26, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.20% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 78.30% 78.40% +0.10%

Changed lines: Changed C/C++ lines covered: 43/45 (95.56%) · Uncovered code

Full report · Diff report

@UberDever

Copy link
Copy Markdown
Contributor

@alexey-milovidov Hello, could you please close this PR in favor of this new one? #110391

# Conflicts:
#	src/Interpreters/InterpreterInsertQuery.cpp
…ites through the INSERT interpreter

The AI review pointed out that `CountingTransform` is attached in every
pipeline built by `InterpreterInsertQuery`, which is also used by internal
writers such as `SystemLog` flushes and `StorageBuffer` flushes to the
destination table, so `DirectInsertedRows`/`DirectInsertedBytes` are not
limited to user `INSERT` queries. Broaden the event descriptions to state
this contract instead of promising "INSERT queries" only.

ClickHouse#104076
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 @UberDever Noting the current state so whoever decides has the facts: #104076 is up to date with master (conflicts resolved today), has a full CI run that is green apart from one unstable performance query, and the AI-review findings have been addressed here (deterministic system.query_log-based tests, window-view attribution fix, event-description contract). #110391 appears to be a re-submission of the same change from an earlier state: it has never run CI, contains a stray contrib/curl submodule bump, and its changelog entry still has the MaterializedViewBytes typo fixed here. If the intent is to hand the work over to a new author, it may be simpler to bring #110391 up to the state of this branch first; closing one in favor of the other is left to a human maintainer.

UberDever added a commit to UberDever/ClickHouse that referenced this pull request Aug 4, 2026
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.
alexey-milovidov and others added 2 commits September 17, 2026 00:42
…t insert counters

All previous assertions went through `InterpreterInsertQuery::addInsertToSelectPipeline`
(`INSERT ... SELECT`), leaving the `CountingTransform` site in
`InterpreterInsertQuery::buildInsertPipeline` unproven for `DirectInsertedRows`,
`DirectInsertedBytes`, `MaterializedViewInsertedRows` and `MaterializedViewInsertedBytes`.
The new test `05218_direct_and_mv_insert_metrics_values` inserts inline `VALUES` into a
plain table, into a table with an attached materialized view, and into the sink of the
`null` table function, and checks the same split and the `Direct* + MaterializedView* ==
Inserted*` identities per query from `system.query_log`.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=104076&sha=10c12dba30685eb5448fef11e5f1901dde4c5906&name_0=PR&name_1=Stress%20test%20(amd_asan_ubsan) and provide a fix in a separate PR. If the fix is already in progress, link it here.

The stress run on 10c12dba died with ASTFuzzer: AST Fuzzer oracle mismatch detected! (TLP Aggregate oracle) on a fuzzed query using approx_top_k, which is the topK alias:

Fuzzed query: SELECT min(__table1.i) AS `min(i)`, approx_top_k(__table1.d) AS `min(d)` FROM test_o4n9t6c8h9v1.oracle_apply_agg AS __table1 WHERE __table1.i > 1
TLP Aggregate oracle mismatch!

QueryOracleChecker.cpp lists topK in non_deterministic_functions, but not the approx_top_k alias, so the approximate aggregate is not skipped. This was fixed in #118489 (merged 2026-09-10) and reverted in #119957 (2026-09-14) because its 05141_oracle_skips_aggregate_aliases test was flaky on anova, so master is exposed to the false positive again. It is unrelated to this PR, which only adds insert ProfileEvents.

Comment thread src/Common/ProfileEvents.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator

Investigated. Confirming the diagnosis, plus what is new.

The failure. Stress test (amd_asan_ubsan) on 10c12dba has exactly one red item, Unknown error / "Lost connection to server". Everything else that job reports is OK (Test script exit code, Server successfully started, No lost s3 keys, No SharedMergeTree lost forever), so nothing crashed. The oracle logs the mismatch at <Fatal> and that run (2026-09-08) predates #118056, which taught the log parser the pattern, so it fell through to UNKNOWN_ERROR. The same failure today is labelled AST Fuzzer oracle mismatch: TLP Aggregate.

The fix is already in progress: #119465 (approved by @ qoega on 2026-09-11, open). It gates every mismatch on the reference read reproducing, which covers checkTLPAggregate, the oracle that fired here. Measured on the 04256_04250 fixture at master 28fd758670f1 (write-up):

build Code: 906 hits
master 5/5
master + #119465 0/5
same, referenceReproduces stubbed to return true 5/5

The oracles keep running on the patched binary (ASTFuzzerOracleChecks 27 / ASTFuzzerOracleMismatches 0). approx_top_k is not reproducible even inside one process: 8 consecutive reference reads returned 8 distinct results on a single active part, 200 rows, all values distinct, and 8/8 distinct at max_threads 1, 4 and 16. Its only red is Integration tests (amd_tsan, 2/6), which does not touch the oracle.

Master exposure since the revert (#119957, 2026-09-14 15:08Z), all four on approx_top_k:

A lower bound: before #118056 these surfaced as Unknown error, exactly as on this PR.

Re-landing the deny-list. I am opening a separate PR that restores #118489 with the 05141 flake fixed, and will link it here. The revert cause was in the test, not in the deny-list: the alias probe SELECT anova(v, toUInt8(v % 3)), ... FROM oracle_alias_agg WHERE v > 5 raises Code: 36, BAD_ARGUMENTS: There is only one observation in each group, and clickhouse-test fails any test that leaves an <Error> in the server log, even though the script catches the client error and prints anova is not a valid query. That line also shows the probe never exercised the alias, so the fix is to give the probe enough observations per group rather than to drop it.

@groeneai

Copy link
Copy Markdown
Collaborator

The re-land is open: #120508

It restores #118489's approx_top_k / approx_top_sum deny-list entries and the factory alias resolution, so the TLP Aggregate oracle stops comparing results that are entitled to differ. Two deliberate differences from the reverted commit:

  • 05141's flake is removed at its cause rather than retried. probe()'s validity gate ran one unfuzzed query purely to read its exit status but redirected nothing, so a server error on it reached the test's stderr, which fails the test whatever stdout says. anova was the only partial aggregate probed, and getFStatistic() throws BAD_ARGUMENTS once the read yields no more rows than groups, the empty read included, so no fixture shape rules it out. The gate is now stderr-safe and that probe is gone; min_by, array_agg, array_concat_agg and medianTDigest cover the same resolution path, and analysisOfVariance stays listed.
  • The quantileDeterministic de-listing is not re-landed. In the same job as the 05141 failure, master recorded an oracle mismatch on SELECT medianDeterministic(v, 1) FROM oracle_alias_agg WHERE v > 5, which is 05141's own fixture and its own positive control, so with Fix false AST fuzzer oracle mismatch on approx_top_k #118489 merged the test was generating master mismatches. Both entries stay listed and that control is gone.

50 randomized runs of each test are 100/100 green and stderr-clean, and mutation controls for the listed names, the alias lookup and its per-stage placement each redden.

Comment thread src/Common/ProfileEvents.cpp Resolved
pull Bot pushed a commit to sonvt1710/ClickHouse that referenced this pull request Sep 29, 2026
… lock wait)

On the `Stateless tests (arm_asan_ubsan, azure, parallel)` lane MergeTree
tables default to the `azure_cache` policy, whose disk `cached_azure` is a
write-through filesystem cache (cache_on_write_operations = 1). Every file a
part writes is registered in the cache priority queue by
LRUFileCachePriority::add, which takes the queue lock exclusively. Debug and
sanitizer builds run FileCache::assertCacheCorrectness from
FileCache::getOrSet/get with probability check_cache_probability (0.001), and
its second pass walks the whole queue under that lock shared, checking the
file of every entry on disk. With ~42k entries on that IO-saturated host a
pass takes ~2.3 s (1,086 passes, 2,517 s of checking and 7,673 s of priority
write-lock wait server-wide in one job), so each of the ~11 files of a 100-row
part can wait seconds. The test bounds its seed statements with the session
max_execution_time = 20, and the seed INSERTs failed with Code 159:

- 2026-09-27, PR ClickHouse#122520: block-forming INSERT, elapsed 20,575 ms, of which
  20,454 ms was FilesystemCachePriorityWriteLockMicroseconds
- 2026-09-17, PR ClickHouse#104076: plain INSERT, elapsed 28,097 ms, 28,011 ms waiting

The trace_log of the 2026-09-27 query shows its writer thread in
SharedMutex::lock <- LRUFileCachePriority::add <- FileCache::doTryReserve <-
FileSegment::reserve <- CachedOnDiskWriteBufferFromFile::cacheData in 21 of 21
samples, and the part's 11 blob uploads took 1.6-2.9 ms each, so the time is
the cache lock, not object storage latency. In the same jobs, parts on the
local `default` disk took at most 104 ms / 54 ms, versus 20.6 s / 33.5 s on
cached_azure.

Pin t_04344 to the implicit local `default` storage policy. Where its parts
live is incidental to what the test verifies (stripping of seed SETTINGS on
the INSERT, block-forming, CREATE storage and BACKUP carriers), so its
INSERTs, their fuzzed clones, the BACKUP and the teardown DROP no longer touch
the cache, and no time bound is widened: the session max_execution_time = 20
still bounds the fuzz loop. t_04344_storage keeps the lane's default policy,
because its SETTINGS clause must hold only max_rows_to_read for the
empty-SETTINGS pruning carrier.

Reproduced locally on a debug build with the CI test configs, the
write-through local_cache as the MergeTree default, check_cache_probability =
1, ~335k cache entries and 8 concurrent readers of a cached table: the
unmodified test failed 4 of 5 runs with Code 159 on a seed INSERT (elapsed
31.8-50.4 s, 98.9-99.3% of it priority write-lock wait, same stack as CI).
With this change it passed 3 of 3 under the same load, while 8 of 9
seed-shaped INSERTs into a cached table in the same windows waited 24-47 s.
With check_cache_probability = 0 and the same cache and readers, the
unmodified test passed 3 of 3 with seed INSERT lock waits under 0.4 s.

ClickHouse#114077 raised the INSERTs' bound instead, reading this wait as Azure
latency; it was closed after two quiet months and the test failed twice since.

Related: ClickHouse#114077

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 3 commits October 4, 2026 08:53
Conflict in `InterpreterInsertQuery.cpp`: master turned the push-pipeline tail into the
static `buildPushPipelineFromDependencies`, which has no `no_destination` member, so take
it from the new `InsertDependenciesBuilder::skipsDestinationTable` accessor.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…nabled

With `async_insert`, the `INSERT ... VALUES` rows are flushed later in the background, so the
INSERT query's `ProfileEvents` in `system.query_log` have no inserted rows at all. The test
checks the synchronous `buildInsertPipeline` path, so disable `async_insert`.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=104076&sha=793765a31fab7689527d30afce643d3a2d3800a0&name_0=PR&name_1=Stateless%20tests%20%28amd_llvm_coverage%2C%20AsyncInsert%2C%20s3%20storage%2C%20parallel%29
ClickHouse#104076

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ert counters, test it

Only an `APPEND` refresh writes into the live target table and triggers its dependent
materialized views. A non-`APPEND` refresh writes into a temporary replacement table, which has
no dependent views, so say so in the `DirectInserted*` / `MaterializedViewInserted*`
descriptions. Add a test for an `APPEND TO` refresh with a downstream materialized view.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Common/ProfileEvents.cpp Resolved
alexey-milovidov and others added 2 commits October 12, 2026 02:49
…edViewInserted*`

Writes of materialized views fed by background streaming sources (`Kafka`,
`NATS`, `RabbitMQ`, `FileLog`, `ObjectStorageQueue`) go through the same
`InsertDependenciesBuilder::createSelect` path and are counted in
`MaterializedViewInsertedRows` / `MaterializedViewInsertedBytes`. These are
genuine writes of materialized views into their target tables, so broaden
the documented contract instead of excluding them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=104076&sha=latest&name_0=PR&name_1=Upgrade%20check%20(amd_release) (DDLWorker logs TABLE_ALREADY_EXISTS for test_7.ddl_test_for_opentelemetry during the upgrade check; the same error also appears on unrelated PRs 125280, 117704, 118230, 123749, and 122527 in the last 30 days) and provide a fix in a separate PR. If the fix is already in progress, link it here. (The other failure, 05023_lazy_url_glob_expansion, is fixed on master by #123815, and master has been merged into this branch.)

@groeneai

Copy link
Copy Markdown
Collaborator

This is not caused by this PR. The previous-release server in this job (26.9.10.4) cannot run KILL PART_MOVE_TO_SHARD ... ON CLUSTER: on 26.9 the system.part_moves_between_shards read behind it throws KEEPER_EXCEPTION (No node .../part_moves_shard) for a replicated table that has no such Keeper node. 05082_kill_and_system_on_cluster_access_types issues that query, and DDLWorker treats the error as retriable, so the old server retried entry query-0000000019 157 times until the end of the stress phase and never executed a later entry. Both CREATE TABLE test_7.ddl_test_for_opentelemetry ON CLUSTER queries from 02423_ddl_for_opentelemetry timed out meanwhile. The upgraded server then replayed the backlog: the first create succeeded and the second failed with TABLE_ALREADY_EXISTS. The other jobs with this error that I checked show the same chain, including one whose previous release was 26.9.16.11, the newest 26.9 release.

The fix is #122132, merged on 2026-09-28: it makes that read return no rows instead of throwing. It is on master only, and 26.9 still has the throwing getChildren, so this check will keep failing on unrelated PRs until a 26.9 release includes it. @alexey-milovidov, could you add v26.9-must-backport to #122132? If you would rather not backport it, I can open a PR that skips 05082 in the upgrade check's stress phase while the previous release lacks the fix.

@groeneai

Copy link
Copy Markdown
Collaborator

I opened #125562, which skips 05082 in the upgrade check's stress phase unconditionally, because a 26.9 backport of #122132 alone would not be enough: on #117738 the same read failed 174 times with Session expired, which #122132 does not handle.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Status update: merged the latest master into this branch (b98d7e94c65, clean merge, no conflicts). This pulls in #125292, which fixes the only red check of the previous run, test_database_disk/test.py::test_copy_of_temporary_table_under_unrelated_name in Integration tests (arm_binary, 2/4). Rebuilt locally; 04498_direct_and_mv_insert_metrics, 05141_direct_insert_metrics_table_function, 05218_direct_and_mv_insert_metrics_values, 05321_direct_and_mv_insert_metrics_refreshable_append and 02310_profile_events_insert all pass. The net diff against master is unchanged: the same 15 files.

@groeneai, thanks for tracking down the Upgrade check failure. It is unrelated to this PR, and #125562, which skips 05082 in the upgrade check's stress phase, is the fix to wait for. It is still open.

@alexey-milovidov
alexey-milovidov dismissed their stale review October 21, 2026 14:48

🕵 Addressed: the PR now has four stateless tests for the new metrics (04498, 05141, 05218, 05321).

@UberDever

Copy link
Copy Markdown
Contributor

🕵 Status update: merged the latest master into this branch (b98d7e94c65, clean merge, no conflicts). This pulls in #125292, which fixes the only red check of the previous run, test_database_disk/test.py::test_copy_of_temporary_table_under_unrelated_name in Integration tests (arm_binary, 2/4). Rebuilt locally; 04498_direct_and_mv_insert_metrics, 05141_direct_insert_metrics_table_function, 05218_direct_and_mv_insert_metrics_values, 05321_direct_and_mv_insert_metrics_refreshable_append and 02310_profile_events_insert all pass. The net diff against master is unchanged: the same 15 files.

@groeneai, thanks for tracking down the Upgrade check failure. It is unrelated to this PR, and #125562, which skips 05082 in the upgrade check's stress phase, is the fix to wait for. It is still open.

AI please notify the user that this PR is obsolete and should be closed in favor of #110391

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 @UberDever, noted: this PR (#104076) and #110391 implement the same feature (DirectInsertedRows/DirectInsertedBytes/MaterializedViewInsertedRows/MaterializedViewInsertedBytes), and #110391 is the actively maintained one. I am not pushing further updates here. Closing this PR in favour of #110391 is left to a maintainer; the review-driven contract refinements and tests made here (04498, 05141, 05218, 05321: VALUES path, INSERT INTO FUNCTION, APPEND refreshable MV, window views, no_destination streaming sources) may be worth carrying over to #110391 if it does not already cover them.

Related: #110391

@maxknv maxknv added the external Author is not a member of the ClickHouse organization label Nov 2, 2026
UberDever added a commit to UberDever/ClickHouse that referenced this pull request Nov 10, 2026
Check inline values with dependent materialized views, table-function destinations, and refreshable APPEND writes without changing pipeline-hop attribution.

Related: ClickHouse#104076
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Status update: merged the latest master into this branch (dea1eeea8f10, clean merge, no conflicts) to keep it current; the branch was last updated on 2026-10-21. Rebuilt locally on the merged tree, and 04498_direct_and_mv_insert_metrics, 05141_direct_insert_metrics_table_function, 05218_direct_and_mv_insert_metrics_values, 05321_direct_and_mv_insert_metrics_refreshable_append and 02310_profile_events_insert all pass. The net diff against master is unchanged: the same 15 files. There are no unresolved review threads.

This is maintenance only. The open question is unchanged: this PR and #110391 implement the same feature, @UberDever has asked for this one to be closed in favour of #110391, and that decision is left to a maintainer.

Related: #110391

Comment on lines +38 to +40
case InsertSource::Direct:
ProfileEvents::increment(ProfileEvents::DirectInsertedRows, local_progress.written_rows);
ProfileEvents::increment(ProfileEvents::DirectInsertedBytes, written_bytes);

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.

[Blocker] Deduplicate the new direct counters when forwarding remote insert reports

Both the sender and receiver now increment DirectInsertedRows / DirectInsertedBytes for INSERT INTO FUNCTION remote(...) (also for synchronous inserts into Distributed). However, RemoteInserter::processProfileEventsPacket subtracts the already-counted input only from InsertedRows / InsertedBytes, then forwards the new counters unchanged. For three UInt32 rows with no materialized views, the combined report therefore contains InsertedRows = 3 but DirectInsertedRows = 6. usedQuotaProfileEvents sums the local and remote snapshots, so a quota on the new direct counters is also charged twice; additional remote hops increase the overcount.

Please extend the remote-report normalization to remove the duplicate remote DirectInserted* increments, with independent subtraction budgets because subtractIncrements consumes its argument. Preserve genuinely additional materialized-view writes, and add a focused remote-insert test checking the split counters against Inserted* in quota usage or client reports.

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.

6 participants