Skip to content

Fix BAD_GET on ALTER for tables created with inline disk SETTINGS - #103818

Closed
groeneai wants to merge 36 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-63019-custom-disk-alter-bad-get
Closed

groeneai wants to merge 36 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-63019-custom-disk-alter-bad-get

Conversation

@groeneai

@groeneai groeneai commented May 1, 2026

Copy link
Copy Markdown
Collaborator

A table created with SETTINGS disk = disk(...) (inline custom-disk
function) cannot be altered: every ALTER raises
Bad get: has CustomType, requested String. (BAD_GET). This happens
even on alters that do not touch the disk setting (e.g. ADD COLUMN,
MODIFY COLUMN, or MODIFY SETTING for any other setting), because
the ALTER pipeline re-applies the table's settings_changes AST
through the validation pipeline and the parser stores disk = disk(...)
as a CustomType Field wrapping the function AST, which trips
SettingFieldString::operator= in BaseSettings::applyChanges.

The CREATE path already handles this in
MergeTreeSettingsImpl::loadFromQuery: it intercepts the CustomType
field, calls DiskFromAST::createCustomDisk to register the inline
disk, and replaces the value with the resulting disk-name string before
calling applyChanges. The ALTER path skipped this conversion in
several places.

This PR extracts the conversion into reusable helpers in DiskFromAST
and applies it in all three previously-affected ALTER call sites in
MergeTreeData:

  • changeSettings (the actual ALTER apply path, called from both
    StorageMergeTree::alter and StorageReplicatedMergeTree::alter).
  • checkAlterIsPossible's settings-validation block, which calls
    MergeTreeSettings::checkCanSet, safeGet<String>, and
    applyChanges on each new setting.
  • checkColumnFilenamesForCollision(metadata, ...), called from
    checkAlterIsPossible to enumerate per-column file names against a
    fresh defaults instance with the new settings applied.

The two existing CREATE-path callers
(MergeTreeSettingsImpl::loadFromQuery and
DatabaseMetadataDiskSettingsImpl::loadFromQuery) are refactored to
use the new helpers — pure de-duplication, no behaviour change.

Adds regression test 04145_alter_with_inline_disk_setting.sql
covering all three throw sites: ADD COLUMN, MODIFY COLUMN, and a
non-disk MODIFY SETTING (which still re-applies the inline disk
through changeSettings).

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):

Fix Bad get: has CustomType, requested String thrown by ALTER TABLE (ADD COLUMN, MODIFY COLUMN, MODIFY SETTING, etc.) on a MergeTree table created with an inline SETTINGS disk = disk(...) function. Closes #63019.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

A table created with `SETTINGS disk = disk(...)` (inline custom-disk
function) could not be altered: every `ALTER` raised
`Bad get: has CustomType, requested String. (BAD_GET)`. This happened
even on alters that do not touch the `disk` setting (e.g. `ADD COLUMN`,
`MODIFY COLUMN`, or `MODIFY SETTING` for any other setting), because the
ALTER pipeline re-applies the table's `settings_changes` AST through
the validation pipeline and the parser stores `disk = disk(...)` as a
`CustomType` `Field` wrapping the function AST, which trips
`SettingFieldString::operator=` in `BaseSettings::applyChanges`.

The CREATE path already handled this in
`MergeTreeSettingsImpl::loadFromQuery`: it intercepts the `CustomType`
field, calls `DiskFromAST::createCustomDisk` to register the inline
disk, and replaces the value with the resulting disk name string before
calling `applyChanges`. The ALTER path skipped this conversion in
several places.

Extract that conversion into reusable helpers in `DiskFromAST`:

- `convertCustomDiskField(Field & value, context, attach)` — the per-
  field conversion (extracted from `loadFromQuery` /
  `DatabaseMetadataDiskSettingsImpl::loadFromQuery` which already
  duplicated this logic).
- `convertCustomDiskSettings(SettingsChanges & changes, context, attach)`
  — walks a settings-changes vector and converts any change named
  `disk`. Used by every code path that re-applies a table's
  `settings_changes` AST.

Apply the conversion in three previously-affected ALTER call sites in
`MergeTreeData`:

- `changeSettings` (the actual ALTER apply path, called by
  `StorageMergeTree::alter` and `StorageReplicatedMergeTree::alter`).
- `checkAlterIsPossible`'s settings-validation block, which calls
  `MergeTreeSettings::checkCanSet`, `safeGet<String>`, and
  `applyChanges` on each new setting.
- `checkColumnFilenamesForCollision(metadata, ...)`, which is called
  from `checkAlterIsPossible` and re-applies the changes onto a fresh
  default settings instance to enumerate per-column file names.

Also refactor the existing CREATE-path callers
(`MergeTreeSettingsImpl::loadFromQuery` and
`DatabaseMetadataDiskSettingsImpl::loadFromQuery`) to use the new
helpers — pure de-duplication, no behaviour change.

Adds regression test
`04145_alter_with_inline_disk_setting.sql` covering all three throw
sites: `ADD COLUMN`, `MODIFY COLUMN`, and a non-`disk` `MODIFY SETTING`
(which still re-applies the inline `disk` through `changeSettings`).

Closes ClickHouse#63019

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

groeneai commented May 1, 2026

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (per our internal worker procedure)

Session: `cron:clickhouse-ci-task-worker:20260501-034500`

a) Deterministic repro? Yes. The exact two queries from #63019:

```sql
CREATE TABLE test_mt (a Int32, b Int64) ENGINE = MergeTree() ORDER BY a
SETTINGS disk = disk(type = object_storage, object_storage_type = local_blob_storage, path = '/tmp/local/');

ALTER TABLE test_mt ADD COLUMN c Int64 AFTER b;
-- Code: 170. DB::Exception: Bad get: has CustomType, requested String. (BAD_GET)
```

reproduce 100% of the time on master HEAD before the fix.

b) Root cause explained? The parser produces a `Field` with type `CustomType` (a `FieldFromASTImpl` wrapping the `disk(...)` AST). `MergeTreeSettingsImpl::loadFromQuery` (CREATE path) intercepts this and converts it to a registered disk-name `String` via `DiskFromAST::createCustomDisk` before calling `applyChanges`. The ALTER pipeline did NOT do this conversion in any of: `MergeTreeData::changeSettings`, `MergeTreeData::checkAlterIsPossible`, `MergeTreeData::checkColumnFilenamesForCollision`. So when these called `safeGet` / `applyChanges` / `MergeTreeSettings::checkCanSet` on the `CustomType` `Field`, they threw `BAD_GET`. Stack trace from the failing run:

```
5. Field.cpp:872 Field::safeGet()
6. Field.h:443 SettingFieldString::operator=(Field const&)
7. MergeTreeSettings.cpp:2219 BaseSettings::set()
8. BaseSettings.h:403 MergeTreeSettings::applyChanges()
9. MergeTreeData.cpp:8952 checkColumnFilenamesForCollision(metadata, ...)
10. MergeTreeData.cpp:4618 checkAlterIsPossible()
11. InterpreterAlterQuery.cpp:304 executeToTable()
```

c) Fix matches root cause? Yes — the fix mirrors the CREATE-path conversion in all three ALTER call sites via a shared `DiskFromAST::convertCustomDiskSettings(SettingsChanges &, ContextPtr, bool)` helper. Targeted (only the `disk` setting is special-cased), no `try/catch`, no skipping the validation.

d) Test intent preserved? / New tests added? No existing assertion is weakened. New test `04145_alter_with_inline_disk_setting.sql` covers all three throw sites: `ADD COLUMN` (hits `checkColumnFilenamesForCollision`), `MODIFY COLUMN` (hits the `checkAlterIsPossible` validation block), and a non-`disk` `MODIFY SETTING` (hits `changeSettings` — the actual apply path).

e) Both directions demonstrated? Yes. Without the patch the test fails on every iteration with `BAD_GET`; with the patch it passes 10/10 with full settings randomization on a debug build.

f) Fix is general, not a narrow patch? I checked every `applyChanges` / `safeGet` / `checkCanSet` site that consumes a metadata `settings_changes` AST in MergeTree code (`MergeTreeData.cpp` lines 4691, 4876, 8952; `MergeTreeSettings.cpp` line 2287; the validation block in `checkAlterIsPossible`). Each one that hit the bug is now protected. The same conversion was already present in `DatabaseMetadataDiskSettings.cpp` — I refactored it to use the shared helper for consistency. I also asked why the bad state arrives here: the `CustomType` representation is intentional (the parser preserves the `disk(...)` AST so it can be re-serialised in the table's CREATE statement), so the fix correctly converts at every consumer rather than trying to "fix the source".

@groeneai

groeneai commented May 1, 2026

Copy link
Copy Markdown
Collaborator Author

cc @kssenii (issue author + comp-object-storage-disks owner) and @alesapin (comp-mergetree manager) — could you review? The fix mirrors the CREATE-path DiskFromAST::createCustomDisk conversion in the three ALTER pipeline sites that re-apply settings_changes (changeSettings, checkAlterIsPossible, checkColumnFilenamesForCollision) via a shared helper.

Also @PedroTadim — thanks for the nudge, this should fix the MODIFY SETTING variant you hit on 2026-04-07 too.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label May 1, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5ea3364]

Summary: ✅


AI Review

Summary

This PR fixes the main BAD_GET path and adds substantial regression coverage around inline disk(...) ownership, but two failure paths still violate the core contract: a failed metadata transition can leave local or live metadata referring to a custom disk that the rollback scope then removes from the global selectors.

Findings

❌ Blockers

  • [src/Storages/StorageReplicatedMergeTree.cpp:6971] The replicated full-ALTER cleanup still only logs if rewriting the old local metadata file throws. In that case the failed .sql can still contain the new inline disk, but unwinding then reaches disk_scope with committed == false and removes that disk from DiskSelector / FileCacheFactory. A restart can therefore reload metadata that references a disk the rollback already deleted. This cleanup path needs the same fail-close rule already used in doCreateOrReplaceTable and createDatabase: if restoring durable local metadata fails, keep the disk scope instead of rolling it back.
  • [src/Interpreters/InterpreterCreateQuery.cpp:2079] The new ambient CREATE scope assumes any database->createTable exception means no live table still owns the tentative disk, but DatabaseOnDisk::commitCreateTable still attaches the table before replaceFile, and its catch only removes .sql.tmp (src/Databases/DatabaseOnDisk.cpp:314-324). If replaceFile throws in an Ordinary database, the table stays attached in memory while unwinding reaches ~CustomDiskRegistrationScope, which removes the inline disk from the global selectors. The fix needs to detach that half-created table on the commitCreateTable failure path, or otherwise keep the disk when cleanup cannot prove the table was removed.
Final Verdict

Changes requested.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label May 1, 2026
@PedroTadim

Copy link
Copy Markdown
Member

@groeneai can you add the ALTER TABLE t0 MODIFY SETTING disk = disk(type = cache, disk = 'default', path = '/var/lib/clickhouse/filesystem_caches/inline_cache_default/'); like test case?

…ouse#63019

Per @PedroTadim's review request on PR ClickHouse#103818, extend
04145_alter_with_inline_disk_setting with explicit coverage of
`ALTER TABLE ... MODIFY SETTING disk = disk(...)` — i.e., changing the
`disk` setting itself to another inline `disk(...)` function, which is
the exact form @PedroTadim originally hit on issue ClickHouse#63019.

Two cases:

1. Idempotent: re-applying the SAME inline `disk(...)` value via
   `MODIFY SETTING`. This still flows through
   `convertCustomDiskSettings` and `change.value.safeGet<String>()` in
   `MergeTreeData::changeSettings`, which is exactly the call site that
   threw `BAD_GET` (code 170) before the fix. With the fix the storage
   policy is the same → no migration → silent success → table data still
   readable.

2. Cache wrap: `MODIFY SETTING disk = disk(type = cache, ...)` wrapping
   the existing inline disk by name. Before the fix this threw `BAD_GET`
   in `checkAlterIsPossible` at the `safeGet<String>` call. After the
   fix the `CustomType` conversion succeeds and the request is correctly
   rejected by the storage-policy migration guard with `BAD_ARGUMENTS`
   (code 36) — changing the `disk` to a different storage policy is
   not permitted because the new policy must include all old disks.
   Asserted via `{ serverError BAD_ARGUMENTS }`. The crucial property is
   that the error code is 36 (domain-level validation) and not 170
   (`Field` type crash).

Verified locally:
* 20/20 passes on the fix branch with the test runner's full settings
  randomization.
* Manually reproduced the pre-fix path by reverting just the
  `convertCustomDiskSettings` call in `MergeTreeData::changeSettings`,
  rebuilding, and confirming the same-disk MODIFY SETTING then throws
  `Code: 170. BAD_GET`.

Closes ClickHouse#63019 (test coverage).
@groeneai

groeneai commented May 5, 2026

Copy link
Copy Markdown
Collaborator Author

@PedroTadim — done in 0b44e16. Added two MODIFY SETTING disk = disk(...) regression cases to 04145_alter_with_inline_disk_setting.sql:

  1. Idempotent: re-applying the SAME inline disk(...) value. This still flows through convertCustomDiskSettings and change.value.safeGet<String>() in MergeTreeData::changeSettings — the exact site that threw BAD_GET (code 170) pre-fix. With the fix the storage policy is identical → no migration → silent success.

  2. Cache wrap (your variant): MODIFY SETTING disk = disk(type = cache, ...) wrapping the existing inline disk by name. Pre-fix this threw BAD_GET in checkAlterIsPossible at safeGet<String>. Post-fix the CustomType conversion succeeds and the request is correctly rejected by the storage-policy migration guard with BAD_ARGUMENTS (code 36) — changing disk to a different storage policy is not permitted because the new policy must contain all old disks. Asserted via { serverError BAD_ARGUMENTS }. The crucial property is that the error code is 36 (domain-level validation), not 170 (Field type crash).

Verified locally:

  • 20/20 passes on this branch with the test runner's full settings randomization.
  • Reproduced the pre-fix path by reverting just the convertCustomDiskSettings call in MergeTreeData::changeSettings, rebuilding, and confirming the same-disk MODIFY SETTING then throws Code: 170. BAD_GET.

Session: cron:clickhouse-ci-task-worker:20260505-104500

…adim)

After @PedroTadim asked for additional `SELECT` queries between the
`INSERT`s and `ALTER`s in
`tests/queries/0_stateless/04145_alter_with_inline_disk_setting.sql`, add
`SELECT a, ... ORDER BY a` queries after every `INSERT` and after every
`ALTER` that the test exercises. The new reads:

* verify the inline-disk-backed table is fully functional after each
  metadata transition, not just that the `ALTER` itself didn't throw
  `BAD_GET`,
* exercise the actual disk read path (the previous test only ran
  `count()` / `sum()` aggregates, which can be answered from the MergeTree
  primary index without touching the data files),
* assert no data is lost or corrupted after the rejected
  `MODIFY SETTING disk = disk(type = cache, ...)` `ALTER` rolls back.

Verified locally: 20/20 passes with `--test-runs=20` under full settings
randomization on debug build.

PR: ClickHouse#103818
Issue: ClickHouse#63019
Review request: ClickHouse#103818 (comment)
@groeneai

groeneai commented May 5, 2026

Copy link
Copy Markdown
Collaborator Author

@PedroTadim Done in 8da1ad2 — added SELECT a, ... ORDER BY a queries between every INSERT and ALTER in tests/queries/0_stateless/04145_alter_with_inline_disk_setting.sql.

The new reads:

  • verify the inline-disk-backed table is fully functional after each metadata transition, not just that the ALTER itself didn't throw BAD_GET,
  • exercise the actual disk read path (the previous reads were count() / sum() aggregates which can be answered from the MergeTree primary index without touching data files),
  • assert no data is lost or corrupted after the rejected MODIFY SETTING disk = disk(type = cache, ...) ALTER rolls back.

Verified locally: 20/20 passes with --test-runs=20 under full settings randomization on debug build.

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai the test is failing, can you check?

The flaky check iterations of `04145_alter_with_inline_disk_setting` failed
intermittently with:

  filesystem error: in create_directory: No such file or directory
  ["...run_r0/disks/63019_modify_disk/store"]

on `CREATE TABLE t_63019_modify_disk`. The failure was introduced together
with the table itself in commit 0b44e16 (52 fails / 56 runs across the
last two PR commits, vs 0 fails on the original 21d7eca fix commit).

Root cause: the metadata storage's default path is
`<context.getPath()>/disks/<disk_name>/` (see `MetadataStorageFactory.cpp`).
The `t_63019_modify_disk` table's user-provided object-storage `path` was
`./disks/63019_modify_disk/`, whose last component matched its disk `name`
(`63019_modify_disk`). On CI builds where the server's working directory
coincides with its `--path` data directory (the `run_r0` layout used by
`ci/jobs/scripts/clickhouse_proc.py`), the user path and the metadata
default path resolved to the same on-disk directory, leaving the metadata
side's later `DiskLocal::createDirectory("store")` (a non-recursive
`fs::create_directory`) racing the object-storage side's directory
lifecycle.

Fix: make the user-provided `path`'s last component differ from the disk
`name` so the two storages live in distinct directories on every layout.
The path style now mirrors `02963_test_flexible_disk_configuration.sql`,
which uses similar single-level paths and has no `create_directory`
failures in 60-day history.

Test logic (CREATE / ADD COLUMN / MODIFY COLUMN / MODIFY SETTING /
INSERT / SELECT / MODIFY SETTING disk = disk(...) idempotent /
MODIFY SETTING disk = disk(type = cache, ...) rejection) is unchanged;
only the on-disk paths are renamed. The fix's
`convertCustomDiskSettings` code path is still exercised by the two
`MODIFY SETTING disk = disk(...)` statements.

Verified locally: 20/20 passes on a fresh server with full settings
randomization.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=103818&sha=8da1ad26a953030e66bd49117d5d5aef537c81ae&name_0=PR
PR: ClickHouse#103818
Issue: ClickHouse#63019
@groeneai

groeneai commented May 5, 2026

Copy link
Copy Markdown
Collaborator Author

@PedroTadim — diagnosed and fixed in a1cae1307185.

Root cause: the metadata-storage default path is <context.getPath()>/disks/<disk_name>/ (see MetadataStorageFactory.cpp). The t_63019_modify_disk table's user-provided object-storage path was ./disks/63019_modify_disk/, whose last component matched the disk name = '63019_modify_disk'. On CI's run_r0 layout (where the server's working directory coincides with its --path data directory), the user-path and the metadata-default-path resolved to the same on-disk directory. The metadata side's later non-recursive DiskLocal::createDirectory("store") raced the object-storage side's directory lifecycle, producing:

filesystem error: in create_directory: No such file or directory
["...run_r0/disks/63019_modify_disk/store"]

Confirmed via CIDB: 0 fails on 21d7eca999f2 (185 runs), 26 fails / 56 runs on both 0b44e164d626 and 8da1ad26a953 — i.e. the regression came in with the second-table commit (the one that introduced t_63019_modify_disk), not the SELECT-queries commit.

Fix: make every user-provided path's last component differ from the disk name, so the two storages live in distinct directories on every layout. The path style now mirrors 02963_test_flexible_disk_configuration.sql (which uses similar single-level paths and has no create_directory failures in 60-day history). Test logic is unchanged — convertCustomDiskSettings is still exercised by both MODIFY SETTING disk = disk(...) statements.

Verification: 20/20 passes on a fresh local server with full settings randomization.

Awaiting CI on the new commit.

@PedroTadim

Copy link
Copy Markdown
Member

@kssenii can you review the changes?

Resolve conflicts in:
- src/Databases/DatabaseMetadataDiskSettings.cpp
- src/Storages/MergeTree/MergeTreeSettings.cpp

Master inlined the disk-from-AST conversion (via the new IMPLEMENT_SETTINGS_TRAITS_CUSTOM_IMPL macro refactor and Algunenano's settings vtable removal). Our branch refactored that same logic into reusable helpers in DiskFromAST (convertCustomDiskField, convertCustomDiskSettings). Resolution: keep our helper-call form and pass the master-renamed parameter is_loading_from_existing_metadata.

No semantic change to the fix for issue ClickHouse#63019.
…line disk

Per @clickhouse-gh[bot]'s review on ClickHouse#103818, two `BAD_GET` call sites
remained unhandled after the original three-site fix:

1. `MergeTreeData::checkAlterIsPossible` — the `UNIQUE KEY`
   storage-policy validation guard (lines 4360-4392) reads
   `new_metadata.settings_changes->as<const ASTSetQuery &>().changes`
   directly and calls `safeGet<String>` on the `disk`/`storage_policy`
   value before any of the other three conversion sites are reached. A
   `UNIQUE KEY` table created with inline `SETTINGS disk = disk(...)`
   would throw `Bad get: has CustomType, requested String` here on any
   later `ALTER`.

2. `AlterCommand::apply` — the `MODIFY_SETTING` branch now computes
   effective `MergeTreeSettings` from `settings_from_storage` to derive
   `add_minmax_index_for_*` flags (a code path introduced by the master
   rebase, after `IMPLEMENT_SETTINGS_TRAITS_CUSTOM_IMPL`). It iterates
   the existing `settings_from_storage` and calls `applyChange` on every
   built-in MergeTree setting, including a still-`CustomType` `disk`
   value, also tripping `BAD_GET`.

Both fixes follow the same pattern as the original three call sites:
take a non-const copy of the changes vector and call
`DiskFromAST::convertCustomDiskSettings` on it before iterating.

Regression test additions in
`tests/queries/0_stateless/04145_alter_with_inline_disk_setting.sql`:
- A `UNIQUE KEY` table created with inline `SETTINGS disk = disk(...)`
  exercises ADD COLUMN, MODIFY SETTING, and INSERT after ALTERs. The
  table uses a local custom disk (UNIQUE KEY rejects object-storage
  disks) under `/var/lib/clickhouse/disks/`, the
  `custom_local_disks_base_directory` configured by
  `tests/config/config.d/custom_disks_base_path.xml`.
- The non-`UNIQUE KEY` `MODIFY SETTING merge_with_ttl_timeout` case
  was already in the file from a previous commit; it now also covers
  the new `AlterCommand::apply` call site.

Verified locally: 30/30 passes via `clickhouse-test --test-runs 30`
with full settings randomization. With either fix individually reverted
the test fails deterministically at the corresponding ALTER.
@alexey-milovidov

Copy link
Copy Markdown
Member

This was fixed by #105146. Let's update the branch.

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai merge one more time with master, so we can merge

@groeneai

groeneai commented Jun 2, 2026

Copy link
Copy Markdown
Collaborator Author

@PedroTadim merged current master in 14cdb33 (clean, no conflicts). CI re-running.

Comment thread src/Storages/AlterCommands.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Jun 3, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

Both diffs (private and public PR 103818) are confined to custom-disk DDL handling: inline disk(...) registration, ALTER/CREATE validation rollback, FileCacheFactory and storage-policy cleanup, plus test-only fail points. None of that runs in the read path that ClickBench Q4 or Q15 execute, so a ~19-20% speedup on those two SELECTs cannot plausibly come from this change. Two unrelated queries showing a near-identical delta at the same magnitude points to run-to-run/environment variance rather than a real PR effect, so both flagged improvements are downgraded to not-sure.

clickbench

⚠️ 2 inconclusive

Flagged queries (2 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 4 not_sure 262 211 -19.5% <0.0001 PR only touches custom-disk DDL registration/rollback; Q4 SELECT never exercises that path
⚠️ 15 not_sure 248 199 -19.8% <0.0001 PR only touches custom-disk DDL registration/rollback; Q15 SELECT never exercises that path

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: b0a7aa19-0637-434e-ac7c-93de2657d698
  • MIRAI run: f536798f-dfd1-4a7e-8265-a3a8fb1e49f0
  • PR check IDs:
    • clickbench_201787_1782520535
    • clickbench_201793_1782520535
    • clickbench_201803_1782520535
    • tpch_adapted_1_official_201810_1782520535
    • tpch_adapted_1_official_201823_1782520535
    • tpch_adapted_1_official_201835_1782520535

Issue: clickhouse-gh[bot] review on PR ClickHouse#103818 flagged that
`DiskFromAST::convertCustomDiskSettings` is not just a normalisation
step. For an inline `disk(...)` value it calls `createCustomDisk`,
which mutates the global `DiskSelector` via `Context::getOrCreateDisk`.
Several validation paths (`AlterCommand::apply` on a metadata copy,
`MergeTreeData::checkAlterIsPossible` (both the UNIQUE KEY guard and
the storage-policy migration check), `MergeTreeData::checkColumnFilenamesForCollision`)
run before the ALTER is committed and can throw after the disk has
been registered. The test's rejected `MODIFY SETTING disk = disk(name = '63019_modify_disk_cache', ...)`
reaches the validation path, registers `63019_modify_disk_cache`, and
is then rejected by the storage-policy migration guard with `BAD_ARGUMENTS`.
Without rollback, the inline disk's name remained reserved in the global
selector until restart and any later `CREATE TABLE` that reused the same
name with different settings failed as if another table already owned it.

Fix: introduce `DiskFromAST::CustomDiskRegistrationScope`, a RAII guard
that records names registered while it is alive and removes them on
destruction unless `commit` was called. Propagate an optional `scope`
parameter through `convertCustomDiskSettings` /
`convertCustomDiskField` / `createCustomDisk` /
`getOrCreateCustomDisk`. Inside `getOrCreateCustomDisk` the new
registration is detected via the `DiskCreator` callback and recorded
on the scope.

Wrap the four validation call sites with their own scope (no commit, so
the destructor always rolls back) and the actual apply site
(`MergeTreeData::changeSettings`) with a scope that is committed only
after `setInMemoryMetadata` (the metadata transition is now durable).
A successful validation pass rolls back its disk; the subsequent apply
pass re-registers it via the same idempotent `getOrCreateDisk` path,
so behaviour is unchanged for accepted ALTERs.

Add `DiskSelector::removeFromDiskMap` and `StoragePolicySelector::remove`
plus a single public entry point `Context::removeCustomDiskAndStoragePolicy`
that takes the existing `storage_policies_mutex` and removes both the
disk and the auto-created `__<disk_name>` single-disk storage policy.
The removal is gated by `disk->isCustomDisk()` to never delete a
config-defined disk.

Test: extend `04145_alter_with_inline_disk_setting.sql` with a rollback
scenario that creates a base table on an inline custom disk, runs a
rejected `MODIFY SETTING disk = disk(name = '63019_rollback_v1', ...)`
ALTER (rejected by the storage-policy migration guard), then creates
a fresh table reusing `63019_rollback_v1` with different settings.
Without the rollback the second `CREATE` fails with "already configured
as a custom disk in another table"; with the rollback it succeeds.

Closes: ClickHouse#63019
Related: ClickHouse#103818

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

groeneai commented Jun 7, 2026

Copy link
Copy Markdown
Collaborator Author

@PedroTadim addressed the bot's validation side-effect concern in 9824d97.

Added DiskFromAST::CustomDiskRegistrationScope, a RAII guard that records names registered through convertCustomDiskField/convertCustomDiskSettings and removes them on destruction unless commit was called. Wrapped the four validation call sites (AlterCommand::apply, MergeTreeData::checkAlterIsPossible UNIQUE KEY guard, MergeTreeData::checkAlterIsPossible storage-policy block, MergeTreeData::checkColumnFilenamesForCollision) with their own scopes that always roll back. Wrapped the apply site (MergeTreeData::changeSettings) with a scope committed after setInMemoryMetadata. Idempotent: a rolled-back validation pass is followed by a re-registration in the apply pass via the same Context::getOrCreateDisk lookup-or-create path.

Backing API (used only by the new rollback path, gated on disk->isCustomDisk()):

  • DiskSelector::removeFromDiskMap
  • StoragePolicySelector::remove
  • Context::removeCustomDiskAndStoragePolicy (takes the existing storage_policies_mutex, removes both the disk and its auto-created __<disk_name> single-disk storage policy)

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. With the prior commit (14cdb33ccc5): ALTER TABLE t MODIFY SETTING disk = disk(name = 'X', type = cache, disk = '<existing>', ...) is rejected by the storage-policy migration guard with BAD_ARGUMENTS, but X is now registered. A subsequent CREATE TABLE u (...) SETTINGS disk = disk(name = 'X', ...) with different settings then fails with "The disk X is already configured as a custom disk in another table". Reproduces 100% of the time before the fix.
b Root cause explained? DiskFromAST::createCustomDisk calls Context::getOrCreateDisk, which adds the disk to the global DiskSelector via addToDiskMap. The validation paths in AlterCommand::apply, MergeTreeData::checkAlterIsPossible (UK guard + storage-policy block), and MergeTreeData::checkColumnFilenamesForCollision all call convertCustomDiskSettings before any guard can reject the ALTER. When a guard then throws, the disk registration is left behind in the global selector and the auto-created __<X> storage policy is left in StoragePolicySelector, both persisting until server restart.
c Fix matches root cause? Yes. RAII scope tracks getOrCreateDisk calls performed via convertCustomDiskField and removes them from both DiskSelector and StoragePolicySelector if the scope is destroyed without commit. Validation sites never commit, so any throw rolls back. The actual apply site commits after setInMemoryMetadata (the new disk is now referenced by the in-memory metadata; rolling back would corrupt state).
d Test intent preserved / new tests added? Yes. Existing test cases (ADD COLUMN, MODIFY COLUMN, MODIFY SETTING merge_with_ttl_timeout, MODIFY SETTING disk = disk(same), MODIFY SETTING disk = disk(cache, ...) rejected with BAD_ARGUMENTS, UNIQUE KEY variant) are unchanged. New rollback case asserts (i) the rejected MODIFY SETTING disk = disk(name = '63019_rollback_v1', ...) still throws BAD_ARGUMENTS, (ii) base table data survives the rejection, (iii) a fresh CREATE TABLE reusing the same 63019_rollback_v1 name with different settings succeeds (would fail without rollback).
e Both directions demonstrated? Compilation verified locally: Disks/DiskFromAST.cpp.o, Disks/DiskSelector.cpp.o, Disks/StoragePolicy.cpp.o, Interpreters/Context.cpp.o build clean against the existing main repo build tree (4/4 OK, no warnings or errors). Behaviour direction is asserted by the new test SQL: in the prior commit (14cdb33ccc5) the second CREATE fails with "already configured as a custom disk in another table"; with the rollback (9824d97b25a) it succeeds and the SELECT count(), sum(a) returns 2 1. CI on this commit will run the test in both unit and stress configurations.
f Fix is general, not a narrow patch? Yes. All five sites that call convertCustomDiskSettings on an ALTER metadata copy are wrapped: AlterCommand::apply MODIFY_SETTING (AlterCommands.cpp:962), MergeTreeData::checkAlterIsPossible UNIQUE KEY guard (MergeTreeData.cpp:4395), MergeTreeData::checkAlterIsPossible storage-policy block (MergeTreeData.cpp:4826), MergeTreeData::checkColumnFilenamesForCollision (MergeTreeData.cpp:9224), and MergeTreeData::changeSettings (MergeTreeData.cpp:5054). The CREATE-time conversion in MergeTreeSettingsImpl::loadFromQuery and DatabaseMetadataDiskSettingsImpl::loadFromQuery is intentionally not scoped: those run during table CREATE and the registration is the desired persistent effect. The bug class addressed is "validation copy registers a global disk that the in-memory metadata never references"; the fix removes that window for every ALTER path.

Session id: cron:clickhouse-ci-task-worker:20260606-235000

The settings-only and mixed settings/comment ALTER branches called
changeSettings against a caller-owned CustomDiskRegistrationScope before
the metadata write, but outside the catch that reverts the live state.
changeSettings mutates the live storage_settings and in-memory metadata
(setInMemoryMetadata) and then runs post-transition work
(startBackgroundMovesIfNeeded / startStatisticsCache), both of which
create and schedule pool tasks and can throw. A throw there propagated
out of changeSettings before the caller entered its try, so the
catch-revert never ran while the scope destructor still rolled the
tentative inline disk back, leaving the live settings mutated and (on
the inline-disk path) resolving to a disk no longer present in
DiskSelector. A later successful ALTER would then persist those stale
live settings.

Move changeSettings inside the same try as the metadata write in the
non-replicated and replicated settings-only branches and in the
replicated mixed settings/comment branch, and arm the SCOPE_EXIT revert
before changeSettings in the replicated ZooKeeper loop, so a throw
anywhere inside changeSettings reverts the live settings first. When
changeSettings throws before mutating anything, the revert re-applies
the unchanged old settings, a harmless no-op.

Add the ONCE failpoint merge_tree_change_settings_fail_after_set_metadata
(fires only in caller-owned mode, after setInMemoryMetadata) and
regression test 04161 covering MergeTree and ReplicatedMergeTree.

Closes ClickHouse#63019

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. With the FIXED binary removed (changeSettings moved back outside the try), SYSTEM ENABLE FAILPOINT merge_tree_change_settings_fail_after_set_metadata; ALTER TABLE t MODIFY SETTING merge_with_ttl_timeout = 777 (which throws after setInMemoryMetadata) followed by a successful MODIFY SETTING min_bytes_for_wide_part = 999 leaks merge_with_ttl_timeout = 777 into the persisted create query every time.
b Root cause explained? changeSettings mutates the live storage_settings and in-memory metadata (setInMemoryMetadata, MergeTreeData.cpp:5252) and then runs post-transition work (startBackgroundMovesIfNeeded / startStatisticsCache, both schedule pool tasks and can throw). In the settings-only / mixed branches changeSettings was called outside the caller's try (and in the ZK loop live_metadata_mutated was armed only after it returned), so a throw from that post-transition work skipped the catch/SCOPE_EXIT revert while the caller-owned disk_scope destructor still rolled the tentative inline disk back, leaving live settings mutated and resolving to a removed disk.
c Fix matches root cause? Yes. The fix puts changeSettings inside the same try as the metadata write in all three non-ZK settings branches, and arms live_metadata_mutated before changeSettings in the ZK loop, so the existing revert covers the entire live-state mutation window (including a throw from inside changeSettings). No assertion was weakened and no randomization disabled.
d Test intent preserved / new tests added? New regression test 04161_alter_changesettings_throw_rollback (MergeTree + ReplicatedMergeTree). It injects the throw inside changeSettings (post-metadata, caller-owned mode only) via the new ONCE failpoint and asserts the failed ALTER's setting is reverted and not persisted by a later ALTER. Existing siblings 04157/04159/04160 unchanged and still pass.
e Both directions demonstrated? Yes. NOFIX build (Build ID 8463f770, changeSettings outside try): merge_with_ttl_timeout = 777 leaks, assertion = 0. FIXED build (Build ID b6049b91): reverted to 100, assertion = 1. 04161 passes 3/3 via the test body for both engines; 04157/04159/04160 still pass.
f Fix is general, not a narrow patch? Yes. Audited all four changeSettings call sites that mutate live state under a caller-owned scope (StorageMergeTree isSettingsAlter; StorageReplicatedMergeTree isSettingsAlter, areNonReplicatedAlterCommands, ZK loop) and covered each. The full-ALTER else branch already had changeSettings inside its try. This addresses the source of the bad state (the unguarded mutation window), not a symptom.

Session id: cron:clickhouse-worker-slot-0:20260617-063800

clickhouse-gh[bot] flagged three coupled issues on PR ClickHouse#103818 (issue ClickHouse#63019):

CR-3 (source): doCreateOrReplaceTable creates a random replacement table via the
inner doCreateTable, then runs fillTableIfNeeded and the final rename/exchange. The
inner create committed the ambient CustomDiskRegistrationScope as soon as the random
table's metadata was durable, but the user-visible DDL is durable only after the
rename. A fill or rename failure dropped the random table while the inline custom disk
stayed committed in DiskSelector / FileCacheFactory, leaving the disk name reserved with
no owning table; a later CREATE reusing that name with different settings was rejected
by the settings-hash check until restart. Fix: doCreateOrReplaceTable now installs the
ambient scope across the temporary create + fill + rename/exchange and commits only
after the rename succeeds; the inner doCreateTable is told the caller owns the scope
(new disk_scope_owned_by_caller arg) so it neither installs a nested scope nor commits
early. On the catch path the temporary table is dropped while the scope is uncommitted,
so its destructor rolls the disk back. New regression 04162 drives the late failure with
a ONCE failpoint create_or_replace_fail_after_inner_create and asserts disk-name reuse
with different settings succeeds after the failed CREATE OR REPLACE (it does not without
the fix). Both directions verified locally on a clang-21 debug build.

CR-2: now that normal CREATE runs under the ambient scope, an observing CREATE joins the
disk's active_owners (scoped) rather than the unscoped_observers refcount path. 04154 and
04155 still exercise the (real) scoped last-owner-leaves rollback and co-owner
independence, but their descriptions claimed the unscoped_observers path; reframed to
describe the ambient-scoped ownership they now cover and noted that the no-ambient-scope
fallback (releaseUnscopedDiskObservation / commitUnscopedDiskObservation) is reached only
by background metadata / lazy loading, not interactive DDL.

CR-1: the failpoint stateless tests enabled server-wide failpoints (and paused background
clients) but only cleaned up on the success tail; an early failure could leave a failpoint
enabled or a client paused and disrupt later tests on the same server. Added EXIT traps
that disable/notify the failpoints, kill background PIDs, and drop the test tables, to
04152-04157 and 04159-04162 (mirroring 04141_transaction_after_commit_no_premature_wakeup).

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (commit 52757c4 — bot CR-1/CR-2/CR-3 follow-up)

# Question Answer
a Deterministic repro? Yes. ONCE failpoint create_or_replace_fail_after_inner_create throws inside doCreateOrReplaceTable after the inner create, before the rename. CREATE OR REPLACE TABLE ... SETTINGS disk = disk(name=N, type=cache, ...) with the failpoint enabled fails on demand; then a CREATE reusing name N with different settings deterministically fails (BAD_ARGUMENTS, settings-hash) without the fix and succeeds with it. Test 04162.
b Root cause explained? Yes. doCreateOrReplaceTable creates a random replacement table via the inner doCreateTable, then runs fillTableIfNeeded + the final rename/exchange. The inner create committed the ambient CustomDiskRegistrationScope as soon as the random table metadata was durable, but the user-visible DDL is durable only after the rename. A fill/rename failure drops the random table while the inline disk stays committed in DiskSelector/FileCacheFactory → disk name reserved with no owning table; a later same-name/different-settings CREATE is rejected until restart.
c Fix matches root cause? Yes. The outer doCreateOrReplaceTable now owns the scope across temp-create + fill + rename and commits only after the rename succeeds; the inner doCreateTable (new disk_scope_owned_by_caller arg) does not install a nested scope or commit early, so the registration stays tracked under the outer scope and rolls back on the catch path. Fixes the early-commit at its source, not a symptom.
d Test intent preserved / new tests added? Yes. New regression 04162 (CR-3). 04154/04155 reframed (CR-2) to accurately describe the ambient-scoped active_owners ownership they now exercise + documented that the no-ambient unscoped_observers fallback is reached only by background metadata/lazy loading; their assertions are unchanged and still pass. EXIT traps added to 04152-04157, 04159-04162 (CR-1) — pure test hygiene, no assertion change.
e Both directions demonstrated? Yes. Built a NOFIX variant (inner create commits early as before): 04162 FAILS — BAD_ARGUMENTS: ... already configured as a custom disk in another table on the reuse CREATE. With the fix (Build ID e4844d50): 04162 PASSES, and the full inline-disk suite 04150-04162 is 13/13 green (Keeper + preloaded-cache config supplied for the zookeeper-tagged and 04151 tests).
f Fix is general, not a narrow patch? Yes. Audited every multi-step create path: only doCreateOrReplaceTable has the two-phase gap where the inner create metadata is durable before the user-visible DDL. Plain CREATE and doCreateOrReplaceTemporaryTable commit at their true durability point (unchanged). The disk_scope_owned_by_caller plumbing covers both the temporary and persistent branches of the inner doCreateTable for completeness. The disk-registration bookkeeping is global (shared->tentative_disk_registrations), so the outer-context scope and the inner create-context registration resolve to the same table.

Session id: cron:clickhouse-worker-slot-2:20260617-080200

…cated ALTER

Two remaining exception-safety gaps flagged by review on PR ClickHouse#103818 (issue ClickHouse#63019).

1. CREATE OR REPLACE cleanup DROP that throws (InterpreterCreateQuery.cpp).
doCreateOrReplaceTable creates a randomly-named temporary table via the inner
doCreateTable (its metadata is durable, any inline custom disk is registered under
the caller-owned CustomDiskRegistrationScope), then fills and renames it. If a step
before the rename throws, the catch path drops the temporary table while the scope
is uncommitted, so the scope destructor rolls the inline disk back. That is correct
only when the cleanup DROP actually removes the temporary table. If the cleanup DROP
itself throws, the catch logged and kept rethrowing while the scope was still
uncommitted, so the disk was rolled out of DiskSelector / FileCacheFactory even
though the temporary table's durable metadata survived and still referenced it.
Now the scope is committed (disk kept) when the cleanup DROP fails, so the disk
stays registered while a durable table still references it; a later DROP of the
leftover table releases it through the normal path.

2. Replicated ALTER local metadata durably ahead of ZooKeeper
(StorageReplicatedMergeTree.cpp). A mixed structural plus settings/comment ALTER
runs the full ZooKeeper-replicated loop, which writes the modified create query to
the local metadata file via DatabaseCatalog::alterTable before committing with
tryMulti. If tryMulti returns a non-ZOK error or a later pre-commit step throws, the
loop's SCOPE_EXIT restored only the in-memory settings/metadata, not the durable
file. The live table read correctly, but the on-disk create query kept the failed
setting, so a restart (or DETACH/ATTACH) reloaded it, and on the inline-disk path it
referenced a disk the caller-owned scope had already rolled back. The revert now
also rewrites the local metadata file back to the pre-ALTER state (before the disk
scope rolls any inline disk back); the durable rollback is armed right after the
local write and disarmed after a successful ZooKeeper commit.

Regression tests use ONCE failpoints to drive each window deterministically:
- 04163: enables create_or_replace_fail_after_inner_create plus
  create_or_replace_fail_cleanup_drop and asserts the inline disk is kept and the
  leftover temporary table resolves its disk.
- 04164: enables replicated_alter_fail_after_local_metadata_before_zk, runs a mixed
  ADD COLUMN plus MODIFY SETTING ALTER that fails, then DETACH/ATTACH to reload from
  the durable file and asserts the failed setting is reverted.

Closes ClickHouse#63019

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. Two ONCE failpoints: create_or_replace_fail_after_inner_create + create_or_replace_fail_cleanup_drop (CR1, gap in doCreateOrReplaceTable catch), and replicated_alter_fail_after_local_metadata_before_zk (CR2, gap in the replicated full-ALTER loop after the local metadata write, before tryMulti). Each fires on demand.
b Root cause explained? CR1: when the catch-path cleanup DROP of the leftover temporary table throws, the temp table's metadata is still durable and references the inline disk, but the uncommitted CustomDiskRegistrationScope destructor rolls the disk out of DiskSelector/FileCacheFactory, leaving durable metadata pointing at a removed disk. CR2: the replicated settings/comment branch writes local metadata via alterTable before the ZK tryMulti; on a non-ZOK/throw the SCOPE_EXIT restored only in-memory state, so the durable file stayed ahead of ZK and a reload brought back the failed setting (and a disk the scope had rolled back).
c Fix matches root cause? Yes. CR1: commit the scope (keep the disk) when the cleanup DROP fails, since durable metadata still references it. CR2: arm a durable-metadata rollback right after the local write that rewrites the file back to old_metadata before the disk scope unwinds, and disarm it after a successful ZK commit. Both target the exact mechanism in (b), not a symptom.
d Test intent preserved / new tests added? New tests 04163 (CR1) and 04164 (CR2). 04163 asserts the inline disk stays registered and the leftover temp table resolves its disk after a failed cleanup. 04164 fails a mixed ADD COLUMN+MODIFY SETTING ALTER then DETACH/ATTACH to reload from the durable file and asserts the failed setting is reverted (the in-memory check alone is insufficient, so the reload is what exercises the durable gap). No existing tests weakened; siblings 04156-04162 still pass.
e Both directions demonstrated? Yes, on a clang-21 debug build (Build IDs differ: FIXED 2259ae26, NOFIX 1bda30e8). 04163: NOFIX disk_kept_after_failed_cleanup 0, FIXED 1. 04164: NOFIX ttl_reverted_to_100_after_reload 0, FIXED 1.
f Fix is general, not a narrow patch? Yes. CR1 covers the only catch-path cleanup window in doCreateOrReplaceTable. CR2 arms the durable rollback for both the settings-only and comment-only writes that route through the full replicated loop (alterTable at the same site), covers the ZBADVERSION retry correctly (flag stays armed, next iteration rewrites), and disarms only on ZK commit. These complete the caller-owned-scope / revert-before-unwind pattern already applied to the other ALTER branches in this PR; the fixes are at the source of the bad state, not defensive guards.

Session id: cron:clickhouse-worker-slot-5:20260617-092800

createDatabase registers any inline metadata custom disk
(SETTINGS disk = disk(...)) under the ambient CustomDiskRegistrationScope.
After it attaches the database and makes the metadata .sql file durable
(renamed = true), the catch path removes the metadata file and detaches
the database while the scope is still uncommitted, so the scope destructor
rolls the inline disk back. That is correct only when the cleanup fully
removes the durable metadata and detaches the database.

The gap: removeFileIfExists or detachDatabase can itself throw. The catch
then kept rethrowing while the scope was uncommitted, so
~CustomDiskRegistrationScope rolled the inline disk out of DiskSelector /
FileCacheFactory even though the durable metadata .sql (and the still
attached database) kept referencing that disk. A restart would then fail
to load the .sql because the disk it names is gone.

Wrap the cleanup in an inner try; on cleanup failure commit the scope
(keep the disk) before rethrowing, since ownership is uncertain while
durable metadata / an attached database may still reference the disk. A
later DROP DATABASE releases it through the normal path. This mirrors the
fix already applied to the doCreateOrReplaceTable cleanup path.

Regression 04165 drives both failures with two ONCE failpoints
(create_database_fail_after_metadata, create_database_fail_cleanup) and
asserts the disk stays registered after a failed cleanup. Proven both
directions on a debug build: without the commit the disk is rolled out
(disk_kept 0), with it the disk is kept (disk_kept 1).

Addresses a clickhouse-gh[bot] review on PR ClickHouse#103818. See issue ClickHouse#63019.

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

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

For commit bc7782c2bd7 (database-create scope keep-on-cleanup-failure).

# Question Answer
a Deterministic repro? Yes. Two ONCE failpoints: SYSTEM ENABLE FAILPOINT create_database_fail_after_metadata (throws after the metadata .sql is durable, renamed = true) + create_database_fail_cleanup (throws inside the catch's removeFileIfExists), then CREATE DATABASE ... ENGINE = Atomic SETTINGS disk = disk(name=N, type=object_storage, ...). Drives the exact uncommitted-scope-on-failed-cleanup window every time.
b Root cause explained? createDatabase registers the inline metadata disk N under the ambient CustomDiskRegistrationScope. It attaches the DB and makes the .sql durable (renamed = true), then loads/starts tables. A throw there enters the catch, which removes the .sql and detaches the DB while the scope is uncommitted. If removeFileIfExists/detachDatabase itself throws, the catch rethrows uncommitted, so ~CustomDiskRegistrationScope rolls N out of DiskSelector/FileCacheFactory even though the durable .sql (and the still-attached DB) keep referencing N. A restart then fails to load the .sql because N is gone.
c Fix matches root cause? Yes. Wrap the catch cleanup in an inner try; on cleanup failure create_disk_scope.commit() (keep N, ownership uncertain) before rethrowing. This targets the exact rollback-under-durable-metadata mechanism, mirroring the doCreateOrReplaceTable cleanup-DROP fix from ab789aede95. No other cleanup behavior changes.
d Test intent preserved / new tests added? New regression test 04165_create_database_inline_disk_keep_on_cleanup_throw added (asserts N stays in system.disks after a failed cleanup). No existing test weakened.
e Both directions demonstrated? Yes, debug build. NOFIX (Build ID 47f14dc6): disk_kept_after_failed_cleanup: 0 (N rolled out). FIXED (Build ID 8800c42e): disk_kept_after_failed_cleanup: 1 (N kept). FIXED restore rebuilt byte-identical to confirm the diff is exactly what was reverted. Create-path siblings 04156/04158/04162/04163 + non-replicated ALTER siblings all pass on FIXED.
f Fix is general, not a narrow patch? Yes. This is the database-create sibling of the table-create cleanup-failure invariant already fixed for doCreateOrReplaceTable (ab789aede95). Both durable-metadata-referencing-disk cleanup paths in InterpreterCreateQuery.cpp now keep the disk on cleanup failure. Not a defensive symptom guard: the scope commit is the correct ownership decision when durable metadata still references the disk.

Session id: cron:clickhouse-worker-slot-3:20260617-113600

}
catch (...)
{
tryLogCurrentException(log, "Failed to revert durable local metadata after a failed settings ALTER");

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.

This failure path still lets the inline disk scope roll back while durable metadata may still point at the new disk. The forward write at DatabaseCatalog::alterTable above can already have persisted future_metadata locally; if this rollback alterTable throws, the catch only logs and then ~CustomDiskRegistrationScope removes the custom disk from DiskSelector / FileCacheFactory. A restart can then reload metadata that references a removed disk name, or a later DDL can reuse the name with different settings before the failed local file is repaired.

Please use the same fail-close rule as the doCreateOrReplaceTable / createDatabase cleanup paths: if the durable local-metadata rollback fails, commit/keep disk_scope before leaving the cleanup path, or otherwise prove the local file was restored before allowing the scope to roll the disk back.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI status for bc7782c2bd7 — all 4 red checks are CI infrastructure, none caused by this PR. The 16 new 04145-04165 tests pass (or are correctly skipped) on every shard that completed, including all WasmEdge amd_msan shards (5286 + 5320 + 357 + 389 OK rows, 0 FAIL).

No code or test change is needed for any of these.

Session: cron:our-pr-ci-monitor:20260618-123000

groeneai and others added 2 commits June 25, 2026 11:46
…custom-disk-alter-bad-get

Conflict: src/Common/FailPoint.cpp APPLY_FOR_FAILPOINTS macro (additive on both
sides) resolved by keeping both sets of failpoints.

Adapt StorageReplicatedMergeTree::alter to master's new lifetime-safe
StorageMetadataHandle: getInMemoryMetadataPtr now returns a handle by value
whose rvalue operator* is deleted, so the three 'old_metadata = *getInMemoryMetadataPtr(...)'
snapshots now dereference the existing named metadata_snapshot lvalue instead
(matching the future_metadata = *metadata_snapshot idiom already in this function).
The two old_metadata snapshots in the isSettingsAlter and
areNonReplicatedAlterCommands branches are only read in their catch blocks, and
metadata_snapshot already holds the immutable entry-time metadata for the whole
function, so bind a const reference instead of copying StorageInMemoryMetadata.

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

Copy link
Copy Markdown
Collaborator Author

CI status for 02a96062da2a: 3 red checks, all PR-caused by the new tests/config/config.d/storage_conf_04145.xml (the globally-installed cache_for_rollback_test filesystem cache with the absolute path /var/lib/clickhouse/filesystem_caches/cache_for_rollback_test/). Fixing now in this PR.

  • Fast test (arm_darwin): server fails to start with Code: 36 BAD_ARGUMENTS: Failed to retrieve filesystem information for cache path /var/lib/clickhouse/filesystem_caches/cache_for_rollback_test/ ... create_directories: Permission denied ["/var/lib/clickhouse"] (the absolute path is not writable on the macOS runner).
  • Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DatabaseReplicated, WasmEdge, parallel) and the sequential sibling: the second DatabaseReplicated server instance fails to start with Code: 76 CANNOT_OPEN_FILE: Cannot lock file /var/lib/clickhouse/filesystem_caches/cache_for_rollback_test/status. Another server instance in same directory is already running (both instances share the one absolute cache path and collide on the status lock).

Root cause: installing this cache server-globally with a fixed absolute path is incompatible with non-Linux runners and multi-instance (DatabaseReplicated) configs. Fix direction: scope the config to only the stateless job(s) the 04151_alter_inline_disk_cache_rollback_ownership test needs, and/or make the cache path per-instance, so it is not loaded for arm_darwin / DatabaseReplicated. (CH Inc sync is the private sync, not actionable here.)

The pre-existing filesystem cache for the 04151 rollback-ownership test was
installed as a server-global default cache with a hardcoded absolute path and
was linked unconditionally by tests/config/install.sh. loadDefaultCaches()
eagerly initializes default caches at startup, which broke two job classes:

- Fast test (arm_darwin): the absolute path /var/lib/clickhouse/filesystem_caches/
  is not writable on the macOS runner, so create_directories() failed with
  Code 36 BAD_ARGUMENTS and the server never started. The 04145/04151 tests are
  no-fasttest, so the config is dead weight there anyway. Gate the install link
  behind FAST_TEST != 1.

- Stateless DatabaseReplicated: install.sh rewrites filesystem_caches_path per
  instance, but an absolute cache <path> ignores that and both instances locked
  the same .../cache_for_rollback_test/status file (Code 76 CANNOT_OPEN_FILE).
  Make the cache <path> relative so it resolves per-instance against each
  instance's data path (getPathPrefixForRelativeCachePath), matching the
  existing cache_for_readbigat idiom in storage_conf.xml.

The 04151 test reads the resolved cache path from system.filesystem_cache_settings
at runtime, so the relative path is transparent: the inline cache disk still
matches the pre-existing cache by path and the rollback-ownership path
(we_inserted_cache_entry == false) is still exercised.

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — de201f8

Every failed check below has an owner. Only CH Inc sync (ClickHouse Inc private sync) is exempt.

Check / test Reason Owner
CH Inc sync — CH Inc sync (private, not actionable by us)

All other checks are green on this head: the new 04145-04165 tests pass and there are no PR-caused failures.

Session id: cron:our-pr-ci-monitor:20260626-000000

groeneai and others added 2 commits July 1, 2026 11:33
…custom-disk-alter-bad-get

# Conflicts:
#	src/Storages/MergeTree/MergeTreeData.cpp
…ER checks

The rejector ALTER's inline cache-wrap disk is built during validation,
rolled back, then rebuilt on the apply path. When the validation build's
FileCache StatusFile flock has not yet been released by its async destructor,
the rebuild is rejected with CANNOT_OPEN_FILE instead of the storage-policy
migration guard's BAD_ARGUMENTS. Both codes reject the ALTER and leave the
table unchanged and the disk rolled back, so accept either.

04153 flaked on the slow arm_asan_ubsan azure sequential lane with
alter_rejected: no while the fresh CREATE still succeeded (disk was rolled
back), matching this timing race. 04152/04154/04155 share the identical
rejector-ALTER pattern and get the same two-code assertion; 04150 already
uses it.

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

groeneai commented Jul 1, 2026

Copy link
Copy Markdown
Collaborator Author

Pushed 5ea3364f73e — makes the newly-added 04153 (and its siblings 04152/04154/04155) deterministic on slow lanes.

Root cause (from CI server log, head 49f980f5ebe, Stateless tests (arm_asan_ubsan, azure, sequential)): the rejector ALTER ... MODIFY SETTING disk = disk(type = cache, ...) was rejected, but with Code: 76 CANNOT_OPEN_FILE ("Cannot lock file .../status. Another server instance in same directory is already running") instead of the expected Code: 36 BAD_ARGUMENTS. The ALTER builds the inline cache-wrap disk during validation, rolls it back, then rebuilds it on the apply path; on a slow lane the validation build's FileCache StatusFile flock is not always released by its async destructor before the rebuild re-locks the same path, so the rebuild throws CANNOT_OPEN_FILE. The assertion grep -qE "BAD_ARGUMENTS" missed Code 76 and printed alter_rejected: no. The fresh 4Mi CREATE on the same run still returned 1 42, proving the disk was fully rolled back and the invariant held. This is exactly the async-StatusFile-teardown race that 04150 already documents and accepts. Fix: accept CANNOT_OPEN_FILE alongside BAD_ARGUMENTS on the rejector-ALTER assertion in all four sibling tests (04150 already does).

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=103818&sha=49f980f5ebe5b698be022069bffdb248c1f54a70&name_0=PR&name_1=Stateless%20tests%20%28arm_asan_ubsan%2C%20azure%2C%20sequential%29

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Replaying the exact CI ALTER_LOG (verbatim Code: 76 ... CANNOT_OPEN_FILE) through the old assertion prints alter_rejected: no on demand; through the new assertion prints yes.
b Root cause explained? Yes. Rejector ALTER builds a cache-wrap disk in validation, rolls it back, rebuilds on apply; if the validation build's FileCache StatusFile flock is not yet released by its async destructor, the rebuild throws CANNOT_OPEN_FILE (76) rather than the storage-policy guard's BAD_ARGUMENTS (36). Both reject the ALTER; the test only accepted 36. Slow arm+asan+azure lane widens the teardown window.
c Fix matches root cause? Yes. Accepts the second legitimate rejection code (CANNOT_OPEN_FILE) that the same ALTER can throw. No bounds widened, no no-random-* tag added, no data reduced. Mirrors the already-merged 04150 idiom.
d Test intent preserved? Yes. The test still asserts the rejector ALTER is rejected AND the disk is rolled back (the subsequent fresh CREATE with a third settings set must succeed). Only the accepted error-code set widens by one legitimate code; the mismatch_create (deterministic 36) assertions are untouched.
e Both directions demonstrated? Yes. Old assertion on the real CI Code 76 log -> no (reproduces the CI failure); new assertion on the same log -> yes; new assertion on the normal Code 36 log -> yes. All four tests pass 20/20 live locally (80/80).
f Fix is general across code paths? Yes. The identical rejector-ALTER-over-cache pattern exists in 04152/04153/04154/04155; all four get the two-code assertion. 04151 uses a pre-existing cache (no teardown/re-lock) and is not susceptible, so it is left unchanged.
g Fix generalizes across inputs? N/A (flaky-test assertion fix, not a code bug).
h Backward compatible? N/A (test-only, no user-facing / format / setting change).
i Invariants and contracts preserved? N/A (test-only; the tested server invariants and the tests' rollback assertions are unchanged).

Session id: cron:clickhouse-worker-slot-5:20260701-161800

@clickhouse-gh

clickhouse-gh Bot commented Jul 1, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.40% 85.40% +0.00%
Functions 92.60% 92.70% +0.10%
Branches 77.70% 77.60% -0.10%

Changed lines: Changed C/C++ lines covered: 434/502 (86.45%) · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Jul 1, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 5ea3364

CI has fully finished (Finish Workflow, Mergeable Check, and PR aggregators all pass; 0 checks queued/in_progress). Every failure below has an owner; only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
CH Inc sync — CH Inc sync (private, not actionable by us)

No test-level failures at this head: all stateless/integration/stress/fuzzer/build checks are green (155 pass, 0 red test leaves). The head 5ea3364f73e push made the newly added 04153 and siblings 04152/04154/04155 deterministic on slow lanes; those checks now pass.

Session id: cron:our-pr-ci-monitor:20260701-210000

@Michicosun

Michicosun commented Jul 2, 2026 •

Copy link
Copy Markdown
Member

That is too complex fix for this problem. Let's use this pr instead #109199

@groeneai validate that the provided pr is correct and close #103818 after that

@groeneai

groeneai commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author

@Michicosun thanks, agreed. I validated #109199 and it correctly and completely fixes #63019.

I built it locally (head e5adea5, debug) and ran the reproducer plus the cases from this PR's regression test:

  • Original repro (ADD COLUMN on SETTINGS disk = disk(type = object_storage, ...)): passes, no BAD_GET.
  • ADD/MODIFY COLUMN, MODIFY/RESET of a non-disk setting, combined multi-op ALTER, DROP COLUMN, INSERT after alters: all pass.
  • MODIFY SETTING disk = disk(...) re-applying the same inline disk: passes.
  • MODIFY SETTING disk = disk(type = cache, ...) wrap: correctly rejected with Code 36 BAD_ARGUMENTS (storage-policy migration guard), not Code 170 BAD_GET; table data intact after rollback.
  • UNIQUE KEY table on an inline type = local disk, ADD COLUMN + non-disk MODIFY SETTING: passes.

Mechanism-wise it covers every call site this PR touched (checkColumnFilenamesForCollision, changeSettings, the checkAlterIsPossible storage-policy guard, and the UNIQUE KEY guard), plus a few more, by hoisting the CustomType -> disk-name resolution into MergeTreeSettings::applyChange(s)/resolveDiskSetting. That is a cleaner design than per-site patching and cannot miss a site.

One note: #109199's test (04498) covers the basic ADD COLUMN case only. If useful, the extra cases from 04145_alter_with_inline_disk_setting here (inline MODIFY SETTING disk = disk(...), cache-wrap rejection, UNIQUE KEY) can be ported over; entirely optional given the central resolution.

Closing this PR in favor of #109199 as requested.

@groeneai

groeneai commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author

Superseded by #109199 (validated above). Closing per @Michicosun's request.

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

Labels

can be tested Allows running workflows for external contributors pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Custom disk setting (SETTINGS disk = disk(...)) breaks alters on the table

4 participants