Skip to content

Add file IO and integrate new keeper storage - #113903

Merged
al13n321 merged 48 commits into
masterfrom
kint
Aug 20, 2026
Merged

al13n321 merged 48 commits into
masterfrom
kint

Conversation

@al13n321

@al13n321 al13n321 commented Aug 8, 2026 •

Copy link
Copy Markdown
Contributor

Changelog category (leave one):

  • New Feature

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

Keeper can store data on disk now, in a custom LSM tree. It has similar performance to the previous storage. Use coordnation setting use_new_storage = true to enable, storage_memory_only = false to store files on disk, add data_storage_path or data_storage_disk to config to specify where to put the files. To write to S3, point data_storage_disk to a disk of type s3_plain.


#107261 added new storage with memory-only mode. This PR

  • Adds ability to store data in files. The storage is not actually persistent, the directory is wiped on startup and re-created from snapshot, just like with previous rocksdb storage. So the files don't have things like headers and version numbers yet, we can add that later if we want faster startup.
  • Integrates the new storage into keeper.

(This PR replaces #112378 )


Workflow [PR]
Sync PR [sync-upstream/pr/113903]

Version info

  • Merged into: 26.8.1.1743 (included in 26.8 and later)

al13n321 and others added 30 commits July 31, 2026 17:24
New events, all with the `KeeperLSMT` prefix, also registered in
`KeeperConstants.cpp` for the standalone keeper build:
 * flushes and merges finished successfully; exceptions in flushes, merges,
   and file deletions;
 * compressed and uncompressed bytes written by flushes;
 * in merge's `publish_results`: published output files and their compressed
   and uncompressed bytes, consumed input files and their uncompressed bytes
   (i.e. read and write throughput measured in files and in bytes);
 * entries appended by `appendUncommittedNode` (count and serialized bytes,
   broken down by `NodeAction`), and serialized bytes appended by
   `appendCommittedNode`;
 * throttled writes; committed and uncommitted memtables created;
 * `getUncommittedNode` hits and misses in uncommitted memtables;
 * the three return cases of `getCommittedNode`, and node cache entries
   re-pointed at a freshly loaded block;
 * for list operations: names obtained from memtables and from files, blocks
   and entries scanned by `SortedFile::listChildrenNames`, and
   `parent_paths_filter` usage (skipped / false positive / true positive);
 * the three cases of `SortedFile::getOrLoadBlock` (from the block info weak
   pointer, from the block cache, loaded a group from disk); blocks and
   uncompressed bytes loaded by `loadBlockGroup`.

Also add the `KeeperLSMTParentPathsFilterSize` asynchronous metric: total size
of `parent_paths_filter` bloom filters across all files.

Co-Authored-By: Claude Fable 5 <[email protected]>
`ErrorCodes::LOGICAL_ERROR` was declared in `SortedRun.cpp` (unused) but
used in `SortedFile.cpp` (undeclared). Five arm_tidy errors:
`getCommittedNode` and `writeInfoFile` can be const, an implicit
single-argument constructor, a non-const `auto &`, and a
`data()[i]` subscript.

CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112378&sha=03092ea47a22cc3906208473b908703e43e7984c&name_0=PR&name_1=Style%20check
PR: #112378
`getCommittedNode` definition made const to match the declaration,
`NodesReadView` constructor made explicit, `const auto &` in
`rollbackUncommittedDelta`.
`KeeperNodeStats::getEphemeralOwner` returns `CONTAINER_EPHEMERAL_OWNER`
(`INT64_MIN`) for container nodes, and `prepareImpl` passed it into
`LSMTDelta` as-is, so committing a container registered it in
`committed_ephemerals` under a nonexistent session. After a restart
nothing re-registers that session, and session cleanup failed with
"Session -9223372036854775808 is expected to have ephemeral paths but
no path is registered" (seen as `test_keeper_container_nodes` failures).
Normalize the owner to 0 for containers; they are tracked separately
via `is_container`/`container_paths`.
…or snapshots

`initializeDataDisk` wipes the node storage root on startup. If an
operator points `data_storage_disk`/`data_storage_path` at a disk or
directory that is (or contains) the log, snapshot or state storage,
startup would delete Keeper's own persistent state. Refuse to start
with `BAD_ARGUMENTS` instead: reject the same named disk, and reject a
local node-storage directory that is or contains another storage's
directory. The opposite nesting stays allowed - it is the default
layout (the node storage is a subdirectory of the coordination path).
The `SCOPE_EXIT` in `preprocessRequest` aborted with "Finalize not
called before returning" even when leaving through an exception.
`std::current_exception` is null while unwinding towards a handler that
has not been entered yet, so nothing useful could be logged here, and
aborting destroyed the only clue about the actual error. Let the
exception propagate to `KeeperStateMachine::preprocess`, whose handler
logs the message and stack trace before aborting.
`node_cache.map` is a `HashMap`, whose `erase` zeroes the cell without
running the value's destructor, so the entry's
`BlockWeakPtrWithSpinlock` never released its weak reference and the
block's control block leaked on every Create+Remove pair.
LeakSanitizer caught this in Keeper integration test runs. Release the
weak ref explicitly before erasing.

Also restore the `AppendRepointsDataIntoBlock` and
`NodeCacheEraseReleasesBlockRef` regression tests.
`KeeperStateMachine::apply_snapshot` destroys and recreates
`KeeperStorage` in-process, without going through the startup wipe in
`initializeDataDisk`. Published sorted files have
`delete_when_destroyed = false`, so every snapshot install left the
previous run set behind on `data_storage_*` until the next full
restart - a follower repeatedly applying snapshots leaked disk
indefinitely. Remove the files in `StorageState::shutdown` (the storage
is not persistent by design), including deletions that were still
queued for the background threads.
The storage-stats refactor silently dropped the metric, while the docs
still list it and existing dashboards may query it. Keep exporting it
as 0: there is no key arena at all in the new node storage.
The `lsmt` stress backend only set `use_new_storage`, but
`storage_memory_only` defaults to true, so it exercised the in-memory
LSMT instead of the file flush/merge/recovery path. Emit
`<storage_memory_only>0</storage_memory_only>` for it.

With `use_new_storage` defaulting to true, the `default` backend is the
memory-only LSMT, and the PR stress job (KEEPER_MATRIX_BACKENDS=default)
no longer covered the on-disk path at all. Widen the PR matrix to
`default,lsmt`.
`SnapshotWriterNodeStream::next` consumes the `memtables` vector as it
iterates (to free memory as it goes), so `getNodeCount` computed from
the remaining memtables shrank during iteration. `KeeperStorageSnapshot::serialize`
calls `getNodeCount` again after the iteration in a `chassert`, which
made every LSMT snapshot serialization fail with a logical error
`nodes_seen == snapshot.view->getNodeCount()` in debug and sanitizer
builds - crashing Keeper on the first snapshot in most integration
tests, in stateless runs, and in the `ApplySnapshotReplacesCommittedState/LSMT`
unit test. Calculate the count once in the constructor.

CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112378&sha=latest&name_0=PR
PR: #112378

Co-Authored-By: Claude Fable 5 <[email protected]>
`SystemKeeperStorageSource::generate` calls `KeeperNodesReadView::next`
once more after the call that returned false (one call per output block),
which tripped `chassert(!at_end)` in `SnapshotWriterNodeStream::next` -
any query of `system.keeper_storage` failed with a logical error
`!at_end` in debug and sanitizer builds (AST fuzzer,
`01161_all_system_tables`). The `Mem` storage view already tolerates
repeated calls; make the LSMT view match, and add a test pinning the
read view contract for both implementations.

CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112378&sha=latest&name_0=PR
PR: #112378

Co-Authored-By: Claude Fable 5 <[email protected]>
> longer available. The RocksDB results recorded here and in the tables below are kept for
> historical reference only. A replacement storage backend is coming soon, and this README will
> be updated with new benchmark results once it lands.
> historical reference only. A replacement storage backend (`use_lsmt_storage`) is coming soon, and

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 note still says the replacement backend is "coming soon", which matches what I can verify in this PR: the public text now claims use_lsmt_storage has similar performance / lower memory usage, but the comparative keeper-stress numbers are still not published here and the Keeper Stress Tests (PR) CI report is pass/fail only. For a new Keeper storage backend, I think we need the actual before/after benchmark summary in this PR (or the performance claim toned down) before merging.

@clickhouse-gh

clickhouse-gh Bot commented Aug 15, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing ea0bd0f26 with master 27f733d4f (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 703.88 MiB 701.30 MiB -2.58 MiB (-0.37%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Object file sizes

36 object files changed (+595.26 KiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Coordination/KeeperStorageImpl.cpp.o 649.49 KiB 886.79 KiB +237.30 KiB (+36.54%)
src/CMakeFiles/dbms.dir/Coordination/KeeperLSMTNodesStorage.cpp.o new 90.08 KiB +90.08 KiB
src/CMakeFiles/dbms.dir/Coordination/Storage/StorageState.cpp.o 148.66 KiB 211.01 KiB +62.35 KiB (+41.94%)
src/CMakeFiles/dbms.dir/Coordination/KeeperContext.cpp.o 254.98 KiB 305.36 KiB +50.38 KiB (+19.76%)
src/CMakeFiles/dbms.dir/Coordination/Storage/SortedFile.cpp.o 42.55 KiB 88.93 KiB +46.37 KiB (+108.97%)
src/CMakeFiles/dbms.dir/Coordination/Storage/NodeRefCache.cpp.o 7.25 KiB 38.45 KiB +31.20 KiB (+430.05%)
src/CMakeFiles/dbms.dir/Coordination/Storage/SortedRun.cpp.o 60.60 KiB 79.20 KiB +18.60 KiB (+30.70%)
src/CMakeFiles/dbms.dir/Coordination/KeeperStorage.cpp.o 399.62 KiB 418.21 KiB +18.59 KiB (+4.65%)
src/CMakeFiles/dbms.dir/Coordination/Storage/BackgroundWork.cpp.o 173.60 KiB 190.86 KiB +17.26 KiB (+9.94%)

737 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

98 translation units recompiled, 683 s compile time in total, 97 of them have a recent master baseline.

Median compile-time ratio to the baselines is ×0.94 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost -44.1 s (-6%) in total before that adjustment.

Symbol sizes
Binary Symbol Master PR Δ
programs/clickhouse-keeper ProfileEvents::global_counters_storage 11.31 MiB 11.62 MiB +320.00 KiB (+2.76%)
programs/clickhouse ProfileEvents::global_counters_storage 11.31 MiB 11.62 MiB +320.00 KiB (+2.76%)

Job report

al13n321 and others added 3 commits August 17, 2026 20:20
Mechanical change: insert <data_storage_path> next to the existing
log_storage_path/snapshot_storage_path in every Keeper config, so that the
LSMT node storage data files land in an explicitly configured directory when
storage_memory_only is disabled.

Co-Authored-By: Claude Fable 5 <[email protected]>
…lt, disable lsmt in keeper stress in ci for now
@al13n321

Copy link
Copy Markdown
Contributor Author

Keeper stress test in CI got MEMORY_LIMIT_EXCEEDED with LSMT storage because its RemoveRecursive uses more temp memory (bigger deltas and temp node list, a few GB for 15M nodes). Instead of optimizing that, #111155 makes keeper-stress avoid RemoveRecursive if there are too many nodes to remove, which seems like a better approach anyway (RemoveRecursive is not going to survive 100M nodes regardless of implementation). We should re-enable LSMT in keeper stress after that PR is merged.

}
catch (...)
{
DB::tryLogCurrentException(log, fmt::format("Failed to delete file {} during shutdown", path));

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.

removeFileIfExists failures are only logged here, but shutdown then drops the last references to those paths (delete_when_destroyed has already been cleared for visible files, and leftover_deletes->paths.clear() runs below). During KeeperStateMachine::apply_snapshot, that means a transient delete error leaks the old sorted-run files/objects until the next full restart, because the recreated storage no longer knows their randomized names.

Could we either fail the snapshot-install cleanup on delete failure or keep failed paths queued for retry instead of forgetting them here?

@antonio2368

antonio2368 commented Aug 18, 2026 •

Copy link
Copy Markdown
Member

RemoveRecursive should have a limit in all its calls because of that reason. Does that mean that old in-memory implementation could survive it?

@al13n321

Copy link
Copy Markdown
Contributor Author

Does that mean that old in-memory implementation could survive it?

Yes. The old storage uses less memory for deltas, and directly removes nodes from the main map (freeing memory) instead of appending tombstones to a memtable (allocating more memory, until a later merge frees it).

Bigger RemoveRecursive requests break either way: preprocessing/committing the request takes long enough for nuraft to give up an reelect the leader. I was thinking of adding partial mode for RemoveRecursive: it would remove up to a given number of nodes per request, then the user would do it in a loop until the whole subtree is gone; so raft doesn't choke on individual requests, and uncommitted state doesn't grow big. But maybe that's overkill and the manual recursive remove from #111155 (traverse the tree on client side using batched List requests, using list-with-stats to avoid listing children of leaves; then do batched Remove-s) is efficient enough.

@al13n321
al13n321 enabled auto-merge August 19, 2026 00:53
"KEEPER_RUN_NO_FAULT_TESTS": "true",
# TODO: re-enable the lsmt backend after the memory usage of huge RemoveRecursive
# preprocessing is bounded (a whole-tree remove at bench cleanup OOMs the container).
"KEEPER_MATRIX_BACKENDS": "default",

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 drops the new lsmt backend from the PR keeper-stress matrix entirely, so the only CI job meant to compare Keeper backends no longer exercises the feature this PR is shipping. That leaves the current public contract unsupported: the PR body still says use_lsmt_storage has "similar performance", CoordinationSettings describes it as lower-memory / same-performance, and the stress README now documents lsmt as a backend, but there is no published before/after evidence for it in this PR anymore.

I think we need either a bounded lsmt stress lane here (for example after the cleanup approach from #111155 lands), or the performance claims should be toned down and the backend presented as experimental / unmeasured until that coverage exists.

<log_storage_disk>log_azure_plain</log_storage_disk>
<latest_log_storage_disk>log_local</latest_log_storage_disk>
<snapshot_storage_disk>snapshot_local</snapshot_storage_disk>
<data_storage_path>/var/lib/clickhouse/coordination/data</data_storage_path>

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 Azure integration test still never turns on the new node-storage backend: use_lsmt_storage stays at its default false, so the added data_storage_path is unused here and the test continues to cover only Keeper log replay from object storage. That is too weak for the user-facing claim in the changelog entry that Keeper node storage can be placed on an s3_plain data_storage_disk.

Please add one focused integration test that boots Keeper with use_lsmt_storage=1, storage_memory_only=0, and node files on object storage, then restarts and verifies the znodes are recovered from snapshot/log replay. Otherwise the changelog entry should stop advertising the s3_plain path for now.

@al13n321
al13n321 added this pull request to the merge queue Aug 20, 2026
Merged via the queue into master with commit bcb7844 Aug 20, 2026
344 of 348 checks passed
@al13n321
al13n321 deleted the kint branch August 20, 2026 08:16
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 20, 2026
pull Bot pushed a commit to admariner/ClickHouse that referenced this pull request Sep 12, 2026
…d named collection

Under the Stress test a table can survive its own `DROP TABLE` while the test's
`DROP NAMED COLLECTION` still runs. The next server start then cannot load the
leftover metadata:

  Code: 722 Waited job failed: Code: 695 Load job 'load table test_7.test_s3_base_nc'
  failed: Code: 669 There is no named collection `nc_04626_s3_base_setting_test_7`:
  Cannot attach table `test_7`.`test_s3_base_nc` from metadata file
  store/8bc/.../test_s3_base_nc.sql (NAMED_COLLECTION_DOESNT_EXIST)
  -> server process is not running after 11 start attempts

With `async_load_databases = 0`, which `tests/docker_scripts/stress_runner.sh` sets
with probability 1/2, that failure aborts the whole server rather than just the one
table, and the entire Stress exercise for that run produces nothing: no crash
detection, no sanitizer report, no hung check. CIDB records only
`Cannot start clickhouse-server` and `Check failed`.

Four links, all three of the first ones observed in that order in the server log of
the most recent occurrence:

  L1 `ignore_drop_queries_probability = 0.2` (`ci/jobs/scripts/stress/stress.py`)
     makes `InterpreterDropQuery` replace a client `DROP TABLE` with
     `TRUNCATE TABLE` when the engine does not store data on disk, and ignore it
     outright when it does. An engine that implements `truncate` (`S3`) or takes
     the ignore branch (`Distributed`) therefore leaves the table in place and
     still reports rc 0, so an exit-code-gated teardown proceeds. An engine
     implementing neither (`URL`, `PostgreSQL` and `S3Queue` inherit the throwing
     `IStorage::truncate`) gives the client `Code: 48` instead and the teardown
     stops there.
  L2 `ast_fuzzer_runs = 5` with `ast_fuzzer_any_query = true`
     (`tests/docker_scripts/stress_tests.lib`, applied by both the Stress test and
     the Upgrade check) lets the server-side AST fuzzer replay table DDL. The two
     observed mutations are a `DETACH TABLE`, which keeps the metadata file, and a
     `__fuzz_N` clone of a `CREATE TABLE`, which inherits the collection reference.
  L3 `InterpreterDropNamedCollectionQuery` filters dependents through
     `DatabaseCatalog::isTableExist`, false for a detached table, so the dependency
     guard passes and the edge is removed. The collection drop succeeds.
  L4 the `ATTACH` at the next start throws `NAMED_COLLECTION_DOESNT_EXIST` and
     `DatabaseOrdinary` rethrows it.

L1 and L2 are deliberate CI fault injections and L3/L4 are server-side, so the fix
belongs in the tests: pin `ast_fuzzer_any_query = 0` on the client invocations that
issue table DDL for the collection-backed table. That closes both observed strand
shapes, including the clone path, and it restores the setting's own default
(`src/Core/Settings.cpp` declares it `false`) for exactly those statements rather
than switching a feature off. `SELECT` and `SHOW CREATE` stay fuzzed, and
`isReadOnlyQuery` in `executeQuery.cpp` admits them whichever value the setting
has. The merged in-tree precedent for this class is
`03822_named_collection_drop_dependency_check.sh`.

Blast radius, CIDB, `test_name = 'Cannot start clickhouse-server'` with
`NAMED_COLLECTION_DOESNT_EXIST` in the context. Over 30 days: 14 rows, 13 distinct
pull requests (ClickHouse#113903 hit twice), 0 with `pull_request_number = 0`, every one a
`Stress test (*)` flavour, spread over 5 tests. The four changed here carry 13 of
those rows:

  04320_url_engine_dispatch_partition_and_format_named_collection.sh  6  08-08..08-17
  04626_s3_base_setting_named_collection.sh                           3  09-05..09-06
  04512_remote_missing_named_collection.sh                            3  08-15..08-19
  04327_s3queue_server_credentials.sh                                 1  08-14

The 14th belongs to `03822`, which is already pinned; its single hit predates its
pins and it has had none since.

The 30-day window is what shows no master hits, and that is a property of the window
rather than of the defect. Widening the same signature query gives 19 rows at 40 days
and 20 at 45, and the two extra rows both satisfy the full true-master predicate
(`pull_request_number = 0` with `head_ref = 'master'`), both stranding
`04320_url_engine_dispatch_partition_and_format_..._n`:

  2026-08-07 15:13:26  Stress test (arm_msan)
  2026-07-31 10:53:22  Stress test (arm_tsan)

So this is not confined to pull requests: it has already destroyed two master Stress
runs.

The carrier list is mechanical rather than a reading of a sample. A candidate is a
stateless test that creates and drops a named collection SQL-side and persists an
engine definition naming it, which means `CREATE TABLE`, `CREATE OR REPLACE TABLE`
or a full-definition `ATTACH TABLE`: the last is an `ASTCreateQuery`, writes the
same metadata file and is cloned the same way, so scanning for `CREATE TABLE` alone
misses it. Three candidates are deliberately left unpinned:

  - `04070_url_base_setting.sh` and `04546_postgresql_engine_settings.sql`, because
    `URL` and `PostgreSQL` implement neither `truncate` nor `storesDataOnDisk`, so
    L1's only reachable branch for them raises `Code: 48`, and in both files that
    aborts the statement stream before the collection drop. The collection outlives
    the table, which is the safe direction.
  - `04891_nats_credential_file_path_restriction.sql`, whose metadata-writing
    statement is a full-definition `ATTACH` carrying an explicit UUID. In an
    `Atomic` database a clone either collides with the live table's UUID or is
    rejected by `InterpreterCreateQuery`, and an `attach`-flag-dropped mutant fails
    NATS strict startup before committing metadata, so no mutant can persist an
    engine definition of its own. The lane is `Atomic`: neither `stress.py` nor
    `stress_runner.sh` passes `--db-engine`.
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.

4 participants