@systemfsoftware/agent-storage-cloudflare 0.0.0-stage → 0.1.0-beta.192
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.
- package/LICENSE +21 -0
- package/dist/DoMemoryStore-AaGtt8CZ.d.mts +29 -0
- package/dist/DoMemoryStore-DVun329p.mjs +67 -0
- package/dist/DoMemoryStore-DVun329p.mjs.map +1 -0
- package/dist/DoMemoryStore.d.mts +2 -0
- package/dist/DoMemoryStore.mjs +1 -0
- package/dist/DoMessageDeliveryStore-BvB6OPI1.mjs +34 -0
- package/dist/DoMessageDeliveryStore-BvB6OPI1.mjs.map +1 -0
- package/dist/DoMessageDeliveryStore-Cb-DNN5s.d.mts +16 -0
- package/dist/DoMessageDeliveryStore.d.mts +2 -0
- package/dist/DoMessageDeliveryStore.mjs +1 -0
- package/dist/DoScheduleStore-BiTgDvX1.d.mts +36 -0
- package/dist/DoScheduleStore-C7GkSReF.mjs +167 -0
- package/dist/DoScheduleStore-C7GkSReF.mjs.map +1 -0
- package/dist/DoScheduleStore.d.mts +2 -0
- package/dist/DoScheduleStore.mjs +1 -0
- package/dist/DoStorageConfig-BqezsbD6.mjs +43 -0
- package/dist/DoStorageConfig-BqezsbD6.mjs.map +1 -0
- package/dist/DoStorageConfig-CuB6ZOtX.d.mts +36 -0
- package/dist/DoStorageConfig.d.mts +2 -0
- package/dist/DoStorageConfig.mjs +1 -0
- package/dist/DoStorageError-C-F5Z_FZ.d.mts +82 -0
- package/dist/DoStorageError-DSQzuCb0.mjs +138 -0
- package/dist/DoStorageError-DSQzuCb0.mjs.map +1 -0
- package/dist/DoStorageError.d.mts +2 -0
- package/dist/DoStorageError.mjs +1 -0
- package/dist/DoStorageFailpoint-C7zLUULu.d.mts +19 -0
- package/dist/DoStorageFailpoint-WO3B_DQl.mjs +20 -0
- package/dist/DoStorageFailpoint-WO3B_DQl.mjs.map +1 -0
- package/dist/DoStorageFailpoint.d.mts +2 -0
- package/dist/DoStorageFailpoint.mjs +1 -0
- package/dist/DoStorageFailpointTesting.d.mts +21 -0
- package/dist/DoStorageFailpointTesting.mjs +18 -0
- package/dist/DoStorageFailpointTesting.mjs.map +1 -0
- package/dist/DoStorageVersion-BrolfBDS.mjs +7 -0
- package/dist/DoStorageVersion-BrolfBDS.mjs.map +1 -0
- package/dist/DoStorageVersion-D7CIxFc_.d.mts +8 -0
- package/dist/DoStorageVersion.d.mts +3 -0
- package/dist/DoStorageVersion.mjs +2 -0
- package/dist/DoSubmissionLedger-Oq5OstxL.mjs +1878 -0
- package/dist/DoSubmissionLedger-Oq5OstxL.mjs.map +1 -0
- package/dist/DoSubmissionLedger-tLjwidUn.d.mts +25 -0
- package/dist/DoSubmissionLedger.d.mts +2 -0
- package/dist/DoSubmissionLedger.mjs +1 -0
- package/dist/DoSubscriptionStore-BMJiFxt3.mjs +185 -0
- package/dist/DoSubscriptionStore-BMJiFxt3.mjs.map +1 -0
- package/dist/DoSubscriptionStore-zx6nfbbh.d.mts +25 -0
- package/dist/DoSubscriptionStore.d.mts +2 -0
- package/dist/DoSubscriptionStore.mjs +1 -0
- package/dist/DoThreadStore-2zTSfui-.d.mts +81 -0
- package/dist/DoThreadStore-CeYHcRR9.mjs +411 -0
- package/dist/DoThreadStore-CeYHcRR9.mjs.map +1 -0
- package/dist/DoThreadStore.d.mts +2 -0
- package/dist/DoThreadStore.mjs +5 -0
- package/dist/MemoryProtocol-CtCFYe4s.mjs +221 -0
- package/dist/MemoryProtocol-CtCFYe4s.mjs.map +1 -0
- package/dist/MemoryProtocol-DXV77CcJ.d.mts +38160 -0
- package/dist/MemoryProtocol.d.mts +2 -0
- package/dist/MemoryProtocol.mjs +1 -0
- package/dist/PortProtocol-4xvMyCgP.mjs +322 -0
- package/dist/PortProtocol-4xvMyCgP.mjs.map +1 -0
- package/dist/PortProtocol-DXuguAgD.d.mts +966 -0
- package/dist/PortProtocol.d.mts +2 -0
- package/dist/PortProtocol.mjs +1 -0
- package/dist/PortRouting-B9302ouX.mjs +683 -0
- package/dist/PortRouting-B9302ouX.mjs.map +1 -0
- package/dist/PortRouting-DsoI6soW.d.mts +105 -0
- package/dist/PortRouting.d.mts +2 -0
- package/dist/PortRouting.mjs +1 -0
- package/dist/do-journal-nPNEAjV5.mjs +769 -0
- package/dist/do-journal-nPNEAjV5.mjs.map +1 -0
- package/dist/index.d.mts +14 -0
- package/dist/index.mjs +14 -0
- package/dist/migrations-BRTvj8Ue.mjs +233 -0
- package/dist/migrations-BRTvj8Ue.mjs.map +1 -0
- package/dist/owned-state-DrOD9s0c.mjs +157 -0
- package/dist/owned-state-DrOD9s0c.mjs.map +1 -0
- package/dist/rolldown-runtime-D3KUYPsf.mjs +12 -0
- package/package.json +106 -3
- package/src/DoMemoryStore.ts +71 -0
- package/src/DoMessageDeliveryStore.ts +46 -0
- package/src/DoScheduleStore.ts +276 -0
- package/src/DoStorageConfig.ts +45 -0
- package/src/DoStorageError.ts +146 -0
- package/src/DoStorageFailpoint.ts +25 -0
- package/src/DoStorageFailpointTesting.ts +42 -0
- package/src/DoStorageVersion.ts +2 -0
- package/src/DoSubmissionLedger.ts +3980 -0
- package/src/DoSubscriptionStore.ts +331 -0
- package/src/DoThreadStore.ts +602 -0
- package/src/MemoryProtocol.ts +357 -0
- package/src/PortProtocol.ts +626 -0
- package/src/PortRouting.ts +1888 -0
- package/src/index.ts +13 -0
- package/src/internal/canonical-append.ts +15 -0
- package/src/internal/do-journal.ts +1449 -0
- package/src/internal/migrations.ts +395 -0
- package/src/internal/owned-state.ts +300 -0
- package/src/internal/prompt-checkpoint.ts +170 -0
- package/src/internal/storage-span.ts +54 -0
- package/README.md +0 -3
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
import * as SqliteClient from '@effect/sql-sqlite-do/SqliteClient'
|
|
2
|
+
import { makeStorageOwner, type StorageOwner } from '@systemfsoftware/agent/run-storage'
|
|
3
|
+
import * as Deferred from 'effect/Deferred'
|
|
4
|
+
import * as Effect from 'effect/Effect'
|
|
5
|
+
import * as Exit from 'effect/Exit'
|
|
6
|
+
import * as Predicate from 'effect/Predicate'
|
|
7
|
+
import * as Schema from 'effect/Schema'
|
|
8
|
+
import * as Scope from 'effect/Scope'
|
|
9
|
+
import * as Semaphore from 'effect/Semaphore'
|
|
10
|
+
import * as SqlClient from 'effect/sql/SqlClient'
|
|
11
|
+
import type * as SqlError from 'effect/sql/SqlError'
|
|
12
|
+
|
|
13
|
+
import { DoStorageCorruptionError, DoStorageError } from '../DoStorageError'
|
|
14
|
+
|
|
15
|
+
/** One disposable view per physical Object database, including separately acquired adapters. */
|
|
16
|
+
export class OwnedState {
|
|
17
|
+
constructor(readonly owner: StorageOwner['Service']) {}
|
|
18
|
+
readonly invalidators = new Set<() => void>()
|
|
19
|
+
|
|
20
|
+
readonly invalidate = Effect.sync(() => {
|
|
21
|
+
for (const invalidate of this.invalidators) invalidate()
|
|
22
|
+
})
|
|
23
|
+
|
|
24
|
+
/** Cached readers must wait for the complete transaction, including rollback/commit. */
|
|
25
|
+
readonly read = <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> => this.owner.withMutation(effect)
|
|
26
|
+
|
|
27
|
+
readonly transaction = <A, E, R>(
|
|
28
|
+
effect: Effect.Effect<A, E, R>,
|
|
29
|
+
): Effect.Effect<A, E | SqlError.SqlError, R | SqlClient.SqlClient> =>
|
|
30
|
+
this.read(
|
|
31
|
+
Effect.flatMap(SqlClient.SqlClient, (sql) =>
|
|
32
|
+
sql
|
|
33
|
+
.withTransaction(effect)
|
|
34
|
+
.pipe(Effect.onExit((exit) => (Exit.isFailure(exit) ? this.invalidate : Effect.void)))),
|
|
35
|
+
)
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
interface RetainedState {
|
|
39
|
+
readonly ready: Deferred.Deferred<OwnedState>
|
|
40
|
+
readonly disposed: Deferred.Deferred<void>
|
|
41
|
+
readonly scope: Scope.Closeable
|
|
42
|
+
references: number
|
|
43
|
+
closing: boolean
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const states = new WeakMap<object, RetainedState>()
|
|
47
|
+
|
|
48
|
+
/** Explicit invalidation for maintenance that writes private tables outside the adapters. */
|
|
49
|
+
export const invalidateOwnedState = (storage: DurableObjectStorage): Effect.Effect<void> =>
|
|
50
|
+
Effect.suspend(() => {
|
|
51
|
+
const state = states.get(storage)
|
|
52
|
+
|
|
53
|
+
return state === undefined
|
|
54
|
+
? Effect.void
|
|
55
|
+
: Deferred.await(state.ready).pipe(Effect.flatMap((state) => state.read(state.invalidate)))
|
|
56
|
+
})
|
|
57
|
+
|
|
58
|
+
const DoClient = Schema.declare<SqliteClient.SqliteClient>(
|
|
59
|
+
(value): value is SqliteClient.SqliteClient => Predicate.hasProperty(value, SqliteClient.TypeId),
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
export const ownedState = (sql: SqlClient.SqlClient) =>
|
|
63
|
+
Schema.decodeUnknownEffect(DoClient)(sql).pipe(
|
|
64
|
+
Effect.mapError(() =>
|
|
65
|
+
DoStorageError.make({
|
|
66
|
+
operation: 'open owned state',
|
|
67
|
+
message: 'Owned state requires a Durable Object SQLite client.',
|
|
68
|
+
})
|
|
69
|
+
),
|
|
70
|
+
Effect.flatMap((client) =>
|
|
71
|
+
Effect.uninterruptible(
|
|
72
|
+
Effect.gen(function*() {
|
|
73
|
+
// Instrumentation may return fresh wrappers; the physical Object identity owns the root.
|
|
74
|
+
const key = client.config.storage ?? client.config.db ?? client
|
|
75
|
+
|
|
76
|
+
for (;;) {
|
|
77
|
+
let retained = states.get(key)
|
|
78
|
+
|
|
79
|
+
if (retained?.closing) {
|
|
80
|
+
yield* Deferred.await(retained.disposed)
|
|
81
|
+
continue
|
|
82
|
+
}
|
|
83
|
+
if (retained === undefined) {
|
|
84
|
+
retained = {
|
|
85
|
+
ready: Deferred.makeUnsafe(),
|
|
86
|
+
disposed: Deferred.makeUnsafe(),
|
|
87
|
+
scope: Scope.makeUnsafe(),
|
|
88
|
+
references: 1,
|
|
89
|
+
closing: false,
|
|
90
|
+
}
|
|
91
|
+
states.set(key, retained)
|
|
92
|
+
|
|
93
|
+
const owner = yield* makeStorageOwner(Semaphore.makeUnsafe(1).withPermits(1)).pipe(
|
|
94
|
+
Scope.provide(retained.scope),
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
yield* Deferred.succeed(retained.ready, new OwnedState(owner))
|
|
98
|
+
} else retained.references++
|
|
99
|
+
const current = retained
|
|
100
|
+
|
|
101
|
+
yield* Effect.addFinalizer(() =>
|
|
102
|
+
Effect.uninterruptible(
|
|
103
|
+
Effect.gen(function*() {
|
|
104
|
+
current.references--
|
|
105
|
+
if (current.references !== 0) return
|
|
106
|
+
current.closing = true
|
|
107
|
+
yield* Scope.close(current.scope, Exit.void).pipe(
|
|
108
|
+
Effect.ensuring(
|
|
109
|
+
Effect.gen(function*() {
|
|
110
|
+
if (states.get(key) === current) states.delete(key)
|
|
111
|
+
yield* Deferred.succeed(current.disposed, undefined)
|
|
112
|
+
}),
|
|
113
|
+
),
|
|
114
|
+
)
|
|
115
|
+
}),
|
|
116
|
+
)
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
return yield* Deferred.await(current.ready)
|
|
120
|
+
}
|
|
121
|
+
}),
|
|
122
|
+
)
|
|
123
|
+
),
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Demand-loaded row views. Writes apply SQLite's RETURNING rows to affected retained views in
|
|
128
|
+
* the same transaction; rollback discards them. Bounded views avoid loading a host's entire
|
|
129
|
+
* retained submission history just to fence one live submission.
|
|
130
|
+
*/
|
|
131
|
+
export const ownedRows = <A, I>(
|
|
132
|
+
schema: Schema.Codec<A, I>,
|
|
133
|
+
table: string,
|
|
134
|
+
key: (row: A) => string,
|
|
135
|
+
identityColumn?: keyof A & string,
|
|
136
|
+
uniqueFields: ReadonlyArray<ReadonlyArray<keyof A & string>> = [],
|
|
137
|
+
projection: (sql: SqlClient.SqlClient) => ReturnType<SqlClient.SqlClient['literal']> = (sql) => sql.literal('*'),
|
|
138
|
+
) => {
|
|
139
|
+
type View = {
|
|
140
|
+
readonly id: string
|
|
141
|
+
readonly matches: (row: A) => boolean
|
|
142
|
+
readonly maxRows: number
|
|
143
|
+
readonly rows: ReadonlyArray<A>
|
|
144
|
+
readonly bytes: number
|
|
145
|
+
}
|
|
146
|
+
const caches = new WeakMap<OwnedState, Map<string, View>>()
|
|
147
|
+
const decodeRows = Schema.decodeUnknownEffect(Schema.Array(schema))
|
|
148
|
+
|
|
149
|
+
return (state: OwnedState, sql: SqlClient.SqlClient) => {
|
|
150
|
+
let cache = caches.get(state)
|
|
151
|
+
|
|
152
|
+
if (cache === undefined) {
|
|
153
|
+
cache = new Map()
|
|
154
|
+
caches.set(state, cache)
|
|
155
|
+
const current = cache
|
|
156
|
+
|
|
157
|
+
state.invalidators.add(() => current.clear())
|
|
158
|
+
}
|
|
159
|
+
const current = cache
|
|
160
|
+
|
|
161
|
+
const decode = (rows: unknown) =>
|
|
162
|
+
decodeRows(rows).pipe(
|
|
163
|
+
Effect.mapErrorEager(() =>
|
|
164
|
+
DoStorageCorruptionError.make({
|
|
165
|
+
table,
|
|
166
|
+
rowKey: 'owned-state',
|
|
167
|
+
message: 'Stored rows do not satisfy the storage schema',
|
|
168
|
+
})
|
|
169
|
+
),
|
|
170
|
+
)
|
|
171
|
+
|
|
172
|
+
const retain = (
|
|
173
|
+
id: string,
|
|
174
|
+
matches: View['matches'],
|
|
175
|
+
rows: ReadonlyArray<A>,
|
|
176
|
+
maxRows: number,
|
|
177
|
+
) => {
|
|
178
|
+
const bytes = new TextEncoder().encode(JSON.stringify(rows)).byteLength
|
|
179
|
+
|
|
180
|
+
current.delete(id)
|
|
181
|
+
if (rows.length > maxRows || bytes > 4 * 1024 * 1024) return
|
|
182
|
+
current.set(id, { id, matches, maxRows, rows, bytes })
|
|
183
|
+
let total = 0
|
|
184
|
+
|
|
185
|
+
for (const view of current.values()) total += view.bytes
|
|
186
|
+
while (current.size > 128 || total > 4 * 1024 * 1024) {
|
|
187
|
+
const oldest = current.entries().next().value
|
|
188
|
+
|
|
189
|
+
if (oldest === undefined) break
|
|
190
|
+
total -= oldest[1].bytes
|
|
191
|
+
current.delete(oldest[0])
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
const matching = (
|
|
196
|
+
id: string,
|
|
197
|
+
matches: View['matches'],
|
|
198
|
+
query: Effect.Effect<ReadonlyArray<unknown>, SqlError.SqlError>,
|
|
199
|
+
maxRows = Infinity,
|
|
200
|
+
) =>
|
|
201
|
+
state.read(
|
|
202
|
+
Effect.suspend(() => {
|
|
203
|
+
const view = current.get(id)
|
|
204
|
+
|
|
205
|
+
if (view !== undefined) return Effect.succeed(view.rows)
|
|
206
|
+
|
|
207
|
+
return Effect.flatMap(query, (rows) =>
|
|
208
|
+
Effect.mapEager(decode(rows), (rows) => {
|
|
209
|
+
retain(id, matches, rows, maxRows)
|
|
210
|
+
|
|
211
|
+
return rows
|
|
212
|
+
}))
|
|
213
|
+
}),
|
|
214
|
+
)
|
|
215
|
+
|
|
216
|
+
const by = (field: keyof A & string, value: string) =>
|
|
217
|
+
matching(
|
|
218
|
+
JSON.stringify([field, value]),
|
|
219
|
+
(row) => row[field] === value,
|
|
220
|
+
Effect.suspend(
|
|
221
|
+
() => sql`SELECT ${projection(sql)} FROM ${sql(table)} WHERE ${sql(field)} = ${value}`,
|
|
222
|
+
),
|
|
223
|
+
)
|
|
224
|
+
|
|
225
|
+
// Only a source mutation proving the complete result may seed a view. This must run
|
|
226
|
+
// under the owner transaction; rollback invalidates it with every other retained view.
|
|
227
|
+
const seed = (field: keyof A & string, value: string, rows: ReadonlyArray<A>) =>
|
|
228
|
+
retain(JSON.stringify([field, value]), (row) => row[field] === value, rows, Infinity)
|
|
229
|
+
|
|
230
|
+
const byFields = (fields: ReadonlyArray<readonly [keyof A & string, string]>) =>
|
|
231
|
+
matching(
|
|
232
|
+
JSON.stringify(fields),
|
|
233
|
+
(row) => fields.every(([field, value]) => row[field] === value),
|
|
234
|
+
Effect.suspend(
|
|
235
|
+
() =>
|
|
236
|
+
sql`SELECT ${projection(sql)} FROM ${sql(table)} WHERE ${
|
|
237
|
+
sql.and(fields.map(([field, value]) => sql`${sql(field)} = ${value}`))
|
|
238
|
+
}`,
|
|
239
|
+
),
|
|
240
|
+
)
|
|
241
|
+
|
|
242
|
+
const apply = (remove: boolean) => <E, R>(effect: Effect.Effect<ReadonlyArray<unknown>, E, R>) =>
|
|
243
|
+
Effect.gen(function*() {
|
|
244
|
+
const rows = yield* decode(yield* effect)
|
|
245
|
+
|
|
246
|
+
if (rows.length === 0) return rows
|
|
247
|
+
const changed = new Set(rows.map(key))
|
|
248
|
+
|
|
249
|
+
for (const { id, matches, maxRows, rows: prior } of Array.from(current.values())) {
|
|
250
|
+
const matchingRows = remove ? [] : rows.filter(matches)
|
|
251
|
+
|
|
252
|
+
if (matchingRows.length === 0 && !prior.some((row) => changed.has(key(row)))) continue
|
|
253
|
+
const next = prior.filter((row) => !changed.has(key(row)))
|
|
254
|
+
|
|
255
|
+
next.push(...matchingRows)
|
|
256
|
+
retain(id, matches, next, maxRows)
|
|
257
|
+
}
|
|
258
|
+
// A RETURNING row completely defines its unique-key view, even on a new Thread.
|
|
259
|
+
if (identityColumn !== undefined) {
|
|
260
|
+
for (const row of rows) {
|
|
261
|
+
const value = row[identityColumn]
|
|
262
|
+
|
|
263
|
+
if (typeof value === 'string') {
|
|
264
|
+
retain(
|
|
265
|
+
JSON.stringify([identityColumn, value]),
|
|
266
|
+
(row) => row[identityColumn] === value,
|
|
267
|
+
remove ? [] : [row],
|
|
268
|
+
Infinity,
|
|
269
|
+
)
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
for (const row of rows) {
|
|
275
|
+
for (const fields of uniqueFields) {
|
|
276
|
+
const values = fields.map((field) => [field, row[field]] as const)
|
|
277
|
+
|
|
278
|
+
retain(
|
|
279
|
+
JSON.stringify(values),
|
|
280
|
+
(candidate) => values.every(([field, value]) => candidate[field] === value),
|
|
281
|
+
remove ? [] : [row],
|
|
282
|
+
1,
|
|
283
|
+
)
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
return rows
|
|
288
|
+
})
|
|
289
|
+
|
|
290
|
+
return {
|
|
291
|
+
by,
|
|
292
|
+
byFields,
|
|
293
|
+
matching,
|
|
294
|
+
seed,
|
|
295
|
+
seedMatching: retain,
|
|
296
|
+
write: apply(false),
|
|
297
|
+
remove: apply(true),
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
}
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
import { utf8ByteLength } from '@systemfsoftware/agent/digest'
|
|
2
|
+
import {
|
|
3
|
+
MAX_PROMPT_CHECKPOINT_BYTES,
|
|
4
|
+
PromptCheckpoint,
|
|
5
|
+
PromptCheckpointHead,
|
|
6
|
+
PromptCheckpointRead,
|
|
7
|
+
type PromptCheckpoints,
|
|
8
|
+
ThreadStoreError,
|
|
9
|
+
} from '@systemfsoftware/agent/thread-store'
|
|
10
|
+
import * as Effect from 'effect/Effect'
|
|
11
|
+
import * as Option from 'effect/Option'
|
|
12
|
+
import * as Schema from 'effect/Schema'
|
|
13
|
+
import * as SqlClient from 'effect/sql/SqlClient'
|
|
14
|
+
|
|
15
|
+
import type { DoJournal } from './do-journal'
|
|
16
|
+
|
|
17
|
+
const Header = Schema.Struct({
|
|
18
|
+
...PromptCheckpointHead.fields,
|
|
19
|
+
chunks: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 64 })),
|
|
20
|
+
})
|
|
21
|
+
|
|
22
|
+
const decodeHeader = Schema.decodeEffect(Schema.fromJsonString(Header))
|
|
23
|
+
const encodeHeader = Schema.encodeEffect(Schema.fromJsonString(Header))
|
|
24
|
+
|
|
25
|
+
const decodeRows = Schema.decodeUnknownEffect(
|
|
26
|
+
Schema.Array(
|
|
27
|
+
Schema.Struct({
|
|
28
|
+
key: Schema.String,
|
|
29
|
+
value: Schema.String.check(Schema.isMaxLength(2_000_000)),
|
|
30
|
+
}),
|
|
31
|
+
).check(Schema.isMaxLength(65)),
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
const decodeWrite = Schema.decodeEffect(PromptCheckpoint)
|
|
35
|
+
const decodeRead = Schema.decodeEffect(PromptCheckpointRead)
|
|
36
|
+
|
|
37
|
+
export const promptCheckpointPrefix = (threadId: string) => `prompt-checkpoint/${JSON.stringify(threadId)}/`
|
|
38
|
+
|
|
39
|
+
const keyFor = (prefix: string, chunk: number) => prefix + String(chunk).padStart(5, '0')
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Versioned derivative keys use the adapter's existing metadata store. Canonical layout and
|
|
43
|
+
* export are unchanged. Chunking keeps SQL values below the DO limit; loading is one bounded
|
|
44
|
+
* query followed by one parse of the native prompt. Retain unchanged chunks when replacing
|
|
45
|
+
* the checkpoint, so append-only growth writes at most the old tail and new chunks.
|
|
46
|
+
*/
|
|
47
|
+
export const makePromptCheckpoints = (
|
|
48
|
+
sql: SqlClient.SqlClient,
|
|
49
|
+
journal: DoJournal,
|
|
50
|
+
maxValueBytes: number,
|
|
51
|
+
): PromptCheckpoints => ({
|
|
52
|
+
load: (input) =>
|
|
53
|
+
journal.state
|
|
54
|
+
.read(
|
|
55
|
+
Effect.gen(function*() {
|
|
56
|
+
const request = yield* decodeRead(input)
|
|
57
|
+
const prefix = promptCheckpointPrefix(request.threadId)
|
|
58
|
+
|
|
59
|
+
// Every row repeats the Thread ID. Bound those known key bytes separately from
|
|
60
|
+
// the prompt and header so supported long IDs do not consume the prompt allowance.
|
|
61
|
+
const maxHydratedBytes = MAX_PROMPT_CHECKPOINT_BYTES + 16_384 + 65 * utf8ByteLength(keyFor(prefix, 0))
|
|
62
|
+
|
|
63
|
+
const rows = yield* decodeRows(
|
|
64
|
+
yield* sql`
|
|
65
|
+
SELECT key, value FROM effect_agent_meta
|
|
66
|
+
WHERE key >= ${prefix} AND key < ${prefix + '~'}
|
|
67
|
+
AND (SELECT sum(length(CAST(key AS BLOB)) + length(CAST(value AS BLOB)))
|
|
68
|
+
FROM effect_agent_meta
|
|
69
|
+
WHERE key >= ${prefix} AND key < ${prefix + '~'})
|
|
70
|
+
<= ${maxHydratedBytes}
|
|
71
|
+
ORDER BY key LIMIT 66`,
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
const first = rows[0]
|
|
75
|
+
|
|
76
|
+
if (first === undefined || first.key !== keyFor(prefix, 0)) return Option.none()
|
|
77
|
+
const header = yield* decodeHeader(first.value)
|
|
78
|
+
|
|
79
|
+
if (
|
|
80
|
+
header.threadId !== request.threadId ||
|
|
81
|
+
header.historyThrough >= header.throughSequence ||
|
|
82
|
+
header.chunks !== rows.length - 1 ||
|
|
83
|
+
rows.some((row, index) => row.key !== keyFor(prefix, index))
|
|
84
|
+
) {
|
|
85
|
+
return Option.none()
|
|
86
|
+
}
|
|
87
|
+
const [head] = yield* journal.getThread(request.threadId)
|
|
88
|
+
|
|
89
|
+
if (
|
|
90
|
+
head === undefined ||
|
|
91
|
+
head.tail_sequence !== request.throughSequence ||
|
|
92
|
+
head.tail_sequence < header.throughSequence
|
|
93
|
+
) {
|
|
94
|
+
return Option.none()
|
|
95
|
+
}
|
|
96
|
+
let bytes = 0
|
|
97
|
+
|
|
98
|
+
for (const row of rows) {
|
|
99
|
+
bytes += utf8ByteLength(row.value)
|
|
100
|
+
if (bytes > MAX_PROMPT_CHECKPOINT_BYTES + 16_384) return Option.none()
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
return Option.some({
|
|
104
|
+
...header,
|
|
105
|
+
promptJson: rows
|
|
106
|
+
.slice(1)
|
|
107
|
+
.map((row) => row.value)
|
|
108
|
+
.join(''),
|
|
109
|
+
})
|
|
110
|
+
}),
|
|
111
|
+
)
|
|
112
|
+
.pipe(Effect.orElseSucceed(() => Option.none())),
|
|
113
|
+
save: Effect.fnUntraced(
|
|
114
|
+
function*(input) {
|
|
115
|
+
const checkpoint = yield* decodeWrite(input)
|
|
116
|
+
|
|
117
|
+
if (
|
|
118
|
+
utf8ByteLength(checkpoint.promptJson) > MAX_PROMPT_CHECKPOINT_BYTES ||
|
|
119
|
+
checkpoint.historyThrough >= checkpoint.throughSequence
|
|
120
|
+
) {
|
|
121
|
+
return
|
|
122
|
+
}
|
|
123
|
+
const prefix = promptCheckpointPrefix(checkpoint.threadId)
|
|
124
|
+
const chunks: Array<string> = []
|
|
125
|
+
// Three UTF-8 bytes per UTF-16 code unit is a conservative bound. Keep surrogate pairs
|
|
126
|
+
// together so SQLite never normalizes an isolated half while persisting a chunk.
|
|
127
|
+
const chars = Math.floor(Math.min(maxValueBytes - 4_096, 1_000_000) / 3)
|
|
128
|
+
|
|
129
|
+
if (chars < 1) return
|
|
130
|
+
for (let offset = 0; offset < checkpoint.promptJson.length;) {
|
|
131
|
+
let end = Math.min(offset + chars, checkpoint.promptJson.length)
|
|
132
|
+
const last = checkpoint.promptJson.charCodeAt(end - 1)
|
|
133
|
+
|
|
134
|
+
if (last >= 0xd800 && last <= 0xdbff) end--
|
|
135
|
+
if (end <= offset || chunks.length >= 64) return
|
|
136
|
+
chunks.push(checkpoint.promptJson.slice(offset, end))
|
|
137
|
+
offset = end
|
|
138
|
+
}
|
|
139
|
+
const header = yield* encodeHeader({ ...checkpoint, chunks: chunks.length })
|
|
140
|
+
|
|
141
|
+
yield* journal.state
|
|
142
|
+
.transaction(
|
|
143
|
+
Effect.gen(function*() {
|
|
144
|
+
const [head] = yield* journal.getThread(checkpoint.threadId)
|
|
145
|
+
|
|
146
|
+
if (head === undefined || head.tail_sequence !== checkpoint.throughSequence) return
|
|
147
|
+
yield* sql`DELETE FROM effect_agent_meta WHERE key >= ${keyFor(prefix, chunks.length + 1)} AND key < ${
|
|
148
|
+
prefix + '~'
|
|
149
|
+
}`
|
|
150
|
+
for (const [index, value] of [header, ...chunks].entries()) {
|
|
151
|
+
yield* sql`INSERT INTO effect_agent_meta (key, value) VALUES (${keyFor(prefix, index)}, ${value})
|
|
152
|
+
ON CONFLICT (key) DO UPDATE SET value = excluded.value
|
|
153
|
+
WHERE effect_agent_meta.value <> excluded.value`
|
|
154
|
+
}
|
|
155
|
+
}),
|
|
156
|
+
)
|
|
157
|
+
.pipe(Effect.provideService(SqlClient.SqlClient, sql))
|
|
158
|
+
},
|
|
159
|
+
(effect) =>
|
|
160
|
+
effect.pipe(
|
|
161
|
+
Effect.mapError((cause) =>
|
|
162
|
+
ThreadStoreError.make({
|
|
163
|
+
operation: 'save prompt checkpoint',
|
|
164
|
+
message: 'Unable to retain a disposable prompt checkpoint',
|
|
165
|
+
cause,
|
|
166
|
+
})
|
|
167
|
+
),
|
|
168
|
+
),
|
|
169
|
+
),
|
|
170
|
+
})
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import * as Effect from 'effect/Effect'
|
|
2
|
+
import * as Predicate from 'effect/Predicate'
|
|
3
|
+
import * as References from 'effect/References'
|
|
4
|
+
import * as Result from 'effect/Result'
|
|
5
|
+
import * as Tracer from 'effect/Tracer'
|
|
6
|
+
|
|
7
|
+
type Tagged = { readonly _tag: string; readonly reason?: unknown }
|
|
8
|
+
|
|
9
|
+
export const isAppendContention = (error: Tagged): boolean =>
|
|
10
|
+
(error._tag === 'DoAppendConflict' || error._tag === 'AppendConflict') && error.reason === 'tail'
|
|
11
|
+
|
|
12
|
+
/** Expected refusals remain typed at the port, but are outcomes of the storage operation. */
|
|
13
|
+
export const storageResult = <A, E extends Tagged, R>(
|
|
14
|
+
effect: Effect.Effect<A, E, R>,
|
|
15
|
+
expected: (error: E) => boolean,
|
|
16
|
+
) =>
|
|
17
|
+
effect.pipe(
|
|
18
|
+
Effect.map(Result.succeed),
|
|
19
|
+
Effect.catchIf(expected, (error) => Effect.succeed(Result.fail(error))),
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
/** Only error discriminants enter telemetry; messages, SQL, identities and payloads do not. */
|
|
23
|
+
export const annotateStorageError = (error: Tagged) =>
|
|
24
|
+
Effect.annotateCurrentSpan({
|
|
25
|
+
'error.type': error._tag,
|
|
26
|
+
...(Predicate.hasProperty(error, 'cause') &&
|
|
27
|
+
Predicate.hasProperty(error.cause, '_tag') &&
|
|
28
|
+
typeof error.cause._tag === 'string'
|
|
29
|
+
? { 'error.cause.type': error.cause._tag }
|
|
30
|
+
: {}),
|
|
31
|
+
})
|
|
32
|
+
|
|
33
|
+
export const withStorageSpan = (
|
|
34
|
+
name: string,
|
|
35
|
+
expected: (error: Tagged) => boolean = () => false,
|
|
36
|
+
) => {
|
|
37
|
+
const span = Effect.withSpan(name)
|
|
38
|
+
|
|
39
|
+
return <A, E extends Tagged, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>
|
|
40
|
+
Effect.withFiber((fiber) =>
|
|
41
|
+
!fiber.getRef(References.TracerEnabled) || fiber.getRef(Tracer.Tracer) === Tracer.nativeTracer
|
|
42
|
+
? effect
|
|
43
|
+
: storageResult(effect, expected).pipe(
|
|
44
|
+
Effect.tap((result) =>
|
|
45
|
+
Result.isFailure(result)
|
|
46
|
+
? Effect.annotateCurrentSpan({ 'storage.outcome': result.failure._tag })
|
|
47
|
+
: Effect.void
|
|
48
|
+
),
|
|
49
|
+
Effect.tapError(annotateStorageError),
|
|
50
|
+
span,
|
|
51
|
+
Effect.flatMap(Effect.fromResult),
|
|
52
|
+
)
|
|
53
|
+
)
|
|
54
|
+
}
|
package/README.md
DELETED