Skip to content

Fix the Replicated database digest diagnostic in sanitizer builds - #113009

Open
groeneai wants to merge 9 commits into
ClickHouse:masterfrom
groeneai:fix-5007-4c3e-digest-commit-create-table
Open

groeneai wants to merge 9 commits into
ClickHouse:masterfrom
groeneai:fix-5007-4c3e-digest-commit-create-table

Conversation

@groeneai

@groeneai groeneai commented Aug 2, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • CI Fix or Improvement (changelog entry is not required)

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

...

Description

Related: #107583 (same family, RENAME path; a different entry point).

Found in CI: Stress test (arm_msan), LOGICAL_ERROR: Digest does not match from DatabaseReplicated::commitCreateTable.

assertDigestWithProbability aborts on a digest divergence. A routine to name the offending table
exists, but three things stopped it working, so no sighting names one:

  1. The assertion is guarded by DEBUG_OR_SANITIZER_BUILD, the dump by #ifndef NDEBUG. Sanitizer
    builds define NDEBUG, so they abort with no diagnostic.
  2. The dump compares formatted renderings, normalizing away what the digest is sensitive to: it
    hashes raw bytes, so a divergence whose spellings parse to one AST is called consistent.
  3. The dump parsed metadata through a helper answering an unexpected form with a 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_error here, replacing the
Digest does not match abort. The parse helper takes an opt-in flag for reporting an unexpected
form; its four real-execution callers keep the assertion.

No test: reaching the dump needs corrupted metadata and log-line assertions, which AGENTS.md
excludes 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]

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

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author
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
read of the resulting code, then a second-model pass, then adjudication. 14 findings over the three
rounds, 11 agreed and fixed, 3 disagreed with evidence. The final round returned zero findings.

Round 1 (6 findings, all fixed)

⚠️ The dump promised a no-throw contract it could not keep. parseQueryFromMetadata answers metadata
that parses but is not in the form this database writes with a LOGICAL_ERROR, and
Exception::handleErrorCode calls abortOnFailedAssertion at exception CONSTRUCTION in these builds,
so no catch inside the dump could contain it. Since this change newly runs that parse in every
sanitizer build, malformed metadata would have killed the server on a different signature, hiding both
the table names and the family's own error. Fixed by an opt-in flag that reports the form instead of
asserting; the four real-execution callers keep the assertion.

⚠️ The byte report sat outside the per-table guard, the table name was logged only after the parse,
and the test oracle asserted the verdict rather than the payload it delivers. Fixed: two passes, name
first, and the tests now assert every reported field.

💡 Both parser-failure logs embedded the metadata they failed on, which is unmasked. Reduced to the
error code.

❌ A claimed out-of-bounds std::mismatch. Disagreed: the code uses the four-iterator C++14
overload, which has no length precondition. Verified empirically at the exact test shape under
-fsanitize=address,undefined, both length orders: clean, zero reports.

Round 2 (7 findings, 5 fixed, 1 disagreed, 1 recorded)

⚠️ A table present only in the coordinator got no digest term, yet that term is exactly the amount by
which the coordinator digest exceeds the local recompute. Fixed, with a test asserting two ghosts with
byte-identical metadata report different terms (the digest hashes the name too).

⚠️ Formatting calls still sat outside the per-table guard: IAST::format runs checkStackSize, whose
TOO_DEEP_RECURSION is catchable and therefore reached the outer catch and ended the whole dump.
Fixed, and verified by a brace/try-depth scan: zero format calls outside a guard.

⚠️ A coordinator snapshot failure cost the entire report, including the local half that needs no
Keeper, which is what the field-observed comparison actually fails on. Fixed with a separate guard and
an explicit unknown state. The test pins the trap: falling back to an empty map instead makes every
table look absent from the coordinator, which is worse than the bug, and that mutation fails the test.

⚠️ One assertion could not fail for the reason its test stated, because the abort line comes from the
root logger and an earlier test had already put it in the log. Changed to a count delta, which does
fail on unpatched master.

Round 3

Zero findings. Two nits I raised myself I then disagreed with on the evidence: the reported
first-difference offset is accurate as printed for a prefix relationship, and the log-rotation
sensitivity of the count helper needs a 100M log inside one test.

One path stays recorded rather than changed: waitTableStarted -> AsyncLoader::wait can throw
LOGICAL_ERROR, but both throws need a load-worker thread context that the dump does not run in, so
it is not constructible here. The header comments were corrected instead of adding a speculative guard.

Session id: cron:clickhouse-review-slot-50:20260802-144900

@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes for what this PR changes: append one byte to a table's metadata, force the digest check, and the diagnostic blindness reproduces every time. The underlying digest divergence itself has no reproducer (481 forced checks across succeeding ALTERs, background ALTER_METADATA, the fuzzer's UUID-reuse create shape, and a cancelled-DDL storm produced 0 mismatches), which is exactly why no behavioral fix for it is included here.
b Root cause explained? Yes. The assertion is guarded by DEBUG_OR_SANITIZER_BUILD, the dump by #ifndef NDEBUG; sanitizer jobs use -DCMAKE_BUILD_TYPE=None, which CMake maps to RelWithDebInfo and so defines NDEBUG. Verified by a compile-time probe over all three build shapes: with -DNDEBUG -fsanitize=memory the assertion is on and the dump is off. Separately, the dump compared normalized AST renderings while the digest hashes raw bytes, so it could not see the divergence class that fires the assertion.
c Fix matches root cause? Yes: guards aligned, comparison made byte-level, report completed, dump made best effort against every catchable failure. The last part needed several changes, because a catch (...) alone cannot deliver it: the dump no longer calls a parse whose LOGICAL_ERROR aborts at Exception construction in these very builds, the byte report for every table precedes the fragile AST pass, formatting is inside the per-table guard (IAST::format runs checkStackSize, which throws TOO_DEEP_RECURSION on deep but parseable metadata), the coordinator snapshot has its own guard so its failure does not cost the on-disk half of the report, and metadata-derived exception messages are reduced to the error code. Completeness: a table present only in the coordinator now reports its digest term, which is exactly the amount by which the coordinator digest exceeds the local recompute. The assertion is not weakened, the 1/16 sampling is not raised, no repair-what-you-find, no fuzzer-side change.
d Test intent preserved / new tests added? Both existing AST branches are kept as supplementary context. New integration test test_replicated_database_digest_diagnostic has five tests: the diverging table is named with its full byte-level payload; one unreportable table does not silence the report for the others, and every table's byte report precedes the first rendering failure; coordinator metadata that parses but is not in the expected form still ends in Digest does not match rather than a different fatal error; a table present only in the coordinator reports its digest term (two such tables holding byte-identical metadata must report different terms, since the hash covers the table name); and a forced snapshot failure still yields every local digest term, under wording that says the coordinator side is unknown rather than claiming any table is absent from it.
e Both directions demonstrated? Yes, and every new assertion was shown to be able to fail. With the change: 5 passed, 15/15 on 3x repeat. Against an unpatched master binary the suite fails: the byte-level tests report AST for table X is the same for every table and name none, the expected-form test dies with Got unexpected query from ... so the family's own signature never reaches the log, and the coordinator-only test finds no digest term. Each new assertion was additionally verified live by transiently mutating the source it guards and confirming the test reddens, then reverting and re-checking the Build ID. The strongest of these is negative-control rather than presence-only: replacing the explicit no-snapshot state with an empty snapshot map (the plausible wrong fix) makes the report claim every locally-present table is absent from the coordinator, and the test catches that too.
f Fix is general across code paths? Yes. tables_metadata_digest lives only in DatabaseReplicated.{h,cpp} plus two call sites; the change is in the shared helper that both mismatch branches call, so it covers the counter-vs-recompute branch and the Keeper-readback branch, and the second checkDigestValid caller in DatabaseReplicatedWorker benefits identically. No #ifndef NDEBUG remains anywhere in the digest path.
g Fix generalizes across inputs (params/datatypes/wrappers)? Type wrappers are not in play: the digest hashes (table_name, metadata_string). The input space that matters is table state, and each case is exercised: divergent, matching, missing in the coordinator, unreadable local metadata, unparseable coordinator metadata, not-yet-loaded (marked as not a digest carrier, so an investigation is not pointed at a table that contributes nothing), present only in the coordinator, and every one of those with no coordinator snapshot available at all.
h Backward compatible? (maintainer-approved exception only) Yes. Log output only, inside the debug and sanitizer guards. No setting, no serialization change, no SettingsChangesHistory.cpp entry, Keeper /digest semantics untouched, release-build behavior unchanged.
i Invariants and contracts preserved? The helper is const and log-only; it mutates no digest state. Its header no longer claims "never throws", which it could not deliver in these builds: the contract is now best effort, every catchable failure contained, so it cannot replace LOGICAL_ERROR: Digest does not match with an unrelated Keeper or parse error, and the header states that a LOGICAL_ERROR still aborts here by design. The shared metadata parser keeps its LOGICAL_ERROR for all four of its real execution callers; only the three dump call sites opt into treating an unexpected form as reportable data. Error paths are the substance here: a per-table failure is reported and the pass continues, and the outer guard uses tryLogCurrentException. Lock discipline is unchanged (metadata_mutex is held by the caller, and isTableExist takes mutex in the order checkDigestValid already uses); the digest-carrier flag is documented as sampled after that mutex was released, so false is not exculpatory. The digest-carrier flag is sampled once per table rather than once per pass, so the two passes cannot print opposite answers about one table. Two known holes are deliberately left open and out of scope: an unreadable .sql still throws from the recompute before the dump runs, so that case reports a filesystem error rather than the digest signature; and tryGetCreateOrAttachTableQuery can in principle reach an uncatchable LOGICAL_ERROR via AsyncLoader::wait, which I could not construct, so no speculative guard is added for it.

Session id: cron:clickhouse-review-slot-50:20260802-144900

@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author

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 DEBUG_OR_SANITIZER_BUILD while the dump was guarded by #ifndef NDEBUG, and sanitizer jobs build RelWithDebInfo, so those aborts carried no diagnostic at all. It also compares raw metadata bytes now, since the digest hashes bytes while the old dump compared normalized ASTs.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Aug 2, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [605f74c]

Summary: ✅


AI Review

Summary

Reviewed #113009 at 605f74c6ca84457f27408c4f06aaa12654d0b4ca. The change enables the Replicated database digest diagnostic in sanitizer builds, reports raw metadata differences, and contains diagnostic failures. No actionable findings remain after reviewing the current code and all prior discussion. The recorded before/after reproductions support this diagnostic-only change; no local build or tests were run during this review.

Final Verdict

✅ Approve — no changes requested.

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Aug 2, 2026
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.
@tiandiwonder tiandiwonder self-assigned this Aug 3, 2026
@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - ac95e1c

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Build (arm_release) / Post Hooks telemetry hook: LogCluster query failed with code 500 on the build_time_trace INSERT (build_profile_hook.py, line 293 in check); the build itself succeeded (check_status = success), so it does not gate this PR a fix task is created (investigating at full effort, fixing-PR link to follow on this PR)
Sync - CH Inc sync (private, not actionable)

All 175 check-runs are complete: 151 success, 24 skipped, 0 failures among them. Finish Workflow
and Mergeable Check both pass, and the combined commit status is success.

The Post Hooks row is not caused by this diff. This PR touches src/Common/FailPoint.cpp,
src/Databases/DatabaseReplicated.{cpp,h} and a new
tests/integration/test_replicated_database_digest_diagnostic/ directory, while the row comes from
the build-profile telemetry upload path. Breadth over 7 days is 513 rows across 43 distinct pull
requests and 317 distinct commits, 466 of those rows on master, confined to the *_release build
variants.

Session id: cron:our-pr-ci-monitor:20260803-040000

Comment thread src/Databases/DatabaseReplicated.cpp Outdated
}
catch (...)
{
tryLogCurrentException(log, "Failed to dump the local and coordinator metadata diff");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - deed731

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Build (arm_release) / Post Hooks telemetry hook: LogCluster query failed with code 500 on the build_time_trace INSERT (build_profile_hook.py); the build itself succeeded (check_status = success), so it does not gate this pull request a fix task is moved to pending (investigating at full effort, fixing-PR link to follow on this pull request)
Sync - CH Inc sync (private, not actionable)

All 174 check-runs are complete: 151 success, 23 skipped, 0 failures among them. Config Workflow,
Finish Workflow and Mergeable Check all pass, and the combined commit status is success.

The Post Hooks row is not caused by this diff. This head touches src/Common/FailPoint.cpp,
src/Databases/DatabaseReplicated.cpp and tests/integration/test_replicated_database_digest_diagnostic/test.py,
while the row comes from the build-profile telemetry upload path. Breadth over 7 days is 960 rows
across 345 distinct pull requests and 758 distinct commits, 482 of those rows on master, confined to
the *_release build variants (arm_release 731, amd_release 203, arm_release_pr_cache_warmup 26).

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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - a5f7a5f

CI fully finished on this head: 174 of 174 check-runs completed (150 success, 23 skipped,
1 failure), 0 queued or in progress, Config Workflow and Finish Workflow both green,
past the 20-minute CIDB ingestion buffer.

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens.

Check / test Reason Owner / fixing PR
Stateless tests (amd_tsan, parallel) / Server died + Logical error: Bad cast from type DB::ColumnNullable to DB::ColumnString (STID 4350-6700) server abort during a part-rewriting mutation; the job's own tally is Failed: 0, Passed: 11063, Skipped: 169, so no individual test asserted, the server died underneath the run #112501 (external, @alexey-milovidov, open) records the storage column type when a mutation rewrites the whole part, which is the cast this abort takes
Build (arm_release) / Post Hooks build-profile telemetry INSERT INTO build_time_trace got LogCluster query failed with code 500. The build itself passed: the job's check_status is success and the check-run concluded success, so it gates nothing infra, not this PR. A fix task is moved to pending (investigating at full effort, fixing-PR link to follow on this PR)

The abort is not reachable from this PR's diff, and the same job reports zero failing tests
across 11063 passes. No other functional, integration, stress, fuzzer, sanitizer or performance
check failed on this head.

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=113009&sha=a5f7a5f1ea7183cddda4c4fc43ede25a2ddb66a4&name_0=PR

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());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

@clickhouse-gh

clickhouse-gh Bot commented Sep 11, 2026

Copy link
Copy Markdown
Contributor

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]>
groeneai and others added 2 commits October 14, 2026 13:46
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]>

This branch has not been deployed

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

Labels

can be tested Allows running workflows for external contributors comp-database-engines Database engine implementations (e.g., Atomic/Replicated) and database-level behavior. groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-ci

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants