Repository navigation
[AI-3618] Log a speech timing line for batch recordings - #2239
Conversation
️✅ 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. 🦉 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
left a comment
There was a problem hiding this comment.
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.Callcaller (22 sites,grep -rn "routing\.Call(" --include=*.go) builds itsMeterwithoutRecorded, socall.go:133skips 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_microsequals the stored row's cost for free and quoted work. The split ofpriceout ofpricedkeeps 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.
errorgoes throughSafeLogText. - 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) |
There was a problem hiding this comment.
[Should fix] R1.1 Three mutants survive every test:
- Here,
pricechanged topriced: the dropped-user counterusage_user_id_droppedthen goes up twice per batch row. sttrouter/recordings.go:136passesProviderConfig{Provider, Model}, which drops region and BYOK.ttsrouter/recordings.go:287does 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.
|
|
||
| func (s *RecordingsSuite) TestAFailedTranscriptionLogsItsCodeAndItsErrorWithNoCredential() { | ||
| app := "acme-" + rand.Text() | ||
| failure := errors.New("deepgram: 401 for Authorization: Bearer sk-live-4f9a8b7c6d5e4f3a2b1c") |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
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") |
There was a problem hiding this comment.
[Should fix] R1.2 Same GitGuardian hit as sttrouter/recordings_timing_test.go:85.
There was a problem hiding this comment.
Fixed in dacd0fb: same change in ttsrouter/recordings_timing_test.go.
| } | ||
| if !omitted { | ||
| meter.record(stat) | ||
| if meter.Recorded != nil { |
There was a problem hiding this comment.
[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.
|
|
||
| // 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) { |
There was a problem hiding this comment.
[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.
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>
350be4e to
dacd0fb
Compare
kanat
left a comment
There was a problem hiding this comment.
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.gocost usespriced) is killed byTestCallSuite/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 b7c48fe02is the two timing test files only, 4 lines (the fake credential string and itsNotContains). 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 beforeRelease, or beforerecord, fails the two newReserveSuitetests. The hook only reads the stat and the price, so it needs no reservation. It still runs inCall's defer, so a slow hook delays the HTTP answer exactly as before. - R1.4 fixed. The hook tests are in
CallHookSuitewith aSetupTest, 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.
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/recordingsand an agent's voice notes (api/recordings.go,api/voicenotes.go) left a row inrequestsand nothing in the logs. Part of AI-3611 (piece 1 of 2; the speech-to-speech line is a separate PR).How it works
cost_microsis the row's owncost_micros:Recorder.priceis the pricingpriceduses, 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.msgis the same as the streaming lines, andbatch=trueappears only on batch lines, so the views that type these msgs (AI-3617) cover batch too.duration_mshere is the request latency (Stat.LatencyMs). There is nottfb_ms: one answer for the whole file has no first-byte point.callis always present, asrouting.LoggedCallwrites it. It is empty for/v1/stt/recordingsand/v1/tts/recordings, which have no call, and it is set for a voice note in a call.agent_idis 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 abatchcolumn to separate batch from streaming. Without that column,batchstays in the raw JSON. That column is for the chat ticket (AI-3617), not this PR.Changes
routing/call.go: addsMeter.Recorded, called fromCall's defer after the row is recorded. It is called on success, failure and panic, and not for work thatOmitleaves out.routing/stats.go: splitsRecorder.priceout ofpriced.sttrouter/recordings.goandttsrouter/recordings.go: the batch lines. STT logs toslogdefault and TTS logs to the router's logger, like each modality's streaming line.Validation
sttrouterTestATranscribedRecordingLogsOneBatchLineWithWhatItCostbatchis dropped,duration_mscomes from the wrong field, the cost is 0callTestAFailedTranscriptionLogsItsCodeAndItsErrorWithNoCredentialttsrouterTestASpokenRecordingLogsOneBatchLineWithWhatItCostcharactersoraudio_msis droppedTestEachCandidateARecordingFallsBackFromLogsItsOwnLineroutingTestARecordedHook*TestCallSuite/TestARecordedHookIsToldWhatTheStoredRowCosts(Postgres)QuoteStat, which ignoresFreeand quoted feesTestACallWithNoRecordedHookLogsNothing,TestACallWithNoRecorderIsStillAnsweredsttrouter/ttsroutertests fail on base 108539d (no line). All of them pass on this head.sttrouter/session.go,ttsrouter/session.goorrouting/logged.go, and base's owntiming_test.goin both packages passes unchanged.go test ./internal/{routing,sttrouter,ttsrouter,llmrouter,api}/,go test -tags integration ./internal/{routing,sttrouter,ttsrouter}/,go vet(both tags) andgofmt -l.🤖 Generated with Claude Code