Skip to content

Try absl::flat_hash_map in Keeper storage - #85138

Closed
antonio2368 wants to merge 25 commits into
masterfrom
try-changing-map-keeper
Closed

antonio2368 wants to merge 25 commits into
masterfrom
try-changing-map-keeper

Conversation

@antonio2368

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Improvement

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

Improve clrs command by rehashing internal hash map to reduce memory usage. Add automatic rehashing of internal hash map controlled with keeper_server.coordination_settings.hash_map_min_load_factor and keeper_server.coordination_settings.min_node_count_for_auto_optimize.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

@clickhouse-gh

clickhouse-gh Bot commented Aug 6, 2025 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [bb9b568]

Summary: ❌

job_name test_name status info comment
AST fuzzer (amd_debug, targeted) FAIL
Logical error: Block structure mismatch in A stream: different columns: (STID: 0993-27f0) FAIL cidb
AST fuzzer (amd_debug, targeted, old_compatibility) FAIL
Logical error: Invalid number of columns in chunk pushed to OutputPort. Expected A, found B (STID: 2270-3258) FAIL cidb
Integration tests (amd_asan_ubsan, db disk, old analyzer, 5/6) ERROR

AI Review

Summary

This PR replaces Keeper's in-memory node index with absl::flat_hash_map, adds optional automatic rehashing through keeper_server.coordination_settings.hash_map_min_load_factor and keeper_server.coordination_settings.min_node_count_for_auto_optimize, and makes clrs force a storage rehash before purging allocator arenas. The current code addresses the earlier auto-rehash edge cases around snapshot reserve, clear, delete-heavy workloads, and redundant rehashing, but the always-on container swap is still missing benchmark evidence, so I cannot approve the Improvement claim yet.

Tests
  • ⚠️ Missing performance evidence: the PR swaps the core Keeper node index on the normal hot path, but the PR discussion still does not include before/after measurements for old HashMap vs new absl::flat_hash_map. Please attach focused numbers for throughput, latency, and memory footprint, for example keeper-bench plus one representative production-like workload. Passing Keeper stress CI is useful, but it does not prove the claimed improvement or rule out a performance regression.
Final Verdict

Status: ⚠️ Request changes

Minimum required action: attach before/after benchmark and memory results for the Keeper storage map change. If the numbers show a regression, adjust the implementation or gate the container change accordingly.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Aug 6, 2025
@george-larionov george-larionov self-assigned this Aug 6, 2025

@george-larionov george-larionov 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.

Overall the changes look good to me, I will approve if you can address my comments and add some tests.

Question: What is the reason for this optimization, and how do we know that it is an optimization, are there any benchmarks?

Note: I'm pretty new at CH, so feel free to request an additional review from someone with more experience with the codebase.

Comment thread src/Coordination/KeeperStateMachine.cpp Resolved

void optimizeIfNeeded()
{
if (min_load_factor > 0 && map.load_factor() < min_load_factor && map.size() > min_node_count_for_auto_optimize)

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.

So by default the optimization is disabled?

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.

Yes, I'm not sure about the impact of it, especially when we have 100mil nodes.
So I added metric and made it configurable.

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.

Do you have plans to test the memory usage and enable it by default? I am worried that this might otherwise never be enabled, it looks like a nice optimization.

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.

Yes, I plan to test it on some of our heavier instances

@antonio2368
antonio2368 force-pushed the try-changing-map-keeper branch from 7e9ae3b to a397cf2 Compare August 7, 2025 07:35
@george-larionov

Copy link
Copy Markdown
Member

I am a little concerned that we don't know for sure whether the new hash map is faster/more efficient than the old one. I understand that rehashing has the potential to keep the memory usage lower, but is there a benchmark that could be run to compare whether the normal operations of the new hash map are at least as fast as the old one?

@antonio2368

antonio2368 commented Aug 8, 2025 •

Copy link
Copy Markdown
Member Author

@george-larionov we have keeper bench + some heavy instance we can test it on.
I will not merge before I verify the performance and memory usage.

@george-larionov george-larionov 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.

Looks good to me!

@clickhouse-gh

clickhouse-gh Bot commented Sep 16, 2025

Copy link
Copy Markdown
Contributor

Dear @george-larionov, this PR hasn't been updated for a while. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@alexey-milovidov

Copy link
Copy Markdown
Member

I will not merge before I verify the performance and memory usage.

How was it?

antonio2368 and others added 2 commits March 2, 2026 14:27
# Conflicts:
#	src/Coordination/CoordinationSettings.cpp
#	src/Coordination/KeeperConstants.cpp
#	src/Coordination/KeeperStorage.cpp
#	src/Coordination/SnapshotableHashTable.h
- Restore `copyFromSnapshotNode` in `updateValue` snapshot path to avoid
  duplicating the children set (moves children to the new copy, clears
  the old snapshot-retained node).
- Restore intermediate `updateDataSize` call so `approximate_data_size`
  correctly accounts for the old node kept alive for the snapshot.
- Fix use-after-move in `insert`: capture `value.sizeInBytes` before
  moving value into the list element.
- Take `insert` value parameter by value to allow callers to move.
- Remove `optimizeIfNeeded` from `erase` to avoid repeated rehashes
  during bulk deletes; keep it only in `clearOutdatedNodes`.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

The Stress test (arm_msan) failure is fixed by #101239, which should be merged first. After it is merged, please update the branch to include the fix.

@alexey-milovidov

Copy link
Copy Markdown
Member

The Hung check failure is fixed by #102008 and #102010, let's update the branch

# Conflicts:
#	src/Coordination/KeeperStateMachine.cpp
#	src/Coordination/SnapshotableHashTable.h
…eper

# Conflicts:
#	src/Coordination/KeeperStorage.cpp
#	src/Coordination/KeeperStorage.h
using List = std::list<ListElem>;
using Mapped = typename List::iterator;
using IndexMap = HashMap<std::string_view, Mapped>;
using IndexMap = absl::flat_hash_map<std::string_view, Mapped, DefaultHash<std::string_view>>;

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.

This change swaps the core Keeper node index from HashMap to absl::flat_hash_map, but I still don't see benchmark evidence attached to the PR that demonstrates the expected improvement (or at least no regression) on real Keeper workloads.

Because this is on a hot path, can you add before/after numbers (e.g. keeper-bench throughput + latency and memory footprint) for the old and new implementations? Without that data it's hard to validate the improvement claim in the PR/changelog.

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.

I re-checked the current PR head and still don't see before/after numbers attached for the absl::flat_hash_map switch in Keeper storage (throughput/latency plus memory footprint).

This is still needed to validate the Improvement claim and ensure there is no regression on normal Keeper workloads. Please attach benchmark results (for example, keeper-bench and a representative production-like workload) so we can verify both performance and memory impact.

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.

I re-checked the current PR head (2d33c6596f55c3a872299dcc6882ee90ba22d0cb) and still do not see benchmark evidence attached for the absl::flat_hash_map switch in Keeper storage. This change is on the Keeper hot path, so we still need before/after measurements (at least throughput/latency and memory footprint) to validate the Improvement claim and rule out regressions.

Please attach concrete numbers (for example keeper-bench plus one representative production-like workload).

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.

Leaving this thread open — the production-workload keeper-bench numbers are still owned by the author (@antonio2368 noted earlier he planned to measure this on heavier instances).

For context on what is already in place:

  • This PR's two settings (hash_map_min_load_factor / min_node_count_for_auto_optimize) default to 0, i.e. automatic rehashing is off by default, so it adds no work on the default hot path. The only always-on change is the HashMap → absl::flat_hash_map container swap, which is the part that needs the before/after numbers.
  • The Keeper Stress Tests run automatically on every commit of this PR and report throughput/latency/memory; the dashboards are linked from the CI summary comment ("Keeper Stress Tests (PR)": run details, 1vs1 comparison, historical progression). Those are the most direct in-CI signal for "no regression on normal Keeper workloads".

So this is the right gate to keep open until the author attaches the explicit before/after keeper-bench (and a representative production-like workload) measurements.

alexey-milovidov and others added 3 commits May 18, 2026 03:39
…lace`

Covers the edge case raised in review where the load factor drops below
`hash_map_min_load_factor` after many `erase`s while the map size is still
under `min_node_count_for_auto_optimize`, then grows back above the
threshold via subsequent `insert`s with no further `erase`s — without
this hook, `clearOutdatedNodes` would never run again to trigger the
rehash. `optimizeIfNeeded` now returns whether it rehashed so the public
`insert` can re-find its returned iterator if the map was rehashed.

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

# Conflicts:
#	src/Coordination/KeeperStateMachine.cpp
alexey-milovidov and others added 2 commits June 4, 2026 11:00
`optimizeIfNeeded` rehashes the in-memory node index when the `absl::flat_hash_map`
load factor drops below `hash_map_min_load_factor`. However `rehash(0)` can only bring
the load factor up to what the container can achieve (`absl::flat_hash_map` tops out
below 1.0), so a `hash_map_min_load_factor` set higher than that left the predicate
permanently true and rehashed the whole index on every insert above
`min_node_count_for_auto_optimize` — turning writes and snapshot loading into repeated
O(N) work.

Skip `optimize` when `rehash(0)` cannot shrink the table further (same bucket count and
no node erased since the last rehash). This keeps the intended shrink-after-erase
behavior while bounding the work for any configured threshold, without rejecting or
capping the setting.

Add a gtest covering the auto-optimize path: insert-with-rehash iterator validity, the
snapshot-mode erase -> clearOutdatedNodes shrink path, and re-insertion after a shrink.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

Updated the branch and addressed the outstanding review item.

  • Merged master (the branch was 552 commits behind). This picks up the fixes referenced above: Fix MSan use-of-uninitialized-value in SimSIMD SVE functions #101239 (arm_msan stress), Do not ignore DROP for refreshable materialized views in stress tests #102008 and Check for query cancellation during vector similarity index building #102010 (Hung check) are all merged and now in the branch.
  • Fixed the auto-rehash config-safety finding at SnapshotableHashTable.h (commit 5f96494). When hash_map_min_load_factor is set higher than the load factor absl::flat_hash_map can reach after rehash(0), the old predicate stayed true and rehashed the whole node index on every insert — O(N) per write. optimizeIfNeeded now skips the rehash when rehash(0) cannot shrink further (unchanged bucket count and no erase since the last optimize), bounding it to at most one rehash per bucket-count growth while keeping the shrink-after-erase behavior. No setting is rejected or capped.
  • Added SnapshotableHashMapAutoOptimize gtest covering the auto-optimize path (insert-with-rehash iterator validity, the snapshot-mode erase → clearOutdatedNodes shrink, and re-insertion after a shrink). Full *SnapshotableHashMap* suite passes locally (ARM, RelWithDebInfo).

On the previous CI run (commit 36aad5e), all 5628 individual stateless tests passed; the two reported items in Stateless tests (arm_asan_ubsan, targeted) were post-run checks: "Server died" has no crash trace in the server logs (clean SIGTERM shutdown — the error log is saturated with CI log-shipping failures to the remote staging cluster), and "Scraping system tables" is the generic zookeeper_log > 10M row-count guard tripped by the heavy Keeper test volume. Neither stems from this change; the re-run after the merge should clarify.

The performance/memory verification on a heavier instance (per the discussion above) is still pending on the author side and is the remaining gate before merge.

@alexey-milovidov

Copy link
Copy Markdown
Member

Merged the latest master into the branch (it was ~700 commits behind and red). The merge was conflict-free. Rebuilt unit_tests_dbms and ran the Coordination snapshot/hash-table suite locally — all 48 tests pass, including the new SnapshotableHashMapAutoOptimize.

The two CI failures on the previous run are both unrelated to this Keeper-only change:

  • AST fuzzer (amd_debug, targeted) — Segmentation fault (STID: 1719-3ae5): crash is in DB::FunctionArrayMapped<DB::ArrayFirstLastIndexImpl<...>, DB::NameArrayLastIndex, true>::getReturnTypeImpl (the arrayLastIndex higher-order function), which this PR does not touch. The same crash signature hit unrelated PR Fix cardinality underestimation when join column NDVs are unknown #101398 (Fix cardinality underestimation when join column NDVs are unknown) on the same day, so it is a latent master bug surfaced by the fuzzer.
  • Stateless tests (arm_asan_ubsan, azure, parallel) — 04033_tpc_ds_q09: this test is flaky on master, failing 16 times across 3 different PRs over the last 90 days (CIDB).

@groeneai, please investigate the arrayLastIndex/FunctionArrayMapped AST-fuzzer segfault (STID: 1719-3ae5, also seen on #101398) and the flaky 04033_tpc_ds_q09, and provide fixes in separate PRs. If a fix is already in progress, please link it here.

@groeneai

groeneai commented Jun 8, 2026

Copy link
Copy Markdown
Collaborator

Tracking.

STID 1719-3ae5 (arrayLastIndex SIGSEGV in FunctionArrayMapped::getReturnTypeImpl): fix in flight as #106271. Same root-cause family — an unresolved-lambda placeholder (DataTypeFunction(args=[nullptr...], return=nullptr)) leaking into a higher-order function's argument types and getting dereferenced by removeNullable. The PR's pre-pass in QueryAnalyzer::resolveFunction rejects the placeholder before it can reach any FunctionArrayMapped branch (including the arrayLastIndex / ArrayFirstLastIndexImpl<NameArrayLastIndex, true> instantiation seen here). State: open, mergeable, awaiting senior review.

04033_tpc_ds_q09: investigating in a separate task. CIDB shows 16 hits / 3 PRs / 90d, 0 master hits in the last 30d — the cluster is the original test-adding PR #99204 (13 same-day hits), an open ReaderExecutor PR #103706 (4 same-day hits), and this PR's single arm_asan_ubsan/azure hit. Will link the fix PR here when ready.

cron:clickhouse-ci-task-worker:20260608-010700

alexey-milovidov and others added 2 commits June 9, 2026 13:58
`KeeperStorageSnapshot::deserialize` calls `reserve(snapshot_container_size)`
before bulk-loading nodes. With automatic optimization enabled
(`hash_map_min_load_factor` > 0), the early inserts see a very low load
factor, so `optimizeIfNeeded` would `rehash(0)` and shrink the table back,
undoing the preallocation and forcing repeated rehashing during snapshot
load - exactly the restart / follower catch-up path where predictable
performance matters.

Track the outstanding `reserve` target and skip automatic optimization while
the reserved capacity is still being filled; the reservation is cleared once
the target node count is reached. Add a unit test asserting the bucket count
never shrinks below the reserved capacity during a bulk load.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

Updated the branch and addressed the latest review.

  • Merged origin/master (the branch was ~600 commits behind), clean merge with the Keeper diff intact. Re-synced the contrib/NuRaft submodule working tree to the pointer recorded in master (c3d2e767), which is required for the new nuraft::snapshot_io_mgr::shutdown_instance call to build.
  • Addressed @clickhouse-gh’s finding that automatic rehashing could undo the reserve(snapshot_container_size) done by KeeperStorageSnapshot::deserialize: SnapshotableHashTable now tracks the outstanding reserve target and optimizeIfNeeded skips shrinking while the reserved capacity is still being filled (cleared once the target node count is reached). This keeps the preallocation intact during bulk snapshot loading — the restart / follower catch-up path — instead of paying rehash(0) per insert. Added a unit test SnapshotableHashMapReserveSurvivesAutoOptimize.
  • Built unit_tests_dbms clean; 52/52 *SnapshotableHashMap* + *TestStorageSnapshot* tests pass (including the new test and SnapshotableHashMapAutoOptimize).

On the previous (pre-merge) CI run, the Stateless (amd_debug) reds were: the Virtual row boundary violated in MergingSortedAlgorithm failure (STID 2651-3359) — a known read-in-order flake fixed on master by 28c01518689, which is now in this branch via the merge — and a Server died cascade that also showed up as 04010_mongodb_dictionary_named_collection; that path is unrelated to this Keeper-only change and should clear on re-run.

@groeneai

Copy link
Copy Markdown
Collaborator

@alexey-milovidov investigation result for the flaky 04033_tpc_ds_q09:

Conclusion: this is not chronic flakiness. Master has 0 failures in 30 days (CIDB). The 90-day "16 across 3 PRs" headline decomposes into three non-chronic clusters, and every recent failure is an OOM victim on the arm_asan_ubsan, azure, parallel runner, not a Q09 bug.

Breakdown:

Two of those three azure hits are from 2026-06-09, which was a runner-wide OOM event: 552 distinct tests failed on arm_asan_ubsan, azure, parallel that day (312 with "memory limit exceeded"). Q09 was one of 312 victims.

So there is no deterministic reproducer and no test-level bug. The test already carries no-random-settings. The only lever I can pull is no-parallel, to stop Q09 co-scheduling with other heavy queries on the azure ASAN runner, but that is a partial mitigation for runner memory pressure rather than a real fix, and the same OOM hits many heavy tests on bad runner days, so I would rather not add it speculatively.

My recommendation is to leave the test as is since master is clean. Do you want me to add no-parallel as a mitigation anyway, or close this out?

(session cron:clickhouse-worker-slot-2:20260610-225500)

alexey-milovidov and others added 2 commits June 11, 2026 10:52
`clear` (also invoked by the destructor) calls `clearOutdatedNodes`, which
ended with `optimizeIfNeeded`. With `hash_map_min_load_factor > 0` this could
spend O(N) rehashing the whole node index immediately before `map.clear`
discards it, on the shutdown / storage replacement paths.

Add an `optimize_after_cleanup` flag to `clearOutdatedNodes` so `clear` can
skip the optimization, and a gtest covering both modes.

Co-Authored-By: Claude Fable 5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

CI triage (head `4969743b036`): the sole red is `AST fuzzer (arm_asan_ubsan)` — `Logical error: Column ... query tree node does not have valid source node after running ... pass` (STID 0250-20a8). This is an analyzer query-tree validation failure inside `QueryTreePassManager::run` / `InterpreterSelectQueryAnalyzer`, unrelated to this PR (the diff is Keeper-only: `SnapshotableHashTable` / `Coordination`). It matches the known open issue #80564 ("Stress tests: Column X Int32 query tree node does not have valid source node").

@groeneai, could you confirm/track this against #80564 and provide a fix in a separate PR if one is not already in flight?

@groeneai

groeneai commented Jun 12, 2026 •

Copy link
Copy Markdown
Collaborator

@alexey-milovidov confirmed, and tracking under #80564.

Unrelated to this PR. STID 0250-20a8 here is the analyzer query-tree validation error Column number UInt64 query tree node does not have valid source node after running QueryAnalysis pass, aborting in QueryTreePassManager::ValidationChecker::visitColumn (QueryTreePassManager.cpp:107) under InterpreterSelectQueryAnalyzer::buildQueryTreeAndRunPasses. This PR's diff is src/Coordination/* (Keeper) only, with no path into src/Analyzer/.

Fuzzed query (from the report):

WITH t AS MATERIALIZED (SELECT 65537 + number, number FROM zeros_mt(5) WHERE -2147483648)
SELECT * FROM numbers(2) WHERE tuple(number + materialize(10)) GLOBAL IN (t)

Pre-existing trunk bug. CIDB over the last 30 days, this exact signature: 0 master hits, 15 hits across 10 unrelated PR branches (all AST fuzzer jobs), first seen 2026-05-19. Representative CI report (the failure on this PR): https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=85138&sha=4969743b036c6641012121fe99fc074dee453aac&name_0=PR&name_1=AST%20fuzzer%20%28arm_asan_ubsan%29&name_1=AST%20fuzzer%20%28arm_asan_ubsan%29 . This matches #80564 (fuzz, OPEN).

One caveat: 0250-20a8 is a hash-collision STID bucket that also holds a separate Function A expects argument B ... type analyzer signature. Different stack, tracked separately; the one on this PR is the valid-source-node variant above.

Edited 2026-06-13: dropped links to unrelated PRs (per davenger's note below); kept the cross-PR count and a representative CI report link instead.

Session: cron:clickhouse-worker-slot-2:20260612-221400

@groeneai

Copy link
Copy Markdown
Collaborator

Follow-up on the fix: no separate PR is needed, a fix is already in flight as #105518 ("Reject correlated MATERIALIZED CTE used in IN at analysis time", closes #105501).

Root cause: a MATERIALIZED CTE whose body is a correlated subquery, used as the RHS of IN. The analyzer already rejects this in the join-tree path (resolveQueryJoinTreeNode: Materialized CTE '...' cannot be correlated), but the identifier-resolution path taken for x IN (t) was unguarded, so resolution proceeds and a correlated ColumnNode survives QueryAnalysis with a null source, aborting in ValidationChecker::visitColumn. #105518 adds the same correlation check on the IN path. It requires enable_materialized_cte = 1 (set in the AST-fuzzer profile), which is why the auto-generated reproduce command alone returns a clean NOT_IMPLEMENTED instead of crashing.

Verified locally on master 4fc87f09390 (debug): the exact fuzzed query from this PR aborts without the fix and returns a clean UNSUPPORTED_METHOD ("Materialized CTE 't' cannot be correlated") with #105518's change. So STID 0250-20a8 / #80564 (valid-source-node) is the same root cause as #105501 (the PLACEHOLDER symptom #105518 was opened for); they differ only by which optimizer settings the fuzzer combined. I will fold #80564 into #105518.

Session: cron:clickhouse-worker-slot-2:20260612-230800

@davenger

Copy link
Copy Markdown
Member

Pre-existing trunk bug. CIDB over the last 30 days, this exact signature: 0 master hits, 15 hits across 10 unrelated PR branches (dphyp_join_reordering #98798, self-dedup #106113, iceberg #102033, per-cpu-memory #104125, ci-runner-label #104870, and this PR's try-changing-map-keeper). First seen 2026-05-19. This matches #80564 (fuzz, OPEN).

@groeneai do not add links to unrelated PRs just because of the same flaky test failures. Those links in github make these PRs look as if they are somehow connected. You can add links to CI reports with test failures instead.

@groeneai

Copy link
Copy Markdown
Collaborator

Understood, thanks for the correction. Going forward, when I cite cross-PR CIDB spread as evidence that a failure is a pre-existing trunk bug, I'll give just the count (e.g. "N hits across M unrelated PRs in 30d, 0 on master") plus a link to a representative CI report, and not write out the unrelated PR numbers.

I've edited the comment above accordingly.

The AI review flagged that the automatic storage optimization
(`hash_map_min_load_factor` / `min_node_count_for_auto_optimize`) never runs
on ordinary, non-snapshot `erase`: only `insert`, `insertOrReplace`, and the
post-snapshot `clearOutdatedNodes` call `optimizeIfNeeded`, so a large
`rmr`/delete workload can leave the `absl::flat_hash_map` at its old bucket
count until the next insert or snapshot cleanup.

This is intentional. `optimize` calls `rehash(0)`, which `absl` rebuilds
unconditionally ("n == 0 unconditionally rehashes as per the standard") - it
is O(N) even when it cannot shrink. Calling it from `erase` would turn a large
delete batch into O(N^2), and the existing no-shrink guard in
`optimizeIfNeeded` only protects the growing (insert) path. The sparse table
is instead reclaimed lazily on the next `insert`/`insertOrReplace`, on the
periodic post-snapshot `clearOutdatedNodes` (`clearGarbageAfterSnapshot`, run
on every snapshot regardless of where the deletes happened), or via a manual
`clrs` four-letter-word command.

Document this explicitly:
- a comment at the `erase` site explaining the deliberate omission;
- expanded descriptions for `hash_map_min_load_factor` and
  `min_node_count_for_auto_optimize`;
- two focused gtests: `SnapshotableHashMapEraseDefersAutoOptimizeUntilInsert`
  (bare erase leaves the bucket count unchanged; the next insert shrinks it)
  and `SnapshotableHashMapEraseReclaimedByPostSnapshotCleanup` (the post-
  snapshot cleanup shrinks the index even when all deletes were non-snapshot).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

Picked this up to clear the AI review's ⚠️ Request changes verdict.

Done (pushed in bb9b568):

  • Addressed the newest blocker — the ordinary-delete auto-optimization gap (SnapshotableHashTable.h:332) — by documenting it as intentional and pinning it with tests. optimize → map.rehash(0) is O(N) unconditionally (absl rebuilds the table even when it can't shrink), so calling it from erase would make a large rmr/delete batch O(N²); the existing no-shrink guard only protects the insert path. Sparse tables are reclaimed lazily on the next insert, on post-snapshot clearOutdatedNodes, or via clrs. Added a comment at the erase site, expanded both setting descriptions, and added two gtests (SnapshotableHashMapEraseDefersAutoOptimizeUntilInsert, SnapshotableHashMapEraseReclaimedByPostSnapshotCleanup). Bucket-count behavior verified against the real absl::flat_hash_map. Resolved that thread.

Still open (for the author):

  • The benchmark-evidence thread for the HashMap → absl::flat_hash_map swap. The two new settings default to 0 (auto-rehash off), so the only always-on change is the container swap. Keeper Stress Tests run in CI on every commit (links in the CI summary), but the explicit before/after keeper-bench + production-like numbers are still the author's to attach.

Recommendation — re-merge master: the branch is only ~2 days behind, but master landed a large Keeper refactor in that window (KeeperStorage.cpp ±2056 lines, KeeperStateMachine.cpp, KeeperStorage.h, ACLMap). A dry-run merge is textually conflict-free, but a refactor that size can merge clean and still be semantically wrong, and I can't build-verify it here. Better for @antonio2368 (Keeper domain) to do that merge and confirm the build/tests.

CI: all current failures are unrelated, pre-existing flakes — DeltaLake test_early_return_limit[1] (fails across ~12 unrelated PRs + master over 30 days), Not-ready Set logical error (#107619, 56 failures / 39 PRs in 14 days), and the BuzzHouse harness ERROR (no sanitizer error; embedded Keeper healthy in the server log).

@clickhouse-gh

clickhouse-gh Bot commented Jun 20, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.30% 85.30% +0.00%
Functions 92.50% 92.60% +0.10%
Branches 77.50% 77.50% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 230/255 (90.20%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 16 line(s) · Uncovered code

Full report · Diff report

@alexey-milovidov alexey-milovidov added the hold Skip for auto-updating. label Jul 6, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

Outdated after the recent rewrite.

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

Labels

hold Skip for auto-updating. pr-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants