Skip to content

perf(http): move default streaming to a shared event-driven reactor - #228

Merged
MisterVVP merged 8 commits into
dev-optimize-streaming-response-latenciesfrom
dev-make-libcurl-streaming-cancellation-event-driven
Aug 30, 2026
Merged

MisterVVP merged 8 commits into
dev-optimize-streaming-response-latenciesfrom
dev-make-libcurl-streaming-cancellation-event-driven

Conversation

@MisterVVP

@MisterVVP MisterVVP commented Aug 28, 2026 •

Copy link
Copy Markdown
Owner

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 CURLM multi 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;
  • eventfd for Add/Cancel/Shutdown wakeups;
  • timerfd for 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 StreamWorkerExecutor worker 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:

  • up to 256 pending callbacks;
  • up to 4 MiB of pending body data.

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:

  • repeated and concurrent cancellation;
  • cancellation racing remote completion;
  • cancellation from the stream's own callback;
  • cancellation of one stream without affecting peers;
  • shutdown with active streams;
  • A2AClient::Destroy() from an observer callback;
  • stream start racing shutdown;
  • prevention of reactor recreation after shutdown begins;
  • suppression of new callbacks after shutdown;
  • safe reusable stream-slot lifetime.

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:

Concurrent streams Client process threads
1 6
16 6
64 6

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:

  1. creates the task;
  2. establishes a real subscription;
  3. waits for the first event;
  4. measures only the synchronous local StreamHandle::Cancel() call.

It does not invoke protocol-level CancelTask and does not include server terminal-event delivery.

At concurrency 64 on the final implementation:

Transport cancellation p95 cancellation p99 Errors
gRPC 4.67 ms 6.64 ms 0
HTTP+JSON 0.41 ms 0.66 ms 0
JSON-RPC 0.49 ms 0.92 ms 0

Streaming latency versus #223

The comparison uses the normal in-memory wire-performance artifacts from:

Both 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 64

Transport #223 first-event p95 #228 Change #223 completion p95 #228 Change
gRPC 7.58 ms 11.53 ms +52.0% 10.24 ms 15.68 ms +53.2%
HTTP+JSON 15.96 ms 12.86 ms -19.4% 16.01 ms 14.53 ms -9.2%
JSON-RPC 31.67 ms 18.93 ms -40.2% 31.74 ms 20.37 ms -35.8%

Despite 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 64

Transport #223 first-event p95 #228 Change
gRPC 8.38 ms 10.67 ms +27.3%
HTTP+JSON 8.63 ms 0.75 ms -91.3%
JSON-RPC 17.61 ms 1.20 ms -93.2%

The 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:

  • gives the SUT a bounded graceful-shutdown interval;
  • reports graceful-shutdown failure explicitly;
  • force-kills only as cleanup;
  • keeps missing HTTP diagnostics as a separate failure condition.

HTTP reuse diagnostics are emitted deterministically during graceful shutdown rather than implicitly depending on connection-thread destruction timing.

Compatibility

The change preserves:

  • existing A2AClient streaming APIs;
  • HTTP+JSON and JSON-RPC streaming semantics;
  • event ordering;
  • cancellation behavior;
  • terminal/error delivery;
  • custom synchronous HTTP requester support;
  • gRPC streaming architecture.

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.

@MisterVVP MisterVVP added the codex Automatic label added by codex agent. Should not be used label Aug 28, 2026 — with ChatGPT Codex Connector
@MisterVVP MisterVVP self-assigned this Aug 28, 2026
@MisterVVP MisterVVP added AI agent AI agent contribution performance Performance improvement related tasks based on benchmark results. Performance tests changes. and removed codex Automatic label added by codex agent. Should not be used labels Aug 28, 2026
@MisterVVP
MisterVVP marked this pull request as draft August 28, 2026 20:12
MisterVVP and others added 3 commits August 29, 2026 11:54
### 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 MisterVVP changed the title perf(http): wake libcurl polls on stream cancellation perf(http): move default streaming to a shared event-driven reactor Aug 30, 2026
@MisterVVP
MisterVVP marked this pull request as ready for review August 30, 2026 19:17
@MisterVVP
MisterVVP merged commit f00340c into dev-optimize-streaming-response-latencies Aug 30, 2026
31 of 32 checks passed
@MisterVVP
MisterVVP deleted the dev-make-libcurl-streaming-cancellation-event-driven branch August 30, 2026 19:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

AI agent AI agent contribution performance Performance improvement related tasks based on benchmark results. Performance tests changes.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant