Skip to content

Don't drop a user table that took a union system log name - #119063

Closed
alexey-milovidov wants to merge 22 commits into
masterfrom
union-system-log-name-collision-117945
Closed

alexey-milovidov wants to merge 22 commits into
masterfrom
union-system-log-name-collision-117945

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

A user table that happens to occupy the name of a union system log table (system.all_query_log and friends) is no longer dropped when create_union_system_log_tables is enabled.

SystemLog::prepareUnionTable issues CREATE OR REPLACE TABLE system.all_<log> whenever the existing definition on that name differs from the one it wants. The name lives in the system database, but users can create tables there, and system.all_query_log is exactly the name a hand-rolled union over the rotated query_log_N tables would take. With the setting enabled, the server replaced such a table on startup and the data was gone, with only a LOG_DEBUG line about an "obsolete or different definition" to show for it.

The union tables this feature generates are proxies over the merge / clusterAllReplicas table function and hold no data, so replacing one of those is safe. Anything else is now left alone: the server logs an error naming the table and skips the union table for that log. A generated table is recognised by reading from this very log table through one of the generated shapes and by the comment every one of them carries ("It is safe to drop this table at any time: it will be recreated automatically."), so a user's own proxy AS merge(...) or AS clusterAllReplicas(...) on such a name is kept too, as is a user's table that copied the comment onto a proxy over something else.

The classification happens outside any DDLGuard, so a table created on the name between it and the exchange has to be protected as well. The rule therefore travels with the query: CREATE OR REPLACE of a definition that declares itself a generated union table of a system log, on the union table name of that log (all_<log>; the same definition under any other name is an ordinary user table), may only replace another generated union table of the same log, whoever issues the query. It is decided in InterpreterCreateQuery::doCreateOrReplaceTable under the DDLGuard of the target name, from the query text and the stored definition of the existing table alone, so it holds identically when a database that replicates its DDL replays the query from its text on the DDL worker. A user who really wants to put such a definition over a table of their own has to drop that table first. The definition is recognized in every spelling the table functions accept (identifiers, currentDatabase(), db.table, a merge nested into clusterAllReplicas), not only the literal one the server writes.

Closes: #117945

Changelog category (leave one):

  • Improvement

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

Fixed a bug where enabling create_union_system_log_tables silently dropped a pre-existing user table occupying the name of a union system log table, such as system.all_query_log, together with its data. Such a table is now kept, and an error is logged instead.


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

`SystemLog::prepareUnionTable` issues `CREATE OR REPLACE TABLE
system.all_<log>` whenever the definition it finds on that name differs
from the one it wants. Users can create tables in the `system` database,
and `system.all_query_log` is exactly the name a hand-rolled union over
the rotated `query_log_N` tables would take, so with
`create_union_system_log_tables` enabled the server dropped such a table
with all of its data, leaving only a `LOG_DEBUG` line about an "obsolete
or different definition".

The union tables this feature generates are proxies over the `merge` /
`clusterAllReplicas` table function and hold no data, so replacing one of
those is safe. Anything else is now left alone: the server logs an error
naming the table and gives up on the union table for that log.

Closes: #117945
@clickhouse-gh

clickhouse-gh Bot commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4876aca]

Summary: ✅


AI Review

Summary

This PR closes the data-loss bug where create_union_system_log_tables could replace a user-owned all_<log> table, and it does the important follow-up work of re-checking ownership under the target name's DDLGuard and on replicated-DDL replay. That design looks directionally right, but one blocker remains in the new pre-swap path: it exposes the existing object's stored CREATE definition before enforcing the final object-kind access check.

Findings

❌ Blockers

  • [src/Interpreters/InterpreterCreateQuery.cpp:3071] The new union-table guard fetches getCreateTableQuery and includes formatForErrorMessage() in the TABLE_ALREADY_EXISTS exception before the later DROP_VIEW / DROP_DICTIONARY check. CREATE OR REPLACE TABLE only requires DROP_TABLE up front, so this failure path becomes a metadata leak: a generated-shaped CREATE OR REPLACE TABLE all_query_log ... can reveal the full definition of an existing view, dictionary, or other object that the caller is not allowed to inspect with SHOW CREATE.
    Suggested fix: determine the existing storage kind and run the type-specific drop access check before reading or formatting its stored definition, or omit the stored definition from the error text.
Final Verdict

Request changes. The ownership re-check itself is valuable, but the new error path should not disclose the existing object's CREATE definition before the required access check has passed.

LLVM Coverage Report

Measured on commit 4876aca.

Metric Baseline Current Δ
Lines 88.10% 88.10% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.40% 79.40% +0.00%

Changed lines: Changed C/C++ lines covered: 171/187 (91.44%) · 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 9, 2026
Comment thread src/Interpreters/SystemLog.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-logging Logging/monitoring/observability (logs, metrics, tracing, instrumentation). label Sep 9, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 4876aca02baa25f32b4a22b3d65ec4e1dc550d5d was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

alexey-milovidov and others added 4 commits September 10, 2026 01:36
…to go

Not marking the union table broken: a flush that still finds a table on
the name returns before reaching the refusal, so the message is logged
once per check rather than once per flush, and the first flush after the
user removes that table creates the union table.

`test_recreated_on_rotation` asserted the behaviour this fixes - that a
table a user put on the union name is replaced at the next rotation of
the log table - so it now asserts that the table survives the rotation
and that the union table returns once the user drops it.
…t its table function

The check that kept a user table on a union system log name treated every
table `AS merge(...)` or `AS clusterAllReplicas(...)` as generated by the
feature, so a user's own proxy over those table functions was still replaced
with `CREATE OR REPLACE`. Every definition that `getCreateUnionTableQuery`
produces has carried a comment ending with "It is safe to drop this table at
any time: it will be recreated automatically." since the feature appeared, so
that sentence is now the ownership marker, in addition to the table function.
A table without it is left alone, whatever it reads from; a table that has it
but a stale definition is still brought up to date, as before.

The integration test now also covers user proxies `AS merge(...)` and
`AS clusterAllReplicas(...)` on union names, a stale generated definition
that must still be replaced, and the recreation of the union tables once the
user tables are gone.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added pr-critical-bugfix pr-must-backport Pull request should be backported intentionally. Use this label with great care! and removed pr-bugfix Pull request with bugfix, not backported by default labels Sep 18, 2026
alexey-milovidov and others added 3 commits September 19, 2026 20:22
…his log

The comment marker alone let a user's proxy over an unrelated table be replaced
as long as it had copied the comment. `prepareUnionTable` now also requires the
table function to be one of the shapes `getCreateUnionTableQuery` generates for
this very log table - `merge` over the log table and its rotated versions, that
`merge` wrapped into `clusterAllReplicas`, or `clusterAllReplicas` over the log
table alone. The cluster name and the choice between the shapes come from the
server configuration and may have changed since the table was generated, so they
are not pinned and the upgrade path is unchanged.

The stale fixture in `test_union_system_log_name_collision` is now a definition
an older server would really have generated, and a comment-bearing proxy over an
unrelated table is added to the tables that must survive.

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

Copy link
Copy Markdown
Member Author

🕵 The only red was Build profile diff failing with RuntimeError: CI logs cluster query failed (job log) — a CI-infrastructure failure unrelated to this change, which touches only SystemLog.cpp and integration tests. Fixes for it are already in flight: #118708 and #121048.

Merged master (the branch was 472 commits behind) to re-run CI; the merged tree compiles.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The only red is 05227_storage_settings_unknown_name on Stateless tests (amd_debug, parallel) and (arm_binary, parallel) (report). It is failing fleet-wide on master itself (e.g. commits 84678846, 4d334b84, 3193a89f across arm_release, amd_release, amd_msan, amd_tsan) and is unrelated to this change, which touches only SystemLog.cpp and integration tests. The test pins where a SETTINGS reset (max_threads = DEFAULT) is stored; the fix is already in flight in #121163.

@groeneai, please land #121163 (or link whichever fix supersedes it) so this clears fleet-wide.

@groeneai

Copy link
Copy Markdown
Collaborator

Confirmed: #121163 is the right fix for this red, and the revert #121144 is not needed for it.

05227_storage_settings_unknown_name is mine (#120898). It is about which SETTINGS names the File/URL/S3/Log-family check rejects, but three of its expected lines also pinned, through a full SHOW CREATE TABLE echo, where an accepted name = DEFAULT query-setting reset ends up in the stored clause. df3cad127e7e of #118423 moved that deliberately: a second loop over ASTSetQuery::default_settings in InterpreterSetQuery::applySettingsFromQuery applies such a reset to the query context and erases it from the clause. That placement already has a test which travels with it, 05099_create_database_with_inline_disk, so the stale expectation is mine. #121163 makes the three affected read-backs assert what the test is about (the CREATE was accepted, the engine setting survived the split), leaves every CREATE statement and every serverError UNKNOWN_SETTING arm unchanged, and keeps full-echo accept coverage on CREATE ... AS SELECT, the one route where the split never runs.

It is green in both worlds, measured rather than argued: the pristine test FAILs on master and is OK with df3cad127e7e reverted in the tree, while the changed test is OK on both. So it unblocks master now and costs nothing if #121144 lands anyway.

#121163 is ready: its PR workflow finished green (run 35500876152), 05227 is OK in both flavours you cite here, Stateless tests (amd_debug, parallel) and (arm_binary, parallel), plus 250/250 across the five flaky-check flavours, CIDB shows zero failing tests on the branch, and it is MERGEABLE/CLEAN. I cannot merge it myself and your review is already requested there, so approval is the only step left.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks — #121163 is merged (1d7d23fc7105 on master), and this branch now carries it via the master merge 21379464e0c3, so the 05227_storage_settings_unknown_name red is cleared here. The rerun is green so far with no failures; the remaining checks are still running.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119063&sha=21379464e0c388f9d1eeff8d3d07c3a0833a1338&name_0=PR&name_1=Performance%20Comparison%20%28arm_release%2C%20master_head%2C%201%2F6%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

The only red on this pull request is Performance Comparison (arm_release, master_head, 1/6): lazy_final_early_exit_limit #0, client_time 0.0200 s -> 0.0234 s (+16.5%), reported as confirmed_regression. This pull request touches only SystemLog.cpp (prepareUnionTable / isGeneratedUnionTableFunction, which run when a system log table is prepared) and two integration tests - nothing on any query execution path, and certainly nothing reachable from a FINAL query with LIMIT.

lazy_final_early_exit_limit #0 is noisy fleet-wide. From the CI database (last 30 days, test_status in slower/unstable), it was flagged on these unrelated pull requests: #120036 (arm_release 1/6, slower), #119763 (arm_release 2/6, slower), #117876 (arm_release 6/6, slower), #119970 (arm_release 4/6, slower), #102499 (arm_release 1/6, slower), plus unstable on #119001 and #120191. The absolute numbers are tiny - a ~20 ms query where a 3.4 ms shift crosses the threshold - and the job itself was labelled under-utilized CPU, disk-almost-full and 3 too long, so the runner was not in good shape either.

I found no open issue tracking this query, so it likely needs one. I merged master (the branch was 319 commits behind) and pushed 2737231fe57b so the check re-runs on a current base.

Search for an existing tracking issue turned up nothing:

  • gh issue list --search "lazy_final_early_exit_limit" - no results.

Comment thread src/Interpreters/SystemLog.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator

The fix is already in progress: #121090, "Perf CI: fail a master_head shard only when its own report also calls the query slower" (open since 2026-09-19). It clears this exact red, and lazy_final_early_exit_limit itself needs no change.

Two judges disagree on that shard, and the one that flagged the query is not the job's own.

  • The dashboard flagged it. From the job log: Dashboard slowdown: lazy_final_early_exit_limit #0 0.0200 -> 0.0234 (+16.5%), tier [confirmed_regression].
  • The job's own report did not. Its report/all-query-metrics.tsv row is client_time 0.02 0.0234 0.165 1.169 0.165 lazy_final_early_exit_limit 0 <query> 0.27 0.32, i.e. diff = 0.165, stat_threshold = 0.165, changed_threshold = 0.27. compare.sh computes changed_fail = abs(diff) > changed_threshold and abs(diff) >= stat_threshold (0.165 > 0.27 is false) and changed_show = abs(diff) > changed_threshold - 0.05 and abs(diff) >= stat_threshold (0.165 > 0.22 is false), so the query appears nowhere in "Changes in Performance" (whose only two rows are timeseries_to_grid_aggregation_functions #1 at -13% and codecs_float_select #2 at +11.7%), and the status line carries no slower count at all: 3 too long; 1 confirmed regression(s) on the performance dashboard.

That changed_threshold = 0.27 is the learned bar: quantileExact(0.99)(abs(diff)) * 1.5 over a month of master runs of this same query, HAVING count() > 100 (GET_HISTORICAL_TRESHOLDS_QUERY, ci/jobs/performance_tests.py). The harness has therefore already measured this 20 ms query's p99 master-to-master swing at about 18%, and +16.5% is below it. That is why I would not open an issue against the query: its own measurements hold nothing to fix. What #120927 changed is that the dashboard's single-episode tier became the sole gate, discarding the per-query historical bar the job itself computes.

#121090 pairs the two: a confirmed_regression blocks only when the same (test, query_index) also satisfies diff > changed_threshold and diff >= stat_threshold in the shard's own all-query-metrics.tsv, and it restores > 10 slower as a floor. Applied to this run's artifacts, lazy_final_early_exit_limit #0 is filtered out, no other query on the shard is a confirmed slowdown, and the shard is green.

One caveat on 2737231fe57b: #121090 is not merged, so the current gate is live on that re-run too. If the dashboard confirms any row of shard 1/6 there, the shard reds again independently of your diff. #121090 is CI green with no review yet.

… table's owner and replacing it

`prepareUnionTable` decided whether `system.all_<log>` holds a table this feature generated, and only
then ran `CREATE OR REPLACE`. Nothing tied the replacement to the object that was inspected, so
between the two another session could `DROP` the generated proxy and `CREATE` a stateful table of its
own on the same name, and the exchange would drop that table with its data - the silent loss this
change exists to prevent, just under concurrent DDL.

`InterpreterCreateQuery` now takes a `ReplacedTableCheck` callback, invoked from the replace path's
pre-swap check - under the target name's `DDLGuard`, immediately before the exchange - with the
`StorageID` of the table that is about to be dropped. Throwing from it aborts the replacement
atomically: no exchange happens and the filled temporary table is dropped by the existing failure
path. `prepareUnionTable` sets it to re-read the definition under the guard and re-apply the same
ownership predicate, now factored out as `isGeneratedUnionTable`, so what is checked is what is
replaced. When the re-check refuses, the outcome matches the up-front collision: the table is left
alone, the reason is logged, and the union table is created on a later flush once the name is free.

The regression test drives the race through the existing `create_or_replace_before_rename`
failpoint: the union table's creation parks before the exchange, a user table is created on the name
and filled, and after resuming the user's rows and `MergeTree` engine survive, no `_tmp_replace_*`
table is left behind, and the union table takes the name again once the user's table is dropped.

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

Copy link
Copy Markdown
Member Author

🕵 Pushed 1388bf2ba84e, which adopts the AI Review blocker: the TOCTOU window between classifying the owner of system.all_<log> and the CREATE OR REPLACE that replaces it is now closed by a re-check that runs under the target name's DDLGuard, immediately before the exchange (a new ReplacedTableCheck hook on InterpreterCreateQuery, invoked from the same pre-swap point as the existing max_table_size_to_drop check). A focused regression drives the concurrent DROP/CREATE sequence through the create_or_replace_before_rename failpoint. Details in the review thread.

@groeneai, thanks for the analysis on lazy_final_early_exit_limit #0 — agreed, and #121090 is the right fix: the job's own report/all-query-metrics.tsv puts diff = 0.165 below both changed_threshold = 0.27 and the changed_show bar, so only the dashboard judge flagged it. Nothing to change on this pull request for it.

The only other red is Build profile diff -> RuntimeError: CI logs cluster query failed, the CI-logs-cluster infrastructure failure already covered by the still-open #118708 and #121048.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119063&sha=1388bf2ba84eb51a5d0c2907de747c84abbe99e5&name_0=PR&name_1=Performance%20Comparison%20%28arm_release%2C%20master_head%2C%201%2F6%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

The only red on this pull request is again Performance Comparison (arm_release, master_head, 1/6), this time order_by_read_in_order #1: client_time 0.0153 s -> 0.0191 s (+24.3% against a learned changed_threshold of 22.5%), so this one is flagged by both the dashboard (confirmed_regression) and the shard's own report (1 slower) - #121090 would not filter it out. The job also carried the under-utilized CPU and disk-almost-full labels.

It is unrelated to this pull request, which touches only SystemLog.cpp / InterpreterCreateQuery (system-log table preparation and the CREATE OR REPLACE pre-swap hook) and two integration tests - nothing on the ORDER BY ... read in order path over hits_100m_single.

order_by_read_in_order #1 is one of the noisiest queries in the fleet. From the CI database (checks, last 30 days):

  • master-vs-master arm_release runs alone: flagged slower 72 times and unstable 88 times out of 1340 runs (about 12% flagged with no code change at all);
  • on pull requests it was flagged slower 1134 times across 391 distinct pull requests (all architectures), roughly 100 times per day over the last ten days.

A ~15 ms query where a 4 ms shift crosses the bar cannot serve as a gate; it probably needs a longer-running variant or a higher per-query threshold. I found no open issue tracking it (gh issue list --search "order_by_read_in_order" is empty), so it likely needs one.

I merged master (the branch was 357 commits behind, clean, no change to the files this pull request touches) and pushed so the check re-runs on a current base.

@groeneai

Copy link
Copy Markdown
Collaborator

The 22.5% is not the learned changed_threshold, it is stat_threshold, and that inverts the answer: this run had no learned thresholds at all.

The row in this shard's all-query-metrics.tsv:

client_time  0.0153  0.0191  0.243  1.248  0.225  order_by_read_in_order  1  SELECT * FROM hits_100m_single ORDER BY CounterID DESC, ...  0.15  0.25

The column order is fixed by all_query_metrics_tsv in ci/jobs/scripts/perf/compare.sh (line 1557 on master today): metric, left, right, diff, ratio, stat_threshold, test, query_index, query_display_name, changed_threshold, unstable_threshold. So 0.225 is column 6, stat_threshold, the per-run permutation estimate. changed_threshold is column 10, and it is 0.15, the bare floor. All 692 queries in the shard carry exactly 0.15 / 0.25.

The job log says why:

09:41:53  > Start execution for [Select historical data]
09:42:03  WARNING: CIDB query failed with exception: HTTPSConnectionPool(host='play.clickhouse.com', port=443): Read timed out. (read timeout=10)
09:42:23  ERROR: Failed to do select query CIDB
09:42:23  WARNING: Failed to fetch historical thresholds, will proceed without them
09:42:23  Run command: [touch .../perf_wd/historical-thresholds.tsv]

historical-thresholds.tsv was created empty, so report_thresholds fell back to greatest(0.15, 0, 0) for every query, and changed_fail is abs(diff) > changed_threshold and abs(diff) >= stat_threshold, that is 0.243 > 0.15 and 0.243 >= 0.225, true. That is the entire 1 slower.

The learned bar for this query is 0.65, and CI printed it itself one push earlier, on this same pull request and the same shard. On 21379464e0c3 the fetch succeeded:

idx=1  left=0.0179  right=0.0206  diff=0.151  stat_threshold=0.151  changed_threshold=0.65  unstable_threshold=0.25

0.151 > 0.65 is false, so the row was not called slower, and that shard reported 3 too long; 1 confirmed regression(s) on the performance dashboard, with no slower in it. Re-running the in-tree GET_HISTORICAL_TRESHOLDS_QUERY agrees: quantileExact(0.99)(abs(diff)) * 1.5 = 0.642 over 1974 rows, ceiling to 0.65 (arm alone, 0.606). Against 0.65 the 0.243 measured here is silent, and unstable_fail needs stat_threshold > 0.25, which 0.225 is not. With the thresholds fetched this shard is green.

So the two reds on this pull request are two different mechanisms, which is why they point at different fixes:

The fix is therefore already in progress, and for this red it is #121189, not #121090. The perf shards on the base you just pushed (a3bce820) are still PENDING.

Your design point is separate and I agree with it. Neither PR makes this query a usable gate: at a correct bar of 0.65 it takes a 65% regression to flag, so it stops detecting anything long before it stops being noisy. I posted a write-up of exactly that on #96844 half an hour before your comment, covering this query among six: the flags come from a per-build, per-query persistent code-layout offset the permutation test cannot see, the bar is learned from pr_number = 0 runs where that offset is absent, and the two architectures are pooled about 5x apart. It puts three options to you, and your "longer-running variant or a higher per-query threshold" is the second half of the first: #96844 (comment)

On the issue, you are right that there is none. I do not open issues unless asked, so tell me and I will file it with the numbers above.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, thanks - you are right, and I misread the row. In all_query_metrics_tsv the sixth column is stat_threshold, so the 0.225 I quoted as the learned bar was the per-run permutation estimate, and changed_threshold for every one of the 692 queries in that shard was the bare 0.15 floor because the Select historical data step timed out against play.clickhouse.com and left historical-thresholds.tsv empty. With the real learned bar of 0.65 (which CI itself printed on 21379464e0c3), a 0.243 shift is silent, so this red is the missing-thresholds mechanism and the fix is #121189, not #121090. Nothing to change on this pull request for it; the perf shards on a3bce820045f are still pending.

Yes, please file the tracking issue with the numbers above (the two mechanisms, the fleet-wide slower/unstable counts for order_by_read_in_order #1 and lazy_final_early_exit_limit #0, and a link to your write-up on #96844), so that future @groeneai requests for these queries can point at it instead of re-deriving the evidence.

@groeneai

Copy link
Copy Markdown
Collaborator

Filed: #121456

It holds both mechanisms (missing thresholds falling back to 0.15/0.25, with #121189 in flight, and the per-build offset with #121090 for the dashboard arm), the 30 day counts for order_by_read_in_order #1 and lazy_final_early_exit_limit #0 as counts plus report links, the learned bars (0.65 pooled, 0.67 amd and 0.61 arm), the job log and metric rows for both shas on this pull request, the re-derivation SQL, and the link to the #96844 options.

Two notes from re-deriving the counts cold:

  • The rate you quoted is exact, 11.99% flagged on master-vs-master arm_release, but the absolute counts halve: a flagged query writes both a ::old and a ::new row into checks, so that scope is 36 slower plus 43 unstable of 659 shard runs, and on pull requests it is 490 slower across 399 distinct pull requests.
  • New evidence in the issue: the offset follows the binary, not the run. Build fb1b2bff runs this query in 12.81 ms as a candidate and 13.16 ms as the next run's reference; 48a754e1, two commits later with +4/-3 lines in the DeltaLake write path as its only src delta, runs it in 19.76 ms and 17.59 ms in those same two roles, 30 repetitions per side and non-overlapping ranges. That is why the confirmation rerun does not demote it, and also why a learned bar of 0.65 would stay silent on a genuine +50% shift.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, thanks for filing #121456 and for the ::old/::new double-counting correction - the halved absolute counts and the "offset follows the binary" evidence are exactly what the issue needed. Nothing to change on this pull request for order_by_read_in_order #1; on a3bce820045f it fired once more on Performance Comparison (arm_release, master_head, 1/6) (+17.1%), which is now covered by that issue, with #121189 and #121090 as the fixes.

The other red on that head is CH Inc sync only: Stateless tests (amd_asan_ubsan, distributed cache, meta in keeper, s3 storage, parallel, 1/2) died with Logical error: Background compaction is not initialized. This is a bug. from IcebergMetadata.cpp while running the unrelated 03826_xxh3_128_types. That is the cloud-build OPTIMIZE-before-first-scheduler-round race on Iceberg tables, tracked in the private repository as issue 76481 with fix PRs #121500 (public) and 76501 (private), both still open. This pull request touches only SystemLog.cpp, the CREATE OR REPLACE pre-swap hook in InterpreterCreateQuery, and two integration tests, so it cannot reach that path.

Merged master again (clean; master changed none of the files this pull request touches) and pushed e61520d185b3.

alexey-milovidov and others added 2 commits September 22, 2026 13:56
…ship rule itself

The re-check of the table about to be replaced was a callback that `SystemLog::prepareUnionTable` set
on its `InterpreterCreateQuery`. That does not hold in a database that replicates its DDL: the
initiator only enqueues the query into the replicated log, and the DDL worker replays it on every
replica from its text with a fresh interpreter, where the callback is not available, so a user table
created between the classification and the replay would still have been dropped.

The rule now travels with the query: a definition that declares itself a generated union table of a
system log (a proxy over one of the generated table functions carrying the generated comment marker)
may only replace another generated union table of the same log, whoever issues the query. That is
decided in `doCreateOrReplaceTable` under the `DDLGuard` of the target name, from the query text and
the stored definition of the existing table alone, so it holds identically on a replay. The predicate
moves out of `SystemLog.cpp` into `SystemLogUnionTable.h` to be shared, and the `ReplacedTableCheck`
callback API is removed.

New stateless test covers the rule in an `Atomic` and in a `Replicated` database, where the query
goes through the DDL worker replay; the failpoint-based integration test keeps covering the race in
the system log flush itself.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
alexey-milovidov and others added 2 commits September 22, 2026 17:05
… spelling the table functions accept

The ownership rule that `CREATE OR REPLACE` applies to a definition generated for a union system log
(`system.all_query_log` and friends) only recognized string-literal arguments, so the same definition spelled
as `merge(system, ...)`, `merge(currentDatabase(), ...)` or `clusterAllReplicas(default, system.query_log)`
was not recognized and could replace a user table sitting on the name.

For the top-level table function the table functions themselves rewrite such arguments into literals in
`parseArguments` before the rule is applied (documented at the call site now), so those spellings were in
fact already covered; the arguments of a `merge` nested into `clusterAllReplicas` are the exception, as the
outer function keeps its inner table function as written and evaluates it remotely. `getSystemLogOfGeneratedUnionTable`
now takes the query context to evaluate those itself, accepts bare identifiers wherever it accepted literals
(so the rule does not depend on that order of events), and accepts the log table as one qualified name
(`system.query_log` / `'system.query_log'`), which is how `clusterAllReplicas(cluster, db.table)` is stored.
A stored definition is still read without a context, as the server wrote it.

`05238_create_or_replace_generated_union_system_log_table` covers the non-literal spellings, including the
nested one, for both the Atomic and the Replicated database.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
alexey-milovidov and others added 3 commits September 23, 2026 00:35
… on the union table name of its log

`SystemLog::prepareUnionTable` manages only `all_<log>` in the database of the log, but the
ownership predicate accepted the generated definition under any name, so
`CREATE OR REPLACE TABLE report ... AS merge(currentDatabase(), '^query_log(_[0-9]+)?$') COMMENT '...'`
refused to replace an unrelated user table `report`. The predicate now takes the name of the
table it classifies and requires it to be the union table name of the log the definition reads.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…d_union_system_log_table`

The private CI replaces `ReplicatedMergeTree` with `SharedMergeTree`, which made the
check of the kept user table in the `Replicated` database fail there
(ClickHouse/clickhouse-private#73717). Check that the engine is
of the `MergeTree` family instead.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…union table definition

`merge('^query_log(_[0-9]+)?$')` reads from the current database and keeps
that single argument in its definition, so `getSystemLogOfGeneratedUnionTable`
did not recognize it, and `CREATE OR REPLACE` of that spelling skipped the
pre-swap guard and dropped a user table on the union table name. With a
context, the single-argument form is now read against the current database,
the same way `TableFunctionMerge::parseArguments` resolves it. A stored
definition is still read without a context, where not recognizing it is the
safe side. `05238` covers the top-level and the nested (`clusterAllReplicas`)
single-argument forms.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Review asked whether a mixed-case `MERGE` / `ClusterAllReplicas` bypasses the
ownership check of a generated union system log table. It does not: both table
functions are registered case-sensitively and without aliases, so such a query
fails with `UNKNOWN_FUNCTION` before anything is replaced, including a `Merge`
nested into `clusterAllReplicas` (which `parseRemoteFunctionArguments` only
treats as a table function through `isTableFunctionName`). Add these spellings
to `05238_create_or_replace_generated_union_system_log_table` so the test pins
that the user table survives them.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
{
if (generated_union_table_log)
{
ASTPtr to_drop_create_query = DatabaseCatalog::instance()

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.

Fetching to_drop_create_query and embedding formatForErrorMessage() into the TABLE_ALREADY_EXISTS error happens before the type-specific drop privilege check below. CREATE OR REPLACE TABLE only requires DROP_TABLE up front (getRequiredAccess at lines 3795-3797), so this makes a generated-shaped CREATE OR REPLACE TABLE all_query_log ... query into a SHOW CREATE oracle for whatever currently owns that name. In particular, if the name is occupied by a view or a dictionary, a user without DROP_VIEW / DROP_DICTIONARY still gets its full definition in the exception text because the throw here runs before lines 3089-3094. Please do the kind-specific access check first, or drop the existing definition from this message.

@alexey-milovidov alexey-milovidov removed pr-must-backport Pull request should be backported intentionally. Use this label with great care! pr-critical-bugfix labels Sep 23, 2026
@alexey-milovidov alexey-milovidov self-assigned this Sep 23, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

I would resolve it simply - by not fixing.

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

Labels

comp-logging Logging/monitoring/observability (logs, metrics, tracing, instrumentation).

Projects

None yet

Development

Successfully merging this pull request may close these issues.

A pre-existing table named system.all_<log> is silently dropped with its data when create_union_system_log_tables is enabled

2 participants