Repository navigation
Description
What version of Effect is running?
[email protected], @effect/[email protected], @effect/[email protected] (latest release). Also reproduced on main at 9394b6d, built from source and linked. [email protected] recovers from the same fault. The code in question (Runners.notifyLocalRequest, from #9336) is in the 4.0.6, 4.0.7 and 4.1.0 sources; 4.0.6 and 4.0.7 were not run. Node 26.13, PostgreSQL 17.
What steps can reproduce the bug?
A workflow runs one activity on SingleRunner with SqlMessageStorage on PostgreSQL. A TCP proxy between the runner and PostgreSQL lets the transaction that saves the activity's reply commit, then closes the connection instead of passing on the answer to COMMIT. The client cannot tell whether the transaction committed. A network blip, a PostgreSQL restart, a failover or a proxy/pooler dropping the connection at that moment does the same.
docker run -d --rm --name effect-reply-repro -e POSTGRES_PASSWORD=pg -p 55432:5432 postgres:17-alpine
npm i [email protected] @effect/[email protected] @effect/[email protected]
CUT=0 node repro.ts # execute: 42; poll: Complete
CUT=1 node repro.ts # execute: no result after 30s; poll: none// repro.ts
import { NodeCrypto } from "@effect/platform-node"
import { PgClient } from "@effect/sql-pg"
import { Effect, Exit, Layer, Option, Redacted, References, Schema } from "effect"
import { ClusterWorkflowEngine, SingleRunner } from "effect/cluster"
import { Activity, Workflow } from "effect/workflow"
import * as Net from "node:net"
// A TCP proxy to PostgreSQL. With CUT=1 it lets the transaction that saves the first reply
// (the activity's) commit, then closes the connection instead of passing on the COMMIT's
// answer, as a network blip or a server restart at that moment would.
const replyInsert = Buffer.from(`INSERT INTO "cluster_replies"`)
const commitComplete = Buffer.from([0x43, 0, 0, 0, 11, ...Buffer.from("COMMIT"), 0])
let armed = process.env.CUT === "1"
const proxy = Net.createServer((client) => {
const server = Net.connect({ host: "127.0.0.1", port: 55432 })
let cutAtCommit = false
server.on("data", (chunk: Buffer) => {
const at = cutAtCommit ? chunk.indexOf(commitComplete) : -1
if (at === -1) return client.write(chunk)
client.write(chunk.subarray(0, at), () => (client.destroy(), server.destroy()))
})
client.on("data", (chunk: Buffer) => {
if (armed && chunk.includes(replyInsert)) {
armed = false
cutAtCommit = true
}
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(() =>
Activity.make({ name: "Step", success: Schema.Number, execute: Effect.succeed(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 program = Effect.gen(function*() {
const id = `run-${Date.now()}`
const exit = yield* MyWorkflow.execute({ id }).pipe(Effect.timeout("30 seconds"), Effect.exit)
const result = yield* MyWorkflow.poll(yield* MyWorkflow.executionId({ id }))
return `execute: ${Exit.isSuccess(exit) ? exit.value : "no result after 30s"}; poll: ${
Option.isSome(result) ? result.value._tag : "none"
}`
})
console.log(
await Effect.runPromise(
program.pipe(Effect.provide(Live), Effect.provideService(References.MinimumLogLevel, "None"))
)
)
process.exit(0)The first INSERT INTO cluster_replies of a fresh database is the activity's reply ({"_tag":"Complete","exit":{"_tag":"Success",...}}): the activity runs before the workflow has a reply of its own. Run each attempt on a fresh database. A workflow left hanging is resumed by the next process on the same database, and its reply would take the cut instead.
What is the expected behavior?
The activity's reply is in the database. The workflow should read it, finish, and return 42, as it does on 4.0.5.
What do you see instead?
The workflow never completes: execute does not return, and poll returns None. The activity's request is processed = true with its exit reply stored, while the workflow's run request stays unprocessed. Nothing is logged at Debug. The process is otherwise healthy: the next workflow in the same process succeeds. It stays like that until the shard moves or the process restarts. One run waited 120 s with the same result. A new process on the same database finished the workflow in about 200 ms without running the activity again.
On the wire after the cut, the runner sends the reply again under a new reply id. PostgreSQL rejects it with duplicate key value violates unique constraint "cluster_replies_request_id_kind_key" (every run below, on every version, 4.0.5 included).
Each cell ran 5 times, one process and one fresh database per run. The timeout is 30 s.
| Install | Connection | execute |
poll after timeout |
Activity reply stored | Retry hit UNIQUE (request_id, kind) |
Next workflow, same process |
|---|---|---|---|---|---|---|
| 4.0.5 | stays up (control) | 42 in 5/5 | Complete 5/5 | yes | — | success |
| 4.0.5 | reply COMMIT acknowledgement lost |
42 in 5/5 (≈0.4 s) | Complete 5/5 | yes | 5/5 | success |
| 4.1.0 | control | 42 in 5/5 | Complete 5/5 | yes | — | success |
| 4.1.0 | acknowledgement lost | no result in 30 s, 5/5 | None 5/5 |
yes, 5/5 | 5/5 | success |
main 9394b6d |
control | 42 in 5/5 | Complete 5/5 | yes | — | success |
main 9394b6d |
acknowledgement lost | no result in 30 s, 5/5 | None 5/5 |
yes, 5/5 | 5/5 | success |
| main + proposed fix | control | 42 in 5/5 | Complete 5/5 | yes | — | success |
| main + proposed fix | acknowledgement lost | 42 in 5/5 (0.4–0.65 s) | Complete 5/5 | yes | 5/5 | success |
| 4.1.0 + workaround below | control | 42 in 5/5 | Complete 5/5 | yes | — | success |
| 4.1.0 + workaround below | acknowledgement lost | 42 in 5/5 (0.2–0.65 s) | Complete 5/5 | yes | 0/5 (the save counts as done, no retry) | success |
The activity ran exactly once in every run.
Mechanism
All links are pinned to main at 9394b6d.
- The workflow sends its activity as a persisted request to an entity on the local shard. Since Answer fresh local cluster requests without a storage readback #9336,
Runners.notifyLocalRequestforksregisterReplyHandler, saves the request, and then waits only onFiber.join(handler). It reads storage only when the handler fails withEntityNotAssignedToRunner. - The entity saves the reply through
MessageStorage.saveReply. It resumes the handlers inflatMapafter the storage save succeeds. If the save fails, nothing resumes them. SqlMessageStorage.saveReplyrunsUPDATE cluster_messagesandINSERT INTO cluster_repliesin one transaction. When the connection closes after PostgreSQL has committed but before the client reads the acknowledgement, the save fails withPersistenceError, although the reply is stored.- The entity manager retries the save with
retryRespond(L1008). Each attempt builds a newReply.WithExitwith a new id, so it hitsUNIQUE (request_id, kind)and fails again. After the retries,Effect.orDieends the reply fiber. - Nothing resumes, unregisters or fails the handler, so the workflow waits on
Fiber.join(handler)with its reply in storage.
In 4.0.5, notifyLocal always raced replyFromStorage against the handler, which only woke the storage loop. Steps 3 and 4 happen the same way there (the table shows the same unique violation), but the storage read finds the committed reply and the workflow finishes.
The fault is close to #10200, where a lost connection during the activity request write turns into a stored defect. Here it hits the reply write, and the result is a hang instead of a defect.
Proposed fix
Race the handler with a storage read, as replyFromStorageWithWake and 4.0.5 do:
--- a/packages/effect/src/cluster/Runners.ts
+++ b/packages/effect/src/cluster/Runners.ts
@@ -385,8 +385,10 @@ export const make: (
}
// The handler can be dropped, for example when its shard moves or a
// commit error hides the notification. The reply is then in storage.
+ // A reply save can also commit and still fail (its acknowledgement was
+ // lost), so the handler is never resumed: read storage as well.
return notifyEntity(message).pipe(
- Effect.andThen(Fiber.join(handler)),
+ Effect.andThen(Effect.raceFirst(Fiber.join(handler), replyFromStorage(outgoing))),
Effect.catchTag("EntityNotAssignedToRunner", () => replyFromStorage(outgoing))
)
})This is what the "main + proposed fix" rows ran. The tradeoff: the storage read loop now also polls for every fresh local request until the handler answers, which takes back part of what #9336 saved. Two cheaper alternatives, neither tested here:
- When the entity manager gives up on a reply save, call
unregisterReplyHandler(requestId). The waiter then fails withEntityNotAssignedToRunnerand falls back toreplyFromStorageon the existing path. This costs nothing on the happy path. - Make the reply save idempotent: keep the reply id across
retryRespondattempts, and letsaveReplytreat "a reply with this id is already stored" as success. That also removes the unique-violation retries.
Workaround
Wrap the encoded SQL storage so a failed saveReply whose row is stored counts as saved, and build the SingleRunner layer by hand with it. The reply id is unique, so finding the row proves that this save committed. It is green 5/5 on 4.1.0 in the table above.
import { Effect, Layer } from "effect"
import {
MessageStorage, RunnerHealth, Runners, Sharding, ShardingConfig, Snowflake, SqlMessageStorage, SqlRunnerStorage
} from "effect/cluster"
import { SqlClient } from "effect/sql"
const ReplyCheckingMessageStorage = Layer.effect(
MessageStorage.MessageStorage,
Effect.gen(function*() {
const sql = yield* SqlClient.SqlClient
const encoded = yield* SqlMessageStorage.makeEncodedStorage()
return yield* MessageStorage.makeEncoded({
...encoded,
saveReply: (reply) =>
encoded.saveReply(reply).pipe(
Effect.catchTag("PersistenceError", (error) =>
sql`SELECT 1 FROM cluster_replies WHERE id = ${reply.id}`.pipe(
Effect.flatMap((rows) => rows.length > 0 ? Effect.void : Effect.fail(error)),
Effect.catchTag("SqlError", () => Effect.fail(error))
))
)
})
})
).pipe(Layer.provide([Snowflake.layerGenerator, SqlMessageStorage.layerMigrations({})]))
// SingleRunner.layer() with the message storage swapped
const SingleRunnerWithWorkaround = Sharding.layer.pipe(
Layer.provideMerge(Runners.layerNoop),
Layer.provideMerge(ReplyCheckingMessageStorage),
Layer.provide([Layer.orDie(SqlRunnerStorage.layer), RunnerHealth.layerNoop]),
Layer.provide(ShardingConfig.layerFromEnv())
)Related, not the same
- Answer fresh local cluster requests without a storage readback #9336: introduced
notifyLocalRequest, which answers fresh local requests from the reply handler without a storage readback. This report is a case where the handler is never resumed. - cluster: a local persisted request can wait forever when its reply is saved before
registerReplyHandler(Runners.notifyLocal) #9175 / cluster: 4.0.5 Runners.notifyLocal reads every local reply from storage and roughly doubles workflow replays #9335: the earlier lost-reply race and the 4.0.5 readback cost that Answer fresh local cluster requests without a storage readback #9336 addressed. - ClusterWorkflowEngine: a PersistenceError while saving an activity request (e.g. a dropped PostgreSQL connection) becomes a stored workflow defect #10200: a lost connection during the activity request write becomes a stored workflow defect. Same kind of fault, different write and outcome.
- ClusterWorkflowEngine: interrupt sent while a replay is persisting its Suspended reply is lost; workflow stays Suspended forever #9644: an interrupt lost while a replay saves its
Suspendedreply. Also a window around a reply save, but a different cause.
Activity