Skip to content

Reduce profile-counter memory with hot/cold storage at every level - #118532

Open
qoega wants to merge 39 commits into
ClickHouse:masterfrom
qoega:codex/compact-query-counters-draft-2026-09-07
Open

qoega wants to merge 39 commits into
ClickHouse:masterfrom
qoega:codex/compact-query-counters-draft-2026-09-07

Conversation

@qoega

@qoega qoega commented Sep 7, 2026 •

Copy link
Copy Markdown
Member

Store ProfileEvents in inline hot counters and lazy 32-counter pages at every level. Keep error/cleanup events resident. Query-owned backing stays query/user-accounted; persistent worker, user and global backing uses global accounting. Cold updates contribute to usage without enforcing memory limits synchronously.

Cache completed page reservations while still traversing current parents, avoiding repeated all-CPU scans. Add warmed benchmarks for actual compression timers and exclusive/shared parts locks. Before/after timings remain pending. The bitmap fits existing padding in the measured 64-bit row layout: 1,728 B before and after.

At 094b2332c6f3, storage CI retained 15,400 B more: 60 cold pages (15,360 B) plus 40 B elsewhere. Initial thread backing is filtered out and static storage is absent, so this is not a net-footprint comparison. The failure remains unresolved; filters and thresholds are unchanged. Earlier focused benchmarks showed ~9% more writer CPU; no net performance win is claimed.

All 17 allocation-interceptor tests, including the three accounting tests, passed in non-sanitized amd_debug at 094b2332c6f3. The process later aborted in the timer test because throwing occurred inside an allocation-denied scope; the guard now covers cleanup only. New cache tests cover concurrent reservations, reset, move and reparenting. Current-head runtime validation is pending; local checks cover source invariants, formatting and field layout only. Dev SSH was unreachable and the local build configuration is stale.

Related: #129357
Related: #121545

Memory report: https://s3.amazonaws.com/clickhouse-test-reports/PRs/118532/094b2332c6f3cad31c74fdfd771ea867d5ce058e/pr/storage_memory_check/storage_memory_report.html

Changelog category (leave one):

  • Improvement

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

Store profile counters in inline hot storage and lazy cold pages to reduce backing memory when few events are used. Cold updates can allocate, and fully populated storage can use more memory. Query-owned backing remains query-accounted; required error and cleanup counters are reserved before use.


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

Keep the ordinary build on its original dense source path. Enable the
process-counter prototype only through an explicit research build option,
with a public functional-trained sample layout and isolated validation.

Document unresolved allocation, signal and lifetime contracts.
@clickhouse-gh

clickhouse-gh Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ecb05e2]

Summary: ❌

job_name test_name status info comment
Performance Comparison (amd_release, master_head, 3/6) FAIL Performance dashboard
low_cardinality_from_json #6 FAIL dashboard
Storage memory check FAIL
02_insert_data.sql FAIL cidb
03_add_secondary_indexes.sql FAIL cidb
05_multiple_tables.sql FAIL cidb
09_cleanup.sql FAIL cidb
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

This PR replaces dense ProfileEvents::Counters backing with hot counters and lazy cold pages at every aggregation level, adds explicit reservations, and caches completed reservations. Reviewed head: ecb05e27843755e7d29eff4a1e7000ee5e30fdf0. Block: first-use counter allocation still introduces process-termination paths during thread startup and cleanup.

Findings

❌ Blockers

  • src/Common/ProfileEvents.cpp:2179: Thread startup must remain exception-safe after launching the worker. ThreadFromThreadPool starts its worker at src/Common/ThreadPool.cpp:908, then publishes the still-cold GlobalThreadPoolThreadCreationMicroseconds and GlobalThreadPoolExpansions. With fresh counter backing, publication can throw std::bad_alloc. The incomplete object's destructor never runs; destroying its joinable std::thread member terminates the process. Make both events resident or reserve their full counter chain before launching the worker. New inline finding.

  • src/Common/ElapsedTimeProfileEventIncrement.h:24: Cleanup still reaches first-use allocation. [dismissed by author -- https://github.com/Reduce profile-counter memory with hot/cold storage at every level #118532#discussion_r4094242557] The broader cleanup finding remains real: FileSegmentsHolder destruction calls reset, which constructs a timer for the cold FileSegmentHolderCompleteMicroseconds even for an empty holder (src/Interpreters/FileCache/FileSegment.cpp:1692,1731). The new timer constructor allocates before the cleanup's catch blocks. PhraseSearchStats also publishes seven cold counters directly from its destructor (src/Storages/MergeTree/MergeTreeReaderTextIndex.cpp:1043). Allocator failure can escape these destructors and terminate the process; suppressing memory-tracker exceptions does not suppress std::bad_alloc. Complete the cleanup reservation audit, including these callers and transferable counter scopes. Retained here without replying to or reopening the dismissed thread.

Missing context / blind spots
  • ⚠️ These failure paths were traced in the current source, without a runtime reproduction. No local build is available, and dedicated current-head unit-test results could not be retrieved. Focused runs covering the paths below would close this gap.
Tests
  • ⚠️ Cover allocation failure around thread startup, proving that counter publication cannot unwind construction with an unjoined worker.
  • ⚠️ Destroy an empty FileSegmentsHolder in a fresh profiling scope under allocation denial, and cover cold phrase-search statistics during teardown. Existing cleanup tests cover other publishers.
  • ⚠️ Report dense-versus-current-head timings for the new warmed compression-timer and parts-lock benchmarks. The reservation cache removes repeated CPU-row scans, but remaining hot-path overhead is unmeasured; the PR still cites an earlier approximately 9% writer-CPU increase. Quantify the memory/CPU tradeoff without requiring a net throughput improvement.
Final Verdict

Status: ❌ Block

Preserve nonallocating publication after worker launch and during cleanup, add focused regression coverage, and supply the pending hot-path measurements.

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Sep 7, 2026
Recognize `ProfileEvents::PagedExperiment` and
`ProfileEvents::PagedExperimentStorage` as namespaces in the event checker.
Use project includes, adjust the standalone include root, and remove an
unused import. Check `close` failures during initialization through the
existing configuration error exit.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/PRs/118532/db233bc80012312a072618b2dede3570e2832d1f/pr/result_style_check.json
Related: ClickHouse#118532
Comment thread src/Common/ProfileEvents.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-logging Logging/monitoring/observability (logs, metrics, tracing, instrumentation). label Sep 7, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

⚠️ Significant changes: symbol sizes.

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.

Object file sizes

163 object files changed (+101.41 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/clickhouse_common_io.dir/Common/ProfileEvents.cpp.o 1.17 MiB 1.19 MiB +20.00 KiB (+1.67%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Median compile-time ratio to the baselines is ×1.06 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +512.2 s (+7%) in total before that adjustment.

Symbol sizes ⚠️
Binary Symbol Master PR Δ
programs/clickhouse ProfileEvents::global_counters_storage 14.69 MiB removed -14.69 MiB (-100.00%)
programs/clickhouse ProfileEvents::Counters::global_storage new 1.69 MiB +1.69 MiB

Job report

Capture the wait duration under the scheduler mutex using a plain
`Stopwatch`, and publish the pending measurement after unlocking. Retain
its `ThreadGroup` through publication.

Keep dequeued requests marked pending until their wait metric is recorded,
then acknowledge callback completion under the mutex. This reuses the
existing cancellation handshake so `free` cannot complete ahead of an
active callback's metric publication.

Run queue-limit failure callbacks outside the queue mutex too, avoiding
lock inversion with cancellation. Finish rejection accounting before
callbacks can release request ownership, and do not count a concurrent
queue drain twice. Add two focused `FifoQueue` regression tests.

Lazy counter allocation can still fail during destructor publication;
this does not resolve the experiment's nonallocating-update contract.

Related: ClickHouse#118532
Review: ClickHouse#118532 (comment)
@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements and removed pr-not-for-changelog This PR should not be mentioned in the changelog labels Sep 7, 2026
Comment thread src/Common/ProfileEvents.cpp Resolved
Add a named-event token and migrate CPU scheduler wait publication. Keep the initial forty-event reservation catalogue independent of the learned hot rank. Extend standalone validation with reservation and allocation-failure cases.
…ogue

Resolve the pinned public event IDs and validate the mandatory CPU, memory-reservation and IO event sets against the shipped rank. Exercise reserved updates and cold-allocation failure at hot budgets 40 and 128; reject insufficient capacity and unsupported catalogue formats.

ClickHouse#118532 (comment)
ClickHouse#118532 (comment)
Mark generated event declarations as used by their trait specializations and register `nonAllocatingEvent` as an API rather than an event name in the existing checker exclusions.

https://github.com/ClickHouse/ClickHouse/actions/runs/34229527818/job/102072421201
ClickHouse#118532
Reject paged process storage before backing allocation, including all-hot configurations. Preserve the standalone paged adapter and add explicit/default dense and paged rejection checks. Update the experiment documentation to distinguish the incomplete named-event subset from the dynamic cleanup contract.

ClickHouse#118532 (comment)
@qoega qoega changed the title Experiment with paged process profile counters Add a paged profile-counter harness and harden scheduler callbacks Sep 8, 2026
@clickhouse-gh clickhouse-gh Bot added comp-scheduler Workload scheduler and resource management: CPU/IO/memory scheduling, concurrency control, worklo... and removed comp-logging Logging/monitoring/observability (logs, metrics, tracing, instrumentation). labels Sep 8, 2026
Enable size-class-aware eager backing in normal jemalloc builds. All counter
cells exist before publication; updates retain their nonallocating contract.
Keep other allocator builds contiguous and select splitting only when the
aligned allocation estimator proves a net memory saving.

Remove the production experiment flag, environment parsing and reservation
API. Replace the standalone research harness in the mergeable diff with
benchmarks of actual `Counters` and regression coverage for all event IDs.
Preserve the research harness and measurements separately.

Add deterministic `CPULeaseAllocation` grant/failure races against `free`
while wait-time publication is outside the scheduler mutex.

ClickHouse#118532 (comment)
ClickHouse#118532 (comment)
ClickHouse#118532 (comment)
@qoega qoega changed the title Add a paged profile-counter harness and harden scheduler callbacks Reduce query and thread profile-counter memory Sep 8, 2026
@qoega
qoega marked this pull request as ready for review September 8, 2026 22:55
The small benchmark link can omit the TLS definition accessed through inline
assembly. Retain the verified symbol in the normal Linux/FreeBSD executable
link so Release/ThinLTO benchmarks run without a manual relink.

Limit the option to the standalone executable; tests-only configurations do
not create that target. Production server link options are unchanged.
@clickhouse-gh clickhouse-gh Bot added comp-logging Logging/monitoring/observability (logs, metrics, tracing, instrumentation). and removed comp-scheduler Workload scheduler and resource management: CPU/IO/memory scheduling, concurrency control, worklo... labels Sep 9, 2026
Keep the intentional moved-from `reset` coverage with a narrow suppression.
Qualify `FifoQueue::purgeQueue` in the destructor to make its existing
base-class dispatch explicit.

Reproduced both diagnostics on the real test translation units and verified
the fixes with the same targeted clang-tidy checks.

ClickHouse#118532
https://s3.amazonaws.com/clickhouse-test-reports/PRs/118532/76ce3ea9e933b06bb98571dab6cbd788629c60aa/pr/build_arm_tidy/build_clickhouse/build_clickhouse.log
@clickhouse-gh

clickhouse-gh Bot commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

Release-transition baseline: compared against the most recent available 26.9 masters at or before the trusted base-commit anchor because no 26.10 master baseline exists there.

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: a5dc0198-586c-4755-bf95-4274d97522a5
  • MIRAI run: dc4840fe-9ded-4969-8b69-c8a1a97655db
  • PR check IDs:
    • clickbench_1858754_1790377153
    • clickbench_1858767_1790377154
    • clickbench_1858773_1790377153
    • tpch_adapted_1_official_1858779_1790377153
    • tpch_adapted_1_official_1858790_1790377153
    • tpch_adapted_1_official_1858825_1790377153

Comment thread src/Common/HTTPConnectionPool.cpp Resolved
Comment thread src/Disks/IO/ThreadPoolReader.cpp Resolved
Replace the integer exception and empty catch with `std::exception` and `EXPECT_THROW`, preserving cleanup under allocation denial while satisfying clang-tidy.

Validation: configured clang-tidy 21 passes on the counter and test translation units; 15 focused debug tests pass with ThinLTO; C++ style check passes.

ClickHouse#118532
https://github.com/ClickHouse/ClickHouse/actions/runs/36160482455/job/108156142362
@clickhouse-gh

clickhouse-gh Bot commented Oct 23, 2026

Copy link
Copy Markdown
Contributor

Dear @Michicosun, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

qoega added 4 commits November 4, 2026 22:34
Keep failed-read metrics hot across all readers. Reserve connection-error
backing before either HTTP connection path. Reserve Keeper server metrics
globally before startup and publish through checked non-allocating updates,
including arbitrary-thread Raft callbacks. Global Keeper exports are retained;
these dispatcher metrics no longer accumulate in unused worker-local counters.

Related: ClickHouse#118532 (comment)
Related: ClickHouse#118532 (comment)
Related: ClickHouse#118532 (comment)
Related: ClickHouse#118532 (comment)
Keep the uncontended path unchanged. Reserve cold wait events before blocking or timed acquisition and use checked non-allocating publication while holding the mutex. Add deterministic tests for acquisition and timeout, including parent accounting.
@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Nov 5, 2026
@CLAassistant

CLAassistant commented Nov 5, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

qoega added 4 commits November 6, 2026 10:53
Keep the global memory-exception guard added to `MetadataOperationsHolder::rollback` while preserving preallocated counter publication.

Related: ClickHouse#118532
Replace the undefined `AdaptiveAggregationSpillBacklogSheds` reference with public `ZooKeeperWatchResponse` in the counter, profiled-lock, and allocation-interceptor tests. The replacement is outside both hot catalogues, preserving cold-page coverage.

The undefined event failed the `unit_tests_dbms` link in debug and sanitizer builds; syntax-only validation cannot detect it.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118532&sha=b0cec097ad9b30984f74c9d5e806b9673a277a4d&name_0=PR

Related: ClickHouse#118532

Build logs: https://github.com/ClickHouse/ClickHouse/actions/runs/41965702189/job/127048833325 https://github.com/ClickHouse/ClickHouse/actions/runs/41965702189/job/127048833416
The storage-memory profile shows a cold page allocated from `MemoryTracker::settleDriftOnQueryEnd` during `ThreadGroup` destruction. Keep both drift events in resident storage and use checked nonallocating publication: cleanup may run on a different thread than construction.

Add a cross-thread cleanup test that verifies nested scope accounting and settles synthetic drift while allocations are denied.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118532&sha=409f5e091ab2797a8252164c71906d43fc4f1e8e&name_0=PR

Memory report: https://s3.amazonaws.com/clickhouse-test-reports/PRs/118532/409f5e091ab2797a8252164c71906d43fc4f1e8e/pr/storage_memory_check/storage_memory_report.html

Related: ClickHouse#118532
Comment thread src/Common/ProfileEvents.cpp Resolved
Separate backing memory tracking from the aggregation level. Default thread/process counters use the active trackers; persistent ThreadStatus worker backing explicitly uses global accounting. Preserve that policy across row/page allocation, moves, and destruction.

Add real ProfileEventsScope and moved-part attribution checks for query/user charges and balanced destruction. Keep cold-update memory-limit exception suppression while restoring accounting.

Review: ClickHouse#118532 (comment)

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118532&sha=44ffac3f765c8d3cf6b7b1397899f9c8a5f0ba75&name_0=PR

Related: ClickHouse#118532
Keep per-endpoint expired-connection accounting in `HTTPConnectionPool`
while retaining checked nonallocating counter publication.

Related: ClickHouse#118532
Preserve the query-owned backing policy and nonallocating publishers.

Related: ClickHouse#118532
Keep `AmberConnectionsReset`, `AmberConnectionsPreserved`, and
`AmberConnectionsExpired` resident for HTTP cleanup on arbitrary threads.
Mark `NonAllocatingEvent::value` as `[[nodiscard]]` for the newly enabled
clang-tidy rule.

Validation: source invariants and isolated accessor tidy check passed.
No full compile or accounting runtime test was performed after this merge.

Related: ClickHouse#118532
Comment thread src/Common/ProfileEvents.cpp Resolved
Preserve both the new upstream thread-profile-events test and the
profile-counter reservation/accounting tests.

Related: ClickHouse#118532
Scope `DENY_ALLOCATIONS_IN_SCOPE` to the timer cleanup callback so throwing
the test exception can allocate its runtime object. Verify the callback
runs while an exception is unwinding.

The previous CI process aborted in `ColdTimerPreparesBeforeCleanup` after
all allocation-interceptor tests had passed. New runtime validation is
pending; local source and format checks passed.

Related: ClickHouse#118532
CI: https://github.com/ClickHouse/ClickHouse/actions/runs/43977464930/job/133706106555
Publish a reservation bitmap after every CPU row owns a page. Warm calls
check one bit per counter instance while still traversing current parents.
Keep the bitmap with backing so moves and resets retain reservations.

Add concurrency and parent-change tests and warmed benchmarks using the
actual compression timer and exclusive/shared parts locks through the
four-level sharded hierarchy. The current 64-bit row layout remains 1728 B.

Source and layout checks passed; new full-runtime tests and performance
measurements remain pending because dev was unreachable and the local
build configuration was stale.

Review: ClickHouse#118532 (comment)
Related: ClickHouse#118532
std::optional<MemoryTrackerBlockerInThread> blocker;
if (tracking == MemoryTracking::Global)
blocker.emplace(VariableContext::Global);
auto fresh = std::make_unique<Count[]>(cold_page_size);

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.

[Blocker] Reserve global thread-startup counters before launching the worker

GlobalThreadPoolThreadCreationMicroseconds and GlobalThreadPoolExpansions are still cold. ThreadPoolImpl::ThreadFromThreadPool publishes them at src/Common/ThreadPool.cpp:910-914, after starting its worker at line 908. In a fresh counter scope, either publication can now reach this allocation. If it throws std::bad_alloc, construction unwinds without calling ThreadFromThreadPool's destructor, so its live std::thread member is destroyed without being joined and terminates the process. LockMemoryExceptionInThread suppresses tracker exceptions, but cannot prevent allocator failure.

Please make these events resident or reserve their complete counter chain before starting the worker, and add focused coverage of allocation failure around thread startup. Reserving only the lock-wait and shrink events does not protect this construction path.

This branch has not been deployed

No deployments
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). pr-improvement Pull request with some product improvements pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants