Repository navigation
Add a native Pulsar client for the Pulsar table engine - #133490
Conversation
…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]>
Pure functions without I/O: frames, the tail of `MESSAGE` (broker entry metadata, checksum, metadata), decompression with the safe APIs of the codecs (the result must have exactly the declared size), validation of batches in one pass without allocating per entry and a cursor that materializes one message at a time, and the assembly of chunked messages with the policy of the `ClickHouse/pulsar-client-cpp` fork (lib/ConsumerImpl.cc at 3e73e60): chunks are assembled raw and decompressed after, because the producer compresses and then slices. Every size from the network is checked against the bytes present and against `Limits` before it is used, and nothing is reserved from a declared count. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A connection is non-blocking for its whole life (connect, TLS handshake, `CONNECT`, frames in and out), so a call never waits longer than its deadline, and a step that does not complete in one call continues in the next one, with a time limit across calls. The client checks the host name in the certificate itself, because Poco does not under `VERIFY_NONE`, without extended verification, and for loopback hosts. The connection validator is called before every connection, also to the brokers from lookup responses. There are no threads. `Interrupter` shuts down the sockets to wake up a call in progress from another thread, which is the only cross-thread operation. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A `Shared` subscription to all partitions of some topics, with one sub-consumer per partition (up to 65536 in total), permits like the C++ client (1000 per partition, 50000 in total), acknowledgements grouped by sub-consumer (a batch is acknowledged when all its messages are), negative acknowledgements, a partition refresh every 60 seconds, and subscribing again inside the following calls after a lost connection or `CLOSE_CONSUMER`. The broker sends an entry only while it has permits left, but a batch may take more permits than were left, so a protocol violation is an entry beyond the granted permits, not a message. `negativeAcknowledge` and `close` never throw, and after any other call threw, all later calls throw, so the engine recreates the consumer. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The producer sends one message at a time and waits for its receipt within the send timeout. If the connection is lost or the broker closes the producer, it is created again with the producer name assigned by the broker the first time, and the message is sent again with the same sequence id, so that the broker can deduplicate it. `interrupt` from another thread ends a `send` in progress. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The fake broker runs on loopback, answers the requests and records them; the tests synchronize with it by events, and the only time bounds are hang guards. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The input is a stream of frames with their sizes, decoded as a consumer does: frames, the tail of `MESSAGE`, chunk assembly, decompression and batches. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The Java client compresses with a sync flush and does not finish the stream, so its zlib output has no final block and no checksum, and requiring `Z_STREAM_END` discarded every such message as corrupted. Accept a stream that ends at a block boundary outside of the final block with all input consumed and exactly the declared size, as the C++ client does (`ClickHouse/pulsar-client-cpp` 023ace8). Found by consuming messages of `pulsar-perf -z ZLIB`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
`TCP` instead of `Tcp`, and an `Ok` in the catch blocks that ignore errors. A socket that cannot report its buffered TLS data does not make `poll` spin: the next read reports the error. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Split ACK and REDELIVER_UNACKNOWLEDGED_MESSAGES into commands of at most `max_message_size / 24` message ids. The broker closes the connection on a frame bigger than `maxMessageSize + 10 KiB`, and one `acknowledge` of a default engine block of non-batched messages (`max_insert_block_size` ids) could exceed 5 MiB: the call returned, the connection was closed, the acks were lost and the messages were redelivered and inserted again. - Send the acknowledgements held for a partition that subscribes again before its first FLOW, so that the broker applies them before it redelivers. - A response to a request this session issued but no longer awaits (a broker CLOSE_CONSUMER or CLOSE_PRODUCER can precede it, or the request expired) is ignored, as in the C++ client; a response to an id never issued is still a protocol violation. Expired in-flight requests are erased. - An interruption (`Client::close`, `Producer::interrupt`) takes precedence over any other failure: the call in progress and all later calls throw ABORTED, as the header promises. - Compare the checksum of a checksummed entry before reading its metadata size, so that a corrupted size is a checksum mismatch (a discard, as in the C++ client), not a connection error. - Keep the SipHash128 of the uuids of dropped chunked messages instead of the uuids, which are written by producers and can be as big as a frame. - Register a socket in both interrupters or in neither. - Compute the next sequence id without a signed overflow. - Add the Apache-2.0 modification notice and the NOTICE attribution of Apache Pulsar to the vendored `PulsarApi.proto`. - Tests: a large acknowledgement is split, acks precede the permits of a new subscription, late and unknown responses, sticky ABORTED for the consumer and the producer, a corrupted metadata size under a checksum, a 1 MiB uuid, a compressed chunked message through the consumer; the fake broker reads and writes its configuration under its mutex. Co-Authored-By: Claude Opus 5.5 <[email protected]>
- One `Connection::process` reads at most 1 MiB, and a PING is answered with a PONG only when nothing else is queued (the broker takes any bytes as a response). A broker that kept the socket readable, for example with a PING flood, kept a call inside the read loop past its deadline, and every PING queued one more PONG until the loop returned. - Check the size of the message with its metadata against the maximum message size of the broker before every send, as `ProducerImpl::sendAsyncWithStatsUpdate` of the C++ client does. A large ordering key made the frame bigger than the broker's limit: the connection was closed and the message sent again until `send_timeout`. - Compute the publish-time expiry of a chunk without an overflow, so that a publish time near the maximum is not expired. - Write at most 64 bytes of a chunk uuid to the log. - Tests: a PING flood, the producer size check with a large ordering key, an acknowledgement split with 10-byte ledger and entry ids against the broker's limit on a whole frame, and a publish time near the maximum. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The permit of a chunk was returned by its own `chunk_id` and `num_chunks_from_msg`, while the assembler completes a message by the number of chunks of its first chunk. A last chunk that declared more chunks than the first one completed the message and was also counted as a chunk to refund, so the broker got 3 permits for 2 entries and the prefetch grew with every such message. Now a chunk returns its permit unless it completes a message, whose permit is returned when it is taken from the queue. Also say in `Consumer::acknowledge` that the acknowledgements of a connection lost before the socket accepted them are not sent (the broker redelivers those messages), and that one `Connection::process` reads about 1 MiB. Test: a 2-chunk message whose last chunk declares 3 chunks gets 2 permits. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The assembler keeps the uuid of each pending chunked message next to its memory-tracked buffer, but in a plain `String`. A producer writes the uuid with no length bound, so it can be as big as a frame, and up to 10 such messages are kept per sub-consumer for up to a minute. Without jemalloc plain allocations are not charged to the memory tracker, so those bytes from the network were not accounted. The uuid is now a `StringWithMemoryTracking`, and the helpers that compare, hash and log it take a `std::string_view`. No behaviour change. Test: two pending chunked messages with 1 MiB uuids that differ only in the last byte are assembled separately. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The producer of a partitioned topic writes all messages to one partition chosen at random when it is created. The comment called that the default routing of the C++ client, but the default there is round robin; one random partition is its non-default `UseSinglePartition`. Round robin would need a producer per partition, so the behaviour stays and the comment now says what the code does. A new test pins the partitioned-producer path. The partition key and ordering key of a queued non-batched message are network bytes the consumer keeps until `takeMessages`, so they are now kept in `StringWithMemoryTracking`, like the payload. No behaviour change; a test reads the partition key of a non-batched message. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Remove two comments that restate the code: the validator contract (documented in Client.h) and the lookup redirect branch label. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 20 findings, then 6, 5, 2, 2 and 1 on the fix rounds) plus my own review (4 findings, then 1 nit). Rows 1-10 are fixed in 4be7d63, rows 19-23 in b7fb234, rows 25, 28 and 30 in c73c3da, row 31 in 4d02751, rows 33-34 in be764c0.
Severity: ❌ blocker / |
|
cc @antaljanosbenjamin, could you review this? It adds a thread-less native client of the Pulsar binary protocol (only what the Pulsar engine of #64184 / #133430 uses), with every size from the network validated, so the engine can drop contrib/pulsar-client-cpp. |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-7:20261122-051100 |
|
Workflow [PR], commit [8fd864a] Summary: ✅
AI ReviewSummaryPR #133490 adds an internal Pulsar binary-protocol client with non-blocking connections, TLS, shared consumers, producers, bounded decoding, and protocol tests. Reviewed head Final VerdictStatus: ✅ Approve |
The broker takes a permit for each message of a batch, counted from its own copy of the metadata, and an acknowledgement with a validation error does not return them. The consumer returned one permit for an entry with a wrong checksum, because the metadata it received cannot be trusted, so a corrupted batch of the whole window left the subscription without permits and nothing more was received on a healthy connection. Now the entry is acknowledged with `ChecksumMismatch`, the consumer is closed with `CLOSE_CONSUMER` (the broker redelivers its other unacknowledged messages), and the partition subscribes again with a full window, as after a lost connection. The test sends a corrupted batch that takes all permits and checks that the client gets permits again and receives the next message. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Build profile diff (arm_release)Comparing Binary sizes
The official master build is compiled with Object file sizes
|
| Object file | Master | PR | Δ |
|---|---|---|---|
src/Storages/Pulsar/Client/Proto/CMakeFiles/clickhouse_pulsar_proto.dir/PulsarApi.pb.cc.o |
new | 1.26 MiB | +1.26 MiB |
src/CMakeFiles/dbms.dir/Storages/Pulsar/Client/Consumer.cpp.o |
new | 338.52 KiB | +338.52 KiB |
src/CMakeFiles/dbms.dir/Storages/Pulsar/Client/Connection.cpp.o |
new | 258.37 KiB | +258.37 KiB |
src/CMakeFiles/dbms.dir/Storages/Pulsar/Client/Protocol.cpp.o |
new | 230.73 KiB | +230.73 KiB |
src/CMakeFiles/dbms.dir/Storages/Pulsar/Client/Producer.cpp.o |
new | 155.67 KiB | +155.67 KiB |
src/CMakeFiles/dbms.dir/Storages/Pulsar/Client/Client.cpp.o |
new | 60.48 KiB | +60.48 KiB |
src/Storages/Pulsar/Client/Proto/CMakeFiles/clickhouse_pulsar_proto.dir/MetadataViews.pb.cc.o |
new | 48.52 KiB | +48.52 KiB |
716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.
Compile time of recompiled translation units
15 translation units recompiled, 27 s compile time in total, 7 of them have a recent master baseline.
`nfds_t` is `unsigned int` on Darwin, so passing `fds.size()` to `poll` failed `Build (arm_darwin)` with `-Wshorten-64-to-32`. The darwin build also compiles the unit tests without musl, so `-Wdisabled-macro-expansion` is on there: zlib-ng's name-mangling header defines every zlib symbol as an identity macro, and using `compress`, `deflateInit` or `deflate` inside a gtest assertion macro trips it. The test now calls them outside the assertions. Both found by compiling every Pulsar TU with the CI `arm_darwin` flags and the macOS SDK from the binary-builder image. Co-Authored-By: Claude Opus 5.5 <[email protected]>
AI review of a later commit does not approve the PR, see the AI Review comment.
`acknowledge` rescanned the acknowledged bits of a batch after each message, so acknowledging a batch of N messages in order took O(N^2) (about 30 s for 200,000 messages in a debug build). Keep the number of unacknowledged messages next to the bits and decrement it only when a bit is set for the first time, so a repeated acknowledgement does not count. The new test acknowledges a batch of 200,000 messages in one call, again (duplicates), then in reverse order over many calls, and checks that the batch is acknowledged once, after its last message. Co-Authored-By: Claude Opus 5.5 <[email protected]>
With N partitions, every reset of a sub-consumer (a lost connection, a `CLOSE_CONSUMER` from the broker) compacted the whole message queue, and every `SUBSCRIBE` response scanned all sub-consumers for its request. Both are O(N^2) when all partitions are affected at once: at 65,536 partitions (the limit), in a debug build, a 10 ms `batchReceive` took 37 s after a lost connection and 44 s after a `CLOSE_CONSUMER` for every partition, and `subscribe` took 9 s. A reset now only counts the messages of the sub-consumer as stale: `takeMessages` skips the entries of a previous subscription, and the queue is compacted once the stale messages outnumber the others, so the memory stays bounded. The pending subscriptions are indexed by request id. The same calls now take 0.23 s, 1.1 s and 1.5 s. The new test closes the consumers of one and then two of three partitions with queued messages and checks that only the messages of the other partitions are returned. Co-Authored-By: Claude Opus 5.5 <[email protected]>
`master` now has a native Pulsar client in `src/Storages/Pulsar/Client` (#133490), written for this engine, in the same directory as the client this branch added. The conflicts are resolved by taking the client and its build wiring from `master` and removing the client of this branch (`BatchIndexAck`, `Checksum`, `Compression`, `Configuration`, `ConnectionRegistry`, `Result`, the old `PulsarApi.proto` location and its `CMakeLists.txt`, the `ENABLE_PULSAR` option). The `Pulsar` table engine is switched to the client from `master`: - `PulsarConsumer` owns a `Pulsar::Consumer` created by `Client::subscribe` and passes the batch size and the poll timeout to `batchReceive`. The client reports errors with exceptions; a consumer whose call has thrown is marked unusable, so the storage closes it and creates the slot again. - `PulsarProducer` uses `Producer::send` with the payload and the optional ordering key, and `Producer::interrupt` in `cancel`. - The connection validator checks the host and port against `remote_url_allow_hosts` and throws to reject the connection. Co-Authored-By: Claude Fable 5.2 <[email protected]>
Related: #64184
Related: #64184 (comment)
Related: #133430
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Description
A client of the Pulsar binary protocol in
src/Storages/Pulsar/Client, implementing only what thePulsarengine (#64184, continued in #133430) uses, so that the engine can dropcontrib/pulsar-client-cpp. Nothing uses it until the engine switches to it, so there is no user-visible change. #133430 describes its own native client without TLS and partitioned topics; this one keeps both, as the engine of #64184 accepted them.Client::closeandProducer::interruptwake a call from another thread.ClickHouse/pulsar-client-cpp.Scope changes from my plan in #64184: no token auth (the engine has no auth setting); reconnecting happens inside calls, not in the background. The producer sends unbatched, uncompressed messages, all to one random partition of a partitioned topic (
UseSinglePartition;pulsar-client-cppdefaults to round robin), so oneINSERTgoes to one partition.Validation: unit tests of the protocol and against a fake broker (including TLS), also under ASan+UBSan;
pulsar_frame_fuzzerran 30 minutes without findings. With the engine of #64184 switched locally, 49 of its 50 integration tests pass (one needs a call before waiting for a log line);test_physical_columns_shadow_virtual_columnsfails in the engine before any client call. Also checked againstapachepulsar/pulsar:4.0.4: partitioned topics, a 7 MiB chunked message, all codecs, and TLS with a test CA (a certificate for another host is rejected, even withverificationModenone).🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/133490]
Version info
26.12.1.180-master(included in26.12and later)