Skip to content

perf(prometheus): reduce temporary scrape allocations - #139535

Merged
steipete merged 1 commit into
mainfrom
codex/perf11-prometheus-scrape
Sep 6, 2026
Merged

steipete merged 1 commit into
mainfrom
codex/perf11-prometheus-scrape

Conversation

@steipete

@steipete steipete commented Sep 6, 2026

Copy link
Copy Markdown
Contributor

What Problem This Solves

Resolves repeated copying and label formatting during Prometheus scrapes, especially near the exporter’s series cap. Rendering copied metric maps, expanded them into arrays, copied those arrays again for sorting, and repeatedly sorted/escaped histogram labels for buckets, sum, and count.

Why This Change Was Made

extensions/diagnostics-prometheus/src/service.ts creates fresh scrape-local entry arrays directly from its canonical private maps, sorts those arrays, shares counter/gauge rendering, and reuses sorted/escaped histogram-label fragments within a scrape. Projection remains synchronous; the former map snapshots were shallow and did not isolate sample objects.

The current-main composition preserves the original optimization and main’s newly added openclaw_gateway_build_info gauge. That existing gauge reserves one slot in the same 2,048-sample cap, captures process identity and optional build ID once at enabled startup, and clears/repopulates on stop/restart. It still uses ordinary gauge rendering. Runtime identity remains with the service host’s lease-validated callback; the optimization changes neither identity lookup nor admission/retention.

Production remains +46/-52 lines (net -6); tests/support: +0/-0. No persistent cache, runtime state, dependency, or identity capability is added by this PR.

User Impact

Scrapes allocate fewer temporary objects while preserving metric names, labels, escaping, buckets, privacy, cap/drop accounting, build identity, reset behavior, and HTTP metadata. Existing series continue updating after saturation, and the reserved build-info sample survives saturation.

Evidence

The new sealed proof compares main 3dff8818ef42872cecc3899b41dffd95942fe70f with that baseline plus the exact reviewed performance edits. Eleven complete body pairs match byte-for-byte, covering startup/restart, mixed metrics, stop/disabled diagnostics, RPC cap/update/overflow, model cap, process-only identity, and unavailable identity capability. The original four-run measurements remain historical; no original output is reused as current-composition proof.

The actual exporter receives synthetic events through the real diagnostic dispatcher. Controlled runtime identity preserves exact comparisons. The build-info sample appears once with value 1 and correctly ordered labels; process/build IDs stay confined to it. With the lifecycle counter and gauge admitted first, RPC drops remain 89 after existing-series updates and rise to 91 for two unseen samples; model drops are 2,154 in both arms.

Six HTTP states per arm exercise real local GET/HEAD/POST, including saturation and optional/disabled identity cases. GET/HEAD return 200, POST returns 405 with Allow: GET, HEAD, HEAD is empty, and Content-Length matches each GET body—including the 31,140-byte mixed response and zero-byte disabled response. All 12 servers close; stop removes subscriptions. Five enabled identity-bearing starts make five identity reads despite repeated scrapes; disabled startup makes none.

One fresh allocation observation per arm on Node 26.8.1/macOS arm64:

Workload Projections Baseline sampled bytes Composed sampled bytes
Mixed 300 237,514,760 82,368,456
RPC cap 25 1,801,207,000 431,546,848
Model cap 25 2,700,152,232 638,509,816

These 4 KiB cumulative V8 samples include collected objects after five warmups; imports, event seeding, and HTTP are excluded. The single shared-host pair is descriptive corroboration, not retained heap/RSS, statistical significance, whole-Gateway performance, or authentication/installation proof.

node scripts/run-vitest.mjs extensions/diagnostics-prometheus/src/service.test.ts extensions/diagnostics-prometheus/src/service.event-loop.test.ts extensions/diagnostics-prometheus/src/service.runtime-identity.test.ts src/plugins/services.runtime-identity.test.ts
node scripts/run-oxlint.mjs --tsconfig extensions/tsconfig.json extensions/diagnostics-prometheus/src/service.ts

Both arms pass 32 tests: 31 plugin tests and one host lease/identity test. Candidate type-aware plugin lint and formatting pass. Independent P2 review of this composition records no actionable findings. Broad duplicate gates were not run; final exact-head required CI/native landing and applicable integration gates remain with publication.

@clawsweeper

clawsweeper Bot commented Sep 6, 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 6, 2026 00:01
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. 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 6, 2026
@clawsweeper

clawsweeper Bot commented Sep 6, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 5, 2026, 8:07 PM ET / September 6, 2026, 00:07 UTC.

ClawSweeper review

What this changes

The Prometheus metrics plugin reduces temporary scrape allocations by sorting fresh entry arrays and reusing formatted histogram labels.

Merge readiness

✅ Ready for maintainer review

Keep open as a useful performance improvement absent from pinned main. No introduced correctness or security defects were found; this maintainer-authored PR remains a viable landing candidate.

Priority: P2
Reviewed head: 7fc0ad93e811195f0f53c7d3fe101f150f3612fb

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused, maintainable optimization with relevant reported runtime observations and no actionable defects found.
Proof confidence 🐚 platinum hermit (4/6) Not applicable: The ordinary contributor proof gate is exempt for this MEMBER-authored PR, and no authority change activates an additional gate. The captured body reports actual exporter/dispatcher and local HTTP comparisons on macOS arm64 covering the changed renderer, with identical responses and lower sampled allocations; raw artifacts were not independently inspected.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The ordinary contributor proof gate is exempt for this MEMBER-authored PR, and no authority change activates an additional gate. The captured body reports actual exporter/dispatcher and local HTTP comparisons on macOS arm64 covering the changed renderer, with identical responses and lower sampled allocations; raw artifacts were not independently inspected.
Evidence reviewed 7 items Verified introduced change: The complete pinned base-to-head diff changes only private sample projection and formatting. Sorting operates on fresh arrays; histogram fragments remain scrape-local. Collection, retention, runtime identity, and HTTP handling are unchanged.
Optimization still needed on pinned main: Pinned main still copies maps, expands their entries, copies arrays for sorting, and formats each histogram bucket separately. No merged replacement is established by the supplied context.
Proof baseline matches reviewed renderer: The proof baseline 3dff881 and pinned main resolve this file to the identical blob ea1fedfa23aa4450c7beacf2850cd41f2e44f019. The latest-release file has a different blob; release inclusion of this optimization is not established.
Findings None None.
Security None None.

How this fits together

The Prometheus plugin aggregates diagnostic events into bounded in-memory metrics. Its authenticated HTTP endpoint renders those metrics for monitoring systems.

flowchart LR
  A[Diagnostic events] --> B[Trusted event filter]
  B --> C[Bounded metric store]
  D[Authenticated scrape request] --> E[Scrape renderer]
  C --> E
  E --> F[Prometheus text response]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source -6. Total -6 across 1 file.

View PR surface stats
Area Files Added Removed Net
Source 1 46 52 -6
Tests 0 0 0 0
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 1 46 52 -6

Review metrics

Metric Value Why it matters
Reported sampled allocation reduction Mixed approximately 65%; RPC cap approximately 76%; model cap approximately 76% The reported single before/after pair supports the allocation goal without establishing retained-memory or whole-Gateway performance gains.

Technical review

Best possible solution:

Keep the optimization within the existing synchronous renderer while preserving metric bytes, bounded retention, and lifecycle semantics.

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

Not applicable as a functional bug reproduction: this is an allocation optimization, and current-main source directly shows the redundant copying and repeated formatting.

Is this the best way to solve the issue?

Yes. Reusing scrape-local arrays and label fragments removes redundant work without adding cache invalidation, changing public APIs, or mutating canonical metric maps.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 8964a4d8dc2f.

Labels

Label changes:

  • add P2: This is a bounded monitoring-performance improvement, especially useful near the exporter’s series cap.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit 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: The ordinary contributor proof gate is exempt for this MEMBER-authored PR, and no authority change activates an additional gate. The captured body reports actual exporter/dispatcher and local HTTP comparisons on macOS arm64 covering the changed renderer, with identical responses and lower sampled allocations; raw artifacts were not independently inspected.

Label justifications:

  • P2: This is a bounded monitoring-performance improvement, especially useful near the exporter’s series cap.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit 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 ordinary contributor proof gate is exempt for this MEMBER-authored PR, and no authority change activates an additional gate. The captured body reports actual exporter/dispatcher and local HTTP comparisons on macOS arm64 covering the changed renderer, with identical responses and lower sampled allocations; raw artifacts were not independently inspected.

Evidence

What I checked:

  • Verified introduced change: The complete pinned base-to-head diff changes only private sample projection and formatting. Sorting operates on fresh arrays; histogram fragments remain scrape-local. Collection, retention, runtime identity, and HTTP handling are unchanged. (extensions/diagnostics-prometheus/src/service.ts:172, 7fc0ad93e811)
  • Optimization still needed on pinned main: Pinned main still copies maps, expands their entries, copies arrays for sorting, and formats each histogram bucket separately. No merged replacement is established by the supplied context. (extensions/diagnostics-prometheus/src/service.ts:177, 8964a4d8dc2f)
  • Proof baseline matches reviewed renderer: The proof baseline 3dff881 and pinned main resolve this file to the identical blob ea1fedfa23aa4450c7beacf2850cd41f2e44f019. The latest-release file has a different blob; release inclusion of this optimization is not established. (extensions/diagnostics-prometheus/src/service.ts, 8964a4d8dc2f)
  • Captured runtime observations: The supplied PR body at context sourceRevision 40d2a29915872092ace1732fdf4a08f9c0cab6efa867a091690395e643c10b45 reports eleven byte-identical response pairs, real local GET/HEAD/POST requests across six states per arm, preserved saturation/reset behavior, and lower sampled allocations on Node 26.8.1/macOS arm64. These are contributor-reported observations; no raw sealed artifact was linked or independently executed in this review. (7fc0ad93e811)
  • Existing boundary coverage: Inspected tests protect continued updates after saturation, overflow accounting, stop/reset behavior, and byte-accurate GET/HEAD metadata. Separate runtime-identity and event-loop tests cover repeated scrapes, startup identity capture, and label-free histogram buckets. Tests were read, not run. (extensions/diagnostics-prometheus/src/service.test.ts:803, 7fc0ad93e811)
  • Security and implementation boundary: The existing route requires Gateway authentication on the trusted-operator surface. The changed renderer uses local metric data and OpenClaw SDK contracts; no Codex dependency contract, new authority transfer, persistent storage, or supply-chain change is introduced. (extensions/diagnostics-prometheus/index.ts:14, 7fc0ad93e811)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • zengLingbiao: 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.

@steipete
steipete merged commit 61690da into main Sep 6, 2026
162 checks passed
@steipete
steipete deleted the codex/perf11-prometheus-scrape branch September 6, 2026 00:19
@steipete

steipete commented Sep 6, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

extensions: diagnostics-prometheus maintainer Maintainer-authored PR P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: S 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.

1 participant