@effect-agent/storage-sqlite 0.1.0-beta.9 → 0.1.0-beta.91

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 (61) 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 +15 -0
  21. package/dist/SqliteStorageFailpointTesting.mjs +19 -0
  22. package/dist/SqliteStorageFailpointTesting.mjs.map +1 -0
  23. package/dist/SqliteStorageVersion-BqmqX0CI.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 +1788 -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 +460 -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-Dy5v0HGe.mjs +346 -0
  39. package/dist/migrations-Dy5v0HGe.mjs.map +1 -0
  40. package/dist/rolldown-runtime-D7D4PA-g.mjs +13 -0
  41. package/dist/sqlite-journal-CBOQDySe.mjs +998 -0
  42. package/dist/sqlite-journal-CBOQDySe.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} +912 -212
  53. package/src/SqliteSubscriptionStore.ts +55 -0
  54. package/src/SqliteThreadStore.ts +999 -0
  55. package/src/index.ts +10 -6
  56. package/src/internal/message-delivery-schema.ts +24 -0
  57. package/src/{migrations.ts → internal/migrations.ts} +156 -79
  58. package/src/internal/recovery-checkpoint-schema.ts +17 -0
  59. package/src/{sqlite-journal.ts → internal/sqlite-journal.ts} +751 -241
  60. package/dist/index.mjs.map +0 -1
  61. package/src/sqlite-conversation-store.ts +0 -841
@@ -0,0 +1,999 @@
1
+ import { NodeCrypto } from "@effect/platform-node";
2
+ import { SqliteClient } from "@effect/sql-sqlite-node";
3
+ import {
4
+ Clock,
5
+ Context,
6
+ Crypto,
7
+ Duration,
8
+ Effect,
9
+ Layer,
10
+ Option,
11
+ Ref,
12
+ Schema,
13
+ Stream,
14
+ } from "effect";
15
+ import { digestCanonicalBatch, EMPTY_TAIL_DIGEST } from "effect-agent/digest";
16
+ import {
17
+ CanonicalBatch,
18
+ CanonicalRecord,
19
+ CanonicalRecordEnvelope,
20
+ CanonicalSequence,
21
+ Digest,
22
+ ObservationOffset,
23
+ } from "effect-agent/records";
24
+ import { DEFAULT_OWNERSHIP_LEASE_DURATION } from "effect-agent/submission-ledger";
25
+ import {
26
+ AppendConflict,
27
+ AppendResult,
28
+ CheckpointRejected,
29
+ ThreadCheckpoint,
30
+ ThreadExport,
31
+ ThreadExportRequest,
32
+ ThreadMaterialization,
33
+ ThreadNotMaterialized,
34
+ ThreadObservation,
35
+ ThreadRead,
36
+ ThreadStore,
37
+ type ThreadCheckpoints,
38
+ ThreadStoreError,
39
+ ThreadTail,
40
+ ThreadTailRequest,
41
+ FenceRejected,
42
+ FencedAppendRequest,
43
+ LoadCheckpointRequest,
44
+ SaveCheckpointRequest,
45
+ SaveRecoveryCheckpointRequest,
46
+ MAX_THREAD_EXPORT_RECORDS,
47
+ type ThreadRecoveryCheckpoints,
48
+ } from "effect-agent/thread-store";
49
+ import type * as SqlClientService from "effect/unstable/sql/SqlClient";
50
+
51
+ import {
52
+ initializeSqliteJournal,
53
+ RawAppendRequest,
54
+ RawCheckpoint,
55
+ RawReadRequest,
56
+ type SqliteJournal,
57
+ } from "./internal/sqlite-journal.ts";
58
+ import { SqliteStorageConfig, SqliteStorageConfigValue } from "./SqliteStorageConfig.ts";
59
+ import {
60
+ type SqliteStorageCompatibilityError,
61
+ SqliteAppendConflict,
62
+ SqliteCheckpointConflict,
63
+ SqliteFenceRejected,
64
+ type SqliteStorageFailpointLocation,
65
+ SqliteStorageCorruptionError,
66
+ SqliteStorageError,
67
+ } from "./SqliteStorageError.ts";
68
+ import {
69
+ SqliteStorageFailpoint,
70
+ type SqliteStorageFailpointHandler,
71
+ } from "./SqliteStorageFailpoint.ts";
72
+
73
+ export interface SqliteStorageOptions {
74
+ readonly filename: string;
75
+ readonly observationPollInterval?: number | undefined;
76
+ /** Bounded SQLITE_BUSY retry window for write-lock acquisition, in milliseconds. */
77
+ readonly busyTimeout?: number | undefined;
78
+ /**
79
+ * Submission ownership lease duration in milliseconds (D5). Defaults to
80
+ * `DEFAULT_OWNERSHIP_LEASE_DURATION` from `effect-agent/submission-ledger`.
81
+ */
82
+ readonly ownershipLeaseDuration?: number | undefined;
83
+ /**
84
+ * Re-verify every stored payload and digest chain while opening the store. Defaults to
85
+ * off: per-operation Schema decoding and the digest chain already fail clearly on corrupt
86
+ * rows without scanning the whole database on every open.
87
+ */
88
+ readonly verifyOnOpen?: boolean | undefined;
89
+ readonly failpoint?: SqliteStorageFailpointHandler | undefined;
90
+ }
91
+
92
+ export type SqliteStorageInitializationError =
93
+ | SqliteStorageCompatibilityError
94
+ | SqliteStorageCorruptionError
95
+ | SqliteStorageError;
96
+
97
+ const OffsetText = Schema.String.check(Schema.isMaxLength(4 * 1024));
98
+ const SQLITE_OFFSET_PREFIX = "effect-agent-sqlite@1:";
99
+ const ZERO_CANONICAL_SEQUENCE = Schema.decodeSync(CanonicalSequence)(0);
100
+ const isDigest = Schema.is(Digest);
101
+ const isSqliteFenceRejected = Schema.is(SqliteFenceRejected);
102
+ const isSqliteAppendConflict = Schema.is(SqliteAppendConflict);
103
+ const isSqliteCheckpointConflict = Schema.is(SqliteCheckpointConflict);
104
+
105
+ const storeError = (operation: string, error: { readonly message: string }) =>
106
+ ThreadStoreError.make({
107
+ cause: error,
108
+ operation,
109
+ message: error.message,
110
+ });
111
+
112
+ const schemaStoreError = (operation: string, error: { readonly message: string }) =>
113
+ ThreadStoreError.make({
114
+ cause: error,
115
+ operation,
116
+ message: error.message,
117
+ });
118
+
119
+ const makeOffset = Effect.fn("SqliteThreadStore.makeOffset")(function* (
120
+ threadId: ThreadMaterialization["threadId"],
121
+ sequence: number,
122
+ ): Effect.fn.Return<ObservationOffset, ThreadStoreError> {
123
+ return yield* Schema.decodeEffect(CanonicalSequence)(sequence).pipe(
124
+ Effect.flatMap((validatedSequence) =>
125
+ Schema.decodeEffect(ObservationOffset)(
126
+ `${SQLITE_OFFSET_PREFIX}${encodeURIComponent(threadId)}:${validatedSequence}`,
127
+ ),
128
+ ),
129
+ Effect.mapError((error) => schemaStoreError("encode observation offset", error)),
130
+ );
131
+ });
132
+
133
+ const parseOffset = Effect.fn("SqliteThreadStore.parseOffset")(function* (
134
+ threadId: ThreadMaterialization["threadId"],
135
+ offset: ObservationOffset | undefined,
136
+ ): Effect.fn.Return<CanonicalSequence, ThreadStoreError> {
137
+ if (offset === undefined) return ZERO_CANONICAL_SEQUENCE;
138
+
139
+ const text = yield* Schema.decodeEffect(OffsetText)(offset).pipe(
140
+ Effect.mapError((error) => schemaStoreError("decode observation offset", error)),
141
+ );
142
+
143
+ const threadPrefix = `${SQLITE_OFFSET_PREFIX}${encodeURIComponent(threadId)}:`;
144
+
145
+ if (!text.startsWith(threadPrefix)) {
146
+ return yield* ThreadStoreError.make({
147
+ operation: "decode observation offset",
148
+ message: "The observation offset belongs to a different adapter, storage version, or Thread.",
149
+ });
150
+ }
151
+ const sequenceText = text.slice(threadPrefix.length);
152
+
153
+ if (!/^(0|[1-9][0-9]*)$/.test(sequenceText)) {
154
+ return yield* ThreadStoreError.make({
155
+ operation: "decode observation offset",
156
+ message: "The observation offset is malformed.",
157
+ });
158
+ }
159
+
160
+ return yield* Schema.decodeEffect(CanonicalSequence)(Number(sequenceText)).pipe(
161
+ Effect.mapError((error) => schemaStoreError("decode observation offset", error)),
162
+ );
163
+ });
164
+
165
+ const mapFence = (threadId: ThreadMaterialization["threadId"], error: SqliteFenceRejected) =>
166
+ FenceRejected.make({
167
+ threadId,
168
+ actualEpoch: error.actualEpoch,
169
+ attemptedEpoch: error.producerEpoch,
170
+ });
171
+
172
+ const encodeCanonicalRecord = Effect.fn("SqliteThreadStore.encodeCanonicalRecord")(function* (
173
+ record: CanonicalRecord,
174
+ ): Effect.fn.Return<string, ThreadStoreError> {
175
+ return yield* Schema.encodeEffect(Schema.fromJsonString(CanonicalRecord))(record).pipe(
176
+ Effect.mapError((error) => schemaStoreError("encode canonical record", error)),
177
+ );
178
+ });
179
+
180
+ const encodeCanonicalBatch = Effect.fn("SqliteThreadStore.encodeCanonicalBatch")(function* (
181
+ batch: CanonicalBatch,
182
+ ): Effect.fn.Return<string, ThreadStoreError> {
183
+ return yield* Schema.encodeEffect(Schema.fromJsonString(CanonicalBatch))(batch).pipe(
184
+ Effect.mapError((error) => schemaStoreError("encode canonical batch", error)),
185
+ );
186
+ });
187
+
188
+ const encodeCheckpoint = Effect.fn("SqliteThreadStore.encodeCheckpoint")(function* (
189
+ checkpoint: ThreadCheckpoint,
190
+ ): Effect.fn.Return<string, ThreadStoreError> {
191
+ return yield* Schema.encodeEffect(Schema.fromJsonString(ThreadCheckpoint))(checkpoint).pipe(
192
+ Effect.mapError((error) => schemaStoreError("encode checkpoint", error)),
193
+ );
194
+ });
195
+
196
+ const decodeEnvelope = Effect.fn("SqliteThreadStore.decodeEnvelope")(function* (row: {
197
+ readonly batch_id: string;
198
+ readonly thread_id: string;
199
+ readonly record_json: string;
200
+ readonly sequence: CanonicalSequence;
201
+ }) {
202
+ const record = yield* Schema.decodeEffect(Schema.fromJsonString(CanonicalRecord))(
203
+ row.record_json,
204
+ ).pipe(
205
+ Effect.mapError((error) =>
206
+ ThreadStoreError.make({
207
+ operation: "decode canonical record",
208
+ message: error.message,
209
+ }),
210
+ ),
211
+ );
212
+
213
+ const threadId = yield* Schema.decodeEffect(CanonicalRecordEnvelope.fields.threadId)(
214
+ row.thread_id,
215
+ ).pipe(Effect.mapError((error) => schemaStoreError("decode thread identity", error)));
216
+
217
+ const offset = yield* makeOffset(threadId, row.sequence);
218
+
219
+ const batchId = yield* Schema.decodeEffect(CanonicalRecordEnvelope.fields.batchId)(
220
+ row.batch_id,
221
+ ).pipe(Effect.mapError((error) => schemaStoreError("decode batch identity", error)));
222
+
223
+ return CanonicalRecordEnvelope.make({
224
+ threadId,
225
+ batchId,
226
+ sequence: row.sequence,
227
+ offset,
228
+ record,
229
+ });
230
+ });
231
+
232
+ const decodeCheckpoint = Effect.fn("SqliteThreadStore.decodeCheckpoint")(function* (
233
+ checkpointJson: string,
234
+ ): Effect.fn.Return<ThreadCheckpoint, ThreadStoreError> {
235
+ return yield* Schema.decodeEffect(Schema.fromJsonString(ThreadCheckpoint))(checkpointJson).pipe(
236
+ Effect.mapError((error) => schemaStoreError("decode checkpoint", error)),
237
+ );
238
+ });
239
+
240
+ const requireThread = Effect.fn("SqliteThreadStore.requireThread")(function* (
241
+ journal: SqliteJournal,
242
+ threadId: ThreadMaterialization["threadId"],
243
+ ) {
244
+ const rows = yield* journal
245
+ .getThread(threadId)
246
+ .pipe(Effect.mapError((error) => storeError("read thread", error)));
247
+
248
+ if (rows.length === 0) {
249
+ return yield* ThreadNotMaterialized.make({ threadId });
250
+ }
251
+
252
+ return rows[0];
253
+ });
254
+
255
+ const tailDigestAt = Effect.fn("SqliteThreadStore.tailDigestAt")(function* (
256
+ journal: SqliteJournal,
257
+ threadId: ThreadMaterialization["threadId"],
258
+ sequence: CanonicalSequence,
259
+ ) {
260
+ if (sequence === 0) return EMPTY_TAIL_DIGEST;
261
+
262
+ const digests = yield* journal
263
+ .getTailDigestAt(threadId, sequence)
264
+ .pipe(Effect.mapError((error) => storeError("read checkpoint digest", error)));
265
+
266
+ if (digests.length !== 1) {
267
+ return yield* CheckpointRejected.make({
268
+ threadId,
269
+ reason: "digest-mismatch",
270
+ });
271
+ }
272
+
273
+ return yield* Schema.decodeEffect(Digest)(digests[0]).pipe(
274
+ Effect.mapError((error) => schemaStoreError("decode checkpoint digest", error)),
275
+ );
276
+ });
277
+
278
+ const groupByKey = <A>(
279
+ rows: ReadonlyArray<A>,
280
+ key: (row: A) => string,
281
+ ): ReadonlyMap<string, ReadonlyArray<A>> => {
282
+ const grouped = new Map<string, Array<A>>();
283
+
284
+ for (const row of rows) {
285
+ const existing = grouped.get(key(row));
286
+
287
+ if (existing === undefined) {
288
+ grouped.set(key(row), [row]);
289
+ } else {
290
+ existing.push(row);
291
+ }
292
+ }
293
+
294
+ return grouped;
295
+ };
296
+
297
+ /**
298
+ * Opt-in integrity audit (`verifyOnOpen`) of canonical payloads, their digest chains and generic
299
+ * projection checkpoints. Disposable recovery checkpoints are validated when loaded. Routine opens
300
+ * skip this scan: per-operation Schema decoding fails clearly on corrupt canonical rows.
301
+ */
302
+ const decodeStartupPayloads = Effect.fn("SqliteThreadStore.decodeStartupPayloads")(function* (
303
+ journal: SqliteJournal,
304
+ crypto: Crypto.Crypto,
305
+ ) {
306
+ const stored = yield* journal.scanStoredPayloads();
307
+
308
+ const batches = yield* Effect.forEach(stored.batches, (batch) =>
309
+ Schema.decodeEffect(Schema.fromJsonString(CanonicalBatch))(batch.batch_json).pipe(
310
+ Effect.map((decoded) => ({ decoded, row: batch })),
311
+ Effect.mapError((error) =>
312
+ SqliteStorageCorruptionError.make({
313
+ table: "effect_agent_canonical_batches",
314
+ rowKey: `${batch.thread_id}/${batch.batch_id}`,
315
+ message: error.message,
316
+ }),
317
+ ),
318
+ ),
319
+ );
320
+
321
+ const records = yield* Effect.forEach(stored.records, (record) =>
322
+ Schema.decodeEffect(Schema.fromJsonString(CanonicalRecord))(record.record_json).pipe(
323
+ Effect.map((decoded) => ({ decoded, row: record })),
324
+ Effect.mapError((error) =>
325
+ SqliteStorageCorruptionError.make({
326
+ table: "effect_agent_canonical_records",
327
+ rowKey: `${record.thread_id}/${record.sequence}`,
328
+ message: error.message,
329
+ }),
330
+ ),
331
+ ),
332
+ );
333
+
334
+ const checkpoints = yield* Effect.forEach(stored.checkpoints, (checkpoint) =>
335
+ Schema.decodeEffect(Schema.fromJsonString(ThreadCheckpoint))(checkpoint.checkpoint_json).pipe(
336
+ Effect.map((decoded) => ({ decoded, row: checkpoint })),
337
+ Effect.mapError((error) =>
338
+ SqliteStorageCorruptionError.make({
339
+ table: "effect_agent_checkpoints",
340
+ rowKey: `${checkpoint.thread_id}/${checkpoint.through_sequence}`,
341
+ message: error.message,
342
+ }),
343
+ ),
344
+ ),
345
+ );
346
+
347
+ const batchesByThread = groupByKey(batches, ({ row }) => row.thread_id);
348
+ const recordsByThread = groupByKey(records, ({ row }) => row.thread_id);
349
+ const checkpointsByThread = groupByKey(checkpoints, ({ row }) => row.thread_id);
350
+ const materializedIds = new Set(stored.threads.map((thread) => thread.thread_id));
351
+
352
+ for (const thread of stored.threads) {
353
+ const threadBatches = batchesByThread.get(thread.thread_id) ?? [];
354
+ const threadRecords = recordsByThread.get(thread.thread_id) ?? [];
355
+ const threadCheckpoints = checkpointsByThread.get(thread.thread_id) ?? [];
356
+ const recordsByBatch = groupByKey(threadRecords, ({ row }) => row.batch_id);
357
+ let previousDigest = EMPTY_TAIL_DIGEST;
358
+ let expectedSequence = 1;
359
+ const tailDigests = new Map<number, string>([[0, EMPTY_TAIL_DIGEST]]);
360
+
361
+ for (const { decoded: canonicalBatch, row: batchRow } of threadBatches) {
362
+ const key = `${batchRow.thread_id}/${batchRow.batch_id}`;
363
+
364
+ if (
365
+ canonicalBatch.batchId !== batchRow.batch_id ||
366
+ batchRow.first_sequence !== expectedSequence ||
367
+ batchRow.last_sequence !== batchRow.first_sequence + canonicalBatch.records.length - 1
368
+ ) {
369
+ return yield* SqliteStorageCorruptionError.make({
370
+ table: "effect_agent_canonical_batches",
371
+ rowKey: key,
372
+ message: "Canonical batch identity, sequence, or record count is inconsistent.",
373
+ });
374
+ }
375
+
376
+ const digest = yield* digestCanonicalBatch(previousDigest, canonicalBatch).pipe(
377
+ Effect.provideService(Crypto.Crypto, crypto),
378
+ Effect.mapError((error) =>
379
+ SqliteStorageCorruptionError.make({
380
+ table: "effect_agent_canonical_batches",
381
+ rowKey: key,
382
+ message: error.message,
383
+ }),
384
+ ),
385
+ );
386
+
387
+ if (batchRow.batch_digest !== digest || batchRow.tail_digest !== digest) {
388
+ return yield* SqliteStorageCorruptionError.make({
389
+ table: "effect_agent_canonical_batches",
390
+ rowKey: key,
391
+ message: "Canonical batch digest does not match its decoded content and prior tail.",
392
+ });
393
+ }
394
+
395
+ const batchRecords = recordsByBatch.get(batchRow.batch_id) ?? [];
396
+
397
+ if (batchRecords.length !== canonicalBatch.records.length) {
398
+ return yield* SqliteStorageCorruptionError.make({
399
+ table: "effect_agent_canonical_records",
400
+ rowKey: key,
401
+ message: "Canonical batch and record-table counts differ.",
402
+ });
403
+ }
404
+ for (let index = 0; index < canonicalBatch.records.length; index++) {
405
+ const expectedRecord = canonicalBatch.records[index];
406
+ const storedRecord = batchRecords[index];
407
+
408
+ const expectedJson = yield* Schema.encodeEffect(Schema.fromJsonString(CanonicalRecord))(
409
+ expectedRecord,
410
+ ).pipe(
411
+ Effect.mapError((error) =>
412
+ SqliteStorageCorruptionError.make({
413
+ table: "effect_agent_canonical_batches",
414
+ rowKey: key,
415
+ message: error.message,
416
+ }),
417
+ ),
418
+ );
419
+
420
+ const storedJson = yield* Schema.encodeEffect(Schema.fromJsonString(CanonicalRecord))(
421
+ storedRecord.decoded,
422
+ ).pipe(
423
+ Effect.mapError((error) =>
424
+ SqliteStorageCorruptionError.make({
425
+ table: "effect_agent_canonical_records",
426
+ rowKey: `${key}/${storedRecord.row.sequence}`,
427
+ message: error.message,
428
+ }),
429
+ ),
430
+ );
431
+
432
+ if (
433
+ storedRecord.row.sequence !== batchRow.first_sequence + index ||
434
+ storedRecord.row.record_id !== expectedRecord.recordId ||
435
+ expectedJson !== storedJson
436
+ ) {
437
+ return yield* SqliteStorageCorruptionError.make({
438
+ table: "effect_agent_canonical_records",
439
+ rowKey: `${key}/${storedRecord.row.sequence}`,
440
+ message: "Canonical record identity, sequence, or payload differs from its batch.",
441
+ });
442
+ }
443
+ }
444
+
445
+ previousDigest = digest;
446
+ expectedSequence = batchRow.last_sequence + 1;
447
+ tailDigests.set(batchRow.last_sequence, digest);
448
+ }
449
+
450
+ if (
451
+ threadRecords.length !== thread.tail_sequence ||
452
+ thread.tail_sequence !== expectedSequence - 1 ||
453
+ thread.tail_digest !== previousDigest
454
+ ) {
455
+ return yield* SqliteStorageCorruptionError.make({
456
+ table: "effect_agent_threads",
457
+ rowKey: thread.thread_id,
458
+ message: "Thread tail does not match its canonical batch chain.",
459
+ });
460
+ }
461
+
462
+ for (const checkpoint of threadCheckpoints) {
463
+ if (
464
+ checkpoint.decoded.threadId !== thread.thread_id ||
465
+ checkpoint.decoded.throughSequence !== checkpoint.row.through_sequence ||
466
+ checkpoint.decoded.tailDigest !== checkpoint.row.tail_digest ||
467
+ tailDigests.get(checkpoint.row.through_sequence) !== checkpoint.row.tail_digest
468
+ ) {
469
+ return yield* SqliteStorageCorruptionError.make({
470
+ table: "effect_agent_checkpoints",
471
+ rowKey: `${thread.thread_id}/${checkpoint.row.through_sequence}`,
472
+ message: "Checkpoint identity or digest is not bound to a canonical batch tail.",
473
+ });
474
+ }
475
+ }
476
+ }
477
+
478
+ if (
479
+ batches.some(({ row }) => !materializedIds.has(row.thread_id)) ||
480
+ records.some(({ row }) => !materializedIds.has(row.thread_id)) ||
481
+ checkpoints.some(({ row }) => !materializedIds.has(row.thread_id))
482
+ ) {
483
+ return yield* SqliteStorageCorruptionError.make({
484
+ table: "effect_agent_threads",
485
+ rowKey: "startup_scan",
486
+ message: "Canonical rows exist without a materialized Thread.",
487
+ });
488
+ }
489
+ });
490
+
491
+ const makeServices = Effect.fn("SqliteThreadStore.makeServices")(function* () {
492
+ const config = yield* SqliteStorageConfig;
493
+ const failpoint = yield* SqliteStorageFailpoint;
494
+ const crypto = yield* Crypto.Crypto;
495
+ const journal = yield* initializeSqliteJournal();
496
+
497
+ if (config.verifyOnOpen) {
498
+ yield* decodeStartupPayloads(journal, crypto);
499
+ }
500
+
501
+ const provideCrypto = <A, E>(effect: Effect.Effect<A, E, Crypto.Crypto>) =>
502
+ Effect.provideService(effect, Crypto.Crypto, crypto);
503
+
504
+ const hitFailpoint = Effect.fn("SqliteThreadStore.hitFailpoint")(
505
+ (location: SqliteStorageFailpointLocation): Effect.Effect<void, ThreadStoreError> =>
506
+ failpoint
507
+ .hit(location)
508
+ .pipe(Effect.mapError((error) => storeError(`storage failpoint ${location}`, error))),
509
+ );
510
+
511
+ const materialize: ThreadStore["Service"]["materialize"] = Effect.fn(
512
+ "SqliteThreadStore.materialize",
513
+ )(function* (request: ThreadMaterialization) {
514
+ const validated = yield* Schema.decodeEffect(Schema.toType(ThreadMaterialization))(
515
+ request,
516
+ ).pipe(Effect.mapError((error) => schemaStoreError("validate materialization", error)));
517
+
518
+ const now = yield* Clock.currentTimeMillis;
519
+
520
+ yield* hitFailpoint("materialize:before");
521
+ yield* journal
522
+ .materialize(
523
+ validated.threadId,
524
+ new Date(now).toISOString(),
525
+ EMPTY_TAIL_DIGEST,
526
+ validated.producerEpoch,
527
+ )
528
+ .pipe(
529
+ Effect.mapError((error) =>
530
+ error._tag === "SqliteFenceRejected"
531
+ ? mapFence(validated.threadId, error)
532
+ : storeError("materialize thread", error),
533
+ ),
534
+ );
535
+ yield* hitFailpoint("materialize:after");
536
+ });
537
+
538
+ const append: ThreadStore["Service"]["append"] = Effect.fn("SqliteThreadStore.append")(function* (
539
+ request: FencedAppendRequest,
540
+ ) {
541
+ const validated = yield* Schema.decodeEffect(Schema.toType(FencedAppendRequest))(request).pipe(
542
+ Effect.mapError((error) => schemaStoreError("validate canonical append", error)),
543
+ );
544
+
545
+ yield* requireThread(journal, validated.threadId);
546
+
547
+ const tailDigest = yield* provideCrypto(
548
+ digestCanonicalBatch(validated.expectedTailDigest, validated.batch),
549
+ ).pipe(Effect.mapError((error) => storeError("digest canonical append", error)));
550
+
551
+ const batchJson = yield* encodeCanonicalBatch(validated.batch);
552
+
553
+ const rawRecords = yield* Effect.forEach(validated.batch.records, (record) =>
554
+ encodeCanonicalRecord(record).pipe(
555
+ Effect.map((recordJson) => ({
556
+ recordId: record.recordId,
557
+ recordJson,
558
+ })),
559
+ ),
560
+ );
561
+
562
+ const rawRequest = yield* Schema.decodeEffect(RawAppendRequest)({
563
+ threadId: validated.threadId,
564
+ batchId: validated.batch.batchId,
565
+ batchDigest: tailDigest,
566
+ batchJson,
567
+ expectedTailSequence: validated.expectedTailSequence,
568
+ expectedTailDigest: validated.expectedTailDigest,
569
+ producerEpoch: validated.producerEpoch,
570
+ records: rawRecords,
571
+ tailDigest,
572
+ }).pipe(Effect.mapError((error) => schemaStoreError("encode canonical append", error)));
573
+
574
+ yield* hitFailpoint("append:before");
575
+
576
+ const result = yield* journal.append(rawRequest).pipe(
577
+ Effect.mapError((error) => {
578
+ if (isSqliteFenceRejected(error)) {
579
+ return mapFence(validated.threadId, error);
580
+ }
581
+ if (isSqliteAppendConflict(error)) {
582
+ return error.actualTailSequence !== undefined && isDigest(error.actualTailDigest)
583
+ ? AppendConflict.make({
584
+ threadId: validated.threadId,
585
+ batchId: validated.batch.batchId,
586
+ reason: error.reason,
587
+ actualTailSequence: error.actualTailSequence,
588
+ actualTailDigest: error.actualTailDigest,
589
+ })
590
+ : AppendConflict.make({
591
+ threadId: validated.threadId,
592
+ batchId: validated.batch.batchId,
593
+ reason: error.reason,
594
+ });
595
+ }
596
+
597
+ return storeError("append canonical batch", error);
598
+ }),
599
+ Effect.flatMap((result) =>
600
+ Schema.decodeEffect(AppendResult)(result).pipe(
601
+ Effect.mapError((error) => schemaStoreError("decode append result", error)),
602
+ ),
603
+ ),
604
+ );
605
+
606
+ yield* hitFailpoint("append:after");
607
+
608
+ return result;
609
+ });
610
+
611
+ const loadRecords = Effect.fn("SqliteThreadStore.loadRecords")(function* (
612
+ request: RawReadRequest,
613
+ ) {
614
+ const rows = yield* journal
615
+ .read(request)
616
+ .pipe(Effect.mapError((error) => storeError("read canonical records", error)));
617
+
618
+ return yield* Effect.forEach(rows, decodeEnvelope);
619
+ });
620
+
621
+ const readEffect = Effect.fn("SqliteThreadStore.read")(function* (request: ThreadRead) {
622
+ const validated = yield* Schema.decodeEffect(Schema.toType(ThreadRead))(request).pipe(
623
+ Effect.mapError((error) => schemaStoreError("validate thread read", error)),
624
+ );
625
+
626
+ yield* requireThread(journal, validated.threadId);
627
+
628
+ const records = yield* loadRecords(
629
+ RawReadRequest.make({
630
+ threadId: validated.threadId,
631
+ fromSequenceExclusive: validated.afterSequence ?? ZERO_CANONICAL_SEQUENCE,
632
+ limit: validated.limit,
633
+ }),
634
+ );
635
+
636
+ return Stream.fromIterable(records);
637
+ });
638
+
639
+ const read: ThreadStore["Service"]["read"] = (request) => Stream.unwrap(readEffect(request));
640
+
641
+ const observeEffect = Effect.fn("SqliteThreadStore.observe")(function* (
642
+ request: ThreadObservation,
643
+ ) {
644
+ const validated = yield* Schema.decodeEffect(Schema.toType(ThreadObservation))(request).pipe(
645
+ Effect.mapError((error) => schemaStoreError("validate thread observation", error)),
646
+ );
647
+
648
+ yield* requireThread(journal, validated.threadId);
649
+ const initialSequence = yield* parseOffset(validated.threadId, validated.afterOffset);
650
+ const cursor = yield* Ref.make(initialSequence);
651
+
652
+ const poll = Effect.fn("SqliteThreadStore.observePoll")(function* () {
653
+ const fromSequenceExclusive = yield* Ref.get(cursor);
654
+
655
+ const records = yield* loadRecords(
656
+ RawReadRequest.make({
657
+ threadId: validated.threadId,
658
+ fromSequenceExclusive,
659
+ limit: 1_024,
660
+ }),
661
+ );
662
+
663
+ if (records.length === 0) {
664
+ yield* Effect.sleep(config.observationPollInterval);
665
+
666
+ return [];
667
+ }
668
+ yield* Ref.set(cursor, records[records.length - 1].sequence);
669
+
670
+ return records;
671
+ });
672
+
673
+ return Stream.fromIterableEffectRepeat(poll());
674
+ });
675
+
676
+ const observe: ThreadStore["Service"]["observe"] = (request) =>
677
+ Stream.unwrap(observeEffect(request));
678
+
679
+ const exportThread: ThreadStore["Service"]["export"] = Effect.fn("SqliteThreadStore.export")(
680
+ function* (request: ThreadExportRequest) {
681
+ const validated = yield* Schema.decodeEffect(Schema.toType(ThreadExportRequest))(
682
+ request,
683
+ ).pipe(Effect.mapError((error) => schemaStoreError("validate thread export", error)));
684
+
685
+ yield* requireThread(journal, validated.threadId);
686
+
687
+ const exported = yield* journal
688
+ .exportThread(validated.threadId)
689
+ .pipe(Effect.mapError((error) => storeError("export thread", error)));
690
+
691
+ const records = yield* Effect.forEach(exported.records, decodeEnvelope);
692
+
693
+ if (records.length > MAX_THREAD_EXPORT_RECORDS) {
694
+ return yield* ThreadStoreError.make({
695
+ operation: "decode thread export",
696
+ message: "The thread exceeds the current export record limit.",
697
+ });
698
+ }
699
+
700
+ const tailDigest = yield* Schema.decodeEffect(Digest)(exported.thread.tail_digest).pipe(
701
+ Effect.mapError((error) => schemaStoreError("decode export tail digest", error)),
702
+ );
703
+
704
+ return ThreadExport.make({
705
+ format: "effect-agent/thread@1",
706
+ threadId: validated.threadId,
707
+ tailSequence: exported.thread.tail_sequence,
708
+ tailDigest,
709
+ records,
710
+ });
711
+ },
712
+ );
713
+
714
+ const inspectTail: ThreadStore["Service"]["inspectTail"] = Effect.fn(
715
+ "SqliteThreadStore.inspectTail",
716
+ )(function* (request: ThreadTailRequest) {
717
+ const validated = yield* Schema.decodeEffect(Schema.toType(ThreadTailRequest))(request).pipe(
718
+ Effect.mapError((error) => schemaStoreError("validate tail inspection", error)),
719
+ );
720
+
721
+ const thread = yield* requireThread(journal, validated.threadId);
722
+
723
+ const tailDigest = yield* Schema.decodeEffect(Digest)(thread.tail_digest).pipe(
724
+ Effect.mapError((error) => schemaStoreError("decode tail digest", error)),
725
+ );
726
+
727
+ return ThreadTail.make({
728
+ threadId: validated.threadId,
729
+ tailSequence: thread.tail_sequence,
730
+ tailDigest,
731
+ producerEpoch: thread.producer_epoch,
732
+ });
733
+ });
734
+
735
+ const saveCheckpoint: ThreadCheckpoints["save"] = Effect.fn("SqliteThreadStore.saveCheckpoint")(
736
+ function* (request: SaveCheckpointRequest) {
737
+ const validated = yield* Schema.decodeEffect(Schema.toType(SaveCheckpointRequest))(
738
+ request,
739
+ ).pipe(Effect.mapError((error) => schemaStoreError("validate checkpoint", error)));
740
+
741
+ const thread = yield* requireThread(journal, validated.checkpoint.threadId);
742
+
743
+ if (validated.checkpoint.throughSequence > thread.tail_sequence) {
744
+ return yield* CheckpointRejected.make({
745
+ threadId: validated.checkpoint.threadId,
746
+ reason: "ahead-of-tail",
747
+ });
748
+ }
749
+
750
+ const canonicalDigest = yield* tailDigestAt(
751
+ journal,
752
+ validated.checkpoint.threadId,
753
+ validated.checkpoint.throughSequence,
754
+ );
755
+
756
+ if (canonicalDigest !== validated.checkpoint.tailDigest) {
757
+ return yield* CheckpointRejected.make({
758
+ threadId: validated.checkpoint.threadId,
759
+ reason: "digest-mismatch",
760
+ });
761
+ }
762
+ const checkpointJson = yield* encodeCheckpoint(validated.checkpoint);
763
+
764
+ const raw = RawCheckpoint.make({
765
+ threadId: validated.checkpoint.threadId,
766
+ throughSequence: validated.checkpoint.throughSequence,
767
+ tailDigest: validated.checkpoint.tailDigest,
768
+ checkpointJson,
769
+ });
770
+
771
+ yield* hitFailpoint("save-checkpoint:before");
772
+ yield* journal.saveCheckpoint(raw).pipe(
773
+ Effect.mapError((error) =>
774
+ isSqliteCheckpointConflict(error)
775
+ ? CheckpointRejected.make({
776
+ threadId: validated.checkpoint.threadId,
777
+ reason: "digest-mismatch",
778
+ })
779
+ : storeError("save checkpoint", error),
780
+ ),
781
+ );
782
+ yield* hitFailpoint("save-checkpoint:after");
783
+ },
784
+ );
785
+
786
+ const loadCheckpoint: ThreadCheckpoints["load"] = Effect.fn("SqliteThreadStore.loadCheckpoint")(
787
+ function* (request: LoadCheckpointRequest) {
788
+ const validated = yield* Schema.decodeEffect(Schema.toType(LoadCheckpointRequest))(
789
+ request,
790
+ ).pipe(Effect.mapError((error) => schemaStoreError("validate checkpoint lookup", error)));
791
+
792
+ const thread = yield* requireThread(journal, validated.threadId);
793
+
794
+ const rows = yield* journal
795
+ .loadCheckpoint(validated.threadId, validated.atOrBeforeSequence ?? thread.tail_sequence)
796
+ .pipe(Effect.mapError((error) => storeError("load checkpoint", error)));
797
+
798
+ if (rows.length === 0) return Option.none();
799
+ if (rows.length !== 1) {
800
+ return yield* ThreadStoreError.make({
801
+ operation: "load checkpoint",
802
+ message: `Expected at most one checkpoint row but found ${rows.length}.`,
803
+ });
804
+ }
805
+ const row = rows[0];
806
+ const checkpoint = yield* decodeCheckpoint(row.checkpoint_json);
807
+
808
+ if (
809
+ row.thread_id !== validated.threadId ||
810
+ checkpoint.threadId !== row.thread_id ||
811
+ checkpoint.throughSequence !== row.through_sequence ||
812
+ checkpoint.tailDigest !== row.tail_digest
813
+ ) {
814
+ return yield* ThreadStoreError.make({
815
+ operation: "load checkpoint",
816
+ message: "Stored checkpoint metadata does not match its canonical row.",
817
+ });
818
+ }
819
+
820
+ const canonicalDigest = yield* tailDigestAt(
821
+ journal,
822
+ checkpoint.threadId,
823
+ checkpoint.throughSequence,
824
+ );
825
+
826
+ if (canonicalDigest !== checkpoint.tailDigest) {
827
+ return yield* CheckpointRejected.make({
828
+ threadId: checkpoint.threadId,
829
+ reason: "digest-mismatch",
830
+ });
831
+ }
832
+
833
+ return Option.some(checkpoint);
834
+ },
835
+ );
836
+
837
+ const saveRecoveryCheckpoint: ThreadRecoveryCheckpoints["save"] = Effect.fn(
838
+ "SqliteThreadStore.saveRecoveryCheckpoint",
839
+ )(function* (request) {
840
+ const validated = yield* Schema.decodeEffect(Schema.toType(SaveRecoveryCheckpointRequest))(
841
+ request,
842
+ ).pipe(Effect.mapError((error) => schemaStoreError("validate recovery checkpoint", error)));
843
+
844
+ const checkpointJson = yield* encodeCheckpoint(validated.checkpoint);
845
+
846
+ yield* journal
847
+ .saveRecoveryCheckpoint(validated, checkpointJson)
848
+ .pipe(
849
+ Effect.mapError((error) =>
850
+ error._tag === "CheckpointRejected" ||
851
+ error._tag === "FenceRejected" ||
852
+ error._tag === "ThreadNotMaterialized"
853
+ ? error
854
+ : storeError("save recovery checkpoint", error),
855
+ ),
856
+ );
857
+ });
858
+
859
+ const loadRecoveryCheckpoint: ThreadRecoveryCheckpoints["load"] = Effect.fn(
860
+ "SqliteThreadStore.loadRecoveryCheckpoint",
861
+ )(function* (request) {
862
+ const validated = yield* Schema.decodeEffect(Schema.toType(LoadCheckpointRequest))(
863
+ request,
864
+ ).pipe(
865
+ Effect.mapError((error) => schemaStoreError("validate recovery checkpoint lookup", error)),
866
+ );
867
+
868
+ const thread = yield* requireThread(journal, validated.threadId);
869
+
870
+ const corrupt = () =>
871
+ CheckpointRejected.make({ threadId: validated.threadId, reason: "corrupt" });
872
+
873
+ const rows = yield* journal
874
+ .loadRecoveryCheckpoint(validated.threadId)
875
+ .pipe(
876
+ Effect.mapError((error) =>
877
+ error._tag === "SqliteStorageCorruptionError"
878
+ ? corrupt()
879
+ : storeError("load recovery checkpoint", error),
880
+ ),
881
+ );
882
+
883
+ if (rows.length === 0) return Option.none();
884
+ if (rows.length !== 1) return yield* corrupt();
885
+ const row = rows[0];
886
+
887
+ const checkpoint = yield* Schema.decodeEffect(Schema.fromJsonString(ThreadCheckpoint))(
888
+ row.checkpoint_json,
889
+ ).pipe(Effect.mapError(corrupt));
890
+
891
+ if (
892
+ row.thread_id !== validated.threadId ||
893
+ checkpoint.threadId !== row.thread_id ||
894
+ checkpoint.throughSequence !== row.through_sequence ||
895
+ checkpoint.tailDigest !== row.tail_digest
896
+ )
897
+ return yield* corrupt();
898
+ if (checkpoint.throughSequence > thread.tail_sequence)
899
+ return yield* CheckpointRejected.make({
900
+ threadId: validated.threadId,
901
+ reason: "ahead-of-tail",
902
+ });
903
+ if (checkpoint.throughSequence > (validated.atOrBeforeSequence ?? thread.tail_sequence))
904
+ return Option.none();
905
+
906
+ const canonicalDigest = yield* tailDigestAt(
907
+ journal,
908
+ checkpoint.threadId,
909
+ checkpoint.throughSequence,
910
+ );
911
+
912
+ if (canonicalDigest !== checkpoint.tailDigest)
913
+ return yield* CheckpointRejected.make({
914
+ threadId: validated.threadId,
915
+ reason: "digest-mismatch",
916
+ });
917
+
918
+ return Option.some(checkpoint);
919
+ });
920
+
921
+ const threadStore = ThreadStore.of({
922
+ append,
923
+ export: exportThread,
924
+ inspectTail,
925
+ materialize,
926
+ observe,
927
+ read,
928
+ checkpoints: { save: saveCheckpoint, load: loadCheckpoint },
929
+ recoveryCheckpoints: { save: saveRecoveryCheckpoint, load: loadRecoveryCheckpoint },
930
+ });
931
+
932
+ return Context.make(ThreadStore, threadStore);
933
+ });
934
+
935
+ /**
936
+ * SQLite Thread Store implementation with configuration, failpoint, SQL, and Crypto
937
+ * authority kept visible in its input channel.
938
+ */
939
+ export const threadStoreLayer: Layer.Layer<
940
+ ThreadStore,
941
+ SqliteStorageInitializationError,
942
+ SqliteStorageConfig | SqliteStorageFailpoint | SqlClientService.SqlClient | Crypto.Crypto
943
+ > = Layer.effectContext(makeServices());
944
+
945
+ /**
946
+ * Validated SQLite storage configuration Layer with the documented defaults applied. Shared
947
+ * by the ThreadStore and SubmissionLedger convenience layers so their defaults cannot
948
+ * drift.
949
+ */
950
+ export const storageConfigLayer = (
951
+ options: SqliteStorageOptions,
952
+ ): Layer.Layer<SqliteStorageConfig, SqliteStorageError> =>
953
+ Layer.effect(SqliteStorageConfig)(
954
+ Schema.decodeEffect(SqliteStorageConfigValue)({
955
+ observationPollInterval: options.observationPollInterval ?? 25,
956
+ busyTimeout: options.busyTimeout ?? 5_000,
957
+ ownershipLeaseDuration:
958
+ options.ownershipLeaseDuration ?? Duration.toMillis(DEFAULT_OWNERSHIP_LEASE_DURATION),
959
+ verifyOnOpen: options.verifyOnOpen ?? false,
960
+ }).pipe(
961
+ Effect.mapError((error) =>
962
+ SqliteStorageError.make({
963
+ cause: error,
964
+ operation: "configure SQLite storage",
965
+ message: error.message,
966
+ }),
967
+ ),
968
+ ),
969
+ );
970
+
971
+ /** The failpoint Layer selected by convenience options: explicit handler or the no-op default. */
972
+ export const storageFailpointLayer = (
973
+ options: SqliteStorageOptions,
974
+ ): Layer.Layer<SqliteStorageFailpoint> =>
975
+ options.failpoint === undefined
976
+ ? SqliteStorageFailpoint.layer
977
+ : Layer.succeed(SqliteStorageFailpoint)({ hit: options.failpoint });
978
+
979
+ /**
980
+ * A composition-root convenience Layer for canonical Threads. Durable accepted work is
981
+ * served by the separate SubmissionLedger port.
982
+ */
983
+ export const layer = (
984
+ options: SqliteStorageOptions,
985
+ ): Layer.Layer<ThreadStore, SqliteStorageInitializationError> =>
986
+ Layer.unwrap(
987
+ Effect.map(SqliteStorageConfig, (config) =>
988
+ threadStoreLayer.pipe(
989
+ Layer.provide(
990
+ Layer.mergeAll(
991
+ Layer.succeed(SqliteStorageConfig)(config),
992
+ storageFailpointLayer(options),
993
+ SqliteClient.layer({ filename: options.filename }),
994
+ NodeCrypto.layer,
995
+ ),
996
+ ),
997
+ ),
998
+ ),
999
+ ).pipe(Layer.provide(storageConfigLayer(options)));