Repository navigation
feat: add per-caller usage metering for inference services - #979
Conversation
There was a problem hiding this comment.
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.
| if fromLocalSocket(r) || remoteAddr == "@" { | ||
| if peerHeader := r.Header.Get(api.HeaderPeerID); peerHeader != "" { | ||
| return peerHeader | ||
| } | ||
| } |
There was a problem hiding this comment.
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
- 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)
There was a problem hiding this comment.
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.
d937d18 to
825feff
Compare
|
The byte-counting middleware, streaming Flusher/Unwrap handling, and peer ID canonicalization look clean. A few things to address before merging:
|
825feff to
c9e3389
Compare
|
Thanks for the review and suggestions, @aojea! I've addressed all three points in the latest commit:
|
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
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.Inference Service Usage Tracking (
internal/node/inference_service.go):trackUsage(next http.Handler)middleware wrapping the reverse proxy handler.GET /v1/modelsand/models) are excluded from metrics so request and byte counters strictly reflect actual inference invocations.countingReadCloser(inbound request body) andcountingResponseWriter(outbound response body).http.FlusherandUnwrap() http.ResponseWriter(for Gohttp.ResponseController).interceptingReader.Close()waits on<-ir.doneafter signaling EOF to ensure background token parsing completes synchronously beforeServeHTTPreturns, eliminating test flakiness and race conditions.t.serviceandmodeltonewInterceptingReaderfor token accounting across both standard JSON and SSE streams.peer.Decodeand.String()fromr.RemoteAddr/ internal transport and ignores spoofedX-Peer-Idheaders from external network clients.Documentation (
site/content/docs/reference/node-api.md):Usage meteringsubsection under Inference services detailing the four metrics, labels, attribution semantics, and exclusion of discovery probes.Testing (
internal/node/inference_test.go,internal/node/inference_metering_test.go):time.Sleep.X-Peer-Id).RemoteAddr./v1/modelsdiscovery probes from inference counters./metricsPrometheus 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
/metricsendpoint on the node's HTTP surface and can be scraped by Prometheus. Example PromQL queries:sum by (peer_id, service) (rate(agentmesh_node_inference_requests_total[5m]))sum by (peer_id, service, model, token_type) (rate(agentmesh_node_inference_tokens_total[5m]))sum by (peer_id, service) (rate(agentmesh_node_inference_request_bytes_total[5m]) + rate(agentmesh_node_inference_response_bytes_total[5m]))Closes #976