Repository navigation
Pulsar table engine on top of the native Pulsar client - #133430
alexey-milovidov wants to merge 178 commits into
Conversation
This reverts commit b0c7d58.
# Conflicts: # .gitmodules # contrib/CMakeLists.txt # src/Core/Settings.h # src/Core/SettingsChangesHistory.h # src/Storages/registerStorages.cpp
The previous merge attempt produced spurious conflicts due to a criss-cross history (two merge bases), so this merge was constructed as: tree of current master plus the Pulsar-only changes of this branch re-applied. Co-Authored-By: Claude Fable 5 <[email protected]>
The pinned pulsar-client-cpp revision predates several changes in the ClickHouse third-party stack, so the contrib CMake file now provides compatibility layers instead of requiring changes inside the submodule: - ClickHouse removed the `curl` submodule (PR #108296), so a minimal stub of the libcurl API is provided in `curl-stub/`. The Pulsar binary protocol (`pulsar://`) is fully functional; HTTP topic lookup (`http://` service URLs) and OAuth2 authentication fail at runtime with a clear error. `curl_easy_escape` (used by `TopicName` percent-encoding) is implemented for real. - Boost was updated to 1.90, which removed the deprecated Asio APIs the client uses (`io_service`, `const_buffers_1`/`mutable_buffers_1`, `resolver::query`/`iterator`, `expires_from_now`, `cancel(error_code &)`, `rfc2818_verification`). Shim headers in `asio-compat/` restore them on top of the modern API. - The vendored protobuf returns `absl::string_view` from descriptor accessors, so `ProtobufNativeSchema.cc` is compiled from a patched copy in `patched/`. - The protobuf codegen and `Version.h` are now generated into the binary directory (the previous version wrote into the submodule working tree and relied on a `LIBARARY_DIR` typo that excluded the generated sources from the first configure). Co-Authored-By: Claude Fable 5 <[email protected]>
The storage code was written in 2024 and needed adaptation to two years of API drift: - `PulsarSettings` migrated to the pimpl settings pattern (`BaseSettingsFwdMacros.h`, `DECLARE_SETTING_TRAIT`, subscript access via `PulsarSetting::` constants), following `NATSSettings`/`KafkaSettings`, with `loadFromNamedCollection`, `getFormatSettings` and `hasBuiltin`. - Core settings access through `Setting::` constants instead of direct member access; `pulsar_max_wait_ms` was already declared in `Core/Settings.cpp` and `SettingsChangesHistory.cpp` by the merge. - `ISource`/`MessageQueueSink` take `SharedHeader` now; the on-error callback of `StreamingFormatExecutor` uses `ColumnCheckpoints` rollback; `FormatFactory::getInput` takes `FormatParserSharedResources`. - `InterpreterInsertQuery` explicit flags; `make_intrusive` for ASTs; `getInMemoryMetadataPtr(context, bypass_metadata_cache)`; `BackgroundSchedulePool::createTask` takes the `StorageID`; `addEphemeral` takes `VirtualsMaterializationPlace`; `noPushingToViews` was renamed to `noPushingToViewsOnInserts`; `IMessageProducer` requires `cancel()`. - `registerStoragePulsar` follows the current NATS registration shape and passes `has_builtin_setting_fn`. - Fixed a typo in the error virtual column name: it was `д` instead of `_error`. - Fixed `pulsar_flush_interval_ms` handling: `Poco::Timespan::milliseconds` returns only the millisecond component; use `totalMilliseconds`. - `dbms_target_link_libraries` no longer exists in `src/CMakeLists.txt`; use `target_link_libraries(dbms ...)`. The engine registers, settings validate, and `CREATE TABLE` fails fast with a clear error when the broker is unreachable. End-to-end produce/consume against a live Pulsar broker still needs an integration test. Co-Authored-By: Claude Fable 5 <[email protected]>
The check validates `extern const ...Settings` declarations against the known settings-declaration files, which are listed explicitly. Co-Authored-By: Claude Fable 5 <[email protected]>
# Conflicts: # .gitmodules
…the nested `vcpkg` submodule The `Check Submodules` CI step forbids recursive submodules, and the pinned commit of the author's personal fork contains a nested `vcpkg` submodule, which caused all builds to be dropped: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=64184&sha=a3090cfc8142880b81c7a08dca8e7212d539b0fe&name_0=PR&name_1=Build%20%28arm_tidy%29 The new fork https://github.com/ClickHouse/pulsar-client-cpp carries the same pinned commit plus one commit on the `clickhouse` branch that removes `.gitmodules` and the `vcpkg` gitlink. This also moves the submodule from a personal fork to the ClickHouse organization, per policy.
…clickhouse` branch
…rable write, bound empty polling Fixes the four blockers from the AI review on #64184: - `StoragePulsar::createProducer` and `createConsumer` now check the `pulsar::Result` and throw `CANNOT_CONNECT_PULSAR` (new error code 780), so a bad topic, auth failure, or unreachable broker fails `CREATE TABLE` and `INSERT` immediately instead of leaving uninitialized clients behind. On ATTACH (server startup), a subscription failure is logged instead of thrown, following the `StorageNATS` pattern, so an unreachable broker does not prevent loading existing tables. - Messages are no longer acknowledged when the next batch is polled. `PulsarConsumer` accumulates consumed message ids and acknowledges them only in `commit`, which `streamToViews` calls after the pipeline finishes successfully - mirroring Kafka. On a pipeline failure the messages are negatively acknowledged (`rollback`) to request redelivery, preserving at-least-once delivery. Direct `SELECT` acknowledges on completion only when the new `pulsar_commit_on_select` setting is enabled (default off), mirroring `kafka_commit_on_select`. - `PulsarProducer::produce` no longer retries every non-OK `send` result in a tight loop. Transient backpressure is already handled by `setBlockIfQueueFull(true)`, so any non-OK result is a real error and now throws. `finish` checks the `flush` result, and `cancel` closes the producer to abort a blocked send. - `PulsarSource` exits after 10 consecutive empty polls (like Kafka's failed poll counter), so a direct `SELECT` from an empty topic terminates instead of hanging forever.
# Conflicts: # .gitmodules
…p negotiated limits per connection The first chunk of a chunked message could declare 2147483647 chunks and make the client reserve 32 GiB for their message IDs; now the layout is validated, the reservation is capped and an allocation failure closes the connection without acknowledging the chunks. The maximum message size negotiated with a broker was static and shared by all connections, so connecting to a broker with a smaller limit made consumers of other brokers discard valid messages; now it belongs to the connection. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… expand each `Pulsar` setting from the top level
A config macro such as `<pulsar_db_topic>{database}_topic</pulsar_db_topic>` was stored unexpanded,
so a detached table of a renamed database (where the rename check is not called) switched to another
topic after `ATTACH`. Now, when the recursive expansion of a broker identity setting of a fresh definition
uses `{database}` or `{table}`, the fully expanded value is stored in the definition.
The settings shared one `MacroExpansionInfo`, whose recursion depth is not reset by `Macros::expand`,
so `{uuid}` in a second setting was rejected as nested. Now each setting is expanded with a fresh
`MacroExpansionInfo`, and only the flags used by the rename check are accumulated.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Resolve conflict in `src/Common/ErrorCodes.cpp`: master took code 787 for `UNKNOWN_DISTRIBUTED_ASYNC_INSERT_FORMAT_VERSION`, so `CANNOT_CONNECT_PULSAR` moves to 788. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…e insertion and decompression allocation failure paths - Check for an uncached chunk before dereferencing its iterator in `ConsumerImpl::processMessageChunk`. - Roll back the key of `MapCache::putIfAbsent` when the insertion throws, and discard orphan keys in `removeOldestValuesIf`, which otherwise spun forever under `chunkProcessMutex_`. - Close the connection when the decompression of a valid message fails to allocate, so that it is redelivered: the unacknowledged message tracker is disabled with the default consumer configuration. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ently of the current macro expansion
A `Pulsar` table created from a named collection whose locked key reaches `{table}` through a macro
from the server configuration stores the unfolded value in its definition. If the macro was later
changed so that it no longer depends on the table, the replayed definition was rejected with
`Override not allowed`, so the table could not be attached again. A replayed definition is now
recognized by the macros in the collection value alone, while fresh definitions are checked as before.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…oned chunked messages Address review: incomplete chunked messages evicted from the chunk cache, and later chunks arriving without a context, were passed to the unacknowledged message tracker, which is disabled by default and is bypassed by the child consumers of the multi-topic consumer used by `StoragePulsar`. Now they are redelivered explicitly. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…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]>
…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]>
# 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: #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]>
# 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: #64184 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop the `contrib/pulsar-client-cpp` submodule and its CMake shims (`asio-compat`, `curl-stub`, the patched sources) and rewrite the Apache Pulsar client from scratch in `src/Storages/Pulsar/Client`, in ClickHouse style. The new client speaks only the Pulsar binary protocol and is deliberately minimal and synchronous: no event loop and no background threads. Each producer and consumer owns one blocking `Connection`; `Client::close` shuts the sockets down from any thread, which unblocks a consumer parked in `batchReceive`. This avoids the whole class of problems that made the upstream library unsuitable for embedding (an exception on an I/O thread terminating the process, a use-after-free on connection close, and assert-only bounds checks on bytes from the network). Every length read from the wire is bounds-checked, the declared uncompressed size is capped before allocation, and the message checksum is verified. Supported: topic lookup with redirects, shared subscriptions with several consumers, earliest/latest initial position, producing, consuming with batch splitting and `LZ4`/`ZLIB`/`ZSTD`/`SNAPPY`/`NONE` decompression, individual and batch-index acknowledgement, negative acknowledgement, and the event-time presence bit. Not supported (reported as a clean error, not mishandled): TLS, authentication, and partitioned topics. The protocol definition `PulsarApi.proto` is generated into a small `clickhouse_pulsar_proto` library (like `clickhouse_buzzhouse_proto`); the hand-written client is compiled into `dbms`. `USE_PULSAR` now depends on protobuf and the compression codecs instead of the removed contrib target. The engine wrappers (`StoragePulsar`, `PulsarConsumer`, `PulsarProducer`, `PulsarSource`) are adapted to the new `DB::Pulsar` API; `PulsarLogger` is removed because the client logs through ClickHouse directly. Related: #64184 Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Workflow [PR], commit [6644d80] Summary: ❌
AI ReviewSummaryPR #133430, reviewed at Findings❌ Blockers
Tests
Missing context / blind spots
Final VerdictStatus: ❌ Block Propagate fatal parser failures, persist the effective broker settings consistently across reload, and interrupt the client before joining background tasks. Add focused regression coverage for these paths and obtain integration results with the native client. |
The previous commit only recorded the removal of the `pulsar-client-cpp` submodule; the new client sources, the adapted engine wrappers and the CMake changes were not staged, so the tree did not configure (it still called `add_contrib (pulsar-client-cpp-cmake pulsar-client-cpp)` for a submodule that no longer exists). Add them: - `src/Storages/Pulsar/Client/*` — the from-scratch binary-protocol client (namespace `DB::Pulsar`) and its `PulsarApi.proto`. - `src/Storages/Pulsar/Client/CMakeLists.txt` — generates `clickhouse_pulsar_proto`. - `src/CMakeLists.txt`, `src/configure_config.cmake` — gate `USE_PULSAR` on protobuf and the compression codecs, build the client into `dbms`, and drop the `add_contrib` call for the removed submodule. - the `StoragePulsar`/`PulsarConsumer`/`PulsarProducer` wrappers adapted to the new API. Co-Authored-By: Claude Opus 4.8 <[email protected]>
The `settings_changes_history` style check requires a setting that is new in the release under development to carry a record for the current version. `enable_pulsar` and `pulsar_max_wait_ms` had `26.11` records; the engine has not shipped, so move them to `26.12`. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
🕵 Superseded by
So the goal of this PR (remove the submodule and replace it with a small native client in |
`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]>
The native client runs no threads and connects only inside a call, so the exception of the connection validator often ends up in a background task. Log the rejection together with the address, as before the switch to the client from `master`. `test_lookup_result_is_checked_against_allowlist` waited for this log line without making any call after the broker was restarted. With a client that reconnects only inside a call, read from the table first. Co-Authored-By: Claude Fable 5.2 <[email protected]>
|
🕵 Correction to my earlier comment: only the client part of this PR is superseded by I merged Verification: the engine translation units compile against the merged tree. I did not link a full binary or run Note: the message of 6644d80 names this test incorrectly as |
| return 0; | ||
| } | ||
|
|
||
| if (put_error_to_stream) |
There was a problem hiding this comment.
[Blocker] Propagate resource failures before converting exceptions into error rows
The isParseError check above protects only pulsar_skip_broken_messages. With pulsar_handle_error_mode = 'stream', a MEMORY_LIMIT_EXCEEDED or an internal exception raised inside StreamingFormatExecutor::execute still reaches this branch: the successfully parsed part of the message is rolled back, its data columns receive defaults, and the callback returns one successful row. If the error-row allocations succeed, streamToViews subsequently acknowledges the message. A transient allocation failure can therefore permanently replace a valid message with default values; an ordinary materialized view need not retain _raw_message or _error.
Propagate fatal/resource exceptions before either recovery branch, so these messages are rolled back and redelivered. Add coverage that triggers a resource failure inside the parser in stream mode and verifies that the original message remains readable after the failure is removed; the existing resource-error test uses the default mode.
| settings_ast->is_standalone = false; | ||
| args.storage_def->set(args.storage_def->settings, settings_ast); | ||
| } | ||
| args.storage_def->settings->changes.setSetting(setting_name, expanded); |
There was a problem hiding this comment.
[Blocker] Freeze the effective occurrence of repeated broker settings
ParserSetQuery preserves repeated settings and BaseSettings::applyChanges applies them in order, so the last occurrence wins. However, SettingsChanges::setSetting updates only the first occurrence. For example, create table t with pulsar_topic_list = 'ignored', pulsar_topic_list = '{table}_topic': the live engine subscribes to t_topic, but the stored definition still ends with pulsar_topic_list = '{table}_topic'. The constructor receives the expanded value, so its rename guard records no use of {table}. After renaming t to u and detaching/attaching it, the table silently subscribes to u_topic instead, abandoning the original topic's backlog; inserts also move to that topic.
Canonicalize or reject repeated broker settings before persisting the expansion, or replace every occurrence so the effective stored value is frozen too. Cover a repeated macro-bearing setting across rename and reload; this also applies to the subscription name and the other broker identity settings handled here.
| shutdown_called.store(true); | ||
| init_task->deactivate(); | ||
| streamer->deactivate(); |
There was a problem hiding this comment.
[Major] Interrupt the synchronous client before waiting for its background tasks
BackgroundSchedulePoolTaskInfo::deactivate waits for the running callback's execution mutex. A streaming callback can be inside Consumer::batchReceive, which observes the client's interrupter but does not observe shutdown_called. With an idle topic and, for example, pulsar_poll_timeout_ms = 600000, shutdown waits here for the long poll to finish before reaching the pulsar_client.close call that would wake it. This stalls table detach/drop and server shutdown for up to the configured poll timeout; an in-progress subscription in init_task similarly cannot be interrupted by the later close.
Call the thread-safe Client::close after setting the shutdown flag and before deactivating/joining either task. Cover shutdown while a consumer is blocked in a long poll using the existing broker fixture.
Adds the experimental
Pulsartable engine (started in #64184) for consuming from and producing to Apache Pulsar, gated by theenable_pulsarsetting.The engine does not use the
pulsar-client-cpplibrary. An evaluation of that library (fuzzing its message path and auditing its concurrency and lifetime) found it unsuitable to embed in the server: an exception on its I/O thread terminates the whole process, there is a use-after-free on connection close reachable by an ordinary disconnect, and its bounds checks on bytes from the network areassert-only.Instead, the engine uses the native client of the Pulsar binary protocol in
src/Storages/Pulsar/Client, which is already inmaster(#133490). This branch originally carried its own smaller client in the same directory; it is removed in favor of the one frommaster, which also supports TLS (pulsar+ssl://), partitioned topics and chunked messages. The client runs no threads: all network I/O happens inside the calls of the engine, and errors are reported with exceptions.What this change contains:
StoragePulsar,PulsarSource,PulsarConsumer,PulsarProducer,PulsarSettings: shared subscriptions with several consumers,earliest/latestinitial position, streaming to materialized views, directSELECT,INSERT(to a single topic), virtual columns, macros and named collections in the engine settings.pulsar_service_urland from lookup responses, is checked againstremote_url_allow_hosts.enable_pulsarandpulsar_max_wait_mssettings, thePULSARsource access type, and integration tests intests/integration/test_storage_pulsar.Related: #133490
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Added the experimental
Pulsartable engine for consuming from and producing to Apache Pulsar, backed by a native client that speaks the Pulsar binary protocol.🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/133430]