From e367afdacfa3041a694a67e4670e98a20e41d45c Mon Sep 17 00:00:00 2001 From: effect-bot <129879685+effect-bot@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:42:04 -0500 Subject: [PATCH] fix(cluster): hand off workflow activity waits promptly during shard rebalance (#10908) Co-authored-by: Valentin Beggi <87306219+valentinbeggi@users.noreply.github.com> --- .changeset/cluster-shard-rebalance-handoff.md | 5 + .../src/cluster/ClusterWorkflowEngine.ts | 34 +++- .../src/cluster/internal/entityActivation.ts | 6 + .../src/cluster/internal/entityManager.ts | 5 +- .../cluster/ClusterWorkflowEngine.test.ts | 167 ++++++++++++++++++ 5 files changed, 211 insertions(+), 6 deletions(-) create mode 100644 .changeset/cluster-shard-rebalance-handoff.md diff --git a/.changeset/cluster-shard-rebalance-handoff.md b/.changeset/cluster-shard-rebalance-handoff.md new file mode 100644 index 0000000000..a2764785f8 --- /dev/null +++ b/.changeset/cluster-shard-rebalance-handoff.md @@ -0,0 +1,5 @@ +--- +"effect": patch +--- + +Fix cluster shard rebalancing stalling workflow activity waits until `entityTerminationTimeout` once in-flight activities complete. diff --git a/packages/effect/src/cluster/ClusterWorkflowEngine.ts b/packages/effect/src/cluster/ClusterWorkflowEngine.ts index e288eaf495..a67cbd9ac6 100644 --- a/packages/effect/src/cluster/ClusterWorkflowEngine.ts +++ b/packages/effect/src/cluster/ClusterWorkflowEngine.ts @@ -16,6 +16,7 @@ import * as Effect from "../Effect.ts" import * as Exit from "../Exit.ts" import * as Fiber from "../Fiber.ts" import * as Headers from "../http/Headers.ts" +import * as Latch from "../Latch.ts" import * as Layer from "../Layer.ts" import * as Option from "../Option.ts" import * as PrimaryKey from "../PrimaryKey.ts" @@ -40,7 +41,7 @@ import * as EntityId from "./EntityId.ts" import * as EntityType from "./EntityType.ts" import * as Envelope from "./Envelope.ts" import * as ClusterAbandon from "./internal/clusterAbandon.ts" -import { CurrentActivationScope } from "./internal/entityActivation.ts" +import { CurrentActivationScope, CurrentRetirementLatch } from "./internal/entityActivation.ts" import * as Message from "./Message.ts" import { MessageStorage } from "./MessageStorage.ts" import type { WithExitEncoded } from "./Reply.ts" @@ -471,12 +472,16 @@ export const make = Effect.gen(function*() { (decoded.exit._tag === "Success" ? decoded.exit.value : decoded.exit) as Exit.Exit ) } + const retired = Option.getOrUndefined(yield* Effect.serviceOption(CurrentRetirementLatch)) pending = { workflowName: workflow._tag, executionId, results, instances: new Set(), - scope: Scope.makeUnsafe() + scope: Scope.makeUnsafe(), + retired, + idle: Latch.makeUnsafe(true), + executing: 0 } yield* Scope.addFinalizer(activation, closeRuns(pending, true)) pendingByActivation.set(activation, pending) @@ -613,6 +618,8 @@ export const make = Effect.gen(function*() { Context.add(CurrentActivationScope, activation), Context.add(Activity.CurrentAttempt, payload.attempt) ) + pending.executing++ + pending.idle.closeUnsafe() return entry.activity.executeEncoded.pipe( Effect.provideContext(context), Workflow.intoResult, @@ -629,6 +636,9 @@ export const make = Effect.gen(function*() { ) return suspend ? Effect.succeed(new Workflow.Suspended({})) : Effect.failCause(cause) }), + Effect.ensuring(Effect.sync(() => { + if (--pending.executing === 0) pending.idle.openUnsafe() + })), Effect.provideService(WorkflowEngine.WorkflowInstance, instance), Effect.provideService(Activity.CurrentAttempt, payload.attempt), Rpc.wrap({ fork: true, uninterruptible: true }) @@ -791,14 +801,25 @@ export const make = Effect.gen(function*() { if (activities.get(activityId) === entry) activities.delete(activityId) }) ) + const activation = yield* Effect.serviceOption(CurrentActivationScope) + const pending = Option.isSome(activation) ? pendingByActivation.get(activation.value) : undefined + const handoff = pending?.retired && + pending.workflowName === instance.workflow._tag && + pending.executionId === instance.executionId + ? Effect.andThen(pending.retired.await, Effect.as(pending.idle.await, Option.none())) + : Effect.never while (true) { - const result = yield* retryPersistence( + const maybeResult = yield* retryPersistence( client.activity({ name: activity.name, attempt, withTransaction: Context.get(activity.annotations, ClusterSchema.WithTransaction) }) - ) + ).pipe(Effect.asSome, Effect.raceFirst(handoff)) + // The retired entity will not run this activity. Leave the run for + // the next owner, which replays it and reads the saved results. + if (Option.isNone(maybeResult)) return yield* ClusterAbandon.interrupt + const result = maybeResult.value // If the activity has suspended and did not execute, we need to resume // it by resetting the attempt and re-executing. if ( @@ -999,6 +1020,11 @@ interface ActivationState { // resources and durable finalizers until the execution finishes. scope: Scope.Closeable readonly instances: Set + // Opens when this activation retires; paired with `idle` so in-flight + // activities finish before any waiting run hands off to the next owner. + readonly retired: Latch.Latch | undefined + readonly idle: Latch.Latch + executing: number } const isSuspendedReply = (reply: WithExitEncoded>) => diff --git a/packages/effect/src/cluster/internal/entityActivation.ts b/packages/effect/src/cluster/internal/entityActivation.ts index 9da82263fd..55018bc84b 100644 --- a/packages/effect/src/cluster/internal/entityActivation.ts +++ b/packages/effect/src/cluster/internal/entityActivation.ts @@ -1,7 +1,13 @@ import * as Context from "../../Context.ts" +import type * as Latch from "../../Latch.ts" import type * as Scope from "../../Scope.ts" /** The entity lifetime, shared by all handler rebuilds within an activation. @internal */ export class CurrentActivationScope extends Context.Service()( "effect/cluster/internal/CurrentActivationScope" ) {} + +/** Opens when the activation retires and stops accepting new requests. @internal */ +export class CurrentRetirementLatch extends Context.Service()( + "effect/cluster/internal/CurrentRetirementLatch" +) {} diff --git a/packages/effect/src/cluster/internal/entityManager.ts b/packages/effect/src/cluster/internal/entityManager.ts index 6ddcbc23a9..c65b7cf8c3 100644 --- a/packages/effect/src/cluster/internal/entityManager.ts +++ b/packages/effect/src/cluster/internal/entityManager.ts @@ -39,7 +39,7 @@ import type { Sharding } from "../Sharding.ts" import { ShardingConfig } from "../ShardingConfig.ts" import * as Snowflake from "../Snowflake.ts" import * as ClusterAbandon from "./clusterAbandon.ts" -import { CurrentActivationScope } from "./entityActivation.ts" +import { CurrentActivationScope, CurrentRetirementLatch } from "./entityActivation.ts" import { EntityReaper } from "./entityReaper.ts" import { acquireEntity, releaseEntity } from "./interruptors.ts" import { ResourceMap } from "./resourceMap.ts" @@ -343,6 +343,7 @@ export const make = Effect.fnUntraced(function*< Context.add(CurrentRunnerAddress, options.runnerAddress), Context.add(KeepAliveLatch, keepAliveLatch), Context.add(CurrentActivationScope, scope), + Context.add(CurrentRetirementLatch, retired), Context.add(Scope.Scope, handlerScope), Context.add(CurrentLogAnnotations, {}) ) @@ -643,9 +644,9 @@ export const make = Effect.fnUntraced(function*< scope, Effect.suspend(() => { activeServers.delete(address.entityId) - retired.openUnsafe() closeLatches.closing = true acquireEntity(address) + retired.openUnsafe() drainingServers.set(address.entityId, state) return Effect.raceFirst( Effect.gen(function*() { diff --git a/packages/effect/test/cluster/ClusterWorkflowEngine.test.ts b/packages/effect/test/cluster/ClusterWorkflowEngine.test.ts index 005efe6370..e26058adfa 100644 --- a/packages/effect/test/cluster/ClusterWorkflowEngine.test.ts +++ b/packages/effect/test/cluster/ClusterWorkflowEngine.test.ts @@ -27,9 +27,12 @@ import { EntityType, type Message, MessageStorage, + Runner, + RunnerAddress, RunnerHealth, Runners, RunnerStorage, + ShardId, Sharding, ShardingConfig, Snowflake @@ -535,6 +538,170 @@ describe.concurrent("ClusterWorkflowEngine", () => { }).pipe(Effect.provide(layer(false))) })) + for (const mode of ["sequential", "queued", "pre-persisted"] as const) { + it.effect(`releases a rebalanced shard promptly after an in-flight activity completes (${mode})`, () => + Effect.gen(function*() { + const otherRunner = Runner.make({ + address: RunnerAddress.make("localhost", 9999), + groups: ["default"], + weight: 1 + }) + let assignSelf = true + const releases: Array = [] + const runnerStorage = Layer.effect( + RunnerStorage.RunnerStorage, + Effect.map(RunnerStorage.makeMemory, (storage) => + RunnerStorage.RunnerStorage.of({ + ...storage, + getRunners: Effect.map( + storage.getRunners, + (runners) => + assignSelf ? runners : [...runners.map(([runner]) => [runner, false] as const), [otherRunner, true]] + ), + release: (_address, shardId) => + Effect.sync(() => { + releases.push(shardId) + }) + })) + ) + const storage = yield* makeSharedStorage + let queuedSaves = 0 + let hideQueued = mode !== "sequential" + const isQueuedActivity = (envelope: Message.Incoming["envelope"] | Message.Outgoing["envelope"]) => + envelope._tag === "Request" && + envelope.tag === "activity" && + (envelope.payload as { readonly name?: string }).name === "queued" + const visible = (messages: Array>) => + hideQueued ? messages.filter((message) => !isQueuedActivity(message.envelope)) : messages + const storageLayer = Layer.succeed(MessageStorage.MessageStorage, { + ...storage, + saveRequest: (message) => + Effect.tap( + storage.saveRequest(message), + () => + Effect.sync(() => { + if (isQueuedActivity(message.envelope)) queuedSaves++ + }) + ), + unprocessedMessages: (shardIds, options) => + Effect.map(storage.unprocessedMessages(shardIds, options), visible), + unprocessedMessagesById: (ids) => Effect.map(storage.unprocessedMessagesById(ids), visible) + }) + const workflow = Workflow.make(`RebalanceHandoff/${mode}`, { + payload: {}, + idempotencyKey: () => "one" + }) + const runs = { slow: 0, after: 0, queued: 0 } + const started = yield* Latch.make() + const release = yield* Latch.make() + const slow = Activity.make({ + name: "slow", + execute: Effect.gen(function*() { + runs.slow++ + yield* started.open + yield* release.await + }) + }) + const queued = Activity.make({ + name: "queued", + success: Schema.String, + execute: Effect.sync(() => { + runs.queued++ + return "queued" + }) + }) + const after = Activity.make({ + name: "after", + execute: Effect.sync(() => { + runs.after++ + }) + }) + const layer = workflow.toLayer(() => + Effect.gen(function*() { + if (mode === "sequential") { + yield* slow + } else { + yield* Effect.all([slow, queued], { concurrency: "unbounded" }) + } + yield* after + }) + ).pipe( + Layer.provideMerge(makeTestWorkflowEngine({ + shardingLayer: Sharding.layer.pipe(Layer.provide(runnerStorage)), + storageLayer, + config: { + shardsPerGroup: 1, + availableShardGroups: ["default"], + assignedShardGroups: ["default"], + entityTerminationTimeout: Duration.seconds(90), + entityMessagePollInterval: 10, + refreshAssignmentsInterval: 10 + } + })) + ) + + yield* Effect.gen(function*() { + const sharding = yield* Sharding.Sharding + const shardId = ShardId.make("default", 1) + yield* advanceUntil(() => sharding.hasShardId(shardId), "runner must acquire the shard", 10, 500) + + const executionId = yield* workflow.executionId({}) + const sharedCaller = mode === "pre-persisted" + ? yield* (yield* Entity.make(`Workflow/${workflow._tag}`, [RecoveryActivityRpc]).client)(executionId) + .activity({ name: "queued", attempt: 1, withTransaction: false }) + .pipe(Effect.forkScoped({ startImmediately: true })) + : undefined + if (sharedCaller) { + yield* advanceUntil(() => queuedSaves >= 1, "pre-persisted activity must be saved", 10, 500) + } + + yield* workflow.execute({}, { discard: true }) + const expectedQueuedSaves = mode === "sequential" ? 0 : mode === "queued" ? 1 : 2 + yield* advanceUntil( + () => started.isOpen() && queuedSaves >= expectedQueuedSaves, + "in-flight activity must start", + 10, + 500 + ) + + assignSelf = false + yield* advanceUntil(() => !sharding.hasShardId(shardId), "runner must drop the moved shard", 10, 500) + yield* TestClock.adjust(1000) + assert.strictEqual(releases.length, 0, "shard release must wait for the in-flight activity") + + yield* release.open + yield* TestClock.adjust(1000) + const released = releases.length > 0 + // A stalled release also stalls teardown, so let it time out before failing. + if (!released) yield* TestClock.adjust(Duration.seconds(90)) + assert.isTrue(released, "shard must be released promptly without waiting for entityTerminationTimeout") + assert.deepStrictEqual(runs, { slow: 1, after: 0, queued: 0 }) + if (sharedCaller) assert.isUndefined(sharedCaller.pollUnsafe(), "shared caller must remain waiting") + + assignSelf = true + hideQueued = false + yield* advanceUntil(() => sharding.hasShardId(shardId), "runner must reacquire the shard", 10, 500) + assert.deepStrictEqual( + yield* pollUntil(workflow, executionId, "Complete"), + new Workflow.Complete({ exit: Exit.void }) + ) + assert.deepStrictEqual(runs, { slow: 1, after: 1, queued: mode === "sequential" ? 0 : 1 }) + if (sharedCaller) { + yield* advanceUntil( + () => sharedCaller.pollUnsafe() !== undefined, + "shared caller must receive the activity reply", + 10, + 500 + ) + assert.deepStrictEqual( + yield* Fiber.join(sharedCaller), + new Workflow.Complete({ exit: Exit.succeed("queued") }) + ) + } + }).pipe(Effect.provide(layer)) + })) + } + it.effect("retries an early activity registered while its Suspended reply is still being persisted", () => Effect.gen(function*() { const workflow = Workflow.make("EarlyActivity", {