diff --git a/.claude/skills/scheduled-tasks/SKILL.md b/.claude/skills/scheduled-tasks/SKILL.md index 80b3708223..4e4a216043 100644 --- a/.claude/skills/scheduled-tasks/SKILL.md +++ b/.claude/skills/scheduled-tasks/SKILL.md @@ -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__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__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 @@ -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` | diff --git a/acceleration/internal/api/scheduled_delivery.go b/acceleration/internal/api/scheduled_delivery.go index a6ecd66b9e..d255598dc8 100644 --- a/acceleration/internal/api/scheduled_delivery.go +++ b/acceleration/internal/api/scheduled_delivery.go @@ -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"` } @@ -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. diff --git a/acceleration/internal/api/scheduled_phone_test.go b/acceleration/internal/api/scheduled_phone_test.go index ccf5399118..3baec7992e 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/api/scheduled_tasks.go b/acceleration/internal/api/scheduled_tasks.go index 5a9dc6f238..52ad051ab7 100644 --- a/acceleration/internal/api/scheduled_tasks.go +++ b/acceleration/internal/api/scheduled_tasks.go @@ -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), diff --git a/acceleration/internal/api/scheduled_tasks_test.go b/acceleration/internal/api/scheduled_tasks_test.go index dee9d781bb..b464b79fdf 100644 --- a/acceleration/internal/api/scheduled_tasks_test.go +++ b/acceleration/internal/api/scheduled_tasks_test.go @@ -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() diff --git a/acceleration/internal/api/scheduled_unpaid_test.go b/acceleration/internal/api/scheduled_unpaid_test.go index 6e0c64cd87..aff53649db 100644 --- a/acceleration/internal/api/scheduled_unpaid_test.go +++ b/acceleration/internal/api/scheduled_unpaid_test.go @@ -135,6 +135,67 @@ 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 + 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))) + 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)) + 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 := 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))) + 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() { @@ -671,6 +732,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(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) + 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() { @@ -811,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" @@ -826,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 @@ -842,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 @@ -858,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) @@ -874,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) @@ -897,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) @@ -935,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") @@ -963,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} }() @@ -1132,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 }() @@ -1159,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") @@ -1175,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") } diff --git a/acceleration/internal/scheduling/AGENTS.md b/acceleration/internal/scheduling/AGENTS.md index fd07cd3f25..1100675d18 100644 --- a/acceleration/internal/scheduling/AGENTS.md +++ b/acceleration/internal/scheduling/AGENTS.md @@ -233,8 +233,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. @@ -248,6 +251,17 @@ 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`, + `TestSchedulerSuite/TestAWorkerClosedAsItsAttemptFailsStillRecordsTheReason`, + `TestStoreSuite/TestAnAttemptsReasonIsReadByTheWorkerTakingTheRunOver`, + `TestStoreSuite/TestAnAttemptsReasonLeavesTheReasonAPlacedCallEndedUnder`, + `TestStoreSuite/TestAFinishedRunTakesNoAttemptsReason`, + `TestStoreSuite/TestAPausedRunBetweenAttemptsIsMissedWithoutTheAttemptsReason`, + `TestStoreSuite/TestADeletedConfigsRunBetweenAttemptsIsMissedWithoutTheAttemptsReason`, `TestTelnyxUnpaidSuite/TestATextTurnRefusedWhileMoneyCannotBeCheckedRunsAgainOnItsRetry`, `TestTelnyxUnpaidSuite/TestATextTurnFailedNotForMoneyIsNotRunAgainOnItsRetry`, `TestTelnyxUnpaidSuite/TestAThreadRetryAfterARefusalForMoneyRunsTheTurnAgain`, diff --git a/acceleration/internal/scheduling/scheduler.go b/acceleration/internal/scheduling/scheduler.go index 961e52e227..0843ccc62a 100644 --- a/acceleration/internal/scheduling/scheduler.go +++ b/acceleration/internal/scheduling/scheduler.go @@ -507,6 +507,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(): @@ -518,9 +523,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) @@ -528,6 +530,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/scheduling/scheduler_test.go b/acceleration/internal/scheduling/scheduler_test.go index 65e2fe48ad..ba31c76fe1 100644 --- a/acceleration/internal/scheduling/scheduler_test.go +++ b/acceleration/internal/scheduling/scheduler_test.go @@ -568,6 +568,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)) @@ -1013,6 +1046,97 @@ 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 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) { + if claimed.Task.ID != task.ID { + return "conversation", claimed.Task.SessionID, nil + } + attempts.Add(1) + if first != nil { + 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 + }, 10*time.Second, 10*time.Millisecond, "the first attempt was made") + 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) 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(_ *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) + 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.go b/acceleration/internal/store/scheduled_task.go index 0dfc4c0101..27ebf0a5a8 100644 --- a/acceleration/internal/store/scheduled_task.go +++ b/acceleration/internal/store/scheduled_task.go @@ -423,6 +423,11 @@ func scopedTasks(query *bun.SelectQuery, scope ScheduledTaskScope) *bun.SelectQu return query } +// 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 @@ -505,6 +510,7 @@ func (r *ScheduledTasks) update(ctx context.Context, task *ScheduledTask, missed 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). @@ -1206,6 +1212,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 d86bd70492..2b1d345f51 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). @@ -183,6 +190,33 @@ 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, 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"). + 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. A placed call is // never given back: it is rung once (callEnded in internal/api). diff --git a/acceleration/internal/store/scheduled_task_run_test.go b/acceleration/internal/store/scheduled_task_run_test.go index 9a7a365a40..6e518a8329 100644 --- a/acceleration/internal/store/scheduled_task_run_test.go +++ b/acceleration/internal/store/scheduled_task_run_test.go @@ -122,6 +122,144 @@ 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 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)). + 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("customer_id = ?", "acme"). + Where("id = ?", taskID).Exec(s.ctx) + s.Require().NoError(err) + 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") + return reclaimed[0] +} + +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, ShardClaim{}) + s.Require().NoError(err) + 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 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, 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, mine.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, ShardClaim{}) + 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") +} + +// 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, 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")) + 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, ShardClaim{}) + 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 }) + 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 + _, 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) @@ -178,6 +316,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() { took, err := s.store.ScheduledTaskRuns.TakeText(s.ctx, "acme", run.ID, "sms") s.Require().NoError(err) diff --git a/acceleration/internal/store/scheduled_task_test.go b/acceleration/internal/store/scheduled_task_test.go index 8b2519866f..6a78af3649 100644 --- a/acceleration/internal/store/scheduled_task_test.go +++ b/acceleration/internal/store/scheduled_task_test.go @@ -983,6 +983,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, ShardClaim{}) + 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 })