Repository navigation
Description
What happens
Entity.keepAlive(true) sends a persisted Cluster/Entity/keepAlive request that the entity manager is meant to hold unanswered until Entity.keepAlive(false) opens the keep-alive latch. After 10 minutes, message storage delivers the same unprocessed request again, and the entity manager answers it immediately. The keep-alive request is marked processed while the entity's work is still running.
Why
In packages/effect/src/cluster/internal/entityManager.ts, the keep-alive branch is:
if (server.keepAliveEnabled) return reply
server.keepAliveEnabled = true
return server.keepAliveLatch.whenOpen(Effect.suspend(() => {
server.keepAliveEnabled = false
return reply
})).pipe(Effect.forkIn(server.scope, { startImmediately: true }), Effect.asVoid)The if (server.keepAliveEnabled) return reply check cannot tell a second keep-alive apart from a redelivery of the one already held.
Message storage hands out an unprocessed request again once its claim is older than 10 minutes: claimExpirationMillis = 10 * 60 * 1000 in the memory driver (packages/effect/src/cluster/MessageStorage.ts), and last_read < NOW() - INTERVAL '10 minutes' (or DATETIME('now', '-10 minute')) in packages/effect/src/cluster/SqlMessageStorage.ts.
The held keep-alive is not in the entity's activeRequests, so EntityManager.isProcessingFor returns false for it and Sharding passes the redelivery to sendLocal. By then keepAliveEnabled is already true, so the redelivered keep-alive is answered on the spot.
Impact
Keep-alive is how an entity gets re-activated after its shard moves or its runner restarts. Once a keep-alive has been held for more than 10 minutes, it is already answered, so a runner restart after that point does not re-activate the entity and its long-running work is not resumed. Nothing fails or logs, the work is just gone. We hit this in production: a run's keep-alive was answered at exactly 10 minutes, and after a deploy restarted the runner the run never resumed.
Reproduction
[email protected] and bun:test only. A single in-memory runner, a MessageStorage wrapper that records keep-alive requests and replies to them, and TestClock. The clock is advanced in 1-second steps so every storage poll on the way runs.
import { expect, test } from "bun:test"
import { Effect, Layer, Schema } from "effect"
import {
Entity,
MessageStorage,
RunnerHealth,
Runners,
RunnerStorage,
Sharding,
ShardingConfig
} from "effect/cluster"
import { Rpc } from "effect/rpc"
import { TestClock } from "effect/testing"
const Holder = Entity.make("Holder", [Rpc.make("Start", { payload: { id: Schema.String } })])
// keep-alive request id -> entity id, and the keep-alive request ids that got a reply
const keepAlives = new Map<string, string>()
const answered = new Set<string>()
const answeredFor = (entityId: string) =>
[...keepAlives].filter(([id, owner]) => owner === entityId && answered.has(id)).length
// Memory storage that records keep-alive requests and replies to them
const recordingStorage = Layer.effect(
MessageStorage.MessageStorage,
Effect.gen(function*() {
const inner = yield* MessageStorage.MessageStorage
return MessageStorage.MessageStorage.of({
...inner,
saveRequest: (message) => {
if (message.envelope.tag === Entity.KeepAliveRpc._tag) {
keepAlives.set(String(message.envelope.requestId), message.envelope.address.entityId)
}
return inner.saveRequest(message)
},
saveReply: (reply) => {
const requestId = String(reply.reply.requestId)
if (keepAlives.has(requestId)) answered.add(requestId)
return inner.saveReply(reply)
}
})
})
).pipe(Layer.provide(MessageStorage.layerMemory))
// "forever": holds keep-alive while work runs indefinitely
// "brief": holds keep-alive for 15 minutes, then releases it
const HolderLive = Holder.toLayer(
Effect.gen(function*() {
const { entityId } = yield* Entity.CurrentAddress
const work = entityId === "brief" ? Effect.sleep("15 minutes") : Effect.never
yield* Entity.keepAlive(true).pipe(
Effect.andThen(work),
Effect.andThen(Entity.keepAlive(false)),
Effect.forkScoped
)
return Holder.of({ Start: () => Effect.void })
})
)
const ClusterLive = HolderLive.pipe(
Layer.provideMerge(
Sharding.layer.pipe(
Layer.provideMerge(Runners.layerNoop),
Layer.provideMerge(recordingStorage),
Layer.provide([RunnerStorage.layerMemory, RunnerHealth.layerNoop]),
Layer.provide(ShardingConfig.layer({ shardsPerGroup: 4 }))
)
)
)
// Advance in 1s steps so every storage poll due on the way runs
const advance = (seconds: number) =>
Effect.forEach(Array.from({ length: seconds }), () => TestClock.adjust("1 second"), { discard: true })
const withHolder = (entityId: string, check: Effect.Effect<void>) =>
Effect.gen(function*() {
yield* Effect.forkScoped(
Holder.client.pipe(
Effect.flatMap((make) => make(entityId).Start({ id: entityId }, { discard: true })),
Effect.andThen(Effect.never),
Effect.provide(ClusterLive)
)
)
yield* check
}).pipe(Effect.provide(TestClock.layer()), Effect.scoped, Effect.runPromise)
test("held keep-alive is not answered when storage redelivers it", () =>
withHolder(
"forever",
Effect.gen(function*() {
yield* advance(30)
expect([...keepAlives.values()]).toContain("forever")
yield* advance(9 * 60)
expect(answeredFor("forever")).toBe(0)
// past the 10 minute claim expiration, storage redelivers the keep-alive
yield* advance(22 * 60)
expect(answeredFor("forever")).toBe(0)
})
))
test("control: keep-alive is answered once keepAlive(false) releases it", () =>
withHolder(
"brief",
Effect.gen(function*() {
yield* advance(30 * 60)
expect(answeredFor("brief")).toBe(1)
})
))Run with bun add [email protected] && bun test repro.test.ts.
Observed (effect 4.1.4, bun 1.4.4)
repro.test.ts:
96 | yield* advance(22 * 60)
97 | expect(answeredFor("forever")).toBe(0)
^
error: expect(received).toBe(expected)
Expected: 0
Received: 1
(fail) held keep-alive is not answered when storage redelivers it
(pass) control: keep-alive is answered once keepAlive(false) releases it
1 pass
1 fail
Sampling once a minute shows the reply is saved between 9.5 and 10.5 minutes after the keep-alive was sent, which is the 10-minute claim expiration. Only one keep-alive request is ever saved, so the reply is to the original request, delivered a second time.
Expected
The held keep-alive stays unanswered until Entity.keepAlive(false) is called, however many times storage redelivers it. Both tests pass.
Versions
[email protected] (current latest on npm). The same code is on main as of 2026-11-17: keepAliveEnabled in packages/effect/src/cluster/internal/entityManager.ts and packages/effect/src/cluster/internal/entityReaper.ts, and the 10-minute claim in both storage drivers.
Proposed fix
Track the id of the held keep-alive request instead of a boolean. A redelivery of that same request is ignored, so it stays held; a different keep-alive while one is held is answered as today; the latch still answers the held one when it opens. With this change both tests above pass.
--- a/packages/effect/src/cluster/internal/entityManager.ts
+++ b/packages/effect/src/cluster/internal/entityManager.ts
@@ export type EntityState = {
readonly keepAliveLatch: Latch.Latch
- keepAliveEnabled: boolean
+ /** The keep-alive request held until the latch opens, if any. */
+ keepAliveRequestId: Snowflake.Snowflake | undefined
}
@@
keepAliveLatch,
- keepAliveEnabled: false
+ keepAliveRequestId: undefined
}
@@
- if (server.keepAliveEnabled) return reply
- server.keepAliveEnabled = true
+ // Storage redelivers an unprocessed request once its claim expires.
+ // The held keep-alive is answered when the latch opens, never on redelivery.
+ if (server.keepAliveRequestId === message.envelope.requestId) return Effect.void
+ if (server.keepAliveRequestId !== undefined) return reply
+ server.keepAliveRequestId = message.envelope.requestId
return server.keepAliveLatch.whenOpen(Effect.suspend(() => {
- server.keepAliveEnabled = false
+ server.keepAliveRequestId = undefined
return reply
})).pipe(
--- a/packages/effect/src/cluster/internal/entityReaper.ts
+++ b/packages/effect/src/cluster/internal/entityReaper.ts
@@
- if (state.keepAliveEnabled || state.activeRequests.size > 0 || duration < maxIdleTime) {
+ if (state.keepAliveRequestId !== undefined || state.activeRequests.size > 0 || duration < maxIdleTime) {With this fix storage still re-claims the held keep-alive every 10 minutes and the entity manager ignores it each time. An alternative (untested) is to have isProcessingFor report the held keep-alive as in progress, so Sharding skips the redelivery before it reaches the entity manager.
Activity