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
103 changes: 72 additions & 31 deletions framework/modelcatalog/datasheet/entryoverrides.go
Original file line number Diff line number Diff line change
Expand Up @@ -617,6 +617,9 @@ func (s *Store) applyPricingEntryOverridesUnsafe() {
s.pricingData.Put(key, patched)
}

// Mode-wide overrides apply before any mode-specific one (orderEntryOverrides), so no custom row
// exists yet when they run and the keys found up front are every key they patch.
modeWideKeys := s.modeWideTargetKeysUnsafe(overrides)
for i := range overrides {
o := &overrides[i]
provider := normalizeProvider(o.Provider)
Expand All @@ -636,15 +639,42 @@ func (s *Store) applyPricingEntryOverridesUnsafe() {
if o.PricingPatch == nil {
continue
}
prefix := strings.ToLower(o.Model + "|" + provider + "|")
for key, row := range tableEntries(s.pricingData) {
if strings.HasPrefix(key, prefix) {
for _, key := range modeWideKeys[makeKeyNormalized(o.Model, provider, "")] {
if row, ok := s.pricingData.Get(key); ok {
apply(key, row, o)
}
}
}
}

// modeWideTargetKeysUnsafe returns the pricing keys of each model and provider a mode-wide override
// with a pricing patch targets, keyed by their model|provider| prefix, from one pass over
// pricingData. Nil when no override is mode-wide. Caller holds s.mu.
func (s *Store) modeWideTargetKeysUnsafe(overrides []EntryOverride) map[string][]string {
var targets map[string][]string
for i := range overrides {
if o := &overrides[i]; o.Mode == "" && o.PricingPatch != nil {
if targets == nil {
targets = make(map[string][]string)
}
targets[makeKeyNormalized(o.Model, normalizeProvider(o.Provider), "")] = nil
}
}
if targets == nil {
return nil
}
for key := range tableEntries(s.pricingData) {
i := strings.LastIndexByte(key, '|')
if i < 0 {
continue
}
if keys, ok := targets[key[:i+1]]; ok {
targets[key[:i+1]] = append(keys, key)
}
}
return targets
}

// datasheetViewRowsUnsafe returns the rows the datasheet view is built from:
// every upstream spelling, with the overridden row standing in for each key an
// override patched (keeping that row's own spelling), plus the custom rows.
Expand Down Expand Up @@ -896,30 +926,38 @@ func (s *Store) ListDatasheetEntries(q DatasheetEntryQuery) ([]DatasheetEntry, i
matched := make([]bool, len(overrides))
var entries []DatasheetEntry
s.mu.RLock()
for key, effective := range tableEntries(s.pricingData) {
// No lookup prices a provider-less row and no override can target one.
if effective.Provider == "" || !matchesFilter(effective.Provider, effective.Model) {
for prefix, keys := range tableEntries(s.modelKeys) {
// A key spells its row's model in lowercase, so a search that misses the key's model misses
// every row under it.
if search != "" && !strings.Contains(keyModel(prefix), search) {
continue
}
entry := DatasheetEntry{Provider: effective.Provider, Model: effective.Model, Mode: effective.Mode}
for i := range overrides {
if overrideTargetsRow(&overrides[i], &effective) {
matched[i] = true
entry.Overrides = append(entry.Overrides, overrides[i].Row)
for _, key := range keys {
effective, ok := s.pricingData.Get(key)
// No lookup prices a provider-less row and no override can target one.
if !ok || effective.Provider == "" || !matchesFilter(effective.Provider, effective.Model) {
continue
}
entry := DatasheetEntry{Provider: effective.Provider, Model: effective.Model, Mode: effective.Mode}
for i := range overrides {
if overrideTargetsRow(&overrides[i], &effective) {
matched[i] = true
entry.Overrides = append(entry.Overrides, overrides[i].Row)
}
}
if q.OverriddenOnly && len(entry.Overrides) == 0 {
continue
}
effectiveCopy := effective
entry.Effective = &effectiveCopy
entry.IsCustom = has(s.customPricingKeys, key)
if upstream, replaced := s.pricingUpstream.Get(key); replaced {
entry.Upstream = &upstream
} else if !entry.IsCustom {
entry.Upstream = &effectiveCopy
}
entries = append(entries, entry)
}
if q.OverriddenOnly && len(entry.Overrides) == 0 {
continue
}
effectiveCopy := effective
entry.Effective = &effectiveCopy
entry.IsCustom = has(s.customPricingKeys, key)
if upstream, replaced := s.pricingUpstream.Get(key); replaced {
entry.Upstream = &upstream
} else if !entry.IsCustom {
entry.Upstream = &effectiveCopy
}
entries = append(entries, entry)
}
s.mu.RUnlock()

Expand Down Expand Up @@ -962,6 +1000,16 @@ func (s *Store) ListDatasheetEntries(q DatasheetEntryQuery) ([]DatasheetEntry, i
return entries[start:end], total
}

// keyModel returns the model part of a model|provider| prefix. Providers never contain "|", so a
// model that does is returned whole.
func keyModel(prefix string) string {
trimmed := strings.TrimSuffix(prefix, "|")
if i := strings.LastIndexByte(trimmed, '|'); i >= 0 {
return trimmed[:i]
}
return trimmed
}

// overrideTargetsRow reports whether o applies to the pricing row.
func overrideTargetsRow(o *EntryOverride, row *configstoreTables.TableModelPricing) bool {
return strings.EqualFold(o.Model, row.Model) && strings.EqualFold(normalizeProvider(o.Provider), row.Provider) && (o.Mode == "" || strings.EqualFold(o.Mode, row.Mode))
Expand Down Expand Up @@ -1156,14 +1204,7 @@ func (s *Store) upstreamPricingRow(o *EntryOverride) *configstoreTables.TableMod
if o.Mode != "" {
return lookup(makeKeyNormalized(o.Model, provider, o.Mode))
}
prefix := strings.ToLower(o.Model + "|" + provider + "|")
var keys []string
for key := range tableEntries(s.pricingData) {
if strings.HasPrefix(key, prefix) {
keys = append(keys, key)
}
}
slices.Sort(keys)
keys, _ := s.modelKeys.Get(makeKeyNormalized(o.Model, provider, ""))
for _, key := range keys {
if row := lookup(key); row != nil {
return row
Expand Down
156 changes: 154 additions & 2 deletions framework/modelcatalog/datasheet/entryoverrides_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"net/http"
"net/http/httptest"
"path/filepath"
"runtime"
"slices"
"strconv"
"sync"
Expand Down Expand Up @@ -569,8 +570,10 @@ func TestEntryOverride_ConcurrentUpsertsKeepEveryOverride(t *testing.T) {
func TestEntryOverride_ModeWideBaselineDoesNotFlagOtherModes(t *testing.T) {
ctx := context.Background()
s := newTestStore(t)
s.pricingData.Put(makeKey("m", "openai", "chat"), configstoreTables.TableModelPricing{Model: "m", Provider: "openai", Mode: "chat", InputCostPerToken: bifrost.Ptr(1.0)})
s.pricingData.Put(makeKey("m", "openai", "responses"), configstoreTables.TableModelPricing{Model: "m", Provider: "openai", Mode: "responses", InputCostPerToken: bifrost.Ptr(2.0)})
s.SetPricingRowsForTest([]configstoreTables.TableModelPricing{
{Model: "m", Provider: "openai", Mode: "chat", InputCostPerToken: bifrost.Ptr(1.0)},
{Model: "m", Provider: "openai", Mode: "responses", InputCostPerToken: bifrost.Ptr(2.0)},
})
row := configstoreTables.TableDatasheetOverride{ID: "all", Provider: "openai", Model: "m", PricingPatch: json.RawMessage(`{"input_cost_per_token": 5}`)}
parsed, err := ParseEntryOverride(&row)
require.NoError(t, err)
Expand Down Expand Up @@ -970,3 +973,152 @@ func BenchmarkCalculateCostWithEntryOverrides(b *testing.B) {
})
}
}

// modeWideOverrides returns n mode-wide overrides on openai models model-0 … model-(n-1), each
// lowering the input price, with a pricing baseline so the listing reports their drift.
func modeWideOverrides(model string, n int) []configstoreTables.TableDatasheetOverride {
rows := make([]configstoreTables.TableDatasheetOverride, 0, n)
for i := range n {
rows = append(rows, configstoreTables.TableDatasheetOverride{
ID: fmt.Sprintf("wide-%d", i),
Provider: "openai",
Model: fmt.Sprintf("%s-%d", model, i),
PricingPatch: json.RawMessage(`{"input_cost_per_token": 9e-06}`),
Baseline: json.RawMessage(`{"pricing": {"input_cost_per_token": 1e-06}}`),
})
}
return rows
}

// targetRows returns a chat and an embedding row for each of n openai models model-0 … model-(n-1).
func targetRows(model string, n int) []configstoreTables.TableModelPricing {
rows := make([]configstoreTables.TableModelPricing, 0, 2*n)
for i := range n {
name := fmt.Sprintf("%s-%d", model, i)
rows = append(rows,
configstoreTables.TableModelPricing{Model: name, Provider: "openai", Mode: "chat", InputCostPerToken: bifrost.Ptr(1e-06)},
configstoreTables.TableModelPricing{Model: name, Provider: "openai", Mode: "embedding", InputCostPerToken: bifrost.Ptr(2e-06)},
)
}
return rows
}

// bytesPerCall returns the heap bytes one call of f allocates, averaged over runs calls.
func bytesPerCall(runs int, f func()) uint64 {
f()
var before, after runtime.MemStats
runtime.ReadMemStats(&before)
for range runs {
f()
}
runtime.ReadMemStats(&after)
return (after.TotalAlloc - before.TotalAlloc) / uint64(runs)
}

// Mode-wide overrides find the rows they patch in one pass over the pricing table, however many
// there are: applying them runs under the write lock every cost calculation waits on.
func TestEntryOverride_ModeWideOverridesShareOnePricingWalk(t *testing.T) {
ctx := context.Background()
s := testStore(t, nil)
s.SetPricingRowsForTest(capabilityRows(2000))
applyAllocs := func(n int) float64 {
// The overrides name models the sheet does not list, so applying them patches nothing and
// what is measured is finding the rows.
s.SetEntryOverrides(ctx, modeWideOverrides("absent", n))
s.mu.Lock()
defer s.mu.Unlock()
return testing.AllocsPerRun(5, s.applyPricingEntryOverridesUnsafe)
}
one, twenty := applyAllocs(1), applyAllocs(20)
if twenty > 2*one {
t.Fatalf("applying 20 mode-wide overrides allocates %.0f times against %.0f for one: each override walks the pricing table", twenty, one)
}
}

// A mode-wide override patches every mode of its own model on its own provider, and no row of a
// model whose name it prefixes or of another provider.
func TestEntryOverride_ModeWidePatchStaysOnItsModel(t *testing.T) {
ctx := context.Background()
s := testStore(t, nil)
s.SetPricingRowsForTest(append(targetRows("target", 1),
configstoreTables.TableModelPricing{Model: "target-0-mini", Provider: "openai", Mode: "chat", InputCostPerToken: bifrost.Ptr(1e-06)},
configstoreTables.TableModelPricing{Model: "target-0", Provider: "azure", Mode: "chat", InputCostPerToken: bifrost.Ptr(1e-06)},
))
s.SetEntryOverrides(ctx, modeWideOverrides("target", 1))

for _, tc := range []struct {
model string
provider schemas.ModelProvider
mode schemas.RequestType
want float64
}{
{"target-0", schemas.OpenAI, schemas.ChatCompletionRequest, 9e-06},
{"target-0", schemas.OpenAI, schemas.EmbeddingRequest, 9e-06},
{"target-0-mini", schemas.OpenAI, schemas.ChatCompletionRequest, 1e-06},
{"target-0", schemas.Azure, schemas.ChatCompletionRequest, 1e-06},
} {
row := s.Get(tc.model, tc.provider, tc.mode)
require.NotNil(t, row, "%s/%s %s", tc.provider, tc.model, tc.mode)
assert.Equal(t, tc.want, *row.InputCostPerToken, "%s/%s %s", tc.provider, tc.model, tc.mode)
}
}

// A filtered listing reads only the rows that match: it walks an index of the pricing keys rather
// than copying every pricing row, and a mode-wide override's drift baseline is found the same way.
func TestListDatasheetEntries_DoesNotCopyThePricingTable(t *testing.T) {
ctx := context.Background()
s := testStore(t, nil)
s.SetPricingRowsForTest(capabilityRows(2000, targetRows("target", 5)...))
s.SetEntryOverrides(ctx, modeWideOverrides("target", 5))

entries, total := s.ListDatasheetEntries(DatasheetEntryQuery{Search: "target"})
require.Equal(t, 10, total)
for _, e := range entries {
require.Len(t, e.Overrides, 1, "%s/%s %s", e.Provider, e.Model, e.Mode)
assert.Equal(t, 9e-06, *e.Effective.InputCostPerToken, "%s/%s %s", e.Provider, e.Model, e.Mode)
// The baseline was taken from the chat row, the first mode in sort order, so nothing drifted.
assert.Empty(t, e.DriftedFields, "%s/%s %s", e.Provider, e.Model, e.Mode)
}

perCall := bytesPerCall(10, func() { s.ListDatasheetEntries(DatasheetEntryQuery{Search: "target"}) })
// One copy of the 2,010 rows alone would be about 2.6 MB.
if perCall > 1<<20 {
t.Fatalf("a listing of 10 rows out of 2,010 allocates %d KB per call, want at most 1 MB", perCall>>10)
}
}

// BenchmarkListDatasheetEntries measures the datasheet editor's listing over a catalog the size of
// a synced datasheet, with five mode-wide overrides whose drift it reports.
func BenchmarkListDatasheetEntries(b *testing.B) {
s := testStore(b, nil)
s.SetPricingRowsForTest(capabilityRows(5000, targetRows("target", 5)...))
s.SetEntryOverrides(context.Background(), modeWideOverrides("target", 5))
for _, bc := range []struct {
name string
query DatasheetEntryQuery
}{
{"first_page", DatasheetEntryQuery{Limit: 50}},
{"search", DatasheetEntryQuery{Search: "target", Limit: 50}},
} {
b.Run(bc.name, func(b *testing.B) {
b.ReportAllocs()
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
for b.Loop() {
s.ListDatasheetEntries(bc.query)
}
})
}
}

// BenchmarkApplyPricingEntryOverrides measures re-applying twenty mode-wide overrides, the work a
// sync or an override save does under the pricing write lock.
func BenchmarkApplyPricingEntryOverrides(b *testing.B) {
s := testStore(b, nil)
s.SetPricingRowsForTest(capabilityRows(5000, targetRows("target", 20)...))
s.SetEntryOverrides(context.Background(), modeWideOverrides("target", 20))
b.ReportAllocs()
for b.Loop() {
s.mu.Lock()
s.applyPricingEntryOverridesUnsafe()
s.mu.Unlock()
}
}
Loading
Loading