Repository navigation
Conversation
Insert the new versions first, then delete the older rows of the keys that now have a newer row, using _block_number. A failure between the steps leaves duplicates instead of missing keys. Closes ClickHouse#771.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Closes #771.
delete+insertdeletes the changed keys before it inserts their new versions, so a run that fails between the two statements leaves those keys missing. This PR addsincremental_strategy='insert+delete', which inserts first and deletes the older rows afterwards. A failure between the steps leaves the changed keys duplicated, never missing, and the next run that writes them removes the older rows.How it works
on_schema_changechange, check that the target persists_block_number(enable_block_number_column = 1, quoted or not); fail without touching the table if it does not.__dbt_new_data_<invocation_id>table from the model SQL, asdelete+insertdoes.max_block_numberof the target's active parts in that partition fromsystem.parts(-1if the partition does not exist yet).INSERTthe new rows into the target.Why these choices:
_block_numberas the "older" marker. Block numbers only grow within a partition, inMergeTreeand inReplicatedMergeTree, so every row inserted in step 4 has a higher number than the recorded maximum of its partition. A partition that did not exist before the insert maps to-1, so all of its rows count as new; this matters onReplicatedMergeTree, where a new partition starts at block 0. Withenable_block_number_column = 1each row keeps its block number through merges. Without the setting, a merge gives every row of the merged part the part's minimum block number (checked on 26.10: two inserts of the same key read as blocks 1 and 2 beforeOPTIMIZEand both as 1 after it), so a new row merged with old ones would look old and be deleted. That is why the setting is required, not optional.replicated_deduplication_window = 0to incremental tables. The setting is added to a copy, so the model config is not changed. An existing table is not altered behind the user's back; the error message gives theALTER TABLE ... MODIFY SETTING enable_block_number_column = 1command. Rows written before thatALTERread their part's block number, which is lower than any later insert, so turning it on for an existing table is safe.Int64, so none of its rows counts as newer and all of them count as older. The statement therefore grows with the batch, not with the table. Listing every partition of the table instead fails on the defaultmax_query_sizeabove about 2,800 partitions with hashed ids (measured withclickhouse-local26.9), and the failure comes after the insert, so every run would add another copy of the changed keys.incremental_predicatesare added to the delete, as indelete+insert.unique_keycolumn that does not exist fails the run, as it does withdelete+insert(the inheritedtest__bad_unique_keychecks this).distributed_incrementalis rejected with a clear error: block numbers are per shard, and this PR does not try to collect a threshold from every shard.Trade-offs, also in the docs
delete+insertshows gaps instead. A model that reads{{ this }}in its incremental SQL sees both versions after a failed run and should pick one row per key.ReplicatedMergeTreethe delete runs on every replica, and a replica that has not received the new rows yet deletes nothing for those keys. So even a successful run can leave duplicates on that replica until a later run writes the same keys. This is the race of delete+insert on ReplicatedMergeTree + cluster leaves duplicate unique_key rows (staging IN subquery not visible on other replicas) #740, which this PR does not fix; withdelete+insertthe same race also leaves duplicates.unique_keycolumns and_block_numberof the whole target to build its key set, on top of the key scan thedelete+insertdelete already does. In a local measurement (single node, ClickHouse 26.10.2.103; a 20 M-row table in 10 monthly partitions, merged before each run; a batch of 100 k keys, of which 50 k update existing keys and 50 k are new keys in 10 new partitions, so the table has 20 partitions afterwards; 5 runs each) the delete took 9.9 s on average (8.5–11.3 s), against 2.4 s (1.5–3.4 s) for thedelete+insertdelete and 7.7 s (7.1–8.5 s) for the same insert-then-delete with the key set taken from the new-data table._block_numberneeds a one-timeALTERor--full-refresh.Alternatives considered
legacy(copy the table and exchange it)insert_overwriteReplacingMergeTreewithFINAL(orargMax) in every readerUPDATE_block_offsetpersisted too, and reads are slower until patches are applied; a separate feature_partnames recorded before the inserttransform_null_in, some types cannot be used inIN, and the whole batch is held in memorydelete+insertdoesOverlaps with open PRs
__dbt_new_data_*table when a run fails, by registering it withadapter.register_staging_relationbefore it is created. This PR creates that table the same waydelete+insertdoes but does not register it, because that method exists only in fix: drop incremental staging tables when a model run fails #770. Whichever merges second should add the tworegister_staging_relation/unregister_staging_relationlines toclickhouse__incremental_insert_delete.state:modified#677 stopsget_model_settingsfrom changingmodel['config']['settings']in place. The setting added here goes into a copy, so it does not add to that problem, but the dedup window setting is still added in place until fix: Avoid injected settings to reach manifest and overselect onstate:modified#677 lands.on_schema_changeon the insert-only paths of the same materialization; the two touch neighbouring lines ofincremental.sqland may need a trivial rebase.Changes
dbt/adapters/clickhouse/impl.py: acceptinsert_delete(same lightweight-delete,unique_keyand predicate rules asdelete_insert); addenable_block_number_column = 1to a copy of the table settings of incremental models using it.dbt/include/clickhouse/macros/materializations/incremental/incremental.sql:clickhouse__validate_block_number_column, called beforeon_schema_change; theclickhouse__incremental_insert_deletemacro and its dispatch.dbt/include/clickhouse/macros/materializations/incremental/distributed_incremental.sql: rejectinsert_delete.docs/materializations.mdxanddocs/guides.mdx: the strategy, its requirements and caveats.tests/integration/adapter/incremental/test_incremental_insert_delete.py,tests/unit/test_incremental_strategy.py,CHANGELOG.md.Testing
Local, single node, ClickHouse 26.10.2.103,
tests/integration/adapter/incremental/test_incremental_insert_delete.py. The cluster runs useDBT_CH_TEST_CLUSTER=test_shardagainst a one-node cluster with embedded Keeper, so theReplicatedMergeTreeanddistributed_incrementalcases run too.unique_key, which never reach the strategy. The 3 skipped ones need a cluster.TestInsertDeleteIncrementaltests, bothTestInsertDeleteReplicatedIncrementaltests andTestInsertDeleteRequiresBlockNumberColumnfail;0instead of-1: bothTestInsertDeleteReplicatedIncrementaltests fail (plainMergeTreestarts at block 1, so only the replicated case catches it);TestInsertDeleteIncrementaland bothTestInsertDeleteReplicatedIncrementaltests fail, because key 2 moves out of such a partition;TestInsertDeleteRequiresBlockNumberColumnfails;on_schema_change:TestInsertDeleteRequiresBlockNumberColumnfails, because the column is added before the run stops.throwIfpredicate) stays in the mutation queue and blocks every later mutation on the table untilKILL MUTATION. ClickHouse does this for any failed mutation,delete+insertincluded, but it would make the follow-up run in the test fail for an unrelated reason.pytest tests/unit: 99 passed; the three new validation tests fail without theimpl.pychange.make lint: clean.Checklist
docswas updated with further explanations or tutorialsNote
Medium Risk
New incremental path runs multi-step inserts and lightweight deletes against production tables; wrong block-number logic or replica timing can leave duplicate rows, though keys should not disappear on partial failure.
Overview
Adds
incremental_strategy='insert+delete'as an alternative todelete+insert: new rows are inserted first, then older versions for the sameunique_keyare removed with a lightweight delete keyed off_block_number(requiresenable_block_number_column = 1).The adapter treats
insert_deletelike other lightweight-delete strategies (LW_DELETE_STRATEGIES), and auto-injectsenable_block_number_columnwhen creating incremental tables with this strategy.distributed_incrementalis rejected at compile time. New macros validate the table setting before schema changes and implement partition-scoped block thresholds plus a safer delete (only keys whose new row is visible).Docs and changelog describe behavior and trade-offs (temporary duplicates vs missing keys on failure). Integration and unit tests cover happy path, failure-after-insert, existing tables without the setting, distributed rejection, predicates, and unique-key cases.
Reviewed by Cursor Bugbot for commit 7fb050c. Bugbot is set up for automated code reviews on this repo. Configure here.