Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/cloudflare-test-quiescence.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@systemfsoftware/agent-platform-cloudflare": none
---

The Cloudflare Durable Object suites no longer leave Object work running past a test; the published package is unchanged.
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
---
title: A Durable Object test that leaves work behind fails when the shared environment closes
date: 2026-11-26
category: test-failures
module: platform-cloudflare workerd suites
problem_type: flaky_test
component: testing
severity: high
applies_when:
- A workerd suite runs under @cloudflare/vitest-plugin with several test files sharing a pool worker
- A test aborts an Object or arms an alarm and returns before its work finishes
- A test caps a deterministic wait with its own wall-clock timeout
tags: [durable-objects, workerd, vitest-pool-workers, eviction, alarms, quiescence]
---

# A Durable Object test that leaves work behind fails when the shared environment closes

## Context

Three failures appeared in one CI lane that runs `@systemfsoftware/agent-platform-cloudflare` under
`@cloudflare/vitest-plugin`. A pool worker reuses one miniflare/workerd instance for every test file
it runs, and the budget is the suite's configured `testTimeout`, not the machine's spare CPU.

- `background-workers.test.ts` passed all nine tests and then reported
`EnvironmentTeardownError: [vitest-worker]: Closing rpc while "resolve" was pending`, 38 ms after
the last test returned. `resolve` is vitest's module-resolution RPC, i.e. an import still running
inside the environment.
- `progress-wait.test.ts` "reconnects after eviction..." hit its own 20 s cap at 20005 ms on a loaded
runner; the log showed the eviction landing 0.4 s in, then silence.
- `join-restart.test.ts` hit its own 10 s cap twice on a busy host; each scenario performs about
135 sequential SQLite operations plus a cold reconstruction, so 10 s was below what the work
needs when the CPUs are shared.

Measured with a probe: an in-flight `awaitProgress` RPC is not rejected by `state.abort()`. Workerd
re-runs the request on the fresh incarnation, the fresh incarnation reports the waiter, and the
client promise resolves when progress arrives. The client's retry classification therefore never
runs for an eviction.

## What does not work

- **Raising the per-test cap**: the cap is not the cause; the wait it guards is deterministic, and
raising it only moves the failure to the suite budget.
- **Retrying or skipping the test**: the test still asserts what it did before, so nothing is fixed.
- **A waiter-count gauge as the reconstruction latch**: a point-in-time count misses a replayed
request that registers and leaves between two observer calls.
- **Polling the Object with a fixed sleep**: it measures the clock under load and buys nothing the
Object can signal directly.

## What works

- Count subscriptions monotonically per incarnation, so a replay is observed whether or not it is
still parked, and latch on the count rather than on a gauge.
- Fork client work through a harness that tracks every fiber, and interrupt and await them after
each test instead of at the end of the file.
- After each test, disarm the eviction failpoints it armed and delete the persisted alarm of every
Object it touched, so no alarm pass starts while the environment is closing.
- Keep a generous per-test cap on a test whose own work is sub-second uncontended: a real hang then
fails in seconds instead of burning the suite budget. Remove the cap only where the test's
legitimate work sits within a small factor of it under CPU contention, as with the five-scenario
join test doing about 135 sequential SQLite operations per scenario against 10 s.
- Remove inner `Effect.timeout` guards on Deferred waits. They race CPU scheduling; a real deadlock
then fails at the suite level rather than as a scheduling accident.
7 changes: 6 additions & 1 deletion packages/platform-cloudflare/test/background-workers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import * as Effect from 'effect/Effect'
import * as Option from 'effect/Option'
import * as Schema from 'effect/Schema'
import * as TestClock from 'effect/testing/TestClock'
import { expect, it } from 'vitest'
import { afterEach, beforeEach, expect, it } from 'vitest'

import { ThreadMaintenance } from '../src/Alarm'
import { CloudflareThreadClient } from '../src/CloudflareThreadClient'
Expand Down Expand Up @@ -62,6 +62,8 @@ import {
import {
allSettled,
drainAlarmsUntil,
forgetTouchedObjects,
quiesceTouchedObjects,
readCanonical,
readExecution,
runClient,
Expand Down Expand Up @@ -102,6 +104,9 @@ const withOwner = <A, E>(
}),
))

beforeEach(forgetTouchedObjects)
afterEach(quiesceTouchedObjects)

// Requested proof seam: count actual cross-Object launch calls and pressure reads. Existing
// lifecycle cases below retain authority, receipt, contention and eviction coverage.
it('admits workers in one RPC and reads completions concurrently only at capacity', async ({
Expand Down
5 changes: 5 additions & 0 deletions packages/platform-cloudflare/test/fixtures.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,11 @@ export const armedEvictionsRemaining = (thread: string): number =>
(armedStorageEvictions.get(thread)?.length ?? 0) +
(armedRuntimeEvictions.get(thread)?.length ?? 0)

export const disarmEvictions = (thread: string): void => {
armedStorageEvictions.delete(thread)
armedRuntimeEvictions.delete(thread)
}

/** Storage failpoint factory for `ThreadObject.make`: armed hit → `ctx.abort()`. */
export const storageEvictionFailpoint = (ctx: DurableObjectState): DoStorageFailpointHandler =>
evictionFailpointHandler({
Expand Down
96 changes: 81 additions & 15 deletions packages/platform-cloudflare/test/harness.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,14 @@ import { env, runDurableObjectAlarm, runInDurableObject } from 'cloudflare:test'
import { DurableObject } from 'effect-cf'
import * as SecureRandom from 'effect/crypto/SecureRandom'
import * as Effect from 'effect/Effect'
import * as Fiber from 'effect/Fiber'
import * as Layer from 'effect/Layer'
import * as Option from 'effect/Option'
import * as Schema from 'effect/Schema'
import * as SqlClientService from 'effect/sql/SqlClient'
import { expect } from 'vitest'

import { decodeThreadId, supplierCountsFor, supplierValuesFor } from './fixtures'
import { decodeThreadId, disarmEvictions, supplierCountsFor, supplierValuesFor } from './fixtures'
import type {
ContextCompactorThreadObject,
ProjectionThreadObject,
Expand All @@ -52,13 +53,71 @@ export type TestNamespace =
| 'TELEMETRY'
| 'CONTEXT_COMPACTOR'

/** A FRESH stub for the named Thread (never cache stubs across aborts). */
export const stubFor = (thread: string, namespace: TestNamespace = 'THREADS') => {
interface TouchedObject {
readonly namespace: TestNamespace
readonly thread: string
}

const touchedObjects = new Map<string, TouchedObject>()
const clientFibers = new Set<() => Promise<void>>()

const namespaceStub = (thread: string, namespace: TestNamespace) => {
const binding = env[namespace]

return binding.get(binding.idFromName(thread))
}

/** A FRESH stub for the named Thread (never cache stubs across aborts). */
export const stubFor = (thread: string, namespace: TestNamespace = 'THREADS') => {
touchedObjects.set(`${namespace}:${thread}`, { namespace, thread })

return namespaceStub(thread, namespace)
}

export const forgetTouchedObjects = (): void => {
touchedObjects.clear()
}

const QUIESCENCE_CEILING = '5 seconds'

/**
* Teardown must not be able to stall the shared environment: a wedge in one Object or one
* uninterruptible RPC is dropped after the ceiling, and the next test starts clean either way.
*/
const settleWithinCeiling = (operation: Promise<unknown>): Promise<void> =>
Effect.runPromise(
Effect.tryPromise({ try: () => operation, catch: () => undefined }).pipe(
Effect.timeoutOption(QUIESCENCE_CEILING),
Effect.asVoid,
Effect.ignore,
),
)

export const interruptClientFibers = async (): Promise<void> => {
const interrupts = [...clientFibers]

clientFibers.clear()
await Promise.all(interrupts.map((interrupt) => settleWithinCeiling(interrupt())))
}

export const quiesceTouchedObjects = async (): Promise<void> => {
const objects = [...touchedObjects.values()]

touchedObjects.clear()
for (const { thread } of objects) disarmEvictions(thread)
await interruptClientFibers()
await Promise.all(
objects.map(({ namespace, thread }) =>
settleWithinCeiling(
runInDurableObject(
namespaceStub(thread, namespace),
(_instance, state) => state.storage.deleteAlarm(),
),
)
),
)
}

let nextProgressWaitIdentity = 0

const deterministicClientCrypto = Layer.succeed(
Expand Down Expand Up @@ -109,19 +168,26 @@ export const runScheduleClient = <A, E>(effect: Effect.Effect<A, E, Scheduling>)
export const runClientFiber = <A, E>(
effect: Effect.Effect<A, E, CloudflareThreadClient>,
namespace: TestNamespace = 'THREADS',
) => Effect.runFork(effect.pipe(Effect.provide(clientLayer(namespace))))
) => {
const fiber = Effect.runFork(effect.pipe(Effect.provide(clientLayer(namespace))))

const isDurableObjectReset = (cause: unknown): boolean =>
typeof cause === 'object' &&
cause !== null &&
(('retryable' in cause && cause.retryable === true) ||
('durableObjectReset' in cause && cause.durableObjectReset === true))
clientFibers.add(() => Effect.runPromise(Fiber.interrupt(fiber)).then(() => undefined))

return fiber
}

const isDurableObjectReset = (cause: unknown): boolean => {
if (typeof cause !== 'object' || cause === null) return false
if (
('retryable' in cause && cause.retryable === true) ||
('durableObjectReset' in cause && cause.durableObjectReset === true)
) {
return true
}

return cause instanceof Error && /outputGateBroken|Durable Object reset/.test(cause.message)
}

/**
* Follow an aborted Object to a fresh incarnation, then park on its exact waiter count.
* Attempts repeat only when the transport reports a reset or still reaches the prior
* incarnation; the count condition itself is an Object-side latch, never a timed poll.
*/
export const awaitReconstructedProgressWaiter = async (
thread: string,
previousIncarnation: number,
Expand All @@ -133,7 +199,7 @@ export const awaitReconstructedProgressWaiter = async (
try {
const incarnation = await (
stubFor(thread) as DurableObjectStub<TestThreadObject>
).awaitProgressWaiterCountAfter(previousIncarnation, expected)
).awaitProgressSubscribedAfter(previousIncarnation, expected)

if (incarnation !== null) return incarnation
} catch (cause) {
Expand Down
16 changes: 9 additions & 7 deletions packages/platform-cloudflare/test/join-restart.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,13 @@ import * as Layer from 'effect/Layer'
import * as Option from 'effect/Option'
import * as Schema from 'effect/Schema'
import * as Stream from 'effect/Stream'
import { expect, it } from 'vitest'
import { afterEach, beforeEach, expect, it } from 'vitest'

import { submitOptions } from './fixtures'
import { stubFor } from './harness'
import { forgetTouchedObjects, quiesceTouchedObjects, stubFor } from './harness'

beforeEach(forgetTouchedObjects)
afterEach(quiesceTouchedObjects)

// Requested Cloudflare seam: authoritative join claims, canonical reply coverage and
// eviction during replacement. Gated provider/handlers force the side-effect race.
Expand Down Expand Up @@ -296,7 +299,7 @@ it.each(['reply', 'tools', 'eviction', 'backlog', 'rejected'] as const)(
receipts = { receipt, joined }
joinedReceipts.push(joined)
if (scenario === 'rejected') {
yield* Deferred.await(rejected).pipe(Effect.timeout('2 seconds'))
yield* Deferred.await(rejected)
yield* Deferred.succeed(releaseFirst, undefined)
} else if (scenario === 'backlog') {
for (let index = 1; index < 32; index++) {
Expand All @@ -309,7 +312,7 @@ it.each(['reply', 'tools', 'eviction', 'backlog', 'rejected'] as const)(
)
}
yield* Deferred.succeed(joinBatches[0]!, undefined)
yield* Deferred.await(replacement).pipe(Effect.timeout('2 seconds'))
yield* Deferred.await(replacement)
for (let index = 32; index < 64; index++) {
joinedReceipts.push(
yield* runtime.submit(
Expand All @@ -320,8 +323,8 @@ it.each(['reply', 'tools', 'eviction', 'backlog', 'rejected'] as const)(
)
}
yield* Deferred.succeed(joinBatches[1]!, undefined)
yield* Deferred.await(secondReplacement).pipe(Effect.timeout('2 seconds'))
} else yield* Deferred.await(replacement).pipe(Effect.timeout('2 seconds'))
yield* Deferred.await(secondReplacement)
} else yield* Deferred.await(replacement)
if (evicts) {
const { ctx } = yield* DurableObjectContext

Expand Down Expand Up @@ -512,5 +515,4 @@ it.each(['reply', 'tools', 'eviction', 'backlog', 'rejected'] as const)(
}),
)
},
10_000,
)
19 changes: 8 additions & 11 deletions packages/platform-cloudflare/test/progress-wait.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { ApprovalDecisionCommand } from '@systemfsoftware/agent/submission-ledge
import { runInDurableObject } from 'cloudflare:test'
import * as Effect from 'effect/Effect'
import * as Fiber from 'effect/Fiber'
import { describe, expect, it, onTestFinished } from 'vitest'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'

import { ProgressWaitRegistry } from '../src/internal/progress-wait'
import { approvalDefinition, BOOK_TOOL_CALL_ID, decodeThreadId, submitOptions } from './fixtures'
Expand All @@ -14,6 +14,8 @@ import {
anyInState,
awaitReconstructedProgressWaiter,
drainAlarmsUntil,
forgetTouchedObjects,
quiesceTouchedObjects,
readCanonical,
runClient,
runClientFiber,
Expand Down Expand Up @@ -85,15 +87,10 @@ const awaitProgressEffect = Effect.fnUntraced(function*(
}
})

const runTrackedClientFiber = <A, E>(effect: Effect.Effect<A, E, CloudflareThreadClient>) => {
const fiber = runClientFiber(effect)

onTestFinished(() => Effect.runPromise(Fiber.interrupt(fiber)))

return fiber
}

describe('#94 Cloudflare durable progress wait', () => {
beforeEach(forgetTouchedObjects)
afterEach(quiesceTouchedObjects)

it('broadcasts cancellation across duplicate and late transport attempts', async () => {
const completed = await Effect.runPromise(
Effect.scoped(
Expand Down Expand Up @@ -155,9 +152,9 @@ describe('#94 Cloudflare durable progress wait', () => {
const approval = await prepareApproval(thread)
const cursor = approval.cursor

const waiting = runTrackedClientFiber(awaitProgressEffect(thread, cursor))
const waiting = runClientFiber(awaitProgressEffect(thread, cursor))

await progressStub(thread).awaitProgressWaiterCount(1)
await progressStub(thread).awaitProgressSubscribed(1)
const priorIncarnation = await progressStub(thread).progressIncarnation()

await runInDurableObject(stubFor(thread), (_instance, state) => {
Expand Down
Loading
Loading