From 64832f0dce0d17038b7f37a6a8f183a1c5b9ccd7 Mon Sep 17 00:00:00 2001 From: Andy Staples Date: Fri, 20 Nov 2026 11:37:31 -0700 Subject: [PATCH 01/12] Add durable entity support to the in-memory test backend Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- CHANGELOG.md | 2 +- README.md | 5 +- durabletasktest/entity_test.go | 364 +++++++++++++++++++++ durabletasktest/host.go | 10 +- durabletasktest/host_test.go | 17 - internal/inmemory/entity.go | 541 +++++++++++++++++++++++++++++++ internal/inmemory/entity_test.go | 97 ++++++ internal/inmemory/server.go | 13 +- internal/inmemory/work.go | 33 +- 9 files changed, 1050 insertions(+), 32 deletions(-) create mode 100644 durabletasktest/entity_test.go create mode 100644 internal/inmemory/entity.go create mode 100644 internal/inmemory/entity_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 573547e3..8bfc01b5 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; 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 the `durabletasktest` package, which runs orchestrations, activities, and entities 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, history, and durable entities, including scheduled signals, entity critical sections, and entity query and cleanup. 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. - 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 41eecb08..fc4cc2d0 100644 --- a/README.md +++ b/README.md @@ -640,7 +640,7 @@ For more information, read the [export history guide](./exporthistory/README.md) ## Testing orchestrations -The `durabletasktest` package runs your orchestrations and activities in your test process. It starts an in-memory Durable Task service, a worker for your registry, and a connected client. The parts talk over an in-memory gRPC transport, so the test needs no emulator, network port, or Azure resource. The worker, executor, and client are the same code that runs against DTS. +The `durabletasktest` package runs your orchestrations, activities, and entities in your test process. It starts an in-memory Durable Task service, a worker for your registry, and a connected client. The parts talk over an in-memory gRPC transport, so the test needs no emulator, network port, or Azure resource. The worker, executor, and client are the same code that runs against DTS. ```go func TestGreeting(t *testing.T) { @@ -659,7 +659,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. +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. Register entities in the same registry to test entity calls, signals, and critical sections. You can use the client to signal, get, query, and clean entities. `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. @@ -668,7 +668,6 @@ The in-memory service has these limits: - Timers use the Go runtime clock. With Go 1.25 or later, `testing/synctest` can advance timers without waiting in real time while the test goroutines are blocked. The `durabletasktest` tests include a 24-hour timer example. -- Durable entities 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/entity_test.go b/durabletasktest/entity_test.go new file mode 100644 index 00000000..b892f427 --- /dev/null +++ b/durabletasktest/entity_test.go @@ -0,0 +1,364 @@ +package durabletasktest_test + +import ( + "errors" + "sync/atomic" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/microsoft/durabletask-go/api" + "github.com/microsoft/durabletask-go/durabletasktest" + "github.com/microsoft/durabletask-go/task" +) + +// counter is an entity that holds an integer. +func counter(ctx *task.EntityContext) (any, error) { + var value int + if ctx.HasState() { + if err := ctx.GetState(&value); err != nil { + return nil, err + } + } + switch ctx.Operation { + case "add": + var amount int + if err := ctx.GetInput(&amount); err != nil { + return nil, err + } + value += amount + return value, ctx.SetState(value) + case "get": + return value, nil + case "fail": + return nil, errors.New("counter failed") + case "delete": + ctx.DeleteState() + return nil, nil + case "forward": + var target string + if err := ctx.GetInput(&target); err != nil { + return nil, err + } + return nil, ctx.SignalEntity(api.NewEntityID("counter", target), "add", value) + case "start": + var instanceID string + if err := ctx.GetInput(&instanceID); err != nil { + return nil, err + } + return nil, ctx.StartNewOrchestration("Echo", + task.WithEntityStartOrchestrationInstanceID(instanceID), + task.WithEntityStartOrchestrationInput(value)) + } + return nil, errors.New("unknown operation " + ctx.Operation) +} + +func newEntityHost(t *testing.T, register func(*task.TaskRegistry)) *durabletasktest.Host { + t.Helper() + r := task.NewTaskRegistry() + require.NoError(t, r.AddEntityN("counter", counter)) + if register != nil { + register(r) + } + return durabletasktest.New(t, r) +} + +// counterValue returns the counter's value, or -1 if the entity doesn't exist. +func counterValue(t *testing.T, host *durabletasktest.Host, key string) int { + t.Helper() + metadata, err := host.Client().GetEntity(testContext(t), api.NewEntityID("counter", key)) + require.NoError(t, err) + if metadata == nil { + return -1 + } + var value int + require.NoError(t, metadata.ReadState(&value)) + return value +} + +func waitForCounter(t *testing.T, host *durabletasktest.Host, key string, want int) { + t.Helper() + require.Eventually(t, func() bool { return counterValue(t, host, key) == want }, + 10*time.Second, 10*time.Millisecond, "counter %q never reached %d", key, want) +} + +func TestEntityClientSignals(t *testing.T) { + host := newEntityHost(t, nil) + c := host.Client() + ctx := testContext(t) + id := api.NewEntityID("counter", "a") + + metadata, err := c.GetEntity(ctx, id) + require.NoError(t, err) + assert.Nil(t, metadata) + + require.NoError(t, c.SignalEntity(ctx, id, "add", api.WithSignalInput(2))) + require.NoError(t, c.SignalEntity(ctx, id, "add", api.WithSignalInput(3))) + waitForCounter(t, host, "a", 5) + + metadata, err = c.GetEntity(ctx, id, api.GetEntityOptions{ExcludeState: true}) + require.NoError(t, err) + require.NotNil(t, metadata) + assert.Equal(t, id, metadata.InstanceID) + assert.False(t, metadata.StateIncluded) + assert.Empty(t, metadata.LockedBy) + + err = c.SignalEntity(ctx, id, "") + assert.ErrorIs(t, err, api.ErrInvalidArgument) +} + +func TestEntityScheduledSignal(t *testing.T) { + host := newEntityHost(t, nil) + ctx := testContext(t) + + start := time.Now() + require.NoError(t, host.Client().SignalEntity(ctx, api.NewEntityID("counter", "later"), "add", + api.WithSignalInput(1), api.WithSignalScheduledTime(start.Add(300*time.Millisecond)))) + assert.Equal(t, -1, counterValue(t, host, "later")) + waitForCounter(t, host, "later", 1) + assert.GreaterOrEqual(t, time.Since(start), 300*time.Millisecond) +} + +func TestOrchestrationCallsAndSignalsEntities(t *testing.T) { + host := newEntityHost(t, func(r *task.TaskRegistry) { + require.NoError(t, r.AddOrchestratorN("UseCounter", func(ctx *task.OrchestrationContext) (any, error) { + id := api.NewEntityID("counter", "orch") + if err := ctx.SignalEntity(id, "add", task.WithSignalEntityInput(10)); err != nil { + return nil, err + } + var value int + if err := ctx.CallEntity(id, "add", task.WithEntityInput(5)).Await(&value); err != nil { + return nil, err + } + return value, nil + })) + }) + + metadata := run(t, host, "UseCounter") + require.Equal(t, api.RUNTIME_STATUS_COMPLETED, metadata.RuntimeStatus) + assert.Equal(t, "15", metadata.SerializedOutput) + assert.Equal(t, 15, counterValue(t, host, "orch")) +} + +func TestEntityOperationFailure(t *testing.T) { + host := newEntityHost(t, func(r *task.TaskRegistry) { + require.NoError(t, r.AddOrchestratorN("CallFails", func(ctx *task.OrchestrationContext) (any, error) { + err := ctx.CallEntity(api.NewEntityID("counter", "f"), "fail").Await(nil) + var failed *task.EntityOperationFailedError + if !errors.As(err, &failed) { + return nil, errors.New("expected an entity operation failure") + } + return failed.FailureDetails.ErrorMessage, nil + })) + }) + + metadata := run(t, host, "CallFails") + require.Equal(t, api.RUNTIME_STATUS_COMPLETED, metadata.RuntimeStatus) + assert.Equal(t, `"counter failed"`, metadata.SerializedOutput) +} + +func TestEntityActions(t *testing.T) { + host := newEntityHost(t, func(r *task.TaskRegistry) { + require.NoError(t, r.AddOrchestratorN("Echo", func(ctx *task.OrchestrationContext) (any, error) { + var input int + err := ctx.GetInput(&input) + return input, err + })) + }) + c := host.Client() + ctx := testContext(t) + source := api.NewEntityID("counter", "source") + + require.NoError(t, c.SignalEntity(ctx, source, "add", api.WithSignalInput(7))) + require.NoError(t, c.SignalEntity(ctx, source, "forward", api.WithSignalInput("target"))) + waitForCounter(t, host, "target", 7) + + require.NoError(t, c.SignalEntity(ctx, source, "start", api.WithSignalInput("started-by-entity"))) + require.Eventually(t, func() bool { + _, err := c.FetchOrchestrationMetadata(ctx, "started-by-entity") + return err == nil + }, 10*time.Second, 10*time.Millisecond) + metadata, err := c.WaitForOrchestrationCompletion(ctx, "started-by-entity") + require.NoError(t, err) + assert.Equal(t, "7", metadata.SerializedOutput) +} + +func TestEntityCriticalSection(t *testing.T) { + a, b := api.NewEntityID("counter", "a"), api.NewEntityID("counter", "b") + host := newEntityHost(t, func(r *task.TaskRegistry) { + require.NoError(t, r.AddOrchestratorN("Transfer", func(ctx *task.OrchestrationContext) (any, error) { + unlock, err := ctx.LockEntities(b, a) + if err != nil { + return nil, err + } + defer unlock() + if err := ctx.CallEntity(a, "add", task.WithEntityInput(1)).Await(nil); err != nil { + return nil, err + } + if err := ctx.CallEntity(b, "add", task.WithEntityInput(1)).Await(nil); err != nil { + return nil, err + } + if err := ctx.WaitForSingleEvent("Continue", time.Minute).Await(nil); err != nil { + return nil, err + } + return nil, ctx.CallEntity(a, "add", task.WithEntityInput(10)).Await(nil) + })) + }) + c := host.Client() + ctx := testContext(t) + + id, err := c.ScheduleNewOrchestration(ctx, "Transfer") + require.NoError(t, err) + waitForCounter(t, host, "b", 1) + + // A signal from outside the critical section waits until the lock is released. + require.NoError(t, c.SignalEntity(ctx, a, "add", api.WithSignalInput(100))) + time.Sleep(200 * time.Millisecond) + metadata, err := c.GetEntity(ctx, a) + require.NoError(t, err) + require.NotNil(t, metadata) + assert.Equal(t, string(id), metadata.LockedBy) + assert.Equal(t, int32(1), metadata.BacklogQueueSize) + assert.Equal(t, 1, counterValue(t, host, "a")) + + require.NoError(t, c.RaiseEvent(ctx, id, "Continue")) + orchestration, err := c.WaitForOrchestrationCompletion(ctx, id) + require.NoError(t, err) + require.Equal(t, api.RUNTIME_STATUS_COMPLETED, orchestration.RuntimeStatus) + waitForCounter(t, host, "a", 111) + metadata, err = c.GetEntity(ctx, a) + require.NoError(t, err) + assert.Empty(t, metadata.LockedBy) + assert.Equal(t, 1, counterValue(t, host, "b")) +} + +func TestQueryEntities(t *testing.T) { + host := newEntityHost(t, nil) + c := host.Client() + ctx := testContext(t) + keys := []string{"q1", "q2", "q3", "q4", "q5"} + for _, key := range keys { + require.NoError(t, c.SignalEntity(ctx, api.NewEntityID("counter", key), "add", api.WithSignalInput(1))) + } + for _, key := range keys { + waitForCounter(t, host, key, 1) + } + + var ids []api.EntityID + query := api.EntityQuery{InstanceIDStartsWith: "counter@q", PageSize: 2} + for pages := 0; ; pages++ { + require.Less(t, pages, len(keys)) + results, err := c.QueryEntities(ctx, query) + require.NoError(t, err) + for _, metadata := range results.Entities { + ids = append(ids, metadata.InstanceID) + var value int + require.NoError(t, metadata.ReadState(&value)) + assert.Equal(t, 1, value) + } + if results.ContinuationToken == "" { + break + } + query.ContinuationToken = results.ContinuationToken + } + var want []api.EntityID + for _, key := range keys { + want = append(want, api.NewEntityID("counter", key)) + } + assert.Equal(t, want, ids) + + results, err := c.QueryEntities(ctx, api.EntityQuery{ + InstanceIDStartsWith: "counter", + LastModifiedFrom: time.Now().Add(time.Hour), + }) + require.NoError(t, err) + assert.Empty(t, results.Entities) +} + +func TestCleanEntityStorage(t *testing.T) { + locked := api.NewEntityID("counter", "locked") + host := newEntityHost(t, func(r *task.TaskRegistry) { + require.NoError(t, r.AddOrchestratorN("HoldLock", func(ctx *task.OrchestrationContext) (any, error) { + if _, err := ctx.LockEntities(locked); err != nil { + return nil, err + } + return nil, ctx.WaitForSingleEvent("Release", time.Minute).Await(nil) + })) + }) + c := host.Client() + ctx := testContext(t) + + // Deleting an entity's state leaves an empty entity that cleanup removes. + empty := api.NewEntityID("counter", "empty") + require.NoError(t, c.SignalEntity(ctx, empty, "add", api.WithSignalInput(1))) + waitForCounter(t, host, "empty", 1) + require.NoError(t, c.SignalEntity(ctx, empty, "delete")) + waitForCounter(t, host, "empty", -1) + results, err := c.QueryEntities(ctx, api.EntityQuery{InstanceIDStartsWith: "counter@empty", IncludeTransient: true}) + require.NoError(t, err) + require.Len(t, results.Entities, 1) + assert.False(t, results.Entities[0].HasState) + + // An orchestration terminated while waiting for a lock releases it once the lock is granted. + lockedBy := func(owner api.InstanceID) func() bool { + return func() bool { + results, err := c.QueryEntities(ctx, api.EntityQuery{InstanceIDStartsWith: "counter@locked", IncludeTransient: true}) + return err == nil && len(results.Entities) == 1 && results.Entities[0].LockedBy == string(owner) + } + } + holder, err := c.ScheduleNewOrchestration(ctx, "HoldLock") + require.NoError(t, err) + require.Eventually(t, lockedBy(holder), 10*time.Second, 10*time.Millisecond) + waiter, err := c.ScheduleNewOrchestration(ctx, "HoldLock") + require.NoError(t, err) + require.Eventually(t, func() bool { + metadata, err := c.FetchOrchestrationMetadata(ctx, waiter) + return err == nil && metadata.RuntimeStatus == api.RUNTIME_STATUS_RUNNING + }, 10*time.Second, 10*time.Millisecond) + require.NoError(t, c.TerminateOrchestration(ctx, waiter)) + _, err = c.WaitForOrchestrationCompletion(ctx, waiter) + require.NoError(t, err) + require.NoError(t, c.RaiseEvent(ctx, holder, "Release")) + _, err = c.WaitForOrchestrationCompletion(ctx, holder) + require.NoError(t, err) + require.Eventually(t, lockedBy(""), 10*time.Second, 10*time.Millisecond) + result, err := c.CleanEntityStorage(ctx) + require.NoError(t, err) + assert.Zero(t, result.OrphanedLocksReleased) + assert.Equal(t, int32(2), result.EmptyEntitiesRemoved) + results, err = c.QueryEntities(ctx, api.EntityQuery{InstanceIDStartsWith: "counter", IncludeTransient: true}) + require.NoError(t, err) + assert.Empty(t, results.Entities) +} + +func TestRewindKeepsEntityResults(t *testing.T) { + var repaired atomic.Bool + host := newEntityHost(t, func(r *task.TaskRegistry) { + require.NoError(t, r.AddActivityN("Flaky", func(task.ActivityContext) (any, error) { + if !repaired.Load() { + return nil, errors.New("dependency unavailable") + } + return nil, nil + })) + require.NoError(t, r.AddOrchestratorN("CallThenFail", func(ctx *task.OrchestrationContext) (any, error) { + var value int + if err := ctx.CallEntity(api.NewEntityID("counter", "rewind"), "add", task.WithEntityInput(1)).Await(&value); err != nil { + return nil, err + } + return value, ctx.CallActivity("Flaky").Await(nil) + })) + }) + ctx := testContext(t) + + failed := run(t, host, "CallThenFail") + require.Equal(t, api.RUNTIME_STATUS_FAILED, failed.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) + assert.Equal(t, "1", completed.SerializedOutput) + assert.Equal(t, 1, counterValue(t, host, "rewind")) +} diff --git a/durabletasktest/host.go b/durabletasktest/host.go index 4e0ce4f2..48f768e9 100644 --- a/durabletasktest/host.go +++ b/durabletasktest/host.go @@ -1,7 +1,7 @@ -// Package durabletasktest runs orchestrations and activities in process for tests. +// Package durabletasktest runs orchestrations, activities, and entities in process for tests. // // A [Host] starts an in-memory Durable Task service, a worker for the -// orchestrators and activities in a [task.TaskRegistry], and a client +// orchestrators, activities, and entities in a [task.TaskRegistry], and a client // connected to the same service. Communication uses an in-memory gRPC // transport, so no network ports or external services are required. // @@ -26,9 +26,9 @@ // 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. +// Durable entities are supported, including entity critical sections: +// signals and calls to a locked entity from outside its critical section wait +// until the lock is released. package durabletasktest import ( diff --git a/durabletasktest/host_test.go b/durabletasktest/host_test.go index 57315622..f9f07910 100644 --- a/durabletasktest/host_test.go +++ b/durabletasktest/host_test.go @@ -509,23 +509,6 @@ func TestInstanceManagement(t *testing.T) { assert.True(t, result.IsComplete) } -func TestUnsupportedFeatures(t *testing.T) { - r := task.NewTaskRegistry() - require.NoError(t, r.AddOrchestratorN("CallsEntity", func(ctx *task.OrchestrationContext) (any, error) { - return nil, ctx.CallEntity(api.NewEntityID("counter", "a"), "add").Await(nil) - })) - host := durabletasktest.New(t, r) - ctx := testContext(t) - - metadata := run(t, host, "CallsEntity") - require.Equal(t, api.RUNTIME_STATUS_FAILED, metadata.RuntimeStatus) - require.NotNil(t, metadata.FailureDetails) - assert.Contains(t, metadata.FailureDetails.ErrorMessage, "not supported") - - err := host.Client().SignalEntity(ctx, api.NewEntityID("counter", "a"), "add") - assert.ErrorIs(t, err, api.ErrFeatureNotSupported) -} - func TestRewindRecovery(t *testing.T) { for _, mode := range []string{"activity", "child", "purged-child", "nested-child"} { t.Run(mode, func(t *testing.T) { diff --git a/internal/inmemory/entity.go b/internal/inmemory/entity.go new file mode 100644 index 00000000..33ecfedd --- /dev/null +++ b/internal/inmemory/entity.go @@ -0,0 +1,541 @@ +package inmemory + +import ( + "cmp" + "context" + "slices" + "strconv" + "strings" + "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/helpers" + "github.com/microsoft/durabletask-go/internal/protos" +) + +// entity is the stored state of a durable entity. +// +// Messages are processed in arrival order. Lock requests and unlocks are +// handled by the service; signals and calls are dispatched to a worker in +// batches. While an entity is locked by a critical section, only calls from +// the lock owner and the owner's unlock are processed; other messages wait. +type entity struct { + id string + name string + state *wrapperspb.StringValue + lastModified time.Time + queue []*protos.HistoryEvent + lock *entityLock + leased bool + queued bool +} + +type entityLock struct { + criticalSectionID string + ownerInstanceID string +} + +type entityLease struct { + entity *entity + events []*protos.HistoryEvent + streamID uint64 +} + +// normalizeEntityID validates an "@name@key" entity instance ID and lowercases its name. +func normalizeEntityID(id string) (string, string, bool) { + name, key, err := helpers.ParseEntityInstanceID(id) + if err != nil { + return "", "", false + } + return "@" + name + "@" + key, name, true +} + +func invalidEntityIDError(id string) error { + return status.Errorf(codes.InvalidArgument, "invalid entity instance ID %q", id) +} + +func (s *Server) getOrCreateEntityLocked(id, name string) *entity { + if e, ok := s.entities[id]; ok { + return e + } + e := &entity{id: id, name: name, lastModified: time.Now()} + s.entities[id] = e + return e +} + +// deliverEntityLocked adds a message to an entity's queue, creating the entity if needed. +func (s *Server) deliverEntityLocked(targetID string, event *protos.HistoryEvent) { + id, name, ok := normalizeEntityID(targetID) + if !ok { + return + } + e := s.getOrCreateEntityLocked(id, name) + e.queue = append(e.queue, event) + s.pumpEntityLocked(e) +} + +// signalEntityLocked delivers a signal now or, if it is scheduled for later, when it is due. +func (s *Server) signalEntityLocked(targetID string, signal *protos.EntityOperationSignaledEvent) { + event := &protos.HistoryEvent{ + EventId: -1, + Timestamp: timestamppb.Now(), + EventType: &protos.HistoryEvent_EntityOperationSignaled{EntityOperationSignaled: signal}, + } + if at := signal.GetScheduledTime(); at != nil && at.AsTime().After(time.Now()) { + s.startServerTimerLocked(at.AsTime(), func() { s.deliverEntityLocked(targetID, event) }) + return + } + s.deliverEntityLocked(targetID, event) +} + +// startServerTimerLocked runs fn under the server lock at the given time, unless +// the server has been closed. +func (s *Server) startServerTimerLocked(at time.Time, fn func()) { + var timer *time.Timer + timer = time.AfterFunc(time.Until(at), func() { + s.mu.Lock() + defer s.mu.Unlock() + s.timers = slices.DeleteFunc(s.timers, func(t *time.Timer) bool { return t == timer }) + if s.closed { + return + } + fn() + s.notifyLocked() + }) + s.timers = append(s.timers, timer) +} + +// nextMessage returns the index of the next message the entity can +// process, or -1 if none can be processed now. +func (e *entity) nextMessage() int { + if e.lock == nil { + if len(e.queue) == 0 { + return -1 + } + return 0 + } + return slices.IndexFunc(e.queue, func(event *protos.HistoryEvent) bool { + if called := event.GetEntityOperationCalled(); called != nil { + return called.GetParentInstanceId().GetValue() == e.lock.ownerInstanceID + } + if unlock := event.GetEntityUnlockSent(); unlock != nil { + return unlock.GetCriticalSectionId() == e.lock.criticalSectionID + } + return false + }) +} + +func isEntityControlMessage(event *protos.HistoryEvent) bool { + return event.GetEntityLockRequested() != nil || event.GetEntityUnlockSent() != nil +} + +// pumpEntityLocked processes lock and unlock messages that are ready and queues +// the entity for dispatch if a signal or call is ready. +func (s *Server) pumpEntityLocked(e *entity) { + if e.leased || s.entities[e.id] != e { + return + } + for { + i := e.nextMessage() + if i < 0 { + return + } + event := e.queue[i] + if !isEntityControlMessage(event) { + break + } + e.queue = slices.Delete(e.queue, i, i+1) + s.processEntityControlMessageLocked(e, event) + } + if !e.queued { + e.queued = true + s.entityQueue = append(s.entityQueue, e) + } + s.notifyLocked() +} + +func (s *Server) processEntityControlMessageLocked(e *entity, event *protos.HistoryEvent) { + if unlock := event.GetEntityUnlockSent(); unlock != nil { + if e.lock != nil && e.lock.criticalSectionID == unlock.GetCriticalSectionId() { + e.lock = nil + } + return + } + request := event.GetEntityLockRequested() + e.lock = &entityLock{ + criticalSectionID: request.GetCriticalSectionId(), + ownerInstanceID: request.GetParentInstanceId().GetValue(), + } + // Locks are acquired one entity at a time in lock-set order. Because lock + // sets are sorted, critical sections can't deadlock. + next := request.GetPosition() + 1 + if int(next) < len(request.GetLockSet()) { + forwarded := proto.CloneOf(request) + forwarded.Position = next + s.deliverEntityLocked(request.GetLockSet()[next], &protos.HistoryEvent{ + EventId: -1, + Timestamp: timestamppb.Now(), + EventType: &protos.HistoryEvent_EntityLockRequested{EntityLockRequested: forwarded}, + }) + return + } + if owner, ok := s.instances[e.lock.ownerInstanceID]; ok { + s.deliverLocked(owner, &protos.HistoryEvent{ + EventId: -1, + Timestamp: timestamppb.Now(), + EventType: &protos.HistoryEvent_EntityLockGranted{ + EntityLockGranted: &protos.EntityLockGrantedEvent{CriticalSectionId: request.GetCriticalSectionId()}, + }, + }) + } +} + +// takeBatch removes the signals and calls that are ready to run, +// stopping at the next lock or unlock message. +func (e *entity) takeBatch() []*protos.HistoryEvent { + var batch []*protos.HistoryEvent + for { + i := e.nextMessage() + if i < 0 || isEntityControlMessage(e.queue[i]) { + return batch + } + batch = append(batch, e.queue[i]) + e.queue = slices.Delete(e.queue, i, i+1) + } +} + +func (s *Server) nextEntityWorkItemLocked(filters *protos.WorkItemFilters, streamID uint64) *protos.WorkItem { + for i, e := range s.entityQueue { + if !matchesEntityFilter(filters, e.name) { + continue + } + s.entityQueue = slices.Delete(s.entityQueue, i, i+1) + e.queued = false + if s.entities[e.id] != e || e.leased { + return s.nextEntityWorkItemLocked(filters, streamID) + } + events := e.takeBatch() + if len(events) == 0 { + return s.nextEntityWorkItemLocked(filters, streamID) + } + e.leased = true + token := newID() + s.entityLeases[token] = &entityLease{entity: e, events: events, streamID: streamID} + return &protos.WorkItem{ + Request: &protos.WorkItem_EntityRequestV2{EntityRequestV2: &protos.EntityRequest{ + InstanceId: e.id, + EntityState: e.state, + OperationRequests: events, + }}, + CompletionToken: token, + } + } + return nil +} + +func matchesEntityFilter(filters *protos.WorkItemFilters, name string) bool { + if filters == nil { + return true + } + return slices.ContainsFunc(filters.GetEntities(), func(f *protos.EntityFilter) bool { + return helpers.ToLowerInvariant(f.GetName()) == name + }) +} + +func (s *Server) abandonEntityLocked(token string, lease *entityLease) { + delete(s.entityLeases, token) + e := lease.entity + e.leased = false + e.queue = append(slices.Clone(lease.events), e.queue...) + s.pumpEntityLocked(e) +} + +// AbandonTaskEntityWorkItem returns an entity work item's operations to the entity's queue. +func (s *Server) AbandonTaskEntityWorkItem( + _ context.Context, + req *protos.AbandonEntityTaskRequest, +) (*protos.AbandonEntityTaskResponse, error) { + s.mu.Lock() + defer s.mu.Unlock() + lease, ok := s.entityLeases[req.GetCompletionToken()] + if !ok { + return nil, status.Error(codes.NotFound, "entity work item not found") + } + s.abandonEntityLocked(req.GetCompletionToken(), lease) + return &protos.AbandonEntityTaskResponse{}, nil +} + +// CompleteEntityTask commits an entity batch: it stores the new state, sends +// results to calling orchestrations, and applies the batch's actions. +func (s *Server) CompleteEntityTask(_ context.Context, result *protos.EntityBatchResult) (*protos.CompleteTaskResponse, error) { + s.mu.Lock() + defer s.mu.Unlock() + lease, ok := s.entityLeases[result.GetCompletionToken()] + if !ok { + return nil, status.Error(codes.NotFound, "entity work item not found") + } + delete(s.entityLeases, result.GetCompletionToken()) + e := lease.entity + e.leased = false + + if batchFailure := result.GetFailureDetails(); batchFailure != nil { + // The batch had no effect. Fail its calls rather than retrying the batch + // so that a persistent failure can't loop forever in a test. + for _, event := range lease.events { + if called := event.GetEntityOperationCalled(); called != nil { + s.respondToCallerLocked(called, &protos.HistoryEvent{EventId: -1, Timestamp: timestamppb.Now(), EventType: &protos.HistoryEvent_EntityOperationFailed{ + EntityOperationFailed: &protos.EntityOperationFailedEvent{ + RequestId: called.GetRequestId(), + FailureDetails: batchFailure, + }, + }}) + } + } + s.pumpEntityLocked(e) + return &protos.CompleteTaskResponse{}, nil + } + + e.state = result.GetEntityState() + e.lastModified = time.Now() + for i, opResult := range result.GetResults() { + if i >= len(lease.events) { + break + } + called := lease.events[i].GetEntityOperationCalled() + if called == nil { + continue + } + if failure := opResult.GetFailure(); failure != nil { + s.respondToCallerLocked(called, &protos.HistoryEvent{EventId: -1, Timestamp: timestamppb.Now(), EventType: &protos.HistoryEvent_EntityOperationFailed{ + EntityOperationFailed: &protos.EntityOperationFailedEvent{ + RequestId: called.GetRequestId(), + FailureDetails: failure.GetFailureDetails(), + }, + }}) + } else { + s.respondToCallerLocked(called, &protos.HistoryEvent{EventId: -1, Timestamp: timestamppb.Now(), EventType: &protos.HistoryEvent_EntityOperationCompleted{ + EntityOperationCompleted: &protos.EntityOperationCompletedEvent{ + RequestId: called.GetRequestId(), + Output: opResult.GetSuccess().GetResult(), + }, + }}) + } + } + for _, action := range result.GetActions() { + switch a := action.GetOperationActionType().(type) { + case *protos.OperationAction_SendSignal: + signal := a.SendSignal + s.signalEntityLocked(signal.GetInstanceId(), &protos.EntityOperationSignaledEvent{ + RequestId: newID(), + Operation: signal.GetName(), + Input: signal.GetInput(), + ScheduledTime: signal.GetScheduledTime(), + }) + case *protos.OperationAction_StartNewOrchestration: + start := a.StartNewOrchestration + id := start.GetInstanceId() + if id == "" { + id = newID() + } + if existing, ok := s.instances[id]; ok && !isTerminal(existing.status) { + continue + } + s.newInstanceLocked(id, start.GetName(), start.GetVersion(), start.GetInput(), start.GetTags(), + nil, start.GetParentTraceContext(), start.GetScheduledTime()) + } + } + s.pumpEntityLocked(e) + s.notifyLocked() + return &protos.CompleteTaskResponse{}, nil +} + +// respondToCallerLocked delivers an operation result to the calling +// orchestration if the calling execution is still active. +func (s *Server) respondToCallerLocked(called *protos.EntityOperationCalledEvent, event *protos.HistoryEvent) { + inst, ok := s.instances[called.GetParentInstanceId().GetValue()] + if !ok { + return + } + if executionID := called.GetParentExecutionId(); executionID != nil && executionID.GetValue() != inst.executionID { + return + } + s.deliverLocked(inst, event) +} + +// sendEntityMessageLocked records an orchestration's entity message in its +// history and delivers the message to the target entity. +func (s *Server) sendEntityMessageLocked(inst *instance, id int32, action *protos.SendEntityMessageAction) { + event := &protos.HistoryEvent{EventId: id, Timestamp: timestamppb.Now()} + message := &protos.HistoryEvent{EventId: -1, Timestamp: event.GetTimestamp()} + switch m := action.GetEntityMessageType().(type) { + case *protos.SendEntityMessageAction_EntityOperationSignaled: + event.EventType = &protos.HistoryEvent_EntityOperationSignaled{EntityOperationSignaled: m.EntityOperationSignaled} + inst.history = append(inst.history, event) + signal := proto.CloneOf(m.EntityOperationSignaled) + signal.TargetInstanceId = nil + s.signalEntityLocked(m.EntityOperationSignaled.GetTargetInstanceId().GetValue(), signal) + case *protos.SendEntityMessageAction_EntityOperationCalled: + event.EventType = &protos.HistoryEvent_EntityOperationCalled{EntityOperationCalled: m.EntityOperationCalled} + inst.history = append(inst.history, event) + called := proto.CloneOf(m.EntityOperationCalled) + called.TargetInstanceId = nil + called.ParentInstanceId = wrapperspb.String(inst.id) + called.ParentExecutionId = wrapperspb.String(inst.executionID) + message.EventType = &protos.HistoryEvent_EntityOperationCalled{EntityOperationCalled: called} + s.deliverEntityLocked(m.EntityOperationCalled.GetTargetInstanceId().GetValue(), message) + case *protos.SendEntityMessageAction_EntityLockRequested: + event.EventType = &protos.HistoryEvent_EntityLockRequested{EntityLockRequested: m.EntityLockRequested} + inst.history = append(inst.history, event) + request := proto.CloneOf(m.EntityLockRequested) + if len(request.GetLockSet()) == 0 { + return + } + request.Position = 0 + request.ParentInstanceId = wrapperspb.String(inst.id) + message.EventType = &protos.HistoryEvent_EntityLockRequested{EntityLockRequested: request} + s.deliverEntityLocked(request.GetLockSet()[0], message) + case *protos.SendEntityMessageAction_EntityUnlockSent: + event.EventType = &protos.HistoryEvent_EntityUnlockSent{EntityUnlockSent: m.EntityUnlockSent} + inst.history = append(inst.history, event) + unlock := proto.CloneOf(m.EntityUnlockSent) + unlock.TargetInstanceId = nil + unlock.ParentInstanceId = wrapperspb.String(inst.id) + message.EventType = &protos.HistoryEvent_EntityUnlockSent{EntityUnlockSent: unlock} + s.deliverEntityLocked(m.EntityUnlockSent.GetTargetInstanceId().GetValue(), message) + } +} + +func (e *entity) metadata(includeState bool) *protos.EntityMetadata { + metadata := &protos.EntityMetadata{ + InstanceId: e.id, + LastModifiedTime: timestamppb.New(e.lastModified), + BacklogQueueSize: int32(len(e.queue)), + } + if e.lock != nil { + metadata.LockedBy = wrapperspb.String(e.lock.ownerInstanceID) + } + if includeState { + metadata.SerializedState = e.state + } + return metadata +} + +// SignalEntity sends a one-way operation to an entity. +func (s *Server) SignalEntity(_ context.Context, req *protos.SignalEntityRequest) (*protos.SignalEntityResponse, error) { + id, _, ok := normalizeEntityID(req.GetInstanceId()) + if !ok { + return nil, invalidEntityIDError(req.GetInstanceId()) + } + if req.GetName() == "" { + return nil, status.Error(codes.InvalidArgument, "entity operation name is required") + } + requestID := req.GetRequestId() + if requestID == "" { + requestID = newID() + } + s.mu.Lock() + defer s.mu.Unlock() + s.signalEntityLocked(id, &protos.EntityOperationSignaledEvent{ + RequestId: requestID, + Operation: req.GetName(), + Input: req.GetInput(), + ScheduledTime: req.GetScheduledTime(), + }) + return &protos.SignalEntityResponse{}, nil +} + +// GetEntity returns an entity's metadata. An entity exists while it has state. +func (s *Server) GetEntity(_ context.Context, req *protos.GetEntityRequest) (*protos.GetEntityResponse, error) { + id, _, ok := normalizeEntityID(req.GetInstanceId()) + if !ok { + return nil, invalidEntityIDError(req.GetInstanceId()) + } + s.mu.Lock() + defer s.mu.Unlock() + e, ok := s.entities[id] + if !ok || e.state == nil { + return &protos.GetEntityResponse{Exists: false}, nil + } + return &protos.GetEntityResponse{Exists: true, Entity: e.metadata(req.GetIncludeState())}, nil +} + +// QueryEntities returns entities that match a query, ordered by instance ID. +func (s *Server) QueryEntities(_ context.Context, req *protos.QueryEntitiesRequest) (*protos.QueryEntitiesResponse, error) { + query := req.GetQuery() + offset := 0 + if token := query.GetContinuationToken().GetValue(); token != "" { + var err error + if offset, err = strconv.Atoi(token); err != nil || offset < 0 { + return nil, status.Errorf(codes.InvalidArgument, "invalid continuation token %q", token) + } + } + pageSize := int(query.GetPageSize().GetValue()) + if pageSize <= 0 { + pageSize = defaultQueryPageSize + } + + s.mu.Lock() + defer s.mu.Unlock() + var matches []*entity + for _, e := range s.entities { + if e.state == nil && !query.GetIncludeTransient() { + continue + } + if prefix := query.GetInstanceIdStartsWith().GetValue(); prefix != "" && !strings.HasPrefix(e.id, prefix) { + continue + } + if !inRange(e.lastModified, query.GetLastModifiedFrom(), query.GetLastModifiedTo()) { + continue + } + matches = append(matches, e) + } + slices.SortFunc(matches, func(a, b *entity) int { return cmp.Compare(a.id, b.id) }) + + resp := &protos.QueryEntitiesResponse{} + if offset >= len(matches) { + return resp, nil + } + end := min(offset+pageSize, len(matches)) + for _, e := range matches[offset:end] { + resp.Entities = append(resp.Entities, e.metadata(query.GetIncludeState())) + } + if end < len(matches) { + resp.ContinuationToken = wrapperspb.String(strconv.Itoa(end)) + } + return resp, nil +} + +// CleanEntityStorage releases locks held by orchestrations that are no longer +// running and removes entities that have no state, messages, or lock. +func (s *Server) CleanEntityStorage(_ context.Context, req *protos.CleanEntityStorageRequest) (*protos.CleanEntityStorageResponse, error) { + s.mu.Lock() + defer s.mu.Unlock() + resp := &protos.CleanEntityStorageResponse{} + if req.GetReleaseOrphanedLocks() { + for _, e := range s.entities { + if e.lock == nil { + continue + } + if owner, ok := s.instances[e.lock.ownerInstanceID]; ok && !isTerminal(owner.status) { + continue + } + e.lock = nil + resp.OrphanedLocksReleased++ + s.pumpEntityLocked(e) + } + } + if req.GetRemoveEmptyEntities() { + for id, e := range s.entities { + if e.state == nil && len(e.queue) == 0 && e.lock == nil && !e.leased { + delete(s.entities, id) + resp.EmptyEntitiesRemoved++ + } + } + } + return resp, nil +} diff --git a/internal/inmemory/entity_test.go b/internal/inmemory/entity_test.go new file mode 100644 index 00000000..c03d6c8f --- /dev/null +++ b/internal/inmemory/entity_test.go @@ -0,0 +1,97 @@ +package inmemory + +import ( + "context" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "google.golang.org/protobuf/types/known/wrapperspb" + + "github.com/microsoft/durabletask-go/internal/protos" +) + +func signalEvent(operation string) *protos.HistoryEvent { + return &protos.HistoryEvent{EventType: &protos.HistoryEvent_EntityOperationSignaled{ + EntityOperationSignaled: &protos.EntityOperationSignaledEvent{RequestId: newID(), Operation: operation}, + }} +} + +func TestLockedEntityDispatchesOnlyOwnerCalls(t *testing.T) { + s := NewServer() + defer s.Close() + s.mu.Lock() + defer s.mu.Unlock() + + s.deliverEntityLocked("@counter@a", &protos.HistoryEvent{EventType: &protos.HistoryEvent_EntityLockRequested{ + EntityLockRequested: &protos.EntityLockRequestedEvent{ + CriticalSectionId: "cs", + LockSet: []string{"@counter@a"}, + ParentInstanceId: wrapperspb.String("owner"), + }, + }}) + s.deliverEntityLocked("@counter@a", signalEvent("outside")) + assert.Nil(t, s.nextEntityWorkItemLocked(nil, 1), "a signal from outside the critical section must wait") + + s.deliverEntityLocked("@counter@a", &protos.HistoryEvent{EventType: &protos.HistoryEvent_EntityOperationCalled{ + EntityOperationCalled: &protos.EntityOperationCalledEvent{ + RequestId: newID(), + Operation: "inside", + ParentInstanceId: wrapperspb.String("owner"), + }, + }}) + item := s.nextEntityWorkItemLocked(nil, 1) + require.NotNil(t, item) + requests := item.GetEntityRequestV2().GetOperationRequests() + require.Len(t, requests, 1) + assert.Equal(t, "inside", requests[0].GetEntityOperationCalled().GetOperation()) +} + +func TestCleanEntityStorageReleasesOrphanedLocks(t *testing.T) { + s := NewServer() + defer s.Close() + s.mu.Lock() + e := s.getOrCreateEntityLocked("@counter@a", "counter") + e.lock = &entityLock{criticalSectionID: "cs", ownerInstanceID: "gone"} + e.queue = append(e.queue, signalEvent("add")) + s.mu.Unlock() + + resp, err := s.CleanEntityStorage(context.Background(), &protos.CleanEntityStorageRequest{ + ReleaseOrphanedLocks: true, + RemoveEmptyEntities: true, + }) + require.NoError(t, err) + assert.Equal(t, int32(1), resp.GetOrphanedLocksReleased()) + assert.Zero(t, resp.GetEmptyEntitiesRemoved(), "an entity with queued messages isn't empty") + + s.mu.Lock() + defer s.mu.Unlock() + assert.Nil(t, e.lock) + assert.NotNil(t, s.nextEntityWorkItemLocked(nil, 1), "the queued signal is dispatched once the lock is released") +} + +func TestReleaseStreamRequeuesEntityWorkItems(t *testing.T) { + s := NewServer() + defer s.Close() + s.mu.Lock() + s.deliverEntityLocked("@counter@a", signalEvent("first")) + s.deliverEntityLocked("@counter@a", signalEvent("second")) + item := s.nextEntityWorkItemLocked(nil, 7) + require.NotNil(t, item) + require.Len(t, item.GetEntityRequestV2().GetOperationRequests(), 2) + s.deliverEntityLocked("@counter@a", signalEvent("third")) + assert.Nil(t, s.nextEntityWorkItemLocked(nil, 7), "a leased entity isn't dispatched again") + s.mu.Unlock() + + s.releaseStream(7) + + s.mu.Lock() + defer s.mu.Unlock() + item = s.nextEntityWorkItemLocked(nil, 8) + require.NotNil(t, item) + var operations []string + for _, event := range item.GetEntityRequestV2().GetOperationRequests() { + operations = append(operations, event.GetEntityOperationSignaled().GetOperation()) + } + assert.Equal(t, []string{"first", "second", "third"}, operations) +} diff --git a/internal/inmemory/server.go b/internal/inmemory/server.go index 98397213..ad00589d 100644 --- a/internal/inmemory/server.go +++ b/internal/inmemory/server.go @@ -2,7 +2,8 @@ // // 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 are not supported. +// worker can run against it, including durable entities and rewind. Timers fire +// in real time. package inmemory import ( @@ -47,6 +48,10 @@ type Server struct { actQueue []*activityItem orchLeases map[string]*orchestrationLease actLeases map[string]*activityLease + entities map[string]*entity + entityQueue []*entity + entityLeases map[string]*entityLease + timers []*time.Timer changed chan struct{} closed bool nextStreamID uint64 @@ -111,6 +116,8 @@ func NewServer() *Server { instances: make(map[string]*instance), orchLeases: make(map[string]*orchestrationLease), actLeases: make(map[string]*activityLease), + entities: make(map[string]*entity), + entityLeases: make(map[string]*entityLease), changed: make(chan struct{}), } } @@ -131,6 +138,10 @@ func (s *Server) Close() { for _, inst := range s.instances { inst.stopTimers() } + for _, t := range s.timers { + t.Stop() + } + s.timers = nil s.notifyLocked() } diff --git a/internal/inmemory/work.go b/internal/inmemory/work.go index 3cf13d77..4071ac94 100644 --- a/internal/inmemory/work.go +++ b/internal/inmemory/work.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/durationpb" "google.golang.org/protobuf/types/known/timestamppb" "google.golang.org/protobuf/types/known/wrapperspb" @@ -17,7 +18,7 @@ import ( "github.com/microsoft/durabletask-go/internal/protos" ) -// GetWorkItems streams orchestration and activity work items to a worker. +// GetWorkItems streams orchestration, activity, and entity work items to a worker. // Work items that are still in flight when the stream ends are returned to the queue. func (s *Server) GetWorkItems(req *protos.GetWorkItemsRequest, stream grpc.ServerStreamingServer[protos.WorkItem]) error { ctx := stream.Context() @@ -31,6 +32,7 @@ func (s *Server) GetWorkItems(req *protos.GetWorkItemsRequest, stream grpc.Serve limits := workItemLimits{ orchestrations: req.GetMaxConcurrentOrchestrationWorkItems(), activities: req.GetMaxConcurrentActivityWorkItems(), + entities: req.GetMaxConcurrentEntityWorkItems(), } ping := time.NewTicker(s.healthPingInterval) defer ping.Stop() @@ -65,6 +67,7 @@ func (s *Server) GetWorkItems(req *protos.GetWorkItemsRequest, stream grpc.Serve type workItemLimits struct { orchestrations int32 activities int32 + entities int32 } func (s *Server) nextWorkItemLocked( @@ -101,7 +104,20 @@ func (s *Server) nextWorkItemLocked( } } } - return nil + if !streamHasCapacity(limits.entities, countEntityLeases(s.entityLeases, streamID)) { + return nil + } + return s.nextEntityWorkItemLocked(filters, streamID) +} + +func countEntityLeases(leases map[string]*entityLease, streamID uint64) int { + count := 0 + for _, lease := range leases { + if lease.streamID == streamID { + count++ + } + } + return count } func streamHasCapacity(limit int32, inFlight int) bool { @@ -148,6 +164,8 @@ func (s *Server) leaseOrchestrationLocked(inst *instance, streamID uint64) *prot ExecutionId: wrapperspb.String(inst.executionID), PastEvents: slices.Clone(inst.history), NewEvents: events, + // Entity messages are delivered in order, so no reorder window is needed. + EntityParameters: &protos.OrchestratorEntityParameters{EntityMessageReorderWindow: durationpb.New(0)}, } item := &protos.WorkItem{ Request: &protos.WorkItem_OrchestratorRequest{OrchestratorRequest: request}, @@ -219,6 +237,11 @@ func (s *Server) releaseStream(streamID uint64) { s.actQueue = append(s.actQueue, lease.item) } } + for token, lease := range s.entityLeases { + if lease.streamID == streamID { + s.abandonEntityLocked(token, lease) + } + } s.notifyLocked() } @@ -413,10 +436,8 @@ func (s *Server) applyActionsLocked(inst *instance, actions []*protos.Orchestrat *protos.OrchestratorAction_CreateSubOrchestration, *protos.OrchestratorAction_SendEvent, *protos.OrchestratorAction_TerminateOrchestration, + *protos.OrchestratorAction_SendEntityMessage, *protos.OrchestratorAction_CompleteOrchestration: - case *protos.OrchestratorAction_SendEntityMessage: - s.failUnsupportedLocked(inst, "durable entities are not supported by the in-memory test backend") - return default: s.failUnsupportedLocked(inst, "orchestrator action %T is not supported by the in-memory test backend", action.GetOrchestratorActionType()) @@ -454,6 +475,8 @@ func (s *Server) applyActionsLocked(inst *instance, actions []*protos.Orchestrat if target, ok := s.instances[terminate.GetInstanceId()]; ok { s.terminateLocked(target, terminate.GetReason(), terminate.GetRecurse()) } + case *protos.OrchestratorAction_SendEntityMessage: + s.sendEntityMessageLocked(inst, id, a.SendEntityMessage) case *protos.OrchestratorAction_CompleteOrchestration: complete = a.CompleteOrchestration } From a8f7b186f3ed6c5a3615545b04b8ed4de893fb42 Mon Sep 17 00:00:00 2001 From: Andy Staples Date: Mon, 23 Nov 2026 12:41:45 -0700 Subject: [PATCH 02/12] Fence entity lock acquisition and bound entity work item size Drop lock acquisitions whose requesting execution has ended so a terminated waiter can't lock entities after its unlocks have passed them. Select entity operations in one pass and stop before a work item exceeds the worker's gRPC receive limit, leaving the remaining operations queued. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- internal/inmemory/entity.go | 112 ++++++++++++++++++++++--------- internal/inmemory/entity_test.go | 96 ++++++++++++++++++++++++-- internal/inmemory/server.go | 12 +++- 3 files changed, 179 insertions(+), 41 deletions(-) diff --git a/internal/inmemory/entity.go b/internal/inmemory/entity.go index 33ecfedd..1b20d685 100644 --- a/internal/inmemory/entity.go +++ b/internal/inmemory/entity.go @@ -3,6 +3,7 @@ package inmemory import ( "cmp" "context" + "encoding/binary" "slices" "strconv" "strings" @@ -10,6 +11,7 @@ import ( "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + "google.golang.org/protobuf/encoding/protowire" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/known/timestamppb" "google.golang.org/protobuf/types/known/wrapperspb" @@ -113,21 +115,22 @@ func (s *Server) startServerTimerLocked(at time.Time, fn func()) { // nextMessage returns the index of the next message the entity can // process, or -1 if none can be processed now. func (e *entity) nextMessage() int { + return slices.IndexFunc(e.queue, e.canProcess) +} + +// canProcess reports whether the entity can process a message now. While the +// entity is locked, only the owner's calls and unlock can be processed. +func (e *entity) canProcess(event *protos.HistoryEvent) bool { if e.lock == nil { - if len(e.queue) == 0 { - return -1 - } - return 0 + return true } - return slices.IndexFunc(e.queue, func(event *protos.HistoryEvent) bool { - if called := event.GetEntityOperationCalled(); called != nil { - return called.GetParentInstanceId().GetValue() == e.lock.ownerInstanceID - } - if unlock := event.GetEntityUnlockSent(); unlock != nil { - return unlock.GetCriticalSectionId() == e.lock.criticalSectionID - } - return false - }) + if called := event.GetEntityOperationCalled(); called != nil { + return called.GetParentInstanceId().GetValue() == e.lock.ownerInstanceID + } + if unlock := event.GetEntityUnlockSent(); unlock != nil { + return unlock.GetCriticalSectionId() == e.lock.criticalSectionID + } + return false } func isEntityControlMessage(event *protos.HistoryEvent) bool { @@ -167,6 +170,13 @@ func (s *Server) processEntityControlMessageLocked(e *entity, event *protos.Hist return } request := event.GetEntityLockRequested() + if !s.lockRequestActiveLocked(request) { + // The requesting execution has ended. Its unlocks may already have + // passed the entities later in the lock set, so the acquisition must + // stop here rather than lock entities that will never be released. + delete(s.lockRequests, request.GetCriticalSectionId()) + return + } e.lock = &entityLock{ criticalSectionID: request.GetCriticalSectionId(), ownerInstanceID: request.GetParentInstanceId().GetValue(), @@ -184,6 +194,7 @@ func (s *Server) processEntityControlMessageLocked(e *entity, event *protos.Hist }) return } + delete(s.lockRequests, request.GetCriticalSectionId()) if owner, ok := s.instances[e.lock.ownerInstanceID]; ok { s.deliverLocked(owner, &protos.HistoryEvent{ EventId: -1, @@ -195,18 +206,53 @@ func (s *Server) processEntityControlMessageLocked(e *entity, event *protos.Hist } } -// takeBatch removes the signals and calls that are ready to run, -// stopping at the next lock or unlock message. -func (e *entity) takeBatch() []*protos.HistoryEvent { +// lockRequestActiveLocked reports whether the execution that sent a lock +// request is still running. +func (s *Server) lockRequestActiveLocked(request *protos.EntityLockRequestedEvent) bool { + executionID, ok := s.lockRequests[request.GetCriticalSectionId()] + if !ok { + return false + } + owner, ok := s.instances[request.GetParentInstanceId().GetValue()] + return ok && !isTerminal(owner.status) && owner.executionID == executionID +} + +// takeBatch removes the signals and calls that are ready to run, stopping at +// the next lock or unlock message or when the next operation would make the +// work item larger than maxBytes. The first operation is always taken so that +// the entity makes progress. +func (e *entity) takeBatch(baseSize, maxBytes int) []*protos.HistoryEvent { var batch []*protos.HistoryEvent - for { - i := e.nextMessage() - if i < 0 || isEntityControlMessage(e.queue[i]) { - return batch + var kept []*protos.HistoryEvent + // Adding operations can lengthen the EntityRequest and WorkItem length prefixes. + size := baseSize + 2*binary.MaxVarintLen32 + stop := len(e.queue) + for i, event := range e.queue { + if !e.canProcess(event) { + kept = append(kept, event) + continue } - batch = append(batch, e.queue[i]) - e.queue = slices.Delete(e.queue, i, i+1) + if isEntityControlMessage(event) { + stop = i + break + } + size += operationRequestSize(event) + if len(batch) > 0 && size > maxBytes { + stop = i + break + } + batch = append(batch, event) + } + if len(batch) > 0 { + e.queue = append(kept, e.queue[stop:]...) } + return batch +} + +// operationRequestSize returns the bytes an operation adds to an EntityRequest. +func operationRequestSize(event *protos.HistoryEvent) int { + const field = 4 // EntityRequest.operationRequests + return protowire.SizeTag(field) + protowire.SizeBytes(proto.Size(event)) } func (s *Server) nextEntityWorkItemLocked(filters *protos.WorkItemFilters, streamID uint64) *protos.WorkItem { @@ -219,21 +265,22 @@ func (s *Server) nextEntityWorkItemLocked(filters *protos.WorkItemFilters, strea if s.entities[e.id] != e || e.leased { return s.nextEntityWorkItemLocked(filters, streamID) } - events := e.takeBatch() - if len(events) == 0 { - return s.nextEntityWorkItemLocked(filters, streamID) - } - e.leased = true token := newID() - s.entityLeases[token] = &entityLease{entity: e, events: events, streamID: streamID} - return &protos.WorkItem{ + item := &protos.WorkItem{ Request: &protos.WorkItem_EntityRequestV2{EntityRequestV2: &protos.EntityRequest{ - InstanceId: e.id, - EntityState: e.state, - OperationRequests: events, + InstanceId: e.id, + EntityState: e.state, }}, CompletionToken: token, } + events := e.takeBatch(proto.Size(item), s.maxEntityWorkItemBytes) + if len(events) == 0 { + return s.nextEntityWorkItemLocked(filters, streamID) + } + e.leased = true + s.entityLeases[token] = &entityLease{entity: e, events: events, streamID: streamID} + item.GetEntityRequestV2().OperationRequests = events + return item } return nil } @@ -397,6 +444,7 @@ func (s *Server) sendEntityMessageLocked(inst *instance, id int32, action *proto } request.Position = 0 request.ParentInstanceId = wrapperspb.String(inst.id) + s.lockRequests[request.GetCriticalSectionId()] = inst.executionID message.EventType = &protos.HistoryEvent_EntityLockRequested{EntityLockRequested: request} s.deliverEntityLocked(request.GetLockSet()[0], message) case *protos.SendEntityMessageAction_EntityUnlockSent: diff --git a/internal/inmemory/entity_test.go b/internal/inmemory/entity_test.go index c03d6c8f..c6864727 100644 --- a/internal/inmemory/entity_test.go +++ b/internal/inmemory/entity_test.go @@ -2,10 +2,13 @@ package inmemory import ( "context" + "strconv" + "strings" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/known/wrapperspb" "github.com/microsoft/durabletask-go/internal/protos" @@ -17,19 +20,34 @@ func signalEvent(operation string) *protos.HistoryEvent { }} } +func lockRequestEvent(s *Server, owner *instance, criticalSectionID string, lockSet ...string) *protos.HistoryEvent { + s.lockRequests[criticalSectionID] = owner.executionID + return &protos.HistoryEvent{EventType: &protos.HistoryEvent_EntityLockRequested{ + EntityLockRequested: &protos.EntityLockRequestedEvent{ + CriticalSectionId: criticalSectionID, + LockSet: lockSet, + ParentInstanceId: wrapperspb.String(owner.id), + }, + }} +} + +func unlockEvent(owner *instance, criticalSectionID string) *protos.HistoryEvent { + return &protos.HistoryEvent{EventType: &protos.HistoryEvent_EntityUnlockSent{ + EntityUnlockSent: &protos.EntityUnlockSentEvent{ + CriticalSectionId: criticalSectionID, + ParentInstanceId: wrapperspb.String(owner.id), + }, + }} +} + func TestLockedEntityDispatchesOnlyOwnerCalls(t *testing.T) { s := NewServer() defer s.Close() s.mu.Lock() defer s.mu.Unlock() - s.deliverEntityLocked("@counter@a", &protos.HistoryEvent{EventType: &protos.HistoryEvent_EntityLockRequested{ - EntityLockRequested: &protos.EntityLockRequestedEvent{ - CriticalSectionId: "cs", - LockSet: []string{"@counter@a"}, - ParentInstanceId: wrapperspb.String("owner"), - }, - }}) + owner := s.newInstanceLocked("owner", "orchestrator", nil, nil, nil, nil, nil, nil) + s.deliverEntityLocked("@counter@a", lockRequestEvent(s, owner, "cs", "@counter@a")) s.deliverEntityLocked("@counter@a", signalEvent("outside")) assert.Nil(t, s.nextEntityWorkItemLocked(nil, 1), "a signal from outside the critical section must wait") @@ -70,6 +88,70 @@ func TestCleanEntityStorageReleasesOrphanedLocks(t *testing.T) { assert.NotNil(t, s.nextEntityWorkItemLocked(nil, 1), "the queued signal is dispatched once the lock is released") } +func TestLockAcquisitionStopsWhenRequesterEnds(t *testing.T) { + s := NewServer() + defer s.Close() + s.mu.Lock() + defer s.mu.Unlock() + lockSet := []string{"@counter@a", "@counter@b", "@counter@c"} + + holder := s.newInstanceLocked("holder", "orchestrator", nil, nil, nil, nil, nil, nil) + s.deliverEntityLocked("@counter@b", lockRequestEvent(s, holder, "holder-cs", "@counter@b")) + waiter := s.newInstanceLocked("waiter", "orchestrator", nil, nil, nil, nil, nil, nil) + s.deliverEntityLocked(lockSet[0], lockRequestEvent(s, waiter, "waiter-cs", lockSet...)) + require.Equal(t, "waiter", s.entities["@counter@a"].lock.ownerInstanceID) + require.Equal(t, "holder", s.entities["@counter@b"].lock.ownerInstanceID) + + // Terminating the waiter releases its lock set while it still waits for B, + // so its unlock reaches C before the acquisition does. + for _, id := range lockSet { + s.deliverEntityLocked(id, unlockEvent(waiter, "waiter-cs")) + } + s.completeLocked(waiter, protos.OrchestrationStatus_ORCHESTRATION_STATUS_TERMINATED, nil, nil) + s.deliverEntityLocked("@counter@b", unlockEvent(holder, "holder-cs")) + + for _, id := range lockSet { + e := s.entities[id] + assert.Nil(t, e.lock, "%s must not stay locked by the terminated execution", id) + assert.Empty(t, e.queue, "%s has no pending messages", id) + } + assert.Empty(t, s.lockRequests) +} + +func TestEntityWorkItemsAreBoundedBySize(t *testing.T) { + s := NewServer() + defer s.Close() + s.mu.Lock() + defer s.mu.Unlock() + s.maxEntityWorkItemBytes = 1024 + + const count = 20 + for i := range count { + event := signalEvent(strconv.Itoa(i)) + event.GetEntityOperationSignaled().Input = wrapperspb.String(strings.Repeat("x", 200)) + s.deliverEntityLocked("@counter@a", event) + } + var operations []string + for streamID := uint64(1); len(operations) < count; streamID++ { + item := s.nextEntityWorkItemLocked(nil, streamID) + require.NotNil(t, item) + requests := item.GetEntityRequestV2().GetOperationRequests() + require.NotEmpty(t, requests) + assert.Less(t, len(requests), count, "a large backlog is split across work items") + assert.LessOrEqual(t, proto.Size(item), s.maxEntityWorkItemBytes) + for _, event := range requests { + operations = append(operations, event.GetEntityOperationSignaled().GetOperation()) + } + s.mu.Unlock() + _, err := s.CompleteEntityTask(context.Background(), &protos.EntityBatchResult{CompletionToken: item.GetCompletionToken()}) + s.mu.Lock() + require.NoError(t, err) + } + for i, operation := range operations { + assert.Equal(t, strconv.Itoa(i), operation, "operations are dispatched in order") + } +} + func TestReleaseStreamRequeuesEntityWorkItems(t *testing.T) { s := NewServer() defer s.Close() diff --git a/internal/inmemory/server.go b/internal/inmemory/server.go index ad00589d..85eb8972 100644 --- a/internal/inmemory/server.go +++ b/internal/inmemory/server.go @@ -34,13 +34,18 @@ const ( defaultQueryPageSize = 100 maxOrchestrationWorkItemSize = 4 << 20 maxHistoryChunkSize = 4 << 20 + + // defaultMaxEntityWorkItemBytes matches gRPC's default client receive + // limit, which the test host's worker uses. + defaultMaxEntityWorkItemBytes = 4 << 20 ) // Server is an in-memory implementation of the TaskHubSidecarService. type Server struct { protos.UnimplementedTaskHubSidecarServiceServer - healthPingInterval time.Duration + healthPingInterval time.Duration + maxEntityWorkItemBytes int mu sync.Mutex instances map[string]*instance @@ -51,6 +56,7 @@ type Server struct { entities map[string]*entity entityQueue []*entity entityLeases map[string]*entityLease + lockRequests map[string]string // critical section ID to requesting execution ID timers []*time.Timer changed chan struct{} closed bool @@ -112,12 +118,14 @@ type activityLease struct { // NewServer creates an empty in-memory service. func NewServer() *Server { return &Server{ - healthPingInterval: defaultHealthPingInterval, + healthPingInterval: defaultHealthPingInterval, + maxEntityWorkItemBytes: defaultMaxEntityWorkItemBytes, instances: make(map[string]*instance), orchLeases: make(map[string]*orchestrationLease), actLeases: make(map[string]*activityLease), entities: make(map[string]*entity), entityLeases: make(map[string]*entityLease), + lockRequests: make(map[string]string), changed: make(chan struct{}), } } From 334b1e89ead895c517d173a5055b5fc03ffcece9 Mon Sep 17 00:00:00 2001 From: Andy Staples Date: Mon, 23 Nov 2026 12:50:53 -0700 Subject: [PATCH 03/12] Reject entity operations that can't fit in a work item Enforce the work item size limit for the first operation in a batch too. Operations that can't fit even alone are removed so they can't stall the entity; calls fail with EntityOperationTooLarge and signals are dropped. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- internal/inmemory/entity.go | 51 ++++++++++++++++++++++++-------- internal/inmemory/entity_test.go | 44 +++++++++++++++++++++++++++ 2 files changed, 83 insertions(+), 12 deletions(-) diff --git a/internal/inmemory/entity.go b/internal/inmemory/entity.go index 1b20d685..2c80ac59 100644 --- a/internal/inmemory/entity.go +++ b/internal/inmemory/entity.go @@ -218,11 +218,11 @@ func (s *Server) lockRequestActiveLocked(request *protos.EntityLockRequestedEven } // takeBatch removes the signals and calls that are ready to run, stopping at -// the next lock or unlock message or when the next operation would make the -// work item larger than maxBytes. The first operation is always taken so that -// the entity makes progress. -func (e *entity) takeBatch(baseSize, maxBytes int) []*protos.HistoryEvent { - var batch []*protos.HistoryEvent +// the next lock or unlock message or at the first operation that would make +// the work item larger than maxBytes; that operation stays queued for the next +// batch. An operation that can't fit even in an otherwise empty work item is +// removed and returned in rejected so that it can't stall the entity. +func (e *entity) takeBatch(baseSize, maxBytes int) (batch, rejected []*protos.HistoryEvent) { var kept []*protos.HistoryEvent // Adding operations can lengthen the EntityRequest and WorkItem length prefixes. size := baseSize + 2*binary.MaxVarintLen32 @@ -236,17 +236,41 @@ func (e *entity) takeBatch(baseSize, maxBytes int) []*protos.HistoryEvent { stop = i break } - size += operationRequestSize(event) - if len(batch) > 0 && size > maxBytes { - stop = i - break + opSize := operationRequestSize(event) + if size+opSize > maxBytes { + if len(batch) > 0 { + stop = i + break + } + rejected = append(rejected, event) + continue } + size += opSize batch = append(batch, event) } - if len(batch) > 0 { + if len(batch) > 0 || len(rejected) > 0 { e.queue = append(kept, e.queue[stop:]...) } - return batch + return batch, rejected +} + +// rejectOversizedOperationsLocked fails calls whose request can't fit in an +// entity work item. Oversized signals are dropped. +func (s *Server) rejectOversizedOperationsLocked(e *entity, events []*protos.HistoryEvent) { + for _, event := range events { + called := event.GetEntityOperationCalled() + if called == nil { + continue + } + s.respondToCallerLocked(called, &protos.HistoryEvent{EventId: -1, Timestamp: timestamppb.Now(), EventType: &protos.HistoryEvent_EntityOperationFailed{ + EntityOperationFailed: &protos.EntityOperationFailedEvent{ + RequestId: called.GetRequestId(), + FailureDetails: failureDetails("EntityOperationTooLarge", + "operation %q on entity %q exceeds the %d-byte entity work item limit", + called.GetOperation(), e.id, s.maxEntityWorkItemBytes), + }, + }}) + } } // operationRequestSize returns the bytes an operation adds to an EntityRequest. @@ -273,8 +297,11 @@ func (s *Server) nextEntityWorkItemLocked(filters *protos.WorkItemFilters, strea }}, CompletionToken: token, } - events := e.takeBatch(proto.Size(item), s.maxEntityWorkItemBytes) + events, rejected := e.takeBatch(proto.Size(item), s.maxEntityWorkItemBytes) + s.rejectOversizedOperationsLocked(e, rejected) if len(events) == 0 { + // Rejecting operations can leave a lock or unlock message ready. + s.pumpEntityLocked(e) return s.nextEntityWorkItemLocked(filters, streamID) } e.leased = true diff --git a/internal/inmemory/entity_test.go b/internal/inmemory/entity_test.go index c6864727..4c2642f9 100644 --- a/internal/inmemory/entity_test.go +++ b/internal/inmemory/entity_test.go @@ -152,6 +152,50 @@ func TestEntityWorkItemsAreBoundedBySize(t *testing.T) { } } +func TestOversizedEntityOperationsAreRejected(t *testing.T) { + s := NewServer() + defer s.Close() + s.mu.Lock() + defer s.mu.Unlock() + s.maxEntityWorkItemBytes = 1024 + + // The signal fits within the limit on its own but not once wrapped in a work item. + oversized := signalEvent("oversized") + oversized.GetEntityOperationSignaled().Input = wrapperspb.String("") + padding := s.maxEntityWorkItemBytes - 8 - operationRequestSize(oversized) + oversized.GetEntityOperationSignaled().Input = wrapperspb.String(strings.Repeat("x", padding)) + require.LessOrEqual(t, operationRequestSize(oversized), s.maxEntityWorkItemBytes) + + caller := s.newInstanceLocked("caller", "orchestrator", nil, nil, nil, nil, nil, nil) + caller.pending = nil + call := &protos.HistoryEvent{EventType: &protos.HistoryEvent_EntityOperationCalled{ + EntityOperationCalled: &protos.EntityOperationCalledEvent{ + RequestId: "call-1", + Operation: "oversizedCall", + Input: wrapperspb.String(strings.Repeat("x", s.maxEntityWorkItemBytes)), + ParentInstanceId: wrapperspb.String("caller"), + }, + }} + + s.deliverEntityLocked("@counter@a", oversized) + s.deliverEntityLocked("@counter@a", call) + s.deliverEntityLocked("@counter@a", signalEvent("next")) + + item := s.nextEntityWorkItemLocked(nil, 1) + require.NotNil(t, item, "the entity keeps making progress after rejecting oversized operations") + assert.LessOrEqual(t, proto.Size(item), s.maxEntityWorkItemBytes) + requests := item.GetEntityRequestV2().GetOperationRequests() + require.Len(t, requests, 1) + assert.Equal(t, "next", requests[0].GetEntityOperationSignaled().GetOperation()) + assert.Empty(t, s.entities["@counter@a"].queue) + + require.Len(t, caller.pending, 1) + failed := caller.pending[0].GetEntityOperationFailed() + require.NotNil(t, failed, "the oversized call fails instead of being dispatched") + assert.Equal(t, "call-1", failed.GetRequestId()) + assert.Equal(t, "EntityOperationTooLarge", failed.GetFailureDetails().GetErrorType()) +} + func TestReleaseStreamRequeuesEntityWorkItems(t *testing.T) { s := NewServer() defer s.Close() From 494c4c0c4ed031a7af8fbd7748abfc4e09e884b4 Mon Sep 17 00:00:00 2001 From: Andy Staples Date: Mon, 23 Nov 2026 12:55:17 -0700 Subject: [PATCH 04/12] Bind entity locks and calls to the owning execution Locks record the owning execution, so cleanup releases locks left by a replaced instance and only that execution's calls run under them. Rewind rebinds outstanding calls, lock requests, and locks to the renewed execution. Entity queries treat LastModifiedTo as exclusive. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- internal/inmemory/entity.go | 62 +++++++++++++++- internal/inmemory/entity_test.go | 122 +++++++++++++++++++++++++++++-- internal/inmemory/rewind.go | 1 + 3 files changed, 173 insertions(+), 12 deletions(-) diff --git a/internal/inmemory/entity.go b/internal/inmemory/entity.go index 2c80ac59..fb107445 100644 --- a/internal/inmemory/entity.go +++ b/internal/inmemory/entity.go @@ -40,6 +40,7 @@ type entity struct { type entityLock struct { criticalSectionID string ownerInstanceID string + ownerExecutionID string } type entityLease struct { @@ -119,13 +120,14 @@ func (e *entity) nextMessage() int { } // canProcess reports whether the entity can process a message now. While the -// entity is locked, only the owner's calls and unlock can be processed. +// entity is locked, only the owning execution's calls and unlock can be processed. func (e *entity) canProcess(event *protos.HistoryEvent) bool { if e.lock == nil { return true } if called := event.GetEntityOperationCalled(); called != nil { - return called.GetParentInstanceId().GetValue() == e.lock.ownerInstanceID + return called.GetParentInstanceId().GetValue() == e.lock.ownerInstanceID && + called.GetParentExecutionId().GetValue() == e.lock.ownerExecutionID } if unlock := event.GetEntityUnlockSent(); unlock != nil { return unlock.GetCriticalSectionId() == e.lock.criticalSectionID @@ -180,6 +182,7 @@ func (s *Server) processEntityControlMessageLocked(e *entity, event *protos.Hist e.lock = &entityLock{ criticalSectionID: request.GetCriticalSectionId(), ownerInstanceID: request.GetParentInstanceId().GetValue(), + ownerExecutionID: s.lockRequests[request.GetCriticalSectionId()], } // Locks are acquired one entity at a time in lock-set order. Because lock // sets are sorted, critical sections can't deadlock. @@ -428,6 +431,52 @@ func (s *Server) CompleteEntityTask(_ context.Context, result *protos.EntityBatc return &protos.CompleteTaskResponse{}, nil } +// rebindEntityExecutionLocked moves an instance's outstanding entity calls, +// lock requests, and locks from one execution to another. Rewind renews the +// execution ID but keeps the history that sent them, so replay waits for their +// results rather than sending them again. +func (s *Server) rebindEntityExecutionLocked(instanceID, oldExecutionID, newExecutionID string) { + if oldExecutionID == newExecutionID { + return + } + rebind := func(events []*protos.HistoryEvent) []*protos.HistoryEvent { + var rebound []*protos.HistoryEvent + for i, event := range events { + called := event.GetEntityOperationCalled() + if called.GetParentInstanceId().GetValue() != instanceID || + called.GetParentExecutionId().GetValue() != oldExecutionID { + continue + } + if rebound == nil { + // Leased events may be in use outside the server lock; don't modify them. + rebound = slices.Clone(events) + } + cloned := proto.CloneOf(event) + cloned.GetEntityOperationCalled().ParentExecutionId = wrapperspb.String(newExecutionID) + rebound[i] = cloned + } + if rebound == nil { + return events + } + return rebound + } + for criticalSectionID, executionID := range s.lockRequests { + if executionID == oldExecutionID { + s.lockRequests[criticalSectionID] = newExecutionID + } + } + for _, lease := range s.entityLeases { + lease.events = rebind(lease.events) + } + for _, e := range s.entities { + e.queue = rebind(e.queue) + if e.lock != nil && e.lock.ownerInstanceID == instanceID && e.lock.ownerExecutionID == oldExecutionID { + e.lock.ownerExecutionID = newExecutionID + } + s.pumpEntityLocked(e) + } +} + // respondToCallerLocked delivers an operation result to the calling // orchestration if the calling execution is still active. func (s *Server) respondToCallerLocked(called *protos.EntityOperationCalledEvent, event *protos.HistoryEvent) { @@ -564,7 +613,11 @@ func (s *Server) QueryEntities(_ context.Context, req *protos.QueryEntitiesReque if prefix := query.GetInstanceIdStartsWith().GetValue(); prefix != "" && !strings.HasPrefix(e.id, prefix) { continue } - if !inRange(e.lastModified, query.GetLastModifiedFrom(), query.GetLastModifiedTo()) { + // LastModifiedFrom is inclusive and LastModifiedTo is exclusive. + if from := query.GetLastModifiedFrom(); from != nil && e.lastModified.Before(from.AsTime()) { + continue + } + if to := query.GetLastModifiedTo(); to != nil && !e.lastModified.Before(to.AsTime()) { continue } matches = append(matches, e) @@ -596,7 +649,8 @@ func (s *Server) CleanEntityStorage(_ context.Context, req *protos.CleanEntitySt if e.lock == nil { continue } - if owner, ok := s.instances[e.lock.ownerInstanceID]; ok && !isTerminal(owner.status) { + if owner, ok := s.instances[e.lock.ownerInstanceID]; ok && !isTerminal(owner.status) && + owner.executionID == e.lock.ownerExecutionID { continue } e.lock = nil diff --git a/internal/inmemory/entity_test.go b/internal/inmemory/entity_test.go index 4c2642f9..92684d45 100644 --- a/internal/inmemory/entity_test.go +++ b/internal/inmemory/entity_test.go @@ -5,10 +5,12 @@ import ( "strconv" "strings" "testing" + "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "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/protos" @@ -53,9 +55,10 @@ func TestLockedEntityDispatchesOnlyOwnerCalls(t *testing.T) { s.deliverEntityLocked("@counter@a", &protos.HistoryEvent{EventType: &protos.HistoryEvent_EntityOperationCalled{ EntityOperationCalled: &protos.EntityOperationCalledEvent{ - RequestId: newID(), - Operation: "inside", - ParentInstanceId: wrapperspb.String("owner"), + RequestId: newID(), + Operation: "inside", + ParentInstanceId: wrapperspb.String("owner"), + ParentExecutionId: wrapperspb.String(owner.executionID), }, }}) item := s.nextEntityWorkItemLocked(nil, 1) @@ -65,6 +68,109 @@ func TestLockedEntityDispatchesOnlyOwnerCalls(t *testing.T) { assert.Equal(t, "inside", requests[0].GetEntityOperationCalled().GetOperation()) } +func callEvent(owner *instance, requestID string) *protos.HistoryEvent { + return &protos.HistoryEvent{EventType: &protos.HistoryEvent_EntityOperationCalled{ + EntityOperationCalled: &protos.EntityOperationCalledEvent{ + RequestId: requestID, + Operation: "get", + ParentInstanceId: wrapperspb.String(owner.id), + ParentExecutionId: wrapperspb.String(owner.executionID), + }, + }} +} + +func TestReplacedOwnerLocksAreOrphaned(t *testing.T) { + s := NewServer() + defer s.Close() + s.mu.Lock() + old := s.newInstanceLocked("owner", "orchestrator", nil, nil, nil, nil, nil, nil) + s.deliverEntityLocked("@counter@a", lockRequestEvent(s, old, "old-cs", "@counter@a")) + require.NotNil(t, s.entities["@counter@a"].lock) + + replacement := s.newInstanceLocked("owner", "orchestrator", nil, nil, nil, nil, nil, nil) + s.deliverEntityLocked("@counter@a", callEvent(replacement, "call-1")) + assert.Nil(t, s.nextEntityWorkItemLocked(nil, 1), "the replacement doesn't own the old execution's lock") + s.mu.Unlock() + + resp, err := s.CleanEntityStorage(context.Background(), &protos.CleanEntityStorageRequest{ReleaseOrphanedLocks: true}) + require.NoError(t, err) + assert.Equal(t, int32(1), resp.GetOrphanedLocksReleased()) + + s.mu.Lock() + defer s.mu.Unlock() + assert.Nil(t, s.entities["@counter@a"].lock) + assert.NotNil(t, s.nextEntityWorkItemLocked(nil, 1), "the replacement's call runs once the old lock is released") +} + +func TestRewindRebindsOutstandingEntityCalls(t *testing.T) { + s := NewServer() + defer s.Close() + s.mu.Lock() + inst := s.newInstanceLocked("caller", "orchestrator", nil, nil, nil, nil, nil, nil) + s.deliverEntityLocked("@counter@a", lockRequestEvent(s, inst, "cs", "@counter@a", "@counter@b")) + s.deliverEntityLocked("@counter@a", callEvent(inst, "leased")) + item := s.nextEntityWorkItemLocked(nil, 1) + require.NotNil(t, item) + s.deliverEntityLocked("@counter@a", callEvent(inst, "queued")) + + started := proto.CloneOf(inst.pending[0]) + started.GetExecutionStarted().OrchestrationInstance.ExecutionId = wrapperspb.String("renewed") + s.applyRewindLocked(inst, &protos.RewindOrchestrationAction{NewHistory: []*protos.HistoryEvent{started}}) + inst.pending = nil + assert.Equal(t, "renewed", s.entities["@counter@a"].lock.ownerExecutionID) + assert.Equal(t, "renewed", s.entities["@counter@b"].lock.ownerExecutionID) + assert.Equal(t, "leased", item.GetEntityRequestV2().GetOperationRequests()[0].GetEntityOperationCalled().GetRequestId()) + assert.NotEqual(t, "renewed", item.GetEntityRequestV2().GetOperationRequests()[0].GetEntityOperationCalled().GetParentExecutionId().GetValue(), + "do not mutate the dispatched request") + s.mu.Unlock() + + _, err := s.CompleteEntityTask(context.Background(), &protos.EntityBatchResult{ + CompletionToken: item.GetCompletionToken(), + Results: []*protos.OperationResult{{ResultType: &protos.OperationResult_Success{Success: &protos.OperationResultSuccess{}}}}, + }) + require.NoError(t, err) + + s.mu.Lock() + next := s.nextEntityWorkItemLocked(nil, 2) + require.NotNil(t, next, "the renewed execution still owns the lock") + s.mu.Unlock() + _, err = s.CompleteEntityTask(context.Background(), &protos.EntityBatchResult{ + CompletionToken: next.GetCompletionToken(), + Results: []*protos.OperationResult{{ResultType: &protos.OperationResult_Success{Success: &protos.OperationResultSuccess{}}}}, + }) + require.NoError(t, err) + + s.mu.Lock() + defer s.mu.Unlock() + var completed []string + for _, event := range inst.pending { + if c := event.GetEntityOperationCompleted(); c != nil { + completed = append(completed, c.GetRequestId()) + } + } + assert.Equal(t, []string{"leased", "queued"}, completed, "results reach the renewed execution") +} + +func TestQueryEntitiesLastModifiedToIsExclusive(t *testing.T) { + s := NewServer() + defer s.Close() + s.mu.Lock() + e := s.getOrCreateEntityLocked("@counter@a", "counter") + e.state = wrapperspb.String("1") + s.mu.Unlock() + + query := func(to time.Time) int { + resp, err := s.QueryEntities(context.Background(), &protos.QueryEntitiesRequest{Query: &protos.EntityQuery{ + LastModifiedFrom: timestamppb.New(e.lastModified), + LastModifiedTo: timestamppb.New(to), + }}) + require.NoError(t, err) + return len(resp.GetEntities()) + } + assert.Zero(t, query(e.lastModified)) + assert.Equal(t, 1, query(e.lastModified.Add(time.Nanosecond))) +} + func TestCleanEntityStorageReleasesOrphanedLocks(t *testing.T) { s := NewServer() defer s.Close() @@ -159,12 +265,12 @@ func TestOversizedEntityOperationsAreRejected(t *testing.T) { defer s.mu.Unlock() s.maxEntityWorkItemBytes = 1024 - // The signal fits within the limit on its own but not once wrapped in a work item. + // The stored state and the signal input each fit within the limit, but not together. + e := s.getOrCreateEntityLocked("@counter@a", "counter") + e.state = wrapperspb.String(strings.Repeat("s", 600)) oversized := signalEvent("oversized") - oversized.GetEntityOperationSignaled().Input = wrapperspb.String("") - padding := s.maxEntityWorkItemBytes - 8 - operationRequestSize(oversized) - oversized.GetEntityOperationSignaled().Input = wrapperspb.String(strings.Repeat("x", padding)) - require.LessOrEqual(t, operationRequestSize(oversized), s.maxEntityWorkItemBytes) + oversized.GetEntityOperationSignaled().Input = wrapperspb.String(strings.Repeat("x", 600)) + require.Less(t, operationRequestSize(oversized), s.maxEntityWorkItemBytes) caller := s.newInstanceLocked("caller", "orchestrator", nil, nil, nil, nil, nil, nil) caller.pending = nil diff --git a/internal/inmemory/rewind.go b/internal/inmemory/rewind.go index 0b18b046..dc9a38a9 100644 --- a/internal/inmemory/rewind.go +++ b/internal/inmemory/rewind.go @@ -250,6 +250,7 @@ func (s *Server) applyRewindLocked(inst *instance, action *protos.RewindOrchestr } inst.rewind = nil s.reconcileRewindTasksLocked(inst, oldExecutionID, childResults) + s.rebindEntityExecutionLocked(inst.id, oldExecutionID, inst.executionID) for _, event := range unfinishedSubOrchestrations(inst.history) { created := event.GetSubOrchestrationInstanceCreated() From 9c1f1288fb924895ef7a9747413ff7626be9a333 Mon Sep 17 00:00:00 2001 From: Andy Staples Date: Mon, 23 Nov 2026 13:20:18 -0700 Subject: [PATCH 05/12] Preserve entity results during rewind Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- durabletasktest/entity_test.go | 53 ++++++++++++++++++++ internal/inmemory/entity.go | 12 +++-- internal/inmemory/entity_test.go | 85 ++++++++++++++++++++++++++++++++ internal/inmemory/work.go | 4 +- 4 files changed, 149 insertions(+), 5 deletions(-) diff --git a/durabletasktest/entity_test.go b/durabletasktest/entity_test.go index b892f427..32a7b533 100644 --- a/durabletasktest/entity_test.go +++ b/durabletasktest/entity_test.go @@ -2,6 +2,7 @@ package durabletasktest_test import ( "errors" + "sync" "sync/atomic" "testing" "time" @@ -159,6 +160,58 @@ func TestEntityOperationFailure(t *testing.T) { assert.Equal(t, `"counter failed"`, metadata.SerializedOutput) } +func TestRewindRetainsLateEntityResult(t *testing.T) { + var repaired atomic.Bool + var entityCalls atomic.Int32 + entered := make(chan struct{}) + release := make(chan struct{}) + var enteredOnce, releaseOnce sync.Once + r := task.NewTaskRegistry() + require.NoError(t, r.AddEntityN("blocked", func(ctx *task.EntityContext) (any, error) { + entityCalls.Add(1) + enteredOnce.Do(func() { close(entered) }) + <-release + return 42, ctx.SetState(42) + })) + require.NoError(t, r.AddActivityN("Flaky", func(ctx task.ActivityContext) (any, error) { + <-entered + if !repaired.Load() { + return nil, errors.New("dependency unavailable") + } + return nil, nil + })) + require.NoError(t, r.AddOrchestratorN("Caller", func(ctx *task.OrchestrationContext) (any, error) { + entity := ctx.CallEntity(api.NewEntityID("blocked", "a"), "get") + if err := ctx.CallActivity("Flaky").Await(nil); err != nil { + return nil, err + } + var result int + err := entity.Await(&result) + return result, err + })) + host := durabletasktest.New(t, r) + t.Cleanup(func() { releaseOnce.Do(func() { close(release) }) }) + ctx := testContext(t) + id, err := host.Client().ScheduleNewOrchestration(ctx, "Caller") + require.NoError(t, err) + failed, err := host.Client().WaitForOrchestrationCompletion(ctx, id) + require.NoError(t, err) + require.Equal(t, api.RUNTIME_STATUS_FAILED, failed.RuntimeStatus) + + releaseOnce.Do(func() { close(release) }) + require.Eventually(t, func() bool { + entity, err := host.Client().GetEntity(ctx, api.NewEntityID("blocked", "a")) + return err == nil && entity != nil + }, 10*time.Second, 10*time.Millisecond) + repaired.Store(true) + require.NoError(t, host.Client().RewindInstance(ctx, id)) + completed, err := host.Client().WaitForOrchestrationCompletion(ctx, id) + require.NoError(t, err) + require.Equal(t, api.RUNTIME_STATUS_COMPLETED, completed.RuntimeStatus) + assert.Equal(t, "42", completed.SerializedOutput) + assert.EqualValues(t, 1, entityCalls.Load()) +} + func TestEntityActions(t *testing.T) { host := newEntityHost(t, func(r *task.TaskRegistry) { require.NoError(t, r.AddOrchestratorN("Echo", func(ctx *task.OrchestrationContext) (any, error) { diff --git a/internal/inmemory/entity.go b/internal/inmemory/entity.go index fb107445..8d15ccdb 100644 --- a/internal/inmemory/entity.go +++ b/internal/inmemory/entity.go @@ -316,7 +316,7 @@ func (s *Server) nextEntityWorkItemLocked(filters *protos.WorkItemFilters, strea } func matchesEntityFilter(filters *protos.WorkItemFilters, name string) bool { - if filters == nil { + if filters == nil || len(filters.GetEntities()) == 0 { return true } return slices.ContainsFunc(filters.GetEntities(), func(f *protos.EntityFilter) bool { @@ -477,8 +477,8 @@ func (s *Server) rebindEntityExecutionLocked(instanceID, oldExecutionID, newExec } } -// respondToCallerLocked delivers an operation result to the calling -// orchestration if the calling execution is still active. +// respondToCallerLocked delivers an operation result to the calling execution, +// retaining it for a failed orchestration in case it is rewound. func (s *Server) respondToCallerLocked(called *protos.EntityOperationCalledEvent, event *protos.HistoryEvent) { inst, ok := s.instances[called.GetParentInstanceId().GetValue()] if !ok { @@ -487,7 +487,11 @@ func (s *Server) respondToCallerLocked(called *protos.EntityOperationCalledEvent if executionID := called.GetParentExecutionId(); executionID != nil && executionID.GetValue() != inst.executionID { return } - s.deliverLocked(inst, event) + if inst.status == protos.OrchestrationStatus_ORCHESTRATION_STATUS_FAILED { + inst.pending = append(inst.pending, event) + } else { + s.deliverLocked(inst, event) + } } // sendEntityMessageLocked records an orchestration's entity message in its diff --git a/internal/inmemory/entity_test.go b/internal/inmemory/entity_test.go index 92684d45..f6d12092 100644 --- a/internal/inmemory/entity_test.go +++ b/internal/inmemory/entity_test.go @@ -13,6 +13,7 @@ import ( "google.golang.org/protobuf/types/known/timestamppb" "google.golang.org/protobuf/types/known/wrapperspb" + "github.com/microsoft/durabletask-go/internal/helpers" "github.com/microsoft/durabletask-go/internal/protos" ) @@ -79,6 +80,90 @@ func callEvent(owner *instance, requestID string) *protos.HistoryEvent { }} } +func TestEntityWorkItemFilters(t *testing.T) { + tests := []struct { + name string + filters *protos.WorkItemFilters + want bool + }{ + {"nil", nil, true}, + {"other work kinds", &protos.WorkItemFilters{ + Orchestrations: []*protos.OrchestrationFilter{{Name: "orchestration"}}, + Activities: []*protos.ActivityFilter{{Name: "activity"}}, + }, true}, + {"matching", &protos.WorkItemFilters{Entities: []*protos.EntityFilter{{Name: "Counter"}}}, true}, + {"different", &protos.WorkItemFilters{Entities: []*protos.EntityFilter{{Name: "other"}}}, false}, + {"reject all", &protos.WorkItemFilters{Entities: []*protos.EntityFilter{{Name: helpers.RejectAllWorkItemFilterName}}}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + s := NewServer() + defer s.Close() + s.deliverEntityLocked("@counter@a", signalEvent("add")) + item := s.nextEntityWorkItemLocked(tt.filters, 1) + assert.Equal(t, tt.want, item != nil) + }) + } +} + +func TestRewindRetainsEntityResults(t *testing.T) { + for _, failed := range []bool{false, true} { + for _, beforeFailure := range []bool{false, true} { + name := "completed" + if failed { + name = "failed" + } + if beforeFailure { + name += "-before-failure" + } else { + name += "-after-failure" + } + t.Run(name, func(t *testing.T) { + s := NewServer() + defer s.Close() + inst := s.newInstanceLocked("caller", "orchestrator", nil, nil, nil, nil, nil, nil) + started := inst.pending[0] + called := callEvent(inst, "request") + inst.history = []*protos.HistoryEvent{started, called} + inst.pending = nil + result := &protos.HistoryEvent{} + if failed { + result.EventType = &protos.HistoryEvent_EntityOperationFailed{ + EntityOperationFailed: &protos.EntityOperationFailedEvent{RequestId: "request"}, + } + } else { + result.EventType = &protos.HistoryEvent_EntityOperationCompleted{ + EntityOperationCompleted: &protos.EntityOperationCompletedEvent{RequestId: "request"}, + } + } + if beforeFailure { + s.respondToCallerLocked(called.GetEntityOperationCalled(), result) + } + s.completeLocked(inst, protos.OrchestrationStatus_ORCHESTRATION_STATUS_FAILED, nil, failureDetails("failure", "boom")) + if !beforeFailure { + s.respondToCallerLocked(called.GetEntityOperationCalled(), result) + } + require.Equal(t, []*protos.HistoryEvent{result}, inst.pending) + s.prepareRewindLocked(inst, nil, nil) + renewed := proto.CloneOf(started) + renewed.GetExecutionStarted().OrchestrationInstance.ExecutionId = wrapperspb.String("renewed") + s.applyRewindLocked(inst, &protos.RewindOrchestrationAction{NewHistory: []*protos.HistoryEvent{renewed, called}}) + item := s.nextWorkItemLocked(nil, 1, workItemLimits{}) + require.NotNil(t, item) + require.Contains(t, item.GetOrchestratorRequest().GetNewEvents(), result) + + inst.pending = nil + s.respondToCallerLocked(called.GetEntityOperationCalled(), result) + assert.Empty(t, inst.pending, "a stale execution must not receive results") + inst.status = protos.OrchestrationStatus_ORCHESTRATION_STATUS_COMPLETED + called.GetEntityOperationCalled().ParentExecutionId = wrapperspb.String("renewed") + s.respondToCallerLocked(called.GetEntityOperationCalled(), result) + assert.Empty(t, inst.pending, "a completed instance must not receive results") + }) + } + } +} + func TestReplacedOwnerLocksAreOrphaned(t *testing.T) { s := NewServer() defer s.Close() diff --git a/internal/inmemory/work.go b/internal/inmemory/work.go index 4071ac94..be11f8a9 100644 --- a/internal/inmemory/work.go +++ b/internal/inmemory/work.go @@ -621,7 +621,9 @@ func (s *Server) completeLocked( *protos.HistoryEvent_TaskFailed, *protos.HistoryEvent_TimerFired, *protos.HistoryEvent_SubOrchestrationInstanceCompleted, - *protos.HistoryEvent_SubOrchestrationInstanceFailed: + *protos.HistoryEvent_SubOrchestrationInstanceFailed, + *protos.HistoryEvent_EntityOperationCompleted, + *protos.HistoryEvent_EntityOperationFailed: return false default: return true From 01b8818aa5df5da8b7047709c42bf4281e3b2345 Mon Sep 17 00:00:00 2001 From: Andy Staples Date: Mon, 23 Nov 2026 13:46:21 -0700 Subject: [PATCH 06/12] Format in-memory server constructor Realign the NewServer field initializers that the entity fields left unformatted. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- internal/inmemory/server.go | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/internal/inmemory/server.go b/internal/inmemory/server.go index 85eb8972..426bd59a 100644 --- a/internal/inmemory/server.go +++ b/internal/inmemory/server.go @@ -120,13 +120,13 @@ func NewServer() *Server { return &Server{ healthPingInterval: defaultHealthPingInterval, maxEntityWorkItemBytes: defaultMaxEntityWorkItemBytes, - instances: make(map[string]*instance), - orchLeases: make(map[string]*orchestrationLease), - actLeases: make(map[string]*activityLease), - entities: make(map[string]*entity), - entityLeases: make(map[string]*entityLease), - lockRequests: make(map[string]string), - changed: make(chan struct{}), + instances: make(map[string]*instance), + orchLeases: make(map[string]*orchestrationLease), + actLeases: make(map[string]*activityLease), + entities: make(map[string]*entity), + entityLeases: make(map[string]*entityLease), + lockRequests: make(map[string]string), + changed: make(chan struct{}), } } From 880da97cbd6f2a255416994d11d36b4dc1bdb33f Mon Sep 17 00:00:00 2001 From: Andy Staples Date: Mon, 23 Nov 2026 13:46:50 -0700 Subject: [PATCH 07/12] Wake entity work item streams after failed batches A failed signal-only batch can leave its entity with nothing to dispatch, so pumping the entity doesn't notify waiting streams. Notify them as the success path does so another queued entity can use the freed concurrency slot without waiting for the next event or health ping. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- internal/inmemory/entity.go | 3 +++ internal/inmemory/entity_test.go | 22 ++++++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/internal/inmemory/entity.go b/internal/inmemory/entity.go index 8d15ccdb..c15f27ad 100644 --- a/internal/inmemory/entity.go +++ b/internal/inmemory/entity.go @@ -374,6 +374,9 @@ func (s *Server) CompleteEntityTask(_ context.Context, result *protos.EntityBatc } } s.pumpEntityLocked(e) + // The completed work item frees a concurrency slot even if this entity + // has nothing more to dispatch. + s.notifyLocked() return &protos.CompleteTaskResponse{}, nil } diff --git a/internal/inmemory/entity_test.go b/internal/inmemory/entity_test.go index f6d12092..39a900fc 100644 --- a/internal/inmemory/entity_test.go +++ b/internal/inmemory/entity_test.go @@ -412,3 +412,25 @@ func TestReleaseStreamRequeuesEntityWorkItems(t *testing.T) { } assert.Equal(t, []string{"first", "second", "third"}, operations) } + +func TestFailedSignalBatchNotifiesWorkItemStreams(t *testing.T) { + s := NewServer() + defer s.Close() + s.mu.Lock() + s.deliverEntityLocked("@counter@a", signalEvent("add")) + item := s.nextEntityWorkItemLocked(nil, 1) + require.NotNil(t, item) + changed := s.changed + s.mu.Unlock() + + _, err := s.CompleteEntityTask(context.Background(), &protos.EntityBatchResult{ + CompletionToken: item.GetCompletionToken(), + FailureDetails: failureDetails("failure", "boom"), + }) + require.NoError(t, err) + select { + case <-changed: + default: + t.Fatal("completing a failed batch must wake streams waiting for a free entity slot") + } +} From 9f78c6f7bf184af47de922c044470f184ba2775f Mon Sep 17 00:00:00 2001 From: Andy Staples Date: Mon, 23 Nov 2026 13:47:20 -0700 Subject: [PATCH 08/12] Use a stable cursor for entity query pages QueryEntities continuation tokens were offsets into a result set rebuilt for each page, so entities added or removed between pages caused later pages to skip or repeat entities. Encode the last returned instance ID instead and resume at greater IDs, as instance queries do. Malformed tokens still return InvalidArgument. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- internal/inmemory/entity.go | 37 +++++++++++++++++-------- internal/inmemory/entity_test.go | 46 ++++++++++++++++++++++++++++++++ 2 files changed, 72 insertions(+), 11 deletions(-) diff --git a/internal/inmemory/entity.go b/internal/inmemory/entity.go index c15f27ad..2cf325c6 100644 --- a/internal/inmemory/entity.go +++ b/internal/inmemory/entity.go @@ -3,9 +3,9 @@ package inmemory import ( "cmp" "context" + "encoding/base64" "encoding/binary" "slices" - "strconv" "strings" "time" @@ -596,12 +596,14 @@ func (s *Server) GetEntity(_ context.Context, req *protos.GetEntityRequest) (*pr } // QueryEntities returns entities that match a query, ordered by instance ID. +// The continuation token encodes the last returned instance ID, so a query +// resumes after it even if entities are added or removed between pages. func (s *Server) QueryEntities(_ context.Context, req *protos.QueryEntitiesRequest) (*protos.QueryEntitiesResponse, error) { query := req.GetQuery() - offset := 0 + var cursor string if token := query.GetContinuationToken().GetValue(); token != "" { - var err error - if offset, err = strconv.Atoi(token); err != nil || offset < 0 { + var ok bool + if cursor, ok = decodeEntityCursor(token); !ok { return nil, status.Errorf(codes.InvalidArgument, "invalid continuation token %q", token) } } @@ -614,6 +616,9 @@ func (s *Server) QueryEntities(_ context.Context, req *protos.QueryEntitiesReque defer s.mu.Unlock() var matches []*entity for _, e := range s.entities { + if cursor != "" && e.id <= cursor { + continue + } if e.state == nil && !query.GetIncludeTransient() { continue } @@ -632,19 +637,29 @@ func (s *Server) QueryEntities(_ context.Context, req *protos.QueryEntitiesReque slices.SortFunc(matches, func(a, b *entity) int { return cmp.Compare(a.id, b.id) }) resp := &protos.QueryEntitiesResponse{} - if offset >= len(matches) { - return resp, nil + if len(matches) > pageSize { + matches = matches[:pageSize] + resp.ContinuationToken = wrapperspb.String(encodeEntityCursor(matches[pageSize-1].id)) } - end := min(offset+pageSize, len(matches)) - for _, e := range matches[offset:end] { + for _, e := range matches { resp.Entities = append(resp.Entities, e.metadata(query.GetIncludeState())) } - if end < len(matches) { - resp.ContinuationToken = wrapperspb.String(strconv.Itoa(end)) - } return resp, nil } +func encodeEntityCursor(instanceID string) string { + return base64.RawURLEncoding.EncodeToString([]byte(instanceID)) +} + +func decodeEntityCursor(token string) (string, bool) { + decoded, err := base64.RawURLEncoding.DecodeString(token) + if err != nil { + return "", false + } + id, _, ok := normalizeEntityID(string(decoded)) + return id, ok && id == string(decoded) +} + // CleanEntityStorage releases locks held by orchestrations that are no longer // running and removes entities that have no state, messages, or lock. func (s *Server) CleanEntityStorage(_ context.Context, req *protos.CleanEntityStorageRequest) (*protos.CleanEntityStorageResponse, error) { diff --git a/internal/inmemory/entity_test.go b/internal/inmemory/entity_test.go index 39a900fc..e7b3faf5 100644 --- a/internal/inmemory/entity_test.go +++ b/internal/inmemory/entity_test.go @@ -9,6 +9,8 @@ import ( "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/timestamppb" "google.golang.org/protobuf/types/known/wrapperspb" @@ -434,3 +436,47 @@ func TestFailedSignalBatchNotifiesWorkItemStreams(t *testing.T) { t.Fatal("completing a failed batch must wake streams waiting for a free entity slot") } } + +func TestQueryEntitiesResumesAfterLastReturnedEntity(t *testing.T) { + s := NewServer() + defer s.Close() + s.mu.Lock() + for _, key := range []string{"a", "b", "c"} { + s.getOrCreateEntityLocked("@counter@"+key, "counter").state = wrapperspb.String("1") + } + s.mu.Unlock() + + query := func(token *wrapperspb.StringValue) *protos.QueryEntitiesResponse { + resp, err := s.QueryEntities(context.Background(), &protos.QueryEntitiesRequest{Query: &protos.EntityQuery{ + PageSize: wrapperspb.Int32(1), + ContinuationToken: token, + }}) + require.NoError(t, err) + return resp + } + ids := func(resp *protos.QueryEntitiesResponse) []string { + var ids []string + for _, e := range resp.GetEntities() { + ids = append(ids, e.GetInstanceId()) + } + return ids + } + first := query(nil) + require.Equal(t, []string{"@counter@a"}, ids(first)) + s.mu.Lock() + delete(s.entities, "@counter@a") + s.mu.Unlock() + + second := query(first.GetContinuationToken()) + assert.Equal(t, []string{"@counter@b"}, ids(second), "removing a returned entity doesn't skip the next one") + third := query(second.GetContinuationToken()) + assert.Equal(t, []string{"@counter@c"}, ids(third)) + assert.Nil(t, third.GetContinuationToken()) + + for _, token := range []string{"1", "not base64!", encodeEntityCursor("not-an-entity")} { + _, err := s.QueryEntities(context.Background(), &protos.QueryEntitiesRequest{Query: &protos.EntityQuery{ + ContinuationToken: wrapperspb.String(token), + }}) + assert.Equal(t, codes.InvalidArgument, status.Code(err), "token %q", token) + } +} From b5605ce8c2c8470b7d6a66ae72aec88241631666 Mon Sep 17 00:00:00 2001 From: Andy Staples Date: Mon, 23 Nov 2026 13:47:40 -0700 Subject: [PATCH 09/12] Reject malformed entity request IDs before enqueueing Workers refuse entity work items whose signal or call request IDs aren't UUIDs, so an accepted malformed ID made the worker abandon the batch repeatedly and blocked the entity. SignalEntity now returns InvalidArgument for a supplied request ID that isn't a UUID and still generates one when it's omitted. Orchestration entity messages with a malformed request ID or entity instance ID now fail the orchestration instead of being delivered undispatchable or dropped. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- internal/inmemory/entity.go | 37 +++++++++++++++++ internal/inmemory/entity_test.go | 68 ++++++++++++++++++++++++++++++++ internal/inmemory/work.go | 10 ++++- 3 files changed, 113 insertions(+), 2 deletions(-) diff --git a/internal/inmemory/entity.go b/internal/inmemory/entity.go index 2cf325c6..8cd160b1 100644 --- a/internal/inmemory/entity.go +++ b/internal/inmemory/entity.go @@ -5,10 +5,12 @@ import ( "context" "encoding/base64" "encoding/binary" + "fmt" "slices" "strings" "time" + "github.com/google/uuid" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" "google.golang.org/protobuf/encoding/protowire" @@ -497,6 +499,38 @@ func (s *Server) respondToCallerLocked(called *protos.EntityOperationCalledEvent } } +// validateEntityMessage reports an entity message that the service couldn't +// deliver or that a worker would refuse to process. +func validateEntityMessage(action *protos.SendEntityMessageAction) error { + var requestID string + var hasRequestID bool + var targets []string + switch m := action.GetEntityMessageType().(type) { + case *protos.SendEntityMessageAction_EntityOperationSignaled: + requestID, hasRequestID = m.EntityOperationSignaled.GetRequestId(), true + targets = []string{m.EntityOperationSignaled.GetTargetInstanceId().GetValue()} + case *protos.SendEntityMessageAction_EntityOperationCalled: + requestID, hasRequestID = m.EntityOperationCalled.GetRequestId(), true + targets = []string{m.EntityOperationCalled.GetTargetInstanceId().GetValue()} + case *protos.SendEntityMessageAction_EntityLockRequested: + targets = m.EntityLockRequested.GetLockSet() + case *protos.SendEntityMessageAction_EntityUnlockSent: + targets = []string{m.EntityUnlockSent.GetTargetInstanceId().GetValue()} + } + for _, target := range targets { + if _, _, ok := normalizeEntityID(target); !ok { + return fmt.Errorf("invalid entity instance ID %q", target) + } + } + if hasRequestID { + // Workers reject entity work items whose request IDs aren't UUIDs. + if _, err := uuid.Parse(requestID); err != nil { + return fmt.Errorf("invalid entity request ID %q: must be a UUID", requestID) + } + } + return nil +} + // sendEntityMessageLocked records an orchestration's entity message in its // history and delivers the message to the target entity. func (s *Server) sendEntityMessageLocked(inst *instance, id int32, action *protos.SendEntityMessageAction) { @@ -568,6 +602,9 @@ func (s *Server) SignalEntity(_ context.Context, req *protos.SignalEntityRequest requestID := req.GetRequestId() if requestID == "" { requestID = newID() + } else if _, err := uuid.Parse(requestID); err != nil { + // Workers reject entity work items whose request IDs aren't UUIDs. + return nil, status.Errorf(codes.InvalidArgument, "invalid entity request ID %q: must be a UUID", requestID) } s.mu.Lock() defer s.mu.Unlock() diff --git a/internal/inmemory/entity_test.go b/internal/inmemory/entity_test.go index e7b3faf5..92ac37dc 100644 --- a/internal/inmemory/entity_test.go +++ b/internal/inmemory/entity_test.go @@ -7,6 +7,7 @@ import ( "testing" "time" + "github.com/google/uuid" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "google.golang.org/grpc/codes" @@ -415,6 +416,73 @@ func TestReleaseStreamRequeuesEntityWorkItems(t *testing.T) { assert.Equal(t, []string{"first", "second", "third"}, operations) } +func TestSignalEntityValidatesRequestID(t *testing.T) { + s := NewServer() + defer s.Close() + signal := func(requestID string) error { + _, err := s.SignalEntity(context.Background(), &protos.SignalEntityRequest{ + InstanceId: "@counter@a", + Name: "add", + RequestId: requestID, + }) + return err + } + assert.Equal(t, codes.InvalidArgument, status.Code(signal("bad-id"))) + s.mu.Lock() + assert.NotContains(t, s.entities, "@counter@a", "a rejected signal isn't enqueued") + s.mu.Unlock() + + require.NoError(t, signal("")) + require.NoError(t, signal(newID())) + s.mu.Lock() + defer s.mu.Unlock() + queue := s.entities["@counter@a"].queue + require.Len(t, queue, 2) + _, err := uuid.Parse(queue[0].GetEntityOperationSignaled().GetRequestId()) + assert.NoError(t, err, "an omitted request ID is generated") +} + +func TestInvalidEntityMessageFailsOrchestration(t *testing.T) { + tests := map[string]*protos.SendEntityMessageAction{ + "call request ID": {EntityMessageType: &protos.SendEntityMessageAction_EntityOperationCalled{ + EntityOperationCalled: &protos.EntityOperationCalledEvent{ + RequestId: "bad-id", Operation: "get", TargetInstanceId: wrapperspb.String("@counter@a"), + }, + }}, + "signal request ID": {EntityMessageType: &protos.SendEntityMessageAction_EntityOperationSignaled{ + EntityOperationSignaled: &protos.EntityOperationSignaledEvent{ + Operation: "add", TargetInstanceId: wrapperspb.String("@counter@a"), + }, + }}, + "call target": {EntityMessageType: &protos.SendEntityMessageAction_EntityOperationCalled{ + EntityOperationCalled: &protos.EntityOperationCalledEvent{ + RequestId: newID(), Operation: "get", TargetInstanceId: wrapperspb.String("counter"), + }, + }}, + "lock set": {EntityMessageType: &protos.SendEntityMessageAction_EntityLockRequested{ + EntityLockRequested: &protos.EntityLockRequestedEvent{ + CriticalSectionId: newID(), LockSet: []string{"@counter@a", "not-an-entity"}, + }, + }}, + } + for name, message := range tests { + t.Run(name, func(t *testing.T) { + s := NewServer() + defer s.Close() + s.mu.Lock() + defer s.mu.Unlock() + inst := s.newInstanceLocked("caller", "orchestrator", nil, nil, nil, nil, nil, nil) + s.applyActionsLocked(inst, []*protos.OrchestratorAction{{ + Id: 1, + OrchestratorActionType: &protos.OrchestratorAction_SendEntityMessage{SendEntityMessage: message}, + }}) + assert.Equal(t, protos.OrchestrationStatus_ORCHESTRATION_STATUS_FAILED, inst.status) + assert.Equal(t, "InvalidEntityMessage", inst.failure.GetErrorType()) + assert.Empty(t, s.entities, "an invalid message isn't delivered") + }) + } +} + func TestFailedSignalBatchNotifiesWorkItemStreams(t *testing.T) { s := NewServer() defer s.Close() diff --git a/internal/inmemory/work.go b/internal/inmemory/work.go index be11f8a9..8d657c97 100644 --- a/internal/inmemory/work.go +++ b/internal/inmemory/work.go @@ -430,14 +430,20 @@ func countsTowardTurnBudget(event *protos.HistoryEvent) bool { func (s *Server) applyActionsLocked(inst *instance, actions []*protos.OrchestratorAction) { for _, action := range actions { - switch action.GetOrchestratorActionType().(type) { + switch a := action.GetOrchestratorActionType().(type) { case *protos.OrchestratorAction_ScheduleTask, *protos.OrchestratorAction_CreateTimer, *protos.OrchestratorAction_CreateSubOrchestration, *protos.OrchestratorAction_SendEvent, *protos.OrchestratorAction_TerminateOrchestration, - *protos.OrchestratorAction_SendEntityMessage, *protos.OrchestratorAction_CompleteOrchestration: + case *protos.OrchestratorAction_SendEntityMessage: + if err := validateEntityMessage(a.SendEntityMessage); err != nil { + failure := failureDetails("InvalidEntityMessage", "%v", err) + failure.IsNonRetriable = true + s.failLocked(inst, failure) + return + } default: s.failUnsupportedLocked(inst, "orchestrator action %T is not supported by the in-memory test backend", action.GetOrchestratorActionType()) From 24b189ae27d882501d02ec5c578a741aa15a631e Mon Sep 17 00:00:00 2001 From: Andy Staples Date: Mon, 23 Nov 2026 17:01:35 -0700 Subject: [PATCH 10/12] Reject entity signals that don't fit with the entity's state SignalEntity now returns InvalidArgument when a signal's input and the entity's current state can't fit together in an entity work item, using the same sizing as dispatch. Signals rejected at dispatch time, such as scheduled signals or signals from orchestrations and entities, are no longer dropped silently: the in-memory service logs a warning with the entity ID, operation, and sizes through the durabletasktest host logger. Document the combined state and input limit. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- README.md | 6 ++ durabletasktest/entity_test.go | 90 ++++++++++++++++++++++++++++ durabletasktest/host.go | 13 +++- internal/inmemory/entity.go | 100 ++++++++++++++++++++++--------- internal/inmemory/entity_test.go | 13 +++- internal/inmemory/server.go | 20 ++++++- 6 files changed, 209 insertions(+), 33 deletions(-) diff --git a/README.md b/README.md index 24268c57..11a75f01 100644 --- a/README.md +++ b/README.md @@ -669,6 +669,12 @@ The in-memory service has these limits: can advance timers without waiting in real time while the test goroutines are blocked. The `durabletasktest` tests include a 24-hour timer example. - State is kept in memory only. It is discarded when the host closes. +- An entity operation's input and the entity's state must fit together in a + 4 MiB work item. `SignalEntity` returns an error wrapping + `api.ErrInvalidArgument` if a signal doesn't fit with the entity's current + state. Operations that don't fit when they're dispatched, such as scheduled + signals or signals sent after the state grew, are rejected: calls fail, and + signals are dropped with a warning logged through `durabletasktest.WithLogger`. ## Development diff --git a/durabletasktest/entity_test.go b/durabletasktest/entity_test.go index 32a7b533..96d17d1e 100644 --- a/durabletasktest/entity_test.go +++ b/durabletasktest/entity_test.go @@ -1,7 +1,10 @@ package durabletasktest_test import ( + "bytes" "errors" + "log/slog" + "strings" "sync" "sync/atomic" "testing" @@ -415,3 +418,90 @@ func TestRewindKeepsEntityResults(t *testing.T) { assert.Equal(t, "1", completed.SerializedOutput) assert.Equal(t, 1, counterValue(t, host, "rewind")) } + +// blob is an entity whose state is the input of its last "set" operation. Its +// "send" operation signals the blob entity named by the input to set a 2 MiB value. +func blob(ctx *task.EntityContext) (any, error) { + var value string + if err := ctx.GetInput(&value); err != nil { + return nil, err + } + if ctx.Operation == "send" { + return nil, ctx.SignalEntity(api.NewEntityID("blob", value), "set", strings.Repeat("x", 2<<20)) + } + return nil, ctx.SetState(value) +} + +func newBlobHost(t *testing.T, opts ...durabletasktest.Option) *durabletasktest.Host { + t.Helper() + r := task.NewTaskRegistry() + require.NoError(t, r.AddEntityN("blob", blob)) + return durabletasktest.New(t, r, opts...) +} + +func waitForBlob(t *testing.T, host *durabletasktest.Host, id api.EntityID, want string) { + t.Helper() + require.Eventually(t, func() bool { + metadata, err := host.Client().GetEntity(testContext(t), id) + require.NoError(t, err) + var value string + return metadata != nil && metadata.ReadState(&value) == nil && value == want + }, 10*time.Second, 10*time.Millisecond, "entity %v never reached the expected state", id) +} + +func TestSignalEntityRejectsSignalThatDoesNotFitWithState(t *testing.T) { + host := newBlobHost(t) + c := host.Client() + ctx := testContext(t) + id := api.NewEntityID("blob", "a") + + state := strings.Repeat("s", 3<<20) + require.NoError(t, c.SignalEntity(ctx, id, "set", api.WithSignalInput(state))) + waitForBlob(t, host, id, state) + + err := c.SignalEntity(ctx, id, "set", api.WithSignalInput(strings.Repeat("x", 2<<20))) + require.ErrorIs(t, err, api.ErrInvalidArgument) + assert.ErrorContains(t, err, "exceeds the 4194304-byte entity work item limit") + + require.NoError(t, c.SignalEntity(ctx, id, "set", api.WithSignalInput("small"))) + waitForBlob(t, host, id, "small") +} + +// lockedBuffer is a bytes.Buffer that is safe for concurrent use. +type lockedBuffer struct { + mu sync.Mutex + buf bytes.Buffer +} + +func (b *lockedBuffer) Write(p []byte) (int, error) { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.Write(p) +} + +func (b *lockedBuffer) String() string { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.String() +} + +func TestDroppedEntitySignalIsLogged(t *testing.T) { + var logs lockedBuffer + host := newBlobHost(t, durabletasktest.WithLogger(api.NewSlogLogger(slog.New(slog.NewTextHandler(&logs, nil))))) + c := host.Client() + ctx := testContext(t) + id := api.NewEntityID("blob", "a") + + state := strings.Repeat("s", 3<<20) + require.NoError(t, c.SignalEntity(ctx, id, "set", api.WithSignalInput(state))) + waitForBlob(t, host, id, state) + + // A signal from another entity can only be checked when it's dispatched. + require.NoError(t, c.SignalEntity(ctx, api.NewEntityID("blob", "sender"), "send", api.WithSignalInput("a"))) + require.Eventually(t, func() bool { return strings.Contains(logs.String(), "dropped entity signal") }, + 10*time.Second, 10*time.Millisecond) + assert.Contains(t, logs.String(), `operation \"set\" on entity \"@blob@a\" has a 2097154-byte input`) + + require.NoError(t, c.SignalEntity(ctx, id, "set", api.WithSignalInput("small"))) + waitForBlob(t, host, id, "small") +} diff --git a/durabletasktest/host.go b/durabletasktest/host.go index 276f36ea..0935e3ff 100644 --- a/durabletasktest/host.go +++ b/durabletasktest/host.go @@ -29,6 +29,12 @@ // Durable entities are supported, including entity critical sections: // signals and calls to a locked entity from outside its critical section wait // until the lock is released. +// An entity operation is dispatched in a work item with the entity's state, so +// an operation's input and the entity's state must fit together in a 4 MiB +// work item. +// SignalEntity returns an error wrapping [api.ErrInvalidArgument] if a signal +// doesn't fit with the entity's current state. Calls that don't fit when they +// are dispatched fail; signals are dropped, and the host logs a warning. package durabletasktest import ( @@ -65,8 +71,9 @@ type options struct { clientOptions []client.TaskHubGrpcClientOption } -// WithLogger sets the logger used by the worker and client. By default, the -// host discards log output. +// WithLogger sets the logger used by the worker, client, and in-memory +// service. The service logs a warning when it drops an entity signal. By +// default, the host discards log output. func WithLogger(logger api.Logger) Option { return func(o *options) { o.logger = logger } } @@ -128,7 +135,7 @@ func NewHost(ctx context.Context, registry *task.TaskRegistry, opts ...Option) ( } h := &Host{ - backend: inmemory.NewServer(), + backend: inmemory.NewServer(inmemory.WithLogger(o.logger)), server: grpc.NewServer(), listener: bufconn.Listen(bufferSize), } diff --git a/internal/inmemory/entity.go b/internal/inmemory/entity.go index 8cd160b1..f6f4bcda 100644 --- a/internal/inmemory/entity.go +++ b/internal/inmemory/entity.go @@ -84,14 +84,19 @@ func (s *Server) deliverEntityLocked(targetID string, event *protos.HistoryEvent s.pumpEntityLocked(e) } -// signalEntityLocked delivers a signal now or, if it is scheduled for later, when it is due. -func (s *Server) signalEntityLocked(targetID string, signal *protos.EntityOperationSignaledEvent) { - event := &protos.HistoryEvent{ +// newSignalEvent returns the message that delivers a signal to an entity. +func newSignalEvent(signal *protos.EntityOperationSignaledEvent) *protos.HistoryEvent { + return &protos.HistoryEvent{ EventId: -1, Timestamp: timestamppb.Now(), EventType: &protos.HistoryEvent_EntityOperationSignaled{EntityOperationSignaled: signal}, } - if at := signal.GetScheduledTime(); at != nil && at.AsTime().After(time.Now()) { +} + +// signalEntityLocked delivers a signal message now or, if it is scheduled for +// later, when it is due. +func (s *Server) signalEntityLocked(targetID string, event *protos.HistoryEvent) { + if at := event.GetEntityOperationSignaled().GetScheduledTime(); at != nil && at.AsTime().After(time.Now()) { s.startServerTimerLocked(at.AsTime(), func() { s.deliverEntityLocked(targetID, event) }) return } @@ -225,12 +230,13 @@ func (s *Server) lockRequestActiveLocked(request *protos.EntityLockRequestedEven // takeBatch removes the signals and calls that are ready to run, stopping at // the next lock or unlock message or at the first operation that would make // the work item larger than maxBytes; that operation stays queued for the next -// batch. An operation that can't fit even in an otherwise empty work item is -// removed and returned in rejected so that it can't stall the entity. +// batch. An operation that can't fit even in a work item with no other +// operations is removed and returned in rejected so that it can't stall the +// entity. baseSize is the work item's size before operations are added, as +// returned by entityWorkItemBaseSize. func (e *entity) takeBatch(baseSize, maxBytes int) (batch, rejected []*protos.HistoryEvent) { var kept []*protos.HistoryEvent - // Adding operations can lengthen the EntityRequest and WorkItem length prefixes. - size := baseSize + 2*binary.MaxVarintLen32 + size := baseSize stop := len(e.queue) for i, event := range e.queue { if !e.canProcess(event) { @@ -260,24 +266,58 @@ func (e *entity) takeBatch(baseSize, maxBytes int) (batch, rejected []*protos.Hi } // rejectOversizedOperationsLocked fails calls whose request can't fit in an -// entity work item. Oversized signals are dropped. -func (s *Server) rejectOversizedOperationsLocked(e *entity, events []*protos.HistoryEvent) { +// entity work item with the entity's state, and logs a warning for each such +// signal, which has no caller to notify. baseSize is the size of the entity's +// work item before operations are added. +func (s *Server) rejectOversizedOperationsLocked(e *entity, events []*protos.HistoryEvent, baseSize int) { for _, event := range events { + message := s.oversizedOperationMessage(e.id, e.state, event, baseSize) called := event.GetEntityOperationCalled() if called == nil { + s.logger.Warnf("in-memory durable task service dropped entity signal %s: %s", + event.GetEntityOperationSignaled().GetRequestId(), message) continue } s.respondToCallerLocked(called, &protos.HistoryEvent{EventId: -1, Timestamp: timestamppb.Now(), EventType: &protos.HistoryEvent_EntityOperationFailed{ EntityOperationFailed: &protos.EntityOperationFailedEvent{ - RequestId: called.GetRequestId(), - FailureDetails: failureDetails("EntityOperationTooLarge", - "operation %q on entity %q exceeds the %d-byte entity work item limit", - called.GetOperation(), e.id, s.maxEntityWorkItemBytes), + RequestId: called.GetRequestId(), + FailureDetails: failureDetails("EntityOperationTooLarge", "%s", message), }, }}) } } +// newEntityWorkItem returns a work item for an entity with no operations. +func newEntityWorkItem(entityID string, state *wrapperspb.StringValue, token string) *protos.WorkItem { + return &protos.WorkItem{ + Request: &protos.WorkItem_EntityRequestV2{EntityRequestV2: &protos.EntityRequest{ + InstanceId: entityID, + EntityState: state, + }}, + CompletionToken: token, + } +} + +// entityWorkItemBaseSize returns the size of an entity work item with no +// operations, plus room for its EntityRequest and WorkItem length prefixes to +// lengthen as operations are added. +func entityWorkItemBaseSize(item *protos.WorkItem) int { + return proto.Size(item) + 2*binary.MaxVarintLen32 +} + +// oversizedOperationMessage describes an operation that can't fit in an entity +// work item with the entity's state. +func (s *Server) oversizedOperationMessage(entityID string, state *wrapperspb.StringValue, event *protos.HistoryEvent, baseSize int) string { + operation, input := event.GetEntityOperationSignaled().GetOperation(), event.GetEntityOperationSignaled().GetInput() + if called := event.GetEntityOperationCalled(); called != nil { + operation, input = called.GetOperation(), called.GetInput() + } + return fmt.Sprintf("operation %q on entity %q has a %d-byte input and the entity has %d bytes of state; "+ + "together they need a %d-byte work item, which exceeds the %d-byte entity work item limit", + operation, entityID, len(input.GetValue()), len(state.GetValue()), + baseSize+operationRequestSize(event), s.maxEntityWorkItemBytes) +} + // operationRequestSize returns the bytes an operation adds to an EntityRequest. func operationRequestSize(event *protos.HistoryEvent) int { const field = 4 // EntityRequest.operationRequests @@ -295,15 +335,10 @@ func (s *Server) nextEntityWorkItemLocked(filters *protos.WorkItemFilters, strea return s.nextEntityWorkItemLocked(filters, streamID) } token := newID() - item := &protos.WorkItem{ - Request: &protos.WorkItem_EntityRequestV2{EntityRequestV2: &protos.EntityRequest{ - InstanceId: e.id, - EntityState: e.state, - }}, - CompletionToken: token, - } - events, rejected := e.takeBatch(proto.Size(item), s.maxEntityWorkItemBytes) - s.rejectOversizedOperationsLocked(e, rejected) + item := newEntityWorkItem(e.id, e.state, token) + baseSize := entityWorkItemBaseSize(item) + events, rejected := e.takeBatch(baseSize, s.maxEntityWorkItemBytes) + s.rejectOversizedOperationsLocked(e, rejected, baseSize) if len(events) == 0 { // Rejecting operations can leave a lock or unlock message ready. s.pumpEntityLocked(e) @@ -412,12 +447,12 @@ func (s *Server) CompleteEntityTask(_ context.Context, result *protos.EntityBatc switch a := action.GetOperationActionType().(type) { case *protos.OperationAction_SendSignal: signal := a.SendSignal - s.signalEntityLocked(signal.GetInstanceId(), &protos.EntityOperationSignaledEvent{ + s.signalEntityLocked(signal.GetInstanceId(), newSignalEvent(&protos.EntityOperationSignaledEvent{ RequestId: newID(), Operation: signal.GetName(), Input: signal.GetInput(), ScheduledTime: signal.GetScheduledTime(), - }) + })) case *protos.OperationAction_StartNewOrchestration: start := a.StartNewOrchestration id := start.GetInstanceId() @@ -542,7 +577,7 @@ func (s *Server) sendEntityMessageLocked(inst *instance, id int32, action *proto inst.history = append(inst.history, event) signal := proto.CloneOf(m.EntityOperationSignaled) signal.TargetInstanceId = nil - s.signalEntityLocked(m.EntityOperationSignaled.GetTargetInstanceId().GetValue(), signal) + s.signalEntityLocked(m.EntityOperationSignaled.GetTargetInstanceId().GetValue(), newSignalEvent(signal)) case *protos.SendEntityMessageAction_EntityOperationCalled: event.EventType = &protos.HistoryEvent_EntityOperationCalled{EntityOperationCalled: m.EntityOperationCalled} inst.history = append(inst.history, event) @@ -608,12 +643,23 @@ func (s *Server) SignalEntity(_ context.Context, req *protos.SignalEntityRequest } s.mu.Lock() defer s.mu.Unlock() - s.signalEntityLocked(id, &protos.EntityOperationSignaledEvent{ + event := newSignalEvent(&protos.EntityOperationSignaledEvent{ RequestId: requestID, Operation: req.GetName(), Input: req.GetInput(), ScheduledTime: req.GetScheduledTime(), }) + // Reject a signal that can't be dispatched with the entity's current state. + // The work item's completion token is a UUID, like every other token. + var state *wrapperspb.StringValue + if e, ok := s.entities[id]; ok { + state = e.state + } + baseSize := entityWorkItemBaseSize(newEntityWorkItem(id, state, newID())) + if baseSize+operationRequestSize(event) > s.maxEntityWorkItemBytes { + return nil, status.Error(codes.InvalidArgument, s.oversizedOperationMessage(id, state, event, baseSize)) + } + s.signalEntityLocked(id, event) return &protos.SignalEntityResponse{}, nil } diff --git a/internal/inmemory/entity_test.go b/internal/inmemory/entity_test.go index 92ac37dc..e30b84a6 100644 --- a/internal/inmemory/entity_test.go +++ b/internal/inmemory/entity_test.go @@ -1,7 +1,9 @@ package inmemory import ( + "bytes" "context" + "log/slog" "strconv" "strings" "testing" @@ -16,6 +18,7 @@ import ( "google.golang.org/protobuf/types/known/timestamppb" "google.golang.org/protobuf/types/known/wrapperspb" + "github.com/microsoft/durabletask-go/api" "github.com/microsoft/durabletask-go/internal/helpers" "github.com/microsoft/durabletask-go/internal/protos" ) @@ -347,7 +350,8 @@ func TestEntityWorkItemsAreBoundedBySize(t *testing.T) { } func TestOversizedEntityOperationsAreRejected(t *testing.T) { - s := NewServer() + var logs bytes.Buffer + s := NewServer(WithLogger(api.NewSlogLogger(slog.New(slog.NewTextHandler(&logs, nil))))) defer s.Close() s.mu.Lock() defer s.mu.Unlock() @@ -388,6 +392,13 @@ func TestOversizedEntityOperationsAreRejected(t *testing.T) { require.NotNil(t, failed, "the oversized call fails instead of being dispatched") assert.Equal(t, "call-1", failed.GetRequestId()) assert.Equal(t, "EntityOperationTooLarge", failed.GetFailureDetails().GetErrorType()) + + log := logs.String() + assert.Contains(t, log, "level=WARN", "the dropped signal is logged") + assert.Contains(t, log, "dropped entity signal "+oversized.GetEntityOperationSignaled().GetRequestId()) + assert.Contains(t, log, `operation \"oversized\" on entity \"@counter@a\" has a 600-byte input and the entity has 600 bytes of state`) + assert.Contains(t, log, "exceeds the 1024-byte entity work item limit") + assert.NotContains(t, log, "oversizedCall", "calls fail instead of being logged") } func TestReleaseStreamRequeuesEntityWorkItems(t *testing.T) { diff --git a/internal/inmemory/server.go b/internal/inmemory/server.go index 1117edf9..77e944b6 100644 --- a/internal/inmemory/server.go +++ b/internal/inmemory/server.go @@ -9,6 +9,7 @@ package inmemory import ( "context" "fmt" + "log/slog" "slices" "sync" "time" @@ -46,6 +47,7 @@ type Server struct { healthPingInterval time.Duration maxEntityWorkItemBytes int + logger api.Logger mu sync.Mutex instances map[string]*instance @@ -118,11 +120,21 @@ type activityLease struct { streamID uint64 } +// ServerOption configures a [Server]. +type ServerOption func(*Server) + +// WithLogger sets the logger the service uses to report messages that it +// drops. By default, the service discards log output. +func WithLogger(logger api.Logger) ServerOption { + return func(s *Server) { s.logger = logger } +} + // NewServer creates an empty in-memory service. -func NewServer() *Server { - return &Server{ +func NewServer(opts ...ServerOption) *Server { + s := &Server{ healthPingInterval: defaultHealthPingInterval, maxEntityWorkItemBytes: defaultMaxEntityWorkItemBytes, + logger: api.NewSlogLogger(slog.New(slog.DiscardHandler)), instances: make(map[string]*instance), orchLeases: make(map[string]*orchestrationLease), actLeases: make(map[string]*activityLease), @@ -131,6 +143,10 @@ func NewServer() *Server { lockRequests: make(map[string]string), changed: make(chan struct{}), } + for _, configure := range opts { + configure(s) + } + return s } // Register registers the service with a gRPC server. From 67d21ca2b413e2bc38313a09afde74bd65074f54 Mon Sep 17 00:00:00 2001 From: Andy Staples Date: Mon, 23 Nov 2026 17:15:54 -0700 Subject: [PATCH 11/12] Fail entity batches whose result exceeds the message limit The worker abandons an entity completion that the service rejects for size, so the service rebuilt and re-ran the same batch indefinitely. CompleteEntityTask now checks the batch result size itself: a result over 4 MiB isn't applied, the entity's state is unchanged, each call in the batch fails with the non-retriable error type EntityResultTooLarge, and each signal is logged as dropped. The operations run once. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- CHANGELOG.md | 2 +- README.md | 2 +- durabletasktest/entity_test.go | 54 ++++++++++++++++++++++++++++++++++ durabletasktest/host.go | 2 ++ internal/inmemory/entity.go | 26 +++++++++++++--- internal/inmemory/limits.go | 5 ++++ internal/inmemory/server.go | 5 ++-- 7 files changed, 87 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6f1f0767..869c9f73 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, activities, and entities 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, history, and durable entities, including scheduled signals, entity critical sections, and entity query and cleanup. 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. Like DTS, the service limits requests and completions to 4 MiB; an activity completion over 4 MiB fails once with the non-retriable error type `ActivityResponseTooLarge`. +- Added the `durabletasktest` package, which runs orchestrations, activities, and entities 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, history, and durable entities, including scheduled signals, entity critical sections, and entity query and cleanup. 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. Like DTS, the service limits requests and completions to 4 MiB; an activity completion over 4 MiB fails once with the non-retriable error type `ActivityResponseTooLarge`, and an entity batch result over 4 MiB isn't applied and fails its calls with the non-retriable error type `EntityResultTooLarge`. - 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 2cdf01b4..cabb808d 100644 --- a/README.md +++ b/README.md @@ -670,7 +670,7 @@ The in-memory service has these limits: blocked. The `durabletasktest` tests include a 24-hour timer example. - The service has no task hub name, so an instance query filtered by `TaskHubNames` returns `api.ErrFeatureNotSupported`. - State is kept in memory only. It is discarded when the host closes. -- Requests and worker completions are limited to 4 MiB, as in DTS. Larger client requests fail with `ResourceExhausted`. An activity whose completion is larger fails once with the non-retriable error type `ActivityResponseTooLarge` instead of running again. +- Requests and worker completions are limited to 4 MiB, as in DTS. Larger client requests fail with `ResourceExhausted`. An activity whose completion is larger fails once with the non-retriable error type `ActivityResponseTooLarge` instead of running again. An entity batch whose result is larger isn't applied: the entity's state is unchanged, its calls fail with the non-retriable error type `EntityResultTooLarge`, and its signals are dropped with a warning. - An entity operation's input and the entity's state must fit together in a 4 MiB work item. `SignalEntity` returns an error wrapping `api.ErrInvalidArgument` if a signal doesn't fit with the entity's current diff --git a/durabletasktest/entity_test.go b/durabletasktest/entity_test.go index 96d17d1e..8739286e 100644 --- a/durabletasktest/entity_test.go +++ b/durabletasktest/entity_test.go @@ -3,6 +3,7 @@ package durabletasktest_test import ( "bytes" "errors" + "fmt" "log/slog" "strings" "sync" @@ -505,3 +506,56 @@ func TestDroppedEntitySignalIsLogged(t *testing.T) { require.NoError(t, c.SignalEntity(ctx, id, "set", api.WithSignalInput("small"))) waitForBlob(t, host, id, "small") } + +func TestOversizedEntityBatchResultFailsCalls(t *testing.T) { + var executions atomic.Int32 + r := task.NewTaskRegistry() + require.NoError(t, r.AddEntityN("large", func(ctx *task.EntityContext) (any, error) { + executions.Add(1) + if err := ctx.SetState(executions.Load()); err != nil { + return nil, err + } + return strings.Repeat("x", 1<<20), nil + })) + id := api.NewEntityID("large", "a") + require.NoError(t, r.AddOrchestratorN("CallsLarge", func(ctx *task.OrchestrationContext) (any, error) { + // The messages are queued together, so the entity runs them in one batch + // whose combined result exceeds the message limit. + if err := ctx.SignalEntity(id, "get"); err != nil { + return nil, err + } + var calls []task.Task + for range 5 { + calls = append(calls, ctx.CallEntity(id, "get")) + } + var failures []*api.FailureDetails + for _, call := range calls { + var failed *task.EntityOperationFailedError + if err := call.Await(nil); !errors.As(err, &failed) { + return nil, fmt.Errorf("expected an entity operation failure, got %w", err) + } + failures = append(failures, failed.FailureDetails) + } + return failures, nil + })) + var logs lockedBuffer + host := durabletasktest.New(t, r, durabletasktest.WithLogger(api.NewSlogLogger(slog.New(slog.NewTextHandler(&logs, nil))))) + + metadata := run(t, host, "CallsLarge") + require.Equal(t, api.RUNTIME_STATUS_COMPLETED, metadata.RuntimeStatus) + var failures []api.FailureDetails + require.NoError(t, metadata.ReadOutput(&failures)) + require.Len(t, failures, 5) + for _, failure := range failures { + assert.Equal(t, api.ErrorType("EntityResultTooLarge"), failure.ErrorType) + assert.Contains(t, failure.ErrorMessage, "4194304-byte") + assert.True(t, failure.NonRetriable()) + } + assert.Equal(t, int32(6), executions.Load(), "each operation runs once") + assert.Contains(t, logs.String(), `dropped entity signal`) + assert.Contains(t, logs.String(), `operation \"get\" on entity \"@large@a\": the `) + + entity, err := host.Client().GetEntity(testContext(t), id) + require.NoError(t, err) + assert.Nil(t, entity, "the failed batch doesn't store state") +} diff --git a/durabletasktest/host.go b/durabletasktest/host.go index 4ddf4ae6..683a4f1c 100644 --- a/durabletasktest/host.go +++ b/durabletasktest/host.go @@ -35,6 +35,8 @@ // SignalEntity returns an error wrapping [api.ErrInvalidArgument] if a signal // doesn't fit with the entity's current state. Calls that don't fit when they // are dispatched fail; signals are dropped, and the host logs a warning. +// An entity batch whose result exceeds 4 MiB isn't applied, and its calls fail +// with the non-retriable error type EntityResultTooLarge. package durabletasktest import ( diff --git a/internal/inmemory/entity.go b/internal/inmemory/entity.go index f6f4bcda..8d09988f 100644 --- a/internal/inmemory/entity.go +++ b/internal/inmemory/entity.go @@ -274,8 +274,7 @@ func (s *Server) rejectOversizedOperationsLocked(e *entity, events []*protos.His message := s.oversizedOperationMessage(e.id, e.state, event, baseSize) called := event.GetEntityOperationCalled() if called == nil { - s.logger.Warnf("in-memory durable task service dropped entity signal %s: %s", - event.GetEntityOperationSignaled().GetRequestId(), message) + s.reportDroppedSignalLocked(event.GetEntityOperationSignaled(), message) continue } s.respondToCallerLocked(called, &protos.HistoryEvent{EventId: -1, Timestamp: timestamppb.Now(), EventType: &protos.HistoryEvent_EntityOperationFailed{ @@ -287,6 +286,12 @@ func (s *Server) rejectOversizedOperationsLocked(e *entity, events []*protos.His } } +// reportDroppedSignalLocked logs a warning for an entity signal that the +// service drops, which has no caller to notify. +func (s *Server) reportDroppedSignalLocked(signal *protos.EntityOperationSignaledEvent, reason string) { + s.logger.Warnf("in-memory durable task service dropped entity signal %s: %s", signal.GetRequestId(), reason) +} + // newEntityWorkItem returns a work item for an entity with no operations. func newEntityWorkItem(entityID string, state *wrapperspb.StringValue, token string) *protos.WorkItem { return &protos.WorkItem{ @@ -385,7 +390,9 @@ func (s *Server) AbandonTaskEntityWorkItem( } // CompleteEntityTask commits an entity batch: it stores the new state, sends -// results to calling orchestrations, and applies the batch's actions. +// results to calling orchestrations, and applies the batch's actions. A batch +// result larger than the message limit isn't applied; its calls fail with +// EntityResultTooLarge instead. func (s *Server) CompleteEntityTask(_ context.Context, result *protos.EntityBatchResult) (*protos.CompleteTaskResponse, error) { s.mu.Lock() defer s.mu.Unlock() @@ -397,7 +404,18 @@ func (s *Server) CompleteEntityTask(_ context.Context, result *protos.EntityBatc e := lease.entity e.leased = false - if batchFailure := result.GetFailureDetails(); batchFailure != nil { + batchFailure := result.GetFailureDetails() + if failure := oversizedCompletionFailure(errorTypeEntityResultTooLarge, "entity batch result", result); failure != nil { + // Fail the batch rather than store a result over the receive limit. + batchFailure = failure + for _, event := range lease.events { + if signal := event.GetEntityOperationSignaled(); signal != nil { + s.reportDroppedSignalLocked(signal, fmt.Sprintf("operation %q on entity %q: %s", + signal.GetOperation(), e.id, failure.GetErrorMessage())) + } + } + } + if batchFailure != nil { // The batch had no effect. Fail its calls rather than retrying the batch // so that a persistent failure can't loop forever in a test. for _, event := range lease.events { diff --git a/internal/inmemory/limits.go b/internal/inmemory/limits.go index 53b1062d..016c583b 100644 --- a/internal/inmemory/limits.go +++ b/internal/inmemory/limits.go @@ -21,11 +21,16 @@ const maxMessageSize = 4 << 20 // exceeded maxMessageSize. const errorTypeActivityResponseTooLarge = "ActivityResponseTooLarge" +// errorTypeEntityResultTooLarge identifies an entity batch whose completion +// exceeded maxMessageSize. +const errorTypeEntityResultTooLarge = "EntityResultTooLarge" + // selfLimitedMethods check their request size themselves. They fail the work // item instead of rejecting the call, because a worker abandons a work item // whose completion is rejected and the service would dispatch it again forever. var selfLimitedMethods = map[string]bool{ protos.TaskHubSidecarService_CompleteActivityTask_FullMethodName: true, + protos.TaskHubSidecarService_CompleteEntityTask_FullMethodName: true, } // ServerOptions returns the gRPC server options for the service. The transport diff --git a/internal/inmemory/server.go b/internal/inmemory/server.go index 1101bcfe..5fb17d14 100644 --- a/internal/inmemory/server.go +++ b/internal/inmemory/server.go @@ -36,9 +36,8 @@ const ( maxOrchestrationWorkItemSize = 4 << 20 maxHistoryChunkSize = 4 << 20 - // defaultMaxEntityWorkItemBytes matches gRPC's default client receive - // limit, which the test host's worker uses. - defaultMaxEntityWorkItemBytes = 4 << 20 + // defaultMaxEntityWorkItemBytes matches the 4 MiB message limit of DTS. + defaultMaxEntityWorkItemBytes = maxMessageSize ) // Server is an in-memory implementation of the TaskHubSidecarService. From 7694d97361e11b3545fccf502caaeb65f5bdec53 Mon Sep 17 00:00:00 2001 From: Andy Staples Date: Mon, 23 Nov 2026 17:18:14 -0700 Subject: [PATCH 12/12] Report dropped entity signals in the test log A host created with durabletasktest.New now also reports each entity signal that the in-memory service drops with testing.TB.Log, so drops show up when a test fails or runs with -v even if the test doesn't set WithLogger. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- README.md | 3 ++- durabletasktest/entity_test.go | 22 ++++++++++++++++++---- durabletasktest/host.go | 21 ++++++++++++++------- internal/inmemory/entity.go | 16 ++++++++++++++-- internal/inmemory/server.go | 1 + 5 files changed, 49 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index cabb808d..6a873c9f 100644 --- a/README.md +++ b/README.md @@ -676,7 +676,8 @@ The in-memory service has these limits: `api.ErrInvalidArgument` if a signal doesn't fit with the entity's current state. Operations that don't fit when they're dispatched, such as scheduled signals or signals sent after the state grew, are rejected: calls fail, and - signals are dropped with a warning logged through `durabletasktest.WithLogger`. + signals are dropped with a warning logged through `durabletasktest.WithLogger` + and, for a host created with `durabletasktest.New`, the test log. ## Development diff --git a/durabletasktest/entity_test.go b/durabletasktest/entity_test.go index 8739286e..fd7fd096 100644 --- a/durabletasktest/entity_test.go +++ b/durabletasktest/entity_test.go @@ -433,7 +433,7 @@ func blob(ctx *task.EntityContext) (any, error) { return nil, ctx.SetState(value) } -func newBlobHost(t *testing.T, opts ...durabletasktest.Option) *durabletasktest.Host { +func newBlobHost(t testing.TB, opts ...durabletasktest.Option) *durabletasktest.Host { t.Helper() r := task.NewTaskRegistry() require.NoError(t, r.AddEntityN("blob", blob)) @@ -486,9 +486,21 @@ func (b *lockedBuffer) String() string { return b.buf.String() } +// logRecorder records the messages that a test logs with Log. +type logRecorder struct { + testing.TB + logs lockedBuffer +} + +func (r *logRecorder) Log(args ...any) { + _, _ = fmt.Fprintln(&r.logs, args...) + r.TB.Log(args...) +} + func TestDroppedEntitySignalIsLogged(t *testing.T) { var logs lockedBuffer - host := newBlobHost(t, durabletasktest.WithLogger(api.NewSlogLogger(slog.New(slog.NewTextHandler(&logs, nil))))) + recorder := &logRecorder{TB: t} + host := newBlobHost(recorder, durabletasktest.WithLogger(api.NewSlogLogger(slog.New(slog.NewTextHandler(&logs, nil))))) c := host.Client() ctx := testContext(t) id := api.NewEntityID("blob", "a") @@ -499,8 +511,10 @@ func TestDroppedEntitySignalIsLogged(t *testing.T) { // A signal from another entity can only be checked when it's dispatched. require.NoError(t, c.SignalEntity(ctx, api.NewEntityID("blob", "sender"), "send", api.WithSignalInput("a"))) - require.Eventually(t, func() bool { return strings.Contains(logs.String(), "dropped entity signal") }, - 10*time.Second, 10*time.Millisecond) + // The service logs the warning before it reports it to the test log. + require.Eventually(t, func() bool { return strings.Contains(recorder.logs.String(), "dropped entity signal") }, + 10*time.Second, 10*time.Millisecond, "New reports the dropped signal in the test log") + assert.Contains(t, recorder.logs.String(), `operation "set" on entity "@blob@a" has a 2097154-byte input`) assert.Contains(t, logs.String(), `operation \"set\" on entity \"@blob@a\" has a 2097154-byte input`) require.NoError(t, c.SignalEntity(ctx, id, "set", api.WithSignalInput("small"))) diff --git a/durabletasktest/host.go b/durabletasktest/host.go index 683a4f1c..8cc500e1 100644 --- a/durabletasktest/host.go +++ b/durabletasktest/host.go @@ -34,7 +34,8 @@ // work item. // SignalEntity returns an error wrapping [api.ErrInvalidArgument] if a signal // doesn't fit with the entity's current state. Calls that don't fit when they -// are dispatched fail; signals are dropped, and the host logs a warning. +// are dispatched fail; signals are dropped, and the host logs a warning, which +// [New] also reports with [testing.TB.Log]. // An entity batch whose result exceeds 4 MiB isn't applied, and its calls fail // with the non-retriable error type EntityResultTooLarge. package durabletasktest @@ -72,9 +73,10 @@ const maxReceiveMessageSize = 64 << 20 type Option func(*options) type options struct { - logger api.Logger - workerOptions []client.TaskHubGrpcWorkerOption - clientOptions []client.TaskHubGrpcClientOption + logger api.Logger + workerOptions []client.TaskHubGrpcWorkerOption + clientOptions []client.TaskHubGrpcClientOption + reportDroppedSignal func(message string) } // WithLogger sets the logger used by the worker, client, and in-memory @@ -106,10 +108,14 @@ type Host struct { } // New starts a [Host] for a test and closes it when the test and its subtests finish. -// It stops the test with [testing.TB.Fatal] if the host can't start. +// It stops the test with [testing.TB.Fatal] if the host can't start. The host +// also reports entity signals that the service drops with [testing.TB.Log]. func New(tb testing.TB, registry *task.TaskRegistry, opts ...Option) *Host { tb.Helper() - host, err := NewHost(tb.Context(), registry, opts...) + logDroppedSignals := func(o *options) { + o.reportDroppedSignal = func(message string) { tb.Log(message) } + } + host, err := NewHost(tb.Context(), registry, append([]Option{logDroppedSignals}, opts...)...) if err != nil { tb.Fatalf("failed to start durable task test host: %v", err) } @@ -141,7 +147,8 @@ func NewHost(ctx context.Context, registry *task.TaskRegistry, opts ...Option) ( } h := &Host{ - backend: inmemory.NewServer(inmemory.WithLogger(o.logger)), + backend: inmemory.NewServer(inmemory.WithLogger(o.logger), + inmemory.WithDroppedSignalReporter(o.reportDroppedSignal)), server: grpc.NewServer(inmemory.ServerOptions()...), listener: bufconn.Listen(bufferSize), } diff --git a/internal/inmemory/entity.go b/internal/inmemory/entity.go index 8d09988f..8c3570cc 100644 --- a/internal/inmemory/entity.go +++ b/internal/inmemory/entity.go @@ -287,9 +287,21 @@ func (s *Server) rejectOversizedOperationsLocked(e *entity, events []*protos.His } // reportDroppedSignalLocked logs a warning for an entity signal that the -// service drops, which has no caller to notify. +// service drops, which has no caller to notify, and passes the warning to the +// dropped-signal reporter, if any. func (s *Server) reportDroppedSignalLocked(signal *protos.EntityOperationSignaledEvent, reason string) { - s.logger.Warnf("in-memory durable task service dropped entity signal %s: %s", signal.GetRequestId(), reason) + message := fmt.Sprintf("in-memory durable task service dropped entity signal %s: %s", signal.GetRequestId(), reason) + s.logger.Warn(message) + if s.reportDroppedSignal != nil && !s.closed { + s.reportDroppedSignal(message) + } +} + +// WithDroppedSignalReporter sets a function that also receives the warning for +// each entity signal that the service drops. The service calls it with its +// lock held and not after the service is closed. +func WithDroppedSignalReporter(report func(message string)) ServerOption { + return func(s *Server) { s.reportDroppedSignal = report } } // newEntityWorkItem returns a work item for an entity with no operations. diff --git a/internal/inmemory/server.go b/internal/inmemory/server.go index 5fb17d14..e73fbaf8 100644 --- a/internal/inmemory/server.go +++ b/internal/inmemory/server.go @@ -47,6 +47,7 @@ type Server struct { healthPingInterval time.Duration maxEntityWorkItemBytes int logger api.Logger + reportDroppedSignal func(message string) mu sync.Mutex instances map[string]*instance