Skip to content

Do not take a data snapshot of the source table for materialized view inserts - #122603

Merged
antonio2368 merged 9 commits into
masterfrom
mv-source-snapshot-without-data
Nov 6, 2026
Merged

antonio2368 merged 9 commits into
masterfrom
mv-source-snapshot-without-data

Conversation

@al13n321

@al13n321 al13n321 commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

When a block is inserted into a table with materialized views, the SELECT of every view is analyzed with the real source table, and only afterwards the table is replaced by the inserted block in replaceStorageInQueryTree. The analyzer resolved the source table through getStorageSnapshot, which for MergeTree collects all active parts and the mutations snapshot. The result was thrown away, so the cost, proportional to the number of active parts multiplied by the number of views, was wasted on every inserted block. On a wide SharedReplacingMergeTree table with about 2,000 parts and 10 views this was about 44 ms of CPU per async insert flush.

The per-query snapshot cache of enable_shared_storage_snapshot_in_query could not mitigate this: the async insert flush never attaches it, and since #112991 it is no longer kept alive during pipeline execution, when the views are processed, for synchronous inserts either.

Now IdentifierResolver::tryResolveTableIdentifier uses getStorageSnapshotWithoutData when the context carries a view source with the same name as the resolved table, exactly the condition under which the table is later replaced by the block. The snapshot is only used for metadata and column resolution in this case.

Related: #112991

Changelog category (leave one):

  • Performance Improvement

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

Inserts into tables with materialized views no longer take a snapshot of all active parts of the source table for every view and every inserted block. This removes CPU overhead proportional to the number of parts multiplied by the number of views, for both synchronous and asynchronous inserts.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.11.1.1529-master (included in 26.11 and later)

… inserts

When a block is inserted into a table with materialized views, the SELECT of
every view is analyzed with the real source table, and only afterwards the
table is replaced by the inserted block in `replaceStorageInQueryTree`. The
analyzer resolved the source table through `getStorageSnapshot`, which for
`MergeTree` collects all active parts and the mutations snapshot. The result
was thrown away, so the cost, proportional to the number of active parts
multiplied by the number of views, was wasted on every inserted block.

The per-query snapshot cache of `enable_shared_storage_snapshot_in_query`
could not mitigate this: the async insert flush never attaches it, and since
#112991 it is no longer kept
alive during pipeline execution, when the views are processed, for
synchronous inserts either.

Now `IdentifierResolver::tryResolveTableIdentifier` uses
`getStorageSnapshotWithoutData` when the context carries a view source with
the same name as the resolved table, exactly the condition under which the
table is later replaced by the block. The snapshot is only used for metadata
and column resolution in this case.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e605564]

Summary: ✅


AI Review

Summary

The PR avoids collecting source-table parts during materialized-view analysis when the interpreter will replace that source with the inserted block. Reviewed head e605564b30f5c1b6e610bb2c41bae7e49a9590ec: no unresolved findings. The previous nested-analyzer block-type finding is addressed in the current code.

Snapshot consumers traced:

  • Column resolution, matchers, query-tree optimization passes, and getResultColumnOrigins consume metadata; TableNode modifiers preserve the snapshot data without interpreting it.
  • Scalar-subquery evaluation, IN handling, interpreter replacement, and filter planning substitute the inserted block before execution. Materialized and recursive CTE query children remain reachable by replacement.
  • Ordinary-view bodies and actual merge child reads retain full snapshots; nested analyses without replacement storage also retain full snapshots. StorageAlias forwards snapshot acquisition to its target.

The focused 05289 test and related source-substitution regressions passed in Fast test. A local run of 05289 using the head's CI binary with asynchronous inserts enabled in the server profile matched the reference exactly, including both zero-snapshot assertions.

Final Verdict

Status: ✅ Approve. No new inline findings to post.

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements comp-materialized-view Materialized views: insert-triggered MV pipeline, insert dependencies, deduplication. labels Sep 28, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing e605564b3 with master c9e18d017 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 831894676; 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.

Compile time of recompiled translation units

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

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

Job report

@clickhouse-gh

clickhouse-gh Bot commented Sep 28, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This PR changes one path: when a materialized view's SELECT runs over an inserted block, the source table is now snapshotted without data. Plain ClickBench and TPC-H SELECTs never take that path. For them the only new cost is one cheap view-source check. The ClickBench Q23 improvement (-46.8%, CPU time also well down) can't come from this diff, so it is downgraded to not_sure. It most likely reflects a difference between the PR build and the master baseline build, since the PR's 50 ms median sits at the fast edge of master's recent 52–100 ms range. Q34 (-6.1%) is inside master's normal variance and correctly counts as no change.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 23 not_sure 94 50 -46.8% <0.0001 The -46.8% gain is not explained by this diff, which only changes how MV inserts snapshot their source table. Q23 is a plain SELECT on hits and never takes that branch.

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: f5698ead-1061-4a17-a38a-cf31232ad272
  • MIRAI run: f77c4280-05fe-453b-9fba-8e5a1333cf1c
  • PR check IDs:
    • clickbench_2173159_1790575099
    • clickbench_2173172_1790575099
    • clickbench_2173178_1790575099
    • tpch_adapted_1_official_2173184_1790575099
    • tpch_adapted_1_official_2173196_1790575099
    • tpch_adapted_1_official_2173230_1790575099

# Conflicts:
#	src/Analyzer/Resolve/IdentifierResolver.cpp
…rge` with a `Distributed` table

A materialized view (or the `RETURNING` query of an `INSERT`) is analyzed with
the inserted block as the view source. `IdentifierResolver::tryResolveTableIdentifier`
gave every reference to the source table the metadata of the block, which has no
primary key. This is correct only for the references that `replaceStorageInQueryTree`
later replaces with the block. A nested analysis also has the view source in its
context but does not replace the reference: `ReadFromMerge::createPlanForTable`
analyzes the child query again when `merge` also covers a `Distributed` table. That
child read the real parts with key-less metadata, and the server crashed in
`KeyCondition`.

Now the analysis gets the storage that its caller replaces afterwards, and only then
does the resolver apply the metadata of the view source. The row policy filter
analysis, which replaces the view source after its own analysis, passes it too.

Related: #122603

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…-snapshot-without-data

The fix (#129493) gives the view source
metadata only to the references that the caller swaps for the block. This PR takes
the snapshot without data only for those references, so nested analyses (such as the
children of `merge` with a `Distributed` sibling) keep reading the real parts.

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

Copy link
Copy Markdown
Member

Depends on this PR #129493

antonio2368 added a commit that referenced this pull request Nov 5, 2026
The previous commit gave the metadata of the inserted block only to the analyses
that got `replaced_storage`. But some nested analyses do not get it and still swap
the block in: an `IN` subquery in the child query of `merge`, and the row policy of
an inlined view (`analyzer_inline_views`). Such a subquery got the types of the
altered source table, but read the block with the old types. The `IN` case gave a
`LOGICAL_ERROR` exception in `arrayExists`, and the policy case removed rows.

Now every reference to the view source outside view inner queries gets the metadata
of the block again, as before the previous commit. The only exception is the root
query of the child query of `merge`, because its table reads the real parts:
`ReadFromMerge::createPlanForTable` marks it with
`SelectQueryOptions::root_query_reads_real_tables`. The mark is a member of
`QueryAnalyzer`, not of the context, so nested analyzers do not get it. This
removes `replaced_storage`.

Related: #129493 (comment)
Related: #122603 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
antonio2368 and others added 2 commits November 5, 2026 17:23
…ough `merge` with a `Distributed` table"

This reverts commit 9696a8c, which came from
#129493. Its rule gave the metadata
of the inserted block only to analyses that swap it in, but nested analyses
that swap in subqueries got the catalog types:
#122603 (comment)
The crash is fixed in master by #129338.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@antonio2368
antonio2368 marked this pull request as ready for review November 6, 2026 07:06
antonio2368 and others added 3 commits November 6, 2026 08:06
…source in

The previous rule skipped the data snapshot of every reference to the view source
in a context that has one. A nested analysis inherits the view source in its
context but may not swap it in, and then it read the real table with no parts:
for example, the children of `merge` with a `Distributed` sibling read 0 rows.

Now `buildQueryTreeAndRunPasses` passes the storage that it swaps in afterwards
(`replaced_storage`, only when it is the view source) through the analysis passes
to `IdentifierResolver::tryResolveTableIdentifier`. Only then is the snapshot taken
without data. Other references keep a full snapshot, so a missed swap costs a full
snapshot, not an empty read. The metadata rule does not change: every reference to
the view source outside view inner queries still gets the types of the block, so a
nested analysis that swaps in an `IN` subquery or a row policy keeps the block's types
(#122603 (comment)).

The test now also reads the source table through `merge` with a `Distributed` sibling.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@antonio2368
antonio2368 added this pull request to the merge queue Nov 6, 2026
Merged via the queue into master with commit 785388b Nov 6, 2026
187 checks passed
@antonio2368
antonio2368 deleted the mv-source-snapshot-without-data branch November 6, 2026 15:09
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 6, 2026
PedroTadim added a commit that referenced this pull request Nov 12, 2026
… `Buffer` over a `Distributed` table

Backport of #125990, ported onto this branch by hand. The fix is written on top of the
`replaced_storage` plumbing of #122603 (and #126075 below it), which this branch does not have, so
the port adds only what the fix needs: `replaced_storage` and `view_source_in_subqueries` through
`addQueryTreePasses`, `QueryAnalysisPass`, `QueryAnalyzer` and `IdentifierResolver`. The resolver
types the source table by the view source only in the analysis that swaps it in, as in #125990; the
data snapshot of the table stays as it is on this branch, since the snapshot-without-data change of
#122603 is a performance change and is not part of this fix.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
PedroTadim added a commit that referenced this pull request Nov 12, 2026
… `Buffer` over a `Distributed` table

Backport of #125990, ported onto this branch by hand. The fix is written on top of the
`replaced_storage` plumbing of #122603 (and #126075 below it), which this branch does not have, so
the port adds only what the fix needs: `replaced_storage` and `view_source_in_subqueries` through
`addQueryTreePasses`, `QueryAnalysisPass`, `QueryAnalyzer` and `IdentifierResolver`. The resolver
types the source table by the view source only in the analysis that swaps it in, as in #125990; the
data snapshot of the table stays as it is on this branch, since the snapshot-without-data change of
#122603 is a performance change and is not part of this fix.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
PedroTadim added a commit that referenced this pull request Nov 12, 2026
… `Buffer` over a `Distributed` table

Backport of #125990, ported onto this branch by hand. The fix is written on top of the
`replaced_storage` plumbing of #122603 (and #126075 below it), which this branch does not have, so
the port adds only what the fix needs: `replaced_storage` and `view_source_in_subqueries` through
`addQueryTreePasses`, `QueryAnalysisPass`, `QueryAnalyzer` and `IdentifierResolver`. The resolver
types the source table by the view source only in the analysis that swaps it in, as in #125990; the
data snapshot of the table stays as it is on this branch, since the snapshot-without-data change of
#122603 is a performance change and is not part of this fix.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-materialized-view Materialized views: insert-triggered MV pipeline, insert dependencies, deduplication. pr-performance Pull request with some performance improvements 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