[vitest-plugin] Durable Objects' on-demand import() fails with "Cannot perform I/O on behalf of a different Durable Object" under Vitest 5.1

Open
#16,850 1 comment 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 1 day

Nobody has claimed this yet.

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
22/100
Issue type
Bug
Clarity
Mostly clear
Activity status
Active
Tech stack
typescript, wasm
Domain
testing-qa

Research direction

The failure surfaces in the Vitest plugin's module runner when several Durable Object instances run dynamic import() at once; the report names no source file, so start by reproducing with the attached files and reading how the runner transport is routed to each object. Done means the concurrent imports resolve without unhandled rejections under vitest 5.1, with the test suite exiting 0.

Written by the indexing model from the issue text.

Description

bug package:vitest regression
What versions & operating system are you using?
System: Linux 7.0 (Ubuntu 26.04), x64
Node: 24.11.1, pnpm: 12.11.2
@cloudflare/vitest-plugin: 1.6.1
vitest: 5.1.0
wrangler: 4.159.0 (workerd 1.20261109.1, miniflare 5.20261109.0-beta)
Please provide a link to a minimal reproduction

Inline below (eighteen small files, no repository): a2.ts to a4.ts and b2.ts to b4.ts are copies of a1.ts and b1.ts with their own number.

Describe the Bug

A Durable Object that imports a module on demand (await import('./a'), where ./a imports ./b) fails under Vitest 5.1 when several objects do it at about the same time: every object but the first gets an unhandled rejection

Error: Cannot perform I/O on behalf of a different Durable Object. I/O objects (such as streams, request/response bodies, and others) created in the context of one Durable Object cannot be accessed from a different Durable Object in the same isolate. This is a limitation of Cloudflare Workers which allows us to improve overall performance. (I/O type: Lock&)

pnpm install && pnpm test with the files below: 4 runs out of 4 end with 36 such errors (four rounds of ten objects, one error per object but the first of each round), exit code 1, while the 41 tests pass. Changing only vitest to 5.0.5 (plugin 1.6.1, or plugin 1.4.7): 0 runs out of 3.

Each of the four is needed to trigger it here:

  • a setupFiles entry, even an empty file;
  • a large package evaluated by the test file before the objects (@sentry/cloudflare; a chain of 300 local modules or tlds did not trigger it);
  • a call to another object in flight when the import starts;
  • an imported module that imports another one (./a1 alone never fails).

The production build is not affected: the same on-demand import (a chunk that imports another chunk), from three objects at once, works under vite preview of the built Worker.

This looks like a regression of #12924 (dynamic import() in handlers, fixed by routing the module runner transport through the runner object), brought by Vitest 5.1.

Expected: each object's import() resolves, as with Vitest 5.0.5.

package.json

{
  "name": "repro",
  "private": true,
  "type": "module",
  "scripts": {
    "test": "vitest run"
  },
  "devDependencies": {
    "@cloudflare/vitest-plugin": "1.6.1",
    "@sentry/cloudflare": "11.8.0",
    "vitest": "5.1.0",
    "wrangler": "4.159.0"
  }
}

pnpm-workspace.yaml

allowBuilds:
  esbuild: true
  workerd: true

wrangler.jsonc

{
  "name": "repro",
  "main": "index.ts",
  "compatibility_date": "2026-10-06",
  "compatibility_flags": ["nodejs_compat"],
  "durable_objects": { "bindings": [{ "name": "OBJECT", "class_name": "Room" }] },
  "migrations": [{ "tag": "v1", "new_sqlite_classes": ["Room"] }]
}

vitest.config.ts

import { cloudflareTest } from '@cloudflare/vitest-plugin'
import { defineConfig } from 'vitest/config'

export default defineConfig({
  plugins: [cloudflareTest({ wrangler: { configPath: './wrangler.jsonc' } })],
  test: { setupFiles: ['./setup.ts'] },
})

tsconfig.json

{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "moduleResolution": "bundler",
    "strict": true,
    "types": ["@cloudflare/vitest-plugin/types"]
  }
}

setup.ts

// Any setup file.
export {}

index.ts

import { DurableObject } from 'cloudflare:workers'

type Env = { OBJECT: DurableObjectNamespace<Room> }

declare global {
  // Shared by the isolate: the test reads it without calling the objects.
  var loaded: string[]
}
globalThis.loaded ??= []

const IMPORTS: Record<string, () => Promise<unknown>> = {
  r1: () => import('./a1'),
  r2: () => import('./a2'),
  r3: () => import('./a3'),
  r4: () => import('./a4'),
}

export class Room extends DurableObject<Env> {
  async fetch(): Promise<Response> {
    const [client, server] = Object.values(new WebSocketPair())
    this.ctx.acceptWebSocket(server)
    return new Response(null, { status: 101, webSocket: client })
  }

  async webSocketMessage(ws: WebSocket): Promise<void> {
    // Calls another object, answers, then imports `./aN` (which imports `./bN`) on demand: one
    // pair of modules per round of objects, each round a new chance to hit the error.
    this.ctx.waitUntil(this.env.OBJECT.get(this.env.OBJECT.idFromName('other')).ping())
    ws.send('received')
    const name = this.ctx.id.name ?? ''
    this.ctx.waitUntil(IMPORTS[name.slice(0, 2)]?.().then(() => void globalThis.loaded.push(name)))
  }

  webSocketClose(ws: WebSocket): void {
    ws.close(1000, 'closed')
  }

  async ping(): Promise<void> {}
}

export default {
  fetch(request, env) {
    const name = new URL(request.url).pathname.slice(1)
    return env.OBJECT.get(env.OBJECT.idFromName(name)).fetch(request)
  },
} satisfies ExportedHandler<Env>

index.test.ts

import { exports } from 'cloudflare:workers'
import { beforeAll, expect, it, vi } from 'vitest'

// A package of @sentry/cloudflare's size, evaluated before the objects.
beforeAll(() => import('@sentry/cloudflare'), 60_000)

const NAMES = ['r1', 'r2', 'r3', 'r4'].flatMap((round) =>
  Array.from({ length: 10 }, (_, i) => `${round}-o${i}`),
)

it.each(NAMES)('object %s answers a message', async (name) => {
  const response = await exports.default.fetch(`http://example.com/${name}`, {
    headers: { Upgrade: 'websocket' },
  })
  const socket = response.webSocket
  if (!socket) throw new Error('No socket')
  socket.accept()
  const answered = new Promise((resolve) => socket.addEventListener('message', resolve, { once: true }))
  socket.send('hello')
  await answered
  socket.close(1000)
})

it('every object has imported its module', async () => {
  await vi.waitFor(() => expect(globalThis.loaded.toSorted()).toEqual(NAMES.toSorted()))
})

a1.ts

import { b } from './b1'

export const a = b + 1

b1.ts

export const b = 41
Please provide any relevant error logs
⎯⎯⎯⎯⎯⎯ Unhandled Errors ⎯⎯⎯⎯⎯⎯

Vitest caught 36 unhandled errors during the test run.
This might cause false positive tests. Resolve unhandled errors to make sure your tests are not affected.

⎯⎯⎯⎯ Unhandled Rejection ⎯⎯⎯⎯⎯
Error: Cannot perform I/O on behalf of a different Durable Object. [...] (I/O type: Lock&)
Dominant language
TypeScript
Stars
4.7k
Forks
1.7k
Avg merge
1d 22h
Merged PRs (30d)
282

Getting set up

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from cloudflare/workers-sdk

All issues in cloudflare/workers-sdk

Similar issues

More TypeScript issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.