From 25adda8b9497ea0ef9f18c71d7d7b7bb3c23e05c Mon Sep 17 00:00:00 2001 From: Andy Staples Date: Fri, 20 Nov 2026 11:22:22 -0700 Subject: [PATCH 1/8] Support rewind in the in-memory test backend Recover failed activities and sub-orchestrations using worker replacement history, including purged child recreation. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- CHANGELOG.md | 2 +- README.md | 6 +- durabletasktest/host.go | 9 +- durabletasktest/host_test.go | 184 ++++++++++++++++++++++++++++++++- internal/inmemory/rewind.go | 132 +++++++++++++++++++++++ internal/inmemory/server.go | 3 +- internal/inmemory/work.go | 18 ++++ internal/inmemory/work_test.go | 110 ++++++++++++++++++++ 8 files changed, 455 insertions(+), 9 deletions(-) create mode 100644 internal/inmemory/rewind.go diff --git a/CHANGELOG.md b/CHANGELOG.md index c1d52751..61d4bb52 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. +- 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; purged children are recreated without their previous history. Durable entities are not supported. - 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 a148d3b2..0506ffb4 100644 --- a/README.md +++ b/README.md @@ -659,12 +659,14 @@ 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. Purged children are recreated from their recorded inputs without their previous history. The same worker [history-safety limitations](./durabletaskscheduler/README.md#rewind) apply. The in-memory service has these limits: - Timers fire in real time. Use short durations in tests. -- 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. +- Durable entities aren't supported. Entity client calls return `api.ErrFeatureNotSupported`. An orchestration that calls, signals, or locks an entity fails. - State is kept in memory only. It is discarded when the host closes. ## Development diff --git a/durabletasktest/host.go b/durabletasktest/host.go index a0b69f2e..b6213434 100644 --- a/durabletasktest/host.go +++ b/durabletasktest/host.go @@ -19,9 +19,12 @@ // dependencies, register stub activities in the test's registry. // // Timers fire in real time, so tests should use short timer durations. -// 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; purged children are recreated without their previous history. +// 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 7b080583..6f1914da 100644 --- a/durabletasktest/host_test.go +++ b/durabletasktest/host_test.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "sync/atomic" "testing" "time" @@ -375,5 +376,186 @@ 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.True(t, completed.CompletedAt.After(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 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) { + 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) + })) + host := durabletasktest.New(t, r) + ctx := testContext(t) + failed := run(t, host, "Unsafe") + 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) + require.Contains(t, rejected.FailureDetails.ErrorMessage, "Go SDK cannot safely rewind this history") + require.Equal(t, failed.ExecutionID, rejected.ExecutionID) + require.EqualValues(t, 3, calls.Load()) } diff --git a/internal/inmemory/rewind.go b/internal/inmemory/rewind.go new file mode 100644 index 00000000..af5d65f8 --- /dev/null +++ b/internal/inmemory/rewind.go @@ -0,0 +1,132 @@ +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) + } + s.prepareRewindLocked(inst, req.GetReason(), nil) + return &protos.RewindInstanceResponse{}, nil +} + +func (s *Server) prepareRewindLocked(inst *instance, reason, parentExecutionID *wrapperspb.StringValue) { + inst.stopTimers() + inst.status = protos.OrchestrationStatus_ORCHESTRATION_STATUS_RUNNING + inst.output = nil + inst.failure = nil + inst.completedAt = time.Time{} + inst.updatedAt = time.Now() + inst.pending = []*protos.HistoryEvent{{ + EventId: -1, + Timestamp: timestamppb.Now(), + EventType: &protos.HistoryEvent_ExecutionRewound{ExecutionRewound: &protos.ExecutionRewoundEvent{ + Reason: reason, ParentExecutionId: parentExecutionID, + }}, + }} + s.enqueueLocked(inst) +} + +func validateRewindHistory(history []*protos.HistoryEvent) 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++ + if started.GetOrchestrationInstance().GetExecutionId().GetValue() == "" { + return status.Error(codes.InvalidArgument, "rewind history requires an execution ID") + } + } + } + if starts != 1 { + return status.Error(codes.InvalidArgument, "rewind history requires exactly one execution start") + } + return nil +} + +// The worker owns history selection. Persist its replacement without adding +// markers, then wake normal replay and recover unfinished children. +func (s *Server) applyRewindLocked(inst *instance, action *protos.RewindOrchestrationAction) { + inst.history = slices.Clone(action.GetNewHistory()) + var reason *wrapperspb.StringValue + completed := make(map[int32]bool) + for _, event := range inst.history { + if started := event.GetExecutionStarted(); started != nil { + inst.executionID = started.GetOrchestrationInstance().GetExecutionId().GetValue() + inst.parent = started.GetParentInstance() + } + if rewound := event.GetExecutionRewound(); rewound != nil { + reason = rewound.GetReason() + } + if child := event.GetSubOrchestrationInstanceCompleted(); child != nil { + completed[child.GetTaskScheduledId()] = true + } + } + for _, event := range inst.history { + created := event.GetSubOrchestrationInstanceCreated() + if created == nil || completed[event.GetEventId()] { + continue + } + 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()] + switch { + case !ok: + child = s.newInstanceLocked(created.GetInstanceId(), created.GetName(), created.GetVersion(), + created.GetInput(), created.GetTags(), parent, created.GetParentTraceContext(), nil) + if !slices.Contains(inst.children, child.id) { + inst.children = append(inst.children, child.id) + } + case child.status == protos.OrchestrationStatus_ORCHESTRATION_STATUS_FAILED: + s.prepareRewindLocked(child, reason, wrapperspb.String(inst.executionID)) + default: + // An unfinished child may still be running. Its completion must + // target the renewed parent, including on subsequent replay. + child.parent = parent + updateParent := func(events []*protos.HistoryEvent) { + for i, childEvent := range events { + if childEvent.GetExecutionStarted() != nil { + cloned := proto.CloneOf(childEvent) + 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) + } + } + } + } + inst.pending = append([]*protos.HistoryEvent{helpers.NewOrchestratorStartedEvent()}, inst.pending...) +} diff --git a/internal/inmemory/server.go b/internal/inmemory/server.go index 1f7e26ab..be821204 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 ( diff --git a/internal/inmemory/work.go b/internal/inmemory/work.go index fd3f5cca..cb18ec61 100644 --- a/internal/inmemory/work.go +++ b/internal/inmemory/work.go @@ -226,6 +226,18 @@ 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 err := validateRewindHistory(replacement.GetNewHistory()); err != nil { + return nil, err + } + rewind = replacement + } + } delete(s.orchLeases, token) inst.leased = false if s.instances[inst.id] != inst || isTerminal(inst.status) { @@ -245,6 +257,12 @@ func (s *Server) CompleteOrchestratorTask(_ context.Context, resp *protos.Orches inst.customStatus = resp.GetCustomStatus() inst.updatedAt = time.Now() + if rewind != nil { + s.applyRewindLocked(inst, rewind) + s.enqueueLocked(inst) + s.notifyLocked() + return &protos.CompleteTaskResponse{}, nil + } s.applyActionsLocked(inst, resp.GetActions()) s.enqueueLocked(inst) s.notifyLocked() diff --git a/internal/inmemory/work_test.go b/internal/inmemory/work_test.go index 72a4864d..d28acb0e 100644 --- a/internal/inmemory/work_test.go +++ b/internal/inmemory/work_test.go @@ -1,10 +1,16 @@ package inmemory import ( + "context" "testing" + "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/types/known/wrapperspb" "github.com/microsoft/durabletask-go/internal/helpers" "github.com/microsoft/durabletask-go/internal/protos" @@ -30,3 +36,107 @@ func TestContinueAsNewDropsPreviousExecutionResults(t *testing.T) { assert.Same(t, carryover, inst.pending[1]) 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) + 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()) + + 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") + 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()) +} From bc42ac78ebd7c3255c28a1bdec00d69c3d3bab7b Mon Sep 17 00:00:00 2001 From: Andy Staples Date: Mon, 23 Nov 2026 12:44:31 -0700 Subject: [PATCH 2/8] Handle concurrent work during rewind Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- CHANGELOG.md | 2 +- README.md | 2 +- durabletasktest/host.go | 5 +- durabletasktest/host_test.go | 189 +++++++++++++++++ internal/inmemory/rewind.go | 374 ++++++++++++++++++++++++++++---- internal/inmemory/server.go | 21 +- internal/inmemory/work.go | 175 +++++++++++---- internal/inmemory/work_test.go | 377 +++++++++++++++++++++++++++++++++ 8 files changed, 1051 insertions(+), 94 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 61d4bb52..573547e3 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, rewind, queries, purge, and history. Rewind preserves successful work and recursively recovers failed children, subject to the worker's history-safety limitations; purged children are recreated without their previous history. Durable entities are not supported. +- 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. - 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 0506ffb4..89025ab3 100644 --- a/README.md +++ b/README.md @@ -661,7 +661,7 @@ 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, 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. Purged children are recreated from their recorded inputs without their previous history. The same worker [history-safety limitations](./durabletaskscheduler/README.md#rewind) apply. +`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: diff --git a/durabletasktest/host.go b/durabletasktest/host.go index b6213434..125b06a1 100644 --- a/durabletasktest/host.go +++ b/durabletasktest/host.go @@ -21,7 +21,10 @@ // Timers fire in real time, so tests should use short timer durations. // Failed orchestrations can be rewound with the same history-safety limitations // as the production worker. Rewind enqueues recovery and preserves successful -// work; purged children are recreated without their previous history. +// 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. diff --git a/durabletasktest/host_test.go b/durabletasktest/host_test.go index 6f1914da..1a8aa14e 100644 --- a/durabletasktest/host_test.go +++ b/durabletasktest/host_test.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "sync" "sync/atomic" "testing" "time" @@ -500,6 +501,194 @@ func TestRewindRecovery(t *testing.T) { } } +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) { diff --git a/internal/inmemory/rewind.go b/internal/inmemory/rewind.go index af5d65f8..de3f96b8 100644 --- a/internal/inmemory/rewind.go +++ b/internal/inmemory/rewind.go @@ -29,6 +29,9 @@ func (s *Server) RewindInstance(_ context.Context, req *protos.RewindInstanceReq return nil, grpcerrors.New(codes.FailedPrecondition, fmt.Sprintf("orchestration instance %q is not in a failed state", inst.id), grpcerrors.ReasonInvalidState) } + if err := s.validateRewindChildrenLocked(inst, inst.history, make(map[*instance]bool)); err != nil { + return nil, err + } s.prepareRewindLocked(inst, req.GetReason(), nil) return &protos.RewindInstanceResponse{}, nil } @@ -40,17 +43,17 @@ func (s *Server) prepareRewindLocked(inst *instance, reason, parentExecutionID * inst.failure = nil inst.completedAt = time.Time{} inst.updatedAt = time.Now() - inst.pending = []*protos.HistoryEvent{{ + inst.rewind = &protos.HistoryEvent{ EventId: -1, Timestamp: timestamppb.Now(), EventType: &protos.HistoryEvent_ExecutionRewound{ExecutionRewound: &protos.ExecutionRewoundEvent{ Reason: reason, ParentExecutionId: parentExecutionID, }}, - }} + } s.enqueueLocked(inst) } -func validateRewindHistory(history []*protos.HistoryEvent) error { +func validateRewindHistory(history []*protos.HistoryEvent, oldExecutionID string) error { starts := 0 for _, event := range history { if event.GetExecutionCompleted() != nil { @@ -58,8 +61,14 @@ func validateRewindHistory(history []*protos.HistoryEvent) error { } if started := event.GetExecutionStarted(); started != nil { starts++ - if started.GetOrchestrationInstance().GetExecutionId().GetValue() == "" { - return status.Error(codes.InvalidArgument, "rewind history requires an execution ID") + 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") } } } @@ -69,29 +78,178 @@ func validateRewindHistory(history []*protos.HistoryEvent) error { return nil } -// The worker owns history selection. Persist its replacement without adding -// markers, then wake normal replay and recover unfinished children. +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 { + parent := child.parent.GetOrchestrationInstance() + if parent.GetInstanceId() == inst.id && parent.GetExecutionId().GetValue() == inst.executionID && + child.parent.GetTaskScheduledId() == 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 + } + parent := child.parent.GetOrchestrationInstance() + if parent.GetInstanceId() != inst.id || + parent.GetExecutionId().GetValue() != inst.executionID || + child.parent.GetTaskScheduledId() != 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 (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) failRewindLocked(inst *instance, err error) { + 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) + } + for i := len(inst.history) - 1; i >= 0; i-- { + if inst.history[i].GetExecutionCompleted() != nil { + inst.history = inst.history[:i] + break + } + } + inst.rewind = nil + errorType := "InvalidRewindState" + if status.Code(err) == codes.AlreadyExists { + errorType = "OrchestrationAlreadyExists" + } + s.failLocked(inst, 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) { - inst.history = slices.Clone(action.GetNewHistory()) + oldExecutionID := inst.executionID + failed := failedSubOrchestrations(inst.history) + childResults := s.pendingRewindChildResults(inst, action.GetNewHistory(), failed) + s.applyRewindIdentityLocked(inst, action.GetNewHistory()) var reason *wrapperspb.StringValue - completed := make(map[int32]bool) for _, event := range inst.history { - if started := event.GetExecutionStarted(); started != nil { - inst.executionID = started.GetOrchestrationInstance().GetExecutionId().GetValue() - inst.parent = started.GetParentInstance() - } if rewound := event.GetExecutionRewound(); rewound != nil { reason = rewound.GetReason() } - if child := event.GetSubOrchestrationInstanceCompleted(); child != nil { - completed[child.GetTaskScheduledId()] = true - } } - for _, event := range inst.history { - created := event.GetSubOrchestrationInstanceCreated() - if created == nil || completed[event.GetEventId()] { + inst.rewind = nil + s.reconcileRewindTasksLocked(inst, oldExecutionID, childResults) + + for _, event := range unfinishedSubOrchestrations(inst.history) { + if childResults[event.GetEventId()] != nil { continue } + created := event.GetSubOrchestrationInstanceCreated() parent := helpers.NewParentInfo(event.GetEventId(), inst.name, inst.id) parent.Version = inst.version parent.OrchestrationInstance.ExecutionId = wrapperspb.String(inst.executionID) @@ -100,33 +258,165 @@ func (s *Server) applyRewindLocked(inst *instance, action *protos.RewindOrchestr case !ok: child = s.newInstanceLocked(created.GetInstanceId(), created.GetName(), created.GetVersion(), created.GetInput(), created.GetTags(), parent, created.GetParentTraceContext(), nil) - if !slices.Contains(inst.children, child.id) { - inst.children = append(inst.children, child.id) - } - case child.status == protos.OrchestrationStatus_ORCHESTRATION_STATUS_FAILED: + case child.status == protos.OrchestrationStatus_ORCHESTRATION_STATUS_FAILED && failed[event.GetEventId()]: s.prepareRewindLocked(child, reason, wrapperspb.String(inst.executionID)) - default: - // An unfinished child may still be running. Its completion must - // target the renewed parent, including on subsequent replay. - child.parent = parent - updateParent := func(events []*protos.HistoryEvent) { - for i, childEvent := range events { - if childEvent.GetExecutionStarted() != nil { - cloned := proto.CloneOf(childEvent) - 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) + case isTerminal(child.status): + 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 be821204..ea596a19 100644 --- a/internal/inmemory/server.go +++ b/internal/inmemory/server.go @@ -67,8 +67,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 leased bool queued bool @@ -82,10 +84,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 { @@ -247,7 +255,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 cb18ec61..51610007 100644 --- a/internal/inmemory/work.go +++ b/internal/inmemory/work.go @@ -8,6 +8,7 @@ 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" @@ -63,7 +64,8 @@ func (s *Server) nextWorkItemLocked(filters *protos.WorkItemFilters, streamID ui } 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) } @@ -85,14 +87,20 @@ func (s *Server) nextWorkItemLocked(filters *protos.WorkItemFilters, streamID ui } func (s *Server) leaseOrchestrationLocked(inst *instance, streamID uint64) *protos.WorkItem { - events := inst.pending - inst.pending = nil - if events[0].GetOrchestratorStarted() == nil { - events = append([]*protos.HistoryEvent{helpers.NewOrchestratorStartedEvent()}, events...) + rewinding := inst.rewind != nil + var events []*protos.HistoryEvent + if rewinding { + events = []*protos.HistoryEvent{helpers.NewOrchestratorStartedEvent(), proto.CloneOf(inst.rewind)} + } else { + events = inst.pending + inst.pending = nil + if events[0].GetOrchestratorStarted() == nil { + events = append([]*protos.HistoryEvent{helpers.NewOrchestratorStartedEvent()}, events...) + } } inst.leased = true token := newID() - s.orchLeases[token] = &orchestrationLease{inst: inst, events: events, streamID: streamID} + s.orchLeases[token] = &orchestrationLease{inst: inst, events: events, streamID: streamID, rewinding: rewinding} return &protos.WorkItem{ Request: &protos.WorkItem_OrchestratorRequest{OrchestratorRequest: &protos.OrchestratorRequest{ InstanceId: inst.id, @@ -153,7 +161,9 @@ func (s *Server) abandonOrchestrationLocked(token string, lease *orchestrationLe if s.instances[inst.id] != inst || isTerminal(inst.status) { return } - inst.pending = append(lease.events, inst.pending...) + if !lease.rewinding { + inst.pending = append(lease.events, inst.pending...) + } s.enqueueLocked(inst) } @@ -204,10 +214,16 @@ func (s *Server) CompleteActivityTask(_ context.Context, resp *protos.ActivityRe return &protos.CompleteTaskResponse{}, nil } taskID := item.request.GetTaskId() + var event *protos.HistoryEvent 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) } return &protos.CompleteTaskResponse{}, nil } @@ -232,18 +248,44 @@ func (s *Server) CompleteOrchestratorTask(_ context.Context, resp *protos.Orches if len(resp.GetActions()) != 1 { return nil, status.Error(codes.InvalidArgument, "rewind must be the only orchestration action") } - if err := validateRewindHistory(replacement.GetNewHistory()); err != nil { + 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) { 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, err) + } else { + s.applyRewindLocked(inst, rewind) + s.enqueueLocked(inst) + s.notifyLocked() + } + return &protos.CompleteTaskResponse{}, nil + } + if lease.rewinding { + inst.rewind = nil + } + processed := lease.events if n := resp.GetNumEventsProcessed(); n != nil && int(n.GetValue()) < len(processed) { // Events that the orchestrator did not process go back to the inbox. @@ -251,18 +293,12 @@ func (s *Server) CompleteOrchestratorTask(_ context.Context, resp *protos.Orches processed = processed[:n.GetValue()] } inst.history = append(inst.history, processed...) + for _, event := range processed { + delete(inst.childResultSources, event) + } if inst.status == protos.OrchestrationStatus_ORCHESTRATION_STATUS_PENDING { inst.status = protos.OrchestrationStatus_ORCHESTRATION_STATUS_RUNNING } - inst.customStatus = resp.GetCustomStatus() - inst.updatedAt = time.Now() - - if rewind != nil { - s.applyRewindLocked(inst, rewind) - s.enqueueLocked(inst) - s.notifyLocked() - return &protos.CompleteTaskResponse{}, nil - } s.applyActionsLocked(inst, resp.GetActions()) s.enqueueLocked(inst) s.notifyLocked() @@ -297,22 +333,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)) @@ -353,14 +374,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(), @@ -410,11 +454,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(), @@ -437,7 +486,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 { + inst.pending = slices.DeleteFunc(inst.pending, func(event *protos.HistoryEvent) bool { + switch event.GetEventType().(type) { + case *protos.HistoryEvent_EventRaised, + *protos.HistoryEvent_ExecutionSuspended, + *protos.HistoryEvent_ExecutionResumed, + *protos.HistoryEvent_ExecutionTerminated, + *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), @@ -451,22 +521,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{ @@ -475,5 +564,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 d28acb0e..3474fb47 100644 --- a/internal/inmemory/work_test.go +++ b/internal/inmemory/work_test.go @@ -10,6 +10,7 @@ import ( "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" @@ -61,6 +62,11 @@ func TestRewindReplacementAndStaleActivity(t *testing.T) { 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{ @@ -70,6 +76,9 @@ func TestRewindReplacementAndStaleActivity(t *testing.T) { _, 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]} @@ -140,3 +149,371 @@ func TestRewindPreservesSuccessfulChildAndRetargetsRunningChild(t *testing.T) { "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 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) + + item := s.nextWorkItemLocked(nil, 1) + require.Len(t, item.GetOrchestratorRequest().GetNewEvents(), 2) + require.NotNil(t, item.GetOrchestratorRequest().NewEvents[0].GetOrchestratorStarted()) + require.NotNil(t, item.GetOrchestratorRequest().NewEvents[1].GetExecutionRewound()) + _, err = s.AbandonTaskOrchestratorWorkItem(context.Background(), &protos.AbandonOrchestrationTaskRequest{ + CompletionToken: item.GetCompletionToken(), + }) + require.NoError(t, err) + item = s.nextWorkItemLocked(nil, 2) + 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 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) + 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) + 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) + 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) + 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) + 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 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()) +} From 78ca5528aa2aebe02d87b77e5279214b517fcb7b Mon Sep 17 00:00:00 2001 From: Andy Staples Date: Mon, 23 Nov 2026 13:08:56 -0700 Subject: [PATCH 3/8] Preserve child ownership during rewind recovery Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- durabletasktest/host_test.go | 76 +++++++++++++++++++++------------- internal/inmemory/rewind.go | 35 +++++++++++----- internal/inmemory/work.go | 1 + internal/inmemory/work_test.go | 76 ++++++++++++++++++++++++++++++++++ 4 files changed, 148 insertions(+), 40 deletions(-) diff --git a/durabletasktest/host_test.go b/durabletasktest/host_test.go index c9908811..775144cf 100644 --- a/durabletasktest/host_test.go +++ b/durabletasktest/host_test.go @@ -863,35 +863,53 @@ func TestRewindInvalidState(t *testing.T) { } func TestRewindRejectsUnsafeHistory(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) + 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 + })) } - 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()) + }) } - 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) - })) - host := durabletasktest.New(t, r) - ctx := testContext(t) - failed := run(t, host, "Unsafe") - 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) - require.Contains(t, rejected.FailureDetails.ErrorMessage, "Go SDK cannot safely rewind this history") - require.Equal(t, failed.ExecutionID, rejected.ExecutionID) - require.EqualValues(t, 3, calls.Load()) } diff --git a/internal/inmemory/rewind.go b/internal/inmemory/rewind.go index de3f96b8..0b18b046 100644 --- a/internal/inmemory/rewind.go +++ b/internal/inmemory/rewind.go @@ -134,9 +134,7 @@ func (s *Server) pendingRewindChildResults( continue } if child, ok := s.instances[source.instanceID]; ok && failedResult { - parent := child.parent.GetOrchestrationInstance() - if parent.GetInstanceId() == inst.id && parent.GetExecutionId().GetValue() == inst.executionID && - child.parent.GetTaskScheduledId() == id && + if childMatchesParent(child, inst, inst.executionID, id) && (child.executionID != source.executionID || !isTerminal(child.status) || child.status == protos.OrchestrationStatus_ORCHESTRATION_STATUS_COMPLETED) { continue @@ -167,10 +165,7 @@ func (s *Server) validateRewindChildrenLocked(inst *instance, history []*protos. if !ok { continue } - parent := child.parent.GetOrchestrationInstance() - if parent.GetInstanceId() != inst.id || - parent.GetExecutionId().GetValue() != inst.executionID || - child.parent.GetTaskScheduledId() != event.GetEventId() { + 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) @@ -184,6 +179,13 @@ func (s *Server) validateRewindChildrenLocked(inst *instance, history []*protos. 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() @@ -206,7 +208,7 @@ func (s *Server) applyRewindIdentityLocked(inst *instance, history []*protos.His } } -func (s *Server) failRewindLocked(inst *instance, err error) { +func (s *Server) retargetRewindParentLocked(inst *instance) { parentExecutionID := inst.rewind.GetExecutionRewound().GetParentExecutionId() if parentExecutionID.GetValue() != "" && inst.parent != nil { parent := proto.CloneOf(inst.parent) @@ -216,6 +218,10 @@ func (s *Server) failRewindLocked(inst *instance, err error) { parent.OrchestrationInstance.ExecutionId = proto.CloneOf(parentExecutionID) s.retargetChildLocked(inst, parent) } +} + +func (s *Server) failRewindLocked(inst *instance, err error) { + s.retargetRewindParentLocked(inst) for i := len(inst.history) - 1; i >= 0; i-- { if inst.history[i].GetExecutionCompleted() != nil { inst.history = inst.history[:i] @@ -246,14 +252,20 @@ func (s *Server) applyRewindLocked(inst *instance, action *protos.RewindOrchestr s.reconcileRewindTasksLocked(inst, oldExecutionID, childResults) for _, event := range unfinishedSubOrchestrations(inst.history) { - if childResults[event.GetEventId()] != nil { - continue - } 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(), @@ -261,6 +273,7 @@ func (s *Server) applyRewindLocked(inst *instance, action *protos.RewindOrchestr case child.status == protos.OrchestrationStatus_ORCHESTRATION_STATUS_FAILED && failed[event.GetEventId()]: s.prepareRewindLocked(child, reason, wrapperspb.String(inst.executionID)) case isTerminal(child.status): + s.retargetChildLocked(child, parent) result := subOrchestrationResultEvent(child) inst.recordChildResult(result, child) index := len(inst.pending) diff --git a/internal/inmemory/work.go b/internal/inmemory/work.go index 6ef94608..3cf13d77 100644 --- a/internal/inmemory/work.go +++ b/internal/inmemory/work.go @@ -356,6 +356,7 @@ func (s *Server) CompleteOrchestratorTask(_ context.Context, resp *protos.Orches return &protos.CompleteTaskResponse{}, nil } if lease.rewinding { + s.retargetRewindParentLocked(inst) inst.rewind = nil } diff --git a/internal/inmemory/work_test.go b/internal/inmemory/work_test.go index f42dda61..6ef8b722 100644 --- a/internal/inmemory/work_test.go +++ b/internal/inmemory/work_test.go @@ -453,6 +453,82 @@ func TestRewindRestoresLateChildResults(t *testing.T) { } } +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()) + }) + } +} + +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) { From 42f1f814f0ce642c48f0fbb590cb9d46304a7852 Mon Sep 17 00:00:00 2001 From: Andy Staples Date: Mon, 23 Nov 2026 13:19:46 -0700 Subject: [PATCH 4/8] Allow equal rewind completion timestamps Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- durabletasktest/host_test.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/durabletasktest/host_test.go b/durabletasktest/host_test.go index 775144cf..57315622 100644 --- a/durabletasktest/host_test.go +++ b/durabletasktest/host_test.go @@ -612,7 +612,9 @@ func TestRewindRecovery(t *testing.T) { require.NoError(t, completed.ReadOutput(&output)) require.Equal(t, want, output) require.Nil(t, completed.FailureDetails) - require.True(t, completed.CompletedAt.After(failed.CompletedAt)) + 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. From 89120d10a86424a3636efccdccbf971a1ece30d2 Mon Sep 17 00:00:00 2001 From: Andy Staples Date: Mon, 23 Nov 2026 13:43:50 -0700 Subject: [PATCH 5/8] Retarget failed children before enqueueing recursive rewind A child prepared for recursive rewind kept its old parent execution until its replacement history was committed. If the renewed parent failed again first, a later rewind rejected the still-owned child as AlreadyExists. Retarget the child's parent metadata immediately, as the other existing-child branches do. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- internal/inmemory/rewind.go | 3 +++ internal/inmemory/work_test.go | 11 +++++++++++ 2 files changed, 14 insertions(+) diff --git a/internal/inmemory/rewind.go b/internal/inmemory/rewind.go index 0b18b046..969f811e 100644 --- a/internal/inmemory/rewind.go +++ b/internal/inmemory/rewind.go @@ -271,6 +271,9 @@ func (s *Server) applyRewindLocked(inst *instance, action *protos.RewindOrchestr 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, reason, wrapperspb.String(inst.executionID)) case isTerminal(child.status): s.retargetChildLocked(child, parent) diff --git a/internal/inmemory/work_test.go b/internal/inmemory/work_test.go index 6ef8b722..b54a62dc 100644 --- a/internal/inmemory/work_test.go +++ b/internal/inmemory/work_test.go @@ -489,6 +489,17 @@ func TestRewindRetargetsLateFailedChild(t *testing.T) { 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()) }) } } From bf0802754ba3c8b21124f8a87792ac15e32f133f Mon Sep 17 00:00:00 2001 From: Andy Staples Date: Mon, 23 Nov 2026 13:45:00 -0700 Subject: [PATCH 6/8] Discard lifecycle requests superseded by failure Suspend, resume, and terminate requests that arrived while a failing turn was leased stayed in the failed instance's inbox. Rewind resets the status to running, so recovery replay could suspend the worker while the service reported running (and ResumeInstance could not release it), or immediately terminate the recovered instance. A failure supersedes these requests, as DTS drops messages to completed instances, so do not retain them for rewind. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- internal/inmemory/work.go | 6 ++--- internal/inmemory/work_test.go | 43 ++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 3 deletions(-) diff --git a/internal/inmemory/work.go b/internal/inmemory/work.go index 3cf13d77..a0aa5cdc 100644 --- a/internal/inmemory/work.go +++ b/internal/inmemory/work.go @@ -588,12 +588,12 @@ func (s *Server) completeLocked( inst.updatedAt = now 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_ExecutionSuspended, - *protos.HistoryEvent_ExecutionResumed, - *protos.HistoryEvent_ExecutionTerminated, *protos.HistoryEvent_TaskCompleted, *protos.HistoryEvent_TaskFailed, *protos.HistoryEvent_TimerFired, diff --git a/internal/inmemory/work_test.go b/internal/inmemory/work_test.go index b54a62dc..e5e63e41 100644 --- a/internal/inmemory/work_test.go +++ b/internal/inmemory/work_test.go @@ -173,6 +173,49 @@ func finishTestRewind( 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() From e4c9e66d796ac7b6ed1ea8c92b81fd87374ec408 Mon Sep 17 00:00:00 2001 From: Andy Staples Date: Mon, 23 Nov 2026 16:59:22 -0700 Subject: [PATCH 7/8] Keep history rewindable when the worker rejects a rewind A rewind work item completed with a failure instead of a replacement used to commit its OrchestratorStarted and ExecutionRewound markers after the original failure, so a later rewind was rejected as unsafe. End the attempt through failRewindLocked instead: replace only the terminal failure with the worker's failure details and notify the renewed parent. Failed rewinds no longer add an extra OrchestratorCompleted marker. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- durabletasktest/host_test.go | 75 ++++++++++++++++++++++++++++++++++++ internal/inmemory/rewind.go | 12 ++++-- internal/inmemory/work.go | 8 ++-- 3 files changed, 89 insertions(+), 6 deletions(-) diff --git a/durabletasktest/host_test.go b/durabletasktest/host_test.go index f46b53bc..8afaca6e 100644 --- a/durabletasktest/host_test.go +++ b/durabletasktest/host_test.go @@ -946,3 +946,78 @@ func TestRewindRejectsUnsafeHistory(t *testing.T) { }) } } + +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) + }) + } +} diff --git a/internal/inmemory/rewind.go b/internal/inmemory/rewind.go index 969f811e..af308d79 100644 --- a/internal/inmemory/rewind.go +++ b/internal/inmemory/rewind.go @@ -220,7 +220,10 @@ func (s *Server) retargetRewindParentLocked(inst *instance) { } } -func (s *Server) failRewindLocked(inst *instance, err error) { +// 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 { @@ -228,12 +231,15 @@ func (s *Server) failRewindLocked(inst *instance, err error) { break } } - inst.rewind = nil + 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" } - s.failLocked(inst, failureDetails(errorType, "%s", status.Convert(err).Message())) + return failureDetails(errorType, "%s", status.Convert(err).Message()) } // Persist the worker's replacement, then reconcile retained work before replay. diff --git a/internal/inmemory/work.go b/internal/inmemory/work.go index 948a2c80..1311bf5c 100644 --- a/internal/inmemory/work.go +++ b/internal/inmemory/work.go @@ -401,7 +401,7 @@ func (s *Server) CompleteOrchestratorTask(_ context.Context, resp *protos.Orches inst.updatedAt = time.Now() if rewind != nil { if err := s.validateRewindChildrenLocked(inst, rewind.GetNewHistory(), make(map[*instance]bool)); err != nil { - s.failRewindLocked(inst, err) + s.failRewindLocked(inst, rewindValidationFailure(err)) } else { s.applyRewindLocked(inst, rewind) s.enqueueLocked(inst) @@ -410,8 +410,10 @@ func (s *Server) CompleteOrchestratorTask(_ context.Context, resp *protos.Orches return &protos.CompleteTaskResponse{}, nil } if lease.rewinding { - s.retargetRewindParentLocked(inst) - inst.rewind = nil + // 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 From 1c76918c7002537542e1beed140755b5cf2c1db4 Mon Sep 17 00:00:00 2001 From: Andy Staples Date: Mon, 23 Nov 2026 16:59:39 -0700 Subject: [PATCH 8/8] Reject rewinds whose work item exceeds the message limit A long rewind reason could make the rewind work item exceed the in-memory backend's gRPC message limit even with streamed history. The worker rejected it, and stream cleanup requeued the same rewind indefinitely. RewindInstance now rejects such a reason with InvalidArgument, and leasing fails an oversized rewind (such as a child carrying its parent's reason) through failRewindLocked instead of delivering it. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- internal/inmemory/rewind.go | 44 ++++++++++++++++++++++++++-------- internal/inmemory/work.go | 13 +++++++++- internal/inmemory/work_test.go | 32 +++++++++++++++++++++++++ 3 files changed, 78 insertions(+), 11 deletions(-) diff --git a/internal/inmemory/rewind.go b/internal/inmemory/rewind.go index af308d79..48c21aa2 100644 --- a/internal/inmemory/rewind.go +++ b/internal/inmemory/rewind.go @@ -29,27 +29,51 @@ func (s *Server) RewindInstance(_ context.Context, req *protos.RewindInstanceReq 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) + 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, req.GetReason(), nil) + s.prepareRewindLocked(inst, rewind) return &protos.RewindInstanceResponse{}, nil } -func (s *Server) prepareRewindLocked(inst *instance, reason, parentExecutionID *wrapperspb.StringValue) { - 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 = &protos.HistoryEvent{ +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) } @@ -280,7 +304,7 @@ func (s *Server) applyRewindLocked(inst *instance, action *protos.RewindOrchestr // 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, reason, wrapperspb.String(inst.executionID)) + s.prepareRewindLocked(child, newRewindEvent(reason, wrapperspb.String(inst.executionID))) case isTerminal(child.status): s.retargetChildLocked(child, parent) result := subOrchestrationResultEvent(child) diff --git a/internal/inmemory/work.go b/internal/inmemory/work.go index 1311bf5c..5f6f0f54 100644 --- a/internal/inmemory/work.go +++ b/internal/inmemory/work.go @@ -136,7 +136,7 @@ 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 { rewinding := inst.rewind != nil var events []*protos.HistoryEvent @@ -165,6 +165,17 @@ func (s *Server) leaseOrchestrationLocked(inst *instance, streamID uint64) *prot request.PastEvents = nil request.RequiresHistoryStreaming = true } + 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. diff --git a/internal/inmemory/work_test.go b/internal/inmemory/work_test.go index 476e27d0..83628d86 100644 --- a/internal/inmemory/work_test.go +++ b/internal/inmemory/work_test.go @@ -290,6 +290,38 @@ func TestRewindWorkItemStreamsLargeHistory(t *testing.T) { 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...) + reason := wrapperspb.String(strings.Repeat("x", maxOrchestrationWorkItemSize)) + + _, err := s.RewindInstance(ctx, &protos.RewindInstanceRequest{InstanceId: inst.id, Reason: reason}) + 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) {