Commit Graph
12304 Commits
Author SHA1 Message Date
Tim Smart 290dc73b05 feat(platform-cloudflare): recover entities after a Durable Object restart
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.
2026-11-02 10:20:12 +00:00
Tim Smart 4136185998 Revert restart recovery tests
This reverts commits 8ed3dc6f62 and 7753e290cd.
2026-11-02 10:20:12 +00:00
Tim Smart 3415308d8b test(platform-cloudflare): split keep-alive recovery into its own test file
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.
2026-11-02 10:20:12 +00:00
Tim Smart 021e08e912 test(platform-cloudflare): cover keep-alive and unprocessed-message recovery after a restart
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.
2026-11-02 10:20:12 +00:00
Tim Smart 5f3271a124 test(platform-cloudflare): reduce the suite to focused contract tests
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.
2026-11-02 10:20:12 +00:00
Tim Smart 99d53fd7d4 refactor(platform-cloudflare): simplify the entity DurableObjectSqlClient plumbing
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`.
2026-11-02 10:20:12 +00:00
Tim Smart d05ae70295 Annotate Cloudflare cluster APIs as unstable 2026-11-02 10:20:12 +00:00
Tim Smart 52fa87649a test(platform-cloudflare): cover DurableObjectSqlClient in entity handlers
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`.
2026-11-02 10:20:12 +00:00
Tim Smart 5a40951edd feat(platform-cloudflare): give entity handlers a Durable Object SqlClient
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
2026-11-02 10:20:12 +00:00
Tim Smart 0950a07603 fix(platform-cloudflare): migrate imports to stable Effect 4 paths 2026-11-02 10:20:12 +00:00
Tim Smart a6a6bdd93b fix(platform-cloudflare): align deferred state with main 2026-11-02 10:20:12 +00:00
Tim 25fe3fdcec Add Alchemy deployment for the Cloudflare cluster (#7550) 2026-11-02 10:20:11 +00:00
Tim Smart 54a2779d1c test(platform-cloudflare): use real Undici under Bun 2026-11-02 10:19:54 +00:00
Tim Smart ea2cd991d1 test(platform-cloudflare): control DeliverAt alarm timing 2026-11-02 10:19:54 +00:00
Tim Smart eaff704eab fix(platform-cloudflare): restore persisted queue compatibility 2026-11-02 10:19:54 +00:00
Tim Smart 0c628ff163 test(platform-cloudflare): specify queue compatibility contract 2026-11-02 10:19:54 +00:00
Tim Smart 550842aa81 test(platform-cloudflare): type readiness scheduler 2026-11-02 10:19:12 +00:00
Tim Smart 462f802416 chore(platform-cloudflare): sync workers types 2026-11-02 10:19:12 +00:00
Tim Smart 48379cc657 feat(platform-cloudflare): add Durable Object readiness 2026-11-02 10:19:12 +00:00
Tim Smart 299d2776bb fix(platform-cloudflare): keep tell non-pinning at the invoke boundary
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.
2026-11-02 10:19:12 +00:00
Tim Smart a1bdb0039b feat(platform-cloudflare): add Miniflare cluster integration test suite
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.
2026-11-02 10:19:12 +00:00
Tim Smart fc3736eefa fix(platform-cloudflare): type SQLite query results 2026-11-02 10:19:12 +00:00
Tim SmartandClaude Fable 5 45c7220d81 Address PR review feedback
- 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>
2026-11-02 10:19:12 +00:00
Tim 932cf869b8 Fix concurrent Cloudflare entity handler builds (#7346) 2026-11-02 10:19:12 +00:00
Tim 4bd08a0b85 Honor uninterruptible Cloudflare entity requests (#7345) 2026-11-02 10:19:12 +00:00
Tim Smart 23e66858a9 fix(platform-cloudflare): complete interrupted streams 2026-11-02 10:19:12 +00:00
Tim SmartandClaude Fable 5 0cd7266d4a refactor(platform-cloudflare): simplify entity concurrency internals
- 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>
2026-11-02 10:19:12 +00:00
Tim Smart 621e4080f5 chore(platform-cloudflare): remove entity concurrency changeset 2026-11-02 10:19:12 +00:00
Tim SmartandClaude Fable 5 bcbcc2df38 feat(platform-cloudflare): honor Entity.toLayer concurrency in entity Durable Objects
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>
2026-11-02 10:19:12 +00:00
Tim SmartandClaude Fable 5 1f11b00bdb refactor(platform-cloudflare): idiomatic Effect cluster internals
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>
2026-11-02 10:19:12 +00:00
Tim SmartandClaude Fable 5 a652136d9f refactor(platform-cloudflare): simplicity pass over cluster internals
- 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>
2026-11-02 10:19:12 +00:00
Tim Smart 8502857f2b test(platform-cloudflare): remove unused entity import 2026-11-02 10:19:12 +00:00
Tim Smart 6f30650863 fix(platform-cloudflare): keep keep-alive handler private 2026-11-02 10:19:12 +00:00
Tim Smart 6916123377 fix(platform-cloudflare): honor defect retry schedules 2026-11-02 10:19:12 +00:00
Tim Smart 34bf5363d3 fix(platform-cloudflare): correct telemetry lifecycles 2026-11-02 10:19:12 +00:00
Tim Smart 27e519e879 feat(platform-cloudflare): add proxy telemetry and guidance 2026-11-02 10:19:12 +00:00
Tim Smart 59c9dff39c feat(platform-cloudflare): run ClusterCron on Durable Objects 2026-11-02 10:19:12 +00:00
Tim Smart 91bf83257c feat(platform-cloudflare): add singleton Durable Object wake 2026-11-02 10:19:12 +00:00
Claude EngineerandClaude Fable 5 c4f00da3f6 refactor(platform-cloudflare): simplify durable queue internals
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>
2026-11-02 10:19:12 +00:00
Claude EngineerandClaude Fable 5 b0e4e8edbd feat(platform-cloudflare): add DurableQueue Durable Object
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>
2026-11-02 10:19:12 +00:00
Claude Engineer 106dba9c04 refactor(platform-cloudflare): simplify workflow engine internals
- 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>
2026-11-02 10:19:12 +00:00
Claude Engineer 6c8a561aff fix(platform-cloudflare): harden workflow engine wake and interrupt paths
- 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>
2026-11-02 10:19:12 +00:00
Claude Engineer cf7d6cd769 fix(platform-cloudflare): apply workflow engine review findings
- 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>
2026-11-02 10:19:12 +00:00
Claude Engineer e55c1b3995 feat(platform-cloudflare): add CloudflareWorkflowEngine with durable clocks
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-11-02 10:19:12 +00:00
Tim Smart 2f8d81ccde feat(platform-cloudflare): pin entity resource holders 2026-11-02 10:19:12 +00:00
Tim Smart 77f7bf1a53 fix(platform-cloudflare): reject ask deduplication to tells 2026-11-02 10:19:12 +00:00
Tim Smart dc311e88b5 fix(platform-cloudflare): preserve delayed request waiters 2026-11-02 10:19:12 +00:00
Tim Smart db9f2e071a feat(platform-cloudflare): add delayed entity delivery 2026-11-02 10:19:12 +00:00
Tim Smart 80e802806d test(platform-cloudflare): cover stream acknowledgements 2026-11-02 10:19:12 +00:00
Tim Smart 9ede17e0e8 fix(platform-cloudflare): address mailbox audit findings 2026-11-02 10:19:12 +00:00