Repository navigation
perf(http): move default streaming to a shared event-driven reactor - #228
Merged
MisterVVP merged 8 commits intoAug 30, 2026
Conversation
MisterVVP
marked this pull request as draft
August 28, 2026 20:12
### Motivation - Replace the previous per-stream blocking libcurl event loop with a single shared non-blocking reactor owned per HTTP client to avoid one blocked I/O worker per stream and to drive socket readiness from the kernel. - Implement a Linux-ready event backend using `epoll`, `eventfd`, and `timerfd` and preserve synchronous `a2a::http::Client::StreamRequest()` semantics while keeping custom requester compatibility. - Authorship: AI agent ### Description - Added a client-scoped `CurlStreamReactor` that owns one `CURLM*`, a reactor thread, a synchronized command queue, active transfer registrations, and shutdown state, and that serializes `Add`/`Cancel`/`Shutdown` commands to the reactor thread (implemented in `src/http/http_client.cpp`). - Implemented Linux readiness using `epoll` + `eventfd` wakeups + `timerfd` and forwarded socket/timer events into `curl_multi_socket_action()` without fixed polling intervals; added a portable fallback that uses libcurl multi wakeups on non-Linux platforms. - Reworked streaming transfer flow: `PerformStreamingTransfer` now enqueues a `Transfer` with the client reactor and waits on the transfer completion condition instead of creating a per-stream `CURLM` and blocking per-stream polling. `Client` now creates/holds a shared reactor (`state_->stream_reactor`). - Removed per-stream `curl_multi_*` ownership/cleanup and updated stream slot acquisition to only create per-easy handle slots; documented the default HTTP reactor behavior in `docs/streaming-usage.md`.
### Motivation - Replace the per-stream blocked worker model with an asynchronous, reactor-driven streaming path so idle default HTTP/JSON and JSON-RPC streams no longer consume a dedicated executor worker. - Ensure no arbitrary user/observer code executes on the libcurl reactor thread and provide per-stream serialized dispatch so slow observers cannot stall unrelated streams. - Make libcurl callback lifetime and cancellation semantics safe for an asynchronous transfer state and preserve the existing synchronous `Client::StreamRequest()` API as a waiting wrapper. - Document the new callback-dispatch model in `docs/streaming-usage.md`. ### Description - Added a shared stream callback dispatch runtime: a fixed `StreamDispatchExecutor` with a small pool and per-stream `SerialStreamDispatch` queues to serialize per-stream callbacks off the reactor thread. (new code in `src/http/http_client.cpp`). - Introduced heap-owned, lifetime-safe `AsyncStreamState` that holds easy-handle, headers, buffers, callback wrappers, cancellation registration, and a transfer `lifetime` object so libcurl callbacks reference only heap-owned state that stays valid until reactor completion. (new code in `src/http/http_client.cpp`). - Extended `a2a::http::Client` with `StartStreamRequest(...)` to register an asynchronous reactor transfer and invoke a `StreamCompletion` callback on completion; made the original synchronous `StreamRequest(...)` a small wrapper that waits on `StartStreamRequest`. (changes in `include/a2a/http/http_client.h` and `src/http/http_client.cpp`). - Made the libcurl reactor `CurlStreamReactor::Transfer` report completions via an `on_complete` callback and stopped performing heavyweight work in socket/timer callbacks; reactor only queues add/remove/complete operations. (changes in `src/http/http_client.cpp`). - Updated default transports to use the async path by default while preserving compatibility with custom synchronous requesters: `HttpJsonTransport` and `JsonRpcTransport` now create and use a default async `a2a::http::Client` for streaming, falling back to the executor-worker compatibility path if a custom synchronous requester was injected. (changes in `src/client/transport/http_json_transport.cpp`, `src/client/transport/json_rpc_transport.cpp`, and headers). - Added conversion helpers between transport-local `HttpRequest/HttpClientResponse` and `a2a::http::Request/Response` for the bridge, and updated `StartSseStream` call sites to use the async client when available. (changes in `src/client/transport/*`). - Updated streaming documentation to state that observer callbacks are serialized per-stream on a shared dispatch executor and never run on the libcurl reactor thread. (change in `docs/streaming-usage.md`).
### Motivation - Remove stale persistent "last callback thread" semantics that could cause incorrect Cancel() waits when dispatch workers are reused by replacing it with a scoped RAII callback execution marker. - Provide explicit shutdown coordination for the default libcurl-backed async HTTP client so transports reject new streams, cancel active streams, wake/drain the reactor, detach transfers, and wait for dispatched observer work before returning. - Authorship: this change set was produced with AI agent assistance and follows repository contribution and documentation requirements. ### Description - Introduced `StreamHandle::State::CallbackExecutionScope` (RAII) and replaced `execution_thread_id` with `callback_thread_id`, and updated `Cancel()` to only skip waiting when the same stream's callback is actively running. - Added `a2a::http::Client::Shutdown()` and `CurlStreamReactor::Shutdown()` plus bookkeeping (`active_streams`, `streams_finished`, `shutting_down`) to reject new streams and wait for active streams to finish; `AsyncStreamState` marks registration and decrements the active counter on destruction. - Added transport-level shutdown hooks and shutdown guards (`HttpJsonTransport::Shutdown`, `JsonRpcTransport::Shutdown`, and `shutting_down_` flags) so default async clients cannot be used once shutdown begins. - Updated streaming documentation to describe scoped callback execution/cancellation semantics, shared reactor behavior, and explicit transport shutdown guarantees. --------- Co-authored-by: Vladimir Pavlov <[email protected]>
MisterVVP
marked this pull request as ready for review
August 30, 2026 19:17
MisterVVP
merged commit Aug 30, 2026
f00340c
into
dev-optimize-streaming-response-latencies
31 of 32 checks passed
MisterVVP
deleted the
dev-make-libcurl-streaming-cancellation-event-driven
branch
August 30, 2026 19:26
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Motivation
Issue #209 identified concurrency-related first-event and completion latency in the existing HTTP+JSON and JSON-RPC streaming paths.
The initial work reduced SSE parsing and JSON-RPC conversion overhead, but default libcurl streaming still relied on synchronous per-stream execution and cancellation polling. That model also made stream cancellation, shutdown, and worker growth increasingly expensive as concurrent stream counts increased.
This PR moves the default HTTP streaming path onto a shared event-driven network reactor while preserving the existing public synchronous streaming APIs and compatibility with injected synchronous requesters.
Part of #209.
What changed
Shared libcurl streaming reactor
Default HTTP streaming clients now use one client-scoped
CURLMmulti handle and one network reactor thread for multiple concurrent streams.On Linux the reactor is driven by:
CURLMOPT_SOCKETFUNCTION;CURLMOPT_TIMERFUNCTION;curl_multi_socket_action();epoll;eventfdfor Add/Cancel/Shutdown wakeups;timerfdfor libcurl timer deadlines.This removes fixed-interval polling from the default Linux streaming path.
Other platforms retain libcurl's portable multi-poll/wakeup path.
The reactor is initialized lazily and is the only thread that adds or removes streaming easy handles.
Asynchronous default HTTP transport dispatch
Default HTTP+JSON and JSON-RPC transports now register streams asynchronously with the shared HTTP client rather than occupying one
StreamWorkerExecutorworker for the lifetime of every stream.Application callbacks are dispatched away from the reactor through a fixed shared callback executor.
Per-stream dispatch remains serialized so event ordering is preserved even when callbacks run on different shared workers.
Injected custom synchronous stream requesters retain their existing worker-based compatibility path.
Bounded callback backlog
A slow observer cannot block the libcurl reactor.
Each stream has bounded pending callback work:
If a stream exceeds its limit, only that stream is failed and cancelled.
There is no fixed SDK limit on the number of active streams.
Cancellation and shutdown correctness
Cancellation is now explicitly connected to the active reactor transfer so an idle stream can wake and cancel immediately instead of waiting for periodic polling or unrelated socket activity.
The lifecycle implementation also covers:
A2AClient::Destroy()from an observer callback;Callback execution state is scoped with RAII rather than retaining a stale worker-thread identity across callbacks.
Streaming scalability validation
The performance driver now exercises concurrent streams through one shared default client.
For HTTP+JSON and JSON-RPC, client-process thread count remains constant across:
This verifies that the default client no longer grows one SDK network/stream worker per active HTTP stream.
Dedicated local-cancellation benchmark
Add
IdleStream_ClientCancellationLatency.The scenario:
StreamHandle::Cancel()call.It does not invoke protocol-level
CancelTaskand does not include server terminal-event delivery.At concurrency 64 on the final implementation:
Streaming latency versus #223
The comparison uses the normal in-memory wire-performance artifacts from:
33108036968, headf26c4fab7d0ee56075943546cc688688ba5f317f33321185837, head33b9c645fd5b38719b95b88d9a11bcdf3243f44dBoth are single GitHub-hosted runner executions, so gRPC is included as a
same-run control. The #228 runner was materially slower on gRPC, therefore
small raw cross-run throughput/latency changes should not be overinterpreted.
SendStreamingMessage_FiniteStream, concurrency 64Despite the materially slower #228 runner, HTTP+JSON still improves c64
first-event p95 by 19%, while JSON-RPC improves both first-event and completion
p95 by approximately 36–40%.
SubscribeToTask_FirstEventLatency, concurrency 64The subscription first-event result is the clearest evidence for the shared
reactor/dispatch change: HTTP+JSON and JSON-RPC fall below 1.3 ms at c64 even
while the same-run gRPC control is slower than the #223 baseline.
Performance-runner shutdown diagnostics
Wire-performance SUT shutdown failures are now distinguished from missing HTTP reuse diagnostics.
The runner:
HTTP reuse diagnostics are emitted deterministically during graceful shutdown rather than implicitly depending on connection-thread destruction timing.
Compatibility
The change preserves:
A2AClientstreaming APIs;The opt-in asynchronous public API tracked separately by #169 is not introduced here.
The Windows-specific native readiness backend remains separate follow-up work; non-Linux platforms currently use libcurl's portable multi wakeup path.