Skip to content

feat(diagnostics): retain event-loop delays across health reads - #138249

Merged
steipete merged 2 commits into
mainfrom
codex/event-loop-window-metrics
Sep 4, 2026
Merged

steipete merged 2 commits into
mainfrom
codex/event-loop-window-metrics

Conversation

@steipete

@steipete steipete commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor
Additional instructions

MUST: Keep Allow edits from maintainers enabled for this PR so maintainers
can help update the branch when needed.

What Problem This Solves

Operators polling event-loop health can miss a high-delay interval when another readiness or status reader consumes it first. A later healthy snapshot can correctly show recovery while leaving cumulative monitoring without evidence of the earlier delay.

Why This Change Was Made

The health monitor publishes each completed observation window after committing its existing snapshot and baselines. The existing Prometheus and OpenTelemetry exporters retain maximum delay and represented duration cumulatively. Readiness and lifecycle decisions stay unchanged; existing diagnostics and consumer-interest gates control collection, with no new timer, configuration, dependency, store or public RPC.

The final composition incorporates the landed RPC diagnostics from #138015. It preserves both metric families, asynchronous delivery, exporter-only subscriptions, the metrics-disabled no-op meter, and exclusion of event-loop samples from traces-only consumers. Against integration base 068ef71bd20e0b22f92c26364b758551aa13363b, production is +80/-6 (net +74) for the cumulative measurement capability. Tests/support are +723/-103, including moved cases and a shared fixture; docs are +115/-62.

User Impact

Operators using the existing diagnostics exporters can retain completed high-delay windows across later health reads and repeated scrapes:

  • Prometheus: openclaw_gateway_event_loop_delay_max_seconds and openclaw_gateway_event_loop_observed_seconds_total.
  • OpenTelemetry: openclaw.gateway.event_loop.delay_max_ms and openclaw.gateway.event_loop.observed_ms.

These metrics have no request or identity labels and do not create reader-attributed spans or logs. Counts and quantiles describe reader-defined window maxima, not individual stalls or native overall percentiles. Queue drops, series limits, export failures and process restarts still bound coverage; JavaScript stack and causal request attribution remain separate capabilities.

Evidence

  • The final production composition passed 320 focused tests in 10 selected files. Its real Gateway flow uses authenticated WebSocket RPCs, a held handler, concurrent requests, arbitrary-method flooding, a real readiness-monitor read, protected Prometheus scraping and a local OTLP receiver in one lifecycle. It preserves both metric families and verifies cleanup. The receiver checks transported metric names; separate real-SDK tests verify numeric aggregation, units, signal toggles and trace isolation.
  • Two subsequent test-only layout repairs preserve all cases: 24 core service tests passed after simplifying an equivalent callback, and all 27 Prometheus cases passed across the service and event-loop files after extracting their shared harness. The moved cases retain both series-cap variants and repeated real HTTP scrapes.
  • All 39 commands in the final canonical changed-check plan have passing evidence: 24 fresh final passes, the unchanged exact core-lint pass, and 14 individually qualified earlier passes whose relevant inputs or type contracts remain unchanged. Fresh proof includes formatting, both plugin lint batches, root-test lint, ratchets, plugin test imports, extension-test typechecking, dead-export analysis, script lint and the remaining ownership guards. The initial aggregate stopped on a 1,002-line test file; its targeted recovery then found the 1,116-line Prometheus file. Both were repaired without suppression, threshold changes or coverage removal. Those failed aggregate receipts remain failures; this is cumulative command coverage, not a claimed fresh successful whole-wrapper run.
  • Independent P2 review of the final composition and fixture ownership is clean. Production bytes remain unchanged through the two test-only repairs.
  • Original-head evidence is retained separately: c9199d919ca4d1a8075d322f5dbb11556d293f04 had native-monitor/HTTP red-green proof, 426 focused tests, and an isolated managed-install Gateway E2E on Linux with Node 24.18.1 and pnpm 12.1.0. That run exercised real plugin installation and trusted runtime checks, rejected unauthenticated scraping, retained authenticated cumulative metrics across readiness reads, and exited cleanly within the existing five-second shutdown budget. The registry was synthetic and no provider/channel messages were sent. Original numeric-tuple, metrics-disabled fixture and test-file-size failures remain recorded as repaired, with their failed wrapper receipts preserved. This remains proof of its original source and dependency closure, not a new packaged-install or load test of the RPC composition.
  • The previous scheduled CI run retained 107 passing checks, but one job never acquired a runner and the targeted retry ended in startup_failure. Those results are historical, not clearance for the composed head. Normal exact-new-head CI is still required after publication; no workflow or recovery policy was bypassed.

Record completed health-monitor windows through existing diagnostics so
Prometheus and OpenTelemetry retain intervals consumed by earlier readers.
Preserve readiness and lifecycle behavior and exclude reader trace identity.

Cover cumulative retention, disabled consumers, queue and series limits,
real SDK context handling, and managed-install Gateway authentication and
graceful shutdown.
@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.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@steipete
steipete marked this pull request as ready for review September 4, 2026 12:10
@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

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

Producer/exporter split looks right. Publishing each completed observation window once preserves historical spikes without changing readiness semantics, and keeping the metrics free of request labels avoids attribution and cardinality problems.

Merge the landed RPC diagnostics owner with cumulative event-loop windows.
Preserve exporter subscriptions, disabled-metrics behavior and trace isolation.
Keep the event-loop Prometheus tests in their own file with a shared harness.
@clawsweeper clawsweeper Bot added P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. 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. 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, 12:08 PM ET / 16:08 UTC.

ClawSweeper review

What this changes

The branch emits each completed Gateway event-loop health window once and exports cumulative delay and represented-duration metrics through Prometheus and OpenTelemetry.

Merge readiness

⛔ Blocked before merge - 2 items remain

No blocking correctness or security defect was found. This current maintainer-authored PR remains open; the only unresolved review limitation is direct verification of the OpenTelemetry context API used by the new exporter call.

Priority: P3
Reviewed head: 7aafc205b36ba6fc9dec09e6b636b56239fb67bc

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The implementation is focused and covered at its owner and integration boundaries, with one unavailable dependency-source verification remaining.
Proof confidence 🌊 off-meta tidepool Not applicable: This maintainer-authored PR is exempt from the external-contributor proof gate; its inspected integration test exercises authenticated Gateway readiness, protected Prometheus scraping, and the local telemetry path.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: This maintainer-authored PR is exempt from the external-contributor proof gate; its inspected integration test exercises authenticated Gateway readiness, protected Prometheus scraping, and the local telemetry path.
Evidence reviewed 6 items Current main lacks the capability: Fetched main commits and returns health snapshots without emitting an event-loop diagnostic sample, so the requested behavior is not already implemented there.
Owner-boundary producer: The head resets and commits the health window before emitting an internal sample, and emits only when diagnostics are enabled and an interested listener exists; cached healthy reads return earlier.
Private exporter path: The new event is asynchronous and excluded from public diagnostics; Prometheus accepts it only from trusted/internal metadata, while OpenTelemetry clears reader trace context before recording the metrics.
Findings None None.
Security None None.

How this fits together

Gateway health readers convert event-loop measurements into readiness and liveness snapshots. Completed windows now flow through the private diagnostics stream to enabled metrics exporters for operator monitoring.

flowchart LR
  A[Gateway health reader] --> B[Committed event-loop window]
  B --> C[Private diagnostics stream]
  C --> D[Prometheus exporter]
  C --> E[OpenTelemetry exporter]
  D --> F[Metrics scrape]
  E --> G[Telemetry collector]
Loading

Before merge

  • Resolve merge risk (P1) - Direct source/type verification of the OpenTelemetry context contract remains unavailable in this review environment; the proposed call is exercised by repository tests but not independently dependency-audited.
  • Complete next step (P2) - Verify the OpenTelemetry ROOT_CONTEXT context-argument contract from pinned dependency source or types before merge.
Agent review details

Security

None.

PR surface

Source +74, Tests +620, Docs +53. Total +747 across 20 files.

View PR surface stats
Area Files Added Removed Net
Source 8 80 6 +74
Tests 10 723 103 +620
Docs 2 115 62 +53
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 20 918 171 +747

Review metrics

Metric Value Why it matters
Production versus test delta production +80/-6; tests/support +723/-103; docs +115/-62 The production growth implements a new health-monitor event plus two exporter metric families, with substantial owner and integration coverage.

Merge-risk options

Maintainer options:

  1. Decide the mitigation before merge
    Keep the health monitor as the sole committed-window producer, preserve exporter-only collection and trace isolation, and verify the pinned OpenTelemetry context call against upstream source or types before merge.
  2. Pause or close
    Do not merge this PR until maintainers decide whether the risk is worth taking.

Technical review

Best possible solution:

Keep the health monitor as the sole committed-window producer, preserve exporter-only collection and trace isolation, and verify the pinned OpenTelemetry context call against upstream source or types before merge.

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

Not applicable: this PR adds operator diagnostics rather than repairing a reported current defect.

Is this the best way to solve the issue?

Yes, subject to the remaining dependency check: recording at the health-monitor owner preserves completed windows before later readers can replace the snapshot, while existing exporters aggregate them.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 300c092d8b4a.

Labels

Label changes:

  • add P3: This is an optional operator-observability enhancement, not a demonstrated availability or delivery regression.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: This maintainer-authored PR is exempt from the external-contributor proof gate; its inspected integration test exercises authenticated Gateway readiness, protected Prometheus scraping, and the local telemetry path.

Label justifications:

  • P3: This is an optional operator-observability enhancement, not a demonstrated availability or delivery regression.
  • 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: This maintainer-authored PR is exempt from the external-contributor proof gate; its inspected integration test exercises authenticated Gateway readiness, protected Prometheus scraping, and the local telemetry path.

Evidence

What I checked:

  • Current main lacks the capability: Fetched main commits and returns health snapshots without emitting an event-loop diagnostic sample, so the requested behavior is not already implemented there. (src/gateway/server/event-loop-health.ts:128, 300c092d8b4a)
  • Owner-boundary producer: The head resets and commits the health window before emitting an internal sample, and emits only when diagnostics are enabled and an interested listener exists; cached healthy reads return earlier. (src/gateway/server/event-loop-health.ts:184, 7aafc205b36b)
  • Private exporter path: The new event is asynchronous and excluded from public diagnostics; Prometheus accepts it only from trusted/internal metadata, while OpenTelemetry clears reader trace context before recording the metrics. (src/infra/diagnostic-events.ts:1008, 7aafc205b36b)
  • Boundary coverage: The added tests cover cached reads, diagnostics-disabled and uninterested consumers, queue pressure, Prometheus retention/series caps, OpenTelemetry signal gating, and an authenticated Gateway readiness-to-exporter flow. (test/gateway-rpc-exporters.test.ts:253, 7aafc205b36b)
  • Feature provenance: The producer lines blame to the feature commit, whose raw recorded parent diff adds the event publication; the exact PR head is the subsequent two-parent integration commit. (src/gateway/server/event-loop-health.ts:184, c9199d919ca4)
  • OpenTelemetry dependency limitation: The branch directly uses ROOT_CONTEXT, but the dependency source/types are absent and the configured promisor remote could not resolve github.com. The repository's real-SDK test exercises the call, but this review could not independently inspect the dependency contract.

Likely related people:

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

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Verify the pinned @opentelemetry/api context-argument contract from dependency source or types before merge.

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.

@steipete

steipete commented Sep 4, 2026

Copy link
Copy Markdown
Contributor Author

Re-read the complete ClawSweeper review for 7aafc20 and verified the requested OpenTelemetry dependency contract directly.

The pinned @opentelemetry/api 1.9.1 types declare Counter.add and Histogram.record with an optional Context as their third argument (build/src/metrics/Metric.d.ts:74,101); ROOT_CONTEXT is a Context backed by an empty BaseContext (context/context.d.ts:13; context.js:24–51). The pinned sdk-metrics 2.10.0 implementation forwards that third argument through Instruments.js:16–30,53–58,81–86. MultiWritableMetricStorage.js:19–25 and SyncMetricStorage.js:31–35 substitute ambient context only when none was supplied. Thus these calls retain ROOT_CONTEXT and do not inherit the health reader's active span.

The installed package/importer lock entries and the recorder plus real-SDK test match this exact PR head. Existing service.event-loop.test.ts proof exercises a preloaded SDK under an active reader trace and checks that process-wide metrics have no reader trace attached. This is a fresh source/type audit of the pinned implementation, not a claim of another test run. It resolves both dependency-access checklist items and the Rank-up request; exact-head CI remains a separate landing requirement.

Exact-head CI 33892086778, attempt 2, is now successful (111 successful jobs, 16 intentional skips). The prior unacquired-runner cancellation and old-head startup failure remain historical failure evidence. No policy or gate was bypassed.

The retained 320-test composition proof used:

node scripts/run-vitest.mjs src/gateway/server/event-loop-health.test.ts src/infra/diagnostic-events.event-loop.test.ts src/infra/diagnostic-events.test.ts src/infra/diagnostic-trace-context.test.ts src/plugins/services.test.ts extensions/diagnostics-otel/src/service.event-loop.test.ts extensions/diagnostics-otel/src/service.gateway-rpc.test.ts extensions/diagnostics-otel/src/service.test.ts extensions/diagnostics-prometheus/src/service.test.ts test/gateway-rpc-exporters.test.ts

The final 39-command changed-check coverage and P2 proof retain the qualifications already documented in the PR body; this is not a new full-wrapper or packaged-load run. Current main was checked through f45b2a45f9b764f05199e80c7b4ab17c65485e94: all 20 touched preimages remain unchanged. Its optional service Cron getter leaves exporter trust/filter/lease ownership unchanged. Main now has fs-safe 0.7.2 and unrelated Workboard dependency changes; the local composition proof remains bound to the original 0.7.1 closure, while the pinned OpenTelemetry dependencies are unchanged.

@steipete
steipete merged commit 9f1c8a1 into main Sep 4, 2026
316 of 318 checks passed
@steipete
steipete deleted the codex/event-loop-window-metrics branch September 4, 2026 17:27
@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
…penclaw#138249)

Record completed health-monitor windows through existing diagnostics so
Prometheus and OpenTelemetry retain intervals consumed by earlier readers.
Preserve readiness and lifecycle behavior and exclude reader trace identity.

Cover cumulative retention, disabled consumers, queue and series limits,
real SDK context handling, and managed-install Gateway authentication and
graceful shutdown.
steipete added a commit that referenced this pull request Sep 5, 2026
…39247)

Observe process close under the existing test lifetime instead of invoking the
five-second forced reaper as the graceful-shutdown assertion path. Keep exact
exit and signal assertions, forced teardown, and install/metrics coverage.
Retain termination state and post-stop Gateway logs on failure.

Follow up the graceful-shutdown coverage added in #138249.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 6, 2026
…enclaw#139247)

Observe process close under the existing test lifetime instead of invoking the
five-second forced reaper as the graceful-shutdown assertion path. Keep exact
exit and signal assertions, forced teardown, and install/metrics coverage.
Retain termination state and post-stop Gateway logs on failure.

Follow up the graceful-shutdown coverage added in openclaw#138249.
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: L 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