Skip to content

feat: add per-caller usage metering for inference services - #979

Merged
aojea merged 1 commit into
google:mainfrom
roonakyadav:feat/per-caller-inference-metering
Nov 28, 2026
Merged

aojea merged 1 commit into
google:mainfrom
roonakyadav:feat/per-caller-inference-metering

Conversation

@roonakyadav

@roonakyadav roonakyadav commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

Summary

This PR implements per-caller usage metering for inference services at the provider node, resolving issue #976.

When inference services are backed by a shared upstream provider (e.g. vLLM, Ollama, OpenAI-compatible backends), the provider node now meters usage per authenticated caller peer ID and service name across requests, tokens, and payload bytes.

Changes

  1. Prometheus Metrics (internal/node/inference_metrics.go):

    • agentmesh_node_inference_requests_total (peer_id, service): Total inference requests served by this node.
    • agentmesh_node_inference_request_bytes_total (peer_id, service): Inbound request payload bytes received from the caller.
    • agentmesh_node_inference_response_bytes_total (peer_id, service): Outbound response payload bytes delivered to the caller.
    • agentmesh_node_inference_tokens_total (peer_id, service, model, token_type): Prompt and completion tokens reported by the upstream provider (token_type="prompt" or "completion"), preserving per-model token attribution alongside per-service accounting.
  2. Inference Service Usage Tracking (internal/node/inference_service.go):

    • Added trackUsage(next http.Handler) middleware wrapping the reverse proxy handler.
    • Discovery probes (GET /v1/models and /models) are excluded from metrics so request and byte counters strictly reflect actual inference invocations.
    • Zero-buffering byte accounting using countingReadCloser (inbound request body) and countingResponseWriter (outbound response body).
    • Transparently supports streaming responses by implementing http.Flusher and Unwrap() http.ResponseWriter (for Go http.ResponseController).
    • interceptingReader.Close() waits on <-ir.done after signaling EOF to ensure background token parsing completes synchronously before ServeHTTP returns, eliminating test flakiness and race conditions.
    • Symmetrically threads t.service and model to newInterceptingReader for token accounting across both standard JSON and SSE streams.
    • Secure caller peer ID attribution: extracts and canonicalizes peer IDs via peer.Decode and .String() from r.RemoteAddr / internal transport and ignores spoofed X-Peer-Id headers from external network clients.
    • Strict privacy: only records metadata metrics; request bodies, prompts, completions, and arguments are never logged or stored.
  3. Documentation (site/content/docs/reference/node-api.md):

    • Added Usage metering subsection under Inference services detailing the four metrics, labels, attribution semantics, and exclusion of discovery probes.
  4. Testing (internal/node/inference_test.go, internal/node/inference_metering_test.go):

    • Updated existing token tests to assert requests count, request bytes, response bytes, and tokens with service and model attribution without relying on time.Sleep.
    • Added comprehensive tests for:
      • Multi-caller, multi-service, and per-model attribution across distinct peer IDs.
      • Missing usage metadata in standard JSON and streaming SSE responses.
      • Error response paths (e.g. 500 Internal Server Error byte and request accounting).
      • Identity spoofing protection (untrusted remote clients attempting to forge X-Peer-Id).
      • Direct libp2p peer ID in RemoteAddr.
      • Boundary peer ID canonicalization (CIDv1 alias mapping to canonical base58 peer ID and invalid format fallback).
      • Exclusion of /v1/models discovery probes from inference counters.
      • End-to-end /metrics Prometheus scrape verification.

Tests Executed

  • go test -v -race ./internal/node -run "TestInference" (14/14 passed)
  • go test -race ./internal/node (passed in 40.3s)
  • golangci-lint run ./... (0 issues)
  • make (all binaries built successfully)

Consuming Metrics

Metrics are exported on the standard /metrics endpoint on the node's HTTP surface and can be scraped by Prometheus. Example PromQL queries:

  • Request rate per caller: sum by (peer_id, service) (rate(agentmesh_node_inference_requests_total[5m]))
  • Token consumption rate per model: sum by (peer_id, service, model, token_type) (rate(agentmesh_node_inference_tokens_total[5m]))
  • Bandwidth usage: sum by (peer_id, service) (rate(agentmesh_node_inference_request_bytes_total[5m]) + rate(agentmesh_node_inference_response_bytes_total[5m]))

Closes #976

@roonakyadav
roonakyadav requested a review from aojea as a code owner November 28, 2026 12:45

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request implements usage metering for inference services by tracking requests, request bytes, and response bytes per authenticated caller peer ID and service name using Prometheus metrics. The changes include adding a usage tracking middleware to the InferenceService, updating the Peer ID extraction logic, and adding comprehensive tests and documentation for the new metrics. A review comment identifies a security vulnerability regarding the lack of canonicalization for Peer IDs extracted from headers, which must be addressed by using peer.Decode to ensure consistent identity verification.

Comment on lines +266 to +270
if fromLocalSocket(r) || remoteAddr == "@" {
if peerHeader := r.Header.Get(api.HeaderPeerID); peerHeader != "" {
return peerHeader
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Rule 1: Peer IDs must be canonicalized at the boundary

The peer ID extracted from the X-Peer-Id header is returned directly as a raw string without being canonicalized. According to the Agent Mesh style guide, all peer IDs must be canonicalized at the boundary using peer.Decode and using its .String() representation. Returning a raw, non-canonicalized string can lead to security bugs where bans, admission, or deduplication checks silently miss because of different string encodings for the same peer ID.

Please decode the peerHeader and return its canonical string representation.

Note: The other peer ID extraction paths in getPeerID (lines 251-257) also suffer from the same issue of returning non-canonicalized peer IDs. Please ensure those are also refactored to return pID.String() instead of the raw remoteAddr or host strings.

	if fromLocalSocket(r) || remoteAddr == "@" {
		if peerHeader := r.Header.Get(api.HeaderPeerID); peerHeader != "" {
			if pID, err := peer.Decode(peerHeader); err == nil {
				return pID.String()
			}
		}
	}
References
  1. Peer IDs must be canonicalized at the boundary. A libp2p peer ID has several valid string encodings. peer.Decode accepts all of them and returns the same peer.ID, but peer.ID.String() always emits the base58 form. Every cache, ban set, storage row, and map[string] in Agent Mesh is keyed on that canonical form. A raw string copied off the wire and used as a key is therefore a different key for the same peer, and a ban, admission or dedup check silently misses. (link)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 825feff: all peer ID extraction paths in getPeerID (from r.RemoteAddr, split host, trusted loopback X-Peer-Id, and local socket X-Peer-Id) now canonicalize via peer.Decode and return pID.String(). Added TestInferenceService_PeerIDCanonicalization verifying CIDv1 aliases are mapped to canonical base58 peer IDs and invalid inputs safely fall back to unknown.

@roonakyadav
roonakyadav force-pushed the feat/per-caller-inference-metering branch from d937d18 to 825feff Compare November 28, 2026 13:15
@aojea

aojea commented Nov 28, 2026

Copy link
Copy Markdown
Collaborator

The byte-counting middleware, streaming Flusher/Unwrap handling, and peer ID canonicalization look clean. A few things to address before merging:

  1. Keep the model label on agentmesh_node_inference_tokens_total: This PR replaces model with service ([peer_id, model, token_type] -> [peer_id, service, token_type]). A single inference service often serves multiple models (e.g., Ollama, vLLM, or a model router), so dropping model loses per-model token attribution and breaks existing queries on that metric. Please keep model alongside service ([peer_id, service, model, token_type]).
  2. Remove time.Sleep(50 * time.Millisecond) from the tests: inference_metering_test.go adds several time.Sleep waits for parseResponseStream, which can flake under -race or CPU load (see AGENTS.md §3). interceptingReader already has a done chan struct{} closed when parseResponseStream finishes — waiting on <-ir.done in interceptingReader.Close() right after ir.pw.CloseWithError(io.EOF) makes token recording complete before ServeHTTP returns, so both inference_test.go and inference_metering_test.go can drop the sleeps.
  3. Clarify or exclude /v1/models discovery probes: Because trackUsage wraps every request hitting InferenceService.Handler(), periodic remote GET /v1/models probes from openai_facade.go also increment agentmesh_node_inference_requests_total and the byte counters. Please either document this in node-api.md (that the counters cover all HTTP traffic to the inference service, including discovery probes) or exclude /v1/models if you intend to count only inference calls.

@roonakyadav
roonakyadav force-pushed the feat/per-caller-inference-metering branch from 825feff to c9e3389 Compare November 28, 2026 14:08
@roonakyadav

Copy link
Copy Markdown
Contributor Author

Thanks for the review and suggestions, @aojea! I've addressed all three points in the latest commit:

  1. Retained model label on agentmesh_node_inference_tokens_total:

    • The token metric now includes both service and model: [peer_id, service, model, token_type].
    • Updated parseJSONResponse, parseSSEResponse, and recordTokens to parse and thread the model name so token attribution retains per-model resolution alongside the service name without breaking existing queries.
  2. Eliminated time.Sleep in tests:

    • In interceptingReader.Close(), after ir.pw.CloseWithError(io.EOF), we now wait on <-ir.done. Since ReverseProxy.ServeHTTP defers closing the response body, this guarantees parseResponseStream and token metric updates complete synchronously before ServeHTTP returns.
    • Removed all time.Sleep calls and the time import from both inference_test.go and inference_metering_test.go.
  3. Excluded discovery probes (GET /v1/models and /models):

    • Added isDiscoveryProbe(r *http.Request) in trackUsage to bypass metering for periodic discovery probes (GET /v1/models and GET /models).
    • Request and byte counters now strictly measure actual inference invocations.
    • Added unit test coverage for probe exclusion (TestInferenceService_ExcludeDiscoveryProbes) and documented this behavior in site/content/docs/reference/node-api.md.

@aojea
aojea merged commit e79ea6b into google:main Nov 28, 2026
21 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Per-caller usage metering for inference services

2 participants