Repository navigation
Conversation
…itizer builds When tables_metadata_digest diverges from the recomputed digest, assertDigestWithProbability aborts with LOGICAL_ERROR "Digest does not match". tryCompareLocalAndZooKeeperTablesAndDumpDiffForDebugOnly exists to name the offending table, but two things stopped it from working, which is why sightings of this failure have never named one. First, the assertion is guarded by DEBUG_OR_SANITIZER_BUILD while both dump call sites were guarded by #ifndef NDEBUG. Sanitizer jobs build with -DCMAKE_BUILD_TYPE=None, which CMakeLists.txt rewrites to RelWithDebInfo, for which CMake defines NDEBUG, while DEBUG_OR_SANITIZER_BUILD is still set through MEMORY_SANITIZER. So every sanitizer build aborted with no diagnostic at all. A compile-time probe over the three build shapes confirms it: with -DNDEBUG -fsanitize=memory the assertion is enabled and the dump is not, and a plain -DNDEBUG build has neither. Second, the dump compared formatWithSecretsOneLine renderings, which normalize away exactly what the digest is sensitive to. getMetadataHash hashes the raw metadata bytes, so a divergence whose two spellings parse to the same AST makes the dump report every table consistent while the abort still fires. Reproduced against an unpatched binary: a one-byte metadata divergence aborts while logging "AST for table X is the same" for every table. Align the guards, and report per table the digest term plus a raw-byte comparison against the coordinator: both sides' sizes, both hashes, and the offset of the first differing byte. The raw content itself is not logged because it is unmasked and may contain secrets, which is why the neighbouring AST path renders through formatForLogging. Also mark whether the table contributes to the digest at all: checkDigestValid sums over the in-memory tables map while the dump iterates getAllTableNames, which additionally lists not-yet-loaded tables, and reporting one of those unmarked would point an investigation at a table that cannot be the diverging term. Make the dump best effort, which is a precondition for widening the guard rather than a cleanup. It calls into Keeper, the filesystem and the parser immediately before an abort; an escaping exception would replace the matched "Digest does not match" signature with an unrelated error and hide the failure family instead of explaining it. Handling is at two levels: per table, so an unreportable table is named with its error state and the loop continues to the rest, and an outer guard so nothing escapes. A single whole-body catch would stop at the first unreportable table and name neither it nor any table after it, and unreadable metadata is itself one of the divergences being hunted. tryGetCreateOrAttachTableQuery dereferenced the result of tryGetCreateTableQuery, which is documented as returning nullptr when a table has no readable metadata. That is reachable exactly in the case above, and now runs in sanitizer builds, so guard it. This does not fix the underlying divergence, which has no reproducer yet: 481 forced digest checks over succeeding ALTERs, background ALTER_METADATA, the fuzzer's UUID-reuse create pattern and a cancelled-DDL storm produced no mismatch. It makes the next occurrence in CI say which table diverged and how. Release builds are unaffected; everything here is inside the debug and sanitizer guards.
The dump added in the previous commit states it never throws, and that is what lets it run immediately before the digest assertion aborts: an escaping exception would replace "Digest does not match" and hide the failure family. Three routes defeated that. parseQueryFromMetadata throws LOGICAL_ERROR when parsed metadata is not in the form this database writes, and Exception::handleErrorCode calls abortOnFailedAssertion at construction when debug_or_sanitizer_build, so a catch(...) can never intercept it. The dump called that helper on both the local and the coordinator side, in exactly the builds it now runs in. Demonstrated on an unpatched binary: coordinator metadata that parses but carries no UUID makes the server die with "Got unexpected query from ..." instead, so CI matches a different signature and no table is named. The dump now passes unexpected_form_is_not_an_error and reports the form itself; the other four callers of that helper are real execution paths and keep the assertion. The per-table loop interleaved the raw-byte report with the fragile AST rendering, so a table whose rendering failed cost the byte report of every table after it. Split into two passes: the byte report for all tables, then the rendering. Reproduced by re-interleaving them, which reduces the set of tables reported before the first failure from three to one. Both catches logged getCurrentExceptionMessage. parseQuery embeds the query text in its SYNTAX_ERROR message via writeQueryAroundTheError, so metadata that the dump deliberately does not log was reaching the log through the error path. Log the error code and name instead. Also name a table before attempting anything that can fail for it, and record that the digest carrier flag is sampled after checkDigestValid released the mutex, so false is not exculpatory. The regression test asserts the whole report payload rather than the verdict: both sizes, both digest terms and the first differing byte offset are the fields this adds over the pre-existing dump, and dropping any one of them was verified to fail the test. A third test covers the unexpected-form path.
…vailable Three gaps in the digest mismatch dump, all in the same "report is best effort per table" direction as the previous commit. A table present in the coordinator but absent locally got only its name. Its coordinator digest term is exactly the amount by which the coordinator digest exceeds the local recompute, so it is the number that answers whether one table explains the whole delta. It is also the class the pre-fix dump treated as its headline case. The per-table guard covered the parse but not the formatting that follows it. IAST::format runs checkStackSize, which throws TOO_DEEP_RECURSION on deeply nested but perfectly parseable metadata, and the parser's depth budget is not the formatter's remaining stack. Being catchable, it reached the outer catch and ended the whole dump, costing the names of every coordinator-only table after it. The coordinator snapshot was fetched inside the outer try, so a snapshot failure cost the entire report, including the on-disk half that needs no coordinator at all. The observed failure is the local recompute disagreeing with the in-memory counter, which reaches the dump without consulting the coordinator, and the lane where this family fires runs Keeper fault injection. The snapshot now has its own guard, and its absence is threaded through as an explicit unknown state rather than an empty map, which would have made every table look absent from the coordinator. Also: the carrier flag was sampled once per pass, so the two passes could print opposite answers for one table; it is now sampled once. The header comments claimed "Never throws", which a catch cannot deliver for a LOGICAL_ERROR in these builds. The digest abort line comes from the root logger, so it carries no database prefix and an earlier test in the module already put it in the log. The tests assert a delta over the counts captured before their own abort instead of a whole-log match.
Internal second-model review (3 rounds, all findings resolved)I put this change through three rounds of independent review before opening it: each round a cold Round 1 (6 findings, all fixed)
💡 Both parser-failure logs embedded the metadata they failed on, which is unmasked. Reduced to the ❌ A claimed out-of-bounds Round 2 (7 findings, 5 fixed, 1 disagreed, 1 recorded)
Round 3Zero findings. Two nits I raised myself I then disagreed with on the evidence: the reported One path stays recorded rather than changed: Session id: cron:clickhouse-review-slot-50:20260802-144900 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-review-slot-50:20260802-144900 |
|
cc @alesapin @tuanpach, could you review this? The routine that names the diverging table on a Replicated database digest mismatch never ran in sanitizer builds: the assertion is guarded by |
|
Workflow [PR], commit [605f74c] Summary: ✅
AI ReviewSummaryReviewed #113009 at Final Verdict✅ Approve — no changes requested. |
The `catch_all` style sub-check flagged this block because the exception is recorded through a local helper rather than one of the names the checker recognizes. The exception is not swallowed: it is stored in `failure_reason` and logged on the next statement, which is what lets the loop go on to name the remaining coordinator-only tables instead of ending the report at the first unparseable one. Adding a second log call at the catch would duplicate that line, so the suppression comment the checker documents is used instead.
CI finish ledger - ac95e1cEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
All 175 check-runs are complete: 151 success, 24 skipped, 0 failures among them. The Session id: cron:our-pr-ci-monitor:20260803-040000 |
| } | ||
| catch (...) | ||
| { | ||
| tryLogCurrentException(log, "Failed to dump the local and coordinator metadata diff"); |
There was a problem hiding this comment.
the outer catch uses tryLogCurrentException, which formats the message — and getExceptionMessage calls abortOnFailedAssertion on a caught std::logic_error in debug/sanitizer builds (Exception.cpp:547-549), so a std::logic_error escaping to here would replace Digest does not match with a different fatal signature, the exact failure this dump exists to avoid. safer to report via describeCurrentExceptionForDumpOnly as the inner handlers do (and then the "catches every catchable failure" comment holds).
There was a problem hiding this comment.
You are right, and it is reachable rather than theoretical. Fixed in deed731.
tryLogCurrentException -> tryLogCurrentExceptionImpl (ExceptionExt.h:14) -> getCurrentExceptionMessageAndPattern, which rethrows to classify and, in the std::exception arm, rethrows again under debug_or_sanitizer_build to call abortOnFailedAssertion on a std::logic_error (Exception.cpp:537-549). std::invalid_argument and std::out_of_range derive from it, and the dump body calls std::map::at twice, so nothing about the shape is exotic. Since the dump runs immediately before the digest abort, that replaced the one signature the dump exists to preserve.
It now reports the code via describeCurrentExceptionForDumpOnly, as the inner handlers do, so the "every catchable failure is contained" comment holds.
Pinned with a new failpoint that throws a std::logic_error into the dump (test_dump_survives_a_std_logic_error). With the fix: abort stays Logical error: 'Digest does not match' and the handler logs error code 1001 (STD_EXCEPTION). Reverting only that line reddens the test, and the abort becomes the dump's own:
Logical error: 'std::exception. Code: 1001, type: std::logic_error, e.what() = Injecting a
std::logic_error while dumping the metadata diff'
...
1. DatabaseReplicated.cpp:1301: DB::DatabaseReplicated::tryCompareLocalAndZooKeeperTablesAndDumpDiffForDebugOnly
2. DatabaseReplicated.cpp:1546: DB::DatabaseReplicated::checkDigestValid
Whole suite 6/6 locally. I also corrected the case count in the description, which still said 5.
The outer handler of tryCompareLocalAndZooKeeperTablesAndDumpDiffForDebugOnly used tryLogCurrentException, which formats the exception via getCurrentExceptionMessageAndPattern. That function rethrows to classify, and on a std::logic_error it calls abortOnFailedAssertion (Exception.cpp:537-549) in debug and sanitizer builds. Since the dump runs immediately before the digest assertion aborts, an escaping std::logic_error made the process abort with the dump's own signature instead of 'Digest does not match', losing precisely the attribution this dump exists to provide. Report the error code instead, via the same describeCurrentExceptionForDumpOnly helper the inner handlers already use. Reachability is real rather than theoretical: std::invalid_argument and std::out_of_range both derive from std::logic_error, and the dump body calls std::map::at. Verified both directions with a new failpoint that throws a std::logic_error into the dump. With the fix the abort stays 'Digest does not match' and the handler logs 'error code 1001 (STD_EXCEPTION)'. Reverting only the handler line reproduces the replaced abort: Logical error: 'std::exception. Code: 1001, type: std::logic_error, e.what() = Injecting a std::logic_error while dumping the metadata diff' Reported by @ tiandiwonder in review.
CI finish ledger - deed731Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
All 174 check-runs are complete: 151 success, 23 skipped, 0 failures among them. The Session id: cron:our-pr-ci-monitor:20260804-133000 |
Master made ApplyWithSubqueryVisitor::visit static (f7a210f, "Do not check the analyzer setting when expanding CTEs"), which removed the constructor this branch was calling. This branch had independently changed the same line's subject from a reference cast to a pointer, so that parseQueryFromMetadata can fold a non-CREATE query into its unexpected-form branch instead of throwing from the cast. Both changes are kept: the static call on the pointer form. src/Common/FailPoint.cpp auto-merged as a union; all four newly added fail points are present and the macro list has no duplicate entry.
| /// aborting form check, and guard the formatting too, since `IAST::format` runs `checkStackSize`. | ||
| try | ||
| { | ||
| ASTPtr local_ast_ptr = tryGetCreateOrAttachTableQuery(table_name, local_context); |
There was a problem hiding this comment.
getAllTableNames() on DatabaseAtomic includes names from startup_table, and this loop preserves those entries via is_digest_carrier = false. But tryGetCreateOrAttachTableQuery() still goes through tryGetCreateTableQuery(), which calls tryGetTable() and then waitTableStarted(). That means the supplementary AST pass can now synchronously wait for a not-yet-loaded table before the fatal digest path finishes.
On the mismatch path this breaks the best-effort contract the rest of the patch is trying to establish: a slow or wedged startup task can delay or deadlock the Digest does not match abort instead of merely reducing the amount of AST context we log. I think this needs to skip the in-memory AST fetch when is_digest_carrier is false (or otherwise avoid tryGetCreateTableQuery() here) and stay on the on-disk / coordinator views only.
There was a problem hiding this comment.
The mechanism is right, but "now" is not: master already makes this exact call over this exact list. In origin/master, tryCompareLocalAndZooKeeperTablesAndDumpDiffForDebugOnly does getAllTableNames(local_context) at :1155 and then tryGetCreateOrAttachTableQuery(table_name, local_context) at :1169, for every name, with no carrier distinction. tryGetCreateOrAttachTableQuery is not touched by this PR. So waitTableStarted on the fatal path pre-dates this change; it is not introduced or widened here.
This PR improves that failure mode rather than creating it. On master it was one pass with the in-memory AST fetch as the first per-table operation, so a wedged startup on the first table cost the whole report. Here the raw-byte pass runs first and to completion, and it is wait-free: readMetadataFile goes to the disk, the carrier flag is isTableExist, i.e. a lock plus tables.contains (DatabasesCommon.cpp:460-464), and getAllTableNames is a lock plus two map walks (DatabaseOrdinary.cpp:704-716). The digest terms and the name of the diverging table are therefore in the log before anything can wait. The AST pass only runs afterwards.
I also do not think is_digest_carrier is the right key. The wait is keyed on startup_table, not on tables: waitTableStarted returns immediately unless startup_table holds the name (DatabaseOrdinary.cpp:637), and startup_table[name] is populated synchronously at graph construction (DatabaseOrdinary.cpp:608 from TablesLoader.cpp:143-149) while attachTable happens inside the load job (DatabaseOrdinary.cpp:395). That gives two windows: load pending, where the table is in startup_table but not in tables so the carrier flag is false and your guard skips it; and startup pending, where it is in both, the carrier flag is true, your guard does not skip it, and waitTableStarted still waits. The second window is the one where table->startup() actually runs, so it is the longer one. Gating on the carrier flag would cover the shorter window and miss the longer.
I am leaving it as is. It is pre-existing, this PR narrows the exposure, and I have not been able to construct the wait, so a defensive change here would be unverifiable. AsyncLoader::wait is unbounded (AsyncLoader.cpp:468-474), so I have kept the residual recorded rather than dismissed; if it is ever fixed, the condition should be a pending-startup test, not the carrier flag.
CI finish ledger - a5f7a5fCI fully finished on this head: 174 of 174 check-runs completed (150 success, 23 skipped, Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
The abort is not reachable from this PR's diff, and the same job reports zero failing tests Session id: cron:our-pr-ci-monitor:20260805-023000 |
| { | ||
| /// Not tryLogCurrentException: it formats the message, which aborts on a caught | ||
| /// std::logic_error in these builds and would replace the mismatch being reported. | ||
| LOG_ERROR(log, "Failed to dump the local and coordinator metadata diff: {}", describeCurrentExceptionForDumpOnly()); |
There was a problem hiding this comment.
this resolves my earlier concern. traced it: getCurrentExceptionCode catches a std::logic_error as std::exception and returns STD_EXCEPTION without ever formatting the message, so it can't reach the abortOnFailedAssertion path tryLogCurrentException would hit — the Digest does not match signature is preserved. and reachability is real (std::map::at → std::out_of_range), which the new failpoint test pins. thanks.
|
Dear @tiandiwonder, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself. |
The one conflict is the `ApplyWithSubqueryVisitor::visit` call in `parseQueryFromMetadata`. This branch takes `create` as a pointer, so a non-CREATE query reaches the `unexpected_form_is_not_an_error` branch instead of throwing from a reference cast. Master now passes `max_expanded_ast_elements = 0` to that call (873da41). The resolution keeps both: the pointer form and master's extra argument and comment. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The in-tree AGENTS.md excludes integration tests that hand-corrupt metadata or only assert that a log line exists. Every case of test_replicated_database_digest_diagnostic does both: it rewrites local or Keeper metadata, forces the digest assertion, and checks the dump's log payload. Remove the module, its configs, and the two failpoints used only by it (database_replicated_dump_fail_to_get_metadata_snapshot and database_replicated_dump_throw_std_logic_error). Validation stays local: the four failpoint-free cases of the removed module still pass on this tree's binary. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment-only change: keep the local invariants, drop the narration of the design and the duplicates of the header comments. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
...
Description
Related: #107583 (same family,
RENAMEpath; a different entry point).Found in CI:
Stress test (arm_msan),LOGICAL_ERROR: Digest does not matchfromDatabaseReplicated::commitCreateTable.assertDigestWithProbabilityaborts on a digest divergence. A routine to name the offending tableexists, but three things stopped it working, so no sighting names one:
DEBUG_OR_SANITIZER_BUILD, the dump by#ifndef NDEBUG. Sanitizerbuilds define
NDEBUG, so they abort with no diagnostic.hashes raw bytes, so a divergence whose spellings parse to one AST is called consistent.
LOGICAL_ERROR,which aborts at construction here, so malformed metadata aborted on a different signature.
The fix is confined to that diagnostic. The guards are aligned. Every table, local or
coordinator-only, now reports its digest term plus a raw-byte comparison against the coordinator;
where the bytes differ it also reports both sizes, both hashes and the first differing offset, never
the content. A coordinator snapshot failure still leaves the local half. Escaped exceptions are
reported by error code: formatting one aborts on a
std::logic_errorhere, replacing theDigest does not matchabort. The parse helper takes an opt-in flag for reporting an unexpectedform; its four real-execution callers keep the assertion.
No test: reaching the dump needs corrupted metadata and log-line assertions, which
AGENTS.mdexcludes from integration tests, and a stateless test cannot survive the abort. Validated locally on
a debug build with one table's metadata bytes changed: master calls every table's AST the same, this
branch names the diverging table. Release builds are unaffected.
Root-cause fixes for the divergences found so far: #117235, #117399. This makes any further
occurrence name the diverging table.
Workflow [PR]
Sync PR [sync-upstream/pr/113009]