Skip to content

Fix BACKUP/RESTORE SETTINGS <name> = DEFAULT parsing and formatting - #112978

Merged
jkartseva merged 26 commits into
ClickHouse:masterfrom
groeneai:fix-112895-backup-settings-default
Sep 28, 2026
Merged

jkartseva merged 26 commits into
ClickHouse:masterfrom
groeneai:fix-112895-backup-settings-default

Conversation

@groeneai

@groeneai groeneai commented Aug 2, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed BACKUP and RESTORE queries with SETTINGS <name> = DEFAULT: such a query either failed to parse or was formatted into text that could not be parsed back, and the other settings of the same clause were discarded. Repeated async items now use the last value, async = '1' no longer fails after the operation has started, and compression is rejected in the SETTINGS clause as in other queries.

Closes: #112895

Description

ParserBackupQuery::parseSettings parses items with ParserSetQuery::parseNameValuePair, which has no DEFAULT branch, and is invoked non-fatally: it rewound and ParserQueryWithOutput consumed the whole clause as a plain query-level SETTINGS node. ASTSetQuery prints all changes and then all default_settings, so that reroute both moved a = DEFAULT item out of place and diverted its siblings away from BackupSettings.

parseSettings now picks the grammar by running both. The plain one wins whenever it reads the clause to the end, so every form accepted today keeps its meaning apart from the two named above; the DEFAULT-aware one is taken only when it reads strictly further without reinterpreting a query parameter or a substitution value. A resolver in the Backups layer then gives each name its meaning per setting class: a backup-specific one loses its changes entry so the field keeps its default, a core one is reset on the query context. Rejecting the form outright, which the issue also offers, would delete working behaviour (BACKUP ... SETTINGS max_execution_time = DEFAULT clears a limit today) and be asymmetric with SET.

Four sibling defects on the same path are fixed here, each in its own commit: BackupSettings::isAsync disagreeing with fromBackupQuery over repeated and string-valued async; the clause skipping checkSettingsConstraintsForSettingsReset, so a reset slipped past a CONST constraint; the clause skipping rejectHTTPOnlyConstructionSettings, so compression was accepted; and the ON CLUSTER rebuild dropping a reset name's overrides under that name only, so an override written through another name of the same setting survived (below). For the = DEFAULT form the second and third would have been regressions of this PR rather than pre-existing gaps, because the rerouted clause used to run both checks. Each is pinned by arms that flip when only that check is removed.

ON CLUSTER does not forward a reset at all. BackupsWorker rebuilds the clause with copySettingsToQuery and hands it to executeDDLQueryOnCluster, which ships it to the other hosts as SQL text that each re-parses with its own parser, together with the DDL settings packet built from the initiator's query context. The reset has already been applied to that context, which clears the setting's changed bit, so the packet leaves the setting out and each receiving host ends with it unset too. The rebuild only drops every override of a reset setting from the text, under every name that setting has (a built-in alias, the names of a merge_tree_ setting), because a receiving host applies the text on top of the packet. The text therefore never contains = DEFAULT, which no released version accepts after a comma (Code: 62 on 26.7.1.1362), so a cluster in the middle of a rolling upgrade keeps working. An earlier version of this PR forwarded a reset as the setting's declared default instead, which marked the setting as changed on the receivers and made object-storage code there override the host's own <s3> configuration.

Found by BuzzHouse (amd_debug) on #96886, STID 1941-1bfa: report.
Also hit on master: report.


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

Version info

  • Merged into: 26.10.1.939-master (included in 26.10 and later)

groeneai and others added 4 commits August 1, 2026 19:05
A `<name> = DEFAULT` item in a BACKUP/RESTORE SETTINGS clause was not
readable by the BACKUP grammar: ParserBackupQuery::parseSettings parses
items with ParserSetQuery::parseNameValuePair, which has no DEFAULT
branch. Because parseSettings is invoked non-fatally, the failure did not
reject the query - it rewound and let ParserQueryWithOutput consume the
whole remaining clause as a plain query-level SETTINGS node instead.

That single reroute caused two user-visible problems. The formatter
prints an ASTSetQuery as all `changes` and then all `default_settings`,
so a leading DEFAULT item was reordered to the end and the printed query
no longer re-parsed (the reported inconsistent-AST-formatting failure);
with the item last, the query did not parse at all. And every sibling
setting in the same clause was diverted with it, so backup-specific
names never reached BackupSettings and were then rejected as unknown
core settings.

parseSettings now decides which grammar reads the clause by running
both, rather than by predicting which items the plain one rejects: the
plain grammar wins whenever it reads the clause to the end, so every
form accepted today keeps its exact current meaning, and the
DEFAULT-aware grammar is taken only when it is strictly better and has
not reinterpreted a query parameter or a substitution value.

A shared resolver in the Backups layer then gives the parsed
`default_settings` their meaning, split by setting class: dropping the
`changes` entry for a defaulted backup-specific setting (which is what
makes its field keep its default), and resetting a defaulted core
setting on the query context. The latter is what the old reroute did as
a side effect, and it has to keep working: `BACKUP ... SETTINGS
max_execution_time = DEFAULT` really does clear a tiny limit today.

The four paths that rebuild a SETTINGS node from `changes` alone -
parseSyncOrAsync, rewriteSettingsWithoutOnCluster and both
copySettingsToQuery - now carry the second carrier too, and the two that
re-inject a name strip it from both carriers so the injected value
cannot be reset by a surviving DEFAULT item. The two copySettingsToQuery
deliberately carry only the core defaults: they emit resolved effective
state, so a stale `backup_uuid = DEFAULT` would discard the UUID
generated after parsing.

Closes: ClickHouse#112895
A format-stability predicate over a BACKUP query exercises only the parser:
ASTSetQuery::formatImpl prints the two SETTINGS carriers and never consults
BackupSettings/RestoreSettings, so it cannot see whether a `name = DEFAULT`
item was actually resolved. Measured: with canonicalBackupSettingName made
the identity, every alias assertion in the round-trip test still prints 1
while the override silently survives the reset the user asked for.

The new shell test therefore asserts through system.backups.settings, which
reports what the settings layer built: a restore-specific reset takes effect
(and the rows really come back), and defaulting either spelling of an alias
pair drops an override written as the other. Each assertion is paired with a
control that must hold in the same run, so an empty result cannot pass
vacuously.

The two rebuilds of a SETTINGS clause are unreachable from a stateless test -
rewriteSettingsWithoutOnCluster runs only via getRewrittenASTWithoutOnCluster,
whose callers are the DDL worker and removeOnClusterClauseIfNeeded (whose
predicate list excludes ASTBackupQuery), and copySettingsToQuery runs only
from BackupsWorker on the ON CLUSTER path - so they get a unit test instead:
the rewrite must strip its injected names from both carriers, and the rebuild
must carry only residual core defaults so the generated backup_uuid survives.

Also: a comment claimed the sub-settings clear their field on `= DEFAULT`,
which the reference file shipped beside it disproves for base_backup, since
parseBackupName accepts a bare identifier as a backup name. The comment now
states what is measured, and a repeated key exercises the branch that does
clear the field. The explicit s3_storage_class entry in the specific-name
array was a duplicate of the list macro.
The BACKUP and RESTORE copySettingsToQuery rebuilds were asymmetric in coverage:
the BACKUP one was pinned by a unit test while the RESTORE one, which emits the
post-parse generated restore_uuid the same way, was not. Add the twin case, and
move both to src/Backups/tests/ where the layer they test lives, so
src/Parsers/tests/gtest_Parser.cpp no longer needs a Backups include.

BackupSettings::isAsync grew a default_settings guard in this branch and it is
the sole input to InterpreterBackupQuery's decision whether to wait for the
operation, but no assertion reached it: the two async rows in 04700 are either
format-only or go through parseSyncOrAsync, which strips async from both
carriers before isAsync runs. Assert the returned status instead, with an
async = 1 control waited out so the file stays deterministic.

Also make the max_execution_time arm in 04700 abort by construction rather than
by a timing margin. checkTimeLimit compares the elapsed time against
totalMicroseconds() * 1000, so the 0.001 s limit was 1 ms against a backup that
takes about 1.1 ms, and the arm failed roughly 0.3% of runs. At 1 us the limit
is below any elapsed time the first check can observe. The oracle is unchanged:
neutering the reset still reddens the arm.

Co-Authored-By: Claude Fable 5 <[email protected]>
OnClusterRebuildCarriesDefaultedNames asserted that `internal` and `host_id`
were absent from the rewritten `default_settings`, but the input query only
defaulted `foo` and `async`, so those two names were never present to begin
with. Deleting either from `names_to_strip` in `rewriteSettingsWithoutOnCluster`
left the test green. `rewriteSettingsWithoutOnCluster` is the only writer that
strips these two names, and this is its only test, so the hole was live: a
surviving `internal = DEFAULT` or `host_id = DEFAULT` would reset the injected
value on every receiving host.

The input now defaults all three injected names and adds an unrelated ordinary
change, and the membership predicates are replaced by one exact-vector
assertion on `default_settings` plus a `changes`-side assertion per injected
name. The exact-vector form also catches a name being added, and the
`structure_only` assertion catches the strip becoming over-broad.

Verified by mutation: dropping `internal` or dropping `host_id` from
`names_to_strip` now reddens the test on the vector assertion (both passed
before this change), and adding `structure_only` to the list reddens it on the
new `changes` assertion.

Also trimmed two comment blocks in BackupSettings.cpp whose worked examples
belong here rather than in the source: the `copySettingsToQuery` carry-over rule
keeps its reason but not the `backup_uuid` walk-through, and the
BACKUP_SPECIFIC_SETTING_NAMES block drops a preamble the code below states
directly. Code is token-identical.

Co-Authored-By: Claude Fable 5 <[email protected]>
@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 4 rounds, 4 findings total;
the final round over this exact content returned 0 findings).

# Sev Finding Verdict Evidence / action
1 ⚠️ The RESTORE side of copySettingsToQuery had no test: only formatting was asserted, which cannot see the settings layer (raised twice) AGREE, fixed Added RestoreCopySettingsToQueryCarriesOnlyCoreDefaults asserting the rebuilt default_settings exactly and that the generated restore_uuid survives, plus delivered-value arms in 04701 read from system.backups.settings. Mutation: carrying the raw default_settings reddens the RESTORE case with {max_execution_time, restore_uuid} while the BACKUP twin stays green
2 ⚠️ The new async = DEFAULT branch in BackupSettings::isAsync was never exercised by a value assertion AGREE, fixed 04701 now asserts async = 1, async = DEFAULT returns BACKUP_CREATED (the reset makes the operation synchronous, so the interpreter waits), with async = 1 alone returning CREATING_BACKUP as the non-vacuity control. Mutation: deleting the guard removes the BACKUP_CREATED line and keeps CREATING_BACKUP
3 ⚠️ The ON CLUSTER rebuild test was vacuous: it asserted internal and host_id were absent from default_settings, but the input never defaulted them AGREE, fixed Input now defaults all three injected names plus an ordinary control; the membership predicates are replaced by one exact-vector assertion plus a value assertion per injected name. Mutation: dropping internal or host_id from the strip list reddens the new test and PASSES the old one, which is the direct proof the hole was live; an over-broad strip reddens the control
4 💡 Comment volume in the source diff AGREE, fixed Two blocks trimmed (7 to 4 and 5 to 4 lines), the worked example moved to the commit message; verified comment-only by stripping comments from both revisions and diffing empty. Census over the whole diff: 105 added comment lines against 361 added code lines

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by a fix round are auto-dropped.

My own independent review of the resulting code raised no blocker and no major. I re-derived the
carrier list myself before reading the plan (every ASTSetQuery construction site plus every
reader of ASTBackupQuery::settings) and it matched the diff exactly; I traced each test back to
the pre-fix failure it guards rather than accepting the claim; and I checked the double-parse in
both directions, confirming that a clause the plain grammar reads to the end keeps its exact
current meaning and that a clause it cannot read is still a syntax error.

Session id: cron:clickhouse-review-slot-8:20260802-031600

@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. A pure parser/formatter identity, so it is not a percentage repro: tests/clickhouse-test 04700_backup_settings_default_round_trip fails on its FIRST assertion against a pristine master build with Code: 62 Syntax error: failed at position 76 (end of query) for SETTINGS foo = DEFAULT, structure_only = 1.
b Root cause explained? Yes. ParserBackupQuery::parseSettings parses items with ParserSetQuery::parseNameValuePair, which has no DEFAULT branch, and ParserList::parseUtil rewinds the clause. Because parseSettings is invoked non-fatally the query still parses, and ParserQueryWithOutput consumes the whole clause into settings_ast instead. ASTSetQuery then prints all changes before all default_settings, so the item is reordered and the output no longer re-parses, and the sibling settings are diverted with it and rejected as unknown core settings.
c Fix matches root cause? Yes. The grammar is taught to read the item, and the layer that owns setting classification is taught to give it meaning. No widened bound, no no-random-* tag, no reduced dataset, no defensive guard at the failure site.
d Test intent preserved / new tests added? Yes, on three levels. 04700_backup_settings_default_round_trip.{sql,reference}: 31 SELECT assertions (22 format-stability predicates, 7 exact-output rows, 2 row-count oracles) plus 10 executed BACKUP/RESTORE statements; 5 of the assertions are no-regression controls that must measure identically before and after (4 forms containing no = DEFAULT at all, plus the lone foo = DEFAULT form that already round-tripped). 04701_backup_settings_default_delivery.{sh,reference}: 12 executed BACKUP/RESTORE statements (7 BACKUP, 5 RESTORE) and 5 SELECT probes that read the resolved values out of system.backups.settings, because a format-stability predicate exercises only the parser half; every assertion is paired with a control that must hold in the same run, and the async rows assert the returned operation status, which is what decides whether the client waits. Three gtests under the one suite BackupSettingsDefault cover the three SETTINGS rebuilds no stateless test can reach: the two copySettingsToQuery twins in src/Backups/tests/gtest_backup_settings_default.cpp and rewriteSettingsWithoutOnCluster in src/Parsers/tests/gtest_Parser.cpp. The rewriteSettingsWithoutOnCluster test asserts the exact post-rewrite default_settings vector and one changes entry per injected name, and each of its three carriers is mutation-verified: removing internal or host_id from the strip list, or making the strip over-broad, reddens it. No existing test removed or weakened; 04073_backup_from_snapshot_ast_format, the only existing test pinning this printer, still passes unchanged.
e Both directions demonstrated? Yes, on distinct binaries with distinct Build IDs. Pristine master (7a551db1c3b783b9...): [ FAIL ], return code: 62. This branch (0f10c12aa2578954..., the binary the stateless tests were measured on; the head build is eebc663afb01f911... and changes no stateless assertion): [ OK ]. Runtime delivery likewise: SETTINGS foo = DEFAULT, structure_only = 1 is Code: 115 Unknown setting 'structure_only' before and BACKUP_CREATED after. Every new assertion additionally has its own mutation arm: neutering the resolver, either alias canonicalizer, the carrier strip, the residual-defaults filter on either the BACKUP or the RESTORE side, or the isAsync guard reddens exactly the assertion that covers it, each with a Build ID that moved.
f Fix is general across code paths? Yes. All four paths that rebuild a SETTINGS node carry the second carrier (parseSyncOrAsync, rewriteSettingsWithoutOnCluster, both copySettingsToQuery), and the two that re-inject a name strip it from both carriers. RESTORE is fixed symmetrically with BACKUP, BACKUP FROM SNAPSHOT is covered, and isAsync (which runs before fromBackupQuery) resolves async = DEFAULT itself. The other four parseNameValuePair callers are deliberately untouched: each fails loudly with Code: 62 on = DEFAULT, so there is no silent reroute to fix.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. The alias pair s3_storage_class/s3_storage_class_name and the obsolete allow_unresolved_access_dependencies canonicalize to one field; names outside the list macro (compression_level, data_file_name_prefix_length) are in the specific-name set; duplicate names resolve order-insensitively in both directions, matching SET; the two OptionalUUID fields are excluded from the copySettingsToQuery carry; unknown names keep today's silently-accepted behavior. Query parameters and {name:Type} substitutions are unchanged by design, with controls pinning them in both arms.
h Backward compatible? (maintainer-approved exception only) Yes. Accepting a previously-rejected spelling is additive, and the no-regression controls measure identically before and after, so no currently valid query changes meaning: 4 SETTINGS forms that contain no = DEFAULT at all (two {name:Type} values, a param_x item, and a clause that must stay SYNTAX_ERROR) plus the lone foo = DEFAULT form that already round-tripped. No setting default changed, so no SettingsChangesHistory.cpp entry is needed, and there is no serialization-format change.
i Invariants and contracts preserved? Yes. parseSettings restores pos exactly to the plain grammar's end position on every non-accepting path, so both existing outcomes survive: a later unparsable item is still Code: 62, and a first unparsable item still falls through to the outer fallback. copySettingsToQuery carries only residual core defaults, so a stale backup_uuid = DEFAULT cannot discard the UUID generated after parsing.

Validation beyond the table: 200 randomized runs of the two stateless tests (two batches of 50 over both files, --order=random) all passed, a further 1400 runs of the .sql test passed, and 16 concurrent copies of the shell test across 8 processes pass together, so neither needs no-parallel. A 67-test backup/restore and AST-format regression sweep run on both binaries shows exactly one outcome change attributable to this branch, the new test going from failing to passing; the one other difference is 03276_database_backup_merge_tree_table_file_engine failing with Code: 701 Requested cluster 'parallel_replicas' not found on a plain SELECT, which has no parser, formatter or backup frame in its stack. To confirm the assertions are not vacuous I built eleven variants with one piece of the fix deliberately removed or made over-broad at a time: each reddened exactly the assertion covering it and passed again once restored, with a Build ID that moved in both directions.

Session id: cron:clickhouse-impl-slot-43:20260801-233600

@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author

cc @pamarcos @evillique, could you review this? BACKUP/RESTORE ... SETTINGS <name> = DEFAULT was parsed by a pair parser with no DEFAULT branch, and because parseSettings is invoked non-fatally the whole clause was rerouted to the generic query-level SETTINGS node, which both broke the format/parse round trip and silently discarded every backup-specific setting beside the defaulted one.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 2, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d0f3c65]

Summary: ✅


AI Review

Summary

This PR fixes the BACKUP/RESTORE ... SETTINGS <name> = DEFAULT parsing path and the earlier reset/constraint gaps, but one ON CLUSTER forwarding bug remains. The per-host query rebuild still drops two backup-specific settings, so worker backups can ignore a user-specified compression_level or data_file_name_prefix_length.

Findings

⚠️ Majors

  • [src/Backups/BackupSettings.cpp:187] copySettingsToQuery rebuilds worker SQL from LIST_OF_BACKUP_SETTINGS plus core_settings, but compression_level and data_file_name_prefix_length are parsed outside that macro and never re-emitted. BackupsWorker::openBackupForWriting consumes both on every host, so BACKUP ... ON CLUSTER ... SETTINGS compression_level = 1 or data_file_name_prefix_length = 1 falls back to each worker's local defaults/config instead of the query value. Suggested fix: emit those two fields in copySettingsToQuery, or move them into LIST_OF_BACKUP_SETTINGS so the rebuild path carries them automatically.
Final Verdict

Changes requested.

LLVM Coverage Report

Measured on commit d0f3c65.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 79.60% 79.60% +0.00%

Changed lines: Changed C/C++ lines covered: 242/252 (96.03%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 2, 2026
Comment thread src/Backups/BackupSettings.cpp Resolved
`BackupSettings::isAsync` is the sole input to InterpreterBackupQuery's decision whether to wait for
the operation, and it reads the SETTINGS clause separately from `fromBackupQuery`, which decides the
operation's effective `async`. The two disagreed in two ways, both reachable from a plain BACKUP or
RESTORE and both present before this PR:

- Duplicates resolved in opposite directions. `SettingsChanges::tryGet` returns the FIRST match, while
  `fromBackupQuery` assigns each match in turn and so keeps the LAST, which is what `SET` does. So
  `BACKUP ... SETTINGS async = 0, async = 1` ran asynchronously but the client waited and reported
  `BACKUP_CREATED`, and `async = 1, async = 0` ran synchronously while the client returned
  `CREATING_BACKUP` immediately.
- Value conversion. `isAsync` used `Field::safeGet<bool>`, which requires the field to already be an
  integer, while `fromBackupQuery` converts through `SettingFieldBool`. So `async = '1'` aborted the
  query with `BAD_GET` after the backup had already been started, leaving it running.

Resolve the last `async` change and convert it through `SettingFieldBool`, so both readers reach the
same value by construction. The `async = DEFAULT` check stays ahead of the lookup: a reset must win
over any change, which is the behaviour the rest of this PR establishes.

Covered by a table-driven gtest that asserts `isAsync` equals `fromBackupQuery(...).async` for every
form, and by 04701 arms asserting the returned status against the effective setting.

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 2, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

Changed lines: Changed C/C++ lines covered: 265/270 (98.15%) · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - da0869a

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stress test (arm_asan_ubsan, s3) / Hung check failed, possible deadlock found one hung row: a cancelled AsyncInsertFlush (is_cancelled: 1, elapsed 931 s, 03365_json_rollback_bug.sh) keeps running inside JSON deserialization, so cancellation is not honoured within one IRowInputFormat::read block #112646 (ours, open)
Bugfix validation (unit tests) harness abort, not a test failure: Bugfix validation inconclusive: submodule state differs between the merge-base and the checkout (contrib/orc). Base-branch motion, not this PR: the diff is 17 files with zero contrib/ paths, and the contrib/orc gitlink is identical at the merge base and at this head a fix task owns it (investigating at full effort - fixing-PR link to follow here)

Build (arm_release) reports success; its CIDB Post Hooks row is a non-gating build-profile
telemetry insert that could not reach the stats database, not a build or test failure.

Session id: cron:our-pr-ci-monitor:20260802-220000

@clickhouse-gh

clickhouse-gh Bot commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing d0f3c6566 with master 7264abe5d (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

9 object files changed (+93.09 KiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Backups/resolveDefaultedSettings.cpp.o new 82.14 KiB +82.14 KiB

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

54 translation units recompiled, 406 s compile time in total, 53 of them have a recent master baseline.

Job report

… setting

`master` gained `Context::checkSettingsConstraintsForSettingsReset`, which both
`SET <name> = DEFAULT` and a query-level `SETTINGS <name> = DEFAULT` run before
the reset is applied. The BACKUP/RESTORE branch of
`InterpreterSetQuery::applySettingsFromQuery` reset the core names this branch
resolves without that check, so `BACKUP ... SETTINGS max_execution_time = DEFAULT`
slipped past a `CONST` constraint that `SELECT ... SETTINGS max_execution_time = DEFAULT`
is rejected by. Before this branch such a clause was rerouted to the generic
query-level `SETTINGS` node, which did run the check, so leaving it out would have
been a regression rather than a pre-existing gap.

Both carriers are now checked before either is applied, as `executeForCurrentContext`
does, so a violation leaves the whole statement without effect. The `changes` check
keeps the emptiness guard it has always had: it also runs a sanity clamp over the
whole settings object, which must not start happening for a clause that overrides
nothing.

`04700` and `04701` are unchanged and still pass. The new test
`05047_backup_settings_default_constraint.sh` asserts the two rejections next to
five controls that must not move: an unconstrained core reset, an override equal to
the constrained value, a clause with no core setting at all, and the two
BACKUP/RESTORE-specific resets, which are resolved in the settings layer and never
reach the context. Removing the new check flips exactly the two rejections to
`accepted` and leaves every control identical.
@groeneai

Copy link
Copy Markdown
Collaborator Author

ON CLUSTER rebuild: this PR breaks mixed-version clusters

Re-reviewing my own delta, and I would rather flag this than have it merge.

copySettingsToQuery carries core name = DEFAULT items in ASTBackupQuery::settings, and that
clause is what other hosts receive: BackupsWorker.cpp:753-754 (:1209-1210 for RESTORE) ->
sendQueryToOtherHosts -> executeDDLQueryOnCluster, where the text is
entry.query = query_ptr->formatWithSecretsOneLine() (:196). ASTSetQuery prints changes
before default_settings, so the distributed text is
SETTINGS backup_uuid = '...', max_execution_time = DEFAULT. Measured rather than read: feeding the
reset first still prints the change first. My gtest
BackupCopySettingsToQueryCarriesOnlyCoreDefaults pins exactly that pair.

A released parser rejects that text. formatQuery on a master binary and on this PR's binary:

SETTINGS clause master this PR
backup_uuid = 'abc' ok ok
max_execution_time = DEFAULT ok (rerouted to the query-level clause) ok
backup_uuid = 'abc', max_execution_time = DEFAULT Code: 62 syntax error ok
RESTORE ... restore_uuid = 'abc', max_execution_time = DEFAULT Code: 62 ok
max_threads = 4, max_execution_time = DEFAULT Code: 62 ok

The last row shows it is not backup_uuid specific: any item, a comma, then = DEFAULT. So on a
rolling upgrade a new initiator distributes a
BACKUP/RESTORE ... ON CLUSTER ... SETTINGS <core setting> = DEFAULT that every not yet upgraded
host fails to parse.

I measured the parse rejection only. There is no mixed-version coverage for this path (stateless
configs are single-host, which is why the rebuild is gtest-pinned), so how it surfaces end to end is
inferred, and distributed_ddl_output_mode is never_throw just before distributing.

One correction to the natural reading of this: the reset did not previously travel in the outer
SETTINGS clause. executeDDLQueryOnCluster.cpp:78 calls resetOutputASTIfExist, which clears
settings_ast before :196 serializes, so before this PR nothing carried the reset to other hosts
and the distributed text parsed everywhere. Moving it back to that carrier is therefore not a fix:
it would be dropped, and silently, because both parsers accept the two-clause form.

Two small options, and I would rather you pick:

  1. Do not carry core resets in the rebuild. Identical to the pre-PR distributed behaviour, so no
    regression, and the reset stays a local effect on the initiator.
  2. Emit the resolved default value as an ordinary change instead of name = DEFAULT. Released
    parsers accept it and the effective value on the receiver is unchanged, but the setting is then
    marked changed, so it appears in query_log.Settings where a true reset makes it absent.

Either is a few lines in BackupSettings::copySettingsToQuery and its RestoreSettings twin, plus
the two gtests that pin the current shape.

Separately, on discussion_r3882011727: rejectHTTPOnlyConstructionSettings is indeed never reached
from this branch, but the compression = <value> half is not new here. At the base (fbc7824) that
function already had one caller, executeForCurrentContext, and this branch never called it. Since
compression shapes the HTTP response before the query runs, it is a no-op on a backup either way,
so the call restores a diagnostic rather than closing a bypass. That is past what this PR set out to
change: it is implemented and validated locally, and I will push it only if you want it here.

groeneai and others added 2 commits August 28, 2026 18:10
…ssion

The arm installed a 1 us `max_execution_time` at session level, so the
`SET max_execution_time = DEFAULT` that undid it ran under that budget itself.
`ProcessList::insert` registers a query with `CancellationChecker` using the
`max_execution_time` in effect at insert time, so the reset statement was
cancelled with `CancelReason::TIMEOUT` whenever the checker reached it before
`executeQuery` got to its killed check, which then reported
`Timeout exceeded: maximum: 0.001 ms`. Whether that happens depends only on how
fast the statement gets through its own prologue, so it is flaky by
construction, and it failed the flaky check on four arms.

A session-level budget that small cannot be undone from the same session. A
clause-carried one needs no undoing: core settings of a BACKUP/RESTORE clause
are applied before `ProcessList::insert`, so a clause resetting
`max_execution_time` is never registered with the checker, and no statement
outside the arm sees the budget.

The pair also pins more than before. The first arm shows a core change in the
clause reaching the query context, the second that a reset of the same name in
the same clause wins over it, matching `SET x = 1, x = DEFAULT`. The session
form of the second arm did not discriminate: it passes on master too, where a
lone `= DEFAULT` item was rerouted to the query-level SETTINGS clause. With
`resetSettingsToDefaultValue` removed the new second arm fails with
TIMEOUT_EXCEEDED while both controls stay green.

Co-Authored-By: Claude Opus 5 <[email protected]>
…GS clause

`rejectHTTPOnlyConstructionSettings` refuses `compression` in both SETTINGS carriers, because the
HTTP response body is shaped before the query runs, so the setting has no effect from an in-query
clause. Its only caller was `executeForCurrentContext`, so the BACKUP/RESTORE branch of
`applySettingsFromQuery` accepted both forms while every other query type refused them.

The two forms got here differently. `compression = <value>` was always accepted on this path, which
never called the rejection. `compression = DEFAULT` used to be refused: before this PR a lone
`= DEFAULT` item was rerouted to the query-level SETTINGS clause, which does call it. Measured over
HTTP, master answers `Code: 36` for `BACKUP ... SETTINGS compression = DEFAULT` while this branch
accepted it, with `SELECT 1 SETTINGS compression = DEFAULT` refused on both as the control. So this
restores a rejection the new path dropped, and closes the older gap next to it.

`compression` is ineffective on a backup either way, so what a backup does is unchanged. Bare
`compression` is not a BACKUP setting: `compression_method` and `compression_level` are different
names and keep working, which the new control arm pins.

The gtest comments lose their hard-coded `file:line` citations, three of which had gone stale as
master moved: they name the symbol instead.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

Two commits on top of 19845b55, both mine, nothing rebased or force-pushed.

04700 was failing the flaky check on four arms. It installed a 1 us max_execution_time at session
level, so the SET max_execution_time = DEFAULT that undid it ran under that budget itself:
ProcessList::insert registers a query with CancellationChecker using the value in effect at insert
time, and executeQuery then reports Timeout exceeded: maximum: 0.001 ms whenever the checker wins
the race against the statement's own prologue. The arm now carries the budget in the BACKUP clause,
where core settings are applied before ProcessList::insert, so no statement outside the arm ever
sees it. 50 runs each of 04700, 04701, 05047 and 04316 pass, and with
resetSettingsToDefaultValue removed only the new second arm fails, with both controls unchanged.

I also pushed the compression rejection, and I was wrong to call it out of scope in my previous
comment. Measured over HTTP: master answers Code: 36 for BACKUP ... SETTINGS compression = DEFAULT
while this branch accepted it, with SELECT 1 SETTINGS compression = DEFAULT refused on both as the
control, so that half is a regression of this PR rather than a pre-existing gap. The = <value> half
does predate it.

The description now names both extra behaviour changes. The ON CLUSTER text compatibility question
from my previous comment is still open.

Comment thread src/Backups/BackupSettings.cpp Resolved
`BackupsWorker` calls `copySettingsToQuery` and then `sendQueryToOtherHosts`
(`BackupsWorker.cpp:753`, `:1209`), which reaches `executeDDLQueryOnCluster`, where the
per-host entry is the rebuilt query as SQL *text*
(`entry.query = query_ptr->formatWithSecretsOneLine()`). Every host re-parses that text
with its own parser: `getRewrittenASTWithoutOnCluster` runs on the receiver
(`DDLTask.cpp:532`), after the parse. So the rebuilt clause has to be readable by a
version that does not have this fix.

`ASTSetQuery` prints all `changes` before all `default_settings`, and the rebuild always
emits a generated `backup_uuid`/`restore_uuid` change, so carrying a core reset in
`default_settings` always produced text of the form
`SETTINGS backup_uuid = '...', max_execution_time = DEFAULT` - a `= DEFAULT` item after a
comma, which is exactly the shape this pull request teaches the parser to read and which
no released version accepts. Measured on 26.7.1.1362: that text is `Code: 62`, while
`SETTINGS backup_uuid = 'abc', max_execution_time = 0` parses. So
`BACKUP/RESTORE ... ON CLUSTER ... SETTINGS <core setting> = DEFAULT` would have failed on
every host of a cluster mid-rolling-upgrade. A regression rather than a pre-existing gap:
before, the item lived in the query-level `settings_ast`, which
`executeDDLQueryOnCluster` clears via `resetOutputASTIfExist`, so nothing carried it.

A core reset is now forwarded as an ordinary change holding the setting's declared
default. That is the value the reset produces - `resetSettingsToDefaultValue` assigns the
declared default and `checkResetToDefault` validates a reset as an assignment of it - so
the receiver ends at the same value, and the text has no `= DEFAULT` in it. The one
observable difference is that the setting counts as changed on the receiver, so it appears
in that host's `query_log.Settings`, where a true reset leaves it absent.

`appendCoreDefaultsAsChanges` appends after the core overrides on purpose: a name written
in both carriers then resolves to the reset on the receiver, which applies the changes in
order, exactly as it resolves on the host that parsed the clause, where the reset is
applied after every override. Order is what decides it, so this holds for an alias
spelling of the same field too, which a name-matching erase would miss. A name that is not
a built-in setting is skipped: resetting one removes a custom setting, which no change can
express, and resetting an unknown name does nothing, so either stays a local effect on the
initiator - where it already was.

The two `copySettingsToQuery` gtests now assert the cross-version property directly, on
the output of the same `formatWithSecretsOneLine` call the DDL path makes, rather than the
AST shape alone. `BackupCopySettingsToQueryResolvesANameInBothCarriers` covers the
resolution order. Reinstating the `default_settings` assignment fails all three with
`the per-host text must contain no = DEFAULT, got: ... max_execution_time = DEFAULT`,
while `IsAsyncAgreesWithFromBackupQuery` and `OnClusterRebuildCarriesDefaultedNames` stay
green.
@PedroTadim

Copy link
Copy Markdown
Member

@pamarcos or @jkartseva can you help reviewing this?

@jkartseva jkartseva self-assigned this Sep 22, 2026
@alexey-milovidov alexey-milovidov added the blocker This issue / pr blocks a new release label Sep 28, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

This is urgent, it fails on master.

alexey-milovidov and others added 3 commits September 28, 2026 01:33
…ettings-default

# Conflicts:
#	src/Parsers/stripQuerySettings.cpp
…alue

`copySettingsToQuery` used to rewrite a core `name = DEFAULT` into
`name = <declared default>` for the per-host text of `ON CLUSTER`. That is not
equivalent on the receiving hosts: an explicit value marks the setting as
changed there, while the reset leaves it unset on the initiator, and
object-storage code keys off that bit (`BackupReaderS3`/`BackupWriterS3` call
`updateFromSettings(..., if_changed = true)`, so `s3_retry_attempts = DEFAULT`
replaced every worker's own `<s3>` configuration with the built-in default).

The reset needs no carrier at all. It is applied to the initiator's query
context, which clears the `changed` bit, and the DDL settings packet sent with
the text is built from that same context
(`DDLLogEntry::setSettingsIfRequired` ships `getSettingsRef().changes()`), so
the setting is already absent there. What has to go is any override of the
reset setting in the rebuilt text, under any of its names, because a receiving
host applies the text on top of the packet. `eraseOverridesOfResetSettings`
does exactly that and replaces `appendCoreDefaultsAsChanges`. This also makes
the `auto(N)` special case for `max_threads` unnecessary, since no default
value is sent any more. The text still contains no `= DEFAULT`, so a cluster
that is mid-rolling-upgrade keeps working.

Addresses the AI review blocker on `resolveDefaultedSettings.cpp`.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
# Conflicts:
#	src/Parsers/stripQuerySettings.cpp
@jkartseva

Copy link
Copy Markdown
Member

@groeneai Reduce the comments to 140 symbols per paragraph

groeneai and others added 2 commits September 28, 2026 03:05
…LECT ... SETTINGS` does

The core settings of a BACKUP/RESTORE clause went through the non-const
`checkSettingsConstraints` overload, which drops every change equal to the value
the setting already has. So for `SETTINGS max_execution_time = 0.000001,
max_execution_time = 0` the trailing item was dropped and the first one applied,
while `SELECT ... SETTINGS` keeps both and ends at 0. That is also the shape an
ON CLUSTER BACKUP/RESTORE forwards to the other hosts for a core reset (the
override, then the declared default), and each host applies it through this
same branch. `execute` and `executeForCurrentContext` already use the const
overload for this reason.

The resets also skipped the profile-aware check from ClickHouse#120376, so
`BACKUP ... SETTINGS profile = 'p', max_execution_time = DEFAULT` was accepted
when `p` makes the setting constant, while `SET` and `SELECT ... SETTINGS` reject
it. Pass the clause's changes to the three-argument overload, as the other two
paths do.

Both are measured over HTTP. The native client applies the clause on its side
first (a `profile` item fails there with THERE_IS_NO_PROFILE), and the
duplicate-item case does not reproduce through it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…agraph

Comments only, as asked in review. The `04700` reference changes only in the
comment lines `-- { echo }` repeats. The two header comments this change had
extended are back to their master wording.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

@jkartseva thanks for the merge. Pushed on top of it:

  • eacd84d: the BACKUP/RESTORE clause is now checked the way SELECT ... SETTINGS is. The non-const checkSettingsConstraints dropped an item equal to the current value, so over HTTP BACKUP ... SETTINGS max_execution_time = 0.000001, max_execution_time = 0 still timed out, and that is also the shape in which an ON CLUSTER reset is forwarded to the other hosts. The reset check also ignored a profile set earlier in the clause (Enforce settings constraints installed by a profile in the same statement #120376), so profile = 'p', max_execution_time = DEFAULT was accepted when p makes the setting constant. New arms in 05047 are red before the change and green after it.
  • d710f6e: every comment paragraph of this change is now at most 140 characters.

@alexey-milovidov the failure on master is this round-trip: BuzzHouse (amd_debug), BACKUP ... SETTINGS <22 settings>, iceberg_snapshot_id = DEFAULT. That query shape formats stably on this head and fails with Code: 62 on re-parse on current master.

alexey-milovidov and others added 2 commits September 28, 2026 03:48
…hosts

`BACKUP`/`RESTORE ON CLUSTER ... SETTINGS max_threads = 3, max_threads = DEFAULT`,
with `max_threads` also set for the whole query, must leave `max_threads` unset in
the per-host queries, as it is on the initiator. The test checks `system.query_log`
on two hosts. It fails with the previous forwarding code, which sent the reset as
an explicit value.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…default' into fix-112895-backup-settings-default

# Conflicts:
#	src/Backups/BackupSettings.cpp
#	src/Backups/RestoreSettings.cpp
#	src/Backups/resolveDefaultedSettings.cpp
#	src/Backups/resolveDefaultedSettings.h
#	src/Backups/tests/gtest_backup_settings_default.cpp
@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default and removed pr-improvement Pull request with some product improvements labels Sep 28, 2026
/// The DDL settings packet already omits it, so only its overrides are dropped.
///
/// A backup-specific reset is not sent: the rebuild carries resolved state, and resolving it again would lose `backup_uuid`.
eraseOverridesOfResetSettings(query_settings->changes, extractCoreSettingsFromQuery(query).default_names);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

copySettingsToQuery still rebuilds the per-host BACKUP ... ON CLUSTER clause only from LIST_OF_BACKUP_SETTINGS plus core_settings, but compression_level and data_file_name_prefix_length are handled outside that macro and never appended manually. fromBackupQuery still parses both as backup-specific settings, and BackupsWorker::openBackupForWriting consumes them on every host, so BACKUP ... ON CLUSTER ... SETTINGS compression_level = 1 or data_file_name_prefix_length = 1 is silently lost on the worker queries and falls back to each host's local defaults/config instead.

Please forward those two fields here as well (or move them into LIST_OF_BACKUP_SETTINGS) so the per-host internal queries reopen the backup destination with the same effective settings as the initiator.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - d0f3c65

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stress test (amd_debug) / Logical error in IColumn::assertTypeEquality (STID: 2508-4620) trunk bug, not this diff: the type assertion in IColumn::insertRangeFrom fails in the shared-variant branch of SerializationDynamicElement::deserializeBinaryBulkWithMultipleStreams, while MergeTreeReaderWide reads a nested dynamic path of a JSON column. This PR changes only how BACKUP/RESTORE settings are parsed, formatted and applied. In the last 30 days the same STID failed the Stress test of one other, unrelated pull request (report) #116393 (external, open)
Mergeable Check, PR rollups, red only because of the row above #116393 (external, open)

All 146 check runs completed (130 pass, 15 not selected, 1 red).

Session id: cron:our-pr-ci-monitor:20260928-100645

@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

@jkartseva
jkartseva enabled auto-merge September 28, 2026 17:43
@jkartseva
jkartseva added this pull request to the merge queue Sep 28, 2026
Merged via the queue into ClickHouse:master with commit 62ff687 Sep 28, 2026
294 of 295 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 28, 2026
inakisoriamrf pushed a commit to inakisoriamrf/ClickHouse that referenced this pull request Oct 2, 2026
…STER`

With `data_file_name_generator = 'checksum'`, every host of a
`BACKUP ... ON CLUSTER` names the data files it writes itself
(`BackupCoordinationFileInfos::prepare` -> `getBackupDataFileName`), while
the initiator writes the `<data_file>` names into `.backup` from its own
computation, so both must use the same prefix length.
`BackupSettings::copySettingsToQuery`, which builds the query sent to the
hosts, emitted only the `LIST_OF_BACKUP_SETTINGS` fields, and
`data_file_name_prefix_length` is parsed outside that list. The hosts got
`checksum` but no prefix length, used their own
`backups.data_file_name_prefix_length` (3 by default), and wrote every
file under a name that `.backup` does not contain. `BACKUP` reported
`BACKUP_CREATED`, and every `RESTORE` from that backup failed with
`FILE_DOESNT_EXIST`.

The initiator now sends its resolved prefix length (from the query or from
its own config) when the resolved generator is `checksum`. The default
generator ignores the prefix length, and not sending it then keeps
`BACKUP ON CLUSTER` working with hosts older than 25.11, which do not know
the setting.

`compression_level` is not forwarded either, but only archive destinations
read it, and those are rejected for `ON CLUSTER`.

Reported in ClickHouse#112978 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

blocker This issue / pr blocks a new release can be tested Allows running workflows for external contributors comp-backup Backup/restore infrastructure and backup formats. groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Inconsistent AST formatting: BACKUP ... SETTINGS <name> = DEFAULT cannot be parsed back

5 participants