@effect-agent/storage-sqlite 0.1.0-beta.12 → 0.1.0-beta.120

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-BBmy73KE.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 +1866 -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-BmgwzT68.mjs +365 -0
  39. package/dist/migrations-BmgwzT68.mjs.map +1 -0
  40. package/dist/rolldown-runtime-D7D4PA-g.mjs +13 -0
  41. package/dist/sqlite-journal-DE4MN8uP.mjs +1106 -0
  42. package/dist/sqlite-journal-DE4MN8uP.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} +1105 -240
  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 +373 -0
  58. package/src/internal/recovery-checkpoint-schema.ts +17 -0
  59. package/src/internal/sqlite-journal.ts +1792 -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,1106 @@
1
+ import { SqliteStorageConfig } from "./SqliteStorageConfig.mjs";
2
+ import { SqliteAppendConflict, SqliteCheckpointConflict, SqliteFenceRejected, SqliteStorageCompatibilityError, SqliteStorageCorruptionError, SqliteStorageError, SqliteStorageFailpointLocation, SqliteWriteContention } from "./SqliteStorageError.mjs";
3
+ import { SqliteStorageFailpoint } from "./SqliteStorageFailpoint.mjs";
4
+ import { a as createRecoveryCheckpointTable, i as sqliteMigrations, n as createNonterminalIndex, o as createMessageDeliveryTables, r as createWorkerStops } from "./migrations-BmgwzT68.mjs";
5
+ import { Effect, Exit, Schema } from "effect";
6
+ import { createMessageDeliveryPendingIndex } from "effect-agent/sql-message-delivery-store";
7
+ import * as SqlClient from "effect/unstable/sql/SqlClient";
8
+ import { NodeCrypto } from "@effect/platform-node";
9
+ import { SqliteMigrator } from "@effect/sql-sqlite-node";
10
+ import { EMPTY_TAIL_DIGEST } from "effect-agent/digest";
11
+ import { CanonicalRecord, CanonicalSequence, ProducerEpoch } from "effect-agent/records";
12
+ import { ScheduleFailpoint, ScheduleFailpointError } from "effect-agent/schedule";
13
+ import { checkV2ThreadLayout, upgradeV2Schedules, upgradeV2Subscriptions } from "effect-agent/sql-storage-v2-upgrade";
14
+ import { createNativeReadIndexes, indexCanonicalRecord, seedNativeReadIndexes } from "effect-agent/sql-thread-native-reads";
15
+ import { SubscriptionFailpoint, SubscriptionFailpointError } from "effect-agent/subscription";
16
+ import { CheckpointRejected, FenceRejected, MAX_THREAD_EXPORT_RECORDS, ThreadNotMaterialized } from "effect-agent/thread-store";
17
+ //#region src/internal/sqlite-journal.ts
18
+ const BoundedStoredText = Schema.String.check(Schema.isMaxLength(16777216));
19
+ const BoundedIdentifier = Schema.NonEmptyString.check(Schema.isMaxLength(1024));
20
+ const NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));
21
+ const MAX_RECORDS_PER_THREAD = MAX_THREAD_EXPORT_RECORDS;
22
+ const ZERO_SEQUENCE = Schema.decodeSync(CanonicalSequence)(0);
23
+ const MAX_STORED_TEXT_BYTES = 16777216;
24
+ const MAX_IDENTIFIER_LENGTH = 1024;
25
+ const storedTextBytes = (value) => new TextEncoder().encode(value).byteLength;
26
+ var SqliteVersionRow = class extends Schema.Class("SqliteVersionRow")({ user_version: NonNegativeInt }) {};
27
+ var SqliteJournalModeRow = class extends Schema.Class("SqliteJournalModeRow")({ journal_mode: Schema.NonEmptyString.check(Schema.isMaxLength(32)) }) {};
28
+ var SqliteNameRow = class extends Schema.Class("SqliteNameRow")({ name: BoundedIdentifier }) {};
29
+ var ThreadRow = class extends Schema.Class("ThreadRow")({
30
+ thread_id: BoundedIdentifier,
31
+ created_at: Schema.NonEmptyString.check(Schema.isMaxLength(128)),
32
+ producer_epoch: ProducerEpoch,
33
+ tail_digest: BoundedStoredText,
34
+ tail_sequence: CanonicalSequence
35
+ }) {};
36
+ var BatchRow = class extends Schema.Class("BatchRow")({
37
+ batch_digest: BoundedStoredText,
38
+ batch_id: BoundedIdentifier,
39
+ batch_json: BoundedStoredText,
40
+ thread_id: BoundedIdentifier,
41
+ first_sequence: CanonicalSequence,
42
+ last_sequence: CanonicalSequence,
43
+ tail_digest: BoundedStoredText
44
+ }) {};
45
+ var RecordRow = class extends Schema.Class("RecordRow")({
46
+ batch_id: BoundedIdentifier,
47
+ thread_id: BoundedIdentifier,
48
+ record_id: BoundedIdentifier,
49
+ record_json: BoundedStoredText,
50
+ sequence: CanonicalSequence
51
+ }) {};
52
+ var CheckpointRow = class extends Schema.Class("CheckpointRow")({
53
+ checkpoint_json: BoundedStoredText,
54
+ thread_id: BoundedIdentifier,
55
+ tail_digest: BoundedStoredText,
56
+ through_sequence: CanonicalSequence
57
+ }) {};
58
+ var RawRecord = class extends Schema.Class("@effect-agent/storage-sqlite/RawRecord")({
59
+ recordId: BoundedIdentifier,
60
+ recordJson: BoundedStoredText
61
+ }) {};
62
+ var RawAppendRequest = class extends Schema.Class("@effect-agent/storage-sqlite/RawAppendRequest")({
63
+ batchDigest: BoundedStoredText,
64
+ batchId: BoundedIdentifier,
65
+ batchJson: BoundedStoredText,
66
+ threadId: BoundedIdentifier,
67
+ expectedTailDigest: BoundedStoredText,
68
+ expectedTailSequence: CanonicalSequence,
69
+ producerEpoch: ProducerEpoch,
70
+ records: Schema.NonEmptyArray(RawRecord).check(Schema.isMaxLength(256)),
71
+ tailDigest: BoundedStoredText
72
+ }) {};
73
+ var RawAppendResult = class extends Schema.Class("@effect-agent/storage-sqlite/RawAppendResult")({
74
+ firstSequence: CanonicalSequence,
75
+ lastSequence: CanonicalSequence,
76
+ replayed: Schema.Boolean,
77
+ tailDigest: BoundedStoredText
78
+ }) {};
79
+ var RawReadRequest = class extends Schema.Class("@effect-agent/storage-sqlite/RawReadRequest")({
80
+ threadId: BoundedIdentifier,
81
+ fromSequenceExclusive: CanonicalSequence,
82
+ limit: Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(1024))
83
+ }) {};
84
+ var RawCheckpoint = class extends Schema.Class("@effect-agent/storage-sqlite/RawCheckpoint")({
85
+ checkpointJson: BoundedStoredText,
86
+ threadId: BoundedIdentifier,
87
+ tailDigest: BoundedStoredText,
88
+ throughSequence: CanonicalSequence
89
+ }) {};
90
+ var RawThreadExport = class extends Schema.Class("@effect-agent/storage-sqlite/RawThreadExport")({
91
+ thread: ThreadRow,
92
+ records: Schema.Array(RecordRow)
93
+ }) {};
94
+ const storageError = (operation) => (error) => SqliteStorageError.make({
95
+ cause: error,
96
+ operation,
97
+ message: error.message
98
+ });
99
+ /** Decode raw SQLite rows against a Schema, reporting failures as typed corruption. */
100
+ const decodeRows = Effect.fn("SqliteJournal.decodeRows")((schema, table, rowKey, rows) => Schema.decodeUnknownEffect(schema)(rows).pipe(Effect.mapError((error) => SqliteStorageCorruptionError.make({
101
+ table,
102
+ rowKey,
103
+ message: String(error)
104
+ }))));
105
+ /** Decode exactly one raw SQLite row against a Schema, reporting failures as typed corruption. */
106
+ const decodeSingleRow = Effect.fn("SqliteJournal.decodeSingleRow")((schema, table, rowKey, rows) => decodeRows(schema, table, rowKey, rows).pipe(Effect.flatMap((decoded) => decoded.length === 1 ? Effect.succeed(decoded[0]) : Effect.fail(SqliteStorageCorruptionError.make({
107
+ table,
108
+ rowKey,
109
+ message: `Expected exactly one row but found ${decoded.length}.`
110
+ })))));
111
+ /** Column inventory of the supported v8 predecessor, independent of physical column order. */
112
+ const predecessorColumns = {
113
+ effect_agent_threads: [
114
+ "thread_id",
115
+ "created_at",
116
+ "tail_sequence",
117
+ "tail_digest",
118
+ "producer_epoch"
119
+ ],
120
+ effect_agent_canonical_batches: [
121
+ "thread_id",
122
+ "batch_id",
123
+ "first_sequence",
124
+ "last_sequence",
125
+ "batch_digest",
126
+ "tail_digest",
127
+ "batch_json"
128
+ ],
129
+ effect_agent_canonical_records: [
130
+ "thread_id",
131
+ "sequence",
132
+ "record_id",
133
+ "batch_id",
134
+ "record_json"
135
+ ],
136
+ effect_agent_checkpoints: [
137
+ "thread_id",
138
+ "through_sequence",
139
+ "tail_digest",
140
+ "checkpoint_json"
141
+ ],
142
+ effect_agent_submissions: [
143
+ "submission_id",
144
+ "thread_id",
145
+ "queue_sequence",
146
+ "principal",
147
+ "idempotency_key",
148
+ "agent_id",
149
+ "agent_digests_json",
150
+ "deployment_id",
151
+ "input_json",
152
+ "input_digest",
153
+ "receipt_id",
154
+ "state",
155
+ "settled_outcome",
156
+ "created_at",
157
+ "ready_at",
158
+ "input_applied_record_id",
159
+ "input_applied_sequence",
160
+ "joined_host_submission_id",
161
+ "suspended_reason_json",
162
+ "suspended_at",
163
+ "unknown_reason",
164
+ "unknown_tool_call_ids_json",
165
+ "parent_submission_id",
166
+ "parent_tool_call_id",
167
+ "admission_group",
168
+ "admission_fence_json"
169
+ ],
170
+ effect_agent_submission_ownership: [
171
+ "submission_id",
172
+ "attempt_id",
173
+ "ownership_token",
174
+ "producer_epoch",
175
+ "owner_producer_id",
176
+ "lease_expires_at"
177
+ ],
178
+ effect_agent_attempts: [
179
+ "attempt_id",
180
+ "submission_id",
181
+ "thread_id",
182
+ "owner_producer_id",
183
+ "producer_epoch",
184
+ "claimed_at"
185
+ ],
186
+ effect_agent_settlement_reservations: [
187
+ "submission_id",
188
+ "settlement_id",
189
+ "outcome",
190
+ "record_id",
191
+ "record_json",
192
+ "record_digest",
193
+ "reserved_at",
194
+ "finalized_at"
195
+ ],
196
+ effect_agent_abort_intents: [
197
+ "submission_id",
198
+ "author",
199
+ "reason",
200
+ "requested_at",
201
+ "canonical_record_id"
202
+ ],
203
+ effect_agent_approval_decisions: [
204
+ "submission_id",
205
+ "tool_call_id",
206
+ "decision",
207
+ "resolver",
208
+ "reason",
209
+ "decided_at"
210
+ ],
211
+ effect_agent_unknown_resolutions: [
212
+ "submission_id",
213
+ "tool_call_id",
214
+ "author",
215
+ "reason",
216
+ "resolution_json",
217
+ "resolved_at"
218
+ ],
219
+ effect_agent_child_reservations: [
220
+ "reservation_id",
221
+ "parent_submission_id",
222
+ "parent_tool_call_id",
223
+ "child_submission_id",
224
+ "status",
225
+ "allocation_json",
226
+ "allocation_digest",
227
+ "accounting_json",
228
+ "reserved_at",
229
+ "release_began_at",
230
+ "released_at"
231
+ ],
232
+ effect_agent_schedules: [
233
+ "tenant_id",
234
+ "owner_id",
235
+ "schedule_id",
236
+ "deadline_at_millis",
237
+ "record_json"
238
+ ],
239
+ effect_agent_subscription_sequences: [
240
+ "tenant_id",
241
+ "source_address",
242
+ "sequence",
243
+ "event_scan_cursor",
244
+ "delivery_scan_cursor",
245
+ "recovery_scan_cursor"
246
+ ],
247
+ effect_agent_subscriptions: [
248
+ "tenant_id",
249
+ "source_address",
250
+ "owner_id",
251
+ "subscription_id",
252
+ "ordinal",
253
+ "source_name",
254
+ "source_version",
255
+ "matching_key",
256
+ "state",
257
+ "expires_at_millis",
258
+ "recovery_at_millis",
259
+ "recovery_present",
260
+ "record_json"
261
+ ],
262
+ effect_agent_subscription_events: [
263
+ "tenant_id",
264
+ "source_address",
265
+ "event_id",
266
+ "source_name",
267
+ "source_version",
268
+ "matching_key",
269
+ "payload_digest",
270
+ "cutoff",
271
+ "cursor",
272
+ "routing_complete",
273
+ "next_attempt_at_millis",
274
+ "record_json",
275
+ "tombstone"
276
+ ],
277
+ effect_agent_subscription_deliveries: [
278
+ "tenant_id",
279
+ "source_address",
280
+ "owner_id",
281
+ "subscription_id",
282
+ "event_id",
283
+ "delivery_key",
284
+ "state",
285
+ "next_attempt_at_millis",
286
+ "record_json"
287
+ ]
288
+ };
289
+ const checkPredecessorLayout = Effect.fn("SqliteJournal.checkPredecessorLayout")(function* (version) {
290
+ const sql = yield* SqlClient.SqlClient;
291
+ const expectedColumns = {
292
+ ...version === 8 ? predecessorColumns : {
293
+ ...predecessorColumns,
294
+ effect_agent_submissions: [
295
+ ...predecessorColumns.effect_agent_submissions,
296
+ "worker_admission_json",
297
+ "message_admission_json"
298
+ ],
299
+ effect_agent_message_deliveries: [
300
+ "owner_thread_id",
301
+ "message_id",
302
+ "version",
303
+ "state",
304
+ "deadline_at_millis",
305
+ "record_json"
306
+ ]
307
+ },
308
+ ...version === 12 ? { effect_agent_canonical_records: [...predecessorColumns.effect_agent_canonical_records, "outstanding"] } : {},
309
+ ...version >= 10 ? { effect_agent_recovery_checkpoints: [
310
+ "thread_id",
311
+ "through_sequence",
312
+ "tail_digest",
313
+ "checkpoint_json"
314
+ ] } : {}
315
+ };
316
+ for (const [table, expected] of Object.entries(expectedColumns)) {
317
+ const columns = yield* decodeRows(Schema.Array(Schema.Struct({ name: BoundedIdentifier })), table, "schema", yield* sql.unsafe(`PRAGMA table_info(${table})`));
318
+ const names = new Set(expected);
319
+ if (columns.length !== names.size || columns.some((column) => !names.has(column.name))) return yield* SqliteStorageCompatibilityError.make({
320
+ actualVersion: version,
321
+ supportedVersion: 14,
322
+ message: `The v${version} ${table} columns do not match the supported predecessor; no upgrade was committed.`
323
+ });
324
+ }
325
+ });
326
+ const initializeSqliteJournal = Effect.fn("SqliteJournal.initialize")(function* () {
327
+ const sql = yield* SqlClient.SqlClient;
328
+ const { hit: failpoint } = yield* SqliteStorageFailpoint;
329
+ const { busyTimeout } = yield* SqliteStorageConfig;
330
+ yield* sql`PRAGMA foreign_keys = ON`.pipe(Effect.mapError(storageError("enable foreign keys")));
331
+ yield* sql.unsafe(`PRAGMA busy_timeout = ${busyTimeout}`).pipe(Effect.mapError(storageError("configure busy timeout")));
332
+ const journalModeRows = yield* sql`PRAGMA journal_mode`.pipe(Effect.mapError(storageError("read journal mode")));
333
+ const journalMode = yield* decodeSingleRow(Schema.Array(SqliteJournalModeRow), "pragma_journal_mode", "singleton", journalModeRows);
334
+ if (journalMode.journal_mode.toLowerCase() !== "wal") return yield* SqliteStorageCompatibilityError.make({
335
+ actualVersion: 0,
336
+ supportedVersion: 14,
337
+ message: `SQLite WAL mode is required; the database reported ${journalMode.journal_mode}.`
338
+ });
339
+ const versionRows = yield* sql`PRAGMA user_version`.pipe(Effect.mapError(storageError("read storage version")));
340
+ const version = yield* decodeSingleRow(Schema.Array(SqliteVersionRow), "pragma_user_version", "singleton", versionRows);
341
+ const verifyWorkerPredecessor = Effect.fnUntraced(function* (workerContract) {
342
+ const requiredRows = yield* sql`
343
+ SELECT name
344
+ FROM sqlite_master
345
+ WHERE (type = 'table'
346
+ AND name IN (
347
+ 'effect_agent_threads',
348
+ 'effect_agent_canonical_batches',
349
+ 'effect_agent_canonical_records',
350
+ 'effect_agent_checkpoints',
351
+ 'effect_agent_submissions',
352
+ 'effect_agent_submission_ownership',
353
+ 'effect_agent_attempts',
354
+ 'effect_agent_settlement_reservations',
355
+ 'effect_agent_abort_intents',
356
+ 'effect_agent_approval_decisions',
357
+ 'effect_agent_unknown_resolutions',
358
+ 'effect_agent_schedules',
359
+ 'effect_agent_message_deliveries',
360
+ 'effect_agent_recovery_checkpoints'
361
+ )) 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'))
362
+ OR (${workerContract ? 1 : 0} = 1 AND name IN ('effect_agent_worker_stops', 'effect_agent_worker_starts', 'effect_agent_worker_pending', 'effect_agent_worker_execution'))
363
+ ORDER BY name
364
+ `.pipe(Effect.mapError(storageError("verify storage tables")));
365
+ if ((yield* decodeRows(Schema.Array(SqliteNameRow), "sqlite_master", "required_tables", requiredRows)).length !== 21 + (workerContract ? 4 : 0)) return yield* SqliteStorageCompatibilityError.make({
366
+ actualVersion: 14,
367
+ supportedVersion: 14,
368
+ message: "The SQLite file claims the current format but is missing required tables or its nonterminal index. Retain the original store for inspection."
369
+ });
370
+ });
371
+ if (version.user_version !== 0 && version.user_version !== 7 && version.user_version !== 8 && version.user_version !== 9 && version.user_version !== 10 && version.user_version !== 11 && version.user_version !== 12 && version.user_version !== 13 && version.user_version !== 14) return yield* SqliteStorageCompatibilityError.make({
372
+ actualVersion: version.user_version,
373
+ supportedVersion: 14,
374
+ message: `The SQLite file uses unsupported storage version ${version.user_version}; this build supports exactly version 14. Only supported v7, v8, v9, v10, v11, v12 and v13 can be upgraded automatically. Keep the original file and use a compatible library version.`
375
+ });
376
+ if (version.user_version === 7 || version.user_version === 8 || version.user_version === 9 || version.user_version === 10) yield* sql.withTransaction(Effect.gen(function* () {
377
+ const current = yield* sql`PRAGMA user_version`;
378
+ if (current.length === 1 && current[0].user_version === 14) return;
379
+ if (current.length !== 1 || current[0].user_version !== 7 && current[0].user_version !== 8 && current[0].user_version !== 9 && current[0].user_version !== 10) return yield* SqliteStorageCompatibilityError.make({
380
+ actualVersion: -1,
381
+ supportedVersion: 14,
382
+ message: "Storage version changed while acquiring the upgrade transaction."
383
+ });
384
+ if ((yield* sql`SELECT name FROM sqlite_master WHERE type='table' AND name IN (
385
+ 'effect_agent_threads', 'effect_agent_canonical_batches', 'effect_agent_canonical_records',
386
+ 'effect_agent_checkpoints', 'effect_agent_submissions', 'effect_agent_submission_ownership',
387
+ 'effect_agent_attempts', 'effect_agent_settlement_reservations', 'effect_agent_abort_intents',
388
+ 'effect_agent_approval_decisions', 'effect_agent_unknown_resolutions', 'effect_agent_schedules'
389
+ )`).length !== 12) return yield* SqliteStorageCompatibilityError.make({
390
+ actualVersion: current[0].user_version,
391
+ supportedVersion: 14,
392
+ message: "The predecessor store is missing required tables; no upgrade was committed."
393
+ });
394
+ if ((yield* sql`SELECT name FROM sqlite_master WHERE type='table' AND name='effect_agent_recovery_checkpoints'`).length !== (current[0].user_version === 10 ? 1 : 0)) return yield* SqliteStorageCompatibilityError.make({
395
+ actualVersion: current[0].user_version,
396
+ supportedVersion: 14,
397
+ message: "The predecessor recovery checkpoint storage does not match its version; refusing ambiguous data without mutation."
398
+ });
399
+ if ((yield* sql`SELECT name FROM sqlite_master WHERE name='effect_agent_submissions_nonterminal'`).length !== 0) return yield* SqliteStorageCompatibilityError.make({
400
+ actualVersion: current[0].user_version,
401
+ supportedVersion: 14,
402
+ message: "The predecessor already contains the nonterminal index; refusing ambiguous storage without mutation."
403
+ });
404
+ if (current[0].user_version === 7) {
405
+ yield* checkV2ThreadLayout();
406
+ for (const statement of [
407
+ sql`ALTER TABLE effect_agent_submissions ADD COLUMN admission_group TEXT`,
408
+ sql`ALTER TABLE effect_agent_submissions ADD COLUMN admission_fence_json TEXT`,
409
+ sql`CREATE INDEX effect_agent_submissions_group ON effect_agent_submissions (thread_id, admission_group, state)`
410
+ ]) {
411
+ yield* failpoint("upgrade:before-mutation");
412
+ yield* statement;
413
+ yield* failpoint("upgrade:after-mutation");
414
+ }
415
+ yield* upgradeV2Schedules(16777216).pipe(Effect.provideService(ScheduleFailpoint, { hit: (point) => Schema.decodeUnknownEffect(SqliteStorageFailpointLocation)(point).pipe(Effect.flatMap(failpoint), Effect.mapError(() => ScheduleFailpointError.make({ point }))) }));
416
+ yield* upgradeV2Subscriptions(16777216).pipe(Effect.provideService(SubscriptionFailpoint, { hit: (point) => Schema.decodeUnknownEffect(SqliteStorageFailpointLocation)(point).pipe(Effect.flatMap(failpoint), Effect.mapError(() => SubscriptionFailpointError.make({ point }))) }));
417
+ }
418
+ if (current[0].user_version === 8 || current[0].user_version === 9 || current[0].user_version === 10) yield* checkPredecessorLayout(current[0].user_version);
419
+ if (current[0].user_version === 7 || current[0].user_version === 8) {
420
+ yield* failpoint("upgrade:before-mutation");
421
+ yield* sql`ALTER TABLE effect_agent_submissions ADD COLUMN worker_admission_json TEXT`;
422
+ yield* failpoint("upgrade:after-mutation");
423
+ yield* failpoint("upgrade:before-mutation");
424
+ yield* sql`ALTER TABLE effect_agent_submissions ADD COLUMN message_admission_json TEXT`;
425
+ yield* failpoint("upgrade:after-mutation");
426
+ yield* failpoint("upgrade:before-mutation");
427
+ yield* createMessageDeliveryTables;
428
+ yield* failpoint("upgrade:after-mutation");
429
+ }
430
+ if (current[0].user_version !== 10) {
431
+ yield* failpoint("upgrade:before-mutation");
432
+ yield* createRecoveryCheckpointTable;
433
+ yield* failpoint("upgrade:after-mutation");
434
+ }
435
+ yield* failpoint("upgrade:before-mutation");
436
+ yield* createNonterminalIndex;
437
+ yield* failpoint("upgrade:after-mutation");
438
+ yield* failpoint("upgrade:before-version");
439
+ yield* createNativeReadIndexes;
440
+ yield* createMessageDeliveryPendingIndex;
441
+ yield* seedNativeReadIndexes.pipe(Effect.catchTag("ThreadStoreError", (error) => SqliteStorageCorruptionError.make({
442
+ table: "effect_agent_canonical_records",
443
+ rowKey: "upgrade",
444
+ message: error.message
445
+ })));
446
+ yield* createWorkerStops;
447
+ yield* sql`PRAGMA user_version = 14`;
448
+ yield* failpoint("upgrade:after-version");
449
+ })).pipe(Effect.provide(NodeCrypto.layer), Effect.catchTag("SqliteStorageFailpointError", (error) => SqliteStorageError.make({
450
+ cause: error,
451
+ operation: "upgrade storage",
452
+ message: error.message
453
+ })), Effect.catchTag(["ScheduleFailpointError", "SubscriptionFailpointError"], (error) => SqliteStorageError.make({
454
+ cause: error,
455
+ operation: "upgrade storage",
456
+ message: "Injected storage upgrade failure"
457
+ })), Effect.catchTag("StorageUpgradeError", (error) => SqliteStorageCorruptionError.make({
458
+ table: error.table,
459
+ rowKey: error.rowKey,
460
+ message: error.message
461
+ })), Effect.catchTag("SqlError", storageError("upgrade supported storage")), Effect.catchTag("SchemaError", (error) => SqliteStorageCorruptionError.make({
462
+ table: "upgrade",
463
+ rowKey: "v7",
464
+ message: error.message
465
+ })));
466
+ if (version.user_version === 0) {
467
+ const existingRows = yield* sql`
468
+ SELECT name
469
+ FROM sqlite_master
470
+ WHERE type = 'table'
471
+ AND name LIKE 'effect_agent_%'
472
+ ORDER BY name
473
+ `.pipe(Effect.mapError(storageError("inspect unversioned storage")));
474
+ if ((yield* decodeRows(Schema.Array(SqliteNameRow), "sqlite_master", "effect_agent_%", existingRows)).length > 0) return yield* SqliteStorageCompatibilityError.make({
475
+ actualVersion: 0,
476
+ supportedVersion: 14,
477
+ message: "The SQLite file contains unversioned Effect Agent tables. Refusing to mutate ambiguous stored data; retain it for inspection with its original writer."
478
+ });
479
+ yield* SqliteMigrator.run({ loader: sqliteMigrations }).pipe(Effect.mapError((error) => SqliteStorageError.make({
480
+ cause: error,
481
+ operation: "initialize current storage",
482
+ message: error.message
483
+ })));
484
+ }
485
+ if (version.user_version === 11) yield* sql.withTransaction(Effect.gen(function* () {
486
+ const current = yield* sql`PRAGMA user_version`;
487
+ if (current[0]?.user_version === 14) return;
488
+ if (current[0]?.user_version !== 11) return yield* SqliteStorageCompatibilityError.make({
489
+ actualVersion: current[0]?.user_version ?? -1,
490
+ supportedVersion: 14,
491
+ message: "Storage version changed during native index upgrade"
492
+ });
493
+ yield* checkPredecessorLayout(10);
494
+ if ((yield* sql`SELECT name FROM sqlite_master WHERE type = 'index' AND name = 'effect_agent_submissions_nonterminal'`).length !== 1) return yield* SqliteStorageCompatibilityError.make({
495
+ actualVersion: 11,
496
+ supportedVersion: 14,
497
+ message: "Predecessor storage is missing its required nonterminal index"
498
+ });
499
+ yield* failpoint("upgrade:before-mutation");
500
+ yield* createNativeReadIndexes;
501
+ yield* createMessageDeliveryPendingIndex;
502
+ yield* seedNativeReadIndexes.pipe(Effect.catchTag("ThreadStoreError", (error) => SqliteStorageCorruptionError.make({
503
+ table: "effect_agent_canonical_records",
504
+ rowKey: "upgrade",
505
+ message: error.message
506
+ })));
507
+ yield* failpoint("upgrade:after-mutation");
508
+ yield* failpoint("upgrade:before-version");
509
+ yield* createWorkerStops;
510
+ yield* sql`PRAGMA user_version = 14`;
511
+ yield* failpoint("upgrade:after-version");
512
+ })).pipe(Effect.mapError((error) => SqliteStorageError.make({
513
+ operation: "upgrade native indexes",
514
+ message: error.message,
515
+ cause: error
516
+ })));
517
+ if (version.user_version === 12) yield* sql.withTransaction(Effect.gen(function* () {
518
+ const current = yield* sql`PRAGMA user_version`;
519
+ if (current[0]?.user_version === 14) return;
520
+ if (current[0]?.user_version !== 12) return yield* SqliteStorageCompatibilityError.make({
521
+ actualVersion: current[0]?.user_version ?? -1,
522
+ supportedVersion: 14,
523
+ message: "Storage version changed during worker stop upgrade"
524
+ });
525
+ yield* checkPredecessorLayout(12);
526
+ yield* verifyWorkerPredecessor(false);
527
+ yield* failpoint("upgrade:before-mutation");
528
+ yield* createWorkerStops;
529
+ yield* failpoint("upgrade:after-mutation");
530
+ yield* failpoint("upgrade:before-version");
531
+ yield* sql`PRAGMA user_version = 14`;
532
+ yield* failpoint("upgrade:after-version");
533
+ })).pipe(Effect.mapError((cause) => SqliteStorageError.make({
534
+ operation: "upgrade worker stop",
535
+ message: "Worker stop upgrade failed",
536
+ cause
537
+ })));
538
+ if (version.user_version === 13) yield* sql.withTransaction(Effect.gen(function* () {
539
+ const current = yield* sql`PRAGMA user_version`;
540
+ if (current[0]?.user_version === 14) return;
541
+ if (current[0]?.user_version !== 13) return yield* SqliteStorageCompatibilityError.make({
542
+ actualVersion: current[0]?.user_version ?? -1,
543
+ supportedVersion: 14,
544
+ message: "Storage version changed during assignment seal upgrade"
545
+ });
546
+ yield* checkPredecessorLayout(12);
547
+ yield* verifyWorkerPredecessor(true);
548
+ const columns = yield* sql`PRAGMA table_info(effect_agent_worker_stops)`;
549
+ yield* Schema.decodeUnknownEffect(Schema.Tuple([Schema.Struct({
550
+ cid: Schema.Literal(0),
551
+ name: Schema.Literal("thread_id"),
552
+ type: Schema.Literal("TEXT"),
553
+ notnull: Schema.Literal(1),
554
+ dflt_value: Schema.Null,
555
+ pk: Schema.Literal(1)
556
+ })]))(columns).pipe(Effect.mapError(() => SqliteStorageCompatibilityError.make({
557
+ actualVersion: 13,
558
+ supportedVersion: 14,
559
+ message: "Unsupported worker seal layout; no upgrade was committed"
560
+ })));
561
+ yield* failpoint("upgrade:before-mutation");
562
+ yield* sql`ALTER TABLE effect_agent_worker_stops ADD COLUMN terminal TEXT`;
563
+ yield* failpoint("upgrade:after-mutation");
564
+ yield* failpoint("upgrade:before-version");
565
+ yield* sql`PRAGMA user_version = 14`;
566
+ yield* failpoint("upgrade:after-version");
567
+ })).pipe(Effect.mapError((cause) => SqliteStorageError.make({
568
+ operation: "upgrade assignment seals",
569
+ message: "Assignment seal upgrade failed",
570
+ cause
571
+ })));
572
+ yield* verifyWorkerPredecessor(true);
573
+ const classifyWriteFailure = (operation) => (error) => error.reason._tag === "LockTimeoutError" ? SqliteWriteContention.make({
574
+ cause: error,
575
+ operation,
576
+ message: `Another producer holds the SQLite write lock; ${operation} is safe to retry.`
577
+ }) : storageError(operation)(error);
578
+ /**
579
+ * Runs one journal write transaction under `BEGIN IMMEDIATE`. SQLite's deferred `BEGIN`
580
+ * would let a read-then-write transaction start as a reader and fail with
581
+ * SQLITE_BUSY_SNAPSHOT on upgrade, which `busy_timeout` never retries. Taking the write
582
+ * lock up front keeps cross-owner contention inside the bounded busy retry; a lock
583
+ * timeout is classified as the retryable SqliteWriteContention. A failed `BEGIN` leaves
584
+ * no transaction, so no rollback is attempted for it.
585
+ *
586
+ * Journal write transactions are always top level. Nesting one inside another would
587
+ * deadlock the single-connection client, so new journal operations must not wrap this
588
+ * helper inside another transaction.
589
+ */
590
+ const withWriteTransaction = (operation) => (effect) => Effect.uninterruptibleMask((restore) => Effect.scoped(Effect.gen(function* () {
591
+ const connection = yield* sql.reserve.pipe(Effect.mapError(classifyWriteFailure(operation)));
592
+ yield* connection.executeUnprepared("BEGIN IMMEDIATE", [], void 0).pipe(Effect.mapError(classifyWriteFailure(operation)));
593
+ const exit = yield* restore(Effect.provideService(effect, sql.transactionService, [connection, 0])).pipe(Effect.exit);
594
+ if (Exit.isSuccess(exit)) {
595
+ yield* connection.executeUnprepared("COMMIT", [], void 0).pipe(Effect.mapError(classifyWriteFailure(operation)));
596
+ return exit.value;
597
+ }
598
+ yield* Effect.orDie(connection.executeUnprepared("ROLLBACK", [], void 0));
599
+ return yield* exit;
600
+ })).pipe(Effect.withSpan("SqliteJournal.withWriteTransaction", { attributes: { operation } })));
601
+ /**
602
+ * Runs a read-only snapshot under a deferred transaction. Effect's SQLite client now
603
+ * starts every writable-client `withTransaction` with `BEGIN IMMEDIATE`, which is the
604
+ * right default for mutations but would make exports take the write lock and block a
605
+ * concurrent append. Reserving the connection and beginning explicitly preserves the
606
+ * adapter's snapshot-with-concurrent-writer contract. As with the write helper, a failed
607
+ * `BEGIN` is reported directly because there is no transaction to roll back.
608
+ */
609
+ const withReadTransaction = (operation) => (effect) => Effect.uninterruptibleMask((restore) => Effect.scoped(Effect.gen(function* () {
610
+ const connection = yield* sql.reserve.pipe(Effect.mapError(storageError(operation)));
611
+ yield* connection.executeUnprepared("BEGIN", [], void 0).pipe(Effect.mapError(storageError(operation)));
612
+ const exit = yield* restore(Effect.provideService(effect, sql.transactionService, [connection, 0])).pipe(Effect.exit);
613
+ if (Exit.isSuccess(exit)) {
614
+ yield* connection.executeUnprepared("COMMIT", [], void 0).pipe(Effect.mapError(storageError(operation)));
615
+ return exit.value;
616
+ }
617
+ yield* Effect.orDie(connection.executeUnprepared("ROLLBACK", [], void 0));
618
+ return yield* exit;
619
+ })).pipe(Effect.withSpan("SqliteJournal.withReadTransaction", { attributes: { operation } })));
620
+ const materialize = Effect.fn("SqliteJournal.materialize")(function* (threadId, createdAt, emptyTailDigest, producerEpoch) {
621
+ if (threadId.length > MAX_IDENTIFIER_LENGTH || storedTextBytes(emptyTailDigest) > MAX_STORED_TEXT_BYTES) return yield* SqliteStorageError.make({
622
+ operation: "materialize thread",
623
+ message: "Thread identity or initial digest exceeds the SQLite storage bounds."
624
+ });
625
+ yield* withWriteTransaction("materialize transaction")(Effect.gen(function* () {
626
+ const existingRows = yield* sql`
627
+ SELECT
628
+ thread_id,
629
+ created_at,
630
+ tail_sequence,
631
+ tail_digest,
632
+ producer_epoch
633
+ FROM effect_agent_threads
634
+ WHERE thread_id = ${threadId}
635
+ `.pipe(Effect.mapError(storageError("read materialized thread")));
636
+ const existing = yield* decodeRows(Schema.Array(ThreadRow), "effect_agent_threads", threadId, existingRows);
637
+ if (existing.length > 1) return yield* SqliteStorageCorruptionError.make({
638
+ table: "effect_agent_threads",
639
+ rowKey: threadId,
640
+ message: "A thread primary key returned more than one row."
641
+ });
642
+ if (existing.length === 0) {
643
+ yield* sql`
644
+ INSERT INTO effect_agent_threads (
645
+ thread_id,
646
+ created_at,
647
+ tail_sequence,
648
+ tail_digest,
649
+ producer_epoch
650
+ ) VALUES (
651
+ ${threadId},
652
+ ${createdAt},
653
+ 0,
654
+ ${emptyTailDigest},
655
+ ${producerEpoch}
656
+ )
657
+ `.pipe(Effect.mapError(storageError("materialize thread")));
658
+ return;
659
+ }
660
+ if (producerEpoch < existing[0].producer_epoch) return yield* SqliteFenceRejected.make({
661
+ producerEpoch,
662
+ actualEpoch: existing[0].producer_epoch,
663
+ message: `Producer epoch ${producerEpoch} is stale; current epoch is ${existing[0].producer_epoch}.`
664
+ });
665
+ if (producerEpoch > existing[0].producer_epoch) yield* sql`
666
+ UPDATE effect_agent_threads
667
+ SET producer_epoch = ${producerEpoch}
668
+ WHERE thread_id = ${threadId}
669
+ `.pipe(Effect.mapError(storageError("advance materialization epoch")));
670
+ }));
671
+ });
672
+ const getThread = Effect.fn("SqliteJournal.getThread")(function* (threadId) {
673
+ const rows = yield* sql`
674
+ SELECT
675
+ thread_id,
676
+ created_at,
677
+ tail_sequence,
678
+ tail_digest,
679
+ producer_epoch
680
+ FROM effect_agent_threads
681
+ WHERE thread_id = ${threadId}
682
+ `.pipe(Effect.mapError(storageError("read thread")));
683
+ return yield* decodeRows(Schema.Array(ThreadRow), "effect_agent_threads", threadId, rows);
684
+ });
685
+ const append = Effect.fn("SqliteJournal.append")(function* (request) {
686
+ if (request.threadId.length > MAX_IDENTIFIER_LENGTH || request.batchId.length > MAX_IDENTIFIER_LENGTH || storedTextBytes(request.batchJson) > MAX_STORED_TEXT_BYTES || storedTextBytes(request.batchDigest) > MAX_STORED_TEXT_BYTES || storedTextBytes(request.tailDigest) > MAX_STORED_TEXT_BYTES || request.records.some((record) => record.recordId.length > MAX_IDENTIFIER_LENGTH || storedTextBytes(record.recordJson) > MAX_STORED_TEXT_BYTES)) return yield* SqliteStorageError.make({
687
+ operation: "append canonical batch",
688
+ message: "Canonical identifiers or encoded JSON exceed the SQLite storage bounds."
689
+ });
690
+ return yield* withWriteTransaction("append transaction")(Effect.gen(function* () {
691
+ const recordIds = request.records.map((record) => record.recordId);
692
+ if (new Set(recordIds).size !== recordIds.length) return yield* SqliteAppendConflict.make({
693
+ message: `Batch ${request.batchId} contains duplicate canonical record IDs.`,
694
+ reason: "record-identity"
695
+ });
696
+ const threadRows = yield* sql`
697
+ SELECT
698
+ thread_id,
699
+ created_at,
700
+ tail_sequence,
701
+ tail_digest,
702
+ producer_epoch
703
+ FROM effect_agent_threads
704
+ WHERE thread_id = ${request.threadId}
705
+ `.pipe(Effect.mapError(storageError("read append tail")));
706
+ const thread = yield* decodeSingleRow(Schema.Array(ThreadRow), "effect_agent_threads", request.threadId, threadRows);
707
+ if (request.producerEpoch !== thread.producer_epoch) return yield* SqliteFenceRejected.make({
708
+ producerEpoch: request.producerEpoch,
709
+ actualEpoch: thread.producer_epoch,
710
+ message: `Producer epoch ${request.producerEpoch} is not the current epoch ${thread.producer_epoch}.`
711
+ });
712
+ const batchRows = yield* sql`
713
+ SELECT
714
+ thread_id,
715
+ batch_id,
716
+ first_sequence,
717
+ last_sequence,
718
+ batch_digest,
719
+ tail_digest,
720
+ batch_json
721
+ FROM effect_agent_canonical_batches
722
+ WHERE thread_id = ${request.threadId}
723
+ AND batch_id = ${request.batchId}
724
+ `.pipe(Effect.mapError(storageError("read idempotent batch")));
725
+ const batches = yield* decodeRows(Schema.Array(BatchRow), "effect_agent_canonical_batches", `${request.threadId}/${request.batchId}`, batchRows);
726
+ if (batches.length > 1) return yield* SqliteStorageCorruptionError.make({
727
+ table: "effect_agent_canonical_batches",
728
+ rowKey: `${request.threadId}/${request.batchId}`,
729
+ message: "A canonical batch primary key returned more than one row."
730
+ });
731
+ if (batches.length === 1) {
732
+ const existing = batches[0];
733
+ if (existing.batch_digest !== request.batchDigest) return yield* SqliteAppendConflict.make({
734
+ message: `Batch ${request.batchId} already exists with different canonical content.`,
735
+ reason: "batch-digest"
736
+ });
737
+ return RawAppendResult.make({
738
+ firstSequence: existing.first_sequence,
739
+ lastSequence: existing.last_sequence,
740
+ replayed: true,
741
+ tailDigest: existing.tail_digest
742
+ });
743
+ }
744
+ if (request.expectedTailSequence !== thread.tail_sequence || request.expectedTailDigest !== thread.tail_digest) return yield* SqliteAppendConflict.make({
745
+ message: `Expected tail ${request.expectedTailSequence}/${request.expectedTailDigest} but found ${thread.tail_sequence}/${thread.tail_digest}.`,
746
+ reason: "tail",
747
+ actualTailSequence: thread.tail_sequence,
748
+ actualTailDigest: thread.tail_digest
749
+ });
750
+ if (thread.tail_sequence + request.records.length > MAX_RECORDS_PER_THREAD) return yield* SqliteStorageError.make({
751
+ operation: "append canonical batch",
752
+ message: `Thread record limit ${MAX_RECORDS_PER_THREAD} would be exceeded.`
753
+ });
754
+ const existingRecordRows = yield* sql`
755
+ SELECT
756
+ thread_id,
757
+ sequence,
758
+ record_id,
759
+ batch_id,
760
+ record_json
761
+ FROM effect_agent_canonical_records
762
+ WHERE thread_id = ${request.threadId}
763
+ AND record_id IN ${sql.in(recordIds)}
764
+ ORDER BY sequence
765
+ `.pipe(Effect.mapError(storageError("check canonical record identities")));
766
+ const existingRecords = yield* decodeRows(Schema.Array(RecordRow), "effect_agent_canonical_records", `${request.threadId}/record_ids`, existingRecordRows);
767
+ if (existingRecords.length > 0) return yield* SqliteAppendConflict.make({
768
+ message: `Canonical record ID ${existingRecords[0].record_id} already exists.`,
769
+ reason: "record-identity"
770
+ });
771
+ const firstSequence = yield* Schema.decodeEffect(CanonicalSequence)(thread.tail_sequence + 1).pipe(Effect.mapError((error) => SqliteStorageError.make({
772
+ cause: error,
773
+ operation: "append canonical batch",
774
+ message: error.message
775
+ })));
776
+ const lastSequence = yield* Schema.decodeEffect(CanonicalSequence)(firstSequence + request.records.length - 1).pipe(Effect.mapError((error) => SqliteStorageError.make({
777
+ cause: error,
778
+ operation: "append canonical batch",
779
+ message: error.message
780
+ })));
781
+ yield* sql`
782
+ INSERT INTO effect_agent_canonical_batches (
783
+ thread_id,
784
+ batch_id,
785
+ first_sequence,
786
+ last_sequence,
787
+ batch_digest,
788
+ tail_digest,
789
+ batch_json
790
+ ) VALUES (
791
+ ${request.threadId},
792
+ ${request.batchId},
793
+ ${firstSequence},
794
+ ${lastSequence},
795
+ ${request.batchDigest},
796
+ ${request.tailDigest},
797
+ ${request.batchJson}
798
+ )
799
+ `.pipe(Effect.mapError(storageError("insert canonical batch")));
800
+ yield* failpoint("append:after-batch-insert");
801
+ yield* Effect.forEach(request.records, (record, index) => Effect.gen(function* () {
802
+ yield* sql`
803
+ INSERT INTO effect_agent_canonical_records (
804
+ thread_id,
805
+ sequence,
806
+ record_id,
807
+ batch_id,
808
+ record_json
809
+ ) VALUES (
810
+ ${request.threadId},
811
+ ${firstSequence + index},
812
+ ${record.recordId},
813
+ ${request.batchId},
814
+ ${record.recordJson}
815
+ )
816
+ `.pipe(Effect.mapError(storageError("insert canonical record")));
817
+ const canonical = yield* Schema.decodeEffect(Schema.fromJsonString(CanonicalRecord))(record.recordJson).pipe(Effect.mapError((error) => SqliteStorageCorruptionError.make({
818
+ table: "effect_agent_canonical_records",
819
+ rowKey: record.recordId,
820
+ message: error.message
821
+ })));
822
+ yield* indexCanonicalRecord(request.threadId, canonical).pipe(Effect.provideService(SqlClient.SqlClient, sql), Effect.mapError(storageError("index canonical record")));
823
+ yield* failpoint("append:after-record-insert");
824
+ }), { discard: true });
825
+ yield* sql`
826
+ UPDATE effect_agent_threads
827
+ SET
828
+ tail_sequence = ${lastSequence},
829
+ tail_digest = ${request.tailDigest},
830
+ producer_epoch = ${request.producerEpoch}
831
+ WHERE thread_id = ${request.threadId}
832
+ `.pipe(Effect.mapError(storageError("advance thread tail")));
833
+ yield* failpoint("append:after-tail-update");
834
+ return RawAppendResult.make({
835
+ firstSequence,
836
+ lastSequence,
837
+ replayed: false,
838
+ tailDigest: request.tailDigest
839
+ });
840
+ }));
841
+ });
842
+ const read = Effect.fn("SqliteJournal.read")(function* (request) {
843
+ const rows = yield* sql`
844
+ SELECT
845
+ thread_id,
846
+ sequence,
847
+ record_id,
848
+ batch_id,
849
+ record_json
850
+ FROM effect_agent_canonical_records
851
+ WHERE thread_id = ${request.threadId}
852
+ AND sequence > ${request.fromSequenceExclusive}
853
+ ORDER BY sequence
854
+ LIMIT ${request.limit}
855
+ `.pipe(Effect.mapError(storageError("read canonical records")));
856
+ return yield* decodeRows(Schema.Array(RecordRow), "effect_agent_canonical_records", `${request.threadId}>${request.fromSequenceExclusive}`, rows);
857
+ });
858
+ const exportThread = Effect.fn("SqliteJournal.exportThread")(function* (threadId) {
859
+ return yield* withReadTransaction("export transaction")(Effect.gen(function* () {
860
+ const threadRows = yield* sql`
861
+ SELECT
862
+ thread_id,
863
+ created_at,
864
+ tail_sequence,
865
+ tail_digest,
866
+ producer_epoch
867
+ FROM effect_agent_threads
868
+ WHERE thread_id = ${threadId}
869
+ `.pipe(Effect.mapError(storageError("export thread")));
870
+ const thread = yield* decodeSingleRow(Schema.Array(ThreadRow), "effect_agent_threads", threadId, threadRows);
871
+ yield* failpoint("export:after-thread-read");
872
+ if (thread.tail_sequence > MAX_RECORDS_PER_THREAD) return yield* SqliteStorageError.make({
873
+ operation: "export thread",
874
+ message: "The thread exceeds the current export record limit."
875
+ });
876
+ const records = [];
877
+ let afterSequence = ZERO_SEQUENCE;
878
+ while (afterSequence < thread.tail_sequence) {
879
+ const limit = Math.min(1024, thread.tail_sequence - afterSequence);
880
+ const request = RawReadRequest.make({
881
+ threadId,
882
+ fromSequenceExclusive: afterSequence,
883
+ limit
884
+ });
885
+ const page = yield* read(request);
886
+ if (page.length !== limit || page.some((record, index) => record.sequence !== afterSequence + index + 1)) return yield* SqliteStorageCorruptionError.make({
887
+ table: "effect_agent_canonical_records",
888
+ rowKey: threadId,
889
+ message: "The exported canonical prefix is not contiguous through its captured tail."
890
+ });
891
+ records.push(...page);
892
+ afterSequence = page[page.length - 1].sequence;
893
+ }
894
+ if ((yield* sql`SELECT sequence FROM effect_agent_canonical_records WHERE thread_id=${threadId} AND sequence > ${thread.tail_sequence} LIMIT 1`.pipe(Effect.mapError(storageError("verify export tail")))).length !== 0) return yield* SqliteStorageCorruptionError.make({
895
+ table: "effect_agent_canonical_records",
896
+ rowKey: threadId,
897
+ message: "Canonical records exist beyond the captured thread tail."
898
+ });
899
+ return RawThreadExport.make({
900
+ thread,
901
+ records
902
+ });
903
+ }));
904
+ });
905
+ const saveCheckpoint = Effect.fn("SqliteJournal.saveCheckpoint")(function* (checkpoint) {
906
+ if (checkpoint.threadId.length > MAX_IDENTIFIER_LENGTH || storedTextBytes(checkpoint.checkpointJson) > MAX_STORED_TEXT_BYTES) return yield* SqliteStorageError.make({
907
+ operation: "save checkpoint",
908
+ message: "Checkpoint identity or encoded JSON exceeds the SQLite storage bounds."
909
+ });
910
+ yield* withWriteTransaction("checkpoint transaction")(Effect.gen(function* () {
911
+ const threadRows = yield* sql`
912
+ SELECT
913
+ thread_id,
914
+ created_at,
915
+ tail_sequence,
916
+ tail_digest,
917
+ producer_epoch
918
+ FROM effect_agent_threads
919
+ WHERE thread_id = ${checkpoint.threadId}
920
+ `.pipe(Effect.mapError(storageError("read checkpoint tail")));
921
+ const thread = yield* decodeSingleRow(Schema.Array(ThreadRow), "effect_agent_threads", checkpoint.threadId, threadRows);
922
+ if (checkpoint.throughSequence > thread.tail_sequence) return yield* SqliteCheckpointConflict.make({ message: `Checkpoint sequence ${checkpoint.throughSequence} is after canonical tail ${thread.tail_sequence}.` });
923
+ const checkpointRows = yield* sql`
924
+ SELECT
925
+ thread_id,
926
+ through_sequence,
927
+ tail_digest,
928
+ checkpoint_json
929
+ FROM effect_agent_checkpoints
930
+ WHERE thread_id = ${checkpoint.threadId}
931
+ AND through_sequence = ${checkpoint.throughSequence}
932
+ `.pipe(Effect.mapError(storageError("read idempotent checkpoint")));
933
+ const existing = yield* decodeRows(Schema.Array(CheckpointRow), "effect_agent_checkpoints", `${checkpoint.threadId}/${checkpoint.throughSequence}`, checkpointRows);
934
+ if (existing.length > 1) return yield* SqliteStorageCorruptionError.make({
935
+ table: "effect_agent_checkpoints",
936
+ rowKey: `${checkpoint.threadId}/${checkpoint.throughSequence}`,
937
+ message: "A checkpoint primary key returned more than one row."
938
+ });
939
+ if (existing.length === 1) {
940
+ if (existing[0].tail_digest !== checkpoint.tailDigest || existing[0].checkpoint_json !== checkpoint.checkpointJson) return yield* SqliteCheckpointConflict.make({ message: "A different checkpoint already exists at this canonical sequence." });
941
+ return;
942
+ }
943
+ yield* sql`
944
+ INSERT INTO effect_agent_checkpoints (
945
+ thread_id,
946
+ through_sequence,
947
+ tail_digest,
948
+ checkpoint_json
949
+ ) VALUES (
950
+ ${checkpoint.threadId},
951
+ ${checkpoint.throughSequence},
952
+ ${checkpoint.tailDigest},
953
+ ${checkpoint.checkpointJson}
954
+ )
955
+ `.pipe(Effect.mapError(storageError("insert checkpoint")));
956
+ }));
957
+ });
958
+ const saveRecoveryCheckpoint = Effect.fn("SqliteJournal.saveRecoveryCheckpoint")(function* (request, checkpointJson) {
959
+ const { checkpoint } = request;
960
+ if (checkpoint.threadId.length > MAX_IDENTIFIER_LENGTH || storedTextBytes(checkpointJson) > MAX_STORED_TEXT_BYTES) return yield* SqliteStorageError.make({
961
+ operation: "save recovery checkpoint",
962
+ message: "Checkpoint identity or encoded JSON exceeds the SQLite storage bounds."
963
+ });
964
+ yield* withWriteTransaction("recovery checkpoint transaction")(Effect.gen(function* () {
965
+ const thread = (yield* getThread(checkpoint.threadId))[0];
966
+ if (thread === void 0) return yield* ThreadNotMaterialized.make({ threadId: checkpoint.threadId });
967
+ if (request.producerEpoch !== thread.producer_epoch) return yield* FenceRejected.make({
968
+ threadId: checkpoint.threadId,
969
+ actualEpoch: thread.producer_epoch,
970
+ attemptedEpoch: request.producerEpoch
971
+ });
972
+ if (checkpoint.throughSequence > thread.tail_sequence) return yield* CheckpointRejected.make({
973
+ threadId: checkpoint.threadId,
974
+ reason: "ahead-of-tail"
975
+ });
976
+ const digests = checkpoint.throughSequence === 0 ? [EMPTY_TAIL_DIGEST] : yield* getTailDigestAt(checkpoint.threadId, checkpoint.throughSequence);
977
+ if (digests.length !== 1 || digests[0] !== checkpoint.tailDigest) return yield* CheckpointRejected.make({
978
+ threadId: checkpoint.threadId,
979
+ reason: "digest-mismatch"
980
+ });
981
+ yield* failpoint("save-recovery-checkpoint:before");
982
+ yield* sql`
983
+ INSERT INTO effect_agent_recovery_checkpoints (thread_id, through_sequence, tail_digest, checkpoint_json)
984
+ VALUES (${checkpoint.threadId}, ${checkpoint.throughSequence}, ${checkpoint.tailDigest}, ${checkpointJson})
985
+ ON CONFLICT (thread_id) DO UPDATE SET
986
+ through_sequence = excluded.through_sequence,
987
+ tail_digest = excluded.tail_digest,
988
+ checkpoint_json = excluded.checkpoint_json
989
+ WHERE excluded.through_sequence >= effect_agent_recovery_checkpoints.through_sequence
990
+ `.pipe(Effect.mapError(storageError("save recovery checkpoint")));
991
+ }));
992
+ yield* failpoint("save-recovery-checkpoint:after");
993
+ });
994
+ const loadRecoveryCheckpoint = Effect.fn("SqliteJournal.loadRecoveryCheckpoint")(function* (threadId) {
995
+ const rows = yield* sql`
996
+ SELECT thread_id, through_sequence, tail_digest, checkpoint_json
997
+ FROM effect_agent_recovery_checkpoints
998
+ WHERE thread_id = ${threadId}
999
+ `.pipe(Effect.mapError(storageError("load recovery checkpoint")));
1000
+ return yield* decodeRows(Schema.Array(CheckpointRow), "effect_agent_recovery_checkpoints", threadId, rows);
1001
+ });
1002
+ const loadCheckpoint = Effect.fn("SqliteJournal.loadCheckpoint")(function* (threadId, atOrBeforeSequence) {
1003
+ const rows = yield* sql`
1004
+ SELECT
1005
+ thread_id,
1006
+ through_sequence,
1007
+ tail_digest,
1008
+ checkpoint_json
1009
+ FROM effect_agent_checkpoints
1010
+ WHERE thread_id = ${threadId}
1011
+ AND through_sequence <= ${atOrBeforeSequence}
1012
+ ORDER BY through_sequence DESC
1013
+ LIMIT 1
1014
+ `.pipe(Effect.mapError(storageError("load checkpoint")));
1015
+ return yield* decodeRows(Schema.Array(CheckpointRow), "effect_agent_checkpoints", `${threadId}<=${atOrBeforeSequence}`, rows);
1016
+ });
1017
+ const getTailDigestAt = Effect.fn("SqliteJournal.getTailDigestAt")(function* (threadId, sequence) {
1018
+ if (sequence === 0) {
1019
+ const threads = yield* getThread(threadId);
1020
+ return threads.length === 0 ? [] : [threads[0].tail_sequence === 0 ? threads[0].tail_digest : void 0].filter((value) => value !== void 0);
1021
+ }
1022
+ const rows = yield* sql`
1023
+ SELECT
1024
+ thread_id,
1025
+ batch_id,
1026
+ first_sequence,
1027
+ last_sequence,
1028
+ batch_digest,
1029
+ tail_digest,
1030
+ batch_json
1031
+ FROM effect_agent_canonical_batches
1032
+ WHERE thread_id = ${threadId}
1033
+ AND last_sequence = ${sequence}
1034
+ `.pipe(Effect.mapError(storageError("read canonical digest at sequence")));
1035
+ return (yield* decodeRows(Schema.Array(BatchRow), "effect_agent_canonical_batches", `${threadId}/${sequence}`, rows)).map((batch) => batch.tail_digest);
1036
+ });
1037
+ return {
1038
+ append,
1039
+ exportThread,
1040
+ getThread,
1041
+ getTailDigestAt,
1042
+ loadCheckpoint,
1043
+ loadRecoveryCheckpoint,
1044
+ saveRecoveryCheckpoint,
1045
+ materialize,
1046
+ read,
1047
+ saveCheckpoint,
1048
+ scanStoredPayloads: Effect.fn("SqliteJournal.scanStoredPayloads")(function* () {
1049
+ return yield* withReadTransaction("startup scan transaction")(Effect.gen(function* () {
1050
+ const threads = yield* sql`
1051
+ SELECT
1052
+ thread_id,
1053
+ created_at,
1054
+ tail_sequence,
1055
+ tail_digest,
1056
+ producer_epoch
1057
+ FROM effect_agent_threads
1058
+ ORDER BY thread_id
1059
+ `.pipe(Effect.mapError(storageError("scan threads")));
1060
+ const batches = yield* sql`
1061
+ SELECT
1062
+ thread_id,
1063
+ batch_id,
1064
+ first_sequence,
1065
+ last_sequence,
1066
+ batch_digest,
1067
+ tail_digest,
1068
+ batch_json
1069
+ FROM effect_agent_canonical_batches
1070
+ ORDER BY thread_id, first_sequence
1071
+ `.pipe(Effect.mapError(storageError("scan canonical batches")));
1072
+ const records = yield* sql`
1073
+ SELECT
1074
+ thread_id,
1075
+ sequence,
1076
+ record_id,
1077
+ batch_id,
1078
+ record_json
1079
+ FROM effect_agent_canonical_records
1080
+ ORDER BY thread_id, sequence
1081
+ `.pipe(Effect.mapError(storageError("scan canonical records")));
1082
+ const checkpoints = yield* sql`
1083
+ SELECT
1084
+ thread_id,
1085
+ through_sequence,
1086
+ tail_digest,
1087
+ checkpoint_json
1088
+ FROM effect_agent_checkpoints
1089
+ ORDER BY thread_id, through_sequence
1090
+ `.pipe(Effect.mapError(storageError("scan checkpoints")));
1091
+ return {
1092
+ threads: yield* decodeRows(Schema.Array(ThreadRow), "effect_agent_threads", "startup_scan", threads),
1093
+ batches: yield* decodeRows(Schema.Array(BatchRow), "effect_agent_canonical_batches", "startup_scan", batches),
1094
+ records: yield* decodeRows(Schema.Array(RecordRow), "effect_agent_canonical_records", "startup_scan", records),
1095
+ checkpoints: yield* decodeRows(Schema.Array(CheckpointRow), "effect_agent_checkpoints", "startup_scan", checkpoints)
1096
+ };
1097
+ }));
1098
+ }),
1099
+ withWriteTransaction,
1100
+ withReadTransaction
1101
+ };
1102
+ });
1103
+ //#endregion
1104
+ export { initializeSqliteJournal as a, decodeRows as i, RawCheckpoint as n, RawReadRequest as r, RawAppendRequest as t };
1105
+
1106
+ //# sourceMappingURL=sqlite-journal-DE4MN8uP.mjs.map