Skip to content

Mark old system log tables as readonly - #95079

Merged
alexey-milovidov merged 43 commits into
ClickHouse:masterfrom
matt-metivier:94628-mark-old-system-logs-readonly
Jun 30, 2026
Merged

alexey-milovidov merged 43 commits into
ClickHouse:masterfrom
matt-metivier:94628-mark-old-system-logs-readonly

Conversation

@matt-metivier

@matt-metivier matt-metivier commented Jan 25, 2026 •

Copy link
Copy Markdown
Contributor

When system log tables are renamed during log rotation (e.g., query_log → query_log_0), mark the rotated table as read-only to stop wasting background CPU and I/O on it.

Changes

  1. Added a new table_readonly MergeTree setting — when set to true, the table performs no modifications on disk and no background work: inserts, mutations, OPTIMIZE, and explicit partition commands (DROP/MOVE/ATTACH/REPLACE/FETCH PARTITION) are rejected, and no background merges (regular, recompression, or TTL), mutations, or part moves are scheduled or even scanned for. The setting can always be toggled back via ALTER ... MODIFY/RESET SETTING.
  2. StorageMergeTree::assertNotReadonly rejects writes/mutations/OPTIMIZE; MergeTreeData::alterPartition rejects mutating partition commands; background scheduling (scheduleDataProcessingJob/scheduleDataMovingJob, MergeTreeDataMergerMutator::selectPartsToMerge) bails out before any candidate scan.
  3. SystemLog::prepareTable — after renaming an obsolete log table, marks it with table_readonly = 1. Replicated tables and tables carrying a TTL are intentionally skipped (a TTL-bearing table must keep reclaiming disk; table_readonly is unsupported on ReplicatedMergeTree). The ALTER is best-effort and wrapped so it can never lose in-flight log data.

Closes #94628

Changelog category (leave one):

  • Performance Improvement

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

Mark rotated non-replicated MergeTree system log tables without TTL as table_readonly to avoid unnecessary background operations. The table_readonly MergeTree setting now also suppresses all background work on a plain MergeTree table — regular, TTL (DELETE/MOVE/recompression) and recompression merges, background mutations, and background part moves — and rejects the mutating partition commands (ATTACH/MOVE/DROP/DROP DETACHED/FETCH/REPLACE PARTITION and MOVE PARTITION ... TO TABLE into the table), in addition to the inserts, mutations, and OPTIMIZE it already rejected. As a result, a table_readonly table with a TTL no longer reclaims its expired data while the setting is enabled.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

No user-facing documentation required. This is an internal optimization that happens automatically during system log rotation.


Note

Medium Risk
Adds an automatic ALTER TABLE ... MODIFY SETTING table_readonly=1 after system log rotation, introducing additional DDL execution during SystemLog::prepareTable() that could surface permission/setting-related failures or edge cases around non-MergeTree/absent tables.

Overview
When SystemLog::prepareTable() detects an obsolete log table and renames it (e.g., query_log -> query_log_N), it now also marks the renamed table as read-only for MergeTree-backed logs to avoid unnecessary background work.

This is implemented by constructing and executing an ALTER TABLE ... MODIFY SETTING table_readonly = 1 via InterpreterAlterQuery immediately after the rename, with new parser/interpreter includes to support building the ALTER AST.

Reviewed by Cursor Bugbot for commit 89e40c5. Bugbot is set up for automated code reviews on this repo. Configure here.

Version info

  • Merged into: 26.7.1.294 (included in 26.7 and later)

@matt-metivier matt-metivier mentioned this pull request Jan 25, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jan 25, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jan 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [34e3def]

Summary: ✅


AI Review

Summary

This PR marks rotated non-replicated MergeTree system log tables without TTL as table_readonly, and tightens the plain MergeTree table_readonly contract so foreground mutations, mutating partition commands, background merges, TTL/recompression merges, background mutations, and background part moves are suppressed. I did not find any new high-confidence correctness issue in the current head; the earlier bot-authored review points are either fixed in the current code or were deliberately accepted by the maintainer.

Missing context / blind spots
  • ⚠️ The current CI run for 34e3def27fa699e14b3889b53f390c6893599acc is still pending. The Praktika PR report exists but currently has 0 completed test entries, so final test validation still depends on CI finishing green.
Final Verdict

Status: ✅ Approve

No new inline findings. Normal CI completion remains the only open validation dependency I saw.

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Jan 25, 2026
Comment thread src/Storages/StorageMergeTree.cpp Resolved
@matt-metivier
matt-metivier force-pushed the 94628-mark-old-system-logs-readonly branch from cb5fc23 to 4954f0e Compare January 25, 2026 15:04
When system log tables are renamed during log rotation (e.g., query_log -> query_log_0),
mark them as readonly to prevent wasting CPU time on background operations.

Implementation:
1. Add new 'read_only' MergeTree setting
2. Check this setting in StorageMergeTree::assertNotReadonly()
3. At startup, treat table as readonly if setting is enabled (similar to readonly disks)
4. Set read_only=1 via ALTER TABLE after renaming system log tables
@matt-metivier
matt-metivier force-pushed the 94628-mark-old-system-logs-readonly branch from 9bb22ca to 88ee720 Compare January 25, 2026 15:31
@matt-metivier

Copy link
Copy Markdown
Contributor Author

Should be ready for review

@matt-metivier matt-metivier changed the title 94628: Mark old system log tables as readonly [#94628]: Mark old system log tables as readonly Jan 26, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

The tests have failed due to an assertion violation. The failures are related to these changes.

@alexey-milovidov alexey-milovidov self-assigned this Jan 26, 2026
Comment thread src/Core/SettingsChangesHistory.cpp Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member

Let's add a test for the new readonly table-level setting.

alexey-milovidov and others added 2 commits February 18, 2026 08:02
…y`, move to 26.2

- Rename MergeTree setting from `table_is_readonly` to `table_readonly`
- Move settings history entry from 26.1 to 26.2
- Allow ALTER MODIFY SETTING / RESET SETTING through even when the table is
  readonly, so the setting can be toggled back
- Add stateless test for the `table_readonly` setting

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Feb 18, 2026

@alexey-milovidov alexey-milovidov 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

@alexey-milovidov

Copy link
Copy Markdown
Member

Continued this PR: implemented the two outstanding AI-review Majors (the inline threads are now resolved) and tightened the changelog entry. Pushed 20b6b9ba33e..569cc7e780b (and merged current master, clean).

AI review — table_readonly did not block explicit ALTER ... PARTITION mutations (MergeTreeData.cpp) ✅ (b6f8da1ff6b)
Partition commands are dispatched by InterpreterAlterQuery straight to MergeTreeData::alterPartition, bypassing StorageMergeTree::alter / assertNotReadonly. alterPartition now rejects the mutating commands (DROP/MOVE/ATTACH/DROP DETACHED/FETCH/REPLACE PARTITION) with TABLE_IS_PERMANENTLY_READ_ONLY when table_readonly is set; read-only operations (FREEZE/UNFREEZE, FORGET PARTITION) stay allowed and MODIFY/RESET SETTING table_readonly still works (it goes through alter). Since table_readonly is rejected on ReplicatedMergeTree, this only ever applies to plain MergeTree. New test 04490_table_readonly_partition_commands covers it.

AI review — background path still scanned merge candidates for read-only tables (StorageMergeTree.cpp) ✅ (ec37b32d6e5)
MergeTreeDataMergerMutator::selectPartsToMerge now bails out before collectAllPossibleRanges (grabAllPossibleRanges) / splitByMergePredicate when the selector is read-only, so a rotated log table with many parts no longer burns CPU on the candidate scan every scheduling pass. MergeSelectorApplier::chooseMergesFrom keeps the same invariant as a secondary guard.

Changelog entry ✅ tightened to "Mark rotated non-replicated MergeTree system log tables without TTL as table_readonly to avoid unnecessary background operations."

CI — the two reds are known, master-wide, and unrelated to this PR (no overlap with the system-log / MergeTree-scheduling code):

Note: @alexey-milovidov's LGTM predates the scope growth (skip background merges/mutations/moves/TTL, partition-command gate, scan short-circuit) and these fixes, so a re-review is warranted.

A `table_readonly` table (the MergeTree setting used e.g. for rotated
system log tables) must not receive new parts. The source-side gate in
`MergeTreeData::alterPartition` only rejects `MOVE PARTITION ... TO TABLE`
when the *source* is read-only, because the command is dispatched through
the source table. When the source is writable and only the destination is
read-only, the gate does not fire and `StorageMergeTree::movePartitionToTable`
clones parts into the read-only destination, violating the invariant.

Add a destination-side `assertNotReadonly` check in
`StorageMergeTree::movePartitionToTable`, alongside the existing
destination-side `UNIQUE KEY` reject, before any parts are cloned. The
symmetric `REPLACE PARTITION ... FROM` command is already covered, because
it is dispatched through the destination table, whose `table_readonly` is
caught by the existing source-side gate.

New test `04491_table_readonly_move_partition_to_table`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

Continued this PR: implemented the outstanding AI-review Major (the MOVE PARTITION ... TO TABLE destination gate) and added a focused test. Pushed 569cc7e780b..df8d5c3e131.

AI review / Cursor Bugbot — MOVE PARTITION ... TO TABLE bypassed the destination's table_readonly ✅ (df8d5c3e131)

ALTER TABLE src MOVE PARTITION ... TO TABLE dst is dispatched through the source table, so the source-side gate in MergeTreeData::alterPartition only rejected it when src was read-only. When src was writable and only dst had table_readonly = 1, the gate did not fire and StorageMergeTree::movePartitionToTable cloned parts into the read-only destination. movePartitionToTable now calls dest_table_storage->assertNotReadonly() before any parts are cloned (alongside the existing destination-side UNIQUE KEY reject), rejecting with TABLE_IS_PERMANENTLY_READ_ONLY.

The symmetric REPLACE PARTITION ... FROM command needs no change: it is dispatched through the destination table (the one being modified), so a read-only destination is already caught by the existing source-side gate in alterPartition; the FROM source is only read.

New test 04491_table_readonly_move_partition_to_table covers the gap: a writable source, a table_readonly = 1 destination, the rejected MOVE PARTITION ... TO TABLE (destination unchanged), and a successful move after the setting is toggled back off. Verified locally against a fresh debug build; the existing 03924_table_readonly_setting and 04490_table_readonly_partition_commands still pass.

Note: @alexey-milovidov's LGTM predates the scope growth and these fixes, so a re-review is warranted.

…iption

Address review (AI Review Major / `clickhouse-gh` thread): the registered
`table_readonly` setting text was written for the original foreground-only
behavior ("Any attempts to insert data or modify the table will fail") and
never updated after this PR broadened the setting to suppress all on-disk
work.

The description now states that a `table_readonly` table performs no
modifications on disk at all: besides rejecting inserts/mutations/`OPTIMIZE`
and the data-mutating partition commands (including `MOVE PARTITION ... TO
TABLE` into the table), it also schedules no background merges, TTL merges
(`DELETE`/`MOVE`/recompression), recompression merges, background mutations,
or background part moves. In particular it spells out the operationally
important consequence that a table with a TTL stops reclaiming or moving
expired data while the setting is enabled, lists the read-only operations
that remain allowed (`FREEZE`/`UNFREEZE`, `FORGET PARTITION`), and notes that
the setting can be toggled back and is unsupported on `ReplicatedMergeTree`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

Continued this PR: implemented the remaining AI-review Major (the only outstanding item) and resolved its inline thread. Pushed df8d5c3e131..34e3def27fa.

AI review — expanded table_readonly semantics not reflected in the user-facing setting docs/changelog ✅ (34e3def27fa)

The registered table_readonly setting description was written for the original foreground-only behavior ("Any attempts to insert data or modify the table will fail") and was never updated after this PR broadened the setting to suppress all on-disk work. Rather than narrowing the behavior, I documented it (the intended contract is that a table_readonly table performs no modifications on disk at all — a single, predictable meaning):

  • The setting description (MergeTreeSettings.cpp) now states that, besides rejecting inserts/mutations/OPTIMIZE and the mutating partition commands (ATTACH/MOVE/DROP/DROP DETACHED/FETCH/REPLACE PARTITION, and MOVE PARTITION ... TO TABLE into the table), the setting schedules no background regular merges, TTL merges (DELETE/MOVE/recompression), recompression merges, background mutations, or background part moves. It calls out explicitly that a table with a TTL stops reclaiming/moving its expired data while the setting is enabled, lists the read-only ops that remain allowed (FREEZE/UNFREEZE, FORGET PARTITION), and notes the setting can be toggled back and is unsupported on ReplicatedMergeTree.
  • The changelog entry was extended to describe the broadened user-facing table_readonly semantics in addition to the system-log rotation optimization.

This is a documentation-only change (a DECLARE raw-string description plus the PR changelog entry); no code behavior changed. The clickhouse-gh thread at MergeSelectorApplier.cpp:223 is now resolved.

Note: @alexey-milovidov's LGTM predates the scope growth and these fixes, so a re-review is warranted.

@clickhouse-gh

clickhouse-gh Bot commented Jun 30, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

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

Changed lines: Changed C/C++ lines covered: 107/116 (92.24%) · Uncovered code

Full report · Diff report

and background part moves are all suppressed. As a consequence, a table with a TTL no longer reclaims or moves its expired data while this setting
is enabled.

The setting can always be toggled back with `ALTER TABLE ... MODIFY SETTING table_readonly = 0` (or `RESET SETTING`). It is not supported for `ReplicatedMergeTree`.

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.

As a follow-up for this PR, we should note that:

  • a table still can be dropped;
  • a table can refresh its data parts (refresh_parts_interval);

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.

@groeneai, do this follow-up (documentation edit + validation).

@alexey-milovidov alexey-milovidov 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.

The new table_readonly setting is the main delivery in this PR.
Marking system tables as readonly became just a "proof" of this feature.

@alexey-milovidov
alexey-milovidov merged commit 344b2e0 into ClickHouse:master Jun 30, 2026
173 of 174 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 30, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi @matt-metivier @alexey-milovidov — while reviewing this PR I found the following:

Could you review the test PR and add the can be tested label if it looks good?
Happy to discuss — close anything that's wrong or already addressed.

Comment on lines +35 to +38
/// If true, the table is read-only (the `table_readonly` MergeTree setting): no merges of any kind run —
/// neither regular merges, nor recompression, nor TTL drop/delete merges. (Tables with a TTL are never
/// marked read-only, so no TTL work is stranded; see `SystemLog::prepareTable`.)
const bool readonly = false;

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.

This breaks abstractions; it should not be a compaction part; it must be implemented at the table level, not in the merge selection algorithm.

@PedroTadim

Copy link
Copy Markdown
Member

Hello! Is this going to be applied to all rotated tables "left behind"?

zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
`SystemLog::prepareTable` now runs `ALTER TABLE ... MODIFY SETTING
table_readonly = 1` on the rotated `system.*_log_N` table when it
detects a schema mismatch. The setting is persisted into the rotated
table's `.sql` metadata as `SETTINGS index_granularity = 8192,
table_readonly = true`.

`table_readonly` is a MergeTree setting that was introduced in 26.3
(`v26.3.1.896-lts`). Releases older than 26.3 do not know it, so when
`MergeTreeSettingsImpl::loadFromQuery` parses the rotated metadata on
those binaries it throws `UNKNOWN_SETTING` and the server refuses to
start with `Cannot attach table ... from metadata file ...`. This is
the cause of the `restart_with_original_version`-style failures across
`test_implicit_index_upgrade`, `test_index_filename_upgrade`,
`test_manipulate_statistics::test_statistics_upgrade_from_old_version`,
`test_storage_s3_queue/test_migration` and
`test_topk_alpha_map_compatibility` on this PR.

Per maintainer direction
(ClickHouse#95079 (comment)),
bump the older-binary image tag in each affected compatibility test to
`26.3`, which is the first release that knows `table_readonly` and can
therefore re-attach a rotated system log table after downgrade.
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…d cover forced merges

The test inserted a "fresh" row with `d = today()` under `TTL d + INTERVAL 1 DAY`.
The flaky check runs tests with a randomized `session_timezone`, so `today()` can
be one day behind the server date (all CI failures had UTC-7 zones during the early
UTC morning), making the fresh row already expired and dropping both parts:
`TTL drop on readonly: FAIL (remaining rows: 0)`. Use a one-month TTL margin so a
one-day timezone skew in either direction cannot expire the fresh part.

Also set `min_age_to_force_merge_seconds = 1` and
`min_age_to_force_merge_on_partition_only = 1` on the read-only table so the test
covers the `getBestPartitionToOptimizeEntire` fallback, which previously bypassed
`table_readonly`.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=95079&sha=be4ee0351a4bd6efab08e358c4787718db94f420&name_0=PR&name_1=Stateless%20tests%20%28amd_asan_ubsan%2C%20flaky%20check%29
PR: ClickHouse#95079

Co-Authored-By: Claude Fable 5 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
A read-only table (the `table_readonly` MergeTree setting, used for rotated
system log tables) already skips regular merges, mutations, and recompression,
but it could still schedule background part moves between volumes/disks (the
storage policy `move_factor` or `TTL ... TO DISK/VOLUME` rules). A rotated
system log table on a multi-volume storage policy therefore kept wasting
background CPU and I/O, which did not match the "no background operations on
rotated log tables" contract.

Guard `MergeTreeData::scheduleDataMovingJob` on `table_readonly`: it is the sole
driver of the background move-selection path (the no-argument `selectPartsForMove`
is called only from there), so a read-only table now never schedules a move.
Explicit `ALTER TABLE ... MOVE` commands remain rejected separately by
`assertNotReadonly`.

Add `04341_table_readonly_background_moves`: a writable control table proves the
background move pool is actively making progress while the read-only table keeps
its part on the original (local) volume.

Addresses the AI review feedback on ClickHouse#95079

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
Most system logs in the default open-source `clickhouse-server` config have
no TTL (the `<ttl>` for `query_log`, `trace_log`, etc. is commented out in
`programs/server/config.xml`); only a few (`processors_profile_log`,
`asynchronous_insert_log`, `blob_storage_log`, `aggregated_zookeeper_log`,
`zookeeper_connection_log`) carry one. The comment in `SystemLog::prepareTable`
wrongly claimed that most system logs use a default `30 DAY` TTL. Correct it so
it reflects that the common case (`query_log` and friends) is frozen as readonly
after rotation, and only the few TTL-configured logs stay writable.

ClickHouse#95079

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…-system-logs-readonly

Mark old system log tables as readonly
@atayy123

Copy link
Copy Markdown

This breaks backward compatibility. Is it possible to disable this feature?

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-performance Pull request with some performance improvements 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.

Mark old system log tables as readonly

8 participants