Repository navigation
AI-3597: a scheduled call's turn refused for money fails the run - #2277
Conversation
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EZsRxWUwySyG1JAn9T7GpE
The root CHANGELOG is written once per release (.claude/skills/pr/SKILL.md); the note is in the PR body. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EZsRxWUwySyG1JAn9T7GpE
…its retry A placed call whose answered turn is refused because the organization's money could not be checked is given back to its run (ReleaseCall), so the retry places the call again and runs the turn again under the rerun's id (replyCommand). The rerun refused as well fails the run, final, so the user is rung twice at most. A final refusal for money keeps the call taken. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EZsRxWUwySyG1JAn9T7GpE
… code carryOutOnCall's failed Create saved delivery_failed on the run (callEnded) even when the session was refused for money; it now fails under the refusal's own code (unpaid), final unless the money could not be checked, and a worker that takes the run over reads that code. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EZsRxWUwySyG1JAn9T7GpE
…again Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EZsRxWUwySyG1JAn9T7GpE
kanat
left a comment
There was a problem hiding this comment.
Reviewed 62c4521f4 merged onto main at e1be8e3b1, in a scratch worktree. CI: this is a draft, so go and integration are skipped and CodeQL Analyze (go) is pending. CI runs at gh pr ready. On the merged tree, TestTelnyxUnpaidSuite, TestScheduledTasksSuite and the internal/api unit tests pass, and vet and gofmt are clean. Base control: with main's scheduled_delivery.go, the 3 not-money and answered tests pass (their ends are unchanged) and the 4 refusal tests fail.
[Question] R1.5 This PR should merge after #2272. On main today, a worker that takes the run over during the retry wait finds run.Error NULL after ReleaseCall. Then replyCommand returns _call, because that turn failed and the reason is not money. The FollowUp is a Duplicate (session.go:1123), so the agent says nothing on the second call and the run ends delivered when the user hangs up. R1.1's fix also reads Earlier. #2272 at 502b8f420 fills that gap: its SetAttemptReason writes error only while session_id='', and ReleaseCall guarantees that. So the two PRs fit together, provided #2272 lands first. The orchestrator decides the order.
Checked and sound:
- A final money refusal still rings once (both final tests keep the
SessionID). - A transient refusal of an answered turn ends the walk on the first attempt.
- After a transient Create refusal, the walk goes on to the next channel, as base does for any Create failure.
- Testing only that
_call_r1exists, together withansweredOn, is enough (the no-rerun-id mutant is killed). - On D1.2, the fixer's dispute about the
followUpWithinhalf holds:FollowUpruns no money check synchronously (session.go:1106-1133, agent.go:993-1009, native.go:77-96).
Verdict: request changes, for R1.1 (a user can be rung up to 4 times when the money check is down).
| if !errors.As(err, &failure) { | ||
| return err | ||
| } | ||
| if !failure.Final { |
There was a problem hiding this comment.
[Blocker] R1.1 Nothing limits how often a placed call is given back. Every transient money refusal releases the call, so a user can be rung on all 4 attempts (1 + DeliveryRetries). Two cases:
- The call's session cannot open while money cannot be checked (
carryOutOnCall, :1194). Each attempt dials the user withphone.Calland thenCreateis refused. The probe repeats that refused Create attempt by attempt and getsrings=4. - The turn is refused on attempt 1, and the session is refused on attempt 2. Attempt 2 comes back non-final and is given back, so a third TakeCall succeeds.
Both break "a user is rung at most twice", which this PR's body and the skill row both claim. On the base, a Create failure was final: one ring.
Fix: give the call back once. If moneyCode(delivery.Earlier) holds, make the failure final and record the reason:
if !failure.Final && moneyCode(delivery.Earlier) {
failure.Final = true
}With that in place, the rerun branch in carryOutAnswered can go. I checked this sketch: all 7 TestACall* tests pass, and both probes end at 2 rings.
Test row for TelnyxUnpaidSuite. Call callOn, then uncheckable, then dial. Expect a failure that is not final, with SessionID empty. Then set Earlier=spend_check_unavailable, call takeCall, then dial again. Expect a final failure, with the SessionID of the second call kept. This row fails on head (rings=4) and passes with the sketch. It also kills mutant RM1 (R1.3).
| } | ||
| if refusal := turnRefusal(event); refusal != nil && !answered { | ||
| if rerun { | ||
| return undeliveredFinally(deliveryReason(refusal), refusal) |
There was a problem hiding this comment.
[Should fix] R1.2 This line wraps the refusal in a new scheduling.Failure. Failure has no Unwrap (scheduler.go:102-108), so refusedTurn returns false for this error. A probe confirms it: refusedTurn is true for the first attempt's refusal and false for this one. As a result, deliverChain (:313) does not stop at the call. For a task with channels [phone, sms], the next channel runs a new turn after the user was rung twice. If that channel fails non-final, final = final && ... turns the run non-final. That contradicts "that rerun refused as well fails the run, final".
Fix: keep the refusal's own Failure and set Final, or take R1.1's fix and delete this branch.
Test row: add s.True(refusedTurn(outcome.err), "the walk ends at the call") to TestACallWhoseTurnIsRefusedAgainOnItsRetryFailsTheRun. I checked it: it fails on head and passes with the R1.1 sketch.
| } | ||
| return refusal | ||
| } | ||
| if reply, ok := event.(agent.Responded); ok && reply.Purpose != agent.PurposeGreeting { |
There was a problem hiding this comment.
[Should fix] R1.3 Three mutants survive:
- RM1: in
carryOutOnCall, replaceunpaid(err)withundeliveredFinally(deliveryReason(err), err). Nothing tests the give-back of a transient Create refusal. The R1.1 test row kills it. - RM6: in
carryOutAnswered, the first-attemptreturn refusalkeeps Reason and Final but dropsturnRefused. Then no test checks that the walk ends at the answered call. Row: adds.True(refusedTurn(outcome.err))toTestACallWhoseTurnIsRefusedForMoneyFailsUnderTheMoney. I checked it: it passes on head and fails under RM6. - M4/RM2: the
Purpose != agent.PurposeGreetingclause on this line. This mutant is equivalent, because on a call the greeting never arrives asagent.Responded. It comes asagent.Said(agent.go:1366).RespondedcarriesPurposeGreetingonly whenoptions.Textis set (agent.go:1340),composedFornever returns it (agent.go:2881), andcallSpecsetsText=false(:1166). Fix: drop the clause. If check-in and update lines must not count as the answer, usereply.Purpose == ""and add a test for it.
| | `account_suspended`, `insufficient_credits`, `system_limit_reached`, `spend_limit_reached`, `user_limit_reached` | A step the organization may not pay for was refused for money (suspended, no credit left, or a spent limit): an SMS, WhatsApp or iMessage text or a thread task's reply (`dlc.ErrUnpaid`, or its reservation), the task's session opening or being carried on, a turn the model refuses, on a text channel (an `agent.Error` in `captureReply`, which ends the walk over the channels, `refusedTurn`), in the conversation (`followUpInConversation` waits for the turn to end and reads it from the session's events; a turn that ends any other way is still `delivered`) or on a thread task (`deliverOnThread` reads it from the session's events), or its call. The run records the refusal's own code (`deliveryReason`, `scheduled_delivery.go:334`), never `channel_unreachable` or `delivery_failed`, and the router warns, naming the task | no (`unpaid`, `scheduled_delivery.go:355`) | | ||
| | `spend_check_unavailable` | The router could not check what the organization has spent, so it refused the step for now (`policy.Transient`). A turn it refused runs once more on the retry, under `st_<run>_r1`: the scheduler hands the next attempt the reason this one failed under (`deliverWithRetries`), a hand-off to the router holding the session carries it (`scheduledHandOff.Earlier`), and `replyCommand` reruns a failed reply after a money code. A conversation rerun refused as well fails the attempt under the same code (`followUpInConversation`), so the run fails once its retries are spent. A reply that failed for any other reason is read back as it was | yes (`unpaid` leaves it retryable) | | ||
| | `account_suspended`, `insufficient_credits`, `system_limit_reached`, `spend_limit_reached`, `user_limit_reached` | A step the organization may not pay for was refused for money (suspended, no credit left, or a spent limit): an SMS, WhatsApp or iMessage text or a thread task's reply (`dlc.ErrUnpaid`, or its reservation), the task's session opening or being carried on, a turn the model refuses, on a text channel (an `agent.Error` in `captureReply`, which ends the walk over the channels, `refusedTurn`), in the conversation (`followUpInConversation` waits for the turn to end and reads it from the session's events; a turn that ends any other way is still `delivered`) or on a thread task (`deliverOnThread` reads it from the session's events), or its call, placed or not: a placed call whose session cannot open fails under the refusal's code (`carryOutOnCall`); on an answered call, a turn refused before the agent answered anything hangs up (`carryOutAnswered`), and a refusal after that is a later turn's, still `delivered`. The run records the refusal's own code (`deliveryReason`, `scheduled_delivery.go:334`), never `channel_unreachable` or `delivery_failed`, and the router warns, naming the task | no (`unpaid`, `scheduled_delivery.go:355`) | | ||
| | `spend_check_unavailable` | The router could not check what the organization has spent, so it refused the step for now (`policy.Transient`). A turn it refused runs once more on the retry, under `st_<run>_r1`: the scheduler hands the next attempt the reason this one failed under (`deliverWithRetries`), a hand-off to the router holding the session carries it (`scheduledHandOff.Earlier`), and `replyCommand` reruns a failed reply after a money code. A conversation rerun refused as well fails the attempt under the same code (`followUpInConversation`), so the run fails once its retries are spent. A reply that failed for any other reason is read back as it was. A call refused this way, its session or its answered turn, is given back to the run (`callEnded`, `ReleaseCall`), so the retry rings the user again and runs the call's turn again under `st_<run>_call_r1` (`carryOutAnswered`); that rerun refused as well fails the run under the same code, final, so the user is rung twice at most | yes (`unpaid` leaves it retryable) | |
There was a problem hiding this comment.
[Should fix] R1.4 The text here ends with "so the user is rung twice at most". That is not true on head (see R1.1). Other docs still describe the old "rings once" rule:
scheduled_delivery.go:1082(deliverByPhone): "An occurrence rings once ... neither a retry nor a worker taking the run over rings the user again".internal/scheduling/AGENTS.md:145: "A call rings once ... (S5)". Line 152 of the same file: "the give-back of a call not placed".internal/store/scheduled_task_run.go:186(ReleaseCall): "took and could not place".
Fix: once R1.1 is fixed, change each of them to say that a placed call refused while money could not be checked is given back once.
There was a problem hiding this comment.
Fixed in 7b9031c: docs say a placed call refused while money could not be checked is given back once (SKILL.md row, deliverByPhone, callEnded, carryOutAnswered, scheduling/AGENTS.md S5, ReleaseCall).
… back once Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EZsRxWUwySyG1JAn9T7GpE
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EZsRxWUwySyG1JAn9T7GpE
…all counts Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EZsRxWUwySyG1JAn9T7GpE
…iven back once Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EZsRxWUwySyG1JAn9T7GpE
kanat
left a comment
There was a problem hiding this comment.
Delta round 2 of AI-3597 (head 7b9031c, merged onto main 9effc9b): NO-GO, one Should fix.
Prior findings
- R1.1 fixed. Dropping the Final override fails
TestACallWhoseSessionCannotOpenWhileMoneyCannotBeCheckedIsGivenBackOnceandTestACallWhoseTurnIsRefusedAgainOnItsRetryFailsTheRun. My round-1 probe (turn refused, then session open refused) now ends at 2 rings and a thirdTakeCallis refused. - R1.2 fixed. Making the refusal always final fails 3 tests, and the
refusedTurnassert is in place. - R1.3 fixed. Ignoring
answeredfailsTestACallWhoseLaterTurnIsRefusedForMoneyIsDelivered. Restoring the greeting clause survives, and that is equivalent: on a call the greeting isagent.Said, andRespondedcarries a purpose only for text agents (agent.go:1340, 1366). - R1.4 fixed in the docs, but the sentence "rung twice at most" is still false on one path (R2.1).
- R1.5 resolved by the merge order. #2272 and #2277 compose: the code merges clean and both suites pass on the composed tree. Only
.claude/skills/scheduled-tasks/SKILL.mdconflicts (the two money rows), so whichever merges second resolves it.
Suites on head merged onto main: TestTelnyxUnpaidSuite ok, TestScheduledTasksSuite ok.
Mutations: 8 run, 2 survived. The Earlier != "" mutant (R2.1) survives. The other survivor is outside this delta (followUpWithin made non-final, a base line).
Question 2 (money on another channel): not a Should fix. The first transient refusal on the call is final only after an earlier attempt already failed under money, so the run was retried once already. That matches Kanat's rule and is no worse than base.
| } | ||
| // The attempt before this one failed under a money code: its call was given back | ||
| // already, so this one is kept, and the user is rung twice at most. | ||
| if !failure.Final && moneyCode(delivery.Earlier) { |
There was a problem hiding this comment.
R2.1 [Should fix] "Given back once" is keyed on moneyCode(delivery.Earlier), the reason of the last attempt only. The call can ring more than twice when that reason is not a money code. Two ways:
- Channels are [text, call] and the text channel fails first for a non-money reason.
deliverChainrecords the first channel's reason (line 315), so every attempt'sEarlieris that reason while the call keeps being refused for money. A probe over all 4 attempts gives rings=4, every one given back. - An attempt between the two fails before it rings (user on a call, number lookup error, daily tier limit). The next attempt's
Earlieris that reason. A probe gives rings=3.
On base a call failure was always final, so this is new. No test covers it: the Earlier != "" mutant survives.
Fix: make "already given back" a fact about the run, not the last attempt (a per-run flag or counter set by ReleaseCall and read by callEnded; that needs a migration, so the orchestrator decides). The cheaper option is to make Earlier keep a money code over an earlier channel's reason and stay across a pre-ring failure.
Test rows (both fail on head):
callOnplusuncheckable, 4 attempts withEarlier="unreachable": at most 2takeCallsucceed and the second call's failure is final.- Ring, turn refused, an attempt with
Earlier="on_a_call"that does not ring, ring refused again, a fourth attempt: still at most 2 rings.
There was a problem hiding this comment.
Fixed in aca2a3f (code + tests 82e36aa): per the orchestrator decision the give-back is gone. A placed call is rung once: callEnded makes every failure after the call was placed final, so a turn refused while money cannot be checked ends the run under spend_check_unavailable after one ring, refusedTurn true, and the call stays taken on the run. The ReleaseCall path and the _call_r1 rerun are removed. Your two rows are TestACallWhoseTurnIsRefusedIsRungOnceWhateverTheAttemptsBetweenFailedUnder (case b, earlier reason on_a_call) and TestACallWhoseSessionCannotOpenIsRungOnceWhateverTheFirstChannelFailedUnder (case a, earlier reason unreachable); both fail with the previous callEnded restored, together with the two other call tests that assert one ring. Docs (SKILL.md row, AGENTS.md S5, ReleaseCall comment, PR body) now say a placed call is rung once.
…t be checked is final Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EZsRxWUwySyG1JAn9T7GpE
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EZsRxWUwySyG1JAn9T7GpE
kanat
left a comment
There was a problem hiding this comment.
VERDICT: GO (round 3, head aca2a3f merged onto main 6d447f6)
Prior findings
- R2.1 fixed: the give-back and the
_call_r1rerun are gone;callEndedsetsFinalon every failure after the call was placed (scheduled_delivery.go:1257). The transient refusal of an answered turn or of the session open ends the run underspend_check_unavailable, final, after one ring, withrefusedTurntrue (tests...FailsFinalAfterOneRing,...FailsFinal, and the two R2.1 rows for cases a and b). Mutations, one file restored each time: droppingFinal = truefails 4 tests; droppingSetCallReason4; dropping the session-open money branch 3; reading the refusal after an answer 1; never settinganswered1; never reading the turn refusal 3. All killed. - R1.1, R1.2, R1.3, R1.4 stay fixed (R1.1 and the give-back path no longer exist; the
refusedTurnasserts and the docs hold). R1.5 is moot: nothing is given back, so the merge order against #2272 no longer matters for rings.
Orchestrator notes
- A non-money failure after the call was placed: no change from base. Every
*scheduling.Failurethat reachedcallEndedon base was alreadyFinal(carryOutOnCallandholdCalluseundeliveredFinally;carryOutAnsweredreturnsundeliveredFinally(ReasonFailed)or a context error, which is not a Failure and returns early). Sofailure.Final = truechanges only the two new transient money sources. A base retry could not ring again either:TakeCallanswersalready_called. - Dead code: none.
ReleaseCallhas one caller left,deliverByPhoneon a call that was not placed (scheduled_delivery.go:1140, as on base).retried,uncheckableCallare gone; every helper of the suite is still used.rerunSuffix,replyCommandandrefusedAgainstill serve the text, conversation and thread paths. No stale "given back once / rung twice" text left in the docs.
New findings: none.
Run: TestTelnyxUnpaidSuite and TestScheduledTasksSuite pass on the head merged onto main (go test -tags integration -p 1), scheduling and store unit tests pass, gofmt and both go vet clean. CI: the code scanners pass; go and integration skip on a draft.
Details: reviewer-3.md in the ledger.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EZsRxWUwySyG1JAn9T7GpE
## Why The `api` group of Integration (router) does not compile on main since dc88f2f ([run 45350145644](https://github.com/GetStream/Agents/actions/runs/45350145644)): ``` internal/api/scheduled_unpaid_test.go:1200:2: cannot assign to scheduledPhoneWindow (neither addressable nor a map index expression) ``` [#2277](#2277) set the package-level `scheduledPhoneWindow` and `scheduledCallLimit` in `TelnyxUnpaidSuite.callOn`. [#2293](#2293), merged before it, made them constants and moved the values a test changes onto the router. Each passed CI on its own. Until this lands, every PR whose CI runs the `api` group fails. ## Changes - `callOn` sets `s.router.phoneWindow` and `s.router.callLimit` and restores them in its cleanup, as `scheduled_phone_test.go:136-138` does. Test-only. ## Validation - `go vet -tags integration ./internal/api`: compiles. - `go test -tags integration ./internal/api -run TestTelnyxUnpaidSuite -count=1`: ok (99.7 s), including the three tests that go through `callOn`. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Why
A phone task whose call was answered, and whose turn the model then refused for money, said nothing to the user: the agent sat silent on the call until the user hung up or
scheduledCallLimitpassed, and the run settleddeliveredtophone(found in the review of #2191, R1.8). Kanat's money rule for scheduled deliveries (AI-2055, AI-3183) says such a delivery ends failed, final, under the refusal's money code, and a transient money check (spend_check_unavailable) is retried. #2191 did that for the conversation, text and thread channels; this PR applies the same rule to voice (orchestrator ruling on AI-3597, applying Kanat's AI-2055 decision to the placed-call path).Root cause:
carryOutAnswered(acceleration/internal/api/scheduled_delivery.go:1272on dff7498) drained the call session's events and never read them. Theagent.Errorthat a money-refused model call ends a turn with (agent.Agent.fail,internal/agent/agent.go:4816) reached it and was dropped.How it works
It reuses
turnRefusal,unpaidanddeliveryReason; no new helper.callEndedmakes every failure after the call was placed final: a placed call is rung once.Path table
TestAPhoneTaskOfAnOrganizationWithNoCreditIsNotRetried(existing)TestACallWhoseTurnIsRefusedForMoneyFailsUnderTheMoneyspend_check_unavailable, final; agent hangs up; the call stays takenTestACallWhoseTurnIsRefusedWhileMoneyCannotBeCheckedFailsFinalAfterOneRing,TestACallWhoseTurnIsRefusedIsRungOnceWhateverTheAttemptsBetweenFailedUnderspend_check_unavailable, final; the call stays takenTestACallWhoseSessionCannotOpenWhileMoneyCannotBeCheckedFailsFinal,TestACallWhoseSessionCannotOpenIsRungOnceWhateverTheFirstChannelFailedUnderTestACallWhoseSessionCannotOpenForMoneyFailsUnderTheMoneyTestACallWhoseTurnFailsNotForMoneyIsDeliveredTestACallWhoseTurnIsAnsweredIsDeliveredTestACallWhoseLaterTurnIsRefusedForMoneyIsDeliveredA transient money refusal on a placed call is final too (orchestrator decision on AI-3597, round 2): a phone call is the most intrusive channel, a bounded second ring would need a per-run record the scheduler does not have, and two review rounds found paths where the user was rung more than twice. So the call is rung once, whatever refuses it, and every failure not about money keeps the call taken as before (
deliverByPhone, AI-2021).User-facing note
A phone task whose answered call's turn is refused for money no longer keeps the user on a silent call and settles
delivered: the agent hangs up and the run fails under the refusal's code, such asinsufficient_credits, not tried again. Underspend_check_unavailableit fails under that code, final, as well: a placed call is rung once. A placed call whose session cannot open for money fails under the refusal's code too. A refusal after the agent answered on the call is a later turn's, and the task staysdelivered. The scheduled-tasks skill's error table says the same.Validation
TelnyxUnpaidSuite(scheduled_unpaid_test.go): a placed call on a ringing test edge, with the organization's real money state (spent credit; the Redis that holds are shared through taken down).scheduled_delivery.gofrom dff7498), the two refusal tests fail ("the call was never let go") and the three controls pass; on the head all five pass.mut/run.sh,mut/run2.shfor three mutants that did not build or apply on the first pass), run againstTestTelnyxUnpaidSuite -testify.m TestACall:carryOutAnsweredscheduled_delivery.goansweredTestACallWhoseLaterTurnIsRefusedForMoneyIsDeliveredfailed(undeliveredFinally(ReasonFailed, …))answeredset on any event butagent.Respondedagent.Said, neveragent.RespondedRound 0 (orchestrator decisions D1.1, D1.2)
callEnded->ReleaseCall); the retry's turn runs under the rerun's id (replyCommand), and that rerun refused again is final. Mutants killed: never give back, always give back, no rerun id, rerun not final.carryOutOnCall->unpaid). Mutant killed: the money branch removed. A follow-up refused at once for money (followUpWithin) is not changed: no money check runs synchronously inSession.FollowUp, so no such refusal reaches it.Rounds 1 and 2
refusedTurnholds and the walk over the channels ends at the call (asserted inTestACallWhoseTurnIsRefusedForMoneyFailsUnderTheMoney); the greeting clause is dropped (equivalent: on a call the greeting isagent.Said, neveragent.Responded).[text, call]with the text failing first; an attempt between failing before it rang). The give-back and the_call_r1rerun are removed: a call's turn refused for money, transient or final, ends the run final under its money code after one ring (callEnded). TestsTestACallWhoseTurnIsRefusedIsRungOnceWhateverTheAttemptsBetweenFailedUnderandTestACallWhoseSessionCannotOpenIsRungOnceWhateverTheFirstChannelFailedUnderare the reviewer's two rows; the give-back restored makes all four call tests of this PR fail.Merge order
Independent of #2272 (AI-3595) now: the call has no retry, so no earlier reason reaches it. Merge main in before merging.
🤖 Generated with Claude Code
https://claude.ai/code/session_01EZsRxWUwySyG1JAn9T7GpE