Repository navigation
Try absl::flat_hash_map in Keeper storage - #85138
antonio2368 wants to merge 25 commits into
Conversation
|
Workflow [PR], commit [bb9b568] Summary: ❌
AI ReviewSummaryThis PR replaces Keeper's in-memory node index with Tests
Final VerdictStatus: 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. |
george-larionov
left a comment
There was a problem hiding this comment.
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.
|
|
||
| void optimizeIfNeeded() | ||
| { | ||
| if (min_load_factor > 0 && map.load_factor() < min_load_factor && map.size() > min_node_count_for_auto_optimize) |
There was a problem hiding this comment.
So by default the optimization is disabled?
There was a problem hiding this comment.
Yes, I'm not sure about the impact of it, especially when we have 100mil nodes.
So I added metric and made it configurable.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Yes, I plan to test it on some of our heavier instances
7e9ae3b to
a397cf2
Compare
|
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? |
|
@george-larionov we have keeper bench + some heavy instance we can test it on. |
|
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. |
How was it? |
# 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]>
b3ce199 to
2d83a3a
Compare
# Conflicts: # src/Common/ProfileEvents.cpp
…LOCK_EXCLUSIVE` macro https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=85138&sha=latest&name_0=PR Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
|
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. |
# 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>>; |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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).
There was a problem hiding this comment.
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 to0, i.e. automatic rehashing is off by default, so it adds no work on the default hot path. The only always-on change is theHashMap→absl::flat_hash_mapcontainer 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.
…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
`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]>
|
Updated the branch and addressed the outstanding review item.
On the previous CI run (commit 36aad5e), all 5628 individual stateless tests passed; the two reported items in 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. |
|
Merged the latest The two CI failures on the previous run are both unrelated to this Keeper-only change:
@groeneai, please investigate the |
|
Tracking. STID 1719-3ae5 ( 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 |
`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]>
|
Updated the branch and addressed the latest review.
On the previous (pre-merge) CI run, the |
|
@alexey-milovidov investigation result for the flaky 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 Breakdown:
Two of those three azure hits are from 2026-06-09, which was a runner-wide OOM event: 552 distinct tests failed on So there is no deterministic reproducer and no test-level bug. The test already carries My recommendation is to leave the test as is since master is clean. Do you want me to add (session cron:clickhouse-worker-slot-2:20260610-225500) |
`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]>
|
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? |
|
@alexey-milovidov confirmed, and tracking under #80564. Unrelated to this PR. STID 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 One caveat: 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 |
|
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 Verified locally on master Session: cron:clickhouse-worker-slot-2:20260612-230800 |
@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. |
|
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. |
…eper Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
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]>
|
Picked this up to clear the AI review's Done (pushed in bb9b568):
Still open (for the author):
Recommendation — re-merge CI: all current failures are unrelated, pre-existing flakes — DeltaLake |
LLVM Coverage Report
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 |
|
Outdated after the recent rewrite. |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Improve
clrscommand by rehashing internal hash map to reduce memory usage. Add automatic rehashing of internal hash map controlled withkeeper_server.coordination_settings.hash_map_min_load_factorandkeeper_server.coordination_settings.min_node_count_for_auto_optimize.Documentation entry for user-facing changes