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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
15 changes: 13 additions & 2 deletions cmd/orchestratorvet/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
11 changes: 3 additions & 8 deletions cmd/orchestratorvet/analysis/orchestratorgo/checks.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
})
}
Expand Down Expand Up @@ -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)
}
Expand Down
164 changes: 154 additions & 10 deletions cmd/orchestratorvet/analysis/orchestratorgo/loops.go
Original file line number Diff line number Diff line change
Expand Up @@ -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, "+
Comment thread
andystaples marked this conversation as resolved.
Resolved
Comment thread
andystaples marked this conversation as resolved.
Resolved
"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)
Comment thread
andystaples marked this conversation as resolved.
Resolved
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,
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -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
Comment on lines +244 to +245
}
}
return false
}

func (p *loopProbe) scanCallee(node ast.Node) {
if p.visitedCallees[node] {
// Recursion is safe because the function is already being scanned.
Expand All @@ -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 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ package loops

import (
"path/filepath"
"slices"
"strings"
"time"

Expand Down Expand Up @@ -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)
Expand All @@ -131,4 +211,7 @@ func register() {
_ = registry.AddOrchestrator(continueAsNewLoop)
_ = registry.AddOrchestrator(boundedLoops)
_ = registry.AddOrchestrator(opaqueLoop)
_ = registry.AddOrchestrator(pollWithoutYield)
_ = registry.AddOrchestrator(spinCheckingCompletion)
_ = registry.AddOrchestrator(pollingLoopsThatProgress)
}
2 changes: 1 addition & 1 deletion samples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
Loading