Skip to content

Support BACKUP/RESTORE for WORKLOAD and RESOURCE entities - #108431

Merged
serxa merged 24 commits into
masterfrom
workload-resource-backup
Sep 11, 2026
Merged

serxa merged 24 commits into
masterfrom
workload-resource-backup

Conversation

@serxa

@serxa serxa commented Jun 25, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • New Feature

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

Support BACKUP/RESTORE for WORKLOAD and RESOURCE entities. SQL-defined CREATE WORKLOAD / CREATE RESOURCE definitions are now included when backing up system.workloads / system.resources and are recreated on restore, including ON CLUSTER.

Documentation entry for user-facing changes

Summary

Implements the backupData / restoreDataFromBackup hooks for system.workloads and system.resources, so WORKLOAD and RESOURCE DDL is covered by BACKUP/RESTORE (mirroring how UDFs in system.functions are handled). Closes #74879.

Details

  • Backup writes one <escaped_name>.sql file per SQL-defined entity. Config-defined entities are excluded — they live in the read-only configuration storage and are expected to be restored together with the configuration. Both system.workloads and system.resources are served from a single consistent snapshot of the storage taken once per backup operation, so a concurrent DDL cannot split an interdependent workload/resource pair across the two calls. On replicated / ON CLUSTER backups a single writer per replication id is elected via BackupCoordinationReplicatedWorkloadEntities.
  • Restore parses the .sql files, accumulates both entity types, and recreates them in dependency order (resources and parent workloads first). A restored definition whose kind does not match the system table being restored is rejected, so the table-based access gate cannot be bypassed. system.workloads and system.resources are expected to be backed up and restored together: a restored workload that references a resource neither in the backup nor already on the server is rejected with a clear error. The create_workloads_and_resources setting selects how an already-existing entity is handled: if not exists (default), create (fail if it exists), or replace (overwrite). Restore requires CREATE WORKLOAD / CREATE RESOURCE, and additionally DROP WORKLOAD / DROP RESOURCE in replace mode.

Testing

  • Stateless 04409_backup_restore_workloads_and_resources: single-node round-trip, access-privilege enforcement (including DROP in replace mode and the structure_only / restore_table_data edge cases), and all three create_workloads_and_resources modes.
  • Integration test_backup_restore_workload_entities: single-node round-trip, a two-node Keeper-backed ON CLUSTER round-trip, exclusion of config-defined entities from backups, rejection of a kind-mismatched definition, and rejection of a workloads-only restore whose referenced resource is missing.

Workflow [PR]
Sync PR [sync-upstream/pr/108431]

Version info

  • Merged into: 26.9.1.1185 (included in 26.9 and later)

Implement backupData/restoreDataFromBackup for system.workloads and
system.resources so that CREATE WORKLOAD and CREATE RESOURCE definitions
are included in BACKUP and recreated on RESTORE, mirroring how UDFs
(system.functions) are backed up.

Backup writes one <name>.sql file per entity. Restore parses the files
and recreates entities in dependency order (resources and parent
workloads first) using CREATE-IF-NOT-EXISTS semantics. ON CLUSTER
backups deduplicate writers via new replicated coordination, analogous
to ReplicatedSQLObjects for UDFs.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5ee1e3c]

Summary: ✅


AI Review

Summary

This PR adds BACKUP/RESTORE support for WORKLOAD and RESOURCE entities, including the access-check fixes, combined restore ordering, and ON CLUSTER coordination needed for the normal happy path. Those pieces now look coherent, but the Keeper-backed path still relies on lagging local caches in two places, so the advertised replicated backup/restore contract is not actually reliable yet.

Findings

❌ Blockers

  • [src/Common/Scheduler/Workload/WorkloadEntityStorageBase.cpp:1044] BACKUP on Keeper-backed workload storage snapshots local_entities, but WorkloadEntityKeeperStorage only refreshes that cache on a new session or when the async watch fires (src/Common/Scheduler/Workload/WorkloadEntityKeeperStorage.cpp:93-103, :148-149). In BACKUP ... ON CLUSTER, the elected writer can therefore serialize a view that is already stale relative to Keeper and silently omit a committed workload/resource from the backup. A later restore then recreates an incomplete scheduler state or fails on missing dependencies. Suggested fix: before freezing entities_to_backup for replicated storage, refresh from authoritative Keeper state (or read Keeper directly) on the writer that will materialize the snapshot. [dismissed by author -- https://github.com/Support BACKUP/RESTORE for WORKLOAD and RESOURCE entities #108431#discussion_r3876244585]
    Matching the existing UDF/access-entity convention does not make this safe: this PR newly documents workload/resource backup as supported, so silently dropping committed entities is still a broken backup contract.

⚠️ Majors

  • [src/Common/Scheduler/Workload/WorkloadEntityStorageBase.cpp:1232-1240] The new pre-check is skipped on replicated storage to avoid stale local state, but the restore still immediately falls through to storeEntity, whose reference validation uses the same lagging entities map (src/Common/Scheduler/Workload/WorkloadEntityStorageBase.cpp:505-509) before WorkloadEntityKeeperStorage::storeEntityImpl can reach its trySet/refreshEntities retry path. As a result, RESTORE TABLE system.workloads on Keeper-backed storage can still reject a workload whose parent/resource already exists in Keeper but has not reached the local watch cache yet, even though the PR description and docs say that restoring workloads without the matching resources is valid when those dependencies are already present on the target server. Suggested fix: resolve these references against fresh Keeper state, or teach the Keeper-backed storeEntity path to refresh and retry missing-reference failures before throwing. [dismissed by author -- https://github.com/Support BACKUP/RESTORE for WORKLOAD and RESOURCE entities #108431#discussion_r3876244587]
    This check is older than the PR, but the PR now exposes it on a documented restore path, so the restore contract is still not met.
Tests
  • ⚠️ The new integration coverage proves only the synchronized happy path: it waits for the second replica to observe the replicated entities before backup/restore. It does not force the elected backup/restore host to run with a stale Keeper watch, so it does not cover either of the remaining replicated-state races above. A focused two-node Keeper regression that delays the watch on the writer/owner replica would close that gap.
Final Verdict

Request changes. The direct access-control and ordering fixes look good, but Keeper-backed workload backup/restore still is not reliable under normal watch lag, so the new replicated support should not merge in its current form.

LLVM Coverage Report

Measured on commit 5ee1e3c.

Metric Baseline Current Δ
Lines 88.90% 88.90% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.30% 81.30% +0.00%

Changed lines: Changed C/C++ lines covered: 246/261 (94.25%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Jun 25, 2026
serxa and others added 2 commits June 25, 2026 02:03
Context::getWorkloadEntityStorage() was renamed to getWorkloadEntityStoragePtr()
(returning a shared_ptr) on master. Update the backupData/restoreDataFromBackup
hooks in system.workloads and system.resources accordingly.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
WorkloadEntityStorageBase::backup() iterated getAllEntities(), which includes
entities provided through the server configuration (the chained
WorkloadEntityConfigStorage). Config-defined entities must not be backed up: the
configuration is backed up and restored separately together with all its
entities, and re-creating them from a backup would persist them as SQL entities,
which is not equivalent. Iterate local_entities (this storage's own SQL-defined
entities) instead.

Add tests:
- 04409_backup_restore_workloads_and_resources (stateless): round-trips
  workloads and resources through BACKUP/RESTORE and checks the definitions are
  preserved.
- test_backup_restore_workload_entities (integration): verifies a backup
  contains only SQL-defined entities, never config-defined ones, and that
  restore recreates the SQL entities without duplicating or converting the
  config-defined ones.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@serxa

serxa commented Jun 25, 2026

Copy link
Copy Markdown
Member Author

@groeneai, the CI failures on this PR are unrelated to its changes (this PR only touches the Backups subsystem and system.workloads / system.resources for BACKUP/RESTORE of WORKLOAD and RESOURCE DDL). Please investigate and provide fixes in separate PRs; if a fix is already in progress, link it here.

  1. Stress test (amd_msan) — Logical error: Not-ready Set is passed as the second argument for function 'A (STID 0250-41a5). Pre-existing, known issue: Logical error: Not-ready Set is passed as the second argument for function 'A (STID: 0250-41a5) #107619.
    https://github.com/ClickHouse/ClickHouse/actions/runs/28141986573/job/83348870583

  2. Stress test (arm_debug) — Logical error: Distributed task iterator is not initialized (STID 4662-3e65). Pre-existing, known issue: Logical error: Distributed task iterator is not initialized (STID: 4662-3e65) #107898.
    https://github.com/ClickHouse/ClickHouse/actions/runs/28141986573/job/83348870595

  3. Integration tests (db disk, old analyzer, 2/6 and amd_msan, 2/6) — test_storage_kafka/test_batch_slow_0.py::test_kafka_formats_with_broken_message (Kafka format parsing, unrelated to this PR).
    https://github.com/ClickHouse/ClickHouse/actions/runs/28141986573/job/83348870453

  4. Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) — connection loss (exit code 210) with S3 result-upload conflicts; appears transient/infra.
    https://github.com/ClickHouse/ClickHouse/actions/runs/28141986573/job/83348870071

@groeneai

Copy link
Copy Markdown
Collaborator

Investigated all 4. None touch the code this PR changes (Backups + Common/Scheduler/Workload + system.workloads/system.resources); all are pre-existing trunk-wide failures. Details + owners:

1. Not-ready Set ... function 'A (STID 0250-41a5), Stress (amd_msan). Chronic trunk LOGICAL_ERROR: 80 hits / 63 distinct PRs / 14 on master in 14d. Tracked in #107619. In-progress fix: #107924 (alexey-milovidov, makes in-place set build non-destructive). Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108431&sha=f0583fa22ceaaa7121818d16f4fdd2e43c31abaf&name_0=PR&name_1=Stress%20test%20%28amd_msan%29

2. Distributed task iterator is not initialized (STID 4662-3e65), Stress (arm_debug). Chronic trunk LOGICAL_ERROR: 16 hits / 16 distinct PRs / 1 on master in 14d. Tracked in #107898. In-progress fix: #107107 (rejects nested cluster table functions with a clear error instead of crashing). Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108431&sha=f0583fa22ceaaa7121818d16f4fdd2e43c31abaf&name_0=PR&name_1=Stress%20test%20%28arm_debug%29

3. test_kafka_formats_with_broken_message, Integration (amd_msan / db disk old analyzer). Trunk-flaky: 21 hits / 14 distinct PRs / 2 on master in 30d. In-progress fix: #108252. Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108431&sha=f0583fa22ceaaa7121818d16f4fdd2e43c31abaf&name_0=PR&name_1=Integration%20tests%20%28amd_msan%2C%202%2F6%29

4. 04033_tpc_ds_q04, Stateless (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel). Not a connection loss: the failing test is 04033_tpc_ds_q04 and it is a deterministic harness timeout (Failed 3 out of 3 reruns ... Timeout! Killing process group). This heavy TPC-DS query exceeds the per-test timeout on the slowest instrumented lane (coverage + parallel replicas + s3). Trunk-wide: 19 hits / 13 distinct PRs / 2 on master in 30d, concentrated on this lane and arm_asan_ubsan, azure, parallel. No fix PR open yet; we are tracking it and will open a separate PR and link it here. Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108431&sha=f0583fa22ceaaa7121818d16f4fdd2e43c31abaf&name_0=PR&name_1=Stateless%20tests%20%28amd_llvm_coverage%2C%20ParallelReplicas%2C%20s3%20storage%2C%20parallel%29

@groeneai

Copy link
Copy Markdown
Collaborator

Follow-up on the 04033_tpc_ds_q04 timeout (1 of the 4 above): it is the known TPC-DS spill-threshold runtime regression on instrumented lanes, not related to this PR.

Mechanism: #107461 (merged Jun 18) enabled disk spill at a 300 MiB threshold in 04033_tpc_ds.lib; under the heavily-instrumented amd_llvm_coverage, ParallelReplicas, s3 lane that makes external aggregation/join dominate wall-clock, pushing q04 past the 600s per-test timeout (coverage-lane q04 timeouts start Jun 19, the day after that merge). It is a wall-clock timeout, not OOM.

Fix is already up and approved: #107968 raises max_bytes_before_external_{group_by,join} 300 MiB → 2 GiB. On that branch q04 runs OK (~271s) on this exact lane. No action needed here; this will stop recurring once #107968 lands.

serxa and others added 2 commits June 28, 2026 00:27
- RestorerFromBackup: require CREATE WORKLOAD / CREATE RESOURCE access when
  restoring system.workloads / system.resources (only CREATE_FUNCTION was
  special-cased before), so RESTORE no longer bypasses these privileges.
- RestoreCoordination: acquire restore ownership once per replication id instead
  of per entity type, so one replica restores both system.workloads and
  system.resources together and a workload's FOR <resource> reference stays
  valid. Record current_host_index in the coordination node so a host that loses
  the Keeper response can recover ownership on retry.
- WorkloadEntityStorageBase: key the restore accumulator and the task-added guard
  by restore id, so concurrent restores no longer mix entities or drop one
  another's restore task.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
WORKLOAD and RESOURCE entities are intertwined (a workload references resources
via SETTINGS ... FOR <resource> and workloads form a hierarchy), so they are
always restored together. Add a single RESTORE setting
create_workloads_and_resources (modes: create / if-not-exists / replace, default
if-not-exists) that governs how RESTORE handles entities that already exist,
mirroring create_function for UDFs. The mode maps to throw_if_exists / replace_if_exists
and is applied uniformly to both system tables.

Extends the stateless test 04409 to cover all three modes.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Comment thread src/Backups/RestorerFromBackup.cpp Resolved
@serxa

serxa commented Jul 3, 2026

Copy link
Copy Markdown
Member Author

@groeneai, the new CI failures on head d49e7e96169 are unrelated to this PR's changes (this PR only touches the Backups subsystem and WorkloadEntityStorageBase for BACKUP/RESTORE of WORKLOAD/RESOURCE DDL — it does not affect query execution or block structure logic).

1. Stress test (arm_release) — Logical error: Block structure mismatch in A stream: different number of columns: (STID: 2228-453d). Pre-existing fuzzer/stress failure in this family — see also open issues #109215 (STID 0993-308a) and #108332 (STID 0993-300c). STID 2228-453d does not appear to be tracked yet.
Report: https://github.com/ClickHouse/ClickHouse/actions/runs/28664486257/job/85036732461

2. Performance Comparison (arm_release, master_head, 3/6) — cascades from the same STID 2228-453d crash (the comparison server died during the benchmark run).
Report: https://github.com/ClickHouse/ClickHouse/actions/runs/28664486257/job/85036732492

Please investigate STID 2228-453d and provide a fix in a separate PR. If a fix is already in progress, link it here.

@groeneai

groeneai commented Jul 3, 2026

Copy link
Copy Markdown
Collaborator

Confirmed, both reds are unrelated to this PR.

STID 2228-453d is the arm_release variant of a trunk fuzzer bug in query planning: a Block structure mismatch in JoinStep logical error raised when a correlated subquery is decorrelated into a join over a relation that carries a duplicate column name and a join runtime filter is pushed onto the duplicated key. CIDB over 30d: 11 hits across 11 distinct PRs, 0 on master (2026-07-01 to 2026-07-03), all bystander branches that happened to fuzz the same query. This PR only touches the Backups subsystem and WorkloadEntityStorageBase, which do not overlap JoinStep or runtime-filter planning, so it cannot produce this signature.

Fix already in progress: #109114 (it skips the runtime filter when a join input header has a duplicate column name; a runtime filter is a pure optimization, so results are unchanged). It Closes #109215 (the 0993-308a variant you cited) and lists 2228-453d as one of its build variants. Currently open, CI green, awaiting review.

The Performance Comparison (arm_release, master_head, 3/6) red shares the same root cause (the same JoinStep logical error surfacing during its benchmark queries), so it is not PR-caused either.

@mintlify

mintlify Bot commented Jul 12, 2026 •

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated (UTC)
ClickHouse-docs 🟢 Ready View Preview Jul 12, 2026, 1:14 PM

@clickhouse-gh

clickhouse-gh Bot commented Jul 12, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.80% 85.80% +0.00%
Functions 92.70% 92.70% +0.00%
Branches 78.00% 78.00% +0.00%

Changed lines: Changed C/C++ lines covered: 108/220 (49.09%) · Uncovered code

Full report · Diff report

@clickhouse-gh

clickhouse-gh Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 40 queries analysed

This PR adds BACKUP/RESTORE support for SQL-defined workloads and resources (new backup coordination classes, restore settings, and access checks) plus a docs section. None of that code runs during a ClickBench SELECT. The only flagged query, Q28 (+5.1%), was already borderline with the two tests disagreeing and sits on an intrinsically noisy history, so this is run-to-run variance rather than a real effect of the change. No plausible performance impact from this PR; no action needed.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 28 not_sure 1050 1104 +5.1% 0.0033 This PR only adds BACKUP/RESTORE support for workload and resource entities; it does not touch ClickBench Q28's SELECT execution path. The +5.1% is run-to-run variance on an intrinsically noisy query.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: cb850fad-e6ad-426f-9761-04d0922efa73
  • MIRAI run: 3f853686-ef25-4a56-b39e-ddf9ecf67038
  • PR check IDs:
    • clickbench_112187_1789093543
    • clickbench_112289_1789093569
    • clickbench_112303_1789093569
    • tpch_adapted_1_official_112492_1789093589
    • tpch_adapted_1_official_112620_1789093627
    • tpch_adapted_1_official_112724_1789093645

@jkartseva jkartseva left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM; Are you planning to include backups of workloads and resources to the Cloud? If so, we might need an operator change.

Comment thread src/Backups/IRestoreCoordination.h Resolved
@serxa

serxa commented Sep 9, 2026 •

Copy link
Copy Markdown
Member Author

Are you planning to include backups of workloads and resources to the Cloud? If so, we might need an operator change.

Yes, we definitely need it.

- Warn at backup when a backed-up workload references a config-defined entity (parent
  workload or FOR resource): such config entities are not included in the backup, so a
  restore on a server that lacks them in its configuration would fail.
- Use map::extract instead of find + swap + erase in restoreEntitiesAccumulatedFromBackup.
- Drop the unused WorkloadEntityType forward declaration in IRestoreCoordination.h.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@serxa
serxa enabled auto-merge September 9, 2026 17:24
serxa and others added 2 commits September 9, 2026 18:07
…backed up

The warning was evaluated once over the whole snapshot before the entity_type filter,
so e.g. BACKUP TABLE system.resources still scanned workloads and logged a spurious
warning about a workload's references even though no workloads were being backed up.
Move it into the per-type loop so it runs only over the entities selected for the
current backup() call.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Reading a Disk(...) backup requires the READ ON DISK source grant, so the limited users
that exercise the WORKLOAD / RESOURCE restore access checks could not read the backup and
their restores failed with ACCESS_DENIED. Grant READ ON DISK up front so the checks
isolate the CREATE / DROP WORKLOAD / RESOURCE privileges under test.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@serxa

serxa commented Sep 11, 2026

Copy link
Copy Markdown
Member Author

The only red, Upgrade check (amd_release), is an unrelated flaky: Logical error: 'Got read request from replica 1 for unknown stream test_3.t_mt_index_rp' (STID 5217-5b3d) — a replica-streaming error with nothing to do with this backup/restore change, and the upgrade check itself marked it flaky. Every other check (151) is green. @groeneai could you re-run it — not related to this PR.

@groeneai

Copy link
Copy Markdown
Collaborator

Confirmed unrelated to your changes: all 29 files here sit under src/Backups, src/Common/Scheduler/Workload, src/Storages/System, tests and docs, and none of them is on the MergeTree read path or in ParallelReplicasReadingCoordinator, which is where that assertion is raised.

I cannot re-run it for you, though: @groeneai has only triage on this repository (push: false, no actions: write), so the re-run API answers 403 for me. A re-run from your own account or the assignee's, or an empty commit to retrigger, is the way.

Two things worth knowing before you retry, because a plain re-run is not a reliable route to green right now:

  • The carrier table identifies the trigger. t_mt_index_rp occurs exactly once in the repository, in tests/queries/0_stateless/04891_mergetree_index_respects_row_policy.sql, whose final statement calls mergeTreeAnalyzeIndexes. The abort therefore comes from that test, not from an arbitrary flake.
  • This is a live burst, not steady background noise. On Upgrade check (amd_release): 17 mutually unrelated PRs have hit it since 00:22:20Z today, i.e. 17 of the 96 commits that ran the check (about 18%), against 0 of 218 yesterday and 0 of 367 the day before. The carrier bases span several days, so no single fresh master commit explains it from the PR side, and the onset itself is still unexplained. Your PR is a bystander.

So expect roughly a 1-in-6 chance of the retry landing on the same abort while this lasts.

@serxa
serxa added this pull request to the merge queue Sep 11, 2026
Merged via the queue into master with commit dc8adb8 Sep 11, 2026
343 of 345 checks passed
@serxa
serxa deleted the workload-resource-backup branch September 11, 2026 08:20
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 11, 2026
@fm4v

fm4v commented Sep 14, 2026

Copy link
Copy Markdown
Member

@groeneai check support for incremental backups and snapshot

@groeneai

Copy link
Copy Markdown
Collaborator

Acknowledged. I'm checking both arms against master: incremental (BACKUP ... SETTINGS base_backup = ..., i.e. whether the WORKLOAD/RESOURCE entities are re-emitted, diffed against the base, or dropped, and whether a RESTORE from the incremental yields the full entity set) and snapshot consistency (whether the entity set is captured as one consistent view rather than raced against concurrent CREATE/DROP WORKLOAD/RESOURCE). I'll follow up here with the measured behaviour, and a PR if there is a gap.

@groeneai

Copy link
Copy Markdown
Collaborator

I read "snapshot" both ways it could be meant, so there are three arms below. Measured on master @
70a16495d1d3a with a debug build; summary first, then the details.

Arm Result
Incremental (SETTINGS base_backup = ...) Works. Dedup engages, including byte-prefix reuse, and a RESTORE from the incremental alone returns the complete entity set. Was untested; PR #119975 adds the test.
The per-backup entity snapshot this PR introduces No leak. A second backup reusing the same backup_uuid sees an entity created in between, so the scope_guard cleanup fires.
experimental_lightweight_snapshot Accepted, and correct via the documented copy fallback: entities are physically in the snapshot and the round trip is byte-identical. OSS only, see the caveat below.

Incremental. With nothing changed between the full backup and the incremental, the incremental writes zero
bytes (num_entries 0, only .backup on disk) yet its manifest still carries a <file> element for all four
files, each with <use_base>. That is the case worth checking, because
WorkloadEntityStorageBase::restore enumerates with backup->listFiles(...): had those entries been absent, a
RESTORE would have silently recreated fewer workloads and resources than existed. It restores all of them.
Control: with the base directory moved away, RESTORE from the incremental fails with
Code: 599 ... Backup Disk('backups', '1/') not found, so the deduplication is real.

Across an evolving set I get exactly the expected split. Base holds sql_wl (priority 3), sql_wl2,
sql_res; then I add sql_res2, drop sql_wl2, extend sql_wl to
priority = 3, max_concurrent_threads = 4, and leave sql_res alone. The incremental physically contains only
data/system/workloads/sql_wl.sql and data/system/resources/sql_res2.sql, and sql_wl.sql holds exactly
", max_concurrent_threads = 4". So BackupEntryFromMemory's partial checksum gives these entities the same
base-prefix reuse that test_incremental_backup_append_table_def pins for table metadata, which goes through
that same entry class (BackupEntriesCollector.cpp:814). Restoring the incremental alone reproduces
name, create_query for both tables byte for byte, with sql_wl2 not resurrected and the config-defined
entities still present exactly once.

Snapshot, the mode. experimental_lightweight_snapshot = 1 is accepted on a Disk(...) destination and
produces a full copy, which is what
docs/concepts/features/backup-restore/snapshot.mdx documents for non-SharedMergeTree engines. Both entity
.sql files are present and the restore is byte-identical. One caveat I do not want to overstate: this is the
OSS copy fallback. A non-Cloud build cannot exercise the object-reference path at all, since the lightweight
branches across src/Backups/ and the Keeper commit under LIGHTWEIGHT_SNAPSHOT_COMMIT_PATH
(BackupsWorker.cpp:706 and :794) are #if CLICKHOUSE_CLOUD, and the system.snapshot_locks /
system.snapshot_parts tables the docs describe are not in the OSS tree at all, so I cannot say from here
whether a Cloud snapshot carries these entities. Given your
"yes, we definitely need it" about the Cloud operator, that seems worth a separate look by someone who can run
it. Separately, the SNAPSHOT ... keyword itself returns Code: 78 Unknown type of query: SnapshotQuery in
this build for every object, not just these tables, since nothing routes ASTSnapshotQuery.

PR: #119975 adds the incremental test to test_backup_restore_workload_entities. It is test-only; I found
nothing to fix.

Two axes I left alone rather than fold in. Incremental x ON CLUSTER: base_backup has zero coverage anywhere
in test_backup_restore_on_cluster/, so that is a pre-existing hole across the whole backup subsystem rather
than something specific to workload entities. And a concurrent-DDL race test for entity-set consistency: there
is no pause hook between the two backupData() calls, so a race loop would have no negative control and would
pass whether or not the shared snapshot keying is correct. If you want that property pinned, a PAUSEABLE
failpoint between the table collections would make it testable and I am happy to add one.

cc @serxa

pull Bot pushed a commit to Mu-L/ClickHouse that referenced this pull request Sep 14, 2026
PR ClickHouse#108431 added BACKUP/RESTORE for SQL-defined WORKLOAD and RESOURCE
entities, and @fm4v asked whether that support holds for incremental
backups. It does, but nothing exercised it: base_backup and
entity-storage backup were disjoint axes in the test suite. All eight
incremental tests in test_backup_restore_new back up test.table,
base_backup appears nowhere in test_backup_restore_on_cluster/, and no
test for access entities, UDFs, workloads or resources did full then
incremental then restore-from-incremental.

That last case is the consequential one. WorkloadEntityStorageBase::restore
enumerates entities with backup->listFiles(), so had an incremental's
manifest omitted files deduplicated into the base, a RESTORE would have
silently recreated fewer workloads and resources than existed. Measured
on master: the manifest carries a <file> element for every file, each
with <use_base>, and restoring the incremental alone returns the
complete set.

The new test walks one evolving entity set across a base and an
incremental so that a single flow carries all three
checkBaseBackupForFile outcomes plus deletion: a resource created after
the base (HasNothing), a workload dropped after it, a workload extended
by one setting (HasPrefix, since BackupEntryFromMemory allows a partial
checksum and formatWithSecretsOneLine appends), and a resource left
untouched (HasFull). The exact-list oracle on the incremental's contents
proves in one assertion that only the changed workload and the new
resource carry bytes. Carrier three gets its own byte-exact assertion
because the restored create_query reads the same whether prefix reuse
engaged or the whole definition was rewritten.

Verified by mutating each carrier out in turn and confirming the
targeted assertion reddens, and by removing the drops to confirm the
arming assertions are load-bearing.

Co-Authored-By: Claude Opus 5 <[email protected]>
@robot-clickhouse robot-clickhouse added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 16, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-backup Backup/restore infrastructure and backup formats. pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-feature Pull request with new product feature pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.8-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Backup and restore for WORKLOAD and RESOURCE entities

7 participants