Repository navigation
Conversation
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…spent the credit Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… is refused Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…settled-audio-at-renewal
kanat
left a comment
There was a problem hiding this comment.
VERDICT: NO-GO
Security review, round 1, head 28055e9. One Should fix; the rest of the change holds.
Held up under probes on a scratch copy:
- Billed exactly once: the renewal, turn, failover and close writes all claim the same counter under one lock.
- A failed billing write still counts: the money gate is settled in memory before the row is queued, so the renewal refuses once the audio spent the credit, as the settled-turn path does.
- A stream moved to a free model is not refused, and the audio before the move is billed on the paid one.
- A vendor-metered provider writes no row at a renewal; no row is written for 0 ms.
- No lock cycle between the renewal goroutine, Close, swap and Move; the new guard (the renewal write) fails the PR's tests when removed.
- No new route, input to the network, SQL or shell, and no internal error text or secret added to a log or row.
Should fix: a stream on the customer's own key now writes a zero-cost row at every renewal, which the base writes only at close. See the inline comment.
Not this PR, noted for a ticket: audio can still be taken faster than real time until two renewals in a row are refused; this PR narrows that and does not bound it.
| // what it took since the last row first: a stream that settles no turn is refused once its | ||
| // audio spent the money. | ||
| return routing.StartLeaseEvery(s.recorder, config, s.owner, "stt", uuid.NewString(), leaseMinute, leaseRenew, 3*leaseRenew, | ||
| func() { s.billUnsettled(nil) }) |
There was a problem hiding this comment.
[Should fix] S1.1 A model on the customer's own key is leased too (the pricer lists it, so the lease starts), so this hook runs for a lease that reserves nothing and writes a zero-cost private row at each renewal. On the base the same stream writes none until its turns settle or it closes. Money is unchanged, but the row count and the rows' timing differ from the base for a class that must stay as it was.
Fix: run the renewal write only while the lease's model quotes a non-zero minute (the check Move already uses), so own-key and free models keep the base's rows.
Test row (add to MoneySuite in reserve_integration_test.go): an own-key model (ownKeyModel) on a router-measured provider, audio sent across several renewals; after the writer flushes and before Close, the owner has no rows. Fails on head, passes on base.
There was a problem hiding this comment.
Fixed in 71e9a94: the lease runs settle only while a minute of its current model costs anything, checked at every tick (Lease.bills, the same quote Move uses). Test: TestMoneySuite/TestAStreamOnTheCustomersOwnKeyWritesNoRowBeforeItEnds (30 s across renewals, one row at close). It fails with the check removed (12 rows).
kanat
left a comment
There was a problem hiding this comment.
VERDICT: NO-GO
Round 1 review at 28055e9, merged onto current main (92fcbb8, clean). The draft has no CI run yet; CI runs at gh pr ready.
The core rule holds. claim is the only code that moves the "billed up to" mark, and it runs under s.mu, so a turn, a renewal and the close each claim different milliseconds. Shown by: sttrouter integration, -race x3 on TestMoneySuite|TestRefusalsSuite, and probes on a scratch copy. A failover bills each model's audio at that model's price, once (probes: free to paid, paid to a model at twice the price, paid to paid with no turn). The lock order holds: settle takes mu before holding and never inside it. Moving settle inside holding hangs TestASessionHoldsItsMinuteFromOneRenewalToTheNext. The stsrouter change passes nil and changes nothing there.
I agree with S1.1 (own-key lease). R1.3 is a second site of the same class.
Mutations: 6 reviewer mutants plus the author's 11. Two survive on the failover paths (R1.1).
Question R1.5 (author's question): stsrouter recordTrailing has the same shape: caller audio is billed only when a reply settles or the session ends. It is outside this PR, so file a ticket. TTS is not affected: it reserves each sentence before sending it.
Should fix: R1.1, R1.2, R1.3. Nit: R1.4.
| // what it took since the last row first: a stream that settles no turn is refused once its | ||
| // audio spent the money. | ||
| return routing.StartLeaseEvery(s.recorder, config, s.owner, "stt", uuid.NewString(), leaseMinute, leaseRenew, 3*leaseRenew, | ||
| func() { s.billUnsettled(nil) }) |
There was a problem hiding this comment.
[Should fix] R1.1 No test pins the renewal write on the leases a failover makes or moves. Two mutants pass every PR test:
- R4:
swap'ss.lease = s.leaseOf(config)(a failover from a free model) starts its lease withnilsettle. - R5:
Movesetsl.settle = nil(a failover to another paid model).
Either way, a stream that settles no turn after the failover is never refused again. Hard-rule paths: failover between models, and a free model.
Test rows for MoneySuite. Fail over through forward: the first stub sends stt.Error{Fatal: true}, reopen returns the next stub, and the test waits for stt.Failover. Calling swap from the test goroutine leaves forward reading the closed provider.
- Free model, 30 s of audio, fail over to a paid model, credit for 3 min, 1 s frames, no turn. Expect
ErrNoCredits. Free-model rows = free audio at zero cost. Paid-model rows = paid audio. Kills R4. - Paid model, 10 s, fail over to a model at twice the price, same credit, no turn. Expect
ErrNoCredits, and per-modelaudio_ms= audio each one took. Kills R5.
I checked both on a scratch copy: they pass on head (x2) and fail under their mutant ("the paid model's audio spent the credit" / "the next model's audio spent the credit").
There was a problem hiding this comment.
Fixed in e59a912: TestMoneySuite/TestAStreamThatSettlesNoTurnOnTheModelAFailoverLeasedEndsOnceItsAudioSpentTheCredit (free model, then a paid one via a fatal error and reopen) and TestMoneySuite/TestAStreamThatSettlesNoTurnOnTheModelItsLeaseMovedToEndsOnceItsAudioSpentTheCredit (paid, then another paid one). Each checks the refusal and the audio billed per model, once. R4 (the new lease of the swap gets nil settle) fails the first. R5 (Move drops settle) fails the second.
| s.heard(session, "a turn") | ||
| } | ||
| // Past two renewals, with half a millisecond no row has billed. | ||
| time.Sleep(3 * leaseRenew) |
There was a problem hiding this comment.
[Should fix] R1.2 The control relies on timing. [61, 82, 0] holds only if both turns settle within 500 ms of newSession, before the first tick. A stalled runner lets a renewal split a turn: the renewal writes a row and the turn writes the rest. That row is correct behaviour, so the test fails with nothing broken. It passed 15/15 under -race on a loaded machine, but nothing enforces the window.
Fix (checked on a scratch copy: passes x3, and author mutant M7 ms < 0 fails it with [61 82 0 0 0 0]): set leaseRenew = time.Hour (no tick during the test) and replace the time.Sleep(3 * leaseRenew) with two session.billUnsettled(nil) calls, the call each renewal makes. The lease wiring stays covered by the other new tests (M1, M4, M5).
TestTheRenewalAfterTheAudioSpentTheCreditIsRefused has the same kind of wall-clock window (0.5 s margin). It is lower risk; widening leaseRenew there would do.
There was a problem hiding this comment.
Fixed in 67e43f4: the control sets leaseRenew = time.Hour and calls billUnsettled(nil) twice by hand, as a renewal does. M7 (0 ms row) fails it with [61 82 0 0 0 0]. TestTheRenewalAfterTheAudioSpentTheCreditIsRefused now renews every 2 s with a 1 s margin. It also requires that the audio was taken before the first renewal. Settle-after-renew fails it (4.0 s, not less than 3 s).
| case <-ticker.C: | ||
| // Before holding is taken: settle may wait on the stream's own lock, which is held | ||
| // while Move takes holding. | ||
| if l.settle != nil { |
There was a problem hiding this comment.
[Should fix] R1.3 This is a second site of S1.1's class. After a failover to a model that bills nothing, Move releases the hold but the lease keeps ticking, and each tick runs settle, which writes a zero-cost row for the free model.
Probe: paid model, then a fatal error hands the stream to a free model, renewals every 20 ms, 10 s of audio, rows read before Close. Head: 10 free-model rows. Base: 0.
Fix: apply S1.1's check here, per tick, not at lease start. Run settle only while l.config quotes a non-zero minute (Move's own check, read under holding). That covers own-key at start and a move to a free or own-key model.
Test row: the probe above. It expects zero free-model rows before close; it fails on head and passes on base.
There was a problem hiding this comment.
Fixed in 71e9a94, with the same change as S1.1: the price is checked at every tick, so a lease moved to a free model stops settling. Test: TestMoneySuite/TestAStreamMovedToAFreeModelWritesNoRowBeforeItEnds. It fails both with the check removed and with the check made only when the lease starts (10 free-model rows of 1000 ms each, not one of 10000).
| if !open { | ||
| // Before the events close, so whoever waits on them waits for the last row. | ||
| s.billUnsettled(nil, current) | ||
| s.billUnsettled(nil) |
There was a problem hiding this comment.
[Nit] R1.4 The renewal's billUnsettled (lease goroutine) can race forward's last one. Sequence: the renewal has claimed its milliseconds but not yet recorded them; forward finds 0 ms left, logTiming reads unsettledMicros without that row's cost, and the events close before the row is queued. The comment "whoever waits on them waits for the last row" no longer always holds. Totals are unaffected, and Close waits for lease.Stop, so its callers do see the row. The window is between claim and Record.
Possible fix: stop or drain the lease before the final bill, or serialise billUnsettled with its own mutex. Ticket.
… costs anything A stream on the customer's own key, or moved to a free model, wrote a zero-cost row at every renewal. The lease now checks the model it is on before each renewal's settle. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…enewal window The control renews by hand with no lease tick of its own, so a turn that settles late cannot be split. The first-renewal test gets a second of margin and checks the audio was taken before it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…settled-audio-at-renewal
kanat
left a comment
There was a problem hiding this comment.
VERDICT: NO-GO
Delta round 2, cd7be6fe8 merged onto main at 21b2551e4. R1.1, R1.2, R1.3 and S1.1 are fixed. One new Should fix: a mutant of the new per-tick check survives the PR's tests.
Prior findings
- S1.1 (own-key stream wrote a zero-cost row at each renewal): fixed. Mutation
settlewithout thebills()check:TestAStreamOnTheCustomersOwnKeyWritesNoRowBeforeItEndsfails. - R1.3 (stream moved to a free model kept writing rows): fixed. Same mutation:
TestAStreamMovedToAFreeModelWritesNoRowBeforeItEndsfails. - R1.1 (failover and Move leases untested): fixed. Mutations: swap's new lease gets a nil settle: the three no-turn tests and the renewal-window test fail. Move drops settle:
...ItsLeaseMovedTo...fails. - R1.2 (control depended on a 500 ms window): fixed. The control now uses an hour-long renew and two direct
billUnsettled(nil)calls. Mutationms < 0(0 ms row): the control fails. Mutation settle-after-renew:TestTheRenewalAfterTheAudioSpentTheCreditIsRefusedfails (4.2 s against the 3 s bound).
Races (the lease's per-tick check)
bills() reads l.config under holding, the same lock Move writes it under, so it is race-free. A tick that reads the old model and then loses to Move bills at most one extra settle on rows the session prices per provider, and claim hands each millisecond to exactly one caller, so nothing is billed twice. A tick that reads a free model skips the settle, and the next tick bills the paid audio before its renewal. Probe: 400 alternating Move(free) / Move(paid) against 1 ms ticks and audio, -race -count=5: no race, billed total equals audio taken once.
New finding
- [Should fix] A mutant that survives: a lease that skips one settle because its model was free or own-key, and then never settles again ("sticky off"), passes every test in the PR. The PR's free-to-paid test (
...AFailoverLeased...) starts on a model that holds no lease, so the lease thatMovecarries from an own-key model to a paid one is not covered. That is the "move from a free model to a paid one" case: the paid audio would then never be billed at renewal. Add this row toTestMoneySuite(checked: passes on head x2, fails under the mutant with "Expected error ... no credit left but got nil"):
func (s *MoneySuite) TestAStreamThatLeftTheCustomersOwnKeyForAPaidModelEndsOnceItsAudioSpentTheCredit() {
leaseRenew = 20 * time.Millisecond
money := policytest.Start(s.T(), "sttrouter_reserve")
owner := money.Owner(s.T(), 50_000)
first := &lastWordsSTT{emitter: stt.NewEmitter(64)}
next := &lastWordsSTT{emitter: stt.NewEmitter(64)}
session := s.on(money, owner, ownKeyModel, first, next, otherModel)
s.Require().NotNil(session.lease)
for range 5 {
s.Require().NoError(session.ProcessAudio(speech(1_000), stt.Participant{}))
time.Sleep(30 * time.Millisecond) // several ticks on the own-key model first
}
s.failover(session, first)
s.Require().ErrorIs(s.spoken(session), policy.ErrNoCredits, "the paid model's audio spent the credit")
s.said(session)
s.EqualValues(next.frames()*1_000, s.billedBy(money, owner)[otherModel.Model], "billed once")
}The mutant: in keep, set a field off the first time bills() is false and skip settle while it is set.
- [Nit]
TestTheRenewalAfterTheAudioSpentTheCreditIsRefusedstill bounds the first refusal by wall-clock (2 s renew, refusal before 3 s): 1 s of margin, so it is not window-free under heavy load. The own-key and moved-to-free tests assert "no row", so on a machine too loaded for any tick to fire they would pass without testing anything. Neither blocks.
Runs
Integration (-p 1) sttrouter, routing, stsrouter: pass. Unit for the same three: pass. TestMoneySuite -race -count=3 and -cpu 1 -count=10: pass. CI on this draft: CodeQL, labeler, GitGuardian, Analyze pass; go and integration skipped (draft).
| s.EqualValues(taken*1_000, s.billed(money, owner), "every second it took is billed, once") | ||
| } | ||
|
|
||
| func (s *MoneySuite) TestAStreamThatSettlesNoTurnOnTheModelAFailoverLeasedEndsOnceItsAudioSpentTheCredit() { |
There was a problem hiding this comment.
[Should fix] This free-to-paid row starts on a model that holds no lease, so a lease that Move carries from an own-key model to a paid one is not covered; a mutant that stops settling after one non-billing tick survives. Row in the review body.
Why
A transcription on a vendor the router measures (the vendor bills every second it hears) wrote its usage row at each settled turn and at close. A stream that settles no turn, a long silence say, wrote nothing until it closed, so the balance did not fall while it ran and the lease renewal's money check (#2403) never refused it. Detail: AI-3857.
How it works
The settle hook runs on the lease's ticker before
holdingis taken (swapholds the session'smuwhileMovetakesholding), and not on the first reservation, whichleaseOfmay make undermu.claimstays the one place that advances the "billed up to" mark, so each millisecond is billed once by a turn, a renewal or the close.billUnsettledskips it)The timing line's
cost_microskeeps the cost of these rows: it now lives instreamedAudio(guarded bymu), since the renewal goroutine cannot touch forward'srelay.Changes
internal/routing/lease.go:StartLeaseEverytakes asettlefunc called before each renewal but the first, while a minute of the lease's current model costs anything (the checkMoveuses).internal/sttrouter/session.go:leaseOfpassesbillUnsettled(nil);billUnsettledkeeps the cost per provider.internal/stsrouter/session.go: passesnil(no change).Validation
New
MoneySuitetests (real enforcer,internal/sttrouter/reserve_integration_test.go):TestAStreamThatSettlesNoTurnEndsOnceItsAudioSpentTheCreditTestTheRenewalAfterTheAudioSpentTheCreditIsRefusedTestTurnsSettledBetweenRenewalsAreBilledAsTheyWereTestAudioTakenAsTheLeaseRenewsIsBilledOnce-race)TestAStreamOnTheCustomersOwnKeyWritesNoRowBeforeItEndsTestAStreamMovedToAFreeModelWritesNoRowBeforeItEndsTestAStreamThatSettlesNoTurnOnTheModelAFailoverLeasedEndsOnceItsAudioSpentTheCreditTestAStreamThatSettlesNoTurnOnTheModelItsLeaseMovedToEndsOnceItsAudioSpentTheCreditMovedrops settleTestTurnsSettledBetweenRenewalsAreBilledAsTheyWererenews by hand (leaseRenewan hour), so a turn that settles late cannot split a row.billednow closes the writer before it reads, so it sums every row, not the first batch written.Mutations, all killed: no settle call, settle nil guard, settle after renew, session passes nil, lease drops settle, close bills the total again, 0 ms row, renewal does not advance the mark, timing line drops the renewal cost (x2), settle on the first reservation (deadlocks a failover from a free model), no price check at the tick, price checked only at start, failover lease with nil settle,
Movedrops settle.Suites run: sttrouter (unit + integration, MoneySuite also
-race), routing (unit +TestReserveSuite), stsrouter (unit + integration), agent (unit +TestAgentMoneySuite).🤖 Generated with Claude Code