Skip to content

Do not let an unparsable KeeperMap metadata node stop the server from starting - #115941

Merged
alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:keeper-map-invalid-metadata-quarantine
Aug 24, 2026
Merged

alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:keeper-map-invalid-metadata-quarantine

Conversation

@groeneai

@groeneai groeneai commented Aug 22, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #115881

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

Stress test jobs fail with Cannot start clickhouse-server: after a restart the server dies with
Code: 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_metadata writes deliberately - it has no metadata envelope, and
replaceOne(value, needle, replacement) cannot return a bare replacement. The stress profile fuzzes every
query type, and fuzzing permutes a function's argument list, so the replacement literal becomes the
haystack and lands in the shared metadata node. The fuzzer runs as a finish callback with exceptions
swallowed, 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. getTableStatus asks isMetadataStringCompatible not to
throw, but the parsing inside it throws unconditionally and escapes the Coordination::Exception-only
handler around it, so the whole load table job fails instead of quarantining the one table as
INVALID_METADATA (the state drop() documents).

Changes. The test pins ast_fuzzer_runs = 0 / ast_fuzzer_any_query = 0 (no-stress is rejected by
design; precedent in 04104_ast_fuzzer_preserves_caller_transaction.sql). The server honours
throw_on_error = false by guarding the whole untrusted-parse region, so startup and ATTACH quarantine
the one table; CREATE on an existing path passes true and still rethrows unchanged. This shrinks the
blast radius but does not make a quarantined table recoverable - DROP TABLE still leaves the Keeper
nodes 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 CREATE on that node still
fails with code 27, and 50/50 randomized runs pass.


Workflow [PR]
Sync PR [sync-upstream/pr/115941]

Version info

  • Merged into: 26.9.1.31 (included in 26.9 and later)
  • Backported to: 26.8.3.100, 26.7.7.90, 26.6.5.118

… 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.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Aug 22, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

Two review rounds before opening this PR. Round 1 raised 3 findings that were agreed and fixed;
round 2 raised none. Findings below are stated with the verdict I reached and the evidence for it.

Round 1

❌ A transient allocation failure would have permanently quarantined a healthy table - AGREED, fixed.
The first version converted every exception inside the parse into "invalid metadata". That verdict is
cached for the table object's lifetime and drop() returns early on it, so a MEMORY_LIMIT_EXCEEDED
from the query's own memory tracker would have stranded a table whose metadata is perfectly compatible,
with no way to clean it up - reachable in exactly the redundant-parenthesis case #115642 shipped for.
Now a not-enough-memory error is rethrown instead, leaving the status unknown so the next access
retries.

❌ The new closing assertion would have been flaky in the stress test it stabilizes - AGREED, fixed.
The stress runner appends ignore_drop_queries_probability=0.2, and an ignored DROP becomes a
TRUNCATE for a storage that does not keep data on disk, which KeeperMap does not. So the final
count() would have returned 1 instead of 0 in about one stress run in five. The test now pins that
setting to 0, which also covers the 8 pre-existing drops. Verified by forcing the setting to 1 on the
same server and binary: without the pin the test fails with count() = 1, with the pin it passes with 0.

⚠️ Direct joins and RESTORE reach a quarantined table without a status check - DISAGREED, but real
and worth recording. The mechanism is correct: getByKeys and the restore path do not call checkTable.
It is not reachable for the population this change newly admits, because the only supported way to attach
a table whose schema diverges from the stored one is CREATE, which passes throw_on_error = true and is
byte-for-byte unchanged here (the test pins that as a control). Every peer on a corrupt path therefore
shares a schema. The gap is pre-existing and its worse instance - a parseable columns mismatch, which
already returned false without throwing - is untouched by this PR. Gating it would change behaviour for
that pre-existing population with no coverage, on a different root cause.

💡 The region comment was 4 lines and half of it narrated the code. Trimmed to 2, keeping the clause that
states why the stored value cannot be trusted.

Round 2

No findings. Four observations, none blocking:

⚠️ The memory guard tests error codes, so a raw std::bad_alloc from operator new arrives as
STD_EXCEPTION and is not covered. Left as is deliberately: the memory tracker throws
MEMORY_LIMIT_EXCEEDED long before the allocator itself fails on any server with a configured limit, and
widening to STD_EXCEPTION would pull std::out_of_range - the pre-#115642 failure mode - back onto the
fatal path this PR removes. The in-tree helper for this class, isNotEnoughMemoryErrorCode, has the same
code-only shape.

⚠️ On the non-throwing path the rethrown memory error still escapes to the load job, so startup can still
fail under memory pressure. That is the intended outcome: the status stays unknown and retries, whereas
returning false would cache the quarantine permanently and make the table's own DROP a no-op.

⚠️ The test still leaves a corrupt node behind if it is killed inside its rewrite window. That value class
is already non-fatal on an unpatched server: replaceOne keeps the metadata envelope, so the value parses,
fails the primary-key comparison, and quarantines without throwing. Only the envelope-less value throws,
and its only producer is the fuzzer this PR pins off - so the two halves compose rather than one being
redundant, and the server change is defence in depth against any future producer.

💡 Also noticed while tracing: 04850_parenthesized_definitions_replica_recovery.sh has the same fuzzer
exposure (four replaceOne calls inside an INSERT INTO system.zookeeper), but it writes to its own
replica path for a table it drops, so a mangled value there cannot strand a shared KeeperMap path. Not
changed here - one root cause per PR - and not raised separately, since there is no user-reachable
consequence.

Known limitation, stated in the description rather than fixed: a quarantined table's Keeper nodes are
still not removed by DROP TABLE, because drop() returns before removing them. Measured, and the test
works around it by repairing the node from the data node first. That is a separate and larger question.

Session id: cron:clickhouse-review-slot-48:20260822-202900

@clickhouse-gh clickhouse-gh Bot closed this Aug 22, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Aug 22, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate
# Check Result
a Deterministic repro Write the envelope-less value with one INSERT INTO system.zookeeper, restart with async_load_databases=false: the server exits without starting, every time. The fuzzer mechanism also reproduced live on a running server (ASTFuzzerQueries 0 -> 100 as a control).
b Root cause explained The stress profile fuzzes every query type; a permuted replaceOne argument list makes the replacement literal the haystack, so the needle stops matching and the bare literal is written to the shared metadata node. The fuzzer is a finish callback with exceptions swallowed, so the test passes and the node survives. On the next start isMetadataStringCompatible throws despite throw_on_error=false, the throw escapes the Coordination::Exception-only handler in getTableStatus, and the load table job fails.
c Fix matches root cause Two changes, one per defect: pin the fuzzer off in the test that manufactures the state, and honour throw_on_error=false so the existing INVALID_METADATA quarantine is reachable. No widened bound, no no-random-* tag, no guard at the failure site.
d Test intent preserved, new tests added No existing arm changed or removed; the three BAD_ARGUMENTS arms still cover the mismatch branch. Five new assertions: quarantine after ATTACH, INVALID_STATE on read and on write, the unchanged hard-error path, metadata repair equality, and post-DROP cleanup.
e Both directions demonstrated Startup on identical corrupt state: exits without starting -> Ready for connections with the load job OK. Test through clickhouse-test: [ FAIL ] (code 27 at the ATTACH) -> [ OK ].
f General across code paths isMetadataStringCompatible has exactly two call sites; the throw_on_error=true one is unchanged (throw; rethrows the original exception, code and message). Fixed in the function that ignores its own flag, not at the load site. The handler in getTableStatus was deliberately not widened.
g Generalizes across inputs Nine malformed shapes all quarantine instead of failing the load: empty, envelope-less, unterminated paren, semicolon-terminated, random bytes, truncated envelope, missing primary-key header, unparsable columns payload, and a 1200-deep parenthesized key. The last throws TOO_DEEP_RECURSION from inside a callee, which is why the guard covers the whole region rather than a list of sites.
h Backward compatible No setting default changed (both SET are session-scoped inside one test), so no SettingsChangesHistory.cpp entry. The stored format is untouched; only the reaction to an already-malformed value changes, and only on the non-throwing path.
i Invariants and contracts preserved The function's contract is now honoured rather than broken: throw_on_error=false returns a bool. columns_equal is initialized before the guarded region so the code after it reads a defined value on every path. A quarantined table still refuses read, write, truncate and mutate with INVALID_STATE, and drop() still removes the local table. The restart re-entry path is the one measured above.

Also run: all 18 keeper_map stateless tests (15 pass; 3 fail identically on a pre-change binary,
caused by gaps in the local repro config rather than this change), and the modified test twice in one
database to confirm no ZooKeeper state is left behind.

@clickhouse-gh

clickhouse-gh Bot commented Aug 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a9bf0ae]

Summary: ✅


AI Review

Summary

This PR makes KeeperMap startup tolerate an unreadable stored metadata znode by quarantining that table as INVALID_METADATA instead of aborting the whole load, and it stabilizes the stateless test against stress-mode AST fuzzing and DROP rewriting. The main direction is correct, but the new non-throwing parse guard is too wide: it also suppresses failures in parsing the locally generated metadata string, which can silently quarantine healthy tables if a future serializer/parser change stops round-tripping.

PR Metadata
  • Changelog category should be Bug Fix (user-visible misbehavior in an official stable release), not CI Fix or Improvement: this patch changes server behavior for a real KeeperMap startup failure, not only test stability.
  • With that category, a user-readable Changelog entry is required. ... is not sufficient.
  • Exact replacement text:
### 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

⚠️ Majors

  • [src/Storages/StorageKeeperMap.cpp:753] The new throw_on_error = false guard now swallows failures while parsing the local metadata string, even though only the Keeper value is untrusted. If a future change makes metadata.columns.toString(true) or the formatted primary key stop round-tripping through ColumnsDescription::parse / tryCanonicalPrimaryKey, startup will now mark healthy KeeperMap tables as INVALID_METADATA and cache that false quarantine instead of surfacing the internal regression.
    Suggested fix: pre-parse the local metadata outside the non-throwing handler, or rethrow failures from the local branch and only downgrade exceptions coming from the stored Keeper string.
Final Verdict

Request changes.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.00% 87.10% +0.10%
Functions 91.90% 91.90% +0.00%
Branches 79.30% 79.40% +0.10%

Changed lines: Changed C/C++ lines covered: 36/41 (87.80%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Aug 22, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @antonio2368 @kssenii, could you review this? getTableStatus asks isMetadataStringCompatible not to throw, but the parsing inside it throws unconditionally and escapes the Coordination::Exception-only handler around it, so one unreadable metadata node fails the whole load table job instead of quarantining that table as INVALID_METADATA. The stress test that manufactures such a node (via the server-side AST fuzzer permuting a replaceOne argument list) now pins the fuzzer off.

Comment thread src/Storages/StorageKeeperMap.cpp Resolved
Comment thread src/Storages/StorageKeeperMap.cpp Resolved
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.
@skuznetsov-clickhouse

Copy link
Copy Markdown
Contributor

@groeneai here is the easier solution for the tests:

-- After all positive checks и check on invalid PK:
DROP TABLE 05024_keeper_map_parenthesized_metadata_second SYNC;
DROP TABLE 05024_keeper_map_parenthesized_metadata_reverse SYNC;
DETACH TABLE 05024_keeper_map_parenthesized_metadata PERMANENTLY SYNC;

-- All current checks malformed (key и key; are staying the same (no changes).

-- Right after recover primary key: (key)\n:
ATTACH TABLE 05024_keeper_map_parenthesized_metadata;

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

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 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?

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.

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 COLUMN diverges 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: ATTACH fine, insert and select round-trip, DROP clean. 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.

@clickhouse-gh

clickhouse-gh Bot commented Aug 23, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing a9bf0ae47 with master 0abbc75f0 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 1562fec97; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 705.74 MiB 702.72 MiB -3.03 MiB (-0.43%)

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 units

7 translation units recompiled, 17 s compile time in total, 7 of them have a recent master baseline.

Job report

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

@alexey-milovidov alexey-milovidov self-assigned this Aug 23, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

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 (Stress test (amd_msan), 105987 / f7d2dd6), 19 occurrences of the message, not one of them with the envelope present:

15  in ZK: primary key: (key)
 4  in ZK: primary key: (key
 0  in ZK: KeeperMap metadata format version: ...

All 7 Code: 27 load-job failures pair with primary key: (key), and 6 of the 7 are ..._reverse. The producer is the stress profile's AST fuzzer permuting a replaceOne argument list so the replacement literal becomes the haystack:

replaceOne('primary key: (key)\n', 'primary key: key\n', <full definition>) = 'primary key: (key)\n'

That fires on the first positive rewrite (key to (key)), which is before the point where your version drops the siblings, and both tables are still attached there. So the reordering narrows the window without closing it; SET ast_fuzzer_runs = 0 is the part that closes it. With that pin in place the malformed (key and key; values keep their envelope, and an envelope-keeping value is not fatal at startup.

On the server side. That half is not about this test. getTableStatus calls isMetadataStringCompatible with throw_on_error = false, the parse inside throws anyway, and the throw escapes the Coordination::Exception-only handler, so any unreadable metadata node fails the entire load job instead of quarantining that one table as INVALID_METADATA. That is #115881, reachable from a corrupt node of any origin.

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.

@groeneai

Copy link
Copy Markdown
Collaborator Author

The write already has a single choke point: StorageSystemZooKeeper::write refuses unless the server config sets allow_zookeeper_write (default false, StorageSystemZooKeeper.cpp:328). Stateless tests only have it because tests/config/install.sh:112 symlinks tests/config/config.d/zookeeper_write.xml unconditionally, and 10 integration test directories already opt in explicitly. So the change is one deleted line plus converting the affected tests, no new code.

7 stateless tests write to system.zookeeper today. Two of them (02311_system_zookeeper_insert.sql, 02311_system_zookeeper_insert_priv.sh) exist to test the write feature itself, including 8 serverError arms and the ACCESS_DENIED check, so they have to move rather than be edited. The other five fabricate replica or table state deliberately: 02447_drop_database_replica.sh, 02447_drop_database_replica_auxiliary_zookeeper.sh, 02980_dist_insert_readonly_replica, 04850_parenthesized_definitions_replica_recovery.sh, 05024_keeper_map_parenthesized_metadata.sql. Six of the seven scope their target path to currentDatabase(), CLICKHOUSE_TEST_ZOOKEEPER_PREFIX or the KeeperMap prefix; the exception is 02980, which writes to a fixed /tables/shard_1/... path, so the damage you are describing is real but concentrated there.

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. getTableStatus asks isMetadataStringCompatible not to throw, the parse throws anyway, and it escapes the Coordination::Exception-only handler, so any unreadable metadata node fails the whole load job instead of quarantining that one table.

clickhouse-gh Bot pushed a commit that referenced this pull request Aug 27, 2026
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]>
@groeneai

groeneai commented Sep 5, 2026

Copy link
Copy Markdown
Collaborator Author

@alexey-milovidov could you apply v26.6-must-backport here? It resolves to the same three branches that both sibling fixes in this family already reached through merged robot backports (#115642 and #116369), and this PR is the only one of the three never backported.

26.7 and 26.8 still abort at server start on an unparsable KeeperMap metadata znode. Marker counts in src/Storages/StorageKeeperMap.cpp, where the two right-hand columns are the positive control that those refs read correctly:

ref will treat the table as having invalid metadata (this PR) tryCanonicalPrimaryKey (#115642) formatPrimaryKeyForMetadata (#116369)
master 1 3 2
26.8 0 3 2
26.7 0 3 2
26.6 0 3 2

CIDB since this merged, on test_context_raw LIKE '%Invalid KeeperMap metadata format version%': true master 0 across 18893 Stress test% rows / 316 trees; 26.8 1 on the branch itself (2026-09-02 16:31:38Z) and 1 on a 26.8 backport PR (2026-09-04 20:02:30Z); 26.7 0. I do not read 26.7's zero as unaffected: master hit this on 2 of 92 trees during the 69h its copy of the test carried no fuzzer pin, and 26.7 has run 72 trees since, so about 1.6 hits would be expected.

26.6 is why I suggest the floor there rather than at 26.7. Your #116730 already hand-ported the test-hardening half of this PR to 26.6, and the 26.6 rows went 2 -> 0 across that merge, but the src half is still absent, so a 26.6 server remains intolerant even though its CI no longer shows it.

Portability, measured per file with git merge-file --diff3 against each branch tip: 26.8, 26.7 and 26.6 are 0 conflict hunks on all three files, this PR's marker goes 0 -> 1, and #115642's and #116369's symbols are preserved. On 26.6 it is idempotent against #116730: the result is byte-identical to master's file with all three of your SETs intact.

Not proposing 26.3: it never received #115642 and does not carry the test, and the three-way there is 6 conflict hunks whose resolution would pull tryCanonicalPrimaryKey in with it.

Context: #115881, which this PR closed.

@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Sep 12, 2026
@robot-clickhouse robot-clickhouse added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 12, 2026
clickhouse-gh Bot pushed a commit that referenced this pull request Sep 12, 2026
clickhouse-gh Bot added a commit that referenced this pull request Sep 12, 2026
Backport #115941 to 26.8: Do not let an unparsable KeeperMap metadata node stop the server from starting
clickhouse-gh Bot added a commit that referenced this pull request Sep 12, 2026
Backport #115941 to 26.6: Do not let an unparsable KeeperMap metadata node stop the server from starting
clickhouse-gh Bot added a commit that referenced this pull request Sep 12, 2026
Backport #115941 to 26.7: Do not let an unparsable KeeperMap metadata node stop the server from starting
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 18, 2026
…p metadata node stop the server from starting
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 18, 2026
…p metadata node stop the server from starting
middas-0706 pushed a commit to middas-0706/ClickHouse that referenced this pull request Sep 19, 2026
…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
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 groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-ci pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.6-must-backport

Projects

None yet

7 participants