From 4563fc46304ff5b08922ee9c8bec5edb7c44346b Mon Sep 17 00:00:00 2001 From: systemfsoftware-bot <318394648+systemfsoftware-bot@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:06:43 -0500 Subject: [PATCH] test(platform-cloudflare): stop test work outliving its test Three Cloudflare suites failed intermittently in one CI lane under CPU contention: - the eviction progress-wait test hit its 20 s cap after a 19.6 s stall that began when it aborted the Object mid-wait; - background-workers passed every test and then reported a pending vitest module-resolution RPC while the environment was closing; - join-restart hit its 10 s cap twice, its five scenarios each running about 135 sequential SQLite operations. The waiter-count latch was a point-in-time gauge: a replayed awaitProgress request that registered and left between two observer calls was missed. It becomes a monotonic per-incarnation subscription counter, and the test latches on the count instead of the gauge. A probe confirmed the platform re-runs an in-flight awaitProgress on the fresh incarnation after state.abort() and resolves the client promise when progress arrives, so the client needs no retry. Client fibers are now tracked by the harness, and each test ends with a quiescence barrier: disarm the eviction failpoints it armed, interrupt and await its fibers, and delete the persisted alarm of every Object it touched. Every barrier step is bounded so a wedged Object cannot stall the shared environment. The join test's 10 s per-test cap and its four inner two-second Effect.timeout guards are removed; that work legitimately sits within a small factor of the cap under contention, and the suite's configured timeout is the budget. The other suites keep their caps, which the fixed tests meet with ample headroom. --- .changeset/cloudflare-test-quiescence.md | 5 + ...t-work-outlives-the-workerd-environment.md | 62 ++++++++++++ .../test/background-workers.test.ts | 7 +- packages/platform-cloudflare/test/fixtures.ts | 5 + packages/platform-cloudflare/test/harness.ts | 96 ++++++++++++++++--- .../test/join-restart.test.ts | 16 ++-- .../test/progress-wait.test.ts | 19 ++-- packages/platform-cloudflare/test/worker.ts | 96 +++++++++---------- 8 files changed, 223 insertions(+), 83 deletions(-) create mode 100644 .changeset/cloudflare-test-quiescence.md create mode 100644 docs/solutions/test-failures/cross-object-test-work-outlives-the-workerd-environment.md diff --git a/.changeset/cloudflare-test-quiescence.md b/.changeset/cloudflare-test-quiescence.md new file mode 100644 index 00000000..cce8e544 --- /dev/null +++ b/.changeset/cloudflare-test-quiescence.md @@ -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. diff --git a/docs/solutions/test-failures/cross-object-test-work-outlives-the-workerd-environment.md b/docs/solutions/test-failures/cross-object-test-work-outlives-the-workerd-environment.md new file mode 100644 index 00000000..0f9e8d5e --- /dev/null +++ b/docs/solutions/test-failures/cross-object-test-work-outlives-the-workerd-environment.md @@ -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. diff --git a/packages/platform-cloudflare/test/background-workers.test.ts b/packages/platform-cloudflare/test/background-workers.test.ts index 323a8d42..980be1d9 100644 --- a/packages/platform-cloudflare/test/background-workers.test.ts +++ b/packages/platform-cloudflare/test/background-workers.test.ts @@ -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' @@ -62,6 +62,8 @@ import { import { allSettled, drainAlarmsUntil, + forgetTouchedObjects, + quiesceTouchedObjects, readCanonical, readExecution, runClient, @@ -102,6 +104,9 @@ const withOwner = ( }), )) +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 ({ diff --git a/packages/platform-cloudflare/test/fixtures.ts b/packages/platform-cloudflare/test/fixtures.ts index ac7dac9b..954907fa 100644 --- a/packages/platform-cloudflare/test/fixtures.ts +++ b/packages/platform-cloudflare/test/fixtures.ts @@ -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({ diff --git a/packages/platform-cloudflare/test/harness.ts b/packages/platform-cloudflare/test/harness.ts index fe98a0ac..6c406c95 100644 --- a/packages/platform-cloudflare/test/harness.ts +++ b/packages/platform-cloudflare/test/harness.ts @@ -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, @@ -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() +const clientFibers = new Set<() => Promise>() + +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): Promise => + Effect.runPromise( + Effect.tryPromise({ try: () => operation, catch: () => undefined }).pipe( + Effect.timeoutOption(QUIESCENCE_CEILING), + Effect.asVoid, + Effect.ignore, + ), + ) + +export const interruptClientFibers = async (): Promise => { + const interrupts = [...clientFibers] + + clientFibers.clear() + await Promise.all(interrupts.map((interrupt) => settleWithinCeiling(interrupt()))) +} + +export const quiesceTouchedObjects = async (): Promise => { + 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( @@ -109,19 +168,26 @@ export const runScheduleClient = (effect: Effect.Effect) export const runClientFiber = ( effect: Effect.Effect, 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, @@ -133,7 +199,7 @@ export const awaitReconstructedProgressWaiter = async ( try { const incarnation = await ( stubFor(thread) as DurableObjectStub - ).awaitProgressWaiterCountAfter(previousIncarnation, expected) + ).awaitProgressSubscribedAfter(previousIncarnation, expected) if (incarnation !== null) return incarnation } catch (cause) { diff --git a/packages/platform-cloudflare/test/join-restart.test.ts b/packages/platform-cloudflare/test/join-restart.test.ts index 03d4074f..6b3adb94 100644 --- a/packages/platform-cloudflare/test/join-restart.test.ts +++ b/packages/platform-cloudflare/test/join-restart.test.ts @@ -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. @@ -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++) { @@ -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( @@ -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 @@ -512,5 +515,4 @@ it.each(['reply', 'tools', 'eviction', 'backlog', 'rejected'] as const)( }), ) }, - 10_000, ) diff --git a/packages/platform-cloudflare/test/progress-wait.test.ts b/packages/platform-cloudflare/test/progress-wait.test.ts index 652467af..cfdf20f8 100644 --- a/packages/platform-cloudflare/test/progress-wait.test.ts +++ b/packages/platform-cloudflare/test/progress-wait.test.ts @@ -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' @@ -14,6 +14,8 @@ import { anyInState, awaitReconstructedProgressWaiter, drainAlarmsUntil, + forgetTouchedObjects, + quiesceTouchedObjects, readCanonical, runClient, runClientFiber, @@ -85,15 +87,10 @@ const awaitProgressEffect = Effect.fnUntraced(function*( } }) -const runTrackedClientFiber = (effect: Effect.Effect) => { - 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( @@ -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) => { diff --git a/packages/platform-cloudflare/test/worker.ts b/packages/platform-cloudflare/test/worker.ts index ec7f1d92..835d5149 100644 --- a/packages/platform-cloudflare/test/worker.ts +++ b/packages/platform-cloudflare/test/worker.ts @@ -175,64 +175,67 @@ export class TestSubscriptionPartitionObject extends makeSubscriptionPartitionOb }, ) {} -/** The eviction/alarm/chaos suites' Thread Object. */ -const progressWaiterCounts = new WeakMap() +interface ProgressWaiterState { + readonly incarnation: number + total: number +} -interface ProgressWaiterCountLatch { - readonly expected: number +interface ProgressWaiterLatch { + readonly qualifies: (state: ProgressWaiterState) => boolean readonly resolve: () => void } -const progressWaiterCountLatches = new WeakMap< - DurableObjectState, - Array ->() - -const progressIncarnations = new WeakMap() +const progressWaiterLatches = new WeakMap>() +const progressWaiterStates = new WeakMap() let nextProgressIncarnation = 0 -const setProgressWaiterCount = (ctx: DurableObjectState, count: number): void => { - progressWaiterCounts.set(ctx, count) - const latches = progressWaiterCountLatches.get(ctx) +const progressWaiterState = (ctx: DurableObjectState): ProgressWaiterState => { + const existing = progressWaiterStates.get(ctx) + + if (existing !== undefined) return existing + const created: ProgressWaiterState = { incarnation: ++nextProgressIncarnation, total: 0 } + + progressWaiterStates.set(ctx, created) + + return created +} + +const settleProgressWaiterLatches = (ctx: DurableObjectState): void => { + const latches = progressWaiterLatches.get(ctx) if (latches === undefined) return - const pending: Array = [] + const state = progressWaiterState(ctx) + const pending: Array = [] for (const latch of latches) { - if (latch.expected === count) { + if (latch.qualifies(state)) { latch.resolve() } else { pending.push(latch) } } if (pending.length === 0) { - progressWaiterCountLatches.delete(ctx) + progressWaiterLatches.delete(ctx) } else { - progressWaiterCountLatches.set(ctx, pending) + progressWaiterLatches.set(ctx, pending) } } -const awaitProgressWaiterCount = (ctx: DurableObjectState, expected: number): Promise => { - if ((progressWaiterCounts.get(ctx) ?? 0) === expected) return Promise.resolve() +const awaitProgressWaiter = ( + ctx: DurableObjectState, + qualifies: (state: ProgressWaiterState) => boolean, +): Promise => { + if (qualifies(progressWaiterState(ctx))) return Promise.resolve() return new Promise((resolve) => { - const latches = progressWaiterCountLatches.get(ctx) ?? [] + const latches = progressWaiterLatches.get(ctx) ?? [] - latches.push({ expected, resolve }) - progressWaiterCountLatches.set(ctx, latches) + latches.push({ qualifies, resolve }) + progressWaiterLatches.set(ctx, latches) }) } -const progressIncarnation = (ctx: DurableObjectState): number => { - const existing = progressIncarnations.get(ctx) - - if (existing !== undefined) return existing - const created = ++nextProgressIncarnation - - progressIncarnations.set(ctx, created) - - return created -} +const progressIncarnation = (ctx: DurableObjectState): number => progressWaiterState(ctx).incarnation // Initialization arms maintenance alarms before event-only layers are available. const maintenanceClockLayer = Layer.effectContext( @@ -449,33 +452,28 @@ export class TestThreadObject extends ThreadObject.make( ) } override async awaitProgressEncoded(encoded: unknown): Promise { - progressIncarnation(this.ctx) - setProgressWaiterCount(this.ctx, (progressWaiterCounts.get(this.ctx) ?? 0) + 1) - try { - return await super.awaitProgressEncoded(encoded) - } finally { - setProgressWaiterCount(this.ctx, Math.max(0, (progressWaiterCounts.get(this.ctx) ?? 1) - 1)) - } - } + const state = progressWaiterState(this.ctx) + + state.total += 1 + settleProgressWaiterLatches(this.ctx) - progressWaiterCount(): number { - return progressWaiterCounts.get(this.ctx) ?? 0 + return await super.awaitProgressEncoded(encoded) } - awaitProgressWaiterCount(expected: number): Promise { - return awaitProgressWaiterCount(this.ctx, expected) + awaitProgressSubscribed(expected: number): Promise { + return awaitProgressWaiter(this.ctx, (state) => state.total >= expected) } - async awaitProgressWaiterCountAfter( + async awaitProgressSubscribedAfter( previousIncarnation: number, expected: number, ): Promise { - const incarnation = progressIncarnation(this.ctx) + const state = progressWaiterState(this.ctx) - if (incarnation === previousIncarnation) return null - await awaitProgressWaiterCount(this.ctx, expected) + if (state.incarnation === previousIncarnation) return null + await awaitProgressWaiter(this.ctx, (current) => current.total >= expected) - return incarnation + return state.incarnation } progressIncarnation(): number {