@effect-agent/storage-sqlite 0.0.1-beta.0
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/dist/index.d.mts +193 -0
- package/dist/index.mjs +3063 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +41 -0
- package/src/errors.ts +164 -0
- package/src/index.ts +6 -0
- package/src/migrations.ts +275 -0
- package/src/sqlite-conversation-store.ts +841 -0
- package/src/sqlite-journal.ts +1065 -0
- package/src/sqlite-ledger.ts +2818 -0
- package/src/sqlite-storage-config.ts +37 -0
- package/src/sqlite-storage-failpoint.ts +50 -0
|
@@ -0,0 +1,2818 @@
|
|
|
1
|
+
import {
|
|
2
|
+
AbortCommand,
|
|
3
|
+
AbortIntent,
|
|
4
|
+
AdmissionAdmitted,
|
|
5
|
+
AdmissionConflict,
|
|
6
|
+
AdmissionNotAdmitted,
|
|
7
|
+
AdmissionRequest,
|
|
8
|
+
AdmissionResult,
|
|
9
|
+
ApprovalConflict,
|
|
10
|
+
ApprovalDecision,
|
|
11
|
+
ApprovalDecisionCommand,
|
|
12
|
+
ApprovalDecisionIntent,
|
|
13
|
+
AttachChildToReservationRequest,
|
|
14
|
+
BeginChildBudgetReleaseRequest,
|
|
15
|
+
CanonicalSequence,
|
|
16
|
+
ChildAttachmentSnapshot,
|
|
17
|
+
ChildBudgetReservationRequest,
|
|
18
|
+
ChildBudgetReservationSnapshot,
|
|
19
|
+
ChildReservationConflict,
|
|
20
|
+
ChildReservationStatus,
|
|
21
|
+
ChildSettledNotification,
|
|
22
|
+
Claim,
|
|
23
|
+
ClaimJoiningRequest,
|
|
24
|
+
ClaimRequest,
|
|
25
|
+
DefinitionDigests,
|
|
26
|
+
Digest,
|
|
27
|
+
EMPTY_TAIL_DIGEST,
|
|
28
|
+
InputAppliedMarker,
|
|
29
|
+
JoinSnapshot,
|
|
30
|
+
JoinedToHost,
|
|
31
|
+
JoiningClaim,
|
|
32
|
+
LedgerCapabilities,
|
|
33
|
+
LedgerError,
|
|
34
|
+
MarkInputAppliedRequest,
|
|
35
|
+
MarkJoinedRequest,
|
|
36
|
+
MarkReadyRequest,
|
|
37
|
+
MarkUnknownRequest,
|
|
38
|
+
OwnershipLost,
|
|
39
|
+
OwnershipRenewal,
|
|
40
|
+
OwnershipSnapshot,
|
|
41
|
+
ParentLinkage,
|
|
42
|
+
PersistedJson,
|
|
43
|
+
ProducerEpoch,
|
|
44
|
+
QueueSequence,
|
|
45
|
+
RecordEnvelope,
|
|
46
|
+
RecoverySnapshot,
|
|
47
|
+
RecoverySnapshotRequest,
|
|
48
|
+
ReleaseChildBudgetRequest,
|
|
49
|
+
ReleaseOwnershipRequest,
|
|
50
|
+
RenewOwnershipRequest,
|
|
51
|
+
ReservedChildBudget,
|
|
52
|
+
ReservedSettlement,
|
|
53
|
+
RevertJoiningRequest,
|
|
54
|
+
Settlement,
|
|
55
|
+
SettlementConflict,
|
|
56
|
+
SettlementFinalization,
|
|
57
|
+
SettlementOutcome,
|
|
58
|
+
SettlementReservation,
|
|
59
|
+
SubmissionLedger,
|
|
60
|
+
SubmissionLookup,
|
|
61
|
+
SubmissionLookupByKey,
|
|
62
|
+
SubmissionSnapshot,
|
|
63
|
+
SubmissionState,
|
|
64
|
+
SettlementReservationSnapshot,
|
|
65
|
+
SuspendRequest,
|
|
66
|
+
SuspensionReason,
|
|
67
|
+
SuspensionSnapshot,
|
|
68
|
+
UnknownResolution,
|
|
69
|
+
UnknownResolutionCommand,
|
|
70
|
+
UnknownResolutionConflict,
|
|
71
|
+
UnknownResolutionIntent,
|
|
72
|
+
submissionAbortRecordId,
|
|
73
|
+
type ChildSettledOutcome,
|
|
74
|
+
type SuspensionOutcome,
|
|
75
|
+
} from "@effect-agent/session";
|
|
76
|
+
import { NodeCrypto } from "@effect/platform-node";
|
|
77
|
+
import { SqliteClient } from "@effect/sql-sqlite-node";
|
|
78
|
+
import { Clock, Context, Crypto, DateTime, Effect, Layer, Option, Schema, Stream } from "effect";
|
|
79
|
+
import * as SqlClientService from "effect/unstable/sql/SqlClient";
|
|
80
|
+
import type { SqlError } from "effect/unstable/sql/SqlError";
|
|
81
|
+
|
|
82
|
+
import {
|
|
83
|
+
SqliteLedgerError,
|
|
84
|
+
SqliteStorageCorruptionError,
|
|
85
|
+
SqliteStorageError,
|
|
86
|
+
SqliteWriteContention,
|
|
87
|
+
type SqliteStorageFailpointLocation,
|
|
88
|
+
} from "./errors.ts";
|
|
89
|
+
import {
|
|
90
|
+
storageConfigLayer,
|
|
91
|
+
storageFailpointLayer,
|
|
92
|
+
type SqliteStorageInitializationError,
|
|
93
|
+
type SqliteStorageOptions,
|
|
94
|
+
} from "./sqlite-conversation-store.ts";
|
|
95
|
+
import { decodeRows, initializeSqliteJournal } from "./sqlite-journal.ts";
|
|
96
|
+
import { SqliteStorageConfig } from "./sqlite-storage-config.ts";
|
|
97
|
+
import { SqliteStorageFailpoint } from "./sqlite-storage-failpoint.ts";
|
|
98
|
+
|
|
99
|
+
type SubmissionId = SubmissionSnapshot["submissionId"];
|
|
100
|
+
|
|
101
|
+
const BoundedStoredText = Schema.String.check(Schema.isMaxLength(16 * 1024 * 1024));
|
|
102
|
+
const BoundedIdentifier = Schema.NonEmptyString.check(Schema.isMaxLength(1024));
|
|
103
|
+
const BoundedTimestamp = Schema.NonEmptyString.check(Schema.isMaxLength(128));
|
|
104
|
+
|
|
105
|
+
const SCAN_PAGE_SIZE = 256;
|
|
106
|
+
const EPOCH_ZERO = Schema.decodeSync(ProducerEpoch)(0);
|
|
107
|
+
|
|
108
|
+
class SubmissionRow extends Schema.Class<SubmissionRow>("SubmissionRow")({
|
|
109
|
+
submission_id: BoundedIdentifier,
|
|
110
|
+
conversation_id: BoundedIdentifier,
|
|
111
|
+
queue_sequence: QueueSequence,
|
|
112
|
+
principal: BoundedIdentifier,
|
|
113
|
+
idempotency_key: BoundedIdentifier,
|
|
114
|
+
agent_id: BoundedIdentifier,
|
|
115
|
+
agent_digests_json: BoundedStoredText,
|
|
116
|
+
deployment_id: BoundedIdentifier,
|
|
117
|
+
input_json: BoundedStoredText,
|
|
118
|
+
input_digest: Digest,
|
|
119
|
+
receipt_id: BoundedIdentifier,
|
|
120
|
+
state: SubmissionState,
|
|
121
|
+
settled_outcome: Schema.NullOr(SettlementOutcome),
|
|
122
|
+
created_at: BoundedTimestamp,
|
|
123
|
+
ready_at: Schema.NullOr(BoundedTimestamp),
|
|
124
|
+
input_applied_record_id: Schema.NullOr(BoundedIdentifier),
|
|
125
|
+
input_applied_sequence: Schema.NullOr(CanonicalSequence),
|
|
126
|
+
joined_host_submission_id: Schema.NullOr(BoundedIdentifier),
|
|
127
|
+
suspended_reason_json: Schema.NullOr(BoundedStoredText),
|
|
128
|
+
suspended_at: Schema.NullOr(BoundedTimestamp),
|
|
129
|
+
unknown_reason: Schema.NullOr(BoundedStoredText),
|
|
130
|
+
unknown_tool_call_ids_json: Schema.NullOr(BoundedStoredText),
|
|
131
|
+
parent_submission_id: Schema.NullOr(BoundedIdentifier),
|
|
132
|
+
parent_tool_call_id: Schema.NullOr(BoundedIdentifier),
|
|
133
|
+
}) {}
|
|
134
|
+
|
|
135
|
+
class ChildReservationRow extends Schema.Class<ChildReservationRow>("ChildReservationRow")({
|
|
136
|
+
reservation_id: BoundedIdentifier,
|
|
137
|
+
parent_submission_id: BoundedIdentifier,
|
|
138
|
+
parent_tool_call_id: BoundedIdentifier,
|
|
139
|
+
child_submission_id: Schema.NullOr(BoundedIdentifier),
|
|
140
|
+
status: ChildReservationStatus,
|
|
141
|
+
allocation_json: BoundedStoredText,
|
|
142
|
+
allocation_digest: Digest,
|
|
143
|
+
accounting_json: Schema.NullOr(BoundedStoredText),
|
|
144
|
+
reserved_at: BoundedTimestamp,
|
|
145
|
+
release_began_at: Schema.NullOr(BoundedTimestamp),
|
|
146
|
+
released_at: Schema.NullOr(BoundedTimestamp),
|
|
147
|
+
}) {}
|
|
148
|
+
|
|
149
|
+
class ApprovalDecisionRow extends Schema.Class<ApprovalDecisionRow>("ApprovalDecisionRow")({
|
|
150
|
+
submission_id: BoundedIdentifier,
|
|
151
|
+
tool_call_id: BoundedIdentifier,
|
|
152
|
+
decision: ApprovalDecision,
|
|
153
|
+
resolver: BoundedIdentifier,
|
|
154
|
+
reason: BoundedStoredText,
|
|
155
|
+
decided_at: BoundedTimestamp,
|
|
156
|
+
}) {}
|
|
157
|
+
|
|
158
|
+
class UnknownResolutionRow extends Schema.Class<UnknownResolutionRow>("UnknownResolutionRow")({
|
|
159
|
+
submission_id: BoundedIdentifier,
|
|
160
|
+
tool_call_id: BoundedIdentifier,
|
|
161
|
+
author: BoundedIdentifier,
|
|
162
|
+
reason: BoundedStoredText,
|
|
163
|
+
resolution_json: BoundedStoredText,
|
|
164
|
+
resolved_at: BoundedTimestamp,
|
|
165
|
+
}) {}
|
|
166
|
+
|
|
167
|
+
class OwnershipRow extends Schema.Class<OwnershipRow>("OwnershipRow")({
|
|
168
|
+
submission_id: BoundedIdentifier,
|
|
169
|
+
attempt_id: BoundedIdentifier,
|
|
170
|
+
ownership_token: BoundedIdentifier,
|
|
171
|
+
producer_epoch: ProducerEpoch,
|
|
172
|
+
owner_producer_id: BoundedIdentifier,
|
|
173
|
+
lease_expires_at: BoundedTimestamp,
|
|
174
|
+
}) {}
|
|
175
|
+
|
|
176
|
+
class ReservationRow extends Schema.Class<ReservationRow>("ReservationRow")({
|
|
177
|
+
submission_id: BoundedIdentifier,
|
|
178
|
+
settlement_id: BoundedIdentifier,
|
|
179
|
+
outcome: SettlementOutcome,
|
|
180
|
+
record_id: BoundedIdentifier,
|
|
181
|
+
record_json: BoundedStoredText,
|
|
182
|
+
record_digest: Digest,
|
|
183
|
+
reserved_at: BoundedTimestamp,
|
|
184
|
+
finalized_at: Schema.NullOr(BoundedTimestamp),
|
|
185
|
+
}) {}
|
|
186
|
+
|
|
187
|
+
class AbortIntentRow extends Schema.Class<AbortIntentRow>("AbortIntentRow")({
|
|
188
|
+
submission_id: BoundedIdentifier,
|
|
189
|
+
author: BoundedIdentifier,
|
|
190
|
+
reason: BoundedStoredText,
|
|
191
|
+
requested_at: BoundedTimestamp,
|
|
192
|
+
canonical_record_id: Schema.NullOr(BoundedIdentifier),
|
|
193
|
+
}) {}
|
|
194
|
+
|
|
195
|
+
class MaxQueueSequenceRow extends Schema.Class<MaxQueueSequenceRow>("MaxQueueSequenceRow")({
|
|
196
|
+
max_queue_sequence: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
|
|
197
|
+
}) {}
|
|
198
|
+
|
|
199
|
+
class CanonicalRecordIdRow extends Schema.Class<CanonicalRecordIdRow>("CanonicalRecordIdRow")({
|
|
200
|
+
record_id: BoundedIdentifier,
|
|
201
|
+
}) {}
|
|
202
|
+
|
|
203
|
+
const SUBMISSION_COLUMNS = `
|
|
204
|
+
submission_id,
|
|
205
|
+
conversation_id,
|
|
206
|
+
queue_sequence,
|
|
207
|
+
principal,
|
|
208
|
+
idempotency_key,
|
|
209
|
+
agent_id,
|
|
210
|
+
agent_digests_json,
|
|
211
|
+
deployment_id,
|
|
212
|
+
input_json,
|
|
213
|
+
input_digest,
|
|
214
|
+
receipt_id,
|
|
215
|
+
state,
|
|
216
|
+
settled_outcome,
|
|
217
|
+
created_at,
|
|
218
|
+
ready_at,
|
|
219
|
+
input_applied_record_id,
|
|
220
|
+
input_applied_sequence,
|
|
221
|
+
joined_host_submission_id,
|
|
222
|
+
suspended_reason_json,
|
|
223
|
+
suspended_at,
|
|
224
|
+
unknown_reason,
|
|
225
|
+
unknown_tool_call_ids_json,
|
|
226
|
+
parent_submission_id,
|
|
227
|
+
parent_tool_call_id
|
|
228
|
+
`;
|
|
229
|
+
|
|
230
|
+
const CHILD_RESERVATION_COLUMNS = `
|
|
231
|
+
reservation_id,
|
|
232
|
+
parent_submission_id,
|
|
233
|
+
parent_tool_call_id,
|
|
234
|
+
child_submission_id,
|
|
235
|
+
status,
|
|
236
|
+
allocation_json,
|
|
237
|
+
allocation_digest,
|
|
238
|
+
accounting_json,
|
|
239
|
+
reserved_at,
|
|
240
|
+
release_began_at,
|
|
241
|
+
released_at
|
|
242
|
+
`;
|
|
243
|
+
|
|
244
|
+
/** The branded ToolCallId schema, reached through the session port so no core import is needed. */
|
|
245
|
+
const ToolCallIdSchema = ApprovalDecisionCommand.fields.toolCallId;
|
|
246
|
+
const ToolCallIdList = Schema.Array(ToolCallIdSchema);
|
|
247
|
+
|
|
248
|
+
const encodePersistedJsonText = Schema.encodeEffect(Schema.fromJsonString(PersistedJson));
|
|
249
|
+
const encodeDefinitionDigestsText = Schema.encodeEffect(Schema.fromJsonString(DefinitionDigests));
|
|
250
|
+
const encodeRecordEnvelopeText = Schema.encodeEffect(Schema.fromJsonString(RecordEnvelope));
|
|
251
|
+
const decodeRecordEnvelopeText = Schema.decodeEffect(Schema.fromJsonString(RecordEnvelope));
|
|
252
|
+
const encodeSuspensionReasonText = Schema.encodeEffect(Schema.fromJsonString(SuspensionReason));
|
|
253
|
+
const encodeUnknownResolutionText = Schema.encodeEffect(Schema.fromJsonString(UnknownResolution));
|
|
254
|
+
const encodeToolCallIdsText = Schema.encodeEffect(Schema.fromJsonString(ToolCallIdList));
|
|
255
|
+
const decodeToolCallIdsText = Schema.decodeEffect(Schema.fromJsonString(ToolCallIdList));
|
|
256
|
+
const parseStoredJsonText = Schema.decodeEffect(Schema.fromJsonString(Schema.Json));
|
|
257
|
+
const decodeAdmissionResult = Schema.decodeUnknownEffect(AdmissionResult);
|
|
258
|
+
const decodeClaim = Schema.decodeUnknownEffect(Claim);
|
|
259
|
+
const decodeOwnershipRenewal = Schema.decodeUnknownEffect(OwnershipRenewal);
|
|
260
|
+
const decodeSettlement = Schema.decodeUnknownEffect(Settlement);
|
|
261
|
+
const decodeAbortIntent = Schema.decodeUnknownEffect(AbortIntent);
|
|
262
|
+
const decodeOwnershipSnapshot = Schema.decodeUnknownEffect(OwnershipSnapshot);
|
|
263
|
+
const decodeInputAppliedMarker = Schema.decodeUnknownEffect(InputAppliedMarker);
|
|
264
|
+
const decodeSubmissionSnapshotUnknown = Schema.decodeUnknownEffect(SubmissionSnapshot);
|
|
265
|
+
const decodeSubmissionId = Schema.decodeUnknownEffect(SubmissionSnapshot.fields.submissionId);
|
|
266
|
+
const decodeQueueSequence = Schema.decodeUnknownEffect(QueueSequence);
|
|
267
|
+
const decodeUtcInstant = Schema.decodeUnknownEffect(Schema.DateTimeUtcFromString);
|
|
268
|
+
const decodeJoiningClaim = Schema.decodeUnknownEffect(JoiningClaim);
|
|
269
|
+
const decodeJoinSnapshot = Schema.decodeUnknownEffect(JoinSnapshot);
|
|
270
|
+
const decodeSuspensionSnapshot = Schema.decodeUnknownEffect(SuspensionSnapshot);
|
|
271
|
+
const decodeApprovalDecisionIntent = Schema.decodeUnknownEffect(ApprovalDecisionIntent);
|
|
272
|
+
const decodeUnknownResolutionIntent = Schema.decodeUnknownEffect(UnknownResolutionIntent);
|
|
273
|
+
const decodeParentLinkage = Schema.decodeUnknownEffect(ParentLinkage);
|
|
274
|
+
const decodeChildReservationSnapshotUnknown = Schema.decodeUnknownEffect(
|
|
275
|
+
ChildBudgetReservationSnapshot,
|
|
276
|
+
);
|
|
277
|
+
const decodeChildAttachmentSnapshot = Schema.decodeUnknownEffect(ChildAttachmentSnapshot);
|
|
278
|
+
|
|
279
|
+
/** Wrap an adapter-internal failure into the port's LedgerError without erasing its tag. */
|
|
280
|
+
const internalFailure =
|
|
281
|
+
(operation: string) =>
|
|
282
|
+
(error: { readonly message: string }): LedgerError =>
|
|
283
|
+
LedgerError.make({ operation, message: error.message, cause: error });
|
|
284
|
+
|
|
285
|
+
/** Classify raw SQL failures: write-lock timeouts stay retryable typed contention. */
|
|
286
|
+
const sqlFailure =
|
|
287
|
+
(operation: string) =>
|
|
288
|
+
(error: SqlError): LedgerError => {
|
|
289
|
+
const internal =
|
|
290
|
+
error.reason._tag === "LockTimeoutError"
|
|
291
|
+
? SqliteWriteContention.make({
|
|
292
|
+
cause: error,
|
|
293
|
+
operation,
|
|
294
|
+
message: `Another producer holds the SQLite write lock; ${operation} is safe to retry.`,
|
|
295
|
+
})
|
|
296
|
+
: SqliteLedgerError.make({
|
|
297
|
+
cause: error,
|
|
298
|
+
operation,
|
|
299
|
+
message: error.message,
|
|
300
|
+
});
|
|
301
|
+
return internalFailure(operation)(internal);
|
|
302
|
+
};
|
|
303
|
+
|
|
304
|
+
const corruptionFailure = (operation: string, table: string, rowKey: string, message: string) =>
|
|
305
|
+
internalFailure(operation)(SqliteStorageCorruptionError.make({ table, rowKey, message }));
|
|
306
|
+
|
|
307
|
+
const makeServices = Effect.fn("SqliteSubmissionLedger.makeServices")(function* () {
|
|
308
|
+
const config = yield* SqliteStorageConfig;
|
|
309
|
+
const failpoint = yield* SqliteStorageFailpoint;
|
|
310
|
+
const sql = yield* SqlClientService.SqlClient;
|
|
311
|
+
const crypto = yield* Crypto.Crypto;
|
|
312
|
+
const journal = yield* initializeSqliteJournal(sql, failpoint.hit, config.busyTimeout);
|
|
313
|
+
|
|
314
|
+
const hitFailpoint = (
|
|
315
|
+
location: SqliteStorageFailpointLocation,
|
|
316
|
+
operation: string,
|
|
317
|
+
): Effect.Effect<void, LedgerError> =>
|
|
318
|
+
failpoint.hit(location).pipe(Effect.mapError((error) => internalFailure(operation)(error)));
|
|
319
|
+
|
|
320
|
+
/**
|
|
321
|
+
* Run one ledger mutation under the journal's `BEGIN IMMEDIATE` write transaction so
|
|
322
|
+
* ownership-token and epoch checks are atomic with their writes (DUR-006). Transaction
|
|
323
|
+
* acquisition failures surface as LedgerError carrying the typed retryable
|
|
324
|
+
* SqliteWriteContention (or SqliteStorageError) as cause.
|
|
325
|
+
*/
|
|
326
|
+
const inWriteTransaction = <
|
|
327
|
+
A,
|
|
328
|
+
E extends
|
|
329
|
+
| AdmissionConflict
|
|
330
|
+
| ApprovalConflict
|
|
331
|
+
| ChildReservationConflict
|
|
332
|
+
| JoinedToHost
|
|
333
|
+
| OwnershipLost
|
|
334
|
+
| SettlementConflict
|
|
335
|
+
| UnknownResolutionConflict
|
|
336
|
+
| LedgerError,
|
|
337
|
+
>(
|
|
338
|
+
operation: string,
|
|
339
|
+
effect: Effect.Effect<A, E>,
|
|
340
|
+
): Effect.Effect<A, E | LedgerError> =>
|
|
341
|
+
journal
|
|
342
|
+
.withWriteTransaction(operation)(effect)
|
|
343
|
+
.pipe(
|
|
344
|
+
Effect.mapError((error) =>
|
|
345
|
+
error instanceof SqliteStorageError || error instanceof SqliteWriteContention
|
|
346
|
+
? internalFailure(operation)(error)
|
|
347
|
+
: error,
|
|
348
|
+
),
|
|
349
|
+
);
|
|
350
|
+
|
|
351
|
+
const mintIdentifier = (prefix: string, operation: string): Effect.Effect<string, LedgerError> =>
|
|
352
|
+
crypto.randomUUIDv7.pipe(
|
|
353
|
+
Effect.map((uuid) => `${prefix}-${uuid}`),
|
|
354
|
+
Effect.mapError((error) => internalFailure(operation)(error)),
|
|
355
|
+
);
|
|
356
|
+
|
|
357
|
+
const currentInstant = Effect.map(Clock.currentTimeMillis, (millis) => ({
|
|
358
|
+
millis,
|
|
359
|
+
iso: new Date(millis).toISOString(),
|
|
360
|
+
}));
|
|
361
|
+
|
|
362
|
+
const timestampMillis = (operation: string, rowKey: string) => (timestamp: string) =>
|
|
363
|
+
decodeUtcInstant(timestamp).pipe(
|
|
364
|
+
Effect.map(DateTime.toEpochMillis),
|
|
365
|
+
Effect.mapError((error) =>
|
|
366
|
+
corruptionFailure(operation, "effect_agent_submission_ownership", rowKey, error.message),
|
|
367
|
+
),
|
|
368
|
+
);
|
|
369
|
+
|
|
370
|
+
const decodeSubmissionRows = (operation: string, rowKey: string, rows: unknown) =>
|
|
371
|
+
decodeRows(Schema.Array(SubmissionRow), "effect_agent_submissions", rowKey, rows).pipe(
|
|
372
|
+
Effect.mapError(internalFailure(operation)),
|
|
373
|
+
);
|
|
374
|
+
|
|
375
|
+
const readSubmission = Effect.fn("SqliteSubmissionLedger.readSubmission")(function* (
|
|
376
|
+
operation: string,
|
|
377
|
+
submissionId: string,
|
|
378
|
+
): Effect.fn.Return<Option.Option<SubmissionRow>, LedgerError> {
|
|
379
|
+
const rows = yield* sql<Record<string, unknown>>`
|
|
380
|
+
SELECT ${sql.literal(SUBMISSION_COLUMNS)}
|
|
381
|
+
FROM effect_agent_submissions
|
|
382
|
+
WHERE submission_id = ${submissionId}
|
|
383
|
+
`.pipe(Effect.mapError(sqlFailure(operation)));
|
|
384
|
+
const decoded = yield* decodeSubmissionRows(operation, submissionId, rows);
|
|
385
|
+
if (decoded.length > 1) {
|
|
386
|
+
return yield* corruptionFailure(
|
|
387
|
+
operation,
|
|
388
|
+
"effect_agent_submissions",
|
|
389
|
+
submissionId,
|
|
390
|
+
"A submission primary key returned more than one row.",
|
|
391
|
+
);
|
|
392
|
+
}
|
|
393
|
+
return decoded.length === 0 ? Option.none() : Option.some(decoded[0]);
|
|
394
|
+
});
|
|
395
|
+
|
|
396
|
+
const requireSubmission = Effect.fn("SqliteSubmissionLedger.requireSubmission")(function* (
|
|
397
|
+
operation: string,
|
|
398
|
+
submissionId: string,
|
|
399
|
+
): Effect.fn.Return<SubmissionRow, LedgerError> {
|
|
400
|
+
const submission = yield* readSubmission(operation, submissionId);
|
|
401
|
+
if (Option.isNone(submission)) {
|
|
402
|
+
return yield* LedgerError.make({
|
|
403
|
+
operation,
|
|
404
|
+
message: `Unknown submission ${submissionId}.`,
|
|
405
|
+
});
|
|
406
|
+
}
|
|
407
|
+
return submission.value;
|
|
408
|
+
});
|
|
409
|
+
|
|
410
|
+
const readOwnership = Effect.fn("SqliteSubmissionLedger.readOwnership")(function* (
|
|
411
|
+
operation: string,
|
|
412
|
+
submissionId: string,
|
|
413
|
+
): Effect.fn.Return<Option.Option<OwnershipRow>, LedgerError> {
|
|
414
|
+
const rows = yield* sql<Record<string, unknown>>`
|
|
415
|
+
SELECT
|
|
416
|
+
submission_id,
|
|
417
|
+
attempt_id,
|
|
418
|
+
ownership_token,
|
|
419
|
+
producer_epoch,
|
|
420
|
+
owner_producer_id,
|
|
421
|
+
lease_expires_at
|
|
422
|
+
FROM effect_agent_submission_ownership
|
|
423
|
+
WHERE submission_id = ${submissionId}
|
|
424
|
+
`.pipe(Effect.mapError(sqlFailure(operation)));
|
|
425
|
+
const decoded = yield* decodeRows(
|
|
426
|
+
Schema.Array(OwnershipRow),
|
|
427
|
+
"effect_agent_submission_ownership",
|
|
428
|
+
submissionId,
|
|
429
|
+
rows,
|
|
430
|
+
).pipe(Effect.mapError(internalFailure(operation)));
|
|
431
|
+
if (decoded.length > 1) {
|
|
432
|
+
return yield* corruptionFailure(
|
|
433
|
+
operation,
|
|
434
|
+
"effect_agent_submission_ownership",
|
|
435
|
+
submissionId,
|
|
436
|
+
"An ownership primary key returned more than one row.",
|
|
437
|
+
);
|
|
438
|
+
}
|
|
439
|
+
return decoded.length === 0 ? Option.none() : Option.some(decoded[0]);
|
|
440
|
+
});
|
|
441
|
+
|
|
442
|
+
const conversationEpoch = Effect.fn("SqliteSubmissionLedger.conversationEpoch")(function* (
|
|
443
|
+
operation: string,
|
|
444
|
+
conversationId: string,
|
|
445
|
+
): Effect.fn.Return<ProducerEpoch, LedgerError> {
|
|
446
|
+
const conversations = yield* journal
|
|
447
|
+
.getConversation(conversationId)
|
|
448
|
+
.pipe(Effect.mapError(internalFailure(operation)));
|
|
449
|
+
return conversations.length === 0 ? EPOCH_ZERO : conversations[0].producer_epoch;
|
|
450
|
+
});
|
|
451
|
+
|
|
452
|
+
/**
|
|
453
|
+
* Verify inside the surrounding write transaction that the presented token still owns the
|
|
454
|
+
* Submission's lane; a superseded or missing token fails with OwnershipLost carrying the
|
|
455
|
+
* Conversation's current producer epoch (DUR-006).
|
|
456
|
+
*/
|
|
457
|
+
const requireOwnership = Effect.fn("SqliteSubmissionLedger.requireOwnership")(function* (
|
|
458
|
+
operation: string,
|
|
459
|
+
submission: SubmissionRow,
|
|
460
|
+
ownershipToken: string,
|
|
461
|
+
): Effect.fn.Return<OwnershipRow, OwnershipLost | LedgerError> {
|
|
462
|
+
const ownership = yield* readOwnership(operation, submission.submission_id);
|
|
463
|
+
if (Option.isNone(ownership) || ownership.value.ownership_token !== ownershipToken) {
|
|
464
|
+
const actualEpoch = yield* conversationEpoch(operation, submission.conversation_id);
|
|
465
|
+
const submissionId = yield* Schema.decodeUnknownEffect(
|
|
466
|
+
SubmissionSnapshot.fields.submissionId,
|
|
467
|
+
)(submission.submission_id).pipe(Effect.mapError(internalFailure(operation)));
|
|
468
|
+
return yield* OwnershipLost.make({ submissionId, actualEpoch });
|
|
469
|
+
}
|
|
470
|
+
return ownership.value;
|
|
471
|
+
});
|
|
472
|
+
|
|
473
|
+
const decodeSubmissionSnapshot = Effect.fn("SqliteSubmissionLedger.decodeSubmissionSnapshot")(
|
|
474
|
+
function* (
|
|
475
|
+
operation: string,
|
|
476
|
+
row: SubmissionRow,
|
|
477
|
+
): Effect.fn.Return<SubmissionSnapshot, LedgerError> {
|
|
478
|
+
const agentDigests = yield* parseStoredJsonText(row.agent_digests_json).pipe(
|
|
479
|
+
Effect.mapError((error) =>
|
|
480
|
+
corruptionFailure(
|
|
481
|
+
operation,
|
|
482
|
+
"effect_agent_submissions",
|
|
483
|
+
row.submission_id,
|
|
484
|
+
error.message,
|
|
485
|
+
),
|
|
486
|
+
),
|
|
487
|
+
);
|
|
488
|
+
const inputPayload = yield* parseStoredJsonText(row.input_json).pipe(
|
|
489
|
+
Effect.mapError((error) =>
|
|
490
|
+
corruptionFailure(
|
|
491
|
+
operation,
|
|
492
|
+
"effect_agent_submissions",
|
|
493
|
+
row.submission_id,
|
|
494
|
+
error.message,
|
|
495
|
+
),
|
|
496
|
+
),
|
|
497
|
+
);
|
|
498
|
+
if ((row.parent_submission_id === null) !== (row.parent_tool_call_id === null)) {
|
|
499
|
+
return yield* corruptionFailure(
|
|
500
|
+
operation,
|
|
501
|
+
"effect_agent_submissions",
|
|
502
|
+
row.submission_id,
|
|
503
|
+
"A parent linkage must record both the parent Submission and the parent Tool Call.",
|
|
504
|
+
);
|
|
505
|
+
}
|
|
506
|
+
return yield* decodeSubmissionSnapshotUnknown({
|
|
507
|
+
submissionId: row.submission_id,
|
|
508
|
+
conversationId: row.conversation_id,
|
|
509
|
+
queueSequence: row.queue_sequence,
|
|
510
|
+
principal: row.principal,
|
|
511
|
+
idempotencyKey: row.idempotency_key,
|
|
512
|
+
agentId: row.agent_id,
|
|
513
|
+
agentDigests,
|
|
514
|
+
deploymentId: row.deployment_id,
|
|
515
|
+
inputPayload,
|
|
516
|
+
inputDigest: row.input_digest,
|
|
517
|
+
receiptId: row.receipt_id,
|
|
518
|
+
state: row.state,
|
|
519
|
+
createdAt: row.created_at,
|
|
520
|
+
...(row.settled_outcome === null ? {} : { settledOutcome: row.settled_outcome }),
|
|
521
|
+
...(row.ready_at === null ? {} : { readyAt: row.ready_at }),
|
|
522
|
+
...(row.parent_submission_id === null || row.parent_tool_call_id === null
|
|
523
|
+
? {}
|
|
524
|
+
: {
|
|
525
|
+
parentLinkage: {
|
|
526
|
+
parentSubmissionId: row.parent_submission_id,
|
|
527
|
+
parentToolCallId: row.parent_tool_call_id,
|
|
528
|
+
},
|
|
529
|
+
}),
|
|
530
|
+
}).pipe(
|
|
531
|
+
Effect.mapError((error) =>
|
|
532
|
+
corruptionFailure(
|
|
533
|
+
operation,
|
|
534
|
+
"effect_agent_submissions",
|
|
535
|
+
row.submission_id,
|
|
536
|
+
error.message,
|
|
537
|
+
),
|
|
538
|
+
),
|
|
539
|
+
);
|
|
540
|
+
},
|
|
541
|
+
);
|
|
542
|
+
|
|
543
|
+
const readReservation = Effect.fn("SqliteSubmissionLedger.readReservation")(function* (
|
|
544
|
+
operation: string,
|
|
545
|
+
submissionId: string,
|
|
546
|
+
): Effect.fn.Return<Option.Option<ReservationRow>, LedgerError> {
|
|
547
|
+
const rows = yield* sql<Record<string, unknown>>`
|
|
548
|
+
SELECT
|
|
549
|
+
submission_id,
|
|
550
|
+
settlement_id,
|
|
551
|
+
outcome,
|
|
552
|
+
record_id,
|
|
553
|
+
record_json,
|
|
554
|
+
record_digest,
|
|
555
|
+
reserved_at,
|
|
556
|
+
finalized_at
|
|
557
|
+
FROM effect_agent_settlement_reservations
|
|
558
|
+
WHERE submission_id = ${submissionId}
|
|
559
|
+
`.pipe(Effect.mapError(sqlFailure(operation)));
|
|
560
|
+
const decoded = yield* decodeRows(
|
|
561
|
+
Schema.Array(ReservationRow),
|
|
562
|
+
"effect_agent_settlement_reservations",
|
|
563
|
+
submissionId,
|
|
564
|
+
rows,
|
|
565
|
+
).pipe(Effect.mapError(internalFailure(operation)));
|
|
566
|
+
if (decoded.length > 1) {
|
|
567
|
+
return yield* corruptionFailure(
|
|
568
|
+
operation,
|
|
569
|
+
"effect_agent_settlement_reservations",
|
|
570
|
+
submissionId,
|
|
571
|
+
"A settlement reservation primary key returned more than one row.",
|
|
572
|
+
);
|
|
573
|
+
}
|
|
574
|
+
return decoded.length === 0 ? Option.none() : Option.some(decoded[0]);
|
|
575
|
+
});
|
|
576
|
+
|
|
577
|
+
const readAbortIntent = Effect.fn("SqliteSubmissionLedger.readAbortIntent")(function* (
|
|
578
|
+
operation: string,
|
|
579
|
+
submissionId: string,
|
|
580
|
+
): Effect.fn.Return<Option.Option<AbortIntentRow>, LedgerError> {
|
|
581
|
+
const rows = yield* sql<Record<string, unknown>>`
|
|
582
|
+
SELECT
|
|
583
|
+
submission_id,
|
|
584
|
+
author,
|
|
585
|
+
reason,
|
|
586
|
+
requested_at,
|
|
587
|
+
canonical_record_id
|
|
588
|
+
FROM effect_agent_abort_intents
|
|
589
|
+
WHERE submission_id = ${submissionId}
|
|
590
|
+
`.pipe(Effect.mapError(sqlFailure(operation)));
|
|
591
|
+
const decoded = yield* decodeRows(
|
|
592
|
+
Schema.Array(AbortIntentRow),
|
|
593
|
+
"effect_agent_abort_intents",
|
|
594
|
+
submissionId,
|
|
595
|
+
rows,
|
|
596
|
+
).pipe(Effect.mapError(internalFailure(operation)));
|
|
597
|
+
if (decoded.length > 1) {
|
|
598
|
+
return yield* corruptionFailure(
|
|
599
|
+
operation,
|
|
600
|
+
"effect_agent_abort_intents",
|
|
601
|
+
submissionId,
|
|
602
|
+
"An abort intent primary key returned more than one row.",
|
|
603
|
+
);
|
|
604
|
+
}
|
|
605
|
+
return decoded.length === 0 ? Option.none() : Option.some(decoded[0]);
|
|
606
|
+
});
|
|
607
|
+
|
|
608
|
+
const decodeChildReservationRows = (operation: string, rowKey: string, rows: unknown) =>
|
|
609
|
+
decodeRows(
|
|
610
|
+
Schema.Array(ChildReservationRow),
|
|
611
|
+
"effect_agent_child_reservations",
|
|
612
|
+
rowKey,
|
|
613
|
+
rows,
|
|
614
|
+
).pipe(Effect.mapError(internalFailure(operation)));
|
|
615
|
+
|
|
616
|
+
const readChildReservation = Effect.fn("SqliteSubmissionLedger.readChildReservation")(function* (
|
|
617
|
+
operation: string,
|
|
618
|
+
reservationId: string,
|
|
619
|
+
): Effect.fn.Return<Option.Option<ChildReservationRow>, LedgerError> {
|
|
620
|
+
const rows = yield* sql<Record<string, unknown>>`
|
|
621
|
+
SELECT ${sql.literal(CHILD_RESERVATION_COLUMNS)}
|
|
622
|
+
FROM effect_agent_child_reservations
|
|
623
|
+
WHERE reservation_id = ${reservationId}
|
|
624
|
+
`.pipe(Effect.mapError(sqlFailure(operation)));
|
|
625
|
+
const decoded = yield* decodeChildReservationRows(operation, reservationId, rows);
|
|
626
|
+
if (decoded.length > 1) {
|
|
627
|
+
return yield* corruptionFailure(
|
|
628
|
+
operation,
|
|
629
|
+
"effect_agent_child_reservations",
|
|
630
|
+
reservationId,
|
|
631
|
+
"A child reservation primary key returned more than one row.",
|
|
632
|
+
);
|
|
633
|
+
}
|
|
634
|
+
return decoded.length === 0 ? Option.none() : Option.some(decoded[0]);
|
|
635
|
+
});
|
|
636
|
+
|
|
637
|
+
const readChildReservationForCall = Effect.fn(
|
|
638
|
+
"SqliteSubmissionLedger.readChildReservationForCall",
|
|
639
|
+
)(function* (
|
|
640
|
+
operation: string,
|
|
641
|
+
parentSubmissionId: string,
|
|
642
|
+
parentToolCallId: string,
|
|
643
|
+
): Effect.fn.Return<Option.Option<ChildReservationRow>, LedgerError> {
|
|
644
|
+
const rows = yield* sql<Record<string, unknown>>`
|
|
645
|
+
SELECT ${sql.literal(CHILD_RESERVATION_COLUMNS)}
|
|
646
|
+
FROM effect_agent_child_reservations
|
|
647
|
+
WHERE parent_submission_id = ${parentSubmissionId}
|
|
648
|
+
AND parent_tool_call_id = ${parentToolCallId}
|
|
649
|
+
`.pipe(Effect.mapError(sqlFailure(operation)));
|
|
650
|
+
const decoded = yield* decodeChildReservationRows(
|
|
651
|
+
operation,
|
|
652
|
+
`${parentSubmissionId}/${parentToolCallId}`,
|
|
653
|
+
rows,
|
|
654
|
+
);
|
|
655
|
+
if (decoded.length > 1) {
|
|
656
|
+
return yield* corruptionFailure(
|
|
657
|
+
operation,
|
|
658
|
+
"effect_agent_child_reservations",
|
|
659
|
+
`${parentSubmissionId}/${parentToolCallId}`,
|
|
660
|
+
"A parent Tool Call returned more than one child reservation.",
|
|
661
|
+
);
|
|
662
|
+
}
|
|
663
|
+
return decoded.length === 0 ? Option.none() : Option.some(decoded[0]);
|
|
664
|
+
});
|
|
665
|
+
|
|
666
|
+
const childReservationSnapshotFromRow = Effect.fn(
|
|
667
|
+
"SqliteSubmissionLedger.childReservationSnapshotFromRow",
|
|
668
|
+
)(function* (
|
|
669
|
+
operation: string,
|
|
670
|
+
row: ChildReservationRow,
|
|
671
|
+
): Effect.fn.Return<ChildBudgetReservationSnapshot, LedgerError> {
|
|
672
|
+
const rowFailure = (error: { readonly message: string }) =>
|
|
673
|
+
corruptionFailure(
|
|
674
|
+
operation,
|
|
675
|
+
"effect_agent_child_reservations",
|
|
676
|
+
row.reservation_id,
|
|
677
|
+
error.message,
|
|
678
|
+
);
|
|
679
|
+
const allocation = yield* parseStoredJsonText(row.allocation_json).pipe(
|
|
680
|
+
Effect.mapError(rowFailure),
|
|
681
|
+
);
|
|
682
|
+
const accounting =
|
|
683
|
+
row.accounting_json === null
|
|
684
|
+
? undefined
|
|
685
|
+
: yield* parseStoredJsonText(row.accounting_json).pipe(Effect.mapError(rowFailure));
|
|
686
|
+
return yield* decodeChildReservationSnapshotUnknown({
|
|
687
|
+
reservationId: row.reservation_id,
|
|
688
|
+
parentSubmissionId: row.parent_submission_id,
|
|
689
|
+
parentToolCallId: row.parent_tool_call_id,
|
|
690
|
+
status: row.status,
|
|
691
|
+
allocation,
|
|
692
|
+
allocationDigest: row.allocation_digest,
|
|
693
|
+
reservedAt: row.reserved_at,
|
|
694
|
+
...(row.child_submission_id === null ? {} : { childSubmissionId: row.child_submission_id }),
|
|
695
|
+
...(accounting === undefined ? {} : { accounting }),
|
|
696
|
+
...(row.release_began_at === null ? {} : { releaseBeganAt: row.release_began_at }),
|
|
697
|
+
...(row.released_at === null ? {} : { releasedAt: row.released_at }),
|
|
698
|
+
}).pipe(Effect.mapError(rowFailure));
|
|
699
|
+
});
|
|
700
|
+
|
|
701
|
+
const readApprovalDecisions = Effect.fn("SqliteSubmissionLedger.readApprovalDecisions")(
|
|
702
|
+
function* (
|
|
703
|
+
operation: string,
|
|
704
|
+
submissionId: string,
|
|
705
|
+
): Effect.fn.Return<ReadonlyArray<ApprovalDecisionRow>, LedgerError> {
|
|
706
|
+
const rows = yield* sql<Record<string, unknown>>`
|
|
707
|
+
SELECT
|
|
708
|
+
submission_id,
|
|
709
|
+
tool_call_id,
|
|
710
|
+
decision,
|
|
711
|
+
resolver,
|
|
712
|
+
reason,
|
|
713
|
+
decided_at
|
|
714
|
+
FROM effect_agent_approval_decisions
|
|
715
|
+
WHERE submission_id = ${submissionId}
|
|
716
|
+
ORDER BY tool_call_id ASC
|
|
717
|
+
`.pipe(Effect.mapError(sqlFailure(operation)));
|
|
718
|
+
return yield* decodeRows(
|
|
719
|
+
Schema.Array(ApprovalDecisionRow),
|
|
720
|
+
"effect_agent_approval_decisions",
|
|
721
|
+
submissionId,
|
|
722
|
+
rows,
|
|
723
|
+
).pipe(Effect.mapError(internalFailure(operation)));
|
|
724
|
+
},
|
|
725
|
+
);
|
|
726
|
+
|
|
727
|
+
const approvalIntentFromRow = Effect.fn("SqliteSubmissionLedger.approvalIntentFromRow")(
|
|
728
|
+
function* (
|
|
729
|
+
operation: string,
|
|
730
|
+
row: ApprovalDecisionRow,
|
|
731
|
+
): Effect.fn.Return<ApprovalDecisionIntent, LedgerError> {
|
|
732
|
+
return yield* decodeApprovalDecisionIntent({
|
|
733
|
+
submissionId: row.submission_id,
|
|
734
|
+
toolCallId: row.tool_call_id,
|
|
735
|
+
decision: row.decision,
|
|
736
|
+
resolver: row.resolver,
|
|
737
|
+
reason: row.reason,
|
|
738
|
+
decidedAt: row.decided_at,
|
|
739
|
+
}).pipe(
|
|
740
|
+
Effect.mapError((error) =>
|
|
741
|
+
corruptionFailure(
|
|
742
|
+
operation,
|
|
743
|
+
"effect_agent_approval_decisions",
|
|
744
|
+
`${row.submission_id}/${row.tool_call_id}`,
|
|
745
|
+
error.message,
|
|
746
|
+
),
|
|
747
|
+
),
|
|
748
|
+
);
|
|
749
|
+
},
|
|
750
|
+
);
|
|
751
|
+
|
|
752
|
+
const readUnknownResolutions = Effect.fn("SqliteSubmissionLedger.readUnknownResolutions")(
|
|
753
|
+
function* (
|
|
754
|
+
operation: string,
|
|
755
|
+
submissionId: string,
|
|
756
|
+
): Effect.fn.Return<ReadonlyArray<UnknownResolutionRow>, LedgerError> {
|
|
757
|
+
const rows = yield* sql<Record<string, unknown>>`
|
|
758
|
+
SELECT
|
|
759
|
+
submission_id,
|
|
760
|
+
tool_call_id,
|
|
761
|
+
author,
|
|
762
|
+
reason,
|
|
763
|
+
resolution_json,
|
|
764
|
+
resolved_at
|
|
765
|
+
FROM effect_agent_unknown_resolutions
|
|
766
|
+
WHERE submission_id = ${submissionId}
|
|
767
|
+
ORDER BY tool_call_id ASC
|
|
768
|
+
`.pipe(Effect.mapError(sqlFailure(operation)));
|
|
769
|
+
return yield* decodeRows(
|
|
770
|
+
Schema.Array(UnknownResolutionRow),
|
|
771
|
+
"effect_agent_unknown_resolutions",
|
|
772
|
+
submissionId,
|
|
773
|
+
rows,
|
|
774
|
+
).pipe(Effect.mapError(internalFailure(operation)));
|
|
775
|
+
},
|
|
776
|
+
);
|
|
777
|
+
|
|
778
|
+
const unknownResolutionIntentFromRow = Effect.fn(
|
|
779
|
+
"SqliteSubmissionLedger.unknownResolutionIntentFromRow",
|
|
780
|
+
)(function* (
|
|
781
|
+
operation: string,
|
|
782
|
+
row: UnknownResolutionRow,
|
|
783
|
+
): Effect.fn.Return<UnknownResolutionIntent, LedgerError> {
|
|
784
|
+
const resolution = yield* parseStoredJsonText(row.resolution_json).pipe(
|
|
785
|
+
Effect.mapError((error) =>
|
|
786
|
+
corruptionFailure(
|
|
787
|
+
operation,
|
|
788
|
+
"effect_agent_unknown_resolutions",
|
|
789
|
+
`${row.submission_id}/${row.tool_call_id}`,
|
|
790
|
+
error.message,
|
|
791
|
+
),
|
|
792
|
+
),
|
|
793
|
+
);
|
|
794
|
+
return yield* decodeUnknownResolutionIntent({
|
|
795
|
+
submissionId: row.submission_id,
|
|
796
|
+
toolCallId: row.tool_call_id,
|
|
797
|
+
author: row.author,
|
|
798
|
+
reason: row.reason,
|
|
799
|
+
resolution,
|
|
800
|
+
resolvedAt: row.resolved_at,
|
|
801
|
+
}).pipe(
|
|
802
|
+
Effect.mapError((error) =>
|
|
803
|
+
corruptionFailure(
|
|
804
|
+
operation,
|
|
805
|
+
"effect_agent_unknown_resolutions",
|
|
806
|
+
`${row.submission_id}/${row.tool_call_id}`,
|
|
807
|
+
error.message,
|
|
808
|
+
),
|
|
809
|
+
),
|
|
810
|
+
);
|
|
811
|
+
});
|
|
812
|
+
|
|
813
|
+
/** The Submission's marked-unknown open Tool Call identities, empty when never marked. */
|
|
814
|
+
const storedUnknownToolCallIds = Effect.fn("SqliteSubmissionLedger.storedUnknownToolCallIds")(
|
|
815
|
+
function* (
|
|
816
|
+
operation: string,
|
|
817
|
+
submission: SubmissionRow,
|
|
818
|
+
): Effect.fn.Return<ReadonlyArray<typeof ToolCallIdSchema.Type>, LedgerError> {
|
|
819
|
+
if (submission.unknown_tool_call_ids_json === null) return [];
|
|
820
|
+
return yield* decodeToolCallIdsText(submission.unknown_tool_call_ids_json).pipe(
|
|
821
|
+
Effect.mapError((error) =>
|
|
822
|
+
corruptionFailure(
|
|
823
|
+
operation,
|
|
824
|
+
"effect_agent_submissions",
|
|
825
|
+
submission.submission_id,
|
|
826
|
+
error.message,
|
|
827
|
+
),
|
|
828
|
+
),
|
|
829
|
+
);
|
|
830
|
+
},
|
|
831
|
+
);
|
|
832
|
+
|
|
833
|
+
/**
|
|
834
|
+
* Canonical history is the abort authority (DUR-015): the intent's canonicalRecordId is
|
|
835
|
+
* derived from the shared canonical-records table using the deterministic abort record
|
|
836
|
+
* identity, never from a cached ledger marker.
|
|
837
|
+
*/
|
|
838
|
+
const canonicalAbortRecordId = Effect.fn("SqliteSubmissionLedger.canonicalAbortRecordId")(
|
|
839
|
+
function* (
|
|
840
|
+
operation: string,
|
|
841
|
+
conversationId: string,
|
|
842
|
+
submissionId: SubmissionId,
|
|
843
|
+
): Effect.fn.Return<string | undefined, LedgerError> {
|
|
844
|
+
const recordId = submissionAbortRecordId(submissionId);
|
|
845
|
+
const rows = yield* sql<Record<string, unknown>>`
|
|
846
|
+
SELECT record_id
|
|
847
|
+
FROM effect_agent_canonical_records
|
|
848
|
+
WHERE conversation_id = ${conversationId}
|
|
849
|
+
AND record_id = ${recordId}
|
|
850
|
+
`.pipe(Effect.mapError(sqlFailure(operation)));
|
|
851
|
+
const decoded = yield* decodeRows(
|
|
852
|
+
Schema.Array(CanonicalRecordIdRow),
|
|
853
|
+
"effect_agent_canonical_records",
|
|
854
|
+
`${conversationId}/${recordId}`,
|
|
855
|
+
rows,
|
|
856
|
+
).pipe(Effect.mapError(internalFailure(operation)));
|
|
857
|
+
return decoded.length === 0 ? undefined : recordId;
|
|
858
|
+
},
|
|
859
|
+
);
|
|
860
|
+
|
|
861
|
+
const abortIntentFromRow = Effect.fn("SqliteSubmissionLedger.abortIntentFromRow")(function* (
|
|
862
|
+
operation: string,
|
|
863
|
+
submission: SubmissionRow,
|
|
864
|
+
submissionId: SubmissionId,
|
|
865
|
+
row: AbortIntentRow,
|
|
866
|
+
): Effect.fn.Return<AbortIntent, LedgerError> {
|
|
867
|
+
const canonicalRecordId = yield* canonicalAbortRecordId(
|
|
868
|
+
operation,
|
|
869
|
+
submission.conversation_id,
|
|
870
|
+
submissionId,
|
|
871
|
+
);
|
|
872
|
+
return yield* decodeAbortIntent({
|
|
873
|
+
submissionId: row.submission_id,
|
|
874
|
+
author: row.author,
|
|
875
|
+
reason: row.reason,
|
|
876
|
+
requestedAt: row.requested_at,
|
|
877
|
+
...(canonicalRecordId === undefined ? {} : { canonicalRecordId }),
|
|
878
|
+
}).pipe(
|
|
879
|
+
Effect.mapError((error) =>
|
|
880
|
+
corruptionFailure(
|
|
881
|
+
operation,
|
|
882
|
+
"effect_agent_abort_intents",
|
|
883
|
+
row.submission_id,
|
|
884
|
+
error.message,
|
|
885
|
+
),
|
|
886
|
+
),
|
|
887
|
+
);
|
|
888
|
+
});
|
|
889
|
+
|
|
890
|
+
const capabilities = Effect.succeed(LedgerCapabilities.make({ durability: "durable-node" }));
|
|
891
|
+
|
|
892
|
+
const admit: SubmissionLedger["Service"]["admit"] = Effect.fn("SqliteSubmissionLedger.admit")(
|
|
893
|
+
function* (request: AdmissionRequest) {
|
|
894
|
+
const operation = "ledger admit";
|
|
895
|
+
const validated = yield* Schema.decodeUnknownEffect(Schema.toType(AdmissionRequest))(
|
|
896
|
+
request,
|
|
897
|
+
).pipe(Effect.mapError(internalFailure(operation)));
|
|
898
|
+
const inputJson = yield* encodePersistedJsonText(validated.inputPayload).pipe(
|
|
899
|
+
Effect.mapError(internalFailure(operation)),
|
|
900
|
+
);
|
|
901
|
+
const agentDigestsJson = yield* encodeDefinitionDigestsText(validated.agentDigests).pipe(
|
|
902
|
+
Effect.mapError(internalFailure(operation)),
|
|
903
|
+
);
|
|
904
|
+
const mintedSubmissionId = yield* mintIdentifier("submission", operation);
|
|
905
|
+
const mintedReceiptId = yield* mintIdentifier("receipt", operation);
|
|
906
|
+
yield* hitFailpoint("ledger:admit:before", operation);
|
|
907
|
+
const result = yield* inWriteTransaction(
|
|
908
|
+
operation,
|
|
909
|
+
Effect.gen(function* () {
|
|
910
|
+
const keyRowKey = `${validated.conversationId}/${validated.principal}/${validated.idempotencyKey}`;
|
|
911
|
+
const existingRows = yield* sql<Record<string, unknown>>`
|
|
912
|
+
SELECT ${sql.literal(SUBMISSION_COLUMNS)}
|
|
913
|
+
FROM effect_agent_submissions
|
|
914
|
+
WHERE conversation_id = ${validated.conversationId}
|
|
915
|
+
AND principal = ${validated.principal}
|
|
916
|
+
AND idempotency_key = ${validated.idempotencyKey}
|
|
917
|
+
`.pipe(Effect.mapError(sqlFailure(operation)));
|
|
918
|
+
const existing = yield* decodeSubmissionRows(operation, keyRowKey, existingRows);
|
|
919
|
+
if (existing.length > 1) {
|
|
920
|
+
return yield* corruptionFailure(
|
|
921
|
+
operation,
|
|
922
|
+
"effect_agent_submissions",
|
|
923
|
+
keyRowKey,
|
|
924
|
+
"An admission idempotency key returned more than one row.",
|
|
925
|
+
);
|
|
926
|
+
}
|
|
927
|
+
if (existing.length === 1) {
|
|
928
|
+
// A replay must repeat the exact canonical input AND the exact parent linkage (or
|
|
929
|
+
// its absence): linkage is immutable child lineage (spec §12 step 5, SUB-016).
|
|
930
|
+
const sameLinkage =
|
|
931
|
+
validated.parentLinkage === undefined
|
|
932
|
+
? existing[0].parent_submission_id === null &&
|
|
933
|
+
existing[0].parent_tool_call_id === null
|
|
934
|
+
: existing[0].parent_submission_id === validated.parentLinkage.parentSubmissionId &&
|
|
935
|
+
existing[0].parent_tool_call_id === validated.parentLinkage.parentToolCallId;
|
|
936
|
+
if (existing[0].input_digest !== validated.inputDigest || !sameLinkage) {
|
|
937
|
+
return yield* AdmissionConflict.make({
|
|
938
|
+
conversationId: validated.conversationId,
|
|
939
|
+
principal: validated.principal,
|
|
940
|
+
idempotencyKey: validated.idempotencyKey,
|
|
941
|
+
existingInputDigest: existing[0].input_digest,
|
|
942
|
+
attemptedInputDigest: validated.inputDigest,
|
|
943
|
+
});
|
|
944
|
+
}
|
|
945
|
+
return yield* decodeAdmissionResult({
|
|
946
|
+
submissionId: existing[0].submission_id,
|
|
947
|
+
receiptId: existing[0].receipt_id,
|
|
948
|
+
queueSequence: existing[0].queue_sequence,
|
|
949
|
+
state: existing[0].state,
|
|
950
|
+
replayed: true,
|
|
951
|
+
}).pipe(Effect.mapError(internalFailure(operation)));
|
|
952
|
+
}
|
|
953
|
+
|
|
954
|
+
const maxRows = yield* sql<Record<string, unknown>>`
|
|
955
|
+
SELECT COALESCE(MAX(queue_sequence), 0) AS max_queue_sequence
|
|
956
|
+
FROM effect_agent_submissions
|
|
957
|
+
WHERE conversation_id = ${validated.conversationId}
|
|
958
|
+
`.pipe(Effect.mapError(sqlFailure(operation)));
|
|
959
|
+
const decodedMax = yield* decodeRows(
|
|
960
|
+
Schema.Array(MaxQueueSequenceRow),
|
|
961
|
+
"effect_agent_submissions",
|
|
962
|
+
validated.conversationId,
|
|
963
|
+
maxRows,
|
|
964
|
+
).pipe(Effect.mapError(internalFailure(operation)));
|
|
965
|
+
const queueSequence = yield* decodeQueueSequence(
|
|
966
|
+
(decodedMax[0]?.max_queue_sequence ?? 0) + 1,
|
|
967
|
+
).pipe(Effect.mapError(internalFailure(operation)));
|
|
968
|
+
const now = yield* currentInstant;
|
|
969
|
+
|
|
970
|
+
yield* sql`
|
|
971
|
+
INSERT INTO effect_agent_submissions (
|
|
972
|
+
submission_id,
|
|
973
|
+
conversation_id,
|
|
974
|
+
queue_sequence,
|
|
975
|
+
principal,
|
|
976
|
+
idempotency_key,
|
|
977
|
+
agent_id,
|
|
978
|
+
agent_digests_json,
|
|
979
|
+
deployment_id,
|
|
980
|
+
input_json,
|
|
981
|
+
input_digest,
|
|
982
|
+
receipt_id,
|
|
983
|
+
state,
|
|
984
|
+
created_at,
|
|
985
|
+
parent_submission_id,
|
|
986
|
+
parent_tool_call_id
|
|
987
|
+
) VALUES (
|
|
988
|
+
${mintedSubmissionId},
|
|
989
|
+
${validated.conversationId},
|
|
990
|
+
${queueSequence},
|
|
991
|
+
${validated.principal},
|
|
992
|
+
${validated.idempotencyKey},
|
|
993
|
+
${validated.agentId},
|
|
994
|
+
${agentDigestsJson},
|
|
995
|
+
${validated.deploymentId},
|
|
996
|
+
${inputJson},
|
|
997
|
+
${validated.inputDigest},
|
|
998
|
+
${mintedReceiptId},
|
|
999
|
+
'admitted',
|
|
1000
|
+
${now.iso},
|
|
1001
|
+
${validated.parentLinkage?.parentSubmissionId ?? null},
|
|
1002
|
+
${validated.parentLinkage?.parentToolCallId ?? null}
|
|
1003
|
+
)
|
|
1004
|
+
`.pipe(Effect.mapError(sqlFailure(operation)));
|
|
1005
|
+
|
|
1006
|
+
return yield* decodeAdmissionResult({
|
|
1007
|
+
submissionId: mintedSubmissionId,
|
|
1008
|
+
receiptId: mintedReceiptId,
|
|
1009
|
+
queueSequence,
|
|
1010
|
+
state: "admitted",
|
|
1011
|
+
replayed: false,
|
|
1012
|
+
}).pipe(Effect.mapError(internalFailure(operation)));
|
|
1013
|
+
}),
|
|
1014
|
+
);
|
|
1015
|
+
yield* hitFailpoint("ledger:admit:after", operation);
|
|
1016
|
+
return result;
|
|
1017
|
+
},
|
|
1018
|
+
);
|
|
1019
|
+
|
|
1020
|
+
const markReady: SubmissionLedger["Service"]["markReady"] = Effect.fn(
|
|
1021
|
+
"SqliteSubmissionLedger.markReady",
|
|
1022
|
+
)(function* (request: MarkReadyRequest) {
|
|
1023
|
+
const operation = "ledger mark ready";
|
|
1024
|
+
const validated = yield* Schema.decodeUnknownEffect(Schema.toType(MarkReadyRequest))(
|
|
1025
|
+
request,
|
|
1026
|
+
).pipe(Effect.mapError(internalFailure(operation)));
|
|
1027
|
+
yield* hitFailpoint("ledger:mark-ready:before", operation);
|
|
1028
|
+
yield* inWriteTransaction(
|
|
1029
|
+
operation,
|
|
1030
|
+
Effect.gen(function* () {
|
|
1031
|
+
const submission = yield* requireSubmission(operation, validated.submissionId);
|
|
1032
|
+
if (submission.state !== "admitted") return;
|
|
1033
|
+
const now = yield* currentInstant;
|
|
1034
|
+
yield* sql`
|
|
1035
|
+
UPDATE effect_agent_submissions
|
|
1036
|
+
SET state = 'ready', ready_at = ${now.iso}
|
|
1037
|
+
WHERE submission_id = ${validated.submissionId}
|
|
1038
|
+
`.pipe(Effect.mapError(sqlFailure(operation)));
|
|
1039
|
+
}),
|
|
1040
|
+
);
|
|
1041
|
+
yield* hitFailpoint("ledger:mark-ready:after", operation);
|
|
1042
|
+
});
|
|
1043
|
+
|
|
1044
|
+
const lookup: SubmissionLedger["Service"]["lookup"] = Effect.fn("SqliteSubmissionLedger.lookup")(
|
|
1045
|
+
function* (request: SubmissionLookup) {
|
|
1046
|
+
const operation = "ledger lookup";
|
|
1047
|
+
const validated = yield* Schema.decodeUnknownEffect(Schema.toType(SubmissionLookup))(
|
|
1048
|
+
request,
|
|
1049
|
+
).pipe(Effect.mapError(internalFailure(operation)));
|
|
1050
|
+
if (validated._tag === "SubmissionLookupById") {
|
|
1051
|
+
const row = yield* readSubmission(operation, validated.submissionId);
|
|
1052
|
+
if (Option.isNone(row)) return Option.none();
|
|
1053
|
+
return Option.some(yield* decodeSubmissionSnapshot(operation, row.value));
|
|
1054
|
+
}
|
|
1055
|
+
const rows = yield* sql<Record<string, unknown>>`
|
|
1056
|
+
SELECT ${sql.literal(SUBMISSION_COLUMNS)}
|
|
1057
|
+
FROM effect_agent_submissions
|
|
1058
|
+
WHERE conversation_id = ${validated.conversationId}
|
|
1059
|
+
AND principal = ${validated.principal}
|
|
1060
|
+
AND idempotency_key = ${validated.idempotencyKey}
|
|
1061
|
+
`.pipe(Effect.mapError(sqlFailure(operation)));
|
|
1062
|
+
const decoded = yield* decodeSubmissionRows(
|
|
1063
|
+
operation,
|
|
1064
|
+
`${validated.conversationId}/${validated.principal}/${validated.idempotencyKey}`,
|
|
1065
|
+
rows,
|
|
1066
|
+
);
|
|
1067
|
+
if (decoded.length > 1) {
|
|
1068
|
+
return yield* corruptionFailure(
|
|
1069
|
+
operation,
|
|
1070
|
+
"effect_agent_submissions",
|
|
1071
|
+
`${validated.conversationId}/${validated.principal}/${validated.idempotencyKey}`,
|
|
1072
|
+
"An admission idempotency key returned more than one row.",
|
|
1073
|
+
);
|
|
1074
|
+
}
|
|
1075
|
+
if (decoded.length === 0) return Option.none();
|
|
1076
|
+
return Option.some(yield* decodeSubmissionSnapshot(operation, decoded[0]));
|
|
1077
|
+
},
|
|
1078
|
+
);
|
|
1079
|
+
|
|
1080
|
+
// A single strongly consistent SQLite file always answers authoritatively (SUB-031): the
|
|
1081
|
+
// key-scoped read IS the admission truth, so the tri-state degenerates to NotAdmitted or
|
|
1082
|
+
// Admitted here — Indeterminate exists for adapters that can fail to reach the owner.
|
|
1083
|
+
const resolveAdmission: SubmissionLedger["Service"]["resolveAdmission"] = Effect.fn(
|
|
1084
|
+
"SqliteSubmissionLedger.resolveAdmission",
|
|
1085
|
+
)(function* (request: SubmissionLookupByKey) {
|
|
1086
|
+
const operation = "ledger resolve admission";
|
|
1087
|
+
const validated = yield* Schema.decodeUnknownEffect(Schema.toType(SubmissionLookupByKey))(
|
|
1088
|
+
request,
|
|
1089
|
+
).pipe(Effect.mapError(internalFailure(operation)));
|
|
1090
|
+
const rows = yield* sql<Record<string, unknown>>`
|
|
1091
|
+
SELECT ${sql.literal(SUBMISSION_COLUMNS)}
|
|
1092
|
+
FROM effect_agent_submissions
|
|
1093
|
+
WHERE conversation_id = ${validated.conversationId}
|
|
1094
|
+
AND principal = ${validated.principal}
|
|
1095
|
+
AND idempotency_key = ${validated.idempotencyKey}
|
|
1096
|
+
`.pipe(Effect.mapError(sqlFailure(operation)));
|
|
1097
|
+
const decoded = yield* decodeSubmissionRows(
|
|
1098
|
+
operation,
|
|
1099
|
+
`${validated.conversationId}/${validated.principal}/${validated.idempotencyKey}`,
|
|
1100
|
+
rows,
|
|
1101
|
+
);
|
|
1102
|
+
if (decoded.length > 1) {
|
|
1103
|
+
return yield* corruptionFailure(
|
|
1104
|
+
operation,
|
|
1105
|
+
"effect_agent_submissions",
|
|
1106
|
+
`${validated.conversationId}/${validated.principal}/${validated.idempotencyKey}`,
|
|
1107
|
+
"An admission idempotency key returned more than one row.",
|
|
1108
|
+
);
|
|
1109
|
+
}
|
|
1110
|
+
if (decoded.length === 0) return AdmissionNotAdmitted.make();
|
|
1111
|
+
return AdmissionAdmitted.make({
|
|
1112
|
+
submission: yield* decodeSubmissionSnapshot(operation, decoded[0]),
|
|
1113
|
+
});
|
|
1114
|
+
});
|
|
1115
|
+
|
|
1116
|
+
const claim: SubmissionLedger["Service"]["claim"] = Effect.fn("SqliteSubmissionLedger.claim")(
|
|
1117
|
+
function* (request: ClaimRequest) {
|
|
1118
|
+
const operation = "ledger claim";
|
|
1119
|
+
const validated = yield* Schema.decodeUnknownEffect(Schema.toType(ClaimRequest))(
|
|
1120
|
+
request,
|
|
1121
|
+
).pipe(Effect.mapError(internalFailure(operation)));
|
|
1122
|
+
const attemptId = yield* mintIdentifier("attempt", operation);
|
|
1123
|
+
const ownershipToken = yield* mintIdentifier("owner", operation);
|
|
1124
|
+
yield* hitFailpoint("ledger:claim:before", operation);
|
|
1125
|
+
const claimed = yield* inWriteTransaction(
|
|
1126
|
+
operation,
|
|
1127
|
+
Effect.gen(function* () {
|
|
1128
|
+
const headRows = yield* sql<Record<string, unknown>>`
|
|
1129
|
+
SELECT ${sql.literal(SUBMISSION_COLUMNS)}
|
|
1130
|
+
FROM effect_agent_submissions
|
|
1131
|
+
WHERE conversation_id = ${validated.conversationId}
|
|
1132
|
+
AND state <> 'settled'
|
|
1133
|
+
ORDER BY queue_sequence ASC
|
|
1134
|
+
LIMIT 1
|
|
1135
|
+
`.pipe(Effect.mapError(sqlFailure(operation)));
|
|
1136
|
+
const heads = yield* decodeSubmissionRows(operation, validated.conversationId, headRows);
|
|
1137
|
+
if (heads.length === 0) return Option.none<Claim>();
|
|
1138
|
+
const head = heads[0];
|
|
1139
|
+
|
|
1140
|
+
// A joining/joined head is host-owned and a suspended/unknown head is durably
|
|
1141
|
+
// blocked (DUR-017); the lane produces no claim and later ready work is never
|
|
1142
|
+
// skipped past the blocked head (DUR-004).
|
|
1143
|
+
if (
|
|
1144
|
+
head.state === "joining" ||
|
|
1145
|
+
head.state === "joined" ||
|
|
1146
|
+
head.state === "suspended" ||
|
|
1147
|
+
head.state === "unknown"
|
|
1148
|
+
) {
|
|
1149
|
+
return Option.none<Claim>();
|
|
1150
|
+
}
|
|
1151
|
+
|
|
1152
|
+
const now = yield* currentInstant;
|
|
1153
|
+
const ownership = yield* readOwnership(operation, head.submission_id);
|
|
1154
|
+
if (Option.isSome(ownership)) {
|
|
1155
|
+
const expiresAt = yield* timestampMillis(
|
|
1156
|
+
operation,
|
|
1157
|
+
head.submission_id,
|
|
1158
|
+
)(ownership.value.lease_expires_at);
|
|
1159
|
+
// A live lease blocks every new claim; expiry alone only revokes the liveness
|
|
1160
|
+
// assumption — correctness stays with producer-epoch fencing (D5).
|
|
1161
|
+
if (expiresAt > now.millis) return Option.none<Claim>();
|
|
1162
|
+
}
|
|
1163
|
+
|
|
1164
|
+
// Bump the Conversation's producer epoch atomically with the claim so every stale
|
|
1165
|
+
// Attempt is fenced out of canonical appends (DUR-006). A Conversation that was
|
|
1166
|
+
// never materialized (crash between admission and materialization) is created here
|
|
1167
|
+
// so recovery can claim first and re-materialize idempotently at this epoch.
|
|
1168
|
+
const conversations = yield* journal
|
|
1169
|
+
.getConversation(head.conversation_id)
|
|
1170
|
+
.pipe(Effect.mapError(internalFailure(operation)));
|
|
1171
|
+
let producerEpoch: number;
|
|
1172
|
+
if (conversations.length === 0) {
|
|
1173
|
+
producerEpoch = 1;
|
|
1174
|
+
yield* sql`
|
|
1175
|
+
INSERT INTO effect_agent_conversations (
|
|
1176
|
+
conversation_id,
|
|
1177
|
+
created_at,
|
|
1178
|
+
tail_sequence,
|
|
1179
|
+
tail_digest,
|
|
1180
|
+
producer_epoch
|
|
1181
|
+
) VALUES (
|
|
1182
|
+
${head.conversation_id},
|
|
1183
|
+
${now.iso},
|
|
1184
|
+
0,
|
|
1185
|
+
${EMPTY_TAIL_DIGEST},
|
|
1186
|
+
${producerEpoch}
|
|
1187
|
+
)
|
|
1188
|
+
`.pipe(Effect.mapError(sqlFailure(operation)));
|
|
1189
|
+
} else {
|
|
1190
|
+
producerEpoch = conversations[0].producer_epoch + 1;
|
|
1191
|
+
yield* sql`
|
|
1192
|
+
UPDATE effect_agent_conversations
|
|
1193
|
+
SET producer_epoch = ${producerEpoch}
|
|
1194
|
+
WHERE conversation_id = ${head.conversation_id}
|
|
1195
|
+
`.pipe(Effect.mapError(sqlFailure(operation)));
|
|
1196
|
+
}
|
|
1197
|
+
|
|
1198
|
+
const leaseExpiresAt = new Date(now.millis + config.ownershipLeaseDuration).toISOString();
|
|
1199
|
+
yield* sql`
|
|
1200
|
+
INSERT INTO effect_agent_submission_ownership (
|
|
1201
|
+
submission_id,
|
|
1202
|
+
attempt_id,
|
|
1203
|
+
ownership_token,
|
|
1204
|
+
producer_epoch,
|
|
1205
|
+
owner_producer_id,
|
|
1206
|
+
lease_expires_at
|
|
1207
|
+
) VALUES (
|
|
1208
|
+
${head.submission_id},
|
|
1209
|
+
${attemptId},
|
|
1210
|
+
${ownershipToken},
|
|
1211
|
+
${producerEpoch},
|
|
1212
|
+
${validated.producerId},
|
|
1213
|
+
${leaseExpiresAt}
|
|
1214
|
+
)
|
|
1215
|
+
ON CONFLICT (submission_id) DO UPDATE SET
|
|
1216
|
+
attempt_id = excluded.attempt_id,
|
|
1217
|
+
ownership_token = excluded.ownership_token,
|
|
1218
|
+
producer_epoch = excluded.producer_epoch,
|
|
1219
|
+
owner_producer_id = excluded.owner_producer_id,
|
|
1220
|
+
lease_expires_at = excluded.lease_expires_at
|
|
1221
|
+
`.pipe(Effect.mapError(sqlFailure(operation)));
|
|
1222
|
+
|
|
1223
|
+
yield* sql`
|
|
1224
|
+
INSERT INTO effect_agent_attempts (
|
|
1225
|
+
attempt_id,
|
|
1226
|
+
submission_id,
|
|
1227
|
+
conversation_id,
|
|
1228
|
+
owner_producer_id,
|
|
1229
|
+
producer_epoch,
|
|
1230
|
+
claimed_at
|
|
1231
|
+
) VALUES (
|
|
1232
|
+
${attemptId},
|
|
1233
|
+
${head.submission_id},
|
|
1234
|
+
${head.conversation_id},
|
|
1235
|
+
${validated.producerId},
|
|
1236
|
+
${producerEpoch},
|
|
1237
|
+
${now.iso}
|
|
1238
|
+
)
|
|
1239
|
+
`.pipe(Effect.mapError(sqlFailure(operation)));
|
|
1240
|
+
|
|
1241
|
+
if (head.state === "ready") {
|
|
1242
|
+
yield* sql`
|
|
1243
|
+
UPDATE effect_agent_submissions
|
|
1244
|
+
SET state = 'running'
|
|
1245
|
+
WHERE submission_id = ${head.submission_id}
|
|
1246
|
+
`.pipe(Effect.mapError(sqlFailure(operation)));
|
|
1247
|
+
}
|
|
1248
|
+
|
|
1249
|
+
const inputPayload = yield* parseStoredJsonText(head.input_json).pipe(
|
|
1250
|
+
Effect.mapError((error) =>
|
|
1251
|
+
corruptionFailure(
|
|
1252
|
+
operation,
|
|
1253
|
+
"effect_agent_submissions",
|
|
1254
|
+
head.submission_id,
|
|
1255
|
+
error.message,
|
|
1256
|
+
),
|
|
1257
|
+
),
|
|
1258
|
+
);
|
|
1259
|
+
return Option.some(
|
|
1260
|
+
yield* decodeClaim({
|
|
1261
|
+
submissionId: head.submission_id,
|
|
1262
|
+
attemptId,
|
|
1263
|
+
ownershipToken,
|
|
1264
|
+
producerEpoch,
|
|
1265
|
+
leaseExpiresAt,
|
|
1266
|
+
inputPayload,
|
|
1267
|
+
}).pipe(Effect.mapError(internalFailure(operation))),
|
|
1268
|
+
);
|
|
1269
|
+
}),
|
|
1270
|
+
);
|
|
1271
|
+
yield* hitFailpoint("ledger:claim:after", operation);
|
|
1272
|
+
return claimed;
|
|
1273
|
+
},
|
|
1274
|
+
);
|
|
1275
|
+
|
|
1276
|
+
const renewOwnership: SubmissionLedger["Service"]["renewOwnership"] = Effect.fn(
|
|
1277
|
+
"SqliteSubmissionLedger.renewOwnership",
|
|
1278
|
+
)(function* (request: RenewOwnershipRequest) {
|
|
1279
|
+
const operation = "ledger renew ownership";
|
|
1280
|
+
const validated = yield* Schema.decodeUnknownEffect(Schema.toType(RenewOwnershipRequest))(
|
|
1281
|
+
request,
|
|
1282
|
+
).pipe(Effect.mapError(internalFailure(operation)));
|
|
1283
|
+
yield* hitFailpoint("ledger:renew:before", operation);
|
|
1284
|
+
const renewal = yield* inWriteTransaction(
|
|
1285
|
+
operation,
|
|
1286
|
+
Effect.gen(function* () {
|
|
1287
|
+
const submission = yield* requireSubmission(operation, validated.submissionId);
|
|
1288
|
+
yield* requireOwnership(operation, submission, validated.ownershipToken);
|
|
1289
|
+
const now = yield* currentInstant;
|
|
1290
|
+
const leaseExpiresAt = new Date(now.millis + config.ownershipLeaseDuration).toISOString();
|
|
1291
|
+
yield* sql`
|
|
1292
|
+
UPDATE effect_agent_submission_ownership
|
|
1293
|
+
SET lease_expires_at = ${leaseExpiresAt}
|
|
1294
|
+
WHERE submission_id = ${validated.submissionId}
|
|
1295
|
+
`.pipe(Effect.mapError(sqlFailure(operation)));
|
|
1296
|
+
return yield* decodeOwnershipRenewal({
|
|
1297
|
+
ownershipToken: validated.ownershipToken,
|
|
1298
|
+
leaseExpiresAt,
|
|
1299
|
+
}).pipe(Effect.mapError(internalFailure(operation)));
|
|
1300
|
+
}),
|
|
1301
|
+
);
|
|
1302
|
+
yield* hitFailpoint("ledger:renew:after", operation);
|
|
1303
|
+
return renewal;
|
|
1304
|
+
});
|
|
1305
|
+
|
|
1306
|
+
const releaseOwnership: SubmissionLedger["Service"]["releaseOwnership"] = Effect.fn(
|
|
1307
|
+
"SqliteSubmissionLedger.releaseOwnership",
|
|
1308
|
+
)(function* (request: ReleaseOwnershipRequest) {
|
|
1309
|
+
const operation = "ledger release ownership";
|
|
1310
|
+
const validated = yield* Schema.decodeUnknownEffect(Schema.toType(ReleaseOwnershipRequest))(
|
|
1311
|
+
request,
|
|
1312
|
+
).pipe(Effect.mapError(internalFailure(operation)));
|
|
1313
|
+
yield* hitFailpoint("ledger:release:before", operation);
|
|
1314
|
+
yield* inWriteTransaction(
|
|
1315
|
+
operation,
|
|
1316
|
+
Effect.gen(function* () {
|
|
1317
|
+
const submission = yield* requireSubmission(operation, validated.submissionId);
|
|
1318
|
+
yield* requireOwnership(operation, submission, validated.ownershipToken);
|
|
1319
|
+
yield* sql`
|
|
1320
|
+
DELETE FROM effect_agent_submission_ownership
|
|
1321
|
+
WHERE submission_id = ${validated.submissionId}
|
|
1322
|
+
`.pipe(Effect.mapError(sqlFailure(operation)));
|
|
1323
|
+
if (submission.state === "running") {
|
|
1324
|
+
yield* sql`
|
|
1325
|
+
UPDATE effect_agent_submissions
|
|
1326
|
+
SET state = 'ready'
|
|
1327
|
+
WHERE submission_id = ${validated.submissionId}
|
|
1328
|
+
`.pipe(Effect.mapError(sqlFailure(operation)));
|
|
1329
|
+
}
|
|
1330
|
+
}),
|
|
1331
|
+
);
|
|
1332
|
+
yield* hitFailpoint("ledger:release:after", operation);
|
|
1333
|
+
});
|
|
1334
|
+
|
|
1335
|
+
const markInputApplied: SubmissionLedger["Service"]["markInputApplied"] = Effect.fn(
|
|
1336
|
+
"SqliteSubmissionLedger.markInputApplied",
|
|
1337
|
+
)(function* (request: MarkInputAppliedRequest) {
|
|
1338
|
+
const operation = "ledger mark input applied";
|
|
1339
|
+
const validated = yield* Schema.decodeUnknownEffect(Schema.toType(MarkInputAppliedRequest))(
|
|
1340
|
+
request,
|
|
1341
|
+
).pipe(Effect.mapError(internalFailure(operation)));
|
|
1342
|
+
yield* hitFailpoint("ledger:mark-input-applied:before", operation);
|
|
1343
|
+
yield* inWriteTransaction(
|
|
1344
|
+
operation,
|
|
1345
|
+
Effect.gen(function* () {
|
|
1346
|
+
const submission = yield* requireSubmission(operation, validated.submissionId);
|
|
1347
|
+
yield* requireOwnership(operation, submission, validated.ownershipToken);
|
|
1348
|
+
if (submission.input_applied_record_id !== null) {
|
|
1349
|
+
if (
|
|
1350
|
+
submission.input_applied_record_id === validated.recordId &&
|
|
1351
|
+
submission.input_applied_sequence === validated.sequence
|
|
1352
|
+
) {
|
|
1353
|
+
return;
|
|
1354
|
+
}
|
|
1355
|
+
return yield* corruptionFailure(
|
|
1356
|
+
operation,
|
|
1357
|
+
"effect_agent_submissions",
|
|
1358
|
+
validated.submissionId,
|
|
1359
|
+
"A different canonical input marker is already recorded for this Submission.",
|
|
1360
|
+
);
|
|
1361
|
+
}
|
|
1362
|
+
yield* sql`
|
|
1363
|
+
UPDATE effect_agent_submissions
|
|
1364
|
+
SET
|
|
1365
|
+
input_applied_record_id = ${validated.recordId},
|
|
1366
|
+
input_applied_sequence = ${validated.sequence},
|
|
1367
|
+
state = CASE
|
|
1368
|
+
WHEN state IN ('admitted', 'ready', 'running') THEN 'input-applied'
|
|
1369
|
+
ELSE state
|
|
1370
|
+
END
|
|
1371
|
+
WHERE submission_id = ${validated.submissionId}
|
|
1372
|
+
`.pipe(Effect.mapError(sqlFailure(operation)));
|
|
1373
|
+
}),
|
|
1374
|
+
);
|
|
1375
|
+
yield* hitFailpoint("ledger:mark-input-applied:after", operation);
|
|
1376
|
+
});
|
|
1377
|
+
|
|
1378
|
+
const reserveSettlement: SubmissionLedger["Service"]["reserveSettlement"] = Effect.fn(
|
|
1379
|
+
"SqliteSubmissionLedger.reserveSettlement",
|
|
1380
|
+
)(function* (request: SettlementReservation) {
|
|
1381
|
+
const operation = "ledger reserve settlement";
|
|
1382
|
+
const validated = yield* Schema.decodeUnknownEffect(Schema.toType(SettlementReservation))(
|
|
1383
|
+
request,
|
|
1384
|
+
).pipe(Effect.mapError(internalFailure(operation)));
|
|
1385
|
+
const recordJson = yield* encodeRecordEnvelopeText(validated.record).pipe(
|
|
1386
|
+
Effect.mapError(internalFailure(operation)),
|
|
1387
|
+
);
|
|
1388
|
+
yield* hitFailpoint("ledger:reserve-settlement:before", operation);
|
|
1389
|
+
const reserved = yield* inWriteTransaction(
|
|
1390
|
+
operation,
|
|
1391
|
+
Effect.gen(function* () {
|
|
1392
|
+
const existing = yield* readReservation(operation, validated.submissionId);
|
|
1393
|
+
if (Option.isSome(existing)) {
|
|
1394
|
+
const identical =
|
|
1395
|
+
existing.value.settlement_id === validated.settlementId &&
|
|
1396
|
+
existing.value.outcome === validated.outcome &&
|
|
1397
|
+
existing.value.record_digest === validated.recordDigest &&
|
|
1398
|
+
existing.value.record_json === recordJson;
|
|
1399
|
+
if (!identical) {
|
|
1400
|
+
return yield* SettlementConflict.make({
|
|
1401
|
+
submissionId: validated.submissionId,
|
|
1402
|
+
existingOutcome: existing.value.outcome,
|
|
1403
|
+
});
|
|
1404
|
+
}
|
|
1405
|
+
const record = yield* decodeRecordEnvelopeText(existing.value.record_json).pipe(
|
|
1406
|
+
Effect.mapError((error) =>
|
|
1407
|
+
corruptionFailure(
|
|
1408
|
+
operation,
|
|
1409
|
+
"effect_agent_settlement_reservations",
|
|
1410
|
+
validated.submissionId,
|
|
1411
|
+
error.message,
|
|
1412
|
+
),
|
|
1413
|
+
),
|
|
1414
|
+
);
|
|
1415
|
+
return ReservedSettlement.make({
|
|
1416
|
+
submissionId: validated.submissionId,
|
|
1417
|
+
settlementId: validated.settlementId,
|
|
1418
|
+
outcome: validated.outcome,
|
|
1419
|
+
record,
|
|
1420
|
+
recordDigest: validated.recordDigest,
|
|
1421
|
+
replayed: true,
|
|
1422
|
+
});
|
|
1423
|
+
}
|
|
1424
|
+
|
|
1425
|
+
const submission = yield* requireSubmission(operation, validated.submissionId);
|
|
1426
|
+
if (submission.state === "settled") {
|
|
1427
|
+
if (submission.settled_outcome === null) {
|
|
1428
|
+
return yield* corruptionFailure(
|
|
1429
|
+
operation,
|
|
1430
|
+
"effect_agent_submissions",
|
|
1431
|
+
validated.submissionId,
|
|
1432
|
+
"A settled Submission carries no terminal outcome.",
|
|
1433
|
+
);
|
|
1434
|
+
}
|
|
1435
|
+
return yield* SettlementConflict.make({
|
|
1436
|
+
submissionId: validated.submissionId,
|
|
1437
|
+
existingOutcome: submission.settled_outcome,
|
|
1438
|
+
});
|
|
1439
|
+
}
|
|
1440
|
+
// A `joined` Submission settles WITH its host (plan §2.5) and its lane is never
|
|
1441
|
+
// worker-claimable, so no ownership token can exist for it: the recorded host linkage
|
|
1442
|
+
// authorizes the reservation and the presented token is not consulted.
|
|
1443
|
+
if (!(submission.state === "joined" && submission.joined_host_submission_id !== null)) {
|
|
1444
|
+
// P7 §7(c): an aborted, never-claimed, still-queued Submission likewise has no live
|
|
1445
|
+
// ownership to fence against — its durable abort intent authorizes exactly its
|
|
1446
|
+
// ABORTED settlement (`terminalizing` is the same pass's crash replay). Every other
|
|
1447
|
+
// reservation stays fenced by the target lane's live ownership.
|
|
1448
|
+
let queuedAbortSettlement = false;
|
|
1449
|
+
if (
|
|
1450
|
+
validated.outcome === "aborted" &&
|
|
1451
|
+
(submission.state === "ready" || submission.state === "terminalizing")
|
|
1452
|
+
) {
|
|
1453
|
+
const abortIntent = yield* readAbortIntent(operation, validated.submissionId);
|
|
1454
|
+
if (Option.isSome(abortIntent)) {
|
|
1455
|
+
const ownership = yield* readOwnership(operation, validated.submissionId);
|
|
1456
|
+
queuedAbortSettlement = Option.isNone(ownership);
|
|
1457
|
+
}
|
|
1458
|
+
}
|
|
1459
|
+
if (!queuedAbortSettlement) {
|
|
1460
|
+
yield* requireOwnership(operation, submission, validated.ownershipToken);
|
|
1461
|
+
}
|
|
1462
|
+
}
|
|
1463
|
+
const now = yield* currentInstant;
|
|
1464
|
+
yield* sql`
|
|
1465
|
+
INSERT INTO effect_agent_settlement_reservations (
|
|
1466
|
+
submission_id,
|
|
1467
|
+
settlement_id,
|
|
1468
|
+
outcome,
|
|
1469
|
+
record_id,
|
|
1470
|
+
record_json,
|
|
1471
|
+
record_digest,
|
|
1472
|
+
reserved_at
|
|
1473
|
+
) VALUES (
|
|
1474
|
+
${validated.submissionId},
|
|
1475
|
+
${validated.settlementId},
|
|
1476
|
+
${validated.outcome},
|
|
1477
|
+
${validated.record.recordId},
|
|
1478
|
+
${recordJson},
|
|
1479
|
+
${validated.recordDigest},
|
|
1480
|
+
${now.iso}
|
|
1481
|
+
)
|
|
1482
|
+
`.pipe(Effect.mapError(sqlFailure(operation)));
|
|
1483
|
+
yield* sql`
|
|
1484
|
+
UPDATE effect_agent_submissions
|
|
1485
|
+
SET state = 'terminalizing'
|
|
1486
|
+
WHERE submission_id = ${validated.submissionId}
|
|
1487
|
+
`.pipe(Effect.mapError(sqlFailure(operation)));
|
|
1488
|
+
return ReservedSettlement.make({
|
|
1489
|
+
submissionId: validated.submissionId,
|
|
1490
|
+
settlementId: validated.settlementId,
|
|
1491
|
+
outcome: validated.outcome,
|
|
1492
|
+
record: validated.record,
|
|
1493
|
+
recordDigest: validated.recordDigest,
|
|
1494
|
+
replayed: false,
|
|
1495
|
+
});
|
|
1496
|
+
}),
|
|
1497
|
+
);
|
|
1498
|
+
yield* hitFailpoint("ledger:reserve-settlement:after", operation);
|
|
1499
|
+
return reserved;
|
|
1500
|
+
});
|
|
1501
|
+
|
|
1502
|
+
const finalizeSettlement: SubmissionLedger["Service"]["finalizeSettlement"] = Effect.fn(
|
|
1503
|
+
"SqliteSubmissionLedger.finalizeSettlement",
|
|
1504
|
+
)(function* (request: SettlementFinalization) {
|
|
1505
|
+
const operation = "ledger finalize settlement";
|
|
1506
|
+
const validated = yield* Schema.decodeUnknownEffect(Schema.toType(SettlementFinalization))(
|
|
1507
|
+
request,
|
|
1508
|
+
).pipe(Effect.mapError(internalFailure(operation)));
|
|
1509
|
+
yield* hitFailpoint("ledger:finalize-settlement:before", operation);
|
|
1510
|
+
const settlement = yield* inWriteTransaction(
|
|
1511
|
+
operation,
|
|
1512
|
+
Effect.gen(function* () {
|
|
1513
|
+
const reservation = yield* readReservation(operation, validated.submissionId);
|
|
1514
|
+
if (Option.isNone(reservation)) {
|
|
1515
|
+
return yield* LedgerError.make({
|
|
1516
|
+
operation,
|
|
1517
|
+
message: `No settlement reservation exists for submission ${validated.submissionId}.`,
|
|
1518
|
+
});
|
|
1519
|
+
}
|
|
1520
|
+
if (reservation.value.settlement_id !== validated.settlementId) {
|
|
1521
|
+
return yield* SettlementConflict.make({
|
|
1522
|
+
submissionId: validated.submissionId,
|
|
1523
|
+
existingOutcome: reservation.value.outcome,
|
|
1524
|
+
});
|
|
1525
|
+
}
|
|
1526
|
+
const submission = yield* requireSubmission(operation, validated.submissionId);
|
|
1527
|
+
if (submission.state === "settled") {
|
|
1528
|
+
if (reservation.value.finalized_at === null) {
|
|
1529
|
+
return yield* corruptionFailure(
|
|
1530
|
+
operation,
|
|
1531
|
+
"effect_agent_settlement_reservations",
|
|
1532
|
+
validated.submissionId,
|
|
1533
|
+
"A settled Submission's reservation carries no finalization timestamp.",
|
|
1534
|
+
);
|
|
1535
|
+
}
|
|
1536
|
+
return yield* decodeSettlement({
|
|
1537
|
+
submissionId: validated.submissionId,
|
|
1538
|
+
settlementId: validated.settlementId,
|
|
1539
|
+
receiptId: submission.receipt_id,
|
|
1540
|
+
outcome: reservation.value.outcome,
|
|
1541
|
+
settledAt: reservation.value.finalized_at,
|
|
1542
|
+
}).pipe(Effect.mapError(internalFailure(operation)));
|
|
1543
|
+
}
|
|
1544
|
+
const now = yield* currentInstant;
|
|
1545
|
+
yield* sql`
|
|
1546
|
+
UPDATE effect_agent_submissions
|
|
1547
|
+
SET state = 'settled', settled_outcome = ${reservation.value.outcome}
|
|
1548
|
+
WHERE submission_id = ${validated.submissionId}
|
|
1549
|
+
`.pipe(Effect.mapError(sqlFailure(operation)));
|
|
1550
|
+
yield* sql`
|
|
1551
|
+
UPDATE effect_agent_settlement_reservations
|
|
1552
|
+
SET finalized_at = ${now.iso}
|
|
1553
|
+
WHERE submission_id = ${validated.submissionId}
|
|
1554
|
+
`.pipe(Effect.mapError(sqlFailure(operation)));
|
|
1555
|
+
yield* sql`
|
|
1556
|
+
DELETE FROM effect_agent_submission_ownership
|
|
1557
|
+
WHERE submission_id = ${validated.submissionId}
|
|
1558
|
+
`.pipe(Effect.mapError(sqlFailure(operation)));
|
|
1559
|
+
return yield* decodeSettlement({
|
|
1560
|
+
submissionId: validated.submissionId,
|
|
1561
|
+
settlementId: validated.settlementId,
|
|
1562
|
+
receiptId: submission.receipt_id,
|
|
1563
|
+
outcome: reservation.value.outcome,
|
|
1564
|
+
settledAt: now.iso,
|
|
1565
|
+
}).pipe(Effect.mapError(internalFailure(operation)));
|
|
1566
|
+
}),
|
|
1567
|
+
);
|
|
1568
|
+
yield* hitFailpoint("ledger:finalize-settlement:after", operation);
|
|
1569
|
+
return settlement;
|
|
1570
|
+
});
|
|
1571
|
+
|
|
1572
|
+
const requestAbort: SubmissionLedger["Service"]["requestAbort"] = Effect.fn(
|
|
1573
|
+
"SqliteSubmissionLedger.requestAbort",
|
|
1574
|
+
)(function* (request: AbortCommand) {
|
|
1575
|
+
const operation = "ledger request abort";
|
|
1576
|
+
const validated = yield* Schema.decodeUnknownEffect(Schema.toType(AbortCommand))(request).pipe(
|
|
1577
|
+
Effect.mapError(internalFailure(operation)),
|
|
1578
|
+
);
|
|
1579
|
+
yield* hitFailpoint("ledger:request-abort:before", operation);
|
|
1580
|
+
const intent = yield* inWriteTransaction(
|
|
1581
|
+
operation,
|
|
1582
|
+
Effect.gen(function* () {
|
|
1583
|
+
const submission = yield* requireSubmission(operation, validated.submissionId);
|
|
1584
|
+
if (submission.state === "settled") {
|
|
1585
|
+
if (submission.settled_outcome === null) {
|
|
1586
|
+
return yield* corruptionFailure(
|
|
1587
|
+
operation,
|
|
1588
|
+
"effect_agent_submissions",
|
|
1589
|
+
validated.submissionId,
|
|
1590
|
+
"A settled Submission carries no terminal outcome.",
|
|
1591
|
+
);
|
|
1592
|
+
}
|
|
1593
|
+
return yield* SettlementConflict.make({
|
|
1594
|
+
submissionId: validated.submissionId,
|
|
1595
|
+
existingOutcome: submission.settled_outcome,
|
|
1596
|
+
});
|
|
1597
|
+
}
|
|
1598
|
+
// A joined Submission settles WITH its host; the abort target is the host (plan
|
|
1599
|
+
// §2.5). A joining Submission still records the intent: it is honored only if the
|
|
1600
|
+
// host has not consumed the input (revert-then-abort).
|
|
1601
|
+
if (submission.state === "joined") {
|
|
1602
|
+
if (submission.joined_host_submission_id === null) {
|
|
1603
|
+
return yield* corruptionFailure(
|
|
1604
|
+
operation,
|
|
1605
|
+
"effect_agent_submissions",
|
|
1606
|
+
validated.submissionId,
|
|
1607
|
+
"A joined Submission carries no host linkage.",
|
|
1608
|
+
);
|
|
1609
|
+
}
|
|
1610
|
+
const hostSubmissionId = yield* decodeSubmissionId(
|
|
1611
|
+
submission.joined_host_submission_id,
|
|
1612
|
+
).pipe(Effect.mapError(internalFailure(operation)));
|
|
1613
|
+
return yield* JoinedToHost.make({
|
|
1614
|
+
submissionId: validated.submissionId,
|
|
1615
|
+
hostSubmissionId,
|
|
1616
|
+
});
|
|
1617
|
+
}
|
|
1618
|
+
const existing = yield* readAbortIntent(operation, validated.submissionId);
|
|
1619
|
+
if (Option.isSome(existing)) {
|
|
1620
|
+
return yield* abortIntentFromRow(
|
|
1621
|
+
operation,
|
|
1622
|
+
submission,
|
|
1623
|
+
validated.submissionId,
|
|
1624
|
+
existing.value,
|
|
1625
|
+
);
|
|
1626
|
+
}
|
|
1627
|
+
const now = yield* currentInstant;
|
|
1628
|
+
yield* sql`
|
|
1629
|
+
INSERT INTO effect_agent_abort_intents (
|
|
1630
|
+
submission_id,
|
|
1631
|
+
author,
|
|
1632
|
+
reason,
|
|
1633
|
+
requested_at
|
|
1634
|
+
) VALUES (
|
|
1635
|
+
${validated.submissionId},
|
|
1636
|
+
${validated.author},
|
|
1637
|
+
${validated.reason},
|
|
1638
|
+
${now.iso}
|
|
1639
|
+
)
|
|
1640
|
+
`.pipe(Effect.mapError(sqlFailure(operation)));
|
|
1641
|
+
const canonicalRecordId = yield* canonicalAbortRecordId(
|
|
1642
|
+
operation,
|
|
1643
|
+
submission.conversation_id,
|
|
1644
|
+
validated.submissionId,
|
|
1645
|
+
);
|
|
1646
|
+
return yield* decodeAbortIntent({
|
|
1647
|
+
submissionId: validated.submissionId,
|
|
1648
|
+
author: validated.author,
|
|
1649
|
+
reason: validated.reason,
|
|
1650
|
+
requestedAt: now.iso,
|
|
1651
|
+
...(canonicalRecordId === undefined ? {} : { canonicalRecordId }),
|
|
1652
|
+
}).pipe(Effect.mapError(internalFailure(operation)));
|
|
1653
|
+
}),
|
|
1654
|
+
);
|
|
1655
|
+
yield* hitFailpoint("ledger:request-abort:after", operation);
|
|
1656
|
+
return intent;
|
|
1657
|
+
});
|
|
1658
|
+
|
|
1659
|
+
const claimJoining: SubmissionLedger["Service"]["claimJoining"] = Effect.fn(
|
|
1660
|
+
"SqliteSubmissionLedger.claimJoining",
|
|
1661
|
+
)(function* (request: ClaimJoiningRequest) {
|
|
1662
|
+
const operation = "ledger claim joining";
|
|
1663
|
+
const validated = yield* Schema.decodeUnknownEffect(Schema.toType(ClaimJoiningRequest))(
|
|
1664
|
+
request,
|
|
1665
|
+
).pipe(Effect.mapError(internalFailure(operation)));
|
|
1666
|
+
yield* hitFailpoint("ledger:claim-joining:before", operation);
|
|
1667
|
+
const claims = yield* inWriteTransaction(
|
|
1668
|
+
operation,
|
|
1669
|
+
Effect.gen(function* () {
|
|
1670
|
+
const host = yield* requireSubmission(operation, validated.hostSubmissionId);
|
|
1671
|
+
if (host.conversation_id !== validated.conversationId) {
|
|
1672
|
+
return yield* LedgerError.make({
|
|
1673
|
+
operation,
|
|
1674
|
+
message: `Host submission ${validated.hostSubmissionId} does not belong to conversation ${validated.conversationId}.`,
|
|
1675
|
+
});
|
|
1676
|
+
}
|
|
1677
|
+
// The host Attempt already owns the lane; no epoch bump happens here (plan §2.5).
|
|
1678
|
+
yield* requireOwnership(operation, host, validated.ownershipToken);
|
|
1679
|
+
const laterRows = yield* sql<Record<string, unknown>>`
|
|
1680
|
+
SELECT ${sql.literal(SUBMISSION_COLUMNS)}
|
|
1681
|
+
FROM effect_agent_submissions
|
|
1682
|
+
WHERE conversation_id = ${validated.conversationId}
|
|
1683
|
+
AND queue_sequence > ${host.queue_sequence}
|
|
1684
|
+
ORDER BY queue_sequence ASC
|
|
1685
|
+
`.pipe(Effect.mapError(sqlFailure(operation)));
|
|
1686
|
+
const later = yield* decodeSubmissionRows(operation, validated.conversationId, laterRows);
|
|
1687
|
+
const claimed: Array<JoiningClaim> = [];
|
|
1688
|
+
for (const row of later) {
|
|
1689
|
+
if (claimed.length >= validated.maxCount) break;
|
|
1690
|
+
// Rows already claimed by THIS host extend its contiguous prefix and are skipped;
|
|
1691
|
+
// the coordinator re-delivers already-joined input through the coverage rule.
|
|
1692
|
+
if (
|
|
1693
|
+
(row.state === "joining" || row.state === "joined") &&
|
|
1694
|
+
row.joined_host_submission_id === validated.hostSubmissionId
|
|
1695
|
+
) {
|
|
1696
|
+
continue;
|
|
1697
|
+
}
|
|
1698
|
+
// P7 §7(c): an aborted-settled row is a CLOSED obligation, not a gap — recovery
|
|
1699
|
+
// settles aborted never-claimed queued work immediately, and settlement order of
|
|
1700
|
+
// never-run work is not execution order (DUR-004 bounds execution).
|
|
1701
|
+
if (row.state === "settled" && row.settled_outcome === "aborted") continue;
|
|
1702
|
+
// Any other non-ready row — an admitted-not-ready gap in particular — breaks the
|
|
1703
|
+
// contiguous ready prefix (plan §2.5); later ready work stays queued (DUR-004).
|
|
1704
|
+
if (row.state !== "ready") break;
|
|
1705
|
+
yield* sql`
|
|
1706
|
+
UPDATE effect_agent_submissions
|
|
1707
|
+
SET state = 'joining', joined_host_submission_id = ${validated.hostSubmissionId}
|
|
1708
|
+
WHERE submission_id = ${row.submission_id}
|
|
1709
|
+
`.pipe(Effect.mapError(sqlFailure(operation)));
|
|
1710
|
+
const inputPayload = yield* parseStoredJsonText(row.input_json).pipe(
|
|
1711
|
+
Effect.mapError((error) =>
|
|
1712
|
+
corruptionFailure(
|
|
1713
|
+
operation,
|
|
1714
|
+
"effect_agent_submissions",
|
|
1715
|
+
row.submission_id,
|
|
1716
|
+
error.message,
|
|
1717
|
+
),
|
|
1718
|
+
),
|
|
1719
|
+
);
|
|
1720
|
+
claimed.push(
|
|
1721
|
+
yield* decodeJoiningClaim({
|
|
1722
|
+
submissionId: row.submission_id,
|
|
1723
|
+
queueSequence: row.queue_sequence,
|
|
1724
|
+
inputPayload,
|
|
1725
|
+
}).pipe(Effect.mapError(internalFailure(operation))),
|
|
1726
|
+
);
|
|
1727
|
+
}
|
|
1728
|
+
return claimed as ReadonlyArray<JoiningClaim>;
|
|
1729
|
+
}),
|
|
1730
|
+
);
|
|
1731
|
+
yield* hitFailpoint("ledger:claim-joining:after", operation);
|
|
1732
|
+
return claims;
|
|
1733
|
+
});
|
|
1734
|
+
|
|
1735
|
+
const markJoined: SubmissionLedger["Service"]["markJoined"] = Effect.fn(
|
|
1736
|
+
"SqliteSubmissionLedger.markJoined",
|
|
1737
|
+
)(function* (request: MarkJoinedRequest) {
|
|
1738
|
+
const operation = "ledger mark joined";
|
|
1739
|
+
const validated = yield* Schema.decodeUnknownEffect(Schema.toType(MarkJoinedRequest))(
|
|
1740
|
+
request,
|
|
1741
|
+
).pipe(Effect.mapError(internalFailure(operation)));
|
|
1742
|
+
yield* hitFailpoint("ledger:mark-joined:before", operation);
|
|
1743
|
+
yield* inWriteTransaction(
|
|
1744
|
+
operation,
|
|
1745
|
+
Effect.gen(function* () {
|
|
1746
|
+
const submission = yield* requireSubmission(operation, validated.submissionId);
|
|
1747
|
+
if (submission.joined_host_submission_id === null) {
|
|
1748
|
+
return yield* LedgerError.make({
|
|
1749
|
+
operation,
|
|
1750
|
+
message: `Submission ${validated.submissionId} was never claimed for joining.`,
|
|
1751
|
+
});
|
|
1752
|
+
}
|
|
1753
|
+
const host = yield* requireSubmission(operation, submission.joined_host_submission_id);
|
|
1754
|
+
// The lane is host-owned: the presented token must own the HOST's ownership period,
|
|
1755
|
+
// which also lets a later host Attempt repair a lost marker from history (DUR-016).
|
|
1756
|
+
yield* requireOwnership(operation, host, validated.ownershipToken);
|
|
1757
|
+
if (submission.input_applied_record_id !== null) {
|
|
1758
|
+
if (
|
|
1759
|
+
submission.input_applied_record_id === validated.recordId &&
|
|
1760
|
+
submission.input_applied_sequence === validated.sequence
|
|
1761
|
+
) {
|
|
1762
|
+
return;
|
|
1763
|
+
}
|
|
1764
|
+
return yield* corruptionFailure(
|
|
1765
|
+
operation,
|
|
1766
|
+
"effect_agent_submissions",
|
|
1767
|
+
validated.submissionId,
|
|
1768
|
+
"A different join marker is already recorded for this Submission.",
|
|
1769
|
+
);
|
|
1770
|
+
}
|
|
1771
|
+
if (submission.state !== "joining" && submission.state !== "joined") {
|
|
1772
|
+
return yield* LedgerError.make({
|
|
1773
|
+
operation,
|
|
1774
|
+
message: `Cannot mark submission ${validated.submissionId} joined from state ${submission.state}.`,
|
|
1775
|
+
});
|
|
1776
|
+
}
|
|
1777
|
+
yield* sql`
|
|
1778
|
+
UPDATE effect_agent_submissions
|
|
1779
|
+
SET
|
|
1780
|
+
input_applied_record_id = ${validated.recordId},
|
|
1781
|
+
input_applied_sequence = ${validated.sequence},
|
|
1782
|
+
state = 'joined'
|
|
1783
|
+
WHERE submission_id = ${validated.submissionId}
|
|
1784
|
+
`.pipe(Effect.mapError(sqlFailure(operation)));
|
|
1785
|
+
}),
|
|
1786
|
+
);
|
|
1787
|
+
yield* hitFailpoint("ledger:mark-joined:after", operation);
|
|
1788
|
+
});
|
|
1789
|
+
|
|
1790
|
+
const revertJoining: SubmissionLedger["Service"]["revertJoining"] = Effect.fn(
|
|
1791
|
+
"SqliteSubmissionLedger.revertJoining",
|
|
1792
|
+
)(function* (request: RevertJoiningRequest) {
|
|
1793
|
+
const operation = "ledger revert joining";
|
|
1794
|
+
const validated = yield* Schema.decodeUnknownEffect(Schema.toType(RevertJoiningRequest))(
|
|
1795
|
+
request,
|
|
1796
|
+
).pipe(Effect.mapError(internalFailure(operation)));
|
|
1797
|
+
yield* hitFailpoint("ledger:revert-joining:before", operation);
|
|
1798
|
+
yield* inWriteTransaction(
|
|
1799
|
+
operation,
|
|
1800
|
+
Effect.gen(function* () {
|
|
1801
|
+
const submission = yield* requireSubmission(operation, validated.submissionId);
|
|
1802
|
+
// Idempotent and recovery-only: only a still-`joining` Submission reverts; an
|
|
1803
|
+
// already-joined (or already-reverted) Submission is a no-op (DUR-016).
|
|
1804
|
+
if (submission.state !== "joining") return;
|
|
1805
|
+
yield* sql`
|
|
1806
|
+
UPDATE effect_agent_submissions
|
|
1807
|
+
SET state = 'ready', joined_host_submission_id = NULL
|
|
1808
|
+
WHERE submission_id = ${validated.submissionId}
|
|
1809
|
+
`.pipe(Effect.mapError(sqlFailure(operation)));
|
|
1810
|
+
}),
|
|
1811
|
+
);
|
|
1812
|
+
yield* hitFailpoint("ledger:revert-joining:after", operation);
|
|
1813
|
+
});
|
|
1814
|
+
|
|
1815
|
+
const suspend: SubmissionLedger["Service"]["suspend"] = Effect.fn(
|
|
1816
|
+
"SqliteSubmissionLedger.suspend",
|
|
1817
|
+
)(function* (request: SuspendRequest) {
|
|
1818
|
+
const operation = "ledger suspend";
|
|
1819
|
+
const validated = yield* Schema.decodeUnknownEffect(Schema.toType(SuspendRequest))(
|
|
1820
|
+
request,
|
|
1821
|
+
).pipe(Effect.mapError(internalFailure(operation)));
|
|
1822
|
+
const reasonJson = yield* encodeSuspensionReasonText(validated.reason).pipe(
|
|
1823
|
+
Effect.mapError(internalFailure(operation)),
|
|
1824
|
+
);
|
|
1825
|
+
yield* hitFailpoint("ledger:suspend:before", operation);
|
|
1826
|
+
const outcome = yield* inWriteTransaction(
|
|
1827
|
+
operation,
|
|
1828
|
+
Effect.gen(function* () {
|
|
1829
|
+
const submission = yield* requireSubmission(operation, validated.submissionId);
|
|
1830
|
+
if (submission.state === "settled") {
|
|
1831
|
+
if (submission.settled_outcome === null) {
|
|
1832
|
+
return yield* corruptionFailure(
|
|
1833
|
+
operation,
|
|
1834
|
+
"effect_agent_submissions",
|
|
1835
|
+
validated.submissionId,
|
|
1836
|
+
"A settled Submission carries no terminal outcome.",
|
|
1837
|
+
);
|
|
1838
|
+
}
|
|
1839
|
+
return yield* SettlementConflict.make({
|
|
1840
|
+
submissionId: validated.submissionId,
|
|
1841
|
+
existingOutcome: submission.settled_outcome,
|
|
1842
|
+
});
|
|
1843
|
+
}
|
|
1844
|
+
// An exact terminal outcome is already reserved (DUR-011); suspension would
|
|
1845
|
+
// contradict it, so the reservation wins.
|
|
1846
|
+
const reservation = yield* readReservation(operation, validated.submissionId);
|
|
1847
|
+
if (Option.isSome(reservation)) {
|
|
1848
|
+
return yield* SettlementConflict.make({
|
|
1849
|
+
submissionId: validated.submissionId,
|
|
1850
|
+
existingOutcome: reservation.value.outcome,
|
|
1851
|
+
});
|
|
1852
|
+
}
|
|
1853
|
+
yield* requireOwnership(operation, submission, validated.ownershipToken);
|
|
1854
|
+
// A covering event that raced ahead of the suspend transaction (an approval decision,
|
|
1855
|
+
// or a child settlement observed directly from the child's row in this single-store
|
|
1856
|
+
// file) resumes the caller immediately WITHOUT releasing the lane (plan §2.6, §12).
|
|
1857
|
+
if (validated.reason._tag === "ApprovalPending") {
|
|
1858
|
+
const decisions = yield* readApprovalDecisions(operation, validated.submissionId);
|
|
1859
|
+
const decided = new Set(decisions.map((row) => row.tool_call_id));
|
|
1860
|
+
if (validated.reason.toolCallIds.every((toolCallId) => decided.has(toolCallId))) {
|
|
1861
|
+
return "resume-immediately" as SuspensionOutcome;
|
|
1862
|
+
}
|
|
1863
|
+
} else {
|
|
1864
|
+
let allSettled = true;
|
|
1865
|
+
for (const child of validated.reason.children) {
|
|
1866
|
+
const childRow = yield* readSubmission(operation, child.childSubmissionId);
|
|
1867
|
+
if (Option.isNone(childRow) || childRow.value.state !== "settled") {
|
|
1868
|
+
allSettled = false;
|
|
1869
|
+
break;
|
|
1870
|
+
}
|
|
1871
|
+
}
|
|
1872
|
+
if (allSettled) {
|
|
1873
|
+
return "resume-immediately" as SuspensionOutcome;
|
|
1874
|
+
}
|
|
1875
|
+
}
|
|
1876
|
+
const now = yield* currentInstant;
|
|
1877
|
+
yield* sql`
|
|
1878
|
+
UPDATE effect_agent_submissions
|
|
1879
|
+
SET
|
|
1880
|
+
state = 'suspended',
|
|
1881
|
+
suspended_reason_json = ${reasonJson},
|
|
1882
|
+
suspended_at = ${now.iso}
|
|
1883
|
+
WHERE submission_id = ${validated.submissionId}
|
|
1884
|
+
`.pipe(Effect.mapError(sqlFailure(operation)));
|
|
1885
|
+
// Suspension ends the ownership period WITHOUT settling: the accepted-work
|
|
1886
|
+
// obligation stays owed while the lane consumes no worker permit (plan §2.6).
|
|
1887
|
+
yield* sql`
|
|
1888
|
+
DELETE FROM effect_agent_submission_ownership
|
|
1889
|
+
WHERE submission_id = ${validated.submissionId}
|
|
1890
|
+
`.pipe(Effect.mapError(sqlFailure(operation)));
|
|
1891
|
+
return "suspended" as SuspensionOutcome;
|
|
1892
|
+
}),
|
|
1893
|
+
);
|
|
1894
|
+
yield* hitFailpoint("ledger:suspend:after", operation);
|
|
1895
|
+
return outcome;
|
|
1896
|
+
});
|
|
1897
|
+
|
|
1898
|
+
/**
|
|
1899
|
+
* Once every pending call of a recorded ApprovalPending suspension has a decision intent,
|
|
1900
|
+
* the lane wakes: suspended → input-applied, suspension cleared (plan §2.6). A
|
|
1901
|
+
* WaitingForChild suspension wakes only through recordChildSettled. Runs inside the caller's
|
|
1902
|
+
* write transaction.
|
|
1903
|
+
*/
|
|
1904
|
+
const wakeSuspendedIfCovered = Effect.fn("SqliteSubmissionLedger.wakeSuspendedIfCovered")(
|
|
1905
|
+
function* (operation: string, submission: SubmissionRow): Effect.fn.Return<void, LedgerError> {
|
|
1906
|
+
if (submission.state !== "suspended" || submission.suspended_reason_json === null) return;
|
|
1907
|
+
const reason = yield* Schema.decodeEffect(Schema.fromJsonString(SuspensionReason))(
|
|
1908
|
+
submission.suspended_reason_json,
|
|
1909
|
+
).pipe(
|
|
1910
|
+
Effect.mapError((error) =>
|
|
1911
|
+
corruptionFailure(
|
|
1912
|
+
operation,
|
|
1913
|
+
"effect_agent_submissions",
|
|
1914
|
+
submission.submission_id,
|
|
1915
|
+
error.message,
|
|
1916
|
+
),
|
|
1917
|
+
),
|
|
1918
|
+
);
|
|
1919
|
+
if (reason._tag !== "ApprovalPending") return;
|
|
1920
|
+
const decisions = yield* readApprovalDecisions(operation, submission.submission_id);
|
|
1921
|
+
const decided = new Set(decisions.map((row) => row.tool_call_id));
|
|
1922
|
+
if (!reason.toolCallIds.every((toolCallId) => decided.has(toolCallId))) return;
|
|
1923
|
+
yield* sql`
|
|
1924
|
+
UPDATE effect_agent_submissions
|
|
1925
|
+
SET
|
|
1926
|
+
state = 'input-applied',
|
|
1927
|
+
suspended_reason_json = NULL,
|
|
1928
|
+
suspended_at = NULL
|
|
1929
|
+
WHERE submission_id = ${submission.submission_id}
|
|
1930
|
+
`.pipe(Effect.mapError(sqlFailure(operation)));
|
|
1931
|
+
},
|
|
1932
|
+
);
|
|
1933
|
+
|
|
1934
|
+
const recordApprovalDecision: SubmissionLedger["Service"]["recordApprovalDecision"] = Effect.fn(
|
|
1935
|
+
"SqliteSubmissionLedger.recordApprovalDecision",
|
|
1936
|
+
)(function* (command: ApprovalDecisionCommand) {
|
|
1937
|
+
const operation = "ledger record approval decision";
|
|
1938
|
+
const validated = yield* Schema.decodeUnknownEffect(Schema.toType(ApprovalDecisionCommand))(
|
|
1939
|
+
command,
|
|
1940
|
+
).pipe(Effect.mapError(internalFailure(operation)));
|
|
1941
|
+
yield* hitFailpoint("ledger:approval-decision:before", operation);
|
|
1942
|
+
const intent = yield* inWriteTransaction(
|
|
1943
|
+
operation,
|
|
1944
|
+
Effect.gen(function* () {
|
|
1945
|
+
const submission = yield* requireSubmission(operation, validated.submissionId);
|
|
1946
|
+
if (submission.state === "settled") {
|
|
1947
|
+
if (submission.settled_outcome === null) {
|
|
1948
|
+
return yield* corruptionFailure(
|
|
1949
|
+
operation,
|
|
1950
|
+
"effect_agent_submissions",
|
|
1951
|
+
validated.submissionId,
|
|
1952
|
+
"A settled Submission carries no terminal outcome.",
|
|
1953
|
+
);
|
|
1954
|
+
}
|
|
1955
|
+
return yield* SettlementConflict.make({
|
|
1956
|
+
submissionId: validated.submissionId,
|
|
1957
|
+
existingOutcome: submission.settled_outcome,
|
|
1958
|
+
});
|
|
1959
|
+
}
|
|
1960
|
+
const decisions = yield* readApprovalDecisions(operation, validated.submissionId);
|
|
1961
|
+
const existing = decisions.find((row) => row.tool_call_id === validated.toolCallId);
|
|
1962
|
+
if (existing !== undefined) {
|
|
1963
|
+
// Idempotent per (submissionId, toolCallId): repeating the SAME decision replays
|
|
1964
|
+
// the recorded intent unchanged; a divergent re-decision conflicts.
|
|
1965
|
+
if (existing.decision !== validated.decision) {
|
|
1966
|
+
return yield* ApprovalConflict.make({
|
|
1967
|
+
submissionId: validated.submissionId,
|
|
1968
|
+
toolCallId: validated.toolCallId,
|
|
1969
|
+
existingDecision: existing.decision,
|
|
1970
|
+
});
|
|
1971
|
+
}
|
|
1972
|
+
return yield* approvalIntentFromRow(operation, existing);
|
|
1973
|
+
}
|
|
1974
|
+
const now = yield* currentInstant;
|
|
1975
|
+
yield* sql`
|
|
1976
|
+
INSERT INTO effect_agent_approval_decisions (
|
|
1977
|
+
submission_id,
|
|
1978
|
+
tool_call_id,
|
|
1979
|
+
decision,
|
|
1980
|
+
resolver,
|
|
1981
|
+
reason,
|
|
1982
|
+
decided_at
|
|
1983
|
+
) VALUES (
|
|
1984
|
+
${validated.submissionId},
|
|
1985
|
+
${validated.toolCallId},
|
|
1986
|
+
${validated.decision},
|
|
1987
|
+
${validated.resolver},
|
|
1988
|
+
${validated.reason},
|
|
1989
|
+
${now.iso}
|
|
1990
|
+
)
|
|
1991
|
+
`.pipe(Effect.mapError(sqlFailure(operation)));
|
|
1992
|
+
yield* wakeSuspendedIfCovered(operation, submission);
|
|
1993
|
+
return yield* decodeApprovalDecisionIntent({
|
|
1994
|
+
submissionId: validated.submissionId,
|
|
1995
|
+
toolCallId: validated.toolCallId,
|
|
1996
|
+
decision: validated.decision,
|
|
1997
|
+
resolver: validated.resolver,
|
|
1998
|
+
reason: validated.reason,
|
|
1999
|
+
decidedAt: now.iso,
|
|
2000
|
+
}).pipe(Effect.mapError(internalFailure(operation)));
|
|
2001
|
+
}),
|
|
2002
|
+
);
|
|
2003
|
+
yield* hitFailpoint("ledger:approval-decision:after", operation);
|
|
2004
|
+
return intent;
|
|
2005
|
+
});
|
|
2006
|
+
|
|
2007
|
+
const markUnknown: SubmissionLedger["Service"]["markUnknown"] = Effect.fn(
|
|
2008
|
+
"SqliteSubmissionLedger.markUnknown",
|
|
2009
|
+
)(function* (request: MarkUnknownRequest) {
|
|
2010
|
+
const operation = "ledger mark unknown";
|
|
2011
|
+
const validated = yield* Schema.decodeUnknownEffect(Schema.toType(MarkUnknownRequest))(
|
|
2012
|
+
request,
|
|
2013
|
+
).pipe(Effect.mapError(internalFailure(operation)));
|
|
2014
|
+
yield* hitFailpoint("ledger:mark-unknown:before", operation);
|
|
2015
|
+
yield* inWriteTransaction(
|
|
2016
|
+
operation,
|
|
2017
|
+
Effect.gen(function* () {
|
|
2018
|
+
const submission = yield* requireSubmission(operation, validated.submissionId);
|
|
2019
|
+
if (submission.state === "settled") {
|
|
2020
|
+
if (submission.settled_outcome === null) {
|
|
2021
|
+
return yield* corruptionFailure(
|
|
2022
|
+
operation,
|
|
2023
|
+
"effect_agent_submissions",
|
|
2024
|
+
validated.submissionId,
|
|
2025
|
+
"A settled Submission carries no terminal outcome.",
|
|
2026
|
+
);
|
|
2027
|
+
}
|
|
2028
|
+
return yield* SettlementConflict.make({
|
|
2029
|
+
submissionId: validated.submissionId,
|
|
2030
|
+
existingOutcome: submission.settled_outcome,
|
|
2031
|
+
});
|
|
2032
|
+
}
|
|
2033
|
+
// A reserved exact outcome wins over a late Unknown marking (DUR-011); the recovery
|
|
2034
|
+
// classifier orders reservation ahead of MarkUnknown for the same reason.
|
|
2035
|
+
const reservation = yield* readReservation(operation, validated.submissionId);
|
|
2036
|
+
if (Option.isSome(reservation)) {
|
|
2037
|
+
return yield* SettlementConflict.make({
|
|
2038
|
+
submissionId: validated.submissionId,
|
|
2039
|
+
existingOutcome: reservation.value.outcome,
|
|
2040
|
+
});
|
|
2041
|
+
}
|
|
2042
|
+
// Idempotent merge: repeating is a no-op; additional open calls extend the marked
|
|
2043
|
+
// set while the first recorded reason is kept.
|
|
2044
|
+
const existingIds = yield* storedUnknownToolCallIds(operation, submission);
|
|
2045
|
+
const known = new Set(existingIds);
|
|
2046
|
+
const merged = [
|
|
2047
|
+
...existingIds,
|
|
2048
|
+
...validated.toolCallIds.filter((toolCallId) => !known.has(toolCallId)),
|
|
2049
|
+
];
|
|
2050
|
+
const idsJson = yield* encodeToolCallIdsText(merged).pipe(
|
|
2051
|
+
Effect.mapError(internalFailure(operation)),
|
|
2052
|
+
);
|
|
2053
|
+
yield* sql`
|
|
2054
|
+
UPDATE effect_agent_submissions
|
|
2055
|
+
SET
|
|
2056
|
+
state = 'unknown',
|
|
2057
|
+
unknown_reason = ${submission.unknown_reason ?? validated.reason},
|
|
2058
|
+
unknown_tool_call_ids_json = ${idsJson}
|
|
2059
|
+
WHERE submission_id = ${validated.submissionId}
|
|
2060
|
+
`.pipe(Effect.mapError(sqlFailure(operation)));
|
|
2061
|
+
}),
|
|
2062
|
+
);
|
|
2063
|
+
yield* hitFailpoint("ledger:mark-unknown:after", operation);
|
|
2064
|
+
});
|
|
2065
|
+
|
|
2066
|
+
const recordUnknownResolution: SubmissionLedger["Service"]["recordUnknownResolution"] = Effect.fn(
|
|
2067
|
+
"SqliteSubmissionLedger.recordUnknownResolution",
|
|
2068
|
+
)(function* (command: UnknownResolutionCommand) {
|
|
2069
|
+
const operation = "ledger record unknown resolution";
|
|
2070
|
+
const validated = yield* Schema.decodeUnknownEffect(Schema.toType(UnknownResolutionCommand))(
|
|
2071
|
+
command,
|
|
2072
|
+
).pipe(Effect.mapError(internalFailure(operation)));
|
|
2073
|
+
const resolutionJson = yield* encodeUnknownResolutionText(validated.resolution).pipe(
|
|
2074
|
+
Effect.mapError(internalFailure(operation)),
|
|
2075
|
+
);
|
|
2076
|
+
yield* hitFailpoint("ledger:unknown-resolution:before", operation);
|
|
2077
|
+
const intent = yield* inWriteTransaction(
|
|
2078
|
+
operation,
|
|
2079
|
+
Effect.gen(function* () {
|
|
2080
|
+
const submission = yield* requireSubmission(operation, validated.submissionId);
|
|
2081
|
+
if (submission.state === "settled") {
|
|
2082
|
+
if (submission.settled_outcome === null) {
|
|
2083
|
+
return yield* corruptionFailure(
|
|
2084
|
+
operation,
|
|
2085
|
+
"effect_agent_submissions",
|
|
2086
|
+
validated.submissionId,
|
|
2087
|
+
"A settled Submission carries no terminal outcome.",
|
|
2088
|
+
);
|
|
2089
|
+
}
|
|
2090
|
+
return yield* SettlementConflict.make({
|
|
2091
|
+
submissionId: validated.submissionId,
|
|
2092
|
+
existingOutcome: submission.settled_outcome,
|
|
2093
|
+
});
|
|
2094
|
+
}
|
|
2095
|
+
const resolutions = yield* readUnknownResolutions(operation, validated.submissionId);
|
|
2096
|
+
const existing = resolutions.find((row) => row.tool_call_id === validated.toolCallId);
|
|
2097
|
+
if (existing !== undefined && existing.resolution_json !== resolutionJson) {
|
|
2098
|
+
return yield* UnknownResolutionConflict.make({
|
|
2099
|
+
submissionId: validated.submissionId,
|
|
2100
|
+
toolCallId: validated.toolCallId,
|
|
2101
|
+
});
|
|
2102
|
+
}
|
|
2103
|
+
let resolved: UnknownResolutionIntent;
|
|
2104
|
+
if (existing !== undefined) {
|
|
2105
|
+
// Idempotent replay of the recorded intent (author/reason may differ; the stored
|
|
2106
|
+
// audit fields win, exactly like requestAbort).
|
|
2107
|
+
resolved = yield* unknownResolutionIntentFromRow(operation, existing);
|
|
2108
|
+
} else {
|
|
2109
|
+
const now = yield* currentInstant;
|
|
2110
|
+
yield* sql`
|
|
2111
|
+
INSERT INTO effect_agent_unknown_resolutions (
|
|
2112
|
+
submission_id,
|
|
2113
|
+
tool_call_id,
|
|
2114
|
+
author,
|
|
2115
|
+
reason,
|
|
2116
|
+
resolution_json,
|
|
2117
|
+
resolved_at
|
|
2118
|
+
) VALUES (
|
|
2119
|
+
${validated.submissionId},
|
|
2120
|
+
${validated.toolCallId},
|
|
2121
|
+
${validated.author},
|
|
2122
|
+
${validated.reason},
|
|
2123
|
+
${resolutionJson},
|
|
2124
|
+
${now.iso}
|
|
2125
|
+
)
|
|
2126
|
+
`.pipe(Effect.mapError(sqlFailure(operation)));
|
|
2127
|
+
const resolution = yield* parseStoredJsonText(resolutionJson).pipe(
|
|
2128
|
+
Effect.mapError(internalFailure(operation)),
|
|
2129
|
+
);
|
|
2130
|
+
resolved = yield* decodeUnknownResolutionIntent({
|
|
2131
|
+
submissionId: validated.submissionId,
|
|
2132
|
+
toolCallId: validated.toolCallId,
|
|
2133
|
+
author: validated.author,
|
|
2134
|
+
reason: validated.reason,
|
|
2135
|
+
resolution,
|
|
2136
|
+
resolvedAt: now.iso,
|
|
2137
|
+
}).pipe(Effect.mapError(internalFailure(operation)));
|
|
2138
|
+
}
|
|
2139
|
+
// The lane reopens only when EVERY marked open call has a durable resolution intent:
|
|
2140
|
+
// unknown → input-applied (DUR-017). Replays re-run the coverage check so a
|
|
2141
|
+
// recovering caller can wake the lane idempotently.
|
|
2142
|
+
if (submission.state === "unknown" && submission.unknown_tool_call_ids_json !== null) {
|
|
2143
|
+
const markedIds = yield* storedUnknownToolCallIds(operation, submission);
|
|
2144
|
+
const covering = yield* readUnknownResolutions(operation, validated.submissionId);
|
|
2145
|
+
const coveredIds = new Set(covering.map((row) => row.tool_call_id));
|
|
2146
|
+
if (markedIds.every((toolCallId) => coveredIds.has(toolCallId))) {
|
|
2147
|
+
yield* sql`
|
|
2148
|
+
UPDATE effect_agent_submissions
|
|
2149
|
+
SET
|
|
2150
|
+
state = 'input-applied',
|
|
2151
|
+
unknown_reason = NULL,
|
|
2152
|
+
unknown_tool_call_ids_json = NULL
|
|
2153
|
+
WHERE submission_id = ${validated.submissionId}
|
|
2154
|
+
`.pipe(Effect.mapError(sqlFailure(operation)));
|
|
2155
|
+
}
|
|
2156
|
+
}
|
|
2157
|
+
return resolved;
|
|
2158
|
+
}),
|
|
2159
|
+
);
|
|
2160
|
+
yield* hitFailpoint("ledger:unknown-resolution:after", operation);
|
|
2161
|
+
return intent;
|
|
2162
|
+
});
|
|
2163
|
+
|
|
2164
|
+
const recordChildSettled: SubmissionLedger["Service"]["recordChildSettled"] = Effect.fn(
|
|
2165
|
+
"SqliteSubmissionLedger.recordChildSettled",
|
|
2166
|
+
)(function* (request: ChildSettledNotification) {
|
|
2167
|
+
const operation = "ledger record child settled";
|
|
2168
|
+
const validated = yield* Schema.decodeUnknownEffect(Schema.toType(ChildSettledNotification))(
|
|
2169
|
+
request,
|
|
2170
|
+
).pipe(Effect.mapError(internalFailure(operation)));
|
|
2171
|
+
yield* hitFailpoint("ledger:child-settled:before", operation);
|
|
2172
|
+
const outcome = yield* inWriteTransaction(
|
|
2173
|
+
operation,
|
|
2174
|
+
Effect.gen(function* () {
|
|
2175
|
+
const parent = yield* requireSubmission(operation, validated.parentSubmissionId);
|
|
2176
|
+
// The child's canonical Settlement is the authority for this wake; a notification for
|
|
2177
|
+
// an unsettled (or unknown) child is a caller error in a single-store adapter.
|
|
2178
|
+
const child = yield* readSubmission(operation, validated.childSubmissionId);
|
|
2179
|
+
if (Option.isNone(child) || child.value.state !== "settled") {
|
|
2180
|
+
return yield* LedgerError.make({
|
|
2181
|
+
operation,
|
|
2182
|
+
message: `Child submission ${validated.childSubmissionId} has no recorded settlement.`,
|
|
2183
|
+
});
|
|
2184
|
+
}
|
|
2185
|
+
if (parent.state !== "suspended" || parent.suspended_reason_json === null) {
|
|
2186
|
+
return "not-waiting" as ChildSettledOutcome;
|
|
2187
|
+
}
|
|
2188
|
+
const reason = yield* Schema.decodeEffect(Schema.fromJsonString(SuspensionReason))(
|
|
2189
|
+
parent.suspended_reason_json,
|
|
2190
|
+
).pipe(
|
|
2191
|
+
Effect.mapError((error) =>
|
|
2192
|
+
corruptionFailure(
|
|
2193
|
+
operation,
|
|
2194
|
+
"effect_agent_submissions",
|
|
2195
|
+
parent.submission_id,
|
|
2196
|
+
error.message,
|
|
2197
|
+
),
|
|
2198
|
+
),
|
|
2199
|
+
);
|
|
2200
|
+
if (reason._tag !== "WaitingForChild") {
|
|
2201
|
+
return "not-waiting" as ChildSettledOutcome;
|
|
2202
|
+
}
|
|
2203
|
+
if (
|
|
2204
|
+
!reason.children.some((entry) => entry.childSubmissionId === validated.childSubmissionId)
|
|
2205
|
+
) {
|
|
2206
|
+
return "not-waiting" as ChildSettledOutcome;
|
|
2207
|
+
}
|
|
2208
|
+
// The parent wakes exactly when EVERY listed child is settled (spec §12 step 10);
|
|
2209
|
+
// replays re-run the coverage check so a recovering caller wakes the lane idempotently.
|
|
2210
|
+
for (const entry of reason.children) {
|
|
2211
|
+
const listed = yield* readSubmission(operation, entry.childSubmissionId);
|
|
2212
|
+
if (Option.isNone(listed) || listed.value.state !== "settled") {
|
|
2213
|
+
return "still-waiting" as ChildSettledOutcome;
|
|
2214
|
+
}
|
|
2215
|
+
}
|
|
2216
|
+
yield* sql`
|
|
2217
|
+
UPDATE effect_agent_submissions
|
|
2218
|
+
SET
|
|
2219
|
+
state = 'input-applied',
|
|
2220
|
+
suspended_reason_json = NULL,
|
|
2221
|
+
suspended_at = NULL
|
|
2222
|
+
WHERE submission_id = ${validated.parentSubmissionId}
|
|
2223
|
+
`.pipe(Effect.mapError(sqlFailure(operation)));
|
|
2224
|
+
return "woken" as ChildSettledOutcome;
|
|
2225
|
+
}),
|
|
2226
|
+
);
|
|
2227
|
+
yield* hitFailpoint("ledger:child-settled:after", operation);
|
|
2228
|
+
return outcome;
|
|
2229
|
+
});
|
|
2230
|
+
|
|
2231
|
+
const reserveChildBudget: SubmissionLedger["Service"]["reserveChildBudget"] = Effect.fn(
|
|
2232
|
+
"SqliteSubmissionLedger.reserveChildBudget",
|
|
2233
|
+
)(function* (request: ChildBudgetReservationRequest) {
|
|
2234
|
+
const operation = "ledger reserve child budget";
|
|
2235
|
+
const validated = yield* Schema.decodeUnknownEffect(
|
|
2236
|
+
Schema.toType(ChildBudgetReservationRequest),
|
|
2237
|
+
)(request).pipe(Effect.mapError(internalFailure(operation)));
|
|
2238
|
+
const allocationJson = yield* encodePersistedJsonText(validated.allocation).pipe(
|
|
2239
|
+
Effect.mapError(internalFailure(operation)),
|
|
2240
|
+
);
|
|
2241
|
+
yield* hitFailpoint("ledger:child-reservation:before", operation);
|
|
2242
|
+
const reserved = yield* inWriteTransaction(
|
|
2243
|
+
operation,
|
|
2244
|
+
Effect.gen(function* () {
|
|
2245
|
+
const existing = yield* readChildReservation(operation, validated.reservationId);
|
|
2246
|
+
if (Option.isSome(existing)) {
|
|
2247
|
+
// Identical replays short-circuit before the fence, mirroring reserveSettlement: a
|
|
2248
|
+
// replay creates nothing, so a recovering caller resumes rather than duplicates.
|
|
2249
|
+
const identical =
|
|
2250
|
+
existing.value.parent_submission_id === validated.parentSubmissionId &&
|
|
2251
|
+
existing.value.parent_tool_call_id === validated.parentToolCallId &&
|
|
2252
|
+
existing.value.allocation_digest === validated.allocationDigest &&
|
|
2253
|
+
existing.value.allocation_json === allocationJson;
|
|
2254
|
+
if (!identical) {
|
|
2255
|
+
return yield* ChildReservationConflict.make({
|
|
2256
|
+
reservationId: validated.reservationId,
|
|
2257
|
+
status: existing.value.status,
|
|
2258
|
+
message:
|
|
2259
|
+
"A reservation with this identity exists with a different parent Tool Call or allocation.",
|
|
2260
|
+
});
|
|
2261
|
+
}
|
|
2262
|
+
return ReservedChildBudget.make({
|
|
2263
|
+
reservation: yield* childReservationSnapshotFromRow(operation, existing.value),
|
|
2264
|
+
replayed: true,
|
|
2265
|
+
});
|
|
2266
|
+
}
|
|
2267
|
+
const collision = yield* readChildReservationForCall(
|
|
2268
|
+
operation,
|
|
2269
|
+
validated.parentSubmissionId,
|
|
2270
|
+
validated.parentToolCallId,
|
|
2271
|
+
);
|
|
2272
|
+
if (Option.isSome(collision)) {
|
|
2273
|
+
return yield* ChildReservationConflict.make({
|
|
2274
|
+
reservationId: validated.reservationId,
|
|
2275
|
+
status: collision.value.status,
|
|
2276
|
+
message: `Parent Tool Call ${validated.parentToolCallId} already owns reservation ${collision.value.reservation_id}.`,
|
|
2277
|
+
});
|
|
2278
|
+
}
|
|
2279
|
+
const parent = yield* requireSubmission(operation, validated.parentSubmissionId);
|
|
2280
|
+
// Creation is fenced by the parent lane's live ownership (spec §12 step 2): a stale
|
|
2281
|
+
// parent Attempt can never create new reservation state.
|
|
2282
|
+
yield* requireOwnership(operation, parent, validated.ownershipToken);
|
|
2283
|
+
const now = yield* currentInstant;
|
|
2284
|
+
yield* sql`
|
|
2285
|
+
INSERT INTO effect_agent_child_reservations (
|
|
2286
|
+
reservation_id,
|
|
2287
|
+
parent_submission_id,
|
|
2288
|
+
parent_tool_call_id,
|
|
2289
|
+
status,
|
|
2290
|
+
allocation_json,
|
|
2291
|
+
allocation_digest,
|
|
2292
|
+
reserved_at
|
|
2293
|
+
) VALUES (
|
|
2294
|
+
${validated.reservationId},
|
|
2295
|
+
${validated.parentSubmissionId},
|
|
2296
|
+
${validated.parentToolCallId},
|
|
2297
|
+
'reserved',
|
|
2298
|
+
${allocationJson},
|
|
2299
|
+
${validated.allocationDigest},
|
|
2300
|
+
${now.iso}
|
|
2301
|
+
)
|
|
2302
|
+
`.pipe(Effect.mapError(sqlFailure(operation)));
|
|
2303
|
+
const inserted = yield* readChildReservation(operation, validated.reservationId);
|
|
2304
|
+
if (Option.isNone(inserted)) {
|
|
2305
|
+
return yield* corruptionFailure(
|
|
2306
|
+
operation,
|
|
2307
|
+
"effect_agent_child_reservations",
|
|
2308
|
+
validated.reservationId,
|
|
2309
|
+
"An inserted child reservation row is missing inside its own transaction.",
|
|
2310
|
+
);
|
|
2311
|
+
}
|
|
2312
|
+
return ReservedChildBudget.make({
|
|
2313
|
+
reservation: yield* childReservationSnapshotFromRow(operation, inserted.value),
|
|
2314
|
+
replayed: false,
|
|
2315
|
+
});
|
|
2316
|
+
}),
|
|
2317
|
+
);
|
|
2318
|
+
yield* hitFailpoint("ledger:child-reservation:after", operation);
|
|
2319
|
+
return reserved;
|
|
2320
|
+
});
|
|
2321
|
+
|
|
2322
|
+
const attachChildToReservation: SubmissionLedger["Service"]["attachChildToReservation"] =
|
|
2323
|
+
Effect.fn("SqliteSubmissionLedger.attachChildToReservation")(function* (
|
|
2324
|
+
request: AttachChildToReservationRequest,
|
|
2325
|
+
) {
|
|
2326
|
+
const operation = "ledger attach child to reservation";
|
|
2327
|
+
const validated = yield* Schema.decodeUnknownEffect(
|
|
2328
|
+
Schema.toType(AttachChildToReservationRequest),
|
|
2329
|
+
)(request).pipe(Effect.mapError(internalFailure(operation)));
|
|
2330
|
+
yield* hitFailpoint("ledger:child-attach:before", operation);
|
|
2331
|
+
const attached = yield* inWriteTransaction(
|
|
2332
|
+
operation,
|
|
2333
|
+
Effect.gen(function* () {
|
|
2334
|
+
const existing = yield* readChildReservation(operation, validated.reservationId);
|
|
2335
|
+
if (Option.isNone(existing)) {
|
|
2336
|
+
return yield* LedgerError.make({
|
|
2337
|
+
operation,
|
|
2338
|
+
message: `Unknown child reservation ${validated.reservationId}.`,
|
|
2339
|
+
});
|
|
2340
|
+
}
|
|
2341
|
+
if (existing.value.child_submission_id !== null) {
|
|
2342
|
+
// Idempotent replay of the recorded attachment (unfenced — it mutates nothing).
|
|
2343
|
+
if (existing.value.child_submission_id === validated.childSubmissionId) {
|
|
2344
|
+
return yield* childReservationSnapshotFromRow(operation, existing.value);
|
|
2345
|
+
}
|
|
2346
|
+
return yield* ChildReservationConflict.make({
|
|
2347
|
+
reservationId: validated.reservationId,
|
|
2348
|
+
status: existing.value.status,
|
|
2349
|
+
message: `Reservation ${validated.reservationId} already records child ${existing.value.child_submission_id}.`,
|
|
2350
|
+
});
|
|
2351
|
+
}
|
|
2352
|
+
const parent = yield* requireSubmission(operation, existing.value.parent_submission_id);
|
|
2353
|
+
yield* requireOwnership(operation, parent, validated.ownershipToken);
|
|
2354
|
+
if (existing.value.status !== "reserved") {
|
|
2355
|
+
return yield* ChildReservationConflict.make({
|
|
2356
|
+
reservationId: validated.reservationId,
|
|
2357
|
+
status: existing.value.status,
|
|
2358
|
+
message: `Cannot attach a child to a ${existing.value.status} reservation.`,
|
|
2359
|
+
});
|
|
2360
|
+
}
|
|
2361
|
+
// Single-store latitude: the admitted child must exist here, so a dangling
|
|
2362
|
+
// attachment can never enter the recovery view.
|
|
2363
|
+
const child = yield* readSubmission(operation, validated.childSubmissionId);
|
|
2364
|
+
if (Option.isNone(child)) {
|
|
2365
|
+
return yield* LedgerError.make({
|
|
2366
|
+
operation,
|
|
2367
|
+
message: `Unknown child submission ${validated.childSubmissionId}.`,
|
|
2368
|
+
});
|
|
2369
|
+
}
|
|
2370
|
+
yield* sql`
|
|
2371
|
+
UPDATE effect_agent_child_reservations
|
|
2372
|
+
SET child_submission_id = ${validated.childSubmissionId}
|
|
2373
|
+
WHERE reservation_id = ${validated.reservationId}
|
|
2374
|
+
`.pipe(Effect.mapError(sqlFailure(operation)));
|
|
2375
|
+
const updated = yield* readChildReservation(operation, validated.reservationId);
|
|
2376
|
+
if (Option.isNone(updated)) {
|
|
2377
|
+
return yield* corruptionFailure(
|
|
2378
|
+
operation,
|
|
2379
|
+
"effect_agent_child_reservations",
|
|
2380
|
+
validated.reservationId,
|
|
2381
|
+
"An updated child reservation row is missing inside its own transaction.",
|
|
2382
|
+
);
|
|
2383
|
+
}
|
|
2384
|
+
return yield* childReservationSnapshotFromRow(operation, updated.value);
|
|
2385
|
+
}),
|
|
2386
|
+
);
|
|
2387
|
+
yield* hitFailpoint("ledger:child-attach:after", operation);
|
|
2388
|
+
return attached;
|
|
2389
|
+
});
|
|
2390
|
+
|
|
2391
|
+
const beginChildBudgetRelease: SubmissionLedger["Service"]["beginChildBudgetRelease"] = Effect.fn(
|
|
2392
|
+
"SqliteSubmissionLedger.beginChildBudgetRelease",
|
|
2393
|
+
)(function* (request: BeginChildBudgetReleaseRequest) {
|
|
2394
|
+
const operation = "ledger begin child budget release";
|
|
2395
|
+
const validated = yield* Schema.decodeUnknownEffect(
|
|
2396
|
+
Schema.toType(BeginChildBudgetReleaseRequest),
|
|
2397
|
+
)(request).pipe(Effect.mapError(internalFailure(operation)));
|
|
2398
|
+
const accountingJson = yield* encodePersistedJsonText(validated.accounting).pipe(
|
|
2399
|
+
Effect.mapError(internalFailure(operation)),
|
|
2400
|
+
);
|
|
2401
|
+
yield* hitFailpoint("ledger:child-release-pending:before", operation);
|
|
2402
|
+
const frozen = yield* inWriteTransaction(
|
|
2403
|
+
operation,
|
|
2404
|
+
Effect.gen(function* () {
|
|
2405
|
+
const existing = yield* readChildReservation(operation, validated.reservationId);
|
|
2406
|
+
if (Option.isNone(existing)) {
|
|
2407
|
+
return yield* LedgerError.make({
|
|
2408
|
+
operation,
|
|
2409
|
+
message: `Unknown child reservation ${validated.reservationId}.`,
|
|
2410
|
+
});
|
|
2411
|
+
}
|
|
2412
|
+
if (existing.value.status !== "reserved") {
|
|
2413
|
+
// The accounting decision was already frozen exactly once; an identical replay is a
|
|
2414
|
+
// no-op and a divergent decision conflicts (spec §12 join step 6).
|
|
2415
|
+
if (existing.value.accounting_json === accountingJson) {
|
|
2416
|
+
return yield* childReservationSnapshotFromRow(operation, existing.value);
|
|
2417
|
+
}
|
|
2418
|
+
return yield* ChildReservationConflict.make({
|
|
2419
|
+
reservationId: validated.reservationId,
|
|
2420
|
+
status: existing.value.status,
|
|
2421
|
+
message: "A different accounting decision is already frozen for this reservation.",
|
|
2422
|
+
});
|
|
2423
|
+
}
|
|
2424
|
+
const now = yield* currentInstant;
|
|
2425
|
+
yield* sql`
|
|
2426
|
+
UPDATE effect_agent_child_reservations
|
|
2427
|
+
SET
|
|
2428
|
+
status = 'releasePending',
|
|
2429
|
+
accounting_json = ${accountingJson},
|
|
2430
|
+
release_began_at = ${now.iso}
|
|
2431
|
+
WHERE reservation_id = ${validated.reservationId}
|
|
2432
|
+
`.pipe(Effect.mapError(sqlFailure(operation)));
|
|
2433
|
+
const updated = yield* readChildReservation(operation, validated.reservationId);
|
|
2434
|
+
if (Option.isNone(updated)) {
|
|
2435
|
+
return yield* corruptionFailure(
|
|
2436
|
+
operation,
|
|
2437
|
+
"effect_agent_child_reservations",
|
|
2438
|
+
validated.reservationId,
|
|
2439
|
+
"An updated child reservation row is missing inside its own transaction.",
|
|
2440
|
+
);
|
|
2441
|
+
}
|
|
2442
|
+
return yield* childReservationSnapshotFromRow(operation, updated.value);
|
|
2443
|
+
}),
|
|
2444
|
+
);
|
|
2445
|
+
yield* hitFailpoint("ledger:child-release-pending:after", operation);
|
|
2446
|
+
return frozen;
|
|
2447
|
+
});
|
|
2448
|
+
|
|
2449
|
+
const releaseChildBudget: SubmissionLedger["Service"]["releaseChildBudget"] = Effect.fn(
|
|
2450
|
+
"SqliteSubmissionLedger.releaseChildBudget",
|
|
2451
|
+
)(function* (request: ReleaseChildBudgetRequest) {
|
|
2452
|
+
const operation = "ledger release child budget";
|
|
2453
|
+
const validated = yield* Schema.decodeUnknownEffect(Schema.toType(ReleaseChildBudgetRequest))(
|
|
2454
|
+
request,
|
|
2455
|
+
).pipe(Effect.mapError(internalFailure(operation)));
|
|
2456
|
+
yield* hitFailpoint("ledger:child-release:before", operation);
|
|
2457
|
+
const released = yield* inWriteTransaction(
|
|
2458
|
+
operation,
|
|
2459
|
+
Effect.gen(function* () {
|
|
2460
|
+
const existing = yield* readChildReservation(operation, validated.reservationId);
|
|
2461
|
+
if (Option.isNone(existing)) {
|
|
2462
|
+
return yield* LedgerError.make({
|
|
2463
|
+
operation,
|
|
2464
|
+
message: `Unknown child reservation ${validated.reservationId}.`,
|
|
2465
|
+
});
|
|
2466
|
+
}
|
|
2467
|
+
// Applied exactly once: replaying a released reservation returns the stored row
|
|
2468
|
+
// unchanged (spec §12: "never available twice").
|
|
2469
|
+
if (existing.value.status === "released") {
|
|
2470
|
+
return yield* childReservationSnapshotFromRow(operation, existing.value);
|
|
2471
|
+
}
|
|
2472
|
+
if (existing.value.status !== "releasePending") {
|
|
2473
|
+
return yield* ChildReservationConflict.make({
|
|
2474
|
+
reservationId: validated.reservationId,
|
|
2475
|
+
status: existing.value.status,
|
|
2476
|
+
message: "Cannot release a reservation whose accounting decision is not frozen.",
|
|
2477
|
+
});
|
|
2478
|
+
}
|
|
2479
|
+
const now = yield* currentInstant;
|
|
2480
|
+
yield* sql`
|
|
2481
|
+
UPDATE effect_agent_child_reservations
|
|
2482
|
+
SET status = 'released', released_at = ${now.iso}
|
|
2483
|
+
WHERE reservation_id = ${validated.reservationId}
|
|
2484
|
+
`.pipe(Effect.mapError(sqlFailure(operation)));
|
|
2485
|
+
const updated = yield* readChildReservation(operation, validated.reservationId);
|
|
2486
|
+
if (Option.isNone(updated)) {
|
|
2487
|
+
return yield* corruptionFailure(
|
|
2488
|
+
operation,
|
|
2489
|
+
"effect_agent_child_reservations",
|
|
2490
|
+
validated.reservationId,
|
|
2491
|
+
"An updated child reservation row is missing inside its own transaction.",
|
|
2492
|
+
);
|
|
2493
|
+
}
|
|
2494
|
+
return yield* childReservationSnapshotFromRow(operation, updated.value);
|
|
2495
|
+
}),
|
|
2496
|
+
);
|
|
2497
|
+
yield* hitFailpoint("ledger:child-release:after", operation);
|
|
2498
|
+
return released;
|
|
2499
|
+
});
|
|
2500
|
+
|
|
2501
|
+
interface ScanCursor {
|
|
2502
|
+
readonly conversationId: string;
|
|
2503
|
+
readonly queueSequence: number;
|
|
2504
|
+
}
|
|
2505
|
+
|
|
2506
|
+
const scanPage = Effect.fn("SqliteSubmissionLedger.scanPage")(function* (
|
|
2507
|
+
cursor: ScanCursor | undefined,
|
|
2508
|
+
): Effect.fn.Return<
|
|
2509
|
+
readonly [ReadonlyArray<SubmissionSnapshot>, Option.Option<ScanCursor | undefined>],
|
|
2510
|
+
LedgerError
|
|
2511
|
+
> {
|
|
2512
|
+
const operation = "ledger scan nonterminal";
|
|
2513
|
+
const rows = yield* (
|
|
2514
|
+
cursor === undefined
|
|
2515
|
+
? sql<Record<string, unknown>>`
|
|
2516
|
+
SELECT ${sql.literal(SUBMISSION_COLUMNS)}
|
|
2517
|
+
FROM effect_agent_submissions
|
|
2518
|
+
WHERE state <> 'settled'
|
|
2519
|
+
ORDER BY conversation_id ASC, queue_sequence ASC
|
|
2520
|
+
LIMIT ${SCAN_PAGE_SIZE}
|
|
2521
|
+
`
|
|
2522
|
+
: sql<Record<string, unknown>>`
|
|
2523
|
+
SELECT ${sql.literal(SUBMISSION_COLUMNS)}
|
|
2524
|
+
FROM effect_agent_submissions
|
|
2525
|
+
WHERE state <> 'settled'
|
|
2526
|
+
AND (
|
|
2527
|
+
conversation_id > ${cursor.conversationId}
|
|
2528
|
+
OR (
|
|
2529
|
+
conversation_id = ${cursor.conversationId}
|
|
2530
|
+
AND queue_sequence > ${cursor.queueSequence}
|
|
2531
|
+
)
|
|
2532
|
+
)
|
|
2533
|
+
ORDER BY conversation_id ASC, queue_sequence ASC
|
|
2534
|
+
LIMIT ${SCAN_PAGE_SIZE}
|
|
2535
|
+
`
|
|
2536
|
+
).pipe(Effect.mapError(sqlFailure(operation)));
|
|
2537
|
+
const decoded = yield* decodeSubmissionRows(operation, "nonterminal_scan", rows);
|
|
2538
|
+
const snapshots = yield* Effect.forEach(decoded, (row) =>
|
|
2539
|
+
decodeSubmissionSnapshot(operation, row),
|
|
2540
|
+
);
|
|
2541
|
+
const last = decoded[decoded.length - 1];
|
|
2542
|
+
const next: Option.Option<ScanCursor | undefined> =
|
|
2543
|
+
last === undefined || decoded.length < SCAN_PAGE_SIZE
|
|
2544
|
+
? Option.none()
|
|
2545
|
+
: Option.some({
|
|
2546
|
+
conversationId: last.conversation_id,
|
|
2547
|
+
queueSequence: last.queue_sequence,
|
|
2548
|
+
});
|
|
2549
|
+
return [snapshots, next] as const;
|
|
2550
|
+
});
|
|
2551
|
+
|
|
2552
|
+
const scanNonterminal: Stream.Stream<SubmissionSnapshot, LedgerError> = Stream.paginate(
|
|
2553
|
+
undefined as ScanCursor | undefined,
|
|
2554
|
+
scanPage,
|
|
2555
|
+
);
|
|
2556
|
+
|
|
2557
|
+
const loadRecoverySnapshot: SubmissionLedger["Service"]["loadRecoverySnapshot"] = Effect.fn(
|
|
2558
|
+
"SqliteSubmissionLedger.loadRecoverySnapshot",
|
|
2559
|
+
)(function* (request: RecoverySnapshotRequest) {
|
|
2560
|
+
const operation = "ledger load recovery snapshot";
|
|
2561
|
+
const validated = yield* Schema.decodeUnknownEffect(Schema.toType(RecoverySnapshotRequest))(
|
|
2562
|
+
request,
|
|
2563
|
+
).pipe(Effect.mapError(internalFailure(operation)));
|
|
2564
|
+
return yield* sql
|
|
2565
|
+
.withTransaction(
|
|
2566
|
+
Effect.gen(function* () {
|
|
2567
|
+
const submissionRow = yield* requireSubmission(operation, validated.submissionId);
|
|
2568
|
+
const submission = yield* decodeSubmissionSnapshot(operation, submissionRow);
|
|
2569
|
+
|
|
2570
|
+
let ownership: OwnershipSnapshot | undefined;
|
|
2571
|
+
const ownershipRow = yield* readOwnership(operation, validated.submissionId);
|
|
2572
|
+
if (Option.isSome(ownershipRow)) {
|
|
2573
|
+
ownership = yield* decodeOwnershipSnapshot({
|
|
2574
|
+
attemptId: ownershipRow.value.attempt_id,
|
|
2575
|
+
ownerProducerId: ownershipRow.value.owner_producer_id,
|
|
2576
|
+
producerEpoch: ownershipRow.value.producer_epoch,
|
|
2577
|
+
leaseExpiresAt: ownershipRow.value.lease_expires_at,
|
|
2578
|
+
}).pipe(Effect.mapError(internalFailure(operation)));
|
|
2579
|
+
}
|
|
2580
|
+
|
|
2581
|
+
let inputApplied: InputAppliedMarker | undefined;
|
|
2582
|
+
if (
|
|
2583
|
+
submissionRow.input_applied_record_id !== null &&
|
|
2584
|
+
submissionRow.input_applied_sequence !== null
|
|
2585
|
+
) {
|
|
2586
|
+
inputApplied = yield* decodeInputAppliedMarker({
|
|
2587
|
+
recordId: submissionRow.input_applied_record_id,
|
|
2588
|
+
sequence: submissionRow.input_applied_sequence,
|
|
2589
|
+
}).pipe(Effect.mapError(internalFailure(operation)));
|
|
2590
|
+
}
|
|
2591
|
+
|
|
2592
|
+
let reservation: SettlementReservationSnapshot | undefined;
|
|
2593
|
+
const reservationRow = yield* readReservation(operation, validated.submissionId);
|
|
2594
|
+
if (Option.isSome(reservationRow)) {
|
|
2595
|
+
const record = yield* decodeRecordEnvelopeText(reservationRow.value.record_json).pipe(
|
|
2596
|
+
Effect.mapError((error) =>
|
|
2597
|
+
corruptionFailure(
|
|
2598
|
+
operation,
|
|
2599
|
+
"effect_agent_settlement_reservations",
|
|
2600
|
+
validated.submissionId,
|
|
2601
|
+
error.message,
|
|
2602
|
+
),
|
|
2603
|
+
),
|
|
2604
|
+
);
|
|
2605
|
+
const settlementId = yield* Schema.decodeUnknownEffect(
|
|
2606
|
+
SettlementReservationSnapshot.fields.settlementId,
|
|
2607
|
+
)(reservationRow.value.settlement_id).pipe(Effect.mapError(internalFailure(operation)));
|
|
2608
|
+
reservation = SettlementReservationSnapshot.make({
|
|
2609
|
+
settlementId,
|
|
2610
|
+
outcome: reservationRow.value.outcome,
|
|
2611
|
+
record,
|
|
2612
|
+
recordDigest: reservationRow.value.record_digest,
|
|
2613
|
+
finalized: reservationRow.value.finalized_at !== null,
|
|
2614
|
+
});
|
|
2615
|
+
}
|
|
2616
|
+
|
|
2617
|
+
let abortIntent: AbortIntent | undefined;
|
|
2618
|
+
const abortRow = yield* readAbortIntent(operation, validated.submissionId);
|
|
2619
|
+
if (Option.isSome(abortRow)) {
|
|
2620
|
+
abortIntent = yield* abortIntentFromRow(
|
|
2621
|
+
operation,
|
|
2622
|
+
submissionRow,
|
|
2623
|
+
validated.submissionId,
|
|
2624
|
+
abortRow.value,
|
|
2625
|
+
);
|
|
2626
|
+
}
|
|
2627
|
+
|
|
2628
|
+
// Host-side view: every Submission whose host linkage points here, in queue order
|
|
2629
|
+
// (the terminalize loop settles them with the host outcome, DUR-002).
|
|
2630
|
+
const joinRows = yield* sql<Record<string, unknown>>`
|
|
2631
|
+
SELECT ${sql.literal(SUBMISSION_COLUMNS)}
|
|
2632
|
+
FROM effect_agent_submissions
|
|
2633
|
+
WHERE joined_host_submission_id = ${validated.submissionId}
|
|
2634
|
+
ORDER BY queue_sequence ASC
|
|
2635
|
+
`.pipe(Effect.mapError(sqlFailure(operation)));
|
|
2636
|
+
const joinSubmissions = yield* decodeSubmissionRows(
|
|
2637
|
+
operation,
|
|
2638
|
+
validated.submissionId,
|
|
2639
|
+
joinRows,
|
|
2640
|
+
);
|
|
2641
|
+
const joins = yield* Effect.forEach(joinSubmissions, (row) =>
|
|
2642
|
+
decodeJoinSnapshot({
|
|
2643
|
+
submissionId: row.submission_id,
|
|
2644
|
+
state: row.state,
|
|
2645
|
+
hostSubmissionId: validated.submissionId,
|
|
2646
|
+
}).pipe(Effect.mapError(internalFailure(operation))),
|
|
2647
|
+
);
|
|
2648
|
+
|
|
2649
|
+
let hostSubmissionId: RecoverySnapshot["hostSubmissionId"];
|
|
2650
|
+
if (submissionRow.joined_host_submission_id !== null) {
|
|
2651
|
+
hostSubmissionId = yield* decodeSubmissionId(
|
|
2652
|
+
submissionRow.joined_host_submission_id,
|
|
2653
|
+
).pipe(Effect.mapError(internalFailure(operation)));
|
|
2654
|
+
}
|
|
2655
|
+
|
|
2656
|
+
let suspension: SuspensionSnapshot | undefined;
|
|
2657
|
+
if (submissionRow.suspended_reason_json !== null && submissionRow.suspended_at !== null) {
|
|
2658
|
+
const reason = yield* parseStoredJsonText(submissionRow.suspended_reason_json).pipe(
|
|
2659
|
+
Effect.mapError((error) =>
|
|
2660
|
+
corruptionFailure(
|
|
2661
|
+
operation,
|
|
2662
|
+
"effect_agent_submissions",
|
|
2663
|
+
validated.submissionId,
|
|
2664
|
+
error.message,
|
|
2665
|
+
),
|
|
2666
|
+
),
|
|
2667
|
+
);
|
|
2668
|
+
suspension = yield* decodeSuspensionSnapshot({
|
|
2669
|
+
reason,
|
|
2670
|
+
suspendedAt: submissionRow.suspended_at,
|
|
2671
|
+
}).pipe(
|
|
2672
|
+
Effect.mapError((error) =>
|
|
2673
|
+
corruptionFailure(
|
|
2674
|
+
operation,
|
|
2675
|
+
"effect_agent_submissions",
|
|
2676
|
+
validated.submissionId,
|
|
2677
|
+
error.message,
|
|
2678
|
+
),
|
|
2679
|
+
),
|
|
2680
|
+
);
|
|
2681
|
+
}
|
|
2682
|
+
|
|
2683
|
+
const decisionRows = yield* readApprovalDecisions(operation, validated.submissionId);
|
|
2684
|
+
const approvalDecisions = yield* Effect.forEach(decisionRows, (row) =>
|
|
2685
|
+
approvalIntentFromRow(operation, row),
|
|
2686
|
+
);
|
|
2687
|
+
|
|
2688
|
+
const resolutionRows = yield* readUnknownResolutions(operation, validated.submissionId);
|
|
2689
|
+
const unknownResolutions = yield* Effect.forEach(resolutionRows, (row) =>
|
|
2690
|
+
unknownResolutionIntentFromRow(operation, row),
|
|
2691
|
+
);
|
|
2692
|
+
|
|
2693
|
+
// Parent-side subagent view: this Submission's child budget reservations in parent
|
|
2694
|
+
// Tool Call order, plus each attached child's current lane state (a disposable
|
|
2695
|
+
// derived view; canonical records stay the recovery truth, DUR-015).
|
|
2696
|
+
const childReservationRows = yield* sql<Record<string, unknown>>`
|
|
2697
|
+
SELECT ${sql.literal(CHILD_RESERVATION_COLUMNS)}
|
|
2698
|
+
FROM effect_agent_child_reservations
|
|
2699
|
+
WHERE parent_submission_id = ${validated.submissionId}
|
|
2700
|
+
ORDER BY parent_tool_call_id ASC
|
|
2701
|
+
`.pipe(Effect.mapError(sqlFailure(operation)));
|
|
2702
|
+
const decodedChildReservations = yield* decodeChildReservationRows(
|
|
2703
|
+
operation,
|
|
2704
|
+
validated.submissionId,
|
|
2705
|
+
childReservationRows,
|
|
2706
|
+
);
|
|
2707
|
+
const childReservations = yield* Effect.forEach(decodedChildReservations, (row) =>
|
|
2708
|
+
childReservationSnapshotFromRow(operation, row),
|
|
2709
|
+
);
|
|
2710
|
+
const childAttachments: Array<ChildAttachmentSnapshot> = [];
|
|
2711
|
+
for (const row of decodedChildReservations) {
|
|
2712
|
+
if (row.child_submission_id === null) continue;
|
|
2713
|
+
const child = yield* readSubmission(operation, row.child_submission_id);
|
|
2714
|
+
if (Option.isNone(child)) continue;
|
|
2715
|
+
childAttachments.push(
|
|
2716
|
+
yield* decodeChildAttachmentSnapshot({
|
|
2717
|
+
toolCallId: row.parent_tool_call_id,
|
|
2718
|
+
childSubmissionId: row.child_submission_id,
|
|
2719
|
+
childState: child.value.state,
|
|
2720
|
+
...(child.value.settled_outcome === null
|
|
2721
|
+
? {}
|
|
2722
|
+
: { childOutcome: child.value.settled_outcome }),
|
|
2723
|
+
}).pipe(Effect.mapError(internalFailure(operation))),
|
|
2724
|
+
);
|
|
2725
|
+
}
|
|
2726
|
+
|
|
2727
|
+
let parentLinkage: ParentLinkage | undefined;
|
|
2728
|
+
if (
|
|
2729
|
+
submissionRow.parent_submission_id !== null &&
|
|
2730
|
+
submissionRow.parent_tool_call_id !== null
|
|
2731
|
+
) {
|
|
2732
|
+
parentLinkage = yield* decodeParentLinkage({
|
|
2733
|
+
parentSubmissionId: submissionRow.parent_submission_id,
|
|
2734
|
+
parentToolCallId: submissionRow.parent_tool_call_id,
|
|
2735
|
+
}).pipe(Effect.mapError(internalFailure(operation)));
|
|
2736
|
+
}
|
|
2737
|
+
|
|
2738
|
+
return RecoverySnapshot.make({
|
|
2739
|
+
submission,
|
|
2740
|
+
joins,
|
|
2741
|
+
approvalDecisions,
|
|
2742
|
+
unknownResolutions,
|
|
2743
|
+
childReservations,
|
|
2744
|
+
childAttachments,
|
|
2745
|
+
...(parentLinkage === undefined ? {} : { parentLinkage }),
|
|
2746
|
+
...(hostSubmissionId === undefined ? {} : { hostSubmissionId }),
|
|
2747
|
+
...(suspension === undefined ? {} : { suspension }),
|
|
2748
|
+
...(ownership === undefined ? {} : { ownership }),
|
|
2749
|
+
...(inputApplied === undefined ? {} : { inputApplied }),
|
|
2750
|
+
...(reservation === undefined ? {} : { reservation }),
|
|
2751
|
+
...(abortIntent === undefined ? {} : { abortIntent }),
|
|
2752
|
+
});
|
|
2753
|
+
}),
|
|
2754
|
+
)
|
|
2755
|
+
.pipe(Effect.catchTag("SqlError", (error) => Effect.fail(sqlFailure(operation)(error))));
|
|
2756
|
+
});
|
|
2757
|
+
|
|
2758
|
+
return Context.make(
|
|
2759
|
+
SubmissionLedger,
|
|
2760
|
+
SubmissionLedger.of({
|
|
2761
|
+
capabilities,
|
|
2762
|
+
admit,
|
|
2763
|
+
markReady,
|
|
2764
|
+
lookup,
|
|
2765
|
+
resolveAdmission,
|
|
2766
|
+
claim,
|
|
2767
|
+
renewOwnership,
|
|
2768
|
+
releaseOwnership,
|
|
2769
|
+
markInputApplied,
|
|
2770
|
+
reserveSettlement,
|
|
2771
|
+
finalizeSettlement,
|
|
2772
|
+
requestAbort,
|
|
2773
|
+
claimJoining,
|
|
2774
|
+
markJoined,
|
|
2775
|
+
revertJoining,
|
|
2776
|
+
suspend,
|
|
2777
|
+
recordApprovalDecision,
|
|
2778
|
+
markUnknown,
|
|
2779
|
+
recordUnknownResolution,
|
|
2780
|
+
recordChildSettled,
|
|
2781
|
+
reserveChildBudget,
|
|
2782
|
+
attachChildToReservation,
|
|
2783
|
+
beginChildBudgetRelease,
|
|
2784
|
+
releaseChildBudget,
|
|
2785
|
+
scanNonterminal,
|
|
2786
|
+
loadRecoverySnapshot,
|
|
2787
|
+
}),
|
|
2788
|
+
);
|
|
2789
|
+
});
|
|
2790
|
+
|
|
2791
|
+
/**
|
|
2792
|
+
* SQLite SubmissionLedger implementation sharing the journal's database file, write
|
|
2793
|
+
* transaction discipline, and producer-epoch fencing substrate. Configuration, failpoint,
|
|
2794
|
+
* SQL, and Crypto authority stay visible in the input channel.
|
|
2795
|
+
*/
|
|
2796
|
+
export const submissionLedgerLayer: Layer.Layer<
|
|
2797
|
+
SubmissionLedger,
|
|
2798
|
+
SqliteStorageInitializationError,
|
|
2799
|
+
SqliteStorageConfig | SqliteStorageFailpoint | SqlClientService.SqlClient | Crypto.Crypto
|
|
2800
|
+
> = Layer.effectContext(makeServices());
|
|
2801
|
+
|
|
2802
|
+
/**
|
|
2803
|
+
* A composition-root convenience Layer for the durable Submission Ledger. Point it at the
|
|
2804
|
+
* same database file as the ConversationStore so claims fence the same producer epochs.
|
|
2805
|
+
*/
|
|
2806
|
+
export const ledgerLayer = (
|
|
2807
|
+
options: SqliteStorageOptions,
|
|
2808
|
+
): Layer.Layer<SubmissionLedger, SqliteStorageInitializationError> =>
|
|
2809
|
+
submissionLedgerLayer.pipe(
|
|
2810
|
+
Layer.provide(
|
|
2811
|
+
Layer.mergeAll(
|
|
2812
|
+
storageConfigLayer(options),
|
|
2813
|
+
storageFailpointLayer(options),
|
|
2814
|
+
SqliteClient.layer({ filename: options.filename }),
|
|
2815
|
+
NodeCrypto.layer,
|
|
2816
|
+
),
|
|
2817
|
+
),
|
|
2818
|
+
);
|