Skip to content

fix: drive Responses orchestration from the client stream - #386

Merged
haoshan98 merged 4 commits into
vllm-project:mainfrom
Zheng-Lu:fix/244-stream-owned-producer
Oct 5, 2026
Merged

haoshan98 merged 4 commits into
vllm-project:mainfrom
Zheng-Lu:fix/244-stream-owned-producer

Conversation

@Zheng-Lu

@Zheng-Lu Zheng-Lu commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Refs #244. The Responses stream spawned its orchestration as a separate task and only aborted it when the stream was dropped. Two problems followed:

  • Dropping the stream released the session lease and cancelled running tools asynchronously, so a follow-up request could see the lease still held.
  • A panic in orchestration reached the client as tokio's JoinError text, including the panic payload (for example stream task failed: task 4 panicked with message "…").

This change polls the orchestration future and its bounded event channel inside the client stream (engine/streaming/producer.rs), instead of spawning a task:

  • Dropping the stream disposes of in-flight inference, running tools and the session lease synchronously.
  • Multi-agent rounds are the exception: they run as tasks owned by RunOwner. Dropping the stream drops the run, and RunOwner's drop aborts those tasks without joining them; each stops at its next await point and its result is discarded. This is documented on RunOwner, the coordinator, run_stream and in ARCHITECTURE.md.
  • A panic becomes a fixed stream producer panicked error (500), recorded as the panic failure category. Queued events are delivered in order first.
  • The agentic.execute span still covers all of the work. The observability docs are updated to match.
  • Persistence still happens before response.completed.
  • WebSocket responses are unchanged. They run through the retained owner (engine/retained.rs), which spawns execution and cancels and joins it. That owner cancels multi-agent runs through the pipeline's cancellation token and the coordinator's cancelled() arm, so both stay.

No new channels, queues or tasks are added.

Test Plan

  • cargo test --workspace: 2,173 passed, 1 failed, 18 ignored. The failure is web_fetch::http::tests::the_deadline_bounds_a_slow_origin. It fails the same way on unmodified main under the full suite and passes in isolation; this PR doesn't touch web_fetch. Clippy with -D warnings, cargo fmt --check and pre-commit (including Rust file sizes) pass.
  • Five producer unit tests cover these cases:
    • an unpolled stream never starts;
    • a backpressured or pending producer is dropped synchronously;
    • queued events are delivered in order before exactly one outcome;
    • a panic is isolated.
  • stream_producer_lifecycle_test.rs replays recorder-generated Qwen reasoning and vLLM tool-call cassettes through seven scenarios. On current main, four fail:
    • the lease is still held after dropping a partially delivered stream;
    • the same happens after dropping a streaming fork;
    • a running tool is not dropped inline;
    • a panic leaks its payload to the client.
      The other three pass on both branches and guard unchanged behavior: an unpolled stream makes no upstream call, persistence finishes before response.completed, and cancelling during a storage wait writes nothing.
  • dropping_multi_agent_stream_aborts_round_tasks_without_storing streams a multi-agent response until both children have sent their deltas and are idle on gated upstream bodies. It then drops the stream and checks two things: both child bodies close within one second, and nothing is stored. Negative control: with the run moved to a detached task, the bodies stay open and the test fails. It passed 20 of 20 repeated runs.
  • The multi-agent and WebSocket teardown tests pass. Removing the coordinator's cancelled() arm makes websocket_shutdown_joins_multi_agent_waiting_for_client_output fail.
  • No cassette was added or edited.

@Zheng-Lu
Zheng-Lu force-pushed the fix/244-stream-owned-producer branch from da6d9e0 to a856ff7 Compare September 29, 2026 14:51
@Zheng-Lu Zheng-Lu changed the title fix: drive Responses orchestration from the client stream (Phrase 2 of #335) fix: drive Responses orchestration from the client stream (Phase 2 of #335) Sep 29, 2026
@Zheng-Lu Zheng-Lu changed the title fix: drive Responses orchestration from the client stream (Phase 2 of #335) fix: drive Responses orchestration from the client stream Sep 29, 2026

@haoshan98 haoshan98 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for this. Owning the producer directly in the stream is a clean fix, and the lifecycle tests make the behavior easy to trust. Main has moved on since, so this needs a rebase; there's one multi-agent detail to settle while resolving the conflicts (comment below).

The Responses stream spawned its orchestration task and only aborted it on
drop. Dropping the stream therefore released the session lease and cancelled
running tools asynchronously, and a panic reached the client as tokio's
JoinError text, including the panic payload.

Poll the orchestration future inside the stream instead. Dropping the stream
now disposes of it inline, and a panic becomes a fixed "stream producer
panicked" error. The execution span still covers the work.

Refs vllm-project#244

Signed-off-by: Zheng Lu <[email protected]>
The stream owns its orchestration, so a client that drops a multi-agent
stream drops the run and its RunOwner. RunOwner's drop aborts the round
tasks without joining them; each stops at its next await point. Document
that teardown on RunOwner, the coordinator and run_stream, and correct
the architecture notes: the rounds are the exception to "nothing keeps
running", and WebSocket responses use the retained owner.

Keep the pipeline cancellation token and the coordinator's cancelled()
arm. Retained (WebSocket) runs cancel through that token and then join;
without the arm, server shutdown cannot end a multi-agent run waiting for
client output.

Add a test that drops a multi-agent stream once both children are idle
on their upstream bodies, then checks that both bodies close within one
second and that nothing is stored.

Signed-off-by: Zheng Lu <[email protected]>
@Zheng-Lu
Zheng-Lu force-pushed the fix/244-stream-owned-producer branch from a856ff7 to 19e966c Compare October 2, 2026 19:54
@Zheng-Lu
Zheng-Lu requested a review from haoshan98 October 2, 2026 19:55

@maralbahari maralbahari left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thank you for addressing stream cancellation and panic handling in this PR.

Could you implement the remaining relay interface from the suggestion on #244 in a follow-up?

In particular, encapsulating the sender, presentation state, round offset, deferred buffer, and limits behind emit_local, emit_upstream, and accept would reduce the coordination required from callers. Consolidating deferred release into one implementation would also keep ordering and byte accounting consistent.

That would complement this PR’s execution ownership with clearer delivery ownership.

@haoshan98
haoshan98 merged commit 00aac17 into vllm-project:main Oct 5, 2026
20 checks passed
@Zheng-Lu

Zheng-Lu commented Oct 5, 2026

Copy link
Copy Markdown
Contributor Author

Thank you for addressing stream cancellation and panic handling in this PR.

Could you implement the remaining relay interface from the suggestion on #244 in a follow-up?

In particular, encapsulating the sender, presentation state, round offset, deferred buffer, and limits behind emit_local, emit_upstream, and accept would reduce the coordination required from callers. Consolidating deferred release into one implementation would also keep ordering and byte accounting consistent.

That would complement this PR’s execution ownership with clearer delivery ownership.

Sure, I will implement the rest of #244

Zheng-Lu added a commit to Zheng-Lu/agentic-api that referenced this pull request Oct 8, 2026
Callers that emitted a client event had to coordinate the sender, the
GatewayStreamAccumulator, the round's output offset, the sink kind, and
for deferred frames the buffer and its byte count. Deferred frames were
released by three implementations: the in-stream flush, the post-stream
emit_deferred_stream_events, and the per-round DeferredRoundEvents
bucketing.

StreamRelay (executor/relay.rs) now owns the client sink, presentation
state, round offset, deferred buffer and RelayLimits. Callers use
emit_local for gateway-synthesized frames, emit_upstream and accept for
translated provider frames, and release_deferred as the one release
path; all of them reach the client through one private send, the only
place an output offset is applied. Release::Item keeps max_tool_calls'
contiguous public indexes after an omitted refusal. begin_round rejects
a new round while deferred frames remain unreleased.

The deferred buffer keeps release order on entry and charges each
frame's serialized size once, refunding it only after the sink accepts
the frame. Wire output is unchanged apart from a distinct error message
for a single deferred frame over the byte limit.

Follows up the vllm-project#386 review; part of vllm-project#244.

Signed-off-by: Zheng Lu <[email protected]>
maralbahari added a commit that referenced this pull request Oct 9, 2026
## Summary

Follows up the [#386
review](#386 (review));
part of #244.

Before this change, any caller that emitted a client event had to
coordinate the sender, the
`GatewayStreamAccumulator`, the round's output offset and the sink kind.
For deferred frames it also had to manage
the buffer and its byte count. Three separate implementations released
deferred frames: the in-stream flush, the
post-stream `emit_deferred_stream_events`, and the per-round
`DeferredRoundEvents` bucketing.

`StreamRelay` (`executor/relay.rs`) now owns the client sink, the
presentation state, the round offset, the
deferred buffer and `RelayLimits`.

- Callers use `emit_local` for gateway-synthesized frames and
`emit_upstream` / `accept` for translated provider
  frames. `release_deferred` is now the only release path.
- Every frame reaches the client through one private `send`. It is the
only place an output offset is applied.
- `Release::Item` keeps `max_tool_calls`' public indexes contiguous
after an omitted refusal.
- `begin_round` rejects a new round while deferred frames are still
unreleased.
- The deferred buffer keeps frames in release order as they enter. It
charges each frame's serialized size once and
  refunds it only after the sink accepts the frame.

Wire output is unchanged, except for a new, distinct error message when
a single deferred frame exceeds the byte
limit. `pipeline/delivery.rs` is removed, and its sink and projection
code moved under `relay/`.
`ARCHITECTURE.md` is updated to match.

## Test Plan

- `cargo test --workspace`: TODO passed, TODO failed, TODO ignored.
`cargo clippy --all-targets -- -D warnings`,
  `cargo fmt -- --check` and pre-commit pass.
- New relay unit tests (`executor/relay/tests.rs`):
- Ordering: synthetic gateway items share public indexes with upstream
items; deferred frames are released in
output order with index-less frames last; a moving defer window releases
indexed frames and holds index-less
ones until it closes; per-item release interleaves upstream frames with
gateway events.
- `max_tool_calls`: frames after an omitted call are presented at
contiguous indexes.
- Round boundaries: a round cannot begin while the previous round still
holds deferred frames.
- Limits: a one-entry deferred buffer rejects the next frame and keeps
the first; `deferred_bytes` bounds both the
buffer and any single frame; a slow consumer's backpressure never spills
into the deferred buffer.
- Byte accounting: a completed partial release refunds only the frames
it sent; cancelling a release keeps the
    unsent frames and their bytes.
- Sequence and lifecycle: a cancelled or rejected send consumes no
sequence number or lifecycle state; a closed
receiver consumes no presentation state; local and upstream events share
one numbering, but only upstream
    events get id rewriting.
- Sinks: a detached relay neither presents nor defers; an agent sink
forwards unstamped frames with only the
    upstream offset; a response sink owns the sequence for both origins.
- Existing ordering and replay tests, including `web_search_tool_test`'s
exact event list and contiguous
  `sequence_number` check, pass unchanged.
- No cassette was added or edited. Wire output is unchanged, so nothing
needed re-recording.

---------

Signed-off-by: Zheng Lu <[email protected]>
Co-authored-by: Maral <[email protected]>
avinashsingh77 pushed a commit to avinashsingh77/agentic-api that referenced this pull request Oct 9, 2026
…project#423)

Follows up the [vllm-project#386
review](vllm-project#386 (review));
part of vllm-project#244.

Before this change, any caller that emitted a client event had to
coordinate the sender, the
`GatewayStreamAccumulator`, the round's output offset and the sink kind.
For deferred frames it also had to manage
the buffer and its byte count. Three separate implementations released
deferred frames: the in-stream flush, the
post-stream `emit_deferred_stream_events`, and the per-round
`DeferredRoundEvents` bucketing.

`StreamRelay` (`executor/relay.rs`) now owns the client sink, the
presentation state, the round offset, the
deferred buffer and `RelayLimits`.

- Callers use `emit_local` for gateway-synthesized frames and
`emit_upstream` / `accept` for translated provider
  frames. `release_deferred` is now the only release path.
- Every frame reaches the client through one private `send`. It is the
only place an output offset is applied.
- `Release::Item` keeps `max_tool_calls`' public indexes contiguous
after an omitted refusal.
- `begin_round` rejects a new round while deferred frames are still
unreleased.
- The deferred buffer keeps frames in release order as they enter. It
charges each frame's serialized size once and
  refunds it only after the sink accepts the frame.

Wire output is unchanged, except for a new, distinct error message when
a single deferred frame exceeds the byte
limit. `pipeline/delivery.rs` is removed, and its sink and projection
code moved under `relay/`.
`ARCHITECTURE.md` is updated to match.

- `cargo test --workspace`: TODO passed, TODO failed, TODO ignored.
`cargo clippy --all-targets -- -D warnings`,
  `cargo fmt -- --check` and pre-commit pass.
- New relay unit tests (`executor/relay/tests.rs`):
- Ordering: synthetic gateway items share public indexes with upstream
items; deferred frames are released in
output order with index-less frames last; a moving defer window releases
indexed frames and holds index-less
ones until it closes; per-item release interleaves upstream frames with
gateway events.
- `max_tool_calls`: frames after an omitted call are presented at
contiguous indexes.
- Round boundaries: a round cannot begin while the previous round still
holds deferred frames.
- Limits: a one-entry deferred buffer rejects the next frame and keeps
the first; `deferred_bytes` bounds both the
buffer and any single frame; a slow consumer's backpressure never spills
into the deferred buffer.
- Byte accounting: a completed partial release refunds only the frames
it sent; cancelling a release keeps the
    unsent frames and their bytes.
- Sequence and lifecycle: a cancelled or rejected send consumes no
sequence number or lifecycle state; a closed
receiver consumes no presentation state; local and upstream events share
one numbering, but only upstream
    events get id rewriting.
- Sinks: a detached relay neither presents nor defers; an agent sink
forwards unstamped frames with only the
    upstream offset; a response sink owns the sequence for both origins.
- Existing ordering and replay tests, including `web_search_tool_test`'s
exact event list and contiguous
  `sequence_number` check, pass unchanged.
- No cassette was added or edited. Wire output is unchanged, so nothing
needed re-recording.

---------

Signed-off-by: Zheng Lu <[email protected]>
Co-authored-by: Maral <[email protected]>
@Zheng-Lu
Zheng-Lu deleted the fix/244-stream-owned-producer branch October 9, 2026 13:17
haoshan98 pushed a commit that referenced this pull request Oct 15, 2026
…llector (#340) (#375)

## Summary

Phase 3 of #279. Closes #340.

Rebuilt on `main` at `5473e02` (2026-10-09), then rebased on 2026-10-12
onto `079a9a3` (#432, #379). `main` reorganized most of the code this PR
instruments: #384, #386, #407, #410 and #423 changed the inference loop,
multi-agent execution, the WebSocket path and client delivery. So each
hook was re-applied at its current owner rather than merged textually,
and the paths that did not exist before are now covered too. See
"Changes in the rebuild" below.

The rebase onto `079a9a3` needed two small changes. #432 wraps
`persist_if_needed` in `Box::pin` at the two call sites where this PR
passes `&exec_ctx.metrics`; both are kept. `engine/multi_agent_tests.rs`
gets a file-size exception (limit 501) for this PR's two-line `metrics`
module declaration, because #432 brought the file to 499 lines; the
tests themselves live in `multi_agent_tests/metrics.rs`.

This adds operational metrics that stay correct without trace sampling,
a backend-neutral local Collector setup, and measured overhead. All
instruments are typed in `agentic-server-core` and are recorded by the
same `ExecutionSpan` guard that already finalizes `agentic.execute`.
They therefore share its exactly-once terminal paths: completion,
in-band upstream failure, disconnect, and shutdown. They are also
independent of the sampling decision.

| Instrument | Type | Attributes |
| --- | --- | --- |
| `agentic.execution.count`, `agentic.execution.duration` | counter,
histogram (s) | `agentic.api`, `agentic.route`, `agentic.stream`,
`agentic.execution.outcome`, `error.type` on failure |
| `agentic.execution.active` | up-down counter | `agentic.api`,
`agentic.route`, `agentic.stream` |
| `agentic.delivery.count` | counter | `agentic.api`, `agentic.route`,
`agentic.stream`, `agentic.delivery.outcome` |
| `agentic.delivery.wait.duration` | histogram (s) | `agentic.api` |
| `agentic.stage.duration` | histogram (s) | `agentic.stage`
(`rehydrate`, `inference`, `tool`, `compaction`, `persist`),
`agentic.tool.type` on tool samples, `error.type` |
| `agentic.inference.rounds` | histogram | `agentic.api` |
| `gen_ai.client.token.usage` | histogram |
`gen_ai.operation.name=chat`, `gen_ai.token.type`, `agentic.api` |
| `agentic.time_to_first_upstream_data`,
`agentic.time_to_first_client_event`, `agentic.time_to_first_text` |
histogram (s) | `agentic.api` |
| `agentic.websocket.connections.active` | up-down counter | none |
| `agentic.websocket.queue.wait.duration` | histogram (s) | none |

- `ExecutorMetrics` lives on `ExecutionContext`. It defaults to the
global meter provider, and embedding applications pass their own with
`ExecutionContext::with_metrics`. Without a provider every instrument is
a no-op.
- Token usage is recorded once per upstream call from that call's own
`usage`, including compaction summaries. Nothing is recorded when the
upstream omits `usage` or a count, so no zeros are fabricated. For
Messages, prompt tokens include cache reads and writes.
- The three first-data timings share an `ExecutionClock` measured from
when the execution was accepted:
  - first upstream data: marked at the pipeline entry;
- first client event and first text: marked where the client-facing
stream yields to the transport.
- Multi-agent responses: each round runs on its own pipeline, which
shares the execution's clock, and the response records one
`agentic.inference.rounds` sample counting every agent's rounds.
- Retained (WebSocket) responses mark first client event and first text
in the event stream that `ResponseEventSink::stream` returns, and
measure delivery wait there.
- Local Collector: `deploy/otel/docker-compose.yaml` runs digest-pinned
collector-contrib 0.161.0 with an OTLP/HTTP receiver, `memory_limiter`,
`batch`, the `debug` exporter, and a Prometheus endpoint carrying
`service.name`. `--env-file deploy/otel/jaeger.env` adds Jaeger 2.21.0.
All ports bind to 127.0.0.1.
- `scripts/tests/otel-smoke.sh` sends streamed, blocking, proxied, and
WebSocket requests through a scripted upstream. It stops the gateway so
it flushes, then checks the Collector's `debug` output and Prometheus
endpoint. The `rust` CI job now runs the smoke test and the checker's
unit tests.
- Docs: `docs/deploying/observability.md` covers every instrument,
attribute value, recording rule, timing anchor, histogram boundary, the
cardinality contract, the local Collector, and the overhead table.
`ARCHITECTURE.md` records which pipeline stage owns each telemetry mark,
so the #243/#244 refactors move marks instead of duplicating them.

### Defaults restated from the #279 design table

These got no reply on #279, so this PR uses the proposed defaults:

- OTLP over HTTP/protobuf only.
- `agentic.*` namespace for project-specific metric and attribute names.
- No model label on metrics (see departures below).
- Cumulative temporality.
- Histogram boundaries as proposed, except delivery wait (see
departures).

### Design departures from the #279 plan

1. **First text is marked where the client-facing stream yields, not at
ingestion.** Ingestion can run ahead of delivery by the bounded
channel's capacity, so an ingestion-time mark can come before the first
client event. Marking both at the same point guarantees
`first_upstream_data ≤ first_client_event ≤ first_text` for a text
response. It also measures what a client sees. Ingestion still owns the
classification: `StreamEvent` carries a typed `text` flag set from
`SSEEventType::OutputTextDelta`.
2. **Delivery wait is one sum per streamed execution, not a sample per
blocked send.** `InstrumentedStream` measures the time between handing a
frame to the transport and the transport polling for the next one. That
covers HTTP and WebSocket at one boundary with one sample per execution.
Boundaries therefore extend to 60 s. A WebSocket response finalizes on
its own task, so frames the connection takes after that are not
included.
3. **No `gen_ai.request.model`, `gen_ai.response.model`, or
`gen_ai.provider.name`.** Per-request-model labels are a #340 non-goal.
The gateway cannot know which provider serves its upstream, so it
records no provider name rather than a guessed one. This deviates from
the semantic convention's required provider attribute, and the docs say
so.
4. **Gateway-executed built-in tools in the Messages loop are not
timed.** They have no stage span yet either (phase 2 traced only the
Responses scheduler). The `tool` stage covers Responses gateway calls,
one sample per tool call.
5. **First-data timings cover streamed executor responses only.**
Blocking requests and the raw proxy have no client-visible first event.
6. **A WebSocket execution starts at admission**, matching its span.
`agentic.execution.active` includes requests queued behind another on
the same stream, and duration includes queue wait.
`agentic.websocket.queue.wait.duration` isolates the wait.

### Changes in the rebuild

- The inference stage timer and per-round usage now sit in
`AgentTurn::run_round`, which both single-agent and multi-agent rounds
use. The file moves the original PR made for size (`engine/round.rs`,
`gateway/input.rs`, `compaction/explicit.rs`) are gone.
- The round count lives on `SingleAgentRun` and `MultiAgentRun`, one per
execution. `MultiAgentRun` passes the execution clock to every round's
pipeline.
- `retained.rs` gives the root pipeline the clock and wraps its event
stream for delivery timing. `persist_if_needed` takes the metrics on all
four call sites, including the retained one.
- The tool timer wraps `GatewayScheduler::run_one`, the same scope as
its `agentic.tool.execute` span. Calls refused by `max_tool_calls` never
run, so they are not timed. The two timing methods live in
`gateway/timing.rs` to keep `gateway.rs` under the size limit.
- `execute_and_emit_output_calls` takes `&ExecutionContext` instead of a
policy and the metrics (`clippy::too_many_arguments`).
- `StreamFrame` carries the typed `text` flag on both frame paths (HTTP
and retained).
- `messages_stream.rs`: `open_round` replaces `prime_messages_stream`
and the later-round branch, as before. `MessagesStreamAccumulator` gains
a fourth flag, so it takes `#[allow(clippy::struct_excessive_bools)]`
like the other such structs in the repository.
- The inner rehydrate future is boxed so the timing wrapper doesn't hold
`RequestPayload` twice (`clippy::large_futures`).
- No size-policy baselines change. The rebase adds one exception, for
`engine/multi_agent_tests.rs` (see the top).
- Public API change: `ExecutionSpan::start` and `start_linked` take
`&ExecutorMetrics`.

## Test Plan

```bash
cargo fmt -- --check
cargo clippy --workspace --all-targets -- -D warnings
cargo test --workspace --no-fail-fast        # 2341 passed, 0 failed, 18 ignored
uvx pre-commit run --all-files                # all hooks pass
docker compose -f deploy/otel/docker-compose.yaml up -d && scripts/tests/otel-smoke.sh
python3 -m unittest discover -s scripts/tests -p test_otel_fixtures.py
uvx --with-requirements docs/requirements.txt mkdocs build --strict
```

`web_fetch::http::tests::the_deadline_bounds_a_slow_origin` is
timing-sensitive and fails intermittently on unmodified `main` under the
full suite; after the rebase it failed in one of two full-suite runs and
passes on its own. This PR doesn't touch `web_fetch`. Clippy also passes
with `--features embedded-code-interpreter` for both crates, as in CI.

**New tests.** Every test builds its own in-memory meter provider, so
they run in parallel. Every assertion passes through a shared
allow-list,
`crates/agentic-server-core/tests/execution_metrics/harness.rs`, which
fails on any instrument, attribute key, or attribute value that isn't
listed.

- `agentic-server-core/tests/execution_metrics_test.rs` (11 tests, no
tracing subscriber installed):
- Each terminal path counts exactly one execution and releases its
active count, for Responses and Messages. The paths are:
    - blocking completion;
    - an in-band SSE failure under HTTP 200;
    - a failure before delivery;
    - a dropped stream;
    - a Messages rejection before headers.
- A recorded text cassette
(`text_only/responses/resp-single-gpt-4o-streaming.yaml`):
    - proves `first_upstream_data ≤ first_client_event ≤ first_text`;
    - reports the cassette's exact usage (14 in, 4 out);
    - records no token sample for `usage: null`.
- The two-round web-search cassette records two rounds, two inference
stages, one `web_search` tool stage, and one usage sample per upstream
call.
- Messages records prompt tokens including cache reads, and orders its
three timings too.
- Explicit `/v1/responses/compact` times rehydrate, compaction, and
persist, and records usage, but no execution.
  - The allow-list rejects unlisted instruments, keys, and values.
- `agentic-server/tests/execution_metrics_test.rs` (4 tests, production
router):
- HTTP completed, in-band failure, blocking, proxied, and client
disconnect: 5 executions, active back to 0.
- Three `response.create` plus one failure on one WebSocket gives 4
executions, 4 queue-wait samples, and `connections.active` = 1 while
open, 0 after close.
- A WebSocket disconnect cancels both the active and the queued request
exactly once.
- Drain cancels the queued request once and lets the active one finish.
- `agentic-server/tests/telemetry_metrics_e2e_test.rs` runs the **real
binary**, configured only through `OTEL_*`, with
`OTEL_TRACES_SAMPLER=parentbased_traceidratio` and
`OTEL_TRACES_SAMPLER_ARG=0`, exporting to an in-process OTLP stub. It
sends HTTP and WebSocket requests, then SIGTERMs the gateway with one
HTTP stream and one WebSocket request still in flight:
  - 0 spans exported;
  - all 15 instruments present, with `service.name`;
  - 6 executions: 4 completed and 2 cancelled;
  - active back to 0 and `connections.active` back to 0.
- Added in the rebuild:
- `multi_agent_execution_records_rounds_and_first_data_once` (core unit
test). A streamed multi-agent response, a root and two children, records
one rounds sample. Its sum equals the number of inference stages across
all agents, and first upstream data is recorded once.
- The WebSocket test also checks first upstream data and first text once
per completed response, and first client event for all four. Those come
from the retained path.
- The mock upstreams and the smoke fixture give each response fresh item
IDs, as a real upstream does. Stored history keys rows by item ID, so a
repeated ID can't be stored twice (#385).
- `scripts/tests/test_otel_fixtures.py` (10 tests): the Collector-log
checker reads the allow-list from the Rust harness and rejects unlisted
keys, values, and instruments.
- The two new Rust test binaries ran 8 times in a row with no failures.

**Mutation checks.** For the code the rebuild re-placed, each new check
fails when its wiring is removed:

| Removed | Result |
| --- | --- |
| The clock on multi-agent round pipelines | the multi-agent test fails:
first upstream data recorded 0 times, expected 1 |
| Counting multi-agent rounds | the multi-agent test fails: no rounds
sample |
| The retained path's clock (pipeline and event stream) | the WebSocket
test fails: first upstream data recorded 0 times, expected 3 |

The original branch (`9a9b052`) had these checks. The tests behind them
pass unchanged on the rebuild, but I did not repeat the mutations:

| Mutation | Result |
| --- | --- |
| `ExecutionSpan` drop never records execution metrics | core: 9 of 10
fail (only the pure allow-list test passes) |
| Execution metrics recorded twice on drop | core: 9 of 10 fail; server:
4 of 4 fail |
| Pipeline never marks first upstream data | core: the Responses
timing-order test fails |
| Missing upstream usage recorded as zero (`unwrap_or_default`) | core:
fails with "the upstream sent `usage: null`; nothing is fabricated" |
| WebSocket guard never releases `connections.active` | server: both
tests that wait for the connection to close fail |
| Control: e2e with `OTEL_TRACES_SAMPLER_ARG=1` | fails with 34 spans
exported, so the 0-span assertion is not vacuous |

**Local Collector.** `scripts/tests/otel-smoke.sh` passes against the
compose stack after the rebase, on five cold Collector starts and a warm
rerun: all 15 instruments and 29 data points are allow-listed, with the
run's `service.name`. The very first run, which also created the Docker
network, reported no metrics even though the Collector logged them a
moment later; this did not reproduce. I did not rerun the Jaeger variant
after the rebuild. This machine only has `docker-compose` v1, so the
script falls back to it locally. CI runs `docker compose` v2.

## Overhead

Measured on the 2026-10-09 rebuild and not re-measured after the rebase,
which changed no instrumented code.

`scripts/otel-overhead.py`, release builds. Setup:
- SQLite storage, so every request is rehydrated, executed, and
persisted.
- In-process scripted upstream.
- 2,000 sequential requests per scenario per round after 200 warm-up
requests.
- 3 rounds alternating the two modes.
- *Enabled* traces every request (`parentbased_always_on`) and exports
traces and metrics over OTLP/HTTP to the local Collector.
- Host: i9-13980HX, Linux 6.6 (WSL2).

Measured again after the rebuild, two runs per build in the same session
(second run shown). This branch:

| Scenario | Telemetry | p50 (ms) | p90 (ms) | p99 (ms) | Gateway CPU /
request (ms) | Peak RSS (MiB) |
| --- | --- | ---: | ---: | ---: | ---: | ---: |
| Streaming | disabled | 0.96 | 1.18 | 13.03 | 0.86 | 31.5 |
| Streaming | enabled | 1.08 | 1.34 | 13.39 | 1.06 | 36.2 |
| Non-streaming | disabled | 0.87 | 1.11 | 12.52 | 0.76 | 31.5 |
| Non-streaming | enabled | 0.97 | 1.18 | 12.76 | 0.90 | 36.2 |

`main` at `5473e02` (traces, no metrics), same benchmark:

| Scenario | Telemetry | p50 (ms) | p90 (ms) | p99 (ms) | Gateway CPU /
request (ms) | Peak RSS (MiB) |
| --- | --- | ---: | ---: | ---: | ---: | ---: |
| Streaming | disabled | 0.90 | 1.10 | 12.45 | 0.80 | 31.5 |
| Streaming | enabled | 1.00 | 1.24 | 12.81 | 0.94 | 36.5 |
| Non-streaming | disabled | 0.81 | 1.00 | 12.17 | 0.71 | 31.5 |
| Non-streaming | enabled | 0.96 | 1.21 | 12.75 | 0.89 | 36.5 |

- Enabling telemetry on this branch added 0.04–0.13 ms at p50, 0.07–0.20
ms of gateway CPU per request, and about 5 MiB of peak RSS.
- Against `main`, this branch measured 0.01–0.13 ms higher at p50 and
0.01–0.14 ms more CPU per request, with telemetry enabled or disabled.
- Run-to-run variation for one build was up to 0.1 ms at p50, so each
difference is within that variation. But every one pointed the same way,
so the docs no longer say "no measurable cost". They say the metrics
cost at most about 0.1 ms per request at this scale.

## Known gaps and follow-ups

- Messages gateway tool timing (departure 4).
- #377: #379 merged and set the MSRV to Rust 1.98.1. This branch is
rebased onto it and passes clippy at `msrv = "1.98.1"`.

---------

Signed-off-by: Zheng Lu <[email protected]>
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.

3 participants