From 0dd1b5702ef5049cec76fff26fb0ecc020f5ae71 Mon Sep 17 00:00:00 2001 From: Andy Staples Date: Fri, 20 Nov 2026 11:51:07 -0700 Subject: [PATCH 1/3] Add selectable orchestration channels Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- CHANGELOG.md | 1 + README.md | 74 +++ cmd/orchestratorvet/README.md | 8 +- samples/coroutines/README.md | 12 +- samples/coroutines/coroutines.go | 61 +- task/cancel.go | 8 + task/channel.go | 333 +++++++++++ task/channel_test.go | 539 ++++++++++++++++++ task/coroutine.go | 1 + task/eventchannel.go | 21 +- task/orchestrator.go | 5 + task/select.go | 152 +++-- .../dts_coroutine_review_test.go | 90 +++ 13 files changed, 1238 insertions(+), 67 deletions(-) create mode 100644 task/channel.go create mode 100644 task/channel_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 9083bcc1..f0ee1957 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- Added typed orchestration-local `task.NewChannel[T]` with buffered and unbuffered send/receive operations, cancellation-aware error forms, and `OnSend`/`OnReceive` cases for durable `Select`. Rendezvous selection commits both endpoints without performing losing operations. Channel waits yield to the existing scheduler and replay reconstructs their state. Channel-only waits with no pending durable work or external event receiver fail with `task.ErrOrchestrationDeadlock`; detection is conservative and channels do not support close. Added `ctx.IsCanceled()` to inspect applied durable scope cancellation. - Added required completion-transport isolation to gRPC workers: one intake and three dedicated completion/abandon connections by default, with a configurable 1–8 completion budget and bounded generation-safe retirement. `WithWorkerCompletionConnections(0)` is invalid. Borrowed workers and client listeners require separate caller-owned channels via `WithWorkerCompletionTransports`; owning factories must return distinct connections and non-nil closers for every invocation. - Added `ResourceId` connection-string support for every DTS authentication mode and optional `AuthorityHost` configuration for SDK-created DefaultAzure, WorkloadIdentity, Environment, and InteractiveBrowser credentials. Caller-supplied credentials own their authority; managed identity and developer-tool cloud configuration remain separate. - Added a flat catalogue of directly runnable DTS samples with outcome assertions, owned-resource cleanup, and process-level E2E validation selected by sample name using Go's `-run` flag. diff --git a/README.md b/README.md index 6abc0d89..d8fb1c76 100644 --- a/README.md +++ b/README.md @@ -311,6 +311,80 @@ Obey these rules when you write a retry handler: Full sample: [samples/retries](./samples/retries). +### Selectable coroutine channels + +Use `task.NewChannel[T](ctx, capacity)` to pass values between `ctx.Go` branches +inside one orchestration. Capacity zero requires a sender/receiver rendezvous; +positive capacity provides a bounded FIFO buffer. This is separate from +`task.NewEventChannel`, which receives events raised by clients or other +orchestrations. + +```go +results := task.NewChannel[int](ctx, 0) +ctx.Go(func(branch *task.OrchestrationContext) { + var value int + if err := branch.CallActivity("Calculate").Await(&value); err != nil { + panic(err) + } + results.Send(branch, value) +}) +value := results.Receive(ctx) +``` + +`Send` and `Receive` are the durable equivalents of Go's `ch <- value` and +`value := <-ch`. `SendErr` and `ReceiveErr` return `task.ErrTaskCanceled` if the +waiting scope is canceled before the operation commits; the convenience forms +panic on cancellation. A committed exchange is not undone by later +cancellation. Values are passed by assignment without serialization, like Go +channels; do not mutate shared values concurrently or make replay-unsafe values +in orchestration code. + +Use the existing selector to wait for channel operations alongside durable +tasks and external events: + +```go +ctx.Select( + task.OnReceive(results, func(value int) { /* process value */ }), + task.OnEvent(task.NewEventChannel[string](ctx, "Stop"), func(string) { + /* request cancellation of branch operations */ + }), + task.OnTask(timer, func(task.Task) { /* handle timeout */ }), +) +``` + +`task.OnSend(channel, value, handler)` is the send equivalent. Only the winning +case sends or consumes a value. For an unbuffered exchange, both selections +commit their channel cases before either callback runs. Each callback executes +in its own selecting coroutine. Task and external event readiness is ordered +by history; channel readiness is ordered deterministically by the SDK scheduler. +Argument order breaks ties, but does not give a stop event priority over an +earlier ready result. Create distinct cases for each alternative within a +single `Select`; a case can be reused by later calls. + +Channel waits yield to the SDK, allowing other branches to schedule activities. +When all branches are waiting and available history is exhausted, the execution +unloads and its durable actions are dispatched. Replay reconstructs branches, +buffers, and exchanges; channels do not keep goroutines alive between turns. +Never use native Go channels or native `select` inside an orchestrator. + +If channel operations are waiting with no runnable coroutine, pending durable +task, or external event wait, the SDK fails the orchestration with +`task.ErrOrchestrationDeadlock` rather than leaving an unrecoverable local +cycle silently stuck. Detection is conservative: pending durable work prevents +this diagnosis even if application logic will still be unable to progress. +It cannot detect arbitrary application loops that never yield. Channels have +no close operation; use known result counts, explicit completion messages, or +cancellation to finish receivers. + +`ctx.IsCanceled()` inspects applied cancellation of the durable scope, not the +host Go context. Cancellation requested by a `WithCancel` cancel function is +applied at the next scheduler boundary. Canceling a scope releases its pending +channel operations without closing the shared channel or canceling other +scopes. It does not guarantee an already-dispatched activity stops remotely. +Join uncanceled coroutine wrappers when cleanup must finish before returning. + +Full sample: [samples/coroutines](./samples/coroutines). + ### Deferred work and cooperative cleanup A root or child coroutine's defers can schedule and await durable work during diff --git a/cmd/orchestratorvet/README.md b/cmd/orchestratorvet/README.md index a4abd519..3da76b62 100644 --- a/cmd/orchestratorvet/README.md +++ b/cmd/orchestratorvet/README.md @@ -88,9 +88,11 @@ creation, send, receive, range, and close, and `select` statements. The check keys on the package that declares a method, so an embedded `sync.Mutex` is recognized through the embedding type. -Not reported: `ctx.Go`, `ctx.NewWaitGroup`, `ctx.Select` with `task.OnTask` or -`task.OnEvent`, `task.NewEventChannel`, and `ctx.WaitForSingleEvent`. These are -scheduled by the deterministic orchestration scheduler. +Not reported: `ctx.Go`, `ctx.NewWaitGroup`, `ctx.Select` with `task.OnTask`, +`task.OnEvent`, `task.OnSend`, or `task.OnReceive`, `task.NewChannel`, +`task.NewEventChannel`, and `ctx.WaitForSingleEvent`. SDK channel operations +are also safe: they yield through the deterministic orchestration scheduler, +not native Go channel synchronization. ### External I/O diff --git a/samples/coroutines/README.md b/samples/coroutines/README.md index 846526d0..b95612e0 100644 --- a/samples/coroutines/README.md +++ b/samples/coroutines/README.md @@ -4,9 +4,11 @@ - Starts bounded orchestration coroutines with `ctx.Go`. - Coordinates coroutine completion with `ctx.NewWaitGroup`. -- Uses `Select` on a typed event channel and a durable timer from a child - cancellation scope. +- Sends activity results through an unbuffered `task.NewChannel`. +- Uses `Select` to receive branch results alongside a typed external event + channel and a durable timer from a child cancellation scope. - Cancels the losing timer when the approval event wins. +- Cancels branch operations and joins their uncanceled wrappers on failure. - Validates the returned doubled values and selected event outcome. ## Prerequisites @@ -34,6 +36,12 @@ it prints: SAMPLE_OK coroutines ``` +Channel operations yield to the SDK scheduler, not Go's native channel +scheduler. Once all branches are waiting and available history is exhausted, +the worker unloads the entire execution and dispatches its pending activities. +Replay recreates the branches and their channel exchanges; no goroutine remains +alive waiting for an activity on another worker. + ## Cleanup The sample terminates if needed and recursively purges only its generated diff --git a/samples/coroutines/coroutines.go b/samples/coroutines/coroutines.go index af45a4e7..5439fa60 100644 --- a/samples/coroutines/coroutines.go +++ b/samples/coroutines/coroutines.go @@ -30,6 +30,12 @@ type coroutineOutput struct { Sum int `json:"sum"` } +type coroutineResult struct { + index int + value int + err error +} + func main() { if err := run(); err != nil { log.Fatal(err) @@ -107,17 +113,23 @@ func CoroutineFanInOrchestrator(ctx *task.OrchestrationContext) (any, error) { } doubled := make([]int, len(input.Values)) + results := task.NewChannel[coroutineResult](ctx, 0) + workCtx, cancelWork := ctx.WithCancel() waitGroup := ctx.NewWaitGroup() waitGroup.Add(len(input.Values)) for i, value := range input.Values { i, value := i, value - ctx.Go(func(ctx *task.OrchestrationContext) { + ctx.Go(func(*task.OrchestrationContext) { defer waitGroup.Done() var result int - if err := ctx.CallActivity("DoubleValue", task.WithActivityInput(value)).Await(&result); err != nil { + err := workCtx.CallActivity("DoubleValue", task.WithActivityInput(value)).Await(&result) + if errors.Is(err, task.ErrTaskCanceled) { + return + } + if err := results.SendErr(workCtx, coroutineResult{index: i, value: result, err: err}); err != nil && + !errors.Is(err, task.ErrTaskCanceled) { panic(err) } - doubled[i] = result }) } @@ -125,17 +137,42 @@ func CoroutineFanInOrchestrator(ctx *task.OrchestrationContext) (any, error) { timer := timerCtx.CreateTimer(input.ApprovalWindow) approvals := task.NewEventChannel[string](ctx, "Approval") selected := "timeout" - ctx.Select( - task.OnEvent(approvals, func(value string) { - selected = "event:" + value - cancelTimer() - }), - task.OnTask(timer, func(task.Task) { - selected = "timeout" - }), - ) + decisionMade := false + received := 0 + var failure error + for (received < len(input.Values) || !decisionMade) && failure == nil { + var cases []task.SelectCase + if received < len(input.Values) { + cases = append(cases, task.OnReceive(results, func(result coroutineResult) { + failure = result.err + doubled[result.index] = result.value + received++ + })) + } + if !decisionMade { + cases = append(cases, + task.OnEvent(approvals, func(value string) { + selected = "event:" + value + decisionMade = true + cancelTimer() + }), + task.OnTask(timer, func(task.Task) { + selected = "timeout" + decisionMade = true + }), + ) + } + ctx.Select(cases...) + } + if failure != nil { + cancelWork() + cancelTimer() + } waitGroup.Wait(ctx) + if failure != nil { + return nil, failure + } sum := 0 for _, value := range doubled { sum += value diff --git a/task/cancel.go b/task/cancel.go index 1afbb377..70e3dfae 100644 --- a/task/cancel.go +++ b/task/cancel.go @@ -1,5 +1,13 @@ package task +// IsCanceled reports applied cancellation of this orchestration scope. +// WithCancel's cancel function queues cancellation for the next scheduler +// boundary, so IsCanceled need not become true immediately after calling it. +func (ctx *OrchestrationContext) IsCanceled() bool { + ctx.effectContext() + return ctx.scope.isCanceled() +} + type cancellationScope struct { parent *cancellationScope parentIndex int diff --git a/task/channel.go b/task/channel.go new file mode 100644 index 00000000..77cd8fb8 --- /dev/null +++ b/task/channel.go @@ -0,0 +1,333 @@ +package task + +import ( + "errors" + "slices" +) + +// ErrOrchestrationDeadlock identifies channel waits that cannot make progress: +// no coroutine is runnable and no durable task or external event wait can wake +// the orchestration. The execution fails rather than remaining silently stuck. +var ErrOrchestrationDeadlock = errors.New("orchestration deadlock: channel operations are waiting with no pending durable work or external event receiver") + +// Channel exchanges values between coroutines in one orchestration. It is +// reconstructed on replay, not a transport between orchestration instances. +// Values are passed by assignment, like Go channels, without serialization. +// Blocking operations yield to the durable scheduler; never use native Go +// channels for orchestration coordination. +type Channel[T any] struct { + ctx *OrchestrationContext + capacity int + buffer []channelValue[T] + senders []*channelOperation[T] + receivers []*channelOperation[T] +} + +type channelValue[T any] struct { + value T + order uint64 +} + +type channelOperation[T any] struct { + selection *selection + candidate *channelSelectCase[T] + matches []*channelMatch[T] + order uint64 + ready bool +} + +// Each potential rendezvous has one globally unique readiness order shared by +// both endpoints. This prevents cyclic preferences between competing selects. +type channelMatch[T any] struct { + sender *channelOperation[T] + receiver *channelOperation[T] + order uint64 +} + +// NewChannel creates a fresh orchestration-local channel. Zero capacity +// requires a sender/receiver rendezvous; positive capacity provides a bounded +// FIFO buffer. Channels do not support close: use completion messages, known +// result counts, or cancellation to finish receivers. +func NewChannel[T any](ctx *OrchestrationContext, capacity int) *Channel[T] { + if ctx == nil { + panic("channel requires an orchestration context") + } + if capacity < 0 { + panic("channel capacity must not be negative") + } + engine := ctx.effectContext() + if engine.scheduler == nil { + panic("channel created outside orchestrator execution") + } + return &Channel[T]{ctx: engine, capacity: capacity} +} + +// Send waits until value can be sent. It panics on cancellation. +func (c *Channel[T]) Send(ctx *OrchestrationContext, value T) { + if err := c.SendErr(ctx, value); err != nil { + panic(err) + } +} + +// SendErr waits until value can be sent, returning ErrTaskCanceled if the +// waiting scope is canceled before the send commits. +func (c *Channel[T]) SendErr(ctx *OrchestrationContext, value T) error { + _, err := ctx.selectCaseErr([]SelectCase{OnSend(c, value, nil)}) + return err +} + +// Receive waits for the next value. It panics on cancellation. +func (c *Channel[T]) Receive(ctx *OrchestrationContext) T { + value, err := c.ReceiveErr(ctx) + if err != nil { + panic(err) + } + return value +} + +// ReceiveErr waits for the next value, returning ErrTaskCanceled if the +// waiting scope is canceled before the receive commits. +func (c *Channel[T]) ReceiveErr(ctx *OrchestrationContext) (T, error) { + var value T + _, err := ctx.selectCaseErr([]SelectCase{OnReceive(c, func(received T) { + value = received + })}) + return value, err +} + +type channelSelectCase[T any] struct { + channel *Channel[T] + send bool + value T + onSend func() + onReceive func(T) + operations map[*selection]*channelOperation[T] +} + +// OnReceive creates a Select case that consumes one channel value only if it +// wins. The handler runs in the selecting coroutine. +func OnReceive[T any](channel *Channel[T], handler func(T)) SelectCase { + if channel == nil { + panic("receive Select case requires a channel") + } + return &channelSelectCase[T]{channel: channel, onReceive: handler} +} + +// OnSend creates a Select case that sends value only if it wins. The handler +// runs in the selecting coroutine after the send commits. +func OnSend[T any](channel *Channel[T], value T, handler func()) SelectCase { + if channel == nil { + panic("send Select case requires a channel") + } + return &channelSelectCase[T]{channel: channel, send: true, value: value, onSend: handler} +} + +func (c *channelSelectCase[T]) owner() *OrchestrationContext { + return c.channel.ctx +} + +func (c *channelSelectCase[T]) subscribe(s *selection) { + if c.operations == nil { + c.operations = make(map[*selection]*channelOperation[T]) + } + op := &channelOperation[T]{selection: s, candidate: c} + c.operations[s] = op + channel := c.channel + peers := channel.senders + if c.send { + peers = channel.receivers + channel.senders = append(channel.senders, op) + } else { + channel.receivers = append(channel.receivers, op) + } + if channel.capacity == 0 { + for _, peer := range peers { + if peer.selection == s || !peer.selection.pending() { + continue + } + match := &channelMatch[T]{order: channel.ctx.scheduler.nextCompletionID()} + if c.send { + match.sender, match.receiver = op, peer + } else { + match.sender, match.receiver = peer, op + } + op.matches = append(op.matches, match) + peer.matches = append(peer.matches, match) + } + } + channel.notify() +} + +func (c *channelSelectCase[T]) unsubscribe(s *selection) { + op := c.operations[s] + if op == nil { + return + } + delete(c.operations, s) + channel := c.channel + if c.send { + channel.senders = slices.DeleteFunc(channel.senders, func(other *channelOperation[T]) bool { + return other == op + }) + } else { + channel.receivers = slices.DeleteFunc(channel.receivers, func(other *channelOperation[T]) bool { + return other == op + }) + } + for _, match := range op.matches { + peer := match.sender + if c.send { + peer = match.receiver + } + peer.matches = slices.DeleteFunc(peer.matches, func(other *channelMatch[T]) bool { + return other == match + }) + } + op.matches = nil + channel.notify() +} + +func (op *channelOperation[T]) firstMatch() *channelMatch[T] { + for _, match := range op.matches { + if match.sender.selection.pending() && match.receiver.selection.pending() { + return match + } + } + return nil +} + +func (c *channelSelectCase[T]) ready(s *selection) (bool, uint64) { + op := c.operations[s] + if op == nil { + return false, 0 + } + if c.channel.capacity == 0 { + if match := op.firstMatch(); match != nil { + return true, match.order + } + return false, 0 + } + if c.send { + return op.ready, op.order + } + if len(c.channel.buffer) != 0 { + return true, c.channel.buffer[0].order + } + return false, 0 +} + +func (c *channelSelectCase[T]) commit(s *selection) bool { + channel := c.channel + if channel.capacity == 0 { + match := c.operations[s].firstMatch() + if match == nil { + return false + } + peer := match.sender + if c.send { + peer = match.receiver + } + // Do not steal a waiting peer from an earlier ready task, event, or + // rendezvous. Let that coroutine resolve its preferred case first. + if peer.selection.preferred() != peer.candidate { + channel.ctx.scheduler.makeRunnable(peer.selection.coroutine) + return false + } + // A case can have multiple peers; both must prefer this exact match. + if peer.firstMatch() != match { + channel.ctx.scheduler.makeRunnable(peer.selection.coroutine) + return false + } + value := match.sender.candidate.value + sendHandler := match.sender.candidate.onSend + receiveHandler := match.receiver.candidate.onReceive + match.sender.selection.finish(match.sender.candidate, sendHandler) + match.receiver.selection.finish(match.receiver.candidate, func() { + if receiveHandler != nil { + receiveHandler(value) + } + }) + return true + } + if c.send { + channel.buffer = append(channel.buffer, channelValue[T]{ + value: c.value, + order: channel.ctx.scheduler.nextCompletionID(), + }) + s.finish(c, c.onSend) + } else { + value := channel.buffer[0].value + channel.buffer = slices.Delete(channel.buffer, 0, 1) + s.finish(c, func() { + if c.onReceive != nil { + c.onReceive(value) + } + }) + } + channel.notify() + return true +} + +func (c *Channel[T]) notify() { + slots := c.capacity - len(c.buffer) + for _, op := range c.senders { + if !op.selection.pending() { + continue + } + if c.capacity > 0 { + ready := slots > 0 + if ready { + slots-- + } + if ready && !op.ready { + op.order = c.ctx.scheduler.nextCompletionID() + } + op.ready = ready + } + c.ctx.scheduler.makeRunnable(op.selection.coroutine) + } + for _, op := range c.receivers { + if op.selection.pending() { + c.ctx.scheduler.makeRunnable(op.selection.coroutine) + } + } +} + +func (s *coroutineScheduler) hasChannelDeadlock() bool { + channelWait := false + for _, c := range s.all { + if c.selection == nil || !c.selection.pending() { + continue + } + for _, candidate := range c.selection.cases { + if _, ok := candidate.(interface{ channelCase() }); ok { + channelWait = true + } + } + } + if !channelWait { + return false + } + // Be conservative: even work not directly awaited by a coroutine may + // complete a compound task and wake a branch. + for _, task := range s.ctx.pendingTasks { + if !task.isCompleted { + return false + } + } + for _, task := range s.ctx.pendingEntityTasks { + if !task.isCompleted { + return false + } + } + for _, tasks := range s.ctx.pendingExternalEventTasks { + for item := tasks.Front(); item != nil; item = item.Next() { + if !item.Value.(*completableTask).isCompleted { + return false + } + } + } + return len(s.ctx.eventWaiters) == 0 +} + +func (*channelSelectCase[T]) channelCase() {} diff --git a/task/channel_test.go b/task/channel_test.go new file mode 100644 index 00000000..9a7242d4 --- /dev/null +++ b/task/channel_test.go @@ -0,0 +1,539 @@ +package task + +import ( + "errors" + "fmt" + "slices" + "testing" + "time" + + "github.com/microsoft/durabletask-go/internal/helpers" + "github.com/microsoft/durabletask-go/internal/protos" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/types/known/wrapperspb" +) + +func channelRegistry(t *testing.T, fn Orchestrator) *TaskRegistry { + t.Helper() + registry := NewTaskRegistry() + require.NoError(t, registry.AddOrchestratorN("channels", fn)) + return registry +} + +func channelStart() []*protos.HistoryEvent { + return []*protos.HistoryEvent{ + helpers.NewOrchestratorStartedEvent(), + helpers.NewExecutionStartedEvent("channels", "instance", nil, nil, nil, nil), + } +} + +func TestChannelRendezvousAndBufferedFIFO(t *testing.T) { + for _, capacity := range []int{0, 1, 3} { + t.Run(fmt.Sprint(capacity), func(t *testing.T) { + registry := channelRegistry(t, func(ctx *OrchestrationContext) (any, error) { + channel := NewChannel[int](ctx, capacity) + wg := ctx.NewWaitGroup() + wg.Add(1) + ctx.Go(func(ctx *OrchestrationContext) { + defer wg.Done() + for _, value := range []int{1, 2, 3} { + channel.Send(ctx, value) + } + }) + results := []int{channel.Receive(ctx), channel.Receive(ctx), channel.Receive(ctx)} + wg.Wait(ctx) + assert.Empty(t, channel.senders) + assert.Empty(t, channel.receivers) + assert.Empty(t, channel.buffer) + return results, nil + }) + for range 10 { + response := executeOrchestrationTurn(t, registry, "instance", nil, channelStart()) + require.Equal(t, "[1,2,3]", completionResult(t, response)) + require.Len(t, response.Actions, 1) + } + }) + } +} + +func TestChannelSelectRendezvousCommitsOnlyWinningCases(t *testing.T) { + registry := channelRegistry(t, func(ctx *OrchestrationContext) (any, error) { + first := NewChannel[int](ctx, 0) + second := NewChannel[int](ctx, 0) + sent := "" + received := 0 + wg := ctx.NewWaitGroup() + wg.Add(1) + ctx.Go(func(ctx *OrchestrationContext) { + defer wg.Done() + ctx.Select( + OnSend(first, 1, func() { sent = "first" }), + OnSend(second, 2, func() { sent = "second" }), + ) + }) + ctx.Select( + OnReceive(second, func(value int) { received = value }), + OnReceive(first, func(value int) { received = value }), + ) + wg.Wait(ctx) + assert.Empty(t, first.senders) + assert.Empty(t, first.receivers) + assert.Empty(t, second.senders) + assert.Empty(t, second.receivers) + return []any{sent, received}, nil + }) + response := executeOrchestrationTurn(t, registry, "instance", nil, channelStart()) + require.Equal(t, `["first",1]`, completionResult(t, response)) +} + +func TestChannelSelectDoesNotStealPeerFromEarlierReadyTask(t *testing.T) { + registry := channelRegistry(t, func(ctx *OrchestrationContext) (any, error) { + channel := NewChannel[int](ctx, 0) + ready := newTaskInScope(ctx, ctx.scope) + ready.complete(nil) + sent := false + wg := ctx.NewWaitGroup() + wg.Add(1) + ctx.Go(func(ctx *OrchestrationContext) { + defer wg.Done() + ctx.Select( + OnSend(channel, 42, func() { sent = true }), + OnTask(ready, nil), + ) + }) + ctx.Select(OnReceive(channel, func(int) { panic("losing send executed") }), OnTask(ready, nil)) + wg.Wait(ctx) + return sent, nil + }) + response := executeOrchestrationTurn(t, registry, "instance", nil, channelStart()) + require.Equal(t, "false", completionResult(t, response)) +} + +func TestChannelRendezvousRespectsWaitingPeersOtherReadyCase(t *testing.T) { + registry := channelRegistry(t, func(ctx *OrchestrationContext) (any, error) { + channel := NewChannel[int](ctx, 0) + ready := newTaskInScope(ctx, ctx.scope) + sent := false + value := 0 + wg := ctx.NewWaitGroup() + wg.Add(3) + ctx.Go(func(ctx *OrchestrationContext) { + defer wg.Done() + ctx.Select(OnSend(channel, 1, func() { sent = true }), OnTask(ready, nil)) + }) + ctx.Go(func(ctx *OrchestrationContext) { + defer wg.Done() + ready.complete(nil) + value = channel.Receive(ctx) + }) + ctx.Go(func(ctx *OrchestrationContext) { + defer wg.Done() + channel.Send(ctx, 2) + }) + wg.Wait(ctx) + return []any{sent, value}, nil + }) + response := executeOrchestrationTurn(t, registry, "instance", nil, channelStart()) + require.Equal(t, "[false,2]", completionResult(t, response)) +} + +func TestChannelCompetingSelectsMakeProgressBeforeDurableWait(t *testing.T) { + selected := 0 + registry := channelRegistry(t, func(ctx *OrchestrationContext) (any, error) { + selected = 0 + a, b, c := NewChannel[int](ctx, 0), NewChannel[int](ctx, 0), NewChannel[int](ctx, 0) + timer := ctx.CreateTimer(time.Hour) + wg := ctx.NewWaitGroup() + wg.Add(3) + for _, pair := range [][2]*Channel[int]{{a, c}, {b, a}, {c, b}} { + ctx.Go(func(ctx *OrchestrationContext) { + defer wg.Done() + ctx.Select( + OnSend(pair[0], 1, func() { selected++ }), + OnReceive(pair[1], func(int) { selected++ }), + OnTask(timer, func(Task) { selected++ }), + ) + }) + } + wg.Wait(ctx) + return selected, nil + }) + start := channelStart() + first := executeOrchestrationTurn(t, registry, "instance", nil, start) + require.Equal(t, 2, selected, "ready rendezvous must not stall behind the timer") + require.Len(t, first.Actions, 1) + require.NotNil(t, first.Actions[0].GetCreateTimer()) + history := append(slices.Clone(start), helpers.NewTimerCreatedEvent(0, first.Actions[0].GetCreateTimer().FireAt)) + second := executeOrchestrationTurn(t, registry, "instance", history, []*protos.HistoryEvent{ + helpers.NewOrchestratorStartedEvent(), + helpers.NewTimerFiredEvent(0, first.Actions[0].GetCreateTimer().FireAt, nil), + }) + require.Equal(t, "3", completionResult(t, second)) +} + +func TestChannelBufferedBlockedSendersKeepQueueOrder(t *testing.T) { + registry := channelRegistry(t, func(ctx *OrchestrationContext) (any, error) { + channel := NewChannel[int](ctx, 1) + gate := NewChannel[struct{}](ctx, 0) + drained := NewChannel[struct{}](ctx, 1) + channel.Send(ctx, 0) + wg := ctx.NewWaitGroup() + wg.Add(3) + received := []int{} + ctx.Go(func(ctx *OrchestrationContext) { + defer wg.Done() + gate.Receive(ctx) + value := channel.Receive(ctx) + if value != 0 { + panic("unexpected initial buffer value") + } + drained.Send(ctx, struct{}{}) + channel.Send(ctx, 2) + }) + ctx.Go(func(ctx *OrchestrationContext) { + defer wg.Done() + channel.Send(ctx, 1) + }) + ctx.Go(func(ctx *OrchestrationContext) { + defer wg.Done() + gate.Send(ctx, struct{}{}) + drained.Receive(ctx) + received = append(received, channel.Receive(ctx), channel.Receive(ctx)) + }) + wg.Wait(ctx) + return received, nil + }) + response := executeOrchestrationTurn(t, registry, "instance", nil, channelStart()) + require.Equal(t, "[1,2]", completionResult(t, response)) +} + +func TestChannelSelectLosingBufferedCasesHaveNoSideEffects(t *testing.T) { + registry := channelRegistry(t, func(ctx *OrchestrationContext) (any, error) { + ready := newTaskInScope(ctx, ctx.scope) + ready.complete(nil) + channel := NewChannel[int](ctx, 1) + channel.Send(ctx, 7) + ctx.Select(OnReceive(channel, func(int) { panic("losing receive ran") }), OnTask(ready, nil)) + value := channel.Receive(ctx) + ctx.Select(OnSend(channel, 99, func() { panic("losing send ran") }), OnTask(ready, nil)) + assert.Empty(t, channel.buffer) + return value, nil + }) + response := executeOrchestrationTurn(t, registry, "instance", nil, channelStart()) + require.Equal(t, "7", completionResult(t, response)) +} + +func TestChannelSelectCannotRendezvousWithItself(t *testing.T) { + registry := channelRegistry(t, func(ctx *OrchestrationContext) (any, error) { + channel := NewChannel[int](ctx, 0) + ctx.Select(OnSend(channel, 1, nil), OnReceive(channel, nil)) + return nil, nil + }) + response := executeOrchestrationTurn(t, registry, "instance", nil, channelStart()) + require.Equal(t, protos.OrchestrationStatus_ORCHESTRATION_STATUS_FAILED, + completionAction(t, response).OrchestrationStatus) + require.Contains(t, completionAction(t, response).FailureDetails.ErrorMessage, ErrOrchestrationDeadlock.Error()) +} + +func TestChannelWaitsYieldDurableActionsAndReplay(t *testing.T) { + registry := channelRegistry(t, func(ctx *OrchestrationContext) (any, error) { + channel := NewChannel[int](ctx, 0) + wg := ctx.NewWaitGroup() + wg.Add(2) + for _, name := range []string{"first", "second"} { + ctx.Go(func(ctx *OrchestrationContext) { + defer wg.Done() + var result int + if err := ctx.CallActivity(name).Await(&result); err != nil { + panic(err) + } + channel.Send(ctx, result) + }) + } + result := []int{channel.Receive(ctx), channel.Receive(ctx)} + wg.Wait(ctx) + return result, nil + }) + start := channelStart() + first := executeOrchestrationTurn(t, registry, "instance", nil, start) + require.Len(t, first.Actions, 2) + require.Equal(t, "first", first.Actions[0].GetScheduleTask().Name) + require.Equal(t, "second", first.Actions[1].GetScheduleTask().Name) + + history := append(slices.Clone(start), + helpers.NewTaskScheduledEvent(0, "first", nil, nil, nil), + helpers.NewTaskScheduledEvent(1, "second", nil, nil, nil), + ) + secondEvents := []*protos.HistoryEvent{ + helpers.NewOrchestratorStartedEvent(), + helpers.NewTaskCompletedEvent(1, wrapperspb.String("20")), + } + second := executeOrchestrationTurn(t, registry, "instance", history, secondEvents) + require.Empty(t, second.Actions) + history = append(history, secondEvents...) + lastEvents := []*protos.HistoryEvent{ + helpers.NewOrchestratorStartedEvent(), + helpers.NewTaskCompletedEvent(0, wrapperspb.String("10")), + } + last := executeOrchestrationTurn(t, registry, "instance", history, lastEvents) + require.Equal(t, "[20,10]", completionResult(t, last)) + for range 20 { + replay := executeOrchestrationTurn(t, registry, "instance", append(slices.Clone(history), lastEvents...), nil) + require.True(t, proto.Equal(last, replay)) + } +} + +func TestChannelWaitCancellationAndReuse(t *testing.T) { + for _, capacity := range []int{0, 1} { + for _, sending := range []bool{false, true} { + t.Run(fmt.Sprintf("capacity=%d/send=%t", capacity, sending), func(t *testing.T) { + registry := channelRegistry(t, func(ctx *OrchestrationContext) (any, error) { + child, cancel := ctx.WithCancel() + channel := NewChannel[int](ctx, capacity) + if sending && capacity > 0 { + channel.Send(ctx, 1) + } + canceled := false + wg := ctx.NewWaitGroup() + wg.Add(1) + ctx.Go(func(*OrchestrationContext) { + defer wg.Done() + var err error + if sending { + err = channel.SendErr(child, 2) + } else { + _, err = channel.ReceiveErr(child) + } + canceled = errors.Is(err, ErrTaskCanceled) + }) + // Yield until the wrapper has registered its channel wait. + ctx.Go(func(*OrchestrationContext) { cancel() }) + wg.Wait(ctx) + assert.Empty(t, channel.senders) + assert.Empty(t, channel.receivers) + assert.True(t, child.IsCanceled()) + assert.False(t, ctx.IsCanceled()) + if sending && capacity > 0 { + assert.Equal(t, 1, channel.Receive(ctx)) + } + ctx.Go(func(ctx *OrchestrationContext) { channel.Send(ctx, 3) }) + return []any{canceled, channel.Receive(ctx)}, nil + }) + response := executeOrchestrationTurn(t, registry, "instance", nil, channelStart()) + require.Equal(t, "[true,3]", completionResult(t, response)) + }) + } + } +} + +func TestChannelCommittedRendezvousSurvivesCancellation(t *testing.T) { + registry := channelRegistry(t, func(ctx *OrchestrationContext) (any, error) { + child, cancel := ctx.WithCancel() + channel := NewChannel[int](ctx, 0) + var received int + var receiveErr error + wg := ctx.NewWaitGroup() + wg.Add(1) + ctx.Go(func(*OrchestrationContext) { + defer wg.Done() + received, receiveErr = channel.ReceiveErr(child) + }) + ctx.Go(func(ctx *OrchestrationContext) { + channel.Send(ctx, 42) + cancel() + }) + wg.Wait(ctx) + return received, receiveErr + }) + response := executeOrchestrationTurn(t, registry, "instance", nil, channelStart()) + require.Equal(t, "42", completionResult(t, response)) +} + +func TestChannelCycleFailsWithoutBlockingWorker(t *testing.T) { + registry := channelRegistry(t, func(ctx *OrchestrationContext) (any, error) { + a, b := NewChannel[int](ctx, 0), NewChannel[int](ctx, 0) + wg := ctx.NewWaitGroup() + wg.Add(2) + ctx.Go(func(ctx *OrchestrationContext) { + defer wg.Done() + a.Send(ctx, b.Receive(ctx)) + }) + ctx.Go(func(ctx *OrchestrationContext) { + defer wg.Done() + b.Send(ctx, a.Receive(ctx)) + }) + wg.Wait(ctx) + return nil, nil + }) + response := executeOrchestrationTurn(t, registry, "instance", nil, channelStart()) + completed := completionAction(t, response) + require.Equal(t, protos.OrchestrationStatus_ORCHESTRATION_STATUS_FAILED, completed.OrchestrationStatus) + require.Contains(t, completed.FailureDetails.ErrorMessage, ErrOrchestrationDeadlock.Error()) +} + +func TestChannelWaitWithExternalEventUnloadsAndResumes(t *testing.T) { + var channel *Channel[int] + registry := channelRegistry(t, func(ctx *OrchestrationContext) (any, error) { + channel = NewChannel[int](ctx, 0) + ctx.Go(func(ctx *OrchestrationContext) { + var value int + if err := ctx.WaitForSingleEvent("value", -1).Await(&value); err != nil { + panic(err) + } + channel.Send(ctx, value) + }) + return channel.Receive(ctx), nil + }) + first := executeOrchestrationTurn(t, registry, "instance", nil, channelStart()) + require.Empty(t, first.Actions) + require.Empty(t, channel.senders) + require.Empty(t, channel.receivers) + second := executeOrchestrationTurn(t, registry, "instance", channelStart(), []*protos.HistoryEvent{ + helpers.NewOrchestratorStartedEvent(), + helpers.NewEventRaisedEvent("value", wrapperspb.String("9")), + }) + require.Equal(t, "9", completionResult(t, second)) +} + +func TestChannelSelectWithStopEventAndTimer(t *testing.T) { + registry := channelRegistry(t, func(ctx *OrchestrationContext) (any, error) { + channel := NewChannel[int](ctx, 0) + stop := NewEventChannel[string](ctx, "stop") + timer := ctx.CreateTimer(time.Hour) + selected := "" + ctx.Select( + OnReceive(channel, func(int) { selected = "channel" }), + OnEvent(stop, func(string) { selected = "stop" }), + OnTask(timer, func(Task) { selected = "timer" }), + ) + return selected, nil + }) + first := executeOrchestrationTurn(t, registry, "instance", nil, channelStart()) + require.Len(t, first.Actions, 1) + require.NotNil(t, first.Actions[0].GetCreateTimer()) + second := executeOrchestrationTurn(t, registry, "instance", channelStart(), []*protos.HistoryEvent{ + helpers.NewOrchestratorStartedEvent(), + helpers.NewEventRaisedEvent("stop", wrapperspb.String(`"requested"`)), + }) + require.Equal(t, `"stop"`, completionResult(t, second)) +} + +func TestIsCanceledObservesAppliedNotRequestedCancellation(t *testing.T) { + registry := channelRegistry(t, func(ctx *OrchestrationContext) (any, error) { + child, cancel := ctx.WithCancel() + cancel() + assert.False(t, child.IsCanceled()) + assert.ErrorIs(t, child.WaitForSingleEvent("never", -1).Await(nil), ErrTaskCanceled) + return child.IsCanceled(), nil + }) + response := executeOrchestrationTurn(t, registry, "instance", nil, channelStart()) + require.Equal(t, "true", completionResult(t, response)) +} + +func TestChannelCancellationConvenienceFormsUnwindChildBranches(t *testing.T) { + registry := channelRegistry(t, func(ctx *OrchestrationContext) (any, error) { + child, cancel := ctx.WithCancel() + channel := NewChannel[int](ctx, 0) + other := NewChannel[int](ctx, 0) + finished := 0 + wg := ctx.NewWaitGroup() + wg.Add(2) + child.Go(func(ctx *OrchestrationContext) { + defer wg.Done() + defer func() { finished++ }() + channel.Send(ctx, 1) + }) + child.Go(func(ctx *OrchestrationContext) { + defer wg.Done() + defer func() { finished++ }() + other.Receive(ctx) + }) + ctx.Go(func(*OrchestrationContext) { cancel() }) + wg.Wait(ctx) + return finished, nil + }) + response := executeOrchestrationTurn(t, registry, "instance", nil, channelStart()) + require.Equal(t, "2", completionResult(t, response)) +} + +func TestChannelRejectsForeignOwnersBeforeRegistering(t *testing.T) { + registry := channelRegistry(t, func(ctx *OrchestrationContext) (any, error) { + foreign := newTestOrchestrationContext(NewTaskRegistry(), "instance", nil, nil) + channel := &Channel[int]{ctx: foreign, capacity: 1} + var recovered any + func() { + defer func() { recovered = recover() }() + ctx.Select(OnSend(channel, 1, nil), OnReceive(channel, nil)) + }() + assert.Empty(t, channel.senders) + assert.Empty(t, channel.receivers) + assert.Empty(t, channel.buffer) + return recovered, nil + }) + response := executeOrchestrationTurn(t, registry, "instance", nil, channelStart()) + require.Equal(t, `"Select case belongs to a different orchestration"`, completionResult(t, response)) +} + +func TestChannelSelectCasesCanBeReusedAcrossBranches(t *testing.T) { + registry := channelRegistry(t, func(ctx *OrchestrationContext) (any, error) { + channel := NewChannel[int](ctx, 0) + sum := 0 + receive := OnReceive(channel, func(value int) { sum += value }) + wg := ctx.NewWaitGroup() + wg.Add(2) + for range 2 { + ctx.Go(func(ctx *OrchestrationContext) { + defer wg.Done() + ctx.Select(receive) + }) + } + channel.Send(ctx, 1) + channel.Send(ctx, 2) + wg.Wait(ctx) + assert.Empty(t, receive.(*channelSelectCase[int]).operations) + return sum, nil + }) + response := executeOrchestrationTurn(t, registry, "instance", nil, channelStart()) + require.Equal(t, "3", completionResult(t, response)) +} + +func TestChannelCancellationDoesNotModifyBuffer(t *testing.T) { + registry := channelRegistry(t, func(ctx *OrchestrationContext) (any, error) { + child, cancel := ctx.WithCancel() + channel := NewChannel[int](ctx, 1) + channel.Send(ctx, 1) + cancel() + _ = child.WaitForSingleEvent("never", -1).Await(nil) + assert.ErrorIs(t, channel.SendErr(child, 2), ErrTaskCanceled) + _, err := channel.ReceiveErr(child) + assert.ErrorIs(t, err, ErrTaskCanceled) + return channel.Receive(ctx), nil + }) + response := executeOrchestrationTurn(t, registry, "instance", nil, channelStart()) + require.Equal(t, "1", completionResult(t, response)) +} + +func TestChannelSelectSnapshotsCasesBeforeYielding(t *testing.T) { + registry := channelRegistry(t, func(ctx *OrchestrationContext) (any, error) { + channel := NewChannel[int](ctx, 0) + cases := []SelectCase{OnReceive(channel, nil)} + wg := ctx.NewWaitGroup() + wg.Add(1) + ctx.Go(func(ctx *OrchestrationContext) { + defer wg.Done() + ctx.Select(cases...) + }) + ctx.Go(func(ctx *OrchestrationContext) { + cases[0] = OnTask(newTaskInScope(ctx, ctx.scope), nil) + channel.Send(ctx, 1) + }) + wg.Wait(ctx) + assert.Empty(t, channel.senders) + assert.Empty(t, channel.receivers) + return "done", nil + }) + response := executeOrchestrationTurn(t, registry, "instance", nil, channelStart()) + require.Equal(t, `"done"`, completionResult(t, response)) +} diff --git a/task/coroutine.go b/task/coroutine.go index 1f04b309..f38a4a78 100644 --- a/task/coroutine.go +++ b/task/coroutine.go @@ -45,6 +45,7 @@ type coroutine struct { stopOnce sync.Once state coroutineState scope *cancellationScope + selection *selection } func (c *coroutine) run() { diff --git a/task/eventchannel.go b/task/eventchannel.go index 93e599fe..e357e4d6 100644 --- a/task/eventchannel.go +++ b/task/eventchannel.go @@ -118,7 +118,7 @@ func (c *eventSelectCase[T]) owner() *OrchestrationContext { return c.channel.ctx } -func (c *eventSelectCase[T]) ready() (bool, uint64) { +func (c *eventSelectCase[T]) ready(*selection) (bool, uint64) { event, ok := c.channel.peek() if !ok { return false, 0 @@ -126,20 +126,23 @@ func (c *eventSelectCase[T]) ready() (bool, uint64) { return true, event.order } -func (c *eventSelectCase[T]) subscribe(coroutine *coroutine) { - c.channel.ctx.addEventWaiter(c.channel.key, coroutine) +func (c *eventSelectCase[T]) subscribe(s *selection) { + c.channel.ctx.addEventWaiter(c.channel.key, s.coroutine) } -func (c *eventSelectCase[T]) unsubscribe(coroutine *coroutine) { - c.channel.ctx.removeEventWaiter(c.channel.key, coroutine) +func (c *eventSelectCase[T]) unsubscribe(s *selection) { + c.channel.ctx.removeEventWaiter(c.channel.key, s.coroutine) } -func (c *eventSelectCase[T]) invoke() { +func (c *eventSelectCase[T]) commit(s *selection) bool { value, ok := c.channel.TryReceive() if !ok { panic("selected event channel no longer has a buffered value") } - if c.handler != nil { - c.handler(value) - } + s.finish(c, func() { + if c.handler != nil { + c.handler(value) + } + }) + return true } diff --git a/task/orchestrator.go b/task/orchestrator.go index 63f7b9fe..9c2f799c 100644 --- a/task/orchestrator.go +++ b/task/orchestrator.go @@ -436,6 +436,11 @@ func (ctx *OrchestrationContext) start() (actions []*protos.OrchestratorAction) break } if !ok { + if !terminal && !ctx.isSuspended && !ctx.maxEventsPerTurnExceeded && + ctx.scheduler.hasChannelDeadlock() { + _ = ctx.setFailed(ErrOrchestrationDeadlock) + markTerminal() + } break } if ctx.isTerminated && !terminal { diff --git a/task/select.go b/task/select.go index 118d7e9e..88be2bd0 100644 --- a/task/select.go +++ b/task/select.go @@ -1,14 +1,64 @@ package task -import "fmt" +import ( + "fmt" + "slices" +) -// SelectCase is a durable selection case created by OnTask or OnEvent. +// SelectCase is a durable selection case created by OnTask, OnEvent, +// OnReceive, or OnSend. type SelectCase interface { owner() *OrchestrationContext - ready() (bool, uint64) - subscribe(*coroutine) - unsubscribe(*coroutine) - invoke() + ready(*selection) (bool, uint64) + subscribe(*selection) + unsubscribe(*selection) + commit(*selection) bool +} + +// A selection owns all its registrations. A rendezvous commits both selections +// before either handler runs, withdrawing their losing cases atomically. +type selection struct { + ctx *OrchestrationContext + coroutine *coroutine + cases []SelectCase + selected SelectCase + handler func() + cleaned bool +} + +func (s *selection) pending() bool { + return s.selected == nil && !s.ctx.scope.isCanceled() && !s.coroutine.scope.isCanceled() +} + +func (s *selection) preferred() SelectCase { + var selected SelectCase + var selectedOrder uint64 + for _, candidate := range s.cases { + ready, order := candidate.ready(s) + if ready && (selected == nil || order < selectedOrder) { + selected = candidate + selectedOrder = order + } + } + return selected +} + +func (s *selection) finish(candidate SelectCase, handler func()) { + s.selected = candidate + s.handler = handler + s.cleanup() + s.ctx.scheduler.makeRunnable(s.coroutine) +} + +func (s *selection) cleanup() { + if s.cleaned { + return + } + s.cleaned = true + for _, candidate := range s.cases { + candidate.unsubscribe(s) + } + s.ctx.scope.removeWaiter(s.coroutine) } type taskSelectCase struct { @@ -30,22 +80,25 @@ func (c *taskSelectCase) owner() *OrchestrationContext { return c.state.orchestrationCtx.engineContext() } -func (c *taskSelectCase) ready() (bool, uint64) { +func (c *taskSelectCase) ready(*selection) (bool, uint64) { return c.state.isCompleted, c.state.completionID } -func (c *taskSelectCase) subscribe(coroutine *coroutine) { - c.state.addWaiter(coroutine) +func (c *taskSelectCase) subscribe(s *selection) { + c.state.addWaiter(s.coroutine) } -func (c *taskSelectCase) unsubscribe(coroutine *coroutine) { - c.state.removeWaiter(coroutine) +func (c *taskSelectCase) unsubscribe(s *selection) { + c.state.removeWaiter(s.coroutine) } -func (c *taskSelectCase) invoke() { - if c.handler != nil { - c.handler(c.task) - } +func (c *taskSelectCase) commit(s *selection) bool { + s.finish(c, func() { + if c.handler != nil { + c.handler(c.task) + } + }) + return true } // WhenAny blocks until the first task completes and returns that task. If @@ -89,11 +142,22 @@ func (ctx *OrchestrationContext) WhenAll(tasks ...Task) error { // Select waits until one case is ready and invokes its handler. // All cases must belong to the same orchestration, including its child scopes. +// Task and event cases are ordered by history; channel cases are ordered by +// deterministic scheduler readiness. Argument order breaks ties, not priority. +// Losing cases do not receive values or send messages. func (ctx *OrchestrationContext) Select(cases ...SelectCase) { ctx.selectCase(cases) } func (ctx *OrchestrationContext) selectCase(cases []SelectCase) SelectCase { + selected, err := ctx.selectCaseErr(cases) + if err != nil { + panic(err) + } + return selected +} + +func (ctx *OrchestrationContext) selectCaseErr(cases []SelectCase) (SelectCase, error) { engine := ctx.effectContext() if len(cases) == 0 { panic("Select requires at least one case") @@ -103,40 +167,46 @@ func (ctx *OrchestrationContext) selectCase(cases []SelectCase) SelectCase { panic("Select called outside orchestrator execution") } current := scheduler.mustCurrent() - - for { - if current.scope.isCanceled() || ctx.scope.isCanceled() { - panic(ErrTaskCanceled) + if current.scope.isCanceled() || ctx.scope.isCanceled() { + return nil, ErrTaskCanceled + } + seen := make(map[SelectCase]struct{}, len(cases)) + for _, candidate := range cases { + if candidate.owner() != engine { + panic("Select case belongs to a different orchestration") } - for _, candidate := range cases { - if candidate.owner() != engine { - panic("Select case belongs to a different orchestration") - } + if _, exists := seen[candidate]; exists { + panic("Select case used more than once") } - var selected SelectCase - var selectedOrder uint64 - for _, candidate := range cases { - ready, order := candidate.ready() - if ready && (selected == nil || order < selectedOrder) { - selected = candidate - selectedOrder = order + seen[candidate] = struct{}{} + } + s := &selection{ctx: ctx, coroutine: current, cases: slices.Clone(cases)} + current.selection = s + defer func() { + s.cleanup() + current.selection = nil + }() + ctx.scope.addWaiter(current) + for _, candidate := range cases { + candidate.subscribe(s) + } + for { + // A committed rendezvous is not undone by cancellation applied before + // the other coroutine resumes. + if s.selected != nil { + if s.handler != nil { + s.handler() } + return s.selected, nil } - if selected != nil { - selected.invoke() - return selected + if !s.pending() { + return nil, ErrTaskCanceled } - - ctx.scope.addWaiter(current) - for _, candidate := range cases { - candidate.subscribe(current) + if candidate := s.preferred(); candidate != nil && candidate.commit(s) { + continue } current.state = coroutineWaiting current.yield() - for _, candidate := range cases { - candidate.unsubscribe(current) - } - ctx.scope.removeWaiter(current) } } diff --git a/tests/durabletaskscheduler/dts_coroutine_review_test.go b/tests/durabletaskscheduler/dts_coroutine_review_test.go index de133829..aaf211cb 100644 --- a/tests/durabletaskscheduler/dts_coroutine_review_test.go +++ b/tests/durabletaskscheduler/dts_coroutine_review_test.go @@ -2,6 +2,9 @@ package durabletaskscheduler_test import ( "context" + "errors" + "fmt" + "slices" "testing" "time" @@ -57,3 +60,90 @@ func TestDTSCanceledScopeSkipsUnstartedCoroutines(t *testing.T) { require.Empty(t, result.SerializedCustomStatus) } } + +func TestDTSChannelsYieldWorkAndFailLocalDeadlocks(t *testing.T) { + name := "DTSChannelCoordinator-" + uuid.NewString() + activityName := "DTSChannelDouble-" + uuid.NewString() + deadlockName := "DTSChannelDeadlock-" + uuid.NewString() + registry := task.NewTaskRegistry() + require.NoError(t, registry.AddActivityN(activityName, func(ctx task.ActivityContext) (any, error) { + var value int + if err := ctx.GetInput(&value); err != nil { + return nil, err + } + return value * 2, nil + })) + require.NoError(t, registry.AddOrchestratorN(name, func(ctx *task.OrchestrationContext) (any, error) { + var capacity int + if err := ctx.GetInput(&capacity); err != nil { + return nil, err + } + results := task.NewChannel[int](ctx, capacity) + group := ctx.NewWaitGroup() + group.Add(3) + for _, value := range []int{2, 4, 6} { + ctx.Go(func(branch *task.OrchestrationContext) { + defer group.Done() + var result int + if err := branch.CallActivity(activityName, task.WithActivityInput(value)).Await(&result); err != nil { + panic(err) + } + results.Send(branch, result) + }) + } + timer := ctx.CreateTimer(15 * time.Second) + var values []int + var failure error + for len(values) < 3 && failure == nil { + ctx.Select( + task.OnReceive(results, func(value int) { values = append(values, value) }), + task.OnTask(timer, func(task.Task) { failure = errors.New("channel coordinator timed out") }), + ) + } + if failure != nil { + return nil, failure + } + group.Wait(ctx) + slices.Sort(values) + return values, nil + })) + require.NoError(t, registry.AddOrchestratorN(deadlockName, func(ctx *task.OrchestrationContext) (any, error) { + return task.NewChannel[int](ctx, 0).Receive(ctx), nil + })) + client, _, _ := startEmulatorClientAndWorker(t, registry, + durabletaskclient.WithAutoWorkItemFilters(), + durabletaskclient.WithMaxConcurrentOrchestrationWorkItems(1), + ) + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + for _, test := range []struct { + name string + capacity int + deadlock bool + }{ + {name: "deadlock", deadlock: true}, + {name: "unbuffered"}, + {name: "buffered", capacity: 1}, + } { + t.Run(test.name, func(t *testing.T) { + id := uniqueInstanceID("go-channel") + t.Cleanup(func() { cleanupRewindInstances(t, client, []api.InstanceID{id}) }) + orchestrator := name + if test.deadlock { + orchestrator = deadlockName + } + _, err := client.ScheduleNewOrchestration(ctx, orchestrator, + api.WithInstanceID(id), api.WithInput(test.capacity)) + require.NoError(t, err) + result, err := client.WaitForOrchestrationCompletion(ctx, id, api.WithFetchPayloads(true)) + require.NoError(t, err) + if test.deadlock { + require.Equal(t, api.RUNTIME_STATUS_FAILED, result.RuntimeStatus) + require.Contains(t, fmt.Sprint(result.FailureDetails), task.ErrOrchestrationDeadlock.Error()) + return + } + require.Equal(t, api.RUNTIME_STATUS_COMPLETED, result.RuntimeStatus, "%+v", result.FailureDetails) + require.Equal(t, "[4,8,12]", result.SerializedOutput) + }) + } +} From 3691e1c423dc230adb6868e7aaa8d9444cd21bef Mon Sep 17 00:00:00 2001 From: Andy Staples Date: Mon, 23 Nov 2026 12:28:20 -0700 Subject: [PATCH 2/3] Address channel selection compatibility and scaling feedback Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- README.md | 4 +- task/channel.go | 136 +++++++++++++++------------------ task/channel_test.go | 177 +++++++++++++++++++++++++++++++++++++++---- task/eventchannel.go | 20 ++++- task/select.go | 68 ++++++++++++++--- task/select_test.go | 98 ++++++++++++++++++++++++ 6 files changed, 396 insertions(+), 107 deletions(-) diff --git a/README.md b/README.md index d8fb1c76..8695920a 100644 --- a/README.md +++ b/README.md @@ -358,8 +358,8 @@ commit their channel cases before either callback runs. Each callback executes in its own selecting coroutine. Task and external event readiness is ordered by history; channel readiness is ordered deterministically by the SDK scheduler. Argument order breaks ties, but does not give a stop event priority over an -earlier ready result. Create distinct cases for each alternative within a -single `Select`; a case can be reused by later calls. +earlier ready result. A repeated case within one `Select` is treated as its +first occurrence and registered only once; cases can also be reused by later calls. Channel waits yield to the SDK, allowing other branches to schedule activities. When all branches are waiting and available history is exhausted, the execution diff --git a/task/channel.go b/task/channel.go index 77cd8fb8..61af6c6c 100644 --- a/task/channel.go +++ b/task/channel.go @@ -1,8 +1,8 @@ package task import ( + "container/list" "errors" - "slices" ) // ErrOrchestrationDeadlock identifies channel waits that cannot make progress: @@ -19,8 +19,8 @@ type Channel[T any] struct { ctx *OrchestrationContext capacity int buffer []channelValue[T] - senders []*channelOperation[T] - receivers []*channelOperation[T] + senders list.List + receivers list.List } type channelValue[T any] struct { @@ -29,19 +29,12 @@ type channelValue[T any] struct { } type channelOperation[T any] struct { - selection *selection - candidate *channelSelectCase[T] - matches []*channelMatch[T] - order uint64 - ready bool -} - -// Each potential rendezvous has one globally unique readiness order shared by -// both endpoints. This prevents cyclic preferences between competing selects. -type channelMatch[T any] struct { - sender *channelOperation[T] - receiver *channelOperation[T] - order uint64 + selection *selection + candidate *channelSelectCase[T] + element *list.Element + registered uint64 + order uint64 + ready bool } // NewChannel creates a fresh orchestration-local channel. Zero capacity @@ -130,32 +123,17 @@ func (c *channelSelectCase[T]) subscribe(s *selection) { if c.operations == nil { c.operations = make(map[*selection]*channelOperation[T]) } - op := &channelOperation[T]{selection: s, candidate: c} + op := &channelOperation[T]{ + selection: s, candidate: c, + registered: c.channel.ctx.scheduler.nextCompletionID(), + } c.operations[s] = op channel := c.channel - peers := channel.senders if c.send { - peers = channel.receivers - channel.senders = append(channel.senders, op) + op.element = channel.senders.PushBack(op) } else { - channel.receivers = append(channel.receivers, op) + op.element = channel.receivers.PushBack(op) } - if channel.capacity == 0 { - for _, peer := range peers { - if peer.selection == s || !peer.selection.pending() { - continue - } - match := &channelMatch[T]{order: channel.ctx.scheduler.nextCompletionID()} - if c.send { - match.sender, match.receiver = op, peer - } else { - match.sender, match.receiver = peer, op - } - op.matches = append(op.matches, match) - peer.matches = append(peer.matches, match) - } - } - channel.notify() } func (c *channelSelectCase[T]) unsubscribe(s *selection) { @@ -166,31 +144,25 @@ func (c *channelSelectCase[T]) unsubscribe(s *selection) { delete(c.operations, s) channel := c.channel if c.send { - channel.senders = slices.DeleteFunc(channel.senders, func(other *channelOperation[T]) bool { - return other == op - }) + channel.senders.Remove(op.element) } else { - channel.receivers = slices.DeleteFunc(channel.receivers, func(other *channelOperation[T]) bool { - return other == op - }) + channel.receivers.Remove(op.element) } - for _, match := range op.matches { - peer := match.sender - if c.send { - peer = match.receiver - } - peer.matches = slices.DeleteFunc(peer.matches, func(other *channelMatch[T]) bool { - return other == match - }) - } - op.matches = nil - channel.notify() } -func (op *channelOperation[T]) firstMatch() *channelMatch[T] { - for _, match := range op.matches { - if match.sender.selection.pending() && match.receiver.selection.pending() { - return match +// Derive the oldest compatible peer on demand instead of retaining every +// possible edge. Pairs are ordered by (later registration, earlier registration). +// Both endpoints see the same order; argument order breaks ties between the +// consecutively registered alternatives of one selection. +func (op *channelOperation[T]) firstPeer() *channelOperation[T] { + peers := &op.candidate.channel.senders + if op.candidate.send { + peers = &op.candidate.channel.receivers + } + for element := peers.Front(); element != nil; element = element.Next() { + peer := element.Value.(*channelOperation[T]) + if peer.selection != op.selection && peer.selection.pending() { + return peer } } return nil @@ -202,8 +174,8 @@ func (c *channelSelectCase[T]) ready(s *selection) (bool, uint64) { return false, 0 } if c.channel.capacity == 0 { - if match := op.firstMatch(); match != nil { - return true, match.order + if peer := op.firstPeer(); peer != nil { + return true, max(op.registered, peer.registered) } return false, 0 } @@ -219,14 +191,11 @@ func (c *channelSelectCase[T]) ready(s *selection) (bool, uint64) { func (c *channelSelectCase[T]) commit(s *selection) bool { channel := c.channel if channel.capacity == 0 { - match := c.operations[s].firstMatch() - if match == nil { + op := c.operations[s] + peer := op.firstPeer() + if peer == nil { return false } - peer := match.sender - if c.send { - peer = match.receiver - } // Do not steal a waiting peer from an earlier ready task, event, or // rendezvous. Let that coroutine resolve its preferred case first. if peer.selection.preferred() != peer.candidate { @@ -234,15 +203,19 @@ func (c *channelSelectCase[T]) commit(s *selection) bool { return false } // A case can have multiple peers; both must prefer this exact match. - if peer.firstMatch() != match { + if peer.firstPeer() != op { channel.ctx.scheduler.makeRunnable(peer.selection.coroutine) return false } - value := match.sender.candidate.value - sendHandler := match.sender.candidate.onSend - receiveHandler := match.receiver.candidate.onReceive - match.sender.selection.finish(match.sender.candidate, sendHandler) - match.receiver.selection.finish(match.receiver.candidate, func() { + sender, receiver := peer, op + if c.send { + sender, receiver = op, peer + } + value := sender.candidate.value + sendHandler := sender.candidate.onSend + receiveHandler := receiver.candidate.onReceive + sender.selection.finish(sender.candidate, sendHandler) + receiver.selection.finish(receiver.candidate, func() { if receiveHandler != nil { receiveHandler(value) } @@ -257,20 +230,21 @@ func (c *channelSelectCase[T]) commit(s *selection) bool { s.finish(c, c.onSend) } else { value := channel.buffer[0].value - channel.buffer = slices.Delete(channel.buffer, 0, 1) + channel.buffer[0] = channelValue[T]{} + channel.buffer = channel.buffer[1:] s.finish(c, func() { if c.onReceive != nil { c.onReceive(value) } }) } - channel.notify() return true } func (c *Channel[T]) notify() { slots := c.capacity - len(c.buffer) - for _, op := range c.senders { + for element := c.senders.Front(); element != nil; element = element.Next() { + op := element.Value.(*channelOperation[T]) if !op.selection.pending() { continue } @@ -284,10 +258,16 @@ func (c *Channel[T]) notify() { } op.ready = ready } - c.ctx.scheduler.makeRunnable(op.selection.coroutine) + if ready, _ := op.candidate.ready(op.selection); ready { + c.ctx.scheduler.makeRunnable(op.selection.coroutine) + } } - for _, op := range c.receivers { + for element := c.receivers.Front(); element != nil; element = element.Next() { + op := element.Value.(*channelOperation[T]) if op.selection.pending() { + if ready, _ := op.candidate.ready(op.selection); !ready { + continue + } c.ctx.scheduler.makeRunnable(op.selection.coroutine) } } @@ -331,3 +311,5 @@ func (s *coroutineScheduler) hasChannelDeadlock() bool { } func (*channelSelectCase[T]) channelCase() {} + +func (c *channelSelectCase[T]) channelNotifier() channelNotifier { return c.channel } diff --git a/task/channel_test.go b/task/channel_test.go index 9a7242d4..7fc681dc 100644 --- a/task/channel_test.go +++ b/task/channel_test.go @@ -1,6 +1,7 @@ package task import ( + "context" "errors" "fmt" "slices" @@ -44,8 +45,8 @@ func TestChannelRendezvousAndBufferedFIFO(t *testing.T) { }) results := []int{channel.Receive(ctx), channel.Receive(ctx), channel.Receive(ctx)} wg.Wait(ctx) - assert.Empty(t, channel.senders) - assert.Empty(t, channel.receivers) + assert.Zero(t, channel.senders.Len()) + assert.Zero(t, channel.receivers.Len()) assert.Empty(t, channel.buffer) return results, nil }) @@ -78,10 +79,10 @@ func TestChannelSelectRendezvousCommitsOnlyWinningCases(t *testing.T) { OnReceive(first, func(value int) { received = value }), ) wg.Wait(ctx) - assert.Empty(t, first.senders) - assert.Empty(t, first.receivers) - assert.Empty(t, second.senders) - assert.Empty(t, second.receivers) + assert.Zero(t, first.senders.Len()) + assert.Zero(t, first.receivers.Len()) + assert.Zero(t, second.senders.Len()) + assert.Zero(t, second.receivers.Len()) return []any{sent, received}, nil }) response := executeOrchestrationTurn(t, registry, "instance", nil, channelStart()) @@ -311,8 +312,8 @@ func TestChannelWaitCancellationAndReuse(t *testing.T) { // Yield until the wrapper has registered its channel wait. ctx.Go(func(*OrchestrationContext) { cancel() }) wg.Wait(ctx) - assert.Empty(t, channel.senders) - assert.Empty(t, channel.receivers) + assert.Zero(t, channel.senders.Len()) + assert.Zero(t, channel.receivers.Len()) assert.True(t, child.IsCanceled()) assert.False(t, ctx.IsCanceled()) if sending && capacity > 0 { @@ -388,8 +389,8 @@ func TestChannelWaitWithExternalEventUnloadsAndResumes(t *testing.T) { }) first := executeOrchestrationTurn(t, registry, "instance", nil, channelStart()) require.Empty(t, first.Actions) - require.Empty(t, channel.senders) - require.Empty(t, channel.receivers) + require.Zero(t, channel.senders.Len()) + require.Zero(t, channel.receivers.Len()) second := executeOrchestrationTurn(t, registry, "instance", channelStart(), []*protos.HistoryEvent{ helpers.NewOrchestratorStartedEvent(), helpers.NewEventRaisedEvent("value", wrapperspb.String("9")), @@ -467,8 +468,8 @@ func TestChannelRejectsForeignOwnersBeforeRegistering(t *testing.T) { defer func() { recovered = recover() }() ctx.Select(OnSend(channel, 1, nil), OnReceive(channel, nil)) }() - assert.Empty(t, channel.senders) - assert.Empty(t, channel.receivers) + assert.Zero(t, channel.senders.Len()) + assert.Zero(t, channel.receivers.Len()) assert.Empty(t, channel.buffer) return recovered, nil }) @@ -530,10 +531,158 @@ func TestChannelSelectSnapshotsCasesBeforeYielding(t *testing.T) { channel.Send(ctx, 1) }) wg.Wait(ctx) - assert.Empty(t, channel.senders) - assert.Empty(t, channel.receivers) + assert.Zero(t, channel.senders.Len()) + assert.Zero(t, channel.receivers.Len()) return "done", nil }) response := executeOrchestrationTurn(t, registry, "instance", nil, channelStart()) require.Equal(t, `"done"`, completionResult(t, response)) } + +type countedChannelCase struct { + SelectCase + polls *int +} + +func (c *countedChannelCase) ready(s *selection) (bool, uint64) { + (*c.polls)++ + return c.SelectCase.ready(s) +} + +func (*countedChannelCase) channelCase() {} + +func (c *countedChannelCase) channelNotifier() channelNotifier { + return c.SelectCase.(interface{ channelNotifier() channelNotifier }).channelNotifier() +} + +func TestChannelSameSideWaitersDoNotResumeBeforeDurableDispatch(t *testing.T) { + const count = 128 + for _, capacity := range []int{0, 1} { + for _, send := range []bool{false, true} { + t.Run(fmt.Sprintf("capacity=%d/send=%t", capacity, send), func(t *testing.T) { + polls := 0 + registry := channelRegistry(t, func(ctx *OrchestrationContext) (any, error) { + channel := NewChannel[int](ctx, capacity) + if send && capacity > 0 { + channel.Send(ctx, 0) + } + for range count { + ctx.Go(func(branch *OrchestrationContext) { + candidate := OnReceive(channel, nil) + if send { + candidate = OnSend(channel, 1, nil) + } + branch.Select(&countedChannelCase{SelectCase: candidate, polls: &polls}) + }) + } + return nil, ctx.CallActivity("pending").Await(nil) + }) + response := executeOrchestrationTurn(t, registry, "instance", nil, channelStart()) + require.Len(t, response.Actions, 1) + require.Equal(t, "pending", response.Actions[0].GetScheduleTask().Name) + require.Equal(t, count, polls, "each blocked branch should run once, not resume for other blocked waiters") + }) + } + } +} + +func TestChannelBufferedDrainClearsValuesWithoutMovingTail(t *testing.T) { + registry := channelRegistry(t, func(ctx *OrchestrationContext) (any, error) { + channel := NewChannel[*int](ctx, 256) + for i := range 256 { + channel.Send(ctx, &i) + } + backing := channel.buffer + for i := range 256 { + value := channel.Receive(ctx) + assert.Equal(t, i, *value) + assert.Nil(t, backing[i].value) + if i < 255 { + assert.Equal(t, i+1, *backing[i+1].value, "unconsumed values must not move") + } + } + return len(channel.buffer), nil + }) + response := executeOrchestrationTurn(t, registry, "instance", nil, channelStart()) + require.Equal(t, "0", completionResult(t, response)) +} + +func BenchmarkChannelCompetingSelects(b *testing.B) { + for _, count := range []int{16, 128, 1024} { + b.Run(fmt.Sprint(count), func(b *testing.B) { + registry := NewTaskRegistry() + if err := registry.AddOrchestratorN("channels", func(ctx *OrchestrationContext) (any, error) { + channel := NewChannel[int](ctx, 0) + sends := make([]SelectCase, count) + receives := make([]SelectCase, count) + for i := range count { + sends[i] = OnSend(channel, i, nil) + receives[i] = OnReceive(channel, nil) + } + group := ctx.NewWaitGroup() + group.Add(1) + ctx.Go(func(branch *OrchestrationContext) { + defer group.Done() + branch.Select(sends...) + }) + ctx.Select(receives...) + group.Wait(ctx) + return nil, nil + }); err != nil { + b.Fatal(err) + } + executor := NewTaskExecutor(registry) + b.ReportAllocs() + b.ResetTimer() + for range b.N { + result, err := executor.ExecuteOrchestrator( + context.Background(), "instance", nil, channelStart(), nil) + if err != nil { + b.Fatal(err) + } + if len(result.Response.Actions) != 1 || + result.Response.Actions[0].GetCompleteOrchestration().GetOrchestrationStatus() != + protos.OrchestrationStatus_ORCHESTRATION_STATUS_COMPLETED { + b.Fatal("competing selects did not complete") + } + } + + }) + } +} + +func TestChannelManyAlternativesCommitOnePairInRegistrationOrder(t *testing.T) { + registry := channelRegistry(t, func(ctx *OrchestrationContext) (any, error) { + channel := NewChannel[int](ctx, 0) + received, sends, receives := -1, 0, 0 + sendCases, receiveCases := make([]SelectCase, 128), make([]SelectCase, 128) + for i := range sendCases { + sendCases[i] = OnSend(channel, i, func() { sends++ }) + receiveCases[i] = OnReceive(channel, func(value int) { + received = value + receives++ + }) + } + group := ctx.NewWaitGroup() + group.Add(1) + ctx.Go(func(branch *OrchestrationContext) { + defer group.Done() + branch.Select(sendCases...) + }) + ctx.Select(receiveCases...) + group.Wait(ctx) + return []int{received, sends, receives, channel.senders.Len(), channel.receivers.Len()}, nil + }) + for range 10 { + for _, replay := range []bool{false, true} { + var oldEvents, newEvents []*protos.HistoryEvent + if replay { + oldEvents = channelStart() + } else { + newEvents = channelStart() + } + response := executeOrchestrationTurn(t, registry, "instance", oldEvents, newEvents) + require.Equal(t, "[0,1,1,0,0]", completionResult(t, response)) + } + } +} diff --git a/task/eventchannel.go b/task/eventchannel.go index e357e4d6..e6ab66bb 100644 --- a/task/eventchannel.go +++ b/task/eventchannel.go @@ -135,10 +135,7 @@ func (c *eventSelectCase[T]) unsubscribe(s *selection) { } func (c *eventSelectCase[T]) commit(s *selection) bool { - value, ok := c.channel.TryReceive() - if !ok { - panic("selected event channel no longer has a buffered value") - } + value := c.takeValue() s.finish(c, func() { if c.handler != nil { c.handler(value) @@ -146,3 +143,18 @@ func (c *eventSelectCase[T]) commit(s *selection) bool { }) return true } + +func (c *eventSelectCase[T]) invoke() { + value := c.takeValue() + if c.handler != nil { + c.handler(value) + } +} + +func (c *eventSelectCase[T]) takeValue() T { + value, ok := c.channel.TryReceive() + if !ok { + panic("selected event channel no longer has a buffered value") + } + return value +} diff --git a/task/select.go b/task/select.go index 88be2bd0..686e6720 100644 --- a/task/select.go +++ b/task/select.go @@ -59,6 +59,28 @@ func (s *selection) cleanup() { candidate.unsubscribe(s) } s.ctx.scope.removeWaiter(s.coroutine) + s.notifyChannels() +} + +type channelNotifier interface { + notify() +} + +func (s *selection) notifyChannels() { + var notified map[channelNotifier]struct{} + for _, candidate := range s.cases { + if c, ok := candidate.(interface{ channelNotifier() channelNotifier }); ok { + channel := c.channelNotifier() + if _, exists := notified[channel]; exists { + continue + } + if notified == nil { + notified = make(map[channelNotifier]struct{}) + } + notified[channel] = struct{}{} + channel.notify() + } + } } type taskSelectCase struct { @@ -93,14 +115,16 @@ func (c *taskSelectCase) unsubscribe(s *selection) { } func (c *taskSelectCase) commit(s *selection) bool { - s.finish(c, func() { - if c.handler != nil { - c.handler(c.task) - } - }) + s.finish(c, c.invoke) return true } +func (c *taskSelectCase) invoke() { + if c.handler != nil { + c.handler(c.task) + } +} + // WhenAny blocks until the first task completes and returns that task. If // multiple tasks are ready, the task completed first in orchestration history wins. func (ctx *OrchestrationContext) WhenAny(tasks ...Task) Task { @@ -145,6 +169,7 @@ func (ctx *OrchestrationContext) WhenAll(tasks ...Task) error { // Task and event cases are ordered by history; channel cases are ordered by // deterministic scheduler readiness. Argument order breaks ties, not priority. // Losing cases do not receive values or send messages. +// Repeated cases are treated as their first occurrence. func (ctx *OrchestrationContext) Select(cases ...SelectCase) { ctx.selectCase(cases) } @@ -170,26 +195,49 @@ func (ctx *OrchestrationContext) selectCaseErr(cases []SelectCase) (SelectCase, if current.scope.isCanceled() || ctx.scope.isCanceled() { return nil, ErrTaskCanceled } - seen := make(map[SelectCase]struct{}, len(cases)) + taskOrEventOnly := true for _, candidate := range cases { if candidate.owner() != engine { panic("Select case belongs to a different orchestration") } - if _, exists := seen[candidate]; exists { - panic("Select case used more than once") + if _, ok := candidate.(interface{ channelCase() }); ok { + taskOrEventOnly = false + } + } + if taskOrEventOnly { + // Ready task/event cases need no snapshot or waiter registrations. + var selected SelectCase + var selectedOrder uint64 + for _, candidate := range cases { + if ready, order := candidate.ready(nil); ready && + (selected == nil || order < selectedOrder) { + selected, selectedOrder = candidate, order + } + } + if selected != nil { + selected.(interface{ invoke() }).invoke() + return selected, nil } - seen[candidate] = struct{}{} } s := &selection{ctx: ctx, coroutine: current, cases: slices.Clone(cases)} + seen := make(map[SelectCase]struct{}, len(cases)) + s.cases = slices.DeleteFunc(s.cases, func(candidate SelectCase) bool { + if _, exists := seen[candidate]; exists { + return true + } + seen[candidate] = struct{}{} + return false + }) current.selection = s defer func() { s.cleanup() current.selection = nil }() ctx.scope.addWaiter(current) - for _, candidate := range cases { + for _, candidate := range s.cases { candidate.subscribe(s) } + s.notifyChannels() for { // A committed rendezvous is not undone by cancellation applied before // the other coroutine resumes. diff --git a/task/select_test.go b/task/select_test.go index 14bcfc54..c4b804de 100644 --- a/task/select_test.go +++ b/task/select_test.go @@ -445,3 +445,101 @@ func TestEventChannelReceiveErrReturnsPayloadError(t *testing.T) { t.Fatalf("result = %s, want %s", got, want) } } + +type observedSelectCase struct { + SelectCase + subscriptions int +} + +func (c *observedSelectCase) subscribe(s *selection) { + c.subscriptions++ + c.SelectCase.subscribe(s) +} + +func (c *observedSelectCase) invoke() { + c.SelectCase.(interface{ invoke() }).invoke() +} + +func TestSelectRepeatedTaskAndEventCasesRetainFirstOccurrence(t *testing.T) { + for _, event := range []bool{false, true} { + for _, ready := range []bool{false, true} { + t.Run(fmt.Sprintf("event=%t/ready=%t", event, ready), func(t *testing.T) { + registry := NewTaskRegistry() + if err := registry.AddOrchestratorN("repeated-case", func(ctx *OrchestrationContext) (any, error) { + calls := 0 + var candidate SelectCase + if event { + channel := NewEventChannel[int](ctx, "value") + if ready { + queue := list.New() + queue.PushBack(&bufferedEvent{ + event: helpers.NewEventRaisedEvent("value", wrapperspb.String("42")), + order: ctx.scheduler.nextCompletionID(), + }) + ctx.bufferedExternalEvents["VALUE"] = queue + } + candidate = OnEvent(channel, func(int) { calls++ }) + } else { + state := newTaskInScope(ctx, ctx.scope) + if ready { + state.complete(nil) + } else { + ctx.Go(func(*OrchestrationContext) { state.complete(nil) }) + } + candidate = OnTask(state, func(Task) { calls++ }) + } + observed := &observedSelectCase{SelectCase: candidate} + ctx.Select(observed, observed) + wantSubscriptions := 1 + if ready { + wantSubscriptions = 0 + } + if calls != 1 || observed.subscriptions != wantSubscriptions { + return nil, fmt.Errorf("calls=%d subscriptions=%d, want 1 and %d", + calls, observed.subscriptions, wantSubscriptions) + } + if len(ctx.scope.waiters) != 0 || len(ctx.eventWaiters) != 0 { + return nil, errors.New("selection left waiters registered") + } + return calls, nil + }); err != nil { + t.Fatal(err) + } + events := []*protos.HistoryEvent{ + helpers.NewOrchestratorStartedEvent(), + helpers.NewExecutionStartedEvent("repeated-case", "instance", nil, nil, nil, nil), + } + if event && !ready { + events = append(events, helpers.NewEventRaisedEvent("value", wrapperspb.String("42"))) + } + for _, replay := range []bool{false, true} { + var oldEvents, newEvents []*protos.HistoryEvent + if replay { + oldEvents = events + } else { + newEvents = events + } + response := executeOrchestrationTurn(t, registry, "instance", oldEvents, newEvents) + if got := completionResult(t, response); got != "1" { + t.Fatalf("result=%s replay=%t, want 1", got, replay) + } + } + + }) + } + } +} + +func BenchmarkSelectReadyTask(b *testing.B) { + ctx := newTestOrchestrationContext(NewTaskRegistry(), "instance", nil, nil) + ctx.scheduler = newCoroutineScheduler(ctx) + ctx.scheduler.current = &coroutine{scope: ctx.scope, state: coroutineRunning} + state := newTaskInScope(ctx, ctx.scope) + state.complete(nil) + candidate := OnTask(state, nil) + b.ReportAllocs() + b.ResetTimer() + for range b.N { + ctx.Select(candidate, candidate) + } +} From 4eb58b08ca91ca135a4c1d9fe8c5e969f9c8b3a5 Mon Sep 17 00:00:00 2001 From: Andy Staples Date: Mon, 23 Nov 2026 16:58:00 -0700 Subject: [PATCH 3/3] Preserve embedded selection cases and group channel waiters Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- task/channel.go | 104 +++++++++++++++++++++--------- task/channel_test.go | 119 +++++++++++++++++++++++++++++++++-- task/eventchannel.go | 4 ++ task/select.go | 22 ++++--- task/select_external_test.go | 79 +++++++++++++++++++++++ task/select_test.go | 4 -- 6 files changed, 286 insertions(+), 46 deletions(-) create mode 100644 task/select_external_test.go diff --git a/task/channel.go b/task/channel.go index 61af6c6c..6a08ee8f 100644 --- a/task/channel.go +++ b/task/channel.go @@ -19,8 +19,43 @@ type Channel[T any] struct { ctx *OrchestrationContext capacity int buffer []channelValue[T] - senders list.List - receivers list.List + senders channelQueue[T] + receivers channelQueue[T] +} + +// Registrations from one selection are consecutive. Grouping them lets peer +// lookup skip all of its own alternatives in one step without changing order. +type channelQueue[T any] struct { + list.List + groups map[*selection]*channelOperationGroup[T] +} + +type channelOperationGroup[T any] struct { + selection *selection + element *list.Element + operations list.List +} + +func (q *channelQueue[T]) add(op *channelOperation[T]) { + if q.groups == nil { + q.groups = make(map[*selection]*channelOperationGroup[T]) + } + group := q.groups[op.selection] + if group == nil { + group = &channelOperationGroup[T]{selection: op.selection} + group.element = q.PushBack(group) + q.groups[op.selection] = group + } + op.element = group.operations.PushBack(op) +} + +func (q *channelQueue[T]) remove(op *channelOperation[T]) { + group := q.groups[op.selection] + group.operations.Remove(op.element) + if group.operations.Len() == 0 { + q.Remove(group.element) + delete(q.groups, op.selection) + } } type channelValue[T any] struct { @@ -130,9 +165,9 @@ func (c *channelSelectCase[T]) subscribe(s *selection) { c.operations[s] = op channel := c.channel if c.send { - op.element = channel.senders.PushBack(op) + channel.senders.add(op) } else { - op.element = channel.receivers.PushBack(op) + channel.receivers.add(op) } } @@ -144,9 +179,9 @@ func (c *channelSelectCase[T]) unsubscribe(s *selection) { delete(c.operations, s) channel := c.channel if c.send { - channel.senders.Remove(op.element) + channel.senders.remove(op) } else { - channel.receivers.Remove(op.element) + channel.receivers.remove(op) } } @@ -160,9 +195,9 @@ func (op *channelOperation[T]) firstPeer() *channelOperation[T] { peers = &op.candidate.channel.receivers } for element := peers.Front(); element != nil; element = element.Next() { - peer := element.Value.(*channelOperation[T]) - if peer.selection != op.selection && peer.selection.pending() { - return peer + group := element.Value.(*channelOperationGroup[T]) + if group.selection != op.selection && group.selection.pending() { + return group.operations.Front().Value.(*channelOperation[T]) } } return nil @@ -198,7 +233,8 @@ func (c *channelSelectCase[T]) commit(s *selection) bool { } // Do not steal a waiting peer from an earlier ready task, event, or // rendezvous. Let that coroutine resolve its preferred case first. - if peer.selection.preferred() != peer.candidate { + if preferred := peer.selection.preferred(); preferred == nil || + preferred.underlyingCase() != peer.candidate { channel.ctx.scheduler.makeRunnable(peer.selection.coroutine) return false } @@ -244,31 +280,37 @@ func (c *channelSelectCase[T]) commit(s *selection) bool { func (c *Channel[T]) notify() { slots := c.capacity - len(c.buffer) for element := c.senders.Front(); element != nil; element = element.Next() { - op := element.Value.(*channelOperation[T]) - if !op.selection.pending() { + group := element.Value.(*channelOperationGroup[T]) + if !group.selection.pending() { continue } - if c.capacity > 0 { - ready := slots > 0 - if ready { - slots-- + for item := group.operations.Front(); item != nil; item = item.Next() { + op := item.Value.(*channelOperation[T]) + if c.capacity > 0 { + ready := slots > 0 + if ready { + slots-- + } + if ready && !op.ready { + op.order = c.ctx.scheduler.nextCompletionID() + } + op.ready = ready } - if ready && !op.ready { - op.order = c.ctx.scheduler.nextCompletionID() + if ready, _ := op.candidate.ready(op.selection); ready { + c.ctx.scheduler.makeRunnable(op.selection.coroutine) } - op.ready = ready - } - if ready, _ := op.candidate.ready(op.selection); ready { - c.ctx.scheduler.makeRunnable(op.selection.coroutine) } } for element := c.receivers.Front(); element != nil; element = element.Next() { - op := element.Value.(*channelOperation[T]) - if op.selection.pending() { - if ready, _ := op.candidate.ready(op.selection); !ready { - continue + group := element.Value.(*channelOperationGroup[T]) + if group.selection.pending() { + for item := group.operations.Front(); item != nil; item = item.Next() { + op := item.Value.(*channelOperation[T]) + if ready, _ := op.candidate.ready(op.selection); !ready { + continue + } + c.ctx.scheduler.makeRunnable(op.selection.coroutine) } - c.ctx.scheduler.makeRunnable(op.selection.coroutine) } } } @@ -280,7 +322,7 @@ func (s *coroutineScheduler) hasChannelDeadlock() bool { continue } for _, candidate := range c.selection.cases { - if _, ok := candidate.(interface{ channelCase() }); ok { + if candidate.channelNotifier() != nil { channelWait = true } } @@ -310,6 +352,10 @@ func (s *coroutineScheduler) hasChannelDeadlock() bool { return len(s.ctx.eventWaiters) == 0 } -func (*channelSelectCase[T]) channelCase() {} +func (*channelSelectCase[T]) invoke() { + panic("channel case requires a committed selection") +} func (c *channelSelectCase[T]) channelNotifier() channelNotifier { return c.channel } + +func (c *channelSelectCase[T]) underlyingCase() SelectCase { return c } diff --git a/task/channel_test.go b/task/channel_test.go index 7fc681dc..726de9ed 100644 --- a/task/channel_test.go +++ b/task/channel_test.go @@ -549,12 +549,6 @@ func (c *countedChannelCase) ready(s *selection) (bool, uint64) { return c.SelectCase.ready(s) } -func (*countedChannelCase) channelCase() {} - -func (c *countedChannelCase) channelNotifier() channelNotifier { - return c.SelectCase.(interface{ channelNotifier() channelNotifier }).channelNotifier() -} - func TestChannelSameSideWaitersDoNotResumeBeforeDurableDispatch(t *testing.T) { const count = 128 for _, capacity := range []int{0, 1} { @@ -607,6 +601,119 @@ func TestChannelBufferedDrainClearsValuesWithoutMovingTail(t *testing.T) { require.Equal(t, "0", completionResult(t, response)) } +func TestChannelMixedSelectionGroupsAlternativesAndResumesFromActivity(t *testing.T) { + registry := channelRegistry(t, func(ctx *OrchestrationContext) (any, error) { + channel := NewChannel[int](ctx, 0) + cases := make([]SelectCase, 0, 257) + for i := range 128 { + cases = append(cases, + OnSend(channel, i, func() { panic("selection sent to itself") }), + OnReceive(channel, func(int) { panic("selection received from itself") })) + } + inspected := false + ctx.Go(func(*OrchestrationContext) { + assert.Equal(t, 1, channel.senders.Len()) + assert.Equal(t, 1, channel.receivers.Len()) + assert.Equal(t, 128, channel.senders.Front().Value.(*channelOperationGroup[int]).operations.Len()) + assert.Equal(t, 128, channel.receivers.Front().Value.(*channelOperationGroup[int]).operations.Len()) + inspected = true + }) + selected := 0 + cases = append(cases, OnTask(ctx.CallActivity("pending"), func(Task) { selected++ })) + ctx.Select(cases...) + assert.True(t, inspected) + assert.Zero(t, channel.senders.Len()) + assert.Zero(t, channel.receivers.Len()) + return selected, nil + }) + first := executeOrchestrationTurn(t, registry, "instance", nil, channelStart()) + require.Len(t, first.Actions, 1) + require.Equal(t, "pending", first.Actions[0].GetScheduleTask().GetName()) + history := append(channelStart(), helpers.NewTaskScheduledEvent(0, "pending", nil, nil, nil)) + completion := []*protos.HistoryEvent{ + helpers.NewOrchestratorStartedEvent(), + helpers.NewTaskCompletedEvent(0, nil), + } + response := executeOrchestrationTurn(t, registry, "instance", history, completion) + require.Equal(t, "1", completionResult(t, response)) + replay := executeOrchestrationTurn(t, registry, "instance", append(history, completion...), nil) + require.True(t, proto.Equal(response, replay)) +} + +func BenchmarkChannelMixedDirectionSelect(b *testing.B) { + for _, count := range []int{128, 512, 2048} { + b.Run(fmt.Sprint(count), func(b *testing.B) { + registry := NewTaskRegistry() + if err := registry.AddOrchestratorN("channels", func(ctx *OrchestrationContext) (any, error) { + channel := NewChannel[int](ctx, 0) + cases := make([]SelectCase, 0, 2*count+1) + for i := range count { + cases = append(cases, OnSend(channel, i, nil), OnReceive(channel, nil)) + } + cases = append(cases, OnTask(ctx.CallActivity("pending"), nil)) + ctx.Select(cases...) + return nil, nil + }); err != nil { + b.Fatal(err) + } + executor := NewTaskExecutor(registry) + b.ReportAllocs() + b.ResetTimer() + for range b.N { + result, err := executor.ExecuteOrchestrator( + context.Background(), "instance", nil, channelStart(), nil) + if err != nil { + b.Fatal(err) + } + if len(result.Response.Actions) != 1 || + result.Response.Actions[0].GetScheduleTask().GetName() != "pending" { + b.Fatal("mixed selection failed to dispatch durable work") + } + } + }) + } +} + +func TestChannelMixedAlternativesSkipOwnGroupAndKeepPeerOrder(t *testing.T) { + registry := channelRegistry(t, func(ctx *OrchestrationContext) (any, error) { + channel := NewChannel[int](ctx, 0) + group := ctx.NewWaitGroup() + group.Add(2) + values := []int{} + for _, offset := range []int{100, 200} { + ctx.Go(func(branch *OrchestrationContext) { + defer group.Done() + cases := make([]SelectCase, 0, 256) + for i := range 128 { + cases = append(cases, + OnSend(channel, offset+i, nil), + OnReceive(channel, func(int) { panic("branches must not receive their own sends") })) + } + branch.Select(cases...) + }) + } + // The root queues its receive first, so the first branch must pair + // with it rather than itself or the later branch. + values = append(values, channel.Receive(ctx), channel.Receive(ctx)) + group.Wait(ctx) + assert.Zero(t, channel.senders.Len()) + assert.Zero(t, channel.receivers.Len()) + assert.Empty(t, channel.senders.groups) + assert.Empty(t, channel.receivers.groups) + return values, nil + }) + for _, replay := range []bool{false, true} { + var oldEvents, newEvents []*protos.HistoryEvent + if replay { + oldEvents = channelStart() + } else { + newEvents = channelStart() + } + response := executeOrchestrationTurn(t, registry, "instance", oldEvents, newEvents) + require.Equal(t, "[100,200]", completionResult(t, response)) + } +} + func BenchmarkChannelCompetingSelects(b *testing.B) { for _, count := range []int{16, 128, 1024} { b.Run(fmt.Sprint(count), func(b *testing.B) { diff --git a/task/eventchannel.go b/task/eventchannel.go index e6ab66bb..b12f31ad 100644 --- a/task/eventchannel.go +++ b/task/eventchannel.go @@ -106,6 +106,10 @@ type eventSelectCase[T any] struct { handler func(T) } +func (*eventSelectCase[T]) channelNotifier() channelNotifier { return nil } + +func (c *eventSelectCase[T]) underlyingCase() SelectCase { return c } + // OnEvent creates a Select case that receives from a durable event channel. func OnEvent[T any](channel *EventChannel[T], handler func(T)) SelectCase { if channel == nil { diff --git a/task/select.go b/task/select.go index 686e6720..5f80fbc6 100644 --- a/task/select.go +++ b/task/select.go @@ -6,13 +6,17 @@ import ( ) // SelectCase is a durable selection case created by OnTask, OnEvent, -// OnReceive, or OnSend. +// OnReceive, or OnSend. Applications may embed it in their own types; +// embedded cases retain the underlying SDK case's selection behavior. type SelectCase interface { owner() *OrchestrationContext ready(*selection) (bool, uint64) subscribe(*selection) unsubscribe(*selection) commit(*selection) bool + invoke() + channelNotifier() channelNotifier + underlyingCase() SelectCase } // A selection owns all its registrations. A rendezvous commits both selections @@ -69,8 +73,7 @@ type channelNotifier interface { func (s *selection) notifyChannels() { var notified map[channelNotifier]struct{} for _, candidate := range s.cases { - if c, ok := candidate.(interface{ channelNotifier() channelNotifier }); ok { - channel := c.channelNotifier() + if channel := candidate.channelNotifier(); channel != nil { if _, exists := notified[channel]; exists { continue } @@ -125,6 +128,10 @@ func (c *taskSelectCase) invoke() { } } +func (*taskSelectCase) channelNotifier() channelNotifier { return nil } + +func (c *taskSelectCase) underlyingCase() SelectCase { return c } + // WhenAny blocks until the first task completes and returns that task. If // multiple tasks are ready, the task completed first in orchestration history wins. func (ctx *OrchestrationContext) WhenAny(tasks ...Task) Task { @@ -200,7 +207,7 @@ func (ctx *OrchestrationContext) selectCaseErr(cases []SelectCase) (SelectCase, if candidate.owner() != engine { panic("Select case belongs to a different orchestration") } - if _, ok := candidate.(interface{ channelCase() }); ok { + if candidate.channelNotifier() != nil { taskOrEventOnly = false } } @@ -215,17 +222,18 @@ func (ctx *OrchestrationContext) selectCaseErr(cases []SelectCase) (SelectCase, } } if selected != nil { - selected.(interface{ invoke() }).invoke() + selected.invoke() return selected, nil } } s := &selection{ctx: ctx, coroutine: current, cases: slices.Clone(cases)} seen := make(map[SelectCase]struct{}, len(cases)) s.cases = slices.DeleteFunc(s.cases, func(candidate SelectCase) bool { - if _, exists := seen[candidate]; exists { + underlying := candidate.underlyingCase() + if _, exists := seen[underlying]; exists { return true } - seen[candidate] = struct{}{} + seen[underlying] = struct{}{} return false }) current.selection = s diff --git a/task/select_external_test.go b/task/select_external_test.go new file mode 100644 index 00000000..7309ca23 --- /dev/null +++ b/task/select_external_test.go @@ -0,0 +1,79 @@ +package task_test + +import ( + "context" + "testing" + + "github.com/microsoft/durabletask-go/internal/helpers" + "github.com/microsoft/durabletask-go/internal/protos" + "github.com/microsoft/durabletask-go/task" + "github.com/stretchr/testify/require" + "google.golang.org/protobuf/types/known/wrapperspb" +) + +type wrappedSelectCase struct { + task.SelectCase +} + +func TestEmbeddedSelectCase(t *testing.T) { + for _, kind := range []string{"task", "event", "channel"} { + t.Run(kind, func(t *testing.T) { + registry := task.NewTaskRegistry() + require.NoError(t, registry.AddOrchestratorN("wrapped", func(ctx *task.OrchestrationContext) (any, error) { + calls := 0 + switch kind { + case "task": + activity := ctx.CallActivity("work") + if err := activity.Await(nil); err != nil { + return nil, err + } + ctx.Select(wrappedSelectCase{task.OnTask(activity, func(task.Task) { calls++ })}) + case "event": + events := task.NewEventChannel[int](ctx, "value") + if err := ctx.CallActivity("work").Await(nil); err != nil { + return nil, err + } + ctx.Select(wrappedSelectCase{task.OnEvent(events, func(value int) { calls += value })}) + case "channel": + channel := task.NewChannel[int](ctx, 0) + group := ctx.NewWaitGroup() + group.Add(1) + ctx.Go(func(branch *task.OrchestrationContext) { + defer group.Done() + send := task.OnSend(channel, 1, nil) + branch.Select(wrappedSelectCase{send}, send) + }) + ctx.Select(wrappedSelectCase{task.OnReceive(channel, func(value int) { calls += value })}) + group.Wait(ctx) + } + return calls, nil + })) + events := []*protos.HistoryEvent{ + helpers.NewOrchestratorStartedEvent(), + helpers.NewExecutionStartedEvent("wrapped", "instance", nil, nil, nil, nil), + } + if kind != "channel" { + events = append(events, + helpers.NewTaskScheduledEvent(0, "work", nil, nil, nil), + helpers.NewEventRaisedEvent("value", wrapperspb.String("1")), + helpers.NewTaskCompletedEvent(0, nil)) + } + for _, replay := range []bool{false, true} { + var oldEvents, newEvents []*protos.HistoryEvent + if replay { + oldEvents = events + } else { + newEvents = events + } + result, err := task.NewTaskExecutor(registry).ExecuteOrchestrator( + context.Background(), "instance", oldEvents, newEvents, nil) + require.NoError(t, err) + require.Len(t, result.Response.Actions, 1) + completed := result.Response.Actions[0].GetCompleteOrchestration() + require.Equal(t, protos.OrchestrationStatus_ORCHESTRATION_STATUS_COMPLETED, + completed.GetOrchestrationStatus(), "%+v", completed.GetFailureDetails()) + require.Equal(t, "1", completed.GetResult().GetValue()) + } + }) + } +} diff --git a/task/select_test.go b/task/select_test.go index c4b804de..5c0fe585 100644 --- a/task/select_test.go +++ b/task/select_test.go @@ -456,10 +456,6 @@ func (c *observedSelectCase) subscribe(s *selection) { c.SelectCase.subscribe(s) } -func (c *observedSelectCase) invoke() { - c.SelectCase.(interface{ invoke() }).invoke() -} - func TestSelectRepeatedTaskAndEventCasesRetainFirstOccurrence(t *testing.T) { for _, event := range []bool{false, true} { for _, ready := range []bool{false, true} {