@effect-agent/storage-sqlite 0.1.0-beta.11 → 0.1.0-beta.110

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 (63) hide show
  1. package/dist/SqliteActivityStore.d.mts +14 -0
  2. package/dist/SqliteActivityStore.mjs +310 -0
  3. package/dist/SqliteActivityStore.mjs.map +1 -0
  4. package/dist/SqliteMessageDeliveryStore.d.mts +14 -0
  5. package/dist/SqliteMessageDeliveryStore.mjs +24 -0
  6. package/dist/SqliteMessageDeliveryStore.mjs.map +1 -0
  7. package/dist/SqliteScheduleStore.d.mts +14 -0
  8. package/dist/SqliteScheduleStore.mjs +255 -0
  9. package/dist/SqliteScheduleStore.mjs.map +1 -0
  10. package/dist/SqliteStorageConfig.d.mts +34 -0
  11. package/dist/SqliteStorageConfig.mjs +39 -0
  12. package/dist/SqliteStorageConfig.mjs.map +1 -0
  13. package/dist/SqliteStorageError-DVWeaWLm.d.mts +86 -0
  14. package/dist/SqliteStorageError.d.mts +2 -0
  15. package/dist/SqliteStorageError.mjs +150 -0
  16. package/dist/SqliteStorageError.mjs.map +1 -0
  17. package/dist/SqliteStorageFailpoint.d.mts +17 -0
  18. package/dist/SqliteStorageFailpoint.mjs +14 -0
  19. package/dist/SqliteStorageFailpoint.mjs.map +1 -0
  20. package/dist/SqliteStorageFailpointTesting.d.mts +14 -0
  21. package/dist/SqliteStorageFailpointTesting.mjs +19 -0
  22. package/dist/SqliteStorageFailpointTesting.mjs.map +1 -0
  23. package/dist/SqliteStorageVersion-BO6U_VHq.d.mts +11 -0
  24. package/dist/SqliteStorageVersion.d.mts +2 -0
  25. package/dist/SqliteStorageVersion.mjs +8 -0
  26. package/dist/SqliteStorageVersion.mjs.map +1 -0
  27. package/dist/SqliteSubmissionLedger.d.mts +23 -0
  28. package/dist/SqliteSubmissionLedger.mjs +1803 -0
  29. package/dist/SqliteSubmissionLedger.mjs.map +1 -0
  30. package/dist/SqliteSubscriptionStore.d.mts +13 -0
  31. package/dist/SqliteSubscriptionStore.mjs +28 -0
  32. package/dist/SqliteSubscriptionStore.mjs.map +1 -0
  33. package/dist/SqliteThreadStore.d.mts +49 -0
  34. package/dist/SqliteThreadStore.mjs +464 -0
  35. package/dist/SqliteThreadStore.mjs.map +1 -0
  36. package/dist/index.d.mts +11 -193
  37. package/dist/index.mjs +11 -3082
  38. package/dist/migrations-BZ89iaTY.mjs +350 -0
  39. package/dist/migrations-BZ89iaTY.mjs.map +1 -0
  40. package/dist/rolldown-runtime-D7D4PA-g.mjs +13 -0
  41. package/dist/sqlite-journal-BCyBc87Y.mjs +1044 -0
  42. package/dist/sqlite-journal-BCyBc87Y.mjs.map +1 -0
  43. package/package.json +1 -41
  44. package/src/SqliteActivityStore.ts +556 -0
  45. package/src/SqliteMessageDeliveryStore.ts +42 -0
  46. package/src/SqliteScheduleStore.ts +404 -0
  47. package/src/{sqlite-storage-config.ts → SqliteStorageConfig.ts} +1 -1
  48. package/src/{errors.ts → SqliteStorageError.ts} +10 -3
  49. package/src/SqliteStorageFailpoint.ts +23 -0
  50. package/src/{sqlite-storage-failpoint.ts → SqliteStorageFailpointTesting.ts} +7 -18
  51. package/src/SqliteStorageVersion.ts +2 -0
  52. package/src/{sqlite-ledger.ts → SqliteSubmissionLedger.ts} +958 -233
  53. package/src/SqliteSubscriptionStore.ts +55 -0
  54. package/src/SqliteThreadStore.ts +1004 -0
  55. package/src/index.ts +10 -6
  56. package/src/internal/message-delivery-schema.ts +24 -0
  57. package/src/internal/migrations.ts +356 -0
  58. package/src/internal/recovery-checkpoint-schema.ts +17 -0
  59. package/src/internal/sqlite-journal.ts +1684 -0
  60. package/dist/index.mjs.map +0 -1
  61. package/src/migrations.ts +0 -275
  62. package/src/sqlite-conversation-store.ts +0 -841
  63. package/src/sqlite-journal.ts +0 -1086
@@ -0,0 +1,1684 @@
1
+ import { NodeCrypto } from "@effect/platform-node";
2
+ import { SqliteMigrator } from "@effect/sql-sqlite-node";
3
+ import { Effect, Exit, Schema } from "effect";
4
+ import { EMPTY_TAIL_DIGEST } from "effect-agent/digest";
5
+ import { CanonicalRecord, CanonicalSequence, ProducerEpoch } from "effect-agent/records";
6
+ import { ScheduleFailpoint, ScheduleFailpointError } from "effect-agent/schedule";
7
+ import { createMessageDeliveryPendingIndex } from "effect-agent/sql-message-delivery-store";
8
+ import {
9
+ checkV2ThreadLayout,
10
+ upgradeV2Schedules,
11
+ upgradeV2Subscriptions,
12
+ } from "effect-agent/sql-storage-v2-upgrade";
13
+ import {
14
+ createNativeReadIndexes,
15
+ seedNativeReadIndexes,
16
+ indexCanonicalRecord,
17
+ } from "effect-agent/sql-thread-native-reads";
18
+ import { SubscriptionFailpoint, SubscriptionFailpointError } from "effect-agent/subscription";
19
+ import {
20
+ MAX_THREAD_EXPORT_RECORDS,
21
+ CheckpointRejected,
22
+ FenceRejected,
23
+ ThreadNotMaterialized,
24
+ type SaveRecoveryCheckpointRequest,
25
+ } from "effect-agent/thread-store";
26
+ import * as SqlClient from "effect/unstable/sql/SqlClient";
27
+ import type { SqlError } from "effect/unstable/sql/SqlError";
28
+
29
+ import { SqliteStorageConfig } from "../SqliteStorageConfig.ts";
30
+ import type { SqliteStorageFailpointError } from "../SqliteStorageError.ts";
31
+ import {
32
+ SqliteAppendConflict,
33
+ SqliteCheckpointConflict,
34
+ SqliteFenceRejected,
35
+ SqliteStorageCompatibilityError,
36
+ SqliteStorageFailpointLocation,
37
+ SqliteStorageCorruptionError,
38
+ SqliteStorageError,
39
+ SqliteWriteContention,
40
+ } from "../SqliteStorageError.ts";
41
+ import { SqliteStorageFailpoint } from "../SqliteStorageFailpoint.ts";
42
+ import { createMessageDeliveryTables } from "./message-delivery-schema.ts";
43
+ import {
44
+ CurrentSqliteStorageVersion,
45
+ createNonterminalIndex,
46
+ sqliteMigrations,
47
+ } from "./migrations.ts";
48
+ import { createRecoveryCheckpointTable } from "./recovery-checkpoint-schema.ts";
49
+
50
+ const BoundedStoredText = Schema.String.check(Schema.isMaxLength(16 * 1024 * 1024));
51
+ const BoundedIdentifier = Schema.NonEmptyString.check(Schema.isMaxLength(1024));
52
+ const NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));
53
+ const MAX_RECORDS_PER_THREAD = MAX_THREAD_EXPORT_RECORDS;
54
+ const ZERO_SEQUENCE = Schema.decodeSync(CanonicalSequence)(0);
55
+ const MAX_STORED_TEXT_BYTES = 16 * 1024 * 1024;
56
+ const MAX_IDENTIFIER_LENGTH = 1_024;
57
+
58
+ const storedTextBytes = (value: string): number => new TextEncoder().encode(value).byteLength;
59
+
60
+ class SqliteVersionRow extends Schema.Class<SqliteVersionRow>("SqliteVersionRow")({
61
+ user_version: NonNegativeInt,
62
+ }) {}
63
+
64
+ class SqliteJournalModeRow extends Schema.Class<SqliteJournalModeRow>("SqliteJournalModeRow")({
65
+ journal_mode: Schema.NonEmptyString.check(Schema.isMaxLength(32)),
66
+ }) {}
67
+
68
+ class SqliteNameRow extends Schema.Class<SqliteNameRow>("SqliteNameRow")({
69
+ name: BoundedIdentifier,
70
+ }) {}
71
+
72
+ class ThreadRow extends Schema.Class<ThreadRow>("ThreadRow")({
73
+ thread_id: BoundedIdentifier,
74
+ created_at: Schema.NonEmptyString.check(Schema.isMaxLength(128)),
75
+ producer_epoch: ProducerEpoch,
76
+ tail_digest: BoundedStoredText,
77
+ tail_sequence: CanonicalSequence,
78
+ }) {}
79
+
80
+ class BatchRow extends Schema.Class<BatchRow>("BatchRow")({
81
+ batch_digest: BoundedStoredText,
82
+ batch_id: BoundedIdentifier,
83
+ batch_json: BoundedStoredText,
84
+ thread_id: BoundedIdentifier,
85
+ first_sequence: CanonicalSequence,
86
+ last_sequence: CanonicalSequence,
87
+ tail_digest: BoundedStoredText,
88
+ }) {}
89
+
90
+ class RecordRow extends Schema.Class<RecordRow>("RecordRow")({
91
+ batch_id: BoundedIdentifier,
92
+ thread_id: BoundedIdentifier,
93
+ record_id: BoundedIdentifier,
94
+ record_json: BoundedStoredText,
95
+ sequence: CanonicalSequence,
96
+ }) {}
97
+
98
+ class CheckpointRow extends Schema.Class<CheckpointRow>("CheckpointRow")({
99
+ checkpoint_json: BoundedStoredText,
100
+ thread_id: BoundedIdentifier,
101
+ tail_digest: BoundedStoredText,
102
+ through_sequence: CanonicalSequence,
103
+ }) {}
104
+
105
+ export class RawRecord extends Schema.Class<RawRecord>("@effect-agent/storage-sqlite/RawRecord")({
106
+ recordId: BoundedIdentifier,
107
+ recordJson: BoundedStoredText,
108
+ }) {}
109
+
110
+ export class RawAppendRequest extends Schema.Class<RawAppendRequest>(
111
+ "@effect-agent/storage-sqlite/RawAppendRequest",
112
+ )({
113
+ batchDigest: BoundedStoredText,
114
+ batchId: BoundedIdentifier,
115
+ batchJson: BoundedStoredText,
116
+ threadId: BoundedIdentifier,
117
+ expectedTailDigest: BoundedStoredText,
118
+ expectedTailSequence: CanonicalSequence,
119
+ producerEpoch: ProducerEpoch,
120
+ records: Schema.NonEmptyArray(RawRecord).check(Schema.isMaxLength(256)),
121
+ tailDigest: BoundedStoredText,
122
+ }) {}
123
+
124
+ export class RawAppendResult extends Schema.Class<RawAppendResult>(
125
+ "@effect-agent/storage-sqlite/RawAppendResult",
126
+ )({
127
+ firstSequence: CanonicalSequence,
128
+ lastSequence: CanonicalSequence,
129
+ replayed: Schema.Boolean,
130
+ tailDigest: BoundedStoredText,
131
+ }) {}
132
+
133
+ export class RawReadRequest extends Schema.Class<RawReadRequest>(
134
+ "@effect-agent/storage-sqlite/RawReadRequest",
135
+ )({
136
+ threadId: BoundedIdentifier,
137
+ fromSequenceExclusive: CanonicalSequence,
138
+ limit: Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(1_024)),
139
+ }) {}
140
+
141
+ export class RawCheckpoint extends Schema.Class<RawCheckpoint>(
142
+ "@effect-agent/storage-sqlite/RawCheckpoint",
143
+ )({
144
+ checkpointJson: BoundedStoredText,
145
+ threadId: BoundedIdentifier,
146
+ tailDigest: BoundedStoredText,
147
+ throughSequence: CanonicalSequence,
148
+ }) {}
149
+
150
+ export class RawThreadExport extends Schema.Class<RawThreadExport>(
151
+ "@effect-agent/storage-sqlite/RawThreadExport",
152
+ )({
153
+ thread: ThreadRow,
154
+ records: Schema.Array(RecordRow),
155
+ }) {}
156
+
157
+ type AppendError =
158
+ | SqliteAppendConflict
159
+ | SqliteFenceRejected
160
+ | SqliteStorageCorruptionError
161
+ | SqliteStorageError
162
+ | SqliteStorageFailpointError
163
+ | SqliteWriteContention;
164
+
165
+ type CheckpointError =
166
+ | SqliteCheckpointConflict
167
+ | SqliteStorageCorruptionError
168
+ | SqliteStorageError
169
+ | SqliteWriteContention;
170
+
171
+ const storageError =
172
+ (operation: string) =>
173
+ (error: SqlError): SqliteStorageError =>
174
+ SqliteStorageError.make({
175
+ cause: error,
176
+ operation,
177
+ message: error.message,
178
+ });
179
+
180
+ /** Decode raw SQLite rows against a Schema, reporting failures as typed corruption. */
181
+ export const decodeRows = Effect.fn("SqliteJournal.decodeRows")(
182
+ <A, I>(
183
+ schema: Schema.Codec<ReadonlyArray<A>, ReadonlyArray<I>>,
184
+ table: string,
185
+ rowKey: string,
186
+ rows: unknown,
187
+ ): Effect.Effect<ReadonlyArray<A>, SqliteStorageCorruptionError> =>
188
+ Schema.decodeUnknownEffect(schema)(rows).pipe(
189
+ Effect.mapError((error) =>
190
+ SqliteStorageCorruptionError.make({
191
+ table,
192
+ rowKey,
193
+ message: String(error),
194
+ }),
195
+ ),
196
+ ),
197
+ );
198
+
199
+ /** Decode exactly one raw SQLite row against a Schema, reporting failures as typed corruption. */
200
+ export const decodeSingleRow = Effect.fn("SqliteJournal.decodeSingleRow")(
201
+ <A, I>(
202
+ schema: Schema.Codec<ReadonlyArray<A>, ReadonlyArray<I>>,
203
+ table: string,
204
+ rowKey: string,
205
+ rows: unknown,
206
+ ): Effect.Effect<A, SqliteStorageCorruptionError> =>
207
+ decodeRows(schema, table, rowKey, rows).pipe(
208
+ Effect.flatMap((decoded) =>
209
+ decoded.length === 1
210
+ ? Effect.succeed(decoded[0])
211
+ : Effect.fail(
212
+ SqliteStorageCorruptionError.make({
213
+ table,
214
+ rowKey,
215
+ message: `Expected exactly one row but found ${decoded.length}.`,
216
+ }),
217
+ ),
218
+ ),
219
+ ),
220
+ );
221
+
222
+ /** Column inventory of the supported v8 predecessor, independent of physical column order. */
223
+ const predecessorColumns = {
224
+ effect_agent_threads: [
225
+ "thread_id",
226
+ "created_at",
227
+ "tail_sequence",
228
+ "tail_digest",
229
+ "producer_epoch",
230
+ ],
231
+ effect_agent_canonical_batches: [
232
+ "thread_id",
233
+ "batch_id",
234
+ "first_sequence",
235
+ "last_sequence",
236
+ "batch_digest",
237
+ "tail_digest",
238
+ "batch_json",
239
+ ],
240
+ effect_agent_canonical_records: ["thread_id", "sequence", "record_id", "batch_id", "record_json"],
241
+ effect_agent_checkpoints: ["thread_id", "through_sequence", "tail_digest", "checkpoint_json"],
242
+ effect_agent_submissions: [
243
+ "submission_id",
244
+ "thread_id",
245
+ "queue_sequence",
246
+ "principal",
247
+ "idempotency_key",
248
+ "agent_id",
249
+ "agent_digests_json",
250
+ "deployment_id",
251
+ "input_json",
252
+ "input_digest",
253
+ "receipt_id",
254
+ "state",
255
+ "settled_outcome",
256
+ "created_at",
257
+ "ready_at",
258
+ "input_applied_record_id",
259
+ "input_applied_sequence",
260
+ "joined_host_submission_id",
261
+ "suspended_reason_json",
262
+ "suspended_at",
263
+ "unknown_reason",
264
+ "unknown_tool_call_ids_json",
265
+ "parent_submission_id",
266
+ "parent_tool_call_id",
267
+ "admission_group",
268
+ "admission_fence_json",
269
+ ],
270
+ effect_agent_submission_ownership: [
271
+ "submission_id",
272
+ "attempt_id",
273
+ "ownership_token",
274
+ "producer_epoch",
275
+ "owner_producer_id",
276
+ "lease_expires_at",
277
+ ],
278
+ effect_agent_attempts: [
279
+ "attempt_id",
280
+ "submission_id",
281
+ "thread_id",
282
+ "owner_producer_id",
283
+ "producer_epoch",
284
+ "claimed_at",
285
+ ],
286
+ effect_agent_settlement_reservations: [
287
+ "submission_id",
288
+ "settlement_id",
289
+ "outcome",
290
+ "record_id",
291
+ "record_json",
292
+ "record_digest",
293
+ "reserved_at",
294
+ "finalized_at",
295
+ ],
296
+ effect_agent_abort_intents: [
297
+ "submission_id",
298
+ "author",
299
+ "reason",
300
+ "requested_at",
301
+ "canonical_record_id",
302
+ ],
303
+ effect_agent_approval_decisions: [
304
+ "submission_id",
305
+ "tool_call_id",
306
+ "decision",
307
+ "resolver",
308
+ "reason",
309
+ "decided_at",
310
+ ],
311
+ effect_agent_unknown_resolutions: [
312
+ "submission_id",
313
+ "tool_call_id",
314
+ "author",
315
+ "reason",
316
+ "resolution_json",
317
+ "resolved_at",
318
+ ],
319
+ effect_agent_child_reservations: [
320
+ "reservation_id",
321
+ "parent_submission_id",
322
+ "parent_tool_call_id",
323
+ "child_submission_id",
324
+ "status",
325
+ "allocation_json",
326
+ "allocation_digest",
327
+ "accounting_json",
328
+ "reserved_at",
329
+ "release_began_at",
330
+ "released_at",
331
+ ],
332
+ effect_agent_schedules: [
333
+ "tenant_id",
334
+ "owner_id",
335
+ "schedule_id",
336
+ "deadline_at_millis",
337
+ "record_json",
338
+ ],
339
+ effect_agent_subscription_sequences: [
340
+ "tenant_id",
341
+ "source_address",
342
+ "sequence",
343
+ "event_scan_cursor",
344
+ "delivery_scan_cursor",
345
+ "recovery_scan_cursor",
346
+ ],
347
+ effect_agent_subscriptions: [
348
+ "tenant_id",
349
+ "source_address",
350
+ "owner_id",
351
+ "subscription_id",
352
+ "ordinal",
353
+ "source_name",
354
+ "source_version",
355
+ "matching_key",
356
+ "state",
357
+ "expires_at_millis",
358
+ "recovery_at_millis",
359
+ "recovery_present",
360
+ "record_json",
361
+ ],
362
+ effect_agent_subscription_events: [
363
+ "tenant_id",
364
+ "source_address",
365
+ "event_id",
366
+ "source_name",
367
+ "source_version",
368
+ "matching_key",
369
+ "payload_digest",
370
+ "cutoff",
371
+ "cursor",
372
+ "routing_complete",
373
+ "next_attempt_at_millis",
374
+ "record_json",
375
+ "tombstone",
376
+ ],
377
+ effect_agent_subscription_deliveries: [
378
+ "tenant_id",
379
+ "source_address",
380
+ "owner_id",
381
+ "subscription_id",
382
+ "event_id",
383
+ "delivery_key",
384
+ "state",
385
+ "next_attempt_at_millis",
386
+ "record_json",
387
+ ],
388
+ } as const;
389
+
390
+ const checkPredecessorLayout = Effect.fn("SqliteJournal.checkPredecessorLayout")(function* (
391
+ version: 8 | 9 | 10,
392
+ ) {
393
+ const sql = yield* SqlClient.SqlClient;
394
+
395
+ const messageColumns =
396
+ version === 8
397
+ ? predecessorColumns
398
+ : {
399
+ ...predecessorColumns,
400
+ effect_agent_submissions: [
401
+ ...predecessorColumns.effect_agent_submissions,
402
+ "worker_admission_json",
403
+ "message_admission_json",
404
+ ],
405
+ effect_agent_message_deliveries: [
406
+ "owner_thread_id",
407
+ "message_id",
408
+ "version",
409
+ "state",
410
+ "deadline_at_millis",
411
+ "record_json",
412
+ ],
413
+ };
414
+
415
+ const expectedColumns = {
416
+ ...messageColumns,
417
+ ...(version === 10
418
+ ? {
419
+ effect_agent_recovery_checkpoints: [
420
+ "thread_id",
421
+ "through_sequence",
422
+ "tail_digest",
423
+ "checkpoint_json",
424
+ ],
425
+ }
426
+ : {}),
427
+ };
428
+
429
+ for (const [table, expected] of Object.entries(expectedColumns)) {
430
+ const columns = yield* decodeRows(
431
+ Schema.Array(Schema.Struct({ name: BoundedIdentifier })),
432
+ table,
433
+ "schema",
434
+ yield* sql.unsafe(`PRAGMA table_info(${table})`),
435
+ );
436
+
437
+ const names = new Set<string>(expected);
438
+
439
+ if (columns.length !== names.size || columns.some((column) => !names.has(column.name)))
440
+ return yield* SqliteStorageCompatibilityError.make({
441
+ actualVersion: version,
442
+ supportedVersion: CurrentSqliteStorageVersion,
443
+ message: `The v${version} ${table} columns do not match the supported predecessor; no upgrade was committed.`,
444
+ });
445
+ }
446
+ });
447
+
448
+ export const initializeSqliteJournal = Effect.fn("SqliteJournal.initialize")(function* () {
449
+ const sql = yield* SqlClient.SqlClient;
450
+ const { hit: failpoint } = yield* SqliteStorageFailpoint;
451
+ const { busyTimeout } = yield* SqliteStorageConfig;
452
+
453
+ yield* sql`PRAGMA foreign_keys = ON`.pipe(Effect.mapError(storageError("enable foreign keys")));
454
+ // PRAGMA statements do not accept bound parameters; the value is a schema-validated
455
+ // non-negative integer, never caller-controlled text.
456
+ yield* sql
457
+ .unsafe(`PRAGMA busy_timeout = ${busyTimeout}`)
458
+ .pipe(Effect.mapError(storageError("configure busy timeout")));
459
+
460
+ const journalModeRows = yield* sql<Record<string, unknown>>`PRAGMA journal_mode`.pipe(
461
+ Effect.mapError(storageError("read journal mode")),
462
+ );
463
+
464
+ const journalMode = yield* decodeSingleRow(
465
+ Schema.Array(SqliteJournalModeRow),
466
+ "pragma_journal_mode",
467
+ "singleton",
468
+ journalModeRows,
469
+ );
470
+
471
+ if (journalMode.journal_mode.toLowerCase() !== "wal") {
472
+ return yield* SqliteStorageCompatibilityError.make({
473
+ actualVersion: 0,
474
+ supportedVersion: CurrentSqliteStorageVersion,
475
+ message: `SQLite WAL mode is required; the database reported ${journalMode.journal_mode}.`,
476
+ });
477
+ }
478
+
479
+ const versionRows = yield* sql<Record<string, unknown>>`PRAGMA user_version`.pipe(
480
+ Effect.mapError(storageError("read storage version")),
481
+ );
482
+
483
+ const version = yield* decodeSingleRow(
484
+ Schema.Array(SqliteVersionRow),
485
+ "pragma_user_version",
486
+ "singleton",
487
+ versionRows,
488
+ );
489
+
490
+ // Support the known beta49/beta50 and immediate predecessor formats atomically.
491
+ if (
492
+ version.user_version !== 0 &&
493
+ version.user_version !== 7 &&
494
+ version.user_version !== 8 &&
495
+ version.user_version !== 9 &&
496
+ version.user_version !== 10 &&
497
+ version.user_version !== 11 &&
498
+ version.user_version !== CurrentSqliteStorageVersion
499
+ ) {
500
+ return yield* SqliteStorageCompatibilityError.make({
501
+ actualVersion: version.user_version,
502
+ supportedVersion: CurrentSqliteStorageVersion,
503
+ message:
504
+ `The SQLite file uses unsupported storage version ${version.user_version}; ` +
505
+ `this build supports exactly version ${CurrentSqliteStorageVersion}. ` +
506
+ "Only supported v7, v8, v9, v10 and v11 can be upgraded automatically. Keep the original file and use a compatible library version.",
507
+ });
508
+ }
509
+
510
+ if (
511
+ version.user_version === 7 ||
512
+ version.user_version === 8 ||
513
+ version.user_version === 9 ||
514
+ version.user_version === 10
515
+ ) {
516
+ yield* sql
517
+ .withTransaction(
518
+ Effect.gen(function* () {
519
+ const current = yield* sql<{ user_version: number }>`PRAGMA user_version`;
520
+
521
+ if (current.length === 1 && current[0].user_version === CurrentSqliteStorageVersion)
522
+ return;
523
+ if (
524
+ current.length !== 1 ||
525
+ (current[0].user_version !== 7 &&
526
+ current[0].user_version !== 8 &&
527
+ current[0].user_version !== 9 &&
528
+ current[0].user_version !== 10)
529
+ )
530
+ return yield* SqliteStorageCompatibilityError.make({
531
+ actualVersion: -1,
532
+ supportedVersion: CurrentSqliteStorageVersion,
533
+ message: "Storage version changed while acquiring the upgrade transaction.",
534
+ });
535
+
536
+ const required = yield* sql<{
537
+ name: string;
538
+ }>`SELECT name FROM sqlite_master WHERE type='table' AND name IN (
539
+ 'effect_agent_threads', 'effect_agent_canonical_batches', 'effect_agent_canonical_records',
540
+ 'effect_agent_checkpoints', 'effect_agent_submissions', 'effect_agent_submission_ownership',
541
+ 'effect_agent_attempts', 'effect_agent_settlement_reservations', 'effect_agent_abort_intents',
542
+ 'effect_agent_approval_decisions', 'effect_agent_unknown_resolutions', 'effect_agent_schedules'
543
+ )`;
544
+
545
+ if (required.length !== 12)
546
+ return yield* SqliteStorageCompatibilityError.make({
547
+ actualVersion: current[0].user_version,
548
+ supportedVersion: CurrentSqliteStorageVersion,
549
+ message:
550
+ "The predecessor store is missing required tables; no upgrade was committed.",
551
+ });
552
+
553
+ const recoveryTables =
554
+ yield* sql`SELECT name FROM sqlite_master WHERE type='table' AND name='effect_agent_recovery_checkpoints'`;
555
+
556
+ if (recoveryTables.length !== (current[0].user_version === 10 ? 1 : 0))
557
+ return yield* SqliteStorageCompatibilityError.make({
558
+ actualVersion: current[0].user_version,
559
+ supportedVersion: CurrentSqliteStorageVersion,
560
+ message:
561
+ "The predecessor recovery checkpoint storage does not match its version; refusing ambiguous data without mutation.",
562
+ });
563
+
564
+ const indexes =
565
+ yield* sql`SELECT name FROM sqlite_master WHERE name='effect_agent_submissions_nonterminal'`;
566
+
567
+ if (indexes.length !== 0)
568
+ return yield* SqliteStorageCompatibilityError.make({
569
+ actualVersion: current[0].user_version,
570
+ supportedVersion: CurrentSqliteStorageVersion,
571
+ message:
572
+ "The predecessor already contains the nonterminal index; refusing ambiguous storage without mutation.",
573
+ });
574
+ if (current[0].user_version === 7) {
575
+ yield* checkV2ThreadLayout();
576
+ for (const statement of [
577
+ sql`ALTER TABLE effect_agent_submissions ADD COLUMN admission_group TEXT`,
578
+ sql`ALTER TABLE effect_agent_submissions ADD COLUMN admission_fence_json TEXT`,
579
+ sql`CREATE INDEX effect_agent_submissions_group ON effect_agent_submissions (thread_id, admission_group, state)`,
580
+ ]) {
581
+ yield* failpoint("upgrade:before-mutation");
582
+ yield* statement;
583
+ yield* failpoint("upgrade:after-mutation");
584
+ }
585
+ yield* upgradeV2Schedules(16 * 1024 * 1024).pipe(
586
+ Effect.provideService(ScheduleFailpoint, {
587
+ hit: (point) =>
588
+ Schema.decodeUnknownEffect(SqliteStorageFailpointLocation)(point).pipe(
589
+ Effect.flatMap(failpoint),
590
+ Effect.mapError(() => ScheduleFailpointError.make({ point })),
591
+ ),
592
+ }),
593
+ );
594
+ yield* upgradeV2Subscriptions(16 * 1024 * 1024).pipe(
595
+ Effect.provideService(SubscriptionFailpoint, {
596
+ hit: (point) =>
597
+ Schema.decodeUnknownEffect(SqliteStorageFailpointLocation)(point).pipe(
598
+ Effect.flatMap(failpoint),
599
+ Effect.mapError(() => SubscriptionFailpointError.make({ point })),
600
+ ),
601
+ }),
602
+ );
603
+ }
604
+ if (
605
+ current[0].user_version === 8 ||
606
+ current[0].user_version === 9 ||
607
+ current[0].user_version === 10
608
+ )
609
+ yield* checkPredecessorLayout(current[0].user_version);
610
+ if (current[0].user_version === 7 || current[0].user_version === 8) {
611
+ yield* failpoint("upgrade:before-mutation");
612
+ yield* sql`ALTER TABLE effect_agent_submissions ADD COLUMN worker_admission_json TEXT`;
613
+ yield* failpoint("upgrade:after-mutation");
614
+ yield* failpoint("upgrade:before-mutation");
615
+ yield* sql`ALTER TABLE effect_agent_submissions ADD COLUMN message_admission_json TEXT`;
616
+ yield* failpoint("upgrade:after-mutation");
617
+ yield* failpoint("upgrade:before-mutation");
618
+ yield* createMessageDeliveryTables;
619
+ yield* failpoint("upgrade:after-mutation");
620
+ }
621
+ if (current[0].user_version !== 10) {
622
+ yield* failpoint("upgrade:before-mutation");
623
+ yield* createRecoveryCheckpointTable;
624
+ yield* failpoint("upgrade:after-mutation");
625
+ }
626
+ yield* failpoint("upgrade:before-mutation");
627
+ yield* createNonterminalIndex;
628
+ yield* failpoint("upgrade:after-mutation");
629
+ yield* failpoint("upgrade:before-version");
630
+ yield* createNativeReadIndexes;
631
+ yield* createMessageDeliveryPendingIndex;
632
+ yield* seedNativeReadIndexes.pipe(
633
+ Effect.catchTag("ThreadStoreError", (error) =>
634
+ SqliteStorageCorruptionError.make({
635
+ table: "effect_agent_canonical_records",
636
+ rowKey: "upgrade",
637
+ message: error.message,
638
+ }),
639
+ ),
640
+ );
641
+ yield* sql`PRAGMA user_version = 12`;
642
+ yield* failpoint("upgrade:after-version");
643
+ }),
644
+ )
645
+ .pipe(
646
+ Effect.provide(NodeCrypto.layer),
647
+ Effect.catchTag("SqliteStorageFailpointError", (error) =>
648
+ SqliteStorageError.make({
649
+ cause: error,
650
+ operation: "upgrade storage",
651
+ message: error.message,
652
+ }),
653
+ ),
654
+ Effect.catchTag(["ScheduleFailpointError", "SubscriptionFailpointError"], (error) =>
655
+ SqliteStorageError.make({
656
+ cause: error,
657
+ operation: "upgrade storage",
658
+ message: "Injected storage upgrade failure",
659
+ }),
660
+ ),
661
+ Effect.catchTag("StorageUpgradeError", (error) =>
662
+ SqliteStorageCorruptionError.make({
663
+ table: error.table,
664
+ rowKey: error.rowKey,
665
+ message: error.message,
666
+ }),
667
+ ),
668
+ Effect.catchTag("SqlError", storageError("upgrade supported storage")),
669
+ Effect.catchTag("SchemaError", (error) =>
670
+ SqliteStorageCorruptionError.make({
671
+ table: "upgrade",
672
+ rowKey: "v7",
673
+ message: error.message,
674
+ }),
675
+ ),
676
+ );
677
+ }
678
+
679
+ if (version.user_version === 0) {
680
+ const existingRows = yield* sql<Record<string, unknown>>`
681
+ SELECT name
682
+ FROM sqlite_master
683
+ WHERE type = 'table'
684
+ AND name LIKE 'effect_agent_%'
685
+ ORDER BY name
686
+ `.pipe(Effect.mapError(storageError("inspect unversioned storage")));
687
+
688
+ const existing = yield* decodeRows(
689
+ Schema.Array(SqliteNameRow),
690
+ "sqlite_master",
691
+ "effect_agent_%",
692
+ existingRows,
693
+ );
694
+
695
+ if (existing.length > 0) {
696
+ return yield* SqliteStorageCompatibilityError.make({
697
+ actualVersion: 0,
698
+ supportedVersion: CurrentSqliteStorageVersion,
699
+ message:
700
+ "The SQLite file contains unversioned Effect Agent tables. Refusing to mutate ambiguous stored data; retain it for inspection with its original writer.",
701
+ });
702
+ }
703
+
704
+ yield* SqliteMigrator.run({ loader: sqliteMigrations }).pipe(
705
+ Effect.mapError((error) =>
706
+ SqliteStorageError.make({
707
+ cause: error,
708
+ operation: "initialize current storage",
709
+ message: error.message,
710
+ }),
711
+ ),
712
+ );
713
+ }
714
+
715
+ if (version.user_version === 11) {
716
+ yield* sql
717
+ .withTransaction(
718
+ Effect.gen(function* () {
719
+ const current = yield* sql<{ user_version: number }>`PRAGMA user_version`;
720
+
721
+ if (current[0]?.user_version === 12) return;
722
+ if (current[0]?.user_version !== 11)
723
+ return yield* SqliteStorageCompatibilityError.make({
724
+ actualVersion: current[0]?.user_version ?? -1,
725
+ supportedVersion: 12,
726
+ message: "Storage version changed during native index upgrade",
727
+ });
728
+ yield* checkPredecessorLayout(10);
729
+
730
+ const requiredIndex =
731
+ yield* sql`SELECT name FROM sqlite_master WHERE type = 'index' AND name = 'effect_agent_submissions_nonterminal'`;
732
+
733
+ if (requiredIndex.length !== 1)
734
+ return yield* SqliteStorageCompatibilityError.make({
735
+ actualVersion: 11,
736
+ supportedVersion: 12,
737
+ message: "Predecessor storage is missing its required nonterminal index",
738
+ });
739
+ yield* failpoint("upgrade:before-mutation");
740
+ yield* createNativeReadIndexes;
741
+ yield* createMessageDeliveryPendingIndex;
742
+ yield* seedNativeReadIndexes.pipe(
743
+ Effect.catchTag("ThreadStoreError", (error) =>
744
+ SqliteStorageCorruptionError.make({
745
+ table: "effect_agent_canonical_records",
746
+ rowKey: "upgrade",
747
+ message: error.message,
748
+ }),
749
+ ),
750
+ );
751
+ yield* failpoint("upgrade:after-mutation");
752
+ yield* failpoint("upgrade:before-version");
753
+ yield* sql`PRAGMA user_version = 12`;
754
+ yield* failpoint("upgrade:after-version");
755
+ }),
756
+ )
757
+ .pipe(
758
+ Effect.mapError((error) =>
759
+ SqliteStorageError.make({
760
+ operation: "upgrade native indexes",
761
+ message: error.message,
762
+ cause: error,
763
+ }),
764
+ ),
765
+ );
766
+ }
767
+
768
+ const requiredRows = yield* sql<Record<string, unknown>>`
769
+ SELECT name
770
+ FROM sqlite_master
771
+ WHERE (type = 'table'
772
+ AND name IN (
773
+ 'effect_agent_threads',
774
+ 'effect_agent_canonical_batches',
775
+ 'effect_agent_canonical_records',
776
+ 'effect_agent_checkpoints',
777
+ 'effect_agent_submissions',
778
+ 'effect_agent_submission_ownership',
779
+ 'effect_agent_attempts',
780
+ 'effect_agent_settlement_reservations',
781
+ 'effect_agent_abort_intents',
782
+ 'effect_agent_approval_decisions',
783
+ 'effect_agent_unknown_resolutions',
784
+ 'effect_agent_schedules',
785
+ 'effect_agent_message_deliveries',
786
+ 'effect_agent_recovery_checkpoints'
787
+ )) OR (type = 'index' AND name IN ('effect_agent_submissions_nonterminal', 'effect_agent_records_subtree', 'effect_agent_message_deliveries_pending', 'effect_agent_records_outstanding', 'effect_agent_records_call', 'effect_agent_records_run_input', 'effect_agent_records_worker_input'))
788
+ ORDER BY name
789
+ `.pipe(Effect.mapError(storageError("verify storage tables")));
790
+
791
+ const required = yield* decodeRows(
792
+ Schema.Array(SqliteNameRow),
793
+ "sqlite_master",
794
+ "required_tables",
795
+ requiredRows,
796
+ );
797
+
798
+ if (required.length !== 21) {
799
+ return yield* SqliteStorageCompatibilityError.make({
800
+ actualVersion: CurrentSqliteStorageVersion,
801
+ supportedVersion: CurrentSqliteStorageVersion,
802
+ message:
803
+ "The SQLite file claims the current format but is missing required tables or its nonterminal index. Retain the original store for inspection.",
804
+ });
805
+ }
806
+
807
+ const classifyWriteFailure =
808
+ (operation: string) =>
809
+ (error: SqlError): SqliteStorageError | SqliteWriteContention =>
810
+ error.reason._tag === "LockTimeoutError"
811
+ ? SqliteWriteContention.make({
812
+ cause: error,
813
+ operation,
814
+ message: `Another producer holds the SQLite write lock; ${operation} is safe to retry.`,
815
+ })
816
+ : storageError(operation)(error);
817
+
818
+ /**
819
+ * Runs one journal write transaction under `BEGIN IMMEDIATE`. SQLite's deferred `BEGIN`
820
+ * would let a read-then-write transaction start as a reader and fail with
821
+ * SQLITE_BUSY_SNAPSHOT on upgrade, which `busy_timeout` never retries. Taking the write
822
+ * lock up front keeps cross-owner contention inside the bounded busy retry; a lock
823
+ * timeout is classified as the retryable SqliteWriteContention. A failed `BEGIN` leaves
824
+ * no transaction, so no rollback is attempted for it.
825
+ *
826
+ * Journal write transactions are always top level. Nesting one inside another would
827
+ * deadlock the single-connection client, so new journal operations must not wrap this
828
+ * helper inside another transaction.
829
+ */
830
+ const withWriteTransaction =
831
+ (operation: string) =>
832
+ <A, E>(
833
+ effect: Effect.Effect<A, E>,
834
+ ): Effect.Effect<A, E | SqliteStorageError | SqliteWriteContention> =>
835
+ Effect.uninterruptibleMask((restore) =>
836
+ Effect.scoped(
837
+ Effect.gen(function* () {
838
+ const connection = yield* sql.reserve.pipe(
839
+ Effect.mapError(classifyWriteFailure(operation)),
840
+ );
841
+
842
+ yield* connection
843
+ .executeUnprepared("BEGIN IMMEDIATE", [], undefined)
844
+ .pipe(Effect.mapError(classifyWriteFailure(operation)));
845
+
846
+ const exit = yield* restore(
847
+ Effect.provideService(effect, sql.transactionService, [connection, 0] as const),
848
+ ).pipe(Effect.exit);
849
+
850
+ if (Exit.isSuccess(exit)) {
851
+ yield* connection
852
+ .executeUnprepared("COMMIT", [], undefined)
853
+ .pipe(Effect.mapError(classifyWriteFailure(operation)));
854
+
855
+ return exit.value;
856
+ }
857
+ yield* Effect.orDie(connection.executeUnprepared("ROLLBACK", [], undefined));
858
+
859
+ return yield* exit;
860
+ }),
861
+ ).pipe(
862
+ Effect.withSpan("SqliteJournal.withWriteTransaction", { attributes: { operation } }),
863
+ ),
864
+ );
865
+
866
+ /**
867
+ * Runs a read-only snapshot under a deferred transaction. Effect's SQLite client now
868
+ * starts every writable-client `withTransaction` with `BEGIN IMMEDIATE`, which is the
869
+ * right default for mutations but would make exports take the write lock and block a
870
+ * concurrent append. Reserving the connection and beginning explicitly preserves the
871
+ * adapter's snapshot-with-concurrent-writer contract. As with the write helper, a failed
872
+ * `BEGIN` is reported directly because there is no transaction to roll back.
873
+ */
874
+ const withReadTransaction =
875
+ (operation: string) =>
876
+ <A, E>(effect: Effect.Effect<A, E>): Effect.Effect<A, E | SqliteStorageError> =>
877
+ Effect.uninterruptibleMask((restore) =>
878
+ Effect.scoped(
879
+ Effect.gen(function* () {
880
+ const connection = yield* sql.reserve.pipe(Effect.mapError(storageError(operation)));
881
+
882
+ yield* connection
883
+ .executeUnprepared("BEGIN", [], undefined)
884
+ .pipe(Effect.mapError(storageError(operation)));
885
+
886
+ const exit = yield* restore(
887
+ Effect.provideService(effect, sql.transactionService, [connection, 0] as const),
888
+ ).pipe(Effect.exit);
889
+
890
+ if (Exit.isSuccess(exit)) {
891
+ yield* connection
892
+ .executeUnprepared("COMMIT", [], undefined)
893
+ .pipe(Effect.mapError(storageError(operation)));
894
+
895
+ return exit.value;
896
+ }
897
+ yield* Effect.orDie(connection.executeUnprepared("ROLLBACK", [], undefined));
898
+
899
+ return yield* exit;
900
+ }),
901
+ ).pipe(Effect.withSpan("SqliteJournal.withReadTransaction", { attributes: { operation } })),
902
+ );
903
+
904
+ const materialize = Effect.fn("SqliteJournal.materialize")(function* (
905
+ threadId: string,
906
+ createdAt: string,
907
+ emptyTailDigest: string,
908
+ producerEpoch: ProducerEpoch,
909
+ ): Effect.fn.Return<
910
+ void,
911
+ SqliteFenceRejected | SqliteStorageCorruptionError | SqliteStorageError | SqliteWriteContention
912
+ > {
913
+ if (
914
+ threadId.length > MAX_IDENTIFIER_LENGTH ||
915
+ storedTextBytes(emptyTailDigest) > MAX_STORED_TEXT_BYTES
916
+ ) {
917
+ return yield* SqliteStorageError.make({
918
+ operation: "materialize thread",
919
+ message: "Thread identity or initial digest exceeds the SQLite storage bounds.",
920
+ });
921
+ }
922
+ yield* withWriteTransaction("materialize transaction")(
923
+ Effect.gen(function* () {
924
+ const existingRows = yield* sql<Record<string, unknown>>`
925
+ SELECT
926
+ thread_id,
927
+ created_at,
928
+ tail_sequence,
929
+ tail_digest,
930
+ producer_epoch
931
+ FROM effect_agent_threads
932
+ WHERE thread_id = ${threadId}
933
+ `.pipe(Effect.mapError(storageError("read materialized thread")));
934
+
935
+ const existing = yield* decodeRows(
936
+ Schema.Array(ThreadRow),
937
+ "effect_agent_threads",
938
+ threadId,
939
+ existingRows,
940
+ );
941
+
942
+ if (existing.length > 1) {
943
+ return yield* SqliteStorageCorruptionError.make({
944
+ table: "effect_agent_threads",
945
+ rowKey: threadId,
946
+ message: "A thread primary key returned more than one row.",
947
+ });
948
+ }
949
+ if (existing.length === 0) {
950
+ yield* sql`
951
+ INSERT INTO effect_agent_threads (
952
+ thread_id,
953
+ created_at,
954
+ tail_sequence,
955
+ tail_digest,
956
+ producer_epoch
957
+ ) VALUES (
958
+ ${threadId},
959
+ ${createdAt},
960
+ 0,
961
+ ${emptyTailDigest},
962
+ ${producerEpoch}
963
+ )
964
+ `.pipe(Effect.mapError(storageError("materialize thread")));
965
+
966
+ return;
967
+ }
968
+ if (producerEpoch < existing[0].producer_epoch) {
969
+ return yield* SqliteFenceRejected.make({
970
+ producerEpoch,
971
+ actualEpoch: existing[0].producer_epoch,
972
+ message: `Producer epoch ${producerEpoch} is stale; current epoch is ${existing[0].producer_epoch}.`,
973
+ });
974
+ }
975
+ if (producerEpoch > existing[0].producer_epoch) {
976
+ yield* sql`
977
+ UPDATE effect_agent_threads
978
+ SET producer_epoch = ${producerEpoch}
979
+ WHERE thread_id = ${threadId}
980
+ `.pipe(Effect.mapError(storageError("advance materialization epoch")));
981
+ }
982
+ }),
983
+ );
984
+ });
985
+
986
+ const getThread = Effect.fn("SqliteJournal.getThread")(function* (threadId: string) {
987
+ const rows = yield* sql<Record<string, unknown>>`
988
+ SELECT
989
+ thread_id,
990
+ created_at,
991
+ tail_sequence,
992
+ tail_digest,
993
+ producer_epoch
994
+ FROM effect_agent_threads
995
+ WHERE thread_id = ${threadId}
996
+ `.pipe(Effect.mapError(storageError("read thread")));
997
+
998
+ return yield* decodeRows(Schema.Array(ThreadRow), "effect_agent_threads", threadId, rows);
999
+ });
1000
+
1001
+ const append = Effect.fn("SqliteJournal.append")(function* (
1002
+ request: RawAppendRequest,
1003
+ ): Effect.fn.Return<RawAppendResult, AppendError> {
1004
+ if (
1005
+ request.threadId.length > MAX_IDENTIFIER_LENGTH ||
1006
+ request.batchId.length > MAX_IDENTIFIER_LENGTH ||
1007
+ storedTextBytes(request.batchJson) > MAX_STORED_TEXT_BYTES ||
1008
+ storedTextBytes(request.batchDigest) > MAX_STORED_TEXT_BYTES ||
1009
+ storedTextBytes(request.tailDigest) > MAX_STORED_TEXT_BYTES ||
1010
+ request.records.some(
1011
+ (record) =>
1012
+ record.recordId.length > MAX_IDENTIFIER_LENGTH ||
1013
+ storedTextBytes(record.recordJson) > MAX_STORED_TEXT_BYTES,
1014
+ )
1015
+ ) {
1016
+ return yield* SqliteStorageError.make({
1017
+ operation: "append canonical batch",
1018
+ message: "Canonical identifiers or encoded JSON exceed the SQLite storage bounds.",
1019
+ });
1020
+ }
1021
+
1022
+ return yield* withWriteTransaction("append transaction")(
1023
+ Effect.gen(function* () {
1024
+ const recordIds = request.records.map((record) => record.recordId);
1025
+
1026
+ if (new Set(recordIds).size !== recordIds.length) {
1027
+ return yield* SqliteAppendConflict.make({
1028
+ message: `Batch ${request.batchId} contains duplicate canonical record IDs.`,
1029
+ reason: "record-identity",
1030
+ });
1031
+ }
1032
+
1033
+ const threadRows = yield* sql<Record<string, unknown>>`
1034
+ SELECT
1035
+ thread_id,
1036
+ created_at,
1037
+ tail_sequence,
1038
+ tail_digest,
1039
+ producer_epoch
1040
+ FROM effect_agent_threads
1041
+ WHERE thread_id = ${request.threadId}
1042
+ `.pipe(Effect.mapError(storageError("read append tail")));
1043
+
1044
+ const thread = yield* decodeSingleRow(
1045
+ Schema.Array(ThreadRow),
1046
+ "effect_agent_threads",
1047
+ request.threadId,
1048
+ threadRows,
1049
+ );
1050
+
1051
+ if (request.producerEpoch !== thread.producer_epoch) {
1052
+ return yield* SqliteFenceRejected.make({
1053
+ producerEpoch: request.producerEpoch,
1054
+ actualEpoch: thread.producer_epoch,
1055
+ message: `Producer epoch ${request.producerEpoch} is not the current epoch ${thread.producer_epoch}.`,
1056
+ });
1057
+ }
1058
+
1059
+ const batchRows = yield* sql<Record<string, unknown>>`
1060
+ SELECT
1061
+ thread_id,
1062
+ batch_id,
1063
+ first_sequence,
1064
+ last_sequence,
1065
+ batch_digest,
1066
+ tail_digest,
1067
+ batch_json
1068
+ FROM effect_agent_canonical_batches
1069
+ WHERE thread_id = ${request.threadId}
1070
+ AND batch_id = ${request.batchId}
1071
+ `.pipe(Effect.mapError(storageError("read idempotent batch")));
1072
+
1073
+ const batches = yield* decodeRows(
1074
+ Schema.Array(BatchRow),
1075
+ "effect_agent_canonical_batches",
1076
+ `${request.threadId}/${request.batchId}`,
1077
+ batchRows,
1078
+ );
1079
+
1080
+ if (batches.length > 1) {
1081
+ return yield* SqliteStorageCorruptionError.make({
1082
+ table: "effect_agent_canonical_batches",
1083
+ rowKey: `${request.threadId}/${request.batchId}`,
1084
+ message: "A canonical batch primary key returned more than one row.",
1085
+ });
1086
+ }
1087
+ if (batches.length === 1) {
1088
+ const existing = batches[0];
1089
+
1090
+ if (existing.batch_digest !== request.batchDigest) {
1091
+ return yield* SqliteAppendConflict.make({
1092
+ message: `Batch ${request.batchId} already exists with different canonical content.`,
1093
+ reason: "batch-digest",
1094
+ });
1095
+ }
1096
+
1097
+ return RawAppendResult.make({
1098
+ firstSequence: existing.first_sequence,
1099
+ lastSequence: existing.last_sequence,
1100
+ replayed: true,
1101
+ tailDigest: existing.tail_digest,
1102
+ });
1103
+ }
1104
+
1105
+ if (
1106
+ request.expectedTailSequence !== thread.tail_sequence ||
1107
+ request.expectedTailDigest !== thread.tail_digest
1108
+ ) {
1109
+ return yield* SqliteAppendConflict.make({
1110
+ message:
1111
+ `Expected tail ${request.expectedTailSequence}/${request.expectedTailDigest} ` +
1112
+ `but found ${thread.tail_sequence}/${thread.tail_digest}.`,
1113
+ reason: "tail",
1114
+ actualTailSequence: thread.tail_sequence,
1115
+ actualTailDigest: thread.tail_digest,
1116
+ });
1117
+ }
1118
+ if (thread.tail_sequence + request.records.length > MAX_RECORDS_PER_THREAD) {
1119
+ return yield* SqliteStorageError.make({
1120
+ operation: "append canonical batch",
1121
+ message: `Thread record limit ${MAX_RECORDS_PER_THREAD} would be exceeded.`,
1122
+ });
1123
+ }
1124
+
1125
+ const existingRecordRows = yield* sql<Record<string, unknown>>`
1126
+ SELECT
1127
+ thread_id,
1128
+ sequence,
1129
+ record_id,
1130
+ batch_id,
1131
+ record_json
1132
+ FROM effect_agent_canonical_records
1133
+ WHERE thread_id = ${request.threadId}
1134
+ AND record_id IN ${sql.in(recordIds)}
1135
+ ORDER BY sequence
1136
+ `.pipe(Effect.mapError(storageError("check canonical record identities")));
1137
+
1138
+ const existingRecords = yield* decodeRows(
1139
+ Schema.Array(RecordRow),
1140
+ "effect_agent_canonical_records",
1141
+ `${request.threadId}/record_ids`,
1142
+ existingRecordRows,
1143
+ );
1144
+
1145
+ if (existingRecords.length > 0) {
1146
+ return yield* SqliteAppendConflict.make({
1147
+ message: `Canonical record ID ${existingRecords[0].record_id} already exists.`,
1148
+ reason: "record-identity",
1149
+ });
1150
+ }
1151
+
1152
+ const firstSequence = yield* Schema.decodeEffect(CanonicalSequence)(
1153
+ thread.tail_sequence + 1,
1154
+ ).pipe(
1155
+ Effect.mapError((error) =>
1156
+ SqliteStorageError.make({
1157
+ cause: error,
1158
+ operation: "append canonical batch",
1159
+ message: error.message,
1160
+ }),
1161
+ ),
1162
+ );
1163
+
1164
+ const lastSequence = yield* Schema.decodeEffect(CanonicalSequence)(
1165
+ firstSequence + request.records.length - 1,
1166
+ ).pipe(
1167
+ Effect.mapError((error) =>
1168
+ SqliteStorageError.make({
1169
+ cause: error,
1170
+ operation: "append canonical batch",
1171
+ message: error.message,
1172
+ }),
1173
+ ),
1174
+ );
1175
+
1176
+ yield* sql`
1177
+ INSERT INTO effect_agent_canonical_batches (
1178
+ thread_id,
1179
+ batch_id,
1180
+ first_sequence,
1181
+ last_sequence,
1182
+ batch_digest,
1183
+ tail_digest,
1184
+ batch_json
1185
+ ) VALUES (
1186
+ ${request.threadId},
1187
+ ${request.batchId},
1188
+ ${firstSequence},
1189
+ ${lastSequence},
1190
+ ${request.batchDigest},
1191
+ ${request.tailDigest},
1192
+ ${request.batchJson}
1193
+ )
1194
+ `.pipe(Effect.mapError(storageError("insert canonical batch")));
1195
+ yield* failpoint("append:after-batch-insert");
1196
+
1197
+ yield* Effect.forEach(
1198
+ request.records,
1199
+ (record, index) =>
1200
+ Effect.gen(function* () {
1201
+ yield* sql`
1202
+ INSERT INTO effect_agent_canonical_records (
1203
+ thread_id,
1204
+ sequence,
1205
+ record_id,
1206
+ batch_id,
1207
+ record_json
1208
+ ) VALUES (
1209
+ ${request.threadId},
1210
+ ${firstSequence + index},
1211
+ ${record.recordId},
1212
+ ${request.batchId},
1213
+ ${record.recordJson}
1214
+ )
1215
+ `.pipe(Effect.mapError(storageError("insert canonical record")));
1216
+
1217
+ const canonical = yield* Schema.decodeEffect(Schema.fromJsonString(CanonicalRecord))(
1218
+ record.recordJson,
1219
+ ).pipe(
1220
+ Effect.mapError((error) =>
1221
+ SqliteStorageCorruptionError.make({
1222
+ table: "effect_agent_canonical_records",
1223
+ rowKey: record.recordId,
1224
+ message: error.message,
1225
+ }),
1226
+ ),
1227
+ );
1228
+
1229
+ yield* indexCanonicalRecord(request.threadId, canonical).pipe(
1230
+ Effect.provideService(SqlClient.SqlClient, sql),
1231
+ Effect.mapError(storageError("index canonical record")),
1232
+ );
1233
+ yield* failpoint("append:after-record-insert");
1234
+ }),
1235
+ { discard: true },
1236
+ );
1237
+
1238
+ yield* sql`
1239
+ UPDATE effect_agent_threads
1240
+ SET
1241
+ tail_sequence = ${lastSequence},
1242
+ tail_digest = ${request.tailDigest},
1243
+ producer_epoch = ${request.producerEpoch}
1244
+ WHERE thread_id = ${request.threadId}
1245
+ `.pipe(Effect.mapError(storageError("advance thread tail")));
1246
+ yield* failpoint("append:after-tail-update");
1247
+
1248
+ return RawAppendResult.make({
1249
+ firstSequence,
1250
+ lastSequence,
1251
+ replayed: false,
1252
+ tailDigest: request.tailDigest,
1253
+ });
1254
+ }),
1255
+ );
1256
+ });
1257
+
1258
+ const read = Effect.fn("SqliteJournal.read")(function* (request: RawReadRequest) {
1259
+ const rows = yield* sql<Record<string, unknown>>`
1260
+ SELECT
1261
+ thread_id,
1262
+ sequence,
1263
+ record_id,
1264
+ batch_id,
1265
+ record_json
1266
+ FROM effect_agent_canonical_records
1267
+ WHERE thread_id = ${request.threadId}
1268
+ AND sequence > ${request.fromSequenceExclusive}
1269
+ ORDER BY sequence
1270
+ LIMIT ${request.limit}
1271
+ `.pipe(Effect.mapError(storageError("read canonical records")));
1272
+
1273
+ return yield* decodeRows(
1274
+ Schema.Array(RecordRow),
1275
+ "effect_agent_canonical_records",
1276
+ `${request.threadId}>${request.fromSequenceExclusive}`,
1277
+ rows,
1278
+ );
1279
+ });
1280
+
1281
+ const exportThread = Effect.fn("SqliteJournal.exportThread")(function* (threadId: string) {
1282
+ return yield* withReadTransaction("export transaction")(
1283
+ Effect.gen(function* () {
1284
+ const threadRows = yield* sql<Record<string, unknown>>`
1285
+ SELECT
1286
+ thread_id,
1287
+ created_at,
1288
+ tail_sequence,
1289
+ tail_digest,
1290
+ producer_epoch
1291
+ FROM effect_agent_threads
1292
+ WHERE thread_id = ${threadId}
1293
+ `.pipe(Effect.mapError(storageError("export thread")));
1294
+
1295
+ const thread = yield* decodeSingleRow(
1296
+ Schema.Array(ThreadRow),
1297
+ "effect_agent_threads",
1298
+ threadId,
1299
+ threadRows,
1300
+ );
1301
+
1302
+ yield* failpoint("export:after-thread-read");
1303
+
1304
+ if (thread.tail_sequence > MAX_RECORDS_PER_THREAD)
1305
+ return yield* SqliteStorageError.make({
1306
+ operation: "export thread",
1307
+ message: "The thread exceeds the current export record limit.",
1308
+ });
1309
+ const records: Array<RecordRow> = [];
1310
+ let afterSequence = ZERO_SEQUENCE;
1311
+
1312
+ while (afterSequence < thread.tail_sequence) {
1313
+ const limit = Math.min(1_024, thread.tail_sequence - afterSequence);
1314
+
1315
+ const request = RawReadRequest.make({
1316
+ threadId,
1317
+ fromSequenceExclusive: afterSequence,
1318
+ limit,
1319
+ });
1320
+
1321
+ const page = yield* read(request);
1322
+
1323
+ if (
1324
+ page.length !== limit ||
1325
+ page.some((record, index) => record.sequence !== afterSequence + index + 1)
1326
+ ) {
1327
+ return yield* SqliteStorageCorruptionError.make({
1328
+ table: "effect_agent_canonical_records",
1329
+ rowKey: threadId,
1330
+ message: "The exported canonical prefix is not contiguous through its captured tail.",
1331
+ });
1332
+ }
1333
+ records.push(...page);
1334
+ afterSequence = page[page.length - 1].sequence;
1335
+ }
1336
+
1337
+ const beyondTail =
1338
+ yield* sql`SELECT sequence FROM effect_agent_canonical_records WHERE thread_id=${threadId} AND sequence > ${thread.tail_sequence} LIMIT 1`.pipe(
1339
+ Effect.mapError(storageError("verify export tail")),
1340
+ );
1341
+
1342
+ if (beyondTail.length !== 0)
1343
+ return yield* SqliteStorageCorruptionError.make({
1344
+ table: "effect_agent_canonical_records",
1345
+ rowKey: threadId,
1346
+ message: "Canonical records exist beyond the captured thread tail.",
1347
+ });
1348
+
1349
+ return RawThreadExport.make({ thread, records });
1350
+ }),
1351
+ );
1352
+ });
1353
+
1354
+ const saveCheckpoint = Effect.fn("SqliteJournal.saveCheckpoint")(function* (
1355
+ checkpoint: RawCheckpoint,
1356
+ ): Effect.fn.Return<void, CheckpointError> {
1357
+ if (
1358
+ checkpoint.threadId.length > MAX_IDENTIFIER_LENGTH ||
1359
+ storedTextBytes(checkpoint.checkpointJson) > MAX_STORED_TEXT_BYTES
1360
+ ) {
1361
+ return yield* SqliteStorageError.make({
1362
+ operation: "save checkpoint",
1363
+ message: "Checkpoint identity or encoded JSON exceeds the SQLite storage bounds.",
1364
+ });
1365
+ }
1366
+ yield* withWriteTransaction("checkpoint transaction")(
1367
+ Effect.gen(function* () {
1368
+ const threadRows = yield* sql<Record<string, unknown>>`
1369
+ SELECT
1370
+ thread_id,
1371
+ created_at,
1372
+ tail_sequence,
1373
+ tail_digest,
1374
+ producer_epoch
1375
+ FROM effect_agent_threads
1376
+ WHERE thread_id = ${checkpoint.threadId}
1377
+ `.pipe(Effect.mapError(storageError("read checkpoint tail")));
1378
+
1379
+ const thread = yield* decodeSingleRow(
1380
+ Schema.Array(ThreadRow),
1381
+ "effect_agent_threads",
1382
+ checkpoint.threadId,
1383
+ threadRows,
1384
+ );
1385
+
1386
+ if (checkpoint.throughSequence > thread.tail_sequence) {
1387
+ return yield* SqliteCheckpointConflict.make({
1388
+ message:
1389
+ `Checkpoint sequence ${checkpoint.throughSequence} is after canonical tail ` +
1390
+ `${thread.tail_sequence}.`,
1391
+ });
1392
+ }
1393
+
1394
+ const checkpointRows = yield* sql<Record<string, unknown>>`
1395
+ SELECT
1396
+ thread_id,
1397
+ through_sequence,
1398
+ tail_digest,
1399
+ checkpoint_json
1400
+ FROM effect_agent_checkpoints
1401
+ WHERE thread_id = ${checkpoint.threadId}
1402
+ AND through_sequence = ${checkpoint.throughSequence}
1403
+ `.pipe(Effect.mapError(storageError("read idempotent checkpoint")));
1404
+
1405
+ const existing = yield* decodeRows(
1406
+ Schema.Array(CheckpointRow),
1407
+ "effect_agent_checkpoints",
1408
+ `${checkpoint.threadId}/${checkpoint.throughSequence}`,
1409
+ checkpointRows,
1410
+ );
1411
+
1412
+ if (existing.length > 1) {
1413
+ return yield* SqliteStorageCorruptionError.make({
1414
+ table: "effect_agent_checkpoints",
1415
+ rowKey: `${checkpoint.threadId}/${checkpoint.throughSequence}`,
1416
+ message: "A checkpoint primary key returned more than one row.",
1417
+ });
1418
+ }
1419
+ if (existing.length === 1) {
1420
+ if (
1421
+ existing[0].tail_digest !== checkpoint.tailDigest ||
1422
+ existing[0].checkpoint_json !== checkpoint.checkpointJson
1423
+ ) {
1424
+ return yield* SqliteCheckpointConflict.make({
1425
+ message: "A different checkpoint already exists at this canonical sequence.",
1426
+ });
1427
+ }
1428
+
1429
+ return;
1430
+ }
1431
+
1432
+ yield* sql`
1433
+ INSERT INTO effect_agent_checkpoints (
1434
+ thread_id,
1435
+ through_sequence,
1436
+ tail_digest,
1437
+ checkpoint_json
1438
+ ) VALUES (
1439
+ ${checkpoint.threadId},
1440
+ ${checkpoint.throughSequence},
1441
+ ${checkpoint.tailDigest},
1442
+ ${checkpoint.checkpointJson}
1443
+ )
1444
+ `.pipe(Effect.mapError(storageError("insert checkpoint")));
1445
+ }),
1446
+ );
1447
+ });
1448
+
1449
+ const saveRecoveryCheckpoint = Effect.fn("SqliteJournal.saveRecoveryCheckpoint")(function* (
1450
+ request: SaveRecoveryCheckpointRequest,
1451
+ checkpointJson: string,
1452
+ ) {
1453
+ const { checkpoint } = request;
1454
+
1455
+ if (
1456
+ checkpoint.threadId.length > MAX_IDENTIFIER_LENGTH ||
1457
+ storedTextBytes(checkpointJson) > MAX_STORED_TEXT_BYTES
1458
+ ) {
1459
+ return yield* SqliteStorageError.make({
1460
+ operation: "save recovery checkpoint",
1461
+ message: "Checkpoint identity or encoded JSON exceeds the SQLite storage bounds.",
1462
+ });
1463
+ }
1464
+ yield* withWriteTransaction("recovery checkpoint transaction")(
1465
+ Effect.gen(function* () {
1466
+ const threads = yield* getThread(checkpoint.threadId);
1467
+ const thread = threads[0];
1468
+
1469
+ if (thread === undefined)
1470
+ return yield* ThreadNotMaterialized.make({ threadId: checkpoint.threadId });
1471
+ if (request.producerEpoch !== thread.producer_epoch)
1472
+ return yield* FenceRejected.make({
1473
+ threadId: checkpoint.threadId,
1474
+ actualEpoch: thread.producer_epoch,
1475
+ attemptedEpoch: request.producerEpoch,
1476
+ });
1477
+ if (checkpoint.throughSequence > thread.tail_sequence)
1478
+ return yield* CheckpointRejected.make({
1479
+ threadId: checkpoint.threadId,
1480
+ reason: "ahead-of-tail",
1481
+ });
1482
+
1483
+ const digests =
1484
+ checkpoint.throughSequence === 0
1485
+ ? [EMPTY_TAIL_DIGEST]
1486
+ : yield* getTailDigestAt(checkpoint.threadId, checkpoint.throughSequence);
1487
+
1488
+ if (digests.length !== 1 || digests[0] !== checkpoint.tailDigest)
1489
+ return yield* CheckpointRejected.make({
1490
+ threadId: checkpoint.threadId,
1491
+ reason: "digest-mismatch",
1492
+ });
1493
+
1494
+ yield* failpoint("save-recovery-checkpoint:before");
1495
+ yield* sql`
1496
+ INSERT INTO effect_agent_recovery_checkpoints (thread_id, through_sequence, tail_digest, checkpoint_json)
1497
+ VALUES (${checkpoint.threadId}, ${checkpoint.throughSequence}, ${checkpoint.tailDigest}, ${checkpointJson})
1498
+ ON CONFLICT (thread_id) DO UPDATE SET
1499
+ through_sequence = excluded.through_sequence,
1500
+ tail_digest = excluded.tail_digest,
1501
+ checkpoint_json = excluded.checkpoint_json
1502
+ WHERE excluded.through_sequence >= effect_agent_recovery_checkpoints.through_sequence
1503
+ `.pipe(Effect.mapError(storageError("save recovery checkpoint")));
1504
+ }),
1505
+ );
1506
+ yield* failpoint("save-recovery-checkpoint:after");
1507
+ });
1508
+
1509
+ const loadRecoveryCheckpoint = Effect.fn("SqliteJournal.loadRecoveryCheckpoint")(function* (
1510
+ threadId: string,
1511
+ ) {
1512
+ const rows = yield* sql<Record<string, unknown>>`
1513
+ SELECT thread_id, through_sequence, tail_digest, checkpoint_json
1514
+ FROM effect_agent_recovery_checkpoints
1515
+ WHERE thread_id = ${threadId}
1516
+ `.pipe(Effect.mapError(storageError("load recovery checkpoint")));
1517
+
1518
+ return yield* decodeRows(
1519
+ Schema.Array(CheckpointRow),
1520
+ "effect_agent_recovery_checkpoints",
1521
+ threadId,
1522
+ rows,
1523
+ );
1524
+ });
1525
+
1526
+ const loadCheckpoint = Effect.fn("SqliteJournal.loadCheckpoint")(function* (
1527
+ threadId: string,
1528
+ atOrBeforeSequence: CanonicalSequence,
1529
+ ) {
1530
+ const rows = yield* sql<Record<string, unknown>>`
1531
+ SELECT
1532
+ thread_id,
1533
+ through_sequence,
1534
+ tail_digest,
1535
+ checkpoint_json
1536
+ FROM effect_agent_checkpoints
1537
+ WHERE thread_id = ${threadId}
1538
+ AND through_sequence <= ${atOrBeforeSequence}
1539
+ ORDER BY through_sequence DESC
1540
+ LIMIT 1
1541
+ `.pipe(Effect.mapError(storageError("load checkpoint")));
1542
+
1543
+ return yield* decodeRows(
1544
+ Schema.Array(CheckpointRow),
1545
+ "effect_agent_checkpoints",
1546
+ `${threadId}<=${atOrBeforeSequence}`,
1547
+ rows,
1548
+ );
1549
+ });
1550
+
1551
+ const getTailDigestAt = Effect.fn("SqliteJournal.getTailDigestAt")(function* (
1552
+ threadId: string,
1553
+ sequence: CanonicalSequence,
1554
+ ) {
1555
+ if (sequence === 0) {
1556
+ const threads = yield* getThread(threadId);
1557
+
1558
+ return threads.length === 0
1559
+ ? []
1560
+ : [threads[0].tail_sequence === 0 ? threads[0].tail_digest : undefined].filter(
1561
+ (value): value is string => value !== undefined,
1562
+ );
1563
+ }
1564
+
1565
+ const rows = yield* sql<Record<string, unknown>>`
1566
+ SELECT
1567
+ thread_id,
1568
+ batch_id,
1569
+ first_sequence,
1570
+ last_sequence,
1571
+ batch_digest,
1572
+ tail_digest,
1573
+ batch_json
1574
+ FROM effect_agent_canonical_batches
1575
+ WHERE thread_id = ${threadId}
1576
+ AND last_sequence = ${sequence}
1577
+ `.pipe(Effect.mapError(storageError("read canonical digest at sequence")));
1578
+
1579
+ const batches = yield* decodeRows(
1580
+ Schema.Array(BatchRow),
1581
+ "effect_agent_canonical_batches",
1582
+ `${threadId}/${sequence}`,
1583
+ rows,
1584
+ );
1585
+
1586
+ return batches.map((batch) => batch.tail_digest);
1587
+ });
1588
+
1589
+ const scanStoredPayloads = Effect.fn("SqliteJournal.scanStoredPayloads")(function* () {
1590
+ return yield* withReadTransaction("startup scan transaction")(
1591
+ Effect.gen(function* () {
1592
+ const threads = yield* sql<Record<string, unknown>>`
1593
+ SELECT
1594
+ thread_id,
1595
+ created_at,
1596
+ tail_sequence,
1597
+ tail_digest,
1598
+ producer_epoch
1599
+ FROM effect_agent_threads
1600
+ ORDER BY thread_id
1601
+ `.pipe(Effect.mapError(storageError("scan threads")));
1602
+
1603
+ const batches = yield* sql<Record<string, unknown>>`
1604
+ SELECT
1605
+ thread_id,
1606
+ batch_id,
1607
+ first_sequence,
1608
+ last_sequence,
1609
+ batch_digest,
1610
+ tail_digest,
1611
+ batch_json
1612
+ FROM effect_agent_canonical_batches
1613
+ ORDER BY thread_id, first_sequence
1614
+ `.pipe(Effect.mapError(storageError("scan canonical batches")));
1615
+
1616
+ const records = yield* sql<Record<string, unknown>>`
1617
+ SELECT
1618
+ thread_id,
1619
+ sequence,
1620
+ record_id,
1621
+ batch_id,
1622
+ record_json
1623
+ FROM effect_agent_canonical_records
1624
+ ORDER BY thread_id, sequence
1625
+ `.pipe(Effect.mapError(storageError("scan canonical records")));
1626
+
1627
+ const checkpoints = yield* sql<Record<string, unknown>>`
1628
+ SELECT
1629
+ thread_id,
1630
+ through_sequence,
1631
+ tail_digest,
1632
+ checkpoint_json
1633
+ FROM effect_agent_checkpoints
1634
+ ORDER BY thread_id, through_sequence
1635
+ `.pipe(Effect.mapError(storageError("scan checkpoints")));
1636
+
1637
+ return {
1638
+ threads: yield* decodeRows(
1639
+ Schema.Array(ThreadRow),
1640
+ "effect_agent_threads",
1641
+ "startup_scan",
1642
+ threads,
1643
+ ),
1644
+ batches: yield* decodeRows(
1645
+ Schema.Array(BatchRow),
1646
+ "effect_agent_canonical_batches",
1647
+ "startup_scan",
1648
+ batches,
1649
+ ),
1650
+ records: yield* decodeRows(
1651
+ Schema.Array(RecordRow),
1652
+ "effect_agent_canonical_records",
1653
+ "startup_scan",
1654
+ records,
1655
+ ),
1656
+ checkpoints: yield* decodeRows(
1657
+ Schema.Array(CheckpointRow),
1658
+ "effect_agent_checkpoints",
1659
+ "startup_scan",
1660
+ checkpoints,
1661
+ ),
1662
+ };
1663
+ }),
1664
+ );
1665
+ });
1666
+
1667
+ return {
1668
+ append,
1669
+ exportThread,
1670
+ getThread,
1671
+ getTailDigestAt,
1672
+ loadCheckpoint,
1673
+ loadRecoveryCheckpoint,
1674
+ saveRecoveryCheckpoint,
1675
+ materialize,
1676
+ read,
1677
+ saveCheckpoint,
1678
+ scanStoredPayloads,
1679
+ withWriteTransaction,
1680
+ withReadTransaction,
1681
+ } as const;
1682
+ });
1683
+
1684
+ export type SqliteJournal = Effect.Success<ReturnType<typeof initializeSqliteJournal>>;