@effect-agent/storage-cloudflare 0.1.0-beta.9 → 0.1.0-beta.90

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 (73) hide show
  1. package/dist/DoMemoryStore.d.mts +29 -0
  2. package/dist/DoMemoryStore.mjs +55 -0
  3. package/dist/DoMemoryStore.mjs.map +1 -0
  4. package/dist/DoMessageDeliveryStore.d.mts +17 -0
  5. package/dist/DoMessageDeliveryStore.mjs +32 -0
  6. package/dist/DoMessageDeliveryStore.mjs.map +1 -0
  7. package/dist/DoScheduleStore.d.mts +36 -0
  8. package/dist/DoScheduleStore.mjs +388 -0
  9. package/dist/DoScheduleStore.mjs.map +1 -0
  10. package/dist/DoStorageConfig.d.mts +45 -0
  11. package/dist/DoStorageConfig.mjs +52 -0
  12. package/dist/DoStorageConfig.mjs.map +1 -0
  13. package/dist/DoStorageError-Cmhvl4TQ.d.mts +98 -0
  14. package/dist/DoStorageError.d.mts +2 -0
  15. package/dist/DoStorageError.mjs +164 -0
  16. package/dist/DoStorageError.mjs.map +1 -0
  17. package/dist/DoStorageFailpoint.d.mts +17 -0
  18. package/dist/DoStorageFailpoint.mjs +14 -0
  19. package/dist/DoStorageFailpoint.mjs.map +1 -0
  20. package/dist/DoStorageFailpointTesting.d.mts +34 -0
  21. package/dist/DoStorageFailpointTesting.mjs +35 -0
  22. package/dist/DoStorageFailpointTesting.mjs.map +1 -0
  23. package/dist/DoStorageVersion-x5OOurvZ.d.mts +12 -0
  24. package/dist/DoStorageVersion.d.mts +2 -0
  25. package/dist/DoStorageVersion.mjs +8 -0
  26. package/dist/DoStorageVersion.mjs.map +1 -0
  27. package/dist/DoSubmissionLedger.d.mts +23 -0
  28. package/dist/DoSubmissionLedger.mjs +1849 -0
  29. package/dist/DoSubmissionLedger.mjs.map +1 -0
  30. package/dist/DoSubscriptionStore.d.mts +25 -0
  31. package/dist/DoSubscriptionStore.mjs +183 -0
  32. package/dist/DoSubscriptionStore.mjs.map +1 -0
  33. package/dist/DoThreadStore.d.mts +59 -0
  34. package/dist/DoThreadStore.mjs +465 -0
  35. package/dist/DoThreadStore.mjs.map +1 -0
  36. package/dist/MemoryProtocol.d.mts +38160 -0
  37. package/dist/MemoryProtocol.mjs +219 -0
  38. package/dist/MemoryProtocol.mjs.map +1 -0
  39. package/dist/PortProtocol.d.mts +3804 -0
  40. package/dist/PortProtocol.mjs +176 -0
  41. package/dist/PortProtocol.mjs.map +1 -0
  42. package/dist/PortRouting.d.mts +83 -0
  43. package/dist/PortRouting.mjs +410 -0
  44. package/dist/PortRouting.mjs.map +1 -0
  45. package/dist/do-journal-dJ01KSKf.mjs +991 -0
  46. package/dist/do-journal-dJ01KSKf.mjs.map +1 -0
  47. package/dist/index.d.mts +14 -1525
  48. package/dist/index.mjs +14 -3695
  49. package/dist/migrations-Ba_kOrSx.mjs +287 -0
  50. package/dist/migrations-Ba_kOrSx.mjs.map +1 -0
  51. package/dist/rolldown-runtime-D7D4PA-g.mjs +13 -0
  52. package/package.json +1 -45
  53. package/src/DoMemoryStore.ts +56 -0
  54. package/src/DoMessageDeliveryStore.ts +53 -0
  55. package/src/DoScheduleStore.ts +622 -0
  56. package/src/{errors.ts → DoStorageError.ts} +10 -3
  57. package/src/DoStorageFailpoint.ts +20 -0
  58. package/src/{do-storage-failpoint.ts → DoStorageFailpointTesting.ts} +5 -18
  59. package/src/DoStorageVersion.ts +2 -0
  60. package/src/{do-ledger.ts → DoSubmissionLedger.ts} +924 -225
  61. package/src/DoSubscriptionStore.ts +329 -0
  62. package/src/DoThreadStore.ts +1012 -0
  63. package/src/MemoryProtocol.ts +351 -0
  64. package/src/{port-protocol.ts → PortProtocol.ts} +45 -38
  65. package/src/{routing.ts → PortRouting.ts} +292 -264
  66. package/src/index.ts +13 -32
  67. package/src/{do-journal.ts → internal/do-journal.ts} +718 -234
  68. package/src/internal/message-delivery-schema.ts +24 -0
  69. package/src/{migrations.ts → internal/migrations.ts} +51 -35
  70. package/src/internal/recovery-checkpoint-schema.ts +17 -0
  71. package/dist/index.mjs.map +0 -1
  72. package/src/do-conversation-store.ts +0 -850
  73. /package/src/{do-storage-config.ts → DoStorageConfig.ts} +0 -0
@@ -0,0 +1,991 @@
1
+ import { DoAppendConflict, DoCheckpointConflict, DoFenceRejected, DoStorageCompatibilityError, DoStorageCorruptionError, DoStorageError, DoValueBoundExceeded } from "./DoStorageError.mjs";
2
+ import { a as createMessageDeliveryTables, i as createRecoveryCheckpointTable, n as createNonterminalIndex, r as doMigrations } from "./migrations-Ba_kOrSx.mjs";
3
+ import { Effect, Schema, Stream } from "effect";
4
+ import * as SqlClient from "effect/unstable/sql/SqlClient";
5
+ import { SqliteMigrator } from "@effect/sql-sqlite-do";
6
+ import { EMPTY_TAIL_DIGEST } from "effect-agent/digest";
7
+ import { CanonicalSequence, ProducerEpoch } from "effect-agent/records";
8
+ import { checkV2ThreadLayout } from "effect-agent/sql-storage-v2-upgrade";
9
+ import { CheckpointRejected, FenceRejected, MAX_THREAD_EXPORT_RECORDS, ThreadNotMaterialized } from "effect-agent/thread-store";
10
+ import { SqlError } from "effect/unstable/sql/SqlError";
11
+ //#region src/internal/do-journal.ts
12
+ /**
13
+ * Static schema ceiling for stored text columns. Writes are bounded in BYTES by the
14
+ * configured `maxStoredValueBytes` (always ≤ 2,000,000); UTF-8 byte length is never smaller
15
+ * than UTF-16 string length, so any value that passed the byte bound also passes this
16
+ * decode-side character ceiling.
17
+ */
18
+ const BoundedStoredText = Schema.String.check(Schema.isMaxLength(2e6));
19
+ const BoundedIdentifier = Schema.NonEmptyString.check(Schema.isMaxLength(1024));
20
+ const MAX_RECORDS_PER_THREAD = MAX_THREAD_EXPORT_RECORDS;
21
+ const ZERO_SEQUENCE = Schema.decodeSync(CanonicalSequence)(0);
22
+ const MAX_IDENTIFIER_LENGTH = 1024;
23
+ const MAX_READ_PAGE_JSON_BYTES = 4194304;
24
+ const isSqlError = Schema.is(SqlError);
25
+ const storedTextBytes = (value) => new TextEncoder().encode(value).byteLength;
26
+ const chunked = (values, size) => {
27
+ const chunks = [];
28
+ for (let index = 0; index < values.length; index += size) chunks.push(values.slice(index, index + size));
29
+ return chunks;
30
+ };
31
+ var DoMetaRow = class extends Schema.Class("DoMetaRow")({ value: Schema.NonEmptyString.check(Schema.isMaxLength(128)) }) {};
32
+ var DoNameRow = class extends Schema.Class("DoNameRow")({ name: BoundedIdentifier }) {};
33
+ var ThreadRow = class extends Schema.Class("ThreadRow")({
34
+ thread_id: BoundedIdentifier,
35
+ created_at: Schema.NonEmptyString.check(Schema.isMaxLength(128)),
36
+ producer_epoch: ProducerEpoch,
37
+ tail_digest: BoundedStoredText,
38
+ tail_sequence: CanonicalSequence
39
+ }) {};
40
+ var BatchRow = class extends Schema.Class("BatchRow")({
41
+ batch_digest: BoundedStoredText,
42
+ batch_id: BoundedIdentifier,
43
+ batch_json: BoundedStoredText,
44
+ thread_id: BoundedIdentifier,
45
+ first_sequence: CanonicalSequence,
46
+ last_sequence: CanonicalSequence,
47
+ tail_digest: BoundedStoredText
48
+ }) {};
49
+ var RecordRow = class extends Schema.Class("RecordRow")({
50
+ batch_id: BoundedIdentifier,
51
+ thread_id: BoundedIdentifier,
52
+ record_id: BoundedIdentifier,
53
+ record_json: BoundedStoredText,
54
+ sequence: CanonicalSequence
55
+ }) {};
56
+ const ReadPlanRow = Schema.Struct({
57
+ sequence: CanonicalSequence,
58
+ record_json_bytes: Schema.Natural.check(Schema.isLessThanOrEqualTo(MAX_READ_PAGE_JSON_BYTES))
59
+ });
60
+ var CheckpointRow = class extends Schema.Class("CheckpointRow")({
61
+ checkpoint_json: BoundedStoredText,
62
+ thread_id: BoundedIdentifier,
63
+ tail_digest: BoundedStoredText,
64
+ through_sequence: CanonicalSequence
65
+ }) {};
66
+ var RawRecord = class extends Schema.Class("@effect-agent/storage-cloudflare/RawRecord")({
67
+ recordId: BoundedIdentifier,
68
+ recordJson: BoundedStoredText
69
+ }) {};
70
+ var RawAppendRequest = class extends Schema.Class("@effect-agent/storage-cloudflare/RawAppendRequest")({
71
+ batchDigest: BoundedStoredText,
72
+ batchId: BoundedIdentifier,
73
+ batchJson: BoundedStoredText,
74
+ threadId: BoundedIdentifier,
75
+ expectedTailDigest: BoundedStoredText,
76
+ expectedTailSequence: CanonicalSequence,
77
+ producerEpoch: ProducerEpoch,
78
+ records: Schema.NonEmptyArray(RawRecord).check(Schema.isMaxLength(256)),
79
+ tailDigest: BoundedStoredText
80
+ }) {};
81
+ var RawAppendResult = class extends Schema.Class("@effect-agent/storage-cloudflare/RawAppendResult")({
82
+ firstSequence: CanonicalSequence,
83
+ lastSequence: CanonicalSequence,
84
+ replayed: Schema.Boolean,
85
+ tailDigest: BoundedStoredText
86
+ }) {};
87
+ var RawReadRequest = class extends Schema.Class("@effect-agent/storage-cloudflare/RawReadRequest")({
88
+ threadId: BoundedIdentifier,
89
+ fromSequenceExclusive: CanonicalSequence,
90
+ limit: Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(1024))
91
+ }) {};
92
+ var RawCheckpoint = class extends Schema.Class("@effect-agent/storage-cloudflare/RawCheckpoint")({
93
+ checkpointJson: BoundedStoredText,
94
+ threadId: BoundedIdentifier,
95
+ tailDigest: BoundedStoredText,
96
+ throughSequence: CanonicalSequence
97
+ }) {};
98
+ var RawThreadExport = class extends Schema.Class("@effect-agent/storage-cloudflare/RawThreadExport")({
99
+ thread: ThreadRow,
100
+ records: Schema.Array(RecordRow)
101
+ }) {};
102
+ const noFailpoint = () => Effect.void;
103
+ const storageError = (operation) => (error) => DoStorageError.make({
104
+ cause: error,
105
+ operation,
106
+ message: error.message
107
+ });
108
+ /** Decode raw Durable Object SQLite rows against a Schema, reporting failures as typed corruption. */
109
+ const decodeRows = Effect.fn((schema, table, rowKey, rows) => Schema.decodeUnknownEffect(schema)(rows).pipe(Effect.mapError((error) => DoStorageCorruptionError.make({
110
+ table,
111
+ rowKey,
112
+ message: String(error)
113
+ }))));
114
+ /** Decode exactly one raw row against a Schema, reporting failures as typed corruption. */
115
+ const decodeSingleRow = Effect.fn((schema, table, rowKey, rows) => decodeRows(schema, table, rowKey, rows).pipe(Effect.flatMap((decoded) => decoded.length === 1 ? Effect.succeed(decoded[0]) : Effect.fail(DoStorageCorruptionError.make({
116
+ table,
117
+ rowKey,
118
+ message: `Expected exactly one row but found ${decoded.length}.`
119
+ })))));
120
+ /** Column inventory of the supported v3 predecessor, independent of physical column order. */
121
+ const predecessorColumns = {
122
+ effect_agent_threads: [
123
+ "thread_id",
124
+ "created_at",
125
+ "tail_sequence",
126
+ "tail_digest",
127
+ "producer_epoch"
128
+ ],
129
+ effect_agent_canonical_batches: [
130
+ "thread_id",
131
+ "batch_id",
132
+ "first_sequence",
133
+ "last_sequence",
134
+ "batch_digest",
135
+ "tail_digest",
136
+ "batch_json"
137
+ ],
138
+ effect_agent_canonical_records: [
139
+ "thread_id",
140
+ "sequence",
141
+ "record_id",
142
+ "batch_id",
143
+ "record_json"
144
+ ],
145
+ effect_agent_checkpoints: [
146
+ "thread_id",
147
+ "through_sequence",
148
+ "tail_digest",
149
+ "checkpoint_json"
150
+ ],
151
+ effect_agent_submissions: [
152
+ "submission_id",
153
+ "thread_id",
154
+ "queue_sequence",
155
+ "principal",
156
+ "idempotency_key",
157
+ "agent_id",
158
+ "agent_digests_json",
159
+ "deployment_id",
160
+ "input_json",
161
+ "input_digest",
162
+ "receipt_id",
163
+ "state",
164
+ "settled_outcome",
165
+ "created_at",
166
+ "ready_at",
167
+ "input_applied_record_id",
168
+ "input_applied_sequence",
169
+ "joined_host_submission_id",
170
+ "suspended_reason_json",
171
+ "suspended_at",
172
+ "unknown_reason",
173
+ "unknown_tool_call_ids_json",
174
+ "parent_submission_id",
175
+ "parent_tool_call_id",
176
+ "admission_group",
177
+ "admission_fence_json"
178
+ ],
179
+ effect_agent_submission_ownership: [
180
+ "submission_id",
181
+ "attempt_id",
182
+ "ownership_token",
183
+ "producer_epoch",
184
+ "owner_producer_id",
185
+ "lease_expires_at"
186
+ ],
187
+ effect_agent_attempts: [
188
+ "attempt_id",
189
+ "submission_id",
190
+ "thread_id",
191
+ "owner_producer_id",
192
+ "producer_epoch",
193
+ "claimed_at"
194
+ ],
195
+ effect_agent_settlement_reservations: [
196
+ "submission_id",
197
+ "settlement_id",
198
+ "outcome",
199
+ "record_id",
200
+ "record_json",
201
+ "record_digest",
202
+ "reserved_at",
203
+ "finalized_at"
204
+ ],
205
+ effect_agent_abort_intents: [
206
+ "submission_id",
207
+ "author",
208
+ "reason",
209
+ "requested_at",
210
+ "canonical_record_id"
211
+ ],
212
+ effect_agent_approval_decisions: [
213
+ "submission_id",
214
+ "tool_call_id",
215
+ "decision",
216
+ "resolver",
217
+ "reason",
218
+ "decided_at"
219
+ ],
220
+ effect_agent_unknown_resolutions: [
221
+ "submission_id",
222
+ "tool_call_id",
223
+ "author",
224
+ "reason",
225
+ "resolution_json",
226
+ "resolved_at"
227
+ ],
228
+ effect_agent_child_reservations: [
229
+ "reservation_id",
230
+ "parent_submission_id",
231
+ "parent_tool_call_id",
232
+ "child_submission_id",
233
+ "status",
234
+ "allocation_json",
235
+ "allocation_digest",
236
+ "accounting_json",
237
+ "reserved_at",
238
+ "release_began_at",
239
+ "released_at"
240
+ ],
241
+ effect_agent_meta: ["key", "value"],
242
+ effect_agent_child_settlements: [
243
+ "parent_submission_id",
244
+ "child_submission_id",
245
+ "child_outcome",
246
+ "recorded_at"
247
+ ]
248
+ };
249
+ const checkPredecessorLayout = Effect.fn("DoJournal.checkPredecessorLayout")(function* (version) {
250
+ const sql = yield* SqlClient.SqlClient;
251
+ const expectedColumns = {
252
+ ...version === 3 ? predecessorColumns : {
253
+ ...predecessorColumns,
254
+ effect_agent_submissions: [
255
+ ...predecessorColumns.effect_agent_submissions,
256
+ "worker_admission_json",
257
+ "message_admission_json"
258
+ ],
259
+ effect_agent_message_deliveries: [
260
+ "owner_thread_id",
261
+ "message_id",
262
+ "version",
263
+ "state",
264
+ "deadline_at_millis",
265
+ "record_json"
266
+ ]
267
+ },
268
+ ...version === 5 ? { effect_agent_recovery_checkpoints: [
269
+ "thread_id",
270
+ "through_sequence",
271
+ "tail_digest",
272
+ "checkpoint_json"
273
+ ] } : {}
274
+ };
275
+ for (const [table, expected] of Object.entries(expectedColumns)) {
276
+ const columns = yield* decodeRows(Schema.Array(Schema.Struct({ name: BoundedIdentifier })), table, "schema", yield* sql.unsafe(`PRAGMA table_info(${table})`));
277
+ const names = new Set(expected);
278
+ if (columns.length !== names.size || columns.some((column) => !names.has(column.name))) return yield* DoStorageCompatibilityError.make({
279
+ actualVersion: version,
280
+ supportedVersion: 6,
281
+ message: `The v${version} ${table} columns do not match the supported predecessor; no upgrade was committed.`
282
+ });
283
+ }
284
+ });
285
+ const REQUIRED_TABLES = [
286
+ "effect_agent_abort_intents",
287
+ "effect_agent_approval_decisions",
288
+ "effect_agent_attempts",
289
+ "effect_agent_canonical_batches",
290
+ "effect_agent_canonical_records",
291
+ "effect_agent_checkpoints",
292
+ "effect_agent_child_reservations",
293
+ "effect_agent_child_settlements",
294
+ "effect_agent_threads",
295
+ "effect_agent_meta",
296
+ "effect_agent_settlement_reservations",
297
+ "effect_agent_submission_ownership",
298
+ "effect_agent_submissions",
299
+ "effect_agent_unknown_resolutions"
300
+ ];
301
+ /**
302
+ * Supported-predecessor or fresh storage gate (DEPLOY-008) over `effect_agent_meta` instead of
303
+ * `PRAGMA user_version` (unverified on Durable Object SQL storage; a meta table is portable
304
+ * regardless). No WAL check (Durable Object storage owns durability and confirms writes
305
+ * through output gates) and no busy timeout (a Durable Object has exactly one writer): the
306
+ * Node machinery those served has no DC analogue and is deliberately absent.
307
+ */
308
+ const ensureCurrentStorage = Effect.fn("DoJournal.ensureCurrentStorage")(function* (sql, failpoint = noFailpoint, maxStoredValueBytes) {
309
+ const metaTableRows = yield* sql`
310
+ SELECT name
311
+ FROM sqlite_master
312
+ WHERE type = 'table'
313
+ AND name = 'effect_agent_meta'
314
+ `.pipe(Effect.mapError(storageError("read storage version table")));
315
+ if ((yield* decodeRows(Schema.Array(DoNameRow), "sqlite_master", "effect_agent_meta", metaTableRows)).length === 0) {
316
+ const existingRows = yield* sql`
317
+ SELECT name
318
+ FROM sqlite_master
319
+ WHERE type = 'table'
320
+ AND name LIKE 'effect_agent_%'
321
+ ORDER BY name
322
+ `.pipe(Effect.mapError(storageError("inspect unversioned storage")));
323
+ if ((yield* decodeRows(Schema.Array(DoNameRow), "sqlite_master", "effect_agent_%", existingRows)).length > 0) return yield* DoStorageCompatibilityError.make({
324
+ actualVersion: 0,
325
+ supportedVersion: 6,
326
+ message: "The Durable Object contains unversioned Effect Agent tables. Refusing to mutate ambiguous stored data; retain it for inspection with its original writer."
327
+ });
328
+ yield* SqliteMigrator.run({
329
+ loader: doMigrations,
330
+ table: "effect_sql_migrations_agent_threads"
331
+ }).pipe(Effect.provideService(SqlClient.SqlClient, sql), Effect.mapError((error) => DoStorageError.make({
332
+ cause: error,
333
+ operation: "initialize current storage",
334
+ message: error.message
335
+ })));
336
+ } else {
337
+ const versionRows = yield* sql`
338
+ SELECT value
339
+ FROM effect_agent_meta
340
+ WHERE key = 'storage_version'
341
+ `.pipe(Effect.mapError(storageError("read storage version")));
342
+ const version = yield* decodeSingleRow(Schema.Array(DoMetaRow), "effect_agent_meta", "storage_version", versionRows);
343
+ if (version.value === "2" || version.value === "3" || version.value === "4" || version.value === "5") yield* sql.withTransaction(Effect.gen(function* () {
344
+ const current = yield* sql`SELECT value FROM effect_agent_meta WHERE key='storage_version'`;
345
+ if (current.length === 1 && current[0].value === String(6)) return;
346
+ if (current.length !== 1 || current[0].value !== "2" && current[0].value !== "3" && current[0].value !== "4" && current[0].value !== "5") return yield* DoStorageCompatibilityError.make({
347
+ actualVersion: -1,
348
+ supportedVersion: 6,
349
+ message: "Storage version changed while acquiring the upgrade transaction."
350
+ });
351
+ if ((yield* decodeRows(Schema.Array(DoNameRow), "sqlite_master", "required_tables", yield* sql`SELECT name FROM sqlite_master WHERE type='table' AND name IN ${sql.in([...REQUIRED_TABLES])}`)).length !== REQUIRED_TABLES.length) return yield* DoStorageCompatibilityError.make({
352
+ actualVersion: Number(current[0].value),
353
+ supportedVersion: 6,
354
+ message: "The predecessor store is missing required tables. Retain the original store for inspection; no upgrade was committed."
355
+ });
356
+ if ((yield* sql`SELECT name FROM sqlite_master WHERE type='table' AND name='effect_agent_recovery_checkpoints'`).length !== (current[0].value === "5" ? 1 : 0)) return yield* DoStorageCompatibilityError.make({
357
+ actualVersion: Number(current[0].value),
358
+ supportedVersion: 6,
359
+ message: "The predecessor recovery checkpoint storage does not match its version; refusing ambiguous data without mutation."
360
+ });
361
+ if ((yield* sql`SELECT name FROM sqlite_master WHERE name='effect_agent_submissions_nonterminal'`).length !== 0) return yield* DoStorageCompatibilityError.make({
362
+ actualVersion: Number(current[0].value),
363
+ supportedVersion: 6,
364
+ message: "The predecessor already contains the nonterminal index; refusing ambiguous storage without mutation."
365
+ });
366
+ if (current[0].value === "2") {
367
+ yield* checkV2ThreadLayout();
368
+ for (const statement of [
369
+ sql`ALTER TABLE effect_agent_submissions ADD COLUMN admission_group TEXT`,
370
+ sql`ALTER TABLE effect_agent_submissions ADD COLUMN admission_fence_json TEXT`,
371
+ sql`CREATE INDEX effect_agent_submissions_group ON effect_agent_submissions (thread_id, admission_group, state)`
372
+ ]) {
373
+ yield* failpoint("upgrade:before-mutation");
374
+ yield* statement;
375
+ yield* failpoint("upgrade:after-mutation");
376
+ }
377
+ }
378
+ if (current[0].value === "3") yield* checkPredecessorLayout(3);
379
+ if (current[0].value === "4") yield* checkPredecessorLayout(4);
380
+ if (current[0].value === "5") yield* checkPredecessorLayout(5);
381
+ if (current[0].value === "2" || current[0].value === "3") {
382
+ yield* failpoint("upgrade:before-mutation");
383
+ yield* sql`ALTER TABLE effect_agent_submissions ADD COLUMN worker_admission_json TEXT`;
384
+ yield* failpoint("upgrade:after-mutation");
385
+ yield* failpoint("upgrade:before-mutation");
386
+ yield* sql`ALTER TABLE effect_agent_submissions ADD COLUMN message_admission_json TEXT`;
387
+ yield* failpoint("upgrade:after-mutation");
388
+ yield* failpoint("upgrade:before-mutation");
389
+ yield* createMessageDeliveryTables;
390
+ yield* failpoint("upgrade:after-mutation");
391
+ }
392
+ if (current[0].value !== "5") {
393
+ yield* failpoint("upgrade:before-mutation");
394
+ yield* createRecoveryCheckpointTable;
395
+ yield* failpoint("upgrade:after-mutation");
396
+ }
397
+ yield* failpoint("upgrade:before-mutation");
398
+ yield* createNonterminalIndex;
399
+ yield* failpoint("upgrade:after-mutation");
400
+ yield* failpoint("upgrade:before-version");
401
+ yield* sql`UPDATE effect_agent_meta SET value='6' WHERE key='storage_version'`;
402
+ yield* failpoint("upgrade:after-version");
403
+ })).pipe(Effect.catchTag("DoStorageFailpointError", (error) => DoStorageError.make({
404
+ cause: error,
405
+ operation: "upgrade storage",
406
+ message: error.message
407
+ })), Effect.catchTag("StorageUpgradeError", (error) => DoStorageCorruptionError.make({
408
+ table: error.table,
409
+ rowKey: error.rowKey,
410
+ message: error.message
411
+ })), Effect.catchTag("SqlError", storageError("upgrade supported thread storage")));
412
+ else if (version.value !== String(6)) {
413
+ const actualVersion = Number.parseInt(version.value, 10);
414
+ return yield* DoStorageCompatibilityError.make({
415
+ actualVersion: Number.isSafeInteger(actualVersion) ? actualVersion : -1,
416
+ supportedVersion: 6,
417
+ message: `The Durable Object uses unsupported storage version ${version.value}; this build supports exactly version 6. Only supported v2, v3, v4 and v5 can be upgraded automatically. Keep the original store and use a compatible library version.`
418
+ });
419
+ }
420
+ }
421
+ const requiredRows = yield* sql`
422
+ SELECT name
423
+ FROM sqlite_master
424
+ WHERE (type = 'table'
425
+ AND name IN ${sql.in([
426
+ ...REQUIRED_TABLES,
427
+ "effect_agent_message_deliveries",
428
+ "effect_agent_recovery_checkpoints"
429
+ ])}
430
+ ) OR (type = 'index' AND name = 'effect_agent_submissions_nonterminal')
431
+ ORDER BY name
432
+ `.pipe(Effect.mapError(storageError("verify storage tables")));
433
+ if ((yield* decodeRows(Schema.Array(DoNameRow), "sqlite_master", "required_tables", requiredRows)).length !== REQUIRED_TABLES.length + 3) return yield* DoStorageCompatibilityError.make({
434
+ actualVersion: 6,
435
+ supportedVersion: 6,
436
+ message: "The Durable Object claims the current format but is missing required tables or its nonterminal index. Retain the original store for inspection."
437
+ });
438
+ return makeJournal(sql, failpoint, maxStoredValueBytes);
439
+ });
440
+ const makeJournal = (sql, failpoint, maxStoredValueBytes) => {
441
+ /** Typed pre-write refusal for any single value over the configured byte bound. */
442
+ const checkValueBound = (operation, value) => {
443
+ const actualBytes = storedTextBytes(value);
444
+ return actualBytes > maxStoredValueBytes ? Effect.fail(DoValueBoundExceeded.make({
445
+ actualBytes,
446
+ maxBytes: maxStoredValueBytes,
447
+ operation
448
+ })) : Effect.void;
449
+ };
450
+ /**
451
+ * Runs one journal write transaction on the Durable Object storage-backed
452
+ * `withTransaction` (`ctx.storage.transaction()` under the hood). Within one Durable
453
+ * Object there is exactly ONE writer, so the Node `BEGIN IMMEDIATE` + busy-retry +
454
+ * `SqliteWriteContention` machinery has no analogue here and is deliberately absent.
455
+ * Ownership-token and epoch checks still run INSIDE the transaction, so fencing atomicity
456
+ * (DUR-006) is preserved identically.
457
+ *
458
+ * Journal write transactions are always top level: the Durable Object client rejects
459
+ * nested transactions, so new journal operations must not wrap this helper inside another
460
+ * transaction.
461
+ */
462
+ const withWriteTransaction = (operation) => (effect) => sql.withTransaction(effect).pipe(Effect.mapError((error) => isSqlError(error) ? storageError(operation)(error) : error), Effect.withSpan("DoJournal.withWriteTransaction", { attributes: { operation } }));
463
+ const materialize = Effect.fn("DoJournal.materialize")(function* (threadId, createdAt, emptyTailDigest, producerEpoch) {
464
+ if (threadId.length > MAX_IDENTIFIER_LENGTH) return yield* DoStorageError.make({
465
+ operation: "materialize thread",
466
+ message: "Thread identity exceeds the Durable Object storage bounds."
467
+ });
468
+ yield* checkValueBound("materialize thread", emptyTailDigest);
469
+ yield* withWriteTransaction("materialize transaction")(Effect.gen(function* () {
470
+ const existingRows = yield* sql`
471
+ SELECT
472
+ thread_id,
473
+ created_at,
474
+ tail_sequence,
475
+ tail_digest,
476
+ producer_epoch
477
+ FROM effect_agent_threads
478
+ WHERE thread_id = ${threadId}
479
+ `.pipe(Effect.mapError(storageError("read materialized thread")));
480
+ const existing = yield* decodeRows(Schema.Array(ThreadRow), "effect_agent_threads", threadId, existingRows);
481
+ if (existing.length > 1) return yield* DoStorageCorruptionError.make({
482
+ table: "effect_agent_threads",
483
+ rowKey: threadId,
484
+ message: "A thread primary key returned more than one row."
485
+ });
486
+ if (existing.length === 0) {
487
+ yield* sql`
488
+ INSERT INTO effect_agent_threads (
489
+ thread_id,
490
+ created_at,
491
+ tail_sequence,
492
+ tail_digest,
493
+ producer_epoch
494
+ ) VALUES (
495
+ ${threadId},
496
+ ${createdAt},
497
+ 0,
498
+ ${emptyTailDigest},
499
+ ${producerEpoch}
500
+ )
501
+ `.pipe(Effect.mapError(storageError("materialize thread")));
502
+ return;
503
+ }
504
+ if (producerEpoch < existing[0].producer_epoch) return yield* DoFenceRejected.make({
505
+ producerEpoch,
506
+ actualEpoch: existing[0].producer_epoch,
507
+ message: `Producer epoch ${producerEpoch} is stale; current epoch is ${existing[0].producer_epoch}.`
508
+ });
509
+ if (producerEpoch > existing[0].producer_epoch) yield* sql`
510
+ UPDATE effect_agent_threads
511
+ SET producer_epoch = ${producerEpoch}
512
+ WHERE thread_id = ${threadId}
513
+ `.pipe(Effect.mapError(storageError("advance materialization epoch")));
514
+ }));
515
+ });
516
+ const getThread = Effect.fn("DoJournal.getThread")(function* (threadId) {
517
+ const rows = yield* sql`
518
+ SELECT
519
+ thread_id,
520
+ created_at,
521
+ tail_sequence,
522
+ tail_digest,
523
+ producer_epoch
524
+ FROM effect_agent_threads
525
+ WHERE thread_id = ${threadId}
526
+ `.pipe(Effect.mapError(storageError("read thread")));
527
+ return yield* decodeRows(Schema.Array(ThreadRow), "effect_agent_threads", threadId, rows);
528
+ });
529
+ const append = Effect.fn("DoJournal.append")(function* (request) {
530
+ if (request.threadId.length > MAX_IDENTIFIER_LENGTH || request.batchId.length > MAX_IDENTIFIER_LENGTH || request.records.some((record) => record.recordId.length > MAX_IDENTIFIER_LENGTH)) return yield* DoStorageError.make({
531
+ operation: "append canonical batch",
532
+ message: "Canonical identifiers exceed the Durable Object storage bounds."
533
+ });
534
+ yield* checkValueBound("append canonical batch", request.batchJson);
535
+ yield* checkValueBound("append canonical batch", request.batchDigest);
536
+ yield* checkValueBound("append canonical batch", request.tailDigest);
537
+ yield* Effect.forEach(request.records, (record) => checkValueBound("append canonical record", record.recordJson), { discard: true });
538
+ return yield* withWriteTransaction("append transaction")(Effect.gen(function* () {
539
+ const recordIds = request.records.map((record) => record.recordId);
540
+ if (new Set(recordIds).size !== recordIds.length) return yield* DoAppendConflict.make({
541
+ message: `Batch ${request.batchId} contains duplicate canonical record IDs.`,
542
+ reason: "record-identity"
543
+ });
544
+ const threadRows = yield* sql`
545
+ SELECT
546
+ thread_id,
547
+ created_at,
548
+ tail_sequence,
549
+ tail_digest,
550
+ producer_epoch
551
+ FROM effect_agent_threads
552
+ WHERE thread_id = ${request.threadId}
553
+ `.pipe(Effect.mapError(storageError("read append tail")));
554
+ const thread = yield* decodeSingleRow(Schema.Array(ThreadRow), "effect_agent_threads", request.threadId, threadRows);
555
+ if (request.producerEpoch !== thread.producer_epoch) return yield* DoFenceRejected.make({
556
+ producerEpoch: request.producerEpoch,
557
+ actualEpoch: thread.producer_epoch,
558
+ message: `Producer epoch ${request.producerEpoch} is not the current epoch ${thread.producer_epoch}.`
559
+ });
560
+ const batchRows = yield* sql`
561
+ SELECT
562
+ thread_id,
563
+ batch_id,
564
+ first_sequence,
565
+ last_sequence,
566
+ batch_digest,
567
+ tail_digest,
568
+ batch_json
569
+ FROM effect_agent_canonical_batches
570
+ WHERE thread_id = ${request.threadId}
571
+ AND batch_id = ${request.batchId}
572
+ `.pipe(Effect.mapError(storageError("read idempotent batch")));
573
+ const batches = yield* decodeRows(Schema.Array(BatchRow), "effect_agent_canonical_batches", `${request.threadId}/${request.batchId}`, batchRows);
574
+ if (batches.length > 1) return yield* DoStorageCorruptionError.make({
575
+ table: "effect_agent_canonical_batches",
576
+ rowKey: `${request.threadId}/${request.batchId}`,
577
+ message: "A canonical batch primary key returned more than one row."
578
+ });
579
+ if (batches.length === 1) {
580
+ const existing = batches[0];
581
+ if (existing.batch_digest !== request.batchDigest) return yield* DoAppendConflict.make({
582
+ message: `Batch ${request.batchId} already exists with different canonical content.`,
583
+ reason: "batch-digest"
584
+ });
585
+ return RawAppendResult.make({
586
+ firstSequence: existing.first_sequence,
587
+ lastSequence: existing.last_sequence,
588
+ replayed: true,
589
+ tailDigest: existing.tail_digest
590
+ });
591
+ }
592
+ if (request.expectedTailSequence !== thread.tail_sequence || request.expectedTailDigest !== thread.tail_digest) return yield* DoAppendConflict.make({
593
+ message: `Expected tail ${request.expectedTailSequence}/${request.expectedTailDigest} but found ${thread.tail_sequence}/${thread.tail_digest}.`,
594
+ reason: "tail",
595
+ actualTailSequence: thread.tail_sequence,
596
+ actualTailDigest: thread.tail_digest
597
+ });
598
+ if (thread.tail_sequence + request.records.length > MAX_RECORDS_PER_THREAD) return yield* DoStorageError.make({
599
+ operation: "append canonical batch",
600
+ message: `Thread record limit ${MAX_RECORDS_PER_THREAD} would be exceeded.`
601
+ });
602
+ const existingRecords = [];
603
+ for (const chunk of chunked(recordIds, 90)) {
604
+ const existingRecordRows = yield* sql`
605
+ SELECT
606
+ thread_id,
607
+ sequence,
608
+ record_id,
609
+ batch_id,
610
+ record_json
611
+ FROM effect_agent_canonical_records
612
+ WHERE thread_id = ${request.threadId}
613
+ AND record_id IN ${sql.in([...chunk])}
614
+ ORDER BY sequence
615
+ `.pipe(Effect.mapError(storageError("check canonical record identities")));
616
+ existingRecords.push(...yield* decodeRows(Schema.Array(RecordRow), "effect_agent_canonical_records", `${request.threadId}/record_ids`, existingRecordRows));
617
+ }
618
+ if (existingRecords.length > 0) return yield* DoAppendConflict.make({
619
+ message: `Canonical record ID ${existingRecords[0].record_id} already exists.`,
620
+ reason: "record-identity"
621
+ });
622
+ const firstSequence = yield* Schema.decodeEffect(CanonicalSequence)(thread.tail_sequence + 1).pipe(Effect.mapError((error) => DoStorageError.make({
623
+ cause: error,
624
+ operation: "append canonical batch",
625
+ message: error.message
626
+ })));
627
+ const lastSequence = yield* Schema.decodeEffect(CanonicalSequence)(firstSequence + request.records.length - 1).pipe(Effect.mapError((error) => DoStorageError.make({
628
+ cause: error,
629
+ operation: "append canonical batch",
630
+ message: error.message
631
+ })));
632
+ yield* sql`
633
+ INSERT INTO effect_agent_canonical_batches (
634
+ thread_id,
635
+ batch_id,
636
+ first_sequence,
637
+ last_sequence,
638
+ batch_digest,
639
+ tail_digest,
640
+ batch_json
641
+ ) VALUES (
642
+ ${request.threadId},
643
+ ${request.batchId},
644
+ ${firstSequence},
645
+ ${lastSequence},
646
+ ${request.batchDigest},
647
+ ${request.tailDigest},
648
+ ${request.batchJson}
649
+ )
650
+ `.pipe(Effect.mapError(storageError("insert canonical batch")));
651
+ yield* failpoint("append:after-batch-insert");
652
+ yield* Effect.forEach(request.records, (record, index) => Effect.gen(function* () {
653
+ yield* sql`
654
+ INSERT INTO effect_agent_canonical_records (
655
+ thread_id,
656
+ sequence,
657
+ record_id,
658
+ batch_id,
659
+ record_json
660
+ ) VALUES (
661
+ ${request.threadId},
662
+ ${firstSequence + index},
663
+ ${record.recordId},
664
+ ${request.batchId},
665
+ ${record.recordJson}
666
+ )
667
+ `.pipe(Effect.mapError(storageError("insert canonical record")));
668
+ yield* failpoint("append:after-record-insert");
669
+ }), { discard: true });
670
+ yield* sql`
671
+ UPDATE effect_agent_threads
672
+ SET
673
+ tail_sequence = ${lastSequence},
674
+ tail_digest = ${request.tailDigest},
675
+ producer_epoch = ${request.producerEpoch}
676
+ WHERE thread_id = ${request.threadId}
677
+ `.pipe(Effect.mapError(storageError("advance thread tail")));
678
+ yield* failpoint("append:after-tail-update");
679
+ return RawAppendResult.make({
680
+ firstSequence,
681
+ lastSequence,
682
+ replayed: false,
683
+ tailDigest: request.tailDigest
684
+ });
685
+ }));
686
+ });
687
+ const read = Effect.fn("DoJournal.read")(function* (request) {
688
+ const planRows = yield* sql`
689
+ SELECT
690
+ sequence,
691
+ length(CAST(record_json AS BLOB)) AS record_json_bytes
692
+ FROM effect_agent_canonical_records
693
+ WHERE thread_id = ${request.threadId}
694
+ AND sequence > ${request.fromSequenceExclusive}
695
+ ORDER BY sequence
696
+ LIMIT ${request.limit}
697
+ `.pipe(Effect.mapError(storageError("read canonical records")));
698
+ const plan = yield* decodeRows(Schema.Array(ReadPlanRow), "effect_agent_canonical_records", `${request.threadId}>${request.fromSequenceExclusive}`, planRows);
699
+ const mismatch = () => DoStorageCorruptionError.make({
700
+ table: "effect_agent_canonical_records",
701
+ rowKey: `${request.threadId}>${request.fromSequenceExclusive}`,
702
+ message: "Canonical read membership, sequence, or payload size changed from its read plan."
703
+ });
704
+ if (plan.length > request.limit) return yield* mismatch();
705
+ const pages = [];
706
+ let page;
707
+ let pageBytes = 0;
708
+ let previousSequence = request.fromSequenceExclusive;
709
+ for (const row of plan) {
710
+ if (row.sequence !== previousSequence + 1) return yield* mismatch();
711
+ previousSequence = row.sequence;
712
+ if (page === void 0 || pageBytes + row.record_json_bytes > MAX_READ_PAGE_JSON_BYTES) {
713
+ page = [row];
714
+ pages.push(page);
715
+ pageBytes = row.record_json_bytes;
716
+ } else {
717
+ page.push(row);
718
+ pageBytes += row.record_json_bytes;
719
+ }
720
+ }
721
+ const readPage = Effect.fn("DoJournal.readPage")(function* (page) {
722
+ const rows = yield* sql`
723
+ SELECT thread_id, sequence, record_id, batch_id, record_json
724
+ FROM effect_agent_canonical_records
725
+ WHERE thread_id = ${request.threadId}
726
+ AND sequence >= ${page[0].sequence}
727
+ AND sequence <= ${page[page.length - 1].sequence}
728
+ ORDER BY sequence
729
+ `.pipe(Effect.mapError(storageError("read canonical records")));
730
+ const decoded = yield* decodeRows(Schema.Array(RecordRow), "effect_agent_canonical_records", `${request.threadId}/${page[0].sequence}`, rows);
731
+ if (decoded.length !== page.length || decoded.some((row, index) => row.thread_id !== request.threadId || row.sequence !== page[index].sequence || storedTextBytes(row.record_json) !== page[index].record_json_bytes)) return yield* mismatch();
732
+ return decoded;
733
+ });
734
+ return {
735
+ count: plan.length,
736
+ records: Stream.fromIterable(pages).pipe(Stream.flatMap((page) => Stream.fromIterableEffect(readPage(page))))
737
+ };
738
+ });
739
+ const exportThread = Effect.fn("DoJournal.exportThread")(function* (threadId) {
740
+ return yield* sql.withTransaction(Effect.gen(function* () {
741
+ const threadRows = yield* sql`
742
+ SELECT
743
+ thread_id,
744
+ created_at,
745
+ tail_sequence,
746
+ tail_digest,
747
+ producer_epoch
748
+ FROM effect_agent_threads
749
+ WHERE thread_id = ${threadId}
750
+ `.pipe(Effect.mapError(storageError("export thread")));
751
+ const thread = yield* decodeSingleRow(Schema.Array(ThreadRow), "effect_agent_threads", threadId, threadRows);
752
+ yield* failpoint("export:after-thread-read");
753
+ if (thread.tail_sequence > MAX_RECORDS_PER_THREAD) return yield* DoStorageError.make({
754
+ operation: "export thread",
755
+ message: "The thread exceeds the current export record limit."
756
+ });
757
+ const records = [];
758
+ let afterSequence = ZERO_SEQUENCE;
759
+ while (afterSequence < thread.tail_sequence) {
760
+ const limit = Math.min(1024, thread.tail_sequence - afterSequence);
761
+ const request = RawReadRequest.make({
762
+ threadId,
763
+ fromSequenceExclusive: afterSequence,
764
+ limit
765
+ });
766
+ const plan = yield* read(request);
767
+ const page = yield* Stream.runCollect(plan.records);
768
+ if (page.length !== limit || page.some((record, index) => record.sequence !== afterSequence + index + 1)) return yield* DoStorageCorruptionError.make({
769
+ table: "effect_agent_canonical_records",
770
+ rowKey: threadId,
771
+ message: "The exported canonical prefix is not contiguous through its captured tail."
772
+ });
773
+ records.push(...page);
774
+ afterSequence = page[page.length - 1].sequence;
775
+ }
776
+ if ((yield* sql`SELECT sequence FROM effect_agent_canonical_records WHERE thread_id=${threadId} AND sequence > ${thread.tail_sequence} LIMIT 1`.pipe(Effect.mapError(storageError("verify export tail")))).length !== 0) return yield* DoStorageCorruptionError.make({
777
+ table: "effect_agent_canonical_records",
778
+ rowKey: threadId,
779
+ message: "Canonical records exist beyond the captured thread tail."
780
+ });
781
+ return RawThreadExport.make({
782
+ thread,
783
+ records
784
+ });
785
+ })).pipe(Effect.catchTag("SqlError", (error) => Effect.fail(storageError("export transaction")(error))));
786
+ });
787
+ const saveCheckpoint = Effect.fn("DoJournal.saveCheckpoint")(function* (checkpoint) {
788
+ if (checkpoint.threadId.length > MAX_IDENTIFIER_LENGTH) return yield* DoStorageError.make({
789
+ operation: "save checkpoint",
790
+ message: "Checkpoint identity exceeds the Durable Object storage bounds."
791
+ });
792
+ yield* checkValueBound("save checkpoint", checkpoint.checkpointJson);
793
+ yield* withWriteTransaction("checkpoint transaction")(Effect.gen(function* () {
794
+ const threadRows = yield* sql`
795
+ SELECT
796
+ thread_id,
797
+ created_at,
798
+ tail_sequence,
799
+ tail_digest,
800
+ producer_epoch
801
+ FROM effect_agent_threads
802
+ WHERE thread_id = ${checkpoint.threadId}
803
+ `.pipe(Effect.mapError(storageError("read checkpoint tail")));
804
+ const thread = yield* decodeSingleRow(Schema.Array(ThreadRow), "effect_agent_threads", checkpoint.threadId, threadRows);
805
+ if (checkpoint.throughSequence > thread.tail_sequence) return yield* DoCheckpointConflict.make({ message: `Checkpoint sequence ${checkpoint.throughSequence} is after canonical tail ${thread.tail_sequence}.` });
806
+ const checkpointRows = yield* sql`
807
+ SELECT
808
+ thread_id,
809
+ through_sequence,
810
+ tail_digest,
811
+ checkpoint_json
812
+ FROM effect_agent_checkpoints
813
+ WHERE thread_id = ${checkpoint.threadId}
814
+ AND through_sequence = ${checkpoint.throughSequence}
815
+ `.pipe(Effect.mapError(storageError("read idempotent checkpoint")));
816
+ const existing = yield* decodeRows(Schema.Array(CheckpointRow), "effect_agent_checkpoints", `${checkpoint.threadId}/${checkpoint.throughSequence}`, checkpointRows);
817
+ if (existing.length > 1) return yield* DoStorageCorruptionError.make({
818
+ table: "effect_agent_checkpoints",
819
+ rowKey: `${checkpoint.threadId}/${checkpoint.throughSequence}`,
820
+ message: "A checkpoint primary key returned more than one row."
821
+ });
822
+ if (existing.length === 1) {
823
+ if (existing[0].tail_digest !== checkpoint.tailDigest || existing[0].checkpoint_json !== checkpoint.checkpointJson) return yield* DoCheckpointConflict.make({ message: "A different checkpoint already exists at this canonical sequence." });
824
+ return;
825
+ }
826
+ yield* sql`
827
+ INSERT INTO effect_agent_checkpoints (
828
+ thread_id,
829
+ through_sequence,
830
+ tail_digest,
831
+ checkpoint_json
832
+ ) VALUES (
833
+ ${checkpoint.threadId},
834
+ ${checkpoint.throughSequence},
835
+ ${checkpoint.tailDigest},
836
+ ${checkpoint.checkpointJson}
837
+ )
838
+ `.pipe(Effect.mapError(storageError("insert checkpoint")));
839
+ }));
840
+ });
841
+ const saveRecoveryCheckpoint = Effect.fn("DoJournal.saveRecoveryCheckpoint")(function* (request, checkpointJson) {
842
+ const { checkpoint } = request;
843
+ if (checkpoint.threadId.length > MAX_IDENTIFIER_LENGTH) return yield* DoStorageError.make({
844
+ operation: "save recovery checkpoint",
845
+ message: "Checkpoint identity exceeds the Durable Object storage bounds."
846
+ });
847
+ yield* checkValueBound("save recovery checkpoint", checkpointJson);
848
+ yield* failpoint("save-recovery-checkpoint:before");
849
+ yield* withWriteTransaction("recovery checkpoint transaction")(Effect.gen(function* () {
850
+ const thread = (yield* getThread(checkpoint.threadId))[0];
851
+ if (thread === void 0) return yield* ThreadNotMaterialized.make({ threadId: checkpoint.threadId });
852
+ if (request.producerEpoch !== thread.producer_epoch) return yield* FenceRejected.make({
853
+ threadId: checkpoint.threadId,
854
+ actualEpoch: thread.producer_epoch,
855
+ attemptedEpoch: request.producerEpoch
856
+ });
857
+ if (checkpoint.throughSequence > thread.tail_sequence) return yield* CheckpointRejected.make({
858
+ threadId: checkpoint.threadId,
859
+ reason: "ahead-of-tail"
860
+ });
861
+ const digests = checkpoint.throughSequence === 0 ? [EMPTY_TAIL_DIGEST] : yield* getTailDigestAt(checkpoint.threadId, checkpoint.throughSequence);
862
+ if (digests.length !== 1 || digests[0] !== checkpoint.tailDigest) return yield* CheckpointRejected.make({
863
+ threadId: checkpoint.threadId,
864
+ reason: "digest-mismatch"
865
+ });
866
+ yield* sql`
867
+ INSERT INTO effect_agent_recovery_checkpoints (thread_id, through_sequence, tail_digest, checkpoint_json)
868
+ VALUES (${checkpoint.threadId}, ${checkpoint.throughSequence}, ${checkpoint.tailDigest}, ${checkpointJson})
869
+ ON CONFLICT (thread_id) DO UPDATE SET
870
+ through_sequence = excluded.through_sequence,
871
+ tail_digest = excluded.tail_digest,
872
+ checkpoint_json = excluded.checkpoint_json
873
+ WHERE excluded.through_sequence >= effect_agent_recovery_checkpoints.through_sequence
874
+ `.pipe(Effect.mapError(storageError("save recovery checkpoint")));
875
+ }));
876
+ yield* failpoint("save-recovery-checkpoint:after");
877
+ });
878
+ const loadRecoveryCheckpoint = Effect.fn("DoJournal.loadRecoveryCheckpoint")(function* (threadId) {
879
+ const rows = yield* sql`
880
+ SELECT thread_id, through_sequence, tail_digest, checkpoint_json
881
+ FROM effect_agent_recovery_checkpoints
882
+ WHERE thread_id = ${threadId}
883
+ `.pipe(Effect.mapError(storageError("load recovery checkpoint")));
884
+ return yield* decodeRows(Schema.Array(CheckpointRow), "effect_agent_recovery_checkpoints", threadId, rows);
885
+ });
886
+ const loadCheckpoint = Effect.fn("DoJournal.loadCheckpoint")(function* (threadId, atOrBeforeSequence) {
887
+ const rows = yield* sql`
888
+ SELECT
889
+ thread_id,
890
+ through_sequence,
891
+ tail_digest,
892
+ checkpoint_json
893
+ FROM effect_agent_checkpoints
894
+ WHERE thread_id = ${threadId}
895
+ AND through_sequence <= ${atOrBeforeSequence}
896
+ ORDER BY through_sequence DESC
897
+ LIMIT 1
898
+ `.pipe(Effect.mapError(storageError("load checkpoint")));
899
+ return yield* decodeRows(Schema.Array(CheckpointRow), "effect_agent_checkpoints", `${threadId}<=${atOrBeforeSequence}`, rows);
900
+ });
901
+ const getTailDigestAt = Effect.fn("DoJournal.getTailDigestAt")(function* (threadId, sequence) {
902
+ if (sequence === 0) {
903
+ const threads = yield* getThread(threadId);
904
+ return threads.length === 0 ? [] : [threads[0].tail_sequence === 0 ? threads[0].tail_digest : void 0].filter((value) => value !== void 0);
905
+ }
906
+ const rows = yield* sql`
907
+ SELECT
908
+ thread_id,
909
+ batch_id,
910
+ first_sequence,
911
+ last_sequence,
912
+ batch_digest,
913
+ tail_digest,
914
+ batch_json
915
+ FROM effect_agent_canonical_batches
916
+ WHERE thread_id = ${threadId}
917
+ AND last_sequence = ${sequence}
918
+ `.pipe(Effect.mapError(storageError("read canonical digest at sequence")));
919
+ return (yield* decodeRows(Schema.Array(BatchRow), "effect_agent_canonical_batches", `${threadId}/${sequence}`, rows)).map((batch) => batch.tail_digest);
920
+ });
921
+ return {
922
+ append,
923
+ checkValueBound,
924
+ exportThread,
925
+ getThread,
926
+ getTailDigestAt,
927
+ loadCheckpoint,
928
+ loadRecoveryCheckpoint,
929
+ saveRecoveryCheckpoint,
930
+ materialize,
931
+ read,
932
+ saveCheckpoint,
933
+ scanStoredPayloads: Effect.fn("DoJournal.scanStoredPayloads")(function* () {
934
+ return yield* sql.withTransaction(Effect.gen(function* () {
935
+ const threads = yield* sql`
936
+ SELECT
937
+ thread_id,
938
+ created_at,
939
+ tail_sequence,
940
+ tail_digest,
941
+ producer_epoch
942
+ FROM effect_agent_threads
943
+ ORDER BY thread_id
944
+ `.pipe(Effect.mapError(storageError("scan threads")));
945
+ const batches = yield* sql`
946
+ SELECT
947
+ thread_id,
948
+ batch_id,
949
+ first_sequence,
950
+ last_sequence,
951
+ batch_digest,
952
+ tail_digest,
953
+ batch_json
954
+ FROM effect_agent_canonical_batches
955
+ ORDER BY thread_id, first_sequence
956
+ `.pipe(Effect.mapError(storageError("scan canonical batches")));
957
+ const records = yield* sql`
958
+ SELECT
959
+ thread_id,
960
+ sequence,
961
+ record_id,
962
+ batch_id,
963
+ record_json
964
+ FROM effect_agent_canonical_records
965
+ ORDER BY thread_id, sequence
966
+ `.pipe(Effect.mapError(storageError("scan canonical records")));
967
+ const checkpoints = yield* sql`
968
+ SELECT
969
+ thread_id,
970
+ through_sequence,
971
+ tail_digest,
972
+ checkpoint_json
973
+ FROM effect_agent_checkpoints
974
+ ORDER BY thread_id, through_sequence
975
+ `.pipe(Effect.mapError(storageError("scan checkpoints")));
976
+ return {
977
+ threads: yield* decodeRows(Schema.Array(ThreadRow), "effect_agent_threads", "startup_scan", threads),
978
+ batches: yield* decodeRows(Schema.Array(BatchRow), "effect_agent_canonical_batches", "startup_scan", batches),
979
+ records: yield* decodeRows(Schema.Array(RecordRow), "effect_agent_canonical_records", "startup_scan", records),
980
+ checkpoints: yield* decodeRows(Schema.Array(CheckpointRow), "effect_agent_checkpoints", "startup_scan", checkpoints)
981
+ };
982
+ })).pipe(Effect.catchTag("SqlError", (error) => Effect.fail(storageError("startup scan transaction")(error))));
983
+ }),
984
+ withWriteTransaction
985
+ };
986
+ };
987
+ const initializeDoJournal = ensureCurrentStorage;
988
+ //#endregion
989
+ export { initializeDoJournal as a, decodeRows as i, RawCheckpoint as n, RawReadRequest as r, RawAppendRequest as t };
990
+
991
+ //# sourceMappingURL=do-journal-dJ01KSKf.mjs.map