Skip to content

[C++] Add stream builder and multiplexed streams - #1194

Draft
dimitrije-djordjevic-db wants to merge 45 commits into
effort/mux-streams-ffifrom
effort/mux-streams-cpp
Draft

dimitrije-djordjevic-db wants to merge 45 commits into
effort/mux-streams-ffifrom
effort/mux-streams-cpp

Conversation

@dimitrije-djordjevic-db

@dimitrije-djordjevic-db dimitrije-djordjevic-db commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Stack

  1. [FFI] Add multiplexed stream create and close #1192
  2. [C++] Add stream builder and multiplexed streams #1194 ← this PR

What changes are proposed in this pull request?

Adds a stream builder and multiplexed streams (Beta) to the C++ SDK. Closes #1123. Builds on the C FFI in #1192.

  • sdk.stream_builder() builds ordinary streams: table, oauth() or headers_provider(), json() or compiled_proto(), stream options and the ack callback, then build(). It shares one create path with create_stream, which keeps working.
  • .multiplexed(n).build() opens n sub-streams (1 to 64) and returns a move-only MultiplexedStream. Ingest returns an opaque MessageId (std::optional<MessageId> for a batch). It also has wait_for_message_id, flush, close, is_closed and get_unacked_records. All methods may be called from several threads at once; only move and destroy must not overlap a call.
  • MultiplexedAckCallback receives message IDs. It is separate from AckCallback because mux callbacks can run concurrently and in no order.
  • Validation messages match the Rust core. Docs, README, an example (ingest in a loop, then flush()), and a NEXT_CHANGELOG entry.
  • Fixes the existing live test's ordinary stream: it now sets the JSON record type.

Why: a single stream is ordered, which caps its throughput. Multiplexing raises throughput when global order isn't needed. The builder gives C++ the same shape as the other SDKs.

How is this tested?

  • Unit tests: the builder maps options like create_stream, validation errors and messages, builder copies, ownership of the headers provider and callbacks, and the mux ack callback trampolines.
  • The env-gated live test (integration_test.cpp) passes against a live Zerobus server: 33 sub-streams including negative message IDs, wait, flush, close, and callback delivery.
  • make test, make lint, and make test SANITIZE=address / SANITIZE=thread pass.

This pull request and its description were written by Isaac.

Signed-off-by: Dimitrije Đorđević <dimitrije.djordjevic@databricks.com>
Document what C callers need but the header did not say: JSON needs
record_type = 2 (NULL options select protobuf), the empty-batch -2 is
not a message ID, a failed ingest queues nothing and is not returned
by get_unacked_records, is_closed reflects only observed failures,
which calls may overlap, and that callbacks must not call back into
the mux. Also note one-lane batches, create jitter, the unused
max_inflight_requests remainder, and how a slow headers callback eats
into each sub-stream's open deadline.

The README example now checks the handle and results, frees error
messages, and shows the recovery path.

Reject a NULL record pointer with a nonzero length instead of reading
through it.

Co-authored-by: Isaac <no-reply@databricks.com>
Signed-off-by: Dimitrije Đorđević <dimitrije.djordjevic@databricks.com>
The ingest doc advised retrying whenever the mux was still open, but a
non-retryable error such as a record type mismatch leaves the mux open,
so that advice loops forever on a bad record. Retry only when
is_retryable is set, and treat a non-retryable error on an open mux as
an invalid record.

The README example now retries in place and re-sends records that were
never queued along with the unacknowledged ones.

Co-authored-by: Isaac <no-reply@databricks.com>
Signed-off-by: Dimitrije Đorđević <dimitrije.djordjevic@databricks.com>
wait_for_message_id did not say when it fails: only the owning
sub-stream's failure or flush_timeout_ms ends it with an error, and
-1, -2 or IDs from another stream are not valid input.

Also name the mux get_unacked_records in zerobus_free_record_array,
state in the README that max_inflight_requests must be at least
stream_count, and back off before retrying in the README example so
copied code does not busy-spin.

Co-authored-by: Isaac <no-reply@databricks.com>
Signed-off-by: Dimitrije Đorđević <dimitrije.djordjevic@databricks.com>
Cover the remaining multiplexed C entry points: pointer and handle
checks on every ingest call, create argument errors and connect
failures, OAuth create, headers user_data ownership on success,
partial open and free with a pending _nowait task, multi-lane message
IDs and waits, empty and closed-mux batches, per-call argument errors,
sub-stream failure recovery, concurrent callers, and ingest after a
queued close. Also scan multiplexed.rs for unguarded entry points.

Co-authored-by: Isaac <no-reply@databricks.com>
Signed-off-by: Dimitrije Đorđević <dimitrije.djordjevic@databricks.com>
The free doc said background _nowait tasks keep the stream alive until
they finish, which reads as if their records are still sent. The tasks
only hold the handle until the record is queued; without a close, those
records are abandoned like any other pending record.

Co-authored-by: Isaac <no-reply@databricks.com>
Signed-off-by: Dimitrije Đorđević <dimitrije.djordjevic@databricks.com>
Re-check "freed exactly once" after a short settle, so a late second
free fails the test. Give a wrongly released mux time to free its
provider before asserting a pending _nowait task kept it alive. Turn
off recovery in the connect-failure create test so it fails fast.

Co-authored-by: Isaac <no-reply@databricks.com>
Signed-off-by: Dimitrije Đorđević <dimitrije.djordjevic@databricks.com>
A _nowait call spawned its task and took the read lock inside it. If
close or get_unacked_records queued for the write lock first, the task
ran after the mux had closed, its ingest failed silently, and the
record was neither sent nor returned as unacknowledged.

Take the owned read guard in the FFI call, before spawning, and move it
into the task, so close and get_unacked_records wait until every
accepted record is queued. try_read_owned never blocks: it fails only
while close or get_unacked_records holds or waits for the write lock,
so such a call, or one on an already closed mux, now reports a
non-retryable error in result instead of being dropped. An empty
_nowait batch reports a closed mux the same way as the blocking batch.

Co-authored-by: Isaac <no-reply@databricks.com>
Signed-off-by: Dimitrije Đorđević <dimitrije.djordjevic@databricks.com>
Co-authored-by: Isaac <no-reply@databricks.com>
Signed-off-by: Dimitrije Đorđević <dimitrije.djordjevic@databricks.com>
Cover _nowait on a closed or closing mux (each export reports a
non-retryable error, empty batches included), records accepted just
before close (all sent and recoverable), and a _nowait call made while
a flush holds the handle (returns at once, record still acked).

Co-authored-by: Isaac <no-reply@databricks.com>
Signed-off-by: Dimitrije Đorđević <dimitrije.djordjevic@databricks.com>
Co-authored-by: Isaac <no-reply@databricks.com>
Signed-off-by: Dimitrije Đorđević <dimitrije.djordjevic@databricks.com>
Co-authored-by: Isaac <no-reply@databricks.com>
Signed-off-by: Dimitrije Đorđević <dimitrije.djordjevic@databricks.com>
flush returned once records already queued in the core were acked, so
a _nowait record whose background task had not queued it yet was not
covered: a nowait loop followed by flush could return before every
record was sent. A nowait API needs such a completion point.

Track _nowait submissions per flush epoch. Each accepted submission
holds a ticket in the current epoch until its task has queued it (or
the ingest failed). flush starts a new epoch and waits for the earlier
ones to drain before flushing, so producers that keep submitting cannot
hold a flush off. close and get_unacked_records already wait through
the read guards the tasks hold.

Document that a _nowait record whose background ingest fails is
dropped and not returned by get_unacked_records.

Co-authored-by: Isaac <no-reply@databricks.com>
Signed-off-by: Dimitrije Đorđević <dimitrije.djordjevic@databricks.com>
Multiplexed streams reused CStreamConfigurationOptions.ack_on_ack and
ack_on_error, whose contract on ordinary streams is ordered, monotonic
offsets from one task. A mux passes message IDs, unordered and possibly
concurrent, so a wrapper that fills those fields for an ordinary stream
would silently wire the wrong contract into a mux. The core and the
other bindings keep a separate mux callback.

Both mux create functions now take ack_on_ack, ack_on_error,
ack_user_data and free_ack_user_data, and reject the options fields with
InvalidArgument. The FFI owns ack_user_data and frees it exactly once,
after the last sub-stream and background task releases the callbacks
(or before returning on failure): the caller cannot observe that moment
itself, since _nowait tasks can outlive free. The mux API is unreleased,
so changing the create signatures is still additive to zerobus.h.

Co-authored-by: Isaac <no-reply@databricks.com>
Signed-off-by: Dimitrije Đorđević <dimitrije.djordjevic@databricks.com>
A flush after a _nowait loop waits for every accepted record, including
one still waiting for in-flight capacity, and returns while another
thread keeps submitting. The proto test no longer polls the server
before flushing.

Co-authored-by: Isaac <no-reply@databricks.com>
Signed-off-by: Dimitrije Đorđević <dimitrije.djordjevic@databricks.com>
Cover the mux create ack parameters: ack callbacks in options are
rejected, a one-sided callback bridge works, and ack_user_data is freed
exactly once on every create failure, on success only after the handle,
pending _nowait tasks and running callbacks release it, and at once when
both callbacks are NULL.

Also check that a flush does not wait for a _nowait accepted after it
began, and make the capacity and proto flush tests fail if flush stops
covering earlier _nowait records.

Co-authored-by: Isaac <no-reply@databricks.com>
Signed-off-by: Dimitrije Đorđević <dimitrije.djordjevic@databricks.com>
A _nowait record whose background ingest failed (a sub-stream at
capacity for 30 seconds, or failing while the task waited) was dropped
with no trace: not sent, not in get_unacked_records, and flush and
close succeeded.

Record the first such failure per flush epoch. The next flush that
covers it, or close, returns it with its typed cause and is_retryable,
unless the flush or close itself fails, whose error wins as in the
core. Either way the stored failure is cleared, so one call reports it.

Also release the handle through a Box, since nothing shares it; free
an unused ack callback as soon as it is known to be unused; correct the
flush timing doc; and state that free_user_data and free_ack_user_data
may run after a failed create returns, since a sub-stream that started
to open is torn down in the background.

Co-authored-by: Isaac <no-reply@databricks.com>
Signed-off-by: Dimitrije Đorđević <dimitrije.djordjevic@databricks.com>
Wrappers with async APIs, such as .NET, build them on the FFI's _async
functions, so a pending call does not park a caller thread for up to
30 seconds. The mux had none.

Add _async variants of both creates, the four ingests,
wait_for_message_id, flush, close and get_unacked_records. Each
validates its arguments and returns at once, then reports through a
completion callback on a runtime thread, reusing the ordinary stream's
callback types; the creates get a new
CreateMultiplexedStreamAsyncCallback returning the mux handle.

Ingest, wait and flush take the owned read guard before returning, and
an async ingest holds a flush ticket until it is queued, so flush, close
and get_unacked_records cover it like a _nowait record. Async close and
get_unacked_records take the write lock inside the task. Guards are
released before the completion callback, so a callback may start the
next _async call.

Co-authored-by: Isaac <no-reply@databricks.com>
Signed-off-by: Dimitrije Đorđević <dimitrije.djordjevic@databricks.com>
The _async bodies run on spawned tasks, outside ffi_guard. A panic there,
such as the core rejecting max_inflight_requests = SIZE_MAX by panicking
while allocating, killed the task before it invoked the completion
callback, so a caller waiting on it hung forever, while the blocking
create returned an error.

Spawn each body as an inner task and await it: if it panicked, invoke
the callback with a non-retryable error carrying the panic message, so
the callback still runs exactly once. Guards and flush tickets held by
the body are released as it unwinds.

Also move the shared _async contract into the header docs, where C
callers see it, and rename the nowait tracker types now that _async
ingests use them too.

Co-authored-by: Isaac <no-reply@databricks.com>
Signed-off-by: Dimitrije Đorđević <dimitrije.djordjevic@databricks.com>
A _nowait record rejected in the background is reported once by the
next flush (batch path included), several failures collapse into one,
close reports one no flush has, exactly one of two racing flushes
reports it, and a lane failure keeps its typed, retryable cause. Also
unit-test that the pending-ingest tracker keeps the first error.

Co-authored-by: Isaac <no-reply@databricks.com>
Signed-off-by: Dimitrije Đorđević <dimitrije.djordjevic@databricks.com>
Every multiplexed _async function rejects invalid arguments without
calling back. Async creates free user_data and ack_user_data once on
each failure, report connect failures, stream_count and options ack
rejections through the callback, and report a task panic there too.

Co-authored-by: Isaac <no-reply@databricks.com>
Signed-off-by: Dimitrije Đorđević <dimitrije.djordjevic@databricks.com>
Async creates return before their lanes open and own the headers and
ack user_data. Async ingests report distinct message IDs, copy their
input, return while blocked on capacity, reject bad input without a
callback, and report in-task errors per call. Async wait, flush, close
and get_unacked_records report through their callbacks, keep the handle
valid across free, release the write guard before calling back, and
fail at once while a close is in progress. Flush covers accepted async
ingests, and callbacks fire exactly once under concurrency.

Co-authored-by: Isaac <no-reply@databricks.com>
Signed-off-by: Dimitrije Đorđević <dimitrije.djordjevic@databricks.com>
When a flush or close failed with its own error, it also cleared a
stored background _nowait failure, so a lost-record error could vanish
behind an unrelated retryable one such as a timeout. Keep the stored
failure until a flush or close without its own error returns it.

An _async ingest, wait or flush made while a close was in progress
returned false, unlike the ordinary _async functions, which report every
stream error through the callback. Report it through the callback too;
only invalid arguments return false. The test for that case now expects
one callback with the closing error.

Also rewrap the doc paragraphs the last edits left over-long.

Co-authored-by: Isaac <no-reply@databricks.com>
Signed-off-by: Dimitrije Đorđević <dimitrije.djordjevic@databricks.com>
On a closed mux, explicitly or by a retryable lane failure, each async
reader returns true and calls back once with its blocking counterpart's
error. While a close is in progress the rejected calls send nothing and
leave nothing recoverable. A flush that fails on its own keeps a stored
_nowait failure for the next flush.

Co-authored-by: Isaac <no-reply@databricks.com>
Signed-off-by: Dimitrije Đorđević <dimitrije.djordjevic@databricks.com>
Co-authored-by: Isaac <no-reply@databricks.com>
Signed-off-by: Dimitrije Đorđević <dimitrije.djordjevic@databricks.com>
Co-authored-by: Isaac <no-reply@databricks.com>
Signed-off-by: Dimitrije Đorđević <dimitrije.djordjevic@databricks.com>
Without recovery, the core can report the server's end-of-stream during
close as close's own error, which made tests that expect a clean close
fail now and then under load. Those tests now keep recovery on; tests
that need a terminal lane failure turn it off explicitly.

Co-authored-by: Isaac <no-reply@databricks.com>
Signed-off-by: Dimitrije Đorđević <dimitrije.djordjevic@databricks.com>
The docs said flush, close and get_unacked_records cover every _nowait
record. A _nowait record whose background ingest fails is dropped, and
after a sub-stream failure flush and close return that failure instead
of the stored one, so the record can be missing from the unacked set
with no separate error. Say so, say that retrying the flush does not
bring a dropped record back, and point to the blocking and _async
ingests when every record must be recoverable.

Also report a panicking _nowait ingest like a failed one instead of
silently draining its ticket; reject options->ack_on_* in the async
creates before spawning; move the thread-safety and callback rules into
the emitted header docs; and mark every mux item Beta.

Co-authored-by: Isaac <no-reply@databricks.com>
Signed-off-by: Dimitrije Đorđević <dimitrije.djordjevic@databricks.com>
The thread-safety and callback rules were in both the module doc and
the CZerobusMultiplexedStream doc, and the copies had drifted. The
module doc is not emitted to zerobus.h, so point it at the type doc.
Also rewrap the flush doc and add a test-only payload that panics, so
tests can reach the _nowait and _async panic paths.

Co-authored-by: Isaac <no-reply@databricks.com>
Signed-off-by: Dimitrije Đorđević <dimitrije.djordjevic@databricks.com>
Check that an ordinary stream still delivers acks to the C callbacks in
its options, that an error-only mux ack callback receives failed
records, that flush_async covers ingests blocked on capacity, that an
async ingest releases its ticket and read guard before calling back,
that a flush reports only errors from before it began, and that panics
in _nowait and _async tasks are reported. The FFI unit tests reuse the
mock gRPC server for the panic paths, which need a live mux.

Co-authored-by: Isaac <no-reply@databricks.com>
Signed-off-by: Dimitrije Đorđević <dimitrije.djordjevic@databricks.com>
Async creates reject ack callbacks in options synchronously, without a
callback, and free both user_data once. Stream-count and in-flight
errors arrive through the callback with a null handle. A panicking
_nowait ingest is reported once by the next flush, or by close, and
the mux keeps working.

Co-authored-by: Isaac <no-reply@databricks.com>
Signed-off-by: Dimitrije Đorđević <dimitrije.djordjevic@databricks.com>
An _async ingest wakes its sub-stream's sender, which tokio parks in
the current worker's LIFO slot, where other workers cannot steal it.
The task then called the user's completion callback on the same
worker, so a callback that blocked also held back the send of its own
record, and a flush issued meanwhile waited for it.

Yield once before invoking the callback in the ingest, wait, flush and
close tasks, so the woken work runs first, and document that callbacks
run on a runtime worker and should return quickly. The create and
get_unacked_records tasks wake no sends for the caller and are
unchanged.

Co-authored-by: Isaac <no-reply@databricks.com>
Signed-off-by: Dimitrije Đorđević <dimitrije.djordjevic@databricks.com>
Co-authored-by: Isaac <no-reply@databricks.com>
Signed-off-by: Dimitrije Đorđević <dimitrije.djordjevic@databricks.com>
A blocking _async ingest callback must not hold up its own record: the
record, single or batch, still reaches the server and a flush still
completes while the callback runs.

Co-authored-by: Isaac <no-reply@databricks.com>
Signed-off-by: Dimitrije Đorđević <dimitrije.djordjevic@databricks.com>
Async wait_for_message_id and flush now take the read lock inside
their task, like the blocking calls, instead of failing fast with a
closing error. A caller that saw that error could re-send a record
the close was about to make durable. Async ingests still report a
close in progress through their callback.

Co-authored-by: Isaac <no-reply@databricks.com>
Signed-off-by: Dimitrije Đorđević <dimitrije.djordjevic@databricks.com>
While close or get_unacked_records runs, the async wait and flush now
wait for it. Split the closing test: the async ingests still report
"closing" at once; the wait and flush get no callback until the writer
finishes, then one with the real outcome. Add a test that an async wait
during a close reports success, also for the record the close flushes.

Co-authored-by: Isaac <no-reply@databricks.com>
Signed-off-by: Dimitrije Đorđević <dimitrije.djordjevic@databricks.com>
Sdk::stream_builder() returns a StreamBuilder (Beta) that collects the
table, auth, record format and the StreamOptions fields, then opens
the stream with build(). Setters never throw; validate() and build()
throw a non-retryable ZerobusException. Unset options keep the
StreamOptions defaults, and build() goes through the same native
create path and conversion as create_stream. The builder also
rejects max_inflight_requests 0.

The headers-provider create path now holds its heap shared_ptr in a
unique_ptr until the native call takes it.

Co-authored-by: Isaac <no-reply@databricks.com>
Signed-off-by: Dimitrije Đorđević <dimitrije.djordjevic@databricks.com>
Add stream_builder_test: an unset builder converts like create_stream
with default StreamOptions, and each setter (with a value and with 0)
and the three callback wait states reach their C fields; each bad state
is rejected by validate() and build() with a non-retryable error, and
the last auth and format setters win; copies are independent, a failed
build() leaves the builder usable, the caller's values are copied, and
the builder survives a move of its Sdk; a failed build() releases the
headers provider and ack callback, and an abandoned builder releases
its copies.

Co-authored-by: Isaac <no-reply@databricks.com>
Signed-off-by: Dimitrije Đorđević <dimitrije.djordjevic@databricks.com>
StreamBuilder::multiplexed(n) returns a MultiplexedStreamBuilder
(Beta) holding a copy of the settings. Its build() opens a
MultiplexedStream of n sub-streams to one table through the FFI's mux
create functions. validate() mirrors the core's checks and wording,
and rejects an ordinary ack_callback instead of dropping it.

MultiplexedStream returns MessageId values (negative IDs are valid, so
success comes from the CResult), and every method may run
concurrently. A MultiplexedAckCallback crosses as a heap shared_ptr
that the FFI frees once, after the last sub-stream releases it.

Stream and MultiplexedStream now share the record marshalling helpers
in detail/record_util.hpp. Adds a json_multiplexed example.

Co-authored-by: Isaac <no-reply@databricks.com>
Signed-off-by: Dimitrije Đorđević <dimitrije.djordjevic@databricks.com>
stream_builder_test now also covers the multiplexed builder: its
stream_count, in-flight and ack_callback checks with the core's
wording, the multiplexed(n) snapshot, and the ack and headers bridges
a failed mux build() releases. The setter mapping uses one case with
distinct values and one with zeros, and the copy check reads the
stored table name and descriptor.

multiplexed_ack_callback_test checks the mux ack trampolines (raw IDs
incl. negative, the error message, null user_data, the free hook,
from()), MessageId equality and hash, and that MultiplexedStream is
move-only.

The env-gated integration test gains a 33-lane mux run: a negative
lane-32 ID, wait, flush, nothing unacked before close, is_closed,
every ID reaching the callback, the errors after close and after a
move, the callback lifetime, and both proto overloads.

Co-authored-by: Isaac <no-reply@databricks.com>
Signed-off-by: Dimitrije Đorđević <dimitrije.djordjevic@databricks.com>
The two proto-overload checks now require the core's record type mismatch, which proves each call reached the FFI.

Co-authored-by: Isaac <no-reply@databricks.com>
Signed-off-by: Dimitrije Đorđević <dimitrije.djordjevic@databricks.com>
The ordinary part of the live test called create_stream without options, so the stream defaulted to Proto and the FFI rejected it for having no descriptor. Pass StreamOptions with the JSON record type.

Co-authored-by: Isaac <no-reply@databricks.com>
Signed-off-by: Dimitrije Đorđević <dimitrije.djordjevic@databricks.com>
get_unacked_records() closes the multiplexed stream, so the live test now checks is_closed() is false before it and true after it.

Co-authored-by: Isaac <no-reply@databricks.com>
Signed-off-by: Dimitrije Đorđević <dimitrije.djordjevic@databricks.com>
An empty batch on a MultiplexedStream now crosses the FFI like any
other batch, so a closed mux throws instead of returning nullopt.
validate() also rejects an empty table name and compiled_proto() with
an empty descriptor, and is_closed() is noexcept. The mux error
trampoline no longer lets a failed string copy unwind into the FFI.

Docs: close() and the destructor say how long closing can block,
including callback_wait_policy; the changelog names the two ways the
mux differs from Stream; the README covers mux thread safety. The mux
example now recovers after an ingest failure too. MessageId moves to
message_id.hpp.

Co-authored-by: Isaac <no-reply@databricks.com>
Signed-off-by: Dimitrije Đorđević <dimitrije.djordjevic@databricks.com>
The live test now proves that wait_for_message_id, flush and close
reach the native stream: a wait on a missing lane, close before
recovery, and flush, ingest and an empty batch failing after close. The
ack check counts each ID exactly once instead of skipping when the
callback is gone. It also builds an ordinary stream through the
builder, move-assigns over a live mux, and ingests from four threads on
one mux. The from() test without an error handler now checks that acks
still arrive, and the builder test pins the new table("") and
compiled_proto({}) errors.

Co-authored-by: Isaac <no-reply@databricks.com>
Signed-off-by: Dimitrije Đorđević <dimitrije.djordjevic@databricks.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant