-
Notifications
You must be signed in to change notification settings - Fork 2.4k
feat: add lightweight observability and metrics service #230
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
ksapru
wants to merge
10
commits into
NVIDIA:main
Choose a base branch
from
ksapru:feat/observability-metrics
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
1c74bc0
feat: add lightweight observability and metrics service
ksapru ad1f2e7
fix: improve metrics server lifecycle and add sandbox operation metric
ksapru 68bb16c
chore: cleanup pr description and rename metric to blueprint_execution
ksapru ceb38d1
Merge branch 'main' into feat/observability-metrics
ksapru ca431d5
Merge remote-tracking branch 'origin/main' into feat/observability-me…
ksapru c490415
Merge upstream/main and resolve conflicts in nemoclaw/src/index.ts an…
ksapru d19fdab
Merge remote-tracking branch 'origin/feat/observability-metrics' into…
ksapru e53dcdb
Merge main into feat/observability-metrics and resolve conflicts in i…
ksapru b0b11e8
Merge branch 'main' into feat/observability-metrics
ksapru a9a5887
Merge branch 'main' into feat/observability-metrics
ksapru File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,153 @@ | ||
| // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| /** | ||
| * Lightweight metrics implementation for NemoClaw. | ||
| * | ||
| * Provides counters and histograms for request tracking and latency observation. | ||
| * Enabled only when NEMOCLAW_METRICS_ENABLED=true. | ||
| */ | ||
|
|
||
| export interface MetricValue { | ||
| name: string; | ||
| help: string; | ||
| type: "counter" | "histogram"; | ||
| labels: Record<string, string>; | ||
| value: number; | ||
| timestamp: number; | ||
| } | ||
|
|
||
| export interface HistogramValue extends MetricValue { | ||
| type: "histogram"; | ||
| buckets: Record<number, number>; | ||
| sum: number; | ||
| count: number; | ||
| } | ||
|
|
||
| class MetricsRegistry { | ||
| private counters: Map<string, number> = new Map(); | ||
| private histograms: Map<string, { sum: number; count: number; buckets: Record<number, number> }> = | ||
| new Map(); | ||
|
|
||
| // Standard buckets for latency (seconds) | ||
| private defaultBuckets = [0.01, 0.05, 0.1, 0.5, 1, 2, 5, 10, 30, 60]; | ||
|
|
||
| public isEnabled(): boolean { | ||
| return process.env.NEMOCLAW_METRICS_ENABLED === "true"; | ||
| } | ||
|
|
||
| public incrementCounter(name: string, labels: Record<string, string> = {}): void { | ||
| if (!this.isEnabled()) return; | ||
| const key = this.formatKey(name, labels); | ||
| this.counters.set(key, (this.counters.get(key) || 0) + 1); | ||
| } | ||
|
|
||
| public observeHistogram( | ||
| name: string, | ||
| value: number, | ||
| labels: Record<string, string> = {}, | ||
| buckets = this.defaultBuckets, | ||
| ): void { | ||
| if (!this.isEnabled()) return; | ||
| const key = this.formatKey(name, labels); | ||
| let hist = this.histograms.get(key); | ||
| if (!hist) { | ||
| hist = { sum: 0, count: 0, buckets: {} }; | ||
| buckets.forEach((b) => (hist!.buckets[b] = 0)); | ||
| this.histograms.set(key, hist); | ||
| } | ||
|
|
||
| hist.sum += value; | ||
| hist.count += 1; | ||
| buckets.forEach((b) => { | ||
| if (value <= b) { | ||
| hist!.buckets[b] = (hist!.buckets[b] || 0) + 1; | ||
| } | ||
| }); | ||
| } | ||
|
|
||
| public getPrometheusMetrics(): string { | ||
| let output = ""; | ||
|
|
||
| // Export counters | ||
| for (const [key, value] of this.counters.entries()) { | ||
| const [name, labelStr] = this.parseKey(key); | ||
| output += `# HELP ${name} Total count of ${name}\n`; | ||
| output += `# TYPE ${name} counter\n`; | ||
| output += `${name}${labelStr} ${value}\n\n`; | ||
| } | ||
|
|
||
| // Export histograms | ||
| for (const [key, hist] of this.histograms.entries()) { | ||
| const [name, labelStr] = this.parseKey(key); | ||
| output += `# HELP ${name} Latency histogram for ${name}\n`; | ||
| output += `# TYPE ${name} histogram\n`; | ||
|
|
||
| const sortedBuckets = Object.keys(hist.buckets) | ||
| .map(Number) | ||
| .sort((a, b) => a - b); | ||
| const labelsBase = labelStr.length > 2 ? labelStr.slice(1, -1) + "," : ""; | ||
|
|
||
| sortedBuckets.forEach((b) => { | ||
| output += `${name}_bucket{${labelsBase}le="${b === Infinity ? "+Inf" : b}"} ${hist.buckets[b]}\n`; | ||
| }); | ||
| output += `${name}_bucket{${labelsBase}le="+Inf"} ${hist.count}\n`; | ||
| output += `${name}_sum${labelStr} ${hist.sum}\n`; | ||
| output += `${name}_count${labelStr} ${hist.count}\n\n`; | ||
| } | ||
|
|
||
| return output; | ||
| } | ||
|
|
||
| private formatKey(name: string, labels: Record<string, string>): string { | ||
| const labelPairs = Object.entries(labels) | ||
| .map(([k, v]) => `${k}="${v}"`) | ||
| .join(","); | ||
| return labelPairs ? `${name}{${labelPairs}}` : name; | ||
| } | ||
|
|
||
| private parseKey(key: string): [string, string] { | ||
| const braceIdx = key.indexOf("{"); | ||
| if (braceIdx === -1) return [key, ""]; | ||
| return [key.slice(0, braceIdx), key.slice(braceIdx)]; | ||
| } | ||
| } | ||
|
|
||
| export const metrics = new MetricsRegistry(); | ||
|
|
||
| /** | ||
| * Helper to measure execution time of a promise. | ||
| */ | ||
| export async function observeLatency<T>( | ||
| name: string, | ||
| labels: Record<string, string>, | ||
| fn: () => Promise<T>, | ||
| ): Promise<T> { | ||
| if (!metrics.isEnabled()) return fn(); | ||
|
|
||
| const start = process.hrtime.bigint(); | ||
| try { | ||
| const result = await fn(); | ||
| const end = process.hrtime.bigint(); | ||
| const durationSec = Number(end - start) / 1e9; | ||
|
|
||
| metrics.observeHistogram(`${name}_latency_seconds`, durationSec, { | ||
| ...labels, | ||
| status: "success", | ||
| }); | ||
| metrics.incrementCounter(`${name}_total`, { ...labels, status: "success" }); | ||
|
|
||
| return result; | ||
| } catch (error) { | ||
| const end = process.hrtime.bigint(); | ||
| const durationSec = Number(end - start) / 1e9; | ||
|
|
||
| metrics.observeHistogram(`${name}_latency_seconds`, durationSec, { | ||
| ...labels, | ||
| status: "error", | ||
| }); | ||
| metrics.incrementCounter(`${name}_total`, { ...labels, status: "error" }); | ||
|
|
||
| throw error; | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,57 @@ | ||
| // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| const test = require("node:test"); | ||
| const assert = require("node:assert"); | ||
| const path = require("node:path"); | ||
|
|
||
| // Load the compiled metrics module | ||
| const metricsPath = path.resolve(__dirname, "../nemoclaw/dist/observability/metrics.js"); | ||
| const { metrics, observeLatency } = require(metricsPath); | ||
|
|
||
| // Enable metrics for testing | ||
| process.env.NEMOCLAW_METRICS_ENABLED = "true"; | ||
|
|
||
| test("MetricsRegistry stores and exports counters", () => { | ||
| metrics.incrementCounter("test_counter", { foo: "bar" }); | ||
| const output = metrics.getPrometheusMetrics(); | ||
|
|
||
| assert.match(output, /# TYPE test_counter counter/); | ||
| assert.match(output, /test_counter\{foo="bar"\} 1/); | ||
| }); | ||
|
|
||
| test("MetricsRegistry stores and exports histograms", () => { | ||
| metrics.observeHistogram("test_hist", 0.5, { abc: "123" }); | ||
| const output = metrics.getPrometheusMetrics(); | ||
|
|
||
| assert.match(output, /# TYPE test_hist histogram/); | ||
| assert.match(output, /test_hist_bucket\{abc="123",le="0\.5"\} 1/); | ||
| assert.match(output, /test_hist_sum\{abc="123"\} 0\.5/); | ||
| assert.match(output, /test_hist_count\{abc="123"\} 1/); | ||
| }); | ||
|
|
||
| test("observeLatency tracks success metrics", async () => { | ||
| const result = await observeLatency("test_op", { op: "success" }, async () => { | ||
| return "done"; | ||
| }); | ||
|
|
||
| assert.strictEqual(result, "done"); | ||
| const output = metrics.getPrometheusMetrics(); | ||
|
|
||
| assert.match(output, /test_op_total\{op="success",status="success"\} 1/); | ||
| assert.match(output, /test_op_latency_seconds_count\{op="success",status="success"\} 1/); | ||
| }); | ||
|
|
||
| test("observeLatency tracks error metrics", async () => { | ||
| try { | ||
| await observeLatency("test_op_err", { op: "fail" }, async () => { | ||
| throw new Error("oops"); | ||
| }); | ||
| } catch (err) { | ||
| assert.strictEqual(err.message, "oops"); | ||
| } | ||
|
|
||
| const output = metrics.getPrometheusMetrics(); | ||
| assert.match(output, /test_op_err_total\{op="fail",status="error"\} 1/); | ||
| assert.match(output, /test_op_err_latency_seconds_count\{op="fail",status="error"\} 1/); | ||
| }); |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.