From decb5a73768480056c4dc8ee3d9b53939a781adb Mon Sep 17 00:00:00 2001 From: Kanat Date: Mon, 23 Nov 2026 21:20:12 +0100 Subject: [PATCH 1/5] fix(test): keep scheduled-delivery timings per router, not process-wide Suites run in parallel in one process (runSuite), and ScheduledTasksSuite and TelnyxUnpaidSuite saved, set and restored package vars every router and worker reads: scheduling.DeliveryRetries, scheduledReplyWindow, scheduledPhoneWindow, scheduledCallLimit and resumedAt. Their restores interleaved, so one suite's worker or router ran on the other's values: an unpaid thread task counted 3 attempts against a default of 4, and a thread task whose session ends mid-turn gave up at another suite's 1 s reply window while the session was still closing. Each now belongs to one Scheduler (SetRetries) or one Server (replyWindow, phoneWindow, callLimit, resumedAt), defaulting to the same values, and a test sets its own. Co-Authored-By: Claude Opus 5.5 --- .claude/skills/scheduled-tasks/SKILL.md | 2 +- .../internal/api/router_suite_test.go | 3 + .../internal/api/scheduled_delivery.go | 28 ++++----- .../internal/api/scheduled_delivery_test.go | 8 ++- .../internal/api/scheduled_phone_test.go | 14 ++--- acceleration/internal/api/scheduled_tasks.go | 6 +- .../internal/api/scheduled_tasks_test.go | 57 ++++++++++++------- .../api/scheduled_thread_delivery_test.go | 2 +- .../internal/api/scheduled_unpaid_test.go | 18 +++--- acceleration/internal/api/server.go | 14 +++++ acceleration/internal/scheduling/scheduler.go | 15 +++-- 11 files changed, 102 insertions(+), 65 deletions(-) diff --git a/.claude/skills/scheduled-tasks/SKILL.md b/.claude/skills/scheduled-tasks/SKILL.md index a0acc61fe3..1679e9f66a 100644 --- a/.claude/skills/scheduled-tasks/SKILL.md +++ b/.claude/skills/scheduled-tasks/SKILL.md @@ -207,7 +207,7 @@ Run `error` codes (`internal/scheduling/scheduler.go:105`): | `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) | | `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 +A failure is retried after 30 s, 2 min and 10 min (`deliveryRetries`) only when the failure is not final; with several channels, it is final only when every channel's failure is. Worker log lines, as the code writes them (`grep -i 'scheduled task'` finds all but the diff --git a/acceleration/internal/api/router_suite_test.go b/acceleration/internal/api/router_suite_test.go index 157ed3f466..7fe82dd559 100644 --- a/acceleration/internal/api/router_suite_test.go +++ b/acceleration/internal/api/router_suite_test.go @@ -339,6 +339,9 @@ type RouterSuite struct { scheduledMu sync.Mutex scheduled []*schedulingModel schedulingScript schedulingScript + // retries, when set, are the waits the test's scheduled-task workers retry a failed + // occurrence after (newScheduler), in place of the scheduler's own. + retries []time.Duration // chat is the Stream Chat the conversations are written to and transcripts read from: // the deployment's own app. apps gives a customer an app of its own instead, and diff --git a/acceleration/internal/api/scheduled_delivery.go b/acceleration/internal/api/scheduled_delivery.go index 14bcaaa9f3..ddd569418f 100644 --- a/acceleration/internal/api/scheduled_delivery.go +++ b/acceleration/internal/api/scheduled_delivery.go @@ -48,16 +48,16 @@ var scheduledReplySettle = 2 * time.Second // scheduledReplyWindow bounds reading an answer for a channel. The lease is // renewed while a delivery runs, so a slow turn is waited out; one still // running at the window's end fails the channel, not the conversation. -var scheduledReplyWindow = 3 * time.Minute +const scheduledReplyWindow = 3 * time.Minute // scheduledPhoneWindow is how long a ring is waited out for somebody to // pick up: a vendor's ring is the best part of a minute. -var scheduledPhoneWindow = 90 * time.Second +const scheduledPhoneWindow = 90 * time.Second // scheduledCallLimit is how long a call a task placed may last: the agent // hangs up then, whatever is being said. A worker holds the call's slot // throughout, and a reminder is a short call, not an open line. -var scheduledCallLimit = 10 * time.Minute +const scheduledCallLimit = 10 * time.Minute // scheduledCallGrace is how late a task may still ring: past it the call is // not placed and the occurrence is missed, because a call long after the time @@ -70,9 +70,9 @@ const scheduledCallGrace = 15 * time.Minute // (scheduledPhoneWindow), the task sent as the call's first turn, which may // wait out a reply for scheduledWindow (followUpWithin), and the call held to // its limit (scheduledCallLimit). The occurrence's own budget still bounds -// it. A function, because tests shorten the ring and the limit. -func scheduledPeerWindow() time.Duration { - return scheduledPhoneWindow + scheduledWindow + scheduledCallLimit +// it. A method, because a test shortens the ring and the limit of its own router. +func (s *Server) scheduledPeerWindow() time.Duration { + return s.phoneWindow + scheduledWindow + s.callLimit } // errScheduledNotHere says the conversation's session is not live on this @@ -399,7 +399,7 @@ func textUnreachable(err error) error { // refusal about money (moneyError), such as a session that cannot open or a text whose // reservation is refused (routing.ReservationRefused). A suspension, spent credit or a spent limit // lasts until somebody pays or the limit resets, so the run's retries, minutes apart -// (scheduling.DeliveryRetries), would only be refused again. A refusal because the money could +// (the scheduler's delivery retries), would only be refused again. A refusal because the money could // not be checked (policy.Transient) passes again on its own, and is tried again. Any other error // is returned as it is. func unpaid(err error) error { @@ -524,7 +524,7 @@ func (s *Server) captureReply(ctx context.Context, found *session.Session, deliv var files []sandbox.Attachment active := found.Busy() last := time.Now() - deadline := time.Now().Add(scheduledReplyWindow) + deadline := time.Now().Add(s.replyWindow) ticker := time.NewTicker(250 * time.Millisecond) defer ticker.Stop() for { @@ -579,7 +579,7 @@ func (s *Server) followUpInConversation(ctx context.Context, found *session.Sess if err := s.followUpWithin(ctx, found, delivery); err != nil || known { return err } - deadline := time.Now().Add(scheduledReplyWindow) + deadline := time.Now().Add(s.replyWindow) ticker := time.NewTicker(s.replyPoll) defer ticker.Stop() for { @@ -683,7 +683,7 @@ func refusedAgain(found *session.Session, delivery scheduledDelivery) error { // has finished: the turn ran for a channel tried before this one, or for an // earlier attempt at the occurrence. func (s *Server) readBackReply(ctx context.Context, found *session.Session, id string) (conversation.FinishedReply, error) { - deadline := time.Now().Add(scheduledReplyWindow) + deadline := time.Now().Add(s.replyWindow) for { state, _, _ := found.FollowUpReply(id) switch state { @@ -912,7 +912,7 @@ func (s *Server) handDeliveryToPeer(ctx context.Context, delivery scheduledDeliv if err != nil { return none, false, err } - ask, cancel := context.WithTimeout(ctx, scheduledPeerWindow()) + ask, cancel := context.WithTimeout(ctx, s.scheduledPeerWindow()) answer, err := s.forwarder.Ask(ask, address, request, body) cancel() if err == nil && answer.GetStatus() == http.StatusOK { @@ -1169,7 +1169,7 @@ func (s *Server) placeCall(ctx context.Context, delivery scheduledDelivery, foun if from == "" { return session.Spec{}, undelivered(scheduling.ReasonNoLine, errors.New("the agent has no number to call from")) } - if deadline, ok := ctx.Deadline(); ok && time.Until(deadline) < scheduledPhoneWindow+scheduledCallLimit { + if deadline, ok := ctx.Deadline(); ok && time.Until(deadline) < s.phoneWindow+s.callLimit { return session.Spec{}, &scheduling.Missed{Err: fmt.Errorf("the call would have %s left to ring and be held", lateFor(time.Until(deadline)))} } placed, err := s.phone.Call(ctx, phone.CallRequest{ @@ -1277,7 +1277,7 @@ func (s *Server) holdCall(ctx context.Context, created *session.Session, deliver if created.CallerJoined() { return s.carryOutAnswered(ctx, created, delivery, events) } - ring := time.NewTimer(scheduledPhoneWindow) + ring := time.NewTimer(s.phoneWindow) defer ring.Stop() for { select { @@ -1308,7 +1308,7 @@ func (s *Server) carryOutAnswered(ctx context.Context, created *session.Session, if err := s.followUpWithin(ctx, created, delivery); err != nil { return undeliveredFinally(scheduling.ReasonFailed, err) } - limit := time.NewTimer(scheduledCallLimit) + limit := time.NewTimer(s.callLimit) defer limit.Stop() for { select { diff --git a/acceleration/internal/api/scheduled_delivery_test.go b/acceleration/internal/api/scheduled_delivery_test.go index a1abf993d9..a1d6d09b40 100644 --- a/acceleration/internal/api/scheduled_delivery_test.go +++ b/acceleration/internal/api/scheduled_delivery_test.go @@ -9,16 +9,20 @@ import ( "github.com/stretchr/testify/require" + "github.com/GetStream/Vision-Agents/acceleration/internal/routing" "github.com/GetStream/Vision-Agents/acceleration/internal/scheduling" "github.com/GetStream/Vision-Agents/acceleration/internal/store" ) func TestAPeerIsGivenLongEnoughToRingAndHoldATasksCall(t *testing.T) { + server, err := NewServer(Options{Routers: map[routing.Modality]routing.Inspector{routing.LLM: idleInspector{}}}) + require.NoError(t, err) // The ring, the task sent while a reply is waited out, and the call held // to its limit: 90 s + 10 min + 10 min. - require.Equal(t, 21*time.Minute+30*time.Second, scheduledPeerWindow()) - require.Greater(t, scheduledPeerWindow(), scheduledPhoneWindow+scheduledCallLimit+time.Minute, + require.Equal(t, 21*time.Minute+30*time.Second, server.scheduledPeerWindow()) + require.Greater(t, server.scheduledPeerWindow(), server.phoneWindow+server.callLimit+time.Minute, "a call answered at the last ring and held to its limit is not cut by the asker") + require.Equal(t, 3*time.Minute, server.replyWindow, "a router reads a channel's answer for 3 min") } // A peer handed an occurrence rebuilds its delivery with taskDelivery from the task's row, so diff --git a/acceleration/internal/api/scheduled_phone_test.go b/acceleration/internal/api/scheduled_phone_test.go index 8b7020a49f..1f34f43db7 100644 --- a/acceleration/internal/api/scheduled_phone_test.go +++ b/acceleration/internal/api/scheduled_phone_test.go @@ -133,9 +133,9 @@ func (s *ScheduledTasksSuite) outcomeOf(done <-chan callOutcome) callOutcome { // shortCalls has calls ring for ring and last for limit. func (s *ScheduledTasksSuite) shortCalls(ring, limit time.Duration) { - window, longest := scheduledPhoneWindow, scheduledCallLimit - scheduledPhoneWindow, scheduledCallLimit = ring, limit - s.T().Cleanup(func() { scheduledPhoneWindow, scheduledCallLimit = window, longest }) + window, longest := s.router.phoneWindow, s.router.callLimit + s.router.phoneWindow, s.router.callLimit = ring, limit + s.T().Cleanup(func() { s.router.phoneWindow, s.router.callLimit = window, longest }) } // shortOfTime has calls ring for half of deliveryWait and last for all of it, @@ -181,7 +181,7 @@ func (s *ScheduledTasksSuite) TestACallATaskPlacedIsGivenTheTaskAsItsFirstTurnAn s.NotContains(model.instructions(), " Date: Mon, 23 Nov 2026 21:43:54 +0100 Subject: [PATCH 2/5] test: a ring that runs out is the router's own window, not the default Co-Authored-By: Claude Opus 5.5 --- acceleration/internal/api/scheduled_tasks_test.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/acceleration/internal/api/scheduled_tasks_test.go b/acceleration/internal/api/scheduled_tasks_test.go index 2d6689e7da..3ad32932ff 100644 --- a/acceleration/internal/api/scheduled_tasks_test.go +++ b/acceleration/internal/api/scheduled_tasks_test.go @@ -3698,8 +3698,10 @@ func (s *ScheduledTasksSuite) TestACallNobodyPicksUpIsNotAnswered() { found, live := s.router.sessions.Get(opened.Id, s.ownerOf(user)) s.Require().True(live) + started := time.Now() err := s.router.holdCall(context.Background(), found, scheduledDelivery{}) s.Equal(scheduling.ReasonNotAnswered, scheduling.ReasonOf(err), "the ring ran out: %v", err) + s.Less(time.Since(started), deliveryWait, "the ring was the router's 50 ms, not the default 90 s") s.True(s.failure(err).Final, "the user is not rung again") s.router.phoneWindow = time.Minute From 829b63073b0b540369fa5fcba581f17353de9c35 Mon Sep 17 00:00:00 2001 From: Kanat Date: Mon, 23 Nov 2026 21:46:00 +0100 Subject: [PATCH 3/5] fix(test): keep the finish retries per worker too FinishRetries, new on main, is the same process-wide value a suite set and restored while other suites' workers read it. Co-Authored-By: Claude Opus 5.5 --- acceleration/internal/api/router_suite_test.go | 6 ++++-- acceleration/internal/api/scheduled_tasks_test.go | 13 ++++++++----- acceleration/internal/scheduling/AGENTS.md | 2 +- acceleration/internal/scheduling/scheduler.go | 12 +++++++++--- 4 files changed, 22 insertions(+), 11 deletions(-) diff --git a/acceleration/internal/api/router_suite_test.go b/acceleration/internal/api/router_suite_test.go index 7fe82dd559..9f1614d460 100644 --- a/acceleration/internal/api/router_suite_test.go +++ b/acceleration/internal/api/router_suite_test.go @@ -340,8 +340,10 @@ type RouterSuite struct { scheduled []*schedulingModel schedulingScript schedulingScript // retries, when set, are the waits the test's scheduled-task workers retry a failed - // occurrence after (newScheduler), in place of the scheduler's own. - retries []time.Duration + // occurrence after (newScheduler), in place of the scheduler's own; finishRetries the + // waits before they write a failed outcome again. + retries []time.Duration + finishRetries []time.Duration // chat is the Stream Chat the conversations are written to and transcripts read from: // the deployment's own app. apps gives a customer an app of its own instead, and diff --git a/acceleration/internal/api/scheduled_tasks_test.go b/acceleration/internal/api/scheduled_tasks_test.go index 3ad32932ff..68df36fc92 100644 --- a/acceleration/internal/api/scheduled_tasks_test.go +++ b/acceleration/internal/api/scheduled_tasks_test.go @@ -3778,12 +3778,15 @@ func (s *RouterSuite) retryAfter(waits ...time.Duration) { } // newScheduler is a scheduled-task worker delivering with deliver, retrying as the test set -// (retryAfter), else as the scheduler does. +// (retryAfter, finishAtOnce), else as the scheduler does. func (s *RouterSuite) newScheduler(deliver scheduling.DeliverFunc, logger *slog.Logger) *scheduling.Scheduler { worker := scheduling.NewScheduler(s.store, deliver, logger) if s.retries != nil { worker.SetRetries(s.retries) } + if s.finishRetries != nil { + worker.SetFinishRetries(s.finishRetries) + } return worker } @@ -3933,11 +3936,11 @@ func (s *ScheduledTasksSuite) TestAFirstOccurrenceRetriedTwiceFollowsUpInTheOneS s.Equal(1, ran, "every attempt followed up in the one session") } -// finishAtOnce has a finish that failed written again straight away, three times. +// finishAtOnce has a finish that failed written again straight away, three times, by the workers +// the test starts next (newScheduler). func (s *ScheduledTasksSuite) finishAtOnce() { - retries := scheduling.FinishRetries - scheduling.FinishRetries = []time.Duration{time.Millisecond, time.Millisecond, time.Millisecond} - s.T().Cleanup(func() { scheduling.FinishRetries = retries }) + s.finishRetries = []time.Duration{time.Millisecond, time.Millisecond, time.Millisecond} + s.T().Cleanup(func() { s.finishRetries = nil }) } // failFinishes has the database refuse the next times writes that finish a run of the test's diff --git a/acceleration/internal/scheduling/AGENTS.md b/acceleration/internal/scheduling/AGENTS.md index 3b3df3758c..54607b2b98 100644 --- a/acceleration/internal/scheduling/AGENTS.md +++ b/acceleration/internal/scheduling/AGENTS.md @@ -96,7 +96,7 @@ Each rule names the test that fails when it breaks. Suites: `SchedulerSuite` `TestStoreSuite/TestAnOccurrenceWhoseWorkersKeepDyingIsFailedAtTheAttemptCap`, `TestStoreSuite/TestTheAttemptCapRecordsWhatThePlacedCallLeft`, `TestSchedulerSuite/TestACappedOccurrence*` (two tests). -- **A failed finish is written again** (`FinishRetries`: 1 s, 2 s, 4 s): a run left running is +- **A failed finish is written again** (`finishRetries`: 1 s, 2 s, 4 s): a run left running is taken over once stale and delivered again. `TestScheduledTasksSuite/TestAnOccurrenceWhoseFinishFailsOnceIsTextedOnce`. - **A run's words are texted once per channel.** The delivery takes (run, channel) on the run diff --git a/acceleration/internal/scheduling/scheduler.go b/acceleration/internal/scheduling/scheduler.go index b011242dd8..e21e962a45 100644 --- a/acceleration/internal/scheduling/scheduler.go +++ b/acceleration/internal/scheduling/scheduler.go @@ -67,10 +67,10 @@ const maxConsecutiveFailures = 5 // being in progress; a task whose retries run out has failed an occurrence. var deliveryRetries = []time.Duration{30 * time.Second, 2 * time.Minute, 10 * time.Minute} -// FinishRetries are the waits before an occurrence's outcome is written again after the write +// finishRetries are the waits before an occurrence's outcome is written again after the write // failed, as a database that blinked fails it: a run left running is taken over by another // worker once it is stale, and delivered again. -var FinishRetries = []time.Duration{time.Second, 2 * time.Second, 4 * time.Second} +var finishRetries = []time.Duration{time.Second, 2 * time.Second, 4 * time.Second} // DeliverFunc delivers one claimed occurrence: it returns where the follow-up // landed (conversation, call, ...) and the session it landed in. An error is @@ -227,7 +227,7 @@ func NewScheduler(db *store.Store, deliver DeliverFunc, logger *slog.Logger) *Sc lease: scheduledLease, renewEvery: renewLeaseEvery, retries: deliveryRetries, - finishRetries: FinishRetries, + finishRetries: finishRetries, budget: occurrenceBudget, kick: make(chan struct{}, 1), slots: make(chan struct{}, inFlight), @@ -243,6 +243,12 @@ func (s *Scheduler) SetRetries(waits []time.Duration) { s.retries = waits } +// SetFinishRetries has the worker wait out waits before each next write of an outcome that failed +// to write, in place of finishRetries. Call it before Start. +func (s *Scheduler) SetFinishRetries(waits []time.Duration) { + s.finishRetries = waits +} + // SetActivity has each occurrence the worker settles counted in record, as area scheduling. Call // it before Start. func (s *Scheduler) SetActivity(record *activity.Recorder) { From 20d4aa34c5582a8ebf4d34692d1f3fc15d406718 Mon Sep 17 00:00:00 2001 From: Kanat Date: Mon, 23 Nov 2026 23:01:49 +0100 Subject: [PATCH 4/5] AI-3655: pin the scheduled phone window and call limit each Co-Authored-By: Claude Sonnet 5.5 --- acceleration/internal/api/scheduled_delivery_test.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/acceleration/internal/api/scheduled_delivery_test.go b/acceleration/internal/api/scheduled_delivery_test.go index a1d6d09b40..0ccaafe1fc 100644 --- a/acceleration/internal/api/scheduled_delivery_test.go +++ b/acceleration/internal/api/scheduled_delivery_test.go @@ -23,6 +23,8 @@ func TestAPeerIsGivenLongEnoughToRingAndHoldATasksCall(t *testing.T) { require.Greater(t, server.scheduledPeerWindow(), server.phoneWindow+server.callLimit+time.Minute, "a call answered at the last ring and held to its limit is not cut by the asker") require.Equal(t, 3*time.Minute, server.replyWindow, "a router reads a channel's answer for 3 min") + require.Equal(t, 90*time.Second, server.phoneWindow, "a router waits out a ring for 90 s") + require.Equal(t, 10*time.Minute, server.callLimit, "a call a task placed lasts 10 min at most") } // A peer handed an occurrence rebuilds its delivery with taskDelivery from the task's row, so From 0ea3798980a039f3bb1011a52607ec3a15c8d375 Mon Sep 17 00:00:00 2001 From: Kanat Date: Mon, 23 Nov 2026 23:02:59 +0100 Subject: [PATCH 5/5] AI-3655: pin how many times a failed finish is written again Co-Authored-By: Claude Sonnet 5.5 --- .../internal/api/scheduled_tasks_test.go | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/acceleration/internal/api/scheduled_tasks_test.go b/acceleration/internal/api/scheduled_tasks_test.go index 68df36fc92..3eb42193d3 100644 --- a/acceleration/internal/api/scheduled_tasks_test.go +++ b/acceleration/internal/api/scheduled_tasks_test.go @@ -3982,6 +3982,40 @@ func (s *ScheduledTasksSuite) TestAnOccurrenceWhoseFinishFailsOnceIsTextedOnce() s.Equal([]string{"Done."}, s.sink.to(writer)) } +// finishRefusedTwice texts a task's run with waits to write the finish again, the database +// refusing its first two writes, and returns the run once the worker is done with it. +func (s *ScheduledTasksSuite) finishRefusedTwice(waits int) store.ScheduledTaskRun { + number, writer := s.lineNumber(), s.writerNumber() + s.connectWhatsApp(number) + config := s.agentOnWhatsApp(number) + user := s.data.createUser() + s.seedWriter(user, config, number, writer) + opened := s.openScheduling(user, config, nil) + s.taskOn(user, config, opened.Id, []string{"whatsapp"}) + s.finishAtOnce() + s.finishRetries = s.finishRetries[:waits] + s.failFinishes(2) + s.runWorker() + task := s.tasksOf(user)[0] + s.makeDue(task) + s.Require().Eventually(func() bool { return len(s.sink.to(writer)) == 1 && s.worker.Running() == 0 }, + 30*time.Second, 50*time.Millisecond, "the worker never texted the run and gave up or finished it") + runs := s.runsOf(task) + s.Require().Len(runs, 1) + return runs[0] +} + +// A finish that failed is written again once per wait the worker is given, no more: one wait +// writes it twice, both refused, and leaves the run running. +func (s *ScheduledTasksSuite) TestAFinishIsNotWrittenAgainPastTheWaitsItIsGiven() { + s.Equal(store.ScheduledTaskRunRunning, s.finishRefusedTwice(1).State) +} + +// Three waits write the finish a third time, once two refusals are past. +func (s *ScheduledTasksSuite) TestAFinishIsWrittenAgainOncePerWaitItIsGiven() { + s.Equal(store.ScheduledTaskRunDelivered, s.finishRefusedTwice(3).State) +} + // A run whose text went out and whose outcome was never written, its worker stopped or its // database down past the finish's retries, is taken over; the words went out already. func (s *ScheduledTasksSuite) TestAnOccurrenceTakenOverAfterItsTextWentOutIsNotTextedAgain() {