Skip to content

feat(diagnostics-prometheus): let plugins add metric families to the scrape route - #198455

Merged
roboclaw-bot merged 6 commits into
openclaw:mainfrom
etzelm:pc/i197880
Nov 18, 2026
Merged

roboclaw-bot merged 6 commits into
openclaw:mainfrom
etzelm:pc/i197880

Conversation

@etzelm

@etzelm etzelm commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Closes #197880

What Problem This Solves

A plugin that wants operator metrics has to serve its own HTTP route, so operators add a second Prometheus scrape job for one Gateway, and that plugin's series skip the exporter's label and series budget.

User Impact

Prometheus still scrapes one authenticated Gateway URL. Core metrics work as before. Plugin metrics are off by default per plugin, even if both Prometheus and the producer plugin are enabled. To publish one plugin’s metrics, explicitly set plugins.entries.<producer-id>.allowMetrics: true. This setting does not enable the plugin or the exporter, and does not change other plugins. Omitting the setting or setting it to false keeps that plugin’s api.metrics undefined.

{ plugins: { entries: {
  "diagnostics-prometheus": { enabled: true },
  "my-plugin": { enabled: true, allowMetrics: true },
} } }

Risks:

  • The type change is additive and optional. Plugins built against this host that use api.metrics?. run unchanged on older hosts, where the field is absent.
  • Samples recorded during register() are dropped, because the exporter service starts after registration. Plugins record from their runtime paths (routes, services, hooks).
  • Reloading a plugin resets its counters in the scrape: the Gateway disposes the previous instance before it registers the replacement, so the old series are dropped and new ones start at zero. Prometheus treats this like any counter reset.
  • Plugin label values are checked only against the character policy, not redacted. A plugin could still put an identifier in a label; the 128 series cap per family bounds the cardinality cost of that mistake.

Why This Change Was Made

#197880 is marked as needing a product decision; this PR is a concrete proposal for that contract, with working code.

api.metrics is a small optional field on the plugin API:

const metrics = api.metrics?.register({
  families: [
    { name: "retain_total", type: "counter", help: "Retains by outcome", labels: ["outcome"] },
    { name: "recall_seconds", type: "histogram", help: "Recall latency", buckets: [0.05, 0.1, 0.5, 1, 5] },
  ],
});
metrics?.counter("retain_total").inc({ outcome: "ok" });
metrics?.histogram("recall_seconds").observe({}, 0.12);
  • Namespace: the host sets it. Every family becomes openclaw_plugin_<plugin id>_<name>, so a plugin cannot claim another plugin's names. The issue proposed a plugin-chosen namespace; this is the main point for owners to decide.
  • Budget: plugin families get no reserve. They draw from the existing shared pool, keep at most 128 label sets per family, and drops appear in openclaw_prometheus_family_series_dropped_total{family="openclaw_plugin_..."}. Core reserves do not change.
  • Lifecycle: declarations are admitted under the existing plugin lifecycle authority (capturePluginLifecycleAuthority, captured when register() runs), and samples are delivered only while the recording instance is the published one (isPluginRecordActive, the same check the session attachment path uses). There is no separate fence for metrics. A replacement instance can register the same families during a reload, but what it records before the reload commits (from register() or a service started in the preparation scope) is dropped and cannot reset the live instance's series. A previous instance that a failed reload resumes keeps its series and recorders without registering again. A family leaves the scrape only when no remaining registration of the plugin declares it: when the same instance registers again without it, or when its owning instance is disposed. When the exporter stops, plugin series reset with the core series.
  • Exporter availability: the operator grants the producing plugin a recorder; delivery requires a live exporter. No listener means samples are discarded, not buffered. Starting or stopping Prometheus does not require a producer reload.
  • Consumer: @etzelm/openclaw-memory-hindsight, a memory slot plugin, serves its own Prometheus route (/plugins/hindsight-native/metrics) today, so operators add a second scrape job. With this API it would register recall_total, retain_total, recall_skipped_total, retain_queue_replays_total, retain_queue_drops_total (counters), retain_queue_depth (gauge), and recall_duration_seconds, retain_duration_seconds, recall_injected_memories, recall_injected_chars (histograms), labelled by agent, bank and fixed outcome or reason enums, and drop the route.

Owners can accept this shape or redirect it; the registration, namespace and allocation choices are theirs to make.

Admission, delivery and SDK surface details
  • api.metrics is defined only for the live full registration, and only if the operator opts this producer in. Otherwise it is undefined; optional chaining keeps plugin code compatible. Samples recorded while no exporter listens are dropped.
  • The plugin id is lowercased and other characters become _, so two ids can still map to one exported name (a-b and a_b, or plugin foo family bar_baz and plugin foo_bar family baz). The second registration of such a name throws at load, so the clash is loud but depends on load order. A histogram also reserves its _bucket, _sum and _count names, so histogram lat and gauge lat_count cannot both register, in one plugin or across plugins (plugin a histogram x blocks plugin a_x gauge count).
  • register() checks names, counter _total suffixes, declared label names and histogram buckets, and throws during plugin load on bad input. A sample whose labels differ from the declaration is dropped with one warning per family on the plugin logger. Label values outside the low-cardinality policy ([A-Za-z0-9_.:-], at most 120 characters) are exported as other.
  • Each register() result is one registration owned by its plugin instance. The first call binds teardown to the instance (lifecycle.onDispose) and captures the instance's lifecycle authority; register() throws when that authority cannot be minted (a disposed, retired or not-yet-published instance outside its own registration). Recorders publish only while their registration is held, the authority still holds and the record is published, so an instance paused by a reload drops samples until it resumes, and an uncommitted replacement's samples (including ones recorded inside the reload preparation scope, where the authority itself still allows calls) are dropped until publication.
  • Re-registration by the same instance replaces only that instance's families and retires the ones no other instance of the plugin declares; recorders from the earlier call go quiet. Disposing an instance retires only names no remaining instance declares, so neither a disposed nor an older instance can evict the live instance's families. If a family's type, help, labels or buckets differ between instances, the exporter drops the old series once the new shape is published: when the previous instance is disposed after the reload commits, or at the first published sample of the new shape, whichever comes first. The scrape keeps one TYPE block per name, and a failed replacement never reaches this step.
  • Delivery follows the existing exporter listeners (onGatewayWsMetrics, onWorkerRequestMetrics): a new trusted internalDiagnostics.onPluginMetrics listener, offered only to the trusted diagnostics exporters and bound to the service capability lease. Core keeps no metric values.
  • No new SDK export names. The types are reachable as NonNullable<OpenClawPluginApi["metrics"]>. The SDK surface changes only by the new optional metrics field on OpenClawPluginApi and the optional onPluginMetrics on the service context's internalDiagnostics.
  • Docs: a "Plugin metric families" section in docs/gateway/prometheus.md and one row in the SDK overview field table.

Evidence

  • The per-plugin regression failed on 27e80d369930 (an unapproved plugin still received the recorder), then passed after the fix. The same operator config covers allowed, denied, and unlisted plugins, including mixed-case plugin IDs.
  • An isolated AWS run passed the updated producer registration/lifecycle and Prometheus rendering suites, including stopping and restarting the exporter listener with the same opted-in producer. The config documentation baseline was regenerated and checked against the integrated main branch.
  • The earlier review found that exporter-only reload could leave a producer without its recorder. 7e78ce7546ca removed that coupling. CI subsequently flagged unsafe reserve-table indexing, mock isolation, test allocation, and two unnecessary conversions. The repair uses an own-key type guard and string diagnostics, and documents the mock’s isolated request scope. The three ratchets passed against the integrated base. The 217-line test allocation covers the 617 net test lines minus the standard 400; it retains distinct regressions for producer opt-in/denial, overlapping registration and retirement, exporter reload, and shared-series limits.

Live Gateway upgrade and scrape, 339c12b0edfb5e20efeed381e13aafc01f5650ee

On isolated Linux, the published 2026.11.5 package (e13cf15, npm integrity verified) ran two fixture plugins. Its own CLI saved one plugin setting, and authenticated requests to that plugin wrote two SQLite rows. Both plugins were enabled, neither had an allowMetrics setting, and the exporter was off. Stopped stable, ran the candidate’s normal doctor --fix --non-interactive migration, and started the Gateway built from this exact PR head against the same config, state and plugin databases. The original producer entries, load paths, setting and both rows survived. Nothing opted itself in.

Operator action on the upgraded Gateway Authenticated scrape Producer result
No config change 404 Both recorders absent, as on stable
Enable only Prometheus 200, core build info Neither producer exported
Set allowMetrics: true only on allowed-producer; hit both producers 200, openclaw_plugin_allowed_producer_hits_total 1 Ordinary producer absent
Stop then start only the exporter 404 → 200 Both registration UUIDs unchanged; approved counter reads 1 after a new hit, not a replay of samples while off
Set that producer’s allowMetrics to false 200, core build info Neither producer exported; both stored rows still present

pnpm build, targeted type-aware lint and the 11 registration/lifecycle tests passed on this head. The 5 exporter tests passed on its parent; the final commit only touched the producer declaration error wording. The fixture used the real Gateway, real HTTP requests and two deterministic local producers, not a production Hindsight deployment. Exact-head CI. No owner sign-off is implied by the proof.

Review and CI on this head: ClawSweeper accepted the live and upgrade proof, reported no findings or pre-merge checklist items, and recommends accepting the SDK contract; a maintainer still owns that decision. The lint and baseline-ratchet jobs that failed on the previous head now pass. CI remains blocked: the Discord transcript capture test rejects a native broker socket during setup/cleanup (unexpected socket destination null:NaN). An unrelated PR hit the identical assertion, and a clean-main reproduction is documented here. The test, broker client and catalog-worker files are byte-identical between that reproduced main parent and this run’s main parent. Our own clean-base run stopped earlier on a temp-directory permission check, so it is not counted as a reproduction. No test guard or CI status was overridden.

Original contributor proof (before per-plugin opt-in)

Isolated Gateway (openclaw.mjs gateway run, token auth, diagnostics-prometheus enabled) with a small standalone fixture plugin that calls api.metrics?.register(...) and records one counter, gauge and histogram sample per request to its route. Two requests, then one scrape:

Build api.metrics Scrape openclaw_plugin_ lines
origin/main undefined 200 0
this branch defined 200 13
this branch, exporter disabled undefined 404 0

Reload through the same Gateway: a manifest fixture whose gauge records which registration served the request. A config edit replaces the plugin; a second edit sets fail: true, so the replacement's register() throws right after api.metrics.register(), and the Gateway restores the previous registration (it registers the previous code and config again, "registration 4" in the log). Sample lines per scrape (7 = counter, gauge and 5 histogram lines):

Step Previous revision of this branch This branch
1. start, 2 requests 7 lines, jobs_total 2, instance 1 7 lines, jobs_total 2, instance 1
2. reload applied, 1 request 7 lines, jobs_total 1, instance 2 7 lines, jobs_total 1, instance 2
3. failed reload, previous restored, 2 requests 7 lines, jobs_total 2, instance 4 7 lines, jobs_total 2, instance 4

The Gateway disposes the previous instance before registering a replacement, so this path re-registers and both revisions keep the families. The other recovery path, a reload that fails early and resumes the paused previous instance without registering it again, is not reachable from a config edit; the "keeps the live instance's families when a reload fails and the instance resumes" test drives it through the real registry, lifecycle authority and PluginInstance pause/resume, and fails on the previous revision.

Scrape lines on this branch
# HELP openclaw_plugin_metrics_fixture_jobs_total Fixture jobs by outcome
# TYPE openclaw_plugin_metrics_fixture_jobs_total counter
openclaw_plugin_metrics_fixture_jobs_total{outcome="ok"} 2
# HELP openclaw_plugin_metrics_fixture_queue_depth Fixture queue depth
# TYPE openclaw_plugin_metrics_fixture_queue_depth gauge
openclaw_plugin_metrics_fixture_queue_depth 3
# HELP openclaw_plugin_metrics_fixture_job_seconds Fixture job latency
# TYPE openclaw_plugin_metrics_fixture_job_seconds histogram
openclaw_plugin_metrics_fixture_job_seconds_bucket{le="0.1"} 0
openclaw_plugin_metrics_fixture_job_seconds_bucket{le="1"} 2
openclaw_plugin_metrics_fixture_job_seconds_bucket{le="+Inf"} 2
openclaw_plugin_metrics_fixture_job_seconds_sum 0.5
openclaw_plugin_metrics_fixture_job_seconds_count 2

After the failed reload (step 3):

openclaw_plugin_metrics_fixture_jobs_total{outcome="ok"} 2
openclaw_plugin_metrics_fixture_recording_instance 4
openclaw_plugin_metrics_fixture_job_seconds_bucket{le="0.1"} 0
openclaw_plugin_metrics_fixture_job_seconds_bucket{le="1"} 2
openclaw_plugin_metrics_fixture_job_seconds_bucket{le="+Inf"} 2
openclaw_plugin_metrics_fixture_job_seconds_sum 0.5
openclaw_plugin_metrics_fixture_job_seconds_count 2

Tests:

  • New src/plugins/plugin-metrics.test.ts (10 tests): api.metrics undefined with no exporter, an explicitly disabled exporter, a scoped registry or discovery mode, and defined with only diagnostics-otel on; prefixed samples reach the trusted exporter listener and stop after the lease is revoked; label mismatch drops with one warning and unsafe values become other; invalid and colliding families are rejected; histogram _bucket/_sum/_count names are reserved in one call, in either order, and across plugins in both directions; the same instance registering again retires only its stale family and silences old recorders, and disposal releases the names; a replacement registering during a reload leaves the live instance's family alone, the paused instance drops samples, the failed replacement's disposal retires only its own new family, and the resumed instance records again without a second register(); a committed reload hands shared families to the replacement, restarts a relabelled family at its first new sample, and retires only the family the replacement dropped; for a generationOverlap plugin, a replacement that relabels a family and records from inside its real register() call and from the real reload preparation scope (withPluginRegistryPreparationScope, where candidate services start) delivers nothing and retires nothing while the live instance keeps recording; a failed replacement leaves the live series intact, and a committed one switches the relabelled family over when the previous instance is disposed; a disposed or older instance cannot register or evict the live family. Registration runs inside the loader's real register() call with the registry's lifecycle authority. Red on origin/main (Cannot find module './plugin-metrics.js'); on the previous revision of this branch the preparation-scope test fails (expected "vi.fn()" to not be called at all, but actually been called 2 times: the replacement's uncommitted samples retired the live series) and the other 9 pass.
  • New extensions/diagnostics-prometheus/src/service.plugin-metrics.test.ts (5 tests): rendered counter, gauge and histogram text; 133 label sets admit 128 and count 5 in the family drop counter; retired families leave the scrape and a re-registered name renders one TYPE block; retiring a full family releases its series budget; exporter stop clears plugin series. Red on origin/main (expected Plugin metrics listener to be defined, the exporter never subscribes), green here.
  • pnpm test src/plugins/plugin-metrics.test.ts extensions/diagnostics-prometheus: 8 files, 77 tests pass.
  • pnpm test on the 29 src/plugins files for registry*, api-facades* and service-diagnostics*: 324 tests pass.
  • pnpm test on the 6 src/gateway/server-plugin-reload* files other than the one listed below: 146 tests pass.
  • pnpm test on 926 more files across src/plugins and src/plugin-sdk: pass, except the failures listed below. update.work-deadline.test.ts and plugin-metadata-state-worker.test.ts failed once on a heavily loaded host and pass when rerun alone.
  • Not run locally: src/plugins/loader.test.ts, plugin-module-generation.sdk.test.ts, setup-registry.migrations.test.ts, source-checkout-runtime.test.ts and src/plugin-sdk/channel-entry-contract.lifecycle.test.ts. The test runner refuses to prepare their built runtime on the test host (it cannot verify separation from a managed Gateway install), so PR CI is their first run. loader.test.ts is the most direct consumer of the registry change.
  • pnpm tsgo:core, tsgo:extensions, tsgo:core:test, tsgo:extensions:test, pnpm build, pnpm check:docs, pnpm plugin-sdk:check-exports, and format check on the touched files: pass.
  • pnpm plugin-sdk:api:diff --base <origin/main> --head <this branch>: passes with no export added or removed; 11 reachable declarations changed (the optional metrics field, the optional onPluginMetrics listener and the new metric types they reference). Acknowledgement digest fa187f0a (against origin/main f3957e8653e).

Not caused by this change, same result on origin/main:

  • pnpm lint: fails on findings in unrelated files (13 max-lines errors among them); the finding list is identical on origin/main.
  • pnpm plugin-sdk:surface:check: fails with the same four budget counts on origin/main (entrypoints 163 > 162, exports 3888 > 3867, callable exports 2243 > 2236, wildcard re-exports 1 > 0). This branch adds no SDK export names.
  • src/plugins/plugin-preparation-exec-argv.test.ts fails on origin/main too, with a Darwin descriptor ACL error from the test host.
  • src/gateway/server-plugin-reload.installed-package.test.ts ("loads installed package roots and retains a sibling with empty runtime conf...") fails the same way on origin/main f3957e8653e.
  • bundled-plugin-icons.test.ts (no extensions/celeris/assets/icon.png on origin/main), bundled-plugin-categories.test.ts (perplexity category) and plugin-sdk-deprecated-imports.test.ts fail the same way on origin/main; this branch touches none of their inputs.

@clawsweeper

clawsweeper Bot commented Nov 13, 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.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime extensions: diagnostics-prometheus size: XL labels Nov 13, 2026
@clawsweeper clawsweeper Bot added P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Nov 13, 2026
@clawsweeper

clawsweeper Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: ready, awaiting a maintainer decision.

What this changes

This PR lets individually opted-in plugins publish metric families through the existing authenticated Prometheus scrape route.

Example: Enable allowed-producer with allowMetrics: true and record one hit.

  • Before: The plugin needs a separate metrics route and Prometheus scrape job.
  • After: The existing scrape includes openclaw_plugin_allowed_producer_hits_total 1.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Meaningful shipped-entry-point and latest-stable upgrade evidence support the implementation; overall readiness remains capped by the unresolved public-contract decision.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The exact-head isolated Linux Gateway evidence exercises authenticated producer requests and scrapes, permission grant and removal, and exporter restart without producer reload; earlier live output covers all three metric types and producer reload recovery, resolving the previous review's proof gap.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Feature · Worth it: Needs a maintainer decision · Fix scope: Complete
User problem: Operators need a second scrape job for plugin metrics, which also bypass the existing exporter's admission budgets.
Reason: The named consumer establishes practical value, while adopting a new SDK capability and producer permission remains an owner choice.

Merge readiness

⏳ Ready, awaiting maintainer decision

Keep open: this PR fills a verified plugin capability gap, has meaningful Gateway proof, and has no identified correctness blocker; its public contract still needs a maintainer decision.

Priority: P3
Reviewed head: 339c12b0edfb5e20efeed381e13aafc01f5650ee
Owner decision: Required. See Decision needed.

Decision needed

  • Question: Should OpenClaw adopt this optional api.metrics contract with per-plugin allowMetrics permission, host-derived namespaces, and shared-pool allocation without plugin reserves?
  • Recommendation: Accept the proposed contract: Approve the generic contribution seam for the named memory-plugin consumer, retaining explicit producer opt-in and existing exporter ownership.
  • Why: The implementation demonstrates the capability, but neither this PR nor its linked issue records owner acceptance of the new public API and configuration contract.

Before merge

None.

Findings

None.

Agent review details

How this fits together

The plugin registry grants lifecycle-bound recorders, a broker forwards samples to trusted exporters, and the Prometheus store applies its existing admission budgets before rendering the authenticated scrape.

flowchart LR
  A[Operator plugin settings] --> B[Plugin registry]
  B --> C[Plugin metric recorder]
  C --> D[Lifecycle bound broker]
  D --> E[Prometheus metric store]
  E --> F[Authenticated scrape route]
  F --> G[Prometheus]
Loading

Technical review

Best possible solution:

Approve a narrow lifecycle-owned contribution contract that keeps metric values and admission in the existing exporter.

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

This is a capability request; current-main source confirms the missing API, and supplied Gateway output demonstrates the proposed behavior without executing target code during this review.

Is this the best way to solve the issue?

The proposal uses the existing store, transport, budgets, and lifecycle owners; its declaration broker handles distinct namespace, shape, and retirement responsibilities without a second metric-value store.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 1619ecb28838.

Provenance checked

  • Prometheus admission and family reservations keeps the original intent (b98018c: Protect late core families from starvation and expose bounded family-drop accounting.)
  • Plugin instance registration and cleanup keeps the original intent (05a2844: Keep registered callbacks and cleanup with their supplying plugin instance across replacement and retirement.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit b98018c adds extensions/diagnostics-prometheus/src/prometheus-metric-store.ts:108 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: b98018c4433d; files: extensions/diagnostics-prometheus/src/prometheus-metric-store.ts)

PR surface

Source +483, Tests +617, Docs +46, Generated 0, Other +1. Total +1147 across 21 files. Added test files: 2.

View PR surface stats
Area Files Added Removed Net
Source 13 504 21 +483
Tests 3 617 0 +617
Docs 2 62 16 +46
Config 0 0 0 0
Generated 2 3 3 0
Other 1 1 0 +1
Total 21 1187 40 +1147

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Review metrics

Metric Value Why it matters
New operator setting 1 optional per-plugin boolean plugins.entries.<id>.allowMetrics defaults to disabled and controls access to the new recorder API.

Labels

Label changes:

No label changes.

Label justifications:

  • P3: This is an optional monitoring improvement with an existing separate-route workaround.
  • merge-risk: 🚨 compatibility: The PR adds a public plugin API and persisted configuration field whose permanent semantics require owner agreement; existing configuration remains unchanged in the supplied upgrade proof.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: ⏳ waiting on maintainer: Only explicit maintainer approvals or decisions remain; merge is still blocked.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (3 earlier review cycles)
  • reviewed 2026-11-13T21:02:48.666Z sha 8df4744 :: blocked before merge. :: [P2] Restrict sample delivery to the published plugin instance
  • reviewed 2026-11-13T23:18:43.498Z sha 27e80d3 :: ready, awaiting a maintainer decision. :: none
  • reviewed 2026-11-18T02:27:04.507Z sha af7113f :: needs real behavior proof before merge. :: none

Reviewed November 17, 2026, 9:59 PM ET / November 18, 2026, 02:59 UTC (Revision 4).

…scrape route

- Add optional api.metrics.register() for counters, gauges and histograms;
  it is defined only in the live full registry while a diagnostics exporter
  plugin (diagnostics-prometheus or diagnostics-otel) is enabled. Only
  diagnostics-prometheus consumes the families today.
- Prefix every family with openclaw_plugin_<plugin id>_ and reject invalid
  names, labels, buckets and collisions at registration. A histogram also
  reserves its _bucket, _sum and _count names, within one plugin and across
  plugins.
- Deliver samples through a trusted internalDiagnostics.onPluginMetrics
  listener; the exporter stores them with no reserve, sharing the existing
  pool and per-family cap and drop counters.
- Admit declarations under the plugin lifecycle authority captured at
  register(), but deliver samples only while the recording instance is the
  published one (isPluginRecordActive). A replacement that registers or
  starts services inside the reload preparation scope cannot record or reset
  the live instance's series before it commits, so a previous instance
  restored after a failed reload keeps its series and recorders.
- Retire a family only when no remaining registration of the plugin declares
  it: on re-registration by the same instance (stale families) and on
  disposal of the owning instance. A changed type, help, label set or bucket
  list starts the family over at its first new sample, or when the previous
  instance is disposed after a committed reload.
- Document the API in the Prometheus guide and the SDK API field table.

Closes openclaw#197880
@etzelm
etzelm marked this pull request as ready for review November 13, 2026 23:12
@etzelm

etzelm commented Nov 13, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on maintainer Only explicit maintainer approvals or decisions remain; merge is still blocked. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Nov 13, 2026
@roboclaw-bot roboclaw-bot added the clawtributors PR from a clawtributor label Nov 14, 2026
roboclaw-bot and others added 3 commits November 18, 2026 02:06
Keep core diagnostics available without exposing plugin-owned metrics. The live registry grants the metrics API only to producers the operator explicitly allows.

Co-authored-by: VACInc <[email protected]>
@roboclaw-bot

Copy link
Copy Markdown
Collaborator

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

roboclaw-bot and others added 2 commits November 18, 2026 02:33
Retain the lifecycle, reload and shared-series regression matrix with an explicit 217-line allocation.

Co-authored-by: VACInc <[email protected]>
@roboclaw-bot

Copy link
Copy Markdown
Collaborator

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@roboclaw-bot
roboclaw-bot merged commit bd1c54c into openclaw:main Nov 18, 2026
246 of 252 checks passed
@roboclaw-bot

Copy link
Copy Markdown
Collaborator

Merged via explicitly authorized admin squash with attributed pre-existing CI failures.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 18, 2026
…scrape route (openclaw#198455)

* feat(diagnostics-prometheus): let plugins add metric families to the scrape route

- Add optional api.metrics.register() for counters, gauges and histograms;
  it is defined only in the live full registry while a diagnostics exporter
  plugin (diagnostics-prometheus or diagnostics-otel) is enabled. Only
  diagnostics-prometheus consumes the families today.
- Prefix every family with openclaw_plugin_<plugin id>_ and reject invalid
  names, labels, buckets and collisions at registration. A histogram also
  reserves its _bucket, _sum and _count names, within one plugin and across
  plugins.
- Deliver samples through a trusted internalDiagnostics.onPluginMetrics
  listener; the exporter stores them with no reserve, sharing the existing
  pool and per-family cap and drop counters.
- Admit declarations under the plugin lifecycle authority captured at
  register(), but deliver samples only while the recording instance is the
  published one (isPluginRecordActive). A replacement that registers or
  starts services inside the reload preparation scope cannot record or reset
  the live instance's series before it commits, so a previous instance
  restored after a failed reload keeps its series and recorders.
- Retire a family only when no remaining registration of the plugin declares
  it: on re-registration by the same instance (stale families) and on
  disposal of the owning instance. A changed type, help, label set or bucket
  list starts the family over at its first new sample, or when the previous
  instance is disposed after a committed reload.
- Document the API in the Prometheus guide and the SDK API field table.

Closes openclaw#197880

* feat(plugins): require per-plugin opt-in for exported metrics

Keep core diagnostics available without exposing plugin-owned metrics. The live registry grants the metrics API only to producers the operator explicitly allows.

Co-authored-by: VACInc <[email protected]>

* fix(plugins): retain opted-in metrics recorders across exporter reloads

Co-authored-by: VACInc <[email protected]>

* test(prometheus): satisfy metrics safety and coverage ratchets

Retain the lifecycle, reload and shared-series regression matrix with an explicit 217-line allocation.

Co-authored-by: VACInc <[email protected]>

* fix(plugins): report invalid metric declarations without coercion

Co-authored-by: VACInc <[email protected]>

---------

Co-authored-by: VACInc <[email protected]>
vincentkoc pushed a commit that referenced this pull request Nov 18, 2026
Apply hosted file-count bounds during weighted balancing instead of slicing already-balanced stripes into stranded tails. Preserve the 77-row hourly nondist cap, runner and worker limits, time budgets, and complete selected inventory.

The scheduled manifest reproduced 78 > 77 after inventory growth in #200967. Expanded GitHub/hybrid regressions and all 174 focused planner tests pass; Codex autoreview is clean. check:changed passes except unrelated main unused exports attributed to #200533, #193550, #198455, and #200817.
steipete added a commit that referenced this pull request Nov 18, 2026
Preserve first-chat authorization when catalog persistence opens the selected absent database. Keep session-row, lifecycle, routing, and source-revocation guards intact. The focused bisect identifies #197510 as the first failing first-chat authorization boundary; #199565 had repaired other cold-registration orderings.

The deterministic regression is red before this fix. All 66 owning tests and three complete real Gateway reload trials pass; Codex review is clean through P2. check:changed passes every check except nine unused exports reproduced identically on exact main parent 97b03f7 and attributed to #200533, #198455, and #200817. Preserve peer cleanup scope in #201019.
steipete added a commit that referenced this pull request Nov 18, 2026
…200966)

* perf(agents): materialize selected rows for simple completions

* style: satisfy selected completion lint checks

* test: bind isolated registry measurement to concrete instances

* test: align participant custody with requester ownership

Follow #200952: Alice owns sessions she requests even when Bob supplies execution authority. Preserve autonomous agent ownership expectations. All 174 spawn-boundary, child-custody, and provenance tests pass; Codex scoped review is clean.

* fix: retain missing-session facts across database creation

Preserve first-chat authorization when catalog persistence opens the selected absent database. Keep session-row, lifecycle, routing, and source-revocation guards intact. The focused bisect identifies #197510 as the first failing first-chat authorization boundary; #199565 had repaired other cold-registration orderings.

The deterministic regression is red before this fix. All 66 owning tests and three complete real Gateway reload trials pass; Codex review is clean through P2. check:changed passes every check except nine unused exports reproduced identically on exact main parent 97b03f7 and attributed to #200533, #198455, and #200817. Preserve peer cleanup scope in #201019.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 19, 2026
…1002)

Apply hosted file-count bounds during weighted balancing instead of slicing already-balanced stripes into stranded tails. Preserve the 77-row hourly nondist cap, runner and worker limits, time budgets, and complete selected inventory.

The scheduled manifest reproduced 78 > 77 after inventory growth in openclaw#200967. Expanded GitHub/hybrid regressions and all 174 focused planner tests pass; Codex autoreview is clean. check:changed passes except unrelated main unused exports attributed to openclaw#200533, openclaw#193550, openclaw#198455, and openclaw#200817.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 19, 2026
…penclaw#200966)

* perf(agents): materialize selected rows for simple completions

* style: satisfy selected completion lint checks

* test: bind isolated registry measurement to concrete instances

* test: align participant custody with requester ownership

Follow openclaw#200952: Alice owns sessions she requests even when Bob supplies execution authority. Preserve autonomous agent ownership expectations. All 174 spawn-boundary, child-custody, and provenance tests pass; Codex scoped review is clean.

* fix: retain missing-session facts across database creation

Preserve first-chat authorization when catalog persistence opens the selected absent database. Keep session-row, lifecycle, routing, and source-revocation guards intact. The focused bisect identifies openclaw#197510 as the first failing first-chat authorization boundary; openclaw#199565 had repaired other cold-registration orderings.

The deterministic regression is red before this fix. All 66 owning tests and three complete real Gateway reload trials pass; Codex review is clean through P2. check:changed passes every check except nine unused exports reproduced identically on exact main parent 4dca39a and attributed to openclaw#200533, openclaw#198455, and openclaw#200817. Preserve peer cleanup scope in openclaw#201019.
RomneyDa added a commit that referenced this pull request Nov 19, 2026
Apply hosted file-count bounds during weighted balancing instead of slicing already-balanced stripes into stranded tails. Preserve the 77-row hourly nondist cap, runner and worker limits, time budgets, and complete selected inventory.

The scheduled manifest reproduced 78 > 77 after inventory growth in #200967. Expanded GitHub/hybrid regressions and all 174 focused planner tests pass; Codex autoreview is clean. check:changed passes except unrelated main unused exports attributed to #200533, #193550, #198455, and #200817.

Backport to beta.2 preparation; exact reviewed adapted patch. Focused parent proof: 35 tests; nine-file type-aware lint; 18-file format. Tooling typecheck retains the same two pre-existing cron UI errors as baseline. No release qualification.

(cherry picked from commit af50b8e)
(cherry picked from commit c7ccc5e)
Co-authored-by: Vincent Koc <[email protected]>
Co-authored-by: RomneyDa <[email protected]>
RomneyDa added a commit that referenced this pull request Nov 19, 2026
…200966)

* perf(agents): materialize selected rows for simple completions

* style: satisfy selected completion lint checks

* test: bind isolated registry measurement to concrete instances

* test: align participant custody with requester ownership

Follow #200952: Alice owns sessions she requests even when Bob supplies execution authority. Preserve autonomous agent ownership expectations. All 174 spawn-boundary, child-custody, and provenance tests pass; Codex scoped review is clean.

* fix: retain missing-session facts across database creation

Preserve first-chat authorization when catalog persistence opens the selected absent database. Keep session-row, lifecycle, routing, and source-revocation guards intact. The focused bisect identifies #197510 as the first failing first-chat authorization boundary; #199565 had repaired other cold-registration orderings.

The deterministic regression is red before this fix. All 66 owning tests and three complete real Gateway reload trials pass; Codex review is clean through P2. check:changed passes every check except nine unused exports reproduced identically on exact main parent 97b03f7 and attributed to #200533, #198455, and #200817. Preserve peer cleanup scope in #201019.

(cherry picked from commit 8610cd6)

Co-authored-by: RomneyDa <[email protected]>
github-actions Bot pushed a commit to clawhaven/openclaw that referenced this pull request Nov 23, 2026
…penclaw#200966)

* perf(agents): materialize selected rows for simple completions

* style: satisfy selected completion lint checks

* test: bind isolated registry measurement to concrete instances

* test: align participant custody with requester ownership

Follow openclaw#200952: Alice owns sessions she requests even when Bob supplies execution authority. Preserve autonomous agent ownership expectations. All 174 spawn-boundary, child-custody, and provenance tests pass; Codex scoped review is clean.

* fix: retain missing-session facts across database creation

Preserve first-chat authorization when catalog persistence opens the selected absent database. Keep session-row, lifecycle, routing, and source-revocation guards intact. The focused bisect identifies openclaw#197510 as the first failing first-chat authorization boundary; openclaw#199565 had repaired other cold-registration orderings.

The deterministic regression is red before this fix. All 66 owning tests and three complete real Gateway reload trials pass; Codex review is clean through P2. check:changed passes every check except nine unused exports reproduced identically on exact main parent 97b03f7 and attributed to openclaw#200533, openclaw#198455, and openclaw#200817. Preserve peer cleanup scope in openclaw#201019.

(cherry picked from commit 8610cd6)
Release adaptation: approved 2026.11.7 models replay; see models-hook-safe-v2/REPORT.md.
Co-authored-by: RomneyDa <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

clawtributors PR from a clawtributor docs Improvements or additions to documentation extensions: diagnostics-prometheus gateway Gateway runtime merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: XL status: ⏳ waiting on maintainer Only explicit maintainer approvals or decisions remain; merge is still blocked.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature]: diagnostics-prometheus: let plugins contribute their own metric families

3 participants