An entity holding Entity.keepAlive, or running a persisted request, keeps
an alarm armed one heartbeat ahead. Cloudflare never re-creates an evicted
object by itself, so that alarm is what brings it back after a deploy,
runtime update, or eviction: it rebuilds a kept-alive entity and restores
its hold, and replays every unprocessed row instead of only due DeliverAt
rows.
- cluster_entity_state stores the keep-alive flag and the encoded name, so
an alarm wake without id.name still resolves the entity.
- The holder count stays in memory, per handler build, and resets when the
build is invalidated. The flag is written in a forked fiber (inline would
deadlock inside withTransaction), and a release writes 0 before the hold
opens.
- One nextAlarmAt covers due rows, unrun unprocessed rows, and the
heartbeat; the alarm arms it before awaiting replayed handlers.
- keepAliveHeartbeat on CloudflareCluster.layer and
AlchemyCloudflareCluster.make, 30 seconds by default.
Recovery.test.ts now covers only unprocessed persisted-message replay
after a restart. The keep-alive restart test moves unchanged to
KeepAliveRecovery.test.ts, which is tracked separately.
Both tests fail until the entity Durable Object wakes itself after a
restart: a keep-alive entity is not rebuilt, and an unprocessed persisted
tell replays only on the next contact.
Remove coverage repeated across seams, keeping one focused test per
contract plus the regression tests for fixed bugs. The end-to-end Miniflare
suite is the primary coverage; unit tests stay only where a contract is not
observable end to end.
- Delete the second Miniflare harness (CloudflareDurableObjects.test.ts and
its fixture worker). Its distinct contracts move to EntityManager unit
tests on the shared node:sqlite storage: unacknowledged stream chunks do
not block other requests, undecodable replay rows are skipped, an ask
deduplicated onto a tell is rejected, and interrupting a deduplicated
delayed waiter leaves the original. The DO-to-DO delayed reply moves to
the integration fixture's Relay entity.
- Delete ClusterCron and EntityKeepAlive unit tests, which repeat the
integration tests.
- Drop unit tests repeated by integration or by the shared PersistedQueue
contract suite, and implementation-coupled program tests that asserted
SQL strings and bindings.
- Move EntityMailbox onto the shared node:sqlite storage and drop its
hand-written SQL fake.
- Drop type tests that only checked core Entity or alchemy types.
The entity client builds with its own `Reactivity` instead of looking one up
in the registration context, so `EntitySql.make` is a plain scoped effect and
the handler build adds it to the context in one line. `toLayer` registers
through `flatMap` instead of a generator, and the docs drop the per-build
client lifetime, an implementation detail.
The node:sqlite Durable Object storage fake is shared between the entity
manager and entity SQL tests from `test/fixtures/sqliteStorage.ts`.
Fake-storage unit tests and Miniflare integration tests for the entity
Durable Object's own SQL client: per-entity rows, atomic handler
transactions, `reset` leaving user tables alone, rows surviving an isolate
restart, and the Worker layer's `SqlClient` staying reachable in handlers.
A Miniflare regression test interleaves two handlers through a user
transaction that rolls back, and checks the other handler's stored reply
survives. Type tests cover `CloudflareCluster.toLayer` erasing only
`DurableObjectSqlClient`, requiring `CloudflareSharding`, and being satisfied
by `CloudflareCluster.layer` and `AlchemyCloudflareCluster.make`.
Each entity Durable Object provides `CloudflareCluster.DurableObjectSqlClient`,
an `@effect/sql-sqlite-do` client on its own SQLite storage, to its handler
build and handlers. It is a separate tag, so an app-wide `SqlClient` stays in
place. `CloudflareCluster.toLayer` registers handlers that use it, removing
the service from the layer requirements and requiring `CloudflareSharding`,
which only `CloudflareCluster.layer` provides.
User transactions and mailbox writes share a gate: workerd runs every write
on the object's one SQLite connection inside an open `storage.transaction()`,
so a handler resumed from inside a user transaction could otherwise save its
reply there and lose it to the rollback.
Closes EFF-1842
Review of the previous commit showed the early return inside the entity
run continuation had collateral effects: the alarm path re-armed a past
deadline while a scheduled tell's handler was still running (hot alarm
loop), and replay failure routing for tell rows became unreachable. The
join is restored there, and the non-pinning behavior moves to the invoke
entry instead: a persisted tell's invoke result completes once the row is
journaled and the handler forked, with forked-machinery failures logged
and left for replay. Replayed tell rows are also excluded from the barrier
that delays other callers' invoke results, while alarm processing still
awaits every replayed handler before re-arming. Volatile tells keep their
best-effort in-request execution.
Also widens two DeliverAt test offsets that raced restart and observation
roundtrips on slow machines.
Adds a public-surface integration suite under test/integration that runs the
Cloudflare cluster modules through real Worker-to-DO bindings in Miniflare:
entity ask/tell for volatile and persisted RPCs, streaming with
acknowledgements, primary-key dedup, cancellation and Uninterruptible
handlers, DeliverAt and alarm wake-up (including cold isolates after a
restart), restart/replay of interrupted persisted requests, terminal defect
retry, keepAlive and EntityResource holder lifetimes, workflows with durable
clock/deferred/queue, singleton wake coalescing, and ClusterCron ticks. The
harness restarts workerd with persisted DO SQLite to simulate isolate loss
deterministically, and every wait is deadline-polled.
The suite surfaced one defect, fixed here: a persisted or volatile tell's
invoke joined the handler fiber, pinning the caller until the handler
finished (and propagating handler outcomes to it). Tells now complete once
the request is persisted and the handler forked; scheduled ask runs keep the
join so replay failure handling still observes the handler outcome.
- Consolidate the PR changesets into one effect patch changeset
- Export Entity.KeepAliveHandler and use it from platform-cloudflare
- Return Effects from the entity mailbox operations
- Use services with optional access instead of References for the
entity reply context
- Build mutateAndWake inside a single Effect.suspend
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
- Replace the Done/Wait/Continue InvokeOutcome ADT with a nested effect:
invokeEntry returns the post-permit continuation directly and invoke
flattens it.
- Move the handler semaphore into makeEntityRuntime next to the other
build options, deleting the manager's lazy tri-state resolution.
- Use a plain Semaphore.withPermit on the discard/scheduled path (no
stream acks there) and build the pausable permit only for sessions.
- Register one waitUntil per replay batch instead of one per row, skip
replay entirely for an empty mailbox, and drop redundant empty-array
guards around Fiber.awaitAll.
- Reuse encodeName and a shared invoke helper in the test fixture.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Split the blanket invoke serialization in makeEntityManager into two
levels: storage entry (decode, persist-before-run, dedupe, duplicate
resume, alarm arming) keeps the single entry permit, while handler
execution runs in forked fibers governed by a per-entity semaphore sized
from the entity's concurrency build option. Replayed mailbox rows and
alarm-due runs draw from the same budget, and a handler's permit is
released while a stream chunk is parked on its client acknowledgement.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Move the ClusterEntity state machine out of the Durable Object class into
an Effect-land entity manager in internal/entityRuntime.ts. The class
methods are now one-line Effect.runPromise adapters; Effect.runPromise
appears only at the DO RPC membrane.
- Replace the hand-rolled #serial promise chain with a Semaphore(1)
permit around invoke/alarm entry.
- Replace ReplySession taker arrays with a Queue per session plus a
Deferred for chunk acknowledgements; handler failure travels as Cause.
- Replace #workerWaiters {resolve, reject} pairs with Deferred values.
- Define the DO invoke result as a Schema tagged union in entityWire.ts;
encode once in the DO, decode once in CloudflareCluster.ts, removing
the string-literal error discriminants and the related casts. Same
treatment for the replay-envelope tag peek.
- Delete the module-global reply handler map in entityReply.ts; pinned
callers now wait on a Deferred in a per-object reply registry provided
through handler context, and deliverReply completes it.
- Remove the `let client!` definite-assignment in CloudflareCluster.ts
and the RequestId casts on client.write.
Behavior preserving: no changes to the locked design, wire semantics
beyond the invoke-result envelope shape (private same-package RPC), or
SQLite schemas. Tests updated only where they fake the internal wire.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
- dedup the three module-level registries behind a shared makeRegistry
- dedup bounded-map eviction (request targets, delivered queue items)
- move request envelope encoding next to its decoder in entityWire
- cache the per-rpc chunk values codec so parser compilation can memoize
- carry reply metadata (kind/terminal) instead of re-parsing reply JSON in
the entity session flow; loadNextReply returns its kind column
- merge the duplicated delayed-duplicate branches and replay loops in
ClusterEntity; skip replay decode for requests with an active session
- split the mailbox capacity check into two indexed counts and add a
partial index for unacked chunks; index queue position for MAX lookups
- drop dead surface: PersistResult.lastReceivedReply, the reply_to
migration fallback, clearReplies RPC, makeRunnerAddress, optional
EntityStub methods that are always present
- fast-path the 2 MB size check to avoid encoding small strings
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Single leasing code path through the waiter wake pass, an eagerly built
queue runtime without the lazy indirection, a derived RPC item type instead
of a duplicated interface, and one shared stub retry policy. Behavior and
test coverage unchanged.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
One queue name is one Durable Object: items, attempt counts, and in-flight
leases live on the object's SQLite storage behind its single alarm, which
acts as a watchdog redelivering items whose worker died. CloudflareCluster
now also provides PersistedQueueFactory, so the DurableQueue user API works
on the Cloudflare path out of the box.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
- Fold loadExecutionName into loadExecution and share one detach helper for
fire-and-forget promises
- Flatten run()'s discard branching and route the wake self-heal through
resume()
- Deduplicate the per-workflow codec caches and drop the redundant conflict
clause on the single-threaded deferred insert
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
- Persist the interrupted completion when a hard interrupt kills the run
fiber before it can encode its result, instead of rejecting callers
- Set resume_pending for alarm-completed clocks and keep a guard alarm armed
while a resume is pending, so a replay lost with the isolate is retried
- Record an in-flight resume request synchronously with the deferred write,
closing the window where a settling attempt could clear it unserviced
- Retry and log parent resume instead of a single swallowed RPC, and resume
the parent on a defect exit like the cluster engine
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
- Recover the Durable Object name from the stored execution on alarm wakes,
where ctx.id.name is undefined, so due clocks fire after eviction
- Persist a resume_pending marker with each deferred exit and replay on wake,
so a resume lost with the isolate cannot strand a suspended execution
- Route in-run engine operations through a context-provided execution handle
instead of a module-level map that could outlive its Durable Object
- Link a late-arriving parent to an existing child execution
- Batch due-clock completions into a single replay per alarm
- Honor an explicit inMemoryThreshold of zero in DurableClock.sleep
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>