Skip to content

Add a native Pulsar client for the Pulsar table engine - #133490

Merged
alexey-milovidov merged 20 commits into
ClickHouse:masterfrom
groeneai:groeneai/native-pulsar-client
Nov 22, 2026
Merged

alexey-milovidov merged 20 commits into
ClickHouse:masterfrom
groeneai:groeneai/native-pulsar-client

Conversation

@groeneai

@groeneai groeneai commented Nov 22, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #64184
Related: #64184 (comment)
Related: #133430

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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 the Pulsar engine (#64184, continued in #133430) uses, so that the engine can drop contrib/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.

  • No threads: socket I/O is non-blocking and happens inside the calls, which wait only up to their timeouts (DNS resolution aside); a step that does not finish continues in the next call, with a time limit across calls. Client::close and Producer::interrupt wake a call from another thread.
  • Every size from the network is checked before use; safe decompressors with exact sizes; memory-tracked buffers; chunk assembly with the policy of ClickHouse/pulsar-client-cpp.
  • The client checks the certificate host name itself, and calls the connection validator before every connection, including brokers from lookup responses.

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-cpp defaults to round robin), so one INSERT goes to one partition.

Validation: unit tests of the protocol and against a fake broker (including TLS), also under ASan+UBSan; pulsar_frame_fuzzer ran 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_columns fails in the engine before any client call. Also checked against apachepulsar/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 with verificationMode none).

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.12.1.180-master (included in 26.12 and later)

groeneai and others added 16 commits November 21, 2026 18:39
…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]>
- 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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
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.

# Sev Finding Verdict Evidence / action
1 ⚠️ ACK frames unbounded in ids; a default engine block exceeds the broker's frame limit (maxMessageSize + 10 KiB) and the acks are lost AGREE, fixed @ 4be7d63 ids split per frame by the connection's max message size
2 ❌ Vendored PulsarApi.proto lacks an in-file modification notice and NOTICE attribution AGREE, fixed @ 4be7d63 notice added after the ASF header
3 ❌ Abandoned chunked-message memory keeps up to 10000 producer-sized uuids AGREE, fixed @ 4be7d63 128-bit hashes kept instead; chunk-id growth is per received frame and memory-tracked (that part DISAGREE)
4 ⚠️ Expired requests stay in flight; late responses fail the consumer AGREE, fixed @ 4be7d63 erased on expiry; responses to request ids issued earlier are ignored, never-issued ids stay protocol violations
5 ⚠️ Interruption not sticky (ABORTED) AGREE, fixed @ 4be7d63 interruption checked first
6 ⚠️ Held acks after a resubscribe AGREE in part, fixed @ 4be7d63 sent before the first FLOW; comment corrected; acknowledge does not block for a reconnect (held acks are sent on the new consumer id)
7 ❌ fd left in one interrupter if the second registration throws AGREE, fixed @ 4be7d63 both or neither
8 ❌ Signed overflow on last_sequence_id + 1 AGREE, fixed @ 4be7d63 unsigned arithmetic
9 💡 Checksum compared after reading the metadata size AGREE, fixed @ 4be7d63 compared first
10 ⚠️ Compressed chunked message not tested through the consumer; fake-broker config writes unlocked AGREE, fixed @ 4be7d63 new test; writes under the config mutex
11 ❌ Trailing bytes after the declared batch entries DISAGREE the batch is exactly num_messages_in_batch entries (what the broker charges); rejecting would ack the declared entry too
12 ❌ ack_set ignored DISAGREE non-empty only after batch-index acks by another client on the same subscription with acknowledgmentAtBatchIndexLevelEnabled (off in Pulsar 3.0/4.0); permit refunds match pulsar-client-cpp; those messages are delivered again (at-least-once)
13 ❌ Later chunk metadata not compared with the first chunk DISAGREE, then AGREE in part (row 25) a frame with num_chunks_from_msg <= 1 is a plain message by its own metadata, classified like pulsar-client-cpp does
14 ⚠️ Batch count refunded before validation DISAGREE the broker charges the same num_messages_in_batch, so the refund restores its permits
15 ⚠️ zlib trailing input / uncompressed payload over max size DISAGREE output size is exact; the frame bound caps memory; rejecting would discard valid messages
16 ⚠️ partitions presence not checked DISAGREE brokers always set it on success
17 ❌ TLS cross-direction retries DISAGREE every wait is capped at 1 s and retried; SSL_write wants a read only on TLS 1.2 renegotiation
18 ⚠️ No failover to the next service host after TCP; payload not rechecked after reconnect; windows not rebalanced on partition growth DISAGREE next attempt starts from the next host; a mismatch ends in a send timeout error; same window rule as pulsar-client-cpp
19 ⚠️ A broker that keeps the socket readable (PING flood) keeps a call reading past its deadline, one PONG queued per PING AGREE, fixed @ b7fb234 at most 1 MiB read per step; a PONG only when nothing else is queued
20 ⚠️ Producer checks the payload but not payload plus metadata (ordering key) against the broker limit AGREE, fixed @ b7fb234 checked before every send, as pulsar-client-cpp does; also covers row 18's reconnect case
21 ⚠️ ACK split not tested with 10-byte ids AGREE, fixed @ b7fb234 test with 2^63 ids against the broker's frame limit
22 💡 publish_time + expiry wraps near 2^64 AGREE (as a nit), fixed @ b7fb234 guarded subtraction
23 💡 Producer-written uuids logged in full AGREE, fixed @ b7fb234 64-byte prefix and length
24 ⚠️ Long-uuid test passes with string storage too DISAGREE the bound is the element type (pair<UInt128, bool>); the test checks behaviour is unchanged and that the hash tells uuids apart
25 ⚠️ A later chunk that changes num_chunks_from_msg gets its permit returned as "not last" although it completes the message: one extra permit per such message AGREE, fixed @ c73c3da a chunk's permit is returned unless it completes a message; the codec and sizes of the last chunk decode the message, as in pulsar-client-cpp, and every size is checked against them (that part DISAGREE)
26 ⚠️ The 1 MiB input bound is per connection, not per call DISAGREE connections are shared per broker address (Session::connection), not per partition; each turn reads at most about 1 MiB per broker and checks the deadline
27 ⚠️ Responses already received are processed before overdue requests expire DISAGREE a request whose response arrived completes; expiring first would fail in-time responses whenever the caller pauses longer than the operation timeout
28 ⚠️ acknowledge returns although a lost connection dropped its queued ACKs AGREE on the comment, fixed @ c73c3da the broker redelivers those messages (ACKs carry no receipt); the comment now says so
29 ⚠️ The PING-flood test allows 5 s for a 200 ms call DISAGREE without the fix the call took 10.3 s; 5 s is the margin for sanitizer and aarch64 runs
30 💡 The comment says "at most 1 MiB"; one call can read 1 MiB + 64 KiB - 1 AGREE, fixed @ c73c3da "about 1 MiB"
31 ⚠️ The uuid of a pending chunked message is kept in an untracked String (up to a frame, 10 pending messages per partition) AGREE, fixed @ 4d02751 kept in a memory-tracked string like the chunks themselves; no length limit (it could reject valid messages)
32 ⚠️ Writing the output is not bounded per step, so a broker that keeps accepting short writes holds a call past its deadline DISAGREE each write takes all free send-buffer space and the loop stops at the first full buffer, so it runs only while the link drains as fast as it writes; the volume is the call's own output (one message, or the acks of one call), unlike row 19 where the broker chose the volume
33 ⚠️ A producer of a partitioned topic writes every message to one random partition, while pulsar-client-cpp defaults to round robin; the comment claimed parity with that default AGREE, fixed @ be764c0 the comment states it (UseSinglePartition), the PR description lists it, and a test pins the partitioned producer; round robin needs one producer per partition and is left out (each INSERT creates its own producer, so INSERTs still spread)
34 ⚠️ Ordering and partition keys of received messages are copied into untracked strings AGREE in part, fixed @ be764c0 the keys of a queued non-batched message are kept in memory-tracked strings; the keys of a returned Message are the caller's data, which the engine copies into its own string per row anyway (that part DISAGREE)
35 ⚠️ Message metadata parsed by protobuf (keys, uuid, unknown fields) is copied into ordinary strings that the reused parse objects keep DISAGREE in release builds ClickHouse's operator new charges every such string to the memory tracker (Common/AllocationInterceptors.cpp, linked into every executable); only sanitizer builds, where the sanitizer's operator new replaces it, miss them, and there it is at most the metadata of one frame per consumer (the reused parse object and one partly read batch), not growing with the queue like rows 31 and 34

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

@groeneai

Copy link
Copy Markdown
Collaborator Author

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.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? New code replacing a library, no failure to reproduce. Each defect class it must design out has a deterministic test: every size check rejects a 3 GiB declared size before sizing anything, each codec rejects the declared size -1 / +1, and the fake-broker tests cover frame-limit and permit violations, held lookup/subscribe responses and the TLS host-name mismatch.
b Root cause explained? contrib/pulsar-client-cpp trusts sizes from the network, runs detached threads with callbacks that outlive connections, and the engine needs only a small subset of it, so a native client of that subset replaces it (directive in #64184).
c Fix matches root cause? Yes: no threads (all I/O inside the calls, non-blocking, with deadlines), every wire size checked against the bytes present and the limits, safe decompressors with exact sizes, memory-tracked buffers, chunk policy ported from the fork.
d Test intent preserved / new tests added? New: gtest_pulsar_protocol (22 tests: every validation rule, codecs, batches incl. 1,000,000 entries, each row of the chunk policy, 1 MiB uuids), gtest_pulsar_client (21 tests against a fake broker incl. TLS, acknowledgements bigger than the broker frame limit, late responses, a compressed chunked message, a chunked message whose last chunk changes the number of chunks, a PING flood, a message whose metadata makes it too big, a producer of a partitioned topic), pulsar_frame_fuzzer. No SQL surface on master, so no stateless test; the engine's integration tests are the functional tests after the switch.
e Both directions demonstrated? Negative controls instead of a before/after: the oversize/corrupt rows are rejected under ASan+UBSan, the fuzzer ran 30 min (53.4 M executions) and 10 more after each review round that changed the parser (16.3 to 17.2 M each), 0 crashes/OOMs/timeouts, 127.0.0.1 against a localhost certificate is rejected while localhost passes. The ZLIB rule was demonstrated both ways end to end: pulsar-perf -z ZLIB messages discarded before 4db16dd, delivered after. The review fixes were shown both ways: the new tests fail on the previous client code (one 1286-byte ACK of 200 ids over a 1000-byte limit, FLOW before the held ACK, a late SUCCESS treated as a violation, CANNOT_CONNECT_PULSAR instead of ABORTED after an interruption, a corrupted metadata size under a checksum thrown instead of discarded, a 200 ms receive held for 10.3 s by a PING flood, a 900-byte message with a 200-byte key sent to a broker with a 1000-byte limit, a chunk with a publish time near the maximum treated as expired, 3 permits returned for a 2-chunk message whose last chunk declares 3 chunks) and pass on the new one.
f Fix is general across code paths? The same rules apply to every path: frame sizes in the one reader, sizes of every metadata field in the one decoder, non-chunked and assembled chunked payloads through one decodePayload, consumer and producer through one Session/Connection. The connection validator runs before every connection (service hosts, redirects, lookup results, proxies).
g Fix generalizes across inputs? Codecs NONE/LZ4/ZLIB (also the Java sync-flushed form)/ZSTD/SNAPPY; batched and not; chunked (incl. compressed then sliced); partitioned and not; plain and TLS; keys and event time present, absent, and present as 0; empty payloads; IPv6 and multi-host service URLs.
h Backward compatible? No existing code changes: new files, one error code (CANNOT_CONNECT_PULSAR = 788, identical to #64184), one build flag (USE_PULSAR, the name #64184 uses).
i Invariants and contracts preserved? No size from the network is used before it is checked; a call never blocks past its deadline, and one step reads about 1 MiB, so a broker that keeps sending cannot hold it; after a call throws the object is unusable, while negativeAcknowledge, close and interrupt never throw; a valid message is never acknowledged as corrupted (allocation failures propagate); a chunked message returns one permit per chunk; acknowledgements survive a resubscription and are sent before the new permits, in commands that fit the broker's frame limit; after an interruption every call throws ABORTED; a response to a request no longer awaited is ignored, one to an id never sent is a violation; the only cross-thread operation shuts down sockets under a mutex.

Session id: cron:clickhouse-impl-slot-7:20261122-051100

@groeneai groeneai mentioned this pull request Nov 22, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8fd864a]

Summary: ✅


AI Review

Summary

PR #133490 adds an internal Pulsar binary-protocol client with non-blocking connections, TLS, shared consumers, producers, bounded decoding, and protocol tests. Reviewed head 8fd864a220dee3c1f533c52ea6514257e0cd6b9b, including the full diff and all prior discussion. Both previous findings are fixed in the current code and have regression coverage; the remaining batch-acknowledgement thread has been resolved. No new material findings. Runtime tests were not rerun locally because this checkout has no build directory or test binary.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-not-for-changelog This PR should not be mentioned in the changelog can be tested Allows running workflows for external contributors comp-message-queues Message queue integrations (Kafka, RabbitMQ, NATS table engines for stream ingestion/egress). labels Nov 22, 2026
Comment thread src/Storages/Pulsar/Client/Consumer.cpp Resolved
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]>
clickhouse-gh[bot]
clickhouse-gh Bot previously approved these changes Nov 22, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 8fd864a22 with master 4c070eb09 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: object file sizes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes ⚠️

4 object files changed (+2.33 MiB total), 8 added.

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.

Job report

`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]>
Comment thread src/Storages/Pulsar/Client/Consumer.cpp Resolved
@clickhouse-gh
clickhouse-gh Bot dismissed their stale review November 22, 2026 10:56

AI review of a later commit does not approve the PR, see the AI Review comment.

groeneai and others added 2 commits November 22, 2026 11:57
`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]>
@alexey-milovidov alexey-milovidov self-assigned this Nov 22, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 22, 2026
Merged via the queue into ClickHouse:master with commit a1c4ce2 Nov 22, 2026
195 checks passed
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 22, 2026
alexey-milovidov added a commit that referenced this pull request Nov 24, 2026
`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]>
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 comp-message-queues Message queue integrations (Kafka, RabbitMQ, NATS table engines for stream ingestion/egress). pr-not-for-changelog This PR should not be mentioned in the changelog pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants