Skip to content

Keeper Nodes with TTL - #100397

Merged
scanhex12 merged 65 commits into
masterfrom
keeper_ttl
Jun 23, 2026
Merged

scanhex12 merged 65 commits into
masterfrom
keeper_ttl

Conversation

@scanhex12

@scanhex12 scanhex12 commented Mar 22, 2026 •

Copy link
Copy Markdown
Member

Continuation of #79071

Changelog category (leave one):

  • New Feature

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

Support TTL nodes in ClickHouse Keeper. ClickHouse-specific notes:

  • Opt-in via the create_ttl feature flag; requires write_snapshot_version >= 8 on every replica (snapshot V8 persists ttl, digest bumped to V5).
  • Unlike ZooKeeper, a TTL node cannot have children — ttl reuses the seq_num slot in the node union, so creating a child under a TTL node returns ZBADARGUMENTS.
  • destroy_time = mtime + ttl, refreshed on every set; ttl bounded by MAX_KEEPER_TTL_MS.
  • Expiry runs on the leader only: a background thread (ttl_gc_period_ms, ttl_gc_batch_size) submits TryRemove through Raft, re-validated deterministically at commit so all replicas agree.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.6.1.1170

@scanhex12
scanhex12 marked this pull request as draft March 22, 2026 22:32
@kssenii kssenii self-assigned this Mar 22, 2026
@clickhouse-gh

clickhouse-gh Bot commented Mar 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f45a401]

Summary: ❌

job_name test_name status info comment
Stress test (arm_asan_ubsan) FAIL
Hung check failed, possible deadlock found FAIL cidb, issue

AI Review

Summary

This PR adds Keeper TTL znodes, including CreateTTL parsing, snapshot/digest persistence, TTL GC, and integration/unit coverage. The implementation is much closer than earlier revisions, but several contract issues remain around long-running GC safety, mixed-config/failover expiry, ZooKeeper-compatible Stat output, log import, and user documentation.

Findings

❌ Blockers

  • [src/Coordination/KeeperDispatcher.cpp:285] next_gc_xid is a signed Int32 incremented once per GC TryRemove. With the default ttl_gc_batch_size=256 and ttl_gc_period_ms=250, a leader that continuously expires nodes can hit signed overflow in about 24 days, which is undefined behavior and also breaks the dispatcher request identity invariant. Suggested fix: use a non-overflowing Int64/UInt64 identity with use_xid_64=true, or implement explicit bounded wrap semantics that cannot collide with in-flight GC requests.

⚠️ Majors

  • [src/Coordination/KeeperDispatcher.cpp:197] TTL expiry is gated only by the local CREATE_TTL feature flag. A node can still contain TTL metadata while the local flag is disabled, for example after failover from an enabled leader or after config rollback; if that node becomes leader, existing TTL nodes stop expiring. Suggested fix: start the GC loop whenever storage contains TTL nodes, or always run it as a cheap no-op and keep the flag only for accepting new CreateTTL writes.
  • [src/Coordination/KeeperStorage.h:100] TTL nodes are stored internally, but public Coordination::Stat still reports ephemeralOwner=0 for them. ZooKeeper encodes TTL nodes in Stat.ephemeralOwner, so clients cannot distinguish TTL znodes and CheckStat against the TTL owner value fails. Suggested fix: convert TTL nodes to the ZooKeeper TTL ephemeralOwner encoding when filling/comparing public Stat, without registering them as ephemeral sessions internally.
  • [src/Common/ZooKeeper/ZooKeeperConstants.h:41] Adding CreateTTL makes Keeper accept op code 21, but ZooKeeperDataReader::deserializeTxnImpl still rejects transaction type 21 with NOT_IMPLEMENTED. Importing or restoring ZooKeeper logs containing TTL znodes fails despite the advertised feature. Suggested fix: add a CreateTTL transaction decoder that preserves ttl, or explicitly reject ZooKeeper-log import for TTL nodes with a clear user-facing guard.
  • [src/Common/ZooKeeper/TestKeeper.cpp:360] TestKeeper records include_ttl, but it does not mirror production validation for TTL creates: child creation under a TTL node, include_ttl && is_ephemeral, and invalid TTL ranges are accepted. Tests using TestKeeper can pass with behavior production Keeper rejects. Suggested fix: apply the same TTL validation in TestKeeperCreateRequest::process.
  • [src/Coordination/KeeperStorage.cpp:4042] [dismissed by author -- https://github.com/Keeper Nodes with TTL #100397#discussion_r3023590774] collectExpiredTTLPaths still scans all ttl_paths and does a container.find per path every GC period. On KeeperRocksStorage this is periodic O(N) RocksDB lookup/deserialization work and can become a foreground-load hazard on large trees. The author preferred scanning to avoid index memory, but the risk remains for large TTL populations. Suggested fix: use a due-time ordered index or another bounded-work design, or add hard evidence that the scan cannot harm Keeper under expected TTL cardinalities.
  • [src/Common/ZooKeeper/KeeperFeatureFlags.h:33] CREATE_TTL is a new user-facing Keeper feature with non-obvious rollout requirements, but the PR has no documentation update and the documentation checkbox is unchecked. Suggested fix: add docs for create_ttl, write_snapshot_version >= 8, TTL limits, GC settings, and mixed-version rollout.

💡 Nits

  • [src/Coordination/CoordinationSettings.cpp:84] write_snapshot_version defaults to 6 and runtime validation still accepts 6..MAX_SUPPORTED, but the setting description says "supported: 8 and above". Suggested fix: change the text to match actual supported values and mention that TTL nodes require 8.
Tests
  • ⚠️ Add focused coverage for TTL Stat.ephemeralOwner on CreateTTL, exists/get, and CheckStat.
  • ⚠️ Add coverage for ZooKeeperDataReader importing a CreateTTL transaction, or for the explicit unsupported-path error if import is intentionally not supported.
  • ⚠️ Add a failover/config-rollback test proving existing TTL nodes still expire when the local CREATE_TTL flag is disabled, or document and reject that state.
Final Verdict

Status: ❌ Block

Minimum required actions: remove the GC Int32 overflow path, fix or explicitly reject the remaining compatibility gaps, add the missing user documentation, and cover the public Stat/log-import/failover behavior with focused tests.

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Mar 24, 2026
Comment thread src/Coordination/KeeperContext.cpp Resolved
Comment thread src/Coordination/KeeperDispatcher.cpp Resolved
Comment thread src/Coordination/Utils.cpp Resolved
Comment thread src/Coordination/KeeperStorage.cpp Resolved
Comment thread src/Coordination/KeeperStorage.h Resolved
@scanhex12
scanhex12 marked this pull request as ready for review March 24, 2026 20:24
Comment thread src/Coordination/KeeperStorage.h Resolved
Comment thread src/Coordination/KeeperStorage.cpp Resolved
Comment thread src/Coordination/KeeperStorage.cpp Resolved
Comment thread src/Coordination/KeeperStorage.cpp Resolved
Comment thread src/Common/ZooKeeper/IKeeper.h Resolved
Comment thread src/Coordination/KeeperStorage.cpp Resolved
Comment thread src/Coordination/KeeperStateMachine.cpp Resolved
Comment thread src/Coordination/KeeperDispatcher.cpp Resolved
Comment thread src/Common/ZooKeeper/ZooKeeperCommon.h Resolved
Comment thread src/Coordination/KeeperStorage.cpp Resolved

@clickhouse-gh clickhouse-gh Bot left a comment

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.

Submitting pending review to allow additional standalone inline comments.

Comment thread src/Coordination/Utils.cpp Resolved
Comment thread src/Coordination/KeeperStorage.cpp Outdated
{
std::vector<std::pair<String, bool>> nodes;

for (const auto & ttl_path : ttl_paths)

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.

collectExpiredTTLPaths does a full scan of ttl_paths and calls container.find for each path on every GC tick. On KeeperRocksStorage, RocksDBContainer::find is a DB lookup/deserialize per key, so this turns into periodic O(N) RocksDB reads every ttl_gc_period_ms (default 250 ms), which can become a hot background load and starve foreground requests on large trees.

Please avoid full key-by-key lookups in the periodic path. A practical fix is to maintain an in-memory TTL index keyed by destroy_time (updated on create/set/remove/snapshot load), so each tick only pops entries with destroy_time <= now and verifies node existence/version before enqueueing TryRemove.

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 is still an O(N) scan over ttl_paths on every GC tick in collectExpiredTTLPaths: we call container.find(ttl_path) for each tracked path and only stop after collecting batch_size expired nodes. If only a small fraction is expired, the loop still walks almost the whole set each period.

For KeeperRocksStorage, each find is a RocksDB lookup, so this remains a potentially heavy periodic background load. Can we switch to an expiry-ordered index (or another due-time driven structure) so per-tick work scales with expired nodes instead of total TTL nodes?

@kssenii kssenii 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.

LGTM, but please remove mutex from KeeperStorage<Container>::updateStats as I wrote in the above comments

Comment thread src/Common/ZooKeeper/ZooKeeperCommon.h Resolved
scanhex12 and others added 3 commits June 21, 2026 23:35
Port the Keeper TTL feature onto master's refactored KeeperStorage:
- createNode/prepareCreateNode now take ACLId acl_id plus optional ttl;
  prepareCreateNode sets the uncommitted node's TTL and carries it in
  CreateNodeDelta.
- Drop the obsolete UncommittedState::applyDelta / materializeACL (master
  applies create deltas via prepareCreateNode; UncommittedNode no longer
  stores acls).
- create preprocess returns Coordination::Error (master convention) instead
  of building a Delta list; keep the TTL validation and the reject-on-TTL
  parent check.
- remove preprocess: re-add the internal TTL garbage-collector session ACL
  bypass under master's inlined check_acl flow.
- Adapt the TTL gtests to master's getNode -> UncommittedNodeRef API.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
DB::setThreadName(ThreadName::KEEPER_TTL_GARBAGE_COLLECTOR);

const auto & shutdown_called = keeper_context->isShutdownCalled();
Int32 next_gc_xid = 0;

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.

next_gc_xid is a signed 32-bit counter that is incremented once per TTL GC TryRemove. On a leader that is continuously expiring TTL nodes, the default ttl_gc_batch_size=256 and ttl_gc_period_ms=250 allow roughly 1024 increments per second, so this reaches signed overflow in about 24 days; a larger configured batch reaches it sooner. Signed overflow is undefined behavior, and after wrap the internal request identity also stops being unique.

Please make the GC request id use a non-overflowing representation, e.g. keep an Int64/UInt64 counter and send these internal requests with 64-bit xids, or otherwise implement explicit bounded wrap semantics that preserve the dispatcher dependency invariant.

@scanhex12
scanhex12 requested a review from Michicosun June 22, 2026 16:38
Comment thread src/Common/ZooKeeper/TestKeeper.cpp Resolved
Comment thread src/Coordination/KeeperDispatcher.cpp Resolved
Comment thread src/Coordination/KeeperStorage.cpp Resolved
Comment thread src/Coordination/KeeperStorage.cpp Resolved
Comment thread src/Coordination/KeeperStorage.cpp Resolved
Comment thread src/Coordination/KeeperStorage.h Resolved
@Michicosun
Michicosun dismissed their stale review June 23, 2026 11:10

unblocking

created_node.data = data;
created_node.is_ephemeral = is_ephemeral;
created_node.is_sequental = is_sequential;
created_node.is_ttl = include_ttl;

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.

TestKeeper now records include_ttl, but its create path still accepts combinations that production Keeper rejects: creating a child under an existing TTL node, include_ttl && is_ephemeral, and invalid TTL ranges. The real storage path rejects those before creating the node, so tests that use TestKeeper can pass with behavior that fails against Keeper. Please mirror the production CreateTTL validation here before setting created_node.is_ttl.

Reconfig = 16,
CheckWatch = 17,
RemoveWatch = 18,
CreateTTL = 21,

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.

Adding CreateTTL here makes Keeper accept op code 21, but the ZooKeeper transaction-log importer has a separate decoder and still rejects transaction type 21 in ZooKeeperDataReader::deserializeTxnImpl. That means importing/restoring ZooKeeper data that already contains TTL nodes fails with NOT_IMPLEMENTED even though the server now advertises TTL-node support. Please add a CreateTTL transaction decoder there that preserves the TTL value, or explicitly keep this feature unsupported for ZooKeeper-log import with a clear user-facing guard.

@clickhouse-gh

clickhouse-gh Bot commented Jun 23, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

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

Changed lines: Changed C/C++ lines covered by tests: 718/895 (80.22%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 8 line(s) · Uncovered code

Full report · Diff report

@scanhex12
scanhex12 enabled auto-merge June 23, 2026 19:39
@scanhex12

Copy link
Copy Markdown
Member Author

The failures in the private CI seem unrelated, so I'll merge PR

@scanhex12
scanhex12 added this pull request to the merge queue Jun 23, 2026
Merged via the queue into master with commit 7a5b9eb Jun 23, 2026
165 of 167 checks passed
@scanhex12
scanhex12 deleted the keeper_ttl branch June 23, 2026 20:31
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 23, 2026
al13n321 added a commit that referenced this pull request Jun 25, 2026
Resolve conflicts from the Keeper TTL garbage-collector feature
(#100397, #100397), the only
PR that conflicted with the Keeper RocksDB storage removal.

Resolution:
- Keep this branch's de-templated, RocksDB-free `KeeperStorage` /
  `KeeperStateMachine` while preserving the new TTL feature: `ttl` parameter
  on `createNode`, `ttl_paths` / `committed_ttl_nodes` bookkeeping in
  `removeNode`, `collectExpiredTTLPaths`, `containsTTLPath`, and
  `getExpiredTTLPathsForGarbageCollector` (now concrete methods, the
  `TSA_NO_THREAD_SAFETY_ANALYSIS` annotations retained).
- `processWatches` for `Remove` now iterates `deltas` (no longer ignored).
- Keep `RocksDBContainer.h` deleted (modify/delete conflict).
- Port the new TTL unit tests in `gtest_coordination_storage.cpp` and
  `gtest_coordination_snapshot.cpp` to the single memory-storage fixture:
  drop the `setRocksDBDirectory` / `ChangelogDirTest rocks` setup and the
  `KeeperSnapshotManager<Storage>` / `KeeperStorageSnapshot<Storage>` template
  arguments, matching this branch's conventions.

All touched Coordination translation units pass `-fsyntax-only` against the
merged headers.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
Fixes from PR ClickHouse#100397 review (comment 4118957777). All seven addressed
behaviour gaps are independently triggerable; no protocol or on-disk
version was bumped, so the change preserves rolling-upgrade safety.

* B1 (snapshot-version gate): refuse to start with `CREATE_TTL` enabled
  while `write_snapshot_version < 8`. Older snapshot formats drop the
  `destroy_time`/`ttl` fields entirely, which would silently turn TTL
  nodes into permanent persistent nodes on the next snapshot. The bump
  must be explicit because the setting can only be raised after the whole
  cluster has been upgraded.
* B3 (TTL-GC scan locking): `collectExpiredTTLPaths` now takes
  `storage_mutex` in shared mode while iterating `ttl_paths`/`container`.
  Commits hold the same mutex exclusively, so the scan no longer races
  with concurrent state mutations.
* B4 (TTL value validation): reject `ttl <= 0` and `ttl > MAX_KEEPER_TTL_MS`
  (matching ZK's `EphemeralType.TTL.maxValue() = 0x00FFFFFFFFFFFFFFL`).
  The bound keeps `time + ttl` from overflowing signed 64-bit when
  computing `destroy_time`.
* B5 (create-mode classification): reject unknown create-mode flag values
  with `ZBADARGUMENTS` and reject the inconsistent combinations
  `Create2 + TTL-create-mode` and `CreateTTL-opnum / non-TTL-create-mode`
  at wire-read time, so feature-gating cannot be bypassed by mismatched
  opnum and flags. `getOpNum` now classifies CreateTTL ahead of Create2.
* B6 (TTL-GC bypasses ACL check): short-circuit `checkAuth` for
  `try_remove` requests issued by `keeper_internal_ttl_garbage_collector_session_id`.
  The server-internal session has no ACLs and must be able to expire
  user nodes regardless of user-level Delete denies.
* B7 (validate TTL+ephemeral before mutating state): move the
  `include_ttl && is_ephemeral` reject above the
  `uncommitted_state.ephemerals` insert so a rejected `Create` inside a
  `Multi` no longer leaves an orphan ephemeral entry behind.
* B8 (rollback restores `destroy_time`): capture `old_destroy_time`
  alongside the existing `old_stats`/`old_num_children` in
  `UpdateNodeStatDelta` and restore it on rollback. Otherwise a `Set`
  that refreshed the TTL deadline, when rolled back as part of a failed
  `Multi`, would leak the refreshed deadline into uncommitted state.

B2 (digest must hash `destroy_time`/`ttl`) is deliberately deferred: it
requires bumping `KEEPER_CURRENT_DIGEST_VERSION`, which by the same
rolling-upgrade policy as `write_snapshot_version` must be operator-opted
in after a full cluster upgrade, and is large enough to warrant its own
change.

CI report: ClickHouse#100397 (comment)

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
Regression tests for the blocker fixes in the previous commit, covering
corner cases of the Keeper TTL feature:

* TestCreateTTLRejectsInvalidValues — Create with ttl <= 0 or
  ttl > MAX_KEEPER_TTL_MS is rejected with ZBADARGUMENTS; boundary
  values (1 and MAX_KEEPER_TTL_MS) are accepted.
* TestCreateTTLAndEphemeralDoesNotLeakEphemeral — a rejected Create
  with both include_ttl and is_ephemeral set does not leave an entry
  behind in uncommitted_state.ephemerals.
* TestFailedMultiRollsBackTTLDestroyTime — when a Multi containing a
  Set on a TTL node fails on a later subrequest, the uncommitted
  destroy_time is restored to its original value.

Each test runs across all four storage variants (memory/rocks ×
digest-enabled/disabled). The previously added
TestTTLGCDoesNotRemoveRecreatedNode (race against delete+recreate)
remains the regression test for the deleteContainer-semantics fix.

CI report: ClickHouse#100397 (comment)

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
Resolve conflicts from the Keeper TTL garbage-collector feature
(ClickHouse#100397, ClickHouse#100397), the only
PR that conflicted with the Keeper RocksDB storage removal.

Resolution:
- Keep this branch's de-templated, RocksDB-free `KeeperStorage` /
  `KeeperStateMachine` while preserving the new TTL feature: `ttl` parameter
  on `createNode`, `ttl_paths` / `committed_ttl_nodes` bookkeeping in
  `removeNode`, `collectExpiredTTLPaths`, `containsTTLPath`, and
  `getExpiredTTLPathsForGarbageCollector` (now concrete methods, the
  `TSA_NO_THREAD_SAFETY_ANALYSIS` annotations retained).
- `processWatches` for `Remove` now iterates `deltas` (no longer ignored).
- Keep `RocksDBContainer.h` deleted (modify/delete conflict).
- Port the new TTL unit tests in `gtest_coordination_storage.cpp` and
  `gtest_coordination_snapshot.cpp` to the single memory-storage fixture:
  drop the `setRocksDBDirectory` / `ChangelogDirTest rocks` setup and the
  `KeeperSnapshotManager<Storage>` / `KeeperStorageSnapshot<Storage>` template
  arguments, matching this branch's conventions.

All touched Coordination translation units pass `-fsyntax-only` against the
merged headers.

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

Labels

pr-feature Pull request with new product feature 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.

6 participants