Repository navigation
Make CREATE MATERIALIZED VIEW ... POPULATE atomic - #108715
Conversation
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]>
|
Workflow [PR], commit [8c06b1f] Summary: ✅
AI ReviewSummaryThis PR makes plain Final Verdict✅ Approve LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 221/232 (95.26%) · Uncovered code |
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]>
|
Addressed the AI review's request:
Extended |
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]>
|
Follow-up on the A Filed it as a separate issue: #108726 So this PR keeps plain |
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]>
|
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]>
|
Continued this PR:
The PR is otherwise ready; the |
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]>
|
Continued this PR (pushed
CI is re-running on the new head. |
…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]>
|
🕵 The sole CI failure on head |
…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]>
|
🕵 The Fast test failure on head 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 |
|
🕵 The sole CI failure on head It is the known mixed 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 |
|
🕵 The |
|
📊 Cloud Performance Report ✅ AI verdict: 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
|
alexey-milovidov
left a comment
There was a problem hiding this comment.
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)?
|
Answering the two questions from #108715 (review), after checking the alternatives against the code:
The population does reuse the single-snapshot SELECT mechanism. The pinned snapshot is an ordinary Constructing the pipeline under the lock does not work with our locking primitive, and would be undesirable even if it did:
Two variants of the question, also considered:
The temporary-table mechanism (
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. |
|
Defended. |
|
@alexey-milovidov — this PR looks backward incompatible but is categorized as Why: Suggested category: |
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]>
Creating a materialized view with
POPULATEwas 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 usingPOPULATE".This makes
POPULATEatomic: 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. AnINSERTinto 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 — theMergeTreefamily andMemory. For any other source (a view,Distributed,Merge,Buffer, theLogfamily, or a table not in anAtomicdatabase) the population falls back to the legacy non-atomic behavior (recorded in the server log), so existingPOPULATEqueries keep working; set the setting to0to force the legacy behavior for all sources. It applies to plainCREATE MATERIALIZED VIEWonly -CREATE OR REPLACE/REPLACEalways use the legacy non-atomic population, and so does a view created in aReplicateddatabase (wherePOPULATErequiresdatabase_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 aReplicatedMergeTreesource or through a distributed write path are not covered.This change also allows
POPULATEtogether withTO, 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 failedINSERT ... SELECTinto that table — so a retry may insert them again.Closes: #2901
Closes: #51465
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Plain
CREATE MATERIALIZED VIEW ... POPULATEis 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 settingmaterialized_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 (theMergeTreefamily andMemory); other sources, as well asCREATE OR REPLACE/REPLACEand views created inReplicateddatabases, keep the legacy non-atomic population.POPULATEcan now also be used together withTOto backfill the target table.Documentation entry for user-facing changes