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.
This is the follow-up I posted on #10200 (comment), which got no reply after the issue was closed, so here it is as its own report with a repro.
What steps can reproduce the bug?
A workflow on SingleRunner with SqlMessageStorage on PostgreSQL either sleeps with DurableClock.sleep (longer than its in-memory threshold, so it is scheduled through the engine) or races with DurableDeferred.raceAll (whose winner is recorded through the engine). A TCP proxy between the runner and PostgreSQL closes the connection once, on the INSERT INTO cluster_messages that saves the clock or the deferred. Network blips, PostgreSQL restarts, failovers and idle-connection reapers close connections in the same way.
docker run -d --rm --name effect-clock-repro -e POSTGRES_PASSWORD=pg -p 55432:5432 postgres:17-alpine
npm i [email protected] @effect/[email protected] @effect/[email protected]
SCENARIO=clock DROP=0 node repro.ts # success: 42
SCENARIO=clock DROP=1 node repro.ts # defect: ~effect/cluster/ClusterError/PersistenceError
SCENARIO=race DROP=0 node repro.ts # success: 42
SCENARIO=race DROP=1 node repro.ts # defect: ~effect/cluster/ClusterError/PersistenceError// repro.ts
import { NodeCrypto } from "@effect/platform-node"
import { PgClient } from "@effect/sql-pg"
import { Cause, Effect, Exit, Layer, Redacted, References, Schema } from "effect"
import { ClusterWorkflowEngine, SingleRunner } from "effect/cluster"
import { DurableClock, DurableDeferred, Workflow } from "effect/workflow"
import * as Net from "node:net"
// A TCP proxy to PostgreSQL. With DROP=1 it closes the connection that carries the first
// INSERT INTO cluster_messages naming MARKER, once, as a network blip or a server restart would.
const marker = Buffer.from(process.env.SCENARIO === "race" ? "/deferred/raceAll/Race" : "Workflow/-/DurableClock/")
let drop = process.env.DROP === "1"
const proxy = Net.createServer((client) => {
const server = Net.connect({ host: "127.0.0.1", port: Number(process.env.PGPORT ?? 55432) })
server.pipe(client)
const inserts = new Set<string>() // prepared statements that insert into cluster_messages
client.on("data", (chunk: Buffer) => {
// Parse ('P') names a statement; Bind ('B') runs it with the message id as a parameter
let insertWithMarker = false
for (let at = 0; at + 5 <= chunk.length; at += 1 + chunk.readInt32BE(at + 1)) {
const body = chunk.subarray(at + 5, at + 1 + chunk.readInt32BE(at + 1))
const [first = "", second = ""] = body.toString("latin1").split("\0")
if (chunk[at] === 0x50 && second.trimStart().startsWith(`INSERT INTO "cluster_messages"`)) inserts.add(first)
if (chunk[at] === 0x42 && inserts.has(second) && body.includes(marker)) insertWithMarker = true
}
if (drop && insertWithMarker) {
drop = false
client.destroy()
server.destroy()
return
}
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
const MyWorkflow = Workflow.make("MyWorkflow", {
payload: { id: Schema.String },
success: Schema.Number,
idempotencyKey: ({ id }) => id
})
const MyWorkflowLive = MyWorkflow.toLayer(() =>
process.env.SCENARIO === "race"
// the winner is recorded with deferredDone
? DurableDeferred.raceAll({
name: "Race",
success: Schema.Number,
error: Schema.Never,
effects: [Effect.succeed(42), Effect.never]
})
// a sleep longer than the in-memory threshold is scheduled with scheduleClock
: Effect.as(DurableClock.sleep({ name: "Wait", duration: "1 second", inMemoryThreshold: 0 }), 42)
)
const Live = MyWorkflowLive.pipe(
Layer.provideMerge(ClusterWorkflowEngine.layer),
Layer.provideMerge(SingleRunner.layer()),
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")
}))
)
const exit = await Effect.runPromiseExit(
MyWorkflow.execute({ id: `run-${Date.now()}` }).pipe(
Effect.provide(Live),
Effect.provideService(References.MinimumLogLevel, "None")
)
)
console.log(Exit.isSuccess(exit) ? `success: ${exit.value}` : `defect: ${Cause.pretty(exit.cause).split("\n")[0]}`)
process.exit(0)inMemoryThreshold: 0 only keeps the repro short. With the default threshold (60 s), any DurableClock.sleep longer than a minute takes the same path. Lookups by message_id also carry the marker, so the proxy matches only the Bind of the prepared INSERT INTO cluster_messages.
What is the expected behavior?
As for activities since #10206: the save is transient and idempotent (both requests are persisted under a primary key), so the engine should retry it, and the workflow should sleep or record its race winner and return 42.
What do you see instead?
The workflow ends with a defect, PersistenceError → SqlError → ConnectionError: PgConnection: Connection closed, and that defect is stored as the workflow's result. A second variant in the results below (ack-lost) lets PostgreSQL commit the INSERT and closes the connection before the answer arrives. The outcome is the same defect, although the clock or deferred row is already stored.
The same deferredDone path also completes a deferred from outside a workflow, with DurableDeferred.succeed/done and a token (token rows below). There the caller dies with PersistenceError. If the INSERT never reached PostgreSQL, the workflow waits for a completion that was never stored, unless the caller catches the defect and retries.
Each cell ran 5 times, one process and one fresh database per run. "Rows" counts what the database holds afterwards for the saved message: requests, and replies to them.
| Save | Connection | 4.1.1 | main 522ad7c |
main + proposed fix | 4.1.1 + workaround |
|---|---|---|---|---|---|
scheduleClock |
stays up (control) | 42, 5/5 | 42, 5/5 | 42, 5/5 | 42, 5/5 |
scheduleClock |
closed before the INSERT reaches PostgreSQL | defect PersistenceError, stored, 5/5 |
same, 5/5 | 42, 5/5; one clock request, one reply | 42, 5/5 |
scheduleClock |
closed after the INSERT commits | defect PersistenceError, stored, 5/5 |
same, 5/5 | 42, 5/5; one clock request, one reply | 42, 5/5 |
raceAll winner (deferredDone) |
stays up (control) | 42, 5/5 | 42, 5/5 | 42, 5/5 | 42, 5/5 |
raceAll winner |
closed before the INSERT | defect PersistenceError, stored, 5/5 |
same, 5/5 | 42, 5/5; one deferred, one reply | 42, 5/5 |
raceAll winner |
closed after the INSERT commits | defect PersistenceError, stored, 5/5 |
same, 5/5 | 42, 5/5; one deferred, one reply | 42, 5/5 |
DurableDeferred.succeed from outside |
stays up (control) | workflow completes, 5/5 | same, 5/5 | same, 5/5 | same, 5/5 |
DurableDeferred.succeed from outside |
closed before the INSERT | caller dies with PersistenceError; nothing stored; workflow still waiting after 20 s, 5/5 |
same, 5/5 | caller returns, workflow completes, 5/5 | same as fix, 5/5 |
DurableDeferred.succeed from outside |
closed after the INSERT commits | caller dies with PersistenceError; deferred stored; workflow completes, 5/5 |
same, 5/5 | caller returns, workflow completes, 5/5 | same as fix, 5/5 |
With the fix, the retry after a committed-but-unacknowledged INSERT finds the stored row and nothing happens twice. The clock fires once (one clock request, one reply, one DurableClock/Wait deferred). The race winner runs and is recorded once (one deferred row, one reply). The activity after the wait runs once. The existing tests in packages/effect/test/cluster/ClusterWorkflowEngine.test.ts, Sharding.test.ts and packages/effect/test/workflow pass with the fix (5 files, 236 tests).
Mechanism
All links are pinned to main at 522ad7c. The same code is in 4.1.1 (bc492f0, L868 and L892).
DurableClock.sleepcallsengine.scheduleClockfor a sleep longer than its in-memory threshold.scheduleClocksaves aClockRpcrequest throughsendDiscardand pipes it intoEffect.orDie.DurableDeferred.raceAll(recordExit) andDurableDeferred.donecallengine.deferredDone.deferredDonesaves aDeferredRpcrequest underEffect.orDie(sendDiscard(...)). When the workflow is not registered on this runner, the client branch at L886 does the same; the repro does not reach that branch.- A dropped connection during the save fails it with
PersistenceError.sendDiscardpasses it on,orDieturns it into a defect, and sinceCaptureDefectsdefaults totrue, the workflow stores that defect as its result. This is the path Retry transient activity persistence failures in ClusterWorkflowEngine #10206 closed for activities. - A retry is safe.
DeferredRpchasprimaryKey: ({ name }) => name, and the clock'sClockPayloaduses its name as primary key. Both arePersisted. On PostgreSQL the save isINSERT … ON CONFLICT (message_id) DO NOTHING, so a repeat after a committed insert is a duplicate, not a second clock or completion. Theack-lostrows check this.
retryPersistence, added in #10206, already does what these sites need: it retries PersistenceError with the engine's retryPolicy, then orDie. activityExecute uses it.
Proposed fix
Use retryPersistence in place of the bare orDie at the three sites:
--- a/packages/effect/src/cluster/ClusterWorkflowEngine.ts
+++ b/packages/effect/src/cluster/ClusterWorkflowEngine.ts
@@ -869,7 +869,7 @@ export const make = Effect.gen(function*() {
}
const workflow = workflows.get(workflowName)
if (workflow) {
- return yield* Effect.orDie(sendDiscard({
+ return yield* retryPersistence(sendDiscard({
rpc: DeferredRpc,
address: entityAddressFor({
workflow,
@@ -883,7 +883,7 @@ export const make = Effect.gen(function*() {
}))
}
const client = yield* RcMap.get(clientsPartial, workflowName)
- return yield* Effect.orDie(
+ return yield* retryPersistence(
client(executionId).deferred({
name: deferredName,
exit
@@ -913,7 +913,7 @@ export const make = Effect.gen(function*() {
}
})
),
- Effect.orDie
+ retryPersistence
)
}
})This is what the "main + proposed fix" column ran.
Workaround
Wrap MessageStorage so it retries saveRequest on PersistenceError, and build the SingleRunner layer by hand with it. A request with a primary key is saved with ON CONFLICT DO NOTHING, so a repeat after a committed insert returns SaveResult.Duplicate. The "4.1.1 + workaround" column ran this:
import { Effect, Layer, Schedule } from "effect"
import { MessageStorage, RunnerHealth, Runners, Sharding, ShardingConfig, SqlMessageStorage, SqlRunnerStorage } from "effect/cluster"
const RetryingMessageStorage = Layer.effect(
MessageStorage.MessageStorage,
Effect.gen(function*() {
const storage = yield* MessageStorage.MessageStorage
return MessageStorage.MessageStorage.of({
...storage,
saveRequest: (message) =>
Effect.retry(storage.saveRequest(message), {
schedule: Schedule.exponential("100 millis", 1.5),
times: 20,
while: (error) => error._tag === "PersistenceError"
})
})
})
).pipe(Layer.provide(SqlMessageStorage.layer))
// SingleRunner.layer() with the message storage swapped
const SingleRunnerRetrying = Sharding.layer.pipe(
Layer.provideMerge(Runners.layerNoop),
Layer.provideMerge(RetryingMessageStorage),
Layer.provide([Layer.orDie(SqlRunnerStorage.layer), RunnerHealth.layerNoop]),
Layer.provide(ShardingConfig.layerFromEnv())
)Related, not the same
- 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: the same pattern for activity requests, fixed with
retryPersistence. These two sites were raised in a comment on #10200 after it was closed. - 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 lost commit acknowledgement on a reply save, which left a local caller waiting.
- ClusterWorkflowEngine: after one missed shard lock refresh, a workflow
resumehandler can keep the forced shard release pending forever (the #9934 case, when an interrupt is already pending) #10253: a forced shard release that stays pending because aresumehandler retries an abandoned wait. A different bug in the same engine.
Activity