Repository navigation
Description
What version of Effect is running?
[email protected], @effect/[email protected], @effect/[email protected] (latest release). Also reproduced on main at 522ad7c, built from source and linked. Node 26.13, PostgreSQL 17.
What steps can reproduce the bug?
One runner (SingleRunner, so Sharding over SqlRunnerStorage with PostgreSQL advisory locks) runs a parent workflow. The parent starts a short child and a 5 s activity side by side. The child finishes first, so its resume request reaches the parent while the parent's run is still in flight. A TCP proxy then holds the runner's lock session for 800 ms once, so one lock refresh misses its 500 ms deadline.
docker run -d --rm --name effect-shard-repro -e POSTGRES_PASSWORD=pg -p 55432:5432 postgres:17-alpine
npm i [email protected] @effect/[email protected] @effect/[email protected]
LAG=0 node repro.ts # workflow: 42
LAG=1 node repro.ts # "Forced shard release is still pending" at +3 s and +33 s; no result after 40 s// repro.ts
import { NodeCrypto } from "@effect/platform-node"
import { PgClient } from "@effect/sql-pg"
import { Effect, Exit, Layer, Logger, Redacted, References, Schema } from "effect"
import { ClusterWorkflowEngine, SingleRunner } from "effect/cluster"
import { Activity, Workflow } from "effect/workflow"
import * as Net from "node:net"
const t0 = Date.now()
const log = (text: string) => console.log(`${String(Date.now() - t0).padStart(6)}ms ${text}`)
// A TCP proxy to PostgreSQL. With LAG=1 it holds the runner's shard lock session for 800 ms,
// once, 2 s after start: one lock refresh misses its 500 ms deadline.
const lag = process.env.LAG === "1"
const proxy = Net.createServer((client) => {
const server = Net.connect({ host: "127.0.0.1", port: 55432 })
server.pipe(client)
let lockSession = false
let queue = Promise.resolve()
client.on("data", (chunk: Buffer) => {
// SqlRunnerStorage opens its dedicated lock session with this statement
if (chunk.includes("SELECT pg_backend_pid()")) lockSession = true
const t = Date.now() - t0
const hold = lag && lockSession && t >= 2000 && t < 2600 ? 800 : 0
queue = queue.then(() => new Promise((resolve) => setTimeout(resolve, hold))).then(() => {
if (!server.destroyed) server.write(chunk)
})
})
for (const socket of [client, server]) socket.on("error", () => {}).on("close", () => (client.destroy(), server.destroy()))
})
const listening = Promise.withResolvers<void>()
proxy.listen(0, "127.0.0.1", listening.resolve)
await listening.promise
// The parent runs a quick child and a 5 s activity side by side. The child finishes first, so
// its `resume` request reaches the parent while the parent's run is still in flight.
const Child = Workflow.make("Child", { payload: { id: Schema.String }, idempotencyKey: ({ id }) => id })
const Parent = Workflow.make("Parent", {
payload: { id: Schema.String },
success: Schema.Number,
idempotencyKey: ({ id }) => id
})
const WorkflowsLive = Layer.mergeAll(
Child.toLayer(() => Effect.void),
Parent.toLayer(({ id }) =>
Effect.all([
Child.execute({ id: `${id}-child` }),
Activity.make({ name: "Slow", success: Schema.Number, execute: Effect.as(Effect.sleep("5 seconds"), 42) })
], { concurrency: 2 }).pipe(Effect.map(([, n]) => n))
)
)
const Live = WorkflowsLive.pipe(
Layer.provideMerge(ClusterWorkflowEngine.layer),
Layer.provideMerge(SingleRunner.layer({
shardingConfig: { shardLockRefreshInterval: "500 millis", shardLockExpiration: "3 seconds" }
})),
Layer.provide(NodeCrypto.layerDigest),
Layer.provide(PgClient.layer({
host: "127.0.0.1",
port: (proxy.address() as Net.AddressInfo).port,
username: "postgres",
password: Redacted.make("pg")
}))
)
// print Sharding's lock messages
const ShardLockLogger = Logger.layer([
Logger.make(({ message }) => {
const text = String(Array.isArray(message) ? message[0] : message)
if (text.startsWith("Shard lock storage") || text.startsWith("Forced shard release")) log(text)
})
])
const exit = await Effect.runPromiseExit(
Parent.execute({ id: `run-${Date.now()}` }).pipe(
Effect.timeout("40 seconds"),
Effect.provide(Live),
Effect.provide(ShardLockLogger),
Effect.provideService(References.MinimumLogLevel, "Info")
)
)
log(Exit.isSuccess(exit) ? `workflow: ${exit.value}` : "workflow: no result after 40 s")
process.exit(0)Output on 4.1.1 with LAG=1:
2679ms Shard lock storage is unhealthy
2693ms Shard lock storage has recovered
5689ms Forced shard release is still pending; reacquisition is blocked until release completes
35691ms Forced shard release is still pending; reacquisition is blocked until release completes
40701ms workflow: no result after 40 s
The short timings only make one slow refresh enough to trigger a forced release. Any refresh that misses its deadline does the same: with the defaults that is a lock session stalled for 10 s instead of 500 ms. A single miss is enough; lock health does not need to keep flapping.
What is the expected behavior?
The runner releases its shards, reacquires them once lock storage has recovered (it reports recovery 14 ms later), and the workflow continues under the new lock: the interrupted activity runs again and the workflow returns 42. That is what happens when no resume is in flight (the "activity only" rows below), and with the fix.
What do you see instead?
The forced release never finishes. Sharding logs Forced shard release is still pending (entity types [Workflow/Parent]) every 30 s, the runner holds no shard lock, and no workflow on its shards makes progress. The interrupted activity is not run again. Every later message to those shards waits. It stays like that until the process restarts.
Each cell ran 5 times, one process and one fresh database per run, one process at a time. Times are from the first Shard lock storage is unhealthy.
| Install | Scenario | Refresh delayed | Workflow | Forced release | Shard locks after the fault | Activity restarted |
|---|---|---|---|---|---|---|
| 4.1.1 | resume in flight | no (control) | 42 in ~5.1 s, 5/5 | — | 16 held | — |
| 4.1.1 | resume in flight | once | no result in 37 s, 5/5 | still pending at +3.0 s and +33.0 s, 5/5 | 0 to the end of the run | never, 5/5 |
| 4.1.1 | activity only | once | 42 in ~7.9 s, 5/5 | completes | released and reacquired | +315–353 ms, 5/5 |
main 522ad7c |
resume in flight | no (control) | 42 in ~5.1 s, 5/5 | — | 16 held | — |
main 522ad7c |
resume in flight | once | no result in 37 s, 5/5 | still pending at +3.0 s and +33.0 s, 5/5 | 0 to the end of the run | never, 5/5 |
main 522ad7c |
activity only | once | 42 in ~7.9 s, 5/5 | completes | released and reacquired | +320–334 ms, 5/5 |
| main + proposed fix | resume in flight | no (control) | 42 in ~5.1 s, 5/5 | — | 16 held | — |
| main + proposed fix | resume in flight | once | 42 in ~7.9 s, 5/5 | completes | released and reacquired | +326–360 ms, 5/5 |
| main + proposed fix | activity only | once | 42 in ~8.0 s, 5/5 | completes | released and reacquired | +319–349 ms, 5/5 |
With the fix, the existing packages/effect/test/cluster/ClusterWorkflowEngine.test.ts, Sharding.test.ts and packages/effect/test/workflow tests pass (5 files, 236 tests).
Mechanism
All links are pinned to main at 522ad7c. The involved Sharding.ts and entityManager.ts are the same in 4.1.1.
- A refresh that misses its deadline calls
markShardLocksUnhealthy. It moves every shard toforceReleasingShardsand force-interrupts their entities. Reacquisition waits for the forced release, which waits for every entity on those shards to close (runShardRelease→interruptShard). The comment inreleaseForcedShardssays this is deliberate: a release cannot cut uninterruptible work short. That is fine as long as the uninterruptible work ends. - The workflow entity's
resumehandler runs withRpc.wrap({ fork: true, uninterruptible: true }), so the RpcServer forks it uninterruptible. When the entity closes, the interrupt it sends that fiber stays pending. - The handler is in
resumeCurrentRun→waitForRunReply, waiting for the run's reply. The run is interrupted, its reply waiter fails withEntityNotAssignedToRunner(2 ms after the lock failure in a trace), andwaitForRunReplyturns that intoClusterAbandon.interrupt, a self-interrupt annotatedAbandon. ClusterAbandon.interruptopens an interruptible region to deliver that self-interrupt. The interrupt already pending from step 2 is delivered first, so the cause carries that interrupt's annotations and notAbandon. In a trace:reasons=Interrupt[effect/Cause/StackTrace],isCause = false.ensureSuccessretries every cause except anAbandonone, so it retries. The retry registers a new waiter for the retired run's reply. Nothing ever answers it, the uninterruptible handler never returns, the entity never closes, and the forced release from step 1 never completes.
#9938 (for #9934) added the ClusterAbandon.isCause check to stop exactly this retry. Its fix holds when the handler fiber has no interrupt pending. When the entity close has already interrupted the fiber, step 4 hides the annotation and the loop is back.
Step 4 is general fiber behaviour. A standalone check with ensureSuccess copied from the engine (pending-probe.mjs in the repro folder):
uninterruptible fiber, outside interrupt pending: false
attempt failed, isAbandon = true
attempts=1: fiber ended
uninterruptible fiber, outside interrupt pending: true
attempt failed, isAbandon = false
attempts=2: still running after 2s
Proposed fix
Treat an interrupt-only cause like an abandonment in ensureSuccess: stop retrying and re-raise it as the annotated interrupt. An interrupt-only cause means the fiber itself was interrupted, so retrying can only wait on a retired run. Other failures keep the retry policy.
--- a/packages/effect/src/cluster/ClusterWorkflowEngine.ts
+++ b/packages/effect/src/cluster/ClusterWorkflowEngine.ts
@@ -941,11 +941,18 @@ const ensureSuccess = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
effect.pipe(
Effect.sandbox,
- Effect.retry({ schedule: retryPolicy, while: (cause) => !ClusterAbandon.isCause(cause) }),
- Effect.catchIf(ClusterAbandon.isCause, () => ClusterAbandon.interrupt),
+ // An interrupt-only cause means this fiber was interrupted. In an
+ // uninterruptible handler, a pending outside interrupt also replaces the
+ // annotated abandonment when it is raised, so treat both the same way:
+ // retrying would only wait on a retired run.
+ Effect.retry({ schedule: retryPolicy, while: (cause) => !isAbandonOrInterrupt(cause) }),
+ Effect.catchIf(isAbandonOrInterrupt, () => ClusterAbandon.interrupt),
Effect.orDie
)
+const isAbandonOrInterrupt = (cause: Cause.Cause<unknown>): boolean =>
+ ClusterAbandon.isCause(cause) || Cause.hasInterruptsOnly(cause)
+This is what the "main + proposed fix" rows ran. The durable resume request is left for replay as before, and the parent resumes once the shard is reacquired. Another option is for ClusterAbandon.interrupt (or waitForRunReply) to fail with a value instead of relying on a self-interrupt's annotation, which a pending interrupt can replace. I did not test that.
Workaround
None tested. A larger shardLockRefreshInterval (default 10 s, which is also the refresh deadline) makes a forced release less likely, but not impossible.
Related, not the same
- ClusterWorkflowEngine retries ClusterAbandon in resume handlers, blocking shard reacquisition after storage recovery #9934 / Stop retrying cluster abandonment in workflow wakes #9938: the same loop (a
resumehandler retrying an abandoned wait, so the forced release never finishes), fixed for the case without a pending interrupt. This report is the remaining case. - cluster: a local persisted request waits forever when its reply commits but the save reports a failure (lost COMMIT acknowledgement), since 4.0.6 #10202 / Recover local persisted replies after lost commit acknowledgements #10205: a local persisted request waiting forever after a lost commit acknowledgement on its reply. A different wait, in
Runners.notifyLocalRequest. - ClusterWorkflowEngine: a PersistenceError while saving an activity request (e.g. a dropped PostgreSQL connection) becomes a stored workflow defect #10200 / Retry transient activity persistence failures in ClusterWorkflowEngine #10206: a
PersistenceErrorduring an activity request stored as a workflow defect. Same engine, different path.
Activity