Skip to content

Make CREATE MATERIALIZED VIEW ... POPULATE atomic - #108715

Merged
alexey-milovidov merged 58 commits into
masterfrom
atomic-populate-materialized-view
Aug 10, 2026
Merged

alexey-milovidov merged 58 commits into
masterfrom
atomic-populate-materialized-view

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jun 27, 2026 •

Copy link
Copy Markdown
Member

Creating a materialized view with POPULATE was never atomic. The view is subscribed to new inserts of the source table and, separately, filled with the data that already exists in the source. Because those two steps used independent, uncoordinated snapshots, a row inserted concurrently with the population could be delivered to the view and also appear in the population snapshot (duplicated), or be routed nowhere and miss the snapshot (lost). This is the long-standing reason the docs said "we do not recommend using POPULATE".

This makes POPULATE atomic: the view is subscribed to new inserts and a snapshot of the existing data is captured together, under a brief exclusive lock on the source table. An INSERT into the source holds a shared lock on it from before it decides which views to push to until after its part is committed, so the exclusive lock drains all in-flight inserts (their data is in the snapshot and they did not see the view yet) and blocks new ones (which, once we release, see the view and are not in the snapshot). Every concurrently inserted row therefore lands on exactly one side of the cut. The snapshot is captured without taking the shared lock, and the population then reads that pinned snapshot without holding any lock, so the lock window stays short even for a long-running population.

This is controlled by the new setting materialized_views_populate_atomically (enabled by default). It works for sources that can provide a pinned point-in-time snapshot — the MergeTree family and Memory. For any other source (a view, Distributed, Merge, Buffer, the Log family, or a table not in an Atomic database) the population falls back to the legacy non-atomic behavior (recorded in the server log), so existing POPULATE queries keep working; set the setting to 0 to force the legacy behavior for all sources. It applies to plain CREATE MATERIALIZED VIEW only - CREATE OR REPLACE / REPLACE always use the legacy non-atomic population, and so does a view created in a Replicated database (where POPULATE requires database_replicated_allow_heavy_create), because a failed population could not be rolled back consistently on all replicas there - and the cut is local: the exclusive lock only serializes with inserts taken on the same server, so inserts arriving on another replica of a ReplicatedMergeTree source or through a distributed write path are not covered.

This change also allows POPULATE together with TO, which was previously a syntax error: it backfills the (possibly non-empty) target table from the existing source data. A failed population drops the just-created view but cannot remove rows already appended to the pre-existing target table — the same semantics as a failed INSERT ... SELECT into that table — so a retry may insert them again.

Closes: #2901
Closes: #51465

Changelog category (leave one):

  • New Feature

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

Plain CREATE MATERIALIZED VIEW ... POPULATE is now locally atomic: the view is subscribed to new inserts of the source table and the existing data is snapshotted together under a brief exclusive lock on the source, so rows inserted through the same server concurrently with the population are no longer missed or duplicated (new setting materialized_views_populate_atomically, enabled by default). The guarantee covers the local insert path only - inserts arriving on another replica or through a distributed write path are outside the cut - and it requires a source that can provide a pinned snapshot (the MergeTree family and Memory); other sources, as well as CREATE OR REPLACE / REPLACE and views created in Replicated databases, keep the legacy non-atomic population. POPULATE can now also be used together with TO to backfill the target table.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Creating a materialized view with `POPULATE` was never atomic: the view is
subscribed to new inserts of the source table and, separately, filled with the
data that already exists in the source. Because those two steps used
independent, uncoordinated snapshots, a row inserted concurrently with the
population could be delivered to the view and also appear in the population
snapshot (duplicated), or be routed nowhere and miss the snapshot (lost).

Fix it by subscribing the view and capturing a snapshot of the source together,
under a brief exclusive lock on the source table. An `INSERT` into the source
holds a shared lock on it from before it decides which views to push to until
after its part is committed, so an exclusive lock drains all in-flight inserts
(their data is in the snapshot and they did not see the view) and blocks new
ones (which, once we release, see the view and are not in the snapshot). Every
concurrently inserted row therefore lands on exactly one side of the cut. The
snapshot is captured via `getStorageSnapshot` (which does not take the shared
lock, so it does not conflict), and the population then reads that pinned
snapshot without holding any lock - so the lock window stays short even for a
long-running population.

The pinned snapshot is threaded into the population `SELECT` through a new
per-table-uuid entry on `Context`, returned by `getStorageSnapshot`. It works
for sources that keep their snapshot in the `StorageSnapshot` object and honor
it on read - the `MergeTree` family and `Memory` (`supportsPinnedSnapshot`).
For any other source (a view, `Distributed`, `Merge`, `Buffer`, the `Log`
family, or a table not in an `Atomic` database) the population falls back to
the legacy non-atomic behavior and records it in the server log, so existing
`POPULATE` queries keep working.

Controlled by the new setting `materialized_views_populate_atomically`
(default on); set it to `false` to force the legacy behavior for all sources.

Also allow `POPULATE` together with `TO`: it now backfills the target table
(which may already contain data) from the existing source data, instead of
being a syntax error.

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

clickhouse-gh Bot commented Jun 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8c06b1f]

Summary: ✅


AI Review

Summary

This PR makes plain CREATE MATERIALIZED VIEW ... POPULATE locally atomic for MergeTree-family and Memory sources by taking the subscription cut and source snapshot together, adds the TO ... POPULATE backfill path, and narrows the documented fallback/rollback behavior for unsupported or legacy paths. I re-checked the current head against the full prior review history and the remaining concurrency/rollback fixes, and I did not find any new actionable issues.

Final Verdict

✅ Approve

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.60% 86.60% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.80% 78.80% +0.00%

Changed lines: Changed C/C++ lines covered: 221/232 (95.26%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 27, 2026
alexey-milovidov and others added 2 commits June 27, 2026 23:16
The atomic-populate dispatch was only wired into the plain CREATE path, so
`CREATE OR REPLACE` / `REPLACE MATERIALIZED VIEW ... POPULATE` (which go through
doCreateOrReplaceTable) kept the legacy non-atomic population while the setting
and docs advertised atomicity. Route doCreateOrReplaceTable through the same
exclusive-lock + pinned-snapshot path: it populates the temporary view that is
then atomically swapped in, so the cut applies to that view's subscription and
the EXCHANGE/RENAME carries it over to the final name. Falls back to the legacy
path for sources that cannot provide a pinned snapshot, same as the plain path.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Extend 04414 to run the exact-once concurrency check for both plain CREATE and
CREATE OR REPLACE MATERIALIZED VIEW ... POPULATE.

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

Copy link
Copy Markdown
Member Author

Addressed the AI review's request: CREATE OR REPLACE / REPLACE MATERIALIZED VIEW ... POPULATE is now atomic too, instead of staying on the legacy path while the contract advertised atomicity.

doCreateOrReplaceTable is routed through the same exclusive-lock + pinned-snapshot helper as plain CREATE: it populates the temporary view that is then atomically swapped in, so the cut applies to that view's subscription and the EXCHANGE/RENAME carries it over to the final name. It falls back to the legacy path for sources that cannot provide a pinned snapshot, same as the plain path.

Extended 04414_atomic_populate_materialized_view.sh to run the exact-once concurrency check for both plain CREATE and CREATE OR REPLACE. Pushed in 9be1c43 and 31d4069.

@clickhouse-gh clickhouse-gh Bot added pr-feature Pull request with new product feature and removed pr-bugfix Pull request with bugfix, not backported by default labels Jun 27, 2026
The atomic populate cut does not compose correctly with the create-or-replace
flow: doCreateOrReplaceTable populates a temporary view and then atomically
swaps it in via EXCHANGE/RENAME, while the old view is still subscribed to the
source. Routing the temporary view's population through the exclusive-lock +
pinned-snapshot helper raced under load (the flaky/stress and tsan/msan/debug CI
jobs caught 04414 producing both missed and duplicated rows for the replace
round), so revert that and keep CREATE OR REPLACE / REPLACE on the legacy
non-atomic population, as the previous commit already documented for sources
that cannot be pinned. Only the plain CREATE flow is atomic.

Narrow the test back to plain CREATE for the concurrency check, add a functional
(non-concurrent) CREATE OR REPLACE ... POPULATE case, and document the limit.

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

Copy link
Copy Markdown
Member Author

Follow-up on the CREATE OR REPLACE atomicity question: I investigated making CREATE OR REPLACE / REPLACE MATERIALIZED VIEW ... POPULATE atomic too, but it turns out the non-atomicity there is a pre-existing race in the replace machinery, not in the POPULATE snapshot cut this PR addresses.

A CREATE OR REPLACE MATERIALIZED VIEW loses rows inserted into the source concurrently with the replace even on unmodified master (forcing the legacy path with materialized_views_populate_atomically = 0): in an aggressive repro it dropped ~23k of 30k concurrent rows. The replace builds a temporary view and swaps it in via EXCHANGE/RENAME, and the source subscription is not transferred atomically with respect to in-flight inserts. My pinned-snapshot mechanism is a different mechanism and can't close that gap.

Filed it as a separate issue: #108726

So this PR keeps plain CREATE MATERIALIZED VIEW ... POPULATE atomic (its own mechanism, tested under stress) and leaves CREATE OR REPLACE / REPLACE on the documented legacy population. Reverted the atomic-replace attempt in 18c2539.

alexey-milovidov and others added 8 commits June 28, 2026 16:37
The plain-CREATE atomic populate test flakes very rarely (only under the
amd_tsan flaky check and arm parallel jobs, ~1/100) with a `0 0` result
(duplicate rows in the view). It is not reproducible locally even under
ThreadSanitizer + the flaky-check Thread Fuzzer config + parallel load, and
ThreadSanitizer reports no data race in the relevant code, so the cut logic
appears sound. Instrument the test so the next CI failure carries actionable
evidence: check the background CREATE's exit code and, on any mismatch, dump
the mv/src counts and a sample of the duplicated and missing ids (and the
CREATE stderr). The success path output is unchanged, so the reference still
matches on the (overwhelmingly common) passing run.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The atomic population pinned the source snapshot on `populate_context`, a copy
of the query context, then ran the population `INSERT ... SELECT` with that
context. But the SELECT is analyzed and executed under contexts derived from the
shared query context (`Context::getQueryContext`), not under `populate_context`
itself, so `MergeTreeData::getStorageSnapshot` did not find the pin and took a
fresh snapshot of the source instead. That fresh snapshot included rows inserted
concurrently with the population, and those rows are also delivered to the view
through the live insert path - so they ended up in the view twice.

This manifested as a flaky `04414_atomic_populate_materialized_view` failure in
CI (`0 0`: the view had duplicate rows, no missing rows). It reproduces reliably
with `merge_tree_storage_snapshot_sleep_ms` plus a concurrent insert: before this
change the view gets thousands of duplicated ids; after it, every row is
delivered exactly once.

Pin the snapshot on the shared query context (and, harmlessly, on
`populate_context`), and have `getStorageSnapshot` also consult the query context
for the pin. Verified locally against a server build: the repro that produced
40000 duplicates now yields 0 duplicates / 0 missing across many runs, and the
exact `04414` scenario returns `1 1` consistently. Legacy
(`materialized_views_populate_atomically = 0`) population is unaffected.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108715&sha=336bb1537412d5bfca0d20186af210a006e9df2f&name_0=PR
Related: #108715

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

Master added `04414_window_transform_cume_dist_peer_groups` and
`04415_use_legacy_to_time_default` while this branch was in flight, colliding
with the atomic-populate tests. Renumber them to the next free numbers
(`04416`/`04417`) and update the internal `create_err` temp-file reference.
The in-flight PR #108657 already claims `04416` (`04416_max_threads_auto_parsing_compat`),
so move the atomic-populate tests off it to the next free pair (`04418`/`04419`) and update
the internal `create_err` temp-file reference.
The atomic `CREATE MATERIALIZED VIEW ... POPULATE` fix in `1ec0c5e2c9a` taught
`MergeTreeData::getStorageSnapshot` to also consult the query context for the
pinned snapshot, because the population's `SELECT` reads under contexts derived
from the query context (`getQueryContext`) rather than the exact context the pin
was set on. `StorageMemory::getStorageSnapshot` only checked the immediate
context, so for a `Memory` source the pin was not found and the population took a
fresh snapshot that could include rows inserted concurrently with the population
- the same duplication this PR fixes for `MergeTree`. Since `Memory` is one of
the advertised pinnable sources (`supportsPinnedSnapshot`), apply the same
query-context fallback for consistency.

Memory concurrency cannot be deterministically reproduced in a stateless test
(there is no snapshot-delay knob like `merge_tree_storage_snapshot_sleep_ms`),
so this mirrors the verified `MergeTree` fix; the non-concurrent `Memory` case is
covered by `04419_atomic_populate_materialized_view_features`.

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

Master added `04418_numeric_indexed_vector_multiply_zero_integer_bits` and
`04419_numeric_indexed_vector_multiply_all_ones_index_sets`, which collide on
the number prefix with this PR's `04418`/`04419` atomic-populate tests. Renumber
this PR's tests to the next free numbers above master's current highest (04488),
and update the internal temp-file name accordingly.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Match the renamed test: the `create_err` temp file is now `04489_create.err`
instead of `04418_create.err`.

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

Copy link
Copy Markdown
Member Author

Obviously, it is atomic with regard to insertions only on the same server. So don't hold too high expectations.

… master

Master now has `04489_max_threads_auto_parsing_compat`, so the atomic
populate tests (previously `04489`/`04490`) collide with a test already
merged on master. Move them to the next free slots `04490`/`04491` and
update the internal scratch-file name in the shell test accordingly.
Test content is unchanged.

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

Copy link
Copy Markdown
Member Author

Continued this PR:

  • Renumbered the tests 04489/04490 → 04490/04491 (pushed in c40dd5e). Master has since gained 04489_max_threads_auto_parsing_compat, so the atomic-populate tests collided with a test already merged on master. 04490/04491 are free on master; the internal scratch-file name in the shell test was updated to match. Test content is otherwise unchanged.
  • CI is green — 154 success / 19 skipped / 0 failed; the only non-green check is CH Inc sync (PENDING, internal).
  • No unresolved review threads, and the AI Review verdict is ✅ Approve.
  • No conflicts (MERGEABLE); merge-base with master is less than a week old and CI is green, so I did not re-merge master.

The PR is otherwise ready; the BLOCKED merge state is awaiting human approval/merge.

alexey-milovidov and others added 3 commits June 30, 2026 21:33
Address the AI review's request changes: the docs and the
`materialized_views_populate_atomically` setting text claimed that every row
inserted concurrently with population is delivered to the view exactly once,
but the exclusive lock only serializes with inserts that acquire the source
table's storage lock on the same server. Rows inserted on another replica of a
`ReplicatedMergeTree` source or through a distributed write path (a
`Distributed` table or `ON CLUSTER`) during population are outside this cut and
can still be missed or duplicated.

Document this as local insert-path atomicity, not a cluster-wide guarantee, in
both `docs/en/sql-reference/statements/create/view.md` and the setting
description in `src/Core/Settings.cpp`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Master gained `04490_dict_get_keys_float_signed_zero_consistency`,
`04490_table_readonly_partition_commands`,
`04491_dict_get_keys_const_path_non_coordinator_layout`, and
`04491_table_readonly_move_partition_to_table`, which collide with the
atomic-populate tests' `04490`/`04491` prefixes after merging master. Move them
to the free `04492`/`04493` slots and update the internal scratch-file name in
the shell test. Test content is otherwise unchanged.

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

Copy link
Copy Markdown
Member Author

Continued this PR (pushed c40dd5ee2cc..7c1822a7593):

  • Addressed the AI review's "Request changes" verdict (qualify the atomicity guarantee as local insert-path scope). Both docs/en/sql-reference/statements/create/view.md and the materialized_views_populate_atomically setting description now state that the exclusive lock only serializes with inserts that take this source table's storage lock on the same server, so the exactly-once guarantee covers inserts arriving through this server and is not a cluster-wide guarantee — rows inserted on another replica of a ReplicatedMergeTree source, or through a distributed write path (a Distributed table / ON CLUSTER), during population can still be missed or duplicated. This matches the earlier note that it is atomic only with regard to insertions on the same server. Resolved the inline thread.
  • Merged master to clear the CONFLICTING merge state (the branch was 954 commits behind; the merge was clean).
  • Renumbered the tests 04490/04491 → 04492/04493. Master gained 04490_dict_get_keys_float_signed_zero_consistency, 04490_table_readonly_partition_commands, 04491_dict_get_keys_const_path_non_coordinator_layout, and 04491_table_readonly_move_partition_to_table, which collided with the atomic-populate tests' prefixes after the merge. Test content is unchanged.

CI is re-running on the new head.

alexey-milovidov and others added 2 commits August 8, 2026 02:00
…ource-name guard is taken

The atomic `CREATE MATERIALIZED VIEW ... POPULATE` validates the view's
SELECT (which resolves the source table) before acquiring the DDL guard of
the source table's name. A `DROP` of the source landing in that window used
to slip past the rollback contract: the view was published,
`getValidatedAtomicPopulateSource` found no source and fell back to the
legacy population, whose `INSERT ... SELECT` then failed with
`UNKNOWN_TABLE` outside the rollback scope of
`fillMaterializedViewAtomically` - the half-created view (subscribed to a
name nobody owns) was left behind and a retry got `TABLE_ALREADY_EXISTS`.

Now `getValidatedAtomicPopulateSource` throws `UNKNOWN_TABLE` when the
already-validated source is gone: the throw lands inside the rollback scope,
so the just-published view is dropped and the failed CREATE leaves behind
nothing of what it created. A new pauseable failpoint
`atomic_populate_pause_before_source_guard` pins the race window in the new
test 04824_atomic_populate_materialized_view_source_dropped_before_guard.

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

Copy link
Copy Markdown
Member Author

🕵 The sole CI failure on head 9e51bddcb14, Stress test (arm_release) — Logical error: 'Not-ready Set is passed as the second argument for function 'globalNotIn'' in VirtualColumnUtils::filterByPathOrFile over object storage (report) — is unrelated to this PR (this PR touches no object-storage or Set code). It is the known GLOBAL IN over object-storage _path/_file issue #107619, fix in progress: #112968.

…urce-name DDL guard

The atomic `CREATE MATERIALIZED VIEW ... POPULATE` validates the view's
SELECT (taking a storage snapshot of the source table, which
`enable_shared_storage_snapshot_in_query` caches in the query-scoped
snapshot cache with a reference to the source storage held until the query
ends) and then blocks acquiring the source-name DDL guard. A concurrent
synchronous `DROP` of the source (`DROP TABLE ... SYNC`, or any `DROP`
under `database_atomic_wait_for_drop_and_detach_synchronously`, the
stateless-test default) holds that guard and, after detaching the table,
waits for every reference to the storage to be released - a deadlock.

In CI the failpoint `atomic_populate_pause_before_source_guard` made this
deterministic: test 04824 timed out at the `DROP`, its kill leaked the
enabled pauseable failpoint server-wide, and subsequent `POPULATE` tests
(04653, 04813, 04727, 00609_mv_index_in_in) hung on it and failed too:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108715&sha=8ce0372abedc8907558cf0c77e23d7505c74a1c7&name_0=PR&name_1=Fast%20test

Drop the source's cached validation snapshot before taking the guard (the
same pattern `InterpreterAlterQuery` uses for the metadata cache): it is of
no further use, because the population pins its own snapshot under the
source's exclusive lock in `fillMaterializedViewAtomically`.

#108715

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

Copy link
Copy Markdown
Member Author

🕵 The Fast test failure on head 8ce0372abed was a genuine deadlock in this PR, made deterministic by the new failpoint: the CREATE's SELECT validation left a storage snapshot of the source in the query-scoped snapshot cache (enable_shared_storage_snapshot_in_query), holding a reference to the source storage while the CREATE blocked on the source-name DDL guard — and the concurrent synchronous DROP of the source (the stateless-test default via database_atomic_wait_for_drop_and_detach_synchronously; DROP TABLE ... SYNC in production) held that guard while waiting for all references to the storage to be released. Test 04824 timed out on the DROP, and its kill leaked the enabled pauseable failpoint server-wide, hanging the other POPULATE tests (04653, 04813, 04727, 00609_mv_index_in_in) as collateral.

Fixed in 8c06b1f: the source's cached validation snapshot is released before taking the source-name guard (the population pins its own snapshot later, under the source's exclusive lock, so the validation snapshot is of no further use). Locally reproduced the hang against a server with the harness's synchronous-drop default and verified the fix: the sync DROP now completes while the CREATE is paused at the failpoint, and all 12 atomic-populate tests plus 00609_mv_index_in_in pass (04824 run 5×).

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The sole CI failure on head 8c06b1f2, Stress test (amd_tsan) — Logical error: '(isConst() || isSparse() || isReplicated() || rhs.isConst() || rhs.isSparse() || rhs.isReplicated()) ? getDataType() == rhs.getDataType() : typeid(*this) == typeid(rhs)' in IColumn::assertTypeEquality via HashJoin buildAdditionalFilter (report) — is unrelated to this PR: this PR touches only the POPULATE create path, StorageMemory, MergeTreeData snapshot pinning, settings, docs, and tests — no join code. CIDB shows the same assertion hitting master and ~20 unrelated PRs per day since 2026-08-04.

It is the known mixed JOIN ON condition over a dictionary with join_use_nulls bug:
Related: #113931
Fixes in flight (neither merged yet, so re-merging master would not clear it): #113534 and #113933

I re-ran the failed job to clear the required-check gate. Otherwise the PR is healthy: the AI Review verdict on this head is ✅ Approve, there are no unresolved review threads, all other checks passed (155 green), and the branch is MERGEABLE (~1 day behind master). The Fast-test deadlock found on the previous head was fixed in 8c06b1f2 (see the previous comment). Awaiting the stress re-run and the human merge decision.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The CH Inc sync check was stuck on "Conflicts found": the private sync PR could not be merged with private master. Resolved it by merging private master into the sync branch — two trivial include/error-code conflicts, plus one adaptation: private master had refactored the snapshot-delay injection into a void helper injectSleepBeforeCreatingStorageSnapshot, and the mechanical merge placed this PR's pinned-snapshot check inside that helper, where return pinned would not compile. Moved the check to the top of MergeTreeData::getStorageSnapshot, before the delay injection, matching the upstream semantics. Both translation units verified with -fsyntax-only against the private build. The sync PR is now MERGEABLE; the check should refresh once private CI finishes. Everything else is green on 8c06b1f (AI review: Approve, no unresolved threads).

@clickhouse-gh

clickhouse-gh Bot commented Aug 9, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 37 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: 15562350-0407-44ca-b48e-827f9598787f
  • MIRAI run: 6aa0e85d-a512-4e08-994d-63afa4f7e5a8
  • PR check IDs:
    • clickbench_461438_1786282935
    • clickbench_461444_1786282935
    • clickbench_461455_1786282936
    • tpch_adapted_1_official_461467_1786282936
    • tpch_adapted_1_official_461480_1786282935
    • tpch_adapted_1_official_461509_1786282936

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

A few questions on this change:

Why do we acquire a full table snapshot in advance? Couldn't we reuse the mechanism of SELECT from a single snapshot, construct a SELECT pipeline under a lock, then run it outside of the lock?

Why do we create a table and explicitly drop it on exception? Shouldn't we reuse the mechanism of temporary tables (which Atomic databases allow with arbitrary engines)?

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Answering the two questions from #108715 (review), after checking the alternatives against the code:

Why do we acquire a full table snapshot in advance? Couldn't we reuse the mechanism of SELECT from a single snapshot, construct a SELECT pipeline under a lock, then run it outside of the lock?

The population does reuse the single-snapshot SELECT mechanism. The pinned snapshot is an ordinary StorageSnapshot — the same object every SELECT builds; for MergeTree it is a list of pinned data parts (no data is copied), for Memory a COW reference to the block list — and the population's INSERT ... SELECT reads it through the standard getStorageSnapshot path. The only addition is which snapshot that path returns: the one captured inside the exclusive-lock window, together with the subscription (that simultaneity is the entire atomicity argument), instead of a fresh one at analysis time. Since the pipeline is built after the lock is released, something must carry the captured snapshot to the build; the pin — a small UUID-keyed map on the query context, consulted unconditionally by getStorageSnapshot — is that carrier.

Constructing the pipeline under the lock does not work with our locking primitive, and would be undesirable even if it did:

  1. Building the pipeline takes lockForShare on the source (the TableNode constructor does it, with the initial query id). The fast path of RWLockImpl::getLock throws RWLockImpl::getLock(): RWLock is already locked in exclusive mode when the same query already holds the lock exclusively — a logical error, by design (src/Common/RWLock.cpp). Taking the shared lock under a different query id instead queues it behind our own write group in the phase-fair queues — a self-deadlock until the timeout. So build-under-lock requires either teaching the interpreters to skip the share lock, or adding a write-to-read downgrade to the phase-fair RWLock — surgery in one of the trickiest primitives we have, in exchange for removing a small map.

  2. Even with such a downgrade, the exclusive window would grow from "register the dependency + copy the parts list" (microseconds to low milliseconds) to the full analysis, planning and PK/index analysis of the view's SELECT — ReadFromMergeTree::selectRangesToRead runs at pipeline-build time and can take seconds on tables with many parts or heavy key conditions. Every concurrent INSERT into the source is stalled for that whole window; keeping the window minimal is the point of the design.

  3. Build-under-lock would remove only the pin; the rest stays. Parallel-replica and distributed-insert scrubbing is still needed, because remote executions take their own snapshots at execution time regardless of where the pipeline was built, and the stale validation-time snapshot in the per-query snapshot cache still has to be evicted.

Two variants of the question, also considered:

  • Reusing enable_shared_storage_snapshot_in_query (the existing per-query single-snapshot cache) as the carrier — capture under the lock and seed the query's StorageSnapshotCache instead of adding the pin. Mechanically possible, but the cache lookup is gated on the setting as seen by whichever derived context performs the read, and the cache object exists only if the setting was on when executeQuery started — so the exactly-once guarantee would silently depend on a user-tunable setting reaching every derived read context. We had exactly this class of bug during development (the pin initially lived on the wrong context, the population read a fresh snapshot, and concurrently inserted rows were duplicated — fixed in 1ec0c5e); the unconditional pin is immune to it. Also the cache is consulted by MergeTree only, so Memory would need new code of the same shape either way.

  • Passing the snapshot into the interpreter explicitly, the way mutations do with MutationsInterpreter::Source. That works for the restricted query shapes of mutations; the view's SELECT is arbitrary — the source can appear several times, in subqueries — and every occurrence must see the same snapshot. getStorageSnapshot is the one chokepoint they all pass through, which is why the pin sits at that layer.

Why do we create a table and explicitly drop it on exception? Shouldn't we reuse the mechanism of temporary tables (which Atomic databases allow with arbitrary engines)?

The temporary-table mechanism (doCreateOrReplaceTable: create under a temporary name, fill, publish via RENAME/EXCHANGE) is not cleanup-for-free — its own failure path is the same explicit drop of the temporary table. And for a live-subscribed materialized view it makes things worse, because it adds a second transition at the end, and that transition is exactly where the known race lives:

  1. The atomic cut requires the view to be subscribed to the source before the population starts, so a temporarily-named view would be live during the whole population and the terminal RENAME would move a live subscription. That transfer is not atomic with respect to a concurrent insert's dependent-view discovery — the residual race documented in Fix CREATE OR REPLACE MATERIALIZED VIEW ... POPULATE losing the source subscription #108728 (a row inserted in the instant of the swap can be missed; an insert landing exactly mid-swap can fail with UNKNOWN_TABLE), and the reason this PR deliberately keeps CREATE OR REPLACE ... POPULATE on the legacy path: the atomic-replace attempt (9be1c43) was reverted (18c2539) after the swap race turned out to exist even on master, filed as CREATE OR REPLACE MATERIALIZED VIEW loses inserts made concurrently with the replace #108726. Making the terminal rename safe would need a second exclusive-lock drain of the source's insert path — strictly more locking than the current single cut, with no correctness gain.

  2. If the server dies mid-population, the temporary-name design leaves a hidden temporarily-named view still subscribed to the source, silently receiving every insert forever. The current design leaves the view under its real name, partially populated — visible, understandable, droppable, and the same artifact legacy POPULATE has always left in that case.

  3. It changes user-visible semantics: POPULATE has always published the view immediately (queryable and receiving live inserts while it fills up). Publishing at the end also means holding the view name's DDL guard across an arbitrarily long population — or racing to lose the name and waste the whole population at the final rename.

  4. The TO target form has nothing to stage: the population appends to a pre-existing target table that is not ours to swap or roll back. The drop of just the view shell is the one rollback that works uniformly for both the ENGINE and the TO forms.

Session temporary tables (the other reading of "temporary tables") cannot hold the view at all: they are visible only to the creating session, while the whole point of the cut is that other sessions' inserts must discover the view and push into it during the population.

@alexey-milovidov alexey-milovidov self-assigned this Aug 10, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Defended.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 10, 2026
Merged via the queue into master with commit b73e960 Aug 10, 2026
354 of 355 checks passed
@alexey-milovidov
alexey-milovidov deleted the atomic-populate-materialized-view branch August 10, 2026 23:37
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 11, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@alexey-milovidov — this PR looks backward incompatible but is categorized as New Feature.

Why: ParserCreateQuery.cpp:1778 adds an unconditional if (is_populate && refresh_strategy) throw ... SYNTAX_ERROR; before this PR the non-TO branch (ParserCreateQuery.cpp:1715) accepted REFRESH ... ENGINE = ... POPULATE and no other layer rejected the combination, so a query that parsed and ran before now fails at parse time. The default flip of materialized_views_populate_atomically additionally changes failure semantics of POPULATE (the view is dropped on failure instead of being left behind).

Suggested category: Backward Incompatible Change. Ignore if the change is intentionally non-breaking.

clickgapai added a commit to clickgapai/ClickHouse that referenced this pull request Aug 12, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
The test loads a 14.7 MB real-world ghdata JSON, builds a text index over
JSONAllValues, OPTIMIZE FINAL, then runs ~35 queries. It is inherently heavy and
only the amd_msan (WasmEdge) build overruns the 600s per-test cap: CIDB over 45d
shows amd_msan max 600.2s vs tsan 273s, asan 226s, debug 60s, arm 74s. This is
raw runtime on the slowest build, not a randomized-setting issue (CIDB rerun
diagnosis: same settings passed on rerun). Add no-msan to skip only that build.

MSan coverage of JSON parsing is retained by sibling ghdata tests
(01825_json_type_ghdata, 03247_ghdata_string_to_json_alter,
03273_ghdata_json_to_json_alter) and of the text index by the 02346_text_index_*
suite. Same precedent as sibling 01825_json_type_ghdata_insert_select (same
dataset), already tagged no-asan, no-tsan, no-msan.

Related: ClickHouse#108715

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

Labels

pr-feature Pull request with new product feature 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.

Please allow creating a materialized view with TO [db].[table] and POPULATE Allow inserting data into a materialized view that is being populated

4 participants