Skip to content

Polygon dictionary memory accounting and load-path improvements - #104231

Closed
Algunenano wants to merge 1 commit into
ClickHouse:masterfrom
Algunenano:polygon-dict-memory-fixes
Closed

Algunenano wants to merge 1 commit into
ClickHouse:masterfrom
Algunenano:polygon-dict-memory-fixes

Conversation

@Algunenano

@Algunenano Algunenano commented May 6, 2026 •

Copy link
Copy Markdown
Member

Polygon dictionaries (polygon_index_cell / polygon_index_each) underreport their footprint
in system.dictionaries.bytes_allocated and their load path has avoidable peak allocations.

Fixes in this PR:

  • bytes_allocated now accounts for the lookup index (slab segment trees + grid cells) plus
    the polygons vector capacity and the polygon-id-to-attribute-index map. New stateless test
    04204_polygon_dict_bytes_allocated asserts the index-bearing layouts (polygon_index_cell,
    polygon_index_each) report meaningfully more bytes than polygon_simple.

  • IPolygonDictionary::loadData no longer copies every polygon into a pair<Polygon, size_t>
    to sort by area; it sorts an index permutation and rebuilds the destination vectors via
    std::move. Peak load-time memory drops from ~3x the polygon storage to ~1x.

  • GridRoot::makeCell no longer constructs a fresh 128-thread ThreadPool on every recursive
    call; one pool is built in the GridRoot constructor and shared across the recursion.

  • SlabsPolygonIndex::uniqueX pre-reserves the gather buffer to its known upper bound
    (bg::num_points) so it doesn't grow by capacity doubling.

Closes ClickHouse/clickhouse-private#57161

Changelog category (leave one):

  • Improvement

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

Reduce memory usage of polygon dictionaries (polygon_index_cell, polygon_index_each) and make system.dictionaries.bytes_allocated correctly reflect the lookup index they build.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

@Algunenano Algunenano added the comp-memory Memory management infrastructure: allocators (Allocator, Arena, PODArray), memory tracking, memor... label May 6, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c8e8682]


AI Review

Summary

This PR improves polygon dictionary memory accounting and reduces load-path peak allocations, and it adds a new bytes_allocated stateless test. One previously reported correctness issue is still live in extractPolygons: mixed empty/non-empty rows in one block can still map polygons to the wrong source row id. Because this can return incorrect attribute values, changes are still required.

Findings

❌ Blockers

  • [src/Dictionaries/PolygonDictionary.cpp:731] extractPolygons still seeds ids with 0 via data.addPolygon(true) and does not advance over leading empty rows before the first point append. For a block with leading empty multi-polygons (for example multi_polygon_offsets = [0, 1], polygon_offsets = [1], ring_offsets = [5]), the first real polygon is still assigned id 0, so lookups can read attributes from the wrong row.
    Suggested fix: skip leading empty rows before the first point is appended (or compute row ids from row-boundary transitions rather than from an initial seeded id), and keep ids aligned with actual source rows.
Tests
  • ⚠️ Missing focused regression for mixed empty/non-empty rows within the same input block. The new 04204_polygon_dict_bytes_allocated test validates memory accounting only and does not cover row-id mapping correctness.
Final Verdict

Status: ⚠️ Request changes
Minimum required actions:

  1. Fix mixed-block row-id mapping in extractPolygons.
  2. Add a regression test that inserts empty and non-empty polygon rows in one block and validates returned attributes map to the correct source row.

Comment thread src/Dictionaries/PolygonDictionary.cpp Outdated
size_t p = 0;
while (p < offset.polygon_offsets.size())
{
const bool new_mp = offset.isFirstPolygonOfMultiPolygon(p);

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This is out of the scope of the PR. If the PR does not change the code it's not responsible to fix all possible issues you find or adding tests to prove they are or aren't there. That will happen in a separate PR

BadLiveware pushed a commit to BadLiveware/ClickHouse that referenced this pull request May 16, 2026
`clickhouse_fuzzer` runs the full `clickhouse-local` binary (see
`programs/local/fuzzers/clickhouse_fuzzer.cpp`) which spins up a complete
clickhouse-server-grade runtime: JeMalloc arenas, OpenSSL initializer,
static initializers, and full query execution. Baseline RSS is close to
the libFuzzer default `rss_limit_mb=2048`, so fuzzed inputs that trigger
even moderate query-time allocations push the process past the limit.

CIDB shows 7 unrelated PRs in 7 days all hitting OOM at 2049-2056 Mb —
just barely over the 2048 Mb default. Failure mode is uniform:

    libFuzzer  out-of-memory (used: 2049-2056Mb; limit: 2048Mb)  oom-<hash>

Bumping to 4096 Mb follows existing precedent for fuzzers with similar
workloads:
  - `execute_query_fuzzer.options`: rss_limit_mb = 4096 (also runs query
    execution; same author bumped this in commit bafb7d7)
  - `data_type_deserialization_fuzzer.options`: rss_limit_mb = 4096
  - `create_parser_fuzzer.options`: rss_limit_mb = 6144

The limit still bounds the target (it does not disable the check via
`rss_limit_mb=0`), so genuine memory regressions above 4 GB will still
be caught.

CIDB evidence (last 30 days, all 10 hits — 0 on master because libFuzzer
does not run on master regularly):
    PR ClickHouse#99740  (4 hits, Apr 19-21)
    PR ClickHouse#104231, ClickHouse#104849, ClickHouse#104956, ClickHouse#96844, ClickHouse#104510, ClickHouse#104492  (1 hit each,
    May 13-15)
@clickhouse-gh

clickhouse-gh Bot commented May 18, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

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

Changed lines: 98.17% (107/109) · Uncovered code

Full report · Diff report

@ClickHouse ClickHouse deleted a comment from clickhouse-gh Bot May 20, 2026
@ClickHouse ClickHouse deleted a comment from clickhouse-gh Bot May 20, 2026
@ClickHouse ClickHouse deleted a comment from clickhouse-gh Bot May 20, 2026
@ClickHouse ClickHouse deleted a comment from clickhouse-gh Bot May 20, 2026
@ClickHouse ClickHouse deleted a comment from clickhouse-gh Bot May 20, 2026
@ClickHouse ClickHouse deleted a comment from clickhouse-gh Bot May 20, 2026
@ClickHouse ClickHouse deleted a comment from clickhouse-gh Bot May 20, 2026
@ClickHouse ClickHouse deleted a comment from clickhouse-gh Bot May 20, 2026
`IPolygonDictionary::calculateBytesAllocated` only counted the polygon
key column, attribute columns, and raw polygon points. The lookup index
(`SlabsPolygonIndex` segment trees, `GridRoot` cells) was deliberately
omitted with a comment claiming it was a small share of the total.

For dense workloads (parcels, address polygons) the index dominates: a
200k-polygon `polygon_index_cell` reports 8.6 MiB while
`jemalloc.allocated` grows by ~412 MiB during load. On small server
pods this drives cold-start OOM kills that are invisible to dictionary
level memory tracking.

Changes:
  - Add a virtual `getIndexBytesAllocated` and walk the cell tree so
    `SlabsPolygonIndex`, `FinalCell`, `FinalCellWithSlabs`,
    `DividedCell`, and `GridRoot` each report the bytes they own.
    `calculateBytesAllocated` also includes the `polygons` vector and
    the polygon-id-to-attribute-index map. Reported `bytes_allocated`
    on the 200k-parcel workload becomes 433.78 MiB, matching jemalloc
    within ~5%.
  - `IPolygonDictionary::loadData` now sorts an index permutation
    instead of deep-copying every polygon into a `pair<Polygon,
    size_t>`. Final `polygons` and
    `polygon_index_to_attribute_value_index` are rebuilt with
    `std::move`, dropping peak extra memory during sort from O(polygon
    bytes) to O(N * sizeof(Polygon)).
  - `GridRoot` constructs a single shared `ThreadPool` and passes it to
    every `makeCell` invocation. The previous code created a fresh
    128-thread pool on every recursive call past
    `kMultiProcessingDepth`, even though those levels never enqueued
    work.
  - `SlabsPolygonIndex::uniqueX` pre-reserves the gather buffer to
    `sum(bg::num_points)` so the inner gather loop performs one
    allocation instead of `log2(N)` reallocations.

Add `04204_polygon_dict_bytes_allocated` to assert that
`bytes_allocated` is meaningfully larger than `polygon_simple` for both
`polygon_index_cell` and `polygon_index_each`.

Note: `calculateBytesAllocated` had to move from the base constructor
into each concrete subclass. Calling it from the base would dispatch
through the base vtable and skip the derived `getIndexBytesAllocated`
override.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@Algunenano
Algunenano force-pushed the polygon-dict-memory-fixes branch from 81cbce8 to c8e8682 Compare May 20, 2026 13:14
@ClickHouse ClickHouse deleted a comment from clickhouse-gh Bot May 20, 2026
@ClickHouse ClickHouse deleted a comment from clickhouse-gh Bot May 20, 2026
@Algunenano Algunenano closed this May 20, 2026
@Algunenano

Copy link
Copy Markdown
Member Author

Closing to reopen with a clear history

@Algunenano

Copy link
Copy Markdown
Member Author

Superseded by #105431 — the branch was squashed to a single commit containing only the memory-related changes; the reverted extract-side reserve / zero-ring handling is no longer in scope here.

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

Labels

comp-memory Memory management infrastructure: allocators (Allocator, Arena, PODArray), memory tracking, memor... pr-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant