workers-sdk icon indicating copy to clipboard operation
workers-sdk copied to clipboard

Returning an object in workflow step.do() emits jsrpc error

Open juliusliu02 opened this issue 4 months ago • 8 comments

What versions & operating system are you using?

System: OS: macOS 26.5.2 CPU: (12) arm64 Apple M4 Pro Memory: 341.64 MB / 24.00 GB Shell: 5.9 - /bin/zsh Binaries: Node: 26.1.0 - /Users/lau/.local/share/mise/installs/node/latest/bin/node npm: 11.13.0 - /Users/lau/.local/share/mise/installs/node/latest/bin/npm pnpm: 11.18.0 - /opt/homebrew/bin/pnpm bun: 1.3.14 - /opt/homebrew/bin/bun Deno: 2.7.14 - /opt/homebrew/bin/deno

The error happens in production deployment on Cloudflare.

Please provide a link to a minimal reproduction

https://github.com/juliusliu02/cloudflare-workflow-step-result-repro/

Describe the Bug

When a Workflow step returns a serializable object, Workers Observability emits an error event for the Workflow's jsrpc invocation:

The Workers runtime canceled this request because it detected that your Worker's code had hung and would never generate a response. Refer to: https://developers.cloudflare.com/workers/observability/errors/

The step and Workflow instance both complete successfully. The error appears only in the events and traces of the Worker containing the Workflow binding.

According to the documentation, any structured-cloneable object should be supported and therefore shouldn't cause an error.

Please provide any relevant error logs

jsrpc span

The Workers runtime canceled this request because it detected that your Worker's code had hung and would never generate a response. Refer to: https://developers.cloudflare.com/workers/observability/errors/

juliusliu02 avatar Aug 01 '26 00:08 juliusliu02

[!NOTE] This is an automated, advisory triage report generated by workers-devprod. It is not an official maintainer response — a maintainer will follow up.

🤖 Automated triage report

Issue Triage: cloudflare/workers-sdk#14959

Summary

Returning a structured-cloneable object from a Workflow step.do() callback causes the host Worker's jsrpc run invocation to emit a spurious "Workers runtime canceled this request... code had hung" error in Observability, even though the step and Workflow instance complete successfully.

Classification

  • Type: Bug
  • Component: packages/wrangler (product:workflows) for tooling ownership; root cause is in the Workers runtime (JSRPC lifecycle) — cloudflare/workerd
  • Severity: Medium
  • Has Reproduction: Yes (with link) — https://github.com/juliusliu02/cloudflare-workflow-step-result-repro/
  • Quality: Complete

Findings

  • Created: 2026-08-01
  • Author: juliusliu02
  • Version: Reporter did not state a wrangler version (env: macOS 26.5.2, Node 26.1.0). Commenters confirmed on wrangler 4.105.0, 4.116.0, and 4.118.0 across compat dates spanning 2025-07-13 to 2026-08-05.
  • Labels: package:wrangler, product:workflows
  • Comments: 8 (1 automated triage bot, 5 independent confirmations from other users, 1 investigation, 1 maintainer disposition)
  • State: Already CLOSED (last activity 2026-08-11)

Analysis

  • Exceptionally well-documented issue: a minimal repro, four independent production confirmations, a controlled variant matrix (return {ok:true} hangs; return 'ok' / no return are clean), and an A/B/A/B reversal test all isolate the trigger to an object returned from step.do().
  • Root cause is a Workers RPC lifecycle behavior in the deployed runtime: object return values get a system disposer that can keep the callee execution context alive (matching the intermittent "An RPC result was not disposed properly" warning). Primitives don't, which is why the JSON-string workaround works. WorkflowEntrypoint/step are platform APIs defined in cloudflare/workerd, not in this monorepo.
  • Symptom is production-only; wrangler dev --local (@cloudflare/workflows-shared / Miniflare) cannot reproduce it and does not implement the production hung-request/disposal diagnostics. So there is nothing shippable via Wrangler to fix this.
  • A maintainer (@petebacondarwin, CONTRIBUTOR) has already given the final disposition: "Let's track in cloudflare/workerd#6925." The issue is closed and being tracked at the canonical runtime issue.
  • Documentation impact worth flagging to the docs team: the Workflows get-started guide and API reference both return objects from steps, so users following the official quickstart hit this on their first run.

Recommendation

Status: CLOSE

Reasoning: The issue is already closed, and a maintainer has confirmed it is a Workers runtime (JSRPC lifecycle) bug being tracked in cloudflare/workerd#6925. It is not fixable in workers-sdk/Wrangler — the affected code lives in the runtime, not this monorepo. This maps to a "wrong repo / runtime issue" closure, tracked at a canonical workerd issue.

Action: Keep closed. Ensure it is linked to cloudflare/workerd#6925 for tracking. Separately, flag the Workflows docs team that the get-started guide example reproduces this so a note/workaround can be added until the runtime fix lands.

Suggested Labels: product:workflows (already applied)

Suggested Comment

Thanks everyone for the thorough investigation, controlled repros, and the A/B/A/B reversal test — that's an unusually clear diagnosis. This is a Workers runtime (JSRPC lifecycle / result disposal) behavior rather than something we can fix in Wrangler or the local tooling, so we're tracking it in cloudflare/workerd#6925. Please follow that issue for updates. In the meantime, returning a primitive (e.g. a JSON string parsed outside the step) from step.do() is a working mitigation.

Structured summary (JSON)
{
  "issueNumber": 14959,
  "title": "Returning an object in workflow step.do() emits jsrpc error",
  "githubUrl": "https://github.com/cloudflare/workers-sdk/issues/14959",
  "recommendation": "CLOSE",
  "difficulty": "n/a",
  "reasoning": "A maintainer confirmed this is a Workers runtime JSRPC lifecycle bug tracked in cloudflare/workerd#6925, not fixable in workers-sdk. The issue is already closed.",
  "suggestedAction": "Keep closed and linked to cloudflare/workerd#6925; separately flag the Workflows docs team that the get-started guide example reproduces this.",
  "hasSuggestedComment": true,
  "suggestedLabels": ["product:workflows"]
}

workers-devprod avatar Aug 01 '26 00:08 workers-devprod

We see the same production defect with small structured-cloneable step results such as {"kind":"resolve"} and {"kind":"done"}. The step callback logs completion, Cloudflare persists the output, and the Workflow reports Completed, but the containing rpcMethod: "run" invocation emits the hung-request exception. In one instance, this was only incorrect observability; in another, Cloudflare converted it into WorkflowInternalError, retried the successful step, and then completed. The impact therefore includes unnecessary retries, latency, and compute—not only error noise.

Environment: Wrangler 4.118.0, compatibility date 2026-05-22, production Worker version f779c1b8-1283-4aeb-b3a6-f1877b059c1a. Correlation examples: instance youtube-download-U7BDMRFpnq8 completed at 2026-08-04T10:57:03Z, then emitted the exception at 10:58:30.258Z; instance youtube-download-IwR-sGFbewA emitted it at 10:58:22.398Z and recorded an internal retry. We can provide the Cloudflare account ID privately for platform trace lookup.

alexander-zuev avatar Aug 04 '26 11:08 alexander-zuev

Independent confirmation in production, with some data that may help narrow the cause

Environment: compatibility_date 2025-07-13, wrangler 4.105.0, executionModel: "stateless", Workflow on a native schedules cron (no scheduled handler). Different compat date and wrangler version from the original report, so this is neither new nor specific to a recent release.

Scale and history

The error fires exactly once per Workflow run, without exception:

Period Schedule Error rate
Jul 29 – Aug 3 */15 * * * * (4 runs/hr) 4/hour
Aug 3 – now * * * * * (~57 runs/hr) ~57/hour

1,613 occurrences over the 7-day log retention window, and it is present at the very start of that window, so it predates this issue report by at least a week, and probably longer than retention can show.

Changing only the cron schedule moved the rate linearly with invocation count. Each run executes 8+ object-returning steps, yet still produces exactly one error, so it appears to be emitted once per jsrpc invocation rather than once per step.

The steps involved

Our steps returning primitives (numbers, booleans, strings, null) never correlate with the error. The two returning objects are present in every affected run:

// returns { mode, where }
const { mode, where } = await step.do("resolve mode", async () => { ... });

// returns { upserted, next } — 8+ times per run
const chunk = await step.do(`sync ${entity.name} #${n}`, STEP_CONFIG, ...);

A possibly useful distinction: run() vs step.do()

We had an unplanned 44-minute window where every invocation took an early return path in run(), executing exactly one step whose callback returns a string, and then returning an object from run() itself:

const blockedBy = await step.do("acquire run lock", async () => {
  const holder = await this.env.KV.get(LOCK_KEY);
  if (holder && holder !== event.instanceId) return holder; // string
  ...
  return null;
});
if (blockedBy) return { skipped: 1, blockedBy };  // object returned from run()

Across ~44 consecutive invocations in that window: outcome=ok, wall times 26–1500ms, and zero hung-request errors. The moment the object-returning steps resumed, the error returned on the very next invocation and every one after it.

That suggests returning an object from run() is fine, and the trigger is specifically an object returned from step.do() —hough we did not set this up as a controlled experiment, so treat it as an observation rather than proof.

Timing signature

The error consistently lands after the work has finished, not during it:

18:26:19Z outcome=exception wall=23085ms cpu~98ms (instance → complete, correct output) 18:26:42Z "...code had hung and would never generate a response"

The instance reaches complete with correct step output every time, ~7–20s before the cancellation is logged.

Impact

Mostly observability noise for us, matching the original report. But we also have runs where the same error correlates with the Workflows engine retrying an already-successful step, which matches @alexander-zuev second case, so the cost isn't purely cosmetic.

aerospace4 avatar Aug 04 '26 20:08 aerospace4

Independent confirmation, and a controlled reproduction that isolates the trigger.

@charlfields' note that primitive-returning steps never correlate with the error, together with his caveat that it was not set up as a controlled experiment, is what prompted this. It now is one.

Harness. A Worker containing one WorkflowEntrypoint and one route that starts an instance. No KV, no Durable Object, no secrets, no binding of any kind beyond the workflow itself, and no import from any other package. Variants are selected per instance, so one deploy yields every data point and every instance below ran on the same script version.

Result

The trigger is a step callback returning an object. Nothing else in the shape matters.

variant what the step does outcome instances
a return { ok: true } exception + the hang message 1/1 hung
h return 'ok' ok 3/3 clean
i no return statement at all ok 3/3 clean
g no step.do in run at all ok 3/3 clean

All ten instances report Completed / Success: Yes, with no retry and no failed step. Step output as persisted: h "ok", i null, a "{\"ok\":true}".

The four variant bodies, which are the entire difference between them:

case 'a': {
  await step.do('emit', async () => {
    done(marker, 'a', '...')
    return { ok: true }
  })
  return
}

case 'h': {
  await step.do('emit', async () => {
    done(marker, 'h', '...')
    return 'ok'
  })
  return
}

case 'i': {
  await step.do('emit', async () => {
    done(marker, 'i', '...')
  })
  return
}

case 'g': {
  done(marker, 'g', '...')
  return
}

done() is a single console.log of a JSON line, and it is the only thing any of them does.

What this rules out

  • The invocation itself. g runs a WorkflowEntrypoint.run containing no step at all and is recorded ok three times out of three. So "a run invocation produces no Response" is not the mechanism.
  • The presence of a return value. i's callback returns undefined and is clean. So the boundary is not value versus no value; it is specifically an object.
  • run's own return. An earlier variant of this harness, byte-identical to a except that run returns a value, hung exactly like a. That matches @charlfields' 44-minute window from the other direction: an object returned from run was fine, an object returned from step.do was not.
  • compatibility_date. Same worker, same script bytes, two deploys differing in nothing but the date: 2026-06-13 and 2026-08-05, both hung, 17 ms and 18 ms. With 2025-07-13 and 2026-05-22 already reported here, that is four dates spanning just over a year.
  • Step count, step.sleep, an outbound fetch, and whether a response body is consumed. Earlier variants covering each of those reproduced the symptom, and each of them returned an object from a step.
  • A partial mitigation. One of those earlier variants runs three steps where the first two return strings and only the third returns an object, and it hung like the rest. That is consistent with the once-per-invocation rate @charlfields measured across 8+ object-returning steps: one object anywhere in the run appears to be enough.

Timing

The message lands 16 to 18 ms after the run's own last log line, taken from the log records' epoch-millisecond timestamps rather than from a rendered view:

08:10:17.778Z  workflow done
08:10:17.794Z  The Workers runtime canceled this request because it detected that your Worker's
               code had hung and would never generate a response.

This thread reports 7 to 20 seconds, and one worked example of 87 seconds between completion and the exception. A spread from 16 ms to 87 s on one symptom suggests at least one of the two is timing log ingestion rather than emission. It seems worth pinning down, because "fires immediately after user code returns" and "fires a minute and a half later" point at different mechanisms.

Record shape, in case it helps whoever picks this up

A hung invocation produces two records, not one:

  • the invocation summary, $metadata.type: "cf-worker-event", carrying outcome: "exception" with wallTimeMs and cpuTimeMs and no exception payload, stamped at invocation start - 185 to 228 ms before the run's own log line;
  • the message, $metadata.type: "cf-worker", at error level, carrying a source.exception object with its own timestamp.

Every affected record carries executionModel: "stateless" and $workers.event = {"rpcMethod": "run"}.

Two things we did not see

  • No retry. Across the twelve invocations above, and across every production run we hold logs for, no successful step was retried and no WorkflowInternalError appeared. That does not contradict @alexander-zuev or @charlfields - our runs here are single-step and theirs are not - but if the retry only appears on some shapes, that distinction is probably worth having.
  • Nothing on the Workflows side. The Instances view reads Complete 23 / Errored 0 over a population that includes every hung invocation above.

Environment

wrangler 4.118.0. compatibility_date 2026-06-13 and 2026-08-05. observability.enabled: true with head_sampling_rate: 1. No other configuration and no other binding. Script versions c3bf44fc-f4fc-4dcd-9b20-52970cf21aa6 and 28373003-4878-4019-b785-968a7a6e44ab. Instance ids and the account id are available privately for a platform trace lookup.

garystupak avatar Aug 05 '26 09:08 garystupak

Fourth independent production confirmation, with an A/B/A/B revert test and a workaround that removes the error.

Summary: returning an object from step.do() reproduces the hung-request exception mentioned above; returning the same value as a JSON string removes it. Reverting between the two behaviors reproduced this cleanly in production.

Environment. wrangler 4.116.0, compatibility_date 2026-07-30, nodejs_compat, executionModel: "stateless", head_sampling_rate: 1. A Workflow on a 15-minute cron, three instances per tick, each running 5–11 object-returning steps against D1 and a third-party API. All records carry rpcMethod: "run", eventType: "workflow".

Baseline was 3 hung of 3 on every tick for days, ~300/day. Account, instance, and request IDs are available privately.

Reversal test (A-B-A-B)

Applying a workaround and watching the error stop proves little on its own, so we withdrew the edit and then reinstated it. Only the step-return serialization changed between phases; cron configuration, input data, account, bindings, and Workflow logic were otherwise unchanged.

phase step returns ticks (UTC) hung
A — baseline object every tick, for days 3 of 3, ~300/day
B — workaround JSON string 23:33, 23:48, 00:03 0 of 9 (all clean)
A′ — withdrawn object 00:33, 00:48 6 of 6
B′ — reinstated JSON string 01:03, 01:18, 01:33 0 of 9

The symptom returned on the very first tick after withdrawing the workaround, every instance, with the exact message from the issue title, and stopped again on reinstatement.

Workaround

Since a step returning a string is clean and an object is not, make the value crossing the boundary a string and parse it back outside the step:

function stepJson<T>(
  step: WorkflowStep, name: string, config: WorkflowStepConfig, fn: () => Promise<T> | T,
): Promise<T> {
  return step
    .do(name, config, async () => {
      const value = await fn();
      return value === undefined ? '' : JSON.stringify(value);
    })
    .then((json) => (json === '' ? undefined : JSON.parse(json)));
}

The step body is untouched, so retries, idempotency and replay are unaffected.

However: Two things to know:

  1. JSON.stringify(undefined) returns undefined rather than a string and JSON.parse then throws on it, so a side-effect-only step needs the empty-string sentinel or it throws after its write has committed.
  2. JSON is narrower than the engine's serialization – a Date returns an ISO string while the type still claims Date – so this only for plain-data step results.

The hang itself costs no clock time

Across the reversal test, application execution time was comparable whether or not the hung-request exception was recorded.

The slowest relevant run in the experiment was a clean invocation at about 27.4 s, while the fastest affected invocation was about 20.7 s. The variation appears attributable to the upstream API rather than time spent in a runtime hang.

So the invocation is not hanging and then being reaped; it ends normally and then an exception is recorded after. That leaves error-rate noise, plus the genuinely costly retries @alexander-zuev and @charlfields saw, but we observed no latency or compute from the hang on its own.

This also fits @garystupak's 16–18 ms and suggests the 7–20 s and 87 s figures are timing log ingestion rather than emission.

An undisposed-RPC-result warning in the same invocation

This is not mentioned in the thread but we consistently observed hung invocations carry this, before their own completion log. One invocation from phase A′ (reverted test), verbatim:

00:33:22.071Z  warn   An RPC result was not disposed properly. One of the RPC calls you made
                      expects you to call dispose() on the return value, but you didn't do so.
                      You cannot rely on the garbage collector for this because it may take
                      arbitrarily long before actually collecting unreachable objects.

00:33:22.649Z  info   mirror.slice_completed

00:33:22.649Z  error  The Workers runtime canceled this request because it detected that your
                      Worker's code had hung and would never generate a response. Refer to:
                      https://developers.cloudflare.com/workers/observability/errors/

During our reversal testing, we observed that 4 of the 6 hung invocations in phase A′ carried it; 0 of the 14 clean invocations in B and B′ whose full logs we observed contain this.

It is not present in every hung invocation, and the ones erroring are reproducible rather than random. The same two of our three parallel streams carried it in both A′ logs, and the third never did, despite all three running the same code against the same bindings. The offset also varies (0.2–6.9s before the last log). So it accompanies the hang without being a one-to-one marker for it.

Adding this additional report because run() takes no RPC stub of its own. There are no Workflow handles, no service bindings, and no Durable Objects. The only binding it touches is D1. The warning is raised on a path where our code holds no RPC result at all.

Offered as an observation, not a diagnosis: it is consistent with the jsrpc boundary wrapping the non-primitive step result in something that is never released.

Possibly the same bug as cloudflare/workerd#6925

workerd#6925 reports identical cancellation on a Workflow invocation from a different trigger: a caught step.waitForEvent() timeout, no object-returning step. Its author asks whether waitForEvent() leaves "a pending resolver, event listener, or other promise associated with the Workflow invocation".

That is the same shape as the warning above: something stays attached to the invocation after user code finishes.

Local dev cannot reproduce this

wrangler dev --local runs the same workflow shape clean. Control: a scratch workflow that deliberately drops an RPC stub undisposed also runs clean locally, with no warning. The local Workflows engine does not implement the production disposal diagnostic at all, so a clean local run is evidence of nothing. Flagging before anyone tries to reproduce it there.

Tested locally on macOS 26.5.1 with wrangler 4.116.0 and in production Workers. Instance and account IDs are available for platform lookup.

NextifyLabs avatar Aug 10 '26 02:08 NextifyLabs

Same conclusion here, and it is now running in production.

@NextifyLabs' A-B-A-B reversal is the strongest evidence in this thread, and our controlled variants above point the same way, so I converted my Workflow to match: every step callback that returned an object now returns a JSON string, parsed outside the step. Callbacks whose result is discarded return nothing. Steps that already returned a string were left unchanged.

The symptom stopped. Across every run since that change, each Workflow invocation is recorded outcome: "ok" - where before it, every completing invocation carried the message.

One thing that has not come up yet, and it may matter: the Workflows get-started guide reproduces the bug with its own example. In /workflows/get-started/guide/, the first step returns await response.json<IPResponse>() and the second returns { name, ipCount }. Both are objects, which is exactly the shape that triggers the message.

And the API reference points the other way: /workflows/build/workers-api/ lists Object and Array as serializable step returns alongside the primitives, with only Function, Symbol and circular references excluded - and those are documented as throwing an error, which this does not.

/workflows/build/rules-of-workflows/ says nothing about the shape of a step's return at all; its guidance is about size.

So this is not a corner case. Anyone following the official quickstart gets the error on their first run, with nothing in the documentation to suggest why.

garystupak avatar Aug 10 '26 05:08 garystupak

Investigation: not actionable in workers-sdk

I looked at this against workers-sdk (including @cloudflare/workflows-shared / Miniflare local Workflows) and the public repro. This is a production Workflows / workerd JSRPC lifecycle bug, not something Wrangler or the local tooling can fix.

Why it isn't a workers-sdk defect

  1. Symptom is production-only. Multiple reporters (and NextifyLabs' explicit local control) show wrangler dev --local stays clean. Local Workflows are powered by @cloudflare/workflows-shared in this repo; that path does not implement the production hung-request / undisposed-RPC diagnostics, and a clean local run does not mean the SDK is correct while production is wrong — it means the failure lives in the deployed runtime.
  2. The failing span is the user Worker's JSRPC run. Records carry rpcMethod: "run" / executionModel: "stateless" on the Worker that hosts the WorkflowEntrypoint. The Workflow instance still completes with the correct step output. That matches an invocation-lifecycle problem on the run RPC, not a Wrangler deploy/config bug.
  3. WorkflowEntrypoint / step are platform APIs. WorkflowEntrypoint is defined in cloudflare/workerd (cloudflare:workers), not in this monorepo. Context in workflows-shared is an RpcTarget used for local engine/binding behavior; production completion/cancellation is not owned by a package we can patch and ship via Wrangler alone (workflows-shared's deploy script is a no-op).
  4. Object-vs-primitive trigger matches Workers RPC lifecycle rules. Per Workers RPC lifecycle: an RPC that returns any object gets a system disposer and can keep the callee's execution context alive until dispose; primitives do not. That lines up exactly with the controlled matrix here (return { ok: true } hangs; return 'ok' / no return are clean) and with the intermittent "An RPC result was not disposed properly" warning. The JSON-string workaround works because it forces a primitive across the step.do RPC boundary.

Recommended venue

  • Track / fix in cloudflare/workerd (JSRPC disposal + Workflow run completion), and/or the internal Workflows engine that invokes run.
  • Likely related: cloudflare/workerd#6925 (same false hung-request cancellation after Workflow teardown, different trigger).
  • Until a runtime fix lands, the JSON-stringify (or equivalent primitive) workaround remains the practical mitigation. using on object-valued RPC results is the generic RPC pattern, but it is poor DX for the documented step.do object/array return types and should not be required for the happy path.

Recommendation: transfer or open a linked workerd/Workflows platform issue; keep this open only as a pointer, or close as transferred once that exists. A cosmetic workers-sdk PR would not fix production.

HaoChiBao avatar Aug 10 '26 22:08 HaoChiBao

Let's track in https://github.com/cloudflare/workerd/issues/6925

petebacondarwin avatar Aug 11 '26 12:08 petebacondarwin