Repository navigation
perf(streaming): reduce synchronous streaming startup and first-event latency - #223
Conversation
### Motivation - Finite HTTP and JSON-RPC SSE responses were being fully buffered server-side, delaying first-event delivery and regressing finite-stream first-event latency. - Make finite `SendStreamingMessage` responses truly incremental so the first event is serialized and sent as soon as `ServerStreamSession::Next()` produces it while preserving envelope/ordering/semantics. ### Description - Write response status line and headers (including `Transfer-Encoding: chunked`) to the transport immediately for reusable streaming responses, then invoke the stream writer; emit the terminal `0\r\n\r\n` only after successful completion and avoid emitting it if the writer fails (`src/server/transport/http_adapter.cpp`). - Rework `ChunkedByteTransport` to avoid large temporary concatenations by formatting the chunk-size into stack storage and performing direct prefix, payload, and terminator writes to the underlying transport (`src/server/transport/http_adapter.cpp`). - Replace REST finite-stream buffering in `BuildStreamingResponse()` with a `stream_writer` that pulls one `StreamResponse`, serializes exactly one SSE event, writes it immediately, then requests the next event; session lifetime is moved into writer-owned state (`src/server/transport/rest_transport.cpp`). - Replace JSON-RPC finite-stream buffering with `StreamFiniteJsonRpcSseEvents()` that builds one JSON-RPC success envelope per event (preserving request `id`), emits exactly one SSE event, writes it immediately, and repeats until completion (`src/server/transport/json_rpc_server_transport.cpp`). - Added deterministic unit tests that assert headers are visible before the first body event, that finite REST streams write each event before requesting the next and propagate producer failure, and that JSON-RPC finite streams preserve request `id` and stream incrementally (`tests/unit/http_adapter_test.cpp`, `tests/unit/rest_transport_test.cpp`, `tests/unit/json_rpc_server_transport_test.cpp`). - Did not add coroutine machinery because `ServerStreamSession::Next()` already provides the correct incremental pull semantics and `HttpByteTransport::Write()` remains synchronous.
… idle executor (#226) ### Motivation - Reduce per-stream OS-thread creation/destruction to lower synchronous streaming startup and high-concurrency first-event latency by reusing worker threads. ### Description - Add an internal-only elastic `StreamWorkerExecutor` that immediately creates a worker when no idle worker is available and retains at most `kMaximumRetainedIdleStreamWorkers` idle workers (default 64). - Refactor `StreamHandle` private state to use a per-stream completion token (`completion_mutex`, `completion_condition`, `execution_thread_id`, `completed`) so handles wait on task completion instead of owning an OS thread, preserving `Cancel()`, `IsActive()`, move semantics and avoiding self-join deadlocks. - Wire the executor into HTTP+JSON and JSON-RPC synchronous streaming paths (`StartSseStream` / `SendStreamingMessage` / `SubscribeTask`) so sessions are executed on executor workers and per-stream completion is signalled on task exit; leave gRPC worker model unchanged. - Add deterministic unit tests covering sequential reuse, concurrent independence, bounded idle retention, and shutdown behavior, and update build/test targets and CMake accordingly.
|
Switching from polling to event-driven approach next. |
…228) ## 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: - #223: CI `33108036968`, head `f26c4fab7d0ee56075943546cc688688ba5f317f` - #228: CI `33321185837`, head `33b9c645fd5b38719b95b88d9a11bcdf3243f44d` 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. --------- Co-authored-by: Vladimir Pavlov <[email protected]>
…nite-stream diagnostics. Optimize sse event delivery (#233)
### Motivation A concurrent `StartStreamRequest()` / `Shutdown()` race could create async stream state and a reactor, then reject registration after shutdown had already won. In that path, retained transfer lifetime state and completion callbacks could keep reactor-related objects alive longer than intended. The previous callback-worker scaling experiment did not demonstrate a reliable HTTP/JSON-RPC throughput benefit, so that change has been reverted. ### Changes - Clear the rejected transfer's retained lifetime state and completion callback when shutdown wins before stream registration. - Restore the shared stream dispatch executor to its original bounded four-worker configuration. - Replace the flaky process-wide thread-count shutdown assertion with deterministic libcurl reactor lifecycle counters. - Verify that concurrent stream starts cannot create or leak a replacement reactor after shutdown wins. - Keep future stream starts rejected after shutdown.
### Motivation The HTTP+JSON and JSON-RPC subscription paths now achieve very low first-event latency, but high-concurrency terminal/completion throughput still needs phase-level attribution. Add internal profiling diagnostics that can be enabled for optimized performance investigations without exposing diagnostics through the public SDK or shipping the instrumentation in normal builds. ### Changes - Add build-private subscription phase diagnostics behind `A2A_ENABLE_SUBSCRIPTION_DIAGNOSTICS`, OFF by default. - Keep diagnostics implementation and headers internal to the repository rather than the installed SDK API. - Compile instrumentation into SDK targets only for explicitly enabled testing/performance builds. - Retain `A2A_SUBSCRIPTION_DIAGNOSTICS=1` as the runtime collection switch inside an instrumentation-enabled build. - Measure clearly named server phases including total cancel execution, terminal store update, terminal publication, subscriber resume, serialization, framing, and HTTP delivery. - Measure client terminal observer and completion callback execution separately. - Emit server and client diagnostic snapshots independently because the wire benchmark client and TCK SUT run in separate processes. - Extend the performance runner to collect the two diagnostic streams separately. - Add tests for diagnostic aggregation/reporting and verify that normal SDK builds contain no subscription-diagnostics symbols or diagnostic environment-variable tokens. - Preserve the existing coroutine subscription architecture, shared libcurl reactor, bounded callback dispatch, and public APIs. --------- Co-authored-by: Vladimir Pavlov <[email protected]>
69334c8 to
b0ceda6
Compare
## Summary Follow-up to #223. This PR unifies the default libcurl unary and streaming HTTP request paths onto the same bounded process-wide `CURLM` reactor pool. Previously, streaming requests used the shared `CURLM` reactors while unary requests used reusable easy handles with `curl_easy_perform()`. As a result, a common unary → stream sequence could cross two independent libcurl connection caches and lose an otherwise reusable HTTP connection. The new implementation preserves the synchronous `SendRequest()` API while executing its network transfer through the same event-driven request engine used by streaming. ## What changed ### Unified CURLM request engine Unary `RequestSlot`s now retain a reactor assignment in addition to their reusable easy handle. `Client::SendRequest()` configures the request as before, submits the easy handle to its assigned `CURLM` reactor, and synchronously waits for that transfer to complete. No public HTTP or A2A client API changes are required. ### Unary → streaming connection-cache affinity Each client establishes a primary reactor affinity for its first unary and streaming handles. This allows the common sequence: `unary request -> streaming request` to use the same `CURLM` connection cache and reuse an existing HTTP connection when the server and protocol allow it. Additional concurrent unary and streaming handles continue to be distributed across the bounded reactor pool rather than concentrating all work on one reactor. ### Bounded global resource usage Both unary and streaming requests now use the existing process-wide pool of at most four `CURLM` reactors. Reusable easy-handle slots retain their reactor assignments, preserving connection-cache locality while keeping reactor/thread growth bounded as more SDK clients are created. ### Regression coverage A dedicated loopback test performs a unary request followed by a streaming request through the same `a2a::http::Client` and verifies that both operations use a single accepted TCP connection. Existing concurrent unary-request coverage continues to verify that moving unary requests onto `CURLM` does not serialize independent requests behind one shared easy handle. Performance documentation has been updated to describe the unified request topology. Co-authored-by: Vladimir Pavlov <[email protected]>
|
Improvements are clear now. Code review shall follow. |
|
There are plenty of problems here, so now, after perf. goal is achieved - it's time to clean the code up. |
|
@codex review this PR again |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4427376a99
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
### Motivation - Prevent the internal diagnostics reset request from contaminating measured HTTP counters and simplify the TCK SUT bootstrap responsibilities. - Make the subscription-symbol-inspection test portable to MSVC/Windows toolchains instead of assuming GNU `nm`. - Reduce cognitive complexity in `tck_sut.cpp` by extracting store and HTTP server implementation details into focused components. ### Description - Extracted HTTP server and diagnostics implementation into `tests/sut/tck_sut_http_server.cpp/.h` and introduced `TckHttpServer` as a small RAII-style helper that owns listener, accept loop, connection workers, FD bookkeeping, and diagnostic counters. - Moved store/environment parsing and store-bundle creation into `tests/sut/tck_sut_store.cpp/.h` and exposed only `CreateStoreBundleFromEnvironment()` to the bootstrap caller. - Implemented explicit detection of the diagnostics-reset request (`kDiagnosticsResetPath`) inside the HTTP server and handled it by executing the reset and returning `204 No Content` while skipping all HTTP accounting for that request so per-connection measurement state is not corrupted. - Reworked `tests/CMakeLists.txt` to build the new sources into the `tck_sut` target and to select a platform-appropriate symbol-inspection tool in CMake; the selected tool and its arguments are passed to the Python test. - Rewrote `tests/scripts/subscription_diagnostics_build_test.py` to accept a `--symbol-tool` and `--symbol-argument` (no platform assumptions) and added `tests/scripts/subscription_diagnostics_build_test_test.py` unit tests for command construction. - Added an integration-style deterministic test `tests/scripts/http_diagnostics_reset_test.py` that opens a persistent connection, sends the internal diagnostics reset, then a measured RPC over the same connection and asserts the reset did not affect diagnostics counts. - Preserved SUT behavior and shutdown ordering: stop subscriptions → shutdown active sockets → join HTTP workers → emit HTTP diagnostics → emit subscription diagnostics → stop gRPC.
|
@codex pls review this PR again |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 30021791f9
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
|
@codex review this PR again |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ec21c24ec4
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
|
@codex review this PR again |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 132a4a5ef1
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
|
@codex review this PR |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 2164132ac8
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
|
@codex review this PR |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 0d5d10e9aa
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
|
@codex review this PR |
|
Codex Review: Didn't find any major issues. Breezy! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
|
Final refactoring incoming. |
Summary
Closes #209.
This PR reduces startup, first-event, completion, and cancellation overhead in the existing synchronous/public streaming APIs, with a particular focus on HTTP+JSON and JSON-RPC SSE streaming under concurrency.
The default HTTP streaming path now uses a bounded, process-wide event-driven libcurl architecture instead of creating one OS worker thread per stream. Network progress is separated from application callback execution while preserving the existing
A2AClient,StreamHandle, transport, observer, and server-streaming APIs.What changed
Shared event-driven HTTP execution
Default HTTP+JSON and JSON-RPC streaming now use shared
CURLMreactors instead of one blocking libcurl worker per stream.epoll,eventfd, andtimerfd.Bounded callback dispatch
Application observer callbacks run away from the network reactor on a bounded shared executor.
Streaming latency and allocation reductions
The streaming path also reduces avoidable work by:
Cancellation and lifecycle correctness
The implementation now covers and tests:
A2AClient::Destroy()with active streams;Custom injected synchronous stream requesters retain their compatibility path and continue using
StreamHandle-owned workers.Diagnostics and performance tooling
The performance suite now includes wire-level measurements and diagnostics for:
Diagnostics are reset at the measurement boundary so warmup/setup traffic is not attributed to measured rows.
Implementation cleanup
The low-level HTTP implementation was split by responsibility:
src/http/http_client.cpp— public client lifecycle and unary orchestration;src/http/http_client_curl.cpp— libcurl request/response configuration and parsing;src/http/http_client_streaming.cpp— streaming state, callback dispatch, cancellation, and completion;src/http/curl_stream_reactor.cpp— event-driven reactor implementation;src/http/http_client_internal.h— private cross-translation-unit implementation types.This reduces
http_client.cppfrom roughly 52 KB to roughly 9 KB without changing public behavior.Performance
Comparison methodology
For acceptance validation, this table compares complete normal-CI artifacts produced with the same performance configuration.
Baseline:
e2bb73e18a6910bb1c94213872f7a0f74b160ffd31522741927perf-artifacts-normal/9114133095PR #223 final head:
1fa92d8ffb7f0965db7696c56df88d52ee0eb56734695805370perf-artifacts-normal/10298841665Configuration:
The table below shows the acceptance-critical in-memory, wire-level, concurrency-64 coordinate.
All target rows completed with zero operation errors.
The final normal performance artifact contains 568 result rows / 568,000 measured operations with zero operation errors.
The PostgreSQL c64 verification also improved the target HTTP streaming coordinates versus the same PR #204 artifact:
Validation
Current head
1fa92d8ffb7f0965db7696c56df88d52ee0eb567passes:The mandatory TCK workflow reports no mandatory requirement failures for either backend.
Issue #209 acceptance
The PR meets the issue's functional and performance goals:
The separate opt-in asynchronous API tracked by #169 remains out of scope.