Skip to content

feat: add the insert+delete incremental strategy - #772

Open
bim-ba wants to merge 2 commits into
ClickHouse:mainfrom
bim-ba:feat/insert-delete-incremental-strategy
Open

bim-ba wants to merge 2 commits into
ClickHouse:mainfrom
bim-ba:feat/insert-delete-incremental-strategy

Conversation

@bim-ba

@bim-ba bim-ba commented Oct 30, 2026 •

Copy link
Copy Markdown

Summary

Closes #771.

delete+insert deletes the changed keys before it inserts their new versions, so a run that fails between the two statements leaves those keys missing. This PR adds incremental_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

  1. Before any on_schema_change change, check that the target persists _block_number (enable_block_number_column = 1, quoted or not); fail without touching the table if it does not.
  2. Create the __dbt_new_data_<invocation_id> table from the model SQL, as delete+insert does.
  3. For each partition the new-data table writes to, read the highest max_block_number of the target's active parts in that partition from system.parts (-1 if the partition does not exist yet).
  4. INSERT the new rows into the target.
  5. Delete older rows of the keys that now have a newer row:
-- newer: _block_number > transform(_partition_id, ['p1', ...], CAST([n1, ...] AS Array(Int64)), toInt64(9223372036854775807))
delete from <target>
where not (<newer>)
  and (<unique_key>) in (select <unique_key> from <target> where <newer>)
  [and <incremental_predicates>]

Why these choices:

  • _block_number as the "older" marker. Block numbers only grow within a partition, in MergeTree and in ReplicatedMergeTree, 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 on ReplicatedMergeTree, where a new partition starts at block 0. With enable_block_number_column = 1 each 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 before OPTIMIZE and 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.
  • The setting is added automatically to tables created with this strategy, the same way the adapter already adds replicated_deduplication_window = 0 to 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 the ALTER TABLE ... MODIFY SETTING enable_block_number_column = 1 command. Rows written before that ALTER read their part's block number, which is lower than any later insert, so turning it on for an existing table is safe.
  • Thresholds only for the partitions the batch writes to. Every other partition maps to the largest 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 default max_query_size above about 2,800 partitions with hashed ids (measured with clickhouse-local 26.9), and the failure comes after the insert, so every run would add another copy of the changed keys.
  • The key set comes from the target's new rows, not from the new-data table. A key loses its older rows only if its new version is visible in the table when the delete runs. If it is not visible (for example on a replica that has not received it yet), nothing is deleted for that key, so this step can leave duplicates but cannot remove the last version of a key.
  • Partition moves are handled. The threshold is per partition, and the key set is read from the whole table, so the older row of a key whose new version landed in another partition is found and deleted.
  • incremental_predicates are added to the delete, as in delete+insert.
  • An empty batch still runs the delete. It matches nothing, but a unique_key column that does not exist fails the run, as it does with delete+insert (the inherited test__bad_unique_key checks this).
  • distributed_incremental is 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

  • While a run is in progress, and after a failed run until the next successful one, readers can see two versions of a changed key. delete+insert shows 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.
  • On ReplicatedMergeTree the 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; with delete+insert the same race also leaves duplicates.
  • The delete reads the unique_key columns and _block_number of the whole target to build its key set, on top of the key scan the delete+insert delete 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 the delete+insert delete 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.
  • Rows that another writer adds during the run to partitions this batch does not write to count as older, so they are deleted if the batch has a newer version of the same key.
  • A table that does not persist _block_number needs a one-time ALTER or --full-refresh.

Alternatives considered

Option Why not
legacy (copy the table and exchange it) Atomic, but copies the whole table on every run
insert_overwrite Atomic per partition, but rewrites whole partitions, so it only fits models that can recompute every partition they touch
ReplacingMergeTree with FINAL (or argMax) in every reader No delete, but duplicates go away only with merges, every reader must deduplicate, and it changes the engine rather than the strategy
Lightweight UPDATE Atomic per statement, but cannot insert new keys, needs _block_offset persisted too, and reads are slower until patches are applied; a separate feature
_part names recorded before the insert A merge between the insert and the delete renames parts and puts old and new rows into one part
Compare full rows with the new data Identical old and new rows cannot be told apart, NULLs need transform_null_in, some types cannot be used in IN, and the whole batch is held in memory
Key set from the new-data table, as delete+insert does About 2 s faster in the measurement above (7.7 s against 9.9 s), but an insert that the delete cannot see yet would then remove the only remaining version of a key. Happy to switch if you prefer the cheaper delete with that as a documented caveat

Overlaps with open PRs

Changes

  • dbt/adapters/clickhouse/impl.py: accept insert_delete (same lightweight-delete, unique_key and predicate rules as delete_insert); add enable_block_number_column = 1 to 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 before on_schema_change; the clickhouse__incremental_insert_delete macro and its dispatch.
  • dbt/include/clickhouse/macros/materializations/incremental/distributed_incremental.sql: reject insert_delete.
  • docs/materializations.mdx and docs/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 use DBT_CH_TEST_CLUSTER=test_shard against a one-node cluster with embedded Keeper, so the ReplicatedMergeTree and distributed_incremental cases run too.

Run HTTP Native
Without the change (strategy rejected), no cluster 11 failed, 3 passed, 3 skipped 11 failed, 3 passed, 3 skipped
Without the change, cluster 14 failed, 3 passed 14 failed, 3 passed
With the change, no cluster 14 passed, 3 skipped 14 passed, 3 skipped
With the change, cluster 17 passed 17 passed
  • The 3 tests that pass without the change are inherited unique-key cases without a unique_key, which never reach the strategy. The 3 skipped ones need a cluster.
  • Each strategy-specific test was also run once against a deliberately broken macro (cluster, HTTP):
    • delete before insert: both TestInsertDeleteIncremental tests, both TestInsertDeleteReplicatedIncremental tests and TestInsertDeleteRequiresBlockNumberColumn fail;
    • a new partition mapped to 0 instead of -1: both TestInsertDeleteReplicatedIncremental tests fail (plain MergeTree starts at block 1, so only the replicated case catches it);
    • partitions the batch does not write to treated as holding newer rows: both TestInsertDeleteIncremental and both TestInsertDeleteReplicatedIncremental tests fail, because key 2 moves out of such a partition;
    • the setting check without the optional quotes: TestInsertDeleteRequiresBlockNumberColumn fails;
    • the setting check moved after on_schema_change: TestInsertDeleteRequiresBlockNumberColumn fails, because the column is added before the run stops.
  • There is no test with thousands of partitions: a 3,000-partition table made the delete exceed the suite's 120 s timeout. With thresholds only for the partitions the batch writes to, the statement does not depend on the table's partition count.
  • The failure test breaks the delete with an unknown column on purpose. A delete that fails while it runs (for example a throwIf predicate) stays in the mutation queue and blocks every later mutation on the table until KILL MUTATION. ClickHouse does this for any failed mutation, delete+insert included, 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 the impl.py change. make lint: clean.
  • Not run: a multi-node cluster (replica lag) and ClickHouse Cloud.

Checklist

  • Unit and integration tests covering the common scenarios were added
  • A changelog entry was added following Updating the Changelog (user-facing, concise, PR link) — the entry is in; the PR link is filled in once the PR has a number
  • For significant changes, documentation in docs was updated with further explanations or tutorials

Note

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 to delete+insert: new rows are inserted first, then older versions for the same unique_key are removed with a lightweight delete keyed off _block_number (requires enable_block_number_column = 1).

The adapter treats insert_delete like other lightweight-delete strategies (LW_DELETE_STRATEGIES), and auto-injects enable_block_number_column when creating incremental tables with this strategy. distributed_incremental is 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.

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.
@CLAassistant

CLAassistant commented Oct 30, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

delete+insert loses the changed keys when a run fails between DELETE and INSERT; add an insert-then-delete strategy

3 participants