Skip to content

[AI-3416] Log speech synthesis and transcription timing - #2212

Merged
kanat merged 9 commits into
mainfrom
kanat/ai-3416-speech-call-log-lines
Nov 23, 2026
Merged

kanat merged 9 commits into
mainfrom
kanat/ai-3416-speech-call-log-lines

Conversation

@kanat

@kanat kanat commented Nov 23, 2026 •

Copy link
Copy Markdown
Collaborator

Why

LLM calls write a model call timing line (#2152). Speech-to-text and text-to-speech work wrote none: their usage was only in the requests rows, 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

routing.LoggedCall(call, owner, config, served...)
  call, app_id, agent_id, provider, model, [served...], region, byok
  ├─ llmrouter  "model call timing"            served = vendor_host (unchanged)
  ├─ ttsrouter  "speech synthesis timing"      one line per synthesis: its row, or none written
  └─ sttrouter  "speech transcription timing"  one line per provider segment

Text-to-speech: the line is written where the row is recorded (ttsrouter/session.go observe): at SynthesisComplete and for a session-level tts.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 new Session, so each voice asked gets its own line. A session-level failure has no synthesis, so its line leaves out operation, ttfb_ms and duration_ms.

A sentence that ends with no completion writes no row, and still gets one line, with success=false and no cost_micros:

sentence sent ─┬─ SynthesisComplete ─────────────────────────────> row + line (as above)
               ├─ Interrupt drops it (per-sentence voice, final
               │  text not sent yet; the voice never completes it) ─> line, error_code "interrupted"
               └─ the voice's events end first: Close (the agent
                  closes its voice at teardown, a cancelled call
                  included), a voice stalled until then, or a voice
                  that ended its events on its own ─────────────────> line, error_code: voice's own, else "closed"

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:

newSession ─ forward ─┬─ provider refused, next took over ─> line (refused, success=false)
                      │                                       └─ next relay ...
                      └─ provider closed its events ──────> line (served)

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 the relay, which only the forward goroutine reads and writes.

field text-to-speech, row text-to-speech, no completion
operation synthesis id; absent for a session-level failure synthesis id
characters / audio_ms characters billed, audio ms produced characters sent / absent
ttfb_ms provider's time to first byte; absent for a session-level failure start -> first audio chunk; absent when none arrived
duration_ms as the row; absent for a session-level failure start -> end; absent when it never started
cost_micros QuoteStat of the row absent: no row
success, error_code, error as the row; error through store.SafeLogText false; interrupted for a barge-in drop, else the code the voice reported for it (provider_fatal, its context, provider_error) or closed when it reported none; error is what the voice reported for it, through store.SafeLogText
field speech-to-text
audio_ms audio ms the provider took
ttfb_ms first audio taken -> first transcript read (interim included); absent when no transcript came after audio
duration_ms segment start -> end
cost_micros sum of QuoteStat over the segment's turn rows and unsettled-audio rows
success, error_code, error first fatal error of the segment; error through store.SafeLogText

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.

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 timing line is the same as before, field for field and in the same order.

ClickHouse: these are two new msg values. The typed view logs.agent_model_calls matches only model call timing, so these lines are in logs.app_logs but 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.loggedCall now uses it.
  • internal/ttsrouter/session.go: logTiming at the two places a row is recorded. The utterance keeps its failure's message and the time its first audio chunk arrived. logAbandoned writes the line of a sentence Interrupt drops and, when the voice's events end (forward), of each sentence still unsettled; their reservations are still let go at Close, as before.
  • internal/sttrouter/session.go: relay keeps the segment's start, first transcript, cost and fatal error. streamedAudio keeps the total and the time of the first frame. logTiming runs at the two forward exits. forward takes its start time from newSession, 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 integration for sttrouter, ttsrouter and llmrouter: pass.
  • LLM line unchanged: the llmrouter log tests pass with no change. A probe printed loggedCall for 4 owner/config/host shapes on the base and on this branch, and the outputs were byte-identical. TestALoggedCallNamesWhoseItWasThenWhatServedIt pins that order.
  • New tests decode the captured JSON line and check each field. Each test catches a named defect:
    • TestASessionLogsOneLineWhoseItWasWhatServedItAndWhatItCost runs on a fake clock, with 75 frames, an interim and 2 finals. It checks for exactly 1 line, exact ttfb_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.
    • TTS: TestAFailedSynthesisLogsWhatItsProviderSaidWithoutItsSecrets, TestARepeatedCompletionLogsItsSynthesisOnce, TestAFailureNoSynthesisSettlesIsLoggedOnItsOwn (no operation/ttfb_ms/duration_ms), TestAFailureWithNoErrorUnderItIsLoggedWithoutOne.
    • TTS, no completion: TestASynthesisTheSessionClosedOnLogsALineWithNoCost (fake clock: exact ttfb_ms from the first chunk, duration_ms, no cost_micros/audio_ms, redacted error, no duration for a sentence never started), TestASynthesisWhoseVoiceEndedOnItsOwnLogsALine, TestASentenceABargeInDropsLogsALine, TestEachSentenceOfAnIdTheVoiceNeverCompletedHasItsOwnLine. Controls for one line per synthesis: TestASentenceLoggedWhenTheVoiceEndedIsNotLoggedAgainByABargeIn, TestACompletedSynthesisIsNotLoggedAgainAtClose.
  • Mutation checks: one batched script ran 39 mutants of every added guard, field and call site. 36 were killed. One redundant ttfb check survived and was deleted. One is equivalent: the LLM line takes the call from the session owner, and the stat owner differs from it only in Spent. One is not caught: forward stamping 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.
  • Round 2: TestASynthesisAFatalErrorEndedLogsTheCodeTheVoiceReported (fatal then events end: provider_fatal; hang-up mid-sentence: closed), TestRowInterruptedLineCarriesItsStart, TestRowInterruptedSecondSentenceDoesNotCarryTheFirstsStart; each mutated both ways, killed.
  • Round 1 fixes: 17 more mutants (the once-guard, each 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

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 kanat changed the title [AI-3416] Log a timing line per speech synthesis and transcription [AI-3416] Log speech synthesis and transcription timing Nov 23, 2026

@kanat kanat left a comment

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.

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_micros equals 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 stamps firstAt only 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_ms 0, no ttfb_ms).
  • TTS: one line per row, none for a repeated completion.
  • The go session.forward(time.Now()) change only feeds the line.
  • SafeLogText is on both error fields (mutants killed).
  • -race -count=50 -cpu 1 passes 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)

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).

// 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,

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.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.

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 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 {

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."

kanat and others added 5 commits November 23, 2026 14:34
…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>
@kanat

kanat commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator Author

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 speech synthesis timing line with success=false, no cost_micros (no row) and no audio_ms: error_code "interrupted" when Interrupt drops it (per-sentence voice, final text not sent), "closed" when the voice's events end first (Close, a stalled voice, events ended by the voice). pending.abandoned keeps it to one line. Tests: TestASynthesisTheSessionClosedOnLogsALineWithNoCost, TestASynthesisWhoseVoiceEndedOnItsOwnLogsALine, TestASentenceABargeInDropsLogsALine, TestEachSentenceOfAnIdTheVoiceNeverCompletedHasItsOwnLine, controls TestASentenceLoggedWhenTheVoiceEndedIsNotLoggedAgainByABargeIn and TestACompletedSynthesisIsNotLoggedAgainAtClose. 15 mutants (the once-guard, each error_code, each left-out field, first-chunk stamping), all killed.

@kanat kanat left a comment

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.

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 gives closed with error: socket reset, where its row would say provider_fatal.
  • [Should fix] R2.2, inline on session.go:205: mutants M1 and M4 of the i == 0 argument 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)

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] 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.

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 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 {

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] 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.

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 b2a0ae0 (head ef3c940): added TestRowInterruptedLineCarriesItsStart and TestRowInterruptedSecondSentenceDoesNotCarryTheFirstsStart. M4 (false) fails the first; M1 (true) fails the second.

kanat and others added 2 commits November 23, 2026 15:03
…the interrupt start

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

@kanat kanat left a comment

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.

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.go abandonUnsettled), else closed. Mutating the condition to false fails FatalErrorEnded and ClosedOn. Mutating it to true fails 5 tests.
  • R2.2 fixed. i == 0 || true at the Interrupt site fails TestRowInterruptedSecondSentenceDoesNotCarryTheFirstsStart. i == 0 && false fails 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>
@kanat
kanat marked this pull request as ready for review November 23, 2026 14:19
@kanat
kanat merged commit 31e9243 into main Nov 23, 2026
15 checks passed
@kanat
kanat deleted the kanat/ai-3416-speech-call-log-lines branch November 23, 2026 15:05
kanat added a commit that referenced this pull request Nov 23, 2026
## 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>
kanat added a commit that referenced this pull request Nov 23, 2026
## 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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant