Skip to content

Keeper log s3 - #79991

Closed
trololo23 wants to merge 62 commits into
ClickHouse:masterfrom
trololo23:keeper_log_s3
Closed

trololo23 wants to merge 62 commits into
ClickHouse:masterfrom
trololo23:keeper_log_s3

Conversation

@trololo23

@trololo23 trololo23 commented May 9, 2025 •

Copy link
Copy Markdown

Experimental support for storing the Keeper changelog directly on object storage (S3) instead of (or in addition to) a local disk, gated behind the coordination setting s3_experimental_changelog. Enables running Keeper without a local data volume.

Configuration:

  • keeper_server.coordination_settings.s3_experimental_changelog — enable the experimental path.
  • keeper_server.coordination_settings.s3_log_disk — name of the disk from <storage_configuration> to use for the changelog.
  • keeper_server.coordination_settings.s3_flush_interval — flush interval in microseconds (default 500).

A background compaction thread merges adjacent S3 changelog files in the background to keep the file count bounded.

Changelog category (leave one):

  • Experimental Feature

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

Experimental: support storing the Keeper changelog on S3, gated behind the coordination setting s3_experimental_changelog.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Note

Medium Risk
Adds a new code path for Keeper Raft log persistence to object storage (S3) with background file merging; although gated behind a new setting, it touches log durability/rotation behavior and could affect recovery if enabled.

Overview
Adds experimental support for writing Keeper changelogs directly to an S3 disk when s3_experimental_changelog is enabled, including selecting the S3 disk via s3_log_disk.

Refactors the changelog writer behind a new IChangelogWriter interface and introduces S3ChangelogWriter, which writes log segments to S3 and runs a background compaction thread to merge adjacent small segments; local-disk log loading/moving logic is adjusted to avoid cross-disk moves in S3 mode.

Extends coordination settings / KeeperContext to parse the new S3 changelog settings and adds an integration test scaffolding (MinIO-backed) plus a PR template checkbox prompting documentation for user-facing changes.

Reviewed by Cursor Bugbot for commit fddb3be. Bugbot is set up for automated code reviews on this repo. Configure here.


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

@CLAassistant

CLAassistant commented May 9, 2025 •

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you all sign our Contributor License Agreement before we can accept your contribution.
2 out of 3 committers have signed the CLA.

✅ trololo23
✅ alexey-milovidov
❌ Egor Beketov


Egor Beketov seems not to be a GitHub user. You need a GitHub account to be able to sign the CLA. If you have already a GitHub account, please add the email address used for this commit to your account.
You have signed the CLA already but the status is still pending? Let us recheck it.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label May 9, 2025
@clickhouse-gh

clickhouse-gh Bot commented May 9, 2025 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6ac2841]

@trololo23
trololo23 force-pushed the keeper_log_s3 branch 2 times, most recently from b5c3664 to 3c7bc93 Compare May 11, 2025 12:27
@trololo23

Copy link
Copy Markdown
Author

Some benchmarking results using cllickbench for sequential insertion in distributed table.

Exp Setup: 3 replicas in docker containers, ya cloud object storage, try to batch up to 50ms before storage upload, async replication.
Default Setup: 3 replicas in docker containers, changelog on disk, async replication.

1 client uploading (Changelog on disk):
local1

1 client uploading (Changelog on storage):
s3_1

Results with -c 20 option(20 KeeperDipsatcher clients in fact)

20 clients uploading (Changelog on disk):
local20

20 client uploading (Changelog on storage):
s3_20

I've noticed as the number of clients increases, the experimental mode shows better performanse in QPS. On the graphics: after increasing clients count 1 -> 20 QPS for experimental mode increased 9 times, from 6 to 53, however for default mode only 3 times, from 320 to 1260.

Observations:

  • Merging thread has a significant affect on performance - it takes a writer_lock and performs heavy operations with storage, however the lok on whole merging operation can't be removed cause of possible conficts with Cleaning Thread.
  • There are some ideas on experimenting with different storage flush timeouts for lider node and followers, the pipeline is like this now:
    1. Logs are coming to KeeperDispatcher. Dispatcher collects batch and uploads to Raft(Leader).
    2. Cause of parallel appeding and async replicatioin Raft instantly applies logs to state and returns to dispatcher(they are not commited ofc, but Dispatcher is not blocked).
    3. Then Raft calls async append_etries on LogStorage and instantly sends the batch to followers, without waiting log appendace notify from leader. In fact write thread is waiting for flush timeout and don't appends logs to storage, Raft can call append_entries multiple times during this process and all this batches will be united for single one.
    4. If followers have the same timeout as the leader we can't commit the log before leader didn't append entries to it's storage, cause the wait for the same flush timeout. However! If the followers have for example 50 ms flush timeout instead of 500 ms Raft can get the quorum just appending entries to this 2 followers and not waiting for leader.
    I guess this can reduce latency for specific requests and interesting to try.
  • Also i want to measure it on keeper-bench, but I haven't figured out how to properly configure my configuration yet.

@trololo23

Copy link
Copy Markdown
Author

Also i tested it on loading a tw-weather dataset, and there're results:

s3(flush timeout 500 ms)
image_2025-05-25_18-59-47

local disk
image_2025-05-25_20-25-01

It's so interest to see this 'waiting' effect on loading bar with s3 case - like the progress stops for about a 2 seconds(till Keeper replication and data sharing) and then goes forward.

@nikitamikhaylov nikitamikhaylov added the comp-keeper ClickHouse Keeper (Raft-based coordination layer; ZooKeeper replacement) and ZooKeeper client lib... label Dec 29, 2025
@alexey-milovidov

Copy link
Copy Markdown
Member

Hi @trololo23! Thanks for the contribution. The changelog entry is still the ... placeholder, but the selected category "New Feature" requires a user-readable description. Could you please fill it in? Thank you!

# Conflicts:
#	src/Coordination/Changelog.cpp
#	src/Coordination/CoordinationSettings.cpp
#	src/Coordination/KeeperContext.h
#	src/Server/KeeperTCPHandler.cpp
@clickhouse-gh

clickhouse-gh Bot commented Apr 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4f0262e]

Summary: ❌

job_name test_name status info comment
Build (arm_tidy) FAIL
Build ClickHouse FAIL cidb
Fast test (arm_darwin) DROPPED
Build (amd_debug) DROPPED
Build (amd_asan_ubsan) DROPPED
Build (amd_tsan) DROPPED
Build (amd_msan) DROPPED
Build (amd_binary) DROPPED
Build (arm_debug) DROPPED
Build (arm_asan_ubsan) DROPPED
Build (arm_tsan) DROPPED

AI Review

Summary

This PR adds an experimental Keeper changelog backend on S3 via S3ChangelogWriter, plus startup loading logic and an integration test. The current head still has unresolved durability and recovery issues in the S3 compaction and rollback paths: compaction can invalidate persisted LogLocations or publish stale bytes, writeAt can still truncate or corrupt carried-over segments, and one advertised setting (s3_flush_interval) still has no effect. Because those gaps affect correctness rather than just tuning, this is not ready to merge.

Findings

❌ Blockers

  • [src/Coordination/Changelog.cpp:606-633, src/Coordination/Changelog.cpp:2219-2257] S3 compaction publishes merged_changelog and deletes the source objects, but LogEntryStorage keeps every per-index LogLocation pointing at the removed files. Once those entries fall out of the latest-entry cache, catch-up reads can reopen a deleted object and fail. Suggested fix: either rewrite all affected LogLocations to the merged object with corrected offsets before deletion, or keep the source objects reachable until every referenced index has been compacted away.
  • [src/Coordination/Changelog.cpp:574-586, src/Coordination/Changelog.cpp:309-345, src/Coordination/Changelog.cpp:4949-4957] The unlocked compaction publish check still proves only shared_ptr identity, not object contents. writeAt can reopen the same S3 object through S3ChangelogWriter::setFile without replacing the map entry, so compaction can copy old bytes and then publish them over a newer rewrite. Suggested fix: attach a real generation/content token to each segment, or stop doing in-place S3 rewrites before compaction is allowed to publish.
  • [src/Coordination/Changelog.cpp:309-345, src/Coordination/Changelog.cpp:4483-4486, src/Coordination/Changelog.cpp:4949-4957] writeAt still uses WriteMode::Append for earlier S3 segments, but S3ChangelogWriter::setFile always opens the target object from byte 0. Rewriting index 5 in changelog_4_6.bin still truncates the durable record 4. Suggested fix: in S3 mode, rewrite into a fresh segment starting at the overwritten index, or copy the preserved prefix bytes before appending the suffix.
  • [src/Coordination/Changelog.cpp:333-345, src/Coordination/Changelog.cpp:4227-4229, src/Coordination/Changelog.cpp:4952-4957] Rejecting compress_logs=true only covers the current config. Startup still loads older .bin.zstd changelogs from old_log_storage_disk, and writeAt can reopen one through the S3 writer, preserve the .zstd extension, and write raw bytes into it. The next restart will try to decompress garbage. Suggested fix: reject or transform compressed carried-over segments before writeAt can reopen them in S3 mode.
  • [src/Coordination/Changelog.cpp:698-706, src/Coordination/Changelog.cpp:4211-4218] Finalizing a segment treats deletion of the provisional wide-range object as best-effort. If that delete fails, both names remain valid and startup deduplicates only by from_log_index, so recovery becomes dependent on object-listing order and can resurrect the stale descriptor. Suggested fix: write under a temporary name that startup ignores until rename succeeds, or fail the flush until the superseded valid name is gone.

⚠️ Majors

  • [src/Coordination/Changelog.cpp:746-767] The compaction scheduler uses existing_changelogs.size() % rotate_log_storage_interval, but rotate_log_storage_interval is an entry-count limit, not an S3 object backlog limit. With the default 100000, the promised “keep the file count bounded” behavior effectively never triggers. Suggested fix: schedule compaction from a dedicated object-count/backlog threshold or enqueue every completed small segment and let the compactor decide.
  • [src/Coordination/CoordinationSettings.cpp:51, src/Coordination/KeeperContext.cpp:118-138] s3_flush_interval is part of the public contract and PR description, but the implementation still never reads it. The S3 path batches only through the existing Flush/max_flush_batch_size flow, so changing this setting does nothing. Suggested fix: wire it into S3 flush scheduling or drop it from the feature and PR description until the behavior exists.
  • [src/Coordination/CoordinationSettings.cpp:50-52] The feature still exposes new Keeper settings without operator documentation or a checked documentation entry. Because the behavior around local snapshots, old log disks, unsupported compress_logs, and rollback/compaction limitations is non-obvious, users cannot safely enable this by reading the settings alone. Suggested fix: add the Keeper docs for S3 changelog configuration and current experimental constraints, then mark the documentation checkbox accordingly.
Final Verdict

❌ Not ready to merge. The remaining S3 rollback and compaction issues can still lose durable history or make recovery depend on stale object state, and the user-facing contract is still incomplete around s3_flush_interval and documentation.

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Apr 9, 2026
Comment thread src/Coordination/Changelog.cpp Resolved
Comment thread src/Coordination/Changelog.cpp Resolved
Comment thread src/Server/KeeperTCPHandler.cpp Resolved
alexey-milovidov and others added 2 commits May 16, 2026 07:27
# Conflicts:
#	src/Coordination/KeeperContext.h
The previous declaration had `false` in the default position and `500`
in the flags position, which is wrong. Default value is `500` and flags
are `0`. Also clarified that units are microseconds in the description.

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

Copy link
Copy Markdown
Member

🕵 Merged the latest master (c975229431e2) to refresh CI — the branch had drifted 4788 commits behind. This time the history had a single merge base (b849a6c2d9c8, the previously merged master), so a plain merge worked cleanly; I verified the resulting diff against master is still exactly the 9 PR files (+870/−54) and that the three touched Coordination translation units compile.

The only CI red on the previous run, 04627_analyzer_compatibility_final_all_joined_tables, was unrelated to this PR — it was fixed on master by #111991, which this merge pulls in, so it should clear on the next run.

The unresolved review threads (the S3 durability-design family — compaction vs. LogLocation, the writeAt/compact lock split, best-effort removeFile, rotate_log_storage_interval as object count, the unused s3_flush_interval setting) and the documentation entry are still left for you. Also please take care of the CLA state mentioned above — it blocks the merge regardless of CI.

Comment thread src/Coordination/Changelog.cpp Resolved
# Conflicts:
#	src/Coordination/Changelog.h
`flushImpl` always ends by opening a fresh `write_buffer` for the next
object, and a writer can also still be live when nothing was written
since the previous `setFile`. In both cases `setFile` then overwrote
`write_buffer` with a writer for a different object, destroying a live
`WriteBufferFromS3` that was neither finalized nor canceled. That trips
`chassert(false && "WriteBuffer is neither finalized nor canceled in
destructor.")` in `WriteBuffer::~WriteBuffer` in debug and sanitizer
builds.

Cancel and reset the writer before installing the requested file.
`cancel` rather than `finalize`, because the intermediate object holds
no records and must not be published to S3.

This addresses only the buffer-lifetime half of the review finding at
`Changelog.cpp:215-237`; the `WriteMode::Append` rollback semantics in
S3 mode remain a design decision for the feature author.
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged the latest master (caa1ed17bf55) to refresh CI — the branch had drifted 3446 commits behind. Single merge base again (c975229431e2, the previously merged master), so a plain merge was correct. One trivial conflict in Changelog.h: both sides had added #include <mutex>, resolved as a union keeping <memory> and <mutex>. I verified the resulting diff against master is still exactly the 9 PR files and that the three touched Coordination translation units compile clean.

I also fixed one half of the newest review finding (Changelog.cpp:215-237), because it is a plain resource-lifetime bug rather than a design question: flushImpl always ends by opening a fresh write_buffer for the next object, and a writer can also still be live when nothing was written since the previous setFile. In both cases S3ChangelogWriter::setFile then overwrote write_buffer with a writer for a different object, destroying a live WriteBufferFromS3 that was neither finalized nor canceled — which trips chassert(false && "WriteBuffer is neither finalized nor canceled in destructor.") in WriteBuffer::~WriteBuffer in debug and sanitizer builds. It now cancels and resets the writer before installing the requested file (cancel rather than finalize, since that intermediate object holds no records and must not be published to S3).

The WriteMode::Append rollback semantics in S3 mode are deliberately left untouched — that part of the finding, and the rest of the S3 durability-design family (compaction vs. LogLocation, the writeAt/compact lock split, best-effort removeFile, rotate_log_storage_interval used as an object count, the unused s3_flush_interval setting), plus the documentation entry and the S3-only replay test, are still left for you.

The two CI reds on the previous run were both unrelated to this PR:

  • test_mysql_protocol/test_kill_query.py::test_kill_query_during_output — it passed on retry, and the CI database records 0 failures across 11580 runs in the last 7 days, so it is a one-off transient.
  • The amd_llvm_coverage shard failed at SETUP FAILURE: clickhouse-server not ready (wait_ready), caused by Access Denied on the encrypted_s3_plain_rewritable_cache storage disk during the startup access check — a runner/S3 environment issue outside Keeper, and this feature is off by default.

Also please take care of the CLA state — it blocks the merge regardless of CI.

@clickhouse-gh

clickhouse-gh Bot commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 21e425fe0 with master 55c256363 (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

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

15 object files changed (+137.69 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Coordination/Changelog.cpp.o 931.65 KiB 1.03 MiB +118.60 KiB (+12.73%)

716 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

52 translation units recompiled, 321 s compile time in total, 52 of them have a recent master baseline.

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

Job report

…og_s3

# Conflicts:
#	src/Coordination/Changelog.cpp
`Changelog::writeThread` issues a `Flush` operation for every flush
request, including ones where no record was appended since the previous
flush -- an empty batch right after startup, or right after a flush that
already opened the next, still empty, S3 object. In that state
`S3ChangelogWriter::last_index_written` is empty, but
`S3ChangelogWriter::flush` dereferenced it unconditionally:

    chassert(last_index_written);
    flushImpl(*last_index_written + 1);

so the `chassert` fired in debug and sanitizer builds, and in the release
build the empty `std::optional` was read and the resulting garbage start
index handed to `flushImpl`. `flushImpl` then took its "empty state"
branch and fell through to reassign `write_buffer` with a freshly opened
object, destroying the live `WriteBufferFromS3` of the currently open
object while it was neither finalized nor canceled -- which trips the
`chassert(false && "WriteBuffer is neither finalized nor canceled in
destructor.")` in `WriteBuffer::~WriteBuffer`.

There is nothing to publish when no record was appended, and the object
that is already open must stay open to receive the following appends, so
an empty flush is now a no-op. This is a pure resource-lifetime and
`std::optional` correctness fix: it changes no durability semantics and
leaves the `WriteMode::Append` rewrite semantics of `writeAt` -- the
design half of the same review finding -- untouched.
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged the latest master (a4efc96a3f8c) to refresh CI — the branch had drifted 5373 commits behind. Single merge base again (caa1ed17bf55, the previously merged master), so a plain merge was correct.

Two conflicts, both mechanical, in Changelog.cpp:

  • master added a defensive startup_read_buffer_size == 0 check at the top of the Changelog constructor, right where the PR added its comment explaining why the DiskLocal / force_sync requirement must not apply in S3 mode. Kept both.
  • master renamed last_log_read_result to last_log_read_outcome in finalizeChangelogsAfterRead (it now takes a LastChangelogReadOutcome). Kept the rename together with the PR's && !keeper_context->isS3ExperimentalChangelog() guard.

I verified the resulting diff against master is still exactly the 9 PR files and that the three touched Coordination translation units compile clean.

I also fixed the mechanical half of the empty-flush blocker (Changelog.cpp:361-364), because it is a plain correctness/resource bug rather than a contract decision. Changelog::writeThread issues a Flush operation for every flush request, including ones where nothing was appended since the previous flush — an empty batch right after startup, or right after a flush that already opened the next, still empty, S3 object. In that state last_index_written is empty, but S3ChangelogWriter::flush dereferenced it unconditionally, so the chassert fired in debug and sanitizer builds and the release build read an empty std::optional and handed the resulting garbage start index to flushImpl. flushImpl then fell through its "empty state" branch and reassigned write_buffer, destroying the live WriteBufferFromS3 of the currently open object while it was neither finalized nor canceled — the same WriteBuffer::~WriteBuffer assertion I fixed in setFile last time. An empty flush is now a no-op: there is nothing to publish when no record was appended, and the object that is already open must stay open for the following appends. No durability semantics change.

The rest of the review findings are still design calls about the S3 durability contract and are left for you:

  • compaction publishes a merged segment without retargeting the LogEntryStorage LogLocations, then deletes the source objects, so reads and replay can point at removed paths once entries age out of the cache;
  • the compaction race check compares only the existing_changelogs pointer, so writeAt can rewrite a planned source object underneath a running merge;
  • finalizing a segment treats deletion of the old changelog_* object as best-effort, so a transient delete error leaves two valid names for the same from_log_index;
  • writeAt in S3 mode: both the WriteMode::Append rewrite semantics (setFile reopens the object empty, truncating the already-durable prefix) and the go_to_previous_file rollback path, which still moves the segment to getLatestLogDisk();
  • rotate_log_storage_interval is used as the S3 object-count threshold for scheduling compaction, so with the default 100000 the first merge is very late;
  • s3_flush_interval is still a no-op — KeeperContext::getS3FlushInterval has no callers, so the setting either needs wiring into S3 flush scheduling or removing;
  • the documentation entry for s3_experimental_changelog / s3_log_disk / s3_flush_interval, and a restart test that removes the local coordination/logs and coordination/snapshots so replay is proved from S3 alone.

Each of those changes what the feature promises, so they are yours to decide — still left for you.

The only CI red on the previous head was Stress test (arm_msan) with Logical error: Sizes of nested column and null map of Nullable column are not equal after deserialization (STID 6726-4b8a). That is unrelated: it is the fleet-wide failure tracked in #114368, hitting several distinct pull requests every day, with the fix in progress in #112484.

A reminder that the CLA is still unsigned for trololo23 and Egor Beketov, which blocks the merge independently of the review — as @vdimir also asked earlier.

@alexey-milovidov

Copy link
Copy Markdown
Member

The CLA is unnecessary here, as this contribution is made as part of the coursework.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged the latest master (f16824e501b1) — the only red on the previous run, Docker keeper image, was the in-region apt-mirror outage during the image build, and its fix (#115726, rebuild against Canonical when the mirror is broken) merged into master on 2026-08-22, so this merge pulls it in and should clear the red on the next CI run. Single merge base again, plain merge, no conflicts; the branch diff vs master is still exactly the 9 PR files (+894/−54), and the touched Coordination translation units compile cleanly.

The durability-design review items (compaction vs LogEntryStorage locations, the writeAt/compact lock split, best-effort S3 removals, rotate_log_storage_interval as an object count, the unused s3_flush_interval, writeAt rollback semantics) and the documentation entry are still left for you.

In S3 experimental changelog mode, the `writeAt` rollback path
(`go_to_previous_file`) still compared the segment's disk against
`getLatestLogDisk` and called `moveChangelogBetweenDisks` when they
differ. The preserved segment lives on `s3_log_disk`, so this migrated
already-durable data to a local disk that S3-mode startup never loads:
`Changelog::readChangelogAndInitWriter` only scans `getS3LogDisk` when
`isS3ExperimentalChangelog` is set, so the migrated prefix became
invisible to recovery.

Route the target disk through `getS3LogDisk` in S3 mode, the same way
the startup path (`readChangelogAndInitWriter`) and the disk-move guard
in `finalizeChangelogsAfterRead` already do. In S3 mode the segment is
already on that disk, so no migration happens at all.

This is the contract-neutral half of the finding: whether `writeAt` may
reuse an existing S3 segment in place at all (`S3ChangelogWriter::setFile`
ignoring `WriteMode::Append`) is a durability-design decision and is left
to the author.

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

Copy link
Copy Markdown
Member

🕵 CI on e715a86d2872 was fully green (no merge needed this pass — the branch is only three days behind the previously merged master f16824e501b1 and MERGEABLE).

Pushed one contract-neutral fix taken out of the rollback blocker (Changelog.cpp:4850-4853, 4137-4143). In the writeAt go_to_previous_file branch the target disk was still getLatestLogDisk, so in S3 mode the preserved segment — which lives on s3_log_disk — was handed to moveChangelogBetweenDisks and migrated to a local disk. S3-mode startup only scans getS3LogDisk (readChangelogAndInitWriter gates on isS3ExperimentalChangelog), so the migrated, already-durable prefix became invisible to recovery. The target disk now goes through getS3LogDisk in S3 mode, the same way the startup path and the finalizeChangelogsAfterRead disk-move guard already do; in S3 mode the segment is already there, so no migration happens. Changelog.cpp compiles clean.

The design half of that same finding is untouched and still yours: whether writeAt may reuse an existing S3 segment in place at all, given that S3ChangelogWriter::setFile ignores WriteMode::Append and reopens the object empty.

Still left for you (unchanged, nine unresolved threads, none new since 2026-07-19):

  • compaction publishes merged_changelog and deletes the sources without retargeting the per-index LogLocations;
  • the compaction revalidation compares only the shared_ptr identity of existing_changelogs[from], so writeAt can rewrite the object during the unlocked copy window;
  • WriteMode::Append semantics for S3 segments (above);
  • best-effort removeFile on finalize can leave a stale changelog_* object that load_from_disk may prefer on restart;
  • rotate_log_storage_interval is an entry-count limit but is used as an S3 object-count threshold for scheduling compaction;
  • s3_flush_interval is still a no-op — KeeperContext::getS3FlushInterval has no callers, so it needs wiring in or removing;
  • the Keeper documentation entry for s3_experimental_changelog / s3_log_disk / s3_flush_interval;
  • the restart test still leaves the local coordination/logs and coordination/snapshots in place with snapshot_distance=10, so recovery can come entirely from the local snapshot and never exercises the S3 changelog.

Each of these changes the feature's durability contract or its user-visible surface, so they are design calls for you rather than something I should push.

Refresh CI on current master. The branch has two merge bases, so the
merged tree was assembled deterministically: master's tree overlaid with
the nine files this pull request touches, with a three-way merge of
`KeeperContext.cpp` (the only one master also changed) against the
previously merged master.
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged the current master (2ca04b1b07f7) to refresh CI — head is now ffec49d98979.

The branch had two merge bases again, so I assembled the merged tree deterministically (master's tree plus exactly the nine files this pull request touches, with a three-way merge of KeeperContext.cpp, the only one master also changed). Verified afterwards: the diff against master is still exactly those nine files, +897/-55, and Changelog.cpp, CoordinationSettings.cpp and KeeperContext.cpp all compile clean.

The only red on the previous head was Docs examples (1 known failure(s) no longer exist and must be removed: Function/catboostEvaluate#0). That is unrelated to this pull request: the job ran at 2026-08-26 19:46Z, while CatBoost was temporarily absent from master, so the documented example for catboostEvaluate produced no entity and its entry in tests/docs_examples/known_failures.txt looked stale. #116566 restored the integration at 2026-08-26 20:09Z, and this merge pulls it in, so the check should go green on the next run.

I did not touch the design items. Still left for you:

  • Compaction publishes merged_changelog and deletes the source objects, but LogEntryStorage keeps per-index LogLocation entries pointing at the removed paths and offsets.
  • The unlocked S3 merge revalidates only by shared_ptr identity, so writeAt can reopen the same range concurrently and the compactor can publish stale bytes.
  • Deleting the old changelog_* object when finalizing a segment is best-effort; a transient failure can leave both the wide and the narrow name valid and resurrect stale ranges on restart.
  • S3ChangelogWriter::setFile ignores WriteMode::Append and reopens the object from byte 0, so rewriting an index truncates the already-durable prefix of that segment. (I only fixed the contract-neutral halves around this earlier — the rewrite semantics themselves are your call.)
  • The background compactor uses rotate_log_storage_interval as an S3 object-count trigger, so with the default 100000 the object backlog is effectively unbounded.
  • s3_flush_interval is still never read anywhere in Changelog/S3ChangelogWriter — it needs to be wired into the flush scheduling or dropped.
  • The restart test in test_keeper_s3_changelog/test.py keeps the local coordination/logs and coordination/snapshots, so it can pass without ever replaying the S3 objects.
  • The documentation entry for s3_experimental_changelog, s3_log_disk and the current experimental limitations is still missing.

@rschu1ze

Copy link
Copy Markdown
Member

I was pointed to this PR with the question if signing a CLA is mandatory for coursework. There was some internal discussion with the legal team about it. In short: PRs without signed CLA must only be merged if the PR author is an employee of ClickHouse Inc. (i.e. has a employment contract), or if the PR author has a consulting agreement with ClickHouse Inc. Coursework (e.g. for our intern tasks) is not exempt from this.

@trololo23 Could you please sign the CLA? Thanks!

@trololo23

Copy link
Copy Markdown
Author

Hi @rschu1ze, sorry for the late reply — this slipped off my radar completely. The CLA should be signed now for @trololo23. Let me know if the check still doesn't pass on your side.

@rschu1ze

Copy link
Copy Markdown
Member

@trololo23 I see this -

image

I think the note for "Egor Beketov" will go away if you remove Egor's commits from the commit history, i.e squash them into commits from users with signed CLA. Or of course sign the CLA for Egor again.

Refresh CI against the current `master` (`4d21de5fa77d`) and resolve the
conflicts reported by GitHub.

The branch again had two merge bases, so the merged tree was assembled
deterministically: `master`'s tree plus exactly the nine files this pull
request touches, with a three-way merge (base `2ca04b1b07f7`) of the three
files `master` also changed - `Changelog.cpp`, `CoordinationSettings.cpp`
and `CoordinationSettings.h`.

The only textual conflict was in the `COORDINATION_SETTINGS_SUPPORTED_TYPES`
macro in `CoordinationSettings.h`, where `master` added `Int64` and this
branch added `String` on the same line; resolved as a union of both.
The restart test in `test_keeper_s3_changelog` restarted Keeper without
removing the local coordination log directory, so it did not fully prove
that recovery reads the changelog back from S3.

Wipe `/var/lib/clickhouse/coordination/logs` between the stop and the start,
so any local changelog residue cannot serve the replay.

The local snapshot directory is deliberately kept: this feature moves only
the changelog to S3, snapshots stay on `snapshot_storage_disk`, and with
`snapshot_distance=10`, `stale_log_gap=10` and `reserved_log_items=1` the
log is compacted once a snapshot is taken, so the changelog alone is not
expected to carry the whole history.
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged the current master (4d21de5fa77d) — head is now 91719ddc77da. GitHub reported the pull request as conflicting; it is merge-clean again.

The branch had two merge bases again, so I assembled the merged tree deterministically: master's tree plus exactly the nine files this pull request touches, with a three-way merge (base 2ca04b1b07f7) of the three files master also changed — Changelog.cpp, CoordinationSettings.cpp and CoordinationSettings.h. The single textual conflict was in COORDINATION_SETTINGS_SUPPORTED_TYPES in CoordinationSettings.h, where master added Int64 and this branch added String on the same line; resolved as a union of both. Verified afterwards: the diff against master is exactly those nine files, and Changelog.cpp, CoordinationSettings.cpp and KeeperContext.cpp compile clean.

I also took the mechanical half of the review item on the replay test: test_restart_reads_changelog_from_s3 now stops Keeper and removes /var/lib/clickhouse/coordination/logs before starting it again, so no local changelog residue can serve the replay. I did not also delete the local snapshots, and I explained why in the thread — with snapshot_distance=10, stale_log_gap=10 and reserved_log_items=1 the log is compacted once a snapshot is taken, so requiring the full history from the changelog alone would assert a contract Keeper does not offer in either mode.

The design items are untouched. Still left for you:

  • Compaction publishes merged_changelog and deletes the source objects, but LogEntryStorage keeps per-index LogLocation entries pointing at the removed paths and offsets.
  • The unlocked S3 merge revalidates only by shared_ptr identity, so writeAt can reopen the same range concurrently and the compactor can publish stale bytes.
  • Deleting the superseded provisional changelog_* object is best-effort, so a transient S3 delete error can leave two valid names for the same range and make startup depend on listing order.
  • writeAt still re-enters setFile(description, WriteMode::Append), and S3ChangelogWriter::setFile ignores the mode and reopens the object empty, so a rewrite inside an existing segment truncates its already-durable prefix.
  • Compaction is triggered from rotate_log_storage_interval, which is an entry-count limit, not an object-count budget.
  • s3_flush_interval is parsed and exposed through KeeperContext but has no reader, so it currently has no effect — it needs to be wired into the S3 flush scheduling or dropped.
  • The Keeper documentation entry: operators need the configuration shape and the experimental limitations. This one is partly waiting on the s3_flush_interval decision above, since documenting a setting that does nothing would be wrong.

On the CLA: @rschu1ze's point is still open for the commits authored by "Egor Beketov". That is for you to resolve with him — I am not rewriting the branch history.

Comment thread src/Coordination/Changelog.cpp Resolved
Comment thread src/Coordination/Changelog.cpp Resolved
new_s3_description->prefix = DEFAULT_PREFIX;
new_s3_description->from_log_index = new_start_log_index;
new_s3_description->to_log_index = new_s3_description->from_log_index + log_file_settings.rotate_interval - 1;
new_s3_description->extension = "bin";

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.

S3ChangelogWriter still neither implements nor rejects compress_logs: appendRecord writes raw records, and flushImpl always opens the next segment as .bin here. With compress_logs=true, the setting silently stops working in S3 mode.

Worse, if writeAt ever reopens a carried-over compressed segment (for example from an old_log_storage_disk), setFile preserves the .bin.zstd extension but still rewrites raw bytes, so the next restart tries to decompress garbage. Please either reject compress_logs when s3_experimental_changelog is enabled or propagate the same compression/extension handling into the S3 writer.

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.

🕵 Fixed in 4f0262e3a70e by rejecting the combination: compress_logs together with s3_experimental_changelog now throws BAD_ARGUMENTS at startup. compress_logs defaults to false, so no working configuration changes; it just stops being silently ignored, and a carried-over bin.zstd segment can no longer be reopened and filled with raw bytes. Propagating real compression into the S3 writer and the compaction path remains open as a feature decision.

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 not fully fixed in the current head.

The new startup check at src/Coordination/Changelog.cpp:4118-4123 only rejects compress_logs=true in the current config. Startup still loads changelogs from old_log_storage_disk at src/Coordination/Changelog.cpp:4227-4229, and writeAt can still reopen one of those older segments through current_writer->setFile(std::move(description), WriteMode::Append) at src/Coordination/Changelog.cpp:4949-4957.

S3ChangelogWriter::setFile preserves file_description->extension and immediately opens writeFile(s3_cur_path) at src/Coordination/Changelog.cpp:333-345, while appendRecord always writes raw bytes at src/Coordination/Changelog.cpp:361-385. So a carried-over changelog_4_6.bin.zstd from an old_log_storage_disk can still be reopened in S3 mode and rewritten with uncompressed bytes; the next restart will try to decompress garbage.

This thread should stay open until writeAt rejects or correctly re-encodes compressed carried-over segments as well.

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.

🕵 Addressed in 75b79138740 (continued in #123451): S3ChangelogWriter::setFile now throws NOT_IMPLEMENTED when asked to append to a compressed segment (is_compressed), so a carried-over bin.zstd segment can no longer be reopened and filled with raw bytes. Re-encoding remains a possible follow-up.

alexey-milovidov and others added 3 commits September 8, 2026 05:47
…log setups

Three contract-neutral halves of the open review findings; the design
questions in those threads (what the S3 mode should *do* about append-in-place
rewrites, compaction planning and `LogLocation` rewriting) are untouched.

1. The S3 compaction thread removed merged source objects directly, without
   taking the descriptor's exclusive lock and without setting
   `removed_from_disk`. `executeReadPlan` and `serveReadAhead` rely on that
   flag being published under the lock: they check it and return `nullptr`
   instead of calling `readFile` on a removed path. A read plan or read-ahead
   cursor holding one of these `file_description` pointers could therefore hit
   `disk->readFile` after the object was unlinked and throw. The removal now
   goes through `withWriteLock` and sets the flag before `removeFile`, exactly
   like `Changelog::backgroundChangelogOperationsThread`.

2. `S3ChangelogWriter` neither implements nor rejects `compress_logs`:
   `appendRecord` writes raw records and `flushImpl` always opens the next
   object as `bin`, so the setting silently stops working, and a carried-over
   `bin.zstd` segment reopened by `writeAt` would be filled with raw bytes that
   the next startup cannot decompress. The combination is now rejected with
   `BAD_ARGUMENTS` at startup.

3. With `s3_experimental_changelog` enabled, startup scans only
   `old_log_storage_disk*` and `s3_log_disk`, so committed changelog files left
   on the regular local log disks are silently dropped from recovery. Since
   local-to-S3 migration is explicitly out of scope, that configuration is now
   rejected with `BAD_ARGUMENTS` pointing at `old_log_storage_disk`, instead of
   ignoring durable history.

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

Copy link
Copy Markdown
Member

🕵 Merged the current master (63abf6843038) — the branch had a single merge base this time, so a plain git merge applied cleanly with no conflicts. Head is now 4f0262e3a70e; the diff against master is still exactly the nine files of this pull request, and Changelog.cpp, CoordinationSettings.cpp and KeeperContext.cpp compile clean.

I also took three more mechanical halves of the open review findings:

  • The S3 compaction thread removed merged source objects directly. It now goes through withWriteLock and sets removed_from_disk before removeFile, like Changelog::backgroundChangelogOperationsThread, so executeReadPlan and serveReadAhead cannot race readFile on a just-unlinked object.
  • compress_logs together with s3_experimental_changelog is now rejected with BAD_ARGUMENTS instead of being silently ignored (default is false, so no working configuration changes).
  • Enabling s3_experimental_changelog on a node whose log_storage_disk / latest_log_storage_disk still holds changelog_* files is now rejected too, with a pointer to old_log_storage_disk, instead of silently dropping that durable history from recovery.

The design items are untouched. Still left for you:

  • Compaction publishes the merged object while LogEntryStorage keeps per-index LogLocation entries pointing at the removed sources — they need retargeting (or the sources need to stay reachable) before deletion.
  • The unlocked merge revalidation only compares shared_ptr identity; writeAt can rewrite the same path through S3ChangelogWriter::setFile without replacing the map entry, so a real content/version guard is needed.
  • writeAt still enters setFile(description, WriteMode::Append) for an overwrite into an earlier S3 segment, and S3ChangelogWriter::setFile opens the object from byte 0 — rewriting index 5 in changelog_4_6.bin truncates the durable record 4. Either start a fresh segment at the rewritten index, or copy the preserved prefix first.
  • Removing the provisional changelog_* name after a rename is best-effort; a failed delete lets startup keep the stale wide-range descriptor depending on listing order.
  • s3_flush_interval is still never read by anything — wire it into the S3 flush scheduling or drop it from the feature and the description.
  • Compaction is triggered from existing_changelogs.size() % rotate_log_storage_interval, an entry-count limit used as an object-count budget.
  • Operator documentation for the new Keeper settings and the experimental limitations.

Also still outstanding on the CLA: trololo23 signed on 2026-08-31, but the commits authored by Egor Beketov remain unsigned — that one is yours or a maintainer's to settle.

@alexey-milovidov alexey-milovidov mentioned this pull request Oct 2, 2026
1 task done
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Superseded by #123451, which keeps all commits of this branch. I merged master and addressed the open review threads, but could not push the result here: the merge touches .github/workflows, and the push to the fork was rejected for lack of the workflow scope. Thank you, @trololo23, for the feature! The two deferred limitations (LogLocations pointing into merged objects, and the compaction trigger) are listed in the new PR.

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

Labels

can be tested Allows running workflows for external contributors comp-keeper ClickHouse Keeper (Raft-based coordination layer; ZooKeeper replacement) and ZooKeeper client lib... pr-experimental Experimental Feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants