Skip to content

feat(diagnostics): measure gateway RPC latency phases - #138015

Merged
steipete merged 4 commits into
mainfrom
codex/gateway-rpc-metrics
Sep 4, 2026
Merged

steipete merged 4 commits into
mainfrom
codex/gateway-rpc-metrics

Conversation

@steipete

@steipete steipete commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Gateway response logs combine admission, queueing and handler work, while existing diagnostics exporters have no per-RPC timing producer. A slow request or early acknowledgment therefore cannot show whether time was spent waiting to start, executing its handler, or sending its first response.

Why This Change Was Made

Record these facts at the authenticated request dispatcher and concrete handler boundary, then reuse the existing diagnostic bus and OpenTelemetry/Prometheus exporters. First accepted send, handler settlement, dispatch rejection/cancellation and unavailable/suppressed delivery remain distinct. Supplied trace parents, including early denials, and explicit parent absence survive asynchronous execution without inheriting unrelated ambient traces.

The producer follows the request-entry lifetime introduced by #136998. Lazy router and handler-family preparation count as admission. Handler timing starts only after preparation, final authorization fences and synchronous lease handoff; a failed loader creates no handler sample. Shutdown still joins preparation and its error response, while executing handlers retain their existing owners. Main's request trace scope makes the earlier prebinding path unnecessary.

Production grows by 340 lines: Gateway producer +152, event/trace contracts +32, OTel export and signal gating +103, Prometheus export +45, and existing listener-interest consumers +8. This adds the missing producer and exporter capability; it introduces no active-span registry, collector, configuration key, dependency, persistent store, schema or protocol field. Test/support growth is +1,399 lines, including shared real-SDK fixtures and test relocation; docs +95.

User Impact

Existing exporter enablement exposes request counts and admission, start-queue, first-response and handler durations. Canonical core methods retain their names; other methods use fixed buckets. Outcomes aggregate by phase/outcome rather than multiplying method labels. Payloads, identities and raw errors are excluded. Enablement and metric semantics are documented in Prometheus diagnostics and OpenTelemetry export.

These are elapsed timings, not CPU profiles or proof of client receipt. Early acknowledgments and detached responses do not imply completed agent work. The existing 2,048 aggregate-sample Prometheus cap and async-event queue remain unchanged; drop counters must be checked before interpreting coverage. Existing samples continue updating when the cap fills. Inactive or uninterested consumers create no observer, clock read or registry lookup. Existing OTel metrics:false is honored even with a preloaded global SDK; traces-only and logs-only modes retain their contracts.

Evidence

Validation is cumulative; the counts below overlap and do not claim one final whole-repository wrapper passed:

  • The final integration tree passed 257 tests across 21 files, paired with main 3ed226a746a8efd223a35a81790014c41ff044a3: 23 diagnostics cases, the real authenticated WebSocket/protected Prometheus/local OTLP case, and 233 adjacent lifecycle/router tests. Coverage includes preparation and credential-barrier shutdown, handler-initiated close, authorization, reconnect/cancellation, late responses, parent isolation and lazy handler families.
  • Three new controlled-clock regressions failed against the prior published source before integration: direct/nested preparation recorded admission 0 ms and handler 140 ms instead of 100 ms and 40 ms; loader rejection incorrectly produced a handler sample. The real WebSocket regression measured a 52.6 ms family hold but only 10.8 ms admission. The integrated owner passes the same assertions without adding sleeps or latency thresholds, while retaining exporter numeric sums, ACK-before-settlement, concurrent requests and bounded method labels. This is isolated source integration proof, not installed-package or production-load proof.
  • All 11 affected static checks passed: core production types, Gateway-root and Gateway-other test graphs, the complete root test graph, two typed-lint passes, code/docs formatting, diff checks, SDK surface and runtime-sidecar loaders. The integration tree is byte-identical before and after the private merge commit 5bffdb4cc5ea0de32eab7b61485f724cec34fc14.
  • Earlier proof is retained for unchanged feature portions: 445 tests across nine shards, 315 exporter tests after test-only relocation, and 98 focused tests for the accidental SDK export repair. That repair keeps the new event alias module-private and derives it from the existing event union in its two test consumers; all three files emit identical JavaScript. No SDK budget was raised by this change.
  • Initial missing-metrics, inactive-meter and ambient/early-parent regressions failed before repair. Earlier broad checks exposed core lint, a test import boundary, temporary type-overlay resolution and test size/shadowing/cleanup issues; those were repaired without raising limits or weakening assertions. An intermediate broad run was deliberately interrupted before an owner repair. During integration, cold router transformation hit the existing first-case timeout; the regression now loads the real router before controlled timing cases and joins dispatch cleanup. The final baseline reaches all intended assertions. Historical failures are retained separately; the earlier npm advisory failure did not establish vulnerability clearance and this metrics change makes no registry-availability claim.
  • Independent P2 review with 17 complete owner source files found no actionable P0–P2 findings or meaningful proof gaps. All candidate preimages and reviewed owners—41 unique paths, including absent new files—are unchanged between the paired base and inspected main ed6e3aabf0ef6cd58a8ee9d9282a6dc6c06cc918. The 28-file candidate source manifest and paired proof remain pinned; later SDK budgets and separate test-acquisition helper changes are outside this paired execution proof. Source qualification is not a substitute for exact-head CI.

Current-head validation and dependency review

Head c8a1a33ea3c0911c9b004eb4a7f539134b4a37d8 mechanically integrates main 95815d895c153773f30f26a7bd2b53b7b7819b7f with the same 28-file feature patch. Fresh final-tree proof passed 60 tests across six files, including the real authenticated WebSocket-to-Prometheus/OTLP flow and current request-entry/router contexts, plus the previously failing QA docs-reference case. Independent P2 found no actionable findings. Exact-head CI 33874530334 passed, including openclaw/ci-gate. The cumulative proof above remains preserved.

The latest review's dependency-inspection gap is resolved by directly inspecting the frozen @opentelemetry/api 1.9.1 source/types and @opentelemetry/sdk-trace 2.10.0 implementation: ROOT_CONTEXT is an empty context; startSpan takes its parent from the third context argument, and the SDK uses active context only when that argument is omitted. The RPC exporter supplies its validated explicit parent or ROOT_CONTEXT. Existing parent-isolation tests and the fresh WebSocket/OTLP proof cover both paths. No source or dependency change was needed for that review-environment limitation.

@steipete
steipete requested a review from a team as a code owner September 4, 2026 07:11
@clawsweeper

clawsweeper Bot commented Sep 4, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime extensions: diagnostics-otel Extension: diagnostics-otel extensions: diagnostics-prometheus size: XL maintainer Maintainer-authored PR labels Sep 4, 2026
Integrate main's preparation leases and start handler timing only after lazy
preparation, final authorization fences, and the synchronous ownership handoff.
Bind diagnostics in the existing request trace scope and remove obsolete early
parent binding.

Validated with 257 focused tests, 11 static checks, and independent P2 review
with complete lifecycle source context. Current-main qualification against
ed6e3aa preserves the touched preimages and reviewed owner contracts; behavior
proof remains paired with 3ed226a.
@clawsweeper clawsweeper Bot added P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. merge-risk: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 4, 2026
@clawsweeper

clawsweeper Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 4, 2026, 8:54 AM ET / 12:54 UTC.

ClawSweeper review

What this changes

The PR records bounded Gateway WebSocket RPC timing phases and exports them through the OpenTelemetry and Prometheus diagnostics plugins.

Merge readiness

⛔ Blocked before merge - 1 item remains

Keep open. This current maintainer-owned feature is not on current main; its dispatcher-to-exporter boundary is coherent and no actionable correctness defect was found in this review.

Priority: P3
Reviewed head: c8a1a33ea3c0911c9b004eb4a7f539134b4a37d8

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused, well-covered diagnostics feature with no supported correctness finding; exact-head validation remains the normal merge gate.
Proof confidence 🌊 off-meta tidepool Not applicable: The trusted-author proof gate does not apply; the PR body nevertheless records authenticated WebSocket-to-exporter regression evidence for the changed dispatcher and exporter path.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The trusted-author proof gate does not apply; the PR body nevertheless records authenticated WebSocket-to-exporter regression evidence for the changed dispatcher and exporter path.
Evidence reviewed 6 items Gateway owner boundary: The dispatcher creates diagnostics only for valid authenticated request frames, measures operator queue admission, and passes the recorder into the actual handler boundary; the handler timer starts after preparation and final authorization.
Exporter and trace behavior: Both exporters consume the new closed event variants; the OpenTelemetry exporter uses ROOT_CONTEXT unless a supplied trace has an explicit parent, so it does not borrow ambient OpenTelemetry context.
Regression coverage and documentation: Focused tests cover queue timing, authorization rejection, retained responses, cancellation, trace handling, bounded method labels, and both exporter representations; documentation matches the intentionally bounded labels and sampling semantics.
Findings None None.
Security None None.

How this fits together

Authenticated Gateway WebSocket requests enter the dispatcher, which handles admission, queueing, handler invocation, and responses. The PR records timing facts there and sends them through the existing diagnostic event bus to optional exporters.

flowchart LR
A[WebSocket request] --> B[Authenticated dispatcher]
B --> C[Admission and queue]
C --> D[Gateway handler]
D --> E[Response sender]
B --> F[Diagnostic event bus]
F --> G[OpenTelemetry exporter]
F --> H[Prometheus exporter]
Loading

Before merge

  • Resolve merge risk (P1) - Direct inspection of the pinned OpenTelemetry API source/types was unavailable in this read-only worktree; retain normal exact-head validation before merge.
Agent review details

Security

None.

PR surface

Source +340, Tests +1399, Docs +95. Total +1834 across 28 files.

View PR surface stats
Area Files Added Removed Net
Source 14 378 38 +340
Tests 12 1552 153 +1399
Docs 2 95 0 +95
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 28 2025 191 +1834

Review metrics

Metric Value Why it matters
Implementation split production +340, tests/support +1,399, docs +95 The feature adds one Gateway-to-diagnostics capability with substantial boundary and exporter regression coverage.

Merge-risk options

Maintainer options:

  1. Decide the mitigation before merge
    Land the bounded dispatcher-owned event producer and existing-bus exporters once normal exact-head checks complete, preserving the documented method-cardinality and trace-parent rules.
  2. Pause or close
    Do not merge this PR until maintainers decide whether the risk is worth taking.

Technical review

Best possible solution:

Land the bounded dispatcher-owned event producer and existing-bus exporters once normal exact-head checks complete, preserving the documented method-cardinality and trace-parent rules.

Do we have a high-confidence way to reproduce the issue?

Not applicable: this PR adds diagnostic visibility rather than repairing a reported malfunction; its focused tests exercise the new request-to-exporter path.

Is this the best way to solve the issue?

Yes. Recording facts at the authenticated dispatcher and handler boundary, then reusing the existing diagnostics bus, avoids a parallel collector or protocol surface.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 390bef2077ea.

Labels

Label justifications:

  • P3: This is optional observability improvement work rather than a regression in Gateway request delivery.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The trusted-author proof gate does not apply; the PR body nevertheless records authenticated WebSocket-to-exporter regression evidence for the changed dispatcher and exporter path.

Evidence

What I checked:

  • Gateway owner boundary: The dispatcher creates diagnostics only for valid authenticated request frames, measures operator queue admission, and passes the recorder into the actual handler boundary; the handler timer starts after preparation and final authorization. (src/gateway/server/ws-connection/authenticated-request-dispatch.ts:100, c8a1a33ea3c0)
  • Exporter and trace behavior: Both exporters consume the new closed event variants; the OpenTelemetry exporter uses ROOT_CONTEXT unless a supplied trace has an explicit parent, so it does not borrow ambient OpenTelemetry context. (extensions/diagnostics-otel/src/service-recorders-operations.ts:60, c8a1a33ea3c0)
  • Regression coverage and documentation: Focused tests cover queue timing, authorization rejection, retained responses, cancellation, trace handling, bounded method labels, and both exporter representations; documentation matches the intentionally bounded labels and sampling semantics. (src/gateway/server/ws-connection/authenticated-request-dispatch.metrics.test.ts:137, c8a1a33ea3c0)
  • Current-main and feature history: The current main commit remains distinct from this PR and the comparison still contains the new dispatcher and exporter implementation; the related merged request-entry work supplies the lifecycle boundary but not this diagnostics feature. (src/gateway/server/ws-connection/request-diagnostics.ts:117, 390bef2077ea)
  • Codex boundary check: The required sibling Codex source check found a separate Rust app-server/OTel implementation; this PR neither imports nor relies on that protocol or runtime. (codex-rs/otel/src/metrics/client.rs:1, 41e22fee981a63b3698df7ed36bad393cda24715)
  • Dependency inspection limitation: The changed OTel plugin imports the pinned @opentelemetry/api 1.9.1 package, but this read-only worktree has no node_modules and network resolution prevented direct upstream type/source inspection. (extensions/diagnostics-otel/package.json:11, c8a1a33ea3c0)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Vincent Koc: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (2 earlier review cycles)
  • reviewed 2026-09-04T09:40:32.428Z sha 5a4330f :: blocked before merge. :: [P2] Clear the trace scope when no traceparent was supplied
  • reviewed 2026-09-04T10:38:58.214Z sha 5bffdb4 :: needs maintainer review before merge. :: none

@steipete

steipete commented Sep 4, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

The integration at 5bffdb4 follows the current request-entry owner: lazy handler-family preparation counts as admission, and handler timing begins after final authorization and lease handoff. The updated PR body records the failing prior-source reproductions, 257 passing integration tests, affected static checks, and independent review.

@clawsweeper

clawsweeper Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. merge-risk: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. labels Sep 4, 2026

@sylvesterkaczmarek sylvesterkaczmarek 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.

The phase ownership is well defined: admission ends at actual handler invocation, queue wait is a subset, handler time excludes lazy preparation, and first-response measures sender acceptance rather than client receipt. Method bucketing plus phase/outcome-only error labels is also the right cardinality discipline for Prometheus. I like that uninterested diagnostics consumers avoid observer/clock work entirely; keep the dropped-series and async-queue caveats prominent because they directly affect percentile interpretation.

@steipete
steipete merged commit 068ef71 into main Sep 4, 2026
183 checks passed
@steipete
steipete deleted the codex/gateway-rpc-metrics branch September 4, 2026 13:41
@steipete

steipete commented Sep 4, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 5, 2026
* feat(diagnostics): measure gateway RPC latency phases

* fix(diagnostics): keep gateway RPC event type internal
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation extensions: diagnostics-otel Extension: diagnostics-otel extensions: diagnostics-prometheus gateway Gateway runtime maintainer Maintainer-authored PR P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: XL status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants