Repository navigation
[AI-3416] Log speech synthesis and transcription timing - #2212
Conversation
Speech-to-text and text-to-speech work left no per-call log line, so the logs could not say which provider served a voice session, what it cost or why it failed. Each synthesis now writes "speech synthesis timing" and each provider's part of a transcription session writes "speech transcription timing", both opening with the owner fields of "model call timing" (routing.LoggedCall), whose output is unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
kanat
left a comment
There was a problem hiding this comment.
Reviewed 86cafa331 merged onto main 51abc6711. Draft: CI has not run yet (#2130). It runs at gh pr ready.
[Question] R1.3 ttsrouter/session.go Close: when a session closes with a synthesis still in flight (a stalled voice, which is the ticket's "voice cut out" case), no line is written, because no row is recorded. The same holds for an in-order sentence that Interrupt drops. The orchestrator decides whether such a synthesis gets a line. Ticket.
[Nit] R1.5 store.SafeLogText is an existing helper. A probe showed it leaves a URL-encoded xi-api-key%3D<hex> and Invalid API key <32 hex> in place. This PR exposes nothing new: the same text is already in the agent's agent failure log and in requests.error_message. Ticket.
Checked and sound:
cost_microsequals the stored row on a real DB (the built-in price list at cost). Router-metered STT: 284 = 284. Flux with an estimated turn: 223 = 223. Failover, per provider: 78/78 and 45/45. TTS synthesis: 615/615. TTS session error: 0/0.- The LLM line is byte-identical to base.
- Hot path:
took()adds one sum and stampsfirstAtonly the first time. A mutant that logs per frame is killed. - Exactly one line per STT segment on each path: end, failover, reopen error, swap refused, fatal error with no reopen, and close before any audio (one line,
audio_ms0, nottfb_ms). - TTS: one line per row, none for a repeated completion.
- The
go session.forward(time.Now())change only feeds the line. SafeLogTextis on both error fields (mutants killed).-race -count=50 -cpu 1passes on the sttrouter package and on the TTS timing tests. The whole ttsrouter package passes at-race -count=5.- Integration runs of sttrouter, ttsrouter, llmrouter and routing pass.
- Mutations: 19 of mine, 1 survived (R1.1).
Verdict: request changes, for R1.1 (the failover cost mutant survives).
| routing.CountHandover(routing.STT, current.config, failure.Err) | ||
| s.billUnsettled(current.provider) | ||
| s.billUnsettled(current.provider, current) | ||
| s.logTiming(current) |
There was a problem hiding this comment.
[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")
}There was a problem hiding this comment.
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).
| // 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. | ||
| func (s *Session) logTiming(stat routing.Stat, message string) { | ||
| logged := append(routing.LoggedCall(s.owner.CallID, s.owner, s.config), "operation", stat.OperationID, |
There was a problem hiding this comment.
[Nit] R1.2 A session-level failure line (no synthesis) logs operation:"", ttfb_ms:0, duration_ms:0, characters:0 and audio_ms:0 as real values. The STT line leaves out a ttfb_ms it does not know. A p50 of ttfb_ms over this msg counts those zeros. Leave the unknown fields out. Ticket.
There was a problem hiding this comment.
Fixed in 5d16565: a session-level failure line now leaves out operation, ttfb_ms and duration_ms (ttsrouter/session.go logTiming, keyed on the row having no OperationID). TestAFailureNoSynthesisSettlesIsLoggedOnItsOwn checks they are absent; it fails if either guard is removed (both mutants killed).
| 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 { |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
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."
…illed as it refused R1.1: a line logged before the swap's bill would miss that audio. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
R1.2: a session-level failure has no synthesis, so its line logged operation "", ttfb_ms 0 and duration_ms 0, which a percentile over the lines counts as zeros. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
R1.3: a sentence still in flight when the voice's events end (the session closed, its context cancelled, the voice stalled or gave up) or one a barge-in drops writes no row, so it had no line. Each now gets one "speech synthesis timing" line, once: success false, error_code "closed" or "interrupted", its characters, ttfb_ms if audio of it arrived, duration_ms if it started, and no cost_micros since no row is written. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
R1.3 (Question in the review; decided: give each such synthesis a line). Fixed in 8bd2f40 (comment wording in 49d1074): a sentence that ends with no completion gets one |
kanat
left a comment
There was a problem hiding this comment.
Delta round 2, head 49d1074 merged onto fe06e15 (main). VERDICT: NO-GO, two Should fix.
Prior findings
- R1.1 fixed. The new STT test passes; I re-ran mutant C2 (log before the bill) and it fails.
- R1.2 fixed. Mutants F1 and F2 (operation, ttfb or duration logged for a session failure) both fail the new test.
- R1.3 open: the line is once per sentence (G1-G15 and my 8 extra mutants killed, except the two below), but R2.1 and R2.2 below.
- R1.4 fixed in the PR body.
New findings
- [Should fix] R2.1, inline on session.go:455: a voice that reported a failure and then ended its events logs
error_code"closed". A probe on head with a fatal error then end givesclosedwitherror: socket reset, where its row would sayprovider_fatal. - [Should fix] R2.2, inline on session.go:205: mutants M1 and M4 of the
i == 0argument in Interrupt survive; no test reaches an interrupted line that carries a start. - [Nit] A stray completion after an Interrupt drop gives two lines (probe). Not blocking: a voice kept by InOrder never completes a non-final sentence, and base wrote the same unreserved row.
- [Nit] A sentence whose Synthesize is refused while the events end gets one line,
closed, which is true there. No change.
The new TTS tests pass -race -count=50, -cpu 1 -count=50 and both together; unit and -tags integration -p 1 suites of ttsrouter and sttrouter pass on the merge. CI: draft, go and integration skipping.
| } | ||
| logged = append(logged, "duration_ms", milliseconds(time.Since(started))) | ||
| } | ||
| logged = append(logged, "success", false, "error_code", code) |
There was a problem hiding this comment.
[Should fix] R2.1: error_code is only ever closed or interrupted here, so the code the voice reported for this sentence is lost. Probe on head: a tts.Error{Fatal: true} for u1, then the events end, logs error_code: closed with error: socket reset; the completed row would say provider_fatal. Every hang-up mid-sentence is also closed, so an operator filtering on error_code cannot find the provider failures that cut a voice out. Fix: for the closed path use abandoned.utterance.errorCode when it is set (I tried it in a scratch copy: P4 logs provider_fatal); then timing_test.go:216 expects read for the "silent" sentence, and add a fatal row.
There was a problem hiding this comment.
Fixed in b2a0ae0 (head ef3c940): the closed path now uses the code the voice reported for the sentence when it reported one. Test: TestASynthesisAFatalErrorEndedLogsTheCodeTheVoiceReported (fatal error then events end gives provider_fatal and the error text; a plain hang-up mid-sentence gives closed); timing_test.go now expects read for the "silent" sentence. Mutants "never use the reported code" and "always use it, even empty" both fail those tests.
| for i, sentence := range queue { | ||
| if !streaming && !sentence.ended { | ||
| dropped = append(dropped, sentence.reserved) | ||
| if abandoned, ok := s.abandon(id, sentence, i == 0); ok { |
There was a problem hiding this comment.
[Should fix] R2.2: surviving mutants. Replacing i == 0 here with true (M1) or false (M4) fails no test: no test has an interrupted line that carries a start. Two rows, each passing on head and failing under its mutant (written in a scratch copy, TestRowInterruptedLineCarriesItsStart and TestRowInterruptedSecondSentenceDoesNotCarryTheFirstsStart, in AI-3416/review-2/probe-tests.go.txt): (1) per-sentence stub, Synthesize u1 non-final, SynthesisStarted, 5 ms, one chunk, 15 ms, Interrupt -> one line, ttfb_ms 5, duration_ms 20, interrupted (kills M4); (2) Synthesize u1 final, SynthesisStarted, Interrupt, Synthesize u1 non-final, 20 ms, Interrupt -> the interrupted line has 4 characters and no duration_ms (kills M1). Add both to TTSRouterSuite.
…the interrupt start Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
kanat
left a comment
There was a problem hiding this comment.
Delta review, round 3 — GO (head ef3c940 merged onto current main; fix b2a0ae0 plus a clean merge of main)
Prior findings
- R2.1 fixed. The closed path now logs the code the voice reported (
session.goabandonUnsettled), elseclosed. Mutating the condition to false fails FatalErrorEnded and ClosedOn. Mutating it to true fails 5 tests. - R2.2 fixed.
i == 0 || trueat the Interrupt site fails TestRowInterruptedSecondSentenceDoesNotCarryTheFirstsStart.i == 0 && falsefails TestRowInterruptedLineCarriesItsStart. The same two mutants on the abandonUnsettled site also fail tests. No survivors. - R2.3 stays wontfix.
Interrupt keeps interrupted: right call, no finding. Interrupt drops only sentences whose final text was not sent, and only for non-streaming voices (gemini, speechify, fish). Those adapters buffer non-final text and start nothing, so no failure can be reported for such a sentence and abandon copies no code. A failure for a sentence that was sent lands on a kept sentence, whose completion line carries the code. The cause of a drop is also the operator's barge-in, not a provider failure.
Nit (not blocking): in TestRowInterruptedSecondSentenceDoesNotCarryTheFirstsStart the if error_code == "interrupted" loop asserts nothing when no line has that code. Asserting exactly one interrupted line would close it.
Suites: go test ./internal/ttsrouter -race -count=20 ok, -cpu 1 -count=50 on the order-sensitive tests ok, ./internal/routing ok. Draft: no CI runs (#2130).
Mutations: 8 checked, 0 survived.
The interrupted-code check sat in a loop, so a run with no interrupted line passed. Require exactly one interrupted line, then check its fields. Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
## Why Streaming speech-to-text and text-to-speech write one timing line per provider or synthesis (#2212). Batch work wrote none: `POST /v1/stt/recordings`, `POST /v1/tts/recordings` and an agent's voice notes (`api/recordings.go`, `api/voicenotes.go`) left a row in `requests` and nothing in the logs. Part of AI-3611 (piece 1 of 2; the speech-to-speech line is a separate PR). ## How it works ``` api/recordings.go, api/voicenotes.go -> sttrouter.Recordings.Transcribe / ttsrouter.Recordings.Record (each Walk candidate) -> routing.Call(meter{..., Recorded: logTiming}, ask) defer: ├─ meter.record(stat) row as before └─ meter.Recorded != nil ? ├─ no -> nothing (every other Call caller) └─ yes -> Recorded(stat, cost) cost = Recorder.price(config, stat), the same pricing Record writes ``` - One line per row: one per transcription, one per TTS candidate the walk asks. A candidate that fails writes its own line, then the next candidate writes its line. - `cost_micros` is the row's own `cost_micros`: `Recorder.price` is the pricing `priced` uses, without the user id check (that check counts a dropped user id per row and must not count it twice). Free work logs 0 and a quoted fee logs the resold fee. `Recorder.QuoteStat`, which the streaming lines use, would log 2,000 for the free row in the test. - The `msg` is the same as the streaming lines, and `batch=true` appears only on batch lines, so the views that type these msgs (AI-3617) cover batch too. `duration_ms` here is the request latency (`Stat.LatencyMs`). There is no `ttfb_ms`: one answer for the whole file has no first-byte point. - `call` is always present, as `routing.LoggedCall` writes it. It is empty for `/v1/stt/recordings` and `/v1/tts/recordings`, which have no call, and it is set for a voice note in a call. `agent_id` is left out when empty. ## Sample lines (fake ids) Before: no line. After, a transcription in a call: ```json {"level":"INFO","msg":"speech transcription timing","call":"default:c1","app_id":"acme","agent_id":"concierge","provider":"deepgram","model":"nova-3","batch":true,"audio_ms":1500,"duration_ms":250,"cost_micros":1500,"success":true,"error_code":""} ``` After, a recording whose first voice failed and whose second voice spoke: ```json {"level":"INFO","msg":"speech synthesis timing","call":"","app_id":"acme","provider":"elevenlabs","model":"eleven_v3","batch":true,"characters":0,"audio_ms":0,"duration_ms":120,"cost_micros":0,"success":false,"error_code":"record_failed","error":"elevenlabs: 500 for [redacted]"} {"level":"INFO","msg":"speech synthesis timing","call":"","app_id":"acme","provider":"cartesia","model":"sonic-3","batch":true,"characters":5,"audio_ms":800,"duration_ms":300,"cost_micros":150,"success":true,"error_code":""} ``` ClickHouse: no new `msg`. A typed view that lists these two msgs needs a `batch` column to separate batch from streaming. Without that column, `batch` stays in the raw JSON. That column is for the chat ticket (AI-3617), not this PR. ## Changes - `routing/call.go`: adds `Meter.Recorded`, called from `Call`'s defer after the row is recorded. It is called on success, failure and panic, and not for work that `Omit` leaves out. - `routing/stats.go`: splits `Recorder.price` out of `priced`. - `sttrouter/recordings.go` and `ttsrouter/recordings.go`: the batch lines. STT logs to `slog` default and TTS logs to the router's logger, like each modality's streaming line. ## Validation | Rule | Test | Defect it catches | | --- | --- | --- | | A batch STT line with exact fields and cost | `sttrouter` `TestATranscribedRecordingLogsOneBatchLineWithWhatItCost` | the line is missing, `batch` is dropped, `duration_ms` comes from the wrong field, the cost is 0 | | A failed STT line has its code, a redacted error and an empty `call` | `TestAFailedTranscriptionLogsItsCodeAndItsErrorWithNoCredential` | the guard is inverted, a bearer token is logged | | A batch TTS line | `ttsrouter` `TestASpokenRecordingLogsOneBatchLineWithWhatItCost` | `characters` or `audio_ms` is dropped | | Each walk candidate writes its own line | `TestEachCandidateARecordingFallsBackFromLogsItsOwnLine` | only successes are logged | | The hook gets the stat and the row cost, and is called on failure and panic but not for omitted work | `routing` `TestARecordedHook*` | the cost is 0, the hook is called for omitted work, a nil recorder panics | | The logged cost equals the stored row's cost (priced, free, quoted) | `TestCallSuite/TestARecordedHookIsToldWhatTheStoredRowCosts` (Postgres) | the cost comes from `QuoteStat`, which ignores `Free` and quoted fees | | No hook means no line | `TestACallWithNoRecordedHookLogsNothing`, `TestACallWithNoRecorderIsStillAnswered` | a nil-hook call panics or logs | - The 4 new `sttrouter`/`ttsrouter` tests fail on base 108539d (no line). All of them pass on this head. - Streaming lines are unchanged: this PR does not touch `sttrouter/session.go`, `ttsrouter/session.go` or `routing/logged.go`, and base's own `timing_test.go` in both packages passes unchanged. - 25 mutants of every changed condition, field and call site were all killed (author log). - Ran: `go test ./internal/{routing,sttrouter,ttsrouter,llmrouter,api}/`, `go test -tags integration ./internal/{routing,sttrouter,ttsrouter}/`, `go vet` (both tags) and `gofmt -l`. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
## Why `store.SafeLogText` (and `RedactLogText`) let two credential shapes through, found in the round-1 review of #2212 (R1.5) and ticketed as AI-3612: - a URL-encoded key with no `?` or `&` before it: `key%3D<hex>` (also `api_key%3D`, `token%3D`, `%3d`); - a vendor refusal that names the key with no `=` or `:`: `Invalid API key <32 hex>`, or with the key before the verdict: `The API key '<32 hex>' is invalid`. The text reaches the model/speech/tool timing lines, the agent failure log and `requests.error_message`, all through `SafeLogText`. ## How it works Three rules in `acceleration/internal/store/logs.go`, run with the other keyword rules in `redactLegacyCredentials` (so the existing `mayHoldCredential` gate already covers them: both texts hold `key` or `token`). `redactCredentials` now runs the shaped rules (JWT, Slack, GitHub...) before the keyword rules, so a keyword rule that takes only part of a shaped token (a JWT after `Invalid API token`, up to its first dot) cannot leave the rest in a shape no rule matches. | Rule | Takes out | Keeps | |---|---|---| | `encodedCredential` | the value after a name plus `%3D` (any case, once or twice encoded). `key`, `token`, `id_token` need a boundary before them: the text start, a character that is not a letter, digit or underscore, `%XX` or `%25XX`, `\n` or `\uXXXX`. The names `credentialText` takes (`api_key`, `access_token`, `refresh_token`, `auth_token`, `private_key`, `password`, `secret`, `_id_token`) match wherever they stand, camel case included (`accessToken`, `clientSecret`) | the name and boundary; `monkey%3D1`, `keys%3D1`, `max_token%3D256`, `sort_key%3Ddate`, `key%3D` with no value | | `vendorKeyBefore` | the same 16+ character key between `API key`/`API token` and `is`/`was` `invalid`/`incorrect`, in single quotes, double quotes (raw or JSON-escaped `\"`) or none | the phrase and quotes; a word, an id of 15 or fewer characters, any other verdict (`is set`) | | `vendorKeyMessage` | the 16+ character key (letters, digits, `_ - + / =`) after `Invalid`/`Incorrect` + `API key`/`API token`/`x-api-key`/`invalid_api_key`, with an optional `provided`, `:` and quote (raw or JSON-escaped) | the phrase; a word after it (`authentication_failed_error`), a short id (`Invalid API key. Request id 01234567`), a text with no key | `Incorrect API key provided: sk-...` was already redacted by `providerCredential`; a row pins it. ``` before: Invalid API key 0123456789abcdef0123456789abcdef after: Invalid API key [redacted] before: request failed: key%3D0123456789abcdef0123456789abcdef tail after: request failed: key%3D[redacted] tail ``` No ClickHouse view change: no new `msg` and no new field. ## Changes - `acceleration/internal/store/logs.go`: the three rules, `redactVendorKeyMessage` (word check per match, as `redactUnlessWord` does), and the shaped rules moved before the keyword rules in `redactCredentials`. - `acceleration/internal/store/logs_test.go`: `TestSafeLogTextTakesAnEncodedKeyAndAVendorRefusalOut` (whole-output rows, each also run a second time for idempotence) and two rows in `TestEveryTextARuleRedactsPassesTheCheck`. ## Validation - `go test ./internal/store/ ./internal/llmrouter/ ./internal/sttrouter/ ./internal/ttsrouter/`: pass; `go vet`, `gofmt`: clean. - The rows with nothing to redact pass on base 31fd2dd too (control); every redaction row except the ones already covered fails there. - Mutations of the three patterns, their boundaries, names, value class, floor, output templates, the per-match word check and the rule order: all killed but one equivalent (swapping `encodedCredential` and `vendorKeyMessage`, whose matches cannot overlap). - False-positive sweep, base vs head: `SafeLogText` over every Go string literal of `acceleration/` and every repo text line with key/token/secret/password/invalid/incorrect (261k items). Only this PR's test fixtures change. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
Why
LLM calls write a
model call timingline (#2152). Speech-to-text and text-to-speech work wrote none: their usage was only in therequestsrows, so the logs could not say which provider served a voice session, what it cost or why it failed. This PR adds one line per synthesis and one per transcription session, with the same owner fields as the LLM line, so the logs of a voice call filter by app.How it works
Text-to-speech: the line is written where the row is recorded (
ttsrouter/session.goobserve): atSynthesisCompleteand for a session-leveltts.Error. A repeated completion records no row, so it writes no line. A failure that names a synthesis in flight keeps its message (first failure wins, as the code does), and the completion logs it. A failover is a newSession, so each voice asked gets its own line. A session-level failure has no synthesis, so its line leaves outoperation,ttfb_msandduration_ms.A sentence that ends with no completion writes no row, and still gets one line, with
success=falseand nocost_micros:Each sentence gets this line once (
pending.abandoned). A streaming voice completes every sentence after a barge-in, so its sentences get a row; only the events ending first leaves one with none.Speech-to-text: the line is written at the two exits of
forward, once per provider that served the session:A session with no failover writes one line. A session that failed over writes two: the refused provider's line, then the line of the provider that took over. Nothing is logged per frame or per transcript:
took()only adds two counter writes (total ms, and the time of the first frame), and the line's fields are kept on therelay, which only the forward goroutine reads and writes.operationcharacters/audio_msttfb_msduration_mscost_microsQuoteStatof the rowsuccess,error_code,errorerrorthroughstore.SafeLogTextinterruptedfor a barge-in drop, else the code the voice reported for it (provider_fatal, its context,provider_error) orclosedwhen it reported none;erroris what the voice reported for it, throughstore.SafeLogTextaudio_msttfb_msduration_mscost_microsQuoteStatover the segment's turn rows and unsettled-audio rowssuccess,error_code,errorerrorthroughstore.SafeLogTextThe 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.
Neither line carries text, transcript, voice, audio or URLs.
Sample lines (fake ids):
{"level":"INFO","msg":"speech synthesis timing","call":"default:lobby","app_id":"acme","agent_id":"concierge","provider":"cartesia","model":"sonic-3","region":"eu","operation":"syn_1","characters":42,"audio_ms":2100,"ttfb_ms":180,"duration_ms":950.4,"cost_micros":1234,"success":true,"error_code":""} {"level":"INFO","msg":"speech synthesis timing","call":"default:lobby","app_id":"acme","agent_id":"concierge","provider":"cartesia","model":"sonic-3","region":"eu","operation":"syn_2","characters":57,"ttfb_ms":210.5,"duration_ms":4012.3,"success":false,"error_code":"closed"} {"level":"INFO","msg":"speech synthesis timing","call":"default:lobby","app_id":"acme","agent_id":"concierge","provider":"cartesia","model":"sonic-3","region":"eu","characters":0,"audio_ms":0,"cost_micros":0,"success":false,"error_code":"connect","error":"voice unreachable"} {"level":"INFO","msg":"speech transcription timing","call":"default:lobby","app_id":"acme","agent_id":"concierge","provider":"deepgram","model":"flux-general-en","audio_ms":61400,"ttfb_ms":310.2,"duration_ms":62010.7,"cost_micros":5678,"success":true,"error_code":""}Before: neither line existed. The
model call timingline is the same as before, field for field and in the same order.ClickHouse: these are two new
msgvalues. The typed viewlogs.agent_model_callsmatches onlymodel call timing, so these lines are inlogs.app_logsbut in no typed view yet. That view change is a separate chat ticket.Changes
internal/routing/logged.go:LoggedCall, the owner fields every timing line opens with.llmrouter.loggedCallnow uses it.internal/ttsrouter/session.go:logTimingat the two places a row is recorded. The utterance keeps its failure's message and the time its first audio chunk arrived.logAbandonedwrites the line of a sentenceInterruptdrops and, when the voice's events end (forward), of each sentence still unsettled; their reservations are still let go atClose, as before.internal/sttrouter/session.go:relaykeeps the segment's start, first transcript, cost and fatal error.streamedAudiokeeps the total and the time of the first frame.logTimingruns at the twoforwardexits.forwardtakes its start time fromnewSession, because audio can reach the provider before the goroutine runs.Validation
go test ./internal/routing/ ./internal/llmrouter/ ./internal/sttrouter/ ./internal/ttsrouter/ ./internal/agent/ ./internal/simulation/: pass. The same with-tags integrationfor sttrouter, ttsrouter and llmrouter: pass.loggedCallfor 4 owner/config/host shapes on the base and on this branch, and the outputs were byte-identical.TestALoggedCallNamesWhoseItWasThenWhatServedItpins that order.TestASessionLogsOneLineWhoseItWasWhatServedItAndWhatItCostruns on a fake clock, with 75 frames, an interim and 2 finals. It checks for exactly 1 line, exactttfb_ms/duration_ms, and cost. It fails on a line per frame or per transcript, or on a last-transcript ttfb.TestAFailedOverSessionLogsALinePerProviderThatServedIt: 2 lines with the right providers, audio, cost and durations. The refused line has success=false,provider_fatal, and the echoed key redacted. It fails if the line is logged for the wrong relay at the swap.TestAFrameInFlightToARefusedProviderIsNotBilledToTheNext: the refused provider's late audio is not added to the next provider's cost.TestARefusedRouterMeteredProviderLogsTheAudioBilledAsItRefused: the refused router-metered provider's line includes the audio billed as it refused. It fails if the line is written before that bill.TestAFailedSynthesisLogsWhatItsProviderSaidWithoutItsSecrets,TestARepeatedCompletionLogsItsSynthesisOnce,TestAFailureNoSynthesisSettlesIsLoggedOnItsOwn(nooperation/ttfb_ms/duration_ms),TestAFailureWithNoErrorUnderItIsLoggedWithoutOne.TestASynthesisTheSessionClosedOnLogsALineWithNoCost(fake clock: exactttfb_msfrom the first chunk,duration_ms, nocost_micros/audio_ms, redacted error, no duration for a sentence never started),TestASynthesisWhoseVoiceEndedOnItsOwnLogsALine,TestASentenceABargeInDropsLogsALine,TestEachSentenceOfAnIdTheVoiceNeverCompletedHasItsOwnLine. Controls for one line per synthesis:TestASentenceLoggedWhenTheVoiceEndedIsNotLoggedAgainByABargeIn,TestACompletedSynthesisIsNotLoggedAgainAtClose.Spent. One is not caught:forwardstamping its own start. That is a scheduling race, and the fake clock cannot show it. On the real clock, an earlier version of the test failed 3 of 5 runs with it.TestASynthesisAFatalErrorEndedLogsTheCodeTheVoiceReported(fatal then events end:provider_fatal; hang-up mid-sentence:closed),TestRowInterruptedLineCarriesItsStart,TestRowInterruptedSecondSentenceDoesNotCarryTheFirstsStart; each mutated both ways, killed.error_code, each left-out field, first-chunk stamping, the refused line before its bill), all killed. The new TTS tests pass-race -count=20, also with-cpu 1.🤖 Generated with Claude Code