Repository navigation
Description
Note: everything below was written by an AI agent working on the author's behalf and may not have been reviewed by a human.
Summary
A child workflow's execution id comes from its idempotencyKey, so two parent workflows that call Child.execute with the same payload share one child execution. When that child completes, only one parent is woken. Any other parent awaiting the child stays Suspended until something calls Parent.resume on it explicitly.
Both engines are affected, with one difference:
@effect/platform-cloudflare(CloudflareWorkflowEngine): the first parent to reach the child is recorded and woken. A second parent is never recorded. If the child was started on its own first (no parent), the first parent that awaits it is recorded later and is woken.ClusterWorkflowEngine: only the parent carried by the child's firstrunrequest is woken. Later parents send arunrequest that is stored as a duplicate, and their parent is dropped. So if the child was started on its own first, even a single parent that awaits it is never woken.
Run on effect / @effect/platform-cloudflare 4.1.4 in wrangler dev, and on main at 0d2bb4a in the repository's tests (the cluster test below, and the same two-parent case against the Cloudflare engine's in-memory test namespace). Published 4.1.5 was only read: these code paths are unchanged there.
Reproduction (ClusterWorkflowEngine, single in-memory runner)
Save as packages/effect/test/cluster/SharedChild.test.ts in this repository, then run pnpm vitest run test/cluster/SharedChild.test.ts from packages/effect.
import { assert, describe, it } from "@effect/vitest"
import { Effect, Layer, Option, Schema } from "effect"
import {
ClusterWorkflowEngine,
MessageStorage,
RunnerHealth,
Runners,
RunnerStorage,
Sharding,
ShardingConfig
} from "effect/cluster"
import { TestClock } from "effect/testing"
import { DurableDeferred, Workflow, WorkflowEngine } from "effect/workflow"
const saves: Array<string> = []
// `saveRequest` is wrapped only to show whether each `run` request is new or a duplicate.
const engine = ClusterWorkflowEngine.layer.pipe(
Layer.provideMerge(Sharding.layer),
Layer.provide(Runners.layerNoop),
Layer.provideMerge(Layer.effect(
MessageStorage.MessageStorage,
Effect.map(MessageStorage.MessageStorage, (storage) => ({
...storage,
saveRequest: (message) =>
Effect.tap(storage.saveRequest(message), (result) =>
Effect.sync(() => {
saves.push(`${message.envelope.address.entityType} ${message.envelope.tag}: ${result._tag}`)
}))
}))
).pipe(Layer.provideMerge(MessageStorage.layerMemory))),
Layer.provide(RunnerStorage.layerMemory),
Layer.provide(RunnerHealth.layerNoop),
Layer.provide(ShardingConfig.layer({ entityMessagePollInterval: 5000 }))
)
// Advances the test clock until the execution reaches `tag`, or for ten simulated minutes.
const settle = <A extends Schema.Top, E extends Schema.Top>(
workflow: Workflow.Workflow<any, any, A, E>,
executionId: string,
tag: "Suspended" | "Complete"
) =>
Effect.gen(function*() {
const sharding = yield* Sharding.Sharding
for (let i = 0; i < 6000; i++) {
const result = yield* workflow.poll(executionId)
if (Option.isSome(result) && result.value._tag === tag) return result
yield* TestClock.adjust(100)
yield* sharding.pollStorage
}
return yield* workflow.poll(executionId)
})
const Gate = DurableDeferred.make("Gate", { success: Schema.String })
const Child = Workflow.make("Child", {
payload: { key: Schema.String },
success: Schema.String,
idempotencyKey: ({ key }) => key
})
const Parent = Workflow.make("Parent", {
payload: { name: Schema.String },
success: Schema.String,
idempotencyKey: ({ name }) => name
})
const register = Effect.gen(function*() {
const engine = yield* WorkflowEngine.WorkflowEngine
// The child waits on a deferred, so the test decides when it completes.
yield* engine.register(Child, () => DurableDeferred.await(Gate))
yield* engine.register(Parent, ({ name }) =>
Effect.map(Child.execute({ key: "shared" }), (value) => `${name} got ${value}`))
})
const completeChild = Effect.gen(function*() {
const childId = yield* Child.executionId({ key: "shared" })
yield* DurableDeferred.succeed(Gate, {
token: DurableDeferred.tokenFromExecutionId(Gate, { workflow: Child, executionId: childId }),
value: "done"
})
console.log("child:", Option.getOrUndefined(yield* settle(Child, childId, "Complete"))?._tag)
})
describe("ClusterWorkflowEngine", () => {
it.effect("wakes a second parent that awaits a child another parent started", () =>
Effect.gen(function*() {
saves.length = 0
yield* register
const a = yield* Parent.execute({ name: "A" }, { discard: true })
yield* settle(Parent, a, "Suspended")
const b = yield* Parent.execute({ name: "B" }, { discard: true })
yield* settle(Parent, b, "Suspended")
yield* completeChild
const resultA = yield* settle(Parent, a, "Complete")
const resultB = yield* settle(Parent, b, "Complete")
console.log("child run requests:", saves.filter((s) => s.startsWith("Workflow/Child run")))
console.log("parent A:", Option.getOrUndefined(resultA)?._tag)
console.log("parent B:", Option.getOrUndefined(resultB)?._tag)
assert.strictEqual(Option.getOrUndefined(resultB)?._tag, "Complete")
}).pipe(Effect.provide(engine)), 60_000)
it.effect("wakes a parent that awaits a child started on its own", () =>
Effect.gen(function*() {
saves.length = 0
yield* register
yield* Child.execute({ key: "shared" }, { discard: true })
yield* settle(Child, yield* Child.executionId({ key: "shared" }), "Suspended")
const a = yield* Parent.execute({ name: "A" }, { discard: true })
yield* settle(Parent, a, "Suspended")
yield* completeChild
const resultA = yield* settle(Parent, a, "Complete")
console.log("child run requests:", saves.filter((s) => s.startsWith("Workflow/Child run")))
console.log("parent A:", Option.getOrUndefined(resultA)?._tag)
assert.strictEqual(Option.getOrUndefined(resultA)?._tag, "Complete")
}).pipe(Effect.provide(engine)), 60_000)
})Output on main (0d2bb4a):
wakes a second parent that awaits a child another parent started
child: Complete
child run requests: [ 'Workflow/Child run: Success', 'Workflow/Child run: Duplicate', 'Workflow/Child run: Duplicate' ]
parent A: Complete
parent B: Suspended
wakes a parent that awaits a child started on its own
child: Complete
child run requests: [ 'Workflow/Child run: Success', 'Workflow/Child run: Duplicate' ]
parent A: Suspended
In a separate run of the same case, calling Parent.resume(b) after this completed B straight away with the child's result, so B is only missing its wake.
Reproduction (@effect/platform-cloudflare, wrangler dev)
effect 4.1.4, @effect/platform-cloudflare 4.1.4, wrangler 4.166.0, local wrangler dev. wrangler.jsonc follows the package README: CLUSTER_ENTITY, CLUSTER_WORKFLOW, CLUSTER_QUEUE and CLUSTER_SINGLETON are bound to the four exported classes, all declared as SQLite classes. The worker below is the one that ran, with only the parts for an unrelated case removed:
import { CloudflareCluster, CloudflareDurableObjects } from "@effect/platform-cloudflare"
import { Effect, Layer, ManagedRuntime, Option, Schema } from "effect"
import { DurableClock, Workflow } from "effect/workflow"
export {
ClusterDurableQueue,
ClusterEntity,
ClusterSingleton,
ClusterWorkflow
} from "@effect/platform-cloudflare/CloudflareDurableObjects"
// Child: suspends once on a durable clock, then completes. Its execution id is
// derived from `key` alone, so every caller passing the same key shares it.
const Child = Workflow.make("Child", {
payload: { key: Schema.String },
success: Schema.String,
idempotencyKey: ({ key }) => key
})
// Parent: starts Child with a fixed key and awaits its result.
const Parent = Workflow.make("Parent", {
payload: { name: Schema.String, childKey: Schema.String },
success: Schema.String,
idempotencyKey: ({ name }) => name
})
const ChildLayer = Child.toLayer(({ key }) =>
Effect.gen(function*() {
yield* DurableClock.sleep({ name: "wait", duration: "10 seconds" })
return `child result for ${key}`
})
)
const ParentLayer = Parent.toLayer(({ childKey, name }) =>
Effect.gen(function*() {
const result = yield* Child.execute({ key: childKey })
return `parent ${name} got: ${result}`
})
)
const clusterLayer = (env: any) =>
Layer.mergeAll(ChildLayer, ParentLayer).pipe(
Layer.provideMerge(CloudflareCluster.layer({
entities: [],
entityNamespace: env.CLUSTER_ENTITY,
workflowNamespace: env.CLUSTER_WORKFLOW,
queueNamespace: env.CLUSTER_QUEUE,
singletonNamespace: env.CLUSTER_SINGLETON
}))
)
// Initializer exactly as in the package README.
let application: ManagedRuntime.ManagedRuntime<any, any> | undefined
const initialize = CloudflareDurableObjects.setInitializer(async (env: any) => {
if (application !== undefined) return application.context()
const runtime = ManagedRuntime.make(clusterLayer(env))
const context = await runtime.context().catch(async (error) => {
await runtime.dispose()
throw error
})
if (application === undefined) {
application = runtime
return context
}
await runtime.dispose()
return application.context()
})
const describe = (id: string, polled: Option.Option<Workflow.Result<any, any>>) =>
Option.match(polled, {
onNone: () => ({ executionId: id, state: "no result stored" }),
onSome: (r) =>
r._tag === "Complete"
? { executionId: id, state: "Complete", exit: r.exit._tag === "Success" ? r.exit.value : String(r.exit) }
: { executionId: id, state: "Suspended" }
})
const routes: Record<string, (q: URLSearchParams) => Effect.Effect<unknown, unknown, any>> = {
// Starts are fire-and-forget (discard), the way a Worker request would start them.
"/parent/start": (q) => Parent.execute({ name: q.get("name")!, childKey: q.get("child")! }, { discard: true }),
"/parent/poll": (q) =>
Effect.gen(function*() {
const id = yield* Parent.executionId({ name: q.get("name")!, childKey: q.get("child")! })
return describe(id, yield* Parent.poll(id))
}),
"/parent/resume": (q) =>
Effect.gen(function*() {
const id = yield* Parent.executionId({ name: q.get("name")!, childKey: q.get("child")! })
yield* Parent.resume(id)
return { resumed: id }
}),
"/child/start": (q) => Child.execute({ key: q.get("key")! }, { discard: true }),
"/child/poll": (q) =>
Effect.gen(function*() {
const id = yield* Child.executionId({ key: q.get("key")! })
return describe(id, yield* Child.poll(id))
}),
}
export default {
async fetch(request: Request, env: any): Promise<Response> {
const url = new URL(request.url)
if (url.pathname === "/health") return new Response("ok")
const route = routes[url.pathname]
if (route === undefined) return new Response("not found", { status: 404 })
await initialize(env)
const exit = await application!.runPromiseExit(route(url.searchParams))
return exit._tag === "Success"
? Response.json({ ok: true, value: exit.value ?? null })
: Response.json({ ok: false, cause: String(exit.cause) }, { status: 500 })
}
}A small script drove it over HTTP: start Parent A (/parent/start?name=A-…&child=c), wait until it is Suspended, start Parent B with the same child, wait until it is Suspended, wait for the child to complete, then poll each parent for up to 75 s. That is longer than the engine's 60 s guard alarm, so the guard had its chance to wake B too.
Run log (verbatim):
[+ 1.1s] starting Parent A (execution A), which runs Child.execute({ key: "child-mwtet0oj" })
[+ 1.2s] Parent A: {"executionId":"7aea5e316620ff017c3d03cf3d70cf3d","state":"Suspended"}
[+ 1.2s] starting Parent B (execution B), which runs the SAME Child.execute({ key: "child-mwtet0oj" })
[+ 1.2s] Parent B: {"executionId":"e350d6dded85b6db5813c8d80351e30a","state":"Suspended"}
[+ 61.2s] child: {"executionId":"928a8ba819f514654b41fe949f2b8a8d","state":"Complete","exit":"child result for child-mwtet0oj"}
[+ 61.2s] Parent A completed: {"executionId":"7aea5e316620ff017c3d03cf3d70cf3d","state":"Complete","exit":"parent A-mwtet0oj got: child result for child-mwtet0oj"}
[+ 61.2s] waiting up to 75s for Parent B to complete ...
[+136.5s] TIMEOUT: Parent B still not complete after 75s: {"executionId":"e350d6dded85b6db5813c8d80351e30a","state":"Suspended"}
[+136.5s] explicit Parent.resume(B) to show B only lacked a wake-up:
[+136.5s] Parent B after resume: {"executionId":"e350d6dded85b6db5813c8d80351e30a","state":"Complete","exit":"parent B-mwtet0oj got: child result for child-mwtet0oj"}
A second run started the child on its own first (/child/start, no parent), then A, then B. A was recorded as the child's parent and woken at +61.1 s. B was still Suspended at +136.7 s and completed straight after an explicit resume.
(The child's 10 s DurableClock.sleep completing at about 60 s rather than 10 s is a separate matter and does not affect this issue.)
Expected
Every non-detached parent that is suspended on Child.execute for an execution is woken when that execution completes, on both engines, whichever caller started the child.
Observed
Only one parent is woken: on Cloudflare the first recorded one, on cluster the one in the first run request. Every other parent stays Suspended until an explicit resume.
Where
@effect/platform-cloudflare at 0d2bb4a:
-
packages/platform/cloudflare/src/internal/workflowRuntime.ts:287-296(run): a second parent is ignored becauserow.parentis already set.} else if (opts.parent !== undefined && row.parent === undefined) { // An execution started standalone can gain a parent later; keep the // first parent so its completion still wakes that parent. WorkflowStorage.setParent(sql, opts.parent)
-
packages/platform/cloudflare/src/internal/workflowStorage.ts:16-17, 143-148: oneparent_name/parent_execution_idpair per execution;setParentonly writesWHERE parent_name IS NULL. -
packages/platform/cloudflare/src/internal/workflowRuntime.ts:142-160(resumeParent,deliverParentWake): wakes onlyrow.parent.
ClusterWorkflowEngine at 0d2bb4a:
packages/effect/src/cluster/ClusterWorkflowEngine.ts:692-707(execute): the parent travels inside therunrequest's payload.packages/effect/src/cluster/ClusterWorkflowEngine.ts:1036-1046: therunRPC'sprimaryKeyis"", so every laterrunfor the execution is a duplicate of the first.packages/effect/src/cluster/Runners.ts:233-256: a duplicate request is answered from the original request; its own payload, including its parent, is never read.packages/effect/src/cluster/ClusterWorkflowEngine.ts:521-536: on exit, the run wakes only the parent read from the first request's payload.
Both engines reach these paths from packages/effect/src/workflow/WorkflowEngine.ts:578-586: a parent whose child reports Suspended suspends itself, and polling with suspendedRetrySchedule only applies to callers outside a workflow (:595-615), so a suspended parent depends entirely on that wake.
Proposed fix
Record every awaiting parent, not one, and wake each of them when the execution completes.
- Cloudflare: replace the single
parent_name/parent_execution_idpair with a small table of parents (keyed by parent workflow name and execution id), insert on everyrunthat carries a non-detached parent, and havedeliverParentWakeresume each recorded parent, clearing each one as its resume is acknowledged, so the existing guard-alarm retry keeps working per parent. If the execution has already completed when a new parent arrives,runalready returns the stored result, so no record is needed in that case. - Cluster: when a
runrequest is a duplicate and carries a parent other than the one in the original request, record that parent (for example as a persistedresumesubscription on the child, or by having the parent's own run register a wake with the child), and have the exit path inClusterWorkflowEngine.ts:535-536sendsendResumeParentto every recorded parent.
Not tested; offered as a direction.
Activity