Skip to content

Finish the conversion to ReplicatedMergeTree under lazy_load_tables - #118135

Merged
alexey-milovidov merged 14 commits into
masterfrom
lazy-load-convert-to-replicated-117413
Oct 14, 2026
Merged

alexey-milovidov merged 14 commits into
masterfrom
lazy-load-convert-to-replicated-117413

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 4, 2026 •

Copy link
Copy Markdown
Member

The second phase of the convert_to_replicated migration (DatabaseOrdinary::restoreMetadataAfterConvertingToReplicated) casts the catalog's storage object to StorageReplicatedMergeTree. With lazy_load_tables that object is a stand-in whose startup does nothing, so the cast returned null and the whole restore was skipped before any log line:

  • the .sql already said ReplicatedMergeTree (phase one wrote it durably), so the table came up replicated with no metadata in ZooKeeper - read-only forever;
  • the convert_to_replicated flag was never removed, and every later restart deferred the table again, so the conversion could not self-heal;
  • the documented recovery SYSTEM RESTORE REPLICA inspected the same stand-in and answered "Table ... is not replicated".

The flag file is now looked up before the storage is touched, and only a table that is really being converted is materialized, so a deferred table that is not being converted is still not loaded. SYSTEM RESTORE REPLICA resolves the stand-in as well.

The flag lives on the first disk of the table's storage policy, and a stand-in has no storage policy of its own (StorageTableProxy::getStoragePolicy returns nullptr by design). Both phases therefore resolve the policy identically, from the CREATE TABLE query, via the shared getStoragePolicyFromCreateQuery (which, like MergeTreeData::getStoragePolicy, gives a disk setting precedence over storage_policy) - so a table on a non-default storage_policy or disk is converted too, and no table has to be loaded just to be asked for its disks.

The new integration tests live next to the other convert_to_replicated tests: lazy tables on the default policy, on a jbod policy and on SETTINGS disk = 'jbod1', plus SYSTEM RESTORE REPLICA on a lazy table whose ZooKeeper metadata was removed.

Closes: #117413

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 to CHANGELOG.md):

Fixed the automatic MergeTree to ReplicatedMergeTree conversion silently not finishing for a table in a database with lazy_load_tables, which left the table read-only with no metadata in ZooKeeper and the conversion flag in place.

🤖 Generated with Claude Code


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

Version info

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

The second phase of the `convert_to_replicated` migration casts the catalog's storage object
to `StorageReplicatedMergeTree`. With `lazy_load_tables` that object is a stand-in whose
`startup` does nothing, so the cast returned null and the whole restore was skipped before
any log line: the table came up as replicated with no metadata in ZooKeeper - read-only
forever - and the flag was never removed, so no further restart could finish the conversion
either. The documented recovery `SYSTEM RESTORE REPLICA` inspected the same stand-in and
answered "Table is not replicated".

The flag file is now looked up before the storage is touched (from the database's own disk
when the table has no storage policy yet, i.e. is a stand-in), and only a table that is
really being converted is materialized. `SYSTEM RESTORE REPLICA` resolves the stand-in too.

Closes: #117413
@clickhouse-gh clickhouse-gh Bot added the comp-database-engines Database engine implementations (e.g., Atomic/Replicated) and database-level behavior. label Sep 4, 2026
@zlareb1

zlareb1 commented Sep 4, 2026

Copy link
Copy Markdown
Member

TL;DR: the reordered second phase looks for the conversion flag only on the database disk when the table is a stand-in, but the first phase resolves the table's storage_policy from the CREATE query and honors a flag on that policy's first disk. A lazy table with a non-default storage_policy therefore still hits exactly the symptom this PR fixes: the .sql is rewritten to Replicated, the restore is skipped, the table comes up read-only, and the flag is never removed.

1. The two phases resolve the flag disk differently.

Phase one, convertMergeTreeToReplicatedIfNeeded (src/Databases/DatabaseOrdinary.cpp:231-243), takes the policy from the server default overridden by the CREATE query's storage_policy setting and checks the flag on policy->getDisks()[0] — so a flag placed in the table's data directory on a custom-policy disk is honored and the .sql is durably rewritten.

Phase two after this PR: for a stand-in, getStoragePolicy returns null by design, so checking_disk falls back to getDisk() — the database disk — and only that disk is checked. When the policy's first disk differs from the database disk (custom storage_policy, or a dedicated database_disk), the flag is missed and the function returns before materializing anything.

2. Resulting state.

.sql says ReplicatedMergeTree, no metadata in ZooKeeper, flag still present on the policy disk. First access materializes a read-only table; INSERT fails with TABLE_IS_READ_ONLY. On the next restart phase one skips the table (engine already Replicated*) and phase two misses the flag again — no restart heals it. SYSTEM RESTORE REPLICA now works thanks to this PR's other hunk, but the flag then lingers forever and the conversion still "silently does not finish" without operator action, which is what the changelog entry claims to fix.

Repro shape: CREATE DATABASE db ENGINE = Atomic SETTINGS lazy_load_tables = 1; CREATE TABLE db.mt (...) ENGINE = MergeTree ORDER BY x SETTINGS storage_policy = 'jbod'; insert; touch convert_to_replicated in the table's data directory on the jbod disk (where phase one looks, and where the docs tell users to put it); restart.

3. A fix that keeps the lazy-loading guarantee.

The comment in the diff is right that materializing every deferred table just to ask for its disks would defeat lazy_load_tables — but materialization isn't needed: phase one already resolves the policy without a storage object, from the stored CREATE query. Phase two can do the same via tryGetCreateTableQuery (as getConvertToReplicatedFlagPath already parses per-table state) and check the same disk phase one checked.

Unrelated to this PR but adjacent: removeFileIfExists still runs before restoreMetadataInZooKeeper, so a kill between the two leaves a replicated table with no ZooKeeper metadata and no flag — pre-existing, and this PR at least makes the documented SYSTEM RESTORE REPLICA recovery work for lazy tables.

alexey-milovidov and others added 2 commits September 10, 2026 18:33
…cond phase

The `convert_to_replicated` flag is looked up on the first disk of the table's
storage policy. The first phase resolves that policy from the `CREATE TABLE`
query, but the second phase asked the storage object - and a lazily loaded
stand-in returns no policy at all, so a table with a non-default
`storage_policy` fell back to the database disk, the flag was missed, the table
stayed read-only and the flag was never removed.

Both phases now share `getStoragePolicyFromCreateQuery`, so they look at the
same disk. Added an integration test for a lazy table on a `jbod` policy.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…o-replicated-117413

# Conflicts:
#	src/Databases/DatabaseOrdinary.cpp
#	src/Databases/DatabaseOrdinary.h
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Good catch, and adopted: the second phase now resolves the storage policy the same way the first phase does, from the CREATE TABLE query, so both look at the same disk.

getStoragePolicyFromCreateQuery was factored out of convertMergeTreeToReplicatedIfNeeded and is used by restoreMetadataAfterConvertingToReplicated whenever the storage object has no policy of its own - which is exactly the lazy stand-in case, since StorageTableProxy::getStoragePolicy returns nullptr by design. No table is materialized to answer the question, so lazy_load_tables is still honored.

Added an integration test for the reported shape: a lazy_load_tables database with a table on a jbod policy, the flag placed in the table's data directory on that policy's disk (which is where system.tables.data_paths and the docs point), restart, then assert the flag is gone, the engine is ReplicatedMergeTree, and the table is writable.

On the adjacent note: agreed that removeFileIfExists running before restoreMetadataInZooKeeper leaves a window where a kill loses both the flag and the ZooKeeper metadata. That is pre-existing and orthogonal to this fix, so I left the ordering alone here.

@clickhouse-gh

clickhouse-gh Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ffd1922]

Summary: ✅


AI Review

Summary

This PR fixes the lazy-proxy blind spot behind #117413 by resolving the convert_to_replicated flag disk from the stored CREATE TABLE and by loading the stand-in only when the flag is actually present; the added regressions cover the default path, non-default storage_policy, named disk, and SYSTEM RESTORE REPLICA. I still see one unresolved gap: lazy_load_tables tables that use inline SETTINGS disk = disk(...) are still skipped entirely, so the "finish under lazy_load_tables" claim is broader than the current behavior.

PR Metadata
  • Changelog category is correct: this is a user-visible bug fix.
  • Changelog entry is required and mostly user-readable, but it is broader than the implementation because lazy inline disk(...) tables are still not handled. Suggested replacement:
    Fixed automatic \MergeTree` to `ReplicatedMergeTree` conversion and `SYSTEM RESTORE REPLICA` for tables in databases with `lazy_load_tables`, including tables on non-default `storage_policy` or named `disk` settings.`
Findings
  • ⚠️ Majors
    • [src/Databases/DatabaseOrdinary.cpp:258-262, src/Databases/DatabaseOrdinary.cpp:726-730] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/118135#discussion_r4168008408] Inline SETTINGS disk = disk(...) is still outside the lazy-load fix. Phase 1 returns nullptr before it can even look for convert_to_replicated, and for a lazy stand-in phase 2 does the same, so the flag is still silently ignored on every restart for that supported disk carrier. That leaves the PR title/body and changelog broader than the actual contract, and operators still have no explicit signal for this no-op path.
      Suggested fix: either support lazy inline-disk(...) tables end-to-end, or scope the PR text down to named disk / storage_policy only and add an explicit warning path for the lazy inline-disk(...) case.
Tests
  • ⚠️ If inline SETTINGS disk = disk(...) is intended to be covered by the disk claim in the PR body, add a focused lazy_load_tables = 1 regression matching test_modify_engine_on_restart_with_inline_disk to prove either successful conversion or the intended explicit warning/no-op contract.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions: resolve the lazy inline-disk(...) gap or narrow the PR/changelog contract and make that remaining no-op visible to operators.

LLVM Coverage Report

Measured on commit ffd1922.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 92.10% 91.80% -0.30%
Branches 79.70% 79.70% +0.00%

Changed lines: Changed C/C++ lines covered: 59/69 (85.51%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 10, 2026
alexey-milovidov and others added 2 commits September 17, 2026 19:31
…ingToReplicated`

The second phase of the conversion resolved the table's storage policy via
`tryGetCreateTableQuery`, which goes through `tryGetTable` and then
`waitTableStarted` on the very table whose startup job is executing. The
`AsyncLoader` reported the self-dependency as a logical error
(`Load job 'startup table db.t' waits for dependent load job 'startup table db.t'`),
failing `ATTACH DATABASE` for every table and aborting the server in the fast test.

Use `getCreateQueryFromMetadata`, which parses the `.sql` file directly without
touching the catalog, so `lazy_load_tables` is still honored and no job waits
on itself.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118135&sha=d7ab7bc0b80469bd0b1371798c222f300bba2692&name_0=PR&name_1=Fast%20test
PR: #118135

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Comment thread src/Databases/DatabaseOrdinary.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit ffd192276eb52a9fc3c264c06f3c4f1ab86d5b2b was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception; stopped retrying after the 1250 s read budget).

See the job log for details.

Comment thread src/Databases/DatabaseOrdinary.cpp Resolved
alexey-milovidov and others added 2 commits September 24, 2026 13:55
`DatabaseOrdinary::getStoragePolicyFromCreateQuery` only looked at `storage_policy`, while
`MergeTreeData::getStoragePolicy` gives `disk` precedence. A table created with
`SETTINGS disk = ...` had its flag looked up on the default-policy disk. Mirror the `disk`-first
resolution (including custom `disk(...)` definitions), and add integration tests for the `disk`
form and for `SYSTEM RESTORE REPLICA` on a lazily loaded table.

Addresses review comments on #118135

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Comment thread src/Databases/DatabaseOrdinary.cpp Resolved
alexey-milovidov and others added 2 commits October 2, 2026 16:40
…ing the metadata scan

`getStoragePolicyFromCreateQuery` runs for every `MergeTree` table before the
`convert_to_replicated` flag is known to exist. Resolving an inline `disk(...)`
setting there created the custom disk, so under `lazy_load_tables` a table that
should stay deferred could fail `ATTACH DATABASE` or server startup (e.g. an
unavailable `include` or `from_zk`). Keep the lookup limited to named disks and
storage policies; tables on inline disk definitions are skipped by both phases.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Databases/DatabaseOrdinary.cpp Resolved
alexey-milovidov and others added 2 commits October 4, 2026 15:46
…o-replicated-117413

Master introduced `castStorage` with `DeferredTable`. In `restoreMetadataAfterConvertingToReplicated`,
keep the PR's flag-first logic and materialize the stand-in with
`castStorage<StorageReplicatedMergeTree>(table, DeferredTable::Load)` instead of the manual
`StorageProxy` unwrap. Drop the PR's manual unwrap in `InterpreterSystemQuery::restoreReplica`:
master's `castStorage(..., DeferredTable::Load)` already loads the stand-in there.
…sk(...)` tables

Without `lazy_load_tables` the table is loaded right after the metadata scan, which creates its
custom disk anyway, so the first phase now resolves the inline `disk(...)` definition and looks for
the flag on that disk. Only with `lazy_load_tables` is the custom disk still not instantiated during
the scan. The second phase now logs a warning when it finds the flag on a table that was not
converted, instead of ignoring it silently. Add a regression test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Databases/DatabaseOrdinary.cpp Resolved
…on-converting tables at startup

The metadata scan resolved an inline `disk(...)` definition without
`for_system_database`. Custom disks are cached by their definition, so the
real load of a `system` table then reused the disk created without the
`s3_allow_server_credentials_for_system_table_disks` exemption, which went
anonymous and failed the server start in
`test_storage_s3/test.py::test_system_table_s3_disk_uses_server_credentials_with_server_setting`:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118135&sha=latest&name_0=PR&name_1=Integration%20tests%20(amd_llvm_coverage%2C%203%2F8)

Address review: `restoreMetadataAfterConvertingToReplicated` reparsed the
metadata of every table without a storage policy (views, dictionaries,
`Log`, any lazy table) and checked the flag for it. The metadata scan now
remembers the CREATE query of the `Replicated*MergeTree` tables of a
database with `lazy_load_tables`, and only those stand-ins resolve the
policy at startup; eagerly loaded tables keep the old fast path of
skipping anything that is not a `StorageReplicatedMergeTree`.

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

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This is borderline harmful, as the original issue is pointless. However, I've read all the code and found it acceptable.

@alexey-milovidov alexey-milovidov self-assigned this Oct 14, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 14, 2026
Merged via the queue into master with commit c7e8caf Oct 14, 2026
149 checks passed
@alexey-milovidov
alexey-milovidov deleted the lazy-load-convert-to-replicated-117413 branch October 14, 2026 00:38
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 14, 2026
alexey-milovidov added a commit that referenced this pull request Oct 14, 2026
…Needed` uses its policy

After merging `master`, `DatabaseOrdinary::getStoragePolicyFromCreateQuery` (from
#118135) resolved an inline `disk(...)` with
`MergeTreeSettings::resolveDiskSetting` and dropped the returned registration. The disk was
unregistered right away, so `getStoragePolicyFromDisk` threw `UNKNOWN_DISK` and `ATTACH DATABASE`
of a database with such a table failed (`05136_custom_disk_released_on_detach`). The registration
is now handed to the caller and kept while the policy is in use.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov added a commit that referenced this pull request Oct 14, 2026
…stem-tables-117420

Conflict resolution:
- `DatabaseOrdinary`: master (#118135) finishes the `convert_to_replicated` conversion of a lazily
  loaded table by materializing the stand-in in the second phase, so this branch's own fix (do not
  defer such a table, `hasConvertToReplicatedFlag`) is dropped in favor of master's.
- `StorageProxy.h`: master now forwards `supportsDelete`, `supportsLightweightDelete`,
  `supportsLightweightUpdate`, `checkMutationIsPossible` and `updateLightweight` itself; the
  duplicate overrides from this branch are removed.
- `InterpreterAlterQuery`: keep resolving the mutation target to the real storage before taking
  the metadata snapshot, which subsumes master's reordering of `checkMutationIsPossible`.
alexey-milovidov added a commit to evillique/ClickHouse that referenced this pull request Nov 2, 2026
Master gained its own fixes for two things this PR also did:
- ClickHouse#118135 finishes a pending conversion to `ReplicatedMergeTree`
  for a deferred table by materializing it in `restoreMetadataAfterConvertingToReplicated`. Drop this PR's
  `converting_to_replicated` set, which kept such tables eager for the same purpose, and its integration
  test, which `test_modify_engine_on_restart/test_lazy_load_tables.py` covers.
- ClickHouse#118152 made `StorageProxy` forward `checkMutationIsPossible`,
  `supportsDelete`, `supportsLightweightDelete`, `supportsLightweightUpdate` and `updateLightweight`. Drop
  this PR's second copy of the same overrides, which no longer compiled.

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

comp-database-engines Database engine implementations (e.g., Atomic/Replicated) and database-level behavior. 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.

MergeTree to ReplicatedMergeTree conversion silently fails and leaves the table read-only forever under lazy_load_tables

3 participants