Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 14 additions & 11 deletions core/schemas/bifrost.go
Original file line number Diff line number Diff line change
Expand Up @@ -335,6 +335,8 @@ const (
BifrostContextKeyRoutingAllowedProviders BifrostContextKey = "bifrost-routing-allowed-providers" // []ModelProvider; when set, downstream routing layers (enterprise LB, model-catalog-resolver) must intersect their candidate providers with this set. Plugins set this when they have an opinion about which providers are valid for the request — even if they couldn't pick one themselves. Empty slice means "no provider is permitted" (fail-closed).
BifrostContextKeyAllowPerRequestStorageOverride BifrostContextKey = "bifrost-allow-per-request-storage-override" // bool (set by transport from config — gates whether x-bf-disable-content-logging and x-bf-store-raw-request-response per-request overrides are honored)
BifrostContextKeyAllowPerRequestRawOverride BifrostContextKey = "bifrost-allow-per-request-raw-override" // bool (set by transport from config — gates whether x-bf-send-back-raw-request and x-bf-send-back-raw-response per-request overrides are honored)
BifrostContextKeyGuardrailDebug BifrostContextKey = "bifrost-guardrail-debug" // *BifrostGuardrailDebug (set by enterprise guardrails plugin - DO NOT SET THIS MANUALLY)
BifrostContextKeyCacheDebug BifrostContextKey = "bifrost-cache-debug" // *BifrostCacheDebug (set by semantic cache plugin - DO NOT SET THIS MANUALLY)
BifrostContextKeyRedactionData BifrostContextKey = "bifrost-redaction-data" // RedactionData (set by enterprise guardrails plugin - DO NOT SET THIS MANUALLY)
BifrostContextKeyDisableContentLogging BifrostContextKey = "x-bf-disable-content-logging" // bool (per-request override for content logging; only honored when BifrostContextKeyAllowPerRequestStorageOverride is true. When retain_content_in_object_storage is on, disabled content is still offloaded to object storage as hidden instead of dropped)
BifrostContextKeySkipListModelsGovernanceFiltering BifrostContextKey = "bifrost-skip-list-models-governance-filtering" // bool (set by bifrost - DO NOT SET THIS MANUALLY))
Expand Down Expand Up @@ -1700,27 +1702,28 @@ type BifrostResponseExtraFields struct {
// matched (i.e. RoutingInfo.ResolvedKeyAlias != nil), otherwise
// RoutingInfo.Model. Still populated for backward compatibility; new
// consumers should read from RoutingInfo.
ResolvedModelUsed string `json:"resolved_model_used,omitempty"`
Latency int64 `json:"latency"` // in milliseconds (for streaming responses this will be each chunk latency, and the last chunk latency will be the total latency)
ResolvedModelUsed string `json:"resolved_model_used,omitempty"`
Latency int64 `json:"latency"` // in milliseconds (for streaming responses this will be each chunk latency, and the last chunk latency will be the total latency)
// UpstreamLatency is the total time spent blocked on upstream sockets across
// every attempt, in milliseconds. Unlike Latency it survives retries and
// fallbacks, so total-UpstreamLatency is Bifrost's own cost. Nil when the
// request never accumulated one; nil means unknown, not zero.
UpstreamLatency *int64 `json:"upstream_latency,omitempty"`
ChunkIndex int `json:"chunk_index"` // used for streaming responses to identify the chunk index, will be 0 for non-streaming responses
RawRequest interface{} `json:"raw_request,omitempty"`
RawResponse interface{} `json:"raw_response,omitempty"`
CacheDebug *BifrostCacheDebug `json:"cache_debug,omitempty"`
ParseErrors []BatchError `json:"parse_errors,omitempty"` // errors encountered while parsing JSONL batch results
ConvertedRequestType RequestType `json:"converted_request_type,omitempty"`
DroppedCompatPluginParams []string `json:"dropped_compat_plugin_params,omitempty"` // params dropped by the compat plugin based on model catalog
ChunkIndex int `json:"chunk_index"` // used for streaming responses to identify the chunk index, will be 0 for non-streaming responses
RawRequest interface{} `json:"raw_request,omitempty"`
RawResponse interface{} `json:"raw_response,omitempty"`
CacheDebug *BifrostCacheDebug `json:"cache_debug,omitempty"`
GuardrailDebug *BifrostGuardrailDebug `json:"guardrail_debug,omitempty"`
ParseErrors []BatchError `json:"parse_errors,omitempty"` // errors encountered while parsing JSONL batch results
ConvertedRequestType RequestType `json:"converted_request_type,omitempty"`
DroppedCompatPluginParams []string `json:"dropped_compat_plugin_params,omitempty"` // params dropped by the compat plugin based on model catalog
// DroppedUnsupportedTools lists tool type strings silently stripped from the
// request because the target provider/model doesn't support them (e.g.
// web_search requested against a non-Nova Bedrock model). Currently populated
// only by the Bedrock provider.
DroppedUnsupportedTools []string `json:"dropped_unsupported_tools,omitempty"`
ProviderResponseHeaders map[string]string `json:"provider_response_headers,omitempty"` // HTTP response headers from the provider (filtered to exclude transport-level headers)
PassthroughPath string `json:"passthrough_path,omitempty"` // Stripped provider path for passthrough requests, e.g. "/v1/chat/completions"
ProviderResponseHeaders map[string]string `json:"provider_response_headers,omitempty"` // HTTP response headers from the provider (filtered to exclude transport-level headers)
PassthroughPath string `json:"passthrough_path,omitempty"` // Stripped provider path for passthrough requests, e.g. "/v1/chat/completions"
}

type RoutingInfo struct {
Expand Down
77 changes: 77 additions & 0 deletions core/schemas/cachedebug.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package schemas

// Clone returns an owned snapshot of cache debug data.
func (d *BifrostCacheDebug) Clone() *BifrostCacheDebug {
if d == nil {
return nil
}
clone := *d
clone.CacheID = cloneString(d.CacheID)
clone.HitType = cloneString(d.HitType)
clone.RequestedProvider = cloneString(d.RequestedProvider)
clone.RequestedModel = cloneString(d.RequestedModel)
clone.ProviderUsed = cloneString(d.ProviderUsed)
clone.ModelUsed = cloneString(d.ModelUsed)
clone.InputTokens = cloneInt(d.InputTokens)
clone.Threshold = cloneFloat64(d.Threshold)
clone.Similarity = cloneFloat64(d.Similarity)
clone.CacheHitLatency = cloneInt64(d.CacheHitLatency)
return &clone
}

// CacheDebugFromContext returns typed cache debug data stored on ctx.
func CacheDebugFromContext(ctx *BifrostContext) (*BifrostCacheDebug, bool) {
if ctx == nil {
return nil, false
}
debug, ok := ctx.Value(BifrostContextKeyCacheDebug).(*BifrostCacheDebug)
if !ok || debug == nil || debug.ProviderUsed == nil || debug.ModelUsed == nil || debug.InputTokens == nil {
return nil, false
}
return debug.Clone(), true
}

// SetCacheDebugOnContext stores semantic cache debug data on ctx.
func SetCacheDebugOnContext(ctx *BifrostContext, debug *BifrostCacheDebug) bool {
if ctx == nil || debug == nil || debug.ProviderUsed == nil || debug.ModelUsed == nil || debug.InputTokens == nil {
return false
}
ctx.SetValue(BifrostContextKeyCacheDebug, debug.Clone())
return true
}

// cloneString returns an owned copy of value.
func cloneString(value *string) *string {
if value == nil {
return nil
}
clone := *value
return &clone
}

// cloneInt returns an owned copy of value.
func cloneInt(value *int) *int {
if value == nil {
return nil
}
clone := *value
return &clone
}

// cloneFloat64 returns an owned copy of value.
func cloneFloat64(value *float64) *float64 {
if value == nil {
return nil
}
clone := *value
return &clone
}

// cloneInt64 returns an owned copy of value.
func cloneInt64(value *int64) *int64 {
if value == nil {
return nil
}
clone := *value
return &clone
}
29 changes: 29 additions & 0 deletions core/schemas/cachedebug_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package schemas

import (
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

// TestCacheDebugContextReturnsOwnedSnapshot verifies semantic cache metadata survives without aliases.
func TestCacheDebugContextReturnsOwnedSnapshot(t *testing.T) {
ctx := NewBifrostContext(nil, NoDeadline)
provider := "openai"
model := "text-embedding-3-small"
inputTokens := 12
require.True(t, SetCacheDebugOnContext(ctx, &BifrostCacheDebug{
ProviderUsed: &provider,
ModelUsed: &model,
InputTokens: &inputTokens,
}))

first, ok := CacheDebugFromContext(ctx)
require.True(t, ok)
*first.InputTokens = 999

second, ok := CacheDebugFromContext(ctx)
require.True(t, ok)
assert.Equal(t, 12, *second.InputTokens)
}
4 changes: 4 additions & 0 deletions core/schemas/chatcompletions.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ func (cr *BifrostChatResponse) ToTextCompletionResponse() *BifrostTextCompletion
Latency: cr.ExtraFields.Latency,
RawResponse: cr.ExtraFields.RawResponse,
CacheDebug: cr.ExtraFields.CacheDebug,
GuardrailDebug: cr.ExtraFields.GuardrailDebug,
ProviderResponseHeaders: cr.ExtraFields.ProviderResponseHeaders,
},
}
Expand Down Expand Up @@ -126,6 +127,7 @@ func (cr *BifrostChatResponse) ToTextCompletionResponse() *BifrostTextCompletion
Latency: cr.ExtraFields.Latency,
RawResponse: cr.ExtraFields.RawResponse,
CacheDebug: cr.ExtraFields.CacheDebug,
GuardrailDebug: cr.ExtraFields.GuardrailDebug,
ProviderResponseHeaders: cr.ExtraFields.ProviderResponseHeaders,
},
}
Expand Down Expand Up @@ -163,6 +165,7 @@ func (cr *BifrostChatResponse) ToTextCompletionResponse() *BifrostTextCompletion
Latency: cr.ExtraFields.Latency,
RawResponse: cr.ExtraFields.RawResponse,
CacheDebug: cr.ExtraFields.CacheDebug,
GuardrailDebug: cr.ExtraFields.GuardrailDebug,
ProviderResponseHeaders: cr.ExtraFields.ProviderResponseHeaders,
},
}
Expand All @@ -184,6 +187,7 @@ func (cr *BifrostChatResponse) ToTextCompletionResponse() *BifrostTextCompletion
Latency: cr.ExtraFields.Latency,
RawResponse: cr.ExtraFields.RawResponse,
CacheDebug: cr.ExtraFields.CacheDebug,
GuardrailDebug: cr.ExtraFields.GuardrailDebug,
ProviderResponseHeaders: cr.ExtraFields.ProviderResponseHeaders,
},
}
Expand Down
110 changes: 110 additions & 0 deletions core/schemas/guardraildebug.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
package schemas

// BifrostGuardrailDebug carries request-scoped guardrail execution metadata.
type BifrostGuardrailDebug struct {
JudgeCalls []BifrostGuardrailJudgeCall `json:"judge_calls,omitempty"`
}

// BifrostGuardrailJudgeCall records one billable guardrail judge invocation.
type BifrostGuardrailJudgeCall struct {
Phase string `json:"phase,omitempty"`
RuleID *uint `json:"rule_id,omitempty"`
RuleName string `json:"rule_name,omitempty"`
GuardrailName string `json:"guardrail_name,omitempty"`
GuardrailProvider string `json:"guardrail_provider,omitempty"`
Action string `json:"action,omitempty"`
Reason string `json:"reason,omitempty"`
JudgeProvider ModelProvider `json:"judge_provider,omitempty"`
JudgeModel string `json:"judge_model,omitempty"`
JudgeRequestType RequestType `json:"judge_request_type,omitempty"`
PromptTokens int `json:"prompt_tokens,omitempty"`
PromptTokensDetails *ChatPromptTokensDetails `json:"prompt_tokens_details,omitempty"`
CompletionTokens int `json:"completion_tokens,omitempty"`
CompletionTokensDetails *ChatCompletionTokensDetails `json:"completion_tokens_details,omitempty"`
TotalTokens int `json:"total_tokens,omitempty"`
}

// Clone returns an owned snapshot of the guardrail debug data.
func (d *BifrostGuardrailDebug) Clone() *BifrostGuardrailDebug {
if d == nil || len(d.JudgeCalls) == 0 {
return nil
}
clone := &BifrostGuardrailDebug{
JudgeCalls: make([]BifrostGuardrailJudgeCall, len(d.JudgeCalls)),
}
for index, call := range d.JudgeCalls {
clone.JudgeCalls[index] = call
clone.JudgeCalls[index].RuleID = cloneUint(call.RuleID)
clone.JudgeCalls[index].PromptTokensDetails = cloneChatPromptTokensDetails(call.PromptTokensDetails)
clone.JudgeCalls[index].CompletionTokensDetails = cloneChatCompletionTokensDetails(call.CompletionTokensDetails)
}
return clone
}

// cloneChatPromptTokensDetails returns an owned copy of nested prompt token details.
func cloneChatPromptTokensDetails(details *ChatPromptTokensDetails) *ChatPromptTokensDetails {
if details == nil {
return nil
}
clone := *details
if details.CachedWriteTokenDetails != nil {
cachedWriteClone := *details.CachedWriteTokenDetails
clone.CachedWriteTokenDetails = &cachedWriteClone
}
return &clone
}

// cloneChatCompletionTokensDetails returns an owned copy of completion token details.
func cloneChatCompletionTokensDetails(details *ChatCompletionTokensDetails) *ChatCompletionTokensDetails {
if details == nil {
return nil
}
clone := *details
clone.CitationTokens = cloneInt(details.CitationTokens)
clone.NumSearchQueries = cloneInt(details.NumSearchQueries)
clone.ImageTokens = cloneInt(details.ImageTokens)
return &clone
}

// cloneUint returns an owned copy of value.
func cloneUint(value *uint) *uint {
if value == nil {
return nil
}
clone := *value
return &clone
}

// GuardrailDebugFromContext returns typed guardrail debug data stored on ctx.
func GuardrailDebugFromContext(ctx *BifrostContext) (*BifrostGuardrailDebug, bool) {
if ctx == nil {
return nil, false
}
debug, ok := ctx.Value(BifrostContextKeyGuardrailDebug).(*BifrostGuardrailDebug)
if !ok || debug == nil || len(debug.JudgeCalls) == 0 {
return nil, false
}
return debug.Clone(), true
}

// SetGuardrailDebugOnContext stores non-empty guardrail debug data on ctx.
func SetGuardrailDebugOnContext(ctx *BifrostContext, debug *BifrostGuardrailDebug) bool {
if ctx == nil || debug == nil || len(debug.JudgeCalls) == 0 {
return false
}
ctx.SetValue(BifrostContextKeyGuardrailDebug, debug.Clone())
return true
}

// AppendGuardrailJudgeCallOnContext appends one guardrail judge call to ctx.
func AppendGuardrailJudgeCallOnContext(ctx *BifrostContext, call BifrostGuardrailJudgeCall) bool {
if ctx == nil || call.TotalTokens == 0 && call.PromptTokens == 0 && call.CompletionTokens == 0 {
return false
}
current, _ := GuardrailDebugFromContext(ctx)
if current == nil {
current = &BifrostGuardrailDebug{}
}
current.JudgeCalls = append(current.JudgeCalls, call)
return SetGuardrailDebugOnContext(ctx, current)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
82 changes: 82 additions & 0 deletions core/schemas/guardraildebug_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
package schemas

import (
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

// TestGuardrailDebugContextRoundTrip verifies typed guardrail debug context storage.
func TestGuardrailDebugContextRoundTrip(t *testing.T) {
ctx := NewBifrostContext(nil, NoDeadline)
call := BifrostGuardrailJudgeCall{
Phase: "input",
RuleName: "pii",
JudgeProvider: OpenAI,
JudgeModel: "gpt-4o-mini",
PromptTokens: 12,
TotalTokens: 12,
}

require.True(t, AppendGuardrailJudgeCallOnContext(ctx, call))
debug, ok := GuardrailDebugFromContext(ctx)
require.True(t, ok)
require.Len(t, debug.JudgeCalls, 1)
assert.Equal(t, call, debug.JudgeCalls[0])
}

// TestGuardrailDebugContextReturnsOwnedSnapshot verifies callers cannot mutate context state.
func TestGuardrailDebugContextReturnsOwnedSnapshot(t *testing.T) {
ctx := NewBifrostContext(nil, NoDeadline)
require.True(t, AppendGuardrailJudgeCallOnContext(ctx, BifrostGuardrailJudgeCall{
JudgeProvider: OpenAI,
JudgeModel: "gpt-4o-mini",
TotalTokens: 10,
}))

first, ok := GuardrailDebugFromContext(ctx)
require.True(t, ok)
first.JudgeCalls[0].TotalTokens = 999

second, ok := GuardrailDebugFromContext(ctx)
require.True(t, ok)
assert.Equal(t, 10, second.JudgeCalls[0].TotalTokens)
}

// TestGuardrailDebugContextClonesUsageDetails verifies nested pricing details cannot alias context state.
func TestGuardrailDebugContextClonesUsageDetails(t *testing.T) {
ctx := NewBifrostContext(nil, NoDeadline)
citationTokens := 3
require.True(t, AppendGuardrailJudgeCallOnContext(ctx, BifrostGuardrailJudgeCall{
JudgeProvider: OpenAI,
JudgeModel: "gpt-4o-mini",
PromptTokens: 10,
PromptTokensDetails: &ChatPromptTokensDetails{
CachedWriteTokenDetails: &ChatCachedWriteTokenDetails{CachedWriteTokens5m: 4},
},
CompletionTokens: 5,
CompletionTokensDetails: &ChatCompletionTokensDetails{
CitationTokens: &citationTokens,
},
TotalTokens: 15,
}))

first, ok := GuardrailDebugFromContext(ctx)
require.True(t, ok)
first.JudgeCalls[0].PromptTokensDetails.CachedWriteTokenDetails.CachedWriteTokens5m = 999
*first.JudgeCalls[0].CompletionTokensDetails.CitationTokens = 999

second, ok := GuardrailDebugFromContext(ctx)
require.True(t, ok)
assert.Equal(t, 4, second.JudgeCalls[0].PromptTokensDetails.CachedWriteTokenDetails.CachedWriteTokens5m)
assert.Equal(t, 3, *second.JudgeCalls[0].CompletionTokensDetails.CitationTokens)
}

// TestAppendGuardrailJudgeCallRejectsEmptyUsage verifies non-billable calls are omitted.
func TestAppendGuardrailJudgeCallRejectsEmptyUsage(t *testing.T) {
ctx := NewBifrostContext(nil, NoDeadline)
assert.False(t, AppendGuardrailJudgeCallOnContext(ctx, BifrostGuardrailJudgeCall{}))
_, ok := GuardrailDebugFromContext(ctx)
assert.False(t, ok)
}
Loading
Loading