@systemfsoftware/agent-storage-cloudflare 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/dist/DoMemoryStore-AaGtt8CZ.d.mts +29 -0
- package/dist/DoMemoryStore-DVun329p.mjs +67 -0
- package/dist/DoMemoryStore-DVun329p.mjs.map +1 -0
- package/dist/DoMemoryStore.d.mts +2 -0
- package/dist/DoMemoryStore.mjs +1 -0
- package/dist/DoMessageDeliveryStore-BvB6OPI1.mjs +34 -0
- package/dist/DoMessageDeliveryStore-BvB6OPI1.mjs.map +1 -0
- package/dist/DoMessageDeliveryStore-Cb-DNN5s.d.mts +16 -0
- package/dist/DoMessageDeliveryStore.d.mts +2 -0
- package/dist/DoMessageDeliveryStore.mjs +1 -0
- package/dist/DoScheduleStore-BiTgDvX1.d.mts +36 -0
- package/dist/DoScheduleStore-C7GkSReF.mjs +167 -0
- package/dist/DoScheduleStore-C7GkSReF.mjs.map +1 -0
- package/dist/DoScheduleStore.d.mts +2 -0
- package/dist/DoScheduleStore.mjs +1 -0
- package/dist/DoStorageConfig-BqezsbD6.mjs +43 -0
- package/dist/DoStorageConfig-BqezsbD6.mjs.map +1 -0
- package/dist/DoStorageConfig-CuB6ZOtX.d.mts +36 -0
- package/dist/DoStorageConfig.d.mts +2 -0
- package/dist/DoStorageConfig.mjs +1 -0
- package/dist/DoStorageError-C-F5Z_FZ.d.mts +82 -0
- package/dist/DoStorageError-DSQzuCb0.mjs +138 -0
- package/dist/DoStorageError-DSQzuCb0.mjs.map +1 -0
- package/dist/DoStorageError.d.mts +2 -0
- package/dist/DoStorageError.mjs +1 -0
- package/dist/DoStorageFailpoint-C7zLUULu.d.mts +19 -0
- package/dist/DoStorageFailpoint-WO3B_DQl.mjs +20 -0
- package/dist/DoStorageFailpoint-WO3B_DQl.mjs.map +1 -0
- package/dist/DoStorageFailpoint.d.mts +2 -0
- package/dist/DoStorageFailpoint.mjs +1 -0
- package/dist/DoStorageFailpointTesting.d.mts +21 -0
- package/dist/DoStorageFailpointTesting.mjs +18 -0
- package/dist/DoStorageFailpointTesting.mjs.map +1 -0
- package/dist/DoStorageVersion-BrolfBDS.mjs +7 -0
- package/dist/DoStorageVersion-BrolfBDS.mjs.map +1 -0
- package/dist/DoStorageVersion-D7CIxFc_.d.mts +8 -0
- package/dist/DoStorageVersion.d.mts +3 -0
- package/dist/DoStorageVersion.mjs +2 -0
- package/dist/DoSubmissionLedger-Oq5OstxL.mjs +1878 -0
- package/dist/DoSubmissionLedger-Oq5OstxL.mjs.map +1 -0
- package/dist/DoSubmissionLedger-tLjwidUn.d.mts +25 -0
- package/dist/DoSubmissionLedger.d.mts +2 -0
- package/dist/DoSubmissionLedger.mjs +1 -0
- package/dist/DoSubscriptionStore-BMJiFxt3.mjs +185 -0
- package/dist/DoSubscriptionStore-BMJiFxt3.mjs.map +1 -0
- package/dist/DoSubscriptionStore-zx6nfbbh.d.mts +25 -0
- package/dist/DoSubscriptionStore.d.mts +2 -0
- package/dist/DoSubscriptionStore.mjs +1 -0
- package/dist/DoThreadStore-2zTSfui-.d.mts +81 -0
- package/dist/DoThreadStore-CeYHcRR9.mjs +411 -0
- package/dist/DoThreadStore-CeYHcRR9.mjs.map +1 -0
- package/dist/DoThreadStore.d.mts +2 -0
- package/dist/DoThreadStore.mjs +5 -0
- package/dist/MemoryProtocol-CtCFYe4s.mjs +221 -0
- package/dist/MemoryProtocol-CtCFYe4s.mjs.map +1 -0
- package/dist/MemoryProtocol-DXV77CcJ.d.mts +38160 -0
- package/dist/MemoryProtocol.d.mts +2 -0
- package/dist/MemoryProtocol.mjs +1 -0
- package/dist/PortProtocol-4xvMyCgP.mjs +322 -0
- package/dist/PortProtocol-4xvMyCgP.mjs.map +1 -0
- package/dist/PortProtocol-DXuguAgD.d.mts +966 -0
- package/dist/PortProtocol.d.mts +2 -0
- package/dist/PortProtocol.mjs +1 -0
- package/dist/PortRouting-B9302ouX.mjs +683 -0
- package/dist/PortRouting-B9302ouX.mjs.map +1 -0
- package/dist/PortRouting-DsoI6soW.d.mts +105 -0
- package/dist/PortRouting.d.mts +2 -0
- package/dist/PortRouting.mjs +1 -0
- package/dist/do-journal-nPNEAjV5.mjs +769 -0
- package/dist/do-journal-nPNEAjV5.mjs.map +1 -0
- package/dist/index.d.mts +14 -0
- package/dist/index.mjs +14 -0
- package/dist/migrations-BRTvj8Ue.mjs +233 -0
- package/dist/migrations-BRTvj8Ue.mjs.map +1 -0
- package/dist/owned-state-DrOD9s0c.mjs +157 -0
- package/dist/owned-state-DrOD9s0c.mjs.map +1 -0
- package/dist/rolldown-runtime-D3KUYPsf.mjs +12 -0
- package/package.json +106 -3
- package/src/DoMemoryStore.ts +71 -0
- package/src/DoMessageDeliveryStore.ts +46 -0
- package/src/DoScheduleStore.ts +276 -0
- package/src/DoStorageConfig.ts +45 -0
- package/src/DoStorageError.ts +146 -0
- package/src/DoStorageFailpoint.ts +25 -0
- package/src/DoStorageFailpointTesting.ts +42 -0
- package/src/DoStorageVersion.ts +2 -0
- package/src/DoSubmissionLedger.ts +3980 -0
- package/src/DoSubscriptionStore.ts +331 -0
- package/src/DoThreadStore.ts +602 -0
- package/src/MemoryProtocol.ts +357 -0
- package/src/PortProtocol.ts +626 -0
- package/src/PortRouting.ts +1888 -0
- package/src/index.ts +13 -0
- package/src/internal/canonical-append.ts +15 -0
- package/src/internal/do-journal.ts +1449 -0
- package/src/internal/migrations.ts +395 -0
- package/src/internal/owned-state.ts +300 -0
- package/src/internal/prompt-checkpoint.ts +170 -0
- package/src/internal/storage-span.ts +54 -0
- package/README.md +0 -3
|
@@ -0,0 +1,1878 @@
|
|
|
1
|
+
import { t as __exportAll } from "./rolldown-runtime-D3KUYPsf.mjs";
|
|
2
|
+
import * as BrowserCrypto from "@effect/platform-browser/BrowserCrypto";
|
|
3
|
+
import * as SqliteClient from "@effect/sql-sqlite-do/SqliteClient";
|
|
4
|
+
import { decodeAbortFact, decodeAdmissionFact, decodeApprovalFact, decodeResolutionFact } from "@systemfsoftware/agent-storage-sql/sql-admission-facts";
|
|
5
|
+
import { definitionJson, makeCanonicalStorage, recordBatchId, runKey } from "@systemfsoftware/agent-storage-sql/sql-canonical-storage";
|
|
6
|
+
import { SqlStorageProgress } from "@systemfsoftware/agent-storage-sql/sql-storage-progress";
|
|
7
|
+
import { BoundedIdentifier, BoundedTimestamp, makeSubmissionRowFields } from "@systemfsoftware/agent-storage-sql/sql-submission-rows";
|
|
8
|
+
import { canonicalRecordJson } from "@systemfsoftware/agent-storage-sql/sql-thread-archive-range";
|
|
9
|
+
import { InputMessage } from "@systemfsoftware/agent/messaging";
|
|
10
|
+
import { CanonicalSequence, DefinitionDigests, PersistedJson, RecordEnvelope, SettlementOutcome, WorkerAdmission } from "@systemfsoftware/agent/records";
|
|
11
|
+
import { runIdForSubmission } from "@systemfsoftware/agent/run-journal";
|
|
12
|
+
import { StorageOwner } from "@systemfsoftware/agent/run-storage";
|
|
13
|
+
import { SettlementPublicationResult, SettlementPublisher, validateCanonicalSettlement, validateJoinedSettlement, validatePublication } from "@systemfsoftware/agent/settlement-publisher";
|
|
14
|
+
import { AbortCommand, AbortIntent, AbortIntentRequest, AdmissionAdmitted, AdmissionConflict, AdmissionFence, AdmissionNotAdmitted, AdmissionPolicyError, AdmissionRequest, AdmissionResult, ApprovalConflict, ApprovalDecisionCommand, ApprovalDecisionIntent, AttachChildToReservationRequest, BeginChildBudgetReleaseRequest, ChildAttachmentSnapshot, ChildBudgetReservationRequest, ChildBudgetReservationSnapshot, ChildReservationConflict, ChildSettledNotification, Claim, ClaimJoiningRequest, ClaimRequest, FundingOwner, FundingOwnerRequest, InputAppliedMarker, JoinSnapshot, JoinedToHost, JoiningClaim, LedgerCapabilities, LedgerError, MarkInputAppliedRequest, MarkJoinedRequest, MarkReadyRequest, MarkUnknownRequest, OwnershipLost, ParentLinkage, QueueSequence, RecoverySnapshot, RecoverySnapshotRequest, ReleaseChildBudgetRequest, ReservedChildBudget, RevertJoiningRequest, Settlement, SettlementConflict, SettlementFinalization, SubmissionAdmissionFence, SubmissionLedger, SubmissionLookup, SubmissionLookupByKey, SubmissionSnapshot, SubmissionWorkItem, SuspendRequest, SuspensionReason, SuspensionSnapshot, UnknownResolution, UnknownResolutionCommand, UnknownResolutionConflict, UnknownResolutionIntent, WorkerLedgerState, WorkerStopCommand, approvalDecisionsCover, settlementFailureFromRecord, submissionAbortRecordId, submissionInputBatchId, submissionInputRecordId, submissionSettlementBatchId, submissionSettlementRecordId, unknownResolutionKind, unknownResolutionMatchesResult, workerTerminalFromRecord } from "@systemfsoftware/agent/submission-ledger";
|
|
15
|
+
import { AppendConflict, ThreadNotMaterialized, ThreadStoreDiagnostic, ThreadStoreError, makeTransferFactCheck } from "@systemfsoftware/agent/thread-store";
|
|
16
|
+
import { AssignmentTerminal } from "@systemfsoftware/agent/worker";
|
|
17
|
+
import * as Cause from "effect/Cause";
|
|
18
|
+
import * as Clock from "effect/Clock";
|
|
19
|
+
import * as Context from "effect/Context";
|
|
20
|
+
import * as CryptoDigest from "effect/crypto/Digest";
|
|
21
|
+
import * as SecureRandom from "effect/crypto/SecureRandom";
|
|
22
|
+
import * as DateTime from "effect/DateTime";
|
|
23
|
+
import * as Effect from "effect/Effect";
|
|
24
|
+
import * as Layer from "effect/Layer";
|
|
25
|
+
import * as Option from "effect/Option";
|
|
26
|
+
import * as Schema from "effect/Schema";
|
|
27
|
+
import * as SqlClientService from "effect/sql/SqlClient";
|
|
28
|
+
import * as Stream from "effect/Stream";
|
|
29
|
+
import { n as DoStorageConfig } from "./DoStorageConfig-BqezsbD6.mjs";
|
|
30
|
+
import { a as DoStorageError, i as DoStorageCorruptionError, n as DoLedgerError } from "./DoStorageError-DSQzuCb0.mjs";
|
|
31
|
+
import { t as DoStorageFailpoint } from "./DoStorageFailpoint-WO3B_DQl.mjs";
|
|
32
|
+
import { l as prepareCanonicalAppend, o as storageConfigLayer, s as storageFailpointLayer } from "./DoThreadStore-CeYHcRR9.mjs";
|
|
33
|
+
import { n as decodeRows, r as initializeDoJournal } from "./do-journal-nPNEAjV5.mjs";
|
|
34
|
+
import { n as ownedRows } from "./owned-state-DrOD9s0c.mjs";
|
|
35
|
+
// src/DoSubmissionLedger.ts
|
|
36
|
+
var DoSubmissionLedger_exports = /* @__PURE__ */ __exportAll({
|
|
37
|
+
ledgerLayer: () => ledgerLayer,
|
|
38
|
+
submissionLedgerLayer: () => submissionLedgerLayer
|
|
39
|
+
});
|
|
40
|
+
/**
|
|
41
|
+
* Static decode-side ceiling; writes are bounded in bytes by the configured
|
|
42
|
+
* `maxStoredValueBytes` (see do-journal.ts).
|
|
43
|
+
*/
|
|
44
|
+
const BoundedStoredText = Schema.String.check(Schema.isMaxLength(2e6));
|
|
45
|
+
const rowFields = makeSubmissionRowFields({
|
|
46
|
+
storedText: BoundedStoredText,
|
|
47
|
+
queueSequence: QueueSequence,
|
|
48
|
+
canonicalSequence: CanonicalSequence
|
|
49
|
+
});
|
|
50
|
+
const SCAN_PAGE_SIZE = 256;
|
|
51
|
+
const admissionFitsTransfer = makeTransferFactCheck(AdmissionRequest);
|
|
52
|
+
const RESUME_IMMEDIATELY = "resume-immediately";
|
|
53
|
+
const SUSPENDED = "suspended";
|
|
54
|
+
const NOT_WAITING = "not-waiting";
|
|
55
|
+
const STILL_WAITING = "still-waiting";
|
|
56
|
+
const WOKEN = "woken";
|
|
57
|
+
const MAX_IDENTIFIER_LENGTH = 1024;
|
|
58
|
+
var SubmissionRow = class extends Schema.Class("SubmissionRow")(rowFields.submission) {};
|
|
59
|
+
const SubmissionWorkRow = Schema.Struct({
|
|
60
|
+
submission_id: SubmissionRow.fields.submission_id,
|
|
61
|
+
thread_id: SubmissionRow.fields.thread_id,
|
|
62
|
+
queue_sequence: SubmissionRow.fields.queue_sequence,
|
|
63
|
+
principal: SubmissionRow.fields.principal,
|
|
64
|
+
idempotency_key: SubmissionRow.fields.idempotency_key,
|
|
65
|
+
deployment_id: SubmissionRow.fields.deployment_id,
|
|
66
|
+
receipt_id: SubmissionRow.fields.receipt_id,
|
|
67
|
+
state: SubmissionRow.fields.state
|
|
68
|
+
});
|
|
69
|
+
var ChildReservationRow = class extends Schema.Class("ChildReservationRow")(rowFields.childReservation) {};
|
|
70
|
+
var ChildSettlementMarkerRow = class extends Schema.Class("ChildSettlementMarkerRow")({
|
|
71
|
+
parent_submission_id: BoundedIdentifier,
|
|
72
|
+
child_submission_id: BoundedIdentifier,
|
|
73
|
+
child_outcome: Schema.NullOr(SettlementOutcome),
|
|
74
|
+
recorded_at: BoundedTimestamp
|
|
75
|
+
}) {};
|
|
76
|
+
var ApprovalDecisionRow = class extends Schema.Class("ApprovalDecisionRow")(rowFields.approvalDecision) {};
|
|
77
|
+
var UnknownResolutionRow = class extends Schema.Class("UnknownResolutionRow")(rowFields.unknownResolution) {};
|
|
78
|
+
var AbortIntentRow = class extends Schema.Class("AbortIntentRow")(rowFields.abortIntent) {};
|
|
79
|
+
var WorkerStopRow = class extends Schema.Class("WorkerStopRow")({
|
|
80
|
+
thread_id: BoundedIdentifier,
|
|
81
|
+
terminal: Schema.NullOr(AssignmentTerminal)
|
|
82
|
+
}) {};
|
|
83
|
+
var MaxQueueSequenceRow = class extends Schema.Class("MaxQueueSequenceRow")({ max_queue_sequence: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)) }) {};
|
|
84
|
+
const SUBMISSION_COLUMNS = `
|
|
85
|
+
submission_id,
|
|
86
|
+
thread_id,
|
|
87
|
+
queue_sequence,
|
|
88
|
+
principal,
|
|
89
|
+
idempotency_key,
|
|
90
|
+
agent_id,
|
|
91
|
+
deployment_id,
|
|
92
|
+
input_json,
|
|
93
|
+
input_digest,
|
|
94
|
+
receipt_id,
|
|
95
|
+
state,
|
|
96
|
+
settled_outcome,
|
|
97
|
+
settled_record_id,
|
|
98
|
+
finalized_at,
|
|
99
|
+
created_at,
|
|
100
|
+
ready_at,
|
|
101
|
+
input_applied_record_id,
|
|
102
|
+
input_applied_sequence,
|
|
103
|
+
joined_host_submission_id,
|
|
104
|
+
suspended_reason_json,
|
|
105
|
+
suspended_at,
|
|
106
|
+
unknown_reason,
|
|
107
|
+
unknown_tool_call_ids_json,
|
|
108
|
+
parent_submission_id,
|
|
109
|
+
parent_tool_call_id,
|
|
110
|
+
admission_group,
|
|
111
|
+
admission_fence_json,
|
|
112
|
+
worker_admission_json,
|
|
113
|
+
message_admission_json
|
|
114
|
+
`;
|
|
115
|
+
const CHILD_RESERVATION_COLUMNS = `
|
|
116
|
+
reservation_id,
|
|
117
|
+
parent_submission_id,
|
|
118
|
+
parent_tool_call_id,
|
|
119
|
+
child_submission_id,
|
|
120
|
+
status,
|
|
121
|
+
allocation_json,
|
|
122
|
+
allocation_digest,
|
|
123
|
+
accounting_json,
|
|
124
|
+
reserved_at,
|
|
125
|
+
release_began_at,
|
|
126
|
+
released_at
|
|
127
|
+
`;
|
|
128
|
+
/** The branded ToolCallId schema, reached through the thread port so no core import is needed. */
|
|
129
|
+
const ToolCallIdSchema = ApprovalDecisionCommand.fields.toolCallId;
|
|
130
|
+
const ToolCallIdList = Schema.Array(ToolCallIdSchema);
|
|
131
|
+
const encodePersistedJsonText = Schema.encodeEffect(Schema.fromJsonString(PersistedJson));
|
|
132
|
+
const encodeDefinitionDigestsText = Schema.encodeEffect(Schema.fromJsonString(DefinitionDigests));
|
|
133
|
+
const decodeRecordEnvelopeText = Schema.decodeEffect(Schema.fromJsonString(RecordEnvelope));
|
|
134
|
+
const encodeSuspensionReasonText = Schema.encodeEffect(Schema.fromJsonString(SuspensionReason));
|
|
135
|
+
const encodeUnknownResolutionText = Schema.encodeEffect(Schema.fromJsonString(UnknownResolution));
|
|
136
|
+
const encodeToolCallIdsText = Schema.encodeEffect(Schema.fromJsonString(ToolCallIdList));
|
|
137
|
+
const decodeToolCallIdsText = Schema.decodeEffect(Schema.fromJsonString(ToolCallIdList));
|
|
138
|
+
const parseStoredJsonText = Schema.decodeEffect(Schema.fromJsonString(Schema.Json));
|
|
139
|
+
const decodeAdmissionResult = Schema.decodeUnknownEffect(AdmissionResult);
|
|
140
|
+
const decodeClaim = Schema.decodeUnknownEffect(Claim);
|
|
141
|
+
const decodeSettlement = Schema.decodeUnknownEffect(Settlement);
|
|
142
|
+
const decodeAbortIntent = Schema.decodeUnknownEffect(AbortIntent);
|
|
143
|
+
const decodeInputAppliedMarker = Schema.decodeUnknownEffect(InputAppliedMarker);
|
|
144
|
+
const decodeSubmissionSnapshotType = (input) => SubmissionSnapshot.makeEffect(input).pipe(Effect.mapError((issue) => new Schema.SchemaError(issue)));
|
|
145
|
+
const decodeSubmissionId = Schema.decodeUnknownEffect(SubmissionSnapshot.fields.submissionId);
|
|
146
|
+
const decodeQueueSequence = Schema.decodeUnknownEffect(QueueSequence);
|
|
147
|
+
const decodeUtcInstant = Schema.decodeUnknownEffect(Schema.DateTimeUtcFromString);
|
|
148
|
+
const decodeJoiningClaim = Schema.decodeUnknownEffect(JoiningClaim);
|
|
149
|
+
const decodeJoinSnapshot = Schema.decodeUnknownEffect(JoinSnapshot);
|
|
150
|
+
const decodeSuspensionSnapshot = Schema.decodeUnknownEffect(SuspensionSnapshot);
|
|
151
|
+
const decodeApprovalDecisionIntent = Schema.decodeUnknownEffect(ApprovalDecisionIntent);
|
|
152
|
+
const decodeUnknownResolutionIntent = Schema.decodeUnknownEffect(UnknownResolutionIntent);
|
|
153
|
+
const decodeParentLinkage = Schema.decodeUnknownEffect(ParentLinkage);
|
|
154
|
+
const decodeChildReservationSnapshotUnknown = Schema.decodeUnknownEffect(ChildBudgetReservationSnapshot);
|
|
155
|
+
const decodeChildAttachmentSnapshot = Schema.decodeUnknownEffect(ChildAttachmentSnapshot);
|
|
156
|
+
const equivalentPersistedJson = Schema.toEquivalence(PersistedJson);
|
|
157
|
+
const equivalentUnknownResolution = Schema.toEquivalence(UnknownResolution);
|
|
158
|
+
const decodeAdmissionRequestType = Schema.decodeEffect(Schema.toType(AdmissionRequest));
|
|
159
|
+
const decodeSubmissionLookupType = Schema.decodeEffect(Schema.toType(SubmissionLookup));
|
|
160
|
+
const decodeClaimRequestType = Schema.decodeEffect(Schema.toType(ClaimRequest));
|
|
161
|
+
const decodeMarkInputAppliedRequestType = Schema.decodeEffect(Schema.toType(MarkInputAppliedRequest));
|
|
162
|
+
const decodeSettlementFinalizationType = Schema.decodeEffect(Schema.toType(SettlementFinalization));
|
|
163
|
+
const decodeClaimJoiningRequestType = Schema.decodeEffect(Schema.toType(ClaimJoiningRequest));
|
|
164
|
+
const decodeAbortIntentRequestType = Schema.decodeEffect(Schema.toType(AbortIntentRequest));
|
|
165
|
+
const decodeRecoverySnapshotRequestType = Schema.decodeEffect(Schema.toType(RecoverySnapshotRequest));
|
|
166
|
+
const SubmissionRows = Schema.Array(SubmissionRow);
|
|
167
|
+
const ChildReservationRows = Schema.Array(ChildReservationRow);
|
|
168
|
+
const MaxQueueSequenceRows = Schema.Array(MaxQueueSequenceRow);
|
|
169
|
+
const SubmissionWorkItems = Schema.Array(SubmissionWorkItem);
|
|
170
|
+
const decodeSubmissionWorkItems = Schema.decodeEffect(SubmissionWorkItems);
|
|
171
|
+
const equivalentWorkerOrigin = Schema.toEquivalence(Schema.optional(WorkerAdmission.fields.origin));
|
|
172
|
+
const decodeFirstWorkerAdmissions = Schema.decodeUnknownEffect(Schema.Array(Schema.Struct({ worker_admission_json: Schema.NullOr(BoundedStoredText) })));
|
|
173
|
+
const CanonicalSettlementRows = Schema.Array(Schema.Struct({
|
|
174
|
+
batch_id: Schema.fromJsonString(BoundedIdentifier),
|
|
175
|
+
record_id: Schema.fromJsonString(BoundedIdentifier),
|
|
176
|
+
record_json: BoundedStoredText
|
|
177
|
+
}));
|
|
178
|
+
const isDoStorageError = Schema.is(DoStorageError);
|
|
179
|
+
/** Wrap an adapter-internal failure into the port's LedgerError without erasing its tag. */
|
|
180
|
+
const internalFailure = (operation) => (error) => LedgerError.make({
|
|
181
|
+
operation,
|
|
182
|
+
message: error.message,
|
|
183
|
+
cause: error
|
|
184
|
+
});
|
|
185
|
+
/**
|
|
186
|
+
* Classify raw SQL failures. Within one Durable Object there is exactly one writer, so the
|
|
187
|
+
* Node adapter's retryable `SqliteWriteContention` classification has no analogue: every raw
|
|
188
|
+
* failure is a `DoLedgerError` preserved as the LedgerError's cause.
|
|
189
|
+
*/
|
|
190
|
+
const sqlFailure = (operation) => (error) => internalFailure(operation)(DoLedgerError.make({
|
|
191
|
+
cause: error,
|
|
192
|
+
operation,
|
|
193
|
+
message: error.message
|
|
194
|
+
}));
|
|
195
|
+
const corruptionFailure = (operation, table, rowKey, message) => internalFailure(operation)(DoStorageCorruptionError.make({
|
|
196
|
+
table,
|
|
197
|
+
rowKey,
|
|
198
|
+
message
|
|
199
|
+
}));
|
|
200
|
+
const submissionsRows = ownedRows(SubmissionRow, "effect_agent_submissions", (row) => row.submission_id, "submission_id", [[
|
|
201
|
+
"thread_id",
|
|
202
|
+
"principal",
|
|
203
|
+
"idempotency_key"
|
|
204
|
+
]], (sql) => sql`*, ${definitionJson(sql)} AS agent_digests_json`);
|
|
205
|
+
const abortsRows = ownedRows(AbortIntentRow, "effect_agent_abort_intents", (row) => row.submission_id, "submission_id");
|
|
206
|
+
const approvalsRows = ownedRows(ApprovalDecisionRow, "effect_agent_approval_decisions", (row) => JSON.stringify([row.submission_id, row.tool_call_id]));
|
|
207
|
+
const resolutionsRows = ownedRows(UnknownResolutionRow, "effect_agent_unknown_resolutions", (row) => JSON.stringify([
|
|
208
|
+
row.submission_id,
|
|
209
|
+
row.tool_call_id,
|
|
210
|
+
row.resolution_kind
|
|
211
|
+
]));
|
|
212
|
+
const childSettlementsRows = ownedRows(ChildSettlementMarkerRow, "effect_agent_child_settlements", (row) => JSON.stringify([row.parent_submission_id, row.child_submission_id]));
|
|
213
|
+
const childReservationsRows = ownedRows(ChildReservationRow, "effect_agent_child_reservations", (row) => row.reservation_id, "reservation_id");
|
|
214
|
+
const workerStopsRows = ownedRows(WorkerStopRow, "effect_agent_worker_stops", (row) => row.thread_id, "thread_id");
|
|
215
|
+
const submissionWorkRows = ownedRows(SubmissionWorkRow, "effect_agent_submissions", (row) => row.submission_id);
|
|
216
|
+
const makeServices = Effect.fnUntraced(function* () {
|
|
217
|
+
const progress = yield* SqlStorageProgress;
|
|
218
|
+
const recordProgress = (kind, operation) => progress.committed(kind).pipe(Effect.catchCause((cause) => Effect.failCause(Cause.map(cause, internalFailure(operation)))));
|
|
219
|
+
const config = yield* DoStorageConfig;
|
|
220
|
+
const failpoint = yield* DoStorageFailpoint;
|
|
221
|
+
const sql = yield* SqlClientService.SqlClient;
|
|
222
|
+
const crypto = yield* CryptoDigest.Digest;
|
|
223
|
+
const random = yield* SecureRandom.SecureRandom;
|
|
224
|
+
const physical = yield* makeCanonicalStorage();
|
|
225
|
+
const submissionColumns = sql`${sql.literal(SUBMISSION_COLUMNS)}, ${definitionJson(sql)} AS agent_digests_json`;
|
|
226
|
+
const admissionFence = yield* SubmissionAdmissionFence;
|
|
227
|
+
const journal = yield* initializeDoJournal(sql, failpoint.hit, config.maxStoredValueBytes);
|
|
228
|
+
const lifecycle = journal.lifecycle;
|
|
229
|
+
const state = journal.state;
|
|
230
|
+
const owner = state.owner;
|
|
231
|
+
const submissionViews = submissionsRows(state, sql);
|
|
232
|
+
const workRows = submissionWorkRows(state, sql);
|
|
233
|
+
const rows = {
|
|
234
|
+
submissions: {
|
|
235
|
+
by: submissionViews.by,
|
|
236
|
+
byFields: submissionViews.byFields,
|
|
237
|
+
seed: submissionViews.seed,
|
|
238
|
+
write: (effect) => submissionViews.write(effect).pipe(Effect.tap((changed) => workRows.write(Effect.succeed(changed))))
|
|
239
|
+
},
|
|
240
|
+
aborts: abortsRows(state, sql),
|
|
241
|
+
approvals: approvalsRows(state, sql),
|
|
242
|
+
resolutions: resolutionsRows(state, sql),
|
|
243
|
+
childSettlements: childSettlementsRows(state, sql),
|
|
244
|
+
childReservations: childReservationsRows(state, sql),
|
|
245
|
+
threads: journal.threads,
|
|
246
|
+
workerStops: workerStopsRows(state, sql)
|
|
247
|
+
};
|
|
248
|
+
const cached = (effect, operation) => effect.pipe(Effect.mapError(internalFailure(operation)));
|
|
249
|
+
const byKey = Effect.fnUntraced(function* (request, operation) {
|
|
250
|
+
return yield* cached(rows.submissions.byFields([
|
|
251
|
+
["thread_id", request.threadId],
|
|
252
|
+
["principal", request.principal],
|
|
253
|
+
["idempotency_key", request.idempotencyKey]
|
|
254
|
+
]), operation);
|
|
255
|
+
}, state.read);
|
|
256
|
+
const retainLifecycle = (submission, fact) => lifecycle === void 0 ? Effect.void : Effect.gen(function* () {
|
|
257
|
+
const ownerThreadId = yield* Schema.decodeEffect(SubmissionSnapshot.fields.threadId)(submission.thread_id).pipe(Effect.mapError(internalFailure("lifecycle owner")));
|
|
258
|
+
yield* lifecycle.retain({
|
|
259
|
+
ownerThreadId,
|
|
260
|
+
createdAt: yield* DateTime.now,
|
|
261
|
+
fact
|
|
262
|
+
}).pipe(Effect.mapError(internalFailure("retain lifecycle publication")));
|
|
263
|
+
});
|
|
264
|
+
const retainWorkerSeal = (threadId, terminal) => lifecycle === void 0 ? Effect.void : Effect.gen(function* () {
|
|
265
|
+
const operation = "retain worker inbox seal";
|
|
266
|
+
const ownerThreadId = yield* Schema.decodeEffect(SubmissionSnapshot.fields.threadId)(threadId).pipe(Effect.mapError(internalFailure(operation)));
|
|
267
|
+
const active = yield* sql`SELECT submission_id FROM effect_agent_submissions WHERE thread_id = ${threadId} AND state <> 'settled' ORDER BY queue_sequence`.pipe(Effect.mapError(sqlFailure(operation)));
|
|
268
|
+
const activeSubmissionIds = yield* Effect.forEach(active, (row) => decodeSubmissionId(row.submission_id).pipe(Effect.mapError(internalFailure(operation))));
|
|
269
|
+
yield* lifecycle.retain({
|
|
270
|
+
id: JSON.stringify([threadId, "inbox-sealed"]),
|
|
271
|
+
ownerThreadId,
|
|
272
|
+
createdAt: yield* DateTime.now,
|
|
273
|
+
fact: {
|
|
274
|
+
_tag: "WorkerInboxSealed",
|
|
275
|
+
threadId: ownerThreadId,
|
|
276
|
+
activeSubmissionIds,
|
|
277
|
+
terminal
|
|
278
|
+
}
|
|
279
|
+
}).pipe(Effect.mapError(internalFailure(operation)));
|
|
280
|
+
});
|
|
281
|
+
const hitFailpoint = (location, operation) => failpoint.hit(location).pipe(Effect.mapError((error) => internalFailure(operation)(error)));
|
|
282
|
+
/**
|
|
283
|
+
* Run one ledger mutation under the journal's Durable Object storage-backed transaction so
|
|
284
|
+
* ownership-token and epoch checks are atomic with their writes (DUR-006). Transaction
|
|
285
|
+
* failures surface as LedgerError carrying the typed `DoStorageError` as cause.
|
|
286
|
+
*/
|
|
287
|
+
const inWriteTransaction = (operation, effect, expected) => journal.withWriteTransaction(operation, expected)(effect).pipe(Effect.mapError((error) => isDoStorageError(error) ? internalFailure(operation)(error) : error));
|
|
288
|
+
const mintUuid = () => random.uuidV7();
|
|
289
|
+
const currentInstant = Effect.map(Clock.currentTimeMillis, (millis) => ({
|
|
290
|
+
millis,
|
|
291
|
+
iso: new Date(millis).toISOString()
|
|
292
|
+
}));
|
|
293
|
+
const decodeSubmissionRows = (operation, rowKey, rows) => decodeRows(SubmissionRows, "effect_agent_submissions", rowKey, rows).pipe(Effect.mapError(internalFailure(operation)));
|
|
294
|
+
const readSubmission = Effect.fnUntraced(function* (operation, submissionId) {
|
|
295
|
+
const found = yield* cached(rows.submissions.by("submission_id", submissionId), operation);
|
|
296
|
+
return Option.fromUndefinedOr(found[0]);
|
|
297
|
+
});
|
|
298
|
+
const requireSubmission = Effect.fnUntraced(function* (operation, submissionId) {
|
|
299
|
+
const submission = yield* readSubmission(operation, submissionId);
|
|
300
|
+
if (Option.isNone(submission)) return yield* LedgerError.make({
|
|
301
|
+
operation,
|
|
302
|
+
message: `Unknown submission ${submissionId}.`
|
|
303
|
+
});
|
|
304
|
+
return submission.value;
|
|
305
|
+
});
|
|
306
|
+
const requireOwner = Effect.fnUntraced(function* (operation, submission) {
|
|
307
|
+
if (owner.hasOwner(submission.thread_id, submission.submission_id)) return;
|
|
308
|
+
const submissionId = yield* decodeSubmissionId(submission.submission_id).pipe(Effect.mapError(internalFailure(operation)));
|
|
309
|
+
return yield* OwnershipLost.make({ submissionId });
|
|
310
|
+
});
|
|
311
|
+
const submissions = /* @__PURE__ */ new WeakMap();
|
|
312
|
+
const decodeSubmissionSnapshot = Effect.fnUntraced(function* (operation, row) {
|
|
313
|
+
const existing = submissions.get(row);
|
|
314
|
+
if (existing !== void 0) return existing;
|
|
315
|
+
const decodeFailure = (error) => internalFailure(operation)(DoStorageCorruptionError.make({
|
|
316
|
+
table: "effect_agent_submissions",
|
|
317
|
+
rowKey: row.submission_id,
|
|
318
|
+
message: "Stored submission does not satisfy the ledger schema",
|
|
319
|
+
diagnostic: ThreadStoreDiagnostic.make({
|
|
320
|
+
causeTag: error._tag,
|
|
321
|
+
operation,
|
|
322
|
+
decoder: "SubmissionSnapshot",
|
|
323
|
+
issueTag: error.issue._tag
|
|
324
|
+
})
|
|
325
|
+
}));
|
|
326
|
+
if (row.parent_submission_id === null !== (row.parent_tool_call_id === null)) return yield* corruptionFailure(operation, "effect_agent_submissions", row.submission_id, "A parent linkage must record both the parent Submission and the parent Tool Call.");
|
|
327
|
+
const admission = yield* decodeAdmissionFact(row).pipe(Effect.mapError(decodeFailure));
|
|
328
|
+
const settledAt = row.finalized_at === null ? void 0 : yield* decodeUtcInstant(row.finalized_at).pipe(Effect.mapError(decodeFailure));
|
|
329
|
+
const readyAt = row.ready_at === null ? void 0 : yield* decodeUtcInstant(row.ready_at).pipe(Effect.mapError(decodeFailure));
|
|
330
|
+
const snapshot = yield* decodeSubmissionSnapshotType({
|
|
331
|
+
...admission,
|
|
332
|
+
state: row.state,
|
|
333
|
+
...row.settled_outcome === null ? {} : { settledOutcome: row.settled_outcome },
|
|
334
|
+
...settledAt === void 0 ? {} : { settledAt },
|
|
335
|
+
...row.settled_record_id === null ? {} : { settledRecordId: row.settled_record_id },
|
|
336
|
+
...readyAt === void 0 ? {} : { readyAt }
|
|
337
|
+
}).pipe(Effect.mapError(decodeFailure));
|
|
338
|
+
submissions.set(row, snapshot);
|
|
339
|
+
return snapshot;
|
|
340
|
+
});
|
|
341
|
+
const readCanonicalSettlement = Effect.fnUntraced(function* (operation, submission) {
|
|
342
|
+
const expected = yield* decodeSubmissionSnapshot(operation, submission);
|
|
343
|
+
const recordId = submissionSettlementRecordId(expected.submissionId);
|
|
344
|
+
const found = yield* sql`SELECT ${recordBatchId(sql)} AS batch_id, record_id, ${canonicalRecordJson(sql)} AS record_json
|
|
345
|
+
FROM effect_agent_canonical_records WHERE thread_id = ${submission.thread_id}
|
|
346
|
+
AND record_id = ${JSON.stringify(recordId)}`.pipe(Effect.mapError(sqlFailure(operation)));
|
|
347
|
+
const decoded = yield* decodeRows(CanonicalSettlementRows, "effect_agent_canonical_records", recordId, found).pipe(Effect.mapError(internalFailure(operation)));
|
|
348
|
+
if (decoded.length === 0) return void 0;
|
|
349
|
+
const row = decoded[0];
|
|
350
|
+
if (decoded.length !== 1 || row.batch_id !== submissionSettlementBatchId(expected.submissionId) || row.record_id !== recordId) return yield* corruptionFailure(operation, "effect_agent_canonical_records", recordId, "Canonical settlement identity is inconsistent.");
|
|
351
|
+
const record = yield* decodeRecordEnvelopeText(row.record_json).pipe(Effect.mapError(internalFailure(operation)));
|
|
352
|
+
return {
|
|
353
|
+
record,
|
|
354
|
+
settlement: yield* validateCanonicalSettlement(record, expected)
|
|
355
|
+
};
|
|
356
|
+
});
|
|
357
|
+
const readAbortIntent = Effect.fnUntraced(function* (operation, submissionId) {
|
|
358
|
+
const found = yield* cached(rows.aborts.by("submission_id", submissionId), operation);
|
|
359
|
+
return Option.fromUndefinedOr(found[0]);
|
|
360
|
+
});
|
|
361
|
+
/**
|
|
362
|
+
* Read the durable cross-store child-settlement markers recorded against one parent
|
|
363
|
+
* Submission (the DC realization of the port's "cross-store adapters record a durable
|
|
364
|
+
* notification marker" contract).
|
|
365
|
+
*/
|
|
366
|
+
const readChildSettlementMarkers = Effect.fnUntraced(function* (operation, parentSubmissionId) {
|
|
367
|
+
return (yield* cached(rows.childSettlements.by("parent_submission_id", parentSubmissionId), operation)).toSorted((a, b) => a.child_submission_id < b.child_submission_id ? -1 : a.child_submission_id > b.child_submission_id ? 1 : 0);
|
|
368
|
+
});
|
|
369
|
+
/**
|
|
370
|
+
* Whether one listed child is provably settled from THIS store: either its own row lives
|
|
371
|
+
* here and is settled (single-store evidence, identical to the Node adapter), or a durable
|
|
372
|
+
* cross-store notification marker was recorded for it (the child's row lives in another
|
|
373
|
+
* Durable Object and its owner reported the settlement through `recordChildSettled`).
|
|
374
|
+
*/
|
|
375
|
+
const childProvablySettled = Effect.fnUntraced(function* (operation, markerChildren, childSubmissionId) {
|
|
376
|
+
if (markerChildren.has(childSubmissionId)) return true;
|
|
377
|
+
const childRow = yield* readSubmission(operation, childSubmissionId);
|
|
378
|
+
return Option.isSome(childRow) && (yield* readCanonicalSettlement(operation, childRow.value)) !== void 0;
|
|
379
|
+
});
|
|
380
|
+
const decodeChildReservationRows = (operation, rowKey, rows) => decodeRows(ChildReservationRows, "effect_agent_child_reservations", rowKey, rows).pipe(Effect.mapError(internalFailure(operation)));
|
|
381
|
+
const readChildReservation = Effect.fnUntraced(function* (operation, reservationId) {
|
|
382
|
+
const rows = yield* sql`
|
|
383
|
+
SELECT ${sql.literal(CHILD_RESERVATION_COLUMNS)}
|
|
384
|
+
FROM effect_agent_child_reservations
|
|
385
|
+
WHERE reservation_id = ${reservationId}
|
|
386
|
+
`.pipe(Effect.mapError(sqlFailure(operation)));
|
|
387
|
+
const decoded = yield* decodeChildReservationRows(operation, reservationId, rows);
|
|
388
|
+
if (decoded.length > 1) return yield* corruptionFailure(operation, "effect_agent_child_reservations", reservationId, "A child reservation primary key returned more than one row.");
|
|
389
|
+
return decoded.length === 0 ? Option.none() : Option.some(decoded[0]);
|
|
390
|
+
});
|
|
391
|
+
const readChildReservationForCall = Effect.fnUntraced(function* (operation, parentSubmissionId, parentToolCallId) {
|
|
392
|
+
const rows = yield* sql`
|
|
393
|
+
SELECT ${sql.literal(CHILD_RESERVATION_COLUMNS)}
|
|
394
|
+
FROM effect_agent_child_reservations
|
|
395
|
+
WHERE parent_submission_id = ${parentSubmissionId}
|
|
396
|
+
AND parent_tool_call_id = ${parentToolCallId}
|
|
397
|
+
`.pipe(Effect.mapError(sqlFailure(operation)));
|
|
398
|
+
const decoded = yield* decodeChildReservationRows(operation, `${parentSubmissionId}/${parentToolCallId}`, rows);
|
|
399
|
+
if (decoded.length > 1) return yield* corruptionFailure(operation, "effect_agent_child_reservations", `${parentSubmissionId}/${parentToolCallId}`, "A parent Tool Call returned more than one child reservation.");
|
|
400
|
+
return decoded.length === 0 ? Option.none() : Option.some(decoded[0]);
|
|
401
|
+
});
|
|
402
|
+
const childReservationSnapshotFromRow = Effect.fnUntraced(function* (operation, row) {
|
|
403
|
+
const rowFailure = (error) => corruptionFailure(operation, "effect_agent_child_reservations", row.reservation_id, error.message);
|
|
404
|
+
const allocation = yield* parseStoredJsonText(row.allocation_json).pipe(Effect.mapError(rowFailure));
|
|
405
|
+
const accounting = row.accounting_json === null ? void 0 : yield* parseStoredJsonText(row.accounting_json).pipe(Effect.mapError(rowFailure));
|
|
406
|
+
return yield* decodeChildReservationSnapshotUnknown({
|
|
407
|
+
reservationId: row.reservation_id,
|
|
408
|
+
parentSubmissionId: row.parent_submission_id,
|
|
409
|
+
parentToolCallId: row.parent_tool_call_id,
|
|
410
|
+
status: row.status,
|
|
411
|
+
allocation,
|
|
412
|
+
allocationDigest: row.allocation_digest,
|
|
413
|
+
reservedAt: row.reserved_at,
|
|
414
|
+
...row.child_submission_id === null ? {} : { childSubmissionId: row.child_submission_id },
|
|
415
|
+
...accounting === void 0 ? {} : { accounting },
|
|
416
|
+
...row.release_began_at === null ? {} : { releaseBeganAt: row.release_began_at },
|
|
417
|
+
...row.released_at === null ? {} : { releasedAt: row.released_at }
|
|
418
|
+
}).pipe(Effect.mapError(rowFailure));
|
|
419
|
+
});
|
|
420
|
+
const readApprovalDecisions = Effect.fnUntraced(function* (operation, submissionId) {
|
|
421
|
+
return (yield* cached(rows.approvals.by("submission_id", submissionId), operation)).toSorted((a, b) => a.tool_call_id < b.tool_call_id ? -1 : a.tool_call_id > b.tool_call_id ? 1 : 0);
|
|
422
|
+
});
|
|
423
|
+
const approvalIntentFromRow = (operation, row) => decodeApprovalFact(row).pipe(Effect.mapError((error) => corruptionFailure(operation, "effect_agent_approval_decisions", `${row.submission_id}/${row.tool_call_id}`, error.message)));
|
|
424
|
+
const readUnknownResolutions = Effect.fnUntraced(function* (operation, submissionId) {
|
|
425
|
+
return (yield* cached(rows.resolutions.by("submission_id", submissionId), operation)).toSorted((a, b) => a.tool_call_id < b.tool_call_id ? -1 : a.tool_call_id > b.tool_call_id ? 1 : 0);
|
|
426
|
+
});
|
|
427
|
+
const unknownResolutionIntentFromRow = Effect.fnUntraced(function* (operation, row) {
|
|
428
|
+
return yield* decodeResolutionFact(row).pipe(Effect.mapError((error) => corruptionFailure(operation, "effect_agent_unknown_resolutions", `${row.submission_id}/${row.tool_call_id}`, error.message)));
|
|
429
|
+
});
|
|
430
|
+
/** The Submission's marked-unknown open Tool Call identities, empty when never marked. */
|
|
431
|
+
const storedUnknownToolCallIds = Effect.fnUntraced(function* (operation, submission) {
|
|
432
|
+
if (submission.unknown_tool_call_ids_json === null) return [];
|
|
433
|
+
return yield* decodeToolCallIdsText(submission.unknown_tool_call_ids_json).pipe(Effect.mapError((error) => corruptionFailure(operation, "effect_agent_submissions", submission.submission_id, error.message)));
|
|
434
|
+
});
|
|
435
|
+
/**
|
|
436
|
+
* Canonical history is the abort authority (DUR-015): the intent's canonicalRecordId is
|
|
437
|
+
* derived from the shared canonical-records table using the deterministic abort record
|
|
438
|
+
* identity, never from a cached ledger marker.
|
|
439
|
+
*/
|
|
440
|
+
const canonicalAbortRecordId = Effect.fnUntraced(function* (operation, threadId, submissionId) {
|
|
441
|
+
const recordId = submissionAbortRecordId(submissionId);
|
|
442
|
+
return (yield* journal.hasRecord(threadId, recordId).pipe(Effect.mapError(internalFailure(operation)))) ? recordId : void 0;
|
|
443
|
+
});
|
|
444
|
+
const abortIntentFromRow = Effect.fnUntraced(function* (operation, submission, submissionId, row) {
|
|
445
|
+
const canonicalRecordId = yield* canonicalAbortRecordId(operation, submission.thread_id, submissionId);
|
|
446
|
+
const fact = yield* decodeAbortFact(row).pipe(Effect.mapError((error) => corruptionFailure(operation, "effect_agent_abort_intents", row.submission_id, error.message)));
|
|
447
|
+
return AbortIntent.make({
|
|
448
|
+
...fact,
|
|
449
|
+
...canonicalRecordId === void 0 ? {} : { canonicalRecordId }
|
|
450
|
+
});
|
|
451
|
+
});
|
|
452
|
+
const capabilities = Effect.succeed(LedgerCapabilities.make({ durability: "durable-cloudflare" }));
|
|
453
|
+
const admit = Effect.fnUntraced(function* (request, options) {
|
|
454
|
+
const operation = "ledger admit";
|
|
455
|
+
const validated = yield* decodeAdmissionRequestType(request).pipe(Effect.mapError(internalFailure(operation)));
|
|
456
|
+
const inputJson = yield* encodePersistedJsonText(validated.inputPayload).pipe(Effect.mapError(internalFailure(operation)));
|
|
457
|
+
yield* journal.checkValueBound(operation, inputJson).pipe(Effect.mapError(internalFailure(operation)));
|
|
458
|
+
const workerAdmissionJson = validated.workerAdmission === void 0 ? null : yield* Schema.encodeEffect(Schema.fromJsonString(WorkerAdmission))(validated.workerAdmission).pipe(Effect.mapError(internalFailure(operation)));
|
|
459
|
+
if (workerAdmissionJson !== null && new TextEncoder().encode(workerAdmissionJson).byteLength > config.maxStoredValueBytes) return yield* LedgerError.make({
|
|
460
|
+
operation,
|
|
461
|
+
message: "Worker admission metadata exceeds the stored value bound"
|
|
462
|
+
});
|
|
463
|
+
const messageAdmissionJson = validated.messageAdmission === void 0 ? null : yield* Schema.encodeEffect(Schema.fromJsonString(InputMessage))(validated.messageAdmission).pipe(Effect.mapError(internalFailure(operation)));
|
|
464
|
+
if (messageAdmissionJson !== null && new TextEncoder().encode(messageAdmissionJson).byteLength > config.maxStoredValueBytes) return yield* LedgerError.make({
|
|
465
|
+
operation,
|
|
466
|
+
message: "Message admission metadata exceeds the stored value bound"
|
|
467
|
+
});
|
|
468
|
+
const agentDigestsJson = yield* encodeDefinitionDigestsText(validated.agentDigests).pipe(Effect.mapError(internalFailure(operation)));
|
|
469
|
+
const mintedSubmissionId = `${yield* mintUuid()}:${validated.threadId}`;
|
|
470
|
+
if (mintedSubmissionId.length > MAX_IDENTIFIER_LENGTH) return yield* LedgerError.make({
|
|
471
|
+
operation,
|
|
472
|
+
message: `A routable Submission identity of ${mintedSubmissionId.length} characters exceeds the ${MAX_IDENTIFIER_LENGTH}-character ledger row bound; shorten the Thread identity.`
|
|
473
|
+
});
|
|
474
|
+
const mintedReceiptId = `receipt-${yield* mintUuid()}`;
|
|
475
|
+
yield* hitFailpoint("ledger:admit:before", operation);
|
|
476
|
+
const result = yield* inWriteTransaction(operation, Effect.gen(function* () {
|
|
477
|
+
const keyRowKey = `${validated.threadId}/${validated.principal}/${validated.idempotencyKey}`;
|
|
478
|
+
const existing = yield* byKey(validated, operation);
|
|
479
|
+
if (existing.length > 1) return yield* corruptionFailure(operation, "effect_agent_submissions", keyRowKey, "An admission idempotency key returned more than one row.");
|
|
480
|
+
if (existing.length === 1) {
|
|
481
|
+
const sameLinkage = validated.parentLinkage === void 0 ? existing[0].parent_submission_id === null && existing[0].parent_tool_call_id === null : existing[0].parent_submission_id === validated.parentLinkage.parentSubmissionId && existing[0].parent_tool_call_id === validated.parentLinkage.parentToolCallId;
|
|
482
|
+
if (existing[0].input_digest !== validated.inputDigest || !sameLinkage) return yield* AdmissionConflict.make({
|
|
483
|
+
threadId: validated.threadId,
|
|
484
|
+
principal: validated.principal,
|
|
485
|
+
idempotencyKey: validated.idempotencyKey,
|
|
486
|
+
existingInputDigest: existing[0].input_digest,
|
|
487
|
+
attemptedInputDigest: validated.inputDigest
|
|
488
|
+
});
|
|
489
|
+
const retainedWorkerAdmission = existing[0].worker_admission_json === null ? void 0 : yield* Schema.decodeEffect(Schema.fromJsonString(WorkerAdmission))(existing[0].worker_admission_json).pipe(Effect.mapError(internalFailure(operation)));
|
|
490
|
+
const retainedInputMessage = existing[0].message_admission_json === null ? void 0 : yield* Schema.decodeEffect(Schema.fromJsonString(InputMessage))(existing[0].message_admission_json).pipe(Effect.mapError(internalFailure(operation)));
|
|
491
|
+
const retainedFence = existing[0].admission_fence_json === null ? void 0 : yield* Schema.decodeEffect(Schema.fromJsonString(AdmissionFence))(existing[0].admission_fence_json).pipe(Effect.mapError(internalFailure(operation)));
|
|
492
|
+
if ((existing[0].admission_group ?? void 0) !== validated.admissionGroup || !Schema.toEquivalence(Schema.optional(WorkerAdmission))(retainedWorkerAdmission, validated.workerAdmission) || !Schema.toEquivalence(Schema.optional(InputMessage))(retainedInputMessage, validated.messageAdmission) || !Schema.toEquivalence(Schema.optional(AdmissionFence))(retainedFence, validated.admissionFence)) return yield* AdmissionConflict.make({
|
|
493
|
+
threadId: validated.threadId,
|
|
494
|
+
principal: validated.principal,
|
|
495
|
+
idempotencyKey: validated.idempotencyKey,
|
|
496
|
+
existingInputDigest: existing[0].input_digest,
|
|
497
|
+
attemptedInputDigest: validated.inputDigest
|
|
498
|
+
});
|
|
499
|
+
return yield* decodeAdmissionResult({
|
|
500
|
+
submissionId: existing[0].submission_id,
|
|
501
|
+
receiptId: existing[0].receipt_id,
|
|
502
|
+
queueSequence: existing[0].queue_sequence,
|
|
503
|
+
state: existing[0].state,
|
|
504
|
+
replayed: true
|
|
505
|
+
}).pipe(Effect.mapError(internalFailure(operation)));
|
|
506
|
+
}
|
|
507
|
+
if (!admissionFitsTransfer(validated.threadId, validated)) return yield* LedgerError.make({
|
|
508
|
+
operation,
|
|
509
|
+
message: "Admission exceeds the complete transfer page byte bound"
|
|
510
|
+
});
|
|
511
|
+
if ((yield* cached(rows.workerStops.by("thread_id", validated.threadId), operation)).length > 0) return yield* AdmissionPolicyError.make({
|
|
512
|
+
reason: "refused",
|
|
513
|
+
code: "worker-stopped"
|
|
514
|
+
});
|
|
515
|
+
const firstRows = yield* sql`
|
|
516
|
+
SELECT worker_admission_json FROM effect_agent_submissions
|
|
517
|
+
WHERE thread_id=${validated.threadId} ORDER BY queue_sequence LIMIT 1
|
|
518
|
+
`.pipe(Effect.mapError(sqlFailure(operation)));
|
|
519
|
+
const first = yield* decodeFirstWorkerAdmissions(firstRows).pipe(Effect.mapError(internalFailure(operation)));
|
|
520
|
+
if (first[0] !== void 0) {
|
|
521
|
+
const previous = first[0].worker_admission_json === null ? void 0 : yield* Schema.decodeEffect(Schema.fromJsonString(WorkerAdmission))(first[0].worker_admission_json).pipe(Effect.mapError(internalFailure(operation)));
|
|
522
|
+
if (!equivalentWorkerOrigin(previous?.origin, validated.workerAdmission?.origin)) return yield* AdmissionPolicyError.make({
|
|
523
|
+
reason: "refused",
|
|
524
|
+
code: "worker-origin-conflict"
|
|
525
|
+
});
|
|
526
|
+
}
|
|
527
|
+
yield* admissionFence.check(validated);
|
|
528
|
+
if (validated.admissionGroup !== void 0) {
|
|
529
|
+
if ((yield* sql`
|
|
530
|
+
SELECT submission_id FROM effect_agent_submissions
|
|
531
|
+
WHERE thread_id=${validated.threadId} AND admission_group=${validated.admissionGroup} AND state<>'settled' LIMIT 1
|
|
532
|
+
`.pipe(Effect.mapError(sqlFailure(operation)))).length > 0) return yield* AdmissionPolicyError.make({
|
|
533
|
+
reason: "occupied",
|
|
534
|
+
code: "admission-group"
|
|
535
|
+
});
|
|
536
|
+
}
|
|
537
|
+
const maxRows = yield* sql`
|
|
538
|
+
SELECT COALESCE(MAX(queue_sequence), 0) AS max_queue_sequence
|
|
539
|
+
FROM effect_agent_submissions
|
|
540
|
+
WHERE thread_id = ${validated.threadId}
|
|
541
|
+
`.pipe(Effect.mapError(sqlFailure(operation)));
|
|
542
|
+
const decodedMax = yield* decodeRows(MaxQueueSequenceRows, "effect_agent_submissions", validated.threadId, maxRows).pipe(Effect.mapError(internalFailure(operation)));
|
|
543
|
+
const queueSequence = yield* decodeQueueSequence((decodedMax[0]?.max_queue_sequence ?? 0) + 1).pipe(Effect.mapError(internalFailure(operation)));
|
|
544
|
+
const now = yield* currentInstant;
|
|
545
|
+
const ready = options?.readyIfInitialized === true && validated.workerAdmission === void 0 && (yield* journal.getThread(validated.threadId).pipe(Effect.mapError(internalFailure(operation)))).some((thread) => thread.tail_sequence > 0);
|
|
546
|
+
yield* sql`
|
|
547
|
+
INSERT INTO effect_agent_submissions (
|
|
548
|
+
submission_id,
|
|
549
|
+
thread_id,
|
|
550
|
+
queue_sequence,
|
|
551
|
+
principal,
|
|
552
|
+
idempotency_key,
|
|
553
|
+
agent_id,
|
|
554
|
+
definition_key,
|
|
555
|
+
deployment_id,
|
|
556
|
+
input_json,
|
|
557
|
+
input_digest,
|
|
558
|
+
receipt_id,
|
|
559
|
+
state,
|
|
560
|
+
created_at,
|
|
561
|
+
ready_at,
|
|
562
|
+
parent_submission_id,
|
|
563
|
+
parent_tool_call_id,
|
|
564
|
+
admission_group,
|
|
565
|
+
admission_fence_json,
|
|
566
|
+
worker_admission_json,
|
|
567
|
+
message_admission_json
|
|
568
|
+
) VALUES (
|
|
569
|
+
${mintedSubmissionId},
|
|
570
|
+
${validated.threadId},
|
|
571
|
+
${queueSequence},
|
|
572
|
+
${validated.principal},
|
|
573
|
+
${validated.idempotencyKey},
|
|
574
|
+
${validated.agentId},
|
|
575
|
+
${yield* physical.definition(agentDigestsJson).pipe(Effect.mapError(internalFailure(operation)))},
|
|
576
|
+
${validated.deploymentId},
|
|
577
|
+
${inputJson},
|
|
578
|
+
${validated.inputDigest},
|
|
579
|
+
${mintedReceiptId},
|
|
580
|
+
${ready ? "ready" : "admitted"},
|
|
581
|
+
${now.iso},
|
|
582
|
+
${ready ? now.iso : null},
|
|
583
|
+
${validated.parentLinkage?.parentSubmissionId ?? null},
|
|
584
|
+
${validated.parentLinkage?.parentToolCallId ?? null},
|
|
585
|
+
${validated.admissionGroup ?? null},
|
|
586
|
+
${validated.admissionFence === void 0 ? null : JSON.stringify(validated.admissionFence)},
|
|
587
|
+
${workerAdmissionJson},
|
|
588
|
+
${messageAdmissionJson}
|
|
589
|
+
)
|
|
590
|
+
RETURNING *, ${definitionJson(sql)} AS agent_digests_json`.pipe(rows.submissions.write, Effect.mapError(internalFailure(operation)));
|
|
591
|
+
if (queueSequence === 1) {
|
|
592
|
+
if ((yield* journal.getThread(validated.threadId).pipe(Effect.mapError(internalFailure(operation)))).length === 0) yield* journal.work.initialize(validated.threadId).pipe(Effect.mapError(internalFailure(operation)));
|
|
593
|
+
}
|
|
594
|
+
submissionViews.seedMatching(JSON.stringify([
|
|
595
|
+
"joining-suffix",
|
|
596
|
+
validated.threadId,
|
|
597
|
+
queueSequence
|
|
598
|
+
]), (row) => row.thread_id === validated.threadId && row.queue_sequence > queueSequence, [], 0);
|
|
599
|
+
rows.aborts.seed("submission_id", mintedSubmissionId, []);
|
|
600
|
+
rows.submissions.seed("joined_host_submission_id", mintedSubmissionId, []);
|
|
601
|
+
rows.approvals.seed("submission_id", mintedSubmissionId, []);
|
|
602
|
+
rows.resolutions.seed("submission_id", mintedSubmissionId, []);
|
|
603
|
+
rows.childReservations.seed("parent_submission_id", mintedSubmissionId, []);
|
|
604
|
+
rows.childSettlements.seed("parent_submission_id", mintedSubmissionId, []);
|
|
605
|
+
yield* recordProgress("submission", operation);
|
|
606
|
+
const admitted = yield* decodeAdmissionResult({
|
|
607
|
+
submissionId: mintedSubmissionId,
|
|
608
|
+
receiptId: mintedReceiptId,
|
|
609
|
+
queueSequence,
|
|
610
|
+
state: ready ? "ready" : "admitted",
|
|
611
|
+
replayed: false
|
|
612
|
+
}).pipe(Effect.mapError(internalFailure(operation)));
|
|
613
|
+
if (ready && lifecycle !== void 0) yield* retainLifecycle(yield* requireSubmission(operation, mintedSubmissionId), {
|
|
614
|
+
_tag: "SubmissionReady",
|
|
615
|
+
submissionId: admitted.submissionId
|
|
616
|
+
});
|
|
617
|
+
return admitted;
|
|
618
|
+
}));
|
|
619
|
+
yield* hitFailpoint("ledger:admit:after", operation);
|
|
620
|
+
return result;
|
|
621
|
+
});
|
|
622
|
+
const markReady = Effect.fnUntraced(function* (request) {
|
|
623
|
+
const operation = "ledger mark ready";
|
|
624
|
+
const validated = yield* Schema.decodeEffect(Schema.toType(MarkReadyRequest))(request).pipe(Effect.mapError(internalFailure(operation)));
|
|
625
|
+
yield* hitFailpoint("ledger:mark-ready:before", operation);
|
|
626
|
+
yield* inWriteTransaction(operation, Effect.gen(function* () {
|
|
627
|
+
const submission = yield* requireSubmission(operation, validated.submissionId);
|
|
628
|
+
if (submission.state !== "admitted") return;
|
|
629
|
+
const now = yield* currentInstant;
|
|
630
|
+
yield* sql`
|
|
631
|
+
UPDATE effect_agent_submissions
|
|
632
|
+
SET state = 'ready', ready_at = ${now.iso}
|
|
633
|
+
WHERE submission_id = ${validated.submissionId}
|
|
634
|
+
RETURNING *, ${definitionJson(sql)} AS agent_digests_json`.pipe(rows.submissions.write, Effect.mapError(internalFailure(operation)));
|
|
635
|
+
yield* recordProgress("submission", operation);
|
|
636
|
+
yield* retainLifecycle(submission, {
|
|
637
|
+
_tag: "SubmissionReady",
|
|
638
|
+
submissionId: validated.submissionId
|
|
639
|
+
});
|
|
640
|
+
}));
|
|
641
|
+
yield* hitFailpoint("ledger:mark-ready:after", operation);
|
|
642
|
+
});
|
|
643
|
+
const resolveFundingOwner = Effect.fnUntraced(function* (input) {
|
|
644
|
+
const operation = "resolve funding owner";
|
|
645
|
+
const request = yield* Schema.decodeEffect(FundingOwnerRequest)(input).pipe(Effect.mapError(internalFailure(operation)));
|
|
646
|
+
const selected = yield* requireSubmission(operation, request.submissionId);
|
|
647
|
+
if (selected.thread_id !== request.threadId) return yield* LedgerError.make({
|
|
648
|
+
operation,
|
|
649
|
+
message: "Selected funding input belongs to another Thread."
|
|
650
|
+
});
|
|
651
|
+
if (selected.state === "joining") return yield* LedgerError.make({
|
|
652
|
+
operation,
|
|
653
|
+
message: "Selected funding input is still joining; retry after durable binding."
|
|
654
|
+
});
|
|
655
|
+
const hostId = selected.joined_host_submission_id;
|
|
656
|
+
if (hostId === null && selected.state === "joined") return yield* corruptionFailure(operation, "effect_agent_submissions", selected.submission_id, "Joined input has no stable host identity.");
|
|
657
|
+
if (hostId !== null && selected.state !== "joined" && selected.state !== "settled") return yield* corruptionFailure(operation, "effect_agent_submissions", selected.submission_id, "Host linkage is inconsistent with selected input state.");
|
|
658
|
+
const owner = hostId === null ? selected : yield* requireSubmission(operation, hostId);
|
|
659
|
+
if (owner.thread_id !== request.threadId || hostId !== null && (owner.submission_id === selected.submission_id || owner.joined_host_submission_id !== null || owner.state === "joining" || owner.state === "joined" || owner.queue_sequence >= selected.queue_sequence)) return yield* corruptionFailure(operation, "effect_agent_submissions", selected.submission_id, "Funding host is not a stable earlier input in this Thread.");
|
|
660
|
+
return yield* Schema.decodeEffect(Schema.toType(FundingOwner))({
|
|
661
|
+
selected: yield* decodeSubmissionSnapshot(operation, selected),
|
|
662
|
+
owner: yield* decodeSubmissionSnapshot(operation, owner)
|
|
663
|
+
}).pipe(Effect.mapError(internalFailure(operation)));
|
|
664
|
+
}, state.read);
|
|
665
|
+
const lookup = Effect.fnUntraced(function* (request) {
|
|
666
|
+
const operation = "ledger lookup";
|
|
667
|
+
const validated = yield* decodeSubmissionLookupType(request).pipe(Effect.mapError(internalFailure(operation)));
|
|
668
|
+
if (validated._tag === "SubmissionLookupById") {
|
|
669
|
+
const row = yield* readSubmission(operation, validated.submissionId);
|
|
670
|
+
if (Option.isNone(row)) return Option.none();
|
|
671
|
+
return Option.some(yield* decodeSubmissionSnapshot(operation, row.value));
|
|
672
|
+
}
|
|
673
|
+
const decoded = yield* byKey(validated, operation);
|
|
674
|
+
if (decoded.length > 1) return yield* corruptionFailure(operation, "effect_agent_submissions", `${validated.threadId}/${validated.principal}/${validated.idempotencyKey}`, "An admission idempotency key returned more than one row.");
|
|
675
|
+
if (decoded.length === 0) return Option.none();
|
|
676
|
+
return Option.some(yield* decodeSubmissionSnapshot(operation, decoded[0]));
|
|
677
|
+
});
|
|
678
|
+
const resolveAdmission = Effect.fnUntraced(function* (request) {
|
|
679
|
+
const operation = "ledger resolve admission";
|
|
680
|
+
const validated = yield* Schema.decodeEffect(Schema.toType(SubmissionLookupByKey))(request).pipe(Effect.mapError(internalFailure(operation)));
|
|
681
|
+
const decoded = yield* byKey(validated, operation);
|
|
682
|
+
if (decoded.length > 1) return yield* corruptionFailure(operation, "effect_agent_submissions", `${validated.threadId}/${validated.principal}/${validated.idempotencyKey}`, "An admission idempotency key returned more than one row.");
|
|
683
|
+
if (decoded.length === 0) return AdmissionNotAdmitted.make();
|
|
684
|
+
return AdmissionAdmitted.make({ submission: yield* decodeSubmissionSnapshot(operation, decoded[0]) });
|
|
685
|
+
});
|
|
686
|
+
const selectHead = Effect.fn("DoSubmissionLedger.selectHead")(function* (request) {
|
|
687
|
+
const operation = "ledger select head";
|
|
688
|
+
const validated = yield* decodeClaimRequestType(request).pipe(Effect.mapError(internalFailure(operation)));
|
|
689
|
+
const attemptId = `attempt-${yield* mintUuid()}`;
|
|
690
|
+
yield* hitFailpoint("ledger:claim:before", operation);
|
|
691
|
+
const claimed = yield* owner.withMutation(Effect.gen(function* () {
|
|
692
|
+
if (owner.hasOwner(validated.threadId)) return Option.none();
|
|
693
|
+
const active = yield* activeNonterminal;
|
|
694
|
+
const heads = [];
|
|
695
|
+
const limit = validated.handoff === void 0 ? 1 : validated.handoff.deferredSubmissionIds.length + 1;
|
|
696
|
+
if (active.length <= 128) {
|
|
697
|
+
const candidates = active.filter((row) => row.thread_id === validated.threadId).sort((left, right) => left.queue_sequence - right.queue_sequence);
|
|
698
|
+
for (const candidate of candidates) {
|
|
699
|
+
if (candidate.state === "unknown" && Option.isNone(yield* readAbortIntent(operation, candidate.submission_id))) continue;
|
|
700
|
+
heads.push(yield* requireSubmission(operation, candidate.submission_id));
|
|
701
|
+
if (heads.length === limit) break;
|
|
702
|
+
}
|
|
703
|
+
} else {
|
|
704
|
+
const headRows = yield* sql`
|
|
705
|
+
SELECT ${submissionColumns}
|
|
706
|
+
FROM effect_agent_submissions
|
|
707
|
+
WHERE thread_id = ${validated.threadId}
|
|
708
|
+
AND state <> 'settled'
|
|
709
|
+
AND (
|
|
710
|
+
state <> 'unknown' OR EXISTS (
|
|
711
|
+
SELECT 1 FROM effect_agent_abort_intents
|
|
712
|
+
WHERE submission_id = effect_agent_submissions.submission_id
|
|
713
|
+
)
|
|
714
|
+
)
|
|
715
|
+
ORDER BY queue_sequence ASC
|
|
716
|
+
LIMIT ${validated.handoff === void 0 ? 1 : validated.handoff.deferredSubmissionIds.length + 1}
|
|
717
|
+
`.pipe(Effect.mapError(sqlFailure(operation)));
|
|
718
|
+
heads.push(...yield* decodeSubmissionRows(operation, validated.threadId, headRows));
|
|
719
|
+
}
|
|
720
|
+
if (heads.length === 0) return Option.none();
|
|
721
|
+
let head = heads[0];
|
|
722
|
+
if (validated.handoff !== void 0) {
|
|
723
|
+
const handoff = validated.handoff;
|
|
724
|
+
for (const candidate of heads) {
|
|
725
|
+
if (candidate.submission_id === handoff.submissionId) {
|
|
726
|
+
head = candidate;
|
|
727
|
+
break;
|
|
728
|
+
}
|
|
729
|
+
if (!handoff.deferredSubmissionIds.some((id) => id === candidate.submission_id) || candidate.state !== "input-applied" || Option.isSome(yield* readAbortIntent(operation, candidate.submission_id))) return Option.none();
|
|
730
|
+
}
|
|
731
|
+
if (head.submission_id !== handoff.submissionId || head.state !== "ready" && head.state !== "input-applied") return Option.none();
|
|
732
|
+
}
|
|
733
|
+
if (head.state === "joining" || head.state === "joined" || head.state === "suspended" || head.state === "unknown" && Option.isNone(yield* readAbortIntent(operation, head.submission_id))) return Option.none();
|
|
734
|
+
const inputPayload = yield* parseStoredJsonText(head.input_json).pipe(Effect.mapError((error) => corruptionFailure(operation, "effect_agent_submissions", head.submission_id, error.message)));
|
|
735
|
+
return Option.some(yield* decodeClaim({
|
|
736
|
+
submissionId: head.submission_id,
|
|
737
|
+
attemptId,
|
|
738
|
+
inputPayload
|
|
739
|
+
}).pipe(Effect.mapError(internalFailure(operation))));
|
|
740
|
+
}));
|
|
741
|
+
yield* hitFailpoint("ledger:claim:after", operation);
|
|
742
|
+
return claimed;
|
|
743
|
+
});
|
|
744
|
+
const markInputAppliedInTransaction = Effect.fnUntraced(function* (validated) {
|
|
745
|
+
const operation = "ledger mark input applied";
|
|
746
|
+
const submission = yield* requireSubmission(operation, validated.submissionId);
|
|
747
|
+
yield* requireOwner(operation, submission);
|
|
748
|
+
if (submission.input_applied_record_id !== null) {
|
|
749
|
+
if (submission.input_applied_record_id === validated.recordId && submission.input_applied_sequence === validated.sequence) return;
|
|
750
|
+
return yield* corruptionFailure(operation, "effect_agent_submissions", validated.submissionId, "A different canonical input marker is already recorded for this Submission.");
|
|
751
|
+
}
|
|
752
|
+
yield* sql`
|
|
753
|
+
UPDATE effect_agent_submissions
|
|
754
|
+
SET
|
|
755
|
+
input_applied_record_id = ${validated.recordId},
|
|
756
|
+
input_applied_sequence = ${validated.sequence},
|
|
757
|
+
state = CASE
|
|
758
|
+
WHEN state IN ('admitted', 'ready') THEN 'input-applied'
|
|
759
|
+
ELSE state
|
|
760
|
+
END
|
|
761
|
+
WHERE submission_id = ${validated.submissionId}
|
|
762
|
+
RETURNING *, ${definitionJson(sql)} AS agent_digests_json`.pipe(rows.submissions.write, Effect.mapError(internalFailure(operation)));
|
|
763
|
+
});
|
|
764
|
+
const markInputApplied = Effect.fnUntraced(function* (request) {
|
|
765
|
+
const operation = "ledger mark input applied";
|
|
766
|
+
const validated = yield* decodeMarkInputAppliedRequestType(request).pipe(Effect.mapError(internalFailure(operation)));
|
|
767
|
+
yield* hitFailpoint("ledger:mark-input-applied:before", operation);
|
|
768
|
+
yield* inWriteTransaction(operation, markInputAppliedInTransaction(validated));
|
|
769
|
+
yield* hitFailpoint("ledger:mark-input-applied:after", operation);
|
|
770
|
+
});
|
|
771
|
+
const appendInput = Effect.fnUntraced(function* (submissionId, request) {
|
|
772
|
+
const operation = "append original input and context";
|
|
773
|
+
const prepared = yield* prepareCanonicalAppend(request).pipe(Effect.provideService(CryptoDigest.Digest, crypto));
|
|
774
|
+
const record = prepared.request.batch.records[0];
|
|
775
|
+
const context = prepared.request.executions?.flatMap((update) => update.facts ?? []).find(({ payload }) => payload._tag === "RunContextRecorded");
|
|
776
|
+
if (prepared.request.executions?.length !== 1 || prepared.request.executions[0]?.previousRevision !== 0 || prepared.request.batch.records.length !== 1 || record?.payload._tag !== "UserInputRecorded" || record.payload.kind !== "user" || record.payload.submissionId !== submissionId || record.payload.runId !== runIdForSubmission(submissionId) || record.recordId !== submissionInputRecordId(submissionId) || prepared.request.batch.batchId !== submissionInputBatchId(submissionId) || context?.payload._tag === "RunContextRecorded" && context.payload.historyThrough !== prepared.request.expectedTailSequence) return yield* ThreadStoreError.make({
|
|
777
|
+
operation,
|
|
778
|
+
message: "Original input publication has a different context boundary"
|
|
779
|
+
});
|
|
780
|
+
const mapError = (cause) => ThreadStoreError.make({
|
|
781
|
+
operation,
|
|
782
|
+
message: cause.message,
|
|
783
|
+
cause
|
|
784
|
+
});
|
|
785
|
+
yield* journal.prepareAppend(prepared.raw).pipe(Effect.mapError(mapError));
|
|
786
|
+
return yield* owner.withProgress(prepared.request.threadId, owner.withMutation(Effect.gen(function* () {
|
|
787
|
+
yield* hitFailpoint("append:before", operation);
|
|
788
|
+
yield* hitFailpoint("ledger:mark-input-applied:before", operation);
|
|
789
|
+
const result = yield* journal.withWriteTransaction(operation)(Effect.gen(function* () {
|
|
790
|
+
const submission = yield* requireSubmission(operation, submissionId);
|
|
791
|
+
yield* requireOwner(operation, submission);
|
|
792
|
+
if (submission.thread_id !== prepared.request.threadId) return yield* LedgerError.make({
|
|
793
|
+
operation,
|
|
794
|
+
message: "Original input belongs to another Thread"
|
|
795
|
+
});
|
|
796
|
+
const result = yield* journal.appendPrepared(prepared.raw);
|
|
797
|
+
yield* markInputAppliedInTransaction(MarkInputAppliedRequest.make({
|
|
798
|
+
submissionId,
|
|
799
|
+
recordId: record.recordId,
|
|
800
|
+
sequence: result.firstSequence
|
|
801
|
+
}));
|
|
802
|
+
return result;
|
|
803
|
+
})).pipe(Effect.mapError((error) => error._tag === "DoAppendConflict" ? AppendConflict.make({
|
|
804
|
+
threadId: prepared.request.threadId,
|
|
805
|
+
batchId: prepared.request.batch.batchId,
|
|
806
|
+
reason: error.reason,
|
|
807
|
+
...error.actualTailSequence === void 0 ? {} : { actualTailSequence: error.actualTailSequence }
|
|
808
|
+
}) : error._tag === "OwnershipLost" ? error : mapError(error)));
|
|
809
|
+
yield* hitFailpoint("ledger:mark-input-applied:after", operation);
|
|
810
|
+
yield* hitFailpoint("append:after", operation);
|
|
811
|
+
return result;
|
|
812
|
+
}).pipe(Effect.mapError((error) => error._tag === "OwnershipLost" || error._tag === "ThreadStoreError" || error._tag === "AppendConflict" ? error : mapError(error)))));
|
|
813
|
+
});
|
|
814
|
+
const publish = Effect.fn("DoSubmissionLedger.publishSettlement")(function* (input) {
|
|
815
|
+
const operation = "publish settlement";
|
|
816
|
+
const { request, record, settlement } = yield* validatePublication(input);
|
|
817
|
+
const prepared = yield* prepareCanonicalAppend(request.append).pipe(Effect.provideService(CryptoDigest.Digest, crypto));
|
|
818
|
+
const mapAppendError = (error) => ThreadStoreError.make({
|
|
819
|
+
operation,
|
|
820
|
+
message: error.message,
|
|
821
|
+
cause: error
|
|
822
|
+
});
|
|
823
|
+
yield* journal.prepareAppend(prepared.raw).pipe(Effect.mapError(mapAppendError));
|
|
824
|
+
return yield* owner.withProgress(request.append.threadId, owner.withMutation(Effect.gen(function* () {
|
|
825
|
+
yield* hitFailpoint("append:before", operation);
|
|
826
|
+
const result = yield* journal.withWriteTransaction(operation)(Effect.gen(function* () {
|
|
827
|
+
const submission = yield* requireSubmission(operation, request.submissionId);
|
|
828
|
+
if (submission.thread_id !== prepared.request.threadId) return yield* LedgerError.make({
|
|
829
|
+
operation,
|
|
830
|
+
message: "Settlement publication belongs to another Thread."
|
|
831
|
+
});
|
|
832
|
+
const snapshot = yield* decodeSubmissionSnapshot(operation, submission);
|
|
833
|
+
yield* validateCanonicalSettlement(record, snapshot);
|
|
834
|
+
const existing = yield* readCanonicalSettlement(operation, submission);
|
|
835
|
+
const thread = (yield* journal.getThread(prepared.request.threadId))[0];
|
|
836
|
+
if (thread === void 0) return yield* ThreadNotMaterialized.make({ threadId: prepared.request.threadId });
|
|
837
|
+
switch (request.authority._tag) {
|
|
838
|
+
case "Owned":
|
|
839
|
+
yield* requireOwner(operation, submission);
|
|
840
|
+
yield* validateCanonicalSettlement(record, {
|
|
841
|
+
submissionId: request.submissionId,
|
|
842
|
+
receiptId: snapshot.receiptId,
|
|
843
|
+
...settlement.outcome === "aborted" && settlement.runId === void 0 ? {} : { runId: runIdForSubmission(request.submissionId) }
|
|
844
|
+
});
|
|
845
|
+
break;
|
|
846
|
+
case "Joined": {
|
|
847
|
+
if (submission.state !== "joined" && !(submission.state === "settled" && existing !== void 0) || submission.joined_host_submission_id !== request.authority.hostSubmissionId) return yield* LedgerError.make({
|
|
848
|
+
operation,
|
|
849
|
+
message: "Submission is not joined to the named host."
|
|
850
|
+
});
|
|
851
|
+
const host = yield* requireSubmission(operation, request.authority.hostSubmissionId);
|
|
852
|
+
if (host.thread_id !== submission.thread_id) return yield* LedgerError.make({
|
|
853
|
+
operation,
|
|
854
|
+
message: "Joined host belongs to another Thread."
|
|
855
|
+
});
|
|
856
|
+
const canonicalHost = yield* readCanonicalSettlement(operation, host);
|
|
857
|
+
if (canonicalHost === void 0) return yield* LedgerError.make({
|
|
858
|
+
operation,
|
|
859
|
+
message: "Joined host has no canonical settlement."
|
|
860
|
+
});
|
|
861
|
+
yield* validateJoinedSettlement(settlement, canonicalHost.settlement);
|
|
862
|
+
break;
|
|
863
|
+
}
|
|
864
|
+
case "QueuedAbort":
|
|
865
|
+
if (submission.state !== "ready" && !(submission.state === "settled" && existing !== void 0) || settlement.outcome !== "aborted" || Option.isNone(yield* readAbortIntent(operation, request.submissionId)) || owner.hasOwner(submission.thread_id, request.submissionId)) return yield* LedgerError.make({
|
|
866
|
+
operation,
|
|
867
|
+
message: "Queued abort is no longer authorized."
|
|
868
|
+
});
|
|
869
|
+
yield* validateCanonicalSettlement(record, {
|
|
870
|
+
submissionId: request.submissionId,
|
|
871
|
+
receiptId: snapshot.receiptId,
|
|
872
|
+
runId: void 0
|
|
873
|
+
});
|
|
874
|
+
}
|
|
875
|
+
if (existing !== void 0) {
|
|
876
|
+
yield* journal.checkCommitIntent(prepared.raw);
|
|
877
|
+
return SettlementPublicationResult.make({
|
|
878
|
+
record: existing.record,
|
|
879
|
+
tailSequence: thread.tail_sequence,
|
|
880
|
+
replayed: true
|
|
881
|
+
});
|
|
882
|
+
}
|
|
883
|
+
if (submission.state === "settled") return yield* LedgerError.make({
|
|
884
|
+
operation,
|
|
885
|
+
message: "Finalized Submission has no canonical settlement."
|
|
886
|
+
});
|
|
887
|
+
const appended = yield* journal.appendPrepared(prepared.raw);
|
|
888
|
+
return SettlementPublicationResult.make({
|
|
889
|
+
record,
|
|
890
|
+
tailSequence: appended.lastSequence,
|
|
891
|
+
replayed: appended.replayed
|
|
892
|
+
});
|
|
893
|
+
})).pipe(Effect.mapError((error) => {
|
|
894
|
+
if (error._tag === "DoAppendConflict") return AppendConflict.make({
|
|
895
|
+
threadId: prepared.request.threadId,
|
|
896
|
+
batchId: prepared.request.batch.batchId,
|
|
897
|
+
reason: error.reason,
|
|
898
|
+
...error.actualTailSequence !== void 0 ? { actualTailSequence: error.actualTailSequence } : {}
|
|
899
|
+
});
|
|
900
|
+
return isDoStorageError(error) || error._tag === "DoStorageCorruptionError" || error._tag === "DoStorageFailpointError" || error._tag === "DoValueBoundExceeded" ? mapAppendError(error) : error;
|
|
901
|
+
}));
|
|
902
|
+
yield* hitFailpoint("append:after", operation);
|
|
903
|
+
return result;
|
|
904
|
+
})));
|
|
905
|
+
});
|
|
906
|
+
const validateFinalization = Effect.fnUntraced(function* (validated, submission) {
|
|
907
|
+
const operation = "ledger finalize settlement";
|
|
908
|
+
const canonical = yield* readCanonicalSettlement(operation, submission);
|
|
909
|
+
if (canonical === void 0) return yield* LedgerError.make({
|
|
910
|
+
operation,
|
|
911
|
+
message: `No canonical settlement exists for submission ${validated.submissionId}.`
|
|
912
|
+
});
|
|
913
|
+
if (canonical.settlement.settlementId !== validated.settlementId) return yield* SettlementConflict.make({
|
|
914
|
+
submissionId: validated.submissionId,
|
|
915
|
+
existingOutcome: canonical.settlement.outcome
|
|
916
|
+
});
|
|
917
|
+
return {
|
|
918
|
+
...canonical,
|
|
919
|
+
settlementFailure: settlementFailureFromRecord(canonical.record)
|
|
920
|
+
};
|
|
921
|
+
});
|
|
922
|
+
const replayFinalization = Effect.fnUntraced(function* (validated, submission, { record, settlement, settlementFailure }) {
|
|
923
|
+
const operation = "ledger finalize settlement";
|
|
924
|
+
if (submission.finalized_at === null || submission.settled_record_id !== record.recordId || submission.settled_outcome !== settlement.outcome) return yield* corruptionFailure(operation, "effect_agent_submissions", validated.submissionId, "Settled projection disagrees with its canonical settlement.");
|
|
925
|
+
return yield* decodeSettlement({
|
|
926
|
+
submissionId: validated.submissionId,
|
|
927
|
+
settlementId: validated.settlementId,
|
|
928
|
+
receiptId: submission.receipt_id,
|
|
929
|
+
outcome: settlement.outcome,
|
|
930
|
+
...settlementFailure === void 0 ? {} : { failure: settlementFailure },
|
|
931
|
+
settledAt: submission.finalized_at
|
|
932
|
+
}).pipe(Effect.mapError(internalFailure(operation)));
|
|
933
|
+
});
|
|
934
|
+
const finalizeSettlement = Effect.fn("DoSubmissionLedger.finalizeSettlement")(function* (request) {
|
|
935
|
+
const operation = "ledger finalize settlement";
|
|
936
|
+
const validated = yield* decodeSettlementFinalizationType(request).pipe(Effect.mapError(internalFailure(operation)));
|
|
937
|
+
yield* hitFailpoint("ledger:finalize-settlement:before", operation);
|
|
938
|
+
const replay = yield* state.read(Effect.gen(function* () {
|
|
939
|
+
const submission = yield* readSubmission(operation, validated.submissionId);
|
|
940
|
+
if (Option.isNone(submission) || submission.value.state !== "settled") return Option.none();
|
|
941
|
+
const finalization = yield* validateFinalization(validated, submission.value);
|
|
942
|
+
return Option.some({
|
|
943
|
+
settlement: yield* replayFinalization(validated, submission.value, finalization),
|
|
944
|
+
threadId: submission.value.thread_id
|
|
945
|
+
});
|
|
946
|
+
}));
|
|
947
|
+
if (Option.isSome(replay)) {
|
|
948
|
+
owner.closeSubmission(replay.value.threadId, validated.submissionId);
|
|
949
|
+
yield* hitFailpoint("ledger:finalize-settlement:after", operation);
|
|
950
|
+
return replay.value.settlement;
|
|
951
|
+
}
|
|
952
|
+
const settlement = yield* inWriteTransaction(operation, Effect.gen(function* () {
|
|
953
|
+
const submission = yield* requireSubmission(operation, validated.submissionId);
|
|
954
|
+
const state = yield* validateFinalization(validated, submission);
|
|
955
|
+
const { settlement: canonicalSettlement, record: canonicalRecord, settlementFailure } = state;
|
|
956
|
+
if (submission.state === "settled") return {
|
|
957
|
+
settlement: yield* replayFinalization(validated, submission, state),
|
|
958
|
+
threadId: submission.thread_id
|
|
959
|
+
};
|
|
960
|
+
const now = yield* currentInstant;
|
|
961
|
+
const terminal = submission.worker_admission_json === null ? void 0 : workerTerminalFromRecord(yield* decodeSubmissionSnapshot(operation, submission), canonicalRecord);
|
|
962
|
+
let sealedTerminal;
|
|
963
|
+
if (terminal !== void 0) {
|
|
964
|
+
if ((terminal === "completed" ? yield* sql`SELECT submission_id FROM effect_agent_submissions
|
|
965
|
+
WHERE thread_id = ${submission.thread_id} AND queue_sequence > ${submission.queue_sequence}
|
|
966
|
+
AND queue_sequence = (SELECT MAX(queue_sequence) FROM effect_agent_submissions WHERE thread_id = ${submission.thread_id})
|
|
967
|
+
AND (joined_host_submission_id IS NULL OR joined_host_submission_id <> ${submission.submission_id}
|
|
968
|
+
OR input_applied_record_id IS NULL) LIMIT 1`.pipe(Effect.mapError(sqlFailure(operation))) : []).length === 0) {
|
|
969
|
+
const sealed = yield* sql`INSERT OR IGNORE INTO effect_agent_worker_stops (thread_id, terminal)
|
|
970
|
+
VALUES (${submission.thread_id}, ${terminal}) RETURNING *`.pipe(rows.workerStops.write, Effect.mapError(internalFailure(operation)));
|
|
971
|
+
yield* sql`INSERT OR IGNORE INTO effect_agent_abort_intents (submission_id, author, reason, requested_at)
|
|
972
|
+
SELECT submission_id, ${submission.principal}, ${`Worker assignment ${terminal}`}, ${now.iso}
|
|
973
|
+
FROM effect_agent_submissions WHERE thread_id = ${submission.thread_id} AND state <> 'settled'
|
|
974
|
+
AND submission_id <> ${submission.submission_id}
|
|
975
|
+
AND (joined_host_submission_id IS NULL OR joined_host_submission_id <> ${submission.submission_id}
|
|
976
|
+
OR input_applied_record_id IS NULL) RETURNING *`.pipe(rows.aborts.write, Effect.mapError(internalFailure(operation)));
|
|
977
|
+
if (sealed.length > 0) sealedTerminal = terminal;
|
|
978
|
+
}
|
|
979
|
+
}
|
|
980
|
+
yield* sql`
|
|
981
|
+
UPDATE effect_agent_submissions
|
|
982
|
+
SET state = 'settled', settled_outcome = ${canonicalSettlement.outcome},
|
|
983
|
+
settled_record_id = ${canonicalRecord.recordId}, finalized_at = ${now.iso}
|
|
984
|
+
WHERE submission_id = ${validated.submissionId}
|
|
985
|
+
RETURNING *, ${definitionJson(sql)} AS agent_digests_json`.pipe(rows.submissions.write, Effect.mapError(internalFailure(operation)));
|
|
986
|
+
yield* recordProgress("submission", operation);
|
|
987
|
+
if (sealedTerminal !== void 0) yield* retainWorkerSeal(submission.thread_id, sealedTerminal);
|
|
988
|
+
return {
|
|
989
|
+
threadId: submission.thread_id,
|
|
990
|
+
settlement: yield* decodeSettlement({
|
|
991
|
+
submissionId: validated.submissionId,
|
|
992
|
+
settlementId: validated.settlementId,
|
|
993
|
+
receiptId: submission.receipt_id,
|
|
994
|
+
outcome: canonicalSettlement.outcome,
|
|
995
|
+
...settlementFailure === void 0 ? {} : { failure: settlementFailure },
|
|
996
|
+
settledAt: now.iso
|
|
997
|
+
}).pipe(Effect.mapError(internalFailure(operation)))
|
|
998
|
+
};
|
|
999
|
+
}));
|
|
1000
|
+
owner.closeSubmission(settlement.threadId, validated.submissionId);
|
|
1001
|
+
yield* hitFailpoint("ledger:finalize-settlement:after", operation);
|
|
1002
|
+
return settlement.settlement;
|
|
1003
|
+
});
|
|
1004
|
+
const inspectWorker = Effect.fnUntraced(function* (threadId) {
|
|
1005
|
+
const operation = "inspect worker";
|
|
1006
|
+
return yield* state.transaction(Effect.gen(function* () {
|
|
1007
|
+
const read = Effect.fnUntraced(function* (active) {
|
|
1008
|
+
const rows = yield* sql`SELECT ${submissionColumns} FROM effect_agent_submissions
|
|
1009
|
+
WHERE thread_id = ${threadId} ${active ? sql`AND state <> 'settled'` : sql``}
|
|
1010
|
+
ORDER BY queue_sequence ${active ? sql`ASC` : sql`DESC`} LIMIT 1`.pipe(Effect.mapError(sqlFailure(operation)));
|
|
1011
|
+
const decoded = yield* decodeSubmissionRows(operation, threadId, rows);
|
|
1012
|
+
return decoded[0] === void 0 ? null : yield* decodeSubmissionSnapshot(operation, decoded[0]);
|
|
1013
|
+
});
|
|
1014
|
+
const latest = yield* read(false);
|
|
1015
|
+
const active = yield* read(true);
|
|
1016
|
+
const stops = yield* cached(rows.workerStops.by("thread_id", threadId), operation);
|
|
1017
|
+
return yield* Schema.decodeEffect(Schema.toType(WorkerLedgerState))({
|
|
1018
|
+
latest,
|
|
1019
|
+
active,
|
|
1020
|
+
stopped: stops.length > 0,
|
|
1021
|
+
...stops[0] === void 0 || stops[0].terminal === null ? {} : { terminal: stops[0].terminal }
|
|
1022
|
+
}).pipe(Effect.mapError(internalFailure(operation)));
|
|
1023
|
+
})).pipe(Effect.provideService(SqlClientService.SqlClient, sql), Effect.catchTag("SqlError", (cause) => sqlFailure(operation)(cause)));
|
|
1024
|
+
});
|
|
1025
|
+
const stopWorker = Effect.fnUntraced(function* (request) {
|
|
1026
|
+
const operation = "ledger stop worker";
|
|
1027
|
+
const validated = yield* Schema.decodeEffect(WorkerStopCommand)(request).pipe(Effect.mapError(internalFailure(operation)));
|
|
1028
|
+
return yield* inWriteTransaction(operation, Effect.gen(function* () {
|
|
1029
|
+
const now = yield* currentInstant;
|
|
1030
|
+
const sealed = yield* sql`INSERT OR IGNORE INTO effect_agent_worker_stops (thread_id) VALUES (${validated.threadId}) RETURNING *`.pipe(rows.workerStops.write, Effect.mapError(internalFailure(operation)));
|
|
1031
|
+
const aborted = yield* sql`INSERT OR IGNORE INTO effect_agent_abort_intents (submission_id, author, reason, requested_at)
|
|
1032
|
+
SELECT submission_id, ${validated.author}, 'Worker owner stopped the worker', ${now.iso}
|
|
1033
|
+
FROM effect_agent_submissions WHERE thread_id = ${validated.threadId} AND state <> 'settled' RETURNING *`.pipe(rows.aborts.write, Effect.mapError(internalFailure(operation)));
|
|
1034
|
+
if (sealed.length > 0 || aborted.length > 0) yield* recordProgress("control", operation);
|
|
1035
|
+
if (sealed.length > 0) yield* retainWorkerSeal(validated.threadId, null);
|
|
1036
|
+
return owner.hasOwner(validated.threadId) ? 1 : 0;
|
|
1037
|
+
}));
|
|
1038
|
+
});
|
|
1039
|
+
const requestAbort = Effect.fnUntraced(function* (request) {
|
|
1040
|
+
const operation = "ledger request abort";
|
|
1041
|
+
const validated = yield* Schema.decodeEffect(Schema.toType(AbortCommand))(request).pipe(Effect.mapError(internalFailure(operation)));
|
|
1042
|
+
yield* hitFailpoint("ledger:request-abort:before", operation);
|
|
1043
|
+
const intent = yield* inWriteTransaction(operation, Effect.gen(function* () {
|
|
1044
|
+
const submission = yield* requireSubmission(operation, validated.submissionId);
|
|
1045
|
+
if (submission.state === "settled") {
|
|
1046
|
+
if (submission.settled_outcome === null) return yield* corruptionFailure(operation, "effect_agent_submissions", validated.submissionId, "A settled Submission carries no terminal outcome.");
|
|
1047
|
+
return yield* SettlementConflict.make({
|
|
1048
|
+
submissionId: validated.submissionId,
|
|
1049
|
+
existingOutcome: submission.settled_outcome
|
|
1050
|
+
});
|
|
1051
|
+
}
|
|
1052
|
+
if (submission.state === "joined") {
|
|
1053
|
+
if (submission.joined_host_submission_id === null) return yield* corruptionFailure(operation, "effect_agent_submissions", validated.submissionId, "A joined Submission carries no host linkage.");
|
|
1054
|
+
const hostSubmissionId = yield* decodeSubmissionId(submission.joined_host_submission_id).pipe(Effect.mapError(internalFailure(operation)));
|
|
1055
|
+
return yield* JoinedToHost.make({
|
|
1056
|
+
submissionId: validated.submissionId,
|
|
1057
|
+
hostSubmissionId
|
|
1058
|
+
});
|
|
1059
|
+
}
|
|
1060
|
+
const existing = yield* readAbortIntent(operation, validated.submissionId);
|
|
1061
|
+
if (Option.isSome(existing)) return yield* abortIntentFromRow(operation, submission, validated.submissionId, existing.value);
|
|
1062
|
+
const now = yield* currentInstant;
|
|
1063
|
+
yield* sql`
|
|
1064
|
+
INSERT INTO effect_agent_abort_intents (
|
|
1065
|
+
submission_id,
|
|
1066
|
+
author,
|
|
1067
|
+
reason,
|
|
1068
|
+
requested_at
|
|
1069
|
+
) VALUES (
|
|
1070
|
+
${validated.submissionId},
|
|
1071
|
+
${validated.author},
|
|
1072
|
+
${validated.reason},
|
|
1073
|
+
${now.iso}
|
|
1074
|
+
)
|
|
1075
|
+
RETURNING *`.pipe(rows.aborts.write, Effect.mapError(internalFailure(operation)));
|
|
1076
|
+
yield* recordProgress("control", operation);
|
|
1077
|
+
const canonicalRecordId = yield* canonicalAbortRecordId(operation, submission.thread_id, validated.submissionId);
|
|
1078
|
+
const intent = yield* decodeAbortIntent({
|
|
1079
|
+
submissionId: validated.submissionId,
|
|
1080
|
+
author: validated.author,
|
|
1081
|
+
reason: validated.reason,
|
|
1082
|
+
requestedAt: now.iso,
|
|
1083
|
+
...canonicalRecordId === void 0 ? {} : { canonicalRecordId }
|
|
1084
|
+
}).pipe(Effect.mapError(internalFailure(operation)));
|
|
1085
|
+
yield* retainLifecycle(submission, {
|
|
1086
|
+
_tag: "AbortIntentRecorded",
|
|
1087
|
+
intent
|
|
1088
|
+
});
|
|
1089
|
+
return intent;
|
|
1090
|
+
}));
|
|
1091
|
+
yield* hitFailpoint("ledger:request-abort:after", operation);
|
|
1092
|
+
return intent;
|
|
1093
|
+
});
|
|
1094
|
+
const claimJoining = Effect.fnUntraced(function* (request) {
|
|
1095
|
+
const operation = "ledger claim joining";
|
|
1096
|
+
const validated = yield* decodeClaimJoiningRequestType(request).pipe(Effect.mapError(internalFailure(operation)));
|
|
1097
|
+
yield* hitFailpoint("ledger:claim-joining:before", operation);
|
|
1098
|
+
const claims = yield* owner.withMutation(Effect.gen(function* () {
|
|
1099
|
+
const host = yield* requireSubmission(operation, validated.hostSubmissionId);
|
|
1100
|
+
if (host.thread_id !== validated.threadId) return yield* LedgerError.make({
|
|
1101
|
+
operation,
|
|
1102
|
+
message: `Host submission ${validated.hostSubmissionId} does not belong to thread ${validated.threadId}.`
|
|
1103
|
+
});
|
|
1104
|
+
yield* requireOwner(operation, host);
|
|
1105
|
+
if ((yield* cached(rows.workerStops.by("thread_id", validated.threadId), operation)).length > 0) return [];
|
|
1106
|
+
const later = yield* submissionViews.matching(JSON.stringify([
|
|
1107
|
+
"joining-suffix",
|
|
1108
|
+
validated.threadId,
|
|
1109
|
+
host.queue_sequence
|
|
1110
|
+
]), (row) => row.thread_id === validated.threadId && row.queue_sequence > host.queue_sequence, sql`
|
|
1111
|
+
SELECT ${submissionColumns}
|
|
1112
|
+
FROM effect_agent_submissions
|
|
1113
|
+
WHERE thread_id = ${validated.threadId}
|
|
1114
|
+
AND queue_sequence > ${host.queue_sequence}
|
|
1115
|
+
ORDER BY queue_sequence ASC
|
|
1116
|
+
`, 0).pipe(Effect.mapError((error) => error._tag === "SqlError" ? sqlFailure(operation)(error) : internalFailure(operation)(error)));
|
|
1117
|
+
if (later.length === 0) return [];
|
|
1118
|
+
return yield* inWriteTransaction(operation, Effect.gen(function* () {
|
|
1119
|
+
const claimed = [];
|
|
1120
|
+
for (const row of later) {
|
|
1121
|
+
if (claimed.length >= validated.maxCount) break;
|
|
1122
|
+
if ((row.state === "joining" || row.state === "joined") && row.joined_host_submission_id === validated.hostSubmissionId) continue;
|
|
1123
|
+
if (row.state === "settled" && row.settled_outcome === "aborted") continue;
|
|
1124
|
+
if (row.state !== "ready") break;
|
|
1125
|
+
const canonical = yield* readCanonicalSettlement(operation, row);
|
|
1126
|
+
if (canonical?.settlement.outcome === "aborted") continue;
|
|
1127
|
+
if (canonical !== void 0) break;
|
|
1128
|
+
yield* sql`
|
|
1129
|
+
UPDATE effect_agent_submissions
|
|
1130
|
+
SET state = 'joining', joined_host_submission_id = ${validated.hostSubmissionId}
|
|
1131
|
+
WHERE submission_id = ${row.submission_id}
|
|
1132
|
+
RETURNING *, ${definitionJson(sql)} AS agent_digests_json`.pipe(rows.submissions.write, Effect.mapError(internalFailure(operation)));
|
|
1133
|
+
const inputPayload = yield* parseStoredJsonText(row.input_json).pipe(Effect.mapError((error) => corruptionFailure(operation, "effect_agent_submissions", row.submission_id, error.message)));
|
|
1134
|
+
claimed.push(yield* decodeJoiningClaim({
|
|
1135
|
+
submissionId: row.submission_id,
|
|
1136
|
+
queueSequence: row.queue_sequence,
|
|
1137
|
+
inputPayload
|
|
1138
|
+
}).pipe(Effect.mapError(internalFailure(operation))));
|
|
1139
|
+
}
|
|
1140
|
+
return claimed;
|
|
1141
|
+
}));
|
|
1142
|
+
}));
|
|
1143
|
+
yield* hitFailpoint("ledger:claim-joining:after", operation);
|
|
1144
|
+
return claims;
|
|
1145
|
+
});
|
|
1146
|
+
const markJoined = Effect.fnUntraced(function* (request) {
|
|
1147
|
+
const operation = "ledger mark joined";
|
|
1148
|
+
const validated = yield* Schema.decodeEffect(Schema.toType(MarkJoinedRequest))(request).pipe(Effect.mapError(internalFailure(operation)));
|
|
1149
|
+
yield* hitFailpoint("ledger:mark-joined:before", operation);
|
|
1150
|
+
yield* inWriteTransaction(operation, Effect.gen(function* () {
|
|
1151
|
+
const submission = yield* requireSubmission(operation, validated.submissionId);
|
|
1152
|
+
if (submission.joined_host_submission_id === null) return yield* LedgerError.make({
|
|
1153
|
+
operation,
|
|
1154
|
+
message: `Submission ${validated.submissionId} was never claimed for joining.`
|
|
1155
|
+
});
|
|
1156
|
+
const host = yield* requireSubmission(operation, submission.joined_host_submission_id);
|
|
1157
|
+
yield* requireOwner(operation, host);
|
|
1158
|
+
if (submission.input_applied_record_id !== null) {
|
|
1159
|
+
if (submission.input_applied_record_id === validated.recordId && submission.input_applied_sequence === validated.sequence) return;
|
|
1160
|
+
return yield* corruptionFailure(operation, "effect_agent_submissions", validated.submissionId, "A different join marker is already recorded for this Submission.");
|
|
1161
|
+
}
|
|
1162
|
+
if (submission.state !== "joining" && submission.state !== "joined") return yield* LedgerError.make({
|
|
1163
|
+
operation,
|
|
1164
|
+
message: `Cannot mark submission ${validated.submissionId} joined from state ${submission.state}.`
|
|
1165
|
+
});
|
|
1166
|
+
yield* sql`
|
|
1167
|
+
UPDATE effect_agent_submissions
|
|
1168
|
+
SET
|
|
1169
|
+
input_applied_record_id = ${validated.recordId},
|
|
1170
|
+
input_applied_sequence = ${validated.sequence},
|
|
1171
|
+
state = 'joined'
|
|
1172
|
+
WHERE submission_id = ${validated.submissionId}
|
|
1173
|
+
RETURNING *, ${definitionJson(sql)} AS agent_digests_json`.pipe(rows.submissions.write, Effect.mapError(internalFailure(operation)));
|
|
1174
|
+
}));
|
|
1175
|
+
yield* hitFailpoint("ledger:mark-joined:after", operation);
|
|
1176
|
+
});
|
|
1177
|
+
const revertJoining = Effect.fnUntraced(function* (request) {
|
|
1178
|
+
const operation = "ledger revert joining";
|
|
1179
|
+
const validated = yield* Schema.decodeEffect(Schema.toType(RevertJoiningRequest))(request).pipe(Effect.mapError(internalFailure(operation)));
|
|
1180
|
+
yield* hitFailpoint("ledger:revert-joining:before", operation);
|
|
1181
|
+
yield* inWriteTransaction(operation, Effect.gen(function* () {
|
|
1182
|
+
const submission = yield* requireSubmission(operation, validated.submissionId);
|
|
1183
|
+
if (submission.state !== "joining") return;
|
|
1184
|
+
const guard = validated.guard;
|
|
1185
|
+
if (guard !== void 0) {
|
|
1186
|
+
if (submission.joined_host_submission_id !== guard.hostSubmissionId) return;
|
|
1187
|
+
const host = yield* requireSubmission(operation, guard.hostSubmissionId);
|
|
1188
|
+
if (host.thread_id !== submission.thread_id) return yield* corruptionFailure(operation, "effect_agent_submissions", validated.submissionId, "The joined host belongs to another Thread.");
|
|
1189
|
+
if (host.state !== "settled") yield* requireOwner(operation, host).pipe(Effect.mapError((cause) => cause._tag === "OwnershipLost" ? LedgerError.make({
|
|
1190
|
+
operation,
|
|
1191
|
+
message: "Joining recovery no longer owns the linked host.",
|
|
1192
|
+
cause
|
|
1193
|
+
}) : cause));
|
|
1194
|
+
}
|
|
1195
|
+
yield* sql`
|
|
1196
|
+
UPDATE effect_agent_submissions
|
|
1197
|
+
SET state = 'ready', joined_host_submission_id = NULL
|
|
1198
|
+
WHERE submission_id = ${validated.submissionId}
|
|
1199
|
+
RETURNING *, ${definitionJson(sql)} AS agent_digests_json`.pipe(rows.submissions.write, Effect.mapError(internalFailure(operation)));
|
|
1200
|
+
}));
|
|
1201
|
+
yield* hitFailpoint("ledger:revert-joining:after", operation);
|
|
1202
|
+
});
|
|
1203
|
+
const suspend = Effect.fnUntraced(function* (request) {
|
|
1204
|
+
const operation = "ledger suspend";
|
|
1205
|
+
const validated = yield* Schema.decodeEffect(Schema.toType(SuspendRequest))(request).pipe(Effect.mapError(internalFailure(operation)));
|
|
1206
|
+
const reasonJson = yield* encodeSuspensionReasonText(validated.reason).pipe(Effect.mapError(internalFailure(operation)));
|
|
1207
|
+
yield* hitFailpoint("ledger:suspend:before", operation);
|
|
1208
|
+
const outcome = yield* inWriteTransaction(operation, Effect.gen(function* () {
|
|
1209
|
+
const submission = yield* requireSubmission(operation, validated.submissionId);
|
|
1210
|
+
if (submission.state === "settled") {
|
|
1211
|
+
if (submission.settled_outcome === null) return yield* corruptionFailure(operation, "effect_agent_submissions", validated.submissionId, "A settled Submission carries no terminal outcome.");
|
|
1212
|
+
return yield* SettlementConflict.make({
|
|
1213
|
+
submissionId: validated.submissionId,
|
|
1214
|
+
existingOutcome: submission.settled_outcome
|
|
1215
|
+
});
|
|
1216
|
+
}
|
|
1217
|
+
const canonical = yield* readCanonicalSettlement(operation, submission);
|
|
1218
|
+
if (canonical !== void 0) return yield* SettlementConflict.make({
|
|
1219
|
+
submissionId: validated.submissionId,
|
|
1220
|
+
existingOutcome: canonical.settlement.outcome
|
|
1221
|
+
});
|
|
1222
|
+
yield* requireOwner(operation, submission);
|
|
1223
|
+
if (validated.reason._tag === "ApprovalPending") {
|
|
1224
|
+
const decisions = yield* readApprovalDecisions(operation, validated.submissionId);
|
|
1225
|
+
const decided = new Map(decisions.map((row) => [row.tool_call_id, row.decision]));
|
|
1226
|
+
if (approvalDecisionsCover(validated.reason.toolCallIds, (toolCallId) => decided.get(toolCallId))) return {
|
|
1227
|
+
outcome: RESUME_IMMEDIATELY,
|
|
1228
|
+
threadId: submission.thread_id
|
|
1229
|
+
};
|
|
1230
|
+
} else {
|
|
1231
|
+
const markers = yield* readChildSettlementMarkers(operation, validated.submissionId);
|
|
1232
|
+
const markerChildren = new Set(markers.map((row) => row.child_submission_id));
|
|
1233
|
+
let allSettled = true;
|
|
1234
|
+
for (const child of validated.reason.children) if (!(yield* childProvablySettled(operation, markerChildren, child.childSubmissionId))) {
|
|
1235
|
+
allSettled = false;
|
|
1236
|
+
break;
|
|
1237
|
+
}
|
|
1238
|
+
if (allSettled) return {
|
|
1239
|
+
outcome: RESUME_IMMEDIATELY,
|
|
1240
|
+
threadId: submission.thread_id
|
|
1241
|
+
};
|
|
1242
|
+
}
|
|
1243
|
+
const now = yield* currentInstant;
|
|
1244
|
+
yield* sql`
|
|
1245
|
+
UPDATE effect_agent_submissions
|
|
1246
|
+
SET
|
|
1247
|
+
state = 'suspended',
|
|
1248
|
+
suspended_reason_json = ${reasonJson},
|
|
1249
|
+
suspended_at = ${now.iso}
|
|
1250
|
+
WHERE submission_id = ${validated.submissionId}
|
|
1251
|
+
RETURNING *, ${definitionJson(sql)} AS agent_digests_json`.pipe(rows.submissions.write, Effect.mapError(internalFailure(operation)));
|
|
1252
|
+
yield* retainLifecycle(submission, {
|
|
1253
|
+
_tag: "SubmissionSuspended",
|
|
1254
|
+
submissionId: validated.submissionId,
|
|
1255
|
+
reason: validated.reason
|
|
1256
|
+
});
|
|
1257
|
+
return {
|
|
1258
|
+
outcome: SUSPENDED,
|
|
1259
|
+
threadId: submission.thread_id
|
|
1260
|
+
};
|
|
1261
|
+
}));
|
|
1262
|
+
if (outcome.outcome === SUSPENDED) owner.closeSubmission(outcome.threadId, validated.submissionId);
|
|
1263
|
+
yield* hitFailpoint("ledger:suspend:after", operation);
|
|
1264
|
+
return outcome.outcome;
|
|
1265
|
+
});
|
|
1266
|
+
/**
|
|
1267
|
+
* Once one pending call is denied or every pending call has a decision intent,
|
|
1268
|
+
* the lane wakes: suspended → input-applied, suspension cleared (plan §2.6). A
|
|
1269
|
+
* WaitingForChild suspension wakes only through recordChildSettled. Runs inside the caller's
|
|
1270
|
+
* write transaction.
|
|
1271
|
+
*/
|
|
1272
|
+
const wakeSuspendedIfCovered = Effect.fnUntraced(function* (operation, submission) {
|
|
1273
|
+
if (submission.state !== "suspended" || submission.suspended_reason_json === null) return;
|
|
1274
|
+
const reason = yield* Schema.decodeEffect(Schema.fromJsonString(SuspensionReason))(submission.suspended_reason_json).pipe(Effect.mapError((error) => corruptionFailure(operation, "effect_agent_submissions", submission.submission_id, error.message)));
|
|
1275
|
+
if (reason._tag !== "ApprovalPending") return;
|
|
1276
|
+
const decisions = yield* readApprovalDecisions(operation, submission.submission_id);
|
|
1277
|
+
const decided = new Map(decisions.map((row) => [row.tool_call_id, row.decision]));
|
|
1278
|
+
if (!approvalDecisionsCover(reason.toolCallIds, (toolCallId) => decided.get(toolCallId))) return;
|
|
1279
|
+
yield* sql`
|
|
1280
|
+
UPDATE effect_agent_submissions
|
|
1281
|
+
SET
|
|
1282
|
+
state = 'input-applied',
|
|
1283
|
+
suspended_reason_json = NULL,
|
|
1284
|
+
suspended_at = NULL
|
|
1285
|
+
WHERE submission_id = ${submission.submission_id}
|
|
1286
|
+
RETURNING *, ${definitionJson(sql)} AS agent_digests_json`.pipe(rows.submissions.write, Effect.mapError(internalFailure(operation)));
|
|
1287
|
+
yield* retainLifecycle(submission, {
|
|
1288
|
+
_tag: "SubmissionResumed",
|
|
1289
|
+
submissionId: yield* decodeSubmissionId(submission.submission_id).pipe(Effect.mapError(internalFailure(operation)))
|
|
1290
|
+
});
|
|
1291
|
+
});
|
|
1292
|
+
const recordApprovalDecision = Effect.fnUntraced(function* (command) {
|
|
1293
|
+
const operation = "ledger record approval decision";
|
|
1294
|
+
const validated = yield* Schema.decodeEffect(Schema.toType(ApprovalDecisionCommand))(command).pipe(Effect.mapError(internalFailure(operation)));
|
|
1295
|
+
yield* hitFailpoint("ledger:approval-decision:before", operation);
|
|
1296
|
+
const intent = yield* inWriteTransaction(operation, Effect.gen(function* () {
|
|
1297
|
+
const submission = yield* requireSubmission(operation, validated.submissionId);
|
|
1298
|
+
if (submission.state === "settled") {
|
|
1299
|
+
if (submission.settled_outcome === null) return yield* corruptionFailure(operation, "effect_agent_submissions", validated.submissionId, "A settled Submission carries no terminal outcome.");
|
|
1300
|
+
return yield* SettlementConflict.make({
|
|
1301
|
+
submissionId: validated.submissionId,
|
|
1302
|
+
existingOutcome: submission.settled_outcome
|
|
1303
|
+
});
|
|
1304
|
+
}
|
|
1305
|
+
const existing = (yield* readApprovalDecisions(operation, validated.submissionId)).find((row) => row.tool_call_id === validated.toolCallId);
|
|
1306
|
+
if (existing !== void 0) {
|
|
1307
|
+
if (existing.decision !== validated.decision) return yield* ApprovalConflict.make({
|
|
1308
|
+
submissionId: validated.submissionId,
|
|
1309
|
+
toolCallId: validated.toolCallId,
|
|
1310
|
+
existingDecision: existing.decision
|
|
1311
|
+
});
|
|
1312
|
+
return yield* approvalIntentFromRow(operation, existing);
|
|
1313
|
+
}
|
|
1314
|
+
const now = yield* currentInstant;
|
|
1315
|
+
yield* sql`
|
|
1316
|
+
INSERT INTO effect_agent_approval_decisions (
|
|
1317
|
+
submission_id,
|
|
1318
|
+
tool_call_id,
|
|
1319
|
+
decision,
|
|
1320
|
+
resolver,
|
|
1321
|
+
reason,
|
|
1322
|
+
decided_at
|
|
1323
|
+
) VALUES (
|
|
1324
|
+
${validated.submissionId},
|
|
1325
|
+
${validated.toolCallId},
|
|
1326
|
+
${validated.decision},
|
|
1327
|
+
${validated.resolver},
|
|
1328
|
+
${validated.reason},
|
|
1329
|
+
${now.iso}
|
|
1330
|
+
)
|
|
1331
|
+
RETURNING *`.pipe(rows.approvals.write, Effect.mapError(internalFailure(operation)));
|
|
1332
|
+
yield* recordProgress("control", operation);
|
|
1333
|
+
yield* wakeSuspendedIfCovered(operation, submission);
|
|
1334
|
+
return yield* decodeApprovalDecisionIntent({
|
|
1335
|
+
submissionId: validated.submissionId,
|
|
1336
|
+
toolCallId: validated.toolCallId,
|
|
1337
|
+
decision: validated.decision,
|
|
1338
|
+
resolver: validated.resolver,
|
|
1339
|
+
reason: validated.reason,
|
|
1340
|
+
decidedAt: now.iso
|
|
1341
|
+
}).pipe(Effect.mapError(internalFailure(operation)));
|
|
1342
|
+
}));
|
|
1343
|
+
yield* hitFailpoint("ledger:approval-decision:after", operation);
|
|
1344
|
+
return intent;
|
|
1345
|
+
});
|
|
1346
|
+
const markUnknown = Effect.fnUntraced(function* (request) {
|
|
1347
|
+
const operation = "ledger mark unknown";
|
|
1348
|
+
const validated = yield* Schema.decodeEffect(Schema.toType(MarkUnknownRequest))(request).pipe(Effect.mapError(internalFailure(operation)));
|
|
1349
|
+
yield* hitFailpoint("ledger:mark-unknown:before", operation);
|
|
1350
|
+
yield* inWriteTransaction(operation, Effect.gen(function* () {
|
|
1351
|
+
const submission = yield* requireSubmission(operation, validated.submissionId);
|
|
1352
|
+
if (submission.state === "settled") {
|
|
1353
|
+
if (submission.settled_outcome === null) return yield* corruptionFailure(operation, "effect_agent_submissions", validated.submissionId, "A settled Submission carries no terminal outcome.");
|
|
1354
|
+
return yield* SettlementConflict.make({
|
|
1355
|
+
submissionId: validated.submissionId,
|
|
1356
|
+
existingOutcome: submission.settled_outcome
|
|
1357
|
+
});
|
|
1358
|
+
}
|
|
1359
|
+
const canonical = yield* readCanonicalSettlement(operation, submission);
|
|
1360
|
+
if (canonical !== void 0) return yield* SettlementConflict.make({
|
|
1361
|
+
submissionId: validated.submissionId,
|
|
1362
|
+
existingOutcome: canonical.settlement.outcome
|
|
1363
|
+
});
|
|
1364
|
+
const existingIds = yield* storedUnknownToolCallIds(operation, submission);
|
|
1365
|
+
const known = new Set(existingIds);
|
|
1366
|
+
const merged = [...existingIds, ...validated.toolCallIds.filter((toolCallId) => !known.has(toolCallId))];
|
|
1367
|
+
const idsJson = yield* encodeToolCallIdsText(merged).pipe(Effect.mapError(internalFailure(operation)));
|
|
1368
|
+
yield* sql`
|
|
1369
|
+
UPDATE effect_agent_submissions
|
|
1370
|
+
SET
|
|
1371
|
+
state = 'unknown',
|
|
1372
|
+
unknown_reason = ${submission.unknown_reason ?? validated.reason},
|
|
1373
|
+
unknown_tool_call_ids_json = ${idsJson}
|
|
1374
|
+
WHERE submission_id = ${validated.submissionId}
|
|
1375
|
+
RETURNING *, ${definitionJson(sql)} AS agent_digests_json`.pipe(rows.submissions.write, Effect.mapError(internalFailure(operation)));
|
|
1376
|
+
if (submission.state !== "unknown") yield* retainLifecycle(submission, {
|
|
1377
|
+
_tag: "SubmissionUnknown",
|
|
1378
|
+
submissionId: validated.submissionId
|
|
1379
|
+
});
|
|
1380
|
+
}));
|
|
1381
|
+
yield* hitFailpoint("ledger:mark-unknown:after", operation);
|
|
1382
|
+
});
|
|
1383
|
+
const recordUnknownResolution = Effect.fnUntraced(function* (command) {
|
|
1384
|
+
const operation = "ledger record unknown resolution";
|
|
1385
|
+
const validated = yield* Schema.decodeEffect(Schema.toType(UnknownResolutionCommand))(command).pipe(Effect.mapError(internalFailure(operation)));
|
|
1386
|
+
const resolutionJson = yield* encodeUnknownResolutionText(validated.resolution).pipe(Effect.mapError(internalFailure(operation)));
|
|
1387
|
+
yield* hitFailpoint("ledger:unknown-resolution:before", operation);
|
|
1388
|
+
const intent = yield* inWriteTransaction(operation, Effect.gen(function* () {
|
|
1389
|
+
const submission = yield* requireSubmission(operation, validated.submissionId);
|
|
1390
|
+
if (submission.state === "settled") {
|
|
1391
|
+
if (submission.settled_outcome === null) return yield* corruptionFailure(operation, "effect_agent_submissions", validated.submissionId, "A settled Submission carries no terminal outcome.");
|
|
1392
|
+
if (validated.resolution._tag !== "CompletedWithResult" && validated.resolution._tag !== "NeverHappened") return yield* SettlementConflict.make({
|
|
1393
|
+
submissionId: validated.submissionId,
|
|
1394
|
+
existingOutcome: submission.settled_outcome
|
|
1395
|
+
});
|
|
1396
|
+
}
|
|
1397
|
+
const resolutions = yield* readUnknownResolutions(operation, validated.submissionId);
|
|
1398
|
+
const kind = unknownResolutionKind(validated.resolution);
|
|
1399
|
+
const existing = resolutions.find((row) => row.tool_call_id === validated.toolCallId && row.resolution_kind === kind);
|
|
1400
|
+
const existingIntent = existing === void 0 ? void 0 : yield* unknownResolutionIntentFromRow(operation, existing);
|
|
1401
|
+
if (existingIntent !== void 0 && !equivalentUnknownResolution(existingIntent.resolution, validated.resolution) || existing === void 0 && kind === "execution" && resolutions.some((row) => row.tool_call_id === validated.toolCallId && row.resolution_kind === "factual")) return yield* UnknownResolutionConflict.make({
|
|
1402
|
+
submissionId: validated.submissionId,
|
|
1403
|
+
toolCallId: validated.toolCallId
|
|
1404
|
+
});
|
|
1405
|
+
if (existingIntent === void 0 && kind === "factual") {
|
|
1406
|
+
const runId = runIdForSubmission(validated.submissionId);
|
|
1407
|
+
const found = yield* sql`
|
|
1408
|
+
SELECT ${canonicalRecordJson(sql)} AS record_json FROM effect_agent_canonical_records
|
|
1409
|
+
WHERE thread_id = ${submission.thread_id}
|
|
1410
|
+
AND record_tag = 27
|
|
1411
|
+
AND run_id = ${runKey(sql, sql`${submission.thread_id}`, sql`${JSON.stringify(runId)}`)}
|
|
1412
|
+
AND tool_call_id = ${JSON.stringify(validated.toolCallId)}
|
|
1413
|
+
LIMIT 2
|
|
1414
|
+
`.pipe(Effect.mapError(sqlFailure(operation)));
|
|
1415
|
+
const outcomes = yield* decodeRows(Schema.Array(Schema.Struct({ record_json: BoundedStoredText })), "effect_agent_canonical_records", validated.toolCallId, found).pipe(Effect.mapError(internalFailure(operation)));
|
|
1416
|
+
const result = outcomes[0] === void 0 ? void 0 : (yield* decodeRecordEnvelopeText(outcomes[0].record_json).pipe(Effect.mapError(internalFailure(operation)))).payload;
|
|
1417
|
+
if (outcomes.length > 1 || result !== void 0 && (result._tag !== "ToolCallSettled" || result.runId !== runId || result.toolCallId !== validated.toolCallId)) return yield* corruptionFailure(operation, "effect_agent_canonical_records", validated.toolCallId, "Canonical Tool result identity is inconsistent.");
|
|
1418
|
+
if (result?._tag === "ToolCallSettled" && !unknownResolutionMatchesResult(validated.resolution, result)) return yield* UnknownResolutionConflict.make({
|
|
1419
|
+
submissionId: validated.submissionId,
|
|
1420
|
+
toolCallId: validated.toolCallId
|
|
1421
|
+
});
|
|
1422
|
+
}
|
|
1423
|
+
let resolved;
|
|
1424
|
+
if (existingIntent !== void 0) resolved = existingIntent;
|
|
1425
|
+
else {
|
|
1426
|
+
const now = yield* currentInstant;
|
|
1427
|
+
yield* sql`
|
|
1428
|
+
INSERT INTO effect_agent_unknown_resolutions (
|
|
1429
|
+
submission_id,
|
|
1430
|
+
tool_call_id,
|
|
1431
|
+
resolution_kind,
|
|
1432
|
+
author,
|
|
1433
|
+
reason,
|
|
1434
|
+
resolution_json,
|
|
1435
|
+
resolved_at
|
|
1436
|
+
) VALUES (
|
|
1437
|
+
${validated.submissionId},
|
|
1438
|
+
${validated.toolCallId},
|
|
1439
|
+
${kind},
|
|
1440
|
+
${validated.author},
|
|
1441
|
+
${validated.reason},
|
|
1442
|
+
${resolutionJson},
|
|
1443
|
+
${now.iso}
|
|
1444
|
+
)
|
|
1445
|
+
RETURNING *`.pipe(rows.resolutions.write, Effect.mapError(internalFailure(operation)));
|
|
1446
|
+
yield* recordProgress("control", operation);
|
|
1447
|
+
const resolution = yield* parseStoredJsonText(resolutionJson).pipe(Effect.mapError(internalFailure(operation)));
|
|
1448
|
+
resolved = yield* decodeUnknownResolutionIntent({
|
|
1449
|
+
submissionId: validated.submissionId,
|
|
1450
|
+
toolCallId: validated.toolCallId,
|
|
1451
|
+
author: validated.author,
|
|
1452
|
+
reason: validated.reason,
|
|
1453
|
+
resolution,
|
|
1454
|
+
resolvedAt: now.iso
|
|
1455
|
+
}).pipe(Effect.mapError(internalFailure(operation)));
|
|
1456
|
+
}
|
|
1457
|
+
if (submission.state === "unknown" && submission.unknown_tool_call_ids_json !== null) {
|
|
1458
|
+
const markedIds = yield* storedUnknownToolCallIds(operation, submission);
|
|
1459
|
+
const covering = yield* readUnknownResolutions(operation, validated.submissionId);
|
|
1460
|
+
const coveredIds = new Set(covering.map((row) => row.tool_call_id));
|
|
1461
|
+
if (markedIds.every((toolCallId) => coveredIds.has(toolCallId))) {
|
|
1462
|
+
yield* sql`
|
|
1463
|
+
UPDATE effect_agent_submissions
|
|
1464
|
+
SET
|
|
1465
|
+
state = 'input-applied',
|
|
1466
|
+
unknown_reason = NULL,
|
|
1467
|
+
unknown_tool_call_ids_json = NULL
|
|
1468
|
+
WHERE submission_id = ${validated.submissionId}
|
|
1469
|
+
RETURNING *, ${definitionJson(sql)} AS agent_digests_json`.pipe(rows.submissions.write, Effect.mapError(internalFailure(operation)));
|
|
1470
|
+
yield* retainLifecycle(submission, {
|
|
1471
|
+
_tag: "SubmissionResumed",
|
|
1472
|
+
submissionId: validated.submissionId
|
|
1473
|
+
});
|
|
1474
|
+
}
|
|
1475
|
+
}
|
|
1476
|
+
return resolved;
|
|
1477
|
+
}));
|
|
1478
|
+
yield* hitFailpoint("ledger:unknown-resolution:after", operation);
|
|
1479
|
+
return intent;
|
|
1480
|
+
});
|
|
1481
|
+
const recordChildSettled = Effect.fnUntraced(function* (request) {
|
|
1482
|
+
const operation = "ledger record child settled";
|
|
1483
|
+
const validated = yield* Schema.decodeEffect(Schema.toType(ChildSettledNotification))(request).pipe(Effect.mapError(internalFailure(operation)));
|
|
1484
|
+
yield* hitFailpoint("ledger:child-settled:before", operation);
|
|
1485
|
+
const outcome = yield* inWriteTransaction(operation, Effect.gen(function* () {
|
|
1486
|
+
const parent = yield* requireSubmission(operation, validated.parentSubmissionId);
|
|
1487
|
+
const child = yield* readSubmission(operation, validated.childSubmissionId);
|
|
1488
|
+
const childCanonical = Option.isSome(child) ? yield* readCanonicalSettlement(operation, child.value) : void 0;
|
|
1489
|
+
if (Option.isSome(child) && childCanonical === void 0) return yield* LedgerError.make({
|
|
1490
|
+
operation,
|
|
1491
|
+
message: `Child submission ${validated.childSubmissionId} has no recorded settlement.`
|
|
1492
|
+
});
|
|
1493
|
+
const now = yield* currentInstant;
|
|
1494
|
+
if ((yield* sql`
|
|
1495
|
+
INSERT INTO effect_agent_child_settlements (
|
|
1496
|
+
parent_submission_id,
|
|
1497
|
+
child_submission_id,
|
|
1498
|
+
child_outcome,
|
|
1499
|
+
recorded_at
|
|
1500
|
+
) VALUES (
|
|
1501
|
+
${validated.parentSubmissionId},
|
|
1502
|
+
${validated.childSubmissionId},
|
|
1503
|
+
${childCanonical?.settlement.outcome ?? null},
|
|
1504
|
+
${now.iso}
|
|
1505
|
+
)
|
|
1506
|
+
ON CONFLICT (parent_submission_id, child_submission_id) DO NOTHING
|
|
1507
|
+
RETURNING *`.pipe(rows.childSettlements.write, Effect.mapError(internalFailure(operation)))).length > 0) yield* recordProgress("control", operation);
|
|
1508
|
+
if (parent.state !== "suspended" || parent.suspended_reason_json === null) return NOT_WAITING;
|
|
1509
|
+
const reason = yield* Schema.decodeEffect(Schema.fromJsonString(SuspensionReason))(parent.suspended_reason_json).pipe(Effect.mapError((error) => corruptionFailure(operation, "effect_agent_submissions", parent.submission_id, error.message)));
|
|
1510
|
+
if (reason._tag !== "WaitingForChild") return NOT_WAITING;
|
|
1511
|
+
if (!reason.children.some((entry) => entry.childSubmissionId === validated.childSubmissionId)) return NOT_WAITING;
|
|
1512
|
+
const markers = yield* readChildSettlementMarkers(operation, validated.parentSubmissionId);
|
|
1513
|
+
const markerChildren = new Set(markers.map((row) => row.child_submission_id));
|
|
1514
|
+
for (const entry of reason.children) if (!(yield* childProvablySettled(operation, markerChildren, entry.childSubmissionId))) return STILL_WAITING;
|
|
1515
|
+
yield* sql`
|
|
1516
|
+
UPDATE effect_agent_submissions
|
|
1517
|
+
SET
|
|
1518
|
+
state = 'input-applied',
|
|
1519
|
+
suspended_reason_json = NULL,
|
|
1520
|
+
suspended_at = NULL
|
|
1521
|
+
WHERE submission_id = ${validated.parentSubmissionId}
|
|
1522
|
+
RETURNING *, ${definitionJson(sql)} AS agent_digests_json`.pipe(rows.submissions.write, Effect.mapError(internalFailure(operation)));
|
|
1523
|
+
yield* retainLifecycle(parent, {
|
|
1524
|
+
_tag: "SubmissionResumed",
|
|
1525
|
+
submissionId: validated.parentSubmissionId
|
|
1526
|
+
});
|
|
1527
|
+
return WOKEN;
|
|
1528
|
+
}));
|
|
1529
|
+
yield* hitFailpoint("ledger:child-settled:after", operation);
|
|
1530
|
+
return outcome;
|
|
1531
|
+
});
|
|
1532
|
+
const reserveChildBudget = Effect.fnUntraced(function* (request) {
|
|
1533
|
+
const operation = "ledger reserve child budget";
|
|
1534
|
+
const validated = yield* Schema.decodeEffect(Schema.toType(ChildBudgetReservationRequest))(request).pipe(Effect.mapError(internalFailure(operation)));
|
|
1535
|
+
const allocationJson = yield* encodePersistedJsonText(validated.allocation).pipe(Effect.mapError(internalFailure(operation)));
|
|
1536
|
+
yield* hitFailpoint("ledger:child-reservation:before", operation);
|
|
1537
|
+
const reserved = yield* inWriteTransaction(operation, Effect.gen(function* () {
|
|
1538
|
+
const existing = yield* readChildReservation(operation, validated.reservationId);
|
|
1539
|
+
if (Option.isSome(existing)) {
|
|
1540
|
+
const existingSnapshot = yield* childReservationSnapshotFromRow(operation, existing.value);
|
|
1541
|
+
if (!(existing.value.parent_submission_id === validated.parentSubmissionId && existing.value.parent_tool_call_id === validated.parentToolCallId && existing.value.allocation_digest === validated.allocationDigest && equivalentPersistedJson(existingSnapshot.allocation, validated.allocation))) return yield* ChildReservationConflict.make({
|
|
1542
|
+
reservationId: validated.reservationId,
|
|
1543
|
+
status: existing.value.status,
|
|
1544
|
+
message: "A reservation with this identity exists with a different parent Tool Call or allocation."
|
|
1545
|
+
});
|
|
1546
|
+
return ReservedChildBudget.make({
|
|
1547
|
+
reservation: existingSnapshot,
|
|
1548
|
+
replayed: true
|
|
1549
|
+
});
|
|
1550
|
+
}
|
|
1551
|
+
const collision = yield* readChildReservationForCall(operation, validated.parentSubmissionId, validated.parentToolCallId);
|
|
1552
|
+
if (Option.isSome(collision)) return yield* ChildReservationConflict.make({
|
|
1553
|
+
reservationId: validated.reservationId,
|
|
1554
|
+
status: collision.value.status,
|
|
1555
|
+
message: `Parent Tool Call ${validated.parentToolCallId} already owns reservation ${collision.value.reservation_id}.`
|
|
1556
|
+
});
|
|
1557
|
+
const parent = yield* requireSubmission(operation, validated.parentSubmissionId);
|
|
1558
|
+
yield* requireOwner(operation, parent);
|
|
1559
|
+
const now = yield* currentInstant;
|
|
1560
|
+
yield* sql`
|
|
1561
|
+
INSERT INTO effect_agent_child_reservations (
|
|
1562
|
+
reservation_id,
|
|
1563
|
+
parent_submission_id,
|
|
1564
|
+
parent_tool_call_id,
|
|
1565
|
+
status,
|
|
1566
|
+
allocation_json,
|
|
1567
|
+
allocation_digest,
|
|
1568
|
+
reserved_at
|
|
1569
|
+
) VALUES (
|
|
1570
|
+
${validated.reservationId},
|
|
1571
|
+
${validated.parentSubmissionId},
|
|
1572
|
+
${validated.parentToolCallId},
|
|
1573
|
+
'reserved',
|
|
1574
|
+
${allocationJson},
|
|
1575
|
+
${validated.allocationDigest},
|
|
1576
|
+
${now.iso}
|
|
1577
|
+
)
|
|
1578
|
+
RETURNING *`.pipe(rows.childReservations.write, Effect.mapError(internalFailure(operation)));
|
|
1579
|
+
const inserted = yield* readChildReservation(operation, validated.reservationId);
|
|
1580
|
+
if (Option.isNone(inserted)) return yield* corruptionFailure(operation, "effect_agent_child_reservations", validated.reservationId, "An inserted child reservation row is missing inside its own transaction.");
|
|
1581
|
+
return ReservedChildBudget.make({
|
|
1582
|
+
reservation: yield* childReservationSnapshotFromRow(operation, inserted.value),
|
|
1583
|
+
replayed: false
|
|
1584
|
+
});
|
|
1585
|
+
}));
|
|
1586
|
+
yield* hitFailpoint("ledger:child-reservation:after", operation);
|
|
1587
|
+
return reserved;
|
|
1588
|
+
});
|
|
1589
|
+
const attachChildToReservation = Effect.fnUntraced(function* (request) {
|
|
1590
|
+
const operation = "ledger attach child to reservation";
|
|
1591
|
+
const validated = yield* Schema.decodeEffect(Schema.toType(AttachChildToReservationRequest))(request).pipe(Effect.mapError(internalFailure(operation)));
|
|
1592
|
+
yield* hitFailpoint("ledger:child-attach:before", operation);
|
|
1593
|
+
const attached = yield* inWriteTransaction(operation, Effect.gen(function* () {
|
|
1594
|
+
const existing = yield* readChildReservation(operation, validated.reservationId);
|
|
1595
|
+
if (Option.isNone(existing)) return yield* LedgerError.make({
|
|
1596
|
+
operation,
|
|
1597
|
+
message: `Unknown child reservation ${validated.reservationId}.`
|
|
1598
|
+
});
|
|
1599
|
+
if (existing.value.child_submission_id !== null) {
|
|
1600
|
+
if (existing.value.child_submission_id === validated.childSubmissionId) return yield* childReservationSnapshotFromRow(operation, existing.value);
|
|
1601
|
+
return yield* ChildReservationConflict.make({
|
|
1602
|
+
reservationId: validated.reservationId,
|
|
1603
|
+
status: existing.value.status,
|
|
1604
|
+
message: `Reservation ${validated.reservationId} already records child ${existing.value.child_submission_id}.`
|
|
1605
|
+
});
|
|
1606
|
+
}
|
|
1607
|
+
const parent = yield* requireSubmission(operation, existing.value.parent_submission_id);
|
|
1608
|
+
yield* requireOwner(operation, parent);
|
|
1609
|
+
if (existing.value.status !== "reserved") return yield* ChildReservationConflict.make({
|
|
1610
|
+
reservationId: validated.reservationId,
|
|
1611
|
+
status: existing.value.status,
|
|
1612
|
+
message: `Cannot attach a child to a ${existing.value.status} reservation.`
|
|
1613
|
+
});
|
|
1614
|
+
yield* sql`
|
|
1615
|
+
UPDATE effect_agent_child_reservations
|
|
1616
|
+
SET child_submission_id = ${validated.childSubmissionId}
|
|
1617
|
+
WHERE reservation_id = ${validated.reservationId}
|
|
1618
|
+
RETURNING *`.pipe(rows.childReservations.write, Effect.mapError(internalFailure(operation)));
|
|
1619
|
+
const updated = yield* readChildReservation(operation, validated.reservationId);
|
|
1620
|
+
if (Option.isNone(updated)) return yield* corruptionFailure(operation, "effect_agent_child_reservations", validated.reservationId, "An updated child reservation row is missing inside its own transaction.");
|
|
1621
|
+
return yield* childReservationSnapshotFromRow(operation, updated.value);
|
|
1622
|
+
}));
|
|
1623
|
+
yield* hitFailpoint("ledger:child-attach:after", operation);
|
|
1624
|
+
return attached;
|
|
1625
|
+
});
|
|
1626
|
+
const beginChildBudgetRelease = Effect.fnUntraced(function* (request) {
|
|
1627
|
+
const operation = "ledger begin child budget release";
|
|
1628
|
+
const validated = yield* Schema.decodeEffect(Schema.toType(BeginChildBudgetReleaseRequest))(request).pipe(Effect.mapError(internalFailure(operation)));
|
|
1629
|
+
const accountingJson = yield* encodePersistedJsonText(validated.accounting).pipe(Effect.mapError(internalFailure(operation)));
|
|
1630
|
+
yield* hitFailpoint("ledger:child-release-pending:before", operation);
|
|
1631
|
+
const frozen = yield* inWriteTransaction(operation, Effect.gen(function* () {
|
|
1632
|
+
const existing = yield* readChildReservation(operation, validated.reservationId);
|
|
1633
|
+
if (Option.isNone(existing)) return yield* LedgerError.make({
|
|
1634
|
+
operation,
|
|
1635
|
+
message: `Unknown child reservation ${validated.reservationId}.`
|
|
1636
|
+
});
|
|
1637
|
+
if (existing.value.status !== "reserved") {
|
|
1638
|
+
const existingSnapshot = yield* childReservationSnapshotFromRow(operation, existing.value);
|
|
1639
|
+
if (existingSnapshot.accounting !== void 0 && equivalentPersistedJson(existingSnapshot.accounting, validated.accounting)) return existingSnapshot;
|
|
1640
|
+
return yield* ChildReservationConflict.make({
|
|
1641
|
+
reservationId: validated.reservationId,
|
|
1642
|
+
status: existing.value.status,
|
|
1643
|
+
message: "A different accounting decision is already frozen for this reservation."
|
|
1644
|
+
});
|
|
1645
|
+
}
|
|
1646
|
+
const now = yield* currentInstant;
|
|
1647
|
+
yield* sql`
|
|
1648
|
+
UPDATE effect_agent_child_reservations
|
|
1649
|
+
SET
|
|
1650
|
+
status = 'releasePending',
|
|
1651
|
+
accounting_json = ${accountingJson},
|
|
1652
|
+
release_began_at = ${now.iso}
|
|
1653
|
+
WHERE reservation_id = ${validated.reservationId}
|
|
1654
|
+
RETURNING *`.pipe(rows.childReservations.write, Effect.mapError(internalFailure(operation)));
|
|
1655
|
+
const updated = yield* readChildReservation(operation, validated.reservationId);
|
|
1656
|
+
if (Option.isNone(updated)) return yield* corruptionFailure(operation, "effect_agent_child_reservations", validated.reservationId, "An updated child reservation row is missing inside its own transaction.");
|
|
1657
|
+
return yield* childReservationSnapshotFromRow(operation, updated.value);
|
|
1658
|
+
}));
|
|
1659
|
+
yield* hitFailpoint("ledger:child-release-pending:after", operation);
|
|
1660
|
+
return frozen;
|
|
1661
|
+
});
|
|
1662
|
+
const releaseChildBudget = Effect.fnUntraced(function* (request) {
|
|
1663
|
+
const operation = "ledger release child budget";
|
|
1664
|
+
const validated = yield* Schema.decodeEffect(Schema.toType(ReleaseChildBudgetRequest))(request).pipe(Effect.mapError(internalFailure(operation)));
|
|
1665
|
+
yield* hitFailpoint("ledger:child-release:before", operation);
|
|
1666
|
+
const released = yield* inWriteTransaction(operation, Effect.gen(function* () {
|
|
1667
|
+
const existing = yield* readChildReservation(operation, validated.reservationId);
|
|
1668
|
+
if (Option.isNone(existing)) return yield* LedgerError.make({
|
|
1669
|
+
operation,
|
|
1670
|
+
message: `Unknown child reservation ${validated.reservationId}.`
|
|
1671
|
+
});
|
|
1672
|
+
if (existing.value.status === "released") return yield* childReservationSnapshotFromRow(operation, existing.value);
|
|
1673
|
+
if (existing.value.status !== "releasePending") return yield* ChildReservationConflict.make({
|
|
1674
|
+
reservationId: validated.reservationId,
|
|
1675
|
+
status: existing.value.status,
|
|
1676
|
+
message: "Cannot release a reservation whose accounting decision is not frozen."
|
|
1677
|
+
});
|
|
1678
|
+
const now = yield* currentInstant;
|
|
1679
|
+
yield* sql`
|
|
1680
|
+
UPDATE effect_agent_child_reservations
|
|
1681
|
+
SET status = 'released', released_at = ${now.iso}
|
|
1682
|
+
WHERE reservation_id = ${validated.reservationId}
|
|
1683
|
+
RETURNING *`.pipe(rows.childReservations.write, Effect.mapError(internalFailure(operation)));
|
|
1684
|
+
const updated = yield* readChildReservation(operation, validated.reservationId);
|
|
1685
|
+
if (Option.isNone(updated)) return yield* corruptionFailure(operation, "effect_agent_child_reservations", validated.reservationId, "An updated child reservation row is missing inside its own transaction.");
|
|
1686
|
+
return yield* childReservationSnapshotFromRow(operation, updated.value);
|
|
1687
|
+
}));
|
|
1688
|
+
yield* hitFailpoint("ledger:child-release:after", operation);
|
|
1689
|
+
return released;
|
|
1690
|
+
});
|
|
1691
|
+
const scanPage = Effect.fnUntraced(function* (cursor) {
|
|
1692
|
+
const operation = "ledger scan nonterminal";
|
|
1693
|
+
const rows = yield* (cursor === void 0 ? sql`
|
|
1694
|
+
SELECT submission_id AS "submissionId", thread_id AS "threadId",
|
|
1695
|
+
queue_sequence AS "queueSequence", principal, idempotency_key AS "idempotencyKey",
|
|
1696
|
+
deployment_id AS "deploymentId", receipt_id AS "receiptId", state
|
|
1697
|
+
FROM effect_agent_submissions
|
|
1698
|
+
WHERE state <> 'settled'
|
|
1699
|
+
ORDER BY thread_id ASC, queue_sequence ASC
|
|
1700
|
+
LIMIT ${SCAN_PAGE_SIZE}
|
|
1701
|
+
` : sql`
|
|
1702
|
+
SELECT submission_id AS "submissionId", thread_id AS "threadId",
|
|
1703
|
+
queue_sequence AS "queueSequence", principal, idempotency_key AS "idempotencyKey",
|
|
1704
|
+
deployment_id AS "deploymentId", receipt_id AS "receiptId", state
|
|
1705
|
+
FROM effect_agent_submissions
|
|
1706
|
+
WHERE state <> 'settled'
|
|
1707
|
+
AND (thread_id, queue_sequence) > (${cursor.threadId}, ${cursor.queueSequence})
|
|
1708
|
+
ORDER BY thread_id ASC, queue_sequence ASC
|
|
1709
|
+
LIMIT ${SCAN_PAGE_SIZE}
|
|
1710
|
+
`).pipe(Effect.mapError(sqlFailure(operation)));
|
|
1711
|
+
const decoded = yield* decodeRows(SubmissionWorkItems, "effect_agent_submissions", "nonterminal_scan", rows, "SubmissionWorkItem").pipe(Effect.mapError(internalFailure(operation)));
|
|
1712
|
+
const last = decoded[decoded.length - 1];
|
|
1713
|
+
return [decoded, last === void 0 || decoded.length < SCAN_PAGE_SIZE ? Option.none() : Option.some({
|
|
1714
|
+
threadId: last.threadId,
|
|
1715
|
+
queueSequence: last.queueSequence
|
|
1716
|
+
})];
|
|
1717
|
+
});
|
|
1718
|
+
const activeNonterminal = cached(workRows.matching("nonterminal", (row) => row.state !== "settled", sql`SELECT submission_id, thread_id, queue_sequence, principal, idempotency_key,
|
|
1719
|
+
deployment_id, receipt_id, state
|
|
1720
|
+
FROM effect_agent_submissions WHERE state <> 'settled' LIMIT 129`, 128), "ledger scan nonterminal");
|
|
1721
|
+
const boundedNonterminal = state.read(Effect.gen(function* () {
|
|
1722
|
+
const active = yield* activeNonterminal;
|
|
1723
|
+
if (active.length > 128) return void 0;
|
|
1724
|
+
const sorted = [...active].sort((left, right) => left.thread_id < right.thread_id ? -1 : left.thread_id > right.thread_id ? 1 : left.queue_sequence - right.queue_sequence);
|
|
1725
|
+
return yield* decodeSubmissionWorkItems(sorted.map((row) => ({
|
|
1726
|
+
submissionId: row.submission_id,
|
|
1727
|
+
threadId: row.thread_id,
|
|
1728
|
+
queueSequence: row.queue_sequence,
|
|
1729
|
+
principal: row.principal,
|
|
1730
|
+
idempotencyKey: row.idempotency_key,
|
|
1731
|
+
deploymentId: row.deployment_id,
|
|
1732
|
+
receiptId: row.receipt_id,
|
|
1733
|
+
state: row.state
|
|
1734
|
+
}))).pipe(Effect.mapError(internalFailure("ledger scan nonterminal")));
|
|
1735
|
+
}));
|
|
1736
|
+
const pagedNonterminal = Stream.paginate(void 0, scanPage);
|
|
1737
|
+
const scanNonterminal = Stream.unwrap(Effect.map(boundedNonterminal, (work) => work === void 0 ? pagedNonterminal : Stream.fromIterable(work)));
|
|
1738
|
+
const listNonterminal = Effect.filterOrElse(boundedNonterminal, (work) => work !== void 0, () => Stream.runCollect(pagedNonterminal));
|
|
1739
|
+
const readAbortIntentForSubmission = Effect.fnUntraced(function* (request) {
|
|
1740
|
+
const operation = "ledger read abort intent";
|
|
1741
|
+
const validated = yield* decodeAbortIntentRequestType(request).pipe(Effect.mapError(internalFailure(operation)));
|
|
1742
|
+
return yield* state.read(Effect.gen(function* () {
|
|
1743
|
+
const submission = yield* requireSubmission(operation, validated.submissionId);
|
|
1744
|
+
const intent = yield* readAbortIntent(operation, validated.submissionId);
|
|
1745
|
+
return Option.isNone(intent) ? void 0 : yield* abortIntentFromRow(operation, submission, validated.submissionId, intent.value);
|
|
1746
|
+
}));
|
|
1747
|
+
});
|
|
1748
|
+
const loadRecoverySnapshot = Effect.fnUntraced(function* (request) {
|
|
1749
|
+
const operation = "ledger load recovery snapshot";
|
|
1750
|
+
const validated = yield* decodeRecoverySnapshotRequestType(request).pipe(Effect.mapError(internalFailure(operation)));
|
|
1751
|
+
return yield* state.read(Effect.gen(function* () {
|
|
1752
|
+
const submissionRow = yield* requireSubmission(operation, validated.submissionId);
|
|
1753
|
+
const submission = yield* decodeSubmissionSnapshot(operation, submissionRow);
|
|
1754
|
+
let inputApplied;
|
|
1755
|
+
if (submissionRow.input_applied_record_id !== null && submissionRow.input_applied_sequence !== null) inputApplied = yield* decodeInputAppliedMarker({
|
|
1756
|
+
recordId: submissionRow.input_applied_record_id,
|
|
1757
|
+
sequence: submissionRow.input_applied_sequence
|
|
1758
|
+
}).pipe(Effect.mapError(internalFailure(operation)));
|
|
1759
|
+
let abortIntent;
|
|
1760
|
+
const abortRow = yield* readAbortIntent(operation, validated.submissionId);
|
|
1761
|
+
if (Option.isSome(abortRow)) abortIntent = yield* abortIntentFromRow(operation, submissionRow, validated.submissionId, abortRow.value);
|
|
1762
|
+
const joinRows = (yield* cached(rows.submissions.by("joined_host_submission_id", validated.submissionId), operation)).filter((row) => row.joined_host_submission_id === validated.submissionId).sort((a, b) => a.queue_sequence - b.queue_sequence);
|
|
1763
|
+
const joins = [];
|
|
1764
|
+
for (const row of joinRows) joins.push(yield* decodeJoinSnapshot({
|
|
1765
|
+
submissionId: row.submission_id,
|
|
1766
|
+
state: row.state,
|
|
1767
|
+
hostSubmissionId: validated.submissionId
|
|
1768
|
+
}).pipe(Effect.mapError(internalFailure(operation))));
|
|
1769
|
+
let hostSubmissionId;
|
|
1770
|
+
if (submissionRow.joined_host_submission_id !== null) hostSubmissionId = yield* decodeSubmissionId(submissionRow.joined_host_submission_id).pipe(Effect.mapError(internalFailure(operation)));
|
|
1771
|
+
let suspension;
|
|
1772
|
+
if (submissionRow.suspended_reason_json !== null && submissionRow.suspended_at !== null) {
|
|
1773
|
+
const reason = yield* parseStoredJsonText(submissionRow.suspended_reason_json).pipe(Effect.mapError((error) => corruptionFailure(operation, "effect_agent_submissions", validated.submissionId, error.message)));
|
|
1774
|
+
suspension = yield* decodeSuspensionSnapshot({
|
|
1775
|
+
reason,
|
|
1776
|
+
suspendedAt: submissionRow.suspended_at
|
|
1777
|
+
}).pipe(Effect.mapError((error) => corruptionFailure(operation, "effect_agent_submissions", validated.submissionId, error.message)));
|
|
1778
|
+
}
|
|
1779
|
+
const decisionRows = yield* readApprovalDecisions(operation, validated.submissionId);
|
|
1780
|
+
const approvalDecisions = [];
|
|
1781
|
+
for (const row of decisionRows) approvalDecisions.push(yield* approvalIntentFromRow(operation, row));
|
|
1782
|
+
const resolutionRows = yield* readUnknownResolutions(operation, validated.submissionId);
|
|
1783
|
+
const unknownResolutions = [];
|
|
1784
|
+
for (const row of resolutionRows) unknownResolutions.push(yield* unknownResolutionIntentFromRow(operation, row));
|
|
1785
|
+
const childReservationRows = (yield* cached(rows.childReservations.by("parent_submission_id", validated.submissionId), operation)).filter((row) => row.parent_submission_id === validated.submissionId).sort((a, b) => a.parent_tool_call_id.localeCompare(b.parent_tool_call_id));
|
|
1786
|
+
const childReservations = [];
|
|
1787
|
+
for (const row of childReservationRows) childReservations.push(yield* childReservationSnapshotFromRow(operation, row));
|
|
1788
|
+
const markers = yield* readChildSettlementMarkers(operation, validated.submissionId);
|
|
1789
|
+
const markersByChild = new Map(markers.map((row) => [row.child_submission_id, row]));
|
|
1790
|
+
const childAttachments = [];
|
|
1791
|
+
for (const row of childReservationRows) {
|
|
1792
|
+
if (row.child_submission_id === null) continue;
|
|
1793
|
+
const child = yield* readSubmission(operation, row.child_submission_id);
|
|
1794
|
+
if (Option.isSome(child)) {
|
|
1795
|
+
childAttachments.push(yield* decodeChildAttachmentSnapshot({
|
|
1796
|
+
toolCallId: row.parent_tool_call_id,
|
|
1797
|
+
childSubmissionId: row.child_submission_id,
|
|
1798
|
+
childState: child.value.state,
|
|
1799
|
+
...child.value.settled_outcome === null ? {} : { childOutcome: child.value.settled_outcome }
|
|
1800
|
+
}).pipe(Effect.mapError(internalFailure(operation))));
|
|
1801
|
+
continue;
|
|
1802
|
+
}
|
|
1803
|
+
const marker = markersByChild.get(row.child_submission_id);
|
|
1804
|
+
if (marker === void 0) continue;
|
|
1805
|
+
childAttachments.push(yield* decodeChildAttachmentSnapshot({
|
|
1806
|
+
toolCallId: row.parent_tool_call_id,
|
|
1807
|
+
childSubmissionId: row.child_submission_id,
|
|
1808
|
+
childState: "settled",
|
|
1809
|
+
...marker.child_outcome === null ? {} : { childOutcome: marker.child_outcome }
|
|
1810
|
+
}).pipe(Effect.mapError(internalFailure(operation))));
|
|
1811
|
+
}
|
|
1812
|
+
let parentLinkage;
|
|
1813
|
+
if (submissionRow.parent_submission_id !== null && submissionRow.parent_tool_call_id !== null) parentLinkage = yield* decodeParentLinkage({
|
|
1814
|
+
parentSubmissionId: submissionRow.parent_submission_id,
|
|
1815
|
+
parentToolCallId: submissionRow.parent_tool_call_id
|
|
1816
|
+
}).pipe(Effect.mapError(internalFailure(operation)));
|
|
1817
|
+
return RecoverySnapshot.make({
|
|
1818
|
+
submission,
|
|
1819
|
+
joins,
|
|
1820
|
+
approvalDecisions,
|
|
1821
|
+
unknownResolutions,
|
|
1822
|
+
childReservations,
|
|
1823
|
+
childAttachments,
|
|
1824
|
+
...parentLinkage === void 0 ? {} : { parentLinkage },
|
|
1825
|
+
...hostSubmissionId === void 0 ? {} : { hostSubmissionId },
|
|
1826
|
+
...suspension === void 0 ? {} : { suspension },
|
|
1827
|
+
hasOwner: owner.hasOwner(submissionRow.thread_id, submissionRow.submission_id),
|
|
1828
|
+
...inputApplied === void 0 ? {} : { inputApplied },
|
|
1829
|
+
...abortIntent === void 0 ? {} : { abortIntent }
|
|
1830
|
+
});
|
|
1831
|
+
}));
|
|
1832
|
+
});
|
|
1833
|
+
return Context.make(SubmissionLedger, SubmissionLedger.of({
|
|
1834
|
+
capabilities,
|
|
1835
|
+
admit,
|
|
1836
|
+
markReady,
|
|
1837
|
+
lookup,
|
|
1838
|
+
resolveFundingOwner,
|
|
1839
|
+
resolveAdmission,
|
|
1840
|
+
selectHead,
|
|
1841
|
+
markInputApplied,
|
|
1842
|
+
appendInput,
|
|
1843
|
+
finalizeSettlement: (request) => owner.withMutation(finalizeSettlement(request)),
|
|
1844
|
+
requestAbort,
|
|
1845
|
+
stopWorker,
|
|
1846
|
+
inspectWorker,
|
|
1847
|
+
claimJoining,
|
|
1848
|
+
markJoined,
|
|
1849
|
+
revertJoining,
|
|
1850
|
+
suspend: (request) => owner.withMutation(suspend(request)),
|
|
1851
|
+
recordApprovalDecision,
|
|
1852
|
+
markUnknown,
|
|
1853
|
+
recordUnknownResolution,
|
|
1854
|
+
recordChildSettled,
|
|
1855
|
+
reserveChildBudget,
|
|
1856
|
+
attachChildToReservation,
|
|
1857
|
+
beginChildBudgetRelease,
|
|
1858
|
+
releaseChildBudget,
|
|
1859
|
+
scanNonterminal,
|
|
1860
|
+
listNonterminal,
|
|
1861
|
+
loadRecoverySnapshot,
|
|
1862
|
+
readAbortIntent: readAbortIntentForSubmission
|
|
1863
|
+
})).pipe(Context.add(StorageOwner, owner), Context.add(SettlementPublisher, { publish }));
|
|
1864
|
+
});
|
|
1865
|
+
/**
|
|
1866
|
+
* Durable Object SubmissionLedger implementation sharing the journal's private SQLite
|
|
1867
|
+
* database, storage-backed transactions, and scoped local owner.
|
|
1868
|
+
* Configuration, failpoint, SQL, Digest, and SecureRandom authority stay visible in the input channel.
|
|
1869
|
+
*/
|
|
1870
|
+
const submissionLedgerLayer = Layer.effectContext(makeServices());
|
|
1871
|
+
/**
|
|
1872
|
+
* A composition-root convenience Layer for the durable Submission Ledger. Point it at the
|
|
1873
|
+
* same `ctx.storage` as the ThreadStore so both share the same scoped storage owner.
|
|
1874
|
+
*/
|
|
1875
|
+
const ledgerLayer = (options) => Layer.unwrap(Effect.map(DoStorageConfig, (config) => submissionLedgerLayer.pipe(Layer.provide(Layer.mergeAll(Layer.succeed(DoStorageConfig)(config), storageFailpointLayer(options), SqliteClient.layer({ storage: options.storage }), BrowserCrypto.layer))))).pipe(Layer.provide(storageConfigLayer(options)));
|
|
1876
|
+
export { ledgerLayer as n, submissionLedgerLayer as r, DoSubmissionLedger_exports as t };
|
|
1877
|
+
|
|
1878
|
+
//# sourceMappingURL=DoSubmissionLedger-Oq5OstxL.mjs.map
|