Skip to content
Merged
25 changes: 6 additions & 19 deletions acceleration/internal/llmrouter/session.go
Original file line number Diff line number Diff line change
Expand Up @@ -268,28 +268,15 @@ func (s *Session) attempt(ctx context.Context, params llm.ResponseParams, hedge
}

// loggedCall is what every "model call timing" line says about whose call it was and what
// served it. The line is logged with no request context, so the app is named here, under the
// field the request lines name it with (api.NewLogHandler), or it could not be filtered by app.
// A hedged response names its hedge and whether it was kept, so the attempt that lost can be
// told apart from the one the caller got.
// served it (routing.LoggedCall), and the host the provider sent it to. A hedged response names
// its hedge and whether it was kept, so the attempt that lost can be told apart from the one
// the caller got.
func (s *Session) loggedCall(stat routing.Stat) []any {
fields := []any{"call", s.owner.CallID}
if stat.CustomerID != "" {
fields = append(fields, "app_id", stat.CustomerID)
}
if stat.AgentID != "" {
fields = append(fields, "agent_id", stat.AgentID)
}
fields = append(fields, "provider", s.config.Provider, "model", s.config.Model)
var served []any
if host := vendorHost(s.provider); host != "" {
fields = append(fields, "vendor_host", host)
}
if s.config.Region != "" {
fields = append(fields, "region", s.config.Region)
}
if s.config.BYOK {
fields = append(fields, "byok", true)
served = []any{"vendor_host", host}
}
fields := routing.LoggedCall(s.owner.CallID, stat.Owner, s.config, served...)
if hedge, hedged := stat.Attributes[routing.AttributeHedge]; hedged {
fields = append(fields, "hedge", hedge, "kept", stat.Attributes[routing.AttributeKept])
}
Expand Down
26 changes: 26 additions & 0 deletions acceleration/internal/routing/logged.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package routing

// LoggedCall is what every per-call timing line ("model call timing", "speech synthesis
// timing", "speech transcription timing") says about whose call it was and what served it,
// under the same names on each so one query filters them all. The lines are logged with no
// request context, so the app is named here, under the field the request lines name it with
// (api.NewLogHandler), or it could not be filtered by app. served is what else a modality
// says about what served the call, placed right after the model.
func LoggedCall(callID string, owner Owner, config ProviderConfig, served ...any) []any {
fields := []any{"call", callID}
if owner.CustomerID != "" {
fields = append(fields, "app_id", owner.CustomerID)
}
if owner.AgentID != "" {
fields = append(fields, "agent_id", owner.AgentID)
}
fields = append(fields, "provider", config.Provider, "model", config.Model)
fields = append(fields, served...)
if config.Region != "" {
fields = append(fields, "region", config.Region)
}
if config.BYOK {
fields = append(fields, "byok", true)
}
return fields
}
25 changes: 25 additions & 0 deletions acceleration/internal/routing/logged_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package routing

import (
"testing"

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

// The fields and their order are those the "model call timing" line wrote before the speech
// lines shared them, so the line a log view already parses is the same.
func TestALoggedCallNamesWhoseItWasThenWhatServedIt(t *testing.T) {
owner := Owner{CustomerID: "acme", AgentID: "concierge", CallID: "ignored:owner-call"}
config := ProviderConfig{Provider: "gemma", Model: "gemma-4", Region: "eu", BYOK: true}

require.Equal(t, []any{
"call", "default:lobby", "app_id", "acme", "agent_id", "concierge",
"provider", "gemma", "model", "gemma-4", "vendor_host", "gemma.example.test",
"region", "eu", "byok", true,
}, LoggedCall("default:lobby", owner, config, "vendor_host", "gemma.example.test"))
}

func TestALoggedCallLeavesOutWhatItDoesNotKnow(t *testing.T) {
require.Equal(t, []any{"call", "", "provider", "gemma", "model", "gemma-4"},
LoggedCall("", Owner{}, ProviderConfig{Provider: "gemma", Model: "gemma-4"}))
}
81 changes: 69 additions & 12 deletions acceleration/internal/sttrouter/session.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package sttrouter
import (
"context"
"errors"
"log/slog"
"math"
"sync"
"sync/atomic"
Expand All @@ -13,6 +14,7 @@ import (

"github.com/GetStream/Vision-Agents/acceleration/internal/pricing"
"github.com/GetStream/Vision-Agents/acceleration/internal/routing"
"github.com/GetStream/Vision-Agents/acceleration/internal/store"
"github.com/GetStream/Vision-Agents/acceleration/internal/stt"
)

Expand Down Expand Up @@ -62,10 +64,13 @@ type Session struct {
// leaseMinute is what a minute of streaming is held at.
var leaseMinute = pricing.Quantities{pricing.AudioMs: 60_000}

// streamedAudio is audio a provider took and no row has billed yet.
// streamedAudio is audio a provider took and no row has billed yet, and what its timing line
// says it took in all, from when.
type streamedAudio struct {
config routing.ProviderConfig
ms float64
config routing.ProviderConfig
ms float64
total float64
firstAt time.Time
}

func newSession(
Expand All @@ -90,7 +95,8 @@ func newSession(
streamed: map[stt.STT]*streamedAudio{},
lease: routing.StartLease(recorder, config, owner, "stt", uuid.NewString(), leaseMinute),
}
go session.forward()
// Stamped here, as audio may reach the provider before forward runs.
go session.forward(time.Now())
return session
}

Expand Down Expand Up @@ -201,27 +207,29 @@ func (s *Session) Close() error {
// forward relays provider events and records statistics as they pass. A refusal the next
// candidate takes over from is not passed on: the caller hears of the Failover instead.
// When no candidate takes over, the caller hears the refusal, as if none had been asked.
func (s *Session) forward() {
func (s *Session) forward(startedAt time.Time) {
defer close(s.done)
defer close(s.events)

current := &relay{provider: s.provider, config: s.config}
current := &relay{provider: s.provider, config: s.config, startedAt: startedAt}
var refused []string
for {
event, open := s.next(current)
if !open {
// Before the events close, so whoever waits on them waits for the last row.
s.billUnsettled(nil)
s.billUnsettled(nil, current)
s.logTiming(current)
return
}
if failure, ok := event.(stt.Error); ok && failure.Fatal && !transportDrop(failure) && s.reopen != nil {
from := current.config.Name()
refused = append(refused, from)
if next, nextConfig, err := s.reopenAnswering(refused); err == nil && s.swap(current.provider, next, nextConfig) {
routing.CountHandover(routing.STT, current.config, failure.Err)
s.billUnsettled(current.provider)
s.billUnsettled(current.provider, current)
s.logTiming(current)

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 At a failover, the refused provider's line must carry the audio billUnsettled bills as it refuses. No test pins that. A mutant that moves s.logTiming(current) above s.billUnsettled(current.provider, current) passes every test: TestAFailedOverSession... uses a vendor-metered quietSTT (no unsettled row), and TestAFrameInFlight... checks only lines[1].

Test row for STTRouterSuite in sttrouter/timing_test.go. It passes on head 3/3 and fails under the mutant:

func (s *STTRouterSuite) TestARefusedRouterMeteredProviderLogsTheAudioBilledAsItRefused() {
	refusing := &meteredSTT{quietSTT: quietSTT{emitter: stt.NewEmitter(64)}}
	next := &meteredSTT{quietSTT: quietSTT{emitter: stt.NewEmitter(64)}}
	reopen := func([]string) (stt.STT, routing.ProviderConfig, error) {
		return next, timingConfig("assemblyai", "universal-streaming"), nil
	}
	session, logs := s.timedSession(refusing, timingConfig("deepgram", "flux-general-en"), reopen)

	s.speak(session, 35)
	refusing.emitter.Send(stt.Error{Fatal: true, Context: "connect", Err: errors.New("account suspended")})
	s.Require().True(s.awaitEvent(session, func(event stt.Event) bool { _, ok := event.(stt.Failover); return ok }))
	s.ended(session)

	lines := s.transcriptionLines(logs)
	s.Require().Len(lines, 2)
	s.Equal("deepgram", lines[0]["provider"])
	s.EqualValues(700, lines[0]["cost_micros"], "the 700 ms the refused vendor heard, billed as it refused")
}

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 25afa28: TestARefusedRouterMeteredProviderLogsTheAudioBilledAsItRefused (sttrouter/timing_test.go) expects the refused line's cost_micros = 700. It passes on the fix and fails under C2 (the line written before billUnsettled at the swap).

// Before the Failover is passed on: a write that fails meanwhile went to next.
current = &relay{provider: next, config: nextConfig}
current = &relay{provider: next, config: nextConfig, startedAt: time.Now()}
s.pass(current, stt.Failover{Provider: nextConfig.Provider, Model: nextConfig.Model, From: from, Err: failure.Err})
continue
}
Expand Down Expand Up @@ -262,6 +270,15 @@ type relay struct {
// ahead is what was read to answer a failed write and not passed on yet. It stops at a
// fatal error, so nothing the provider sends after one is read.
ahead []stt.Event

// What the provider's timing line says, kept by forward alone: when it started serving,
// when its first transcript was read, what its turns and its unsettled audio cost (a failed
// row bills no audio), and the fatal error that ended it.
startedAt time.Time
firstTranscriptAt time.Time
costMicros int64
errorCode string
errorMessage string
}

// next returns the provider's next event, observed, and reads ahead for a failed write
Expand Down Expand Up @@ -341,6 +358,9 @@ func (s *Session) swap(refusing, next stt.STT, config routing.ProviderConfig) bo
func (s *Session) observe(current *relay, event stt.Event) {
switch typed := event.(type) {
case stt.Transcript:
if current.firstTranscriptAt.IsZero() {
current.firstTranscriptAt = time.Now()
}
// Only settled transcripts are billable work; interim ones are revisions of a
// turn that has not finished yet.
if !typed.Final() {
Expand All @@ -367,6 +387,7 @@ func (s *Session) observe(current *relay, event stt.Event) {
stat.Estimated()
}
s.recorder.Record(current.config, stat)
current.costMicros += s.recorder.QuoteStat(current.config, stat).CostMicros

case stt.Error:
stat := routing.Stat{
Expand All @@ -386,21 +407,53 @@ func (s *Session) observe(current *relay, event stt.Event) {
// socket that dropped as a fatal error with the context read or write, and the
// next session can still reach the model.
stat.Fatal = !transportDrop(typed)
// The first is what ended the provider's part of the session.
if current.errorCode == "" {
current.errorCode, current.errorMessage = stat.ErrorCode, stat.ErrorMessage
}
}
s.recorder.Record(current.config, stat)
}
}

// logTiming writes the "speech transcription timing" line for what one provider served of
// the session: all of it, or what it served until it refused the session and the next
// candidate took over, which then has a line of its own. Time to first byte runs from the
// first audio the provider took to the first transcript read from it, interim ones included.
func (s *Session) logTiming(current *relay) {
var audioMs float64
var firstAudioAt time.Time
s.mu.Lock()
if streamed := s.streamed[current.provider]; streamed != nil {
audioMs, firstAudioAt = streamed.total, streamed.firstAt
}
s.mu.Unlock()
logged := append(routing.LoggedCall(s.owner.CallID, s.owner, current.config), "audio_ms", int64(audioMs))
// No transcript, or one read before any audio was taken, answers none of it.
if !firstAudioAt.IsZero() && !current.firstTranscriptAt.Before(firstAudioAt) {
logged = append(logged, "ttfb_ms", milliseconds(current.firstTranscriptAt.Sub(firstAudioAt)))
}
logged = append(logged, "duration_ms", milliseconds(time.Since(current.startedAt)),
"cost_micros", current.costMicros, "success", current.errorCode == "", "error_code", current.errorCode)
if current.errorMessage != "" {
logged = append(logged, "error", store.SafeLogText(current.errorMessage))
}
slog.Info("speech transcription timing", logged...)
}

func milliseconds(elapsed time.Duration) float64 { return float64(elapsed.Microseconds()) / 1000 }

// took counts audio a provider accepted, against the config it was routed under.
func (s *Session) took(provider stt.STT, config routing.ProviderConfig, ms float64) {
s.mu.Lock()
defer s.mu.Unlock()
streamed := s.streamed[provider]
if streamed == nil {
streamed = &streamedAudio{config: config}
streamed = &streamedAudio{config: config, firstAt: time.Now()}
s.streamed[provider] = streamed
}
streamed.ms += ms
streamed.total += ms
}

// claim is the whole milliseconds of audio the provider took since it was last billed, which
Expand All @@ -422,8 +475,9 @@ func (s *Session) claim(provider stt.STT) int64 {
// billed: what such a vendor heard after its last turn, when it refuses the session or the
// session ends, which it bills every second of. Nil bills every provider's. A vendor that
// measures itself reports what it bills on its turns, so what it took after them is not
// billed. The row is the router's own measure and times nothing the provider did.
func (s *Session) billUnsettled(only stt.STT) {
// billed. The row is the router's own measure and times nothing the provider did. What a row
// of current's provider costs is added to current's.
func (s *Session) billUnsettled(only stt.STT, current *relay) {
s.mu.Lock()
var providers []stt.STT
for provider := range s.streamed {
Expand All @@ -446,6 +500,9 @@ func (s *Session) billUnsettled(only stt.STT) {
stat := routing.Stat{Owner: s.owner, StartedAt: time.Now().UTC(), Usage: routing.Usage{AudioMs: ms}, Success: true, Unmeasured: true}
stat.MeasuredByRouter()
s.recorder.Record(config, stat)
if provider == current.provider {

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.

[Nit] R1.4 Audio that a refused provider takes after its line was written (a frame in flight at the failover) is billed in the end-of-session row (billUnsettled(nil, ...)), but no line carries it, because provider != current.provider. The lines' cost_micros then add up to less than the rows. Say so in the body, or ticket it.

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 the PR body (no code change): the speech-to-text section now says "The lines of a session can sum to less than its rows: audio a refused provider took after its line was written (a frame in flight at the failover) is billed to that provider in the row written when the session ends, and is in no line."

current.costMicros += s.recorder.QuoteStat(config, stat).CostMicros
}
}
}

Expand Down
Loading
Loading