experimental-a2 0.0.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/dist/ai-server.browser.js +2 -2
  3. package/dist/ai-server.d.ts +19 -7
  4. package/dist/ai-server.js +730 -96
  5. package/dist/ai.d.ts +32 -11
  6. package/dist/ai.js +253 -75
  7. package/dist/client.d.ts +1 -1
  8. package/dist/client.js +4 -4
  9. package/dist/{contract-B0kAXoaL.js → contract-CG_adnu_.js} +2 -1
  10. package/dist/{contract-DL8btVd9.d.ts → contract-C_3dIIEU.d.ts} +4 -1
  11. package/dist/devtools-server.browser.js +2 -2
  12. package/dist/devtools-server.js +1 -1
  13. package/dist/http.d.ts +1 -1
  14. package/dist/http.js +4 -3
  15. package/dist/idempotent-replay-BMyHrP0L.js +19 -0
  16. package/dist/index.d.ts +4 -4
  17. package/dist/index.js +1 -1
  18. package/dist/{internal-Dm8Ejnud.js → internal-D6wNxTck.js} +3 -3
  19. package/dist/{log-Dg1I8NRr.d.ts → log-ldf5g8Cx.d.ts} +74 -56
  20. package/dist/log-memory.d.ts +1 -1
  21. package/dist/log-memory.js +173 -96
  22. package/dist/{log-polling-RO7kclzR.js → log-polling-6COoN60V.js} +1 -1
  23. package/dist/log-postgres.d.ts +1 -1
  24. package/dist/log-postgres.js +235 -192
  25. package/dist/log-redis.d.ts +1 -1
  26. package/dist/log-redis.js +453 -263
  27. package/dist/log-sqlite.d.ts +1 -1
  28. package/dist/log-sqlite.js +216 -127
  29. package/dist/otel.d.ts +1 -1
  30. package/dist/otel.js +1 -1
  31. package/dist/react.d.ts +1 -1
  32. package/dist/react.js +1 -1
  33. package/dist/recovery-vercel.d.ts +2 -2
  34. package/dist/recovery-vercel.js +9 -10
  35. package/dist/server-DJgD2YWP.js +877 -0
  36. package/dist/server.browser.js +4 -4
  37. package/dist/server.d.ts +46 -27
  38. package/dist/server.js +1 -1
  39. package/dist/{telemetry-C78al20p.d.ts → telemetry-Cso0qyHQ.d.ts} +1 -1
  40. package/dist/{wire-2QpU1EtJ.js → wire-BVsgR8o9.js} +1 -1
  41. package/docs/01-quickstart.mdx +7 -7
  42. package/docs/concepts/01-contracts.mdx +22 -22
  43. package/docs/concepts/02-handlers.mdx +223 -89
  44. package/docs/concepts/03-durability.mdx +199 -112
  45. package/docs/concepts/04-state.mdx +27 -1
  46. package/docs/guides/01-timers.mdx +4 -4
  47. package/docs/guides/02-cancellation.mdx +32 -4
  48. package/docs/guides/05-production.mdx +61 -27
  49. package/docs/guides/06-ai-agents.mdx +151 -70
  50. package/docs/guides/07-devtools.mdx +6 -3
  51. package/docs/guides/08-application-data.mdx +5 -6
  52. package/docs/index.mdx +30 -14
  53. package/docs/reference/01-api.mdx +305 -70
  54. package/package.json +31 -31
  55. package/dist/server-DYsnKTTy.js +0 -780
@@ -9,47 +9,44 @@ description: Appends are effectively-once, handlers are at-least-once, and retri
9
9
  `append` returns, the event is in the log.
10
10
  - **Handlers are at-least-once.** They may run again after a crash, so
11
11
  [side effects use idempotency keys](/concepts/handlers#handlers-can-run-twice).
12
- - **Order holds per session.** Events are processed in log order. A2 never
13
- dispatches past a pending event.
12
+ - **The log stays ordered.** Every session has one immutable event order.
13
+ - **Handlers are concurrent by default.** Independent events can run at the
14
+ same time. Events in the same lane run one at a time in log order.
14
15
 
15
16
  ## The correctness model
16
17
 
17
- The log says what needs work. The lease says who may work now. The processed
18
- marker says what finished. The watchdog says when to look again.
18
+ The log says what needs work. A per-event claim says who may work now. The
19
+ processed marker says what finished. The watchdog says when to look again.
19
20
 
20
21
  ```text
21
- +-----------------+
22
- | Wakeups |
23
- | |
24
- | append |
25
- | watchdog |
26
- | state / stream |
27
- +--------+--------+
22
+ +------------------+
23
+ | Wakeups |
24
+ | append, watchdog |
25
+ +--------+---------+
28
26
  |
29
27
  v
30
- +-----------------+
31
- | drain(session) |
32
- +--------+--------+
28
+ +------------------+
29
+ | drain(session) |
30
+ +--------+---------+
33
31
  |
34
32
  v
35
- +-----------------+
36
- | claimNext |
37
- +--------+--------+
33
+ +------------------+
34
+ | claimAvailable |
35
+ +--------+---------+
38
36
  |
39
- +----+----+
40
- | |
41
- v v
42
- +----------+ +-----------------+
43
- | return | | run handler |
44
- | busy or | | claimed event |
45
- | settled | +-----------------+
46
- +----------+
37
+ +----+----------------+
38
+ | |
39
+ v v
40
+ +-------------+ +-------------------+
41
+ | busy or | | run every claimed |
42
+ | settled | | event concurrently|
43
+ +-------------+ +-------------------+
47
44
  ```
48
45
 
49
46
  A queue message names a session. It carries no event index or continuation
50
47
  state. Every wakeup runs the same drain, and the log decides what remains.
51
- Append follows its causal tree; recovery and explicit `server.drain()` inspect
52
- the full session. Reads never dispatch handlers.
48
+ Recovery and explicit `server.drain()` inspect the full session. Reads never
49
+ dispatch handlers.
53
50
 
54
51
  :::note[Recovery is not an event]
55
52
  A2 does not append `recovered` or `continued`. Recovery retries the same event.
@@ -59,72 +56,157 @@ Your log contains only application facts.
59
56
  ## One event, many attempts
60
57
 
61
58
  An event is pending until it has a processed marker. Attempt tracking is part
62
- of the operations that already claim and advance that event:
59
+ of the operations that already claim and complete that event:
63
60
 
64
61
  ```text
65
62
  +----------------------------+ one backend operation
66
- | claimNext |
67
- | head + lease + attempt |
63
+ | claimAvailable |
64
+ | eligible events + attempts |
68
65
  +-------------+--------------+
69
66
  |
70
- v
71
- +----------------------------+
72
- | handler 1 |
73
- +-------------+--------------+
74
- |
75
- v
76
- +----------------------------+ one backend operation
77
- | completeAndClaimNext |
78
- | complete 1 + claim 2 |
79
- +-------------+--------------+
80
- |
81
- v
82
- +----------------------------+
83
- | handler 2 |
84
- +----------------------------+
67
+ +------+------+
68
+ | |
69
+ v v
70
+ +-------------+ +-------------+
71
+ | handler A | | handler B |
72
+ +------+------+ +------+------+
73
+ | |
74
+ v v
75
+ +-------------+ +-------------+ one operation per event
76
+ | complete A | | complete B |
77
+ +-------------+ +-------------+
85
78
  ```
86
79
 
87
80
  `ctx.attempt` is the durable, 1-based claim ordinal. A kill after the claim can
88
81
  consume an ordinal before user code sees it, but adds no caught failure. A
89
82
  retry gets the same event id, index, type, and payload with a larger attempt.
90
83
 
91
- Use `event.id` to deduplicate external effects. `ctx.append` derives stable
92
- child ids when call order is stable. Otherwise, pass
93
- [explicit child ids](/concepts/handlers#handlers-can-run-twice).
84
+ Use `event.id` to deduplicate external effects. `ctx.session.append` derives
85
+ stable child ids from its handler-local name. See
86
+ [Handlers can run twice](/concepts/handlers#handlers-can-run-twice).
87
+
88
+ Each claim stores its holder and expiry on the event. Claiming an expired event
89
+ increments its attempt before a new handler starts. Completion and failure are
90
+ fenced by that ordinal, so an older attempt cannot overwrite a newer one.
91
+
92
+ ## Immediate and dependent events
93
+
94
+ Handlers have two ways to publish more events:
95
+
96
+ - `ctx.session.append(name, ...events)` commits immediately. Its events may run
97
+ before the current handler finishes. The stable name makes the append
98
+ idempotent across retries.
99
+ - `return event` or `return [eventA, eventB]` publishes only when the handler
100
+ succeeds. A2 completes the parent and appends the whole returned batch in
101
+ one transaction.
102
+
103
+ ```ts server/pipeline.ts
104
+ import { z } from 'zod'
105
+ import * as a2 from 'experimental-a2'
106
+ import { createServer } from 'experimental-a2/server'
107
+
108
+ const pipeline = a2.contract({
109
+ name: 'pipeline',
110
+ events: {
111
+ 'build.requested': z.object({ buildId: z.string() }),
112
+ 'build.completed': z.object({ buildId: z.string() }),
113
+ 'deploy.requested': z.object({ buildId: z.string() }),
114
+ },
115
+ })
116
+
117
+ export const pipelineServer = createServer({
118
+ contract: pipeline,
119
+ handlers: {
120
+ 'build.requested': async ({ event }) => {
121
+ // your side effect, idempotent via event.id:
122
+ // await build(event.payload, { idempotencyKey: event.id })
123
+ return [
124
+ { type: 'build.completed', payload: { buildId: event.payload.buildId } },
125
+ { type: 'deploy.requested', payload: { buildId: event.payload.buildId } },
126
+ ]
127
+ },
128
+ },
129
+ })
130
+ ```
131
+
132
+ If the handler throws, neither returned event exists. If the completion
133
+ transaction commits but its acknowledgment is lost, A2 retries with the same
134
+ ordered child ids and returns the already-committed rows. A partial or changed
135
+ batch is rejected.
136
+
137
+ This transaction covers only A2's log. An HTTP call, database write, Bash
138
+ command, or other external effect cannot join it. If an effect succeeds and
139
+ the process dies before completion commits, the handler runs it again. Use
140
+ `event.id` as an idempotency key or add fencing in the external system.
141
+
142
+ ## Lanes
143
+
144
+ A lane is a session-scoped serial group. A2 resolves the lane when it appends
145
+ the event and stores the value beside it.
146
+
147
+ - Events without a lane are independently eligible.
148
+ - Only the lowest-index unfinished event in a lane is eligible.
149
+ - Different lanes run concurrently.
150
+ - A failure blocks later events in that lane, not the whole session.
151
+
152
+ Persisting the value matters for recovery. A deployment that changes a lane
153
+ resolver affects new events, not pending ones already in the log.
154
+
155
+ A lane controls A2 dispatch, not the outside world. A worker can perform an
156
+ external effect and disappear before recording completion. Its successor then
157
+ retries the same event. External idempotency is still required.
158
+
159
+ A2 claims every currently eligible event. It does not add a global concurrency
160
+ limit or priority queue. Use lanes for ordered mutual exclusion. Put capacity
161
+ limits near the constrained resource, such as an API client, connection pool,
162
+ or execution runtime.
94
163
 
95
164
  ## Append and recovery
96
165
 
97
- A top-level append commits first, then starts the inline drain and optional
98
- watchdog arm in parallel. The drain never waits for the queue. Append joins the
99
- arm for at most two seconds; on failure, its telemetry span records
100
- `a2.append.armed = false`, but committed work continues. `ctx.append` rides the
101
- active drain and adds no arm.
166
+ A top-level append commits first. When pending handler work remains, it starts
167
+ the inline drain and optional watchdog arm in parallel. The drain never waits
168
+ for the queue. Append joins the arm for at most two seconds; on failure, its
169
+ telemetry span records `a2.append.armed = false`, but committed work continues.
170
+ `ctx.session.append` rides the active session drain and adds no arm. Returned
171
+ events enter the log as part of completion, then become eligible immediately.
172
+
173
+ `session.append.dispatch(...events)` chooses the other execution path. It
174
+ commits first, skips the current invocation's inline drain, and awaits an
175
+ immediate recovery send. It requires configured recovery. Queue delivery then
176
+ claims the same durable events through the normal drain path. If the send
177
+ fails, retry with the same explicit event IDs; the append itself may already
178
+ have committed. The recovery message is a wakeup, not worker affinity. An
179
+ already-active drain may claim the new work first.
180
+
181
+ An event type without a handler settles in the append transaction with no
182
+ dispatch attempt. It starts no drain or recovery arm when the session has no
183
+ older pending work. If older handled work is pending, the append still wakes
184
+ the session-wide healing path.
102
185
 
103
186
  ## Causal trees are durable
104
187
 
105
- Every event written by `ctx.append` stores one atomic `cause` with the
106
- triggering event's index and current dispatch ordinal. Top-level appends store
107
- null. In newly written data that is a root, but durable readers also use null
108
- for legacy events whose origin is unknown. Several appends from one handler are
109
- siblings. Nested handler appends create further levels. If a handler retries
110
- after writing a child, idempotency preserves that child's original cause.
188
+ Every event written by `ctx.session.append` or returned by a handler stores one
189
+ atomic `cause` with the triggering event's index and current dispatch ordinal.
190
+ Top-level appends store null. Several children from one handler are siblings.
191
+ Nested handler output creates further levels. If a handler retries after
192
+ writing a child, idempotency preserves that child's original cause.
111
193
 
112
194
  The edge is part of the existing append batch and survives process restarts.
113
- The stored event also carries `firstClaimedAt`, `lastClaimedAt`,
114
- `lastFailedAt`, `lastFailedAttempt`, `processedAt`, and `processedByAttempt`.
115
- These timestamps are adapter clock values captured for atomic log operations,
116
- not exact database commit times. `processedAt` is write-once, so a stale worker
117
- cannot rewrite a newer completion. The durable log can therefore rebuild a
118
- causal forest and show useful lifecycle boundaries. `attemptCount` summarizes
119
- intermediate claims instead of storing one row per attempt.
195
+ The stored event also carries `lane`, `firstClaimedAt`, `lastClaimedAt`,
196
+ `claimHolder`, `claimExpiresAt`, `lastFailedAt`, `lastFailedAttempt`,
197
+ `processedAt`, `processedByAttempt`, and `returnedEventIds`. Timestamps are
198
+ adapter clock values captured for atomic log operations, not exact database
199
+ commit times. A stale worker cannot rewrite a newer completion. The durable
200
+ log can rebuild a causal forest and useful lifecycle boundaries without one
201
+ row per attempt.
120
202
 
121
- ## Lease and watchdog timing
203
+ ## Claim and watchdog timing
122
204
 
123
- A heartbeat renews the session lease and arms a watchdog after each lease
124
- window. For illustration, use a five-second lease, two-second heartbeat, and
125
- one-second grace:
205
+ A heartbeat renews every live claim owned by the drain and arms a watchdog
206
+ after each claim window. For illustration, use a five-second claim, two-second
207
+ heartbeat, and one-second grace:
126
208
 
127
- | Time | Live worker | Lease | Watchdog |
209
+ | Time | Live worker | Event claim | Watchdog |
128
210
  | ---: | --- | --- | --- |
129
211
  | t0 | Claim attempt 1 | Through t5 | Arm t6 |
130
212
  | t2 | Heartbeat | Through t7 | Arm t8 |
@@ -135,15 +217,17 @@ one-second grace:
135
217
  | t9 | | Expires | t10 remains scheduled |
136
218
  | t10 | Claim attempt 2 | New window | Deliver t10: wins |
137
219
 
138
- Lease renewal and queue sends do not block each other. A busy watchdog ensures
139
- a later watchdog before acknowledging; if that send fails, it does not
140
- acknowledge. If a deadline is available, A2 caps the current lease window at
141
- it. The deadline never gates handler dispatch.
220
+ Claim renewal and queue sends do not block each other. An expired claim cannot
221
+ be renewed. It becomes eligible for a new claim, which increments the attempt
222
+ and fences the previous worker. A busy watchdog ensures a later watchdog
223
+ before acknowledging; if that send fails, it does not acknowledge. If a
224
+ deadline is available, A2 caps the current claim window at it. The deadline
225
+ never gates handler dispatch.
142
226
 
143
227
  ## A chain that crosses the function timeout
144
228
 
145
- Four eight-second handlers do not fit together in a 20-second invocation, but
146
- each fits in a fresh one:
229
+ Four eight-second handlers returned one after another do not fit together in a
230
+ 20-second invocation, but each fits in a fresh one:
147
231
 
148
232
  | Time | Work | Durable state |
149
233
  | ---: | --- | --- |
@@ -161,55 +245,57 @@ One handler that always exceeds a fresh invocation cannot finish this way. A2
161
245
  cannot checkpoint arbitrary async code. Split the work into smaller events or
162
246
  increase the function duration.
163
247
 
164
- ## Crash after a child append
248
+ ## Crash around a returned batch
165
249
 
166
250
  ```text
167
- +------------------------+
168
- | Invocation A |
169
- | event 2, attempt 1 |
170
- | append child event 3 |
171
- +-----------+------------+
172
- |
173
- v
174
- +------------------------+
175
- | Durable log |
176
- | event 2: pending |
177
- | event 3: pending |
178
- +-----------+------------+
179
- |
180
- SIGKILL, then lease expiry
181
- |
182
- v
183
- +------------------------+
184
- | Invocation B |
185
- | event 2, attempt 2 |
186
- | append reuses event 3 |
187
- +-----------+------------+
188
- |
189
- v
190
- complete 2, drain 3
251
+ +-------------------------+
252
+ | Invocation A |
253
+ | event 2, attempt 1 |
254
+ | handler returns event 3 |
255
+ +------------+------------+
256
+ |
257
+ completeAttempt
258
+ |
259
+ +-----+------+
260
+ | |
261
+ v v
262
+ transaction SIGKILL before
263
+ commits transaction
264
+ | |
265
+ v v
266
+ event 2 done event 2 pending
267
+ event 3 exists event 3 absent
191
268
  ```
192
269
 
193
- The deterministic child id makes the retry reuse event 3. External effects
194
- use event 2's id as their idempotency key.
270
+ If the commit acknowledgment is lost, a retry with the exact returned ids gets
271
+ event 3 back without duplicating it. If the transaction did not commit, event
272
+ 2 retries and produces the same deterministic returned id. External effects
273
+ still use event 2's id as their idempotency key.
274
+
275
+ With `ctx.session.append`, the child commits before its parent finishes. It
276
+ remains in the log if the parent crashes and can run concurrently unless both
277
+ events use the same lane.
195
278
 
196
279
  ## Why this stays correct
197
280
 
198
281
  | Property | Durable rule |
199
282
  | --- | --- |
200
283
  | Commit | Store the event before any wakeup. |
201
- | Order | Claim only the lowest pending index. |
202
- | Ownership | Only a live lease holder can claim the next event. |
203
- | Handoff | Complete the current event and claim the next atomically. |
284
+ | Concurrency | Claim every eligible unlaned event and one unfinished head per lane. |
285
+ | Ownership | Store an expiring claim on each event. |
286
+ | Completion | Complete the parent and append its returned batch atomically. |
287
+ | Fencing | Only the current attempt can complete or record a failure. |
204
288
  | Retry | Without a processed marker, the same event remains pending. |
205
- | Identity | Event and derived child ids stay stable across retries. |
289
+ | Identity | Event, immediate child, and returned child ids stay stable across retries. |
206
290
  | Liveness | A watchdog, later append, or explicit drain re-enters `drain(session)`. |
207
291
 
208
292
  ## When a handler keeps failing
209
293
 
210
- A caught failure increments `failureCount`; a stale failure changes nothing.
211
- Ten caught failures dead-letter the event and stall that session. Hard kills
212
- do not consume this budget. Resolution is manual: fix and retry, or skip.
294
+ A caught failure increments `failureCount`, clears that event's claim, and
295
+ leaves other eligible events running. A stale failure changes nothing. Ten
296
+ caught failures dead-letter the event. Later events in its lane remain blocked;
297
+ unlaned events and other lanes continue. Hard kills do not consume this budget.
298
+ Resolution is manual: fix and retry, or skip.
213
299
 
214
300
  ## Limits
215
301
 
@@ -218,7 +304,8 @@ do not consume this budget. Resolution is manual: fix and retry, or skip.
218
304
  | Process dies before the first arm is durable | Retry with the same ids, append again later, or call `drain()`. |
219
305
  | No recovery configured | A later top-level append or explicit `drain()` wakes the session. Reads never do. |
220
306
  | Recovery dies after claiming but before arming | Its unacknowledged queue delivery is the slower fallback. |
221
- | Log or lease backend unavailable | Safe progress stops until it returns. |
307
+ | Log backend unavailable | Safe progress stops until it returns. |
308
+ | External effect succeeds before A2 completion | The handler may repeat it. Use idempotency or external fencing. |
222
309
 
223
310
  ## What append never throws for
224
311
 
@@ -67,6 +67,25 @@ const { state, index } = await ordersServer
67
67
  .state(ordersReducer)
68
68
  ```
69
69
 
70
+ Handlers receive the same session interface for their triggering session:
71
+
72
+ ```ts server.ts
73
+ import { createServer } from 'experimental-a2/server'
74
+ import { orders } from './contracts'
75
+ import { ordersReducer } from './reducer'
76
+
77
+ export const ordersServer = createServer({
78
+ contract: orders,
79
+ handlers: {
80
+ created: async ({ session }) => {
81
+ const { state, index } = await session.state(ordersReducer)
82
+ void state
83
+ void index
84
+ },
85
+ },
86
+ })
87
+ ```
88
+
70
89
  A reducer is a name (its identity, more on that below) plus the values that
71
90
  anchor it: `initialState` (the seed), an optional `stateSchema`, and the
72
91
  pure `fold`, `(state, event) => state`. It's derived *from* the
@@ -83,7 +102,14 @@ The snapshot and its remaining event tail come back in one consistent log
83
102
  operation. A missing snapshot reads the full log. A snapshot rejected by
84
103
  `stateSchema`, or a failed cache read, falls back to the full log and rebuilds
85
104
  from truth. `state()` is observational: it never runs handlers or waits for
86
- pending work to finish.
105
+ pending work to finish. Inside a handler, the returned index includes the
106
+ triggering event and may include later events that committed before the read.
107
+
108
+ The read and a following `ctx.session.append(name, ...events)` are separate
109
+ operations. Concurrent appends and retries can move the frontier between them.
110
+ For joins, use a monotone readiness check (once ready, always ready) and give
111
+ the output event a stable explicit `id`. Repeated attempts then converge on the
112
+ same append.
87
113
 
88
114
  `stateSchema` declares the state's shape once. Without it, the state type
89
115
  is inferred from `initialState`, fine while every fold arm returns the
@@ -25,14 +25,14 @@ import { orders } from '@/contracts'
25
25
  export const ordersServer = createServer({
26
26
  contract: orders,
27
27
  handlers: {
28
- created: async ({ event }) => {
28
+ created: async ({ session }) => {
29
29
  // schedule with anything that can deliver an HTTP call later:
30
30
  // QStash, cron, a provider webhook:
31
31
  //
32
32
  // await scheduleHttpCall({
33
33
  // delay: '5d',
34
34
  // url: '/api/append',
35
- // body: { sessionId: event.sessionId, type: 'expired', payload: {} },
35
+ // body: { sessionId: session.id, type: 'expired', payload: {} },
36
36
  // })
37
37
  },
38
38
  },
@@ -70,8 +70,8 @@ import { orders } from '@/contracts'
70
70
  export const ordersServer = createServer({
71
71
  contract: orders,
72
72
  handlers: {
73
- expired: async ({ history }) => {
74
- const events = await history()
73
+ expired: async ({ session }) => {
74
+ const events = await session.history()
75
75
  if (events.some((e) => e.type === 'shop.started')) return // stale, ignore
76
76
  // ...actually expire the order
77
77
  },
@@ -65,10 +65,38 @@ generate: {
65
65
  The pushing side already knows the id it's cancelling; it's in the
66
66
  `events` feed the hook exposes.
67
67
 
68
- Because sessions process serially, the `cancelled` event's own handler runs
69
- *after* the interrupted one settles. That makes it the natural place for
70
- cleanup. The signal is the preemption channel; the event is the durable
71
- record.
68
+ Handlers are concurrent by default. A `cancelled` handler may therefore run
69
+ while the interrupted handler is still unwinding. The signal is the
70
+ preemption channel; the event is the durable record.
71
+
72
+ When cleanup must wait for the interrupted handler, put both event types in
73
+ one lane. The event fires the signal as soon as it is appended, but its own
74
+ handler waits for earlier work in that lane:
75
+
76
+ ```ts server/chat-with-cleanup.ts
77
+ import { createServer } from 'experimental-a2/server'
78
+ import { chat } from '@/contracts'
79
+
80
+ export const chatServer = createServer({
81
+ contract: chat,
82
+ handlers: {
83
+ generate: {
84
+ lane: 'generation',
85
+ abortOn: ['cancelled'],
86
+ handler: async (ctx) => {
87
+ // your abortable work; hand it ctx.signal:
88
+ // await streamText({ signal: ctx.signal, ... })
89
+ },
90
+ },
91
+ cancelled: {
92
+ lane: 'generation',
93
+ handler: async () => {
94
+ // your cleanup, after generate has returned
95
+ },
96
+ },
97
+ },
98
+ })
99
+ ```
72
100
 
73
101
  ## The view cuts
74
102