Repository navigation
Do not let an unparsable KeeperMap metadata node stop the server from starting - #115941
alexey-milovidov merged 3 commits into
Conversation
… starting Stress test jobs fail with "Cannot start clickhouse-server": after a restart the server dies with Code: 722 ... Code: 695 ... Load job 'load table ...' failed: Code: 27 ... Invalid KeeperMap metadata format version or columns definition in ZK: primary key: (key) Two independent defects are involved. The corrupt node is not written by 05024_keeper_map_parenthesized_metadata's own deliberately malformed metadata: the value observed in CI carries no metadata envelope at all, and replaceOne(value, needle, replacement) cannot return a bare replacement. The stress profile enables the server-side AST fuzzer for every query type (tests/docker_scripts/stress_tests.lib), and fuzzExpressionList permutes a function's argument list, so the replacement literal becomes the haystack, the needle no longer matches, and that literal is written to the shared metadata node. The fuzzer runs as a query finish callback with exceptions swallowed, so the original statement has already committed, the test still passes, and the corrupt node is left behind. Measured with the fuzzer enabled: the unmodified test leaves such a node in 4 of 8 runs, the pinned test in 0 of 8. The test now pins ast_fuzzer_runs and ast_fuzzer_any_query off; the no-stress tag is rejected by design, and there is precedent in 04104_ast_fuzzer_preserves_caller_transaction.sql. Separately, getTableStatus passes throw_on_error=false to isMetadataStringCompatible intending to mark the table INVALID_METADATA, but every parse step inside that function throws unconditionally, and the surrounding handler catches only Coordination::Exception. The throw therefore escapes checkTable<false> and the constructor, so the load job for that one table fails and startup aborts - even though drop() documents INVALID_METADATA as a per-table quarantine that read, write, truncate and mutate already rely on. The parsing is now guarded as a whole region rather than per site, because tryCanonicalPrimaryKey throws TOO_DEEP_RECURSION from inside tryParseQuery and a site list cannot cover callee throws. When throw_on_error is true the original exception is rethrown unchanged, so CREATE and ATTACH on a corrupt path fail with the same code and message as before; only the non-throwing path changes, and it now returns false as its contract promises. Validated on identical corrupt Keeper state with only the binary differing: before, the server exits without starting; after, it logs a warning, finishes the load job and serves. The test fails before the change and passes after, while a fresh CREATE against the same node is asserted to still fail with code 27 so the strict path is pinned as unchanged. Nine malformed shapes were checked, including a 1200-deep parenthesized primary key, and all quarantine rather than failing the load. The new arm repairs the metadata node from the data node before dropping, because DROP TABLE on a table with invalid metadata removes only the local table and would otherwise leave the path behind. Closes: ClickHouse#115881
…he test Three follow-ups on the previous commit. Rethrow a not-enough-memory failure instead of converting it to an invalid-metadata verdict. The verdict is cached for the lifetime of the table object and drop() returns early on it, so an allocation failure inside the parse would strand a table with perfectly compatible metadata until the next restart, unable even to be dropped. Before the region guard such an exception escaped getTableStatus and the next query simply retried. Implemented as a local getCurrentExceptionCode() comparison rather than isNotEnoughMemoryErrorCode, because that helper's header pulls in MergeTreeData.h and only the two MergeTree storages include it today. CANNOT_MUNMAP and CANNOT_MREMAP are excluded deliberately: they are mmap-teardown failures, unreachable from this parse. Not covered by a new test arm - a memory failure inside a few hundred bytes of parsing is not reachable from SQL, and a failpoint would be new machinery for a two-code guard. Measured: ATTACH under max_memory_usage of 1, 1024 and 100000 all complete normally. Pin ignore_drop_queries_probability in the test. The stress runner sets it to 0.2, and for an engine that reports no on-disk data a DROP is then converted to a TRUNCATE, so the Keeper root survives and the closing count() assertion returns 1 instead of 0 about one stress run in five. The pin sits in the prologue so it also covers the pre-existing drops. Verified in both directions with the conversion forced to always fire: without the pin the test fails on that assertion, with it the test passes. Also trim the region comment to the property a reader cannot infer.
Internal second-model reviewTwo review rounds before opening this PR. Round 1 raised 3 findings that were agreed and fixed; Round 1❌ A transient allocation failure would have permanently quarantined a healthy table - AGREED, fixed. ❌ The new closing assertion would have been flaky in the stress test it stabilizes - AGREED, fixed.
💡 The region comment was 4 lines and half of it narrated the code. Trimmed to 2, keeping the clause that Round 2No findings. Four observations, none blocking:
💡 Also noticed while tracing: Known limitation, stated in the description rather than fixed: a quarantined table's Keeper nodes are Session id: cron:clickhouse-review-slot-48:20260822-202900 |
Pre-PR validation gate
Also run: all 18 |
|
Workflow [PR], commit [a9bf0ae] Summary: ✅
AI ReviewSummaryThis PR makes PR Metadata
### Changelog category (leave one):
- Bug Fix (user-visible misbehavior in an official stable release)
### Changelog entry (a [user-readable short description](https://github.com/ClickHouse/ClickHouse/blob/master/docs/changelog_entry_guidelines.md) of the changes that goes into CHANGELOG.md):
Fixes a `KeeperMap` startup failure where an unreadable `metadata` node in Keeper could prevent the server from loading the table and starting normally.Findings
Final VerdictRequest changes. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 36/41 (87.80%) · Uncovered code |
|
cc @antonio2368 @kssenii, could you review this? |
The generic handler recognized a transient allocation failure by error code, but operator new throws std::bad_alloc directly (src/Common/AllocationInterceptors.cpp), which getCurrentExceptionCode maps to STD_EXCEPTION. Such a failure was therefore cached as INVALID_METADATA and stranded a healthy table until restart, the exact false quarantine the code check was added to avoid. Catching std::bad_alloc specifically keeps std::out_of_range on the quarantine path. Also assert that a single-key lookup on an unreadable path is refused: the direct-join lookup reaches the same plan-time gate as a whole-table read, and the arm was verified to fail against a table whose metadata had been repaired.
|
@groeneai here is the easier solution for the tests: -- After all positive checks и check on invalid PK: -- All current checks malformed -- Right after recover All other changes are not necessary. |
|
|
||
| auto local_columns = ColumnsDescription::parse(local_metadata_string.substr(metadata_format_version_prefix.size(), local_pk_pos + 1 - metadata_format_version_prefix.size())); | ||
| auto zk_columns = ColumnsDescription::parse(zk_metadata_string.substr(metadata_format_version_prefix.size(), zk_pk_pos + 1 - metadata_format_version_prefix.size())); | ||
| auto local_columns = ColumnsDescription::parse(local_metadata_string.substr(metadata_format_version_prefix.size(), local_pk_pos + 1 - metadata_format_version_prefix.size())); |
There was a problem hiding this comment.
This try now downgrades failures while parsing the local metadata string as well as the Keeper value. Only the Keeper string is untrusted here; local_metadata_string is generated from our own metadata.columns.toString(true) / formatted primary key. If a future formatter or parser change stops those local strings from round-tripping, startup will now quietly cache INVALID_METADATA for healthy tables instead of surfacing the internal regression.
Can we keep the local-side parsing outside the throw_on_error = false handler (or rethrow failures from the local branch) and only quarantine exceptions that come from the stored Keeper metadata?
There was a problem hiding this comment.
Agreed, and the premise checks out: local_metadata_string is built by this server at construction from metadata.columns.toString(true) plus the formatted primary key, yet four local-derived throw sites sat inside the region (starts_with, the primary key: search, ColumnsDescription::parse, and tryCanonicalPrimaryKey, which can throw TOO_DEEP_RECURSION). Worse than losing the signal: the cached INVALID_METADATA also makes drop() return before tryRemove, so a healthy table could neither be read nor cleaned up.
Fixed by hoisting all four local-side steps ahead of the guarded region, so only Keeper-derived parsing stays inside it. That splits by input rather than by throw site, so the untrusted region remains a single try.
Two measurements, since a guard is only worth what its arms prove:
- The healthy path through the region is genuinely exercised.
ALTER TABLE ... COMMENT COLUMNdiverges local from stored, because comments are excluded from the compare but included in the generated string, so the equal-strings fast path is skipped and the local parse really runs. Result:ATTACHfine, insert and select round-trip,DROPclean. No false quarantine. - The hoist is load-bearing in both directions. Mutating only the local producer's envelope makes startup fatal with
Code: 27 ... Invalid local KeeperMap metadata ..., while a malformed stored value on the same build is quarantined and the server starts. Reverting the mutation returns a bit-identical build.
Honest about reachability: I could not find a way to make the local string fail to parse today. The formatter normalizes a deeply nested primary key down to primary key: (key), and a column comment containing a newline plus a fake header is escaped to a two-byte literal, so exactly one real header survives. So this preserves an internal-regression signal rather than fixing a reachable bug.
Not pushed yet: I have asked the author of #115642 whether the server-side half of this PR should stay here at all, and I would rather not spend a CI round on a refinement to code that may be dropped. The commit is ready either way.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction. Compile time of recompiled translation units7 translation units recompiled, 17 s compile time in total, 7 of them have a recent master baseline. |
alexey-milovidov
left a comment
There was a problem hiding this comment.
This is highly doubtful. It might be better to prevent writes to system.zookeeper in stateless tests, because it can damage any internal data, that is not supposed to be damaged. However, I can accept this change.
|
The test restructuring is better and I will take it. One measured caveat on it, and then the server-side question is yours. The value that is fatal in CI is not the one the malformed-PK checks write. From the failing run's server log ( All 7 That fires on the first positive rewrite ( On the server side. That half is not about this test. It is your code, so it is your call: keep that half here, or drop it and let #115881 be fixed on its own. I will do whichever you prefer. |
|
The write already has a single choke point: 7 stateless tests write to This is the ZooKeeper analogue of what you asked for on #111922, so I agree with the direction and will do it as a separate PR if you want it. Independent of the test layer: the server change here is what #115881 is about. |
644d2e0
The stress test on the 26.6 backport branch failed to restart the server: the AST fuzzer enabled by the stress profile permuted `replaceOne` arguments in `05024_keeper_map_parenthesized_metadata`, corrupting the shared `metadata` znode, and `ignore_drop_queries_probability` left the table behind, so the server could not attach it after restart (`Invalid KeeperMap metadata format version or columns definition in ZK`). Master already pins these settings in the test (#115941); bring the same hardening to 26.6. CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=116265&sha=87a16e9e33d4bd2f5c5665c50278bc11262b2ee8&name_0=BackportPR&name_1=Stress%20test%20%28amd_tsan%29 PR: #116265 Co-Authored-By: Claude Fable 5 <[email protected]>
|
@alexey-milovidov could you apply
CIDB since this merged, on
Portability, measured per file with Not proposing Context: #115881, which this PR closed. |
… node stop the server from starting
Backport #115941 to 26.8: Do not let an unparsable KeeperMap metadata node stop the server from starting
Backport #115941 to 26.6: Do not let an unparsable KeeperMap metadata node stop the server from starting
Backport #115941 to 26.7: Do not let an unparsable KeeperMap metadata node stop the server from starting
…p metadata node stop the server from starting
…p metadata node stop the server from starting
…check The `Error message in clickhouse-server.log` sub-result of `Upgrade check (amd_release)` fails on unrelated PRs because the post-upgrade server logs <Error> StorageKeeperMap (test_1.`05024_keeper_map_parenthesized_metadata_unparsable` (...)): Failed to activate table because of invalid metadata in ZooKeeper. Please DROP/DETACH table for a table that `05024_keeper_map_parenthesized_metadata` deliberately left with an unreadable `metadata` znode. The job replays the previous release's suite under `stress --upgrade-check`. The test rewrites its shared `metadata` znode through shapes a server must refuse and reverts them near the end of the file; stress worker 1 (`--database=test_1`) runs with `memory_tracker_fault_probability`, so an injected `Code: 241` can stop the file before the `DROP`s at its end run, leaving the tables it created behind with an unreadable znode. The upgrade restart re-attaches the surviving tables and logs the message above per table instead of refusing to start, which is what ClickHouse#115941 made it do on purpose (it replaced the startup abort of ClickHouse#115881), and the runner greps the post-upgrade log for `<Error>`. Measured on the three PRs the signature has hit (ClickHouse#94105, ClickHouse#118419, ClickHouse#94730): the fixture accounts for 1/1, 1/1 and 3/3 of the leaked lines while every other sub-result of the job is OK, so the check yields no signal at all for the carrier. The entry requires the `StorageKeeperMap` logger AND a backquoted table name starting with the fixture prefix AND the message, so the same message on any other KeeperMap table, which is the shape a real metadata-compatibility regression takes, still fails the job. Replaying the job's own scan pipeline over each carrier's `clickhouse-server.upgrade.log` reproduces that job's `upgrade_error_messages.txt` byte for byte, and the entry takes each of the three to zero; over the 156,750 pre-filter log lines the pattern matches exactly the leaked lines and nothing else. Related: ClickHouse#115881
Closes: #115881
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
...
Description
Stress testjobs fail withCannot start clickhouse-server: after a restart the server dies withCode: 695 ... Load job 'load table ...' failed: Code: 27 ... Invalid KeeperMap metadata format version or columns definition in ZK: primary key: (key).Root cause, and it differs from what #115881 assumes. The fatal value is not the malformed metadata
05024_keeper_map_parenthesized_metadatawrites deliberately - it has no metadata envelope, andreplaceOne(value, needle, replacement)cannot return a bare replacement. The stress profile fuzzes everyquery type, and fuzzing permutes a function's argument list, so the replacement literal becomes the
haystack and lands in the shared
metadatanode. The fuzzer runs as a finish callback with exceptionsswallowed, so the test still passes: with it on, the unmodified test leaves such a node in 4 of 8 runs, the
pinned one in 0 of 8.
A second, pre-existing defect makes that fatal.
getTableStatusasksisMetadataStringCompatiblenot tothrow, but the parsing inside it throws unconditionally and escapes the
Coordination::Exception-onlyhandler around it, so the whole
load tablejob fails instead of quarantining the one table asINVALID_METADATA(the statedrop()documents).Changes. The test pins
ast_fuzzer_runs = 0/ast_fuzzer_any_query = 0(no-stressis rejected bydesign; precedent in
04104_ast_fuzzer_preserves_caller_transaction.sql). The server honoursthrow_on_error = falseby guarding the whole untrusted-parse region, so startup andATTACHquarantinethe one table;
CREATEon an existing path passestrueand still rethrows unchanged. This shrinks theblast radius but does not make a quarantined table recoverable -
DROP TABLEstill leaves the Keepernodes behind.
Validation. Same corrupt state, only the binary differs: before, the server exits without starting;
after it warns and serves. The test fails before and passes after, a fresh
CREATEon that node stillfails with code 27, and 50/50 randomized runs pass.
Workflow [PR]
Sync PR [sync-upstream/pr/115941]
Version info
26.9.1.31(included in26.9and later)26.8.3.100,26.7.7.90,26.6.5.118