Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
d972d89
AI-3595: keep a failed attempt's reason on its run between attempts
kanat Nov 23, 2026
981c0ed
AI-3595: test a run taken over between attempts
kanat Nov 23, 2026
cfc3d8b
AI-3595: document the reason a run keeps between attempts
kanat Nov 23, 2026
2102827
AI-3595: fence an attempt's reason to the run's own task and customer…
kanat Nov 23, 2026
fb8a261
AI-3595: test that a worker closing as its attempt fails still record…
kanat Nov 23, 2026
2ca733a
Merge remote-tracking branch 'origin/main' into kanat/ai-3595-retry-r…
kanat Nov 23, 2026
61913da
AI-3595: a running run between attempts lists no reason
kanat Nov 23, 2026
d7e9822
AI-3595: no CHANGELOG line, the root changelog is written once per re…
kanat Nov 23, 2026
502b8f4
Merge remote-tracking branch 'origin/main' into kanat/ai-3595-retry-r…
kanat Nov 23, 2026
a44f597
Merge remote-tracking branch 'origin/main' into kanat/ai-3595-retry-r…
kanat Nov 23, 2026
d98ca31
AI-3595: taking a call clears the run's earlier attempt reason
kanat Nov 23, 2026
7c21598
AI-3595: SetAttemptReason's doc says what its claim check guarantees
kanat Nov 23, 2026
9a1104e
AI-3595: test that a run held after a failed attempt keeps the attemp…
kanat Nov 23, 2026
1486e79
Merge remote-tracking branch 'origin/main' into kanat/ai-3595-retry-r…
kanat Nov 23, 2026
63f9553
Merge remote-tracking branch 'origin/main' into kanat/ai-3595-retry-r…
kanat Nov 23, 2026
a550c6b
Merge remote-tracking branch 'origin/main' into kanat/ai-3595-retry-r…
kanat Nov 24, 2026
557ac28
AI-3595: port the takeover tests to the scheduler's SetRetries and th…
kanat Nov 24, 2026
f1f3cbe
AI-3595: merge origin/main
kanat Nov 25, 2026
01da879
AI-3595: claim with a ShardClaim in this PR's store tests
kanat Nov 25, 2026
4aca927
AI-3595: build TelnyxUnpaidSuite on main's scheduledOwnerContext
kanat Nov 25, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .claude/skills/scheduled-tasks/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ Run `error` codes (`internal/scheduling/scheduler.go:105`):
| `not_answered` | Nobody picked up within the 90 s ring | no |
| `already_called` | A call was placed for this occurrence already, and its end is not recorded; no channel after `phone` is tried. That call may have carried the task out, so the run leaves the failure streak as it is and the task moves on as after a run that did not fail (a one-shot is `completed`) | no |
| `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 (`captureReply`, which ends the walk over the channels, `refusedTurn`), in the conversation (`followUpInConversation` waits for the turn to end; a turn that ends any other way is still `delivered`) or on a thread task (`deliverOnThread`), 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`, which reads its events), and a refusal after that is a later turn's, still `delivered`. Each reads how the turn ended from the conversation, which keeps the error that failed the reply (`Session.FollowUpFailure`, `turnRefusal`), never from the session's events alone, which a watcher that falls behind loses; a text channel carries only its own follow-up's reply, read back once its turn ends (`readBackReply`). A turn that ended while no attempt watched it, such as one an attempt cut short left running, fails the same way while the session that ran it is still open. That error is kept in memory only: once the conversation is opened again (a restart, a drain, or the end of the session's unwatched grace), the retry reads a bare `failed` and records `reply_failed` on a text channel or a thread, or `delivered` in the conversation (known gap). The run records the refusal's own code (`deliveryReason`, `scheduled_delivery.go:356`), never `channel_unreachable` or `delivery_failed`, and the router warns, naming the task | no (`unpaid`, `scheduled_delivery.go:400`) |
| `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 placed call is rung once: refused this way, its session or its answered turn fails the run under this code, final, with the call kept on the run (`callEnded`), so the user is not rung again | yes (`unpaid` leaves it retryable) |
| `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`) and records it on the run, so a router that takes the run over after a crash or a lost lease reruns the turn too, 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 placed call is rung once: refused this way, its session or its answered turn fails the run under this code, final, with the call kept on the run (`callEnded`), so the user is not rung again | yes (`unpaid` leaves it retryable) |
| `task_paused` | On a `missed` run: a one-shot whose time came while it was paused, or an occurrence the cut-over of a move skipped whose run the source had started | — |

A failure is retried after 30 s, 2 min and 10 min (`deliveryRetries`) only when the failure
Expand All @@ -230,6 +230,7 @@ it also finds the job queue's `Failed to forward scheduled tasks`, which is nois
| `a scheduled task changed under its run; the hold was left alone` | info | `scheduler.go:471` |
| `a scheduled task is held` (with `until`) | info | `scheduler.go:473` |
| `could not renew a scheduled task's lease` | error | `scheduler.go:497` |
| `could not record why a scheduled task's attempt failed` | error | `scheduler.go` (`keepReason`) |
| `could not record a scheduled task run` | error | `scheduler.go:563` |
| `a scheduled task changed under its run; the schedule was left alone` | info | `scheduler.go:565` |
| `could not hand a scheduled task to the node holding its session` | warn | `internal/api/scheduled_delivery.go:577` |
Expand Down
7 changes: 4 additions & 3 deletions acceleration/internal/api/scheduled_delivery.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,8 +97,9 @@ type scheduledDelivery struct {
APIKey string `json:"api_key,omitempty"`
UsageCategories []string `json:"usage_categories,omitempty"`
// Earlier is the reason the occurrence's run records so far (store.ScheduledTaskRun.Error),
// if any: the one its last attempt on this worker failed under (deliverWithRetries), or how a
// call placed for it ended (SetCallReason). replyCommand reads it.
// if any: the one its last attempt failed under (deliverWithRetries, which keeps it on the row
// for a worker that takes the run over), or how a call placed for it ended (SetCallReason).
// replyCommand reads it.
Earlier string `json:"earlier,omitempty"`
}

Expand All @@ -116,7 +117,7 @@ func (d scheduledDelivery) attribution() routing.Attribution {

// scheduledHandOff is what a peer reads of a scheduledDelivery it is handed: the ids that
// name the task's occurrence and its owner, which it checks against the rows, and the reason
// the asker's last attempt failed under, which the run's row does not hold between attempts.
// the asker's last attempt failed under, as the asker read it from its claim.
// Nothing else the asker sends reaches the delivery, so a payload cannot name another
// conversation, zone, key, prompt or due time. An asker sends the whole scheduledDelivery, so
// routers on either side of this change still hand off to each other.
Expand Down
28 changes: 28 additions & 0 deletions acceleration/internal/api/scheduled_phone_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -421,6 +421,34 @@ func (s *ScheduledTasksSuite) TestAnOccurrenceTakenOverAfterItsCallWasPlacedIsNo
s.Zero(stored.ConsecutiveFailures)
}

// An earlier attempt failed before it rang (its reason is on the run), the next one placed the
// call, and its worker stopped mid-call: the reason of the failed attempt is not the call's, so
// the worker taking over ends as already called and texts nothing (AI-2021).
func (s *ScheduledTasksSuite) TestAnOccurrenceTakenOverMidCallAfterAFailedAttemptIsNotTextedToo() {
s.retryLate()
user := s.data.createUser()
due := time.Now().Add(-14 * time.Minute).UTC().Truncate(time.Second)
task := s.phoneTask(user, []string{"phone", "sms"}, due)
s.ranAlready(task, due, nil, "")
runID := s.runsOf(task)[0].ID
_, err := s.store.GlobalDB().ExecContext(context.Background(),
"UPDATE scheduled_tasks SET leased_by = 'worker-a', lease_until = now() - interval '1 minute' WHERE customer_id = ? AND id = ?",
task.CustomerID, task.ID)
s.Require().NoError(err)
s.Require().NoError(s.store.ScheduledTaskRuns.SetAttemptReason(context.Background(), task.CustomerID, runID, "worker-a", scheduling.ReasonTierLimit))
took, _, err := s.store.ScheduledTaskRuns.TakeCall(context.Background(), task.CustomerID, runID, "the-earlier-call")
s.Require().NoError(err)
s.Require().True(took)
s.runWorker()

run := s.settledRun(task)
s.Require().Equal(store.ScheduledTaskRunFailed, run.State)
s.Require().NotNil(run.Error)
s.Equal(scheduling.ReasonRungAlready, *run.Error, "not the reason the earlier attempt failed under")
s.Empty(run.DeliveredTo)
s.Empty(s.sink.to(s.numberRungFor(task)), "the user was rung for this occurrence, so it is not texted too")
}

// A channel before the call failing does not hide the call: the run says
// already_called, so the occurrence is not counted a failure.
func (s *ScheduledTasksSuite) TestAnOccurrenceThatRangAlreadyAfterAFailedChannelIsNotCountedFailed() {
Expand Down
6 changes: 6 additions & 0 deletions acceleration/internal/api/scheduled_tasks.go
Original file line number Diff line number Diff line change
Expand Up @@ -829,6 +829,12 @@ func scheduledTaskRunOf(task store.ScheduledTask, run store.ScheduledTaskRun) Sc
if err != nil {
loc = time.UTC
}
// A running run's error is the reason its last attempt failed under, kept for a worker that
// takes the run over (ScheduledTaskRuns.SetAttemptReason): not listed, as nothing has failed
// the run yet. A placed call's reason is (SetCallReason).
if run.State == store.ScheduledTaskRunRunning && run.SessionID == "" {
run.Error = nil
}
return ScheduledTaskRun{
Id: run.ID, TaskId: run.TaskID,
ScheduledFor: run.ScheduledFor.In(loc).Format(time.RFC3339),
Expand Down
25 changes: 25 additions & 0 deletions acceleration/internal/api/scheduled_tasks_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3274,6 +3274,31 @@ func utcTaskRequest(config string) CreateScheduledTaskRequest {
return body
}

func (s *ScheduledTasksSuite) TestARunningRunBetweenAttemptsListsNoReasonUntilItSettles() {
config := s.agentWithScheduling(nil)
user := s.data.createUser()
between := s.createTask(user, utcTaskRequest(config))
called := s.createTask(user, utcTaskRequest(config))
now := time.Now().UTC().Truncate(time.Second)
retry, ended := "spend_check_unavailable", scheduling.ReasonNoReply
for _, run := range []store.ScheduledTaskRun{
{TaskID: between.Id, State: store.ScheduledTaskRunRunning, Attempts: 1, Error: &retry},
{TaskID: called.Id, State: store.ScheduledTaskRunRunning, Attempts: 1, SessionID: "call-1", Error: &ended},
} {
run.CustomerID, run.ScheduledFor, run.StartedAt = s.customerID(), now, &now
s.Require().NoError(s.store.ScheduledTaskRuns.Insert(context.Background(), &run))
}

var page ScheduledTaskRunPage
s.Require().Equal(http.StatusOK, user.do(http.MethodGet, "/v1/agents/scheduled-tasks/"+between.Id+"/runs", nil, &page))
s.Require().Len(page.Items, 1)
s.Nil(page.Items[0].Error, "the reason an attempt failed under is kept for a takeover, not listed while the run runs")

s.Require().Equal(http.StatusOK, user.do(http.MethodGet, "/v1/agents/scheduled-tasks/"+called.Id+"/runs", nil, &page))
s.Require().Len(page.Items, 1)
s.Equal(&ended, page.Items[0].Error, "how a placed call ended is listed, as before")
}

func (s *ScheduledTasksSuite) TestRunningATaskByHandDeliversWithoutMovingTheSchedule() {
config := s.agentWithScheduling(nil)
user := s.data.createUser()
Expand Down
Loading
Loading