Repository navigation
Fix logical error exception in getConsistentMetadataSnapshotImpl when log pointer goes backwards - #100651
Conversation
…en log pointer goes backwards The `chassert(max_log_ptr == new_max_log_ptr)` assertion in `getConsistentMetadataSnapshotImpl` fires when the database is recreated between the initial `max_log_ptr` read and a subsequent loop iteration, causing the log pointer to go backwards. Handle this case gracefully by resetting `max_log_ptr` to the new (smaller) value and retrying. https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100641&sha=c7c8447120affec1e60b8c7c6380dab230aa9439&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20parallel%29 Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
|
Workflow [PR], commit [fc34664] Summary: ✅
AI ReviewSummaryThis PR changes Final VerdictStatus: ✅ Approve |
The test concurrently runs backups and drops/recreates a `DatabaseReplicated`, triggering the code path where `max_log_ptr` goes backwards in `getConsistentMetadataSnapshotImpl`. Before the fix this caused a logical error exception in debug builds. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
The test was failing because `BACKUP ... ASYNC` outputs a result table (id, status) to stdout, and `SYSTEM UNFREEZE` can also produce output. Only stderr was being suppressed, so the extra stdout was mismatching the reference file which expects only "1". Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…p IDs per worker The `CREATE DATABASE ... ENGINE = Replicated(...)` outputs shard/replica info to stdout, which leaked into the test output causing a reference mismatch. Redirect both stdout and stderr to /dev/null for all DDL commands. Also include `$BASHPID` in backup IDs to avoid collisions between the two concurrent `do_backups` workers. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
The test now checks that `system.backups` contains at least one entry matching the test prefix, ensuring the stress scenario actually exercises the target race condition rather than silently passing when all backup attempts fail. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
… failure Under TSan, the concurrent `DROP DATABASE` prevents all backups from being recorded in `system.backups` within the timeout. The real assertion of this test is server liveness (no logical error exception), not that backups succeeded, so downgrade the "no backups attempted" check to a warning. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…trying When `max_log_ptr` moves backwards in `getConsistentMetadataSnapshotImpl`, it means the database was dropped and recreated as another instance. Silently retrying with the new pointer would back up a different database than the caller asked for, which is not what we want. Fail the operation cleanly with `CANNOT_GET_REPLICATED_DATABASE_SNAPSHOT`. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…ilure The test wrote "Backups attempted: $BACKUP_COUNT" to stderr, which causes `clickhouse-test` to mark the test as failed regardless of exit code. Since the real assertion of this test is server liveness (via the final `SELECT 1`), the informational echo is not needed. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100651&sha=696e74894edee8cefebb95f235644482350ef933&name_0=PR&name_1=Stateless%20tests%20%28arm_asan_ubsan%2C%20flaky%20check%29 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…n backups The test previously only asserted server liveness (`SELECT 1`), so a regression of the original `chassert(max_log_ptr == new_max_log_ptr)` failure could go undetected: the `chassert` raises a `LOGICAL_ERROR` exception that is silently swallowed by `BACKUP ... ASYNC`, and the test could pass even if the regression path was never exercised at all. Now the test: - counts successful `DROP DATABASE` cycles in `drop_and_recreate` and asserts that at least one full recreate completed, otherwise `max_log_ptr` cannot have moved backwards and the regression path is untested - queries `system.backups` for any backup whose `error` contains `LOGICAL_ERROR` and asserts the count is `0` Addresses review feedback on #100651
…reate, wait for backups Under randomized settings (flaky check), the previous concurrent `drop_and_recreate` background loop never completed a full `DROP DATABASE`+recreate cycle within the 10 second timeout, so the test deterministically printed `not recreated: 0` instead of the expected `recreated`. Restructure the test: - Drive recreates in the foreground, synchronously. Backup workers stay in the background, so the race against `BACKUP ... ASYNC` is preserved while recreate cycles are guaranteed to make progress. - Drop the 5-table `create_and_populate` loop down to a single table; one table is enough to advance `max_log_ptr`. - Bump `TIMEOUT` from 10s to 30s. - After the stress loops, poll `system.backups` until no row for this test's prefix is in `CREATING_BACKUP` before checking for `LOGICAL_ERROR`. `BACKUP ... ASYNC` only waits for submission, so the previous code could read `system.backups` while in-flight backups still had a chance to hit the regression path. Addresses reviewer feedback. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100651&sha=cfdb1b3242dcfd23a58aaf77cd2eeb22e3cfab82&name_0=PR&name_1=Stateless%20tests%20%28amd_asan_ubsan%2C%20flaky%20check%29 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
Re-checked CI and reviews on No The single open review thread ( |
The AI review flagged a residual window in `getTablesForBackup`: if the backup collector retained a stale `DatabaseReplicated` object and a `DROP DATABASE`+recreate completes before the first `/max_log_ptr` read, the captured `czxid` belongs to the new database and all in-function identity checks compare new-to-new. This window cannot make the *written* backup substitute a different database, because `BackupEntriesCollector` bounds it across attempts: it clears `database_infos`/`table_infos` and re-fetches a fresh `DatabasePtr` from `DatabaseCatalog` on every attempt (so a stale object never carries across attempts), and `compareWithPrevious` requires two consecutive attempts to agree on both the database `CREATE` text and the full table set. A transitional attempt mixing the stale object's old `CREATE` (different UUID) with the recreated subtree's new tables disagrees with the next all-new attempt and is discarded; the loop converges to a consistent snapshot or fails with `INCONSISTENT_METADATA_FOR_BACKUP` at the deadline. Add a code comment capturing this invariant so the `czxid` pinning's scope (the narrower intra-operation window) is clear to future readers. No behavioral change. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Addressed the AI review's " The new comment in CI: the only red was |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 108/163 (66.26%) · Uncovered code |
|
Re-checked CI and reviews on Public CI: fully green — all 170 check runs are AI Review: flipped back to ✅ Approve on
Neither touches the |
alexey-milovidov
left a comment
There was a problem hiding this comment.
While it might sound complex, this is just fixing ABA with asserting the version.
|
How the database got recreated "under the hood" — the exact scenario from the original failure. The CI report in the description ( with the test comment DROP DATABASE IF EXISTS d1_test_069hvpy6;
CREATE DATABASE d1_test_069hvpy6 ENGINE = Replicated('/clickhouse/databases/d1_test_069hvpy6', '{shard}', '{replica}');
CREATE TABLE d1_test_069hvpy6."t4" (...) ENGINE = Set();
BACKUP DATABASE d2_... TO File(...) ... ASYNC;
BACKUP TABLE d1_test_069hvpy6."t4" TO Memory(...) ... ASYNC;So while one thread's To answer the two questions from the earlier thread explicitly:
The exact interleaving that fired the assertion:
|
|
Could this be prevented instead of detected — e.g. Several alternatives exist, but one structural fact limits all of them: no local lock can fully protect this, because the Keeper subtree can be removed by a different server. A With that caveat, the options:
Assessment: blocking is possible (option 1 is a small change on existing |
…n backups The test previously only asserted server liveness (`SELECT 1`), so a regression of the original `chassert(max_log_ptr == new_max_log_ptr)` failure could go undetected: the `chassert` raises a `LOGICAL_ERROR` exception that is silently swallowed by `BACKUP ... ASYNC`, and the test could pass even if the regression path was never exercised at all. Now the test: - counts successful `DROP DATABASE` cycles in `drop_and_recreate` and asserts that at least one full recreate completed, otherwise `max_log_ptr` cannot have moved backwards and the regression path is untested - queries `system.backups` for any backup whose `error` contains `LOGICAL_ERROR` and asserts the count is `0` Addresses review feedback on ClickHouse#100651
The cleanup loop streamed `SELECT id FROM system.backups` through a pipe into `while read`. When the loop hit the deadline and `break`-ed mid-stream, the upstream `clickhouse-client` was still writing IDs and surfaced a `CANNOT_WRITE_TO_FILE_DESCRIPTOR` (`Broken pipe`) error on stderr, which the test harness flagged as "having stderror" and reported as `FAIL` even though the test logic itself succeeded. Read the full ID list into a `BACKUP_IDS` array first, then iterate. No pipe exists, so an early `break` cannot cause a `SIGPIPE` upstream. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100651&sha=fca9e2d7d63e0bb1fa597ae5ac4c2e7a6d7d2a3f&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20parallel%29 ClickHouse#100651 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
… `DROP` per-attempt Under flaky-check stress, the test ran back-to-back five times and reported `not recreated: 0` every time -- meaning the foreground `DROP DATABASE SYNC` never completed within the 45-second window. With six backup workers in tight `BACKUP ... ASYNC` submission loops, the foreground drop got starved for the entire stress phase: a single hung iteration consumed the whole budget, the regression path went unexercised, and `bugfix_validation` reported `Failed to reproduce the bug`. Bound each drop attempt with `max_execution_time=10`. A stuck drop is now killed and the loop retries on the next iteration, so `RECREATE_COUNT >= 1` is reliably reached even when the system is overloaded. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100651&sha=774cb3f05f3aae0a517bcfb1184c2042e972390e&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20flaky%20check%29 ClickHouse#100651 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
`getConsistentMetadataSnapshotImpl` has two execution paths: a fast path that uses `FILTERED_LIST` + `MULTI_READ` + `LIST_WITH_STAT_AND_DATA` for a single atomic Keeper read, and a slow retry-loop fallback. The previous commit added the `max_log_ptr` rollback rejection only to the slow path. If the fast path is taken (modern Keeper, no name filter), the caller's prior `max_log_ptr` value would be silently overwritten with whatever the recreated database has, defeating the regression check the previous commit introduced. Apply the same backwards-rollback check to the fast path: if the value the caller already observed is greater than the value just read, throw `CANNOT_GET_REPLICATED_DATABASE_SNAPSHOT` instead of silently substituting the new database's metadata for the old. ClickHouse#100651
…recreate The previous attempt to bound each `DROP DATABASE SYNC` with `max_execution_time=10` was not enough. Under flaky-check stress the test runs ~10 times back-to-back on a busy CI host, and every single attempt inside the 45s pressure loop kept timing out -- five consecutive flaky runs all reported `not recreated: 0`, failing the reference check before the regression assertion ever ran. Add an unconditional fallback `DROP DATABASE`+recreate cycle after `wait`. Once the worker submission loops have exited the contention drops sharply, but previously-submitted backups are still draining on the server, so this final cycle still gives in-flight backups a chance to observe `max_log_ptr` moving backwards. `RECREATE_COUNT >= 1` is now reliable even when every in-pressure attempt was starved. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100651&sha=5408ff39232a560b091094fe0b9d39cb22a3942f&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20flaky%20check%29 ClickHouse#100651
The in-loop rollback guard in `getConsistentMetadataSnapshotImpl` only catches the case where the recreated database has `max_log_ptr` *below* the value the caller observed before the call. As pointed out in review on PR ClickHouse#100651, a fast recreated database can advance past the old pointer before the snapshot iteration reads `/max_log_ptr` again, in which case the rollback guard silently substitutes metadata from the new database. Add a Keeper-path identity check in `getTablesForBackup`: read `/max_log_ptr` with its `Stat` once before the snapshot, then re-read it after the snapshot and compare `czxid`. `czxid` is set when the node is created and is stable across `Set`s, so any change implies the entire database subtree was dropped and a new database was created at the same Keeper path during the operation. This is strictly stronger than the rollback guard and catches both shapes of the recreate race.
…he new error fires The CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100651&sha=97a6ba2dfbe8d5fe2c3e19008ac29fe99681cee7&name_0=PR&name_1=Bugfix%20validation%20%28functional%20tests%29 Bugfix validation runs the new test against the master HEAD release binary to confirm the test actually catches the bug. On that binary, the original regression is mostly silent: the fast path in `getConsistentMetadataSnapshotImpl` just substitutes the recreated database's metadata without raising any error, and only the (rarely entered) retry-loop branch surfaces the bug as `Cannot get consistent metadata snapshot` after exhausting retries. The `chassert` symptom requires a debug build. Whenever the run takes the silent path the test passes on unfixed master, and bugfix validation reports `Failed to reproduce the bug`. Add a deterministic positive assertion: with the existing stress (six backup workers + foreground recreate loop), the new guards (in-loop monotonicity plus post-loop `czxid` identity) must throw `CANNOT_GET_REPLICATED_DATABASE_SNAPSHOT` with message prefix `Replicated database was dropped` for at least one in-flight backup. That message string is introduced by this PR and does not exist in master, so a non-zero count is a unique signature of the fix being engaged. Reference gains a trailing `1`. PR: ClickHouse#100651
…stentMetadataSnapshotImpl Move the `czxid` revalidation of `/max_log_ptr` from `getTablesForBackup` into `getConsistentMetadataSnapshotImpl`. The check now runs at the start and end of every snapshot operation, so it covers `recoverLostReplica` and `tryCompareLocalAndZooKeeperTablesAndDumpDiffForDebugOnly` in addition to backup. Both branches (the fast `MULTI_READ` path and the retry loop) now throw `CANNOT_GET_REPLICATED_DATABASE_SNAPSHOT` when the Keeper subtree identity changes during the snapshot. The final read uses `tryGet` so the case where `/max_log_ptr` has been removed by `DROP DATABASE` but not yet recreated also surfaces as the same descriptive error, instead of leaking a `ZNONODE` keeper exception that does not mention the recreate. Addresses review on ClickHouse#100651 (comment)
Convert the initial `zookeeper->get(/max_log_ptr)` (fast path) and
`zookeeper->get(/metadata)` (slow path) to `tryGet` with an explicit
`CANNOT_GET_REPLICATED_DATABASE_SNAPSHOT` throw when the node is missing.
Without this, when `DROP DATABASE` completes between resolving the
in-memory `DatabaseReplicated` object and the first Keeper read inside
`getConsistentMetadataSnapshotImpl`, callers see a generic
`KEEPER_EXCEPTION` ("node doesn't exist") instead of the
fix-specific `Replicated database was dropped` message. The race is
detected either way, but the message becomes diagnostic.
This widens the deterministic signal that bugfix validation
(`04057_backup_replicated_db_recreate`) relies on: the test counts
backups whose error contains `Replicated database was dropped`, and
this commit ensures that count is non-zero whenever the stress loop
hits the recreate-during-backup race - including the much more common
case where `DROP` finishes before the snapshot's first Keeper read.
CI report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100651&sha=46036cc047e4cd2428bd0be5ab15e01d456ac99b&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20parallel%29
PR: ClickHouse#100651
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…ic failpoint The previous version relied on natural concurrency between six backup workers and a foreground `DROP`+`CREATE` loop to land a backup inside `getConsistentMetadataSnapshotImpl` exactly while the database was recreated. The race window is short (a few `tryGet` round-trips), and under flaky-check stress every one of the 5 reruns missed it (third assertion `count > 0` of `Replicated database was dropped` returned 0), causing the test to fail across every CI configuration (amd_debug parallel, amd_asan_ubsan distributed plan, amd_msan WasmEdge, amd_llvm_coverage AsyncInsert / DatabaseReplicated, arm_asan_ubsan targeted, all 4 flaky-check variants). Replace it with a single deterministic reproducer driven by a new `PAUSEABLE_ONCE` failpoint `database_replicated_pause_after_reading_log_pointer` inserted in `DatabaseReplicated::getTablesForBackup` between the `snapshot_version` read and the call to `getConsistentMetadataSnapshotImpl`. The test: 1. Creates the database with 10 tables so `max_log_ptr` advances to ~11. 2. Submits `BACKUP ... ASYNC` and waits for the pause. 3. Runs `DROP`+`CREATE` at the same Keeper path, resetting `max_log_ptr` to 1. 4. Notifies the failpoint. On resume, the in-loop monotonicity guard in `getConsistentMetadataSnapshotImpl` fires `Replicated database was dropped` because `max_log_ptr (~11) > new_max_log_ptr (1)`. On unfixed master the same path produces `LOGICAL_ERROR` (debug, via the `chassert(max_log_ptr == new_max_log_ptr)`) or `Cannot get consistent metadata snapshot` (release, via retry exhaustion); both are caught by the second assertion, which makes bugfix-validation reliable too. Tag the test `no-parallel` because `PAUSEABLE_ONCE` is global and a concurrent backup from another test could steal the pause. CI report (failures the previous version produced): https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100651&sha=9206a137aa432f08d2afe2cf409e5b9661e0052e&name_0=PR PR: ClickHouse#100651 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…og-ptr-assertion Fix logical error exception in getConsistentMetadataSnapshotImpl when log pointer goes backwards
test_concurrent_reads runs 25 concurrent SELECT * queries against one accumulating Iceberg table while 15 Spark writers commit in parallel, for 10 rounds. By default each SELECT fans out to ~max_threads (number of CPU cores) internal read threads, so 25 simultaneous readers request hundreds of threads at once. On a loaded CI shard this oversubscribes the global thread pool: a single SELECT either gets starved past the 300s client receive_timeout (Return code 159, seen on the asan/db-disk/old-analyzer 5/6 shard for PRs ClickHouse#100651 and ClickHouse#108049 and on master) or the server rejects the query outright with CANNOT_SCHEDULE_TASK (Code 439, threads=1000, jobs=1000). Pin max_threads=4 on the concurrent SELECT so the readers' aggregate thread demand stays bounded. This does not change what the test verifies: all 25 readers still race all 15 writers across every round and the exact row-count assertion is unchanged. Only the per-query intra-read parallelism is capped, which is irrelevant to concurrent-read snapshot consistency. Locally reproduced both directions on a debug build: pristine test fails at round 2 with CANNOT_SCHEDULE_TASK; with the cap it passes all 10 rounds (~150s). (cherry picked from commit 0ee2f26) Signed-off-by: CarlosFelipeOR <[email protected]>
The
chassert(max_log_ptr == new_max_log_ptr)ingetConsistentMetadataSnapshotImplfires when aDatabaseReplicatedis dropped and recreated during a backup operation. The initialmax_log_ptris read from the old database, but after recreation the new database has a smaller log pointer, causing the assertion to fail.Throw
CANNOT_GET_REPLICATED_DATABASE_SNAPSHOTinstead, since the database that was asked to back up no longer exists; the new database (with the same name but different identity) should not be silently substituted.CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100641&sha=c7c8447120affec1e60b8c7c6380dab230aa9439&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20parallel%29
#100641
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a
LOGICAL_ERRORexception during backup of aReplicateddatabase that is being dropped and recreated concurrently; such backups now fail cleanly withCANNOT_GET_REPLICATED_DATABASE_SNAPSHOT.Documentation entry for user-facing changes
Note
Medium Risk
Changes snapshotting logic used by
DatabaseReplicatedbackup and recovery to detect concurrentDROP DATABASE+recreate via Keeperczxid/log-pointer checks; incorrect handling could cause backup/recovery failures or wrong metadata selection, so it needs careful concurrency coverage but is scoped to this race.Overview
Prevents
DatabaseReplicatedmetadata snapshots (used by backups and lost-replica recovery) from crashing or silently reading from a recreated database instance when a concurrentDROP DATABASEremoves and re-creates the same Keeper subtree.getConsistentMetadataSnapshotImplnow pins database identity using/max_log_ptr’sczxid, converts multiple KeeperZNONODE/rollback situations into a consistentCANNOT_GET_REPLICATED_DATABASE_SNAPSHOTerror (replacing the previouschassert/retry-exhaustion behavior), and forwards an optional expectedczxidfrom callers (getTablesForBackup,DatabaseReplicatedWorker::initializeReplication). A newPAUSEABLE_ONCEfailpoint plus a stateless test were added to deterministically reproduce the drop+recreate race during backup.Reviewed by Cursor Bugbot for commit 3439122. Bugbot is set up for automated code reviews on this repo. Configure here.
Version info
26.7.1.810(included in26.7and later)