Skip to content

Attach the system tables in clickhouse local on first access - #115489

Merged
alexey-milovidov merged 13 commits into
masterfrom
cli-startup-deferred-system-tables
Aug 29, 2026
Merged

alexey-milovidov merged 13 commits into
masterfrom
cli-startup-deferred-system-tables

Conversation

@thevar1able

@thevar1able thevar1able commented Aug 19, 2026 •

Copy link
Copy Markdown
Member

Split out of #112496, where profiling showed that clickhouse local --query "SELECT 1" spends
almost all of its 45ms before the query, 1ms of which is the query itself.

clickhouse local attached all ~164 system tables and both spellings of information_schema up front, about 10ms of work. information_schema alone parses 20 embedded CREATE VIEW statements and builds 40 view storages, and an invocation such as clickhouse local --query "SELECT 1" never reads any of it.

image

Changelog category (leave one):

  • Performance Improvement

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

clickhouse local now attaches the system and information_schema tables on first access
instead of at startup.


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

Version info

  • Merged into: 26.9.1.304 (included in 26.9 and later)

`clickhouse local` attached all ~164 system tables and both spellings of
`information_schema` up front. The latter alone parses 20 embedded `CREATE VIEW`
statements and builds 40 view storages, and an invocation such as
`clickhouse local --query "SELECT 1"` never reads any of them. Now
`DatabaseWithOwnTablesBase::setDeferredPopulation` fills the table list on first
access instead.

`system.one` is the exception and stays eager: every `FROM`-less query resolves it
during analysis, so deferring it along with the rest would just move the whole
cost into the first query. Accordingly the table lookups check the already
attached tables before triggering population.

The server keeps attaching its system tables eagerly.

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

clickhouse-gh Bot commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c5bf967]

Summary: ✅


AI Review

Summary

This PR defers clickhouse local attachment of the system and information_schema tables until first access, and the current head also covers the persistent Atomic system database path plus the sticky-error behavior after a failed deferred population. After reviewing the current diff, the prior review threads, and the updated tests, I did not find a remaining correctness or regression issue that warrants a new inline comment.

Missing context / blind spots
  • ⚠️ I could not run a local end-to-end repro or startup benchmark in this workspace because there is no built clickhouse binary available here.
  • ⚠️ The GitHub checks were still incomplete while reviewing (Build (arm_tidy) and the aggregate PR check were pending), so this review does not incorporate their final results.
Final Verdict

✅ No new findings on the current head.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.20% 87.20% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.30% 79.30% +0.00%

Changed lines: Changed C/C++ lines covered: 169/170 (99.41%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Aug 19, 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.

Ok. However, an interactive client requests system.comptetions immediately. Just a note, because the startup of the interactive client is not a concern.

@alexey-milovidov alexey-milovidov self-assigned this Aug 19, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

Also, I'm planning to make clickhouse-local with a real path by default (it will be something like a share-dir/clickhouse-local) for better UX. If it defies your changes due to the system database being physical, we should rethink.

@thevar1able
thevar1able marked this pull request as draft August 19, 2026 18:58
`04516_user_query_log_local` checks that `clickhouse local` rejects
`query_log.table = user_query_log` right away, but the check lived inside
`attachSystemTablesServer`, which this branch defers until the first access to
the `system` database. `clickhouse local --query "SELECT 1"` only resolves
`system.one`, so the bad configuration was silently accepted.

Split the check out as `validateUserQueryLogConfig` - it inspects the
configuration rather than the database - and call it eagerly at both
`clickhouse local` call sites that defer the system tables.
Comment thread programs/local/LocalServer.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 709.96 MiB 706.93 MiB -3.03 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

69 translation units recompiled, 621 s compile time in total, 69 of them have a recent master baseline.

Symbol sizes
Binary Symbol Master PR Δ
programs/clickhouse DB::attachSystemTablesServer(std::__1::shared_ptr<DB::Context const>, DB::IDatabase&, bool, bool) 274.74 KiB removed -274.74 KiB (-100.00%)
programs/clickhouse DB::attachSystemTablesServerExceptOne(std::__1::shared_ptr<DB::Context const>, DB::IDatabase&, bool… new 272.20 KiB +272.20 KiB

Job report

@thevar1able
thevar1able marked this pull request as ready for review August 20, 2026 16:02
thevar1able and others added 2 commits August 20, 2026 18:05
`clickhouse local --path` loads a `system` database from disk when the path
holds one, as a running server leaves behind, and until now that path attached
all the system table storages eagerly, so the deferral only applied to the
ephemeral `system` database that `clickhouse local` creates on its own.

Arm the deferred population for the database loaded from disk too: the tables
that come from disk stay attached and visible, and the system table storages are
added on top of them on the first access to the database.

The collision checks that `attachSystemTablesServer` runs before it attaches
`system.user_query_log` move into `validateSystemUserQueryLog`, which now covers
the pre-existing-table check as well - it is the one that matters for a database
loaded from disk - and runs before the population is armed, so that the
existence check does not trigger it.

The on-disk database engines reach the table list through a few accessors of
their own, so those get the `ensurePopulated` hook as well:
`DatabaseOrdinary::getAllTableNames` reads `tables` directly, and
`DatabaseAtomic::detachTable` does not go through
`DatabaseWithOwnTablesBase::detachTable`. `DatabaseOnDisk::createTable` gets it
so that a `CREATE TABLE system.<name>` colliding with a not-yet-attached system
table fails at `CREATE` time, rather than throwing `TABLE_ALREADY_EXISTS` from
an unrelated later query.
`RENAME TABLE ... TO system.numbers` reached the rename path in `DatabaseAtomic` and `DatabaseOnDisk` without
the destination database ever being asked for its full table list: the target-name checks there look at
metadata files only, and a deferred `system` database keeps its reserved names in the not-yet-attached
populator. `InterpreterRenameQuery` does call `assertTableDoesntExist`, which forces population, so the
user-facing behaviour was already correct, but the invariant "anything that inspects the table list sees a
populated database" did not hold for the rename entry points themselves.

Populate the source and the destination at the start of both rename implementations - before the source table
is detached, so a collision can no longer be discovered halfway through the `Ordinary` rename - and cover
`RENAME` into a reserved `system` name, for both the persistent and the ephemeral `system` database, in
`05023_local_system_database_on_disk_deferred`.
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Addressed the AI review blocker in 2f31c32: DatabaseAtomic::renameTable and DatabaseOnDisk::renameTable now populate the source and the destination database up front, before the source table is detached, so a deferred system database owns its reserved names for RENAME/EXCHANGE as well and the Ordinary path can no longer discover the collision halfway through. 05023_local_system_database_on_disk_deferred covers RENAME TABLE ... TO system.numbers for both the persistent (--path) and the ephemeral system database, and checks that the rejected source table survives.

The only red check, Stress test (amd_debug), is the unrelated known Logical error: 'Equal values are not contiguous within the range assumed to be sorted' in the merging sorted transform (ColumnVector::getEqualRangeEndAssumeSorted from SortCursor), which hit 20 different pull requests and master on 2026-08-20 alone. Tracked in #115455.

Comment thread programs/local/LocalServer.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

Release-transition baseline: compared against the last 26.8 master because no 26.9 master baseline exists at or before the trusted base-commit anchor.

This PR only changes clickhouse-local startup, deferring system and information_schema table population until first access; it does not touch the server's query-execution hot path that ClickBench and TPC-H exercise. Both flagged ClickBench queries (Q16 at +11.1%, Q28 at -6.5%) landed as not_sure, and neither can plausibly be attributed to this change, so they read as run-to-run variance rather than real deltas. tpch_adapted_1_official showed nothing flagged. No action needed on this PR from a performance standpoint.

clickbench

⚠️ 2 inconclusive

Flagged queries (2 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 16 not_sure 620 689 +11.1% 0.0001 This PR only defers system-table population during clickhouse-local startup; a ClickBench Q16 SELECT never runs that path, so the +11.1% is off-path run-to-run variance, not a PR effect.
⚠️ 28 not_sure 1125 1052 -6.5% <0.0001 Same off-path reasoning: the clickhouse-local startup change cannot touch Q28's execution, and the two tests disagree, so the -6.5% is noise, not a real improvement.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. 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: 9355f317-559f-4610-8572-66665f5cc026
  • MIRAI run: 462b4c2d-ce1a-44e5-b403-025efcb209cf
  • PR check IDs:
    • clickbench_319875_1787664160
    • clickbench_319887_1787664160
    • clickbench_319893_1787664160
    • tpch_adapted_1_official_319906_1787664160
    • tpch_adapted_1_official_319932_1787664160
    • tpch_adapted_1_official_319946_1787664160

…the path

`DatabaseWithOwnTablesBase::isTableExist` and `tryGetTableNoWait` answer from the
already attached tables without running the deferred population, which is what
keeps `system.one` from dragging in the whole `system` database. For a `system`
database loaded from a `--path` that fast path also covered the tables the path
stores, so a stored `system.settings` (or any other name a later version gave to
a system table) was returned instead of the system table, while the eager
attachment it replaces reports `TABLE_ALREADY_EXISTS` at startup.

`setDeferredPopulation` now remembers the names attached before it was armed, and
a lookup of one of them populates the database first, so the collision is
reported. A failed population is remembered too and rethrown by every later
`ensurePopulated`, instead of leaving a half-filled database behind.

`system.one` is attached after the population is armed, so that it is not taken
for such a name, and `validateSystemUserQueryLog` runs before, so that its
existence check does not trigger what it is supposed to precede.
Comment thread src/Databases/DatabasesCommon.cpp Resolved
A failed deferred population leaves `has_deferred_population` set so that
`ensurePopulated` rethrows the saved error, but the lock-free fast path in
`tryGetTableNoWait` and `isTableExist` only consulted the shadowing
candidates: a table the populator managed to attach before it threw (such
as `system.numbers` before a `system.settings` collision), or the eagerly
attached `system.one`, kept being served, exposing an observably
half-populated database. Remember the failure in an atomic flag and route
every lookup through `ensurePopulated` once it is set.
…ation test

The `--path` coverage only staged an `Ordinary` `system` database, while
a running server leaves behind an `Atomic` one, and the deferred
population touches `DatabaseAtomic::detachTable` and
`DatabaseAtomic::renameTable` specifically. Stage an `Atomic` persistent
`system` database (created under a staging name and renamed on disk,
since the database metadata file stores a placeholder instead of the
name) and repeat the reserved-name `CREATE`/`RENAME` collision cases and
the stored-table shadowing cases on it.

Co-Authored-By: Claude Fable 5 <[email protected]>
StoragePtr tryGetTableNoWait(const String & table_name) const;

private:
mutable std::atomic<bool> has_deferred_population{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.

The implementation is complex, especially here, but acceptable.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 28, 2026
Merged via the queue into master with commit 2e619bf Aug 29, 2026
694 of 700 checks passed
@alexey-milovidov
alexey-milovidov deleted the cli-startup-deferred-system-tables branch August 29, 2026 00:03
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

3 participants