Skip to content

Pulsar table engine on top of the native Pulsar client - #133430

Open
alexey-milovidov wants to merge 178 commits into
masterfrom
pulsar-native-client
Open

alexey-milovidov wants to merge 178 commits into
masterfrom
pulsar-native-client

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Nov 21, 2026 •

Copy link
Copy Markdown
Member

Adds the experimental Pulsar table engine (started in #64184) for consuming from and producing to Apache Pulsar, gated by the enable_pulsar setting.

The engine does not use the pulsar-client-cpp library. 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 are assert-only.

Instead, the engine uses the native client of the Pulsar binary protocol in src/Storages/Pulsar/Client, which is already in master (#133490). This branch originally carried its own smaller client in the same directory; it is removed in favor of the one from master, 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/latest initial position, streaming to materialized views, direct SELECT, INSERT (to a single topic), virtual columns, macros and named collections in the engine settings.
  • Messages are acknowledged only after the block built from them is written; a consumer whose call failed, or which was rolled back, is closed and created again, so its messages are redelivered.
  • Every broker address, both from pulsar_service_url and from lookup responses, is checked against remote_url_allow_hosts.
  • The enable_pulsar and pulsar_max_wait_ms settings, the PULSAR source access type, and integration tests in tests/integration/test_storage_pulsar.

Related: #133490

Changelog category (leave one):

  • Experimental Feature

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

Added the experimental Pulsar table 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]

SteveBalayanAKAMedian and others added 30 commits May 1, 2024 21:11
# 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]>
…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.
…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.
alexey-milovidov and others added 16 commits November 9, 2026 07:28
…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]>
@clickhouse-gh

clickhouse-gh Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6644d80]

Summary: ❌

job_name test_name status info comment
Build (arm_tidy, 1/4) FAIL
Build ClickHouse FAIL cidb
Build (arm_tidy, 3/4) FAIL
Build ClickHouse FAIL cidb
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL
Fast test (arm_darwin) DROPPED
Build (amd_debug) DROPPED
Build (amd_asan_ubsan) DROPPED
Build (amd_tsan) DROPPED
Build (amd_msan) DROPPED
Build (amd_binary) DROPPED
Build (arm_debug) DROPPED

AI Review

Summary

PR #133430, reviewed at 6644d80d8fe9f1b662dccd8589204b3562c4da2a, adds the experimental Pulsar table engine using the native client from master, with direct reads, inserts, materialized-view streaming, settings, virtual columns, and integration coverage. Changes are required for acknowledgement safety, persistence of broker identity, and shutdown ordering. There were no existing inline review threads or earlier AI findings to reconcile.

Findings

❌ Blockers

  • src/Storages/Pulsar/PulsarSource.cpp:158: stream error handling also recovers from resource/internal exceptions. If parsing a valid message raises MEMORY_LIMIT_EXCEEDED and the recovery allocations succeed, the engine substitutes default values and acknowledges the message after the insert pipeline succeeds. Views that omit _raw_message lose the original data. Propagate fatal/resource exceptions before both recovery branches so the message is redelivered.
  • src/Storages/Pulsar/StoragePulsar.cpp:1064: macro persistence rewrites the first occurrence of a setting, although the last occurrence determines its effective value. Creating t with pulsar_topic_list = 'ignored', pulsar_topic_list = '{table}_topic', then renaming it to u and reloading it, switches from t_topic to u_topic. The original backlog is abandoned and writes change destinations. Canonicalize/reject repeated broker settings or rewrite every occurrence when freezing macros; the same issue affects the subscription name and other broker identity settings.

⚠️ Majors

  • src/Storages/Pulsar/StoragePulsar.cpp:391: shutdown waits for background callbacks before interrupting their synchronous client. An idle consumer with pulsar_poll_timeout_ms = 600000 can consequently delay detach/drop and server shutdown for ten minutes. Set the shutdown flag, close the client to interrupt network calls, then deactivate the tasks.
Tests
  • ⚠️ Exercise a resource exception raised inside parsing with pulsar_handle_error_mode = 'stream', then verify redelivery of the original valid message. Existing resource-error coverage uses the default mode.
  • ⚠️ Extend broker-identity coverage with a repeated macro-bearing setting across rename and reload.
  • ⚠️ Verify shutdown while a consumer is blocked in a long poll, reusing the existing broker fixture.
Missing context / blind spots
  • ⚠️ The head CI report currently reports clang-tidy failures and dropped build jobs; it supplies no integration results for the engine after the client switch. A successful test_storage_pulsar run on the revised head would close this validation gap. No local tests were run, as requested for this CI review environment.
Final Verdict

Status: ❌ 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.

@clickhouse-gh clickhouse-gh Bot added pr-experimental Experimental Feature submodule changed At least one submodule changed in this PR. comp-message-queues Message queue integrations (Kafka, RabbitMQ, NATS table engines for stream ingestion/egress). labels Nov 21, 2026
alexey-milovidov and others added 2 commits November 24, 2026 00:59
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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Superseded by master — this can be closed.

master already drops the contrib/pulsar-client-cpp submodule and ships a native Pulsar client in src/Storages/Pulsar/Client/ (landed around 2026-11-22). That client is more complete than the one here: it adds Protocol.cpp/Proto, partitioned topics (handled in linear time), chunked and compressed messages, TLS via the server's openSSL.client configuration, constant-time per-message batch acknowledgement, and a macOS build fix — while keeping the same synchronous, thread-free DB::Pulsar design this PR used.

So the goal of this PR (remove the submodule and replace it with a small native client in src) is already achieved on master, and better. Nothing here needs to be merged.

alexey-milovidov and others added 2 commits November 24, 2026 15:15
`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]>
@alexey-milovidov alexey-milovidov changed the title Pulsar table engine with a native client (drop the pulsar-client-cpp submodule) Pulsar table engine on top of the native Pulsar client Nov 24, 2026
@alexey-milovidov

alexey-milovidov commented Nov 24, 2026 •

Copy link
Copy Markdown
Member Author

🕵 Correction to my earlier comment: only the client part of this PR is superseded by master (#133490). The Pulsar table engine itself (StoragePulsar, PulsarSource, PulsarConsumer, PulsarProducer, the settings and the integration tests) is not in master, so this PR stays open for it.

I merged master and resolved the conflicts by taking the client from master and removing the smaller client this branch carried in the same directory, then switched the engine to that client (402dbe7, 6644d80). The PR is now the engine only: 28 files instead of 54.

Verification: the engine translation units compile against the merged tree. I did not link a full binary or run test_storage_pulsar locally, so the integration tests against the new client are verified only by CI on this push. One test was adapted: test_remote_host_filter_applies_to_lookup_results now reads from the table before waiting for the rejection log line, because the client from master connects only inside a call.

Note: the message of 6644d80 names this test incorrectly as test_lookup_result_is_checked_against_allowlist; the test it changes is test_remote_host_filter_applies_to_lookup_results.

return 0;
}

if (put_error_to_stream)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[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.

Comment on lines +391 to +393
shutdown_called.store(true);
init_task->deactivate();
streamer->deactivate();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[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.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-message-queues Message queue integrations (Kafka, RabbitMQ, NATS table engines for stream ingestion/egress). 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.

4 participants