@systemfsoftware/agent-storage-cloudflare 0.0.0-stage → 0.1.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 (101) hide show
  1. package/LICENSE +21 -0
  2. package/dist/DoMemoryStore-AaGtt8CZ.d.mts +29 -0
  3. package/dist/DoMemoryStore-DVun329p.mjs +67 -0
  4. package/dist/DoMemoryStore-DVun329p.mjs.map +1 -0
  5. package/dist/DoMemoryStore.d.mts +2 -0
  6. package/dist/DoMemoryStore.mjs +1 -0
  7. package/dist/DoMessageDeliveryStore-BvB6OPI1.mjs +34 -0
  8. package/dist/DoMessageDeliveryStore-BvB6OPI1.mjs.map +1 -0
  9. package/dist/DoMessageDeliveryStore-Cb-DNN5s.d.mts +16 -0
  10. package/dist/DoMessageDeliveryStore.d.mts +2 -0
  11. package/dist/DoMessageDeliveryStore.mjs +1 -0
  12. package/dist/DoScheduleStore-BiTgDvX1.d.mts +36 -0
  13. package/dist/DoScheduleStore-C7GkSReF.mjs +167 -0
  14. package/dist/DoScheduleStore-C7GkSReF.mjs.map +1 -0
  15. package/dist/DoScheduleStore.d.mts +2 -0
  16. package/dist/DoScheduleStore.mjs +1 -0
  17. package/dist/DoStorageConfig-BqezsbD6.mjs +43 -0
  18. package/dist/DoStorageConfig-BqezsbD6.mjs.map +1 -0
  19. package/dist/DoStorageConfig-CuB6ZOtX.d.mts +36 -0
  20. package/dist/DoStorageConfig.d.mts +2 -0
  21. package/dist/DoStorageConfig.mjs +1 -0
  22. package/dist/DoStorageError-C-F5Z_FZ.d.mts +82 -0
  23. package/dist/DoStorageError-DSQzuCb0.mjs +138 -0
  24. package/dist/DoStorageError-DSQzuCb0.mjs.map +1 -0
  25. package/dist/DoStorageError.d.mts +2 -0
  26. package/dist/DoStorageError.mjs +1 -0
  27. package/dist/DoStorageFailpoint-C7zLUULu.d.mts +19 -0
  28. package/dist/DoStorageFailpoint-WO3B_DQl.mjs +20 -0
  29. package/dist/DoStorageFailpoint-WO3B_DQl.mjs.map +1 -0
  30. package/dist/DoStorageFailpoint.d.mts +2 -0
  31. package/dist/DoStorageFailpoint.mjs +1 -0
  32. package/dist/DoStorageFailpointTesting.d.mts +21 -0
  33. package/dist/DoStorageFailpointTesting.mjs +18 -0
  34. package/dist/DoStorageFailpointTesting.mjs.map +1 -0
  35. package/dist/DoStorageVersion-BrolfBDS.mjs +7 -0
  36. package/dist/DoStorageVersion-BrolfBDS.mjs.map +1 -0
  37. package/dist/DoStorageVersion-D7CIxFc_.d.mts +8 -0
  38. package/dist/DoStorageVersion.d.mts +3 -0
  39. package/dist/DoStorageVersion.mjs +2 -0
  40. package/dist/DoSubmissionLedger-Oq5OstxL.mjs +1878 -0
  41. package/dist/DoSubmissionLedger-Oq5OstxL.mjs.map +1 -0
  42. package/dist/DoSubmissionLedger-tLjwidUn.d.mts +25 -0
  43. package/dist/DoSubmissionLedger.d.mts +2 -0
  44. package/dist/DoSubmissionLedger.mjs +1 -0
  45. package/dist/DoSubscriptionStore-BMJiFxt3.mjs +185 -0
  46. package/dist/DoSubscriptionStore-BMJiFxt3.mjs.map +1 -0
  47. package/dist/DoSubscriptionStore-zx6nfbbh.d.mts +25 -0
  48. package/dist/DoSubscriptionStore.d.mts +2 -0
  49. package/dist/DoSubscriptionStore.mjs +1 -0
  50. package/dist/DoThreadStore-2zTSfui-.d.mts +81 -0
  51. package/dist/DoThreadStore-CeYHcRR9.mjs +411 -0
  52. package/dist/DoThreadStore-CeYHcRR9.mjs.map +1 -0
  53. package/dist/DoThreadStore.d.mts +2 -0
  54. package/dist/DoThreadStore.mjs +5 -0
  55. package/dist/MemoryProtocol-CtCFYe4s.mjs +221 -0
  56. package/dist/MemoryProtocol-CtCFYe4s.mjs.map +1 -0
  57. package/dist/MemoryProtocol-DXV77CcJ.d.mts +38160 -0
  58. package/dist/MemoryProtocol.d.mts +2 -0
  59. package/dist/MemoryProtocol.mjs +1 -0
  60. package/dist/PortProtocol-4xvMyCgP.mjs +322 -0
  61. package/dist/PortProtocol-4xvMyCgP.mjs.map +1 -0
  62. package/dist/PortProtocol-DXuguAgD.d.mts +966 -0
  63. package/dist/PortProtocol.d.mts +2 -0
  64. package/dist/PortProtocol.mjs +1 -0
  65. package/dist/PortRouting-B9302ouX.mjs +683 -0
  66. package/dist/PortRouting-B9302ouX.mjs.map +1 -0
  67. package/dist/PortRouting-DsoI6soW.d.mts +105 -0
  68. package/dist/PortRouting.d.mts +2 -0
  69. package/dist/PortRouting.mjs +1 -0
  70. package/dist/do-journal-nPNEAjV5.mjs +769 -0
  71. package/dist/do-journal-nPNEAjV5.mjs.map +1 -0
  72. package/dist/index.d.mts +14 -0
  73. package/dist/index.mjs +14 -0
  74. package/dist/migrations-BRTvj8Ue.mjs +233 -0
  75. package/dist/migrations-BRTvj8Ue.mjs.map +1 -0
  76. package/dist/owned-state-DrOD9s0c.mjs +157 -0
  77. package/dist/owned-state-DrOD9s0c.mjs.map +1 -0
  78. package/dist/rolldown-runtime-D3KUYPsf.mjs +12 -0
  79. package/package.json +106 -3
  80. package/src/DoMemoryStore.ts +71 -0
  81. package/src/DoMessageDeliveryStore.ts +46 -0
  82. package/src/DoScheduleStore.ts +276 -0
  83. package/src/DoStorageConfig.ts +45 -0
  84. package/src/DoStorageError.ts +146 -0
  85. package/src/DoStorageFailpoint.ts +25 -0
  86. package/src/DoStorageFailpointTesting.ts +42 -0
  87. package/src/DoStorageVersion.ts +2 -0
  88. package/src/DoSubmissionLedger.ts +3980 -0
  89. package/src/DoSubscriptionStore.ts +331 -0
  90. package/src/DoThreadStore.ts +602 -0
  91. package/src/MemoryProtocol.ts +357 -0
  92. package/src/PortProtocol.ts +626 -0
  93. package/src/PortRouting.ts +1888 -0
  94. package/src/index.ts +13 -0
  95. package/src/internal/canonical-append.ts +15 -0
  96. package/src/internal/do-journal.ts +1449 -0
  97. package/src/internal/migrations.ts +395 -0
  98. package/src/internal/owned-state.ts +300 -0
  99. package/src/internal/prompt-checkpoint.ts +170 -0
  100. package/src/internal/storage-span.ts +54 -0
  101. package/README.md +0 -3
@@ -0,0 +1,1449 @@
1
+ import * as SqliteClient from '@effect/sql-sqlite-do/SqliteClient'
2
+ import { makeCanonicalStorage, recordBatchId } from '@systemfsoftware/agent-storage-sql/sql-canonical-storage'
3
+ import type { RawAppendRequest } from '@systemfsoftware/agent-storage-sql/sql-journal'
4
+ import { makeSqlExecutions } from '@systemfsoftware/agent-storage-sql/sql-journal'
5
+ import {
6
+ makeSqlLifecyclePublication,
7
+ SqlLifecycleRetainer,
8
+ type SqlLifecycleRetainMany,
9
+ SqlLifecycleSource,
10
+ } from '@systemfsoftware/agent-storage-sql/sql-lifecycle-publication'
11
+ import { publishCanonicalDeliveries } from '@systemfsoftware/agent-storage-sql/sql-message-delivery-store'
12
+ import { SqlStorageProgress } from '@systemfsoftware/agent-storage-sql/sql-storage-progress'
13
+ import {
14
+ canonicalRecordJson,
15
+ makeSqlThreadArchiveRange,
16
+ } from '@systemfsoftware/agent-storage-sql/sql-thread-archive-range'
17
+ import { makeSqlThreadWork } from '@systemfsoftware/agent-storage-sql/sql-thread-work'
18
+ import { ThreadId } from '@systemfsoftware/agent/identifiers'
19
+ import { LifecyclePublicationError, LifecyclePublicationFact } from '@systemfsoftware/agent/lifecycle-publication'
20
+ import { BatchId, CanonicalRecord, CanonicalSequence } from '@systemfsoftware/agent/records'
21
+ import { StorageOwner } from '@systemfsoftware/agent/run-storage'
22
+ import { SqlStorageOwner } from '@systemfsoftware/agent/sql-storage-owner'
23
+ import {
24
+ type AppendConflict,
25
+ AppendResult,
26
+ ThreadStoreDiagnostic,
27
+ ThreadStoreError,
28
+ } from '@systemfsoftware/agent/thread-store'
29
+ import { WORK_INDEX_VERSION } from '@systemfsoftware/agent/thread-work'
30
+ import * as Arr from 'effect/Array'
31
+ import * as Cause from 'effect/Cause'
32
+ import * as Clock from 'effect/Clock'
33
+ import * as Context from 'effect/Context'
34
+ import * as Effect from 'effect/Effect'
35
+ import * as Layer from 'effect/Layer'
36
+ import * as Option from 'effect/Option'
37
+ import * as Predicate from 'effect/Predicate'
38
+ import * as References from 'effect/References'
39
+ import * as Result from 'effect/Result'
40
+ import * as Schema from 'effect/Schema'
41
+ import * as SqlClient from 'effect/sql/SqlClient'
42
+ import * as SqlError from 'effect/sql/SqlError'
43
+ import * as Statement from 'effect/sql/Statement'
44
+ import * as Stream from 'effect/Stream'
45
+ import * as Tracer from 'effect/Tracer'
46
+
47
+ import { DoStorageConfig } from '../DoStorageConfig'
48
+ import {
49
+ DoAppendConflict,
50
+ DoStorageCorruptionError,
51
+ DoStorageError,
52
+ type DoStorageFailpointError,
53
+ type DoStorageFailpointLocation,
54
+ DoValueBoundExceeded,
55
+ } from '../DoStorageError'
56
+ import { DoStorageFailpoint, isDefaultDoStorageFailpoint } from '../DoStorageFailpoint'
57
+ import { ensureDoStorageLayout } from './migrations'
58
+ import { ownedRows, type OwnedState, ownedState } from './owned-state'
59
+ import { annotateStorageError, isAppendContention, storageResult, withStorageSpan } from './storage-span'
60
+
61
+ /**
62
+ * Static schema ceiling for stored text columns. Writes are bounded in BYTES by the
63
+ * configured `maxStoredValueBytes` (always ≤ 2,000,000); UTF-8 byte length is never smaller
64
+ * than UTF-16 string length, so any value that passed the byte bound also passes this
65
+ * decode-side character ceiling.
66
+ */
67
+ const BoundedStoredText = Schema.String.check(Schema.isMaxLength(2_000_000))
68
+ const BoundedIdentifier = Schema.NonEmptyString.check(Schema.isMaxLength(1024))
69
+ const MAX_IDENTIFIER_LENGTH = 1_024
70
+ const MAX_READ_PAGE_JSON_BYTES = 4 * 1024 * 1024
71
+ // A shared isolate budget permits multi-page hydration without multiplying its
72
+ // retained payload by the number of resident Durable Object instances.
73
+ const MAX_RECORD_CACHE_JSON_BYTES = 8 * 1024 * 1024
74
+ const MAX_RECORD_CACHE_ENTRIES = 4_096
75
+ /** Durable Object SQL storage allows at most 100 bound parameters per statement. */
76
+ const MAX_BOUND_PARAMETERS = 100
77
+ const isSqlError = Schema.is(SqlError.SqlError)
78
+
79
+ const isNativeClient = Schema.is(
80
+ Schema.declare<SqliteClient.SqliteClient>((value): value is SqliteClient.SqliteClient =>
81
+ Predicate.hasProperty(value, SqliteClient.TypeId)
82
+ ),
83
+ )
84
+
85
+ const storedTextBytes = (value: string): number => new TextEncoder().encode(value).byteLength
86
+
87
+ class ThreadRow extends Schema.Class<ThreadRow>('ThreadRow')({
88
+ thread_id: BoundedIdentifier,
89
+ created_at: Schema.NullOr(Schema.NonEmptyString.check(Schema.isMaxLength(128))),
90
+ tail_sequence: CanonicalSequence,
91
+ }) {}
92
+
93
+ const threadRows = ownedRows(
94
+ ThreadRow,
95
+ 'effect_agent_threads',
96
+ (row) => row.thread_id,
97
+ 'thread_id',
98
+ )
99
+
100
+ class RecordRow extends Schema.Class<RecordRow>('RecordRow')({
101
+ batch_id: Schema.fromJsonString(BatchId.check(Schema.isMaxLength(MAX_IDENTIFIER_LENGTH))),
102
+ thread_id: ThreadId.check(Schema.isMaxLength(MAX_IDENTIFIER_LENGTH)),
103
+ record_id: Schema.fromJsonString(BoundedIdentifier),
104
+ record_json: BoundedStoredText,
105
+ sequence: CanonicalSequence,
106
+ }) {}
107
+
108
+ interface RecordCacheEntry {
109
+ readonly row: RecordRow
110
+ readonly bytes: number
111
+ readonly evict: () => void
112
+ }
113
+
114
+ // Entries retain only their local row map, never a storage owner or incarnation.
115
+ const isolateRecords = new Map<RecordCacheEntry, true>()
116
+ let isolateRecordBytes = 0
117
+
118
+ const releaseRecord = (entry: RecordCacheEntry) => {
119
+ if (!isolateRecords.delete(entry)) return
120
+ isolateRecordBytes -= entry.bytes
121
+ entry.evict()
122
+ }
123
+
124
+ const recordCaches = new WeakMap<OwnedState, ReturnType<typeof makeRecordCache>>()
125
+
126
+ const makeRecordCache = () => {
127
+ const records = new Map<string, RecordCacheEntry>()
128
+ const key = (thread: string, sequence: number) => JSON.stringify([thread, sequence])
129
+
130
+ return {
131
+ clear: () => {
132
+ for (const entry of records.values()) releaseRecord(entry)
133
+ },
134
+ get: (thread: string, sequence: number) => records.get(key(thread, sequence))?.row,
135
+ prefix: (thread: string, through: number): ReadonlyArray<RecordRow> | undefined => {
136
+ const prefix: Array<RecordRow> = []
137
+
138
+ for (let sequence = 1; sequence <= through; sequence++) {
139
+ const row = records.get(key(thread, sequence))
140
+
141
+ if (row === undefined) return undefined
142
+ prefix.push(row.row)
143
+ }
144
+
145
+ return prefix
146
+ },
147
+ put: (row: RecordRow, capturedBytes?: number) => {
148
+ const id = key(row.thread_id, row.sequence)
149
+ const prior = records.get(id)
150
+
151
+ if (prior?.row === row) return
152
+ const size = capturedBytes ?? storedTextBytes(row.record_json)
153
+
154
+ if (prior !== undefined) releaseRecord(prior)
155
+
156
+ const entry: RecordCacheEntry = {
157
+ row,
158
+ bytes: size,
159
+ evict: () => records.delete(id),
160
+ }
161
+
162
+ records.set(id, entry)
163
+ isolateRecords.set(entry, true)
164
+ isolateRecordBytes += size
165
+ while (
166
+ isolateRecordBytes > MAX_RECORD_CACHE_JSON_BYTES ||
167
+ isolateRecords.size > MAX_RECORD_CACHE_ENTRIES
168
+ ) {
169
+ const oldest = isolateRecords.keys().next().value
170
+
171
+ if (oldest === undefined) break
172
+ releaseRecord(oldest)
173
+ }
174
+ },
175
+ }
176
+ }
177
+
178
+ const ReadPlanRow = Schema.Struct({
179
+ sequence: CanonicalSequence,
180
+ record_json_bytes: Schema.Natural.check(Schema.isLessThanOrEqualTo(MAX_READ_PAGE_JSON_BYTES)),
181
+ })
182
+
183
+ type ReadPage = [typeof ReadPlanRow.Type, ...Array<typeof ReadPlanRow.Type>]
184
+
185
+ const LifecycleCursorRow = Schema.Struct({
186
+ thread_id: BoundedIdentifier,
187
+ through_sequence: CanonicalSequence,
188
+ })
189
+
190
+ const lifecycleCursorRows = ownedRows(
191
+ LifecycleCursorRow,
192
+ 'effect_agent_lifecycle_cursors',
193
+ (row) => row.thread_id,
194
+ 'thread_id',
195
+ )
196
+
197
+ const initializedLifecycleSources = new WeakSet<OwnedState>()
198
+
199
+ export type { RawAppendRequest } from '@systemfsoftware/agent-storage-sql/sql-journal'
200
+
201
+ export class RawReadRequest extends Schema.Class<RawReadRequest>(
202
+ '@effect-agent/storage-cloudflare/RawReadRequest',
203
+ )({
204
+ threadId: BoundedIdentifier,
205
+ fromSequenceExclusive: CanonicalSequence,
206
+ limit: Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(1_024)),
207
+ }) {}
208
+
209
+ type AppendError =
210
+ | ThreadStoreError
211
+ | DoAppendConflict
212
+ | DoStorageCorruptionError
213
+ | DoStorageError
214
+ | DoStorageFailpointError
215
+ | DoValueBoundExceeded
216
+
217
+ type DoJournalFailpoint = (
218
+ location: DoStorageFailpointLocation,
219
+ ) => Effect.Effect<void, DoStorageFailpointError>
220
+
221
+ const noFailpoint: DoJournalFailpoint = () => Effect.void
222
+
223
+ const storageError = (operation: string) => (error: SqlError.SqlError): DoStorageError =>
224
+ DoStorageError.make({
225
+ cause: error,
226
+ operation,
227
+ message: error.message,
228
+ diagnostic: ThreadStoreDiagnostic.make({
229
+ causeTag: error._tag,
230
+ operation,
231
+ issueTag: error.reason._tag,
232
+ }),
233
+ })
234
+
235
+ /** Decode raw Durable Object SQLite rows against a Schema, reporting failures as typed corruption. */
236
+ export const decodeRows = <A, I>(
237
+ schema: Schema.Codec<ReadonlyArray<A>, ReadonlyArray<I>>,
238
+ table: string,
239
+ rowKey: string,
240
+ rows: unknown,
241
+ decoder: string = table,
242
+ ): Effect.Effect<ReadonlyArray<A>, DoStorageCorruptionError> =>
243
+ Schema.decodeUnknownEffect(schema)(rows).pipe(
244
+ Effect.mapError((error) =>
245
+ DoStorageCorruptionError.make({
246
+ table,
247
+ rowKey,
248
+ message: 'Stored rows do not satisfy the storage schema',
249
+ diagnostic: ThreadStoreDiagnostic.make({
250
+ causeTag: error._tag,
251
+ operation: 'decode storage rows',
252
+ decoder,
253
+ issueTag: error.issue._tag,
254
+ }),
255
+ })
256
+ ),
257
+ Effect.tapError((error) =>
258
+ Effect.annotateCurrentSpan({
259
+ 'storage.failure.operation': error.diagnostic?.operation,
260
+ 'storage.failure.cause': error.diagnostic?.causeTag,
261
+ 'storage.failure.decoder': decoder,
262
+ 'storage.failure.issue': error.diagnostic?.issueTag,
263
+ })
264
+ ),
265
+ )
266
+
267
+ /** Decode exactly one raw row against a Schema, reporting failures as typed corruption. */
268
+ export const decodeSingleRow = <A, I>(
269
+ schema: Schema.Codec<ReadonlyArray<A>, ReadonlyArray<I>>,
270
+ table: string,
271
+ rowKey: string,
272
+ rows: unknown,
273
+ ): Effect.Effect<A, DoStorageCorruptionError> =>
274
+ decodeRows(schema, table, rowKey, rows).pipe(
275
+ Effect.flatMap((decoded) =>
276
+ decoded.length === 1
277
+ ? Effect.succeed(decoded[0])
278
+ : Effect.fail(
279
+ DoStorageCorruptionError.make({
280
+ table,
281
+ rowKey,
282
+ message: `Expected exactly one row but found ${decoded.length}.`,
283
+ }),
284
+ )
285
+ ),
286
+ )
287
+
288
+ /** Open a validated layout and bind this Object's storage owner. */
289
+ const ensureCurrentStorage = Effect.fnUntraced(function*(
290
+ sql: SqlClient.SqlClient,
291
+ failpoint: DoJournalFailpoint = noFailpoint,
292
+ maxStoredValueBytes: number,
293
+ ) {
294
+ const state = yield* ownedState(sql)
295
+ const owner = (yield* SqlStorageOwner) ?? state
296
+
297
+ yield* ensureDoStorageLayout().pipe(
298
+ Effect.provideService(SqlStorageOwner, owner),
299
+ Effect.provideService(SqlClient.SqlClient, sql),
300
+ )
301
+
302
+ let journal: DoJournal | undefined
303
+
304
+ const lifecycle = yield* makeSqlLifecyclePublication(undefined, maxStoredValueBytes).pipe(
305
+ Effect.provideService(SqlStorageOwner, owner),
306
+ Effect.provideService(SqlLifecycleSource, {
307
+ beforeRetain: (threadId) =>
308
+ Effect.suspend(() =>
309
+ journal === undefined
310
+ ? Effect.fail(LifecyclePublicationError.make({ reason: 'unavailable' }))
311
+ : journal.flushCanonical(threadId)
312
+ ),
313
+ beforePending: Effect.suspend(() =>
314
+ journal === undefined
315
+ ? Effect.fail(LifecyclePublicationError.make({ reason: 'unavailable' }))
316
+ : journal.flushPublications()
317
+ ),
318
+ }),
319
+ Effect.provideService(SqlClient.SqlClient, sql),
320
+ Effect.mapError((cause) =>
321
+ DoStorageError.make({
322
+ operation: 'initialize lifecycle publication',
323
+ message: 'Native publication storage unavailable',
324
+ cause,
325
+ })
326
+ ),
327
+ )
328
+
329
+ journal = yield* makeJournal(sql, failpoint, maxStoredValueBytes, lifecycle, state).pipe(
330
+ Effect.provideService(SqlStorageOwner, owner),
331
+ )
332
+ if (lifecycle !== undefined) yield* journal.initializeLifecycleSource()
333
+
334
+ return journal
335
+ })
336
+
337
+ const makeJournal = Effect.fnUntraced(function*(
338
+ sql: SqlClient.SqlClient,
339
+ failpoint: DoJournalFailpoint,
340
+ maxStoredValueBytes: number,
341
+ lifecycle: Effect.Success<ReturnType<typeof makeSqlLifecyclePublication>>,
342
+ state: OwnedState,
343
+ ) {
344
+ const owner = (yield* SqlStorageOwner) ?? state
345
+ const progress = yield* SqlStorageProgress
346
+
347
+ const publishDeliveries = Effect.fnUntraced(
348
+ function*(records: RawAppendRequest['deliveries']) {
349
+ yield* publishCanonicalDeliveries(records)
350
+ },
351
+ Effect.provideService(StorageOwner, state.owner),
352
+ Effect.mapError((cause) =>
353
+ ThreadStoreError.make({
354
+ operation: 'publish canonical message deliveries',
355
+ message: 'Canonical message obligations could not be retained',
356
+ deliveryReason: cause.reason,
357
+ cause,
358
+ })
359
+ ),
360
+ )
361
+
362
+ const nativeDb = isNativeClient(sql) &&
363
+ sql.config.transformQueryNames === undefined &&
364
+ sql.config.transformResultNames === undefined &&
365
+ isDefaultDoStorageFailpoint(failpoint)
366
+ ? sql.config.storage?.sql
367
+ : undefined
368
+
369
+ const work = yield* makeSqlThreadWork({
370
+ read: (body) => state.read(body),
371
+ write: (body) =>
372
+ owner.transaction(body.pipe(Effect.tap(() => state.invalidate))).pipe(
373
+ Effect.provideService(SqlClient.SqlClient, sql),
374
+ Effect.catchTag('SqlError', (cause) =>
375
+ ThreadStoreError.make({
376
+ operation: 'rebuild Thread work',
377
+ message: 'Thread work transaction failed',
378
+ cause,
379
+ })),
380
+ ),
381
+ }).pipe(Effect.provideService(SqlClient.SqlClient, sql))
382
+
383
+ yield* Effect.acquireRelease(
384
+ Effect.sync(() => state.invalidators.add(work.invalidate)),
385
+ () => Effect.sync(() => state.invalidators.delete(work.invalidate)),
386
+ )
387
+
388
+ const workFailure = (cause: unknown) =>
389
+ DoStorageError.make({
390
+ operation: 'publish Thread work',
391
+ message: 'Canonical work metadata could not be published',
392
+ cause,
393
+ })
394
+
395
+ const executions = yield* makeSqlExecutions().pipe(
396
+ Effect.provideService(SqlClient.SqlClient, sql),
397
+ )
398
+
399
+ const executionConflict = <A>(effect: Effect.Effect<A, AppendConflict | ThreadStoreError>) =>
400
+ effect.pipe(
401
+ Effect.catchTag('AppendConflict', (error) =>
402
+ Effect.fail(
403
+ DoAppendConflict.make({
404
+ reason: error.reason,
405
+ message: 'Active execution conflicts with the captured commit',
406
+ ...(error.actualTailSequence === undefined
407
+ ? {}
408
+ : { actualTailSequence: error.actualTailSequence }),
409
+ }),
410
+ )),
411
+ )
412
+
413
+ const threads = threadRows(state, sql)
414
+ const cursors = lifecycleCursorRows(state, sql)
415
+ let records = recordCaches.get(state)
416
+
417
+ if (records === undefined) {
418
+ records = makeRecordCache()
419
+ recordCaches.set(state, records)
420
+ state.invalidators.add(records.clear)
421
+ }
422
+ const recordCache = records
423
+
424
+ const archives = yield* makeSqlThreadArchiveRange({
425
+ read: (body) => state.read(body),
426
+ write: (body) =>
427
+ owner.transaction(body.pipe(Effect.tap(() => state.invalidate))).pipe(
428
+ Effect.provideService(SqlClient.SqlClient, sql),
429
+ Effect.catchTag('SqlError', (cause) =>
430
+ ThreadStoreError.make({
431
+ operation: 'archive write',
432
+ message: 'Archive transaction failed.',
433
+ cause,
434
+ })),
435
+ ),
436
+ }).pipe(Effect.provideService(SqlClient.SqlClient, sql))
437
+
438
+ const recordJson = canonicalRecordJson(sql)
439
+
440
+ const physical = yield* makeCanonicalStorage().pipe(
441
+ Effect.provideService(SqlClient.SqlClient, sql),
442
+ )
443
+
444
+ /** Typed pre-write refusal for any single value over the configured byte bound. */
445
+ const checkValueBound = (
446
+ operation: string,
447
+ value: string,
448
+ actualBytes = storedTextBytes(value),
449
+ ): Effect.Effect<void, DoValueBoundExceeded> => {
450
+ return actualBytes > maxStoredValueBytes
451
+ ? Effect.fail(
452
+ DoValueBoundExceeded.make({
453
+ actualBytes,
454
+ maxBytes: maxStoredValueBytes,
455
+ operation,
456
+ }),
457
+ )
458
+ : Effect.void
459
+ }
460
+
461
+ /**
462
+ * Runs one journal write transaction on the Durable Object storage-backed
463
+ * `withTransaction` (`ctx.storage.transaction()` under the hood). Within one Durable
464
+ * Object there is exactly ONE writer, so the Node `BEGIN IMMEDIATE` + busy-retry +
465
+ * `SqliteWriteContention` machinery has no analogue here and is deliberately absent.
466
+ * The shared local owner gate covers the transaction and acknowledgement.
467
+ *
468
+ * Journal write transactions are always top level: the Durable Object client rejects
469
+ * nested transactions, so new journal operations must not wrap this helper inside another
470
+ * transaction. Expected outcomes may be captured only when every such refusal precedes
471
+ * mutation; real faults still roll back. Successful preflight reads never authorize a write.
472
+ */
473
+ const withWriteTransaction = (
474
+ operation: string,
475
+ expected?: (error: { readonly _tag: string }) => boolean,
476
+ ) => {
477
+ const transaction = <A, E extends { readonly _tag: string }>(
478
+ effect: Effect.Effect<A, E>,
479
+ ): Effect.Effect<A, E | DoStorageError> =>
480
+ Effect.withFiber((fiber) => {
481
+ const body = state.owner.withMutation(owner.transaction(effect)).pipe(
482
+ Effect.provideService(SqlClient.SqlClient, sql),
483
+ Effect.mapError((error) => (isSqlError(error) ? storageError(operation)(error) : error)),
484
+ )
485
+
486
+ const traced = fiber.getRef(References.TracerEnabled) &&
487
+ fiber.getRef(Tracer.Tracer) !== Tracer.nativeTracer
488
+
489
+ return traced
490
+ ? body.pipe(
491
+ Effect.tapError(annotateStorageError),
492
+ Effect.withSpan('DoJournal.withWriteTransaction', { attributes: { operation } }),
493
+ )
494
+ : body
495
+ })
496
+
497
+ return <A, E extends { readonly _tag: string }>(effect: Effect.Effect<A, E>) =>
498
+ expected === undefined
499
+ ? transaction(effect)
500
+ : transaction(storageResult(effect, expected)).pipe(Effect.flatMap(Effect.fromResult))
501
+ }
502
+
503
+ const materialize = Effect.fnUntraced(function*(
504
+ threadId: string,
505
+ createdAt: string,
506
+ ): Effect.fn.Return<void, DoStorageCorruptionError | DoStorageError | DoValueBoundExceeded> {
507
+ if (threadId.length > MAX_IDENTIFIER_LENGTH) {
508
+ return yield* DoStorageError.make({
509
+ operation: 'materialize thread',
510
+ message: 'Thread identity exceeds the Durable Object storage bounds.',
511
+ })
512
+ }
513
+ // Refusals and idempotent materialization need no transaction. Recheck before writes.
514
+ const current = yield* getThread(threadId)
515
+
516
+ if (current.length === 1) {
517
+ return
518
+ }
519
+ yield* withWriteTransaction('materialize transaction')(
520
+ Effect.gen(function*() {
521
+ const existingRows = yield* getThread(threadId)
522
+
523
+ const existing = yield* decodeRows(
524
+ Schema.Array(ThreadRow),
525
+ 'effect_agent_threads',
526
+ threadId,
527
+ existingRows,
528
+ )
529
+
530
+ if (existing.length > 1) {
531
+ return yield* DoStorageCorruptionError.make({
532
+ table: 'effect_agent_threads',
533
+ rowKey: threadId,
534
+ message: 'A thread primary key returned more than one row.',
535
+ })
536
+ }
537
+ if (existing.length === 0) {
538
+ yield* sql`
539
+ INSERT INTO effect_agent_threads (
540
+ thread_id,
541
+ created_at,
542
+ tail_sequence,
543
+ work_version
544
+ ) VALUES (
545
+ ${threadId},
546
+ ${createdAt},
547
+ 0,
548
+ ${WORK_INDEX_VERSION}
549
+ ) ON CONFLICT(thread_id) DO UPDATE SET created_at=excluded.created_at
550
+ WHERE effect_agent_threads.created_at IS NULL
551
+ RETURNING *`.pipe(
552
+ threads.write,
553
+ Effect.mapError((error) => error._tag === 'SqlError' ? storageError('materialize thread')(error) : error),
554
+ )
555
+
556
+ if (lifecycle !== undefined) {
557
+ yield* sql`INSERT INTO effect_agent_lifecycle_cursors (thread_id, through_sequence)
558
+ VALUES (${threadId}, 0) RETURNING *`.pipe(
559
+ cursors.write,
560
+ Effect.mapError((error) =>
561
+ error._tag === 'SqlError'
562
+ ? storageError('initialize lifecycle source')(error)
563
+ : error
564
+ ),
565
+ )
566
+ }
567
+
568
+ return
569
+ }
570
+ }),
571
+ )
572
+ }, withStorageSpan('DoJournal.materialize'))
573
+
574
+ const getThread = Effect.fnUntraced(function*(threadId: string) {
575
+ return (yield* threads
576
+ .by('thread_id', threadId)
577
+ .pipe(
578
+ Effect.mapError((error) => error._tag === 'SqlError' ? storageError('read thread')(error) : error),
579
+ )).filter((row) => row.thread_id === threadId && row.created_at !== null)
580
+ })
581
+
582
+ const hasRecord = Effect.fnUntraced(function*(threadId: string, recordId: string) {
583
+ const thread = (yield* getThread(threadId))[0]
584
+ const prefix = recordCache.prefix(threadId, thread?.tail_sequence ?? 0)
585
+
586
+ if (prefix !== undefined) return prefix.some((row) => row.record_id === recordId)
587
+
588
+ const rows = yield* sql`SELECT record_id FROM effect_agent_canonical_records
589
+ WHERE thread_id = ${threadId} AND record_id = ${JSON.stringify(recordId)}`.pipe(
590
+ Effect.mapError(storageError('read canonical record identity')),
591
+ )
592
+
593
+ return rows.length > 0
594
+ })
595
+
596
+ const prepareAppend = Effect.fnUntraced(function*(request: RawAppendRequest) {
597
+ if (
598
+ request.threadId.length > MAX_IDENTIFIER_LENGTH ||
599
+ request.batchId.length > MAX_IDENTIFIER_LENGTH ||
600
+ request.executionWrites.some(
601
+ ({ update }) => update.checkpoint.progress.runId.length > MAX_IDENTIFIER_LENGTH,
602
+ ) ||
603
+ request.records.some((record) => record.recordId.length > MAX_IDENTIFIER_LENGTH)
604
+ ) {
605
+ return yield* DoStorageError.make({
606
+ operation: 'append canonical batch',
607
+ message: 'Canonical identifiers exceed the Durable Object storage bounds.',
608
+ })
609
+ }
610
+ // Archives store the full batch as one value, so their ceiling also bounds hot appends.
611
+ // The trusted append SPI pairs captured JSON with its exact UTF-8 width.
612
+ yield* checkValueBound('append canonical batch', request.batchJson, request.batchBytes)
613
+ for (const record of request.records) {
614
+ if (record.recordBytes > maxStoredValueBytes) {
615
+ return yield* DoValueBoundExceeded.make({
616
+ actualBytes: record.recordBytes,
617
+ maxBytes: maxStoredValueBytes,
618
+ operation: 'append canonical record',
619
+ })
620
+ }
621
+ }
622
+ for (const write of request.executionWrites) {
623
+ yield* checkValueBound('commit active execution', write.json, write.bytes)
624
+ }
625
+
626
+ const recordIds: Array<string> = request.records.map((record) => record.recordId)
627
+
628
+ if (new Set(recordIds).size !== recordIds.length) {
629
+ return yield* DoAppendConflict.make({
630
+ message: `Batch ${request.batchId} contains duplicate canonical record IDs.`,
631
+ reason: 'record-identity',
632
+ })
633
+ }
634
+
635
+ return request
636
+ })
637
+
638
+ // Replay and progress validation precede this body in the same owner transaction.
639
+ // A miss makes no native change; the ordinary path reuses any tentative batch.
640
+ // After advancing the frontier, failures must roll back rather than fall back.
641
+ const appendNativeBody = Effect.fnUntraced(function*(
642
+ request: RawAppendRequest,
643
+ first: CanonicalSequence,
644
+ last: CanonicalSequence,
645
+ batchInserted: boolean,
646
+ ) {
647
+ const db = nativeDb
648
+
649
+ // Effectful statement transformers and exported SQL spans retain the ordinary path.
650
+ const ordinaryStatement = yield* Effect.withFiber((fiber) =>
651
+ Effect.succeed(
652
+ fiber.getRef(Statement.CurrentTransformer) !== undefined ||
653
+ (fiber.getRef(References.TracerEnabled) &&
654
+ fiber.getRef(Tracer.Tracer) !== Tracer.nativeTracer),
655
+ )
656
+ )
657
+
658
+ if (ordinaryStatement) return false
659
+ if (
660
+ db === undefined ||
661
+ request.executionWrites.length !== 1 ||
662
+ request.executionWrites[0]?.update.retire ||
663
+ request.executionWrites[0]?.update.facts.length !== 0
664
+ ) {
665
+ return false
666
+ }
667
+
668
+ const workPlan = yield* work.prepareClosedPair(
669
+ request.threadId,
670
+ first,
671
+ last,
672
+ request.records.map((record) => record.canonical),
673
+ )
674
+
675
+ if (workPlan === undefined) return false
676
+
677
+ const native = yield* Effect.suspend(() => {
678
+ const query = (statement: Statement.Statement<object>, operation: string) =>
679
+ Result.try({
680
+ try: () => {
681
+ const [text, parameters] = statement.compile()
682
+
683
+ return db.exec(text, ...parameters).toArray()
684
+ },
685
+ catch: (cause) =>
686
+ storageError(operation)(
687
+ SqlError.SqlError.make({
688
+ reason: SqlError.classifySqliteError(cause, {
689
+ operation,
690
+ message: 'Native canonical statement failed',
691
+ }),
692
+ }),
693
+ ),
694
+ })
695
+
696
+ return Effect.fromResult(
697
+ Result.gen(function*() {
698
+ const captured = physical.cachedRecords(request.threadId, first, request.records)
699
+
700
+ if (captured === undefined) return undefined
701
+ const physicalRecords = yield* captured
702
+
703
+ if (!Arr.isReadonlyArrayNonEmpty(physicalRecords)) return undefined
704
+ const rows = yield* query(workPlan.advance, 'advance native work frontier')
705
+
706
+ // A zero-row predicate miss has made no change. A successful update
707
+ // must never fall back: every later refusal rolls back this transaction.
708
+ if (rows.length === 0) return undefined
709
+ const executionPlans = executions.prepareCommit(request)
710
+
711
+ if (!batchInserted) {
712
+ yield* query(
713
+ sql`INSERT INTO effect_agent_canonical_batches
714
+ (thread_id, batch_id, first_sequence, last_sequence, producer_id_json)
715
+ VALUES (${request.threadId}, ${
716
+ JSON.stringify(request.batchId)
717
+ }, ${first}, ${last}, ${request.producerIdJson})`,
718
+ 'insert canonical batch',
719
+ )
720
+ }
721
+
722
+ const inserted = yield* query(
723
+ sql`INSERT INTO effect_agent_canonical_records ${sql.insert(Arr.map(physicalRecords, (row) => row.columns))}
724
+ ON CONFLICT(thread_id, record_id) DO NOTHING RETURNING 1`,
725
+ 'insert canonical records',
726
+ )
727
+
728
+ if (inserted.length !== request.records.length) {
729
+ return yield* Result.fail(
730
+ DoAppendConflict.make({
731
+ message: 'A canonical record ID already exists.',
732
+ reason: 'record-identity',
733
+ }),
734
+ )
735
+ }
736
+ const memberships = physicalRecords.flatMap((row) => row.memberships)
737
+
738
+ for (const group of Arr.chunksOf(memberships, Math.floor(MAX_BOUND_PARAMETERS / 3))) {
739
+ yield* query(
740
+ sql`INSERT INTO effect_agent_record_runs ${sql.insert(group)}`,
741
+ 'index canonical Run membership',
742
+ )
743
+ }
744
+ for (const pointer of workPlan.pointers) {
745
+ yield* query(pointer, 'index canonical pointers')
746
+ }
747
+
748
+ for (const plan of executionPlans) {
749
+ const changed = yield* query(plan.statement, 'commit active execution')
750
+ const accepted = plan.accept(changed)
751
+
752
+ if (Result.isFailure(accepted)) {
753
+ return yield* Result.fail(
754
+ DoAppendConflict.make({
755
+ reason: accepted.failure.reason,
756
+ message: 'Active execution conflicts with the captured commit',
757
+ ...(accepted.failure.actualTailSequence === undefined
758
+ ? {}
759
+ : { actualTailSequence: accepted.failure.actualTailSequence }),
760
+ }),
761
+ )
762
+ }
763
+ }
764
+ for (let index = 0; index < request.records.length; index++) {
765
+ const record = request.records[index]!
766
+
767
+ recordCache.put(
768
+ RecordRow.make({
769
+ ...physicalRecords[index]!.columns,
770
+ thread_id: request.threadId,
771
+ record_id: record.recordId,
772
+ batch_id: request.batchId,
773
+ record_json: record.recordJson,
774
+ sequence: CanonicalSequence.make(first + index),
775
+ }),
776
+ record.recordBytes,
777
+ )
778
+ }
779
+
780
+ return rows
781
+ }),
782
+ )
783
+ })
784
+
785
+ if (native === undefined) return false
786
+ yield* threads.write(Effect.succeed(native))
787
+
788
+ return true
789
+ })
790
+
791
+ const appendPreparedBody = Effect.fnUntraced(function*(
792
+ request: RawAppendRequest,
793
+ ): Effect.fn.Return<AppendResult, AppendError> {
794
+ const threadRows = yield* getThread(request.threadId)
795
+
796
+ const thread = threadRows.length === 1 ? threadRows[0] : undefined
797
+
798
+ if (thread === undefined) {
799
+ return yield* DoStorageCorruptionError.make({
800
+ table: 'effect_agent_threads',
801
+ rowKey: request.threadId,
802
+ message: `Expected exactly one row but found ${threadRows.length}.`,
803
+ })
804
+ }
805
+
806
+ // A fresh canonical batch key and absence of an active receipt prove the two
807
+ // negative replay lookups in the same statement that retains the batch header.
808
+ // Keep the read-first path for stale/overflowed coordinates so exact retries
809
+ // still precede sequence and tail refusals.
810
+ const canInsert = request.records.length > 0 &&
811
+ request.expectedTailSequence === thread.tail_sequence &&
812
+ Number.isSafeInteger(thread.tail_sequence + request.records.length)
813
+
814
+ const inserted = canInsert
815
+ ? yield* sql`INSERT INTO effect_agent_canonical_batches
816
+ (thread_id, batch_id, first_sequence, last_sequence, producer_id_json)
817
+ SELECT ${request.threadId}, ${JSON.stringify(request.batchId)},
818
+ ${thread.tail_sequence + 1}, ${thread.tail_sequence + request.records.length},
819
+ ${request.producerIdJson}
820
+ WHERE NOT EXISTS (
821
+ SELECT 1 FROM effect_agent_executions
822
+ WHERE thread_id=${request.threadId} AND last_commit_id=${request.batchId}
823
+ )
824
+ ON CONFLICT(thread_id, batch_id) DO NOTHING RETURNING 1`.pipe(
825
+ Effect.mapError(storageError('insert canonical batch')),
826
+ )
827
+ : []
828
+
829
+ if (inserted.length === 0) {
830
+ const replay = yield* executionConflict(executions.replay(request))
831
+
832
+ if (replay !== undefined) return AppendResult.make(replay)
833
+
834
+ const prefix = recordCache.prefix(request.threadId, thread.tail_sequence)
835
+
836
+ const existing = prefix !== undefined && !prefix.some((row) => row.batch_id === request.batchId)
837
+ ? undefined
838
+ : yield* archives.replay(request.threadId, request.batchId)
839
+
840
+ if (existing !== undefined) {
841
+ if (existing.batch_json !== request.batchJson) {
842
+ return yield* DoAppendConflict.make({
843
+ message: `Batch ${request.batchId} already exists with different canonical content.`,
844
+ reason: 'batch-content',
845
+ })
846
+ }
847
+
848
+ return AppendResult.make({
849
+ firstSequence: existing.first_sequence,
850
+ lastSequence: existing.last_sequence,
851
+ replayed: true,
852
+ })
853
+ }
854
+ if (canInsert) {
855
+ return yield* DoStorageCorruptionError.make({
856
+ table: 'effect_agent_canonical_batches',
857
+ rowKey: request.threadId,
858
+ message: 'Batch insertion conflicted without a durable replay receipt.',
859
+ })
860
+ }
861
+ }
862
+
863
+ yield* executionConflict(executions.rejectSuperseded(request))
864
+
865
+ if (request.expectedTailSequence !== thread.tail_sequence) {
866
+ return yield* DoAppendConflict.make({
867
+ message: `Expected tail ${request.expectedTailSequence} ` + `but found ${thread.tail_sequence}.`,
868
+ reason: 'tail',
869
+ actualTailSequence: thread.tail_sequence,
870
+ })
871
+ }
872
+
873
+ const result = yield* Schema.decodeEffect(AppendResult)({
874
+ firstSequence: thread.tail_sequence + (request.records.length === 0 ? 0 : 1),
875
+ lastSequence: thread.tail_sequence + request.records.length,
876
+ replayed: false,
877
+ }).pipe(
878
+ Effect.mapError((error) =>
879
+ DoStorageError.make({
880
+ cause: error,
881
+ operation: 'append canonical batch',
882
+ message: error.message,
883
+ })
884
+ ),
885
+ )
886
+
887
+ const { firstSequence, lastSequence } = result
888
+
889
+ yield* executionConflict(executions.validate(request))
890
+
891
+ if (yield* appendNativeBody(request, firstSequence, lastSequence, inserted.length > 0)) {
892
+ yield* progress.committed('canonical').pipe(
893
+ Effect.catchCause((cause) =>
894
+ Effect.failCause(
895
+ Cause.map(cause, (error) =>
896
+ DoStorageError.make({
897
+ operation: 'enroll canonical progress',
898
+ message: error.message,
899
+ cause: error,
900
+ })),
901
+ )
902
+ ),
903
+ )
904
+
905
+ return result
906
+ }
907
+
908
+ if (request.records.length > 0 && inserted.length === 0) {
909
+ yield* sql`
910
+ INSERT INTO effect_agent_canonical_batches (
911
+ thread_id,
912
+ batch_id,
913
+ first_sequence,
914
+ last_sequence,
915
+ producer_id_json
916
+ ) VALUES (
917
+ ${request.threadId},
918
+ ${JSON.stringify(request.batchId)},
919
+ ${firstSequence},
920
+ ${lastSequence},
921
+ ${request.producerIdJson}
922
+ )
923
+ `.pipe(Effect.mapError(storageError('insert canonical batch')))
924
+ }
925
+ yield* failpoint('append:after-batch-insert')
926
+
927
+ const physicalRecords = yield* physical.records(
928
+ request.threadId,
929
+ firstSequence,
930
+ request.records,
931
+ )
932
+
933
+ const records = physicalRecords.map(({ columns, memberships }, index) => ({
934
+ record: request.records[index]!,
935
+ canonical: request.records[index]!.canonical,
936
+ row: columns,
937
+ memberships,
938
+ }))
939
+
940
+ // Captured scalar locators avoid parsing canonical JSON under the writer.
941
+ // Eighteen bound columns per row stay within workerd's statement limit.
942
+ for (const group of Arr.chunksOf(records, Math.floor(MAX_BOUND_PARAMETERS / 18))) {
943
+ const inserted = yield* sql`INSERT INTO effect_agent_canonical_records ${
944
+ sql.insert(Arr.map(group, ({ row }) => row))
945
+ }
946
+ ON CONFLICT(thread_id, record_id) DO NOTHING RETURNING 1`.pipe(
947
+ Effect.mapError(storageError('insert canonical records')),
948
+ )
949
+
950
+ if (inserted.length !== group.length) {
951
+ return yield* DoAppendConflict.make({
952
+ message: 'A canonical record ID already exists.',
953
+ reason: 'record-identity',
954
+ })
955
+ }
956
+
957
+ const memberships = group.flatMap(({ memberships }) => memberships)
958
+
959
+ for (const members of Arr.chunksOf(memberships, Math.floor(MAX_BOUND_PARAMETERS / 3))) {
960
+ yield* sql`INSERT INTO effect_agent_record_runs ${sql.insert(members)}`.pipe(
961
+ Effect.mapError(storageError('index canonical Run membership')),
962
+ )
963
+ }
964
+ for (const { row, record } of group) {
965
+ recordCache.put(
966
+ RecordRow.make({
967
+ ...row,
968
+ thread_id: request.threadId,
969
+ record_id: record.recordId,
970
+ batch_id: request.batchId,
971
+ record_json: record.recordJson,
972
+ sequence: yield* Schema.decodeEffect(CanonicalSequence)(row.sequence).pipe(
973
+ Effect.orDie,
974
+ ),
975
+ }),
976
+ record.recordBytes,
977
+ )
978
+ yield* failpoint('append:after-record-insert')
979
+ }
980
+ }
981
+
982
+ if (request.records.length > 0) {
983
+ const workFields = yield* work
984
+ .apply(
985
+ request.threadId,
986
+ firstSequence,
987
+ request.records.map((record) => record.canonical),
988
+ )
989
+ .pipe(Effect.mapError(workFailure))
990
+
991
+ yield* sql`UPDATE effect_agent_threads SET ${sql.update({ tail_sequence: lastSequence, ...workFields })}
992
+ WHERE thread_id=${request.threadId} RETURNING *`.pipe(
993
+ threads.write,
994
+ Effect.mapError((error) => error._tag === 'SqlError' ? storageError('advance thread tail')(error) : error),
995
+ )
996
+ }
997
+ yield* executionConflict(executions.commit(request, result))
998
+ if (request.executionWrites.length > 0) yield* failpoint('append:after-record-insert')
999
+ if (
1000
+ lifecycle !== undefined &&
1001
+ request.executionWrites.some(({ update }) => update.facts.some(({ payload }) => payload._tag === 'RunStarted'))
1002
+ ) {
1003
+ yield* flushCanonical(request.threadId).pipe(
1004
+ Effect.provideService(SqlLifecycleRetainer, { retainMany: lifecycle.retainMany }),
1005
+ Effect.mapError((cause) =>
1006
+ DoStorageError.make({
1007
+ operation: 'retain lifecycle start prefix',
1008
+ message: 'Lifecycle start intent could not be retained',
1009
+ cause,
1010
+ })
1011
+ ),
1012
+ )
1013
+ }
1014
+ for (const { update } of request.executionWrites) {
1015
+ for (const fact of update.facts) {
1016
+ if (
1017
+ lifecycle !== undefined &&
1018
+ Schema.is(Schema.toType(LifecyclePublicationFact))(fact.payload)
1019
+ ) {
1020
+ yield* lifecycle
1021
+ .retain({
1022
+ id: JSON.stringify([request.threadId, 'record', fact.recordId]),
1023
+ ownerThreadId: request.threadId,
1024
+ canonicalSequence: lastSequence,
1025
+ createdAt: fact.createdAt,
1026
+ fact: fact.payload,
1027
+ })
1028
+ .pipe(
1029
+ Effect.mapError((cause) =>
1030
+ DoStorageError.make({
1031
+ operation: 'retain operational lifecycle',
1032
+ message: cause.message,
1033
+ cause,
1034
+ })
1035
+ ),
1036
+ )
1037
+ }
1038
+ }
1039
+ }
1040
+ yield* failpoint('append:after-tail-update')
1041
+
1042
+ // Retain one start prefix atomically with its canonical proof, before model/tool
1043
+ // execution. Later facts stay journal-backed until the settlement publication wave.
1044
+ if (
1045
+ lifecycle !== undefined &&
1046
+ records.some(
1047
+ ({ canonical: { payload } }) => payload._tag === 'RunStarted' || payload._tag === 'SubagentStarted',
1048
+ )
1049
+ ) {
1050
+ yield* flushCanonical(request.threadId).pipe(
1051
+ Effect.provideService(SqlLifecycleRetainer, { retainMany: lifecycle.retainMany }),
1052
+ Effect.mapError((cause) =>
1053
+ DoStorageError.make({
1054
+ operation: 'retain lifecycle start prefix',
1055
+ message: 'Lifecycle start intent could not be retained',
1056
+ cause,
1057
+ })
1058
+ ),
1059
+ )
1060
+ }
1061
+
1062
+ yield* progress.committed('canonical').pipe(
1063
+ Effect.catchCause((cause) =>
1064
+ Effect.failCause(
1065
+ Cause.map(cause, (error) =>
1066
+ DoStorageError.make({
1067
+ operation: 'enroll canonical progress',
1068
+ message: error.message,
1069
+ cause: error,
1070
+ })),
1071
+ )
1072
+ ),
1073
+ )
1074
+
1075
+ return result
1076
+ })
1077
+
1078
+ const appendPrepared = (request: RawAppendRequest) => {
1079
+ const appended = appendPreparedBody(request)
1080
+
1081
+ // All paths, including native fast appends and exact replays, remain inside the
1082
+ // caller's source transaction. The configured writer never opens another one.
1083
+ return request.deliveries.length === 0
1084
+ ? appended
1085
+ : appended.pipe(Effect.tap(() => publishDeliveries(request.deliveries)))
1086
+ }
1087
+
1088
+ const append = Effect.fnUntraced(
1089
+ function*(
1090
+ request: RawAppendRequest,
1091
+ observed: ThreadRow,
1092
+ ): Effect.fn.Return<AppendResult, AppendError> {
1093
+ yield* prepareAppend(request)
1094
+ // The facade already read this tail. Reject a known stale writer without opening a
1095
+ // transaction; a matching tail is still checked atomically below. Replays precede tail
1096
+ // conflicts, preserving retry identity even after the log has advanced.
1097
+ if (request.records.length > 0 && request.expectedTailSequence !== observed.tail_sequence) {
1098
+ const batches = yield* sql`
1099
+ SELECT batch_id FROM effect_agent_canonical_batches
1100
+ WHERE thread_id = ${request.threadId} AND batch_id = ${JSON.stringify(request.batchId)}
1101
+ UNION ALL SELECT last_commit_id FROM effect_agent_executions
1102
+ WHERE thread_id = ${request.threadId} AND last_commit_id = ${request.batchId}
1103
+ LIMIT 1
1104
+ `.pipe(Effect.mapError(storageError('preflight append replay')))
1105
+
1106
+ // A possible replay still checks exact content in the transaction.
1107
+ if (batches.length === 0) {
1108
+ return yield* DoAppendConflict.make({
1109
+ reason: 'tail',
1110
+ message: 'The canonical tail has advanced.',
1111
+ actualTailSequence: observed.tail_sequence,
1112
+ })
1113
+ }
1114
+ }
1115
+
1116
+ // Receipt arbitration may have tentatively inserted a batch. Even typed
1117
+ // contention must roll back before leaving the owner mutation gate.
1118
+ return yield* withWriteTransaction('append transaction')(appendPrepared(request))
1119
+ },
1120
+ withStorageSpan('DoJournal.append', isAppendContention),
1121
+ )
1122
+
1123
+ const read = Effect.fnUntraced(function*(request: RawReadRequest) {
1124
+ const thread = (yield* getThread(request.threadId))[0]
1125
+
1126
+ const through = Math.min(
1127
+ thread?.tail_sequence ?? 0,
1128
+ request.fromSequenceExclusive + request.limit,
1129
+ )
1130
+
1131
+ const cached: Array<RecordRow> = []
1132
+
1133
+ for (let sequence = request.fromSequenceExclusive + 1; sequence <= through; sequence++) {
1134
+ const record = recordCache.get(request.threadId, sequence)
1135
+
1136
+ if (record === undefined) break
1137
+ cached.push(record)
1138
+ }
1139
+ if (cached.length === Math.max(0, through - request.fromSequenceExclusive)) {
1140
+ return { count: cached.length, records: Stream.fromIterable(cached) }
1141
+ }
1142
+
1143
+ // Capture membership without retaining payloads. Append-only sequences keep each later
1144
+ // payload query inside this snapshot, even when new records arrive during consumption.
1145
+ const planRows = yield* sql<Record<string, unknown>>`
1146
+ SELECT
1147
+ sequence,
1148
+ length(CAST(${recordJson} AS BLOB)) AS record_json_bytes
1149
+ FROM effect_agent_canonical_records
1150
+ WHERE thread_id = ${request.threadId}
1151
+ AND sequence > ${request.fromSequenceExclusive}
1152
+ ORDER BY sequence
1153
+ LIMIT ${request.limit}
1154
+ `.pipe(Effect.mapError(storageError('read canonical records')))
1155
+
1156
+ const plan = yield* decodeRows(
1157
+ Schema.Array(ReadPlanRow),
1158
+ 'effect_agent_canonical_records',
1159
+ `${request.threadId}>${request.fromSequenceExclusive}`,
1160
+ planRows,
1161
+ 'ReadPlanRow',
1162
+ )
1163
+
1164
+ const mismatch = () =>
1165
+ DoStorageCorruptionError.make({
1166
+ table: 'effect_agent_canonical_records',
1167
+ rowKey: `${request.threadId}>${request.fromSequenceExclusive}`,
1168
+ message: 'Canonical read membership, sequence, or payload size changed from its read plan.',
1169
+ })
1170
+
1171
+ if (plan.length > request.limit) return yield* mismatch()
1172
+
1173
+ const pages: Array<ReadPage> = []
1174
+ let page: ReadPage | undefined
1175
+ let pageBytes = 0
1176
+ let previousSequence = request.fromSequenceExclusive
1177
+
1178
+ for (const row of plan) {
1179
+ if (row.sequence !== previousSequence + 1) return yield* mismatch()
1180
+ previousSequence = row.sequence
1181
+ if (page === undefined || pageBytes + row.record_json_bytes > MAX_READ_PAGE_JSON_BYTES) {
1182
+ page = [row]
1183
+ pages.push(page)
1184
+ pageBytes = row.record_json_bytes
1185
+ } else {
1186
+ page.push(row)
1187
+ pageBytes += row.record_json_bytes
1188
+ }
1189
+ }
1190
+
1191
+ const readPage = Effect.fnUntraced(function*(page: ReadPage) {
1192
+ const rows = yield* sql<Record<string, unknown>>`
1193
+ SELECT thread_id, sequence, record_id, ${recordBatchId(sql)} AS batch_id, ${recordJson} AS record_json
1194
+ FROM effect_agent_canonical_records
1195
+ WHERE thread_id = ${request.threadId}
1196
+ AND sequence >= ${page[0].sequence}
1197
+ AND sequence <= ${page[page.length - 1].sequence}
1198
+ ORDER BY sequence
1199
+ `.pipe(Effect.mapError(storageError('read canonical records')))
1200
+
1201
+ const decoded = yield* decodeRows(
1202
+ Schema.Array(RecordRow),
1203
+ 'effect_agent_canonical_records',
1204
+ `${request.threadId}/${page[0].sequence}`,
1205
+ rows,
1206
+ 'RecordRow',
1207
+ )
1208
+
1209
+ if (
1210
+ decoded.length !== page.length ||
1211
+ decoded.some(
1212
+ (row, index) =>
1213
+ row.thread_id !== request.threadId ||
1214
+ row.sequence !== page[index].sequence ||
1215
+ storedTextBytes(row.record_json) !== page[index].record_json_bytes,
1216
+ )
1217
+ ) {
1218
+ return yield* mismatch()
1219
+ }
1220
+
1221
+ for (const row of decoded) recordCache.put(row)
1222
+
1223
+ return decoded
1224
+ })
1225
+
1226
+ return {
1227
+ count: plan.length,
1228
+ records: Stream.fromIterable(pages).pipe(
1229
+ Stream.flatMap((page) => Stream.fromIterableEffect(state.read(readPage(page)))),
1230
+ ),
1231
+ }
1232
+ })
1233
+
1234
+ const sourceFailure = (cause: unknown) => LifecyclePublicationError.make({ reason: 'unavailable', cause })
1235
+
1236
+ const sourceThreads = Effect.fnUntraced(function*() {
1237
+ const all = yield* threads.matching(
1238
+ 'lifecycle-owners',
1239
+ (row) => row.created_at !== null,
1240
+ sql`SELECT * FROM effect_agent_threads WHERE created_at IS NOT NULL LIMIT 129`,
1241
+ 128,
1242
+ )
1243
+
1244
+ if (all.length <= 128) return all
1245
+
1246
+ // Large custom hosts hydrate only owners whose journal has an unmaterialized suffix.
1247
+ return yield* Schema.decodeUnknownEffect(Schema.Array(ThreadRow))(
1248
+ yield* sql`SELECT t.* FROM effect_agent_threads t LEFT JOIN effect_agent_lifecycle_cursors c ON c.thread_id=t.thread_id
1249
+ WHERE t.created_at IS NOT NULL AND (c.thread_id IS NULL OR t.tail_sequence > c.through_sequence) ORDER BY t.thread_id LIMIT 128`,
1250
+ )
1251
+ })
1252
+
1253
+ const initializeLifecycleSource = Effect.fnUntraced(function*() {
1254
+ if (initializedLifecycleSources.has(state)) return
1255
+ yield* state
1256
+ .transaction(
1257
+ Effect.gen(function*() {
1258
+ const existing = yield* sql`SELECT name FROM sqlite_master WHERE name='effect_agent_lifecycle_cursors'`
1259
+
1260
+ if (existing.length === 0) {
1261
+ yield* sql`CREATE TABLE effect_agent_lifecycle_cursors (
1262
+ thread_id TEXT PRIMARY KEY, through_sequence INTEGER NOT NULL
1263
+ )`
1264
+ // Existing inline writers already retained their facts. Enabling publication on an
1265
+ // old store starts here too; it does not publish historical facts retroactively.
1266
+ }
1267
+ // New Threads created with publication disabled have no cursor. Never advance
1268
+ // existing cursors: they can owe intent from an interrupted Attempt.
1269
+ yield* sql`INSERT INTO effect_agent_lifecycle_cursors(thread_id, through_sequence)
1270
+ SELECT thread_id, tail_sequence FROM effect_agent_threads WHERE created_at IS NOT NULL
1271
+ ON CONFLICT(thread_id) DO NOTHING`
1272
+ yield* sourceThreads()
1273
+ }),
1274
+ )
1275
+ .pipe(
1276
+ Effect.provideService(SqlClient.SqlClient, sql),
1277
+ Effect.mapError((cause) =>
1278
+ DoStorageError.make({
1279
+ operation: 'initialize lifecycle source',
1280
+ message: 'Lifecycle source cursor unavailable',
1281
+ cause,
1282
+ })
1283
+ ),
1284
+ )
1285
+ initializedLifecycleSources.add(state)
1286
+ })
1287
+
1288
+ /** The journal is durable intent; only the bounded publication wave materializes a write set. */
1289
+ const flushCanonical = Effect.fnUntraced(function*(threadId: string, maxRecords = Infinity) {
1290
+ const { retainMany } = yield* SqlLifecycleRetainer
1291
+ const thread = (yield* getThread(threadId))[0]
1292
+
1293
+ if (thread === undefined) return
1294
+ const cursor = (yield* cursors.by('thread_id', threadId))[0]
1295
+
1296
+ if (cursor === undefined || cursor.through_sequence > thread.tail_sequence) {
1297
+ return yield* LifecyclePublicationError.make({ reason: 'corrupt' })
1298
+ }
1299
+ let through = cursor.through_sequence
1300
+ const bound = Math.min(thread.tail_sequence, through + maxRecords)
1301
+
1302
+ while (through < bound) {
1303
+ const page = yield* read(
1304
+ RawReadRequest.make({
1305
+ threadId,
1306
+ fromSequenceExclusive: through,
1307
+ limit: Math.min(128, bound - through),
1308
+ }),
1309
+ )
1310
+
1311
+ const facts: Array<Parameters<SqlLifecycleRetainMany>[0][number]> = []
1312
+ let bytes = 0
1313
+
1314
+ yield* Stream.runForEach(page.records, (row) =>
1315
+ Effect.gen(function*() {
1316
+ const record = yield* Schema.decodeEffect(Schema.fromJsonString(CanonicalRecord))(
1317
+ row.record_json,
1318
+ )
1319
+
1320
+ if (record.recordId !== row.record_id || row.sequence !== through + 1) {
1321
+ return yield* LifecyclePublicationError.make({ reason: 'corrupt' })
1322
+ }
1323
+ if (Schema.is(Schema.toType(LifecyclePublicationFact))(record.payload)) {
1324
+ if (
1325
+ bytes + storedTextBytes(row.record_json) > MAX_READ_PAGE_JSON_BYTES &&
1326
+ facts.length > 0
1327
+ ) {
1328
+ yield* retainMany(facts)
1329
+ facts.length = 0
1330
+ bytes = 0
1331
+ }
1332
+ facts.push({
1333
+ id: JSON.stringify([threadId, 'record', record.recordId]),
1334
+ ownerThreadId: yield* Schema.decodeEffect(ThreadId)(threadId),
1335
+ canonicalSequence: row.sequence,
1336
+ createdAt: record.createdAt,
1337
+ fact: record.payload,
1338
+ })
1339
+ bytes += storedTextBytes(row.record_json)
1340
+ }
1341
+ through = row.sequence
1342
+ }))
1343
+ if (page.count === 0) return yield* LifecyclePublicationError.make({ reason: 'corrupt' })
1344
+ yield* retainMany(facts)
1345
+ yield* sql`UPDATE effect_agent_lifecycle_cursors SET through_sequence=${through} WHERE thread_id=${threadId} RETURNING *`
1346
+ .pipe(
1347
+ cursors.write,
1348
+ )
1349
+ }
1350
+ }, Effect.mapError(sourceFailure))
1351
+
1352
+ const flushPublications = Effect.fnUntraced(function*() {
1353
+ let owners = 0
1354
+
1355
+ for (const thread of yield* sourceThreads()) {
1356
+ const cursor = (yield* cursors.by('thread_id', thread.thread_id))[0]
1357
+
1358
+ if (cursor !== undefined && cursor.through_sequence === thread.tail_sequence) continue
1359
+ yield* flushCanonical(thread.thread_id, 1024)
1360
+ if (++owners === 4) break
1361
+ }
1362
+ }, Effect.mapError(sourceFailure))
1363
+
1364
+ const sourcePending = Effect.gen(function*() {
1365
+ for (const thread of yield* sourceThreads()) {
1366
+ const cursor = (yield* cursors.by('thread_id', thread.thread_id))[0]
1367
+
1368
+ if (cursor === undefined || cursor.through_sequence > thread.tail_sequence) {
1369
+ return yield* LifecyclePublicationError.make({ reason: 'corrupt' })
1370
+ }
1371
+ if (cursor.through_sequence < thread.tail_sequence) return true
1372
+ }
1373
+
1374
+ return false
1375
+ }).pipe(Effect.mapError(sourceFailure))
1376
+
1377
+ const ownedLifecycle = lifecycle === undefined
1378
+ ? undefined
1379
+ : {
1380
+ ...lifecycle,
1381
+ storage: {
1382
+ ...lifecycle.storage,
1383
+ retainedPendingDeadline: lifecycle.storage.pendingDeadline,
1384
+ pendingDeadline: state.read(
1385
+ Effect.gen(function*() {
1386
+ const deadline = yield* lifecycle.storage.pendingDeadline
1387
+
1388
+ if (!(yield* sourcePending)) return deadline
1389
+ const now = yield* Clock.currentTimeMillis
1390
+
1391
+ return Option.some(Option.isSome(deadline) ? Math.min(now, deadline.value) : now)
1392
+ }),
1393
+ ),
1394
+ },
1395
+ }
1396
+
1397
+ return {
1398
+ archives: archives.storage,
1399
+ archiveRanges: archives,
1400
+ work,
1401
+ state,
1402
+ owner,
1403
+ threads,
1404
+ lifecycle: ownedLifecycle,
1405
+ initializeLifecycleSource,
1406
+ flushCanonical,
1407
+ flushPublications,
1408
+ append,
1409
+ prepareAppend,
1410
+ appendPrepared,
1411
+ checkCommitIntent: (request: RawAppendRequest) => executionConflict(executions.checkCommitIntent(request)),
1412
+ readExecution: executions.read,
1413
+ checkValueBound,
1414
+ getThread,
1415
+ hasRecord,
1416
+ materialize,
1417
+ read: (request: RawReadRequest) => state.read(read(request)),
1418
+ withWriteTransaction,
1419
+ } as const
1420
+ })
1421
+
1422
+ export type DoJournal = Effect.Success<ReturnType<typeof makeJournal>>
1423
+
1424
+ const InitializedDoJournal = Context.Reference<DoJournal | undefined>(
1425
+ '@effect-agent/storage-cloudflare/InitializedDoJournal',
1426
+ { defaultValue: () => undefined },
1427
+ )
1428
+
1429
+ /** Build once in the common owner, SQL, configuration, failpoint and lifecycle context. */
1430
+ export const initializedDoJournalLayer = Layer.effect(InitializedDoJournal)(
1431
+ Effect.gen(function*() {
1432
+ const sql = yield* SqlClient.SqlClient
1433
+ const config = yield* DoStorageConfig
1434
+ const failpoint = yield* DoStorageFailpoint
1435
+
1436
+ return yield* ensureCurrentStorage(sql, failpoint.hit, config.maxStoredValueBytes)
1437
+ }),
1438
+ )
1439
+
1440
+ export const initializeDoJournal = (
1441
+ sql: SqlClient.SqlClient,
1442
+ failpoint: DoJournalFailpoint,
1443
+ maxStoredValueBytes: number,
1444
+ ) =>
1445
+ Effect.filterOrElse(
1446
+ InitializedDoJournal,
1447
+ Predicate.isNotUndefined,
1448
+ () => ensureCurrentStorage(sql, failpoint, maxStoredValueBytes),
1449
+ )