Skip to content

Latest commit

 

History

History
264 lines (213 loc) · 14.6 KB

durable-object-lifecycle.md

File metadata and controls

264 lines (213 loc) · 14.6 KB

Durable Object lifecycle

Lifecycle composes runtime behavior into a Cloudflare Durable Object. It owns runtime handlers, ordered capability phases, host-hook context, identity, and hibernating WebSocket connections. A host continues to extend Cloudflare's DurableObject; it does not become the Agent class exported from agents.

agents/lifecycle exports LifecycleObject, an interface for a DurableObject with an installed Lifecycle and the optional semantic hooks Lifecycle dispatches. The interface names the host contract without introducing another base class.

The batteries-included Agent class installs the same Lifecycle, then adds state, RPC, scheduling, MCP, workflows, fibers, and sub-agents.

Capability and host phases

Lifecycle runs startup in this order:

  1. capability onStart hooks in registration order;
  2. the host's onStart hook.

For an HTTP request, capability onRequest hooks run in registration order. The first Response wins; otherwise the host's onRequest handles the request. For an alarm, capability onAlarm hooks run in registration order before the host's onAlarm.

Failures stop the phase and propagate. Failed startup remains retryable.

A failure that propagates out of fetch (startup, a capability's request or upgrade hook, or the host's onRequest) ends in one place. Lifecycle logs the error, then offers it to the host's optional onFetchError(request, error). If the host returns no response, or the hook throws, Lifecycle sends a default that never carries the error: 500 Internal Server Error, or for an upgrade an accepted socket closed with 1011. In both cases, an original thrown value that is not an Error is rethrown to the runtime instead, as before. The defaults used to send err.stack, which leaked internals to callers who were not authenticated (#2828).

Choosing that response is a host hook, not a LifecycleOptions flag such as "expose errors in development". A flag covers one policy, while a hook covers every policy (dev-only stacks, error codes, a reporting ID, an upgrade that sends one frame before it closes) with no further API. Agent's onError was not reused: it observes errors from schedules, queues, and sockets as well as requests, where no response exists to choose, and capability failures never reach it. The hook is named for fetch, the entry point it answers, and not onRequestError: onRequest handles only plain HTTP, while this hook also answers failed upgrades, onConnect, startup, and capability hooks. The name keeps upgrades in view: an HTTP response returned from this hook also answers a failed WebSocket upgrade, in place of the default 1011 close. Capabilities do not get the hook yet. If one needs to shape failure responses, it can join the same dispatch the way onRequest does: first response wins, then the host.

Only fetch has a hook that chooses a failure response, because only fetch has a caller waiting for one. The other entry points have no response to choose. A failed alarm rethrows so that the platform retries it, except for a memory-limit reset, which the memory-limit circuit breaker handles instead. A failed WebSocket message is logged and dropped. A job's final failure goes to its capability's onJobError, if it has one, which decides the job's outcome; otherwise the job completes. A new entry point gets a hook that chooses a response only if a caller waits for its result.

A failed Agent request (from onStart, onRequest, or onConnect) passes through two hooks: onError observes it and can replace it by throwing, then, if onError returns, the original error continues to onFetchError, which chooses the response. The intended direction is for onError to only observe errors, and for an Agent to shape failures in onFetchError. That change, along with removing the second onError call that AIChatAgent makes for an onRequest failure, is separate work, because it changes when existing overrides run.

Native Durable Object RPC bypasses Lifecycle handlers, so a plain Lifecycle host calls lifecycle.start() from any RPC method that needs startup. Concurrent start() callers share one in-flight startup and all see its result. A call made from inside that startup (a capability or onStart calling back into the host) returns immediately instead of waiting on itself; an async-context marker tells those nested calls apart from independent ones. lifecycle.isStarted() reports whether startup has finished.

What is a capability

Code is a capability when it needs its own storage (tables, keys), or an alarm or scheduled work (it pushes Lifecycle jobs or must be woken). Anything else is a plain internal module: functions or a small class that takes what it needs. A harness is a capability too, as the unit a host installs (rfc-capability-instances.md).

A capability has one id, and Lifecycle.use() refuses a second capability with the same id, so an object has one Streams, one Tasks and one Sessions today. rfc-capability-instances.md is accepted and changes that; this section will describe it once it is built.

Alarm ownership and scheduling

Lifecycle owns the one physical Durable Object alarm. A capability can return its next requested epoch time from getNextAlarm() and request recalculation through this.lifecycle.alarms.rearm(). Lifecycle serializes recalculation, chooses the earliest contribution, runs every capability's onAlarm() followed by the host's onAlarm(), then recalculates once more.

Capabilities own their durable work. Scheduler stores named callback rows in its table; the Tasks capability stores replayable runs and step journals in its own tables and contributes its earliest run deadline the same way (rfc-fibers.md); an MCP capability can store reconnect state in its own table. They coordinate only through Lifecycle's alarm contract and do not depend on Scheduler.

A host can also implement getNextAlarm() for work not yet extracted into a capability. Exclusive contributions replace ordinary wake-time candidates, which supports teardown without teaching other capabilities about destroy semantics; they do not alter alarm hook order. Agent currently uses the host contribution for deferred destruction, keep-alive, fiber recovery, and facet-run checks. These can move into separate capabilities without changing Scheduler or alarm selection.

Scheduler is a plain Lifecycle primitive. Its onStart hook owns schedule schema migration, onAlarm owns due-row processing, and getNextAlarm contributes its earliest runnable row or hung-interval recheck. Agent constructs the same Scheduler exposed at Agent.this.scheduler; existing Agent scheduling methods remain compatibility delegators.

Capabilities extending LifecycleCapability receive storage, readiness, startup state, alarm coordination, a host invocation boundary, events, and generic capability routing. Scheduled callbacks are registered on the Scheduler itself, so the typed scheduling surface and the runtime dispatch target are the same object by construction. That service surface is the whole contract: Scheduler consumes only standard services plus its own callbacks and policy options, and a future capability composes the same way with no host adapter. Lifecycle routes an envelope to the matching capability ID at the destination. Agent supplies an internal facet transport through one generic RPC aperture, so Scheduler routes owner-scoped CRUD and callbacks without facet-specific methods or an Agent adapter. Existing facet rows stay in the root Scheduler table.

Host adaptation happens only at a composition root, through three internal apertures: the capability event sink, the routed-capability transport, and the host invoker behind the host invocation boundary. Agent uses them to route events into its observability interface, carry envelopes between facets, and wrap capability-run user callbacks in its tracing invocation boundary. Agent adds one Scheduler-specific aperture — a callback-name resolver — so its historical name-based scheduling methods keep dispatching to Agent methods. A plain Lifecycle Object uses the defaults and configures nothing.

Capabilities publish best-effort telemetry through this.lifecycle.events.emit(). Lifecycle sends plain Lifecycle Object events to the existing diagnostics channels. Agent adapts the terminal sink to its existing observability implementation. The bus is not durable; a capability that requires guaranteed delivery owns an outbox.

Alarm contribution, capability hooks, and capability-event delivery run outside ambient host context. Registered scheduled callbacks are user code, so Scheduler runs them through the host invocation boundary in Lifecycle Object or Agent context as appropriate.

Testing capabilities

Capabilities are testable at every layer without module mocks or fake services. Harness Durable Objects live one-per-capability in tests/capabilities/, with their pool-only drivers in tests/shared/ (see tests/capabilities/AGENTS.md), so every capability follows the same pattern:

  1. Pure domain logic (timing parsers, selection rules) lives in dependency-free modules and is unit tested directly, e.g. tests/schedules/timing.test.ts.
  2. The capability in isolation, on a real Durable Object — withCapabilityHarness() binds per-test-constructed capabilities to a real Lifecycle over real SQLite storage inside a bare harness object (the MCP client suites), while a capability whose tests need real platform dispatch gets a dedicated harness object with runtime handlers installed — SchedulerHarnessObject driven through real alarms in tests/schedules/capability.test.ts. The Workers vitest pool makes real objects cheap, so there is no fake-services seam to keep in sync with Lifecycle semantics.
  3. Lifecycle integration proves cross-capability behavior: alarm arbitration across contributors, phase order, context boundaries, and eviction recovery — the per-functionality files in tests/lifecycle/.
  4. Host surface tests exercise the capability through the complete Agent class and its public API — tests/schedule.test.ts, the MCP agent suites, and the think/ai-chat packages.

A new capability should arrive with layers 2 and 3; layer 1 applies when it owns non-trivial pure rules.

Host context

Lifecycle owns the AsyncLocalStorage read by getCurrentAgent(). The accessor is exported from agents/lifecycle; the root agents export is the same function for Agent compatibility.

Lifecycle establishes context only around semantic host hooks:

  • startup and alarm expose the host;
  • HTTP requests expose the host and request;
  • WebSocket connect exposes the host, connection, and upgrade request;
  • WebSocket message, close, and error expose the host and connection.

getConnectionTags(connection, { request }) remains argument-driven because both values are already explicit.

Capability hooks deliberately run outside the host context. Capabilities use their own this, phase arguments, and explicit dependencies. Lifecycle exits any inherited current-Agent context before invoking capability startup, request, or alarm hooks, so behavior does not depend on the entrypoint that triggered the phase.

User callbacks are the exception: when a capability runs one through this.lifecycle.runInHostContext(), Lifecycle establishes the host invocation context around that call. This is the one boundary a host composition root may wrap — Agent substitutes its tracing invocation scope — so every capability that dispatches user callbacks inherits the host's invocation semantics without capability-specific hooks.

Agent entry surfaces

The Agent class has entry surfaces beyond Lifecycle, including native Durable Object RPC, WebSocket callables, email, schedules, fibers, chat turns, and detached work. Its existing invocation wrappers continue to own those surfaces. In particular, the automatic public-method wrapper is not made redundant by Lifecycle because native Durable Object RPC does not pass through a Lifecycle handler.

That wrapper also starts the Lifecycle. When an async method defined below Agent (a user subclass method, or Think's and AIChatAgent's public API) is entered from outside this Agent's context on an unstarted instance, it awaits lifecycle.start() before running. Framework _cf_* RPCs and Think's _host* bridge methods call __unsafe_ensureInitialized() themselves. These still run without startup unless they call await this.lifecycle.start():

  • synchronous methods, which are never deferred so they keep their return type;
  • non-async methods that return a Promise;
  • methods defined on Agent itself, such as getMcpServers() and schedule(), which are not wrapped.

See rfc-cold-rpc-initialization.md.

Tracing remains in Agent's existing invocation boundaries. Moving or consolidating tracing in Lifecycle is separate work.

WebSockets

Lifecycle WebSockets always use Cloudflare's Hibernation API. It accepts sockets with DurableObjectState.acceptWebSocket, stores connection metadata in attachments, and reconstructs Connection objects after hibernation.

There is no in-memory WebSocket mode.

What the platform does to these sockets, measured on deployed Workers (22 Nov 2026):

  • A code deploy keeps them connected, and the new version serves them with the attachments the old one wrote. ctx.abort(), a crash or the memory-limit breaker closes all of them (the client sees 1006).
  • Idle sockets are not closed for idleness (30 minutes measured).
  • A message over 33,554,359 bytes (32 MiB less 73, measured) is dropped silently: send() returns normally and the peer gets nothing, not even a close. rpc responses go through serializeRpcResponse (websockets/frame-limit.ts), which answers an over-limit result or stream chunk with an error response for the same call, so the caller is not left waiting. That error ends the call: a StreamingResponse reports closed and a ReadableStream result is cancelled, with no further frame for the call. The check uses WEBSOCKET_MESSAGE_BYTES (internal/platform-limits.ts), 1 KiB under 32 MiB. Other senders must keep their frames under the limit themselves.

Identity

For supported named objects, ctx.id.name is authoritative. Lifecycle exposes it as lifecycle.name and reads the historical __ps_name storage key only as a migration fallback. It never writes a duplicate name.

History