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
18 changes: 18 additions & 0 deletions acceleration/internal/routing/call.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,11 @@ type Meter struct {
// longer, such as a picture a queued provider takes minutes over, holds it for as long as
// it may run, or concurrent work could spend past a limit once the hold lapsed.
ReserveFor time.Duration
// Recorded, when set, is told how a Call ended once its row is recorded: the stat the row
// was made of and what the row costs, priced as Record prices it (free work and a quoted
// cost included), for a line logged beside the row. It is told of a failure and a panic
// too, and not of work Omit leaves out. Nil tells nobody.
Recorded func(stat Stat, costMicros int64)
}

// ReserveTTL is how long what a unit of request-and-answer work may cost is set aside before
Expand Down Expand Up @@ -130,6 +135,10 @@ func Call[R pricing.Metered](ctx context.Context, meter Meter, ask func(context.
if reserved != uuid.Nil && (omitted || stat.UsageID != reserved) {
meter.Recorder.Release(reserved)
}
// Last, so a hook that panics leaves the row queued and the reservation let go.
if !omitted && meter.Recorded != nil {
meter.Recorded(stat, meter.cost(stat))
}
}()

result, err := ask(ctx)
Expand Down Expand Up @@ -222,6 +231,15 @@ func (m Meter) record(stat Stat) {
}
}

// cost is what the stat's row costs, priced as Record prices it. Zero with no recorder.
func (m Meter) cost(stat Stat) int64 {
if m.Recorder == nil {
return 0
}
request, _ := m.Recorder.price(m.Config, stat)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

[Should fix] R1.1 Three mutants survive every test:

  1. Here, price changed to priced: the dropped-user counter usage_user_id_dropped then goes up twice per batch row.
  2. sttrouter/recordings.go:136 passes ProviderConfig{Provider, Model}, which drops region and BYOK.
  3. ttsrouter/recordings.go:287 does the same.

Test rows, each checked to pass on head and fail under its mutant:

(1) In call_integration_test.go, CallSuite:

// A refused user id is counted once for the row: the line's pricing must not count it again.
func (s *CallSuite) TestARecordedHookCountsARefusedUserIDOncePerRow() {
	for id, reason := range refusedUsers {
		meter := s.meter(priced)
		meter.Owner.UserID = id
		told := 0
		meter.Recorded = func(Stat, int64) { told++ }
		before := testutil.ToFloat64(usageUserIDDropped.WithLabelValues(reason))

		_, err := Call(s.ctx, meter, func(context.Context) (used, error) { return used{pricing.InputTokens: 1_000}, nil })

		s.Require().NoError(err)
		s.Equal(1, told)
		s.Empty(s.only(meter).UserID)
		s.Equal(1.0, testutil.ToFloat64(usageUserIDDropped.WithLabelValues(reason))-before, reason)
	}
}

(2) In sttrouter transcribeLogged, give the provider config Region: "us". Any other region fails Select with "sets no endpoint". Add "region": "us" to both expected maps.

(3) In ttsrouter recordLogged, give the voicy config Region: "us", and add "region": "us" to the two voicy expected maps.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in dacd0fb (commit afd0cdd): CallSuite TestARecordedHookCountsARefusedUserIDOncePerRow (mutant A: expected 1, actual 2), and "region": "us" in the sttrouter and ttsrouter timing tests (I10s, I10t mutants now fail both tests each).

return request.CostMicros
}

func (m Meter) code(err error) string {
if m.Code == nil {
return "provider_error"
Expand Down
47 changes: 47 additions & 0 deletions acceleration/internal/routing/call_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
"time"

"github.com/google/uuid"
"github.com/prometheus/client_golang/prometheus/testutil"
"github.com/stretchr/testify/suite"

"github.com/GetStream/Vision-Agents/acceleration/internal/alerts"
Expand Down Expand Up @@ -325,3 +326,49 @@ func (s *CallSuite) TestAMeterNamesTheRowsAttributes() {

s.Equal(map[string]string{"parent_session": "session-1"}, s.only(meter).Attributes)
}

// The row of free work costs nothing, and the row of a quoted fee costs the fee resold:
// neither is what its quantities would cost from the price list (Recorder.QuoteStat), 2,000
// and nothing.
func (s *CallSuite) TestARecordedHookIsToldWhatTheStoredRowCosts() {
free := s.meter(priced)
free.Free = true
quoted := s.meter(number)
quoted.CostMicros = 1_150_000
for name, meter := range map[string]Meter{"priced": s.meter(priced), "free": free, "quoted": quoted} {
var costs []int64
meter.Recorded = func(_ Stat, costMicros int64) { costs = append(costs, costMicros) }

_, err := Call(s.ctx, meter, func(context.Context) (used, error) { return used{pricing.InputTokens: 1_000}, nil })
s.Require().NoError(err, name)

row := s.only(meter)
s.Equal([]int64{row.CostMicros}, costs, "%s: the line says what the row costs", name)
switch name {
case "priced":
s.EqualValues(2_000, row.CostMicros)
case "free":
s.Zero(row.CostMicros)
case "quoted":
s.Positive(row.CostMicros)
}
}
}

// A refused user id is counted once for the row: the line's pricing must not count it again.
func (s *CallSuite) TestARecordedHookCountsARefusedUserIDOncePerRow() {
for id, reason := range refusedUsers {
meter := s.meter(priced)
meter.Owner.UserID = id
told := 0
meter.Recorded = func(Stat, int64) { told++ }
before := testutil.ToFloat64(usageUserIDDropped.WithLabelValues(reason))

_, err := Call(s.ctx, meter, func(context.Context) (used, error) { return used{"input_tokens": 1_000}, nil })

s.Require().NoError(err)
s.Equal(1, told)
s.Empty(s.only(meter).UserID)
s.Equal(1.0, testutil.ToFloat64(usageUserIDDropped.WithLabelValues(reason))-before, reason)
}
}
133 changes: 133 additions & 0 deletions acceleration/internal/routing/call_test.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
package routing

import (
"bytes"
"context"
"errors"
"log/slog"
"testing"

"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"

"github.com/GetStream/Vision-Agents/acceleration/internal/pricing"
)
Expand Down Expand Up @@ -36,3 +40,132 @@ func TestAStatTakesWhatTheWorkUsedIntoItsColumnsAndMeters(t *testing.T) {
require.Equal(t, Usage{InputTokens: 2_400, CachedInputTokens: 11, OutputTokens: 22, Requests: 1}, stat.Usage)
require.Equal(t, pricing.Quantities{pricing.CacheWriteInputTokens: 2_386, pricing.OutputAudioTokens: 40}, stat.Meters)
}

// hooked is every call a Meter.Recorded hook was told of: the stat and what its row costs.
type hooked struct {
stats []Stat
costs []int64
}

func (t *hooked) hook(stat Stat, costMicros int64) {
t.stats, t.costs = append(t.stats, stat), append(t.costs, costMicros)
}

// inputTokens is work that read n input tokens.
type inputTokens int64

func (n inputTokens) Used() pricing.Quantities {
return pricing.Quantities{pricing.InputTokens: int64(n)}
}

// CallHookSuite calls vendors through Call with a Meter.Recorded hook that keeps what it is told,
// on a meter of a model priced at 2 US dollars a million input tokens, whose recorder writes
// nothing.
type CallHookSuite struct {
suite.Suite
meter Meter
hook *hooked
}

func TestCallHookSuite(t *testing.T) {
suite.Run(t, new(CallHookSuite))
}

func (s *CallHookSuite) SetupTest() {
config := ProviderConfig{Provider: "vendor", Model: "told", Price: Price{PerMillionInputTokens: 2}}
logger := slog.New(slog.DiscardHandler)
prices, err := Prices(Config{LLM: {Providers: []ProviderConfig{config}}}, logger)
s.Require().NoError(err)
recorder := NewRecorder(LLM, nil, nil, prices, logger)
s.T().Cleanup(recorder.Close)
s.hook = &hooked{}
s.meter = Meter{Recorder: recorder, Config: config, Owner: Owner{CustomerID: "acme", CallID: "default:c1"},
Code: func(error) string { return "vendor_refused" }, Recorded: s.hook.hook}
}

func (s *CallHookSuite) TestARecordedHookIsToldWhatTheCallUsedAndWhatItsRowCosts() {
meter, hook := s.meter, s.hook

_, err := Call(context.Background(), meter, func(context.Context) (inputTokens, error) { return 1_000, nil })

s.Require().NoError(err)
s.Len(hook.stats, 1, "one call is told once")
stat := hook.stats[0]
s.True(stat.Success)
s.Empty(stat.ErrorCode)
s.EqualValues(1_000, stat.InputTokens)
s.Equal("default:c1", stat.CallID)
s.Equal([]int64{2_000}, hook.costs, "a thousand tokens at 2 US dollars a million")
}

func (s *CallHookSuite) TestARecordedHookIsToldOfAFailureWithItsCodeAndNoCost() {
meter, hook := s.meter, s.hook

_, err := Call(context.Background(), meter, func(context.Context) (inputTokens, error) {
return 1_000, errors.New("vendor said no")
})

s.Require().Error(err)
s.Len(hook.stats, 1)
s.False(hook.stats[0].Success)
s.Equal("vendor_refused", hook.stats[0].ErrorCode)
s.Equal("vendor said no", hook.stats[0].ErrorMessage)
s.Zero(hook.stats[0].InputTokens, "a failure is recorded without quantities")
s.Equal([]int64{0}, hook.costs)
}

func (s *CallHookSuite) TestARecordedHookIsToldOfAPanicBeforeItCarriesOn() {
meter, hook := s.meter, s.hook

s.PanicsWithValue("vendor fell over", func() {
_, _ = Call(context.Background(), meter, func(context.Context) (inputTokens, error) { panic("vendor fell over") })
})

s.Len(hook.stats, 1)
s.Equal("panic", hook.stats[0].ErrorCode)
}

func (s *CallHookSuite) TestARecordedHookIsNotToldOfWorkTheMeterOmits() {
meter, hook := s.meter, s.hook
meter.Omit = func(used pricing.Quantities) bool { return used[pricing.InputTokens] == 0 }

_, err := Call(context.Background(), meter, func(context.Context) (inputTokens, error) { return 0, nil })
s.Require().NoError(err)
_, err = Call(context.Background(), meter, func(context.Context) (inputTokens, error) { return 5, nil })
s.Require().NoError(err)

s.Len(hook.stats, 1, "only the work with a row is told")
s.EqualValues(5, hook.stats[0].InputTokens)
}

func (s *CallHookSuite) TestARecordedHookOfAMeterWithNoRecorderIsToldItCostsNothing() {
hook := &hooked{}

_, err := Call(context.Background(), Meter{Recorded: hook.hook}, func(context.Context) (inputTokens, error) { return 1_000, nil })

s.Require().NoError(err)
s.Len(hook.stats, 1, "a router built without a recorder still logs its line")
s.Equal([]int64{0}, hook.costs)
}

func (s *CallHookSuite) TestACallWithNoRecordedHookLogsNothing() {
var logs bytes.Buffer
logger := slog.New(slog.NewJSONHandler(&logs, nil))
previous := slog.Default()
slog.SetDefault(logger)
s.T().Cleanup(func() { slog.SetDefault(previous) })
meter := s.meter
meter.Recorded = nil
recorder := NewRecorder(LLM, nil, nil, meter.Recorder.pricer, logger)
s.T().Cleanup(recorder.Close)
meter.Recorder = recorder

_, err := Call(context.Background(), meter, func(context.Context) (inputTokens, error) { return 1_000, nil })
s.Require().NoError(err)
_, err = Call(context.Background(), meter, func(context.Context) (inputTokens, error) {
return 0, errors.New("vendor said no")
})
s.Require().Error(err)

s.Empty(logs.String(), "the other callers of Call log no line of their own")
}
33 changes: 33 additions & 0 deletions acceleration/internal/routing/reserve_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,39 @@ func (s *ReserveSuite) TestAFailedCallReleasesItsReservation() {
s.False(s.rows(1)[0].Success)
}

func (s *ReserveSuite) TestARecordedHookIsToldOnlyOnceTheReservationIsReleased() {
s.credit(2_000_000)
meter := s.meter()
meter.Estimate = pricing.Quantities{pricing.InputTokens: 1_000_000}
var held error
told := false
meter.Recorded = func(routing.Stat, int64) { held, told = s.spend(), true }

_, err := routing.Call(s.ctx, meter, func(context.Context) (worked, error) {
return nil, errors.New("vendor down")
})

s.Require().Error(err)
s.True(told)
s.NoError(held, "the hook runs after the reservation is let go, so work it does holds no money")
}

func (s *ReserveSuite) TestAPanickingRecordedHookStillReleasesTheReservation() {
s.credit(2_000_000)
meter := s.meter()
meter.Estimate = pricing.Quantities{pricing.InputTokens: 1_000_000}
meter.Recorded = func(routing.Stat, int64) { panic("hook fell over") }

s.PanicsWithValue("hook fell over", func() {
_, _ = routing.Call(s.ctx, meter, func(context.Context) (worked, error) {
return nil, errors.New("vendor down")
})
})

s.NoError(s.spend(), "a failed call holds nothing, though its hook panicked")
s.False(s.rows(1)[0].Success, "and the row was queued before the hook ran")
}

func (s *ReserveSuite) TestWorkThatNamesItsOwnIDReleasesTheReservation() {
s.credit(2_000_000)
meter := s.meter()
Expand Down
9 changes: 8 additions & 1 deletion acceleration/internal/routing/stats.go
Original file line number Diff line number Diff line change
Expand Up @@ -436,8 +436,15 @@ func (r *Recorder) lose(config ProviderConfig, entry Stat, cause error) {
// priced is the stat's row priced, and the quote of its quantities. It builds each row Record
// writes or lose loses once, so a user id left off is counted once per row.
func (r *Recorder) priced(config ProviderConfig, entry Stat) (store.Request, pricing.Quote) {
request := row(r.modality, config, entry)
request, priced := r.price(config, entry)
request.UserID = userOnRow(entry.CustomerID, entry.UserID)
return request, priced
}

// price is what priced builds, its user id unchecked, for a caller that only reads what the
// row costs: a user id left off is counted by the row Record writes, not again here.
func (r *Recorder) price(config ProviderConfig, entry Stat) (store.Request, pricing.Quote) {
request := row(r.modality, config, entry)
pricedBy := quote
if entry.CostMicros != 0 {
pricedBy = quoteBesideQuoted
Expand Down
18 changes: 17 additions & 1 deletion acceleration/internal/sttrouter/recordings.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@ package sttrouter

import (
"context"
"log/slog"

"github.com/GetStream/Vision-Agents/acceleration/internal/options"
"github.com/GetStream/Vision-Agents/acceleration/internal/routing"
"github.com/GetStream/Vision-Agents/acceleration/internal/store"
"github.com/GetStream/Vision-Agents/acceleration/internal/stt"
"github.com/GetStream/Vision-Agents/acceleration/internal/stt/deepgram"
)
Expand Down Expand Up @@ -130,7 +132,8 @@ func (r *Recordings) Transcribe(

transcription, err := routing.Call(ctx, routing.Meter{
Recorder: r.Recorder(), Config: config, Owner: request.Owner(),
Code: func(error) string { return "transcribe_failed" },
Code: func(error) string { return "transcribe_failed" },
Recorded: func(stat routing.Stat, costMicros int64) { logRecordingTiming(config, stat, costMicros) },
}, func(ctx context.Context) (stt.Transcription, error) {
return provider.Transcribe(ctx, recording.Source)
})
Expand All @@ -139,3 +142,16 @@ func (r *Recordings) Transcribe(
}
return transcription, config, nil
}

// logRecordingTiming writes the "speech transcription timing" line of a whole recording, for
// the row its transcription recorded. batch tells it from a session's line, its duration is
// the request's, and with one answer for the whole file it has no first transcript to time.
func logRecordingTiming(config routing.ProviderConfig, stat routing.Stat, costMicros int64) {
logged := append(routing.LoggedCall(stat.CallID, stat.Owner, config), "batch", true,
"audio_ms", stat.AudioMs, "duration_ms", stat.LatencyMs, "cost_micros", costMicros,
"success", stat.Success, "error_code", stat.ErrorCode)
if stat.ErrorMessage != "" {
logged = append(logged, "error", store.SafeLogText(stat.ErrorMessage))
}
slog.Info("speech transcription timing", logged...)
}
Loading
Loading