← Back to Pull requests

[Bug] Accept arbitrary JSON metadata values in Chat and Responses decoders #5293

Open
Paramveersingh-S opened this pull request with 655 lines diff across 8 files
View on GitHub
Paramveersingh-S Paramveersingh-S commented on Oct 20, 2026 04:58 UTC
Author

Closes #5252
Related #3983

Purpose

The Chat Completions and Responses request decoders previously typed metadata as map[string]string (chatRequestWire in protocolcodec/codec_openai_chat.go, responsesRequestWire in protocolcodec/codec_openai_responses.go) and client_metadata as map[string]string on Responses. Consequently, any request containing non-string metadata values (such as list tags, turn numbers, boolean flags, or nested objects) failed decodeWire during strict validation and was rejected before routing with 400 invalid_json: request JSON is invalid.

LiteLLM-based clients conventions (such as Langfuse and spend-tracking) attach request metadata with list tags or scalar metrics (e.g., {"tags": ["agent"], "turn": 1, "active": true}), causing every call from such clients to fail at the Router.

Changes

1. Flexible Wire Metadata: Changed chatRequestWire.Metadata, responsesRequestWire.Metadata, and responsesRequestWire.ClientMetadata from map[string]string to map[string]any.
2. Metadata Value Coercion: Added coerceWireMetadata and coerceMetadataValue in pkg/protocolcodec/json_helpers.go to coerce arbitrary JSON values (strings, numbers, booleans, arrays, objects, nulls) into string values for the protocol-neutral llmprotocol.Request.Metadata contract. This ensures downstream classifier signals (MetadataRule), routing predicates, masking, and request validation limits work without modification.
3. Verbatim Replay Preservation: Same-format routes (Chat -> Chat, Responses -> Responses) continue to forward raw client request bytes via envelope caching (envelope.CanReplay), preserving the native JSON types upstream.
4. Wire Encoding: Added encodeWireMetadata for re-encoding requests when cross-format translation or modifications prevent envelope replay.
5. Comprehensive Tests: Added codec_openai_metadata_test.go covering LiteLLM list tags, numbers, booleans, nested objects, compound metadata, round-trip encoding, client_metadata omission diagnostics, and rejection of non-object metadata types (e.g. strings or arrays).

Diff: 655 lines (+599 / -56) across 8 files Reviewer: subin9 Review duration: 60403m
All Vouch review confidence checks passed
Residual risk 0.12 = Change Risk (0.64) × (1 − Review Confidence (0.81)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.64 · 655 lines diff across 8 files
0.64
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.81 · 5 substantive comment(s)
0.81
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 50%
80%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.388
Ai Authored ai_authored
0.050
Real PR Conversation Timeline
12 items
Paramveersingh-S Paramveersingh-S commented on Oct 20, 2026 05:52 UTC
Author

/assign

Paramveersingh-S Paramveersingh-S commented on Nov 09, 2026 04:40 UTC
Author

Hi @FAUST-BENCHOU
Please review this PR

mergify[bot] mergify[bot] commented on Nov 10, 2026 14:14 UTC
Bot

Tick the box to add this pull request to the merge queue (same as @mergifyio queue). If it does not match the queue conditions yet, it enters the queue once it does.

  • Queue this pull request <!-- mergify:queue-control:queue -->
  • subin9 subin9 requested changes on Nov 13, 2026 10:23 UTC
    Changes Requested Reviewer

    Thanks for picking this up. One concern: when the request has to be re-encoded, which happens for every streamed Chat call because the Router adds include_usage, the backend gets "tags":"[\"agent\"]" and "turn":"1" instead of the values the client sent, and large integers lose precision. drivebyer suggested on the issue keeping metadata as JSON with its types and rejecting translations that can't carry it. Could you follow that, and add a test that re-encodes the request?

    Paramveersingh-S Paramveersingh-S commented on Nov 14, 2026 05:24 UTC
    Author

    Good catch, thanks @subin9. You're completely right about the reencoding behavior on streaming calls.

    I've updated the implementation following drivebyer's recommendation:

    1. Chat and Responses wire structs now type metadata and client_metadata as map[string]json.RawMessage.
    2. Added MetadataJSON map[string]json.RawMessage to llmprotocol.Request to preserve uncoerced raw JSON byte representations across routing, while keeping stringified values in Metadata so existing routing predicates and limits continue to function as expected.
    3. Updated encodeChatBaseRequest and encodeResponsesRequestWire so reencoded requests serialize native JSON types directly rather than stringified values, preserving arrays, booleans, objects, and large integers beyond 2^53 without float64 precision loss.
    4. Added an explicit check in alidateAnthropicEncodableRequest returning unsupported_metadata whenever a request carrying metadata is translated to Anthropic Messages, as Messages cannot represent request metadata.
    5. Added unit tests covering forced reencoding type fidelity, large integer precision preservation, and cross protocol translation rejection.

    github-actions[bot] github-actions[bot] commented on Nov 14, 2026 05:34 UTC
    Bot

    <!-- semantic-router-ci-status:v1 -->
    All required CI qualification passed

    All selected and required checks have completed successfully for this revision.

    Revision 34916d8b6426 · CI run, attempt 2

    subin9 subin9 commented on code on Nov 18, 2026 06:35 UTC
    Code Review
    src/semantic-router/pkg/protocolcodec/codec_openai_metadata_test.go:1
    @@ -0,0 +1,460 @@
    +package protocolcodec
    +
    +import (
    +	"bytes"
    +	"encoding/json"
    +	"testing"
    +
    +	"github.com/vllm-project/semantic-router/src/semantic-router/pkg/llmprotocol"
    +)
    +
    +func TestOpenAIChatMetadataNonStringValues(t *testing.T) {
    +	codec := OpenAIChatCodec{}
    +	policy := llmprotocol.DefaultPolicy()
    +
    +	cases := []struct {
    +		name     string
    +		metadata string
    +		key      string
    +		wantVal  string
    +	}{
    +		{
    +			name:     "string value",
    +			metadata: `{"a":"b"}`,
    +			key:      "a",
    +			wantVal:  "b",
    +		},
    +		{
    +			name:     "list of strings (LiteLLM tags)",
    +			metadata: `{"tags":["agent","prod"]}`,
    +			key:      "tags",
    +			wantVal:  `["agent","prod"]`,
    +		},
    +		{
    +			name:     "integer number",
    +			metadata: `{"turn":1}`,
    +			key:      "turn",
    +			wantVal:  "1",
    +		},
    +		{
    +			name:     "floating point number",
    +			metadata: `{"score":98.5}`,
    +			key:      "score",
    +			wantVal:  "98.5",
    +		},
    +		{
    +			name:     "boolean true",
    +			metadata: `{"flag":true}`,
    +			key:      "flag",
    +			wantVal:  "true",
    +		},
    +		{
    +			name:     "boolean false",
    +			metadata: `{"flag":false}`,
    +			key:      "flag",
    +			wantVal:  "false",
    +		},
    +		{
    +			name:     "nested object",
    +			metadata: `{"nested":{"key":"val"}}`,
    +			key:      "nested",
    +			wantVal:  `{"key":"val"}`,
    +		},
    +		{
    +			name:     "null value",
    +			metadata: `{"empty":null}`,
    +			key:      "empty",
    +			wantVal:  "null",
    +		},
    +	}
    +
    +	for _, tc := range cases {
    +		t.Run(tc.name, func(t *testing.T) {
    +			rawBody := []byte(`{"model":"vllm-sr/auto","stream":true,"messages":[{"role":"user","content":"hi"}],"metadata":` + tc.metadata + `}`)
    +			req, envelope, _, err := codec.DecodeRequest(rawBody, policy)
    +			if err != nil {
    +				t.Fatalf("unexpected error decoding metadata %s: %v", tc.metadata, err)
    +			}
    +			if req.Metadata == nil {
    +				t.Fatalf("req.Metadata is nil")
    +			}
    +			if got := req.Metadata[tc.key]; got != tc.wantVal {
    +				t.Errorf("Metadata[%q] = %q, want %q", tc.key, got, tc.wantVal)
    +			}
    +			if req.MetadataJSON == nil || len(req.MetadataJSON[tc.key]) == 0 {
    +				t.Fatalf("req.MetadataJSON missing key %q", tc.key)
    +			}
    +			if err = llmprotocol.ValidateRequest(req, policy.Limits); err != nil {
    +				t.Errorf("ValidateRequest failed: %v", err)
    +			}
    +
    +			// Same-format re-encoding should replay verbatim bytes via envelope
    +			var encoded []byte
    +			encoded, _, err = codec.EncodeRequest(req, envelope, policy)
    +			if err != nil {
    +				t.Fatalf("EncodeRequest replay failed: %v", err)
    +			}
    +			if !bytes.Equal(encoded, rawBody) {
    +				t.Errorf("replayed bytes mismatch: got %s, want %s", string(encoded), string(rawBody))
    +			}
    +
    +			// Forced re-encoding (empty envelope, e.g. when router adds include_usage)
    +			// should preserve original JSON types rather than stringifying them.
    +			var reencoded []byte
    +			reencoded, _, err = codec.EncodeRequest(req, llmprotocol.Envelope{}, policy)
    +			if err != nil {
    +				t.Fatalf("Forced EncodeRequest failed: %v", err)
    +			}
    +			var parsed map[string]any
    +			if err := json.Unmarshal(reencoded, &parsed); err != nil {
    +				t.Fatalf("unmarshal reencoded JSON: %v", err)
    +			}
    +			meta, ok := parsed["metadata"].(map[string]any)
    +			if !ok {
    +				t.Fatalf("re-encoded metadata is not a map: %v", parsed["metadata"])
    +			}
    +			val := meta[tc.key]
    +			switch tc.name {
    +			case "string value":
    +				if val != "b" {
    +					t.Errorf("reencoded string: got %v (%T), want 'b'", val, val)
    +				}
    +			case "list of strings (LiteLLM tags)":
    +				list, ok := val.([]any)
    +				if !ok || len(list) != 2 || list[0] != "agent" || list[1] != "prod" {
    +					t.Errorf("reencoded list: got %v (%T), want []any{'agent', 'prod'}", val, val)
    +				}
    +			case "integer number":
    +				if val != float64(1) {
    +					t.Errorf("reencoded int: got %v (%T), want 1", val, val)
    +				}
    +			case "floating point number":
    +				if val != 98.5 {
    +					t.Errorf("reencoded float: got %v (%T), want 98.5", val, val)
    +				}
    +			case "boolean true":
    +				if val != true {
    +					t.Errorf("reencoded bool: got %v (%T), want true", val, val)
    +				}
    +			case "boolean false":
    +				if val != false {
    +					t.Errorf("reencoded bool: got %v (%T), want false", val, val)
    +				}
    +			case "nested object":
    +				obj, ok := val.(map[string]any)
    +				if !ok || obj["key"] != "val" {
    +					t.Errorf("reencoded object: got %v (%T), want map with key=val", val, val)
    +				}
    +			case "null value":
    +				if val != nil {
    +					t.Errorf("reencoded null: got %v (%T), want nil", val, val)
    +				}
    +			}
    +		})
    +	}
    +}
    +
    +func TestOpenAIMetadataLargeIntegerPrecisionPreserved(t *testing.T) {
    +	codec := OpenAIChatCodec{}
    +	policy := llmprotocol.DefaultPolicy()
    +
    +	// 9007199254740993 is 2^53 + 1, which loses precision in float64 (truncating to 9007199254740992)
    +	raw := []byte(`{"model":"vllm-sr/auto","stream":true,"messages":[{"role":"user","content":"hi"}],"metadata":{"large_int":9007199254740993}}`)
    +	req, _, _, err := codec.DecodeRequest(raw, policy)
    +	if err != nil {
    +		t.Fatalf("DecodeRequest: %v", err)
    +	}
    +
    +	if req.Metadata["large_int"] != "9007199254740993" {
    +		t.Errorf("req.Metadata[large_int] = %q, want 9007199254740993", req.Metadata["large_int"])
    +	}
    +	if string(req.MetadataJSON["large_int"]) != "9007199254740993" {
    +		t.Errorf("req.MetadataJSON[large_int] = %s, want 9007199254740993", string(req.MetadataJSON["large_int"]))
    +	}
    +
    +	// Forced re-encoding (e.g. streaming Chat where router adds include_usage)
    +	reencoded, _, err := codec.EncodeRequest(req, llmprotocol.Envelope{}, policy)
    +	if err != nil {
    +		t.Fatalf("EncodeRequest: %v", err)
    +	}
    +
    +	if !bytes.Contains(reencoded, []byte(`"large_int":9007199254740993`)) {
    +		t.Errorf("re-encoded wire JSON lost large integer precision: %s", string(reencoded))
    +	}
    +}
    +
    +func TestOpenAIChatCompoundMetadata(t *testing.T) {
    +	codec := OpenAIChatCodec{}
    +	policy := llmprotocol.DefaultPolicy()
    +
    +	raw := []byte(`{
    +		"model":"vllm-sr/auto",
    +		"messages":[{"role":"user","content":"hi"}],
    +		"metadata":{
    +			"trace_id":"trace-123",
    +			"session_id":"sess-456",
    +			"tags":["agent","vllm"],
    +			"turn":3,
    +			"score":99.25,
    +			"active":true,
    +			"extra":{"debug":true}
    +		}
    +	}`)
    +
    +	req, _, _, err := codec.DecodeRequest(raw, policy)
    +	if err != nil {
    +		t.Fatalf("decode compound metadata: %v", err)
    +	}
    +
    +	expected := map[string]string{
    +		"trace_id":   "trace-123",
    +		"session_id": "sess-456",
    +		"tags":       `["agent","vllm"]`,
    +		"turn":       "3",
    +		"score":      "99.25",
    +		"active":     "true",
    +		"extra":      `{"debug":true}`,
    +	}
    +
    +	for k, want := range expected {
    +		if got := req.Metadata[k]; got != want {
    +			t.Errorf("Metadata[%q] = %q, want %q", k, got, want)
    +		}
    +	}
    +
    +	// Verify forced re-encode retains compound JSON structure
    +	reencoded, _, err := codec.EncodeRequest(req, llmprotocol.Envelope{}, policy)
    +	if err != nil {
    +		t.Fatalf("forced encode compound metadata: %v", err)
    +	}
    +
    +	var parsed map[string]any
    +	if err := json.Unmarshal(reencoded, &parsed); err != nil {
    +		t.Fatalf("unmarshal reencoded JSON: %v", err)
    +	}
    +	meta := parsed["metadata"].(map[string]any)
    +	if meta["trace_id"] != "trace-123" {
    +		t.Errorf("reencoded trace_id = %v", meta["trace_id"])
    +	}
    +	if meta["turn"] != float64(3) {
    +		t.Errorf("reencoded turn = %v", meta["turn"])
    +	}
    +	if tags, ok := meta["tags"].([]any); !ok || len(tags) != 2 {
    +		t.Errorf("reencoded tags = %v", meta["tags"])
    +	}
    +	if extra, ok := meta["extra"].(map[string]any); !ok || extra["debug"] != true {
    +		t.Errorf("reencoded extra = %v", meta["extra"])
    +	}
    +}
    +
    +func TestOpenAIResponsesMetadataNonStringValues(t *testing.T) {
    +	codec := OpenAIResponsesCodec{}
    +	policy := llmprotocol.DefaultPolicy()
    +
    +	raw := []byte(`{
    +		"model":"vllm-sr/auto",
    +		"input":"hi",
    +		"metadata":{
    +			"trace_id":"trace-123",
    +			"tags":["agent","prod"],
    +			"turn":2,
    +			"enabled":true,
    +			"config":{"retry":3}
    +		},
    +		"client_metadata":{
    +			"client_tags":["telemetry"],
    +			"client_turn":1,
    +			"client_flag":false
    +		}
    +	}`)
    +
    +	req, envelope, diagnostics, err := codec.DecodeRequest(raw, policy)
    +	if err != nil {
    +		t.Fatalf("decode responses request: %v", err)
    +	}
    +
    +	if req.Metadata["trace_id"] != "trace-123" {
    +		t.Errorf("Metadata[trace_id] = %q, want trace-123", req.Metadata["trace_id"])
    +	}
    +	if req.Metadata["tags"] != `["agent","prod"]` {
    +		t.Errorf("Metadata[tags] = %q, want [\"agent\",\"prod\"]", req.Metadata["tags"])
    +	}
    +	if req.Metadata["turn"] != "2" {
    +		t.Errorf("Metadata[turn] = %q, want 2", req.Metadata["turn"])
    +	}
    +	if req.Metadata["enabled"] != "true" {
    +		t.Errorf("Metadata[enabled] = %q, want true", req.Metadata["enabled"])
    +	}
    +	if req.Metadata["config"] != `{"retry":3}` {
    +		t.Errorf("Metadata[config] = %q, want {\"retry\":3}", req.Metadata["config"])
    +	}
    +
    +	// Client metadata should be omitted with a diagnostic
    +	foundDiagnostic := false
    +	for _, diag := range diagnostics {
    +		if diag.Field == "client_metadata" {
    +			foundDiagnostic = true
    +			break
    +		}
    +	}
    +	if !foundDiagnostic {
    +		t.Errorf("expected client_metadata diagnostic omission, got: %v", diagnostics)
    +	}
    +
    +	if err = llmprotocol.ValidateRequest(req, policy.Limits); err != nil {
    +		t.Errorf("ValidateRequest failed: %v", err)
    +	}
    +
    +	// Replay preserves bytes
    +	var encoded []byte
    +	encoded, _, err = codec.EncodeRequest(req, envelope, policy)
    +	if err != nil {
    +		t.Fatalf("EncodeRequest failed: %v", err)
    +	}
    +	if !bytes.Equal(encoded, raw) {
    +		t.Errorf("replayed bytes mismatch")
    +	}
    +
    +	// Forced re-encode preserves native JSON types
    +	reencoded, _, err := codec.EncodeRequest(req, llmprotocol.Envelope{}, policy)
    +	if err != nil {
    +		t.Fatalf("forced EncodeRequest failed: %v", err)
    +	}
    +	var parsed map[string]any
    +	if err := json.Unmarshal(reencoded, &parsed); err != nil {
    +		t.Fatalf("unmarshal reencoded JSON: %v", err)
    +	}
    +	meta := parsed["metadata"].(map[string]any)
    +	if meta["trace_id"] != "trace-123" {
    +		t.Errorf("trace_id: got %v, want trace-123", meta["trace_id"])
    +	}
    +	if tags, ok := meta["tags"].([]any); !ok || len(tags) != 2 || tags[0] != "agent" {
    +		t.Errorf("tags: got %v, want ['agent', 'prod']", meta["tags"])
    +	}
    +	if meta["turn"] != float64(2) {
    +		t.Errorf("turn: got %v, want 2", meta["turn"])
    +	}
    +	if meta["enabled"] != true {
    +		t.Errorf("enabled: got %v, want true", meta["enabled"])
    +	}
    +	if cfg, ok := meta["config"].(map[string]any); !ok || cfg["retry"] != float64(3) {
    +		t.Errorf("config: got %v, want map[retry:3]", meta["config"])
    +	}
    +}
    +
    +func TestAnthropicRejectsMetadataTranslation(t *testing.T) {
    +	chatCodec := OpenAIChatCodec{}
    +	anthropicCodec := AnthropicMessagesCodec{}
    +	policy := llmprotocol.DefaultPolicy()
    +
    +	raw := []byte(`{"model":"claude-3-5-sonnet","messages":[{"role":"user","content":"hi"}],"metadata":{"tags":["agent"],"turn":1}}`)
    +	req, _, _, err := chatCodec.DecodeRequest(raw, policy)
    +	if err != nil {
    +		t.Fatalf("DecodeRequest: %v", err)
    +	}
    +
    +	// Attempting to cross-translate metadata to Anthropic Messages should be rejected
    +	_, _, err = anthropicCodec.EncodeRequest(req, llmprotocol.Envelope{}, policy)
    +	if err == nil {
    +		t.Fatalf("expected error translating metadata to Anthropic Messages, got nil")
    +	}
    +
    +	protocolErr, ok := err.(*llmprotocol.ProtocolError)

    Thanks, this fixes the re-encoding. CI's lint flags this assertion; errors.As would pass it.

    Paramveersingh-S Paramveersingh-S commented on code on Nov 18, 2026 13:00 UTC
    Code Review
    src/semantic-router/pkg/protocolcodec/codec_openai_metadata_test.go:1
    @@ -0,0 +1,460 @@
    +package protocolcodec
    +
    +import (
    +	"bytes"
    +	"encoding/json"
    +	"testing"
    +
    +	"github.com/vllm-project/semantic-router/src/semantic-router/pkg/llmprotocol"
    +)
    +
    +func TestOpenAIChatMetadataNonStringValues(t *testing.T) {
    +	codec := OpenAIChatCodec{}
    +	policy := llmprotocol.DefaultPolicy()
    +
    +	cases := []struct {
    +		name     string
    +		metadata string
    +		key      string
    +		wantVal  string
    +	}{
    +		{
    +			name:     "string value",
    +			metadata: `{"a":"b"}`,
    +			key:      "a",
    +			wantVal:  "b",
    +		},
    +		{
    +			name:     "list of strings (LiteLLM tags)",
    +			metadata: `{"tags":["agent","prod"]}`,
    +			key:      "tags",
    +			wantVal:  `["agent","prod"]`,
    +		},
    +		{
    +			name:     "integer number",
    +			metadata: `{"turn":1}`,
    +			key:      "turn",
    +			wantVal:  "1",
    +		},
    +		{
    +			name:     "floating point number",
    +			metadata: `{"score":98.5}`,
    +			key:      "score",
    +			wantVal:  "98.5",
    +		},
    +		{
    +			name:     "boolean true",
    +			metadata: `{"flag":true}`,
    +			key:      "flag",
    +			wantVal:  "true",
    +		},
    +		{
    +			name:     "boolean false",
    +			metadata: `{"flag":false}`,
    +			key:      "flag",
    +			wantVal:  "false",
    +		},
    +		{
    +			name:     "nested object",
    +			metadata: `{"nested":{"key":"val"}}`,
    +			key:      "nested",
    +			wantVal:  `{"key":"val"}`,
    +		},
    +		{
    +			name:     "null value",
    +			metadata: `{"empty":null}`,
    +			key:      "empty",
    +			wantVal:  "null",
    +		},
    +	}
    +
    +	for _, tc := range cases {
    +		t.Run(tc.name, func(t *testing.T) {
    +			rawBody := []byte(`{"model":"vllm-sr/auto","stream":true,"messages":[{"role":"user","content":"hi"}],"metadata":` + tc.metadata + `}`)
    +			req, envelope, _, err := codec.DecodeRequest(rawBody, policy)
    +			if err != nil {
    +				t.Fatalf("unexpected error decoding metadata %s: %v", tc.metadata, err)
    +			}
    +			if req.Metadata == nil {
    +				t.Fatalf("req.Metadata is nil")
    +			}
    +			if got := req.Metadata[tc.key]; got != tc.wantVal {
    +				t.Errorf("Metadata[%q] = %q, want %q", tc.key, got, tc.wantVal)
    +			}
    +			if req.MetadataJSON == nil || len(req.MetadataJSON[tc.key]) == 0 {
    +				t.Fatalf("req.MetadataJSON missing key %q", tc.key)
    +			}
    +			if err = llmprotocol.ValidateRequest(req, policy.Limits); err != nil {
    +				t.Errorf("ValidateRequest failed: %v", err)
    +			}
    +
    +			// Same-format re-encoding should replay verbatim bytes via envelope
    +			var encoded []byte
    +			encoded, _, err = codec.EncodeRequest(req, envelope, policy)
    +			if err != nil {
    +				t.Fatalf("EncodeRequest replay failed: %v", err)
    +			}
    +			if !bytes.Equal(encoded, rawBody) {
    +				t.Errorf("replayed bytes mismatch: got %s, want %s", string(encoded), string(rawBody))
    +			}
    +
    +			// Forced re-encoding (empty envelope, e.g. when router adds include_usage)
    +			// should preserve original JSON types rather than stringifying them.
    +			var reencoded []byte
    +			reencoded, _, err = codec.EncodeRequest(req, llmprotocol.Envelope{}, policy)
    +			if err != nil {
    +				t.Fatalf("Forced EncodeRequest failed: %v", err)
    +			}
    +			var parsed map[string]any
    +			if err := json.Unmarshal(reencoded, &parsed); err != nil {
    +				t.Fatalf("unmarshal reencoded JSON: %v", err)
    +			}
    +			meta, ok := parsed["metadata"].(map[string]any)
    +			if !ok {
    +				t.Fatalf("re-encoded metadata is not a map: %v", parsed["metadata"])
    +			}
    +			val := meta[tc.key]
    +			switch tc.name {
    +			case "string value":
    +				if val != "b" {
    +					t.Errorf("reencoded string: got %v (%T), want 'b'", val, val)
    +				}
    +			case "list of strings (LiteLLM tags)":
    +				list, ok := val.([]any)
    +				if !ok || len(list) != 2 || list[0] != "agent" || list[1] != "prod" {
    +					t.Errorf("reencoded list: got %v (%T), want []any{'agent', 'prod'}", val, val)
    +				}
    +			case "integer number":
    +				if val != float64(1) {
    +					t.Errorf("reencoded int: got %v (%T), want 1", val, val)
    +				}
    +			case "floating point number":
    +				if val != 98.5 {
    +					t.Errorf("reencoded float: got %v (%T), want 98.5", val, val)
    +				}
    +			case "boolean true":
    +				if val != true {
    +					t.Errorf("reencoded bool: got %v (%T), want true", val, val)
    +				}
    +			case "boolean false":
    +				if val != false {
    +					t.Errorf("reencoded bool: got %v (%T), want false", val, val)
    +				}
    +			case "nested object":
    +				obj, ok := val.(map[string]any)
    +				if !ok || obj["key"] != "val" {
    +					t.Errorf("reencoded object: got %v (%T), want map with key=val", val, val)
    +				}
    +			case "null value":
    +				if val != nil {
    +					t.Errorf("reencoded null: got %v (%T), want nil", val, val)
    +				}
    +			}
    +		})
    +	}
    +}
    +
    +func TestOpenAIMetadataLargeIntegerPrecisionPreserved(t *testing.T) {
    +	codec := OpenAIChatCodec{}
    +	policy := llmprotocol.DefaultPolicy()
    +
    +	// 9007199254740993 is 2^53 + 1, which loses precision in float64 (truncating to 9007199254740992)
    +	raw := []byte(`{"model":"vllm-sr/auto","stream":true,"messages":[{"role":"user","content":"hi"}],"metadata":{"large_int":9007199254740993}}`)
    +	req, _, _, err := codec.DecodeRequest(raw, policy)
    +	if err != nil {
    +		t.Fatalf("DecodeRequest: %v", err)
    +	}
    +
    +	if req.Metadata["large_int"] != "9007199254740993" {
    +		t.Errorf("req.Metadata[large_int] = %q, want 9007199254740993", req.Metadata["large_int"])
    +	}
    +	if string(req.MetadataJSON["large_int"]) != "9007199254740993" {
    +		t.Errorf("req.MetadataJSON[large_int] = %s, want 9007199254740993", string(req.MetadataJSON["large_int"]))
    +	}
    +
    +	// Forced re-encoding (e.g. streaming Chat where router adds include_usage)
    +	reencoded, _, err := codec.EncodeRequest(req, llmprotocol.Envelope{}, policy)
    +	if err != nil {
    +		t.Fatalf("EncodeRequest: %v", err)
    +	}
    +
    +	if !bytes.Contains(reencoded, []byte(`"large_int":9007199254740993`)) {
    +		t.Errorf("re-encoded wire JSON lost large integer precision: %s", string(reencoded))
    +	}
    +}
    +
    +func TestOpenAIChatCompoundMetadata(t *testing.T) {
    +	codec := OpenAIChatCodec{}
    +	policy := llmprotocol.DefaultPolicy()
    +
    +	raw := []byte(`{
    +		"model":"vllm-sr/auto",
    +		"messages":[{"role":"user","content":"hi"}],
    +		"metadata":{
    +			"trace_id":"trace-123",
    +			"session_id":"sess-456",
    +			"tags":["agent","vllm"],
    +			"turn":3,
    +			"score":99.25,
    +			"active":true,
    +			"extra":{"debug":true}
    +		}
    +	}`)
    +
    +	req, _, _, err := codec.DecodeRequest(raw, policy)
    +	if err != nil {
    +		t.Fatalf("decode compound metadata: %v", err)
    +	}
    +
    +	expected := map[string]string{
    +		"trace_id":   "trace-123",
    +		"session_id": "sess-456",
    +		"tags":       `["agent","vllm"]`,
    +		"turn":       "3",
    +		"score":      "99.25",
    +		"active":     "true",
    +		"extra":      `{"debug":true}`,
    +	}
    +
    +	for k, want := range expected {
    +		if got := req.Metadata[k]; got != want {
    +			t.Errorf("Metadata[%q] = %q, want %q", k, got, want)
    +		}
    +	}
    +
    +	// Verify forced re-encode retains compound JSON structure
    +	reencoded, _, err := codec.EncodeRequest(req, llmprotocol.Envelope{}, policy)
    +	if err != nil {
    +		t.Fatalf("forced encode compound metadata: %v", err)
    +	}
    +
    +	var parsed map[string]any
    +	if err := json.Unmarshal(reencoded, &parsed); err != nil {
    +		t.Fatalf("unmarshal reencoded JSON: %v", err)
    +	}
    +	meta := parsed["metadata"].(map[string]any)
    +	if meta["trace_id"] != "trace-123" {
    +		t.Errorf("reencoded trace_id = %v", meta["trace_id"])
    +	}
    +	if meta["turn"] != float64(3) {
    +		t.Errorf("reencoded turn = %v", meta["turn"])
    +	}
    +	if tags, ok := meta["tags"].([]any); !ok || len(tags) != 2 {
    +		t.Errorf("reencoded tags = %v", meta["tags"])
    +	}
    +	if extra, ok := meta["extra"].(map[string]any); !ok || extra["debug"] != true {
    +		t.Errorf("reencoded extra = %v", meta["extra"])
    +	}
    +}
    +
    +func TestOpenAIResponsesMetadataNonStringValues(t *testing.T) {
    +	codec := OpenAIResponsesCodec{}
    +	policy := llmprotocol.DefaultPolicy()
    +
    +	raw := []byte(`{
    +		"model":"vllm-sr/auto",
    +		"input":"hi",
    +		"metadata":{
    +			"trace_id":"trace-123",
    +			"tags":["agent","prod"],
    +			"turn":2,
    +			"enabled":true,
    +			"config":{"retry":3}
    +		},
    +		"client_metadata":{
    +			"client_tags":["telemetry"],
    +			"client_turn":1,
    +			"client_flag":false
    +		}
    +	}`)
    +
    +	req, envelope, diagnostics, err := codec.DecodeRequest(raw, policy)
    +	if err != nil {
    +		t.Fatalf("decode responses request: %v", err)
    +	}
    +
    +	if req.Metadata["trace_id"] != "trace-123" {
    +		t.Errorf("Metadata[trace_id] = %q, want trace-123", req.Metadata["trace_id"])
    +	}
    +	if req.Metadata["tags"] != `["agent","prod"]` {
    +		t.Errorf("Metadata[tags] = %q, want [\"agent\",\"prod\"]", req.Metadata["tags"])
    +	}
    +	if req.Metadata["turn"] != "2" {
    +		t.Errorf("Metadata[turn] = %q, want 2", req.Metadata["turn"])
    +	}
    +	if req.Metadata["enabled"] != "true" {
    +		t.Errorf("Metadata[enabled] = %q, want true", req.Metadata["enabled"])
    +	}
    +	if req.Metadata["config"] != `{"retry":3}` {
    +		t.Errorf("Metadata[config] = %q, want {\"retry\":3}", req.Metadata["config"])
    +	}
    +
    +	// Client metadata should be omitted with a diagnostic
    +	foundDiagnostic := false
    +	for _, diag := range diagnostics {
    +		if diag.Field == "client_metadata" {
    +			foundDiagnostic = true
    +			break
    +		}
    +	}
    +	if !foundDiagnostic {
    +		t.Errorf("expected client_metadata diagnostic omission, got: %v", diagnostics)
    +	}
    +
    +	if err = llmprotocol.ValidateRequest(req, policy.Limits); err != nil {
    +		t.Errorf("ValidateRequest failed: %v", err)
    +	}
    +
    +	// Replay preserves bytes
    +	var encoded []byte
    +	encoded, _, err = codec.EncodeRequest(req, envelope, policy)
    +	if err != nil {
    +		t.Fatalf("EncodeRequest failed: %v", err)
    +	}
    +	if !bytes.Equal(encoded, raw) {
    +		t.Errorf("replayed bytes mismatch")
    +	}
    +
    +	// Forced re-encode preserves native JSON types
    +	reencoded, _, err := codec.EncodeRequest(req, llmprotocol.Envelope{}, policy)
    +	if err != nil {
    +		t.Fatalf("forced EncodeRequest failed: %v", err)
    +	}
    +	var parsed map[string]any
    +	if err := json.Unmarshal(reencoded, &parsed); err != nil {
    +		t.Fatalf("unmarshal reencoded JSON: %v", err)
    +	}
    +	meta := parsed["metadata"].(map[string]any)
    +	if meta["trace_id"] != "trace-123" {
    +		t.Errorf("trace_id: got %v, want trace-123", meta["trace_id"])
    +	}
    +	if tags, ok := meta["tags"].([]any); !ok || len(tags) != 2 || tags[0] != "agent" {
    +		t.Errorf("tags: got %v, want ['agent', 'prod']", meta["tags"])
    +	}
    +	if meta["turn"] != float64(2) {
    +		t.Errorf("turn: got %v, want 2", meta["turn"])
    +	}
    +	if meta["enabled"] != true {
    +		t.Errorf("enabled: got %v, want true", meta["enabled"])
    +	}
    +	if cfg, ok := meta["config"].(map[string]any); !ok || cfg["retry"] != float64(3) {
    +		t.Errorf("config: got %v, want map[retry:3]", meta["config"])
    +	}
    +}
    +
    +func TestAnthropicRejectsMetadataTranslation(t *testing.T) {
    +	chatCodec := OpenAIChatCodec{}
    +	anthropicCodec := AnthropicMessagesCodec{}
    +	policy := llmprotocol.DefaultPolicy()
    +
    +	raw := []byte(`{"model":"claude-3-5-sonnet","messages":[{"role":"user","content":"hi"}],"metadata":{"tags":["agent"],"turn":1}}`)
    +	req, _, _, err := chatCodec.DecodeRequest(raw, policy)
    +	if err != nil {
    +		t.Fatalf("DecodeRequest: %v", err)
    +	}
    +
    +	// Attempting to cross-translate metadata to Anthropic Messages should be rejected
    +	_, _, err = anthropicCodec.EncodeRequest(req, llmprotocol.Envelope{}, policy)
    +	if err == nil {
    +		t.Fatalf("expected error translating metadata to Anthropic Messages, got nil")
    +	}
    +
    +	protocolErr, ok := err.(*llmprotocol.ProtocolError)

    Updated the assertion in codec_openai_metadata_test.go to use errors.As(err, &protocolErr) in commit 34916d8b6 to satisfy errorlint, and verified go test ./pkg/protocolcodec/... ./pkg/llmprotocol/... passes locally. Thanks for catching that @subin9!

    subin9 subin9 commented on Nov 18, 2026 23:46 UTC
    Contributor

    /ci run

    subin9 subin9 approved these changes on Nov 19, 2026 00:46 UTC
    Approved Reviewer

    Thanks, LGTM.

    wilsonwu wilsonwu approved these changes on Nov 19, 2026 02:32 UTC
    Approved Reviewer

    Approved these changes.

    Reviewers
    Assignees
    Paramveersingh-S Paramveersingh-S
    Labels
    risk: low confidence: 80.7% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 64.1% (MEDIUM) · Higher = larger blast radius
    64.1%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 80.7% · Lower = rushed or shallow review
    80.7%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 12.3% · Safe to merge
    12.3%