diff --git a/CHANGELOG.md b/CHANGELOG.md index 9083bcc1..5891c653 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -43,6 +43,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Added benchmarks for analyzer scaling and allocations across orchestrator count and call-graph depth, for `task.TaskRegistry` orchestrator, activity, versioned, snapshot, and concurrent lookups, and for client work-item filter construction, wire conversion, validation, and per-work-item matching. - Added the preview top-level `exporthistory` package, which exports terminal orchestration histories to Azure Blob Storage as gzip-compressed JSONL. It provides a public client for creating, getting, listing, and per-job create/describe/delete operations; batch and continuous jobs; the `ExportJob` durable entity with `Pending`/`Active`/`Failed`/`Completed` lifecycle transitions; durable checkpoints; terminal-status filters; a per-batch instance limit; per-instance failure collection with implicit job failure when a checkpoint batch fails; delete-and-recreate rules; and typed validation, not-found, invalid-transition, and operation errors carrying stable cross-language error types. Each `Create` mints a nonempty run-generation token and reserves a generation-specific orchestration ID before signaling Run. Only the current generation can mutate job state, though older work may briefly remain in flight. Recreation performs no destructive cleanup and retains previous generations' histories. `Delete` atomically captures the removed generation's ID, and client cleanup targets only that typed result, preserving concurrent recreations even with custom data converters. Read `ExportJobDescription.OrchestratorInstanceID` instead of the removed job-name-only `GetOrchestratorInstanceID` helper. Legacy export-job state and mixed .NET/older Go export workers are not supported. Exported objects are stored as opaque gzip files, named `.jsonl.gz` with content type `application/gzip` and no `Content-Encoding`, so a reader always receives exactly the bytes the object name promises. The system entity, orchestrators, and activities are registered unversioned, and `exporthistory.WithExportHistory()` keeps them routable under strict worker versioning. Destination writes go through a narrow `exporthistory.Store` interface with a production `AzureBlobHistoryStore` implementation that validates containers and prefixes, rejects account URLs carrying userinfo, a query string, or a fragment, and creates each container once. The package is preview: its API, the serialized `ExportJob` state, and its system task names may change without a major version bump, and extended sessions remain unsupported. - Added `client.WithUnversionedActivityNames` and `task.WithUnversionedActivityNames`, the activity counterparts of the existing unversioned-orchestrator allow-lists. An activity inherits its caller's version, so a system component whose orchestration runs unversioned schedules unversioned activities that a strict-version worker would otherwise refuse to accept and would advertise under its own version. +- Added `task.IsCompleted`, a non-blocking check that reports whether an orchestration task has succeeded, failed, or been canceled, without consuming its result or advancing history. It observes completion at the current replay position: after `WhenAny` or `Select` wakes on a completion, only the selected task is guaranteed complete. It panics for nil or custom `Task` implementations, matching `OnTask`, and outside an orchestration coroutine, matching `Select`. The `Task` interface is unchanged. The `orchestratorgo` analyzer treats it as a pure read and reports `for !task.IsCompleted(t)` loops that can never make durable progress. ### Removed diff --git a/README.md b/README.md index cdbf9c23..f5ab790c 100644 --- a/README.md +++ b/README.md @@ -229,6 +229,8 @@ func UpdateDevicesOrchestrator(ctx *task.OrchestrationContext) (any, error) { Full sample: [samples/parallel](./samples/parallel). +To check whether a task has finished without blocking, call `task.IsCompleted(t)`. A task counts as finished when it succeeds, fails, or is canceled. The check doesn't consume the result, so call `Await` to read it. The check reflects the current replay position. After `WhenAny` or `Select` wakes on a completion, only the selected task is guaranteed to be complete. Other completions in the same batch become visible only after the orchestration waits again. A loop that only polls never lets a task finish, so wait with `Await`, `WhenAny`, or `Select`. The [externalevents](./samples/externalevents) sample checks for a stop request between checkpoints. + ### Pattern 3: External events An orchestration can wait for input from an external system. For example, an approval workflow waits for a signal from a user. Use the `WaitForSingleEvent` method to stop the orchestration until the event comes. diff --git a/cmd/orchestratorvet/README.md b/cmd/orchestratorvet/README.md index a4abd519..2d4fdff2 100644 --- a/cmd/orchestratorvet/README.md +++ b/cmd/orchestratorvet/README.md @@ -121,8 +121,19 @@ when the whole-package loop and call graph proves that the body can neither leave the loop nor make durable progress. Any `return`, `break`, `goto`, labelled statement, closure, `go` statement, `defer`, or `panic` in the loop body ends the proof, as does any call the analyzer cannot follow, except calls -to packages it explicitly models as pure. Any interaction with the durable task -package counts as possible progress and suppresses the report. +to packages it explicitly models as pure. A pure-package call that accepts a +function or type-parameter argument also ends the proof because it may invoke +user code. Ranging over a function or type parameter is treated the same way. +Any interaction with the durable task package counts as possible progress and +suppresses the report, except `task.IsCompleted`, which only reads completion +state and never yields. + +A loop whose only condition is `!task.IsCompleted(t)` is held to the same proof +and reported with a polling-specific message, because a task cannot complete +while the orchestration never yields. The report requires `t` to be a local +variable that the loop does not assign and whose address is never taken or +captured by a closure. Compound conditions, such as an added counter bound, are +not reported. Await a task, wait for an event, or call `ctx.ContinueAsNew` to make the loop durable. diff --git a/cmd/orchestratorvet/analysis/orchestratorgo/checks.go b/cmd/orchestratorvet/analysis/orchestratorgo/checks.go index ec7861ee..47394bed 100644 --- a/cmd/orchestratorvet/analysis/orchestratorgo/checks.go +++ b/cmd/orchestratorvet/analysis/orchestratorgo/checks.go @@ -79,16 +79,11 @@ func (c *checker) checkFunction(node ast.Node) { } file := c.index.fileOf[node] stack := c.index.enclosingFunctionStack(node) - ast.Inspect(body, func(current ast.Node) bool { - if current == nil { - stack = stack[:len(stack)-1] - return true - } + ast.PreorderStack(body, stack, func(current ast.Node, stack []ast.Node) bool { if _, ok := current.(*ast.FuncLit); ok { return false } - stack = append(stack, current) - c.inspect(current, stack, file) + c.inspect(current, append(stack, current), file) return true }) } @@ -134,7 +129,7 @@ func (c *checker) inspect(node ast.Node, stack []ast.Node, file *ast.File) { ) } case *ast.ForStmt: - c.checkUnboundedLoop(node) + c.checkUnboundedLoop(node, stack) case *ast.CallExpr: c.checkCall(node, stack, file) } diff --git a/cmd/orchestratorvet/analysis/orchestratorgo/loops.go b/cmd/orchestratorvet/analysis/orchestratorgo/loops.go index 715643c5..c53811db 100644 --- a/cmd/orchestratorvet/analysis/orchestratorgo/loops.go +++ b/cmd/orchestratorvet/analysis/orchestratorgo/loops.go @@ -12,27 +12,139 @@ import ( // checkUnboundedLoop reports a condition-free orchestrator loop only when the // whole-package loop and call graph proves the body can neither leave the loop // nor make durable progress. Any call the analyzer cannot follow, and any use of -// the task package, leaves the loop unreported. -func (c *checker) checkUnboundedLoop(loop *ast.ForStmt) { +// the task package other than the pure task.IsCompleted check, leaves the loop +// unreported. A loop whose only condition is !task.IsCompleted(t) is held to +// the same proof, because its condition cannot change while nothing yields. +func (c *checker) checkUnboundedLoop(loop *ast.ForStmt, stack []ast.Node) { + var polled *types.Var if loop.Cond != nil && !isConstantTrue(c.pass, loop.Cond) { - return - } - if loop.Body == nil { - // `for {}` with an empty body is unambiguously a spin. - c.reportUnboundedLoop(loop) - return + polled = c.polledTask(loop, stack) + if polled == nil { + return + } } probe := &loopProbe{ checker: c, visitedCallees: make(map[ast.Node]bool), } - probe.scan(loop.Body, true) + if loop.Body != nil { + probe.scan(loop.Body, true) + } + if loop.Post != nil { + probe.scan(&ast.BlockStmt{List: []ast.Stmt{loop.Post}}, true) + } if probe.inconclusive { return } + if polled != nil { + c.report( + loop.For, + categoryLoop, + nil, + "loop polls task.IsCompleted without awaiting a durable task or waiting for an event, "+ + "so the task can never complete; use Await, WhenAny, or Select", + ) + return + } c.reportUnboundedLoop(loop) } +// polledTask returns the variable t when the loop condition is exactly +// !task.IsCompleted(t) and t is a local that the loop cannot change: it is not +// assigned in the loop, its address is never taken, and no closure captures it. +func (c *checker) polledTask(loop *ast.ForStmt, stack []ast.Node) *types.Var { + negated, ok := ast.Unparen(loop.Cond).(*ast.UnaryExpr) + if !ok || negated.Op != token.NOT { + return nil + } + call, ok := ast.Unparen(negated.X).(*ast.CallExpr) + if !ok || len(call.Args) != 1 || !isTaskIsCompleted(staticFunc(c.pass, call.Fun)) { + return nil + } + identifier, ok := ast.Unparen(call.Args[0]).(*ast.Ident) + if !ok { + return nil + } + variable, ok := c.pass.TypesInfo.Uses[identifier].(*types.Var) + if !ok || variable.IsField() { + return nil + } + var function ast.Node + for i := len(stack) - 1; i >= 0 && function == nil; i-- { + switch stack[i].(type) { + case *ast.FuncDecl, *ast.FuncLit: + function = stack[i] + } + } + if function == nil || variable.Pos() < function.Pos() || variable.Pos() >= function.End() { + return nil + } + if c.mayChange(function, loop, variable) { + return nil + } + return variable +} + +// mayChange reports whether variable could be modified while loop runs. +func (c *checker) mayChange(function ast.Node, loop *ast.ForStmt, variable *types.Var) bool { + uses := func(expression ast.Expr) bool { + identifier, ok := ast.Unparen(expression).(*ast.Ident) + return ok && c.pass.TypesInfo.Uses[identifier] == variable + } + changed := false + var walk func(node ast.Node, inLoop, inClosure bool) + walk = func(node ast.Node, inLoop, inClosure bool) { + ast.Inspect(node, func(current ast.Node) bool { + if changed { + return false + } + switch current := current.(type) { + case *ast.FuncLit: + if current != function { + walk(current.Body, inLoop, true) + return false + } + case *ast.ForStmt: + if current == loop && !inLoop { + walk(current, true, inClosure) + return false + } + case *ast.Ident: + if inClosure && c.pass.TypesInfo.Uses[current] == variable { + changed = true + } + case *ast.UnaryExpr: + if current.Op == token.AND && uses(current.X) { + changed = true + } + case *ast.AssignStmt: + if inLoop { + for _, target := range current.Lhs { + if uses(target) { + changed = true + } + } + } + case *ast.RangeStmt: + if inLoop && current.Tok == token.ASSIGN && (uses(current.Key) || uses(current.Value)) { + changed = true + } + } + return true + }) + } + walk(function, false, false) + return changed +} + +func isTaskIsCompleted(function *types.Func) bool { + if function == nil || function.Pkg() == nil || function.Pkg().Path() != taskPackagePath { + return false + } + signature, ok := function.Type().(*types.Signature) + return ok && signature.Recv() == nil && function.Name() == "IsCompleted" +} + func (c *checker) reportUnboundedLoop(loop *ast.ForStmt) { c.report( loop.For, @@ -80,7 +192,8 @@ func (p *loopProbe) scan(body *ast.BlockStmt, inLoop bool) { return false } case *ast.RangeStmt: - if isChannel(p.checker.pass.TypesInfo.TypeOf(node.X)) { + rangeType := p.checker.pass.TypesInfo.TypeOf(node.X) + if isChannel(rangeType) || isFunction(rangeType) || isTypeParameter(rangeType) { p.inconclusive = true return false } @@ -111,15 +224,30 @@ func (p *loopProbe) scanCall(call *ast.CallExpr) { return } switch path := function.Pkg().Path(); { + case isTaskIsCompleted(function): + // IsCompleted only reads completion state; it never yields. case path == taskPackagePath: // Any durable task interaction may make progress or block. p.inconclusive = true case pureLoopPackages[path]: + if callMayInvokeUserCode(p.checker.pass, call) { + p.inconclusive = true + } default: p.inconclusive = true } } +func callMayInvokeUserCode(pass *analysis.Pass, call *ast.CallExpr) bool { + for _, argument := range call.Args { + argumentType := pass.TypesInfo.TypeOf(argument) + if isFunction(argumentType) || isTypeParameter(argumentType) { + return true + } + } + return false +} + func (p *loopProbe) scanCallee(node ast.Node) { if p.visitedCallees[node] { // Recursion is safe because the function is already being scanned. @@ -134,6 +262,22 @@ func (p *loopProbe) scanCallee(node ast.Node) { p.scan(body, false) } +func isFunction(value types.Type) bool { + if value == nil { + return false + } + _, ok := value.Underlying().(*types.Signature) + return ok +} + +func isTypeParameter(value types.Type) bool { + if value == nil { + return false + } + _, ok := types.Unalias(value).(*types.TypeParam) + return ok +} + func isConstantTrue(pass *analysis.Pass, expression ast.Expr) bool { typeInfo, ok := pass.TypesInfo.Types[expression] if !ok || typeInfo.Value == nil || typeInfo.Value.Kind() != constant.Bool { diff --git a/cmd/orchestratorvet/analysis/orchestratorgo/testdata/src/github.com/microsoft/durabletask-go/task/task.go b/cmd/orchestratorvet/analysis/orchestratorgo/testdata/src/github.com/microsoft/durabletask-go/task/task.go index 26bb99b2..03450f6e 100644 --- a/cmd/orchestratorvet/analysis/orchestratorgo/testdata/src/github.com/microsoft/durabletask-go/task/task.go +++ b/cmd/orchestratorvet/analysis/orchestratorgo/testdata/src/github.com/microsoft/durabletask-go/task/task.go @@ -26,6 +26,8 @@ type Task interface { Await(v any) error } +func IsCompleted(t Task) bool { return false } + type WaitGroup interface { Add(delta int) Done() diff --git a/cmd/orchestratorvet/analysis/orchestratorgo/testdata/src/loops/loops.go b/cmd/orchestratorvet/analysis/orchestratorgo/testdata/src/loops/loops.go index bcc85d72..48455e20 100644 --- a/cmd/orchestratorvet/analysis/orchestratorgo/testdata/src/loops/loops.go +++ b/cmd/orchestratorvet/analysis/orchestratorgo/testdata/src/loops/loops.go @@ -5,6 +5,7 @@ package loops import ( "path/filepath" + "slices" "strings" "time" @@ -120,6 +121,85 @@ func opaqueLoop(ctx *task.OrchestrationContext) (any, error) { } } +// pollWithoutYield checks completion but never lets the task complete. +func pollWithoutYield(ctx *task.OrchestrationContext) (any, error) { + work := ctx.CallActivity("work") + polls := 0 + for !task.IsCompleted(work) { // want `loop polls task.IsCompleted without awaiting` + polls++ + _ = strings.Repeat("a", polls) + } + for !(task.IsCompleted(work)) { // want `loop polls task.IsCompleted without awaiting` + } + return polls, work.Await(nil) +} + +// spinCheckingCompletion treats IsCompleted as a pure read inside the body. +func spinCheckingCompletion(ctx *task.OrchestrationContext) (any, error) { + work := ctx.CallActivity("work") + ready := 0 + for { // want `unbounded orchestrator loop never awaits a durable task` + if task.IsCompleted(work) { + ready++ + } + } +} + +// pollingLoopsThatProgress are not reported: each can make durable progress, +// leave the loop, or observe a different task. +func pollingLoopsThatProgress(ctx *task.OrchestrationContext) (any, error) { + other := ctx.CallActivity("other") + work := ctx.CallActivity("work") + for !task.IsCompleted(work) { + _ = ctx.CreateTimer(time.Second).Await(nil) + } + wait := func(yield func() bool) { + _ = ctx.CreateTimer(time.Second).Await(nil) + yield() + } + for !task.IsCompleted(work) { + for range wait { + } + } + pollWithGenericIterator(work, wait) + waitValues := func(yield func(int) bool) { + _ = ctx.CreateTimer(time.Second).Await(nil) + yield(0) + } + for !task.IsCompleted(work) { + _ = slices.Collect(waitValues) + } + for !task.IsCompleted(work) { + break + } + for !task.IsCompleted(work) { + work = other + } + swapped := ctx.CallActivity("swapped") + pointer := &swapped + for !task.IsCompleted(swapped) { + *pointer = other + } + captured := ctx.CallActivity("captured") + swap := func() { captured = other } + for !task.IsCompleted(captured) { + swap() + } + tasks := []task.Task{work} + for !task.IsCompleted(tasks[0]) { + } + for i := 0; !task.IsCompleted(work) && i < 3; i++ { + } + return nil, nil +} + +func pollWithGenericIterator[F ~func(func() bool)](work task.Task, wait F) { + for !task.IsCompleted(work) { + for range wait { + } + } +} + func register() { registry := task.NewTaskRegistry() _ = registry.AddOrchestrator(spinForever) @@ -131,4 +211,7 @@ func register() { _ = registry.AddOrchestrator(continueAsNewLoop) _ = registry.AddOrchestrator(boundedLoops) _ = registry.AddOrchestrator(opaqueLoop) + _ = registry.AddOrchestrator(pollWithoutYield) + _ = registry.AddOrchestrator(spinCheckingCompletion) + _ = registry.AddOrchestrator(pollingLoopsThatProgress) } diff --git a/samples/README.md b/samples/README.md index 1a3b330f..00dce757 100644 --- a/samples/README.md +++ b/samples/README.md @@ -14,7 +14,7 @@ operation is not evidence that a feature works end to end. | [parallel](parallel) | Fan-out/fan-in, WhenAll/WhenAny, aggregation | None | | [coroutines](coroutines) | Durable coroutines, wait groups, selection, cancellation scopes | None | | [timers](timers) | Durable delays, scheduled starts, timer splitting, deterministic time/IDs | None | -| [externalevents](externalevents) | Typed and repeated events, timeouts, cross-instance events | Piped or interactive input | +| [externalevents](externalevents) | Typed and repeated events, task readiness, timeouts, cross-instance events | Piped or interactive input | | [suborchestrations](suborchestrations) | Child workflows, results, IDs, metadata and failures | None | | [retries](retries) | Controlled retries, retry handlers, typed/non-retriable failures | None | | [rewind](rewind) | Failed-activity recovery, renewed execution identity and preserved successful work | Rewind-capable DTS service | diff --git a/samples/externalevents/README.md b/samples/externalevents/README.md index fc4127dd..d0f65110 100644 --- a/samples/externalevents/README.md +++ b/samples/externalevents/README.md @@ -6,6 +6,8 @@ - Preserves the five-minute host timeout and the 30-second durable event timeout on the single-event orchestration. - Demonstrates repeated typed `EventChannel` receives and verifies event order. +- Checks a `Stop` event with `task.IsCompleted` between checkpoints, without + blocking normal checkpoint processing while no stop has arrived. - Demonstrates cross-instance durable `SendEvent`. - Runs a controlled expected timeout path that completes successfully only when the durable event wait times out. @@ -28,8 +30,15 @@ printf 'Taylor\n' | go run ./samples/externalevents ## Expected result The sample verifies `Hello, Taylor!`, receives three typed checkpoint events in -order, sends a typed signal from one orchestration to another, and confirms the -expected timeout scenario. On success it prints: +order, verifies a stop request after one checkpoint, sends a typed signal from +one orchestration to another, and confirms the expected timeout scenario. + +The stop check observes events at the current replay position and does not +advance history. A stop request arriving while the orchestration is waiting for +a checkpoint is handled after that checkpoint arrives, not immediately. Use +`Select` with `OnEvent` and `OnTask` if stop must interrupt that wait. + +On success it prints: ```text SAMPLE_OK externalevents diff --git a/samples/externalevents/externalevents.go b/samples/externalevents/externalevents.go index 68778747..9b2406c1 100644 --- a/samples/externalevents/externalevents.go +++ b/samples/externalevents/externalevents.go @@ -179,6 +179,40 @@ func runRepeatedEventChannelScenario( if !reflect.DeepEqual(output, expected) { return fmt.Errorf("repeated event output = %#v, want %#v", output, expected) } + + stopID := dtssample.NewInstanceID("externalevents-stop") + *ownedIDs = append(*ownedIDs, stopID) + if _, err := client.ScheduleNewOrchestration( + ctx, + "RepeatedEventChannelOrch", + api.WithInstanceID(stopID), + api.WithInput(3), + ); err != nil { + return fmt.Errorf("failed to schedule stop event orchestration: %w", err) + } + if _, err := client.WaitForOrchestrationStart(ctx, stopID); err != nil { + return fmt.Errorf("failed to wait for stop event orchestration start: %w", err) + } + if err := client.RaiseEvent(ctx, stopID, "Stop"); err != nil { + return fmt.Errorf("failed to raise stop event: %w", err) + } + if err := client.RaiseEvent(ctx, stopID, "Checkpoint", api.WithEventPayload(events[0])); err != nil { + return fmt.Errorf("failed to raise final checkpoint: %w", err) + } + stopped, err := client.WaitForOrchestrationCompletion(ctx, stopID, api.WithFetchPayloads(true)) + if err != nil { + return fmt.Errorf("failed to wait for stopped orchestration: %w", err) + } + if err := dtssample.RequireCompleted(stopped); err != nil { + return err + } + var stoppedOutput []string + if err := stopped.ReadOutput(&stoppedOutput); err != nil { + return fmt.Errorf("failed to decode stopped output: %w", err) + } + if want := []string{"01:received"}; !reflect.DeepEqual(stoppedOutput, want) { + return fmt.Errorf("stopped output = %#v, want %#v", stoppedOutput, want) + } return nil } @@ -303,14 +337,23 @@ func ExternalEventOrchestrator(ctx *task.OrchestrationContext) (any, error) { return fmt.Sprintf("Hello, %s!", nameInput), nil } +// RepeatedEventChannelOrchestrator checks for stop requests between checkpoints. +// A pending checkpoint wait is not interrupted by a stop request. func RepeatedEventChannelOrchestrator(ctx *task.OrchestrationContext) (any, error) { var count int if err := ctx.GetInput(&count); err != nil { return nil, err } channel := task.NewEventChannel[checkpointEvent](ctx, "Checkpoint") + stop := ctx.WaitForSingleEvent("Stop", -1) results := make([]string, 0, count) for range count { + if task.IsCompleted(stop) { + if err := stop.Await(nil); err != nil { + return nil, err + } + break + } event, err := channel.ReceiveErr(ctx) if err != nil { return nil, err diff --git a/samples/externalevents/externalevents_test.go b/samples/externalevents/externalevents_test.go index aca120a0..bfd52dbb 100644 --- a/samples/externalevents/externalevents_test.go +++ b/samples/externalevents/externalevents_test.go @@ -2,12 +2,20 @@ package main import ( "context" + "encoding/json" "errors" "io" + "slices" "strings" "testing" "testing/iotest" "time" + + "github.com/microsoft/durabletask-go/api" + "github.com/microsoft/durabletask-go/internal/helpers" + "github.com/microsoft/durabletask-go/internal/protos" + "github.com/microsoft/durabletask-go/task" + "google.golang.org/protobuf/types/known/wrapperspb" ) func TestTimeoutSemantics(t *testing.T) { @@ -68,3 +76,113 @@ func TestReadAndRaiseEvent(t *testing.T) { }) } } + +func TestRepeatedEventChannelStopAtCheckpointBoundary(t *testing.T) { + checkpoint := func(index int, label string) *protos.HistoryEvent { + payload, err := json.Marshal(checkpointEvent{Index: index, Label: label}) + if err != nil { + t.Fatal(err) + } + return helpers.NewEventRaisedEvent("Checkpoint", wrapperspb.String(string(payload))) + } + stop := func() *protos.HistoryEvent { + return helpers.NewEventRaisedEvent("Stop", nil) + } + for _, test := range []struct { + name string + batches [][]*protos.HistoryEvent + want []string + wantFailure string + }{ + { + name: "no stop", + batches: [][]*protos.HistoryEvent{ + {checkpoint(1, "received")}, + {checkpoint(2, "validated")}, + {checkpoint(3, "approved")}, + }, + want: []string{"01:received", "02:validated", "03:approved"}, + }, + { + name: "stop does not interrupt pending checkpoint", + batches: [][]*protos.HistoryEvent{{stop()}, {checkpoint(1, "received")}}, + want: []string{"01:received"}, + }, + { + name: "stop and checkpoint in same batch", + batches: [][]*protos.HistoryEvent{{stop(), checkpoint(1, "received")}}, + want: []string{"01:received"}, + }, + { + name: "stop after prior work", + batches: [][]*protos.HistoryEvent{ + {checkpoint(1, "received")}, + {stop()}, + {checkpoint(2, "validated")}, + }, + want: []string{"01:received", "02:validated"}, + }, + { + name: "invalid final checkpoint surfaces error", + batches: [][]*protos.HistoryEvent{ + {stop()}, + {helpers.NewEventRaisedEvent("Checkpoint", wrapperspb.String("{invalid"))}, + }, + wantFailure: "failed to decode task result", + }, + } { + t.Run(test.name, func(t *testing.T) { + registry := task.NewTaskRegistry() + if err := registry.AddOrchestratorN("repeated", RepeatedEventChannelOrchestrator); err != nil { + t.Fatal(err) + } + executor := task.NewTaskExecutor(registry) + history := []*protos.HistoryEvent{ + helpers.NewOrchestratorStartedEvent(), + helpers.NewExecutionStartedEvent("repeated", "instance", wrapperspb.String("3"), nil, nil, nil), + } + first, err := executor.ExecuteOrchestrator(context.Background(), "instance", nil, history, nil) + if err != nil { + t.Fatal(err) + } + if len(first.Response.Actions) != 0 { + t.Fatalf("initial actions = %v, want pending checkpoint wait", first.Response.Actions) + } + for i, batch := range test.batches { + events := append([]*protos.HistoryEvent{helpers.NewOrchestratorStartedEvent()}, batch...) + turn, err := executor.ExecuteOrchestrator(context.Background(), "instance", history, events, nil) + if err != nil { + t.Fatal(err) + } + history = append(history, events...) + if i < len(test.batches)-1 { + if len(turn.Response.Actions) != 0 { + t.Fatalf("batch %d unexpectedly completed: %v", i, turn.Response.Actions) + } + continue + } + if len(turn.Response.Actions) != 1 || turn.Response.Actions[0].GetCompleteOrchestration() == nil { + t.Fatalf("final actions = %v, want completion", turn.Response.Actions) + } + completed := turn.Response.Actions[0].GetCompleteOrchestration() + if test.wantFailure != "" { + if completed.GetOrchestrationStatus() != api.RUNTIME_STATUS_FAILED || + !strings.Contains(completed.GetFailureDetails().GetErrorMessage(), test.wantFailure) { + t.Fatalf("expected failure %q, got %v", test.wantFailure, completed) + } + continue + } + if completed.GetOrchestrationStatus() != api.RUNTIME_STATUS_COMPLETED { + t.Fatalf("expected successful completion, got %v", completed) + } + var output []string + if err := json.Unmarshal([]byte(completed.GetResult().GetValue()), &output); err != nil { + t.Fatal(err) + } + if !slices.Equal(output, test.want) { + t.Fatalf("output = %v, want %v", output, test.want) + } + } + }) + } +} diff --git a/task/task.go b/task/task.go index 57b3b0db..e6ea1790 100644 --- a/task/task.go +++ b/task/task.go @@ -26,6 +26,34 @@ type Task interface { Await(v any) error } +// IsCompleted reports whether a task has completed successfully, failed, or +// been canceled. It does not block, consume the result, or advance history. +// Call Await to retrieve the result or error. +// +// The result reflects the current replay position, not necessarily all events +// already present in history. Completions are applied one at a time, so when +// WhenAny or Select wakes on a completion, only the selected task is guaranteed +// complete; other tasks completing in the same batch are not observed until the +// orchestration waits again. Polling does not yield to the orchestration +// scheduler, so a loop that only polls never makes progress; use Await, +// WhenAny, or Select to wait. +// +// IsCompleted panics for nil or custom Task implementations, and when called +// outside an orchestration coroutine. It supports tasks returned by the +// orchestration context. +func IsCompleted(t Task) bool { + state, ok := taskState(t) + if !ok || state == nil { + panic(fmt.Sprintf("task type %T cannot be checked for completion", t)) + } + scheduler := state.orchestrationCtx.engineContext().scheduler + if scheduler == nil { + panic("IsCompleted called outside orchestrator execution") + } + scheduler.mustCurrent() + return state.isCompleted +} + type completableTask struct { orchestrationCtx *OrchestrationContext isCompleted bool diff --git a/task/task_completion_test.go b/task/task_completion_test.go index 0f159fe3..aaddfcb6 100644 --- a/task/task_completion_test.go +++ b/task/task_completion_test.go @@ -1,9 +1,14 @@ package task import ( + "errors" + "fmt" + "strings" "testing" + "github.com/microsoft/durabletask-go/internal/helpers" "github.com/microsoft/durabletask-go/internal/protos" + "google.golang.org/protobuf/types/known/wrapperspb" ) func TestCompletedTaskIgnoresLaterCancellationFailureAndCompletion(t *testing.T) { @@ -24,3 +29,201 @@ func TestCompletedTaskIgnoresLaterCancellationFailureAndCompletion(t *testing.T) t.Fatalf("result = %q, want first", result) } } + +func TestIsCompletedOutcomes(t *testing.T) { + localErr := errors.New("local failure") + for _, test := range []struct { + name string + finish func(*completableTask) + checkErr func(error) bool + want string + }{ + { + name: "success", + finish: func(task *completableTask) { task.complete([]byte(`"done"`)) }, + checkErr: func(err error) bool { + return err == nil + }, + want: "done", + }, + { + name: "failure", + finish: func(task *completableTask) { + task.fail(&protos.TaskFailureDetails{ErrorMessage: "failed"}) + }, + checkErr: func(err error) bool { + var failed *TaskFailedError + return errors.As(err, &failed) + }, + }, + { + name: "local failure", + finish: func(task *completableTask) { task.failLocal(localErr) }, + checkErr: func(err error) bool { return errors.Is(err, localErr) }, + }, + { + name: "cancellation", + finish: func(task *completableTask) { task.cancel() }, + checkErr: func(err error) bool { return errors.Is(err, ErrTaskCanceled) }, + }, + } { + t.Run(test.name, func(t *testing.T) { + ctx := newTestOrchestrationContext(NewTaskRegistry(), "completion-check", nil, nil) + ctx.scheduler = newCoroutineScheduler(ctx) + ctx.scheduler.current = &coroutine{} + task := newTaskInScope(ctx, ctx.scope) + for i := 0; i < 2; i++ { + if IsCompleted(task) { + t.Fatal("pending task reported complete") + } + } + test.finish(task) + for i := 0; i < 2; i++ { + if !IsCompleted(task) { + t.Fatal("finished task reported incomplete") + } + var result string + if err := task.Await(&result); !test.checkErr(err) { + t.Fatalf("Await() error = %v", err) + } + if result != test.want { + t.Fatalf("result = %q, want %q", result, test.want) + } + } + }) + } +} + +type customCompletionTask struct{} + +func (customCompletionTask) Await(any) error { return nil } +func (customCompletionTask) IsCompleted() bool { return true } + +func TestIsCompletedRejectsUnsupportedTasks(t *testing.T) { + for _, test := range []struct { + name string + task Task + }{ + {name: "nil"}, + {name: "typed nil", task: (*completableTask)(nil)}, + {name: "custom", task: customCompletionTask{}}, + } { + t.Run(test.name, func(t *testing.T) { + defer func() { + if value := recover(); value == nil || !strings.Contains(fmt.Sprint(value), "cannot be checked for completion") { + t.Fatalf("panic = %v, want unsupported-task message", value) + } + }() + IsCompleted(test.task) + }) + } +} + +func TestIsCompletedRequiresOrchestratorExecution(t *testing.T) { + ctx := newTestOrchestrationContext(NewTaskRegistry(), "completion-check", nil, nil) + task := newTaskInScope(ctx, ctx.scope) + task.complete([]byte(`"done"`)) + for _, test := range []struct { + name string + setup func() + want string + }{ + {name: "no scheduler", setup: func() {}, want: "outside orchestrator execution"}, + { + name: "no current coroutine", + setup: func() { ctx.scheduler = newCoroutineScheduler(ctx) }, + want: "outside an orchestration coroutine", + }, + } { + t.Run(test.name, func(t *testing.T) { + test.setup() + defer func() { + if value := recover(); value == nil || !strings.Contains(fmt.Sprint(value), test.want) { + t.Fatalf("panic = %v, want %q", value, test.want) + } + }() + IsCompleted(task) + }) + } +} + +func TestIsCompletedAtReplayPosition(t *testing.T) { + registry := NewTaskRegistry() + if err := registry.AddOrchestratorN("completion-check", func(ctx *OrchestrationContext) (any, error) { + first := ctx.CallActivity("first") + second := ctx.CallActivity("second") + before := IsCompleted(first) || IsCompleted(second) + if ctx.WhenAny(first, second) != first { + return nil, errors.New("unexpected first task") + } + firstReady := IsCompleted(first) + firstReadyAgain := IsCompleted(first) + if firstReady != firstReadyAgain { + return nil, errors.New("first task completion changed between reads") + } + secondBeforeYield := IsCompleted(second) + var firstResult string + if err := first.Await(&firstResult); err != nil { + return nil, err + } + secondAfterFirstAwait := IsCompleted(second) + var secondResult string + if err := second.Await(&secondResult); err != nil { + return nil, err + } + return []any{before, firstReady, secondBeforeYield, secondAfterFirstAwait, IsCompleted(second), firstResult, secondResult}, nil + }); err != nil { + t.Fatal(err) + } + + history := []*protos.HistoryEvent{ + helpers.NewOrchestratorStartedEvent(), + helpers.NewExecutionStartedEvent("completion-check", "completion-replay", nil, nil, nil, nil), + helpers.NewTaskScheduledEvent(0, "first", nil, nil, nil), + helpers.NewTaskScheduledEvent(1, "second", nil, nil, nil), + helpers.NewTaskCompletedEvent(0, wrapperspb.String(`"one"`)), + helpers.NewTaskCompletedEvent(1, wrapperspb.String(`"two"`)), + } + for _, test := range []struct { + name string + old []*protos.HistoryEvent + new []*protos.HistoryEvent + }{ + {name: "replayed", old: history}, + {name: "new events", old: history[:4], new: history[4:]}, + } { + t.Run(test.name, func(t *testing.T) { + response := executeOrchestrationTurn(t, registry, "completion-replay", test.old, test.new) + if got, want := completionResult(t, response), `[false,true,false,false,true,"one","two"]`; got != want { + t.Fatalf("result = %s, want %s", got, want) + } + }) + } +} + +func TestIsCompletedForFailedAndCanceledTasksInOrchestration(t *testing.T) { + registry := NewTaskRegistry() + if err := registry.AddOrchestratorN("completion-outcomes", func(ctx *OrchestrationContext) (any, error) { + failed := ctx.CallActivity("fails") + child, cancel := ctx.WithCancel() + canceled := child.WaitForSingleEvent("never", -1) + cancel() + before := IsCompleted(failed) || IsCompleted(canceled) + err := failed.Await(nil) + var taskErr *TaskFailedError + failureObserved := errors.As(err, &taskErr) + cancelObserved := errors.Is(canceled.Await(nil), ErrTaskCanceled) + return []bool{before, IsCompleted(failed), IsCompleted(canceled), failureObserved, cancelObserved}, nil + }); err != nil { + t.Fatal(err) + } + response := executeOrchestrationTurn(t, registry, "completion-outcomes", nil, []*protos.HistoryEvent{ + helpers.NewOrchestratorStartedEvent(), + helpers.NewExecutionStartedEvent("completion-outcomes", "completion-outcomes", nil, nil, nil, nil), + helpers.NewTaskScheduledEvent(0, "fails", nil, nil, nil), + helpers.NewTaskFailedEvent(0, &protos.TaskFailureDetails{ErrorMessage: "failed"}), + }) + if got, want := completionResult(t, response), `[false,true,true,true,true]`; got != want { + t.Fatalf("result = %s, want %s", got, want) + } +}