diff --git a/CHANGELOG.md b/CHANGELOG.md index 7f234169..0c18ace9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,7 +15,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added -- Added the `durabletasktest` package, which runs orchestrations and activities in a test process against an in-memory Durable Task service over an in-memory gRPC transport. It supports activities, sub-orchestrations, real-time timers, external events, continue-as-new, suspend/resume, terminate, restart, queries, purge, and history. Durable entities and rewind are not supported. Like DTS, the service limits requests and completions to 4 MiB; an activity completion over 4 MiB fails once with the non-retriable error type `ActivityResponseTooLarge`. +- Added the `durabletasktest` package, which runs orchestrations and activities in a test process against an in-memory Durable Task service over an in-memory gRPC transport. It supports activities, sub-orchestrations, real-time timers, external events, continue-as-new, suspend/resume, terminate, restart, rewind, queries, purge, and history. Rewind preserves successful work and recursively recovers failed children, subject to the worker's history-safety limitations; outstanding activities may run again if their results are unavailable, and purged children without retained results are recreated without their previous history. Durable entities are not supported. Like DTS, the service limits requests and completions to 4 MiB; an activity completion over 4 MiB fails once with the non-retriable error type `ActivityResponseTooLarge`. - 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 3db4f7cf..7df6b468 100644 --- a/README.md +++ b/README.md @@ -659,14 +659,16 @@ func TestGreeting(t *testing.T) { } ``` -To isolate an orchestration from its dependencies, register stub activities and sub-orchestrators in the test registry. You can use the client to raise events, suspend, resume, terminate, restart, query, and purge instances, and read history. +To isolate an orchestration from its dependencies, register stub activities and sub-orchestrators in the test registry. You can use the client to raise events, suspend, resume, terminate, restart, rewind, query, and purge instances, and read history. + +`RewindInstance` enqueues recovery of a failed orchestration, preserving successful work and recursively recovering failed sub-orchestrations. Wait for completion to observe recovery. Outstanding timers retain their deadlines, and activities can run again if their results are unavailable. Purged children without retained results are recreated from their recorded inputs without their previous history; conflicting child IDs prevent rewind. The same worker [history-safety limitations](./durabletaskscheduler/README.md#rewind) apply. The in-memory service has these limits: - Timers use the Go runtime clock. `testing/synctest` can advance timers without waiting in real time while the test goroutines are blocked. The `durabletasktest` tests include a 24-hour timer example. -- Durable entities and rewind aren't supported. Entity client calls and `RewindInstance` return `api.ErrFeatureNotSupported`. An orchestration that calls, signals, or locks an entity fails. The service has no task hub name, so a query filtered by `TaskHubNames` also returns `api.ErrFeatureNotSupported`. +- Durable entities aren't supported. Entity client calls return `api.ErrFeatureNotSupported`. An orchestration that calls, signals, or locks an entity fails. The service has no task hub name, so a query filtered by `TaskHubNames` also returns `api.ErrFeatureNotSupported`. - State is kept in memory only. It is discarded when the host closes. - Requests and worker completions are limited to 4 MiB, as in DTS. Larger client requests fail with `ResourceExhausted`. An activity whose completion is larger fails once with the non-retriable error type `ActivityResponseTooLarge` instead of running again. diff --git a/durabletasktest/host.go b/durabletasktest/host.go index 231db350..32911575 100644 --- a/durabletasktest/host.go +++ b/durabletasktest/host.go @@ -20,9 +20,15 @@ // // Timers use the Go runtime clock. Tests can use testing/synctest to // advance timers without waiting in real time. -// Durable entities and orchestration rewind are not supported: entity client -// operations and rewind fail with [api.ErrFeatureNotSupported], and an -// orchestration that calls, signals, or locks an entity fails. +// Failed orchestrations can be rewound with the same history-safety limitations +// as the production worker. Rewind enqueues recovery and preserves successful +// work; outstanding timers and activities are recovered. Activities can run +// again if their results are unavailable. Purged children without retained +// results are recreated without their previous history; conflicting child IDs +// prevent rewind. +// Durable entities are not supported: entity client operations fail with +// [api.ErrFeatureNotSupported], and an orchestration that calls, signals, or +// locks an entity fails. package durabletasktest import ( diff --git a/durabletasktest/host_test.go b/durabletasktest/host_test.go index 98f9f183..f7d858a4 100644 --- a/durabletasktest/host_test.go +++ b/durabletasktest/host_test.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "strings" + "sync" "sync/atomic" "testing" "testing/synctest" @@ -591,7 +592,471 @@ func TestUnsupportedFeatures(t *testing.T) { err := host.Client().SignalEntity(ctx, api.NewEntityID("counter", "a"), "add") assert.ErrorIs(t, err, api.ErrFeatureNotSupported) - assert.ErrorIs(t, host.Client().RewindInstance(ctx, metadata.InstanceID), api.ErrFeatureNotSupported) +} + +func TestRewindRecovery(t *testing.T) { + for _, mode := range []string{"activity", "child", "purged-child", "nested-child"} { + t.Run(mode, func(t *testing.T) { + var repaired atomic.Bool + var goodCalls, failedCalls, parentGoodCalls atomic.Int32 + r := task.NewTaskRegistry() + require.NoError(t, r.AddActivityN("Good", func(task.ActivityContext) (any, error) { + goodCalls.Add(1) + return "kept", nil + })) + require.NoError(t, r.AddActivityN("ParentGood", func(task.ActivityContext) (any, error) { + parentGoodCalls.Add(1) + return "parent", nil + })) + require.NoError(t, r.AddActivityN("Flaky", func(ctx task.ActivityContext) (any, error) { + failedCalls.Add(1) + var input string + if err := ctx.GetInput(&input); err != nil { + return nil, err + } + if !repaired.Load() { + return nil, errors.New("dependency unavailable") + } + return "recovered:" + input, nil + })) + require.NoError(t, r.AddOrchestratorN("Leaf", func(ctx *task.OrchestrationContext) (any, error) { + var input, good, result string + if err := ctx.GetInput(&input); err != nil { + return nil, err + } + if err := ctx.CallActivity("Good").Await(&good); err != nil { + return nil, err + } + err := ctx.CallActivity("Flaky", task.WithActivityInput(input)).Await(&result) + return good + ":" + result, err + })) + require.NoError(t, r.AddOrchestratorN("Parent", func(ctx *task.OrchestrationContext) (any, error) { + var input, good, result string + if err := ctx.GetInput(&input); err != nil { + return nil, err + } + if err := ctx.CallActivity("ParentGood").Await(&good); err != nil { + return nil, err + } + childName := "Leaf" + if mode == "nested-child" && ctx.ID == "root" { + childName = "Parent" + } + err := ctx.CallSubOrchestrator(childName, task.WithSubOrchestratorInput(input), + task.WithSubOrchestrationInstanceID(string(ctx.ID)+"-child")).Await(&result) + return good + ":" + result, err + })) + host := durabletasktest.New(t, r) + ctx := testContext(t) + name := "Leaf" + ids := []api.InstanceID{"root"} + want := "kept:recovered:payload" + if mode != "activity" { + name = "Parent" + ids = append(ids, "root-child") + want = "parent:" + want + } + if mode == "nested-child" { + ids = append(ids, "root-child-child") + want = "parent:" + want + } + failed := run(t, host, name, api.WithInstanceID("root"), api.WithInput("payload")) + require.Equal(t, api.RUNTIME_STATUS_FAILED, failed.RuntimeStatus) + before := make(map[api.InstanceID]string) + for _, id := range ids { + metadata, err := host.Client().FetchOrchestrationMetadata(ctx, id) + require.NoError(t, err) + before[id] = metadata.ExecutionID + } + if mode == "purged-child" { + require.NoError(t, host.Client().PurgeOrchestrationState(ctx, "root-child")) + } + repaired.Store(true) + require.NoError(t, host.Client().RewindInstance(ctx, "root", api.WithRewindReason("dependency repaired"))) + completed, err := host.Client().WaitForOrchestrationCompletion(ctx, "root") + require.NoError(t, err) + require.Equal(t, api.RUNTIME_STATUS_COMPLETED, completed.RuntimeStatus) + var output string + require.NoError(t, completed.ReadOutput(&output)) + require.Equal(t, want, output) + require.Nil(t, completed.FailureDetails) + require.False(t, completed.CompletedAt.IsZero()) + // Successive completions can share a wall-clock tick. + require.False(t, completed.CompletedAt.Before(failed.CompletedAt)) + goodWant := int32(1) + if mode == "purged-child" { + goodWant = 2 // A purged child's successful history is no longer available. + } + require.Equal(t, goodWant, goodCalls.Load()) + require.EqualValues(t, 2, failedCalls.Load()) + require.EqualValues(t, len(ids)-1, parentGoodCalls.Load()) + for i, id := range ids { + history, historyErr := host.Client().GetOrchestrationHistory(ctx, id, api.HistoryQuery{}) + require.NoError(t, historyErr) + require.NotEqual(t, before[id], history.ExecutionID) + rewinds := 0 + for _, event := range history.Events { + require.NotEqual(t, api.HistoryEventTaskFailed, event.Type) + require.NotEqual(t, api.HistoryEventSubOrchestrationInstanceFailed, event.Type) + if event.ExecutionRewound != nil { + rewinds++ + require.Equal(t, "dependency repaired", event.ExecutionRewound.Reason) + } + if i > 0 && event.ExecutionStarted != nil { + parent, parentErr := host.Client().FetchOrchestrationMetadata(ctx, ids[i-1]) + require.NoError(t, parentErr) + require.Equal(t, parent.ExecutionID, event.ExecutionStarted.Parent.ExecutionID) + } + } + wantRewinds := 1 + if mode == "purged-child" && i > 0 { + wantRewinds = 0 + } + require.Equal(t, wantRewinds, rewinds) + } + }) + } +} + +func TestRewindRecoversOutstandingWork(t *testing.T) { + var repaired atomic.Bool + var siblingCalls atomic.Int32 + var startedOnce, releaseOnce sync.Once + started, release := make(chan struct{}), make(chan struct{}) + unblock := func() { releaseOnce.Do(func() { close(release) }) } + r := task.NewTaskRegistry() + require.NoError(t, r.AddActivityN("Sibling", func(ctx task.ActivityContext) (any, error) { + siblingCalls.Add(1) + startedOnce.Do(func() { close(started) }) + select { + case <-release: + return "sibling", nil + case <-ctx.Context().Done(): + return nil, ctx.Context().Err() + } + })) + require.NoError(t, r.AddActivityN("Flaky", func(ctx task.ActivityContext) (any, error) { + select { + case <-started: + case <-ctx.Context().Done(): + return nil, ctx.Context().Err() + } + if !repaired.Load() { + return nil, errors.New("dependency unavailable") + } + return "repaired", nil + })) + require.NoError(t, r.AddOrchestratorN("Concurrent", func(ctx *task.OrchestrationContext) (any, error) { + sibling := ctx.CallActivity("Sibling") + timer := ctx.CreateTimer(2 * time.Second) + flaky := ctx.CallActivity("Flaky") + var fixed, message, result string + if err := flaky.Await(&fixed); err != nil { + return nil, err + } + if err := ctx.WaitForSingleEvent("message", -1).Await(&message); err != nil { + return nil, err + } + if err := sibling.Await(&result); err != nil { + return nil, err + } + if err := timer.Await(nil); err != nil { + return nil, err + } + return fixed + ":" + result + ":" + message, nil + })) + host := durabletasktest.New(t, r) + t.Cleanup(unblock) + ctx := testContext(t) + failed := run(t, host, "Concurrent", api.WithInstanceID("concurrent")) + require.Equal(t, api.RUNTIME_STATUS_FAILED, failed.RuntimeStatus) + history, err := host.Client().GetOrchestrationHistory(ctx, failed.InstanceID, api.HistoryQuery{}) + require.NoError(t, err) + var timerCreated bool + for _, event := range history.Events { + timerCreated = timerCreated || event.Type == api.HistoryEventTimerCreated + require.NotEqual(t, api.HistoryEventTimerFired, event.Type) + } + require.True(t, timerCreated) + + repaired.Store(true) + require.NoError(t, host.Client().RewindInstance(ctx, failed.InstanceID)) + require.NoError(t, host.Client().RaiseEvent(ctx, failed.InstanceID, "message", api.WithEventPayload("kept"))) + require.Eventually(t, func() bool { + metadata, fetchErr := host.Client().FetchOrchestrationMetadata(ctx, failed.InstanceID) + return fetchErr == nil && metadata.ExecutionID != failed.ExecutionID + }, 10*time.Second, 5*time.Millisecond) + unblock() + + completed, err := host.Client().WaitForOrchestrationCompletion(ctx, failed.InstanceID) + require.NoError(t, err) + require.Equal(t, api.RUNTIME_STATUS_COMPLETED, completed.RuntimeStatus) + var output string + require.NoError(t, completed.ReadOutput(&output)) + require.Equal(t, "repaired:sibling:kept", output) + require.EqualValues(t, 1, siblingCalls.Load()) +} + +func TestRewindRecoversChildCompletedAfterParentFailure(t *testing.T) { + var repaired atomic.Bool + var childCalls atomic.Int32 + var startedOnce, releaseOnce sync.Once + started, release := make(chan struct{}), make(chan struct{}) + unblock := func() { releaseOnce.Do(func() { close(release) }) } + r := task.NewTaskRegistry() + require.NoError(t, r.AddActivityN("ChildWork", func(ctx task.ActivityContext) (any, error) { + childCalls.Add(1) + startedOnce.Do(func() { close(started) }) + select { + case <-release: + return "child result", nil + case <-ctx.Context().Done(): + return nil, ctx.Context().Err() + } + })) + require.NoError(t, r.AddActivityN("Flaky", func(ctx task.ActivityContext) (any, error) { + select { + case <-started: + case <-ctx.Context().Done(): + return nil, ctx.Context().Err() + } + if !repaired.Load() { + return nil, errors.New("dependency unavailable") + } + return nil, nil + })) + require.NoError(t, r.AddOrchestratorN("Child", func(ctx *task.OrchestrationContext) (any, error) { + var result string + err := ctx.CallActivity("ChildWork").Await(&result) + return result, err + })) + require.NoError(t, r.AddOrchestratorN("Parent", func(ctx *task.OrchestrationContext) (any, error) { + child := ctx.CallSubOrchestrator("Child", task.WithSubOrchestrationInstanceID("late-child")) + if err := ctx.CallActivity("Flaky").Await(nil); err != nil { + return nil, err + } + var result string + err := child.Await(&result) + return result, err + })) + host := durabletasktest.New(t, r) + t.Cleanup(unblock) + ctx := testContext(t) + failed := run(t, host, "Parent", api.WithInstanceID("parent")) + require.Equal(t, api.RUNTIME_STATUS_FAILED, failed.RuntimeStatus) + unblock() + child, err := host.Client().WaitForOrchestrationCompletion(ctx, "late-child") + require.NoError(t, err) + require.Equal(t, api.RUNTIME_STATUS_COMPLETED, child.RuntimeStatus) + + repaired.Store(true) + require.NoError(t, host.Client().RewindInstance(ctx, failed.InstanceID)) + completed, err := host.Client().WaitForOrchestrationCompletion(ctx, failed.InstanceID) + require.NoError(t, err) + require.Equal(t, api.RUNTIME_STATUS_COMPLETED, completed.RuntimeStatus) + var output string + require.NoError(t, completed.ReadOutput(&output)) + require.Equal(t, "child result", output) + after, err := host.Client().FetchOrchestrationMetadata(ctx, child.InstanceID) + require.NoError(t, err) + require.Equal(t, child.ExecutionID, after.ExecutionID) + require.EqualValues(t, 1, childCalls.Load()) +} + +func TestRewindRejectsChildIDCollision(t *testing.T) { + r := task.NewTaskRegistry() + require.NoError(t, r.AddOrchestratorN("Unrelated", func(ctx *task.OrchestrationContext) (any, error) { + return nil, ctx.WaitForSingleEvent("release", -1).Await(nil) + })) + require.NoError(t, r.AddOrchestratorN("Child", func(*task.OrchestrationContext) (any, error) { + return "owned", nil + })) + require.NoError(t, r.AddOrchestratorN("Parent", func(ctx *task.OrchestrationContext) (any, error) { + var result string + err := ctx.CallSubOrchestrator("Child", task.WithSubOrchestrationInstanceID("shared")).Await(&result) + return result, err + })) + host := durabletasktest.New(t, r) + ctx := testContext(t) + shared, err := host.Client().ScheduleNewOrchestration(ctx, "Unrelated", api.WithInstanceID("shared")) + require.NoError(t, err) + unrelated, err := host.Client().WaitForOrchestrationStart(ctx, shared) + require.NoError(t, err) + failed := run(t, host, "Parent", api.WithInstanceID("parent")) + require.Equal(t, api.RUNTIME_STATUS_FAILED, failed.RuntimeStatus) + require.Contains(t, failed.FailureDetails.ErrorMessage, "already exists") + + require.ErrorIs(t, host.Client().RewindInstance(ctx, failed.InstanceID), api.ErrDuplicateInstance) + after, err := host.Client().FetchOrchestrationMetadata(ctx, shared) + require.NoError(t, err) + require.Equal(t, unrelated.ExecutionID, after.ExecutionID) + require.Equal(t, "Unrelated", after.Name) + require.Equal(t, api.RUNTIME_STATUS_RUNNING, after.RuntimeStatus) + + require.NoError(t, host.Client().RaiseEvent(ctx, shared, "release")) + _, err = host.Client().WaitForOrchestrationCompletion(ctx, shared) + require.NoError(t, err) + require.NoError(t, host.Client().PurgeOrchestrationState(ctx, shared)) + require.NoError(t, host.Client().RewindInstance(ctx, failed.InstanceID)) + completed, err := host.Client().WaitForOrchestrationCompletion(ctx, failed.InstanceID) + require.NoError(t, err) + require.Equal(t, api.RUNTIME_STATUS_COMPLETED, completed.RuntimeStatus) + var output string + require.NoError(t, completed.ReadOutput(&output)) + require.Equal(t, "owned", output) +} + +func TestRewindInvalidState(t *testing.T) { + r := task.NewTaskRegistry() + require.NoError(t, r.AddOrchestratorN("Done", func(*task.OrchestrationContext) (any, error) { + return nil, nil + })) + require.NoError(t, r.AddOrchestratorN("Waiting", func(ctx *task.OrchestrationContext) (any, error) { + return nil, ctx.WaitForSingleEvent("finish", -1).Await(nil) + })) + host := durabletasktest.New(t, r) + ctx := testContext(t) + require.ErrorIs(t, host.Client().RewindInstance(ctx, "missing"), api.ErrInstanceNotFound) + done := run(t, host, "Done") + require.ErrorIs(t, host.Client().RewindInstance(ctx, done.InstanceID), api.ErrInvalidState) + id, err := host.Client().ScheduleNewOrchestration(ctx, "Waiting") + require.NoError(t, err) + _, err = host.Client().WaitForOrchestrationStart(ctx, id) + require.NoError(t, err) + require.ErrorIs(t, host.Client().RewindInstance(ctx, id), api.ErrInvalidState) + require.NoError(t, host.Client().SuspendOrchestration(ctx, id, "test")) + require.ErrorIs(t, host.Client().RewindInstance(ctx, id), api.ErrInvalidState) + require.NoError(t, host.Client().TerminateOrchestration(ctx, id)) + _, err = host.Client().WaitForOrchestrationCompletion(ctx, id) + require.NoError(t, err) + require.ErrorIs(t, host.Client().RewindInstance(ctx, id), api.ErrInvalidState) +} + +func TestRewindRejectsUnsafeHistory(t *testing.T) { + for _, mode := range []string{"root", "child"} { + t.Run(mode, func(t *testing.T) { + var calls atomic.Int32 + r := task.NewTaskRegistry() + for _, name := range []string{"handled", "good", "terminal"} { + require.NoError(t, r.AddActivityN(name, func(task.ActivityContext) (any, error) { + calls.Add(1) + if name != "good" { + return nil, errors.New(name) + } + return "kept", nil + })) + } + require.NoError(t, r.AddOrchestratorN("Unsafe", func(ctx *task.OrchestrationContext) (any, error) { + if err := ctx.CallActivity("handled").Await(nil); err == nil { + return nil, errors.New("expected a handled failure") + } + if err := ctx.CallActivity("good").Await(nil); err != nil { + return nil, err + } + return nil, ctx.CallActivity("terminal").Await(nil) + })) + require.NoError(t, r.AddOrchestratorN("Parent", func(ctx *task.OrchestrationContext) (any, error) { + return nil, ctx.CallSubOrchestrator("Unsafe", task.WithSubOrchestrationInstanceID("unsafe-child")).Await(nil) + })) + host := durabletasktest.New(t, r) + ctx, cancel := context.WithTimeout(testContext(t), 10*time.Second) + defer cancel() + name := "Unsafe" + if mode == "child" { + name = "Parent" + } + failed := run(t, host, name) + require.Equal(t, api.RUNTIME_STATUS_FAILED, failed.RuntimeStatus) + require.NoError(t, host.Client().RewindInstance(ctx, failed.InstanceID)) + rejected, err := host.Client().WaitForOrchestrationCompletion(ctx, failed.InstanceID) + require.NoError(t, err) + require.Equal(t, api.RUNTIME_STATUS_FAILED, rejected.RuntimeStatus) + if mode == "child" { + require.NotEqual(t, failed.ExecutionID, rejected.ExecutionID) + rejected, err = host.Client().FetchOrchestrationMetadata(ctx, "unsafe-child") + require.NoError(t, err) + } else { + require.Equal(t, failed.ExecutionID, rejected.ExecutionID) + } + require.Contains(t, rejected.FailureDetails.ErrorMessage, "Go SDK cannot safely rewind this history") + require.EqualValues(t, 3, calls.Load()) + }) + } +} + +func TestRewindRetriesAfterRejectedReplacement(t *testing.T) { + for _, mode := range []string{"root", "child"} { + t.Run(mode, func(t *testing.T) { + var repaired atomic.Bool + r := task.NewTaskRegistry() + require.NoError(t, r.AddActivityN("Good", func(task.ActivityContext) (any, error) { + return strings.Repeat("x", 40_000), nil + })) + require.NoError(t, r.AddActivityN("Flaky", func(task.ActivityContext) (any, error) { + if !repaired.Load() { + return nil, errors.New("dependency unavailable") + } + return "recovered", nil + })) + require.NoError(t, r.AddOrchestratorN("Leaf", func(ctx *task.OrchestrationContext) (any, error) { + if err := ctx.CallActivity("Good").Await(nil); err != nil { + return nil, err + } + var result string + err := ctx.CallActivity("Flaky").Await(&result) + return result, err + })) + require.NoError(t, r.AddOrchestratorN("Parent", func(ctx *task.OrchestrationContext) (any, error) { + var result string + err := ctx.CallSubOrchestrator("Leaf", task.WithSubOrchestrationInstanceID("leaf-child")).Await(&result) + return result, err + })) + // The leaf's replacement history exceeds this limit only with the long reason. + host := durabletasktest.New(t, r, + durabletasktest.WithWorkerOptions(client.WithMaxOrchestratorCompletionBytes(64*1024))) + ctx := testContext(t) + name, leafID := "Leaf", api.InstanceID("") + if mode == "child" { + name, leafID = "Parent", "leaf-child" + } + failed := run(t, host, name) + require.Equal(t, api.RUNTIME_STATUS_FAILED, failed.RuntimeStatus) + if leafID == "" { + leafID = failed.InstanceID + } + leafBefore, err := host.Client().FetchOrchestrationMetadata(ctx, leafID) + require.NoError(t, err) + repaired.Store(true) + + require.NoError(t, host.Client().RewindInstance(ctx, failed.InstanceID, + api.WithRewindReason(strings.Repeat("r", 30_000)))) + rejected, err := host.Client().WaitForOrchestrationCompletion(ctx, failed.InstanceID) + require.NoError(t, err) + require.Equal(t, api.RUNTIME_STATUS_FAILED, rejected.RuntimeStatus) + if mode == "child" { + require.NotEqual(t, failed.ExecutionID, rejected.ExecutionID, "the renewed parent observes the rejection") + } + leaf, err := host.Client().FetchOrchestrationMetadata(ctx, leafID) + require.NoError(t, err) + require.Equal(t, api.RUNTIME_STATUS_FAILED, leaf.RuntimeStatus) + require.Equal(t, leafBefore.ExecutionID, leaf.ExecutionID) + require.Equal(t, api.ErrorTypeOrchestratorResponseTooLarge, api.ErrorType(leaf.FailureDetails.ErrorType)) + history, err := host.Client().GetOrchestrationHistory(ctx, leafID, api.HistoryQuery{}) + require.NoError(t, err) + for _, event := range history.Events { + require.NotEqual(t, api.HistoryEventExecutionRewound, event.Type, + "a rejected rewind must not change the rewindable history") + } + + require.NoError(t, host.Client().RewindInstance(ctx, failed.InstanceID, api.WithRewindReason("short"))) + completed, err := host.Client().WaitForOrchestrationCompletion(ctx, failed.InstanceID) + require.NoError(t, err) + require.Equal(t, api.RUNTIME_STATUS_COMPLETED, completed.RuntimeStatus) + var output string + require.NoError(t, completed.ReadOutput(&output)) + require.Equal(t, "recovered", output) + }) + } } func TestQueryByTaskHubNameIsNotSupported(t *testing.T) { diff --git a/internal/inmemory/rewind.go b/internal/inmemory/rewind.go new file mode 100644 index 00000000..a12fbd8a --- /dev/null +++ b/internal/inmemory/rewind.go @@ -0,0 +1,470 @@ +package inmemory + +import ( + "context" + "fmt" + "slices" + "time" + + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/types/known/timestamppb" + "google.golang.org/protobuf/types/known/wrapperspb" + + "github.com/microsoft/durabletask-go/internal/grpcerrors" + "github.com/microsoft/durabletask-go/internal/helpers" + "github.com/microsoft/durabletask-go/internal/protos" +) + +// RewindInstance enqueues recovery of a failed instance through the worker. +func (s *Server) RewindInstance(_ context.Context, req *protos.RewindInstanceRequest) (*protos.RewindInstanceResponse, error) { + s.mu.Lock() + defer s.mu.Unlock() + inst, err := s.lookupLocked(req.GetInstanceId()) + if err != nil { + return nil, err + } + if inst.status != protos.OrchestrationStatus_ORCHESTRATION_STATUS_FAILED { + return nil, grpcerrors.New(codes.FailedPrecondition, + fmt.Sprintf("orchestration instance %q is not in a failed state", inst.id), grpcerrors.ReasonInvalidState) + } + rewind := newRewindEvent(req.GetReason(), nil) + // The request limit leaves room for a reason that fits the request but not + // the work item that delivers it. + if size := rewindWorkItemSize(inst, rewind); size > maxOrchestrationWorkItemSize { + return nil, status.Errorf(codes.InvalidArgument, + "rewind reason is too large: the %d-byte rewind work item exceeds the %d-byte gRPC message limit of the in-memory test backend", + size, maxOrchestrationWorkItemSize) + } + if err := s.validateRewindChildrenLocked(inst, inst.history, make(map[*instance]bool)); err != nil { + return nil, err + } + s.prepareRewindLocked(inst, rewind) + return &protos.RewindInstanceResponse{}, nil +} + +func newRewindEvent(reason, parentExecutionID *wrapperspb.StringValue) *protos.HistoryEvent { + return &protos.HistoryEvent{ + EventId: -1, + Timestamp: timestamppb.Now(), + EventType: &protos.HistoryEvent_ExecutionRewound{ExecutionRewound: &protos.ExecutionRewoundEvent{ + Reason: reason, ParentExecutionId: parentExecutionID, + }}, + } +} + +// rewindWorkItemSize returns the size of the work item that delivers a rewind +// with streamed history, which is the smallest form it can take. +func rewindWorkItemSize(inst *instance, rewind *protos.HistoryEvent) int { + return proto.Size(&protos.WorkItem{ + Request: &protos.WorkItem_OrchestratorRequest{OrchestratorRequest: &protos.OrchestratorRequest{ + InstanceId: inst.id, + ExecutionId: wrapperspb.String(inst.executionID), + NewEvents: []*protos.HistoryEvent{helpers.NewOrchestratorStartedEvent(), rewind}, + RequiresHistoryStreaming: true, + }}, + CompletionToken: newID(), + }) +} + +func (s *Server) prepareRewindLocked(inst *instance, rewind *protos.HistoryEvent) { + inst.stopTimers() + inst.status = protos.OrchestrationStatus_ORCHESTRATION_STATUS_RUNNING + inst.output = nil + inst.failure = nil + inst.completedAt = time.Time{} + inst.updatedAt = time.Now() + inst.rewind = rewind + s.enqueueLocked(inst) +} + +func validateRewindHistory(history []*protos.HistoryEvent, oldExecutionID string) error { + starts := 0 + for _, event := range history { + if event.GetExecutionCompleted() != nil { + return status.Error(codes.InvalidArgument, "rewind history must not contain execution completion") + } + if started := event.GetExecutionStarted(); started != nil { + starts++ + executionID := started.GetOrchestrationInstance().GetExecutionId().GetValue() + if executionID == "" || executionID == oldExecutionID { + return status.Error(codes.InvalidArgument, "rewind history requires a new execution ID") + } + } + if timer := event.GetTimerCreated(); timer != nil { + if timer.GetFireAt() == nil || timer.GetFireAt().CheckValid() != nil { + return status.Error(codes.InvalidArgument, "rewind history contains an invalid timer deadline") + } + } + } + if starts != 1 { + return status.Error(codes.InvalidArgument, "rewind history requires exactly one execution start") + } + return nil +} + +func unfinishedSubOrchestrations(history []*protos.HistoryEvent) []*protos.HistoryEvent { + completed := make(map[int32]bool) + for _, event := range history { + if child := event.GetSubOrchestrationInstanceCompleted(); child != nil { + completed[child.GetTaskScheduledId()] = true + } + } + var unfinished []*protos.HistoryEvent + for _, event := range history { + if event.GetSubOrchestrationInstanceCreated() != nil && !completed[event.GetEventId()] { + unfinished = append(unfinished, event) + } + } + return unfinished +} + +func failedSubOrchestrations(history []*protos.HistoryEvent) map[int32]bool { + failed := make(map[int32]bool) + for _, event := range history { + if child := event.GetSubOrchestrationInstanceFailed(); child != nil { + failed[child.GetTaskScheduledId()] = true + } + } + return failed +} + +func (s *Server) pendingRewindChildResults( + inst *instance, + history []*protos.HistoryEvent, + failed map[int32]bool, +) map[int32]*protos.HistoryEvent { + created := make(map[int32]string) + for _, event := range unfinishedSubOrchestrations(history) { + created[event.GetEventId()] = event.GetSubOrchestrationInstanceCreated().GetInstanceId() + } + results := make(map[int32]*protos.HistoryEvent) + for _, event := range inst.pending { + var id int32 + failedResult := false + switch { + case event.GetSubOrchestrationInstanceCompleted() != nil: + id = event.GetSubOrchestrationInstanceCompleted().GetTaskScheduledId() + case event.GetSubOrchestrationInstanceFailed() != nil: + id = event.GetSubOrchestrationInstanceFailed().GetTaskScheduledId() + failedResult = true + if failed[id] { + continue + } + default: + continue + } + source := inst.childResultSources[event] + if source.instanceID == "" || source.instanceID != created[id] { + continue + } + if child, ok := s.instances[source.instanceID]; ok && failedResult { + if childMatchesParent(child, inst, inst.executionID, id) && + (child.executionID != source.executionID || !isTerminal(child.status) || + child.status == protos.OrchestrationStatus_ORCHESTRATION_STATUS_COMPLETED) { + continue + } + } + if previous := results[id]; previous == nil || previous.GetSubOrchestrationInstanceFailed() != nil { + results[id] = event + } + } + return results +} + +func (s *Server) validateRewindChildrenLocked(inst *instance, history []*protos.HistoryEvent, seen map[*instance]bool) error { + if seen[inst] { + return status.Errorf(codes.FailedPrecondition, "cannot rewind cyclic sub-orchestration %q", inst.id) + } + seen[inst] = true + defer delete(seen, inst) + + failed := failedSubOrchestrations(inst.history) + results := s.pendingRewindChildResults(inst, history, failed) + for _, event := range unfinishedSubOrchestrations(history) { + if results[event.GetEventId()] != nil { + continue + } + childID := event.GetSubOrchestrationInstanceCreated().GetInstanceId() + child, ok := s.instances[childID] + if !ok { + continue + } + if !childMatchesParent(child, inst, inst.executionID, event.GetEventId()) { + return status.Errorf(codes.AlreadyExists, + "cannot rewind orchestration %q: sub-orchestration ID %q belongs to another parent or execution", + inst.id, childID) + } + if child.status == protos.OrchestrationStatus_ORCHESTRATION_STATUS_FAILED && failed[event.GetEventId()] { + if err := s.validateRewindChildrenLocked(child, child.history, seen); err != nil { + return err + } + } + } + return nil +} + +func childMatchesParent(child, parent *instance, parentExecutionID string, taskID int32) bool { + ref := child.parent.GetOrchestrationInstance() + return ref.GetInstanceId() == parent.id && + ref.GetExecutionId().GetValue() == parentExecutionID && + child.parent.GetTaskScheduledId() == taskID +} + +func (s *Server) applyRewindIdentityLocked(inst *instance, history []*protos.HistoryEvent) { + inst.history = slices.Clone(history) + parentExecutionID := inst.rewind.GetExecutionRewound().GetParentExecutionId() + for i, event := range inst.history { + started := event.GetExecutionStarted() + if started == nil { + continue + } + if parentExecutionID.GetValue() != "" && started.GetParentInstance() != nil { + event = proto.CloneOf(event) + started = event.GetExecutionStarted() + if started.ParentInstance.OrchestrationInstance == nil { + started.ParentInstance.OrchestrationInstance = &protos.OrchestrationInstance{} + } + started.ParentInstance.OrchestrationInstance.ExecutionId = proto.CloneOf(parentExecutionID) + inst.history[i] = event + } + inst.executionID = started.GetOrchestrationInstance().GetExecutionId().GetValue() + inst.parent = started.GetParentInstance() + } +} + +func (s *Server) retargetRewindParentLocked(inst *instance) { + parentExecutionID := inst.rewind.GetExecutionRewound().GetParentExecutionId() + if parentExecutionID.GetValue() != "" && inst.parent != nil { + parent := proto.CloneOf(inst.parent) + if parent.OrchestrationInstance == nil { + parent.OrchestrationInstance = &protos.OrchestrationInstance{} + } + parent.OrchestrationInstance.ExecutionId = proto.CloneOf(parentExecutionID) + s.retargetChildLocked(inst, parent) + } +} + +// failRewindLocked ends a rewind attempt that didn't replace the history. Only +// the failure is replaced, so the history stays rewindable, and the parent +// that rewound the instance is notified. +func (s *Server) failRewindLocked(inst *instance, failure *protos.TaskFailureDetails) { + s.retargetRewindParentLocked(inst) + for i := len(inst.history) - 1; i >= 0; i-- { + if inst.history[i].GetExecutionCompleted() != nil { + inst.history = inst.history[:i] + break + } + } + s.completeLocked(inst, protos.OrchestrationStatus_ORCHESTRATION_STATUS_FAILED, nil, failure) +} + +func rewindValidationFailure(err error) *protos.TaskFailureDetails { + errorType := "InvalidRewindState" + if status.Code(err) == codes.AlreadyExists { + errorType = "OrchestrationAlreadyExists" + } + return failureDetails(errorType, "%s", status.Convert(err).Message()) +} + +// Persist the worker's replacement, then reconcile retained work before replay. +func (s *Server) applyRewindLocked(inst *instance, action *protos.RewindOrchestrationAction) { + oldExecutionID := inst.executionID + failed := failedSubOrchestrations(inst.history) + childResults := s.pendingRewindChildResults(inst, action.GetNewHistory(), failed) + s.applyRewindIdentityLocked(inst, action.GetNewHistory()) + var reason *wrapperspb.StringValue + for _, event := range inst.history { + if rewound := event.GetExecutionRewound(); rewound != nil { + reason = rewound.GetReason() + } + } + inst.rewind = nil + s.reconcileRewindTasksLocked(inst, oldExecutionID, childResults) + + for _, event := range unfinishedSubOrchestrations(inst.history) { + created := event.GetSubOrchestrationInstanceCreated() + parent := helpers.NewParentInfo(event.GetEventId(), inst.name, inst.id) + parent.Version = inst.version + parent.OrchestrationInstance.ExecutionId = wrapperspb.String(inst.executionID) + child, ok := s.instances[created.GetInstanceId()] + if result := childResults[event.GetEventId()]; result != nil { + source := inst.childResultSources[result] + // A buffered result can outlive its child and a reused ID. + if ok && child.executionID == source.executionID && + childMatchesParent(child, inst, oldExecutionID, event.GetEventId()) { + s.retargetChildLocked(child, parent) + } + continue + } + switch { + case !ok: + child = s.newInstanceLocked(created.GetInstanceId(), created.GetName(), created.GetVersion(), + created.GetInput(), created.GetTags(), parent, created.GetParentTraceContext(), nil) + case child.status == protos.OrchestrationStatus_ORCHESTRATION_STATUS_FAILED && failed[event.GetEventId()]: + // Retarget now: the renewed parent can fail and be rewound again + // before this child's replacement history is committed. + s.retargetChildLocked(child, parent) + s.prepareRewindLocked(child, newRewindEvent(reason, wrapperspb.String(inst.executionID))) + case isTerminal(child.status): + s.retargetChildLocked(child, parent) + result := subOrchestrationResultEvent(child) + inst.recordChildResult(result, child) + index := len(inst.pending) + for i, pending := range inst.pending { + if result.GetTimestamp().AsTime().Before(pending.GetTimestamp().AsTime()) { + index = i + break + } + } + inst.pending = slices.Insert(inst.pending, index, result) + default: + s.retargetChildLocked(child, parent) + } + if !slices.Contains(inst.children, child.id) { + inst.children = append(inst.children, child.id) + } + } + inst.pending = append([]*protos.HistoryEvent{helpers.NewOrchestratorStartedEvent()}, inst.pending...) +} + +func (s *Server) retargetChildLocked(child *instance, parent *protos.ParentInstanceInfo) { + child.parent = parent + if child.rewind != nil { + child.rewind = proto.CloneOf(child.rewind) + child.rewind.GetExecutionRewound().ParentExecutionId = proto.CloneOf(parent.GetOrchestrationInstance().GetExecutionId()) + } + updateParent := func(events []*protos.HistoryEvent) { + for i, event := range events { + if event.GetExecutionStarted() != nil { + cloned := proto.CloneOf(event) + cloned.GetExecutionStarted().ParentInstance = parent + events[i] = cloned + } + } + } + updateParent(child.history) + updateParent(child.pending) + for _, lease := range s.orchLeases { + if lease.inst == child { + lease.events = slices.Clone(lease.events) + updateParent(lease.events) + } + } +} + +func (s *Server) reconcileRewindTasksLocked( + inst *instance, + oldExecutionID string, + childResults map[int32]*protos.HistoryEvent, +) { + activities := make(map[int32]*protos.TaskScheduledEvent) + timers := make(map[int32]*timestamppb.Timestamp) + for _, event := range inst.history { + switch { + case event.GetTaskScheduled() != nil: + activities[event.GetEventId()] = event.GetTaskScheduled() + case event.GetTaskCompleted() != nil: + delete(activities, event.GetTaskCompleted().GetTaskScheduledId()) + case event.GetTaskFailed() != nil: + delete(activities, event.GetTaskFailed().GetTaskScheduledId()) + case event.GetTimerCreated() != nil: + timers[event.GetEventId()] = event.GetTimerCreated().GetFireAt() + case event.GetTimerFired() != nil: + delete(timers, event.GetTimerFired().GetTimerId()) + } + } + + pending := inst.pending[:0] + for _, event := range inst.pending { + switch { + case event.GetTaskCompleted() != nil: + id := event.GetTaskCompleted().GetTaskScheduledId() + if _, ok := activities[id]; ok { + pending = append(pending, event) + delete(activities, id) + } + case event.GetTaskFailed() != nil: + id := event.GetTaskFailed().GetTaskScheduledId() + if _, ok := activities[id]; ok { + pending = append(pending, event) + delete(activities, id) + } + case event.GetTimerFired() != nil: + id := event.GetTimerFired().GetTimerId() + if _, ok := timers[id]; ok { + pending = append(pending, event) + delete(timers, id) + } + case event.GetSubOrchestrationInstanceCompleted() != nil: + id := event.GetSubOrchestrationInstanceCompleted().GetTaskScheduledId() + if childResults[id] == event { + pending = append(pending, event) + } else { + delete(inst.childResultSources, event) + } + case event.GetSubOrchestrationInstanceFailed() != nil: + id := event.GetSubOrchestrationInstanceFailed().GetTaskScheduledId() + if childResults[id] == event { + pending = append(pending, event) + } else { + delete(inst.childResultSources, event) + } + default: + pending = append(pending, event) + } + } + inst.pending = pending + + for _, lease := range s.actLeases { + item := lease.item + if item.inst == inst && item.executionID == oldExecutionID { + if _, ok := activities[item.request.GetTaskId()]; ok { + item.retarget(inst.executionID) + delete(activities, item.request.GetTaskId()) + } + } + } + queue := s.actQueue + kept := queue[:0] + for _, item := range queue { + if item.inst == inst && item.executionID == oldExecutionID { + if _, ok := activities[item.request.GetTaskId()]; !ok { + continue + } + item.retarget(inst.executionID) + delete(activities, item.request.GetTaskId()) + } + kept = append(kept, item) + } + clear(queue[len(kept):]) + s.actQueue = kept + + for _, event := range inst.history { + if task := event.GetTaskScheduled(); task != nil { + if _, ok := activities[event.GetEventId()]; ok { + s.queueActivityLocked(inst, event.GetEventId(), task) + delete(activities, event.GetEventId()) + } + } + if event.GetTimerCreated() != nil { + if fireAt, ok := timers[event.GetEventId()]; ok { + id := event.GetEventId() + s.startTimerLocked(inst, fireAt.AsTime(), func() { + s.deliverLocked(inst, helpers.NewTimerFiredEvent(id, fireAt, nil)) + }) + delete(timers, id) + } + } + } +} + +func (item *activityItem) retarget(executionID string) { + item.executionID = executionID + item.request = proto.CloneOf(item.request) + if item.request.OrchestrationInstance == nil { + item.request.OrchestrationInstance = &protos.OrchestrationInstance{} + } + item.request.OrchestrationInstance.ExecutionId = wrapperspb.String(executionID) +} diff --git a/internal/inmemory/server.go b/internal/inmemory/server.go index 855a56b4..d5d6ffeb 100644 --- a/internal/inmemory/server.go +++ b/internal/inmemory/server.go @@ -2,8 +2,7 @@ // // The service keeps all orchestration state in process memory and serves the // same gRPC protocol as the Durable Task Scheduler, so the regular client and -// worker can run against it. Timers fire in real time. Entities and rewind are -// not supported. +// worker can run against it. Timers fire in real time. Entities are not supported. package inmemory import ( @@ -71,8 +70,10 @@ type instance struct { scheduledStart *timestamppb.Timestamp executionID string - history []*protos.HistoryEvent - pending []*protos.HistoryEvent + history []*protos.HistoryEvent + pending []*protos.HistoryEvent + rewind *protos.HistoryEvent + childResultSources map[*protos.HistoryEvent]childResultSource // started is set once the first orchestration turn commits. Suspension // changes status but not whether the instance has started. @@ -89,10 +90,16 @@ type activityItem struct { request *protos.ActivityRequest } +type childResultSource struct { + instanceID string + executionID string +} + type orchestrationLease struct { - inst *instance - events []*protos.HistoryEvent - streamID uint64 + inst *instance + events []*protos.HistoryEvent + streamID uint64 + rewinding bool } type activityLease struct { @@ -254,7 +261,8 @@ func (s *Server) startTimerLocked(inst *instance, at time.Time, fn func()) { } func (s *Server) enqueueLocked(inst *instance) { - if inst.queued || inst.leased || len(inst.pending) == 0 || s.instances[inst.id] != inst { + if inst.queued || inst.leased || isTerminal(inst.status) || + (len(inst.pending) == 0 && inst.rewind == nil) || s.instances[inst.id] != inst { return } if inst.scheduledStart != nil && len(inst.history) == 0 && inst.scheduledStart.AsTime().After(time.Now()) { diff --git a/internal/inmemory/work.go b/internal/inmemory/work.go index 9dfa6a69..7cc83808 100644 --- a/internal/inmemory/work.go +++ b/internal/inmemory/work.go @@ -81,7 +81,8 @@ func (s *Server) nextWorkItemLocked( } s.orchQueue = slices.Delete(s.orchQueue, i, i+1) inst.queued = false - if s.instances[inst.id] != inst || inst.leased || len(inst.pending) == 0 { + if s.instances[inst.id] != inst || inst.leased || isTerminal(inst.status) || + (len(inst.pending) == 0 && inst.rewind == nil) { // A stale queue entry; look again from the start. return s.nextWorkItemLocked(filters, streamID, limits) } @@ -135,13 +136,19 @@ func countActivityLeases(leases map[string]*activityLease, streamID uint64) int // leaseOrchestrationLocked leases an instance's pending events as a work item // that fits in one gRPC message. History that doesn't fit is streamed, and new // events that don't fit stay pending for later turns. If the first new event -// can't fit on its own, the instance fails and nil is returned. +// or a rewind can't fit on its own, the instance fails and nil is returned. func (s *Server) leaseOrchestrationLocked(inst *instance, streamID uint64) *protos.WorkItem { - events := inst.pending + rewinding := inst.rewind != nil + var events []*protos.HistoryEvent prepended := 0 - if events[0].GetOrchestratorStarted() == nil { - events = append([]*protos.HistoryEvent{helpers.NewOrchestratorStartedEvent()}, events...) - prepended = 1 + if rewinding { + events = []*protos.HistoryEvent{helpers.NewOrchestratorStartedEvent(), proto.CloneOf(inst.rewind)} + } else { + events = inst.pending + if events[0].GetOrchestratorStarted() == nil { + events = append([]*protos.HistoryEvent{helpers.NewOrchestratorStartedEvent()}, events...) + prepended = 1 + } } token := newID() request := &protos.OrchestratorRequest{ @@ -158,7 +165,18 @@ func (s *Server) leaseOrchestrationLocked(inst *instance, streamID uint64) *prot request.PastEvents = nil request.RequiresHistoryStreaming = true } - if proto.Size(item) > maxOrchestrationWorkItemSize { + if rewinding && proto.Size(item) > maxOrchestrationWorkItemSize { + // Requeuing would fail the same way, so end the attempt. + s.failRewindLocked(inst, &protos.TaskFailureDetails{ + ErrorType: "OrchestrationWorkItemTooLarge", + ErrorMessage: fmt.Sprintf( + "a %d-byte rewind work item can't be delivered within the %d-byte gRPC message limit of the in-memory test backend", + proto.Size(item), maxOrchestrationWorkItemSize), + IsNonRetriable: true, + }) + return nil + } + if !rewinding && proto.Size(item) > maxOrchestrationWorkItemSize { n := fittingNewEventCount(item, events) // The batch must hold the OrchestratorStarted marker and at least one event. if n < 2 { @@ -174,9 +192,11 @@ func (s *Server) leaseOrchestrationLocked(inst *instance, streamID uint64) *prot events = slices.Clip(events[:n]) request.NewEvents = events } - inst.pending = slices.Clone(inst.pending[len(events)-prepended:]) + if !rewinding { + inst.pending = slices.Clone(inst.pending[len(events)-prepended:]) + } inst.leased = true - s.orchLeases[token] = &orchestrationLease{inst: inst, events: events, streamID: streamID} + s.orchLeases[token] = &orchestrationLease{inst: inst, events: events, streamID: streamID, rewinding: rewinding} return item } @@ -275,7 +295,9 @@ func (s *Server) abandonOrchestrationLocked(token string, lease *orchestrationLe s.notifyLocked() return } - inst.pending = append(lease.events, inst.pending...) + if !lease.rewinding { + inst.pending = append(lease.events, inst.pending...) + } s.enqueueLocked(inst) s.notifyLocked() } @@ -328,13 +350,19 @@ func (s *Server) CompleteActivityTask(_ context.Context, resp *protos.ActivityRe return &protos.CompleteTaskResponse{}, nil } taskID := item.request.GetTaskId() + var event *protos.HistoryEvent if failure := oversizedCompletionFailure(errorTypeActivityResponseTooLarge, "activity response", resp); failure != nil { // Fail the task rather than store a result over the receive limit. - s.deliverLocked(inst, helpers.NewTaskFailedEvent(taskID, failure)) + event = helpers.NewTaskFailedEvent(taskID, failure) } else if resp.GetFailureDetails() != nil { - s.deliverLocked(inst, helpers.NewTaskFailedEvent(taskID, resp.GetFailureDetails())) + event = helpers.NewTaskFailedEvent(taskID, resp.GetFailureDetails()) } else { - s.deliverLocked(inst, helpers.NewTaskCompletedEvent(taskID, resp.GetResult())) + event = helpers.NewTaskCompletedEvent(taskID, resp.GetResult()) + } + if inst.status == protos.OrchestrationStatus_ORCHESTRATION_STATUS_FAILED { + inst.pending = append(inst.pending, event) + } else { + s.deliverLocked(inst, event) } s.notifyLocked() return &protos.CompleteTaskResponse{}, nil @@ -354,6 +382,28 @@ func (s *Server) CompleteOrchestratorTask(_ context.Context, resp *protos.Orches s.abandonOrchestrationLocked(token, lease) return &protos.CompleteTaskResponse{}, nil } + var rewind *protos.RewindOrchestrationAction + for _, action := range resp.GetActions() { + if replacement := action.GetRewindOrchestration(); replacement != nil { + if len(resp.GetActions()) != 1 { + return nil, status.Error(codes.InvalidArgument, "rewind must be the only orchestration action") + } + if !lease.rewinding { + return nil, status.Error(codes.InvalidArgument, "rewind replacement requires a rewind work item") + } + if err := validateRewindHistory(replacement.GetNewHistory(), inst.executionID); err != nil { + return nil, err + } + rewind = replacement + } + } + if lease.rewinding && rewind == nil { + if len(resp.GetActions()) != 1 || + resp.GetActions()[0].GetCompleteOrchestration().GetOrchestrationStatus() != + protos.OrchestrationStatus_ORCHESTRATION_STATUS_FAILED { + return nil, status.Error(codes.InvalidArgument, "rewind work item requires a replacement or failure") + } + } delete(s.orchLeases, token) inst.leased = false if s.instances[inst.id] != inst || isTerminal(inst.status) { @@ -361,6 +411,25 @@ func (s *Server) CompleteOrchestratorTask(_ context.Context, resp *protos.Orches return &protos.CompleteTaskResponse{}, nil } + inst.customStatus = resp.GetCustomStatus() + inst.updatedAt = time.Now() + if rewind != nil { + if err := s.validateRewindChildrenLocked(inst, rewind.GetNewHistory(), make(map[*instance]bool)); err != nil { + s.failRewindLocked(inst, rewindValidationFailure(err)) + } else { + s.applyRewindLocked(inst, rewind) + s.enqueueLocked(inst) + s.notifyLocked() + } + return &protos.CompleteTaskResponse{}, nil + } + if lease.rewinding { + // The worker rejected the rewind. Don't record the attempt, so that a + // later rewind sees the original failure. + s.failRewindLocked(inst, resp.GetActions()[0].GetCompleteOrchestration().GetFailureDetails()) + return &protos.CompleteTaskResponse{}, nil + } + processed := lease.events if n := resp.GetNumEventsProcessed(); n != nil && int(n.GetValue()) < len(processed) { // NumEventsProcessed counts work events, not control markers in the @@ -370,13 +439,13 @@ func (s *Server) CompleteOrchestratorTask(_ context.Context, resp *protos.Orches processed = processed[:split] } inst.history = append(inst.history, processed...) + for _, event := range processed { + delete(inst.childResultSources, event) + } inst.started = true if inst.status == protos.OrchestrationStatus_ORCHESTRATION_STATUS_PENDING { inst.status = protos.OrchestrationStatus_ORCHESTRATION_STATUS_RUNNING } - inst.customStatus = resp.GetCustomStatus() - inst.updatedAt = time.Now() - s.applyActionsLocked(inst, resp.GetActions()) s.enqueueLocked(inst) s.notifyLocked() @@ -435,22 +504,7 @@ func (s *Server) applyActionsLocked(inst *instance, actions []*protos.Orchestrat event := helpers.NewTaskScheduledEvent(id, task.GetName(), task.GetVersion(), task.GetInput(), task.GetParentTraceContext()) event.GetTaskScheduled().Tags = task.GetTags() inst.history = append(inst.history, event) - s.actQueue = append(s.actQueue, &activityItem{ - inst: inst, - executionID: inst.executionID, - request: &protos.ActivityRequest{ - Name: task.GetName(), - Version: task.GetVersion(), - Input: task.GetInput(), - OrchestrationInstance: &protos.OrchestrationInstance{ - InstanceId: inst.id, - ExecutionId: wrapperspb.String(inst.executionID), - }, - TaskId: id, - ParentTraceContext: task.GetParentTraceContext(), - Tags: task.GetTags(), - }, - }) + s.queueActivityLocked(inst, id, event.GetTaskScheduled()) case *protos.OrchestratorAction_CreateTimer: fireAt := a.CreateTimer.GetFireAt() inst.history = append(inst.history, helpers.NewTimerCreatedEvent(id, fireAt)) @@ -491,14 +545,37 @@ func (s *Server) applyActionsLocked(inst *instance, actions []*protos.Orchestrat s.completeLocked(inst, complete.GetOrchestrationStatus(), complete.GetResult(), complete.GetFailureDetails()) } +func (s *Server) queueActivityLocked(inst *instance, id int32, task *protos.TaskScheduledEvent) { + s.actQueue = append(s.actQueue, &activityItem{ + inst: inst, + executionID: inst.executionID, + request: &protos.ActivityRequest{ + Name: task.GetName(), + Version: task.GetVersion(), + Input: task.GetInput(), + OrchestrationInstance: &protos.OrchestrationInstance{ + InstanceId: inst.id, + ExecutionId: wrapperspb.String(inst.executionID), + }, + TaskId: id, + ParentTraceContext: task.GetParentTraceContext(), + Tags: task.GetTags(), + }, + }) +} + func (s *Server) createSubOrchestrationLocked(parent *instance, taskID int32, action *protos.CreateSubOrchestrationAction) { childID := action.GetInstanceId() + existing, exists := s.instances[childID] + collision := exists && !isTerminal(existing.status) + + // Record the scheduling decision even when it fails, so replay can match it. created := helpers.NewSubOrchestrationCreatedEvent( taskID, action.GetName(), action.GetVersion(), action.GetInput(), childID, action.GetParentTraceContext()) created.GetSubOrchestrationInstanceCreated().Tags = action.GetTags() parent.history = append(parent.history, created) - if existing, ok := s.instances[childID]; ok && !isTerminal(existing.status) { + if collision { s.deliverLocked(parent, &protos.HistoryEvent{ EventId: -1, Timestamp: timestamppb.Now(), @@ -553,11 +630,16 @@ func (s *Server) continueAsNewLocked(inst *instance, complete *protos.CompleteOr } } inst.pending = pending + inst.childResultSources = nil } func (s *Server) failUnsupportedLocked(inst *instance, format string, args ...any) { failure := failureDetails("NotSupported", format, args...) failure.IsNonRetriable = true + s.failLocked(inst, failure) +} + +func (s *Server) failLocked(inst *instance, failure *protos.TaskFailureDetails) { inst.history = append(inst.history, &protos.HistoryEvent{ EventId: -1, Timestamp: timestamppb.Now(), @@ -580,7 +662,28 @@ func (s *Server) completeLocked( inst.failure = failure inst.completedAt = now inst.updatedAt = now - inst.pending = nil + inst.rewind = nil + if runtimeStatus == protos.OrchestrationStatus_ORCHESTRATION_STATUS_FAILED { + // Retain results for rewind, but not suspend, resume, or terminate + // requests: the failure superseded them, and rewind restarts the + // instance as running. + inst.pending = slices.DeleteFunc(inst.pending, func(event *protos.HistoryEvent) bool { + switch event.GetEventType().(type) { + case *protos.HistoryEvent_EventRaised, + *protos.HistoryEvent_TaskCompleted, + *protos.HistoryEvent_TaskFailed, + *protos.HistoryEvent_TimerFired, + *protos.HistoryEvent_SubOrchestrationInstanceCompleted, + *protos.HistoryEvent_SubOrchestrationInstanceFailed: + return false + default: + return true + } + }) + } else { + inst.pending = nil + inst.childResultSources = nil + } inst.history = append(inst.history, &protos.HistoryEvent{ EventId: -1, Timestamp: timestamppb.New(now), @@ -594,22 +697,41 @@ func (s *Server) completeLocked( parentRef := inst.parent.GetOrchestrationInstance() parent, ok := s.instances[parentRef.GetInstanceId()] - if !ok || parent.executionID != parentRef.GetExecutionId().GetValue() { + if !ok || parent.executionID != parentRef.GetExecutionId().GetValue() || + (isTerminal(parent.status) && parent.status != protos.OrchestrationStatus_ORCHESTRATION_STATUS_FAILED) { return } + event := subOrchestrationResultEvent(inst) + parent.recordChildResult(event, inst) + if parent.status == protos.OrchestrationStatus_ORCHESTRATION_STATUS_FAILED { + parent.pending = append(parent.pending, event) + } else { + s.deliverLocked(parent, event) + } +} + +func (inst *instance) recordChildResult(event *protos.HistoryEvent, child *instance) { + if inst.childResultSources == nil { + inst.childResultSources = make(map[*protos.HistoryEvent]childResultSource) + } + inst.childResultSources[event] = childResultSource{instanceID: child.id, executionID: child.executionID} +} + +func subOrchestrationResultEvent(inst *instance) *protos.HistoryEvent { taskID := inst.parent.GetTaskScheduledId() - event := &protos.HistoryEvent{EventId: -1, Timestamp: timestamppb.New(now)} - if runtimeStatus == protos.OrchestrationStatus_ORCHESTRATION_STATUS_COMPLETED { + event := &protos.HistoryEvent{EventId: -1, Timestamp: timestamppb.New(inst.completedAt)} + if inst.status == protos.OrchestrationStatus_ORCHESTRATION_STATUS_COMPLETED { event.EventType = &protos.HistoryEvent_SubOrchestrationInstanceCompleted{ SubOrchestrationInstanceCompleted: &protos.SubOrchestrationInstanceCompletedEvent{ TaskScheduledId: taskID, - Result: output, + Result: inst.output, }, } } else { + failure := inst.failure if failure == nil { failure = failureDetails("OrchestrationTerminated", - "sub-orchestration %q ended with status %s", inst.id, helpers.ToRuntimeStatusString(runtimeStatus)) + "sub-orchestration %q ended with status %s", inst.id, helpers.ToRuntimeStatusString(inst.status)) } event.EventType = &protos.HistoryEvent_SubOrchestrationInstanceFailed{ SubOrchestrationInstanceFailed: &protos.SubOrchestrationInstanceFailedEvent{ @@ -618,5 +740,5 @@ func (s *Server) completeLocked( }, } } - s.deliverLocked(parent, event) + return event } diff --git a/internal/inmemory/work_test.go b/internal/inmemory/work_test.go index ccfd7033..1b29d385 100644 --- a/internal/inmemory/work_test.go +++ b/internal/inmemory/work_test.go @@ -11,6 +11,8 @@ import ( "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/types/known/timestamppb" "google.golang.org/protobuf/types/known/wrapperspb" "github.com/microsoft/durabletask-go/internal/helpers" @@ -148,6 +150,681 @@ func TestContinueAsNewDropsPreviousExecutionResults(t *testing.T) { assert.Same(t, raised, inst.pending[2]) } +func TestRewindReplacementAndStaleActivity(t *testing.T) { + s := NewServer() + defer s.Close() + inst := s.newInstanceLocked("id", "orchestrator", nil, nil, nil, nil, nil, nil) + started := inst.pending[0] + oldExecution := inst.executionID + inst.history = []*protos.HistoryEvent{started} + s.completeLocked(inst, protos.OrchestrationStatus_ORCHESTRATION_STATUS_FAILED, nil, failureDetails("failure", "boom")) + s.actLeases["old-activity"] = &activityLease{item: &activityItem{ + inst: inst, executionID: oldExecution, request: &protos.ActivityRequest{TaskId: 0}, + }} + _, err := s.RewindInstance(context.Background(), &protos.RewindInstanceRequest{ + InstanceId: inst.id, Reason: wrapperspb.String("repaired"), + }) + require.NoError(t, err) + require.True(t, inst.completedAt.IsZero()) + require.Nil(t, inst.failure) + require.Equal(t, oldExecution, inst.executionID, "identity changes only when the worker replaces history") + item := s.nextWorkItemLocked(nil, 1, workItemLimits{}) + req := item.GetOrchestratorRequest() + require.Len(t, req.GetNewEvents(), 2) + require.NotNil(t, req.NewEvents[0].GetOrchestratorStarted()) + require.Equal(t, "repaired", req.NewEvents[1].GetExecutionRewound().GetReason().GetValue()) + + _, err = s.CompleteOrchestratorTask(context.Background(), &protos.OrchestratorResponse{ + CompletionToken: item.GetCompletionToken(), + }) + require.Equal(t, codes.InvalidArgument, status.Code(err)) + require.True(t, inst.leased, "an incomplete rewind must not consume the lease") + response := &protos.OrchestratorResponse{ + CompletionToken: item.GetCompletionToken(), + Actions: []*protos.OrchestratorAction{{OrchestratorActionType: &protos.OrchestratorAction_RewindOrchestration{ + RewindOrchestration: &protos.RewindOrchestrationAction{}, + }}}, + } + _, err = s.CompleteOrchestratorTask(context.Background(), response) + require.Equal(t, codes.InvalidArgument, status.Code(err)) + require.True(t, inst.leased, "invalid replacement must not consume the lease") + response.Actions[0].GetRewindOrchestration().NewHistory = []*protos.HistoryEvent{started} + _, err = s.CompleteOrchestratorTask(context.Background(), response) + require.Equal(t, codes.InvalidArgument, status.Code(err), "replacement must renew the execution ID") + replacementStart := proto.CloneOf(started) + replacementStart.GetExecutionStarted().OrchestrationInstance.ExecutionId = wrapperspb.String("renewed") + replacement := []*protos.HistoryEvent{replacementStart, req.NewEvents[0], req.NewEvents[1]} + response.Actions[0].GetRewindOrchestration().NewHistory = replacement + arrival := helpers.NewEventRaisedEvent("during-rewrite", nil) + s.deliverLocked(inst, arrival) + _, err = s.CompleteOrchestratorTask(context.Background(), response) + require.NoError(t, err) + require.Equal(t, "renewed", inst.executionID) + require.Equal(t, replacement, inst.history, "persist replacement without extra markers") + require.Len(t, inst.pending, 2) + require.NotNil(t, inst.pending[0].GetOrchestratorStarted()) + require.Same(t, arrival, inst.pending[1], "retain events arriving during replacement") + _, err = s.CompleteActivityTask(context.Background(), &protos.ActivityResponse{CompletionToken: "old-activity"}) + require.NoError(t, err) + require.Len(t, inst.pending, 2, "old execution results must not reach the renewed execution") +} + +func TestRewindRejectsNonFailedStates(t *testing.T) { + for _, state := range []protos.OrchestrationStatus{ + protos.OrchestrationStatus_ORCHESTRATION_STATUS_PENDING, + protos.OrchestrationStatus_ORCHESTRATION_STATUS_RUNNING, + protos.OrchestrationStatus_ORCHESTRATION_STATUS_SUSPENDED, + protos.OrchestrationStatus_ORCHESTRATION_STATUS_COMPLETED, + protos.OrchestrationStatus_ORCHESTRATION_STATUS_TERMINATED, + protos.OrchestrationStatus_ORCHESTRATION_STATUS_CANCELED, + } { + t.Run(state.String(), func(t *testing.T) { + s := NewServer() + defer s.Close() + inst := &instance{id: "id", status: state, completedAt: time.Now()} + s.instances[inst.id] = inst + _, err := s.RewindInstance(context.Background(), &protos.RewindInstanceRequest{InstanceId: inst.id}) + require.Equal(t, codes.FailedPrecondition, status.Code(err)) + require.Equal(t, state, inst.status) + require.Empty(t, inst.pending) + }) + } +} + +func TestRewindPreservesSuccessfulChildAndRetargetsRunningChild(t *testing.T) { + s := NewServer() + defer s.Close() + parent := s.newInstanceLocked("parent", "parent", nil, nil, nil, nil, nil, nil) + oldParent := helpers.NewParentInfo(1, parent.name, parent.id) + oldParent.OrchestrationInstance.ExecutionId = wrapperspb.String(parent.executionID) + running := s.newInstanceLocked("running", "child", nil, nil, nil, oldParent, nil, nil) + runningItem := s.leaseOrchestrationLocked(running, 1) + dispatched := runningItem.GetOrchestratorRequest().GetNewEvents() + completed := &instance{id: "completed", status: protos.OrchestrationStatus_ORCHESTRATION_STATUS_COMPLETED} + s.instances[completed.id] = completed + started := proto.CloneOf(parent.pending[0]) + started.GetExecutionStarted().OrchestrationInstance.ExecutionId = wrapperspb.String("renewed-parent") + history := []*protos.HistoryEvent{ + started, + helpers.NewSubOrchestrationCreatedEvent(0, "child", nil, nil, completed.id, nil), + {EventType: &protos.HistoryEvent_SubOrchestrationInstanceCompleted{ + SubOrchestrationInstanceCompleted: &protos.SubOrchestrationInstanceCompletedEvent{TaskScheduledId: 0}, + }}, + helpers.NewSubOrchestrationCreatedEvent(1, "child", nil, nil, running.id, nil), + } + s.applyRewindLocked(parent, &protos.RewindOrchestrationAction{NewHistory: history}) + require.Equal(t, protos.OrchestrationStatus_ORCHESTRATION_STATUS_COMPLETED, completed.status) + require.Empty(t, completed.pending) + require.Equal(t, "renewed-parent", running.parent.GetOrchestrationInstance().GetExecutionId().GetValue()) + lease := s.orchLeases[runningItem.GetCompletionToken()] + require.NotEqual(t, "renewed-parent", dispatched[1].GetExecutionStarted().GetParentInstance().GetOrchestrationInstance().GetExecutionId().GetValue(), + "do not mutate the dispatched request") + require.Equal(t, "renewed-parent", lease.events[1].GetExecutionStarted().GetParentInstance().GetOrchestrationInstance().GetExecutionId().GetValue()) +} + +func finishTestRewind( + t *testing.T, + s *Server, + item *protos.WorkItem, + started *protos.HistoryEvent, + executionID string, + retained ...*protos.HistoryEvent, +) { + t.Helper() + started = proto.CloneOf(started) + started.GetExecutionStarted().OrchestrationInstance.ExecutionId = wrapperspb.String(executionID) + history := append([]*protos.HistoryEvent{started}, retained...) + history = append(history, item.GetOrchestratorRequest().GetNewEvents()...) + _, err := s.CompleteOrchestratorTask(context.Background(), &protos.OrchestratorResponse{ + CompletionToken: item.GetCompletionToken(), + Actions: []*protos.OrchestratorAction{{OrchestratorActionType: &protos.OrchestratorAction_RewindOrchestration{ + RewindOrchestration: &protos.RewindOrchestrationAction{NewHistory: history}, + }}}, + }) + require.NoError(t, err) +} + +func TestRewindDiscardsLifecycleRequestsFromFailedTurn(t *testing.T) { + ctx := context.Background() + for name, request := range map[string]func(s *Server, id string) error{ + "suspend": func(s *Server, id string) error { + _, err := s.SuspendInstance(ctx, &protos.SuspendRequest{InstanceId: id}) + return err + }, + "terminate": func(s *Server, id string) error { + _, err := s.TerminateInstance(ctx, &protos.TerminateRequest{InstanceId: id}) + return err + }, + } { + t.Run(name, func(t *testing.T) { + s := NewServer() + defer s.Close() + inst := s.newInstanceLocked("id", "orchestrator", nil, nil, nil, nil, nil, nil) + started := inst.pending[0] + item := s.nextWorkItemLocked(nil, 1, workItemLimits{}) + require.NoError(t, request(s, inst.id)) + require.NotEmpty(t, inst.pending) + _, err := s.CompleteOrchestratorTask(ctx, &protos.OrchestratorResponse{ + CompletionToken: item.GetCompletionToken(), + Actions: []*protos.OrchestratorAction{{OrchestratorActionType: &protos.OrchestratorAction_CompleteOrchestration{ + CompleteOrchestration: &protos.CompleteOrchestrationAction{ + OrchestrationStatus: protos.OrchestrationStatus_ORCHESTRATION_STATUS_FAILED, + FailureDetails: failureDetails("failure", "boom"), + }, + }}}, + }) + require.NoError(t, err) + require.Equal(t, protos.OrchestrationStatus_ORCHESTRATION_STATUS_FAILED, inst.status) + + _, err = s.RewindInstance(ctx, &protos.RewindInstanceRequest{InstanceId: inst.id}) + require.NoError(t, err) + item = s.nextWorkItemLocked(nil, 1, workItemLimits{}) + finishTestRewind(t, s, item, started, "renewed") + require.Equal(t, protos.OrchestrationStatus_ORCHESTRATION_STATUS_RUNNING, inst.status) + require.Len(t, inst.pending, 1, "a request superseded by failure must not reach the recovered worker") + require.NotNil(t, inst.pending[0].GetOrchestratorStarted()) + }) + } +} + +func TestRewindIsolatesInboxAcrossRedelivery(t *testing.T) { + s := NewServer() + defer s.Close() + inst := s.newInstanceLocked("id", "orchestrator", nil, nil, nil, nil, nil, nil) + started, oldExecutionID := inst.pending[0], inst.executionID + inst.history = []*protos.HistoryEvent{started} + s.completeLocked(inst, protos.OrchestrationStatus_ORCHESTRATION_STATUS_FAILED, nil, failureDetails("failure", "boom")) + for _, token := range []string{"before", "during"} { + s.actLeases[token] = &activityLease{item: &activityItem{ + inst: inst, executionID: oldExecutionID, request: &protos.ActivityRequest{TaskId: 99}, + }} + } + + _, err := s.RewindInstance(context.Background(), &protos.RewindInstanceRequest{InstanceId: inst.id}) + require.NoError(t, err) + _, err = s.RaiseEvent(context.Background(), &protos.RaiseEventRequest{InstanceId: inst.id, Name: "before"}) + require.NoError(t, err) + _, err = s.CompleteActivityTask(context.Background(), &protos.ActivityResponse{CompletionToken: "before"}) + require.NoError(t, err) + + limits := workItemLimits{orchestrations: 1} + item := s.nextWorkItemLocked(nil, 1, limits) + require.Len(t, item.GetOrchestratorRequest().GetNewEvents(), 2) + require.NotNil(t, item.GetOrchestratorRequest().NewEvents[0].GetOrchestratorStarted()) + require.NotNil(t, item.GetOrchestratorRequest().NewEvents[1].GetExecutionRewound()) + s.newInstanceLocked("other", "orchestrator", nil, nil, nil, nil, nil, nil) + require.Nil(t, s.nextWorkItemLocked(nil, 1, limits), "a rewind lease consumes stream capacity") + other := s.nextWorkItemLocked(nil, 2, limits) + require.Equal(t, "other", other.GetOrchestratorRequest().GetInstanceId()) + _, err = s.AbandonTaskOrchestratorWorkItem(context.Background(), &protos.AbandonOrchestrationTaskRequest{ + CompletionToken: item.GetCompletionToken(), + }) + require.NoError(t, err) + item = s.nextWorkItemLocked(nil, 1, limits) + require.Len(t, item.GetOrchestratorRequest().GetNewEvents(), 2) + require.NotNil(t, item.GetOrchestratorRequest().NewEvents[1].GetExecutionRewound()) + + _, err = s.RaiseEvent(context.Background(), &protos.RaiseEventRequest{InstanceId: inst.id, Name: "during"}) + require.NoError(t, err) + _, err = s.CompleteActivityTask(context.Background(), &protos.ActivityResponse{CompletionToken: "during"}) + require.NoError(t, err) + finishTestRewind(t, s, item, started, "renewed") + + require.Len(t, inst.pending, 3) + require.NotNil(t, inst.pending[0].GetOrchestratorStarted()) + require.Equal(t, "before", inst.pending[1].GetEventRaised().GetName()) + require.Equal(t, "during", inst.pending[2].GetEventRaised().GetName()) +} + +func TestRewindWorkItemStreamsLargeHistory(t *testing.T) { + s := NewServer() + defer s.Close() + inst := s.newInstanceLocked("id", "orchestrator", nil, nil, nil, nil, nil, nil) + inst.history = []*protos.HistoryEvent{inst.pending[0]} + data := wrapperspb.String(strings.Repeat("x", 1<<20)) + for range 5 { + inst.history = append(inst.history, &protos.HistoryEvent{EventType: &protos.HistoryEvent_GenericEvent{ + GenericEvent: &protos.GenericEvent{Data: data}, + }}) + } + s.completeLocked(inst, protos.OrchestrationStatus_ORCHESTRATION_STATUS_FAILED, nil, failureDetails("failure", "boom")) + + _, err := s.RewindInstance(context.Background(), &protos.RewindInstanceRequest{InstanceId: inst.id}) + require.NoError(t, err) + item := s.nextWorkItemLocked(nil, 1, workItemLimits{}) + request := item.GetOrchestratorRequest() + require.True(t, request.GetRequiresHistoryStreaming()) + require.Empty(t, request.GetPastEvents()) + require.Len(t, request.GetNewEvents(), 2) + require.NotNil(t, request.NewEvents[0].GetOrchestratorStarted()) + require.NotNil(t, request.NewEvents[1].GetExecutionRewound()) + require.Equal(t, inst.executionID, request.GetExecutionId().GetValue()) +} + +func TestRewindRejectsOversizedWorkItem(t *testing.T) { + ctx := context.Background() + s := NewServer() + defer s.Close() + inst := s.newInstanceLocked("id", "orchestrator", nil, nil, nil, nil, nil, nil) + inst.history = []*protos.HistoryEvent{inst.pending[0]} + s.completeLocked(inst, protos.OrchestrationStatus_ORCHESTRATION_STATUS_FAILED, nil, failureDetails("failure", "boom")) + history := append([]*protos.HistoryEvent(nil), inst.history...) + // The reason fits in a request but not in the work item that delivers it. + reason := wrapperspb.String(strings.Repeat("x", maxMessageSize-32)) + request := &protos.RewindInstanceRequest{InstanceId: inst.id, Reason: reason} + require.LessOrEqual(t, proto.Size(request), maxMessageSize) + + _, err := s.RewindInstance(ctx, request) + require.Equal(t, codes.InvalidArgument, status.Code(err)) + require.Equal(t, protos.OrchestrationStatus_ORCHESTRATION_STATUS_FAILED, inst.status) + require.Nil(t, inst.rewind) + + // A child's rewind carries its parent's reason, so leasing checks the size too. + s.prepareRewindLocked(inst, newRewindEvent(reason, nil)) + require.Nil(t, s.nextWorkItemLocked(nil, 1, workItemLimits{})) + require.Empty(t, s.orchLeases) + require.False(t, inst.queued) + require.Equal(t, protos.OrchestrationStatus_ORCHESTRATION_STATUS_FAILED, inst.status) + require.Equal(t, "OrchestrationWorkItemTooLarge", inst.failure.GetErrorType()) + require.Nil(t, inst.rewind) + require.Len(t, inst.history, len(history)) + require.Equal(t, history[:len(history)-1], inst.history[:len(history)-1], "only the failure is replaced") + + _, err = s.RewindInstance(ctx, &protos.RewindInstanceRequest{InstanceId: inst.id, Reason: wrapperspb.String("short")}) + require.NoError(t, err) + item := s.nextWorkItemLocked(nil, 1, workItemLimits{}) + require.Equal(t, "short", item.GetOrchestratorRequest().GetNewEvents()[1].GetExecutionRewound().GetReason().GetValue()) +} + +func TestRewindReconcilesRetainedActivities(t *testing.T) { + for _, mode := range []string{"before", "during", "in-flight", "queued", "missing"} { + t.Run(mode, func(t *testing.T) { + s := NewServer() + defer s.Close() + inst := s.newInstanceLocked("id", "orchestrator", nil, nil, nil, nil, nil, nil) + started, oldExecutionID := inst.pending[0], inst.executionID + scheduled := helpers.NewTaskScheduledEvent(3, "sibling", nil, wrapperspb.String(`"input"`), nil) + inst.history = []*protos.HistoryEvent{started, scheduled} + s.completeLocked(inst, protos.OrchestrationStatus_ORCHESTRATION_STATUS_FAILED, nil, failureDetails("failure", "boom")) + + request := &protos.ActivityRequest{ + Name: "sibling", TaskId: 3, Input: wrapperspb.String(`"input"`), + OrchestrationInstance: &protos.OrchestrationInstance{ + InstanceId: inst.id, ExecutionId: wrapperspb.String(oldExecutionID), + }, + } + activity := &activityItem{inst: inst, executionID: oldExecutionID, request: request} + switch mode { + case "queued": + s.actQueue = append(s.actQueue, activity) + case "missing": + default: + s.actLeases["activity"] = &activityLease{item: activity} + } + complete := func() { + t.Helper() + _, err := s.CompleteActivityTask(context.Background(), &protos.ActivityResponse{ + CompletionToken: "activity", Result: wrapperspb.String(`"kept"`), + }) + require.NoError(t, err) + } + if mode == "before" { + complete() + } + _, err := s.RewindInstance(context.Background(), &protos.RewindInstanceRequest{InstanceId: inst.id}) + require.NoError(t, err) + item := s.nextWorkItemLocked(nil, 1, workItemLimits{}) + require.Len(t, item.GetOrchestratorRequest().GetNewEvents(), 2) + if mode == "during" { + complete() + } + finishTestRewind(t, s, item, started, "renewed", scheduled) + + if mode == "in-flight" { + require.Equal(t, "renewed", activity.executionID) + require.Equal(t, oldExecutionID, request.GetOrchestrationInstance().GetExecutionId().GetValue()) + require.Equal(t, "renewed", activity.request.GetOrchestrationInstance().GetExecutionId().GetValue()) + complete() + } + switch mode { + case "queued", "missing": + require.Len(t, s.actQueue, 1) + require.Equal(t, "renewed", s.actQueue[0].executionID) + require.Equal(t, "sibling", s.actQueue[0].request.GetName()) + require.Equal(t, `"input"`, s.actQueue[0].request.GetInput().GetValue()) + require.Len(t, inst.pending, 1) + default: + require.Empty(t, s.actQueue) + require.Len(t, inst.pending, 2) + require.Equal(t, `"kept"`, inst.pending[1].GetTaskCompleted().GetResult().GetValue()) + } + }) + } +} + +func TestRewindRestoresOutstandingTimer(t *testing.T) { + s := NewServer() + defer s.Close() + inst := s.newInstanceLocked("id", "orchestrator", nil, nil, nil, nil, nil, nil) + started := inst.pending[0] + fireAt := timestamppb.New(time.Now().Add(-time.Second)) + timer := helpers.NewTimerCreatedEvent(4, fireAt) + inst.history = []*protos.HistoryEvent{started, timer, helpers.NewTaskFailedEvent(5, nil)} + s.completeLocked(inst, protos.OrchestrationStatus_ORCHESTRATION_STATUS_FAILED, nil, failureDetails("failure", "boom")) + + _, err := s.RewindInstance(context.Background(), &protos.RewindInstanceRequest{InstanceId: inst.id}) + require.NoError(t, err) + item := s.nextWorkItemLocked(nil, 1, workItemLimits{}) + finishTestRewind(t, s, item, started, "renewed", timer) + require.Eventually(t, func() bool { + s.mu.Lock() + defer s.mu.Unlock() + for _, event := range inst.pending { + if fired := event.GetTimerFired(); fired != nil { + return fired.GetTimerId() == 4 && proto.Equal(fired.GetFireAt(), fireAt) + } + } + return false + }, time.Second, time.Millisecond) +} + +func TestRewindRejectsUnrelatedChildIdentities(t *testing.T) { + for _, mismatch := range []string{"parent", "execution", "task"} { + t.Run(mismatch, func(t *testing.T) { + s := NewServer() + defer s.Close() + parent := s.newInstanceLocked("parent", "parent", nil, nil, nil, nil, nil, nil) + started := parent.pending[0] + created := helpers.NewSubOrchestrationCreatedEvent(7, "child", nil, nil, "child", nil) + parent.history = []*protos.HistoryEvent{started, created, { + EventType: &protos.HistoryEvent_SubOrchestrationInstanceFailed{ + SubOrchestrationInstanceFailed: &protos.SubOrchestrationInstanceFailedEvent{TaskScheduledId: 7}, + }, + }} + s.completeLocked(parent, protos.OrchestrationStatus_ORCHESTRATION_STATUS_FAILED, nil, failureDetails("failure", "boom")) + info := helpers.NewParentInfo(7, parent.name, parent.id) + info.OrchestrationInstance.ExecutionId = wrapperspb.String(parent.executionID) + switch mismatch { + case "parent": + info.OrchestrationInstance.InstanceId = "other" + case "execution": + info.OrchestrationInstance.ExecutionId = wrapperspb.String("other") + case "task": + info.TaskScheduledId = 8 + } + child := &instance{id: "child", parent: info, status: protos.OrchestrationStatus_ORCHESTRATION_STATUS_RUNNING} + s.instances[child.id] = child + + _, err := s.RewindInstance(context.Background(), &protos.RewindInstanceRequest{InstanceId: parent.id}) + require.Equal(t, codes.AlreadyExists, status.Code(err)) + require.Contains(t, status.Convert(err).Message(), "child") + require.Equal(t, protos.OrchestrationStatus_ORCHESTRATION_STATUS_FAILED, parent.status) + require.Nil(t, parent.rewind) + require.Same(t, child, s.instances[child.id]) + require.Same(t, info, child.parent) + }) + } +} + +func TestRewindReportsChildCollisionDuringRewrite(t *testing.T) { + s := NewServer() + defer s.Close() + parent := s.newInstanceLocked("parent", "parent", nil, nil, nil, nil, nil, nil) + started, oldExecutionID := parent.pending[0], parent.executionID + created := helpers.NewSubOrchestrationCreatedEvent(1, "child", nil, nil, "child", nil) + parent.history = []*protos.HistoryEvent{started, created, helpers.NewTaskFailedEvent(2, nil)} + s.completeLocked(parent, protos.OrchestrationStatus_ORCHESTRATION_STATUS_FAILED, nil, failureDetails("failure", "boom")) + + _, err := s.RewindInstance(context.Background(), &protos.RewindInstanceRequest{InstanceId: parent.id}) + require.NoError(t, err) + item := s.nextWorkItemLocked(nil, 1, workItemLimits{}) + unrelated := &instance{id: "child", status: protos.OrchestrationStatus_ORCHESTRATION_STATUS_RUNNING} + s.instances[unrelated.id] = unrelated + finishTestRewind(t, s, item, started, "discarded", created) + require.Equal(t, protos.OrchestrationStatus_ORCHESTRATION_STATUS_FAILED, parent.status) + require.Equal(t, oldExecutionID, parent.executionID) + require.Equal(t, "OrchestrationAlreadyExists", parent.failure.GetErrorType()) + require.Same(t, unrelated, s.instances[unrelated.id]) + require.Nil(t, unrelated.parent) + + delete(s.instances, unrelated.id) + _, err = s.RewindInstance(context.Background(), &protos.RewindInstanceRequest{InstanceId: parent.id}) + require.NoError(t, err) + item = s.nextWorkItemLocked(nil, 2, workItemLimits{}) + finishTestRewind(t, s, item, started, "renewed", created) + require.Equal(t, protos.OrchestrationStatus_ORCHESTRATION_STATUS_RUNNING, parent.status) + child := s.instances["child"] + require.NotNil(t, child) + require.Equal(t, "parent", child.parent.GetOrchestrationInstance().GetInstanceId()) + require.Equal(t, "renewed", child.parent.GetOrchestrationInstance().GetExecutionId().GetValue()) +} + +func TestRewindRestoresLateChildResults(t *testing.T) { + for _, state := range []protos.OrchestrationStatus{ + protos.OrchestrationStatus_ORCHESTRATION_STATUS_COMPLETED, + protos.OrchestrationStatus_ORCHESTRATION_STATUS_FAILED, + protos.OrchestrationStatus_ORCHESTRATION_STATUS_TERMINATED, + } { + t.Run(state.String(), func(t *testing.T) { + s := NewServer() + defer s.Close() + parent := s.newInstanceLocked("parent", "parent", nil, nil, nil, nil, nil, nil) + started := parent.pending[0] + created := helpers.NewSubOrchestrationCreatedEvent(0, "child", nil, nil, "child", nil) + parent.history = []*protos.HistoryEvent{started, created, helpers.NewTaskFailedEvent(1, nil)} + s.completeLocked(parent, protos.OrchestrationStatus_ORCHESTRATION_STATUS_FAILED, nil, failureDetails("failure", "boom")) + info := helpers.NewParentInfo(0, parent.name, parent.id) + info.OrchestrationInstance.ExecutionId = wrapperspb.String(parent.executionID) + child := &instance{ + id: "child", parent: info, status: state, completedAt: time.Now().Add(-time.Second), + output: wrapperspb.String(`"child result"`), + } + if state == protos.OrchestrationStatus_ORCHESTRATION_STATUS_FAILED { + child.failure = failureDetails("ChildFailed", "late failure") + } + s.instances[child.id] = child + + _, err := s.RewindInstance(context.Background(), &protos.RewindInstanceRequest{InstanceId: parent.id}) + require.NoError(t, err) + _, err = s.RaiseEvent(context.Background(), &protos.RaiseEventRequest{InstanceId: parent.id, Name: "later"}) + require.NoError(t, err) + item := s.nextWorkItemLocked(nil, 1, workItemLimits{}) + finishTestRewind(t, s, item, started, "renewed", created) + require.Len(t, parent.pending, 3) + if state == protos.OrchestrationStatus_ORCHESTRATION_STATUS_COMPLETED { + require.Equal(t, `"child result"`, parent.pending[1].GetSubOrchestrationInstanceCompleted().GetResult().GetValue()) + } else { + require.NotNil(t, parent.pending[1].GetSubOrchestrationInstanceFailed().GetFailureDetails()) + } + require.Equal(t, "later", parent.pending[2].GetEventRaised().GetName()) + require.Equal(t, state, child.status) + }) + } +} + +func TestRewindRetargetsLateFailedChild(t *testing.T) { + for _, mode := range []string{"buffered", "terminal-state"} { + t.Run(mode, func(t *testing.T) { + s := NewServer() + defer s.Close() + parent := s.newInstanceLocked("parent", "parent", nil, nil, nil, nil, nil, nil) + started := parent.pending[0] + created := helpers.NewSubOrchestrationCreatedEvent(0, "child", nil, nil, "child", nil) + parent.history = []*protos.HistoryEvent{started, created} + s.completeLocked(parent, protos.OrchestrationStatus_ORCHESTRATION_STATUS_FAILED, nil, failureDetails("failure", "parent")) + info := helpers.NewParentInfo(0, parent.name, parent.id) + info.OrchestrationInstance.ExecutionId = wrapperspb.String(parent.executionID) + child := s.newInstanceLocked("child", "child", nil, nil, nil, info, nil, nil) + child.history = []*protos.HistoryEvent{child.pending[0]} + s.completeLocked(child, protos.OrchestrationStatus_ORCHESTRATION_STATUS_FAILED, nil, failureDetails("failure", "child")) + if mode == "terminal-state" { + parent.pending = nil + parent.childResultSources = nil + } + + _, err := s.RewindInstance(context.Background(), &protos.RewindInstanceRequest{InstanceId: parent.id}) + require.NoError(t, err) + item := s.leaseOrchestrationLocked(parent, 1) + finishTestRewind(t, s, item, started, "new-parent", created) + require.Equal(t, "new-parent", child.parent.GetOrchestrationInstance().GetExecutionId().GetValue()) + require.Len(t, parent.pending, 2) + require.NotNil(t, parent.pending[1].GetSubOrchestrationInstanceFailed()) + + parent.history = append(parent.history, parent.pending[1]) + parent.pending = nil + s.completeLocked(parent, protos.OrchestrationStatus_ORCHESTRATION_STATUS_FAILED, nil, failureDetails("failure", "child")) + _, err = s.RewindInstance(context.Background(), &protos.RewindInstanceRequest{InstanceId: parent.id}) + require.NoError(t, err) + item = s.leaseOrchestrationLocked(parent, 1) + finishTestRewind(t, s, item, started, "new-parent-again", created) + require.Equal(t, "new-parent-again", child.rewind.GetExecutionRewound().GetParentExecutionId().GetValue()) + require.Equal(t, "new-parent-again", child.parent.GetOrchestrationInstance().GetExecutionId().GetValue()) + + // The renewed parent can fail again before the child's recovery is committed. + parent.pending = nil + s.completeLocked(parent, protos.OrchestrationStatus_ORCHESTRATION_STATUS_FAILED, nil, failureDetails("failure", "sibling")) + _, err = s.RewindInstance(context.Background(), &protos.RewindInstanceRequest{InstanceId: parent.id}) + require.NoError(t, err) + item = s.leaseOrchestrationLocked(parent, 1) + finishTestRewind(t, s, item, started, "new-parent-third", created) + require.Equal(t, "new-parent-third", child.parent.GetOrchestrationInstance().GetExecutionId().GetValue()) + require.Equal(t, "new-parent-third", child.rewind.GetExecutionRewound().GetParentExecutionId().GetValue()) + }) + } +} + +func TestRewindDoesNotRetargetReusedChildWithBufferedResult(t *testing.T) { + for _, mode := range []string{"unrelated", "new-execution"} { + t.Run(mode, func(t *testing.T) { + s := NewServer() + defer s.Close() + parent := s.newInstanceLocked("parent", "parent", nil, nil, nil, nil, nil, nil) + started := parent.pending[0] + created := helpers.NewSubOrchestrationCreatedEvent(0, "child", nil, nil, "child", nil) + parent.history = []*protos.HistoryEvent{started, created} + s.completeLocked(parent, protos.OrchestrationStatus_ORCHESTRATION_STATUS_FAILED, nil, failureDetails("failure", "parent")) + info := helpers.NewParentInfo(0, parent.name, parent.id) + info.OrchestrationInstance.ExecutionId = wrapperspb.String(parent.executionID) + child := s.newInstanceLocked("child", "child", nil, nil, nil, info, nil, nil) + s.completeLocked(child, protos.OrchestrationStatus_ORCHESTRATION_STATUS_COMPLETED, wrapperspb.String(`"done"`), nil) + s.purgeLocked(child, false) + var replacementParent *protos.ParentInstanceInfo + if mode == "new-execution" { + replacementParent = proto.CloneOf(info) + } + replacement := s.newInstanceLocked("child", "unrelated", nil, nil, nil, replacementParent, nil, nil) + replacementExecutionID := replacement.executionID + parentExecutionID := replacement.parent.GetOrchestrationInstance().GetExecutionId().GetValue() + + _, err := s.RewindInstance(context.Background(), &protos.RewindInstanceRequest{InstanceId: parent.id}) + require.NoError(t, err) + item := s.leaseOrchestrationLocked(parent, 1) + finishTestRewind(t, s, item, started, "new-parent", created) + require.Same(t, replacement, s.instances["child"]) + require.Equal(t, replacementExecutionID, replacement.executionID) + require.Equal(t, parentExecutionID, replacement.parent.GetOrchestrationInstance().GetExecutionId().GetValue()) + require.Len(t, parent.pending, 2) + require.Equal(t, `"done"`, parent.pending[1].GetSubOrchestrationInstanceCompleted().GetResult().GetValue()) + }) + } +} + +func TestRewindPreservesBufferedResultAfterChildPurge(t *testing.T) { + for _, phase := range []string{"failed", "rewriting"} { + t.Run(phase, func(t *testing.T) { + s := NewServer() + defer s.Close() + parent := s.newInstanceLocked("parent", "parent", nil, nil, nil, nil, nil, nil) + started := parent.pending[0] + created := helpers.NewSubOrchestrationCreatedEvent(0, "child", nil, nil, "child", nil) + parent.history = []*protos.HistoryEvent{started, created, helpers.NewTaskFailedEvent(1, nil)} + s.completeLocked(parent, protos.OrchestrationStatus_ORCHESTRATION_STATUS_FAILED, nil, failureDetails("failure", "boom")) + info := helpers.NewParentInfo(0, parent.name, parent.id) + info.OrchestrationInstance.ExecutionId = wrapperspb.String(parent.executionID) + child := s.newInstanceLocked("child", "child", nil, nil, nil, info, nil, nil) + + var item *protos.WorkItem + if phase == "rewriting" { + _, err := s.RewindInstance(context.Background(), &protos.RewindInstanceRequest{InstanceId: parent.id}) + require.NoError(t, err) + item = s.leaseOrchestrationLocked(parent, 1) + } + s.completeLocked(child, protos.OrchestrationStatus_ORCHESTRATION_STATUS_COMPLETED, wrapperspb.String(`"done"`), nil) + s.purgeLocked(child, false) + if phase == "failed" { + _, err := s.RewindInstance(context.Background(), &protos.RewindInstanceRequest{InstanceId: parent.id}) + require.NoError(t, err) + item = s.leaseOrchestrationLocked(parent, 1) + } + finishTestRewind(t, s, item, started, "renewed", created) + require.NotContains(t, s.instances, "child") + require.Len(t, parent.pending, 2) + require.Equal(t, `"done"`, parent.pending[1].GetSubOrchestrationInstanceCompleted().GetResult().GetValue()) + }) + } +} + +func TestRewindPrefersRecoveredChildResultAfterPurge(t *testing.T) { + s := NewServer() + defer s.Close() + parent := s.newInstanceLocked("parent", "parent", nil, nil, nil, nil, nil, nil) + started := parent.pending[0] + created := helpers.NewSubOrchestrationCreatedEvent(0, "child", nil, nil, "child", nil) + parent.history = []*protos.HistoryEvent{started, created, helpers.NewTaskFailedEvent(1, nil)} + s.completeLocked(parent, protos.OrchestrationStatus_ORCHESTRATION_STATUS_FAILED, nil, failureDetails("failure", "boom")) + info := helpers.NewParentInfo(0, parent.name, parent.id) + info.OrchestrationInstance.ExecutionId = wrapperspb.String(parent.executionID) + child := s.newInstanceLocked("child", "child", nil, nil, nil, info, nil, nil) + childStart := child.pending[0] + child.history = []*protos.HistoryEvent{childStart} + s.completeLocked(child, protos.OrchestrationStatus_ORCHESTRATION_STATUS_FAILED, nil, failureDetails("failure", "child")) + + _, err := s.RewindInstance(context.Background(), &protos.RewindInstanceRequest{InstanceId: child.id}) + require.NoError(t, err) + childItem := s.leaseOrchestrationLocked(child, 1) + finishTestRewind(t, s, childItem, childStart, "recovered-child") + s.completeLocked(child, protos.OrchestrationStatus_ORCHESTRATION_STATUS_COMPLETED, wrapperspb.String(`"done"`), nil) + s.purgeLocked(child, false) + + _, err = s.RewindInstance(context.Background(), &protos.RewindInstanceRequest{InstanceId: parent.id}) + require.NoError(t, err) + parentItem := s.leaseOrchestrationLocked(parent, 1) + finishTestRewind(t, s, parentItem, started, "renewed", created) + require.Len(t, parent.pending, 2) + require.Equal(t, `"done"`, parent.pending[1].GetSubOrchestrationInstanceCompleted().GetResult().GetValue()) +} + +func TestRewindRetargetsChildAlreadyRewriting(t *testing.T) { + s := NewServer() + defer s.Close() + parent := s.newInstanceLocked("parent", "parent", nil, nil, nil, nil, nil, nil) + parentStart := parent.pending[0] + created := helpers.NewSubOrchestrationCreatedEvent(0, "child", nil, nil, "child", nil) + parent.history = []*protos.HistoryEvent{parentStart, created, helpers.NewTaskFailedEvent(1, nil)} + s.completeLocked(parent, protos.OrchestrationStatus_ORCHESTRATION_STATUS_FAILED, nil, failureDetails("failure", "boom")) + info := helpers.NewParentInfo(0, parent.name, parent.id) + info.OrchestrationInstance.ExecutionId = wrapperspb.String(parent.executionID) + child := s.newInstanceLocked("child", "child", nil, nil, nil, info, nil, nil) + childStart := child.pending[0] + child.history = []*protos.HistoryEvent{childStart} + s.completeLocked(child, protos.OrchestrationStatus_ORCHESTRATION_STATUS_FAILED, nil, failureDetails("failure", "boom")) + + _, err := s.RewindInstance(context.Background(), &protos.RewindInstanceRequest{InstanceId: child.id}) + require.NoError(t, err) + childItem := s.leaseOrchestrationLocked(child, 1) + _, err = s.RewindInstance(context.Background(), &protos.RewindInstanceRequest{InstanceId: parent.id}) + require.NoError(t, err) + parentItem := s.leaseOrchestrationLocked(parent, 1) + finishTestRewind(t, s, parentItem, parentStart, "new-parent", created) + finishTestRewind(t, s, childItem, childStart, "new-child") + require.Equal(t, "new-parent", child.parent.GetOrchestrationInstance().GetExecutionId().GetValue()) + require.Equal(t, "new-parent", child.history[0].GetExecutionStarted().GetParentInstance().GetOrchestrationInstance().GetExecutionId().GetValue()) + + s.completeLocked(child, protos.OrchestrationStatus_ORCHESTRATION_STATUS_COMPLETED, wrapperspb.String(`"done"`), nil) + require.Len(t, parent.pending, 2) + require.Equal(t, `"done"`, parent.pending[1].GetSubOrchestrationInstanceCompleted().GetResult().GetValue()) +} + func TestCompleteOrchestratorTaskSplitsByProcessedEvents(t *testing.T) { s := NewServer() defer s.Close()