Repository navigation
Flush Buffer tables before any database shuts down - #118985
Conversation
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.
|
Workflow [PR], commit [50e87af] Summary: ✅
AI ReviewSummaryThis PR fixes the main eager-load cases where a graceful shutdown could silently discard acknowledged rows from a Findings❌ Blockers
Tests
Final VerdictChanges requested. The eager-load cases from the linked issues are covered, but the shutdown drain is not complete yet because LLVM Coverage ReportMeasured on commit 50e87af.
Changed lines: Changed C/C++ lines covered: 32/33 (96.97%) · Uncovered code |
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.
| * 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; } |
There was a problem hiding this comment.
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()) |
There was a problem hiding this comment.
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?
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units685 translation units recompiled, 5395 s compile time in total, 685 of them have a recent master baseline. |
alexey-milovidov
left a comment
There was a problem hiding this comment.
This is an overkill, but meaningful.
ReproducerShell reproducer — set #!/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 2Results:
CC component owner: @alexey-milovidov @Michicosun Analysis metadata
Introducing change: predates `v23.8.16.40` (oldest testable release)
|
|
@alexey-milovidov — ClickGap found the following in this PR:
Close anything that's wrong or already addressed. |
A
Buffertable hands its in-memory rows to its destination when its own database shuts down, andDatabaseCatalog::shutdownImplshuts databases down one at a time in name order. Two silent losses of acknowledged rows follow from that on an ordinary graceful shutdown:StorageBuffertakes the missing-destination branch:Destination table za.mt doesn't exist. Block of data is discarded.(Buffer table with a destination in another database discards all acked rows on graceful shutdown when the destination's database shuts down first #117845);Buffertables moves rows at most one link per sequential pass, and rows left in an already-preparedBufferdie with its in-memory buffer, so a chain of depth three or more loses everything (Chain of three or more Buffer tables silently loses all acked rows on graceful shutdown (flush passes < chain depth) #117834).Both are deterministic at default settings whenever the destination sorts before its source, and
StorageBuffer.hpromises 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
Bufferpointing at itself cannot spin.IStorage::flushBufferedRowsBeforeShutdownreturns the number of buffers it flushed and is a no-op for everything exceptBuffer, 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):
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
Buffertable whose destination lives in another database or is anotherBuffertable.Workflow [PR]
Sync PR [sync-upstream/pr/118985]
Version info
26.9.1.1092(included in26.9and later)