diff --git a/acceleration/internal/llmrouter/session.go b/acceleration/internal/llmrouter/session.go index f539f754c7..4425460157 100644 --- a/acceleration/internal/llmrouter/session.go +++ b/acceleration/internal/llmrouter/session.go @@ -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]) } diff --git a/acceleration/internal/routing/logged.go b/acceleration/internal/routing/logged.go new file mode 100644 index 0000000000..03518df7fa --- /dev/null +++ b/acceleration/internal/routing/logged.go @@ -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 +} diff --git a/acceleration/internal/routing/logged_test.go b/acceleration/internal/routing/logged_test.go new file mode 100644 index 0000000000..0392ceb0bb --- /dev/null +++ b/acceleration/internal/routing/logged_test.go @@ -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"})) +} diff --git a/acceleration/internal/sttrouter/session.go b/acceleration/internal/sttrouter/session.go index fbba58f2b0..8db8439306 100644 --- a/acceleration/internal/sttrouter/session.go +++ b/acceleration/internal/sttrouter/session.go @@ -3,6 +3,7 @@ package sttrouter import ( "context" "errors" + "log/slog" "math" "sync" "sync/atomic" @@ -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" ) @@ -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( @@ -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 } @@ -201,17 +207,18 @@ 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 { @@ -219,9 +226,10 @@ func (s *Session) forward() { 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) // 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 } @@ -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 @@ -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() { @@ -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{ @@ -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 @@ -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 { @@ -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 { + current.costMicros += s.recorder.QuoteStat(config, stat).CostMicros + } } } diff --git a/acceleration/internal/sttrouter/timing_test.go b/acceleration/internal/sttrouter/timing_test.go new file mode 100644 index 0000000000..c06df082ce --- /dev/null +++ b/acceleration/internal/sttrouter/timing_test.go @@ -0,0 +1,353 @@ +package sttrouter + +import ( + "bytes" + "crypto/rand" + "encoding/json" + "errors" + "log/slog" + "sync" + "testing" + "testing/synctest" + "time" + + "github.com/GetStream/Vision-Agents/acceleration/internal/routing" + "github.com/GetStream/Vision-Agents/acceleration/internal/stt" +) + +// timingConfig is a transcriber priced at 3.60 US dollars an audio hour: a millisecond of +// audio costs one micro-dollar. +func timingConfig(provider, model string) routing.ProviderConfig { + return routing.ProviderConfig{Provider: provider, Model: model, Price: routing.Price{PerAudioHour: 3.6}} +} + +// timedSession is a session over provider whose log lines are kept, owned the way an agent's +// transcriber in a call is. reopen, when set, is the next candidate a refusal hands over to. +func (s *STTRouterSuite) timedSession(provider stt.STT, config routing.ProviderConfig, + reopen func([]string) (stt.STT, routing.ProviderConfig, error)) (*Session, *timingLog) { + var configs []routing.ProviderConfig + configs = append(configs, config, timingConfig("assemblyai", "universal-streaming")) + prices, err := routing.Prices(routing.Config{routing.STT: {Providers: configs}}, slog.Default()) + s.Require().NoError(err) + recorder := routing.NewRecorder(routing.STT, nil, nil, prices, slog.Default()) + logs := &timingLog{call: "default:" + rand.Text()} + previous := slog.Default() + slog.SetDefault(slog.New(slog.NewJSONHandler(logs, nil))) + owner := routing.Owner{CustomerID: "acme", AgentID: "concierge", CallID: logs.call} + session := newSession(provider, config, owner, recorder, reopen, nil) + s.T().Cleanup(func() { + _ = session.Close() + slog.SetDefault(previous) + recorder.Close() + }) + return session, logs +} + +// timingLog keeps what is logged. The session logs from its own goroutine. +type timingLog struct { + call string + mu sync.Mutex + logs bytes.Buffer +} + +func (l *timingLog) Write(line []byte) (int, error) { + l.mu.Lock() + defer l.mu.Unlock() + return l.logs.Write(line) +} + +// lines are this session's "speech transcription timing" lines, decoded, oldest first. A +// session an earlier test closed may still be logging, so lines of other calls are left out. +func (s *STTRouterSuite) transcriptionLines(logs *timingLog) []map[string]any { + logs.mu.Lock() + defer logs.mu.Unlock() + var found []map[string]any + for decoder := json.NewDecoder(bytes.NewReader(logs.logs.Bytes())); decoder.More(); { + var line map[string]any + s.Require().NoError(decoder.Decode(&line)) + if line["msg"] == "speech transcription timing" && line["call"] == logs.call { + found = append(found, line) + } + } + return found +} + +// ended closes the session and waits until its events close, which is after its last line. +func (s *STTRouterSuite) ended(session *Session) { + s.Require().NoError(session.Close()) + s.awaitEvent(session, func(stt.Event) bool { return false }) +} + +// awaitEvent reads the session's events until one matches, and reports whether one did before +// they closed. +func (s *STTRouterSuite) awaitEvent(session *Session, match func(stt.Event) bool) bool { + deadline := time.After(5 * time.Second) + for { + select { + case event, open := <-session.Events(): + if !open { + return false + } + if match(event) { + return true + } + case <-deadline: + s.FailNow("timed out reading the session's events") + return false + } + } +} + +// speak sends frames of 20 ms of audio. +func (s *STTRouterSuite) speak(session *Session, frames int) { + frame := stt.PcmData{Samples: make([]int16, 320), SampleRate: 16000, Channels: 1} + for range frames { + s.Require().NoError(session.ProcessAudio(frame, stt.Participant{})) + } +} + +// onFakeClock runs body in a synctest bubble, where time moves only as the test sleeps, so +// the times a line logs are exact. +func (s *STTRouterSuite) onFakeClock(body func()) { + outer := s.T() + synctest.Test(outer, func(t *testing.T) { + s.SetT(t) + defer s.SetT(outer) + body() + }) +} + +func (s *STTRouterSuite) TestASessionLogsOneLineWhoseItWasWhatServedItAndWhatItCost() { + s.onFakeClock(func() { + provider := &quietSTT{emitter: stt.NewEmitter(64)} + config := timingConfig("deepgram", "flux-general-en") + config.Region, config.BYOK = "eu", true + session, logs := s.timedSession(provider, config, nil) + + time.Sleep(100 * time.Millisecond) + s.speak(session, 50) + time.Sleep(300 * time.Millisecond) + provider.emitter.Send(stt.Transcript{Text: "hello th", Mode: stt.ModeReplacement}) + synctest.Wait() + time.Sleep(time.Second) + provider.emitter.Send(stt.Transcript{Text: "hello there", Mode: stt.ModeFinal, AudioDurationMs: 600}) + s.speak(session, 25) + provider.emitter.Send(stt.Transcript{Text: "how are you", Mode: stt.ModeFinal, AudioDurationMs: 400}) + s.ended(session) + + lines := s.transcriptionLines(logs) + s.Require().Len(lines, 1, "one line for the session, not one per frame or per turn") + line := lines[0] + s.Equal("acme", line["app_id"], "named under the field the request lines use, so it filters by app") + s.Equal("concierge", line["agent_id"]) + s.Equal("deepgram", line["provider"]) + s.Equal("flux-general-en", line["model"]) + s.Equal("eu", line["region"]) + s.Equal(true, line["byok"]) + s.EqualValues(1500, line["audio_ms"], "every frame the provider took") + s.EqualValues(300, line["ttfb_ms"], "from its first audio to its first transcript, interim included") + s.EqualValues(1400, line["duration_ms"], "from the session's start to its end") + s.EqualValues(1000, line["cost_micros"], "the two turns the vendor billed, 1000 ms of audio") + s.Equal(true, line["success"]) + s.Equal("", line["error_code"]) + s.NotContains(line, "error") + logs.mu.Lock() + defer logs.mu.Unlock() + s.NotContains(logs.logs.String(), "hello there", "what was said is never logged") + }) +} + +func (s *STTRouterSuite) TestATranscriptWithNoAudioUnderItIsNoTimeToFirstByte() { + provider := &quietSTT{emitter: stt.NewEmitter(64)} + session, logs := s.timedSession(provider, timingConfig("deepgram", "flux-general-en"), nil) + + provider.emitter.Send(stt.Transcript{Text: "", Mode: stt.ModeReplacement}) + s.ended(session) + + lines := s.transcriptionLines(logs) + s.Require().Len(lines, 1) + s.EqualValues(0, lines[0]["audio_ms"]) + s.NotContains(lines[0], "ttfb_ms") +} + +func (s *STTRouterSuite) TestTheFirstFatalErrorIsWhatEndedTheSession() { + provider := &quietSTT{emitter: stt.NewEmitter(64)} + session, logs := s.timedSession(provider, timingConfig("deepgram", "flux-general-en"), nil) + + provider.emitter.Send(stt.Error{Context: "read", Err: errors.New("a hiccup the vendor recovered from")}) + provider.emitter.Send(stt.Error{Fatal: true, Context: "connect", Err: errors.New("account suspended")}) + provider.emitter.Send(stt.Error{Fatal: true, Context: "write", Err: errors.New("websocket: close sent")}) + s.ended(session) + + lines := s.transcriptionLines(logs) + s.Require().Len(lines, 1) + s.Equal(false, lines[0]["success"]) + s.Equal("provider_fatal", lines[0]["error_code"]) + s.Equal("account suspended", lines[0]["error"]) +} + +func (s *STTRouterSuite) TestAnErrorTheVendorRecoveredFromLeavesTheSessionServed() { + provider := &quietSTT{emitter: stt.NewEmitter(64)} + session, logs := s.timedSession(provider, timingConfig("deepgram", "flux-general-en"), nil) + + provider.emitter.Send(stt.Error{Context: "read", Err: errors.New("a hiccup the vendor recovered from")}) + s.ended(session) + + lines := s.transcriptionLines(logs) + s.Require().Len(lines, 1) + s.Equal(true, lines[0]["success"]) + s.Equal("", lines[0]["error_code"]) + s.NotContains(lines[0], "error") +} + +func (s *STTRouterSuite) TestASessionNothingWasTranscribedInHasNoTimeToFirstByte() { + provider := &quietSTT{emitter: stt.NewEmitter(64)} + session, logs := s.timedSession(provider, timingConfig("deepgram", "flux-general-en"), nil) + + provider.emitter.Send(stt.Connected{At: time.Now()}) + s.speak(session, 10) + s.ended(session) + + lines := s.transcriptionLines(logs) + s.Require().Len(lines, 1) + s.EqualValues(200, lines[0]["audio_ms"]) + s.NotContains(lines[0], "ttfb_ms", "no transcript answered the audio") + s.NotContains(lines[0], "region") + s.NotContains(lines[0], "byok") +} + +func (s *STTRouterSuite) TestATranscriptReadBeforeAnyAudioIsNoTimeToFirstByte() { + provider := &quietSTT{emitter: stt.NewEmitter(64)} + session, logs := s.timedSession(provider, timingConfig("deepgram", "flux-general-en"), nil) + + provider.emitter.Send(stt.Transcript{Text: "", Mode: stt.ModeReplacement}) + s.awaitEvent(session, func(event stt.Event) bool { _, ok := event.(stt.Transcript); return ok }) + s.speak(session, 10) + s.ended(session) + + lines := s.transcriptionLines(logs) + s.Require().Len(lines, 1) + s.NotContains(lines[0], "ttfb_ms") +} + +func (s *STTRouterSuite) TestARouterMeteredSessionLogsWhatTheRouterBilledAtItsEnd() { + provider := &meteredSTT{quietSTT: quietSTT{emitter: stt.NewEmitter(64)}} + session, logs := s.timedSession(provider, timingConfig("deepgram", "flux-general-en"), nil) + + s.speak(session, 75) + s.ended(session) + + lines := s.transcriptionLines(logs) + s.Require().Len(lines, 1) + s.EqualValues(1500, lines[0]["cost_micros"], "every second the vendor heard, billed when the session ended") +} + +func (s *STTRouterSuite) TestAFailedOverSessionLogsALinePerProviderThatServedIt() { + s.onFakeClock(func() { + refusing := &quietSTT{emitter: stt.NewEmitter(64)} + next := &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, 10) + time.Sleep(200 * time.Millisecond) + refusing.emitter.Send(stt.Transcript{Text: "hello", Mode: stt.ModeFinal, AudioDurationMs: 200}) + refusing.emitter.Send(stt.Error{Fatal: true, Context: "connect", + Err: errors.New("account suspended, api_key=sk-live-0123456789abcdef")}) + s.Require().True(s.awaitEvent(session, func(event stt.Event) bool { _, ok := event.(stt.Failover); return ok })) + s.speak(session, 40) + time.Sleep(500 * time.Millisecond) + next.emitter.Send(stt.Transcript{Text: "there", Mode: stt.ModeFinal, AudioDurationMs: 800}) + s.ended(session) + + lines := s.transcriptionLines(logs) + s.Require().Len(lines, 2, "the refused provider's line, then the one that took over") + refused, served := lines[0], lines[1] + s.Equal("deepgram", refused["provider"]) + s.Equal("flux-general-en", refused["model"]) + s.EqualValues(200, refused["audio_ms"]) + s.EqualValues(200, refused["ttfb_ms"]) + s.EqualValues(200, refused["duration_ms"], "until it refused") + s.EqualValues(200, refused["cost_micros"], "its turn, and not the next provider's") + s.Equal(false, refused["success"]) + s.Equal("provider_fatal", refused["error_code"]) + s.Contains(refused["error"], "account suspended") + s.NotContains(refused["error"], "0123456789abcdef", "the key the vendor echoed is redacted") + + s.Equal("acme", served["app_id"]) + s.Equal("assemblyai", served["provider"]) + s.Equal("universal-streaming", served["model"]) + s.EqualValues(800, served["audio_ms"], "only the audio it took") + s.EqualValues(500, served["ttfb_ms"]) + s.EqualValues(500, served["duration_ms"], "from when it took over") + s.EqualValues(800, served["cost_micros"]) + s.Equal(true, served["success"]) + s.Equal("", served["error_code"]) + s.NotContains(served, "error") + }) +} + +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") +} + +func (s *STTRouterSuite) TestAFrameInFlightToARefusedProviderIsNotBilledToTheNext() { + refusing := &meteredSTT{quietSTT: quietSTT{emitter: stt.NewEmitter(64)}, held: make(chan struct{}), entered: make(chan struct{}, 1)} + 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) + + sent := make(chan error, 1) + go func() { + sent <- session.ProcessAudio(stt.PcmData{Samples: make([]int16, 16000), SampleRate: 16000, Channels: 1}, stt.Participant{}) + }() + <-refusing.entered + 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 })) + close(refusing.held) + s.Require().NoError(<-sent) + s.speak(session, 25) + s.ended(session) + + lines := s.transcriptionLines(logs) + s.Require().Len(lines, 2) + s.Equal("assemblyai", lines[1]["provider"]) + s.EqualValues(500, lines[1]["cost_micros"], "the refused provider's second, billed late, is not the next one's") +} + +// meteredSTT is a transcriber whose vendor bills every second of audio it hears, which the +// router measures. held, when set, keeps a frame on its way to it until it is closed. +type meteredSTT struct { + quietSTT + held chan struct{} + entered chan struct{} +} + +func (m *meteredSTT) Metering() stt.Metering { return stt.MeteredByRouter } + +func (m *meteredSTT) ProcessAudio(stt.PcmData, stt.Participant) error { + if m.held != nil { + m.entered <- struct{}{} + <-m.held + } + return nil +} diff --git a/acceleration/internal/ttsrouter/session.go b/acceleration/internal/ttsrouter/session.go index 4da7e0a168..8ec8037b06 100644 --- a/acceleration/internal/ttsrouter/session.go +++ b/acceleration/internal/ttsrouter/session.go @@ -9,6 +9,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/tts" "github.com/google/uuid" ) @@ -66,6 +67,9 @@ type pending struct { // so its final text ends it. A streaming voice completes once for the utterance and speaks // text sent after the final text in it, so only a barge-in ends it before it settles. ended bool + // abandoned is set once it has the timing line of a sentence that ended with no + // completion, so it never has a second. + abandoned bool } // utterance is what the session remembers about one synthesis until it completes. @@ -76,6 +80,11 @@ type utterance struct { // errorCode is set when the provider reported a failure for this synthesis. It turns // the completion into a failed row rather than adding a second one. errorCode string + // errorMessage is what that failure said, for the synthesis's timing line. + errorMessage string + // firstByteAt is when its first audio reached the session, for the timing line of a + // synthesis that never completes. Zero until then. + firstByteAt time.Time } func newSession( @@ -186,12 +195,16 @@ func (s *Session) forget(id string, refused *pending) { func (s *Session) Interrupt() error { streaming := s.provider.Streaming() var dropped []uuid.UUID + var cut []abandonment s.mu.Lock() for id, queue := range s.sentences { var kept []*pending - for _, sentence := range queue { + for i, sentence := range queue { if !streaming && !sentence.ended { dropped = append(dropped, sentence.reserved) + if abandoned, ok := s.abandon(id, sentence, i == 0); ok { + cut = append(cut, abandoned) + } continue } sentence.ended = true @@ -207,6 +220,9 @@ func (s *Session) Interrupt() error { for _, reserved := range dropped { s.recorder.Release(reserved) } + for _, abandoned := range cut { + s.logAbandoned(abandoned, "interrupted") + } return s.provider.Interrupt() } @@ -271,6 +287,9 @@ func (s *Session) Close() error { func (s *Session) forward() { defer close(s.forwarded) defer close(s.events) + // Once the voice's events end, because the session was closed or the voice ended them on + // its own, a sentence it has not completed never will be. + defer s.abandonUnsettled() for event := range s.provider.Events() { s.observe(event) @@ -296,6 +315,13 @@ func (s *Session) observe(event tts.Event) { s.inFlight[typed.SynthesisID] = &utterance{startedAt: typed.At} s.mu.Unlock() + case tts.AudioChunk: + s.mu.Lock() + if current := s.inFlight[typed.SynthesisID]; current != nil && current.firstByteAt.IsZero() { + current.firstByteAt = time.Now() + } + s.mu.Unlock() + case tts.SynthesisComplete: // One utterance is one unit of billable work, the way one turn is for // speech-to-text. An interrupted one still produced audio and still cost money. @@ -310,7 +336,7 @@ func (s *Session) observe(event tts.Event) { s.warnMiscounted(typed.Characters, characters) } } - s.recorder.Record(s.config, routing.Stat{ + stat := routing.Stat{ Owner: s.owner, UsageID: settled.reserved, StartedAt: settled.startedAt, @@ -326,25 +352,132 @@ func (s *Session) observe(event tts.Event) { LatencyMs: typed.TimeToFirstByteMs, Success: settled.errorCode == "", ErrorCode: settled.errorCode, - }) + } + s.recorder.Record(s.config, stat) + s.logTiming(stat, settled.errorMessage) case tts.Error: // A failure that names an utterance is settled by that utterance's completion, so // one synthesis is still one row. Anything else is a session-level failure. - if typed.SynthesisID != "" && s.fail(typed.SynthesisID, errorCode(typed)) { + message := errorMessage(typed) + if typed.SynthesisID != "" && s.fail(typed.SynthesisID, errorCode(typed), message) { return } - s.recorder.Record(s.config, routing.Stat{ + stat := routing.Stat{ Owner: s.owner, StartedAt: time.Now().UTC(), Success: false, ErrorCode: errorCode(typed), - }) + } + s.recorder.Record(s.config, stat) + s.logTiming(stat, message) + } +} + +// logTiming writes the "speech synthesis timing" line for a row just recorded: a synthesis, +// or a failure of the session that no synthesis settles. A failover is a session of its own, +// so each voice asked has its own line. A failure of the session has no synthesis, so no +// operation and nothing timed: those fields are left out rather than logged as zero. +func (s *Session) logTiming(stat routing.Stat, message string) { + logged := routing.LoggedCall(s.owner.CallID, s.owner, s.config) + synthesis := stat.OperationID != "" + if synthesis { + logged = append(logged, "operation", stat.OperationID) + } + logged = append(logged, "characters", stat.Characters, "audio_ms", stat.AudioMs) + if synthesis { + logged = append(logged, "ttfb_ms", stat.LatencyMs, "duration_ms", stat.DurationMs) + } + logged = append(logged, "cost_micros", s.recorder.QuoteStat(s.config, stat).CostMicros, + "success", stat.Success, "error_code", stat.ErrorCode) + if message != "" { + logged = append(logged, "error", store.SafeLogText(message)) + } + s.logger.Info("speech synthesis timing", logged...) +} + +// abandonment is a sentence sent that ended with no completion, so with no row, as its +// timing line tells it. +type abandonment struct { + id string + characters int64 + // utterance is what the voice reported of it; started is false when it never started. + utterance utterance + started bool +} + +// abandon is the timing line of a sentence of id that ends with no completion, once: ok is +// false when it already has one. first is whether it is id's oldest sentence, which a start +// and a failure of id belong to, as they do when one settles. The caller holds mu. +func (s *Session) abandon(id string, sentence *pending, first bool) (abandonment, bool) { + if sentence.abandoned { + return abandonment{}, false + } + sentence.abandoned = true + abandoned := abandonment{id: id, characters: sentence.characters} + if current, ok := s.inFlight[id]; ok && first { + abandoned.utterance, abandoned.started = *current, true + } + return abandoned, true +} + +// abandonUnsettled logs every sentence the voice had not completed when its events ended, +// with the code the voice reported for it, or "closed" when it reported none. +// Their reservations are let go at Close, as before. +func (s *Session) abandonUnsettled() { + var left []abandonment + s.mu.Lock() + for id, queue := range s.sentences { + for i, sentence := range queue { + if abandoned, ok := s.abandon(id, sentence, i == 0); ok { + left = append(left, abandoned) + } + } + } + s.mu.Unlock() + for _, abandoned := range left { + // The code the voice reported for it, when it did, is what its row would say. + code := "closed" + if reported := abandoned.utterance.errorCode; reported != "" { + code = reported + } + s.logAbandoned(abandoned, code) + } +} + +// logAbandoned writes the timing line of a sentence that ended with no completion, failed +// with code. What was not measured is left out: the audio, a time to first byte when none +// arrived, a duration when it never started. No row is written for it, so it has no +// cost_micros either; what was reserved for it is let go. +func (s *Session) logAbandoned(abandoned abandonment, code string) { + logged := append(routing.LoggedCall(s.owner.CallID, s.owner, s.config), + "operation", abandoned.id, "characters", abandoned.characters) + if started := abandoned.utterance.startedAt; abandoned.started { + if first := abandoned.utterance.firstByteAt; !first.IsZero() { + logged = append(logged, "ttfb_ms", milliseconds(first.Sub(started))) + } + logged = append(logged, "duration_ms", milliseconds(time.Since(started))) + } + logged = append(logged, "success", false, "error_code", code) + if message := abandoned.utterance.errorMessage; message != "" { + logged = append(logged, "error", store.SafeLogText(message)) + } + s.logger.Info("speech synthesis timing", logged...) +} + +func milliseconds(elapsed time.Duration) float64 { return float64(elapsed.Microseconds()) / 1000 } + +// errorMessage is what a provider's failure said. An adapter may report one with no error +// under it, which says nothing. +func errorMessage(failure tts.Error) string { + if failure.Err == nil { + return "" } + return failure.Err.Error() } // fail marks an utterance as failed, reporting whether it was still in flight. -func (s *Session) fail(synthesisID, code string) bool { +func (s *Session) fail(synthesisID, code, message string) bool { s.mu.Lock() defer s.mu.Unlock() @@ -354,7 +487,7 @@ func (s *Session) fail(synthesisID, code string) bool { } // The first failure is the one that explains the utterance. if current.errorCode == "" { - current.errorCode = code + current.errorCode, current.errorMessage = code, message } return true } @@ -407,7 +540,7 @@ func (s *Session) settle(synthesisID string) (settled, bool) { } delete(s.inFlight, synthesisID) return settled{ - utterance: utterance{startedAt: current.startedAt.UTC(), errorCode: current.errorCode}, + utterance: utterance{startedAt: current.startedAt.UTC(), errorCode: current.errorCode, errorMessage: current.errorMessage}, characters: characters, sent: sent, reserved: reserved, diff --git a/acceleration/internal/ttsrouter/timing_test.go b/acceleration/internal/ttsrouter/timing_test.go new file mode 100644 index 0000000000..6cf3c4c459 --- /dev/null +++ b/acceleration/internal/ttsrouter/timing_test.go @@ -0,0 +1,386 @@ +package ttsrouter + +import ( + "bytes" + "encoding/json" + "errors" + "log/slog" + "strings" + "testing" + "testing/synctest" + "time" + + "github.com/GetStream/Vision-Agents/acceleration/internal/routing" + "github.com/GetStream/Vision-Agents/acceleration/internal/tts" +) + +// timedSession is a session over a stub provider whose log lines are kept, owned the way an +// agent's voice in a call is. +func (s *TTSRouterSuite) timedSession(region string, byok bool) (*Session, *stubTTS, *bytes.Buffer) { + provider := newStubTTS() + session, logs := s.timedVoice(provider, region, byok) + return session, provider, logs +} + +// timedVoice is timedSession over a provider of the test's own. +func (s *TTSRouterSuite) timedVoice(provider *stubTTS, region string, byok bool) (*Session, *bytes.Buffer) { + config := routing.ProviderConfig{ + Provider: "stub", + Model: "stub-model", + Region: region, + BYOK: byok, + Price: routing.Price{PerMillionChars: 50}, + } + prices, err := routing.Prices(routing.Config{routing.TTS: {Providers: []routing.ProviderConfig{config}}}, slog.Default()) + s.Require().NoError(err) + recorder := routing.NewRecorder(routing.TTS, nil, nil, prices, slog.Default()) + var logs bytes.Buffer + owner := routing.Owner{CustomerID: "acme", AgentID: "concierge", CallID: "default:lobby"} + session := newSession(provider, config, owner, recorder, slog.New(slog.NewJSONHandler(&logs, nil))) + s.T().Cleanup(func() { + _ = session.Close() + recorder.Close() + }) + return session, &logs +} + +// onFakeClock runs body in a synctest bubble, where time moves only as the test sleeps, so +// the times a line logs are exact. +func (s *TTSRouterSuite) onFakeClock(body func()) { + outer := s.T() + synctest.Test(outer, func(t *testing.T) { + s.SetT(t) + defer s.SetT(outer) + body() + }) +} + +// byOperation is the lines keyed by the synthesis each is about, failing on a second line +// for one. +func (s *TTSRouterSuite) byOperation(lines []map[string]any) map[string]map[string]any { + keyed := map[string]map[string]any{} + for _, line := range lines { + operation, _ := line["operation"].(string) + s.Require().NotContains(keyed, operation, "one line per synthesis") + keyed[operation] = line + } + return keyed +} + +// settled closes the session and waits until every event the provider sent was observed. +func (s *TTSRouterSuite) settled(session *Session) { + s.Require().NoError(session.Close()) + s.drain(session) +} + +// synthesisLines are the "speech synthesis timing" lines among those logged, decoded. +func (s *TTSRouterSuite) synthesisLines(logs *bytes.Buffer) []map[string]any { + var found []map[string]any + for decoder := json.NewDecoder(logs); decoder.More(); { + var line map[string]any + s.Require().NoError(decoder.Decode(&line)) + if line["msg"] == "speech synthesis timing" { + found = append(found, line) + } + } + return found +} + +func (s *TTSRouterSuite) TestASynthesisLogsWhoseItWasWhatServedItAndWhatItCost() { + session, provider, logs := s.timedSession("eu", true) + s.Require().NoError(session.Synthesize(tts.Request{ID: "u1", Text: "twenty characters ok", Final: true})) + provider.emitter.Send(tts.SynthesisStarted{SynthesisID: "u1", At: time.Now().Add(-40 * time.Millisecond)}) + provider.emitter.Send(tts.SynthesisComplete{SynthesisID: "u1", Characters: 20, AudioDurationMs: 1500, TimeToFirstByteMs: 120}) + s.settled(session) + + lines := s.synthesisLines(logs) + s.Require().Len(lines, 1, "one line for one synthesis") + line := lines[0] + s.Equal("default:lobby", line["call"]) + s.Equal("acme", line["app_id"], "named under the field the request lines use, so it filters by app") + s.Equal("concierge", line["agent_id"]) + s.Equal("stub", line["provider"]) + s.Equal("stub-model", line["model"]) + s.Equal("eu", line["region"]) + s.Equal(true, line["byok"]) + s.Equal("u1", line["operation"]) + s.EqualValues(20, line["characters"]) + s.EqualValues(1500, line["audio_ms"]) + s.EqualValues(120, line["ttfb_ms"]) + s.GreaterOrEqual(line["duration_ms"], 40.0, "from when the provider took it") + s.EqualValues(1000, line["cost_micros"], "20 characters at 50 per million characters") + s.Equal(true, line["success"]) + s.Equal("", line["error_code"]) + s.NotContains(line, "error", "a served synthesis says nothing went wrong") + s.NotContains(logs.String(), "twenty characters ok", "the text spoken is never logged") +} + +func (s *TTSRouterSuite) TestASynthesisWithNoRegionOrOwnKeyLeavesThemOut() { + session, provider, logs := s.timedSession("", false) + provider.emitter.Send(tts.SynthesisStarted{SynthesisID: "u1", At: time.Now()}) + provider.emitter.Send(tts.SynthesisComplete{SynthesisID: "u1", Characters: 5}) + s.settled(session) + + lines := s.synthesisLines(logs) + s.Require().Len(lines, 1) + s.NotContains(lines[0], "region") + s.NotContains(lines[0], "byok") +} + +func (s *TTSRouterSuite) TestAFailedSynthesisLogsWhatItsProviderSaidWithoutItsSecrets() { + session, provider, logs := s.timedSession("", false) + provider.emitter.Send(tts.SynthesisStarted{SynthesisID: "u1", At: time.Now()}) + provider.emitter.Send(tts.Error{SynthesisID: "u1", Fatal: true, Context: "read", + Err: errors.New("voice refused the request, api_key=sk-live-0123456789abcdef")}) + provider.emitter.Send(tts.Error{SynthesisID: "u1", Context: "write", Err: errors.New("a later failure")}) + provider.emitter.Send(tts.SynthesisComplete{SynthesisID: "u1", Characters: 5}) + s.settled(session) + + lines := s.synthesisLines(logs) + s.Require().Len(lines, 1, "the failure is settled by its synthesis, as its row is") + line := lines[0] + s.Equal("u1", line["operation"]) + s.Equal(false, line["success"]) + s.Equal("provider_fatal", line["error_code"]) + s.Contains(line["error"], "voice refused the request", "the first failure explains the synthesis") + s.NotContains(line["error"], "0123456789abcdef", "the key the provider echoed is redacted") +} + +func (s *TTSRouterSuite) TestAFailureNoSynthesisSettlesIsLoggedOnItsOwn() { + session, provider, logs := s.timedSession("", false) + provider.emitter.Send(tts.Error{SynthesisID: "never-started", Context: "connect", Err: errors.New("voice unreachable")}) + s.settled(session) + + lines := s.synthesisLines(logs) + s.Require().Len(lines, 1) + s.Equal("acme", lines[0]["app_id"]) + s.Equal(false, lines[0]["success"]) + s.Equal("connect", lines[0]["error_code"]) + s.Equal("voice unreachable", lines[0]["error"]) + for _, unknown := range []string{"operation", "ttfb_ms", "duration_ms"} { + s.NotContains(lines[0], unknown, "no synthesis was timed, so a percentile over the lines counts no zero") + } + s.EqualValues(0, lines[0]["characters"]) + s.EqualValues(0, lines[0]["cost_micros"]) +} + +func (s *TTSRouterSuite) TestAFailureWithNoErrorUnderItIsLoggedWithoutOne() { + session, provider, logs := s.timedSession("", false) + provider.emitter.Send(tts.Error{Fatal: true}) + s.settled(session) + + lines := s.synthesisLines(logs) + s.Require().Len(lines, 1) + s.Equal("provider_fatal", lines[0]["error_code"]) + s.NotContains(lines[0], "error") +} + +func (s *TTSRouterSuite) TestARepeatedCompletionLogsItsSynthesisOnce() { + session, provider, logs := s.timedSession("", false) + for _, id := range []string{"u1", "u2"} { + provider.emitter.Send(tts.SynthesisStarted{SynthesisID: id, At: time.Now()}) + provider.emitter.Send(tts.SynthesisComplete{SynthesisID: id, Characters: 5}) + } + provider.emitter.Send(tts.SynthesisComplete{SynthesisID: "u1", Characters: 5}) + s.settled(session) + + var operations []string + for _, line := range s.synthesisLines(logs) { + operations = append(operations, line["operation"].(string)) + } + s.Equal("u1,u2", strings.Join(operations, ","), "a line per synthesis, and none for the repeat") +} + +func (s *TTSRouterSuite) TestASynthesisTheSessionClosedOnLogsALineWithNoCost() { + s.onFakeClock(func() { + session, provider, logs := s.timedSession("", false) + s.Require().NoError(session.Synthesize(tts.Request{ID: "heard", Text: "hello there", Final: true})) + s.Require().NoError(session.Synthesize(tts.Request{ID: "silent", Text: "four", Final: true})) + s.Require().NoError(session.Synthesize(tts.Request{ID: "queued", Text: "never begun", Final: true})) + provider.emitter.Send(tts.SynthesisStarted{SynthesisID: "heard", At: time.Now()}) + provider.emitter.Send(tts.SynthesisStarted{SynthesisID: "silent", At: time.Now()}) + provider.emitter.Send(tts.Error{SynthesisID: "silent", Context: "read", + Err: errors.New("voice stalled, api_key=sk-live-0123456789abcdef")}) + time.Sleep(120 * time.Millisecond) + provider.emitter.Send(tts.AudioChunk{SynthesisID: "heard", Index: 0}) + time.Sleep(200 * time.Millisecond) + provider.emitter.Send(tts.AudioChunk{SynthesisID: "heard", Index: 1}) + time.Sleep(30 * time.Millisecond) + s.settled(session) + + lines := s.byOperation(s.synthesisLines(logs)) + s.Require().Len(lines, 3, "a line for each synthesis the voice never completed") + for operation, line := range lines { + s.Equal("acme", line["app_id"], operation) + s.Equal(false, line["success"], operation) + if operation == "silent" { + s.Equal("read", line["error_code"], "the code the voice reported for it") + } else { + s.Equal("closed", line["error_code"], operation) + } + s.NotContains(line, "cost_micros", "%s wrote no row, so it has no cost", operation) + s.NotContains(line, "audio_ms", "%s: the audio of a synthesis that never completed is not counted", operation) + } + heard := lines["heard"] + s.EqualValues(11, heard["characters"]) + s.EqualValues(120, heard["ttfb_ms"], "until its first audio, not its last") + s.EqualValues(350, heard["duration_ms"], "from its start until the session closed") + s.NotContains(heard, "error") + + silent := lines["silent"] + s.EqualValues(4, silent["characters"]) + s.NotContains(silent, "ttfb_ms", "no audio of it arrived") + s.EqualValues(350, silent["duration_ms"]) + s.Contains(silent["error"], "voice stalled", "what the voice said of it") + s.NotContains(silent["error"], "0123456789abcdef", "the key the provider echoed is redacted") + + queued := lines["queued"] + s.EqualValues(11, queued["characters"]) + s.NotContains(queued, "ttfb_ms") + s.NotContains(queued, "duration_ms", "it never started") + }) +} + +func (s *TTSRouterSuite) TestASynthesisWhoseVoiceEndedOnItsOwnLogsALine() { + session, provider, logs := s.timedSession("", false) + s.Require().NoError(session.Synthesize(tts.Request{ID: "u1", Text: "cut off", Final: true})) + provider.emitter.Send(tts.SynthesisStarted{SynthesisID: "u1", At: time.Now()}) + provider.emitter.Close() + s.drain(session) + + lines := s.synthesisLines(logs) + s.Require().Len(lines, 1, "logged once the voice's events ended, before the session closed") + s.Equal("u1", lines[0]["operation"]) + s.Equal("closed", lines[0]["error_code"]) + s.EqualValues(7, lines[0]["characters"]) +} + +func (s *TTSRouterSuite) TestASentenceABargeInDropsLogsALine() { + session, logs := s.timedVoice(&stubTTS{emitter: tts.NewEmitter(64), perSentence: true}, "", false) + s.Require().NoError(session.Synthesize(tts.Request{ID: "u1", Text: "half a sentence"})) + s.Require().NoError(session.Synthesize(tts.Request{ID: "u2", Text: "said", Final: true})) + s.Require().NoError(session.Interrupt()) + s.settled(session) + + lines := s.byOperation(s.synthesisLines(logs)) + s.Require().Len(lines, 2) + dropped := lines["u1"] + s.Equal(false, dropped["success"]) + s.Equal("interrupted", dropped["error_code"], "the barge-in dropped it, not the close after") + s.EqualValues(15, dropped["characters"]) + s.NotContains(dropped, "cost_micros") + s.Equal("closed", lines["u2"]["error_code"], "its final text was sent, so the voice still owed its completion") +} + +func (s *TTSRouterSuite) TestASentenceLoggedWhenTheVoiceEndedIsNotLoggedAgainByABargeIn() { + provider := &stubTTS{emitter: tts.NewEmitter(64), perSentence: true} + session, logs := s.timedVoice(provider, "", false) + s.Require().NoError(session.Synthesize(tts.Request{ID: "u1", Text: "half a sentence"})) + provider.emitter.Close() + s.drain(session) + s.Require().NoError(session.Interrupt()) + s.settled(session) + + lines := s.synthesisLines(logs) + s.Require().Len(lines, 1, "one line for one synthesis") + s.Equal("closed", lines[0]["error_code"]) +} + +func (s *TTSRouterSuite) TestEachSentenceOfAnIdTheVoiceNeverCompletedHasItsOwnLine() { + s.onFakeClock(func() { + session, provider, logs := s.timedSession("", false) + s.Require().NoError(session.Synthesize(tts.Request{ID: "u1", Text: "first"})) + provider.emitter.Send(tts.SynthesisStarted{SynthesisID: "u1", At: time.Now()}) + time.Sleep(20 * time.Millisecond) + s.Require().NoError(session.Interrupt()) + s.Require().NoError(session.Synthesize(tts.Request{ID: "u1", Text: "second part"})) + time.Sleep(30 * time.Millisecond) + s.settled(session) + + lines := s.synthesisLines(logs) + s.Require().Len(lines, 2, "a line for each sentence, as each would have had a row") + characters := map[float64]map[string]any{} + for _, line := range lines { + characters[line["characters"].(float64)] = line + } + s.Require().Contains(characters, 5.0) + s.Require().Contains(characters, 11.0) + s.EqualValues(50, characters[5]["duration_ms"], "the start belongs to the oldest sentence, as its row would") + s.NotContains(characters[11], "duration_ms", "the voice never said it started the second") + }) +} + +func (s *TTSRouterSuite) TestACompletedSynthesisIsNotLoggedAgainAtClose() { + session, provider, logs := s.timedSession("", false) + s.Require().NoError(session.Synthesize(tts.Request{ID: "u1", Text: "done", Final: true})) + provider.emitter.Send(tts.SynthesisStarted{SynthesisID: "u1", At: time.Now()}) + provider.emitter.Send(tts.AudioChunk{SynthesisID: "u1"}) + provider.emitter.Send(tts.SynthesisComplete{SynthesisID: "u1", Characters: 4, TimeToFirstByteMs: 80}) + s.settled(session) + + lines := s.synthesisLines(logs) + s.Require().Len(lines, 1, "its row's line, and none at close") + s.Equal(true, lines[0]["success"]) + s.EqualValues(80, lines[0]["ttfb_ms"], "a completed synthesis logs the time to first byte its voice reported") +} + +func (s *TTSRouterSuite) TestASynthesisAFatalErrorEndedLogsTheCodeTheVoiceReported() { + session, provider, logs := s.timedSession("", false) + s.Require().NoError(session.Synthesize(tts.Request{ID: "u1", Text: "hello", Final: true})) + s.Require().NoError(session.Synthesize(tts.Request{ID: "u2", Text: "hung up", Final: true})) + provider.emitter.Send(tts.SynthesisStarted{SynthesisID: "u1", At: time.Now()}) + provider.emitter.Send(tts.Error{SynthesisID: "u1", Fatal: true, Err: errors.New("socket reset")}) + provider.emitter.Send(tts.SynthesisStarted{SynthesisID: "u2", At: time.Now()}) + provider.emitter.Close() + s.drain(session) + + lines := s.byOperation(s.synthesisLines(logs)) + s.Require().Len(lines, 2) + s.Equal("provider_fatal", lines["u1"]["error_code"], "what the row would say") + s.Equal("socket reset", lines["u1"]["error"]) + s.Equal("closed", lines["u2"]["error_code"], "a hang-up mid-sentence reported nothing") +} + +func (s *TTSRouterSuite) TestRowInterruptedLineCarriesItsStart() { + s.onFakeClock(func() { + provider := &stubTTS{emitter: tts.NewEmitter(64), perSentence: true} + session, logs := s.timedVoice(provider, "", false) + s.Require().NoError(session.Synthesize(tts.Request{ID: "u1", Text: "half"})) + provider.emitter.Send(tts.SynthesisStarted{SynthesisID: "u1", At: time.Now()}) + time.Sleep(5 * time.Millisecond) + provider.emitter.Send(tts.AudioChunk{SynthesisID: "u1"}) + time.Sleep(15 * time.Millisecond) + s.Require().NoError(session.Interrupt()) + s.settled(session) + lines := s.synthesisLines(logs) + s.Require().Len(lines, 1) + s.Equal("interrupted", lines[0]["error_code"]) + s.EqualValues(5, lines[0]["ttfb_ms"]) + s.EqualValues(20, lines[0]["duration_ms"]) + }) +} + +func (s *TTSRouterSuite) TestRowInterruptedSecondSentenceDoesNotCarryTheFirstsStart() { + s.onFakeClock(func() { + provider := &stubTTS{emitter: tts.NewEmitter(64), perSentence: true} + session, logs := s.timedVoice(provider, "", false) + s.Require().NoError(session.Synthesize(tts.Request{ID: "u1", Text: "first", Final: true})) + provider.emitter.Send(tts.SynthesisStarted{SynthesisID: "u1", At: time.Now()}) + s.Require().NoError(session.Interrupt()) // first is kept: its completion is owed + s.Require().NoError(session.Synthesize(tts.Request{ID: "u1", Text: "more"})) + time.Sleep(20 * time.Millisecond) + s.Require().NoError(session.Interrupt()) // second dropped + s.settled(session) + lines := s.synthesisLines(logs) + s.Require().Len(lines, 2) + var interrupted []map[string]any + for _, l := range lines { + if l["error_code"] == "interrupted" { + interrupted = append(interrupted, l) + } + } + s.Require().Len(interrupted, 1, "the second sentence's drop is the one interrupted line") + s.EqualValues(4, interrupted[0]["characters"]) + s.NotContains(interrupted[0], "duration_ms", "the second sentence never started") + }) +}