Skip to content

Fix shared cache issues between Protobuf and ProtobufList - #100849

Merged
Avogar merged 6 commits into
ClickHouse:masterfrom
callumc34:fix/fallback-from-envelope
May 1, 2026
Merged

Avogar merged 6 commits into
ClickHouse:masterfrom
callumc34:fix/fallback-from-envelope

Conversation

@callumc34

@callumc34 callumc34 commented Mar 26, 2026 •

Copy link
Copy Markdown

This PR fixes a caching issue with protobuf format in which the WithEnvelope is not considered. This leads to misleading broken format parsing when first using FORMAT Protobuf in which both Protobuf and ProtobufList format are able to use the provided message type, however when the cache is reset, ProtobufList attempts to force the Envelope format which can lead to errors when not available. The Envelope specific format is not truly required - any Envelope will work and pointing to the original format is all thats required for the schema.

The secondary fix, allowing fallback from envelope may be undesirable, if so I can remove.

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

...

Fixes a protobuf cache entry issue and adds fallback to message type if Envelope schema not found

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.5.1.208 (included in 26.5 and later)
  • Backported to: 26.4.5.137

Signed-off-by: Callum C <[email protected]>
@CLAassistant

CLAassistant commented Mar 26, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@nikitamikhaylov

Copy link
Copy Markdown
Member

The test is required.

@callumc34

Copy link
Copy Markdown
Author

@nikitamikhaylov I have added a test for this

@ilejn

ilejn commented Apr 7, 2026

Copy link
Copy Markdown
Contributor

Hello @callumc34 , thank you for your finding and for contribution.
Minor questions and suggestions, if you don't mind.

  1. Are there particular reasons why Envelope should not be mandatory? I mean do you just feel that it is redundant restriction, or your workflow somehow benefits from suggested change? 1a. Is not it better to make FindMessageTypeByName() envelope-aware or check its result to avoid dependency on cache, assuming this is the real issue this PR addresses?
  2. We have to document the proposed change in docs/en/interfaces/formats/Protobuf/ProtobufList.md
  3. I believe that the title of this PR should contain ProtobufList

Comment thread src/Formats/ProtobufSchemas.h Resolved
@callumc34 callumc34 changed the title fix: Fix cache issue Fix shared cache issues between Protobuf and ProtobufList Apr 7, 2026
@callumc34

callumc34 commented Apr 7, 2026 •

Copy link
Copy Markdown
Author

@ilejn thanks for taking a look at this. Happy to make changes.

  1. Are there particular reasons why Envelope should not be mandatory? I mean do you just feel that it is redundant restriction, or your workflow somehow benefits from suggested change?
    I think the main reason it should not be mandatory is that it's not actually seriously used and just imposed some strict naming conventions that can be frustrating when using many Protobufs in a large package. The Envelope is only for schema lookup but the serialiser doesn't actually use it, both the Protobuf and ProtobufList will end up using the same format.

For our workflow, we have several Protobufs we are trying to store, notably position and object, if these are both in the same Protobuf package then we can only choose one of these to be the envelope and this repeats even if we decompose them into their own package then the components of these Protobuf models can't have their own envelopes and so on. What we were doing, before we encountered this bug, was dynamically generating the Protobuf envelops, say both PositionEnvelope and ObjectEnvelope, and using those to send to Clickhouse which makes our code more clear and allows us to reuse these envelopes in other places nicely.

1a. Is not it better to make FindMessageTypeByName() envelope-aware or check its result to avoid dependency on cache, assuming this is the real issue this PR addresses?

The cache key fix is the main reason for this PR, without it, ProtobufList and Protobuf silently interfere with each other. However, theEnvelope fallback is a practical improvement to make the format easier to use given it's not actually required for the parsing and serialisation to work. This also ensures that any existing usages will remain unaffected by this change and we still treat the Envelope as first class.

  1. We have to document the proposed change in docs/en/interfaces/formats/Protobuf/ProtobufList.md
  2. I believe that the title of this PR should contain ProtobufList

Have updated the PR for both of these, would appreciate any feedback on the documentation.

@callumc34
callumc34 requested a review from ilejn April 14, 2026 19:28
@ilejn

ilejn commented Apr 15, 2026 •

Copy link
Copy Markdown
Contributor

Hello @callumc34, it is quite possible that I am missing something, so your inputs are appreciated.

  1. Is it correct that importer.pool()->FindMessageTypeByName(message_name) is truly global? In other words, if we have different message types with the same name in different .proto files, the behavior may be unpredictable?
  2. Is it correct that importers.find(key) is bound to a directory? This means that if a non-envelope message exists in a .proto file, other .proto files with a message of the same name would be ignored?
  3. Is it correct that the new implementation falls back when an Envelope exists but does not contain the requested nested type (and this behavior is not documented)?

@callumc34

Copy link
Copy Markdown
Author

@ilejn thanks for following up.

  1. Is it correct that importer.pool()->FindMessageTypeByName(message_name) is truly global? In other words, if we have different message types with the same name in different .proto files, the behavior may be unpredictable?

It's not global across ClickHouse, the pool is scoped to a single ImporterWithSourceTree. Before this PR there was one per directory. which is what caused the cache bug this PR fixes, with the fix there's one per (directory, with_envelope) pair. Note that filesystem directory and protobuf package are independent concepts, a directory can contain files from any mix of packages. Within a pool, protobuf enforces uniqueness of fully-qualified names, which include the package, so messages in different packages don't conflict. The case where behavior could be surprising is unqualified top-level messages with the same simple name across different .proto files in the same directory — if a.proto is imported first with a top-level Person, a later call for b.proto:Person would return a.proto's Person without re-importing b.proto. This is pre-existing behavior and isn't changed by this PR.

  1. Is it correct that importers.find(key) is bound to a directory? This means that if a non-envelope message exists in a .proto file, other .proto files with a message of the same name would be ignored?

Yes, the importer cache is keyed per (directory, with_envelope) and .proto files within the same directory share a pool. As above, protobuf enforces full-name uniqueness within a pool, so collisions only matter for unqualified simple names shared across files in the same directory. This is also pre-existing behavior and not introduced by this PR.

  1. Is it correct that the new implementation falls back when an Envelope exists but does not contain the requested nested type (and this behavior is not documented)?

Yes, that's correct when with_envelope is set, the lookup tries Envelope. first and falls through to a top-level lookup if that doesn't find a match, regardless of whether Envelope itself is present. The intent is to prefer the Envelope form when WithEnvelope is specified, otherwise use the top-level message. This keeps serialization behavior consistent (the wire format is the same either way) and avoids forcing users to remove an Envelope wrapper in order to reference an unrelated top-level message in the same file. I have updated the documentation to reflect that.

Please let me know if you'd like any of this behaviour changed.

@ilejn

ilejn commented Apr 15, 2026

Copy link
Copy Markdown
Contributor

This is pre-existing behavior and isn't changed by this PR.

Yes, sure, I am just trying to clarify what is going on.

To me a possible collision between a.proto:Person and b.proto:Person is pretty hard to ignore.
Not sure if it is Ok to leave it out of the scope.

@callumc34

Copy link
Copy Markdown
Author

This is pre-existing behavior and isn't changed by this PR.

Yes, sure, I am just trying to clarify what is going on.

To me a possible collision between a.proto:Person and b.proto:Person is pretty hard to ignore. Not sure if it is Ok to leave it out of the scope.

@ilejn I think we could bring this into scope reasonably easily by just removing the pool lookup which isn't file-scoped.

      const auto * descriptor = importer.pool()->FindMessageTypeByName(message_name);
      if (descriptor)
          return descriptor;

The subsequent import.Import code is still cached internally and so there shouldn't be any performance concerns.

Worth noting: this pool lookup was added in 2019 (commit e9721c9) when there was a single global Importer for all schemas, a shared pool across the entire instance. This shortcut was a more meaningful optimization, since the alternative was re-running path resolution and file import logic. The same commit refactored to the current per-directory ImporterWithSourceTree model but kept the pool lookup, which is where the file-collision behavior was unintentionally introduced. Removing it now essentially finishes that refactor.

@nikitamikhaylov nikitamikhaylov added the can be tested Allows running workflows for external contributors label Apr 16, 2026
@clickhouse-gh

clickhouse-gh Bot commented Apr 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [0ce860d]

Summary: ❌
UndefinedBehaviorSanitizer in Lexer.cpp:119:43: issue

job_name test_name status info comment
Integration tests (amd_msan, 1/6) FAIL
test_distributed_frozen_replica/test.py::test_cluster_all_replicas_query[1-test_cluster] FAIL cidb, issue ISSUE CREATED
test_distributed_frozen_replica/test.py::test_cluster_all_replicas_query[3-test_cluster] FAIL cidb, issue ISSUE CREATED
UndefinedBehaviorSanitizer in Lexer.cpp:119:43 FAIL issue ISSUE CREATED
Unit tests (msan, function_prop_fuzzer) FAIL IGNORED

AI Review

Summary

This PR fixes ProtobufSchemas cache keying so Protobuf and ProtobufList do not share incompatible cache entries, removes a stale pool-level shortcut that could return descriptors from the wrong .proto file, and documents/implements the intended Envelope-first then top-level fallback behavior for ProtobufList. I did not find a high-confidence blocker or major issue in the changed code and tests.

ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ✅
Compilation time ✅
No large/binary files ✅
Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Apr 16, 2026
@ilejn

ilejn commented Apr 17, 2026

Copy link
Copy Markdown
Contributor

Hello @callumc34 , removing global pool alone is not enough.
See https://github.com/ClickHouse/ClickHouse/pull/35152/changes/BASE..514d4d21870e37b81c073c81d4ace3071a22e3a6#r825948075 for details.

I think that 233e8aa from branch https://github.com/ilejn/ClickHouse/commits/fix/fallback-from-envelope/ does the trick. Feel free to cherry-pick or just reuse.

To me the behavior we have in master is not perfect and worth fixing, but lets ask @Avogar and @rschu1ze what are their opinions.

@callumc34

Copy link
Copy Markdown
Author

Thanks for looking into that and supporting this PR @ilejn , have cherry-picked that commit, looks right to me.

@ilejn

ilejn commented Apr 17, 2026

Copy link
Copy Markdown
Contributor

Test failures are not related.
We are suffering from https://play.clickhouse.com/play?user=play&run=1#V0lUSAogICAgOTAgQVMgaW50ZXJ2YWxfZGF5cwpTRUxFQ1QKICAgIHRvU3RhcnRPZkRheShjaGVja19zdGFydF90aW1lKSBBUyBkYXksCiAgICBjb3VudCgpIEFTIGZhaWx1cmVzLAogICAgZ3JvdXBVbmlxQXJyYXkocHVsbF9yZXF1ZXN0X251bWJlcikgQVMgcHJzLAogICAgYW55KHJlcG9ydF91cmwpIEFTIHJlcG9ydF91cmwKRlJPTSBjaGVja3MKV0hFUkUgKG5vdygpIC0gdG9JbnRlcnZhbERheShpbnRlcnZhbF9kYXlzKSkgPD0gY2hlY2tfc3RhcnRfdGltZQogICAgQU5EIHRlc3RfbmFtZSA9ICcwNDA2MF90cmFuc2FjdGlvbl9zbmFwc2hvdF92aXNpYmlsaXR5JwogICAgLS0gQU5EIGNoZWNrX25hbWUgPSAnU3RhdGVsZXNzIHRlc3RzIChhbWRfbGx2bV9jb3ZlcmFnZSwgQXN5bmNJbnNlcnQsIHMzIHN0b3JhZ2UsIHBhcmFsbGVsKScKICAgIEFORCB0ZXN0X3N0YXR1cyBJTiAoJ0ZBSUwnLCAnRVJST1InKQogICAgQU5EIChwdWxsX3JlcXVlc3RfbnVtYmVyID0gMCBPUiBiYXNlX3JlZiBJTiAoJ21hc3RlcicpKQogICAgQU5EIHRlc3RfY29udGV4dF9yYXcgTElLRSAnJXJlc3VsdCBkaWZmZXJzIHdpdGggcmVmZXJlbmNlJScKR1JPVVAgQlkgZGF5Ck9SREVSIEJZIGRheSBERVNDCg== and https://play.clickhouse.com/play?user=play&run=1#V0lUSAogICAgOTAgQVMgaW50ZXJ2YWxfZGF5cwpTRUxFQ1QKICAgIHRvU3RhcnRPZkRheShjaGVja19zdGFydF90aW1lKSBBUyBkYXksCiAgICBjb3VudCgpIEFTIGZhaWx1cmVzLAogICAgZ3JvdXBVbmlxQXJyYXkocHVsbF9yZXF1ZXN0X251bWJlcikgQVMgcHJzLAogICAgYW55KHJlcG9ydF91cmwpIEFTIHJlcG9ydF91cmwKRlJPTSBjaGVja3MKV0hFUkUgKG5vdygpIC0gdG9JbnRlcnZhbERheShpbnRlcnZhbF9kYXlzKSkgPD0gY2hlY2tfc3RhcnRfdGltZQogICAgQU5EIHRlc3RfbmFtZSA9ICcwNDA1N190cmFuc2FjdGlvbl92ZXJzaW9uX21ldGFkYXRhX2xpZmVjeWNsZScKICAgIC0tIEFORCBjaGVja19uYW1lID0gJ1N0YXRlbGVzcyB0ZXN0cyAoYW1kX2xsdm1fY292ZXJhZ2UsIEFzeW5jSW5zZXJ0LCBzMyBzdG9yYWdlLCBwYXJhbGxlbCknCiAgICBBTkQgdGVzdF9zdGF0dXMgSU4gKCdGQUlMJywgJ0VSUk9SJykKICAgIEFORCAocHVsbF9yZXF1ZXN0X251bWJlciA9IDAgT1IgYmFzZV9yZWYgSU4gKCdtYXN0ZXInKSkKICAgIEFORCB0ZXN0X2NvbnRleHRfcmF3IExJS0UgJyVyZXN1bHQgZGlmZmVycyB3aXRoIHJlZmVyZW5jZSUnCkdST1VQIEJZIGRheQpPUkRFUiBCWSBkYXkgREVTQwo=

Besides this, we have two performance degradation reports for arm, but protobuf is not involved and presumably it is a glitch. I'll double check though.

@ilejn

ilejn commented Apr 23, 2026

Copy link
Copy Markdown
Contributor

Hello @Avogar ,
could you have a look, please.

@Avogar Avogar self-assigned this Apr 23, 2026

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

Looks good. Just one minor comment

Comment thread src/Formats/ProtobufSchemas.h Outdated
Comment on lines +95 to +102
std::unordered_map<ImporterKey,
std::shared_ptr<ImporterWithSourceTree>,
decltype([](const ImporterKey & key)
{
auto h1 = std::hash<String>{}(key.schema_directory);
auto h2 = std::hash<String>{}(key.schema_path);
return h1 ^ (h2 << 1) ^ (static_cast<uint8_t>(key.with_envelope) << 2);
})> importers;

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.

It's better to extract the hasher into a separate struct to make the code more readable. Also you can use our sipHash implementation with update method here:

 struct ImporterKeyHash
  {
      size_t operator()(const ImporterKey & key) const
      {
          SipHash hash;
          hash.update(key.schema_directory);
          hash.update(key.schema_path);
          hash.update(key.with_envelope);
          return hash.get64();
      }
  };

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.

It is close to the original approach of the author of the PR ;)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Thanks for taking a look, have separated this out as suggested

@clickhouse-gh

clickhouse-gh Bot commented Apr 24, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 83.80% 83.80% +0.00%
Functions 91.10% 91.10% +0.00%
Branches 76.20% 76.20% +0.00%

Changed lines: 88.57% (31/35) | lost baseline coverage: 2 line(s) · Uncovered code

Full report · Diff report

@callumc34

Copy link
Copy Markdown
Author

@ilejn I don't believe any of these GHA failures are related to the changes in this PR. What is the process from here to get this merged?

@Avogar
Avogar added this pull request to the merge queue May 1, 2026
Merged via the queue into ClickHouse:master with commit 8dc1d7f May 1, 2026
160 of 164 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label May 1, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi — this PR may need backporting to 26.3 (LTS), 26.2, 26.1, 25.8 (LTS), but no backport label was found.

Affected code: ProtobufSchemas::getMessageTypeForFormatSchema / ProtobufSchemas::ImporterWithSourceTree::import — core code present in all supported branches.

Why: User-visible bug: switching between Protobuf and ProtobufList in the same session previously corrupted the shared cache, producing misleading errors. ProtobufSchemas::ImporterWithSourceTree and its global cache exist in all supported branches (file predates 25.8 by years per typical ClickHouse history). No backport label currently set in the PR labels (only pr-bugfix, can be tested).

If this should be backported, consider adding pr-must-backport or a version-specific label (e.g. v26.3-must-backport). Ignore this if backporting is not applicable.

@ilejn

ilejn commented May 1, 2026 •

Copy link
Copy Markdown
Contributor

Hello, congratulations ! ;)
@Avogar , thanks a lot for caring and for merging.

@callumc34, what do you think about backporting?
Is it possible to have a workflow that would be broken by the change?

@ilejn

ilejn commented May 1, 2026

Copy link
Copy Markdown
Contributor

@ilejn I don't believe any of these GHA failures are related to the changes in this PR. What is the process from here to get this merged?

From Alexey M' standpoint the process is to fix all issues regardless if they are related or not.
In reality it varies.

@callumc34

Copy link
Copy Markdown
Author

@ilejn Thanks!

@callumc34, what do you think about backporting?
Is it possible to have a workflow that would be broken by the change?

I think this should be backported. For any user whose workflow was working, schemas still resolve to the same descriptor so nothing changes. The only way a workflow could break is if it was depending on the broken cache state, and since that resets on every restart I don't think such a workflow would survive in practice, nor should such a workflow be incentivised as this would likely lead to a bug report, but I would be interested for your thoughts on that. The Envelope fallback only kicks in for schemas that previously errored, so no working flow is at risk there either.

strtgbb pushed a commit to Altinity/ClickHouse that referenced this pull request Jun 30, 2026
…-envelope

Fix shared cache issues between Protobuf and ProtobufList
@fm4v fm4v self-assigned this Jul 16, 2026
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Jul 16, 2026
@robot-clickhouse robot-clickhouse added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Jul 16, 2026
fm4v added a commit that referenced this pull request Jul 17, 2026
Backport #100849 to 26.4: Fix shared cache issues between Protobuf and ProtobufList
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 24, 2026
bytehalo-infra added a commit to sentioxyz/ClickHouse that referenced this pull request Sep 25, 2026
…ickHouse#110754, not to 26.3)

PROTO: ProtobufSchemas cached one importer per schema directory and looked a message up by name in the importer's
whole descriptor pool before importing the requested file. Two schema files in the same directory that define a
message with the same name (or the same file used as Protobuf and as ProtobufList with an Envelope) then shared the
first descriptor: a query could parse its input with another file's message definition, i.e. wrong columns, errors or
wrongly parsed data. The fix keys the importer by (directory, schema file, envelope) and looks the message up in the
imported file only.
Found by the CAND5 gtest run: three unit tests of the ClickHouse#106905 backport (gtest_protobuf_sync_after_error.cpp) give each
test its own inline schema with a message named Row and failed with "Not found matches between the names of the
columns (d) and the fields (number) of the message 'Row'" - the previous test's schema. The stateless test is the
upstream 04061_protobuf_cache_with_envelope. Upstream patch unchanged (applies cleanly), with its test and schemas.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
bytehalo-infra added a commit to sentioxyz/ClickHouse that referenced this pull request Sep 25, 2026
…49, test 04061)

04061_protobuf_cache_with_envelope fails on the production build a394e92 and passes on official 26.8.8.8
(isolated servers, evidence/fix_ci_20260925/upstream_repro/pr100849/). Registry 148 entries, 3 open; 230 selected tests.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
mkmkme pushed a commit to Altinity/ClickHouse that referenced this pull request Oct 17, 2026
…0849

Backport ClickHouse#100849 to 26.4: Fix shared cache issues between Protobuf and ProtobufList
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 pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default 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.4-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

10 participants