Skip to content

perf: optimize async client and server - #334

Closed
MisterVVP wants to merge 14 commits into
release/v0.6.0from
perf/grpc-client-streaming
Closed

MisterVVP wants to merge 14 commits into
release/v0.6.0from
perf/grpc-client-streaming

Conversation

@MisterVVP

@MisterVVP MisterVVP commented Nov 13, 2026 •

Copy link
Copy Markdown
Owner

Summary

Improve async SDK thread scaling and reduce dispatch/HTTP overhead on release/v0.6.0.

  • Replace channel-backed gRPC per-stream blocking readers with native ClientReadReactor callbacks. Preserve observer ordering, one outstanding read, backpressure, cancellation and shutdown; keep the compatibility reader for injected RpcClient implementations.
  • Use direct native dispatch for built-in HTTP JSON/JSON-RPC bindings, coalesce headers with the first SSE event, reuse owned chunk buffers, and keep application callbacks off network reactors.
  • Reuse SDK completion workers for internal HTTP adapter continuations and avoid unnecessary deadline-timer notifications, while preserving deferred public initiation and independent cancellation scopes.
  • Share immutable dispatch configuration. Reserve admission under a short lock, construct calls outside the registry lock, and roll back reservations on failure. Under concurrent HTTP load, unary response encoding can be posted to the HTTP application executor.
  • Emit application/a2a+json for 1.0.1 HTTP+JSON protocol errors. The conformance fixture accepts text/plain, application/json and unlabelled parts; the performance fixture retains wildcard opaque-input support.

No PostgreSQL storage implementation changes. Coverage includes cancellation/cleanup races, owner destruction, retained streams, connection reuse, output bounds and cleanup that outlives the HTTP listener.

Current CI performance

Source: CI #1559, normal + sustained artifact.

The artifact tests merge commit d078b4f (head b00d667 over release base 2e3f388). The direct-parent comparison uses CI #1558, merge 4a2b0a0 (head 122510b over the same base). Both sustained suites use Release/in-memory, two logical CPUs per process, 250 ms warmup, three seconds per case and one measurement per configuration.

Concurrency 64: hold the client API constant

Unary rows use the async client against both server modes. Stream rows use the same observer client against both server modes; its raw client-mode label is sync.

Ratio = current async-server / current sync-server ops/s. The last column compares the current async-server result with the same client/scenario on the direct parent.

Transport Operation Client Sync server ops/s Async server ops/s Server ratio Async vs parent
gRPC GetTask async 24,870 30,754 1.24× −2.5%
gRPC ListTasks async 19,493 20,450 1.05× −1.4%
gRPC Finite stream observer 14,416 21,158 1.47× −3.2%
HTTP JSON GetTask async 22,031 18,427 0.84× +1.5%
HTTP JSON ListTasks async 13,013 12,743 0.98× −1.7%
HTTP JSON Finite stream observer 16,746 15,994 0.96× +1.7%
JSON-RPC GetTask async 10,588 10,813 1.02× +1.9%
JSON-RPC ListTasks async 10,805 11,417 1.06× −0.5%
JSON-RPC Finite stream observer 15,679 15,076 0.96× +0.9%

The latest commit shows small, mixed changes, not a broad measured throughput gain. Unchanged fully synchronous c64 controls also move by approximately −4.7% to +0.5% between runs. Separate single-pass CI runners cannot establish causation for these small deltas.

Current c64 GetTask p99, with the async client fixed, is 4.79 → 3.20 ms for gRPC, 5.88 → 6.03 ms for HTTP JSON and 14.79 → 9.89 ms for JSON-RPC when switching the server from sync to async. Tail-latency benefits are therefore also workload-dependent.

Concurrency 1 and resources

C1 GetTask p50 with the same async client is 112 → 147 µs (gRPC), 155 → 254 µs (HTTP JSON) and 232 → 353 µs (JSON-RPC) when switching the server to async. Finite-stream p50 is 175 → 388 µs for HTTP JSON and 193 → 400 µs for JSON-RPC. The c1 and HTTP streaming overhead remains unresolved.

Thread scaling remains useful: c64 GetTask sampled server-thread peaks fall 65 → 30 for gRPC and 74 → 22 for HTTP with the async client held constant. Resource samples include setup/warmup and are not per-request measurements.

Both revisions report 764 normal rows and 78 sustained rows, with zero operation errors. Performance jobs are report-only; green status does not enforce a speedup or regression threshold.

Client coverage and interpretation

  • The broad normal matrix sets both server modes but leaves client modes at the runner default, sync.
  • The focused sustained step explicitly sets A2A_PERF_CLIENT_MODES=sync,async. Its 24 async-client rows cover GetTask and paginated ListTasks across all three transports at c1/c64, paired with both server modes.
  • Callback-client benchmark coverage currently extends only to GetTask/ListTasks scenarios, even though the SDK offers more async unary methods. Streaming uses the common observer API and is measured once per server mode; its sync label does not mean a separate blocking streaming implementation was selected.
  • PostgreSQL client/server async comparisons are not measured by this matrix. In-process benchmarks bypass transport servers.

Validation and remaining work

Windows/macOS builds, ASan/UBSan, ThreadSanitizer, interoperability, coverage and performance jobs have completed successfully in the linked run. The main Linux job was still running clang-tidy when reviewed; consult the live checks for its final result. TCK Conformance #1417 passed with the restricted-input conformance fixture. The earlier MIME and wildcard-fixture failures are resolved without modifying upstream TCK assertions.

Next experiments should isolate response-encoding offload versus direct encoding under equal CPU budgets, including mixed unary/idle-stream traffic. The current pending-request heuristic includes idle streams and is not a measurement of encoding CPU pressure. Profile the remaining HTTP dispatch and SSE write/acknowledgment costs before further scheduler changes. Preserve bounded admission, socket-acceptance backpressure and off-network application execution.

Authorship and AI usage

  • Contains substantive content written by a human
  • Contains substantive content generated by an AI agent

@MisterVVP MisterVVP added AI agent AI agent contribution performance Performance improvement related tasks based on benchmark results. Performance tests changes. labels Nov 13, 2026 — with ChatGPT Codex Connector
@MisterVVP MisterVVP self-assigned this Nov 13, 2026
Bound HTTP callback batches and add optional queue-wait diagnostics. Avoid copying JSON-RPC streaming responses, update Windows gRPC dependencies, and ignore generated validation artifacts.

AI-assisted contribution: implementation, tests, and documentation generated with Codex.
Use 1.41.0 because the vcpkg version database has no entry for 1.38.0. This preserves the Windows callback support requirement.
## Summary

Stacked on #334 (`perf/grpc-client-streaming`, `df97c3c`). Keep this
draft until CI's sync/async measurements have been reviewed.

HTTP unary responses currently queue an SDK completion after decoding on
an SDK completion worker. Allow those internal HTTP JSON/JSON-RPC
adapters to finish on the current completion worker, removing that
second queue hop. Public initiation still defers callbacks, including
nested calls started from callbacks; reactor threads never run
application completions.

- Keep a safe earlier timeout wait after completion, and compare new
deadlines with that actual wait instead of the current map head.
Completing calls and later admissions no longer wake the timer
unnecessarily; earlier deadlines and shutdown still wake it.
- Reuse the SSE encoder's owned string when adding HTTP chunk framing.
Let ready socket writes complete on the network executor immediately,
while application write acknowledgments still post back to the
application executor. Preserve output limits, socket-acceptance
backpressure, cancellation and connection reuse.
- Cover nested initiation, continuation cleanup after scope
destruction/throwing callbacks, and exact chunk framing. Document the
threading behavior. Retain independent HTTP-client/SDK cancellation
scopes.

### Shared-executor experiment

Also tested sharing the HTTP application and native dispatcher executor
and resuming pending mailbox continuations without an extra post. A
two-worker shared pool reduced the existing four-worker application
budget and hurt concurrent unary throughput. Matching the four-worker
budget restored throughput to roughly baseline, without a consistent
benefit. Leave that executor API, ownership/drain plumbing and SUT
wiring out of this patch.

No PostgreSQL, dependency, benchmark-runner or CI workflow changes. No
benchmark artifacts are committed.

## Local measurements

Exact parent binaries versus this branch, Release/in-memory, 250 ms
warmup and three seconds per case, concurrency 1 and 64, one pass per
distinct configuration. The local host has a two-CPU quota, with one CPU
assigned to each process; CI has two CPUs per process. These are local
experiment results, not new CI results or statistical proof. Controls
also fluctuate.

All throughput columns below are at c64. Unary async columns use both
async client and server; streams use the same observer client and
compare server modes. The sync column uses this branch's synchronous
mode.

| Transport | Operation | Sync ops/s | Parent async ops/s | New async
ops/s | New/parent |
| --- | --- | ---: | ---: | ---: | ---: |
| HTTP JSON | GetTask | 12,507 | 14,440 | 14,669 | 1.02× |
| HTTP JSON | ListTasks | 7,593 | 9,626 | 9,792 | 1.02× |
| HTTP JSON | Finite stream | 12,089 | 12,020 | 11,833 | 0.98× |
| JSON-RPC | GetTask | 5,766 | 7,904 | 7,589 | 0.96× |
| JSON-RPC | ListTasks | 6,837 | 8,480 | 7,982 | 0.94× |
| JSON-RPC | Finite stream | 11,001 | 11,807 | 11,950 | 1.01× |

C1 full-async GetTask p50: HTTP JSON **230 → 231 µs**, JSON-RPC **331 →
328 µs**. ListTasks: **305 → 295 µs** and **352 → 428 µs**. Finite
streams: **279 → 276 µs** and **283 → 290 µs**. Subscription and
idle-cancellation cases are included in the 56-row comparison, with zero
errors in both revisions.

Holding the **synchronous server constant** isolates the client
comparison: c1 async-client GetTask p50 is **192 → 179 µs** for HTTP
JSON and **274 → 268 µs** for JSON-RPC. Its measured gap relative to the
synchronous client narrows **14 → 7 µs** and **10 → 4 µs**,
respectively. Async-client ListTasks p50 is **253 → 246 µs** and **296 →
283 µs**. This is consistent with lower client overhead; the larger
remaining c1 penalty appears when switching the server to async.

The additional eight-row gRPC GetTask check also has zero errors: c64
full-async throughput **32,944 → 33,341 ops/s (1.01×)** and p99 **4.066
→ 4.705 ms**.

A separate syscall trace isolates the reduced machinery: for **500
successful async HTTP JSON GetTask calls** per driver, using the same
new server, the client's deadline thread made **507 → 1 timed futex-wait
calls**. Completion-worker condition-variable futex-wait calls fell
**1,004 → 504**, consistent with removing the extra delivery hop. Traced
timings are excluded from the throughput table.

**This does not resolve the c1 or HTTP streaming performance gap.** The
trace confirms less scheduling work, but there is no broad measured
throughput win: HTTP concurrent unary improves slightly, JSON-RPC
concurrent unary declines in this pass, and streams remain near
baseline. Unmodified fully synchronous c64 controls also range from
**0.87–1.01×** their earlier results, so these single-pass differences
cannot establish causation. CI results should determine whether each
fast path is worth retaining. Further work needs profiling of the HTTP
application/dispatcher and stream handoffs; both synchronous and
asynchronous HTTP clients already share the libcurl-multi reactor.

## Validation

- Final `./scripts/verify_changes.sh`: **passed (exit 0)**; full build,
**1,199 CTest cases with zero failures and three expected skips**, and
all **190 source/test/example lint checks** passed.
- CI GoogleTest 1.14 / clang-tidy 19 preflight passes for the modified
tests.
- ASan/UBSan with leak detection: **98 focused tests passed, one
expected skip**, no sanitizer findings.
- Mandatory TCK (`pytest -m must`, all three transports, upstream
checkout unchanged): **215 passed, 14 skipped, 34 deselected**, zero
failed MUST checks. The upstream catalogue still lists
unimplemented/manual checks; this is not a claim of 100% catalogue
coverage. The separate existing MUST/SHOULD Content-Type contradiction
in #328 is unchanged.
- Required performance smoke: **54 rows, zero errors**. Exact CI
formatting and `mdbook build book` pass.
- No dependency changes. OSV scanning was attempted; its API is blocked
with HTTP 403, so vulnerability status remains unverified.

## Authorship and AI usage

- [ ] Contains substantive content written by a human
- [x] Contains substantive content generated by an AI agent

## Checklist

- [x] `./scripts/verify_changes.sh` passed locally
- [x] Docs updated
@MisterVVP

Copy link
Copy Markdown
Owner Author

@codex review this PR

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-20T06:55:31.090146Z 5202055 Manual request
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

Reviewed commit: 81473a1c91

ℹ️ 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".

@MisterVVP MisterVVP changed the title perf(grpc): use native callbacks for client streams perf: optimize async client and server Nov 18, 2026
@MisterVVP

Copy link
Copy Markdown
Owner Author

@codex review this PR

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b00d667598

ℹ️ 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".

MisterVVP and others added 4 commits November 19, 2026 13:06
## Summary

- Add callback-driven `SendMessage_CreateTask` alongside the synchronous
API. Both require a task ID, and each async lane keeps one call in
flight.
- Start each client/server comparison on a fresh in-memory SUT. Warm
each measured client with one task, wait for completion, and reuse its
connection for measurement.
- Add a fixed-count CI step to the existing performance artifact and
label wire streams and subscriptions `observer` in JSON, CSV, and
Markdown.

## Local task-creation results

The hosted performance job passed the 24-wire-row check and uploaded the
report. [CI performance
artifact](https://github.com/MisterVVP/a2a-cpp/actions/runs/44519412513/artifacts/14529500461)

The local Release run also produced **24 wire rows**, **2,000 measured
requests per row**, and **zero errors**. All 12 fixed-client server
comparisons were valid. Each cell lists ops/s · p50/p99 in ms from a
single pass on a shared host while local analysis was running.

| Transport | Concurrency | Sync client / sync server | Sync client /
async server | Async client / sync server | Async client / async server
|
| --- | ---: | ---: | ---: | ---: | ---: |
| grpc | 1 | 4,614 · 0.214/0.316 | 3,856 · 0.242/0.669 | 3,978 ·
0.227/1.004 | 3,632 · 0.263/0.565 |
| grpc | 64 | 13,367 · 4.129/9.097 | 11,960 · 4.775/12.000 | 11,568 ·
4.893/11.364 | 14,074 · 4.403/7.754 |
| jsonrpc | 1 | 2,026 · 0.470/1.034 | 1,598 · 0.545/2.924 | 2,188 ·
0.457/0.545 | 1,542 · 0.543/2.765 |
| jsonrpc | 64 | 15,751 · 2.737/26.392 | 9,514 · 5.509/26.867 | 18,420 ·
3.093/9.034 | 10,583 · 5.623/12.290 |
| http_json | 1 | 2,817 · 0.349/0.657 | 2,335 · 0.410/0.906 | 2,579 ·
0.349/1.425 | 1,997 · 0.423/2.617 |
| http_json | 64 | 20,397 · 2.142/19.636 | 13,050 · 3.628/33.597 |
17,848 · 2.683/10.170 | 14,231 · 3.826/13.989 |

## HTTP/JSON server follow-up

In the earlier concurrency-one HTTP/JSON `GetTask` run, holding the
async client fixed, p50 rose from **179 µs** on the sync server to **231
µs** on the async server, a gap of **52 µs (29%)**. [Earlier GetTask
comparison](#335)

Start the server investigation with the network-to-application,
application-to-dispatcher, and response-to-network handoffs in the HTTP
unary path.

## Validation

- `./scripts/verify_changes.sh` and `./scripts/run_clang_tidy.sh build`
both exited successfully. The clean Asio Debug build and CTest completed
with zero failures across 1,135 registered tests. Three tests were
skipped by CTest.
- CI-equivalent clang-format, changed-file Clang 19 analysis,
actionlint, mdBook, and the 54-row performance smoke passed.
- Ubuntu's installed-package security check found no pending security
updates. OSV returned no matches for the Boost.Asio and simdjson
releases used in final verification. Local TCK was skipped at the
maintainer's request, and hosted TCK passed. Full local clang-tidy
finished after the authorized push.

## AI authorship

An AI agent generated the submitted code, tests, workflow, and
documentation from the maintainer-approved plan.
)

## Summary

- Route canonical native HTTP/JSON `GetTask` ingress onto the dispatcher
pool owned by `AsyncRuntime`. Requests start through the existing queued
per-request strand.
- Keep JSON-RPC, streams, and other REST routes on the listener
application pool.
- Drain borrowed ingress callbacks during listener join. Cover route
eligibility and shutdown with focused tests.

## Authorship and AI usage

- [x] Contains substantive content generated by an AI agent

## Testing

The prototype passed 38 focused tests. The seven paired Release
repetitions produced 98 result rows with zero errors. The comparison
used an in-memory store, the same async unary client, fixed CPU
placement, a 250 ms warmup, and three-second timed runs.

| Workload | Result |
| --- | --- |
| HTTP/JSON `GetTask`, concurrency 1 | Paired median p50 improved 17.79
µs, with gains in 7/7 pairs |
| HTTP/JSON `GetTask`, concurrency 64 | Throughput +0.41%, p99 +4.47% |
| JSON-RPC `GetTask`, concurrency 64 | Throughput −0.25%, p99 −0.81% |
| gRPC `GetTask`, concurrency 64 | Throughput +3.52%, p99 −14.31% |
| Mixed finite SSE | Throughput +7.78%, p99 −12.28% |
| Mixed HTTP/JSON `GetTask` | Throughput −3.32%, p99 −6.00% |
| Bounded HTTP/JSON task creation | Throughput −1.89%. Median p99 across
runs +17.31%. Median paired p99 change −2.4%, with increases in 3/7
pairs. |

The benchmark results are from the existing prototype runs. Full
validation is deferred to CI.
@MisterVVP

Copy link
Copy Markdown
Owner Author

@codex review this PR

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. More of your lovely PRs please.

Reviewed commit: 52020559ca

ℹ️ 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".

## Changes

- Route native HTTP request preparation through the dispatcher runtime
when the server uses `AsyncRuntime`. REST, JSON-RPC, discovery, and SSE
share the same ingress choice.
- Add regression tests for JSON-RPC shutdown draining and
dispatcher-backed discovery and ListTasks. Add benchmarks for client
concurrency, dispatcher overhead, and cancellable waits.
- Require no regression in mandatory TCK compliance against the target
branch, checking both the score and previously passing requirements.
[Contributor policy](AGENTS.md)

## Measured performance

### Native HTTP ingress compared with `5202055`

| Workload | Throughput, baseline → candidate | p99, baseline →
candidate |
| --- | ---: | ---: |
| JSON-RPC GetTask, C16 | 7,301 → 8,063 req/s (**+10.4%**) | 4.13 → 3.58
ms (−13.3%) |
| JSON-RPC GetTask, C64 | 7,552 → 8,263 req/s (**+9.4%**) | 17.41 →
20.88 ms (+19.9%) |
| JSON-RPC GetTask, C256 | 8,654 → 8,528 req/s (−1.5%) | 45.33 → 48.73
ms (+7.5%) |

These percentages use `(candidate / baseline − 1) × 100` on the reported
medians. For example, `(8,263 / 7,552 − 1) × 100 = 9.4%`. The C64
throughput gain came with higher p99.

In a separate sync-versus-async test on the starting branch, a simulated
1 ms HTTP wait at C256 went from 9,899 to 14,111 req/s (+42.5%) and from
120.40 to 30.07 ms p99 (−75.0%). The server thread count went from 265
to 21 (−92.1%). This test measures the effect of suspending the request,
independently of the ingress change above.

### Topology and serialization follow-up

The corrected one-core topology sweep completed 684 samples with zero
errors across C1, C16, C64, and C256. Four shared dispatcher workers at
C64 moved real JSON-RPC median throughput from 18,064 to 19,299 req/s,
and real gRPC from 46,696 to 41,110 req/s. The median changes calculated
within each interleaved pair were **+7.5%** and **−12.6%**,
respectively. Real JSON-RPC at C256 lost 4.0% throughput and gained
15.1% p99 by the same paired calculation. The local CPU quota supported
one dedicated server core and one client core.

The direct JSON-RPC envelope experiment reduced isolated serialization
from 14.59 to 7.54 µs (−48.3%, or 1.94× as many serializations per unit
time). Real async JSON-RPC C1 throughput improved 7.3% by the paired
calculation. At C256 the real sync server lost throughput and p99
increased 9.0% with the sync load driver and 13.0% with the async load
driver. Those C256 results ruled out the candidate.

The C64 native trace measured 390.52 µs p99 waiting to start posted
JSON-RPC serialization, 390.41 µs returning the reply to the network
loop, and 31.17 µs for the socket write callback. Each interval is
measured separately. Their percentiles cannot be added.

## Local validation

- The starting branch and candidate matched at 84.6% mandatory TCK
compatibility across all four sync/async and in-memory/PostgreSQL
profiles. Each profile passed 216 executed tests and every mandatory
requirement and transport status matched.
- The standard `verify_changes.sh` build, test, and full lint checks
passed, along with HTTP and gRPC interoperability and the 54-row
performance smoke. The signing-enabled test run reproduced the same
signing-corpus failure on `main`. The OSV service returned HTTP 403 for
the vendored component scan.

## Authorship

The proposed changes were generated by an AI agent.
@MisterVVP
MisterVVP marked this pull request as ready for review November 21, 2026 17:29
@MisterVVP MisterVVP closed this Nov 21, 2026
@MisterVVP
MisterVVP deleted the perf/grpc-client-streaming branch November 21, 2026 21:04
MisterVVP added a commit that referenced this pull request Nov 25, 2026
## Changes

- Optimize async gRPC client streaming and HTTP/JSON + JSON-RPC request
handling.
- Improve async dispatcher scheduling, cancellation, streaming and
response lifecycle handling.
- Include the native HTTP ingress improvements already reviewed in #337
and #338.
- Add targeted tests and performance benchmarks; fix related protocol
compatibility issues.

## Verification

The identical head commit (`355db351f7e1161fdffad55e2f2baf33d8e5fe8a`)
passed the CI, TCK Conformance, CodeQL, Docs, Tutorials and Commit
messages workflows on #334: [CI
#1571](https://github.com/MisterVVP/a2a-cpp/actions/runs/44828943977).

**Policy note:** the diff includes the contributor TCK-gate change from
#338 (100% mandatory compliance → no regression), which should be
reviewed independently of performance improvements.
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