Skip to content

[AI-3618] Log a speech timing line for batch recordings - #2239

Merged
kanat merged 5 commits into
mainfrom
kanat/ai-3618-batch-speech-timing
Nov 23, 2026
Merged

kanat merged 5 commits into
mainfrom
kanat/ai-3618-batch-speech-timing

Conversation

@kanat

@kanat kanat commented Nov 23, 2026 •

Copy link
Copy Markdown
Collaborator

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:

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

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

@gitguardian

gitguardian Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

️✅ There are no secrets present in this pull request anymore.

If these secrets were true positive and are still valid, we highly recommend you to revoke them.
While these secrets were previously flagged, we no longer have a reference to the
specific commits where they were detected. Once a secret has been leaked into a git
repository, you should consider it compromised, even if it was deleted immediately.
Find here more information about risks.


🦉 GitGuardian detects secrets in your source code to help developers and security teams secure the modern development process. You are seeing this because you or someone else with access to this repository has authorized GitGuardian to scan your pull request.

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

Round-1 review at 350be4e, merged onto current main (284349e) in a scratch tree.

CI: GitGuardian Security Checks fails on this head: "Bearer Token" in both new recordings_timing_test.go files (R1.2, inline). CodeQL, Analyze and labeler pass. go and integration are skipped because the PR is a draft; they run at gh pr ready.

Checked and sound:

  • Every other routing.Call caller (22 sites, grep -rn "routing\.Call(" --include=*.go) builds its Meter without Recorded, so call.go:133 skips the hook for them.
  • I wrote two probes, ran each on base and on head, and diffed the output:
    • Stored rows (priced, free, quoted fee, refused user id, failure): every priced field, the user id and the attributes are the same on base and head.
    • Streaming STT and TTS lines (ok and failed, region and BYOK set): byte for byte the same on base and head, with the time removed.
  • The logged cost_micros equals the stored row's cost for free and quoted work. The split of price out of priced keeps the row as it was, and with a hook set a refused user id is still counted once per row.
  • The row is queued before the hook runs. The lines carry no text, transcript or audio, because the tests compare the whole map. error goes through SafeLogText.
  • Touched suites pass: unit tests for routing, sttrouter, ttsrouter, api and llmrouter. Integration runs for routing, sttrouter, ttsrouter, plus the api suites for recordings, speech failover, speech recorders and voice notes (62 subtests).

Author questions: the rows written for a candidate that failed to build or start get no line: that goes to a ticket, out of scope here. The batch column belongs to the ClickHouse views ticket, not this PR.

Verdict: request changes, for R1.1 (3 surviving mutants) and R1.2 (red GitGuardian check).

if m.Recorder == nil {
return 0
}
request, _ := m.Recorder.price(m.Config, stat)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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

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

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

(1) In call_integration_test.go, CallSuite:

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

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

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

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

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

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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


func (s *RecordingsSuite) TestAFailedTranscriptionLogsItsCodeAndItsErrorWithNoCredential() {
app := "acme-" + rand.Text()
failure := errors.New("deepgram: 401 for Authorization: Bearer sk-live-4f9a8b7c6d5e4f3a2b1c")

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.2 GitGuardian Security Checks is red on this head: it flags this fake Authorization: Bearer sk-live-… as a Bearer Token, and the same at ttsrouter/recordings_timing_test.go:91. Use the shape the streaming timing tests use, which the scanner passes (sttrouter/timing_test.go:258, api_key=sk-live-0123456789abcdef), and keep the NotContains. The token is fake, so nothing needs rotating. Mark the incident as a false positive.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in dacd0fb: the fake token is now api_key=sk-live-0123456789abcdef, as in sttrouter/timing_test.go; the commit was amended so the flagged text is not in the branch history. GitGuardian passes on the new head.


func (s *RecordingsSuite) TestEachCandidateARecordingFallsBackFromLogsItsOwnLine() {
app := "acme-" + rand.Text()
failure := errors.New("voicy: 500 for Authorization: Bearer sk-live-4f9a8b7c6d5e4f3a2b1c")

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.2 Same GitGuardian hit as sttrouter/recordings_timing_test.go:85.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in dacd0fb: same change in ttsrouter/recordings_timing_test.go.

Comment thread acceleration/internal/routing/call.go Outdated
}
if !omitted {
meter.record(stat)
if meter.Recorded != nil {

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.3 The hook runs before Release. A hook that panicked would skip the release of a reservation and turn the answer into a panic. Neither batch meter sets Estimate, so nothing breaks today. Call the hook after the Release block, or say in the Recorded doc that it must not panic. Goes to a 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 dacd0fb (commit ebfc9d8): the hook runs after Release. Tests: ReserveSuite TestAPanickingRecordedHookStillReleasesTheReservation and TestARecordedHookIsToldOnlyOnceTheReservationIsReleased; both fail with the old order.


// toldMeter is a meter of a model priced at 2 US dollars a million input tokens, whose
// recorder writes nothing, with a hook that keeps what it is told.
func toldMeter(t *testing.T) (Meter, *hooked) {

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 Six new top-level tests share the toldMeter setup. The go-testing skill asks for a suite with shared setup, though this file already uses plain functions. Goes to a 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 dacd0fb (commit 1eae1f8): the tests are in CallHookSuite with a shared SetupTest.

kanat and others added 5 commits November 23, 2026 18:07
A batch transcription and each voice a batch recording asks now log
"speech transcription timing" / "speech synthesis timing" with
batch=true, beside the row routing.Call records. Meter.Recorded is the
hook: Call tells it the final stat and what the row costs as Record
prices it (free and quoted work included). Nil changes nothing for the
other Call callers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…nts once

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@kanat
kanat force-pushed the kanat/ai-3618-batch-speech-timing branch from 350be4e to dacd0fb Compare November 23, 2026 17:14

@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 2 — GO (reviewed dacd0fbc0, which already contains base 284349e10)

Prior findings:

  • R1.1 fixed. I re-ran the three mutants on the new head: A (call.go cost uses priced) is killed by TestCallSuite/TestARecordedHookCountsARefusedUserIDOncePerRow (expected 1, got 2); I10s (stt call site drops region/byok) is killed by both stt timing tests; I10t (tts, same) is killed by both tts timing tests.
  • R1.2 fixed. GitGuardian passes on dacd0fbc0. git diff 350be4ec8 b7c48fe02 is the two timing test files only, 4 lines (the fake credential string and its NotContains). Nothing else changed in the amended commit.
  • R1.3 fixed. The defer is now record → Release → hook. The row is still queued before the hook. Moving the hook back before Release, or before record, fails the two new ReserveSuite tests. The hook only reads the stat and the price, so it needs no reservation. It still runs in Call's defer, so a slow hook delays the HTTP answer exactly as before.
  • R1.4 fixed. The hook tests are in CallHookSuite with a SetupTest, assertions unchanged.
  • R1.5 stays a ticket (build_failed/start_failed rows write no line); not part of this PR.

New findings: none. The delta's only production hunk is the order change in call.go.

Checks: build, vet (default and integration tags) and gofmt are clean. Unit tests pass for routing, sttrouter, ttsrouter, api and llmrouter. Integration (-p 1) passes for routing, sttrouter and ttsrouter. 5 mutations, 0 survived. Draft: go and integration jobs skip (#2130); the other checks pass.

@kanat
kanat marked this pull request as ready for review November 23, 2026 17:26
@kanat
kanat merged commit a9ee6fa into main Nov 23, 2026
15 checks passed
@kanat
kanat deleted the kanat/ai-3618-batch-speech-timing branch November 23, 2026 19:14
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