Skip to content

Remove the per-call metadata copy in debug and sanitizer builds - #125697

Merged
Algunenano merged 3 commits into
ClickHouse:masterfrom
groeneai:share-column-asts-in-readonly-metadata-copies
Oct 15, 2026
Merged

Algunenano merged 3 commits into
ClickHouse:masterfrom
groeneai:share-column-asts-in-readonly-metadata-copies

Conversation

@groeneai

@groeneai groeneai commented Oct 13, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #124016

Changelog category (leave one):

  • CI Fix or Improvement (changelog entry is not required)

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

Debug and sanitizer builds no longer copy the table metadata on every MergeTreeData::getInMemoryMetadataPtr call, which makes the system.dashboards queries over the bucketed system.metric_log about 18% faster in a debug build.

Description

03540_system_dashboards hit the 600 s per-test timeout on master in Stateless tests (amd_tsan, s3 storage, sequential, 1/2) (report). Since the bucketed system.metric_log schema became the default (#124016), the test is about 2x slower on every debug and sanitizer lane.

In debug and sanitizer builds MergeTreeData::getInMemoryMetadataPtr returned a deep copy of the metadata on every call, so that a reference kept after its metadata pointer was dropped became a use-after-free under ASan. The bucketed schema has ~2200 ALIAS columns, so every copy cloned and destroyed thousands of default expression ASTs. This removes the copy, so debug and sanitizer builds behave like release here. The copy was added together with StorageMetadataHandle in #106200; the handle still rejects the common misuse, a reference taken through a temporary handle, at compile time.

Validation: the test's 498 dashboard queries in clickhouse local (debug, min of 2 runs, same base): bucketed schema 24.6 s -> 20.1 s, wide schema 13.4 s -> 12.0 s, no errors. The separate cost of clusterAllReplicas dashboards reading the whole metrics map on S3 lanes (#114174) is not addressed here.

🤖 Generated with Claude Code


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

Version info

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

groeneai and others added 2 commits October 13, 2026 20:04
Copying a `ColumnDefault` deep-clones its expression AST, and copying a
`ColumnDescription` also clones its codec and TTL ASTs. With the bucketed
`system.metric_log` schema (the default since ClickHouse#124016) the table has ~2200
`ALIAS` columns, and every metadata copy clones and later destroys all of
their ASTs. A `system.dashboards` query copies that metadata many times:
in debug and sanitizer builds `MergeTreeData::getInMemoryMetadataPtr`
returns a fresh copy on every call (to catch lifetime bugs), and
`StorageMerge::getInMemoryMetadataPtr` / `StorageMaterializedView::getInMemoryMetadataPtr`
copy it on every call through `withVirtuals`. Under ASan the clones were 39%
of the CPU of the test's queries, and `03540_system_dashboards` doubled its
runtime on every debug and sanitizer lane and hit the 600 s timeout on
amd_tsan with s3 storage.

Add `StorageInMemoryMetadata::copySharingColumnASTs` (backed by
`ColumnsDescription::copySharingASTs`, a tagged `ColumnDescription`
constructor and `ColumnDefault::copySharingExpression`): the copy has its own
metadata, columns description and column descriptions, and shares only the
immutable ASTs. Use it at the three read-only per-call sites. It never goes
through `ColumnsDescription::add`, whose function name normalizer modifies
the AST in place. The copy constructor and assignment still deep-copy, so
every mutable copy (ALTER, CREATE AS, ...) keeps owning its ASTs. In debug
builds the lifetime check still returns a distinct metadata object per call;
only a dangling reference into a column AST is no longer caught by it.

Also add an rvalue `IStorage::setInMemoryMetadata` overload and move the
local metadata in the `Merge`, `Distributed` and `Dummy` constructors. The
`Distributed` constructor reads the columns for the sharding key after
setting the metadata, so it now reads them from its `columns_` argument,
which is what the metadata was built from.

Measured on the test's 498 dashboard queries in `clickhouse local` (debug
build): bucketed schema 25.2 s -> 20.6 s, wide schema unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
read-only per-call copy, and extend the unit test to the codec, TTL and
metadata-level copies.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Oct 13, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; round 1: 3 findings, round 2 re-review of ccd019bd26a19: 0 findings) plus my own review (2 nits).

# Sev Finding Verdict Evidence / action
1 ⚠️ StorageProxy::getStorageSnapshot still deep-copies the column ASTs through withVirtuals (StorageProxy.h:69) AGREE, fixed @ ccd019bd26a19 same sharing copy + setVirtuals as StorageMerge / StorageMaterializedView
2 ⚠️ the unit test does not check codec / TTL sharing or the metadata-level copy AGREE in part, fixed @ ccd019bd26a19 codec, TTL and StorageInMemoryMetadata::copySharingColumnASTs asserts added; no per-storage wiring test (the wiring is the measured runtime)
3 ⚠️ the TSan / S3 timeout is not verified locally DISAGREE the PR claims only the debug measurement and leaves the S3 clusterAllReplicas cost out (#114174); this PR's own CI runs the test on that lane
4 💡 ColumnsDescription::getDefault still clones the expression to read the kind (QueryAnalyzer.cpp:5281, StorageMerge::supportedPrewhereColumns) noted, not blocking same cost class, outside this change

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding.

Session id: cron:clickhouse-review-slot-9:20261013-214400

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. The test's 498 dashboard queries in clickhouse local (debug, CI-like metric_log): bucketed schema 25.2-26.0 s vs wide 13.5-13.8 s on master, 3 runs each.
b Root cause explained? The bucketed schema has ~2200 ALIAS columns; copying ColumnDefault deep-clones the expression AST, and every query copies the metadata many times (debug/sanitizer per-call copy in MergeTreeData::getInMemoryMetadataPtr, per-call withVirtuals copies in StorageMerge/StorageMaterializedView). Under ASan the clones were 39% of query CPU.
c Fix matches root cause? Yes. The read-only copies share the immutable column ASTs instead of cloning them; no test-side timeout, tag or bound change.
d Test intent preserved / new tests added? The test is unchanged. New gtest ColumnsDescriptionTest.CopySharingASTs: the sharing copy shares the default, alias, codec and TTL ASTs, the regular copy does not.
e Both directions demonstrated? Yes. Same probe, base vs fix: bucketed 25.16 s -> 20.59 s (0.82x), wide 13.53 s -> 13.78 s (noise), 0 query errors in every run.
f Fix is general across code paths? All four per-call read-only copy sites (MergeTreeData, StorageMerge, StorageMaterializedView, StorageProxy::getStorageSnapshot); the other overrides forward without a copy; mutable copies keep the deep copy.
g Fix generalizes across inputs (params/datatypes/wrappers)? Default, materialized, alias and ephemeral expressions, codec and TTL ASTs are all shared by the same rule; no type-dependent logic. Tables without such columns are unaffected (wide schema unchanged).
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or on-disk change.
i Invariants and contracts preserved? Shared ASTs are never modified: sharing copies are const metadata handles (release builds already share one object), IAST refcounting is atomic, mutable copies still clone. 557 + 123 related stateless tests: no failure absent on master, with and without randomized settings.

Session id: cron:clickhouse-impl-slot-5:20261013-210200

@clickhouse-gh

clickhouse-gh Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2ce3b29]

Summary: ✅


AI Review

Summary

PR #125697, reviewed at 2ce3b29394f7ab03305a00e2ae6a11d814d7d334, removes the per-call metadata deep copy from MergeTreeData::getInMemoryMetadataPtr in debug and sanitizer builds. This deliberately drops the extra lifetime diagnostic and uses the existing release behavior. The PR reports dashboard-query timings improving from 24.6 s to 20.1 s in a debug build. No actionable findings remain in the current diff or prior discussion.

Missing context / blind spots
  • ⚠️ Sanitizer validation for the current head is still pending in the Praktika report. Completed sanitizer results, including 03540_system_dashboards on the affected TSan/S3 lane, would confirm the end-to-end CI impact; the reported debug measurements were not independently reproduced during this review.
Final Verdict

Status: ✅ Approve. No code changes requested.

@clickhouse-gh clickhouse-gh Bot added pr-ci comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Oct 13, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - ccd019b

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Build (arm_tidy, 1/4) / (no test row) infra, not from this PR: the host Docker daemon died mid-build (error waiting for container: unexpected EOF, exit code 125), no clang-tidy diagnostic, never re-run (see below) a fix task is created (fixing-PR link to follow here)

Three Build (arm_tidy, *) jobs failed in attempt 1, during the 22:00Z hour in which Build jobs errored on 71 PRs. The automatic retry re-ran one of them per attempt (3/4, then 2/4, both green) and has not re-run 1/4; the run is at attempt 3. That failure dropped 97 dependent jobs, so only Fast test and Style check have results on this head. The retry policy for this case is asked of the CI owner in #122501. Mergeable Check and PR are the rollups of this row.

Session id: cron:our-pr-ci-monitor:20261014-030009

@Algunenano Algunenano self-assigned this Oct 14, 2026
/// The column ASTs are shared, the metadata and column descriptions are still distinct objects.
#if defined(DEBUG_OR_SANITIZER_BUILD)
return std::make_shared<StorageInMemoryMetadata>(*base);
return std::make_shared<StorageInMemoryMetadata>(base->copySharingColumnASTs());

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.

Isn't it simpler to remove this instead if it's no longer useful? Adding 150 lines of code to avoid a perf issue in sanitizers isn't really something I feel inclined to do

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Agreed, and removing it is also faster. Same base, debug clickhouse local, the test's 498 dashboard queries (sum of durations, min of 2 runs):

  • bucketed schema: 24.6 s on master, 21.5 s with the AST sharing, 20.1 s with the copy removed
  • wide schema: 13.4 s, 13.2 s, 12.0 s

I reduced the PR to removing the copy in 2ce3b29, which reverts the AST sharing; the diff is now MergeTreeData.cpp only.

On whether it is still useful: it was added in #106200 to find metadata lifetime misuse, together with StorageMetadataHandle, which already rejects the common case (dereferencing a temporary handle) at compile time. I did not find a later fix that came from the copy. @Michicosun, are you OK with dropping it?

`MergeTreeData::getInMemoryMetadataPtr` deep-copied the whole
`StorageInMemoryMetadata` on every call in debug and sanitizer builds, so
that a reference kept after its metadata pointer was dropped became a
use-after-free under ASan. With the bucketed `system.metric_log` schema
every copy clones thousands of `ALIAS` default ASTs, a large part of why
`03540_system_dashboards` is slow on the sanitizer lanes.

The copy was added together with `StorageMetadataHandle` in ClickHouse#106200, and
the handle already rejects the common misuse, a reference taken through a
temporary handle, at compile time. Removing the copy is simpler than
making it cheaper, so this drops it and reverts the AST-sharing copies of
the previous two commits, as asked in review.

Dashboards probe (debug, 166 dashboards x 3 variants, sum of query
durations, min of 2, same base):
- bucketed: base 24.57 s, AST sharing 21.50 s, copy removed 20.06 s
- wide:     base 13.36 s, AST sharing 13.23 s, copy removed 11.99 s

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai changed the title Share column ASTs in read-only copies of table metadata Remove the per-call metadata copy in debug and sanitizer builds Oct 14, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 14, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 2ce3b2939 with master a48b12b37 (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

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

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

Job report

@Algunenano
Algunenano added this pull request to the merge queue Oct 15, 2026
Merged via the queue into ClickHouse:master with commit f50402e Oct 15, 2026
177 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 15, 2026
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 comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-ci 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