From d972d8958d353dfa6ab878e292b5cedb059e9b72 Mon Sep 17 00:00:00 2001 From: Kanat Date: Mon, 23 Nov 2026 18:32:58 +0100 Subject: [PATCH 01/13] AI-3595: keep a failed attempt's reason on its run between attempts Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EZsRxWUwySyG1JAn9T7GpE --- acceleration/internal/scheduling/scheduler.go | 21 +++++++++++++--- acceleration/internal/store/scheduled_task.go | 7 ++++++ .../internal/store/scheduled_task_run.go | 25 +++++++++++++++++++ 3 files changed, 50 insertions(+), 3 deletions(-) diff --git a/acceleration/internal/scheduling/scheduler.go b/acceleration/internal/scheduling/scheduler.go index 425cca4f0e..ad5975bf0d 100644 --- a/acceleration/internal/scheduling/scheduler.go +++ b/acceleration/internal/scheduling/scheduler.go @@ -476,6 +476,11 @@ func (s *Scheduler) deliverWithRetries(ctx, draining context.Context, claim stor if err == nil || errors.As(err, &held) || final(err) { return deliveredTo, sessionID, err } + // The next attempt reads the reason this one failed under as the run's, as a worker + // taking the run over reads how its call ended (store.ScheduledTaskRuns.TakeCall). The + // row keeps it too, for a worker that takes the run over during the wait. + reason := ReasonOf(err) + s.keepReason(claim, reason) timer := time.NewTimer(wait) select { case <-draining.Done(): @@ -487,9 +492,6 @@ func (s *Scheduler) deliverWithRetries(ctx, draining context.Context, claim stor case <-timer.C: } earlier := err - // The next attempt reads the reason this one failed under as the run's, as a worker - // taking the run over reads how its call ended (store.ScheduledTaskRuns.TakeCall). - reason := ReasonOf(earlier) claim.Run.Error = &reason deliveredTo, sessionID, err = s.deliver(ctx, claim) err = rungEarlier(earlier, err) @@ -497,6 +499,19 @@ func (s *Scheduler) deliverWithRetries(ctx, draining context.Context, claim stor return deliveredTo, sessionID, err } +// keepReason records on claim's run the reason its attempt failed under, before the wait for the +// next attempt: a router that stops or loses the lease meanwhile leaves the run to another worker, +// which rebuilds the delivery from the row. A write that fails leaves that worker no reason, as +// before the write was made, and this worker's next attempt reads it from memory still. +func (s *Scheduler) keepReason(claim store.ClaimedScheduledTask, reason string) { + ctx, cancel := context.WithTimeout(context.WithoutCancel(s.ctx), 15*time.Second) + defer cancel() + if err := s.store.ScheduledTaskRuns.SetAttemptReason(ctx, claim.Task.CustomerID, claim.Run.ID, claim.LeasedBy, reason); err != nil { + s.logger.Error("could not record why a scheduled task's attempt failed", + "task", claim.Task.ID, "run", claim.Run.ID, "customer", claim.Task.CustomerID, "error", err) + } +} + // rungEarlier is a later attempt's failure, kept under the reason the earlier // attempt failed under when the later one found the occurrence's call placed // already: that call is the earlier attempt's, and how it went (nobody diff --git a/acceleration/internal/store/scheduled_task.go b/acceleration/internal/store/scheduled_task.go index ad42cde746..9b334258c0 100644 --- a/acceleration/internal/store/scheduled_task.go +++ b/acceleration/internal/store/scheduled_task.go @@ -329,6 +329,11 @@ func (r *ScheduledTasks) Select(ctx context.Context, customerID string, filter S return tasks, nil } +// missedRunError is the error a running run keeps when a pause or an edit settles it missed: the +// reason a placed call ended under stays, and a failed attempt's (ScheduledTaskRuns.SetAttemptReason) +// goes, since nothing failed the occurrence. +const missedRunError = "error = CASE WHEN session_id = '' THEN NULL ELSE error END" + // Update replaces a task's editable fields and clears any claim, so // a worker finishing an older claim cannot advance what this save changed. // An occurrence still running (held by quiet hours, or cut short when its @@ -388,6 +393,7 @@ func (r *ScheduledTasks) Update(ctx context.Context, task *ScheduledTask) error settle := tx.NewUpdate().Model((*ScheduledTaskRun)(nil)). Set("state = ?", ScheduledTaskRunMissed). Set("finished_at = now()"). + Set(missedRunError). Where("customer_id = ?", task.CustomerID). Where("task_id = ?", task.ID). Where("trigger = ?", ScheduledTaskTriggerSchedule). @@ -1007,6 +1013,7 @@ func (r *ScheduledTasks) PauseForConfig(ctx context.Context, customerID, configI if _, err := tx.NewUpdate().Model((*ScheduledTaskRun)(nil)). Set("state = ?", ScheduledTaskRunMissed). Set("finished_at = now()"). + Set(missedRunError). Where("customer_id = ?", customerID). Where("task_id IN (?)", bun.In(paused)). Where("trigger = ?", ScheduledTaskTriggerSchedule). diff --git a/acceleration/internal/store/scheduled_task_run.go b/acceleration/internal/store/scheduled_task_run.go index 9cb2ca8d6d..d06eca70c1 100644 --- a/acceleration/internal/store/scheduled_task_run.go +++ b/acceleration/internal/store/scheduled_task_run.go @@ -183,6 +183,31 @@ func (r *ScheduledTaskRuns) SetCallReason(ctx context.Context, customerID, runID return nil } +// SetAttemptReason records on a running run the reason an attempt failed under, for the +// attempt after it: a worker that takes the run over reads it from the row, as the worker that +// made the attempt reads it from memory. It writes only under the claim leasedBy, so a worker +// that lost its claim cannot overwrite the next one's, and only while no call is placed for the +// run: the reason that call ended under is the run's (SetCallReason). +func (r *ScheduledTaskRuns) SetAttemptReason(ctx context.Context, customerID, runID, leasedBy, reason string) error { + claimed := r.store.global.NewSelect().Model((*ScheduledTask)(nil)). + ColumnExpr("1"). + Where("st.customer_id = str.customer_id"). + Where("st.id = str.task_id"). + Where("st.leased_by = ?", leasedBy) + _, err := r.store.global.NewUpdate().Model((*ScheduledTaskRun)(nil)). + Set("error = ?", reason). + Where("customer_id = ?", customerID). + Where("id = ?", runID). + Where("state = ?", ScheduledTaskRunRunning). + Where("session_id = ''"). + Where("EXISTS (?)", claimed). + Exec(ctx) + if err != nil { + return stack.Wrap(fmt.Errorf("store: set scheduled task run attempt reason: %w", err)) + } + return nil +} + // ReleaseCall gives back a call TakeCall // took and could not place, so a later attempt may ring. func (r *ScheduledTaskRuns) ReleaseCall(ctx context.Context, customerID, runID, sessionID string) error { From 981c0edb35a190cceab537c078ec2d55f01576fa Mon Sep 17 00:00:00 2001 From: Kanat Date: Mon, 23 Nov 2026 18:37:46 +0100 Subject: [PATCH 02/13] AI-3595: test a run taken over between attempts Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EZsRxWUwySyG1JAn9T7GpE --- .../internal/api/scheduled_unpaid_test.go | 123 ++++++++++++++++++ .../internal/scheduling/scheduler_test.go | 79 +++++++++++ .../internal/store/scheduled_task_run_test.go | 80 ++++++++++++ .../internal/store/scheduled_task_test.go | 53 ++++++++ 4 files changed, 335 insertions(+) diff --git a/acceleration/internal/api/scheduled_unpaid_test.go b/acceleration/internal/api/scheduled_unpaid_test.go index 7c61b1dd8b..96369e06d4 100644 --- a/acceleration/internal/api/scheduled_unpaid_test.go +++ b/acceleration/internal/api/scheduled_unpaid_test.go @@ -133,6 +133,69 @@ func (s *TelnyxUnpaidSuite) settledByTheWorkerAfter(task store.ScheduledTask, be return settled, attempts.Load() } +// takenOver makes task due and has a worker fail its first attempt, then stops that worker while +// it waits to retry, as a router that crashes or loses its lease leaves the run. between runs +// next; then the run goes stale and a second worker, retrying at once, takes it over. It returns +// the settled run and how many attempts the second worker made. +func (s *TelnyxUnpaidSuite) takenOver(task store.ScheduledTask, between func()) (store.ScheduledTaskRun, int32) { + var failed atomic.Int32 + retries := scheduling.DeliveryRetries + scheduling.DeliveryRetries = []time.Duration{time.Hour} + lost := scheduling.NewScheduler(s.store, func(ctx context.Context, claimed store.ClaimedScheduledTask) (string, string, error) { + deliveredTo, sessionID, err := s.router.DeliverScheduledTask(ctx, claimed) + if err != nil { + failed.Add(1) + } + return deliveredTo, sessionID, err + }, slog.New(slog.NewTextHandler(s.logged, nil))) + scheduling.DeliveryRetries = retries + past := time.Now().Add(-time.Minute) + task.NextRunAt = &past + s.Require().NoError(s.store.ScheduledTasks.Update(context.Background(), &task)) + lost.Start(context.Background()) + lost.Kick() + s.Require().Eventually(func() bool { + return failed.Load() == 1 && lost.Running() == 1 + }, deliveryWait, 20*time.Millisecond, "the first attempt failed and the delivery waits to retry") + lost.Close() + if between != nil { + between() + } + _, err := s.store.GlobalDB().NewUpdate().Model((*store.ScheduledTaskRun)(nil)). + Set("started_at = now() - interval '1 hour'"). + Where("task_id = ?", task.ID). + Where("state = ?", store.ScheduledTaskRunRunning). + Exec(context.Background()) + s.Require().NoError(err) + _, err = s.store.GlobalDB().NewUpdate().Model((*store.ScheduledTask)(nil)). + Set("lease_until = now() - interval '1 second'"). + Where("customer_id = ?", task.CustomerID). + Where("id = ?", task.ID). + Exec(context.Background()) + s.Require().NoError(err) + + s.retryAtOnce() + var attempts atomic.Int32 + worker := scheduling.NewScheduler(s.store, func(ctx context.Context, claimed store.ClaimedScheduledTask) (string, string, error) { + attempts.Add(1) + return s.router.DeliverScheduledTask(ctx, claimed) + }, slog.New(slog.NewTextHandler(s.logged, nil))) + worker.Start(context.Background()) + defer worker.Close() + worker.Kick() + var settled store.ScheduledTaskRun + s.Require().Eventually(func() bool { + runs, err := s.store.ScheduledTaskRuns.Select(context.Background(), task.CustomerID, store.ScheduledTaskRunFilter{TaskID: task.ID, Limit: 25}) + s.Require().NoError(err) + if len(runs) != 1 || runs[0].State == store.ScheduledTaskRunRunning { + return false + } + settled = runs[0] + return true + }, deliveryWait, 20*time.Millisecond, "the task's run never settled") + return settled, attempts.Load() +} + // A task made in a thread of a suspended organization texts nothing and is not tried again: the // run says the account is suspended, and the router warns, naming the customer. func (s *TelnyxUnpaidSuite) TestAThreadTaskOfASuspendedOrganizationIsNotRetried() { @@ -662,6 +725,66 @@ func (s *TelnyxUnpaidSuite) TestAConversationTurnRefusedOnAnotherRouterRunsAgain s.NotEmpty(said, "the user got a reply") } +// A conversation task whose turn is refused because the money cannot be checked, and whose worker +// stops while it waits to retry, runs its turn again on the worker that takes the run over once the +// check passes: that worker reads the refusal from the run, and the user gets the reply. +func (s *TelnyxUnpaidSuite) TestAConversationTurnRefusedWhileMoneyCannotBeCheckedRunsAgainForTheWorkerTakingItOver() { + user, opened := s.uncheckableAfterOpening() + task := s.userTask(user, opened.Id, "conversation") + + run, attempts := s.takenOver(task, s.sharedAgain) + + s.Equal(store.ScheduledTaskRunDelivered, run.State) + s.Equal(store.ScheduledTaskDeliveredConversation, run.DeliveredTo) + s.Nil(run.Error) + s.Equal(int32(1), attempts) + found, running := s.router.sessions.Get(opened.Id, session.Owner{CustomerID: s.customerID(), UserID: user.userID, Kind: auth.KindAuthenticated}) + s.Require().True(running) + refused, _, _ := found.FollowUpReply(conversation.ReadBackPrefix + run.ID) + s.Equal("failed", refused, "the first turn was refused") + state, said, _ := found.FollowUpReply(conversation.ReadBackPrefix + run.ID + rerunSuffix) + s.Equal("completed", state, "the worker taking over ran the turn again") + s.NotEmpty(said, "the user got a reply") +} + +// A conversation task whose session another router holds, whose turn there is refused because the +// money cannot be checked and whose worker stops while it waits to retry: the worker taking the run +// over hands that router the refusal, and the turn runs again there. +func (s *TelnyxUnpaidSuite) TestAConversationTurnRefusedOnAnotherRouterRunsAgainThereForTheWorkerTakingItOver() { + other, _, sessions := s.otherNodeHolding(nil, s.sealer, slog.New(slog.DiscardHandler)) + user, opened := s.uncheckableAfterOpeningOn(other) + task := s.userTask(user, opened.Id, "conversation") + + run, attempts := s.takenOver(task, s.sharedAgain) + + s.Equal(store.ScheduledTaskRunDelivered, run.State) + s.Equal(int32(1), attempts) + found, running := sessions.Get(opened.Id, session.Owner{CustomerID: s.customerID(), UserID: user.userID, Kind: auth.KindAuthenticated}) + s.Require().True(running, "the session is the other router's") + state, said, _ := found.FollowUpReply(conversation.ReadBackPrefix + run.ID + rerunSuffix) + s.Equal("completed", state, "the turn ran again on the router holding the session") + s.NotEmpty(said, "the user got a reply") +} + +// A text task whose turn fails for a reason that is not money, and whose worker stops while it +// waits to retry, reads that reply back on the worker that takes the run over, as on its own +// retries: the turn is not run again, and the run fails as a reply that failed. +func (s *TelnyxUnpaidSuite) TestATextTurnFailedNotForMoneyIsNotRunAgainByTheWorkerTakingItOver() { + user, opened := s.creditedOpening("failing/failing-model") + task := s.userTask(user, opened.Id, "sms") + + run, attempts := s.takenOver(task, nil) + + s.Equal(store.ScheduledTaskRunFailed, run.State) + s.Require().NotNil(run.Error) + s.Equal(scheduling.ReasonReplyFailed, *run.Error) + s.Equal(int32(1+len(scheduling.DeliveryRetries)), attempts) + found, running := s.router.sessions.Get(opened.Id, session.Owner{CustomerID: s.customerID(), UserID: user.userID, Kind: auth.KindAuthenticated}) + s.Require().True(running) + _, _, rerun := found.FollowUpReply(conversation.ReadBackPrefix + run.ID + rerunSuffix) + s.False(rerun, "a reply that failed not for money is not run again") +} + // A thread task whose reply failed, retried after a refusal for money, runs its turn again in the // thread under the rerun's command id, as the conversation and the text channels do. func (s *TelnyxUnpaidSuite) TestAThreadRetryAfterARefusalForMoneyRunsTheTurnAgain() { diff --git a/acceleration/internal/scheduling/scheduler_test.go b/acceleration/internal/scheduling/scheduler_test.go index 02f5be067b..f4d055d1f8 100644 --- a/acceleration/internal/scheduling/scheduler_test.go +++ b/acceleration/internal/scheduling/scheduler_test.go @@ -993,6 +993,85 @@ func (s *SchedulerSuite) TestADrainStopsARetryWaitAndLeavesTheRunToItsLease() { s.Len(other.callsFor(task.ID), 1) } +// lostDuringItsRetryWait has a worker fail task's first attempt with failure, then stops it while +// it waits to retry, as a router that crashes or loses its lease leaves the run. Before the +// failure, first runs on the attempt's claim. It returns the deliveries a second worker made once +// the run went stale and it took the run over. +func (s *SchedulerSuite) lostDuringItsRetryWait(task store.ScheduledTask, failure error, first func(store.ClaimedScheduledTask)) []store.ClaimedScheduledTask { + var attempts atomic.Int32 + lost := NewScheduler(s.db, func(ctx context.Context, claimed store.ClaimedScheduledTask) (string, string, error) { + if claimed.Task.ID != task.ID { + return "conversation", claimed.Task.SessionID, nil + } + attempts.Add(1) + if first != nil { + first(claimed) + } + return "", "", failure + }, slog.New(slog.DiscardHandler)) + lost.retries = []time.Duration{time.Hour} + lost.Start(s.ctx) + s.Require().Eventually(func() bool { + return attempts.Load() == 1 && lost.Running() == 1 + }, 10*time.Second, 10*time.Millisecond, "the first attempt failed and the delivery waits to retry") + lost.Close() + runs := s.runs(task) + s.Require().Len(runs, 1) + s.Require().Equal(store.ScheduledTaskRunRunning, runs[0].State, "the run is left to its lease") + + // The run ages past the store's stale-run time and its lease lapses, as the stopped worker + // leaves them. + _, err := s.db.GlobalDB().NewUpdate().Model((*store.ScheduledTaskRun)(nil)). + Set("started_at = now() - interval '1 hour'"). + Where("id = ?", runs[0].ID). + Exec(s.ctx) + s.Require().NoError(err) + _, err = s.db.GlobalDB().NewUpdate().Model((*store.ScheduledTask)(nil)). + Set("lease_until = now() - interval '1 second'"). + Where("customer_id = ?", task.CustomerID). + Where("id = ?", task.ID). + Exec(s.ctx) + s.Require().NoError(err) + other := &deliverer{} + s.started(other.deliver, nil) + s.Require().Eventually(func() bool { + return s.read(task).State == store.ScheduledTaskCompleted + }, 10*time.Second, 10*time.Millisecond, "another worker delivers the occurrence") + s.EqualValues(1, attempts.Load(), "the stopped worker made no retry") + calls := other.callsFor(task.ID) + s.Require().Len(calls, 1) + s.Equal(runs[0].ID, calls[0].Run.ID, "under the same run") + return calls +} + +func (s *SchedulerSuite) TestAWorkerTakingARunOverReadsTheReasonItsLastAttemptFailedUnder() { + task := s.task(time.Now().UTC().Add(-time.Minute).Truncate(time.Second), nil) + + calls := s.lostDuringItsRetryWait(task, &Failure{Reason: ReasonOnACall, Err: errors.New("the user is on a call")}, nil) + + s.Require().NotNil(calls[0].Run.Error, "the delivery is rebuilt with the reason the last attempt failed under") + s.Equal(ReasonOnACall, *calls[0].Run.Error) + s.Nil(s.runs(task)[0].Error, "a delivered run says nothing failed") +} + +func (s *SchedulerSuite) TestAWorkerTakingARunOverAfterItsCallReadsHowTheCallEnded() { + task := s.task(time.Now().UTC().Add(-time.Minute).Truncate(time.Second), nil) + // A [phone, whatsapp] task: nobody answered the call, and WhatsApp failed too. It runs on the + // worker's goroutine, so it checks without stopping the test there. + called := func(claimed store.ClaimedScheduledTask) { + call := "call-" + uuid.NewString() + took, _, err := s.db.ScheduledTaskRuns.TakeCall(s.ctx, task.CustomerID, claimed.Run.ID, call) + s.NoError(err) + s.True(took) + s.NoError(s.db.ScheduledTaskRuns.SetCallReason(s.ctx, task.CustomerID, claimed.Run.ID, call, ReasonNotAnswered)) + } + + calls := s.lostDuringItsRetryWait(task, &Failure{Reason: ReasonUnreachable, Err: errors.New("whatsapp: no window")}, called) + + s.Require().NotNil(calls[0].Run.Error) + s.Equal(ReasonNotAnswered, *calls[0].Run.Error, "how the call ended is the run's reason, as before") +} + func (s *SchedulerSuite) TestADrainLetsARetryAttemptInFlightFinish() { due := time.Now().UTC().Add(-time.Minute).Truncate(time.Second) task := s.task(due, nil) diff --git a/acceleration/internal/store/scheduled_task_run_test.go b/acceleration/internal/store/scheduled_task_run_test.go index 95d4f33f39..c9423dcfb8 100644 --- a/acceleration/internal/store/scheduled_task_run_test.go +++ b/acceleration/internal/store/scheduled_task_run_test.go @@ -96,6 +96,83 @@ func (s *StoreSuite) TestARunsCallKeepsTheReasonItEndedUnderForTheWorkerTakingIt s.Equal("not_answered", reason, "the taking over keeps how the call went") } +// staleRun ages a claimed run past the stale window and lapses its task's lease, as a worker that +// died leaves them, and returns the claim that takes the run over. +func (s *StoreSuite) staleRun(taskID, runID string) ClaimedScheduledTask { + _, err := s.store.global.NewUpdate().Model((*ScheduledTaskRun)(nil)). + Set("started_at = ?", s.base.Add(-time.Hour)). + Where("id = ?", runID).Exec(s.ctx) + s.Require().NoError(err) + _, err = s.store.global.NewUpdate().Model((*ScheduledTask)(nil)). + Set("lease_until = ?", s.base.Add(-time.Minute)). + Where("id = ?", taskID).Exec(s.ctx) + s.Require().NoError(err) + reclaimed, err := s.store.ScheduledTasks.Claim(s.ctx, 16, time.Minute) + s.Require().NoError(err) + s.Require().Len(reclaimed, 1) + s.Require().Equal(runID, reclaimed[0].Run.ID, "taken over under the same run") + return reclaimed[0] +} + +func (s *StoreSuite) TestAnAttemptsReasonIsReadByTheWorkerTakingTheRunOver() { + due := s.base.Add(-time.Minute) + s.task("one", func(task *ScheduledTask) { task.NextRunAt = &due }) + claimed, err := s.store.ScheduledTasks.Claim(s.ctx, 16, time.Minute) + s.Require().NoError(err) + s.Require().Len(claimed, 1) + run := claimed[0].Run + s.Nil(run.Error, "a new run has no reason") + // Only the claim that holds the task, on the customer's own run, records a reason. + s.Require().NoError(s.store.ScheduledTaskRuns.SetAttemptReason(s.ctx, "acme", run.ID, "a-lost-claim", "user_on_call")) + s.Require().NoError(s.store.ScheduledTaskRuns.SetAttemptReason(s.ctx, "globex", run.ID, claimed[0].LeasedBy, "user_on_call")) + s.Nil(s.run(run.ID).Error) + + s.Require().NoError(s.store.ScheduledTaskRuns.SetAttemptReason(s.ctx, "acme", run.ID, claimed[0].LeasedBy, "spend_check_unavailable")) + reclaimed := s.staleRun("one", run.ID) + + s.Require().NotNil(reclaimed.Run.Error) + s.Equal("spend_check_unavailable", *reclaimed.Run.Error, "the worker taking over reads why the last attempt failed") + s.Require().NoError(s.store.ScheduledTaskRuns.SetAttemptReason(s.ctx, "acme", run.ID, claimed[0].LeasedBy, "user_on_call")) + s.Equal("spend_check_unavailable", *s.run(run.ID).Error, "the claim taken over records nothing more") +} + +func (s *StoreSuite) TestAnAttemptsReasonLeavesTheReasonAPlacedCallEndedUnder() { + due := s.base.Add(-time.Minute) + s.task("one", func(task *ScheduledTask) { task.NextRunAt = &due }) + claimed, err := s.store.ScheduledTasks.Claim(s.ctx, 16, time.Minute) + s.Require().NoError(err) + s.Require().Len(claimed, 1) + run := claimed[0].Run + took, _, err := s.store.ScheduledTaskRuns.TakeCall(s.ctx, "acme", run.ID, "call-1") + s.Require().NoError(err) + s.Require().True(took) + s.Require().NoError(s.store.ScheduledTaskRuns.SetCallReason(s.ctx, "acme", run.ID, "call-1", "not_answered")) + + s.Require().NoError(s.store.ScheduledTaskRuns.SetAttemptReason(s.ctx, "acme", run.ID, claimed[0].LeasedBy, "channel_unreachable")) + + took, reason, err := s.store.ScheduledTaskRuns.TakeCall(s.ctx, "acme", run.ID, "call-2") + s.Require().NoError(err) + s.False(took) + s.Equal("not_answered", reason, "how the call ended is the run's reason") +} + +func (s *StoreSuite) TestAFinishedRunTakesNoAttemptsReason() { + due := s.base.Add(-time.Minute) + s.task("one", func(task *ScheduledTask) { task.NextRunAt = &due }) + claimed, err := s.store.ScheduledTasks.Claim(s.ctx, 16, time.Minute) + s.Require().NoError(err) + s.Require().Len(claimed, 1) + run := claimed[0].Run + _, err = s.store.global.NewUpdate().Model((*ScheduledTaskRun)(nil)). + Set("state = ?", ScheduledTaskRunDelivered). + Where("id = ?", run.ID).Exec(s.ctx) + s.Require().NoError(err) + + s.Require().NoError(s.store.ScheduledTaskRuns.SetAttemptReason(s.ctx, "acme", run.ID, claimed[0].LeasedBy, "user_on_call")) + + s.Nil(s.run(run.ID).Error, "a delivered run says nothing failed") +} + func (s *StoreSuite) TestTheLastRunOfEveryTaskIsReadAtOnce() { for _, id := range []string{"one", "two", "three", "four"} { s.task(id, nil) @@ -152,6 +229,9 @@ func (s *StoreSuite) TestScheduledTaskRunQueryBudgets() { s.Equal(1, s.countQueries(func() { s.Require().NoError(s.store.ScheduledTaskRuns.ReleaseCall(s.ctx, "acme", run.ID, "call-1")) }), "ReleaseCall") + s.Equal(1, s.countQueries(func() { + s.Require().NoError(s.store.ScheduledTaskRuns.SetAttemptReason(s.ctx, "acme", run.ID, "claim-1", "user_on_call")) + }), "SetAttemptReason") s.Equal(1, s.countQueries(func() { s.Require().NoError(s.store.ScheduledTaskRuns.FinishManual(s.ctx, run.CustomerID, run.ID, ScheduledTaskRunDelivered, "conversation", "session-1", "")) }), "FinishManual") diff --git a/acceleration/internal/store/scheduled_task_test.go b/acceleration/internal/store/scheduled_task_test.go index 84c31920a5..f0a09ce27c 100644 --- a/acceleration/internal/store/scheduled_task_test.go +++ b/acceleration/internal/store/scheduled_task_test.go @@ -927,6 +927,59 @@ func (s *StoreSuite) TestDeletingAConfigPausesOnlyItsActiveTasks() { s.Equal(ScheduledTaskActive, other.State, "another customer's config of the same id is not this one") } +// retryingRuns claims two due tasks between attempts: "failed", whose attempt failed and is +// recorded, and "called", whose call nobody answered. It returns their runs by task. +func (s *StoreSuite) retryingRuns() map[string]ScheduledTaskRun { + due := s.base.Add(-time.Minute) + s.task("failed", func(task *ScheduledTask) { task.NextRunAt = &due }) + s.task("called", func(task *ScheduledTask) { task.NextRunAt = &due }) + claimed, err := s.store.ScheduledTasks.Claim(s.ctx, 16, time.Minute) + s.Require().NoError(err) + s.Require().Len(claimed, 2) + runs := map[string]ScheduledTaskRun{} + for _, claim := range claimed { + runs[claim.Task.ID] = claim.Run + if claim.Task.ID == "called" { + took, _, err := s.store.ScheduledTaskRuns.TakeCall(s.ctx, "acme", claim.Run.ID, "call-1") + s.Require().NoError(err) + s.Require().True(took) + s.Require().NoError(s.store.ScheduledTaskRuns.SetCallReason(s.ctx, "acme", claim.Run.ID, "call-1", "not_answered")) + } + s.Require().NoError(s.store.ScheduledTaskRuns.SetAttemptReason(s.ctx, "acme", claim.Run.ID, claim.LeasedBy, "user_on_call")) + } + return runs +} + +// settledWithoutTheAttemptsReason checks runs from retryingRuns once a change settled them missed. +func (s *StoreSuite) settledWithoutTheAttemptsReason(runs map[string]ScheduledTaskRun) { + failed, called := s.run(runs["failed"].ID), s.run(runs["called"].ID) + s.Equal(ScheduledTaskRunMissed, failed.State) + s.Nil(failed.Error, "a missed run did not fail: the attempt's reason goes") + s.Equal(ScheduledTaskRunMissed, called.State) + s.Require().NotNil(called.Error) + s.Equal("not_answered", *called.Error, "how the call ended stays") +} + +func (s *StoreSuite) TestAPausedRunBetweenAttemptsIsMissedWithoutTheAttemptsReason() { + runs := s.retryingRuns() + for _, id := range []string{"failed", "called"} { + task, err := s.store.ScheduledTasks.Get(s.ctx, "acme", id) + s.Require().NoError(err) + task.State = ScheduledTaskPaused + s.Require().NoError(s.store.ScheduledTasks.Update(s.ctx, &task)) + } + + s.settledWithoutTheAttemptsReason(runs) +} + +func (s *StoreSuite) TestADeletedConfigsRunBetweenAttemptsIsMissedWithoutTheAttemptsReason() { + runs := s.retryingRuns() + + s.Require().NoError(s.store.ScheduledTasks.PauseForConfig(s.ctx, "acme", "config-1")) + + s.settledWithoutTheAttemptsReason(runs) +} + func (s *StoreSuite) TestDeletingAConfigWritesItsTasksHeldOccurrenceMissed() { due := s.base.Add(-time.Minute) s.task("one", func(task *ScheduledTask) { task.NextRunAt = &due }) From cfc3d8b1b41f67f3089f31f7f67da38de95bc7ad Mon Sep 17 00:00:00 2001 From: Kanat Date: Mon, 23 Nov 2026 18:40:05 +0100 Subject: [PATCH 03/13] AI-3595: document the reason a run keeps between attempts Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EZsRxWUwySyG1JAn9T7GpE --- .claude/skills/scheduled-tasks/SKILL.md | 3 ++- CHANGELOG.md | 4 ++++ acceleration/internal/api/scheduled_delivery.go | 7 ++++--- acceleration/internal/scheduling/AGENTS.md | 17 +++++++++++++++-- 4 files changed, 25 insertions(+), 6 deletions(-) diff --git a/.claude/skills/scheduled-tasks/SKILL.md b/.claude/skills/scheduled-tasks/SKILL.md index 1cf299b9fa..f1589205a3 100644 --- a/.claude/skills/scheduled-tasks/SKILL.md +++ b/.claude/skills/scheduled-tasks/SKILL.md @@ -202,7 +202,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 (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__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) | +| `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__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 | 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 @@ -224,6 +224,7 @@ last; it also finds the job queue's `Failed to forward scheduled tasks`, which i | `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` | diff --git a/CHANGELOG.md b/CHANGELOG.md index af84ea0ae7..ede667ab66 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -865,6 +865,10 @@ A folder whose `agent.yaml` names a `plugins` list now fails to load with `plugi ## Bug Fixes +### A scheduled task's turn refused while money could not be checked runs again after a router stops + +A router that stopped, or lost the task's lease, while it waited to retry a task left the run to another router, which did not know why the last attempt failed. A turn refused under `spend_check_unavailable` was then read back as it was, and a conversation task settled `delivered` with no reply. The run now records the reason each attempt failed under before the wait, and the router that takes the run over runs that turn again, as the first router would have (AI-3595). + ### A scheduled task whose turn is refused for money in an open conversation fails its run A task delivered in a conversation whose session is open settled its run `delivered` as soon as the agent was asked, even when the model then refused the turn for money and the user got nothing. The conversation channel now waits for the turn to end: refused for money, the run fails under the refusal's code, such as `insufficient_credits` or `spend_limit_reached`, and is not tried again, as on the text channels; `spend_check_unavailable` is still tried again, and the first retry now runs the turn once more, in the conversation or on a text channel, also when another router holds the session, or in a thread, so the user gets the reply once the money can be checked. A conversation turn refused again on that retry fails the run under `spend_check_unavailable` once its retries are spent, never `delivered`. A turn that ends any other way, failed for another reason included, is still `delivered` (AI-3183). diff --git a/acceleration/internal/api/scheduled_delivery.go b/acceleration/internal/api/scheduled_delivery.go index 8b24fa114d..5b05f2fc0f 100644 --- a/acceleration/internal/api/scheduled_delivery.go +++ b/acceleration/internal/api/scheduled_delivery.go @@ -102,8 +102,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"` } @@ -121,7 +122,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. diff --git a/acceleration/internal/scheduling/AGENTS.md b/acceleration/internal/scheduling/AGENTS.md index 5d979bb95b..a8c17d3e4c 100644 --- a/acceleration/internal/scheduling/AGENTS.md +++ b/acceleration/internal/scheduling/AGENTS.md @@ -180,8 +180,11 @@ Each rule names the test that fails when it breaks. Suites: `SchedulerSuite` more under `st__r1`, in the conversation, a text channel or a thread. In the conversation an `_r1` that failed as well fails the attempt under that reason, tried again (`followUpInConversation`), so the run fails under it once its retries are spent and is never - `delivered`. Any other failed reply is read back as it was. A worker that takes the run over - rebuilds it from the row, which keeps no reason between attempts, so it reruns nothing. + `delivered`. Any other failed reply is read back as it was. Before each retry wait the worker records that + reason on the running run (`ScheduledTaskRuns.SetAttemptReason`, under its claim, and only while + no call is placed for the run, whose reason is how that call ended), so a worker that takes the + run over reads it from the row and reruns the turn as well; a pause or an edit that settles the + run `missed` drops it. A call's turn keeps `st__call`. A channel carries the agent's reply only, never settled work's own words (`spokenOf`, AI-1559), so the first attempt and a read-back send the same words. @@ -195,6 +198,16 @@ Each rule names the test that fails when it breaks. Suites: `SchedulerSuite` `TestTelnyxUnpaidSuite/TestAConversationTurnRefusedWhileMoneyCannotBeCheckedRunsAgainOnItsRetry`, `TestTelnyxUnpaidSuite/TestAConversationTurnRefusedAgainOnItsRerunFailsTheRun`, `TestTelnyxUnpaidSuite/TestAConversationTurnRefusedOnAnotherRouterRunsAgainThereOnItsRetry`, + `TestTelnyxUnpaidSuite/TestAConversationTurnRefusedWhileMoneyCannotBeCheckedRunsAgainForTheWorkerTakingItOver`, + `TestTelnyxUnpaidSuite/TestAConversationTurnRefusedOnAnotherRouterRunsAgainThereForTheWorkerTakingItOver`, + `TestTelnyxUnpaidSuite/TestATextTurnFailedNotForMoneyIsNotRunAgainByTheWorkerTakingItOver`, + `TestSchedulerSuite/TestAWorkerTakingARunOverReadsTheReasonItsLastAttemptFailedUnder`, + `TestSchedulerSuite/TestAWorkerTakingARunOverAfterItsCallReadsHowTheCallEnded`, + `TestStoreSuite/TestAnAttemptsReasonIsReadByTheWorkerTakingTheRunOver`, + `TestStoreSuite/TestAnAttemptsReasonLeavesTheReasonAPlacedCallEndedUnder`, + `TestStoreSuite/TestAFinishedRunTakesNoAttemptsReason`, + `TestStoreSuite/TestAPausedRunBetweenAttemptsIsMissedWithoutTheAttemptsReason`, + `TestStoreSuite/TestADeletedConfigsRunBetweenAttemptsIsMissedWithoutTheAttemptsReason`, `TestTelnyxUnpaidSuite/TestATextTurnRefusedWhileMoneyCannotBeCheckedRunsAgainOnItsRetry`, `TestTelnyxUnpaidSuite/TestATextTurnFailedNotForMoneyIsNotRunAgainOnItsRetry`, `TestTelnyxUnpaidSuite/TestAThreadRetryAfterARefusalForMoneyRunsTheTurnAgain`, From 2102827be2b8c2910501d3b0365ebb49fefdc430 Mon Sep 17 00:00:00 2001 From: Kanat Date: Mon, 23 Nov 2026 18:42:58 +0100 Subject: [PATCH 04/13] AI-3595: fence an attempt's reason to the run's own task and customer in its test Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EZsRxWUwySyG1JAn9T7GpE --- .../internal/store/scheduled_task_run_test.go | 27 +++++++++++++------ 1 file changed, 19 insertions(+), 8 deletions(-) diff --git a/acceleration/internal/store/scheduled_task_run_test.go b/acceleration/internal/store/scheduled_task_run_test.go index c9423dcfb8..75b58b3db4 100644 --- a/acceleration/internal/store/scheduled_task_run_test.go +++ b/acceleration/internal/store/scheduled_task_run_test.go @@ -96,7 +96,7 @@ func (s *StoreSuite) TestARunsCallKeepsTheReasonItEndedUnderForTheWorkerTakingIt s.Equal("not_answered", reason, "the taking over keeps how the call went") } -// staleRun ages a claimed run past the stale window and lapses its task's lease, as a worker that +// staleRun ages a claimed run past the stale window and lapses the lease of acme's task, as a worker that // died leaves them, and returns the claim that takes the run over. func (s *StoreSuite) staleRun(taskID, runID string) ClaimedScheduledTask { _, err := s.store.global.NewUpdate().Model((*ScheduledTaskRun)(nil)). @@ -105,6 +105,7 @@ func (s *StoreSuite) staleRun(taskID, runID string) ClaimedScheduledTask { s.Require().NoError(err) _, err = s.store.global.NewUpdate().Model((*ScheduledTask)(nil)). Set("lease_until = ?", s.base.Add(-time.Minute)). + Where("customer_id = ?", "acme"). Where("id = ?", taskID).Exec(s.ctx) s.Require().NoError(err) reclaimed, err := s.store.ScheduledTasks.Claim(s.ctx, 16, time.Minute) @@ -117,22 +118,32 @@ func (s *StoreSuite) staleRun(taskID, runID string) ClaimedScheduledTask { func (s *StoreSuite) TestAnAttemptsReasonIsReadByTheWorkerTakingTheRunOver() { due := s.base.Add(-time.Minute) s.task("one", func(task *ScheduledTask) { task.NextRunAt = &due }) + s.task("two", func(task *ScheduledTask) { task.NextRunAt = &due }) + s.task("one", func(task *ScheduledTask) { task.CustomerID, task.NextRunAt = "globex", &due }) claimed, err := s.store.ScheduledTasks.Claim(s.ctx, 16, time.Minute) s.Require().NoError(err) - s.Require().Len(claimed, 1) - run := claimed[0].Run + s.Require().Len(claimed, 3) + claims := map[string]ClaimedScheduledTask{} + for _, claim := range claimed { + claims[claim.Task.CustomerID+"/"+claim.Task.ID] = claim + } + mine := claims["acme/one"] + run := mine.Run s.Nil(run.Error, "a new run has no reason") - // Only the claim that holds the task, on the customer's own run, records a reason. - s.Require().NoError(s.store.ScheduledTaskRuns.SetAttemptReason(s.ctx, "acme", run.ID, "a-lost-claim", "user_on_call")) - s.Require().NoError(s.store.ScheduledTaskRuns.SetAttemptReason(s.ctx, "globex", run.ID, claimed[0].LeasedBy, "user_on_call")) + // Only the claim that holds the run's own task records a reason: not a lost claim, another + // task's, or another customer's task of the same id. + for _, leasedBy := range []string{"a-lost-claim", claims["acme/two"].LeasedBy, claims["globex/one"].LeasedBy} { + s.Require().NoError(s.store.ScheduledTaskRuns.SetAttemptReason(s.ctx, "acme", run.ID, leasedBy, "user_on_call")) + } + s.Require().NoError(s.store.ScheduledTaskRuns.SetAttemptReason(s.ctx, "globex", run.ID, mine.LeasedBy, "user_on_call")) s.Nil(s.run(run.ID).Error) - s.Require().NoError(s.store.ScheduledTaskRuns.SetAttemptReason(s.ctx, "acme", run.ID, claimed[0].LeasedBy, "spend_check_unavailable")) + s.Require().NoError(s.store.ScheduledTaskRuns.SetAttemptReason(s.ctx, "acme", run.ID, mine.LeasedBy, "spend_check_unavailable")) reclaimed := s.staleRun("one", run.ID) s.Require().NotNil(reclaimed.Run.Error) s.Equal("spend_check_unavailable", *reclaimed.Run.Error, "the worker taking over reads why the last attempt failed") - s.Require().NoError(s.store.ScheduledTaskRuns.SetAttemptReason(s.ctx, "acme", run.ID, claimed[0].LeasedBy, "user_on_call")) + s.Require().NoError(s.store.ScheduledTaskRuns.SetAttemptReason(s.ctx, "acme", run.ID, mine.LeasedBy, "user_on_call")) s.Equal("spend_check_unavailable", *s.run(run.ID).Error, "the claim taken over records nothing more") } From fb8a261319dbe83b2b4e1eeb038780379817a02b Mon Sep 17 00:00:00 2001 From: Kanat Date: Mon, 23 Nov 2026 19:03:03 +0100 Subject: [PATCH 05/13] AI-3595: test that a worker closing as its attempt fails still records the reason Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EZsRxWUwySyG1JAn9T7GpE --- acceleration/internal/scheduling/AGENTS.md | 1 + .../internal/scheduling/scheduler_test.go | 28 +++++++++++++------ 2 files changed, 21 insertions(+), 8 deletions(-) diff --git a/acceleration/internal/scheduling/AGENTS.md b/acceleration/internal/scheduling/AGENTS.md index a8c17d3e4c..e00ad0d796 100644 --- a/acceleration/internal/scheduling/AGENTS.md +++ b/acceleration/internal/scheduling/AGENTS.md @@ -203,6 +203,7 @@ Each rule names the test that fails when it breaks. Suites: `SchedulerSuite` `TestTelnyxUnpaidSuite/TestATextTurnFailedNotForMoneyIsNotRunAgainByTheWorkerTakingItOver`, `TestSchedulerSuite/TestAWorkerTakingARunOverReadsTheReasonItsLastAttemptFailedUnder`, `TestSchedulerSuite/TestAWorkerTakingARunOverAfterItsCallReadsHowTheCallEnded`, + `TestSchedulerSuite/TestAWorkerClosedAsItsAttemptFailsStillRecordsTheReason`, `TestStoreSuite/TestAnAttemptsReasonIsReadByTheWorkerTakingTheRunOver`, `TestStoreSuite/TestAnAttemptsReasonLeavesTheReasonAPlacedCallEndedUnder`, `TestStoreSuite/TestAFinishedRunTakesNoAttemptsReason`, diff --git a/acceleration/internal/scheduling/scheduler_test.go b/acceleration/internal/scheduling/scheduler_test.go index f4d055d1f8..f6f21083f8 100644 --- a/acceleration/internal/scheduling/scheduler_test.go +++ b/acceleration/internal/scheduling/scheduler_test.go @@ -995,25 +995,26 @@ func (s *SchedulerSuite) TestADrainStopsARetryWaitAndLeavesTheRunToItsLease() { // lostDuringItsRetryWait has a worker fail task's first attempt with failure, then stops it while // it waits to retry, as a router that crashes or loses its lease leaves the run. Before the -// failure, first runs on the attempt's claim. It returns the deliveries a second worker made once -// the run went stale and it took the run over. -func (s *SchedulerSuite) lostDuringItsRetryWait(task store.ScheduledTask, failure error, first func(store.ClaimedScheduledTask)) []store.ClaimedScheduledTask { +// failure, first runs with that worker and the attempt's claim. It returns the deliveries a second +// worker made once the run went stale and it took the run over. +func (s *SchedulerSuite) lostDuringItsRetryWait(task store.ScheduledTask, failure error, first func(*Scheduler, store.ClaimedScheduledTask)) []store.ClaimedScheduledTask { + var lost *Scheduler var attempts atomic.Int32 - lost := NewScheduler(s.db, func(ctx context.Context, claimed store.ClaimedScheduledTask) (string, string, error) { + lost = NewScheduler(s.db, func(ctx context.Context, claimed store.ClaimedScheduledTask) (string, string, error) { if claimed.Task.ID != task.ID { return "conversation", claimed.Task.SessionID, nil } attempts.Add(1) if first != nil { - first(claimed) + first(lost, claimed) } return "", "", failure }, slog.New(slog.DiscardHandler)) lost.retries = []time.Duration{time.Hour} lost.Start(s.ctx) s.Require().Eventually(func() bool { - return attempts.Load() == 1 && lost.Running() == 1 - }, 10*time.Second, 10*time.Millisecond, "the first attempt failed and the delivery waits to retry") + return attempts.Load() == 1 + }, 10*time.Second, 10*time.Millisecond, "the first attempt was made") lost.Close() runs := s.runs(task) s.Require().Len(runs, 1) @@ -1054,11 +1055,22 @@ func (s *SchedulerSuite) TestAWorkerTakingARunOverReadsTheReasonItsLastAttemptFa s.Nil(s.runs(task)[0].Error, "a delivered run says nothing failed") } +func (s *SchedulerSuite) TestAWorkerClosedAsItsAttemptFailsStillRecordsTheReason() { + task := s.task(time.Now().UTC().Add(-time.Minute).Truncate(time.Second), nil) + // The router closes as the attempt fails: what it was given to work under has ended. + closing := func(lost *Scheduler, _ store.ClaimedScheduledTask) { lost.cancel() } + + calls := s.lostDuringItsRetryWait(task, &Failure{Reason: ReasonOnACall, Err: errors.New("the user is on a call")}, closing) + + s.Require().NotNil(calls[0].Run.Error, "the reason is recorded after the close") + s.Equal(ReasonOnACall, *calls[0].Run.Error) +} + func (s *SchedulerSuite) TestAWorkerTakingARunOverAfterItsCallReadsHowTheCallEnded() { task := s.task(time.Now().UTC().Add(-time.Minute).Truncate(time.Second), nil) // A [phone, whatsapp] task: nobody answered the call, and WhatsApp failed too. It runs on the // worker's goroutine, so it checks without stopping the test there. - called := func(claimed store.ClaimedScheduledTask) { + called := func(_ *Scheduler, claimed store.ClaimedScheduledTask) { call := "call-" + uuid.NewString() took, _, err := s.db.ScheduledTaskRuns.TakeCall(s.ctx, task.CustomerID, claimed.Run.ID, call) s.NoError(err) From 61913da8e94022e1e64e9c9b4bef43b5ab4df34c Mon Sep 17 00:00:00 2001 From: Kanat Date: Mon, 23 Nov 2026 20:12:35 +0100 Subject: [PATCH 06/13] AI-3595: a running run between attempts lists no reason The reason a failed attempt left on the run row is for a worker that takes the run over, not for the runs list: while the run runs, error stays what it was (a placed call's reason only). Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01EZsRxWUwySyG1JAn9T7GpE --- acceleration/internal/api/scheduled_tasks.go | 6 +++++ .../internal/api/scheduled_tasks_test.go | 25 +++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/acceleration/internal/api/scheduled_tasks.go b/acceleration/internal/api/scheduled_tasks.go index d0facd6b74..400d4c1c4e 100644 --- a/acceleration/internal/api/scheduled_tasks.go +++ b/acceleration/internal/api/scheduled_tasks.go @@ -773,6 +773,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), diff --git a/acceleration/internal/api/scheduled_tasks_test.go b/acceleration/internal/api/scheduled_tasks_test.go index 8aa6c68841..bf28685aca 100644 --- a/acceleration/internal/api/scheduled_tasks_test.go +++ b/acceleration/internal/api/scheduled_tasks_test.go @@ -2774,6 +2774,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() From d7e9822e87befdcf48089be9d50596a3c46acf47 Mon Sep 17 00:00:00 2001 From: Kanat Date: Mon, 23 Nov 2026 20:12:39 +0100 Subject: [PATCH 07/13] AI-3595: no CHANGELOG line, the root changelog is written once per release Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01EZsRxWUwySyG1JAn9T7GpE --- CHANGELOG.md | 4 ---- 1 file changed, 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1ea3c7d5f5..cb26da99e0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -865,10 +865,6 @@ A folder whose `agent.yaml` names a `plugins` list now fails to load with `plugi ## Bug Fixes -### A scheduled task's turn refused while money could not be checked runs again after a router stops - -A router that stopped, or lost the task's lease, while it waited to retry a task left the run to another router, which did not know why the last attempt failed. A turn refused under `spend_check_unavailable` was then read back as it was, and a conversation task settled `delivered` with no reply. The run now records the reason each attempt failed under before the wait, and the router that takes the run over runs that turn again, as the first router would have (AI-3595). - ### A scheduled task whose turn is refused for money in an open conversation fails its run A task delivered in a conversation whose session is open settled its run `delivered` as soon as the agent was asked, even when the model then refused the turn for money and the user got nothing. The conversation channel now waits for the turn to end: refused for money, the run fails under the refusal's code, such as `insufficient_credits` or `spend_limit_reached`, and is not tried again, as on the text channels; `spend_check_unavailable` is still tried again, and the first retry now runs the turn once more, in the conversation or on a text channel, also when another router holds the session, or in a thread, so the user gets the reply once the money can be checked. A conversation turn refused again on that retry fails the run under `spend_check_unavailable` once its retries are spent, never `delivered`. A turn that ends any other way, failed for another reason included, is still `delivered` (AI-3183). From d98ca31bcee3abfe901ad771b72eb9ef94e1e708 Mon Sep 17 00:00:00 2001 From: Kanat Date: Mon, 23 Nov 2026 21:00:44 +0100 Subject: [PATCH 08/13] AI-3595: taking a call clears the run's earlier attempt reason Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01EZsRxWUwySyG1JAn9T7GpE --- .../internal/api/scheduled_phone_test.go | 28 +++++++++++ .../internal/store/scheduled_task_run.go | 7 +++ .../internal/store/scheduled_task_run_test.go | 50 +++++++++++++++++++ 3 files changed, 85 insertions(+) diff --git a/acceleration/internal/api/scheduled_phone_test.go b/acceleration/internal/api/scheduled_phone_test.go index 8b7020a49f..0bf15ccedc 100644 --- a/acceleration/internal/api/scheduled_phone_test.go +++ b/acceleration/internal/api/scheduled_phone_test.go @@ -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() { diff --git a/acceleration/internal/store/scheduled_task_run.go b/acceleration/internal/store/scheduled_task_run.go index d06eca70c1..fea9d22009 100644 --- a/acceleration/internal/store/scheduled_task_run.go +++ b/acceleration/internal/store/scheduled_task_run.go @@ -137,9 +137,16 @@ func (r *ScheduledTaskRuns) FinishManual(ctx context.Context, customerID, runID, // an earlier attempt, or a worker that stopped, placed a call for this // occurrence, so the user is not rung again. reason is then the one the run // records, such as how that call ended (SetCallReason), if any. +// +// Taking the call clears the run's error: with no call placed, the only error a running run +// holds is the reason an earlier attempt failed under (SetAttemptReason), and once a call is +// taken, how that call ends is the run's reason, as on a run that never had an earlier attempt. +// A call given back (ReleaseCall) leaves the run with no reason until the next failed attempt +// records its own. func (r *ScheduledTaskRuns) TakeCall(ctx context.Context, customerID, runID, sessionID string) (took bool, reason string, err error) { result, err := r.store.global.NewUpdate().Model((*ScheduledTaskRun)(nil)). Set("session_id = ?", sessionID). + Set("error = NULL"). Where("customer_id = ?", customerID). Where("id = ?", runID). Where("state = ?", ScheduledTaskRunRunning). diff --git a/acceleration/internal/store/scheduled_task_run_test.go b/acceleration/internal/store/scheduled_task_run_test.go index 75b58b3db4..3215314456 100644 --- a/acceleration/internal/store/scheduled_task_run_test.go +++ b/acceleration/internal/store/scheduled_task_run_test.go @@ -167,6 +167,56 @@ func (s *StoreSuite) TestAnAttemptsReasonLeavesTheReasonAPlacedCallEndedUnder() s.Equal("not_answered", reason, "how the call ended is the run's reason") } +// callTakenAfterAnAttemptFailed claims a due task, records an earlier attempt's reason on its run +// and takes a call for it, as a worker does on the attempt that rings after one that failed. +func (s *StoreSuite) callTakenAfterAnAttemptFailed() ClaimedScheduledTask { + due := s.base.Add(-time.Minute) + s.task("one", func(task *ScheduledTask) { task.NextRunAt = &due }) + claimed, err := s.store.ScheduledTasks.Claim(s.ctx, 16, time.Minute) + s.Require().NoError(err) + s.Require().Len(claimed, 1) + s.Require().NoError(s.store.ScheduledTaskRuns.SetAttemptReason(s.ctx, "acme", claimed[0].Run.ID, claimed[0].LeasedBy, "tier_limit_reached")) + took, _, err := s.store.ScheduledTaskRuns.TakeCall(s.ctx, "acme", claimed[0].Run.ID, "call-1") + s.Require().NoError(err) + s.Require().True(took) + return claimed[0] +} + +func (s *StoreSuite) TestAnEarlierAttemptsReasonIsNotTheReasonOfTheCallTakenAfterIt() { + claimed := s.callTakenAfterAnAttemptFailed() + + // The worker stops mid-call, before it records how the call ended. + reclaimed := s.staleRun("one", claimed.Run.ID) + + s.Nil(reclaimed.Run.Error, "the call is the run's, the earlier attempt's reason is not") + took, reason, err := s.store.ScheduledTaskRuns.TakeCall(s.ctx, "acme", claimed.Run.ID, "call-2") + s.Require().NoError(err) + s.False(took, "the user is not rung again") + s.Empty(reason, "so the delivery fails as already called, not under the earlier attempt's reason") +} + +func (s *StoreSuite) TestARunTakenOverMidCallAfterAFailedAttemptEndsAsAlreadyCalled() { + claimed := s.callTakenAfterAnAttemptFailed() + _, err := s.store.global.NewUpdate().Model((*ScheduledTaskRun)(nil)). + Set("attempts = ?", maxScheduledTaskRunAttempts). + Set("started_at = ?", s.base.Add(-time.Hour)). + Where("id = ?", claimed.Run.ID).Exec(s.ctx) + s.Require().NoError(err) + _, err = s.store.global.NewUpdate().Model((*ScheduledTask)(nil)). + Set("lease_until = ?", s.base.Add(-time.Minute)). + Where("customer_id = ?", "acme"). + Where("id = ?", "one").Exec(s.ctx) + s.Require().NoError(err) + + _, err = s.store.ScheduledTasks.Claim(s.ctx, 16, time.Minute) + s.Require().NoError(err) + + run := s.run(claimed.Run.ID) + s.Equal(ScheduledTaskRunFailed, run.State) + s.Require().NotNil(run.Error) + s.Equal(scheduledTaskRunRungAlready, *run.Error) +} + func (s *StoreSuite) TestAFinishedRunTakesNoAttemptsReason() { due := s.base.Add(-time.Minute) s.task("one", func(task *ScheduledTask) { task.NextRunAt = &due }) From 7c21598cb65fcb8070e388511a12d1a7e741fa2b Mon Sep 17 00:00:00 2001 From: Kanat Date: Mon, 23 Nov 2026 21:00:53 +0100 Subject: [PATCH 09/13] AI-3595: SetAttemptReason's doc says what its claim check guarantees Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01EZsRxWUwySyG1JAn9T7GpE --- acceleration/internal/store/scheduled_task_run.go | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/acceleration/internal/store/scheduled_task_run.go b/acceleration/internal/store/scheduled_task_run.go index fea9d22009..93af4e8e2c 100644 --- a/acceleration/internal/store/scheduled_task_run.go +++ b/acceleration/internal/store/scheduled_task_run.go @@ -193,8 +193,10 @@ func (r *ScheduledTaskRuns) SetCallReason(ctx context.Context, customerID, runID // SetAttemptReason records on a running run the reason an attempt failed under, for the // attempt after it: a worker that takes the run over reads it from the row, as the worker that // made the attempt reads it from memory. It writes only under the claim leasedBy, so a worker -// that lost its claim cannot overwrite the next one's, and only while no call is placed for the -// run: the reason that call ended under is the run's (SetCallReason). +// that lost its claim cannot overwrite the next one's, as far as the claim is checked +// when the statement starts (a write that waits on the run's row behind a takeover's claim still +// lands after it, with a reason of the same occurrence), and only while no call is placed for +// the run: the reason that call ended under is the run's (SetCallReason). func (r *ScheduledTaskRuns) SetAttemptReason(ctx context.Context, customerID, runID, leasedBy, reason string) error { claimed := r.store.global.NewSelect().Model((*ScheduledTask)(nil)). ColumnExpr("1"). From 9a1104e8187f8788345c2777a0a6e6163cf452be Mon Sep 17 00:00:00 2001 From: Kanat Date: Mon, 23 Nov 2026 21:02:58 +0100 Subject: [PATCH 10/13] AI-3595: test that a run held after a failed attempt keeps the attempt's reason Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01EZsRxWUwySyG1JAn9T7GpE --- .../internal/scheduling/scheduler_test.go | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/acceleration/internal/scheduling/scheduler_test.go b/acceleration/internal/scheduling/scheduler_test.go index f6f21083f8..b7c48ec68b 100644 --- a/acceleration/internal/scheduling/scheduler_test.go +++ b/acceleration/internal/scheduling/scheduler_test.go @@ -548,6 +548,39 @@ func (s *SchedulerSuite) TestAHeldTaskIsDeliveredWhenTheHoldEnds() { s.Require().NotNil(runs[0].PostponedUntil, "the hold is on the run") } +func (s *SchedulerSuite) TestAnOccurrenceHeldAfterAFailedAttemptIsDeliveredAfterTheHoldUnderThatReason() { + task := s.task(time.Now().UTC().Add(-time.Minute).Truncate(time.Second), nil) + var mu sync.Mutex + var calls []store.ClaimedScheduledTask + deliver := func(_ context.Context, claimed store.ClaimedScheduledTask) (string, string, error) { + if claimed.Task.ID != task.ID { + return "conversation", claimed.Task.SessionID, nil + } + mu.Lock() + defer mu.Unlock() + calls = append(calls, claimed) + switch len(calls) { + case 1: + return "", "", &Failure{Reason: ReasonOnACall, Err: errors.New("the user is on a call")} + case 2: + return "", "", &Postponed{Until: time.Now().Add(300 * time.Millisecond)} + } + return "conversation", claimed.Task.SessionID, nil + } + s.started(deliver, func(scheduler *Scheduler) { + scheduler.retries = []time.Duration{10 * time.Millisecond} + }) + + s.Require().Eventually(func() bool { + return s.read(task).State == store.ScheduledTaskCompleted + }, 10*time.Second, 10*time.Millisecond) + mu.Lock() + defer mu.Unlock() + s.Require().Len(calls, 3, "failed, held, then delivered after the hold") + s.Require().NotNil(calls[2].Run.Error, "the claim after the hold reads why the attempt before it failed") + s.Equal(ReasonOnACall, *calls[2].Run.Error) +} + func (s *SchedulerSuite) TestAHeldOccurrenceIsCountedFromTheHoldAndNotFromWhenItCameDue() { now := time.Now().UTC().Truncate(time.Second) scheduler := NewScheduler(s.db, nil, slog.New(slog.DiscardHandler)) From 557ac2866d2d2d5d4fa519e23b59303f0e7f58f8 Mon Sep 17 00:00:00 2001 From: Kanat Date: Tue, 24 Nov 2026 08:50:03 +0100 Subject: [PATCH 11/13] AI-3595: port the takeover tests to the scheduler's SetRetries and the router's call windows Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01EZsRxWUwySyG1JAn9T7GpE --- acceleration/internal/api/scheduled_unpaid_test.go | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/acceleration/internal/api/scheduled_unpaid_test.go b/acceleration/internal/api/scheduled_unpaid_test.go index 13d34df4d5..1e5e4095a6 100644 --- a/acceleration/internal/api/scheduled_unpaid_test.go +++ b/acceleration/internal/api/scheduled_unpaid_test.go @@ -140,8 +140,6 @@ func (s *TelnyxUnpaidSuite) settledByTheWorkerAfter(task store.ScheduledTask, be // the settled run and how many attempts the second worker made. func (s *TelnyxUnpaidSuite) takenOver(task store.ScheduledTask, between func()) (store.ScheduledTaskRun, int32) { var failed atomic.Int32 - retries := scheduling.DeliveryRetries - scheduling.DeliveryRetries = []time.Duration{time.Hour} lost := scheduling.NewScheduler(s.store, func(ctx context.Context, claimed store.ClaimedScheduledTask) (string, string, error) { deliveredTo, sessionID, err := s.router.DeliverScheduledTask(ctx, claimed) if err != nil { @@ -149,7 +147,7 @@ func (s *TelnyxUnpaidSuite) takenOver(task store.ScheduledTask, between func()) } return deliveredTo, sessionID, err }, slog.New(slog.NewTextHandler(s.logged, nil))) - scheduling.DeliveryRetries = retries + lost.SetRetries([]time.Duration{time.Hour}) past := time.Now().Add(-time.Minute) task.NextRunAt = &past s.Require().NoError(s.store.ScheduledTasks.Update(context.Background(), &task)) @@ -177,7 +175,7 @@ func (s *TelnyxUnpaidSuite) takenOver(task store.ScheduledTask, between func()) s.retryAtOnce() var attempts atomic.Int32 - worker := scheduling.NewScheduler(s.store, func(ctx context.Context, claimed store.ClaimedScheduledTask) (string, string, error) { + worker := s.newScheduler(func(ctx context.Context, claimed store.ClaimedScheduledTask) (string, string, error) { attempts.Add(1) return s.router.DeliverScheduledTask(ctx, claimed) }, slog.New(slog.NewTextHandler(s.logged, nil))) @@ -779,7 +777,7 @@ func (s *TelnyxUnpaidSuite) TestATextTurnFailedNotForMoneyIsNotRunAgainByTheWork s.Equal(store.ScheduledTaskRunFailed, run.State) s.Require().NotNil(run.Error) s.Equal(scheduling.ReasonReplyFailed, *run.Error) - s.Equal(int32(1+len(scheduling.DeliveryRetries)), attempts) + s.Equal(int32(1+len(s.retries)), attempts) found, running := s.router.sessions.Get(opened.Id, session.Owner{CustomerID: s.customerID(), UserID: user.userID, Kind: auth.KindAuthenticated}) s.Require().True(running) _, _, rerun := found.FollowUpReply(conversation.ReadBackPrefix + run.ID + rerunSuffix) @@ -1317,11 +1315,11 @@ func (s *TelnyxUnpaidSuite) ringingOn(model string) ringing { // callOn is ringing, on model, with the call taken on its run and not placed yet. func (s *TelnyxUnpaidSuite) callOn(model string) ringing { - window, longest := scheduledPhoneWindow, scheduledCallLimit + window, longest := s.router.phoneWindow, s.router.callLimit // The limit is longer than the test waits for the call to be let go: a call let go is one // the agent hung up, or the test ended. - scheduledPhoneWindow, scheduledCallLimit = deliveryWait, 2*deliveryWait - s.T().Cleanup(func() { scheduledPhoneWindow, scheduledCallLimit = window, longest }) + s.router.phoneWindow, s.router.callLimit = deliveryWait, 2*deliveryWait + s.T().Cleanup(func() { s.router.phoneWindow, s.router.callLimit = window, longest }) number, writer := "+1555"+digits(s.utils.uuid()), "+1347"+digits(s.utils.uuid()) s.seedSMSLine(number) s.config.Channels.Lines = store.AgentChannels{SMS: &store.ChannelLine{Number: number}} From 01da879d84e6e947682dc0b458dd4bc69d5fdb39 Mon Sep 17 00:00:00 2001 From: Kanat Date: Wed, 25 Nov 2026 13:48:02 -0500 Subject: [PATCH 12/13] AI-3595: claim with a ShardClaim in this PR's store tests #2336 gave ScheduledTasks.Claim a ShardClaim; the zero one claims every shard's task, as these tests did before. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EZsRxWUwySyG1JAn9T7GpE --- .../internal/store/scheduled_task_run_test.go | 12 ++++++------ acceleration/internal/store/scheduled_task_test.go | 2 +- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/acceleration/internal/store/scheduled_task_run_test.go b/acceleration/internal/store/scheduled_task_run_test.go index cf16d10254..6e518a8329 100644 --- a/acceleration/internal/store/scheduled_task_run_test.go +++ b/acceleration/internal/store/scheduled_task_run_test.go @@ -134,7 +134,7 @@ func (s *StoreSuite) staleRun(taskID, runID string) ClaimedScheduledTask { Where("customer_id = ?", "acme"). Where("id = ?", taskID).Exec(s.ctx) s.Require().NoError(err) - reclaimed, err := s.store.ScheduledTasks.Claim(s.ctx, 16, time.Minute) + reclaimed, err := s.store.ScheduledTasks.Claim(s.ctx, 16, time.Minute, ShardClaim{}) s.Require().NoError(err) s.Require().Len(reclaimed, 1) s.Require().Equal(runID, reclaimed[0].Run.ID, "taken over under the same run") @@ -146,7 +146,7 @@ func (s *StoreSuite) TestAnAttemptsReasonIsReadByTheWorkerTakingTheRunOver() { s.task("one", func(task *ScheduledTask) { task.NextRunAt = &due }) s.task("two", func(task *ScheduledTask) { task.NextRunAt = &due }) s.task("one", func(task *ScheduledTask) { task.CustomerID, task.NextRunAt = "globex", &due }) - claimed, err := s.store.ScheduledTasks.Claim(s.ctx, 16, time.Minute) + claimed, err := s.store.ScheduledTasks.Claim(s.ctx, 16, time.Minute, ShardClaim{}) s.Require().NoError(err) s.Require().Len(claimed, 3) claims := map[string]ClaimedScheduledTask{} @@ -176,7 +176,7 @@ func (s *StoreSuite) TestAnAttemptsReasonIsReadByTheWorkerTakingTheRunOver() { func (s *StoreSuite) TestAnAttemptsReasonLeavesTheReasonAPlacedCallEndedUnder() { due := s.base.Add(-time.Minute) s.task("one", func(task *ScheduledTask) { task.NextRunAt = &due }) - claimed, err := s.store.ScheduledTasks.Claim(s.ctx, 16, time.Minute) + claimed, err := s.store.ScheduledTasks.Claim(s.ctx, 16, time.Minute, ShardClaim{}) s.Require().NoError(err) s.Require().Len(claimed, 1) run := claimed[0].Run @@ -198,7 +198,7 @@ func (s *StoreSuite) TestAnAttemptsReasonLeavesTheReasonAPlacedCallEndedUnder() func (s *StoreSuite) callTakenAfterAnAttemptFailed() ClaimedScheduledTask { due := s.base.Add(-time.Minute) s.task("one", func(task *ScheduledTask) { task.NextRunAt = &due }) - claimed, err := s.store.ScheduledTasks.Claim(s.ctx, 16, time.Minute) + claimed, err := s.store.ScheduledTasks.Claim(s.ctx, 16, time.Minute, ShardClaim{}) s.Require().NoError(err) s.Require().Len(claimed, 1) s.Require().NoError(s.store.ScheduledTaskRuns.SetAttemptReason(s.ctx, "acme", claimed[0].Run.ID, claimed[0].LeasedBy, "tier_limit_reached")) @@ -234,7 +234,7 @@ func (s *StoreSuite) TestARunTakenOverMidCallAfterAFailedAttemptEndsAsAlreadyCal Where("id = ?", "one").Exec(s.ctx) s.Require().NoError(err) - _, err = s.store.ScheduledTasks.Claim(s.ctx, 16, time.Minute) + _, err = s.store.ScheduledTasks.Claim(s.ctx, 16, time.Minute, ShardClaim{}) s.Require().NoError(err) run := s.run(claimed.Run.ID) @@ -246,7 +246,7 @@ func (s *StoreSuite) TestARunTakenOverMidCallAfterAFailedAttemptEndsAsAlreadyCal func (s *StoreSuite) TestAFinishedRunTakesNoAttemptsReason() { due := s.base.Add(-time.Minute) s.task("one", func(task *ScheduledTask) { task.NextRunAt = &due }) - claimed, err := s.store.ScheduledTasks.Claim(s.ctx, 16, time.Minute) + claimed, err := s.store.ScheduledTasks.Claim(s.ctx, 16, time.Minute, ShardClaim{}) s.Require().NoError(err) s.Require().Len(claimed, 1) run := claimed[0].Run diff --git a/acceleration/internal/store/scheduled_task_test.go b/acceleration/internal/store/scheduled_task_test.go index 29d04b96b6..6a78af3649 100644 --- a/acceleration/internal/store/scheduled_task_test.go +++ b/acceleration/internal/store/scheduled_task_test.go @@ -989,7 +989,7 @@ func (s *StoreSuite) retryingRuns() map[string]ScheduledTaskRun { due := s.base.Add(-time.Minute) s.task("failed", func(task *ScheduledTask) { task.NextRunAt = &due }) s.task("called", func(task *ScheduledTask) { task.NextRunAt = &due }) - claimed, err := s.store.ScheduledTasks.Claim(s.ctx, 16, time.Minute) + claimed, err := s.store.ScheduledTasks.Claim(s.ctx, 16, time.Minute, ShardClaim{}) s.Require().NoError(err) s.Require().Len(claimed, 2) runs := map[string]ScheduledTaskRun{} From 4aca927bd0eb27d9f19b8cd20211b0ec0c400103 Mon Sep 17 00:00:00 2001 From: Kanat Date: Wed, 25 Nov 2026 13:48:03 -0500 Subject: [PATCH 13/13] AI-3595: build TelnyxUnpaidSuite on main's scheduledOwnerContext #2404 made scheduledOwnerContext a Server method that returns an error; #2278's tests, merged after it, still call the old function, so main's internal/api integration tests do not build. They go through the suite's ownerContext, as the other tests in the file do. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EZsRxWUwySyG1JAn9T7GpE --- .../internal/api/scheduled_unpaid_test.go | 22 +++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/acceleration/internal/api/scheduled_unpaid_test.go b/acceleration/internal/api/scheduled_unpaid_test.go index 7efee71cec..aff53649db 100644 --- a/acceleration/internal/api/scheduled_unpaid_test.go +++ b/acceleration/internal/api/scheduled_unpaid_test.go @@ -932,7 +932,7 @@ func (s *TelnyxUnpaidSuite) followUpIn(user *testClient, opened Session, channel // attempt after it, in the same open session, watches none of the turn's events: it can only read // how the turn ended. func (s *TelnyxUnpaidSuite) failedBefore(found *session.Session, delivery scheduledDelivery) { - s.Require().NoError(s.router.followUpWithin(scheduledOwnerContext(context.Background(), delivery), found, delivery)) + s.Require().NoError(s.router.followUpWithin(s.ownerContext(context.Background(), delivery), found, delivery)) s.Require().Eventually(func() bool { state, _, _ := found.FollowUpReply(delivery.CommandID) return state == "failed" @@ -947,7 +947,7 @@ func (s *TelnyxUnpaidSuite) TestAConversationTurnRefusedForMoneyUnwatchedFailsUn found, delivery := s.followUpIn(user, opened, "conversation") s.failedBefore(found, delivery) - _, _, err := s.router.deliverOn(scheduledOwnerContext(context.Background(), delivery), delivery, found, + _, _, err := s.router.deliverOn(s.ownerContext(context.Background(), delivery), delivery, found, store.ScheduledTaskDeliveredConversation) var failure *scheduling.Failure @@ -963,7 +963,7 @@ func (s *TelnyxUnpaidSuite) TestAConversationTurnRefusedUncheckedUnwatchedIsRetr found, delivery := s.followUpIn(user, opened, "conversation") s.failedBefore(found, delivery) - _, _, err := s.router.deliverOn(scheduledOwnerContext(context.Background(), delivery), delivery, found, + _, _, err := s.router.deliverOn(s.ownerContext(context.Background(), delivery), delivery, found, store.ScheduledTaskDeliveredConversation) var failure *scheduling.Failure @@ -979,7 +979,7 @@ func (s *TelnyxUnpaidSuite) TestATextTurnRefusedForMoneyUnwatchedFailsUnderTheMo found, delivery := s.followUpIn(user, opened, "sms") s.failedBefore(found, delivery) - _, _, err := s.router.captureReply(scheduledOwnerContext(context.Background(), delivery), found, delivery) + _, _, err := s.router.captureReply(s.ownerContext(context.Background(), delivery), found, delivery) var failure *scheduling.Failure s.Require().ErrorAs(err, &failure) @@ -995,7 +995,7 @@ func (s *TelnyxUnpaidSuite) TestATextTurnRefusedUncheckedUnwatchedIsRetried() { found, delivery := s.followUpIn(user, opened, "sms") s.failedBefore(found, delivery) - _, _, err := s.router.captureReply(scheduledOwnerContext(context.Background(), delivery), found, delivery) + _, _, err := s.router.captureReply(s.ownerContext(context.Background(), delivery), found, delivery) var failure *scheduling.Failure s.Require().ErrorAs(err, &failure) @@ -1018,7 +1018,7 @@ func (s *TelnyxUnpaidSuite) TestAThreadTurnRefusedForMoneyUnwatchedFailsUnderThe CallerKind: "server", TaskID: task.ID, RunID: "run", CommandID: "st_run", Text: "stretch"} s.failedBefore(found, delivery) - _, _, err := s.router.deliverOnThread(scheduledOwnerContext(context.Background(), delivery), delivery, channel) + _, _, err := s.router.deliverOnThread(s.ownerContext(context.Background(), delivery), delivery, channel) var failure *scheduling.Failure s.Require().ErrorAs(err, &failure) @@ -1056,7 +1056,7 @@ func (s *TelnyxUnpaidSuite) TestATextReplyCarriesOnlyItsOwnTurnsWords() { } captured := make(chan reply, 1) go func() { - text, _, err := s.router.captureReply(scheduledOwnerContext(context.Background(), delivery), found, delivery) + text, _, err := s.router.captureReply(s.ownerContext(context.Background(), delivery), found, delivery) captured <- reply{text, err} }() s.Never(func() bool { return len(captured) > 0 }, time.Second, 20*time.Millisecond, "the reply did not wait behind the busy turn") @@ -1084,7 +1084,7 @@ func (s *TelnyxUnpaidSuite) TestATextReplyIsTextedAsItWasOnceItsTurnEnds() { } captured := make(chan reply, 1) go func() { - text, _, err := s.router.captureReply(scheduledOwnerContext(context.Background(), delivery), found, delivery) + text, _, err := s.router.captureReply(s.ownerContext(context.Background(), delivery), found, delivery) captured <- reply{text, err} }() @@ -1253,7 +1253,7 @@ func (s *TelnyxUnpaidSuite) TestAConversationRetryWaitsOutTheTurnAnEarlierAttemp CallerKind: "authenticated", TaskID: "task", RunID: "run", CommandID: "st_run", Text: "stretch"} retried := make(chan error, 1) go func() { - _, _, err := s.router.deliverOn(scheduledOwnerContext(context.Background(), delivery), delivery, found, + _, _, err := s.router.deliverOn(s.ownerContext(context.Background(), delivery), delivery, found, store.ScheduledTaskDeliveredConversation) retried <- err }() @@ -1280,7 +1280,7 @@ func (s *TelnyxUnpaidSuite) TestAConversationFollowUpTheSessionRefusesIsNotDeliv found, delivery := s.followUpIn(user, opened, "conversation") delivery.Text = "" - _, _, err := s.router.deliverOn(scheduledOwnerContext(context.Background(), delivery), delivery, found, + _, _, err := s.router.deliverOn(s.ownerContext(context.Background(), delivery), delivery, found, store.ScheduledTaskDeliveredConversation) s.ErrorContains(err, "there is nothing to answer") @@ -1296,7 +1296,7 @@ func (s *TelnyxUnpaidSuite) TestATextFollowUpTheSessionRefusesFailsWithWhy() { found, delivery := s.followUpIn(user, opened, "sms") delivery.Text = "" - _, _, err := s.router.captureReply(scheduledOwnerContext(context.Background(), delivery), found, delivery) + _, _, err := s.router.captureReply(s.ownerContext(context.Background(), delivery), found, delivery) s.ErrorContains(err, "there is nothing to answer") }