Skip to content

Fix logical error exception in getConsistentMetadataSnapshotImpl when log pointer goes backwards - #100651

Merged
alexey-milovidov merged 85 commits into
masterfrom
fix-backup-max-log-ptr-assertion
Jul 11, 2026
Merged

alexey-milovidov merged 85 commits into
masterfrom
fix-backup-max-log-ptr-assertion

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Mar 24, 2026 •

Copy link
Copy Markdown
Member

The chassert(max_log_ptr == new_max_log_ptr) in getConsistentMetadataSnapshotImpl fires when a DatabaseReplicated is dropped and recreated during a backup operation. The initial max_log_ptr is 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_SNAPSHOT instead, 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):

  • 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 LOGICAL_ERROR exception during backup of a Replicated database that is being dropped and recreated concurrently; such backups now fail cleanly with CANNOT_GET_REPLICATED_DATABASE_SNAPSHOT.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Note

Medium Risk
Changes snapshotting logic used by DatabaseReplicated backup and recovery to detect concurrent DROP DATABASE+recreate via Keeper czxid/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 DatabaseReplicated metadata snapshots (used by backups and lost-replica recovery) from crashing or silently reading from a recreated database instance when a concurrent DROP DATABASE removes and re-creates the same Keeper subtree.

getConsistentMetadataSnapshotImpl now pins database identity using /max_log_ptr’s czxid, converts multiple Keeper ZNONODE/rollback situations into a consistent CANNOT_GET_REPLICATED_DATABASE_SNAPSHOT error (replacing the previous chassert/retry-exhaustion behavior), and forwards an optional expected czxid from callers (getTablesForBackup, DatabaseReplicatedWorker::initializeReplication). A new PAUSEABLE_ONCE failpoint 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

  • Merged into: 26.7.1.810 (included in 26.7 and later)

…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]>
@clickhouse-gh

clickhouse-gh Bot commented Mar 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [fc34664]

Summary: ✅


AI Review

Summary

This PR changes DatabaseReplicated metadata snapshotting so a concurrent DROP DATABASE plus recreate at the same Keeper path no longer trips the old LOGICAL_ERROR assertion or silently substitutes metadata from the recreated database. The current code pins /max_log_ptr identity with czxid, normalizes the relevant ZNONODE windows to CANNOT_GET_REPLICATED_DATABASE_SNAPSHOT, handles non-ZOK Keeper responses explicitly, and adds focused failpoint-based stateless tests for the entry identity check, forward-pointer recreate case, and rollback guard. I did not find any remaining correctness issue that needs a new inline comment.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Mar 24, 2026
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]>
alexey-milovidov and others added 12 commits March 25, 2026 21:16
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]>
Comment thread src/Databases/DatabaseReplicated.cpp Resolved
alexey-milovidov and others added 3 commits April 24, 2026 14:55
…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
alexey-milovidov and others added 2 commits April 26, 2026 05:01
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Re-checked CI and reviews on 3a6cca88; nothing material has changed since my previous status, so I re-triggered the two flaky Stress test jobs (amd_tsan, arm_tsan). Both failed only on Hung check failed, possible deadlock found, the chronic master-wide flake #107941 (OPEN); neither captured stack contains any DatabaseReplicated/backup frame (amd_tsan = QueryAnalyzer::resolveFunction recursion, arm_tsan = executeASTFuzzerQueries → TCPHandler). A fresh run is now in progress.

No master re-merge: the branch is ~195 commits behind but the merge-base is from yesterday (2026-06-29 23:39Z, <1 day), there are no conflicts, and the two reds are flakes a master merge cannot fix.

The single open review thread (DatabaseReplicated.cpp:2776, AI ⚠️ Request changes) remains satisfied via the verdict's explicit "or document why" alternative — see my traced reply on that thread; no code change is needed.

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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Addressed the AI review's "⚠️ Request changes" verdict. Its minimum required action allowed either closing the pre-first-read identity window or documenting why the backup collector cannot end up snapshotting a recreated database — pushed fc34664b9b1, which takes the documentation route in code (comment-only, no behavioral change).

The new comment in getTablesForBackup records why the residual pre-first-read window is benign: BackupEntriesCollector re-gathers all metadata from scratch on every attempt (clears database_infos/table_infos and re-fetches a fresh DatabasePtr from DatabaseCatalog, so no stale object survives 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 a stale object's old CREATE (different UUID) with the recreated subtree's new tables is therefore discarded; the loop converges to a consistent snapshot or fails with INCONSISTENT_METADATA_FOR_BACKUP. The czxid pinning only has to close the narrower intra-operation window. The verdict's alternative (pin identity at object construction to also reject backing up x after an already-completed recreate) is a separate name-addressed-backup semantics decision left as a maintainer call. Resolved the corresponding review thread.

CI: the only red was Stress test (arm_tsan) → Hung check failed, possible deadlock found, the chronic master-wide flake #107941 (OPEN); the captured stack is an AST-fuzzer query with no DatabaseReplicated frames, unrelated to this change. A fresh CI run is now in progress on fc34664b9b1.

@clickhouse-gh

clickhouse-gh Bot commented Jul 1, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.40% 85.50% +0.10%
Functions 92.60% 92.70% +0.10%
Branches 77.70% 77.70% +0.00%

Changed lines: Changed C/C++ lines covered: 108/163 (66.26%) · Uncovered code

Full report · Diff report

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Re-checked CI and reviews on fc34664b.

Public CI: fully green — all 170 check runs are SUCCESS/SKIPPED, including every Stress test job (the chronic hung-check flake #107941 did not recur this run). Mergeable Check is SUCCESS.

AI Review: flipped back to ✅ Approve on fc34664b — "I did not find any remaining correctness issue that needs a new inline comment." 0 unresolved review threads.

CH Inc sync (private #53573, on the correct head fc34664b): the only non-green status, and not caused by this PR. It failed on exactly two unrelated Cloud-only integration tests:

  • test_distributed_cache/test.py::test_idle_client_ttl — a timing flake (idle_client_ttl_sec=3, idle_client_check_interval_sec=1): client2 cache was purged despite continuous activity (assert 0 > 0) under ASan load. Distributed Cache is a Cloud-only feature.
  • test_refreshable_mv_no_multi_read/test.py::test_refreshable_mv_attach_without_multi_read — Refreshable MV attach.

Neither touches the DatabaseReplicated backup/recovery metadata snapshotting that this PR changes (DatabaseReplicated.cpp, DatabaseReplicatedWorker.cpp, FailPoint.cpp). I re-triggered the two failed private integration shards. No code change needed.

@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.

While it might sound complex, this is just fixing ABA with asserting the version.

@alexey-milovidov alexey-milovidov self-assigned this Jul 11, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

How the database got recreated "under the hood" — the exact scenario from the original failure.

The CI report in the description (Stateless tests (amd_debug, parallel) on #100641) shows the aborted query was

BACKUP TABLE d1_test_069hvpy6."t4" TO Memory('test_069hvpy6_19/backup2.tar')
SETTINGS base_backup = File('test_069hvpy6_19/backup0.tar.zst'), ... ASYNC

with the test comment 03784_bad_base_backup.sh-test_069hvpy6. The test 03784_bad_base_backup.sh runs four identical shell loops in parallel, all operating on the same database names. Each iteration does:

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 ASYNC backup was still collecting metadata on a BackupAsync pool thread, another loop thread had already started its next iteration and executed DROP DATABASE + CREATE DATABASE for the same name (the server log around the abort is full of DATABASE_ALREADY_EXISTS / UNKNOWN_DATABASE / "was dropped or renamed concurrently" errors from the four threads stomping on each other).

To answer the two questions from the earlier thread explicitly:

  • "With the same path in Keeper?" — Yes, necessarily: the path is a literal derived from the database name, so every recreate lands at exactly /clickhouse/databases/d1_test_069hvpy6. Any workflow that recreates a database under the same name with a name-derived path (the usual convention) reproduces this.
  • "And why didn't it get cleaned up while dropped?" — It did get cleaned up, and that is precisely what enables the ABA. When the last replica is dropped, DatabaseReplicated::drop removes the entire Keeper subtree (tryRemoveRecursive(zookeeper_path) after successfully removing /replicas). The subsequent CREATE DATABASE then re-initializes the same path from scratch: fresh czxids and /max_log_ptr = 1. What is not cleaned up is the in-memory DatabaseReplicated object on the server: BackupEntriesCollector obtained a DatabasePtr from DatabaseCatalog before the drop, and DROP DATABASE removes the catalog entry but cannot invalidate in-flight shared_ptr holders. That stale object addresses Keeper purely by the path string, so after the recreate all of its reads transparently resolve to the new instance's znodes.

The exact interleaving that fired the assertion:

  1. BackupAsync thread: getTablesForBackup on d1_test_069hvpy6 (note that BACKUP TABLE goes through it too — the collector gathers table metadata via the database object) reads /max_log_ptr = N, where N > 1 because the CREATE TABLEs had bumped it.
  2. Another loop thread: DROP DATABASE d1_test_069hvpy6 — last (only) replica, so the whole subtree is removed.
  3. A loop thread: CREATE DATABASE d1_test_069hvpy6 at the same path — fresh subtree, /max_log_ptr = 1.
  4. BackupAsync thread, inside getConsistentMetadataSnapshotImpl: re-reads /max_log_ptr at the same path and gets 1 < N. The old code assumed the log pointer can only move forward (> means "retry") and asserted equality otherwise, so chassert(max_log_ptr == new_max_log_ptr) aborted the debug build (the Server died entry in that report). In a release build the chassert is a no-op and the retry loop ran to exhaustion, throwing Cannot get consistent metadata snapshot.

ASYNC only widens the window (the drop can equally overlap a synchronous backup); the essential ingredients are just a retained DatabasePtr, a DROP DATABASE of the last replica (full subtree removal), and a re-CREATE under the same name/path. Same path, new identity — a textbook ABA, which is why the fix pins the identity via the czxid of /max_log_ptr and treats a backwards-moving log pointer as the drop/recreate signature.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 11, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Could this be prevented instead of detected — e.g. BACKUP blocking DROP DATABASE?

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 DROP DATABASE of the last replica on another host, or SYSTEM DROP DATABASE REPLICA from any server that reaches the same Keeper (InterpreterSystemQuery.cpp → the static DatabaseReplicated::dropReplica, which removes the whole subtree when /replicas becomes empty), never touches any mutex on the server running the backup. So whatever prevention is added, the czxid identity check stays necessary as the backstop — locking can only make the local race rarer, not eliminate the error path.

With that caveat, the options:

  1. BACKUP blocks local DROP DATABASE — feasible and cheap, the machinery already exists. DROP DATABASE takes the database-level lock exclusively (getExclusiveDDLGuardForDatabase in InterpreterDropQuery, locking DatabaseGuard::database_ddl_mutex), while table DDL holds the same SharedMutex shared. The metadata-collection phase of backup could hold it shared too — table DDL keeps flowing (which the consistency loop needs), only DROP DATABASE waits. There is precedent one level down: the collector already takes tryLockForShare on every table (BackupEntriesCollector.cpp), so DROP TABLE during a backup already blocks up to lock_acquire_timeout (120s default). The costs: priority inversion — DROP DATABASE hangs for up to the metadata phase (bounded by collect_metadata_timeout, default 600s), or the whole backup if held through data copying (hours). The general philosophy is that DROP wins — it kills merges and mutations; a scheduled nightly backup silently blocking an operator's DROP DATABASE for 10 minutes is arguably worse than the backup failing with a clear error. And it is incomplete anyway, per the structural point above — the original CI scenario happened to be a local drop, but the fix cannot assume that.

  2. Distributed lease in Keeper — the only complete prevention. Backup creates an ephemeral node like <db_path>/lock_backups/<id>; drop/dropReplica either waits for it or fails with "database is being backed up". This does cover cross-server drops, but needs a Keeper schema addition with backward compatibility (an older server dropping the database won't check the node), session-expiry edge cases, an atomicity dance (create lease + verify subtree in one multi), and the same policy question of DROP-waits vs DROP-fails. Heavy machinery to protect a rare race that already has a clean retry story on the backup side.

  3. Deferred cleanup / graveyard (analogous to marking tables as dropped locally): don't delete the subtree, move it aside and GC later, so in-flight readers finish against a frozen snapshot. Doesn't really work here: ZooKeeper has no atomic subtree rename, and the reader addresses the database by path string, so relocation breaks it exactly like deletion does — it would rebuild the same detection problem plus garbage-collection complexity.

  4. Atomic snapshot reads (single multi-read of the whole metadata subtree): removes torn reads and retries, but doesn't address identity at all — a fully consistent read of the recreated database is precisely the silent substitution that must not happen. Complementary at best.

  5. Pin identity earlier / address by UUID — capture the identity when the DatabaseReplicated object (or the backup) is created, so even an already-completed recreate is rejected. That is a semantics decision about name-addressed backups (should BACKUP DATABASE x mean "whatever x is now" or "the instance first seen"?) — orthogonal to the race fix, and it still reduces to comparing a czxid.

Assessment: blocking is possible (option 1 is a small change on existing DDLGuard machinery), but every prevention variant either doesn't cover cross-server drops or requires a distributed lease with real compatibility and liveness costs — and all of them invert the "DROP wins" priority. Since the collector is already an optimistic retry loop, optimistic detection with a version assertion is the cheapest mechanism that is actually correct, and it is required regardless of any locking. A shared DDL guard during metadata collection could be layered on later as a UX improvement for the local case, but it would not allow removing a single line of this fix.

Merged via the queue into master with commit ab8535b Jul 11, 2026
174 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-backup-max-log-ptr-assertion branch July 11, 2026 23:44
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 11, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…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
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
… `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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
`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
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…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
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
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.
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…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
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…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)
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…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]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…og-ptr-assertion

Fix logical error exception in getConsistentMetadataSnapshotImpl when log pointer goes backwards
CarlosFelipeOR pushed a commit to Altinity/ClickHouse that referenced this pull request Oct 20, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

Development

Successfully merging this pull request may close these issues.

4 participants