Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .claude/skills/scheduled-tasks/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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_<run>_r1`: the scheduler hands the next attempt the reason this one failed under (`deliverWithRetries`), a hand-off to the router holding the session carries it (`scheduledHandOff.Earlier`), and `replyCommand` reruns a failed reply after a money code. A conversation rerun refused as well fails the attempt under the same code (`followUpInConversation`), so the run fails once its retries are spent. A reply that failed for any other reason is read back as it was | yes (`unpaid` leaves it retryable) |
| `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
Expand Down
5 changes: 5 additions & 0 deletions acceleration/internal/api/router_suite_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -339,6 +339,11 @@ 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; 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
Expand Down
28 changes: 14 additions & 14 deletions acceleration/internal/api/scheduled_delivery.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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{
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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 {
Expand Down
10 changes: 8 additions & 2 deletions acceleration/internal/api/scheduled_delivery_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,22 @@ 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")

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Should fix] R1.1 The control test checks replyWindow and the sum phoneWindow + scheduledWindow + callLimit, but not the ring and the call limit on their own. A mutant of NewServer that swaps them (phoneWindow: scheduledCallLimit, callLimit: scheduledPhoneWindow) keeps the sum at 21 min 30 s and passes this test. In production, that mutant rings for 10 min and hangs up after 90 s. No integration test covers the two defaults either, because every phone test shortens both.

Fix: add these two lines here (I checked them in a scratch copy: they pass on head and fail under the mutant with expected: 1m30s, actual: 10m0s).

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")

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 20d4aa3: TestAPeerIsGivenLongEnoughToRingAndHoldATasksCall now requires phoneWindow == 90s and callLimit == 10m each. With the two NewServer defaults swapped it fails (expected 1m30s, actual 10m0s).

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

R1.2 (no thread of its own) fixed in 0ea3798: TestScheduledTasksSuite/TestAFinishIsNotWrittenAgainPastTheWaitsItIsGiven (1 wait, 2 refusals leaves the run running) and TestAFinishIsWrittenAgainOncePerWaitItIsGiven (3 waits settle it). SetFinishRetries as a no-op and newScheduler dropping the finishRetries branch both fail the first.

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
Expand Down
14 changes: 6 additions & 8 deletions acceleration/internal/api/scheduled_phone_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -181,7 +181,7 @@ func (s *ScheduledTasksSuite) TestACallATaskPlacedIsGivenTheTaskAsItsFirstTurnAn
s.NotContains(model.instructions(), "<scheduled_task", "the task is no part of what the agent is told it is")
s.NotContains(model.instructions(), "Remind them to stretch.")
s.Contains(model.instructions(), "You have called this number", "the agent knows it placed the call")
s.GreaterOrEqual(time.Since(started), scheduledCallLimit, "the call was held until its limit")
s.GreaterOrEqual(time.Since(started), s.router.callLimit, "the call was held until its limit")
_, live := s.router.sessions.Get(call.spec.ID, session.OwnerOf(call.spec))
s.False(live, "the agent hung up at the call's limit")
}
Expand Down Expand Up @@ -334,9 +334,7 @@ func (s *ScheduledTasksSuite) settledRun(task store.ScheduledTask) store.Schedul
// retryLate has a failed occurrence wait ten minutes before it is tried
// again, so one that finishes at once was not retried.
func (s *ScheduledTasksSuite) retryLate() {
retries := scheduling.DeliveryRetries
scheduling.DeliveryRetries = []time.Duration{10 * time.Minute}
s.T().Cleanup(func() { scheduling.DeliveryRetries = retries })
s.retryAfter(10 * time.Minute)
}

func (s *ScheduledTasksSuite) TestAPhoneTaskMoreThanAQuarterHourLateIsMissedWithoutACall() {
Expand Down Expand Up @@ -543,7 +541,7 @@ func (s *ScheduledTasksSuite) TestACallTheOccurrenceHasTimeToRingAndHoldIsTried(
s.shortCalls(2*time.Second, 10*time.Second)
task := s.phoneTask(s.data.createUser(), []string{"phone"}, time.Now())

run, err := s.deliverWithin(task, scheduledPhoneWindow+scheduledCallLimit+deliveryWait)
run, err := s.deliverWithin(task, s.router.phoneWindow+s.router.callLimit+deliveryWait)

failure := s.failure(err)
s.Equal(scheduling.ReasonFailed, failure.Reason, "the call was tried, and none can be placed here")
Expand Down
6 changes: 1 addition & 5 deletions acceleration/internal/api/scheduled_tasks.go
Original file line number Diff line number Diff line change
Expand Up @@ -524,10 +524,6 @@ func (s *Server) pauseScheduledTask(ctx context.Context, request *pauseScheduled
return &pauseScheduledTaskResponse{Body: rendered}, nil
}

// resumedAt is the clock a resume counts a task's next run from. A test sets
// it to resume inside an hour the wall clock is not in.
var resumedAt = time.Now

func (s *Server) resumeScheduledTask(ctx context.Context, request *resumeScheduledTaskRequest) (*resumeScheduledTaskResponse, error) {
customerID, failure := s.scheduledTasksCustomer(ctx)
if failure != nil {
Expand All @@ -546,7 +542,7 @@ func (s *Server) resumeScheduledTask(ctx context.Context, request *resumeSchedul
return nil, scheduleFailure(err)
}
// Counted from now: what a pause slept through is never replayed.
next, ok := schedule.Next(resumedAt())
next, ok := schedule.Next(s.resumedAt())
if !ok {
// A one-shot whose time came while it was paused takes no place and runs
// on nothing: it is only closed, with the occurrence it slept through on
Expand Down
Loading
Loading