Skip to content

Adding storage pulsar - #64184

Closed
SteveBalayanAKAMedian wants to merge 173 commits into
ClickHouse:masterfrom
SteveBalayanAKAMedian:Adding-storage-pulsar
Closed

SteveBalayanAKAMedian wants to merge 173 commits into
ClickHouse:masterfrom
SteveBalayanAKAMedian:Adding-storage-pulsar

Conversation

@SteveBalayanAKAMedian

@SteveBalayanAKAMedian SteveBalayanAKAMedian commented May 21, 2024 •

Copy link
Copy Markdown

Changelog category:

  • Experimental Feature

Changelog entry:

Added the experimental Pulsar table engine for reading from and writing to Apache Pulsar topics. Creating tables with the engine requires enabling the enable_pulsar setting.

Closes: #4226


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

@CLAassistant

CLAassistant commented May 21, 2024 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@nikitamikhaylov nikitamikhaylov added the can be tested Allows running workflows for external contributors label May 21, 2024
@robot-ch-test-poll3 robot-ch-test-poll3 added pr-feature Pull request with new product feature submodule changed At least one submodule changed in this PR. labels May 21, 2024
@alexey-milovidov

Copy link
Copy Markdown
Member

Please sign CLA.

@clickhouse-gh

clickhouse-gh Bot commented Jul 23, 2024

Copy link
Copy Markdown
Contributor

Dear @nikitamikhaylov, this PR hasn't been updated for a while. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

…rly with `lazy_load_tables`

`isPushSourceEngine` lists the engines whose ingestion only starts in
`startup`, which a lazily loaded stand-in never calls. `Pulsar` was missing,
so after a server restart or `DETACH DATABASE` / `ATTACH DATABASE` a `Pulsar`
source of a materialized view in a database with `lazy_load_tables = 1`
silently stopped ingesting.

Add a broker test that reloads such a database and publishes externally,
without touching the source table. It fails without the fix.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Storages/Pulsar/PulsarSource.cpp Resolved
Comment thread contrib/pulsar-client-cpp Resolved
alexey-milovidov and others added 2 commits November 15, 2026 22:40
…ze-mismatched zlib output

`CompressionCodecZLib::decode` accepted a decoded payload of any size and a finished
stream without its checksum trailer. Now the decoded size must match the declared size,
and the stream must either end properly or (for the sync-flushed output of the Java
client) be fully consumed at a block boundary. Regression tests are in the fork.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A table with a physical column named like an ephemeral virtual column, e.g.
`_topic String` or `_timestamp DateTime`, passes `CREATE`, but `PulsarSource`
appended the virtual column to the block next to the physical one, so
`Block::insert` threw `AMBIGUOUS_COLUMN_NAME` and nothing could be read.
Use `insertUnique`, so the physical column takes precedence.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Storages/Pulsar/StoragePulsar.cpp Resolved
alexey-milovidov and others added 3 commits November 19, 2026 10:36
# Conflicts:
#	src/configure_config.cmake
Build fixes after merging master:
- `StreamingFormatExecutor` now takes a format creator instead of a format.
- `MessageQueueSink` now takes the full sample block as the input header and
  the non-materialized one as the format header (as for `NATS` and `RabbitMQ`).
- `PulsarProducer.cpp` includes `Common/Exception.h` explicitly.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=64184&sha=add310501e2e609d5dbbb75465f7896ac81ec9f2&name_0=PR&name_1=Build%20%28arm_tidy%2C%203%2F4%29
PR: ClickHouse#64184

Address review: with `pulsar_max_wait_ms = 0`, `popConsumer` waited for a
free consumer without a bound and could not be cancelled. With
`SELECT ... FROM t UNION ALL SELECT ... FROM t` over a one-consumer table the
second source waited forever, because the first one keeps the consumer until
the pipeline is destroyed, and `KILL QUERY` did not wake the wait. Now a zero
timeout does not wait at all, and a positive timeout is waited in short slices
that check the query and `SYSTEM STOP STREAMING` cancellation.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…e decompression runs out of memory

`Z_MEM_ERROR` from zlib and `ZSTD_error_memory_allocation` from zstd were
treated as corrupted input, so the message was acknowledged and lost. The
codecs now throw `std::bad_alloc`, which makes the consumer close the
connection without acknowledging, so the message is redelivered.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 2 commits November 20, 2026 14:17
# Conflicts:
#	tests/queries/0_stateless/01271_show_privileges.reference
The `Pulsar` contrib selected the native-build `protoc` when cross-compiling
or when `USE_MUSL`, but the `native/` sub-build is only produced when host
and target differ. With musl now the default, the native `arm_tidy` build
had a dangling ninja dependency:
`native/contrib/google-protobuf-cmake/protoc`, needed by
`PulsarApi.pb.cc`, missing and no known rule to make it.
Use the same condition as `protobuf_generate.cmake` (changed on master in
1411c0c): a statically linked musl `protoc` runs on the host.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=64184&sha=latest&name_0=PR&name_1=Build%20(arm_tidy%2C%204%2F4)
PR: ClickHouse#64184

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

Let's send these PRs to our fork as well and merge them.
Also, evaluate the general sanity of pulsar-client-cpp.

If it is akin to the Apache ORC library or rdkafka in terms of quality, we should not use it.

@groeneai

Copy link
Copy Markdown
Collaborator

Acknowledged. I'm checking which of the six upstream PRs still differ from the clickhouse branch (you opened ClickHouse/pulsar-client-cpp#2, ClickHouse/pulsar-client-cpp#3 and ClickHouse/pulsar-client-cpp#4 for three of them) and evaluating the quality of pulsar-client-cpp; I'll follow up here with the result shortly.

@groeneai

Copy link
Copy Markdown
Collaborator

Fork. apache/pulsar-client-cpp#626, apache/pulsar-client-cpp#627 and apache/pulsar-client-cpp#629 are already on clickhouse (they were cut from its commits). What apache/pulsar-client-cpp#628, apache/pulsar-client-cpp#630 and apache/pulsar-client-cpp#631 add on top is exactly ClickHouse/pulsar-client-cpp#2, ClickHouse/pulsar-client-cpp#3 and ClickHouse/pulsar-client-cpp#4, all mergeable, so nothing else is left to send. I have only pull access to the fork and can't merge them. This PR still pins ClickHouse/pulsar-client-cpp@7ec79df, which sits on the 2024 upstream base (108 commits behind), not the merged tip ClickHouse/pulsar-client-cpp@3e73e60.

Quality. Measured against the points of #127470, it is in the same class as rdkafka:

  • Buffer overflows from the network. It trusts the sizes it receives (frame and command lengths, uncompressed_size, chunk total size and count, batch entry lengths). The only bounds checks are asserts in SharedBuffer, which release builds compile out. Under ASan on upstream main (apache/pulsar-client-cpp@f71d7e9), one message whose metadata understates uncompressed_size makes the Snappy codec write past its heap buffer. One that overstates it makes the LZ4 codec read past its input: it calls LZ4_decompress_fast from a vendored lz4 1.7.1, and so does the fork; only this PR's patched/CompressionCodecLZ4.cc uses LZ4_decompress_safe. Any producer on the topic can send such a message. Two more of this kind are in neither upstream nor the fork. KeyValueImpl trusts its length prefixes (ASan: a 5-byte payload reads 4 KiB past the buffer), and MessageCrypto::decryptData copies the producer's encryption_param into a 12-byte IV. This engine reaches neither, since it uses no KEY_VALUE schema and no CryptoKeyReader.
  • Its own threads, which take the process down. Each Client runs detached event-loop threads (3 per table here) that catch only system_error. A 4-byte frame header can make it allocate up to 4 GiB, as can a message declaring a 4 GiB uncompressed_size. If such an allocation fails, the process ends in std::terminate; the pinned commit's loop catches nothing at all. close() waits up to 10 s per connection, one connection after another, then continues into the state its own comment in lib/ConnectionPool.cc says will crash.
  • Races and silent message loss. TSan found two races that are still on upstream main (the close counter and the random generators: [fix][client] Fix data race on the close counter of ClientImpl apache/pulsar-client-cpp#626, [fix][client] Fix data races on the random generators of generateRandomName and ConnectionPool apache/pulsar-client-cpp#627). Valid messages are acknowledged as corrupted when zlib or zstd fail to allocate, and when any broker lowers the process-wide maxMessageSize_. Truncated zlib output is delivered as a valid message. Abandoned chunked messages are never redelivered, because the default unacked-message tracker is a no-op.
  • Upstream. No commit on main since 2026-09-01, and the last release was v4.2.0 on 2026-06-14. 19 of the 43 PRs opened since May 21 are still open. CI runs clang-tidy and CodeQL, but no ASan, TSan, UBSan or fuzzing. Most tests need a live apachepulsar/pulsar:latest broker and are retried 3 times on failure. The six PRs above got no review in 8 days, and their CI has not been approved to run.

12 of the 18 fork-only commits fix defects like these (the rdkafka fork: 9 of 20). Two of the 12 are backports of upstream fixes (apache/pulsar-client-cpp#438, apache/pulsar-client-cpp#441). The other ten fix defects that are still on upstream main; the only exception is one end-iterator dereference, which apache/pulsar-client-cpp#587 fixed.

My recommendation is not to use it. The engine calls only subscribe, batchReceive, acknowledge, negativeAcknowledge, createProducer and send. If Pulsar support is wanted, a native client for that subset of the binary protocol (protobuf commands over TCP), built on the ClickHouse codecs, TLS and thread pools, would take the same approach as #127470.

Either way, the size-validation fixes still need a private report to [email protected] (upstream SECURITY.md), which I can't send.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Both requests from #64184 (comment).

1. Fork pull requests

apache/pulsar-client-cpp#626, #627 and #629 are already on our clickhouse branch (as c968f41, be55562, c589ca4), so they only needed the formatting and the two tests that the upstream pull requests added on top of what we already carry. I opened these against ClickHouse/pulsar-client-cpp, base clickhouse:

  • ClickHouse/pulsar-client-cpp#2 — merges apache/pulsar-client-cpp#628 (the connection-pointer-logging change is already c162ff9; this only adopts the upstream line wrapping in lib/ConnectionPool.cc, so our fork matches upstream once it lands).
  • ClickHouse/pulsar-client-cpp#3 — adds the ClientTest.testConnectionValidator test from apache/pulsar-client-cpp#630.
  • ClickHouse/pulsar-client-cpp#4 — adds the MessageTest.testHasEventTimestamp test from apache/pulsar-client-cpp#631.

All three are MERGEABLE/CLEAN; MessageTest.testHasEventTimestamp and the whole MessageTest suite pass locally, and ClientTest.cc compiles. I could not merge them myself (the agent runner blocks gh pr merge, as with our librdkafka fork), so the merge is yours.

The six upstream pull requests apache/pulsar-client-cpp#626–#631 are still open, 8 days on, with no review, no comment and their CI left in action_required (never approved). That is relevant to the sanity question below.

2. Sanity of pulsar-client-cpp

Short answer: the core is better written than librdkafka, and the fork on our clickhouse branch has genuinely closed the memory-safety holes a producer could trigger. But there are two crashes left that still hit the fork, and upstream is effectively unmaintained, so adopting it means owning the fork like we own librdkafka. I would keep it experimental and binary-protocol-only, and fix the two issues below in our fork before it is promoted.

How I tested

I built an end-to-end harness: a real pulsar::Client subscribes to an in-process fake broker over loopback, the broker completes the handshake and then writes attacker-shaped frames (fuzzed metadata, batches, compression, chunking, encryption fields, and malformed commands), and the client consumes through the public API under AddressSanitizer with libFuzzer. Every delivered message is fully read, so ASan catches any message not backed by a real buffer. Nothing touches private members, so every crash is reachable by a real peer. Harness and reproducers are in tmp/pulsar-fuzz/.

Result

  • Upstream main (f71d7e9), ~10 min: ~770 distinct crashes. Almost all are producer-triggerable memory corruption, because SharedBuffer's bounds checks are assert-only and vanish under NDEBUG: attacker-sized allocation in ClientConnection::handleRead (the 4-byte frame size), out-of-bounds reads in SharedBuffer::readUnsignedInt / processIncomingBuffer, heap overflow in the LZ4 path (LZ4_decompress_fast), crc32c_sw, the batch de-serializer, Snappy, and a 4 GiB allocation from uncompressed_size.
  • Fork clickhouse (3e73e60), ~15 min: zero producer-triggerable memory unsafety. The 18 fork commits really do validate the frame, batch, chunk, Snappy/ZLib/Zstd and uncompressed-size paths. The LZ4 hole is closed too, because our CMake compiles the patched CompressionCodecLZ4.cc that uses LZ4_decompress_safe (the submodule's own file is still the unsafe one — that matters only if someone builds the library outside ClickHouse).

Two crashes that remain in the fork (both confirmed live, both also present upstream)

  1. Use-after-free on connection close. ClientConnection::close iterates pendingLookupRequests and calls PendingRequest::fail; setFailed synchronously runs the RetryableOperation continuation, which frees the shared DeadlineTimerPtr, and then fail calls cancelTimer(timer_) on the freed timer. Reproduced on the fork (lib/ClientConnection.cc:1439) and on upstream (lib/ClientConnection.cc:1377); PendingRequest.h, RetryableOperation.h and BinaryProtoLookupService.cc are byte-identical in the fork. This needs no malicious peer — a disconnect while a lookup/partition-metadata request is in flight is enough. Likely fix: in PendingRequest::fail/complete, cancel the timer before completing the promise, or move the timer into a local first.
  2. std::terminate on any non-asio exception on the I/O thread. ExecutorService::start wraps io_context::run() in catch (const ASIO_SYSTEM_ERROR&) only, so anything else ends the process. I reproduced it with a broker TOPIC_MIGRATED carrying a malformed URL: ServiceURI::parse throws std::invalid_argument on the I/O thread and the process aborts. The same shape covers std::bad_alloc, which in ClickHouse can be thrown at any allocation under a memory limit. For embedding in the server this is the most important one; the fix is an exception barrier (catch (...)) around io_context::run() that closes the connection instead of terminating.

(The MessageCrypto IV overflow, KeyValueImpl INLINE decode and HTTP-lookup null-dereference that also exist are not reachable from StoragePulsar today — binary protocol only, no CryptoKeyReader, no KEY_VALUE schema, HTTP service URLs rejected — but they are still in the compiled files.)

Compared to Apache ORC / librdkafka

  • Design quality: above librdkafka. One io_context per thread (no strands needed), weak back-references, atomic state machines, and timeouts on every network wait. The I/O path is coherent, not the layered mess we fought in librdkafka.
  • Bug backlog / history: better than librdkafka (72 open issues vs 339; far fewer open crash/race/leak issues), comparable to ORC C++.
  • Quality infrastructure: worse than both. No sanitizer, no fuzzing, no Valgrind in CI (ORC gates every PR on ASan+UBSan; librdkafka has partial ASan/TSan/Valgrind plus one OSS-Fuzz target). Tests need a live broker. This is why the bugs above survived.
  • Upstream health — the librdkafka-like part: no commit since 2026-09-01, no release since 2026-06-14, review/merge concentrated in one person, and our six fixes sit unreviewed with CI not even approved. If we adopt this, we maintain the fork ourselves indefinitely.

Recommendation

Not "akin to ORC/librdkafka" on code quality — the code is cleaner and the fork has already removed the producer-facing memory-safety bugs, which is the main thing that made those libraries painful. But it is librdkafka-like operationally: a dead upstream that will not take our patches. I would keep enable_pulsar experimental and binary-protocol-only, and before it is promoted beyond experimental, land two fork fixes — the io_context::run() exception barrier and the PendingRequest/cancelTimer use-after-free. With those two in, I think it is safe to use; without them, it can abort or corrupt the server on an ordinary disconnect or a hostile broker. I can prepare both fork fixes (with the reproducers above) if you want them.

🤖 Generated with Claude Code

@alexey-milovidov

Copy link
Copy Markdown
Member

My assessment: pulsar-cpp is trash and has no place in ClickHouse.

Let's rewrite the library entirely.

@alexey-milovidov

Copy link
Copy Markdown
Member

CI runs clang-tidy and CodeQL, but no ASan, TSan, UBSan or fuzzing.

In what century do they live? Should we even consider integration with Pulsar if they allow such low-quality libraries?

@alexey-milovidov

Copy link
Copy Markdown
Member

Most tests need a live apachepulsar/pulsar:latest broker and are retried 3 times on failure.

This is 🤣. Instead of increasing the chances of finding bugs, they hide them.

@alexey-milovidov

Copy link
Copy Markdown
Member

Either way, the size-validation fixes still need a private report to [email protected] (upstream SECURITY.md), which I can't send.

It is already out of the bag, thanks to the trivial automatic analysis. So we can draft it here and then send an email.

@groeneai

Copy link
Copy Markdown
Collaborator

Should we even consider integration with Pulsar if they allow such low-quality libraries?

I think yes, but only with our own client. The C++ client is a separate repository, split out of apache/pulsar in 2022: 54 commits on main in the last 12 months, 19 of them by one person. The broker is a different codebase (apache/pulsar, Java) with 559 commits on master in the last month. A native client depends only on the wire protocol, which is documented (https://pulsar.apache.org/docs/next/developing-binary-protocol/), with all commands defined in one PulsarApi.proto. There is no Kafka-protocol shortcut either: StreamNative's Kafka protocol handler for Pulsar (KoP) is archived. Demand is real but modest: #4226 has been open since 2019 with 35 upvotes, plus two duplicates (#9615, #18555).

I'll write the client: a ClickHouse-native implementation of only what StoragePulsar uses (connect and lookup, partitioned-topic metadata, subscribe with flow permits, batched, chunked and compressed messages, acknowledge and negative acknowledge, producer with send receipts, TLS and token auth, reconnect), on our codecs, sockets and thread pools, with every size from the network validated and a libFuzzer target over the frame parser from the start. I'll open it as a separate PR against master, so this PR then only switches its engine to it and drops contrib/pulsar-client-cpp.

I'll post the draft of the security report here next.

@groeneai

Copy link
Copy Markdown
Collaborator

Draft for [email protected], with a copy to [email protected] (upstream SECURITY.md). I checked every item in the code of main and v4.2.0. It leaves out the HTTP lookup null dereference and the use-after-free on disconnect from #64184 (comment), which I have not verified.


Subject: Heap buffer overflows and process aborts in the Pulsar C++ client, reachable by any producer or broker

Affected: apache/pulsar-client-cpp v4.2.0 (latest release) and main at f71d7e99019d (2026-09-01). Items 1-5 and 8 are already in v3.0.0. Line numbers refer to main.

Summary. The client trusts the lengths and sizes it receives from the network. SharedBuffer (lib/SharedBuffer.h) checks bounds only with assert, which the default RelWithDebInfo build compiles out. Any client allowed to produce to a topic can therefore corrupt the heap of, or crash, every C++ consumer of that topic (items 1-7), and a broker, or anyone on the network path without TLS, can do the same with frame fields (items 8-9). ClickHouse found these while integrating the client, and reproduced items 1, 2 and 6 with AddressSanitizer.

Controlled by a producer (message metadata and payload, which the broker forwards unchanged):

  1. Snappy, heap buffer overflow (write). CompressionCodecSnappy::decode (lib/CompressionCodecSnappy.cc:40-42) allocates uncompressed_size bytes and decompresses into them through snappy::UncheckedByteArraySink. A stream that inflates to more writes past the buffer. ASan, 4096-byte stream with uncompressed_size = 16: heap-buffer-overflow WRITE of size 32 in snappy::MemCopy64, called from CompressionCodecSnappy::decode.
  2. LZ4, heap buffer over-read. CompressionCodecLZ4::decode (lib/CompressionCodecLZ4.cc:44) calls LZ4_decompress_fast from the vendored lz4 1.7.1, which is not safe for untrusted input. ASan, a valid 16-byte block with uncompressed_size = 4096: heap-buffer-overflow READ in LZ4_decompress_generic, called from LZ4_decompress_fast and CompressionCodecLZ4::decode.
  3. Unbounded allocations. uncompressed_size (ConsumerImpl::uncompressMessageIfNeeded, lib/ConsumerImpl.cc:1062-1078, which compares only the compressed size with maxMessageSize) and total_chunk_msg_size and num_chunks_from_msg (ChunkedMessageCtx, lib/ConsumerImpl.h:292-294) are used as allocation sizes as received, up to 4 GiB per message.
  4. Chunked messages, heap buffer overflow (write). ChunkedMessageCtx::appendChunk (lib/ConsumerImpl.h:306-308) copies every chunk into the total_chunk_msg_size buffer with SharedBuffer::write, bounded only by an assert. Chunks that add up to more than the declared total write past the buffer.
  5. Batches, out-of-bounds reads. Commands::deSerializeSingleMessageInBatch (lib/Commands.cc:977-985) takes each entry's metadata size and payload_size, and ConsumerImpl::receiveIndividualMessagesFromBatch (lib/ConsumerImpl.cc:938-949) loops num_messages_in_batch times, without checking either against the remaining payload. The resulting messages point past the buffer.
  6. KEY_VALUE schema with INLINE encoding, out-of-bounds read. KeyValueImpl::KeyValueImpl (lib/KeyValueImpl.cc:29-40) trusts the key and value length prefixes. ASan, a 5-byte payload declaring a 4096-byte key: heap-buffer-overflow READ of size 4096.
  7. End-to-end encryption, heap buffer overflow (write). MessageCrypto::decryptData (lib/MessageCrypto.cc:457) copies encryption_param, whatever its length, into the 12-byte iv_ before the GCM tag is checked. It is reachable by any producer that holds the consumer's public key, which on an encrypted topic is every producer.

Controlled by the broker, or by the network without TLS:

  1. Frames (lib/ClientConnection.cc:692-772). The 4-byte frame size is used as an allocation size, up to 4 GiB. The command, broker entry metadata and metadata sizes are not checked against the frame size, so ParseFromArray, the CRC32C in verifyChecksum and the payload copy read past the received data, and frameSize - (cmdSize + 4) can underflow.
  2. Process abort. ExecutorService::start (lib/ExecutorService.cc:37-46) runs each event loop in a detached thread that catches only asio's system_error, so any other exception from a handler ends the process in std::terminate. Examples are std::bad_alloc when an allocation from items 3 or 8 fails, and std::invalid_argument from ServiceURI for a TOPIC_MIGRATED command with a malformed URL.

Fixes. Items 1 and 3-5 and 8 are fixed by five patches against main: https://github.com/groeneai/pulsar-client-cpp/commits/clickhouse-rebased-on-upstream-main (f58552c, 0602271, 49ce297, 3e584d9, dfe267e). These are the same changes as ffc1d92, d186c63, 62603d6, c475e54 and 9555eee in https://github.com/ClickHouse/pulsar-client-cpp. For item 2, ClickHouse uses LZ4_decompress_safe and requires the result to equal uncompressed_size: https://github.com/SteveBalayanAKAMedian/ClickHouse/blob/bfd688c0db9b/contrib/pulsar-client-cpp-cmake/patched/CompressionCodecLZ4.cc. Items 6, 7 and 9 are not fixed anywhere yet.

Disclosure. These issues are already public in #64184 and in the fix commits above. They are easy to find independently: fuzzing the frame parser finds most of them within minutes.

Reproducers for items 1, 2 and 6 (compile with the codec or KeyValueImpl sources and -fsanitize=address -DNDEBUG)
// Items 1 and 2: uncompressed_size from MessageMetadata disagrees with the data.
std::string raw(4096, 'x');
std::string comp;
snappy::Compress(raw.data(), raw.size(), &comp);                   // inflates to 4096 bytes
SharedBuffer enc = SharedBuffer::copy(comp.data(), comp.size()), out;
CompressionCodecSnappy().decode(enc, /*uncompressed_size*/ 16, out);   // write overflow

std::string lz(LZ4_compressBound(16), '\0');
int n = LZ4_compress_default(raw.data(), &lz[0], 16, lz.size());   // valid 16-byte block
SharedBuffer enc2 = SharedBuffer::copy(lz.data(), n), out2;
CompressionCodecLZ4().decode(enc2, /*uncompressed_size*/ 4096, out2);  // read overflow

// Item 6: INLINE KeyValue payload declaring a 4096-byte key and carrying 1 byte.
std::string payload("\x00\x00\x10\x00" "k", 5);
char * heap = new char[payload.size()];
std::copy(payload.begin(), payload.end(), heap);
KeyValueImpl kv(heap, payload.size(), KeyValueEncodingType::INLINE);  // read overflow

@alexey-milovidov

Copy link
Copy Markdown
Member

Continued in #133430

@groeneai

Copy link
Copy Markdown
Collaborator

The client is in #133490: only the part of the binary protocol the engine uses, with no threads, every size from the network checked, memory-tracked buffers and a libFuzzer target over the frame parser. Switching this PR's engine to it took 10 files locally (+88 -264), and 49 of its 50 integration tests pass with it; the 50th fails in the engine before any client call.

The engine continues in #133430, whose head still uses pulsar::Client and whose description leaves out TLS and partitioned topics; #133490 supports both. If you prefer the client planned in #133430, I will close mine.

mosya415 pushed a commit to mosya415/ClickHouse that referenced this pull request Nov 22, 2026
…lsar client

`src/Storages/Pulsar/Client/Proto/PulsarApi.proto` is a verbatim copy of
`proto/PulsarApi.proto` of apache/pulsar-client-cpp at f71d7e99019d (Apache-2.0,
the ASF header kept), except one line: `package pulsar.proto;` is
`package DB.PulsarProto;`. The package does not affect the wire format, and it
avoids duplicate `pulsar::proto` symbols while the `Pulsar` engine of ClickHouse#64184
still links `contrib/pulsar-client-cpp`.

`MetadataViews.proto` declares views of `MessageMetadata` and
`SingleMessageMetadata` with only the singular fields the client reads (same
field numbers and wire types): these messages are written by producers, and
parsing their repeated fields into the full classes would allocate one object
per element.

`USE_PULSAR` and `CANNOT_CONNECT_PULSAR` (788) are byte-identical to the lines
ClickHouse#64184 adds, so that the engine can switch to the native client without
conflicts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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 ci-relocation-headroom-ok Accept an expected decrease of the relocation headroom in the build check comp-message-queues Message queue integrations (Kafka, RabbitMQ, NATS table engines for stream ingestion/egress). external Author is not a member of the ClickHouse organization manual approve Manual approve required to run CI pr-experimental Experimental Feature submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add support for Apache Pulsar as a table engine

9 participants