Schedule icon
Query icon
Script icon
Log icon
If icon
SlackIncomingWebhook icon
Fail icon
Queries icon
Pause icon
Loop icon

ClickHouse Partition Export Verify Purge Guard

Export expired ClickHouse partitions, prove each archive restores to the same rows and checksum, then drop only what was proven, behind approval.

Categories
Data

Safety

ALTER TABLE ... DROP PARTITION is instant and there is no undo inside ClickHouse. Retention jobs usually export the partition to a file first and then drop it in the same script, on the assumption that the export worked. A Native or Parquet file truncated by a killed writer reads fine as a file while it is still the only copy. So does one written before somebody backfilled rows. The gap is found months later when an auditor asks for last January. This flow turns that assumption into a measurement: the archive is read back through the format parser, restored into a real table, hashed against the live partition and only then is the partition dropped. Every guard below is load bearing and each one was proven by its own execution.

Guard What it stops
Row count plus order-independent cityHash64 checksum on live, parsed and restored rows dropping a partition whose archive is short, stale or scrambled
restore_probe, a clone table the archive is inserted into trusting a file that parses but does not land as the same data
Epoch guard on system.parts max time judging a non temporal partition key, where no date exists to judge
purgeable_tables write allowlist, ships empty archiving or dropping a table nobody named
protected_partitions denylist dropping a period an investigation or regulator still needs
max_partitions_per_run ceiling, oldest first turning a cleanup into an unbounded migration
Engine and partition key check from system.tables truncating a table that has no PARTITION BY at all
Breaker on archives of already dropped partitions handing more data to an archive path that has already lost some
auto_remediate false, dry_run true, Pause three separate gates before one write
Re-read of live rows and archive bytes after the approval acting on a plan that went stale while the approval waited
Loop with concurrencyLimit: 1 and allowFailure on the drop a refused drop hiding behind a sibling iteration
system.parts plus archive re-read after the drop a DROP PARTITION that returned no error being reported as done

How it works

  1. read_table_catalog (io.kestra.plugin.jdbc.clickhouse.Query) reads the engine, the PARTITION BY expression and the full column list from system.tables and system.columns. check_table_shape (io.kestra.plugin.scripts.python.Script) refuses a missing table, a non MergeTree engine or a table with no partition key, because that table's whole content is one partition.
  2. read_partitions reads every active partition with its rows, bytes and newest row from system.parts. read_archive_index lists the archive files already on disk with the One format, which returns one row per file without parsing a byte.
  3. plan_candidates picks candidates: newest row older than retention_days, a real timestamp rather than the epoch placeholder a non temporal key leaves behind, not on protected_partitions, under the ceiling, oldest first. Every spared partition gets a named verdict. It also splits the files on disk into those whose partition is still live and those whose partition is already gone.
  4. fingerprint_live hashes each candidate in place with sum(cityHash64(toString(tuple(*)))), a sum of per-row hashes so the result does not depend on row order, with every column cast to text so a NULL cannot drop out. read_candidate_archives and read_purged_archives parse the matching files through the file table function and hash what comes out.
  5. assess_archives labels every candidate archive verified, missing, mismatched or unreadable. It judges the archives of already dropped partitions separately. log_findings and notify_findings (io.kestra.plugin.slack.notifications.SlackIncomingWebhook) report. archive_store_breaker fails the run in every mode, dry run included, when an archive whose partition is already gone cannot be shown to hold its rows.
  6. route_remediation (If) needs auto_remediate: true, dry_run: false, the table on purgeable_tables and at least one target. Otherwise log_report_only ends the run.
  7. export_partitions writes one file per partition with INSERT INTO FUNCTION file('<dir>/<table>-{_partition_id}.<ext>') and the table's own partition expression, so the id in the file name is the server's. Partitions whose archive already matched are not rewritten. verify_export parses every target file back with no allowFailure. restore_into_probe (Queries) clones the table, truncates the clone and inserts the archive files into it, fingerprint_restored hashes the restored rows per partition and drop_probe_table removes the clone.
  8. confirm_restorable is the gate. A partition passes only when the parsed rows and checksum plus the restored rows and checksum all equal the live partition. One failure refuses the whole pass with a non-zero exit.
  9. approve_purge (Pause) holds for a person. apply_if_approved reads onResume.approved ?? false, so an unanswered resume is a refusal. recheck_live and recheck_archive read both sides again. confirm_plan_fresh compares them to the approved plan by partition id. Any drift fails the run before a single DDL statement.
  10. purge_remediation (io.kestra.plugin.core.flow.Loop, concurrencyLimit: 1) issues one ALTER TABLE ... DROP PARTITION ID per target with allowFailure, because the re-read is the real gate. reread_partitions and reread_archive read system.parts plus the files again. verify_purge fails the run when a partition is still there or its archive no longer holds exactly the rows that were dropped. On success it prints rows removed, bytes reclaimed and rows preserved, which have to add up. alert_failure posts any failure to Slack.

The weekly_archive_sweep Schedule trigger ships disabled: true and pins dry_run: true with auto_remediate: false, so enabling it cannot write.

What you get

  • An alert naming every partition past retention, how many rows it holds and whether its archive is missing, stale or already verified.
  • Archive files written by the server itself, one per partition, named with the server's own partition ids.
  • A drop that happens only for partitions whose data was read back out of the file and restored into a table at the same checksum.
  • Counts after the fact: rows removed from the table, bytes reclaimed and rows still readable in the archive, with a run that fails when they do not agree.

Who it's for

Data platform engineers and analytics DBAs who keep ClickHouse disks under control by archiving old partitions and need the archive to be worth something when it is the only copy.

Why orchestrate this with Kestra

The export, the read back, the restore, the human approval and the drop belong to one decision, but a shell script that chains them cannot pause for a person and cannot prove it rechecked the world after that person answered. Kestra holds the approval, re-reads both the table and the files immediately before the write, serialises the drops then keeps the evidence of each step in one execution. ClickHouse supplies the proof itself through system.parts, the file table function and a clone table, so nothing depends on this flow's own bookkeeping.

Tested end to end

Kestra 2.0.5, plugin-jdbc-clickhouse 2.1.0, plugin-slack 2.1.0, plugin-script-python 1.14.0, ClickHouse 25.3.6.56 on Alpine. Validate was clean on stock Kestra: no constraints, warnings or deprecations. The fixture is one analytics.events MergeTree table partitioned by toYYYYMM(ts) holding 300, 200, 150 and 120 rows in 202601, 202602, 202603 and 202610, plus three lookalikes that must be spared: analytics.metrics which is never allowlisted, analytics.by_region partitioned by a String region plus analytics.audit_log with no PARTITION BY. Every number below was read back with clickhouse-client against system.parts, system.query_log and the file table function, never from a Kestra output. All twelve cases ran on the final revision 5 and carry 86 independent assertions.

Case Execution Result
Healthy gWKd9phPG2CT6TTpgMn7u SUCCESS. Live mode with a 3650 day window. Four partitions spared within_retention, no archive file written
Dry run 7fIhZPMgdYT3i28I2isRuH SUCCESS. One candidate, the other three spared as protected_partition, over_ceiling and within_retention. Nothing on disk
Table not allowlisted 6J4UVfjkq76cH2JUuYJkW3 SUCCESS. Live mode, three expired partitions assessed in full, purgeable_tables empty, nothing written
Non temporal key 23GKffilPrMVijtMOOdPf8 SUCCESS. by_region allowlisted in live mode, all three partitions spared no_temporal_bound, nothing written
No partition key 5weAxaM4qYHrBas87tIAEM FAILED as intended at check_table_shape. audit_log kept its 40 rows and the flow never read a partition
Declined approval 76AazZZmQaWO9OmiM2QVCv SUCCESS. Both archives written and verified on three reads, no DROP reached ClickHouse, all four partitions intact, probe table gone
Reuse of the archive 4U0O8jncWAxLpnRB20kx51 SUCCESS. Second run found both archives already verified and exported nothing. The two files stayed byte identical by SHA-256
Change during the Pause 6YmWgQP90fdDlV3JhHqkzD FAILED as intended. Five rows were appended to 202601 while the approval waited, 300 to 305. confirm_plan_fresh refused and system.query_log shows no ALTER statement at all
Refused write 6JOFfyxVzm9gpOsCygl4qv FAILED as intended. max_partition_size_to_drop set to one byte. The drifted 202601 was re-exported at 305 rows, both drops were issued and refused with code 359, every partition survived and verify_purge failed the run
Remediation 5GDzUaynJ5AgLhuj9kXMGT SUCCESS. Reconciled the refused pass without re-exporting. Table rows 775 to 270, 8189 bytes reclaimed by system.parts, 505 rows still readable in the two files at the same checksums, conserved=true. system.query_log shows both ALTERs finishing with code 0. 202603 and 202610 untouched
Repeat 73invG7C3sJKnasgGYLAKv SUCCESS. No candidate left, both purged archives re-verified readable, archive files byte identical, no drop and no probe table
Damaged archive 5FZLlvg5uvHLE1VKxD4QbT FAILED as intended. One purged archive truncated to 40 bytes. The breaker stopped a dry run that had a candidate. Nothing was exported

A second fresh fixture container repeated healthy, remediation and the change during the Pause from the pinned image and the same seed script, with its own execution ids. Slack was a local HTTP sink.

Prerequisites

  • ClickHouse with a MergeTree family table and a date based partition key. Tested on 25.3.6.56 only.
  • A writable user_files path on the server that holds the table, because the archive is written by the server through the file table function. Put it on storage you back up.
  • Kestra 2.0.5 with the JDBC ClickHouse, Python script and Slack plugins.
  • Minimum permissions: SELECT on the table, system.tables, system.columns and system.parts, the FILE source privilege to read and write the archive, CREATE TABLE plus DROP TABLE for the restore probe, then ALTER DELETE level rights for DROP PARTITION on the allowlisted tables only. No admin rights.

Secrets

  • CLICKHOUSE_USERNAME, CLICKHOUSE_PASSWORD: the account used for every read and write.
  • SLACK_WEBHOOK_URL: Slack incoming webhook for findings and failures.

Inputs

Input Default Purpose
clickhouse_url jdbc:clickhouse://localhost:8123/default The node whose user_files directory the archive lands in
database, table default, events The table to archive
retention_days 90 A partition becomes a candidate once its newest row is older than this
archive_dir clickhouse-archive Directory under user_files holding one file per partition
archive_format Native Lossless by default, so restored rows hash identically
purgeable_tables [] Write allowlist as database.table. Empty means nothing may be dropped
protected_partitions [] Partition ids that are reported but never archived or dropped
max_partitions_per_run 3 Per-run ceiling, oldest first
restore_probe true Insert each archive into a clone table and hash it there
dry_run true Read and report only
auto_remediate false Allow the archive plus drop path at all

Quick start

  1. Add the three secrets and point clickhouse_url at the node that holds the table.
  2. Execute with the defaults. Read the findings: one line per partition with its verdict, one per archive file.
  3. Set retention_days to your policy and list anything an investigation needs in protected_partitions.
  4. Check that archive_dir resolves to backed up storage inside the server's user_files path.
  5. Execute with auto_remediate: true, dry_run: false and the table in purgeable_tables. Read the confirm_restorable lines, which name the row count and checksum proven on all three reads.
  6. Approve the Pause. Read the closing line: rows removed, bytes reclaimed, rows still readable in the archive and conserved.
  7. Enable weekly_archive_sweep once you want the report on a schedule.

How to extend

  • Point archive_dir at an S3 backed disk and swap the file table function for s3, keeping the same read back and restore steps.
  • Add a restore flow that takes a partition id and inserts its archive file into the live table, which is the other half of this contract.
  • Raise max_partitions_per_run for a one-off migration. Lower it to one while you are learning what the detector picks.
  • Feed purgeable_tables from a data catalog so the allowlist is owned where retention policy is owned.

Limits: the archive is written by the server into its own user_files path, so the flow cannot prove that path is backed up. Native files are also tied to the ClickHouse major version that wrote them. The checksum proves the rows match, not that the file will still be readable in five years. The purged-partition archives are parsed in one query, so one truncated file marks that whole set unproven and stops the run, which is deliberate but coarse. DROP PARTITION is not transactional with the verification, so the window between confirm_plan_fresh and the drop is small but real; rows inserted inside it are lost from the archive, which is why the per-run ceiling exists. Replicated tables were not tested, nor was a partition large enough to make the full-table checksum scan expensive.

Links

This blueprint was created by zkasuran.

See How

New to Kestra?

Use blueprints to kickstart your first workflows.