Skip to content

Flush Buffer tables before any database shuts down - #118985

Merged
alexey-milovidov merged 2 commits into
masterfrom
buffer-flush-before-shutdown-117834
Sep 9, 2026
Merged

alexey-milovidov merged 2 commits into
masterfrom
buffer-flush-before-shutdown-117834

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 9, 2026 •

Copy link
Copy Markdown
Member

A Buffer table hands its in-memory rows to its destination when its own database shuts down, and DatabaseCatalog::shutdownImpl shuts databases down one at a time in name order. Two silent losses of acknowledged rows follow from that on an ordinary graceful shutdown:

Both are deterministic at default settings whenever the destination sorts before its source, and StorageBuffer.h promises the opposite ("When you destroy a Buffer table, all remaining data is flushed to the subordinate table").

Every table of every database is now asked to hand over its buffered rows before any database shuts down, repeating while a pass still moves something - one pass per link of the longest chain, bounded by the number of tables so a Buffer pointing at itself cannot spin. IStorage::flushBufferedRowsBeforeShutdown returns the number of buffers it flushed and is a no-op for everything except Buffer, and the per-database prepare pass keeps running afterwards for whatever arrived in the meantime.

Closes: #117834
Closes: #117845
Related: #116803

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed a graceful shutdown silently discarding the rows of a Buffer table whose destination lives in another database or is another Buffer table.


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

Version info

  • Merged into: 26.9.1.1092 (included in 26.9 and later)

A `Buffer` table hands its in-memory rows to its destination when its
own database shuts down, and `DatabaseCatalog::shutdownImpl` shuts
databases down one at a time in name order. Two silent losses of
acknowledged rows follow on an ordinary graceful shutdown:

  - a destination in an earlier-sorting database is already gone by
    then, and `StorageBuffer` takes the missing-destination branch:
    "Destination table za.mt doesn't exist. Block of data is discarded.";
  - a chain of `Buffer` tables moves rows at most one link per
    sequential pass, and the rows left in an already-prepared `Buffer`
    die with its in-memory buffer, so a chain of depth three or more
    loses everything.

Both are deterministic at default settings whenever the destination
sorts before its source, while `StorageBuffer.h` promises the opposite:
"When you destroy a Buffer table, all remaining data is flushed to the
subordinate table".

Every table of every database is now asked to hand over its buffered
rows before any database shuts down, repeating while a pass still moves
something - one pass per link of the longest chain, bounded by the
number of tables so a `Buffer` pointing at itself cannot spin.
`IStorage::flushBufferedRowsBeforeShutdown` returns the number of
buffers it flushed and is a no-op for everything except `Buffer`, and
the per-database prepare pass keeps running afterwards for whatever
arrived in the meantime.
@clickhouse-gh

clickhouse-gh Bot commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [50e87af]

Summary: ✅


AI Review

Summary

This PR fixes the main eager-load cases where a graceful shutdown could silently discard acknowledged rows from a Buffer table by draining buffers before any database is shut down. The approach is directionally correct, but it still misses one important local-storage carrier (lazy_load_tables via StorageTableProxy) and it introduces an avoidable shutdown dependency on external database catalogs.

Findings

❌ Blockers

  • [src/Storages/IStorage.h:655] The new flushBufferedRowsBeforeShutdown contract does not reach loaded StorageTableProxy wrappers. In Atomic / Ordinary databases with lazy_load_tables = 1, a used Buffer table stays wrapped in the proxy, which still inherits the default no-op here. The global pre-shutdown drain therefore skips that table and the original row-loss bug remains for cross-database destinations and multi-Buffer chains.
    Suggested fix: add a StorageTableProxy override (or equivalent proxy forwarding with a no-load fast path) that forwards this hook to an already materialized nested storage.

⚠️ Majors

  • [src/Interpreters/DatabaseCatalog.cpp:340] The new drain enumerates every non-predefined database even when the engine cannot host Buffer tables at all. External databases such as MySQL, PostgreSQL, Remote, and DataLake fetch remote metadata from their getTablesIterator implementations, so graceful shutdown now blocks on unnecessary remote I/O before it can finish stopping local storages.
    Suggested fix: skip external databases here, or gate the pass on a narrower capability than not predefined.
Tests
  • ⚠️ Add a regression that creates a Buffer table in an Atomic database with SETTINGS lazy_load_tables = 1 and verifies that shutdown still flushes into a destination in another database (or through another Buffer). The current integration test only exercises eagerly loaded tables, so it would not catch the proxy bypass.
Final Verdict

Changes requested. The eager-load cases from the linked issues are covered, but the shutdown drain is not complete yet because lazy_load_tables still preserves the original data-loss path, and the new database scan adds an unnecessary dependency on remote catalogs during shutdown.

LLVM Coverage Report

Measured on commit 50e87af.

Metric Baseline Current Δ
Lines 88.90% 88.90% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.30% 81.30% +0.00%

Changed lines: Changed C/C++ lines covered: 32/33 (96.97%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-simple-engines Lightweight single-node table engines: Log/StripeLog (append-only logs), Buffer (async batching),... labels Sep 9, 2026
Listing the tables of a persistent `system` database while shutting down
materializes its lazily created table storages, which aborts
`clickhouse local` (`05023_local_system_database_on_disk_deferred`,
`05042_local_system_database_deferred_populate_error`). None of the
predefined databases holds a `Buffer` table, so the drain skips them,
and a database that cannot be listed at all is logged instead of taking
the process down.
Comment thread src/Storages/IStorage.h
* down a chain. `DatabaseCatalog` therefore calls this for every table first, repeating while
* rows keep moving; the return value is the number of buffers this call actually flushed.
*/
virtual size_t flushBufferedRowsBeforeShutdown() { return 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.

StorageTableProxy still inherits this default no-op, while only flushAndPrepareForShutdown is forwarded there today. In Atomic / Ordinary databases with lazy_load_tables = 1, a Buffer table that has accepted writes remains wrapped in the proxy, so the new global drain never reaches the nested StorageBuffer and we fall back to the old per-database shutdown order. That means acknowledged rows can still be discarded on graceful shutdown for cross-database targets or multi-Buffer chains in the lazy-load configuration. Can we forward this hook for already-materialized proxies without forcing unresolved tables to load?


try
{
for (auto it = database.second->getTablesIterator(getContext(), {}, /*skip_not_loaded=*/ true); it->isValid(); it->next())

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 loop still walks every non-predefined database, including external catalogs that cannot contain Buffer tables. DatabaseMySQL::getTablesIterator, DatabasePostgreSQL::getTablesIterator, DatabaseRemote::getTablesIterator, and the DataLake iterator all fetch remote metadata here, so an unavailable external service now delays graceful shutdown before any local database is stopped. Can this be restricted to non-external databases (or another can host Buffer predicate) so shutdown does not gain a needless dependency on remote catalogs?

@clickhouse-gh

clickhouse-gh Bot commented Sep 9, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 50e87afe6 with master 05dc6f0a8 (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.

Compile time of recompiled translation units

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

Job report

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is an overkill, but meaningful.

@alexey-milovidov alexey-milovidov self-assigned this Sep 9, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 9, 2026
Merged via the queue into master with commit 20efb7f Sep 9, 2026
174 checks passed
@alexey-milovidov
alexey-milovidov deleted the buffer-flush-before-shutdown-117834 branch September 9, 2026 23:51
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 10, 2026
@clickgapai

Copy link
Copy Markdown
Contributor
Reproducer

Shell reproducer — set BIN to a ClickHouse binary path and run with bash; requires the referenced test fixtures from the repo.

#!/bin/bash
BIN="${BIN:-./clickhouse}"  # path to the ClickHouse binary under test
# PR #118985 — a graceful shutdown must hand a `Buffer` table's rows to its destination.
# Databases shut down one at a time in name order, so `za` (holding the destination) is already
# gone when `zb.buf` prepares for shutdown.
#   clean : SELECT count() FROM za.mt == 100 after the restart
#   buggy : 0 — server log has "Destination table za.mt doesn't exist. Block of data is discarded."
set -uo pipefail

[ -n "$BIN" ] && [ -x "$BIN" ] || { echo "INCONCLUSIVE: binary '$BIN' not executable"; exit 2; }

WORK=$(mktemp -d /tmp/ch_buf118985.XXXXXX)
TCP=$(( (RANDOM % 900) * 10 + 21000 ))
SRV_PID=""
cleanup() { { [ -n "$SRV_PID" ] && kill -9 "$SRV_PID"; pkill -f "$WORK/config.xml"; } 2>/dev/null; sleep 1; rm -rf "$WORK"; } 2>/dev/null
trap cleanup EXIT

cat > "$WORK/config.xml" <<EOF
<clickhouse>
    <logger><level>debug</level><log>$WORK/server.log</log><errorlog>$WORK/server.err.log</errorlog><console>false</console></logger>
    <tcp_port>$TCP</tcp_port>
    <listen_host>127.0.0.1</listen_host>
    <path>$WORK/data/</path>
    <tmp_path>$WORK/tmp/</tmp_path>
    <user_files_path>$WORK/user_files/</user_files_path>
    <mark_cache_size>536870912</mark_cache_size>
    <users><default>
        <password></password><profile>default</profile><quota>default</quota>
        <networks><ip>::/0</ip></networks>
    </default></users>
    <profiles><default></default></profiles>
    <quotas><default/></quotas>
</clickhouse>
EOF

CL=("$BIN" client --host 127.0.0.1 --port "$TCP")
q() { timeout 60 "${CL[@]}" --query "$1" 2>&1; }
alive() { [ -d "/proc/$1" ] && ! grep -qE '^State:[[:space:]]+Z' "/proc/$1/status" 2>/dev/null; }

start_server() {
    nohup "$BIN" server --config-file="$WORK/config.xml" >> "$WORK/stdout.log" 2>&1 < /dev/null &
    SRV_PID=$!
    for _ in $(seq 1 120); do
        "${CL[@]}" --query "SELECT 1" >/dev/null 2>&1 && return 0
        alive "$SRV_PID" || return 1
        sleep 1
    done
    return 1
}

stop_gracefully() {
    kill -TERM "$SRV_PID" 2>/dev/null
    for _ in $(seq 1 120); do
        alive "$SRV_PID" || { wait "$SRV_PID" 2>/dev/null; SRV_PID=""; return 0; }
        sleep 1
    done
    return 1
}

if ! start_server; then
    echo "observed: server did not come up: $(tail -2 "$WORK/stdout.log" "$WORK/server.err.log" 2>/dev/null | tr '\n' ' ')"
    exit 2
fi

# `1, 100000, 100000, ...` — one layer, thresholds far away so nothing flushes on its own.
SETUP=$(q "CREATE DATABASE za"; q "CREATE DATABASE zb";
          q "CREATE TABLE za.mt (x UInt64) ENGINE = MergeTree ORDER BY x";
          q "CREATE TABLE zb.buf (x UInt64) ENGINE = Buffer(za, mt, 1, 100000, 100000, 1000000, 1000000000, 10000000, 1000000000)";
          q "INSERT INTO zb.buf SELECT number FROM numbers(100)")
if echo "$SETUP" | grep -qiE "exception|Code: [0-9]+|NOT_IMPLEMENTED"; then
    echo "observed: setup failed: $(echo "$SETUP" | head -2 | tr '\n' ' ')"
    exit 2
fi

BEFORE_MT=$(q "SELECT count() FROM za.mt" | tr -d '[:space:]')
BEFORE_BUF=$(q "SELECT count() FROM zb.buf" | tr -d '[:space:]')
if [ "$BEFORE_MT" != "0" ] || [ "$BEFORE_BUF" != "100" ]; then
    echo "observed: rows did not stay in the buffer (za.mt=$BEFORE_MT zb.buf=$BEFORE_BUF) — scenario not exercised"
    exit 2
fi

if ! stop_gracefully; then
    echo "observed: TIMEOUT — server did not finish its graceful shutdown"
    exit 2
fi

if ! start_server; then
    echo "observed: server did not come back up after the restart: $(tail -2 "$WORK/stdout.log" "$WORK/server.err.log" 2>/dev/null | tr '\n' ' ')"
    exit 2
fi

AFTER=$(q "SELECT count() FROM za.mt" | tr -d '[:space:]')
DISCARD=$(grep -o "Destination table za.mt doesn't exist. Block of data is discarded." "$WORK/server.log" 2>/dev/null | head -1)

echo "observed: za.mt after restart = ${AFTER:-<error>} (expected 100) ${DISCARD:+| log: $DISCARD}"

[ "$AFTER" = "100" ] && exit 0
[ "$AFTER" = "0" ] && exit 1
exit 2

Results:

  • Reproduces on: 26.8, 26.7, 26.6, 26.3
  • Tested versions: master, 26.8, 26.7, 26.6, 26.3
  • Also tested (unsupported, context only): 26.2 reproduces, 24.8 reproduces, 23.8 reproduces
  • Fix merged on master (not re-verified: tested master build predates this PR's merge — a clean verdict is not attributable to the fix). The releases listed above still have the bug and need the backport.

CC component owner: @alexey-milovidov @Michicosun

Analysis metadata

comp-simple-engines · Severity P2 · Finding phase_d_pr118985

  • Verified against master build fbd946491f4d (aarch64)
  • Could not test: master
Introducing change: predates `v23.8.16.40` (oldest testable release)
  • v23.8.16.40 is the oldest release with a downloadable binary for this reproducer, and it already reproduces — the introducing change predates it and cannot be identified from release builds.
  • Walked 6 release(s) below the supported window: still reproduces down to 25.8.
  • Secondary components: comp-database-engines

@clickgapai

Copy link
Copy Markdown
Contributor

@alexey-milovidov — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

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

Labels

comp-simple-engines Lightweight single-node table engines: Log/StripeLog (append-only logs), Buffer (async batching),... pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

3 participants