Skip to content

Apply *WithMemoryTracking containers to Compression, Daemon, IO, Loggers, QueryPipeline, TableFunctions - #105580

Merged
nickitat merged 24 commits into
masterfrom
wmt_others
May 27, 2026
Merged

nickitat merged 24 commits into
masterfrom
wmt_others

Conversation

@nickitat

@nickitat nickitat commented May 21, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

Note

Medium Risk
Touches many hot-path components (compression, IO, query pipeline, S3, logging) by changing container types and some public function signatures, which could cause subtle perf/behavior regressions or downstream compile breaks.

Overview
This PR broadens the project’s memory-limit safety work by replacing many std::vector/std::map/std::deque/std::list/std::unordered_* usages across Compression, Daemon, IO, Loggers, QueryPipeline, and TableFunctions with their *WithMemoryTracking aliases (and core aliases like Strings, NameSet, NameToNameMap).

It also updates several APIs and internal data structures accordingly (e.g., archive readers’ getAllFiles(), pipeline/chain builders, S3 helpers, insert/view pipeline wiring), adds QueueWithMemoryTracking, and tightens the C++ style check to lint more directories and ignore commented-out std-container matches.

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

Version info

  • Merged into: 26.6.1.207

nickitat and others added 17 commits May 21, 2026 13:56
Swap std::vector, std::map, std::set, std::unordered_map, std::list to the
corresponding *WithMemoryTracking aliases in src/Compression. Mark a few
spots as STYLE_CHECK_ALLOW_STD_CONTAINERS where the type is bound to
IFactoryWithAliases::InnerMap covariance or referenced in a documentation
comment block. Add src/Compression to the directories linted by
check_cpp.sh.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Swap `BaseDaemon::graphite_writers` (`std::map`) to `MapWithMemoryTracking`,
local `fds` (`std::vector`) and `GraphiteWriter::KeyValueVector` (`std::vector`)
to `VectorWithMemoryTracking`. Add `src/Daemon` to the directories linted
by `check_cpp.sh`.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Swap `AsyncLogQueueSizes` alias (`std::vector`) and `OwnAsyncSplitChannel`
members (`std::map`, `std::deque`, `std::vector`) to the corresponding
`*WithMemoryTracking` aliases. Locals in `Loggers.cpp` bound to
`Poco::Logger::names(std::vector<std::string> &)` use the `Strings`
alias since the underlying type matches. Add `src/Loggers` to the
directories linted by `check_cpp.sh`.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…liases

Convert the `ITableFunction::skipAnalysisForArguments` virtual to return
`VectorWithMemoryTracking<size_t>` and cascade through all overrides
(`TableFunctionMerge`, `TableFunctionURL`, `TableFunctionObjectStorage`,
`TableFunctionExplain`, `TableFunctionExecutable`, `TableFunctionView`,
`TableFunctionViewIfPermitted`, `TableFunctionMergeTreeAnalyzeIndexes`),
`TableFunctionNode::resolve` and the `unresolved_arguments_indexes`
member it stores. Mark `IFactoryWithAliases::InnerMap` cases and the
`getVirtualsToCheckBeforeUsingStructureHint` chain (binds to `NameSet`
in `ITableFunctionFileLike`) with `STYLE_CHECK_ALLOW_STD_CONTAINERS`.
Cross-subsystem updates: `Storages::NamedCollectionsHelpers::complex_args`,
`Storages::VectorSearchParameters::reference_vector`,
`Storages::StorageExecutable::input_queries`,
`Processors::useVectorSearch::reference_vector`. Add `src/TableFunctions`
to the directories linted by `check_cpp.sh`.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…iases

Mark widely-used base aliases (`Processors`, `Pipes`, `OutputPortRawPtrs`,
`StorageLimitsList`) with `STYLE_CHECK_ALLOW_STD_CONTAINERS` since they
appear in 1000+ files. Convert other locals and members to
`*WithMemoryTracking` aliases: `BlockIO` 4 vector members,
`QueryPlanResourceHolder` 6 vector members, `Pipe::set`,
`QueryPipeline::processors`/`limit_candidates`/`visited`,
`QueryPipelineBuilder` locals (`addChains` param, `joins`,
`delayed_ports_numbers`, etc.), `printPipeline::pointer_to_id`,
`printPipeline::Edge`/`Node::edges`/`agents`/`graph`/`steps_map`,
`narrowPipe::Distribution`/`partitions`,
`RemoteQueryExecutor::setPartUUIDs` (now `UUIDs`),
`local_granted_roles` (now `Strings`).

Cross-subsystem cascades: `DelayedPortsProcessor::delayed_ports`,
`IQueryPlanStep::QueryPipelineBuilders` alias,
`InsertDependenciesBuilder::createChainWithDependenciesForAllStreams`
return type and locals, `ProcessorsProfileLog::getProcessorsProfileLogInfo`/
`logProcessorProfile`, `StorageMerge::pipelines`,
`executeQuery::processors_profile_infos`.

Add `src/QueryPipeline` to the directories linted by `check_cpp.sh`.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Convert `IArchiveReader::getAllFiles` virtual to return `Strings`
across `ZipArchiveReader` and `LibArchiveReader`. Convert
`SeekableReadBuffer::readBigAtRetainCells` virtual to return
`VectorWithMemoryTracking<CachedRegion>` and cascade through
`CachedInMemoryReadBufferFromFile`. Convert class aliases
(`ConcatReadBuffer::Buffers`, `CascadeWriteBuffer::WriteBufferConstructors`/
`WriteBufferPtrs`, `ForkWriteBuffer::WriteBufferPtrs`, `PackedFilesIO::Index`,
`OpenedFileCache::Files`) and members (`WriteBufferFromS3` deque members,
`ParallelReadBuffer::read_workers`, `PackedFilesWriter` members,
`ConcatReadBufferFromFile::buffers`, `S3AuthSettings::users`,
`ZipArchiveReader::free_handles`) to `*WithMemoryTracking` aliases.

Mark template helpers in `WriteHelpers.h`/`ReadHelpers.h` (already
allocator-templated, work with both `std::vector` and
`VectorWithMemoryTracking`), AWS-SDK-bound types (`std::map<String, String>`
S3 object metadata, `std::vector<Aws::String>` AWS API params,
`std::optional<std::map<String, String>>` widely-used in `copyS3File`,
`Aws::S3::Model::ObjectIdentifier` locals, `Aws::Utils::StringUtils::Split`
locals), Azure SDK bindings, and the widely-used `HTTPHeaderEntries`
alias (39 files) with `STYLE_CHECK_ALLOW_STD_CONTAINERS`.

Cross-subsystem updates: `Disks::DiskObjectStorageTransaction::writers`,
`Interpreters::AsynchronousInsertQueue` `ConcatReadBuffer::Buffers` local,
`Processors::Transforms::getSourceFromASTInsertQuery` same,
`Client::ClientBase::out_file_buf` `ForkWriteBuffer::WriteBufferPtrs`.

Add `src/IO` to the directories linted by `check_cpp.sh`.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
This removes the only `STYLE_CHECK_ALLOW_STD_CONTAINERS` marker
on this branch that existed solely because `Common/` was missing
a `QueueWithMemoryTracking` alias. All other markers cover
external SDK bindings, widely-used aliases, or virtual API
surface — they are not for missing alternatives.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Use `Strings` alias for `block_ids` (identical to `std::vector<std::string>`
that the Azure SDK `CommitBlockList` expects), and `ListWithMemoryTracking`
for the private `bg_tasks` list — none cross an external API boundary that
requires the literal `std::list` type.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
`Strings` is `std::vector<std::string>`, identical to `Aws::Vector<Aws::String>`
(`Aws::Allocator` is `std::allocator` in our build) and to
`Poco::Util::AbstractConfiguration::Keys`. Replacing the literal
`std::vector<String>` with the alias drops 5 lint markers without
changing behavior or signatures.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
`NameSet` and `NameToNameMap` (from `Core/Names.h`) are identical
typedefs to the std types they replace, so this is a pure rename
that hides the literal `std::unordered_{set,map}<...>` from the lint
without changing any signatures or behavior.

- `ITableFunction::getVirtualsToCheckBeforeUsingStructureHint` and
  its override in `TableFunctionObjectStorage` now return `NameSet`
  (matches the existing `ITableFunctionFileLike` override).
- `AggregateFunctionFactory::ActionMap`, `S3 URI::modifyURI` parameter
  and `mapper`, `ClientCache::region_for_bucket_cache`,
  S3RequestSettings storage_class_names, fuzzer settings, gtest
  fixture all switched to the aliases.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Internal buffers/locals that never cross an external API boundary
are switched to `VectorWithMemoryTracking`, dropping 5 lint markers:

- `PocoHTTPClient.cpp`: 8 KiB manual-copy buffer between Azure body
  stream and Poco request stream.
- `examples/parse_int_perf.cpp`: benchmark `data`, `data2`, `formatted`
  (plus the matching `WriteBufferFromVector` template argument).
- `examples/zlib_ng_bug.cpp`: 1 MiB in/out buffers for the zlib-ng
  bug reproducer.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
`ObjectAttributes` (≡ `std::map<std::string, std::string>`) was
duplicated between `IO/S3/getObjectInfo.h` and the Disks headers,
and 10 sites in `WriteBufferFromS3` and `copyS3File` spelled the
type out as `std::optional<std::map<String, String>>` (with marker)
because they didn't include `getObjectInfo.h`.

Move the alias to `IO/S3Settings.h` (already transitively included
by all four files via the `S3RequestSettings` chain) and drop the
duplicate from `getObjectInfo.h`. The 10 marker sites switch to
`std::optional<ObjectAttributes>`, leaving a single marker on the
alias declaration.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
`tag_loggers`, `client_caches`, `uri_for_bucket_cache`, the
credentials LRU queue/map, and the `deleteFileFromS3` removed-keys
set are all internal-only caches/locals that never cross an
external API boundary. Replace each `std::list`/`std::unordered_map`/
`std::unordered_set` with the corresponding `*WithMemoryTracking`
alias and drop the lint markers.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
- `S3SettingsByEndpoint::s3_settings` (the per-endpoint settings
  cache) → `MapWithMemoryTracking`.
- `replaceHeadersFromS3ForGCS` local `new_meta_headers` →
  `VectorWithMemoryTracking`.
- `deleteFilesFromS3` `file_sizes_for_blob_storage_log` parameter
  → `VectorWithMemoryTracking<size_t>` (cascades to the single
  caller in `S3ObjectStorage::removeObjectsImpl`).
- `getRunningAvailabilityZone` local `az_getters` →
  `VectorWithMemoryTracking`.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The lint at `check_cpp.sh:08` flagged any line in the linted
directories containing `std::vector<` (and friends), including
lines that were entirely inside C++ comments — like the docstring
in `IO/BufferWithOwnMemory.h:31` (\`Replacement for std::vector<char>
to use in buffers.\`). The marker noise on those lines was a false
positive.

Filter out lines whose source text (after `filename:lineno:`)
starts with optional whitespace followed by `*`, `//`, or `/*` —
i.e. block-comment continuations, single-line comments, and
block-comment openers. Drop the marker from the
`BufferWithOwnMemory.h` docstring now that the filter handles it.

Code lines inside a multi-line `/* ... */` block (e.g. the example
`std::vector<int>` inside the LZ4 docstring in `Compression/`)
still need the explicit marker because the line itself does not
start with a comment token; line-by-line grep cannot see the
enclosing block.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The local `mapping` lookup table in `convertLogLevel` was the last
std-container in `IO/S3/AWSLogger.cpp`. It is a function-local
static initialised once at first call and only read via `.at()`,
so it can use `UnorderedMapWithMemoryTracking` without any
behavioural change. Drop the marker.

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

clickhouse-gh Bot commented May 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b166b41]

Summary: ✅


AI Review

Summary

This PR aims to replace plain STL containers with *WithMemoryTracking equivalents across Compression, Daemon, IO, Loggers, QueryPipeline, and TableFunctions, but several changed paths still route through aliases that remain plain STL containers (Strings, UUIDs, ConnectionPoolEntries). On user-influenced or fan-out code paths, that leaves memory-limit enforcement gaps inconsistent with the PR contract.

Findings
⚠️ Majors
  • [src/Client/ConnectionPool.h:57] ConnectionPoolEntries is still std::vector<IConnectionPool::Entry>, so the QueryPipeline fan-out path in RemoteQueryExecutor still uses a non-throwing allocator. Large distributed queries can accumulate many entries here; use VectorWithMemoryTracking<IConnectionPool::Entry> (or explicitly mark this as an intentional exclusion).
  • [src/IO/PackedFilesWriter.cpp:162] ordered_file_names was switched to Strings, but Strings is still std::vector<String>. PackedFilesWriter::finalize materializes one entry per packed file, so large archives still bypass throwing memory tracking on this list.
  • [src/QueryPipeline/RemoteQueryExecutor.h:321] duplicated_part_uuids was switched to UUIDs, but UUIDs is still std::vector<UUID>. This vector grows with duplicate UUIDs returned by remote replicas and remains untracked.
  • [src/TableFunctions/TableFunctionRemote.cpp:283] shards was switched to Strings, which keeps parsing results from user-supplied remote descriptions on a plain std::vector allocator.
  • [src/IO/Archives/IArchiveReader.h:64] [dismissed by author -- https://github.com/Apply *WithMemoryTracking containers to Compression, Daemon, IO, Loggers, QueryPipeline, TableFunctions #105580#discussion_r3288877386] getAllFiles still returns Strings (std::vector<String>), so full archive file-name materialization remains untracked on a potentially large input surface.
Final Verdict

Status: ⚠️ Request changes

Minimum required actions:

  1. Replace remaining plain-container aliases on unbounded/fan-out paths with tracked containers (VectorWithMemoryTracking / tracked aliases), or
  2. Narrow the PR contract and mark intentional non-tracked exceptions explicitly so this change set does not claim memory-limit safety where it is not actually provided.

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label May 21, 2026
const bool resolve_by_uuid;
StorageID source_table_id{StorageID::createEmpty()};
std::vector<String> parts;
Strings parts;

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.

Strings is still an alias for std::vector<String> in Core/Types.h, so this replacement does not switch this path to a *WithMemoryTracking allocator.

parts is directly populated from user-supplied arguments, so with this type it can still grow outside throwing memory tracking limits. Could we use VectorWithMemoryTracking<String> here (and similarly for other Strings/NameSet substitutions in this PR) so the change actually enforces the intended invariant?

The 11 vector-overload templates in `IO/ReadHelpers.h` and
`IO/WriteHelpers.h` (`readVectorBinary`, `writeVectorBinary`,
`readBinary`/`writeBinary`, `readQuoted`/`writeQuoted`,
`readDoubleQuoted`/`writeDoubleQuoted`, `readText`/`writeText`,
`toStringWithFinalSeparator`) used to spell out `std::vector<T, Alloc>`
in their parameter lists, which tripped the std-containers style
check and forced a `STYLE_CHECK_ALLOW_STD_CONTAINERS` marker on each
line.

Add a small `IsStdVector` trait + `StdVector` concept to
`src/Common/Concepts.h` (next to the existing `is_any_of`,
`OptionalArgument`, `InVariant` concepts) and change the templates
to `template <StdVector V> void readBinary(V & x, ReadBuffer & buf)`.
This keeps overload semantics identical (only `std::vector<T, A>`
instantiations match — including `VectorWithMemoryTracking<T>`,
which is `std::vector<T, AllocatorWithMemoryTracking<T>>`) while
removing the literal `std::vector<` token from the linted headers.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

/// Parts uuids, collected from remote replicas
std::vector<UUID> duplicated_part_uuids;
UUIDs duplicated_part_uuids;

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.

UUIDs is an alias for std::vector<UUID> (Core/UUID.h), so this change still keeps duplicated_part_uuids on a non-throwing allocator.

This container can accumulate duplicate part IDs from remote replicas and may grow with table/shard cardinality, so it remains outside throwing memory tracking limits. Can we switch this field to VectorWithMemoryTracking<UUID> (or an equivalent *WithMemoryTracking alias) so this path actually enforces the PR invariant?

Comment thread src/IO/Archives/IArchiveReader.h Resolved
nickitat and others added 3 commits May 22, 2026 18:59
`ComposeObjectRequest` in `IO/S3/Requests.{h,cpp}` stored its
component names as `std::vector<Aws::String>`. Since
`Aws::String` is `std::string`, this is the same type as `Strings`
from `Core/Types.h` — switch to that alias and drop the
`STYLE_CHECK_ALLOW_STD_CONTAINERS` marker. The only caller in
`IO/S3/Client.cpp` passes `{key}`, which still works.

The small static lookup `unretryable_errors` in `IO/S3Common.cpp`
is internal-only and never crosses an SDK boundary, so convert
the `std::unordered_set<Aws::S3::S3Errors>` to
`UnorderedSetWithMemoryTracking`.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
`RemoteQueryExecutor` had five sites spelling out
`std::vector<IConnectionPool::Entry>` and one spelling out
`std::vector<ExternalTablesData>`, each guarded with a
`STYLE_CHECK_ALLOW_STD_CONTAINERS` marker.

Add two aliases in non-linted `Client/` headers and use them from
`QueryPipeline/RemoteQueryExecutor.{h,cpp}`:

  - `ConnectionPoolEntries` in `Client/ConnectionPool.h`
    (`Connections` would clash with the existing alias in
    `Client/Connection.h`).
  - `ExternalTablesDataPerReplica` in `Client/IConnections.h`.

Both aliases resolve to the same underlying `std::vector<...>` types,
so existing callers and the `IConnections::sendExternalTablesData`
interface continue to work unchanged.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Drop the `ExternalTablesDataPerReplica` alias added in the previous
commit and restore the `STYLE_CHECK_ALLOW_STD_CONTAINERS` marker on
the `external_tables_data` member of `RemoteQueryExecutor`. The
`ConnectionPoolEntries` alias is kept.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@nickitat nickitat changed the title Apply *WithMemoryTracking containers to more directories Apply *WithMemoryTracking containers to Compression, Daemon, IO, Loggers, QueryPipeline, TableFunctions May 22, 2026
@nickitat
nickitat marked this pull request as ready for review May 22, 2026 19:02
Comment thread src/TableFunctions/ITableFunction.h Resolved

using ConnectionPoolPtr = std::shared_ptr<IConnectionPool>;
using ConnectionPoolPtrs = std::vector<ConnectionPoolPtr>;
using ConnectionPoolEntries = std::vector<IConnectionPool::Entry>;

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.

ConnectionPoolEntries is still an alias for std::vector<IConnectionPool::Entry>, so RemoteQueryExecutor keeps a non-throwing allocator on this fan-out path.

This constructor can accumulate one entry per remote replica; on large distributed queries that defeats the memory-limit safety goal of this PR. Please switch the alias to VectorWithMemoryTracking<IConnectionPool::Entry> (or keep std::vector with an explicit STYLE_CHECK_ALLOW_STD_CONTAINERS marker if this path is intentionally excluded).

writeIntBinary(num_files, out);

std::vector<String> ordered_file_names;
Strings ordered_file_names;

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.

Strings is still std::vector<String> (Core/Types.h), so ordered_file_names remains on a non-throwing allocator.

PackedFilesWriter::finalize materializes one entry per packed file before serializing the index, so large archives can still bypass memory-limit enforcement here. Please use a tracked container (VectorWithMemoryTracking<String>, or an equivalent tracked alias) for this list.

@clickhouse-gh

clickhouse-gh Bot commented May 27, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.20% 84.10% -0.10%
Functions 91.40% 91.40% +0.00%
Branches 76.60% 76.60% +0.00%

Changed lines: 88.07% (384/436) | lost baseline coverage: 17 line(s) · Uncovered code

Full report · Diff report

@nickitat
nickitat added this pull request to the merge queue May 27, 2026
Merged via the queue into master with commit 7aed0cc May 27, 2026
166 checks passed
@nickitat
nickitat deleted the wmt_others branch May 27, 2026 20:47
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label May 27, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jun 22, 2026
…ine helper

The FPC codec ARM throughput regression (PR ClickHouse#105580, issue ClickHouse#106606) came from
converting the predictor tables to VectorWithMemoryTracking. Codegen analysis
(clang-21, ThinLTO-equivalent flattened-inline model) showed the per-pair hot
loop is byte-identical; the only delta is the once-per-block construction path.
AllocatorWithMemoryTracking::allocate is header-inlined and its inline
'throw std::bad_alloc()' injects a landing pad and EH machinery
(.gcc_except_table, __clang_call_terminate). Under ThinLTO the construction
inlines into the hot doCompressData, so that EH lands in the hot function and
shifts register allocation throughout. std::allocator avoids this because its
throw lives out-of-line in the overridden global operator new.

Move the allocator's bad_alloc throw into a cold [[noreturn]] [[gnu::cold]]
[[gnu::noinline]] helper and mark the failure branches [[unlikely]], so the
inlined allocate body carries no EH to spread into hot callers while keeping the
throwing memory tracker. This matches the global-new shape without reverting
memory tracking (every allocation is still tracked, whether via this allocator
or the global operator new override).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jun 23, 2026
…C codec ARM regression

PR ClickHouse#105580 switched the FPC codec predictor tables from std::vector to
VectorWithMemoryTracking, causing a ~16% throughput regression on the ARM
codecs_float_insert performance test (query ClickHouse#12, FPC Float64 insert). The
regression is ARM-only.

Root cause (confirmed by disassembling the real CompressionCodecFPC.cpp TU
cross-compiled to aarch64 -O3 with the production ARM target):
std::vector<T, std::allocator> inlines its fill-constructor into
doCompressData (4 inline 'bl operator new' + an inline fill loop). With the
tracking allocator, allocate()/deallocate() were header-inlined and carried
the whole tracker + malloc + onAlloc/onFree + EH body, which made the
container's fill-constructor too large for the inliner. It became an
out-of-line call, so doCompressData makes 4 out-of-line vector-ctor calls
plus out-of-line predictor destructor calls. Those calls clobber
caller-saved registers and force spills/reloads, shifting register
allocation across the whole hot function. On the generic-scheduled (no
-mtune) ARM target this costs measurable throughput; x86 absorbs it.

This is why the earlier cold-throw-helper change did not move the number:
the helper lives inside that out-of-line constructor, so doCompressData kept
making the same perturbing calls.

Fix: move the tracker + malloc + onAlloc/onFree machinery into
AllocatorWithMemoryTracking.cpp so allocate()/deallocate() inline to a single
call, matching std::allocator's shape (operator new/delete are also
out-of-line). The container fill-constructor then inlines back into
doCompressData and the out-of-line vector-ctor calls disappear. Tracking is
unchanged: every allocation still goes through CurrentMemoryTracker.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jun 23, 2026
…C codec ARM regression

PR ClickHouse#105580 converted the FPC codec predictor tables (DfcmPredictor,
FcmPredictor) from std::vector to VectorWithMemoryTracking. On ARM this
regressed the codecs_float_insert benchmark (query 12) by ~16%.

Root cause: AllocatorWithMemoryTracking::allocate()/deallocate() carried
the full tracker + malloc + onAlloc/onFree body inline. That made the
container fill-constructor too large for the inliner, so it became an
out-of-line call. doCompressData then made several out-of-line
vector-constructor calls, which perturbed register allocation across the
hot function. Generic-scheduled ARM lost throughput; x86 absorbed it.

Move the allocation machinery into AllocatorWithMemoryTracking.cpp so
allocate()/deallocate() inline to a single call, matching the shape of
std::allocator (operator new/delete are also out-of-line). The
fill-constructor inlines back into doCompressData and the out-of-line
constructor calls disappear. Memory tracking is unchanged: every
allocation still goes through CurrentMemoryTracker.

The bad_alloc throw stays in a cold, never-inlined helper (NO_INLINE)
so the inline allocate() body carries no exception-handling machinery.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…C codec ARM regression

PR ClickHouse#105580 converted the FPC codec predictor tables (DfcmPredictor,
FcmPredictor) from std::vector to VectorWithMemoryTracking. On ARM this
regressed the codecs_float_insert benchmark (query 12) by ~16%.

Root cause: AllocatorWithMemoryTracking::allocate()/deallocate() carried
the full tracker + malloc + onAlloc/onFree body inline. That made the
container fill-constructor too large for the inliner, so it became an
out-of-line call. doCompressData then made several out-of-line
vector-constructor calls, which perturbed register allocation across the
hot function. Generic-scheduled ARM lost throughput; x86 absorbed it.

Move the allocation machinery into AllocatorWithMemoryTracking.cpp so
allocate()/deallocate() inline to a single call, matching the shape of
std::allocator (operator new/delete are also out-of-line). The
fill-constructor inlines back into doCompressData and the out-of-line
constructor calls disappear. Memory tracking is unchanged: every
allocation still goes through CurrentMemoryTracker.

The bad_alloc throw stays in a cold, never-inlined helper (NO_INLINE)
so the inline allocate() body carries no exception-handling machinery.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 25, 2026
This stores the FPC lookup tables in a VectorWithMemoryTracking
(introduced in 26.2 with
ClickHouse#96235).

A similar change was made in 26.6
(ClickHouse#105580) - this PR only
applies it to FPC.
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 25, 2026
This stores the FPC lookup tables in a VectorWithMemoryTracking
(introduced in 26.2 with
ClickHouse#96235).

A similar change was made in 26.6
(ClickHouse#105580) - this PR only
applies it to FPC.
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Oct 2, 2026
This stores the FPC lookup tables in a VectorWithMemoryTracking
(introduced in 26.2 with
ClickHouse#96235).

A similar change was made in 26.6
(ClickHouse#105580) - this PR only
applies it to FPC.
javyxu pushed a commit to javyxu/ClickHouse that referenced this pull request Nov 2, 2026
…limit

`ZipArchiveReader::releaseRawHandle` pushes the handle back into
`free_handles`, a `VectorWithMemoryTracking` since 35ca56f (ClickHouse#105580),
and is called from `~HandleHolder`. When more handles are checked out at once
than the pool has held before (an `s3`/`s3Cluster` read of
`archive.zip :: <glob>` keeps the iterator's handle while a read buffer takes
another), the push reallocates. If the query memory tracker refuses that
allocation during pipeline teardown inside a `catch` block (a real limit or an
injected fault), the exception leaves the destructor and `std::terminate`
aborts the server (Stress test (amd_debug), STID 7014-7054). The same push in
`init()` leaked the just-opened `unzFile` on a throw.

Block memory-limit exceptions for the push with `LockMemoryExceptionInThread`;
the allocation is still tracked.

The new gtest checks out two read buffers, sets the query tracker hard limit
to 1 byte and releases the second buffer, which has to grow the pool. Without
the fix the test binary aborts; with it the test passes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-not-for-changelog This PR should not be mentioned in the changelog 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