@effect-agent/storage-memory 0.1.0-beta.8 → 0.1.0-beta.81
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/MemoryMessageDeliveryStore.d.mts +15 -0
- package/dist/MemoryMessageDeliveryStore.mjs +144 -0
- package/dist/MemoryMessageDeliveryStore.mjs.map +1 -0
- package/dist/MemoryScheduleStore.d.mts +10 -0
- package/dist/MemoryScheduleStore.mjs +169 -0
- package/dist/MemoryScheduleStore.mjs.map +1 -0
- package/dist/MemorySemanticIndex.d.mts +21 -0
- package/dist/MemorySemanticIndex.mjs +222 -0
- package/dist/MemorySemanticIndex.mjs.map +1 -0
- package/dist/MemorySubmissionLedger.d.mts +24 -0
- package/dist/MemorySubmissionLedger.mjs +1058 -0
- package/dist/MemorySubmissionLedger.mjs.map +1 -0
- package/dist/MemorySubscriptionStore.d.mts +9 -0
- package/dist/MemorySubscriptionStore.mjs +849 -0
- package/dist/MemorySubscriptionStore.mjs.map +1 -0
- package/dist/MemoryThreadStore.d.mts +17 -0
- package/dist/MemoryThreadStore.mjs +377 -0
- package/dist/MemoryThreadStore.mjs.map +1 -0
- package/dist/index.d.mts +7 -30
- package/dist/index.mjs +7 -1298
- package/dist/rolldown-runtime-D7D4PA-g.mjs +13 -0
- package/package.json +1 -45
- package/src/MemoryMessageDeliveryStore.ts +285 -0
- package/src/MemoryScheduleStore.ts +328 -0
- package/src/MemorySemanticIndex.ts +357 -0
- package/src/{memory-ledger.ts → MemorySubmissionLedger.ts} +478 -86
- package/src/MemorySubscriptionStore.ts +1549 -0
- package/src/MemoryThreadStore.ts +766 -0
- package/src/index.ts +6 -2
- package/dist/index.mjs.map +0 -1
- package/dist/testing.d.mts +0 -2
- package/dist/testing.mjs +0 -2
- package/src/memory-storage.ts +0 -614
- package/src/testing.ts +0 -10
|
@@ -0,0 +1,1058 @@
|
|
|
1
|
+
import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
|
|
2
|
+
import { Cause, Clock, DateTime, Duration, Effect, Exit, Fiber, Layer, Option, Ref, Schema, Stream } from "effect";
|
|
3
|
+
import { AttemptId, ReceiptId, SubmissionId } from "@effect-agent/core/Identifiers";
|
|
4
|
+
import { MessageAdmission } from "@effect-agent/core/Messaging";
|
|
5
|
+
import { PersistedJson, ProducerEpoch, WorkerAdmission } from "@effect-agent/thread/Records";
|
|
6
|
+
import { AbortCommand, AbortIntent, AbortIntentRequest, AdmissionAdmitted, AdmissionConflict, AdmissionIndeterminate, AdmissionNotAdmitted, AdmissionPolicyError, AdmissionRequest, AdmissionResult, ApprovalConflict, ApprovalDecisionCommand, ApprovalDecisionIntent, AttachChildToReservationRequest, BeginChildBudgetReleaseRequest, ChildAttachmentSnapshot, ChildBudgetReservationRequest, ChildBudgetReservationSnapshot, ChildReservationConflict, ChildSettledNotification, Claim, ClaimJoiningRequest, ClaimRequest, DEFAULT_OWNERSHIP_LEASE_DURATION, InputAppliedMarker, JoinSnapshot, JoinedToHost, JoiningClaim, LedgerCapabilities, LedgerError, MarkInputAppliedRequest, MarkJoinedRequest, MarkReadyRequest, MarkUnknownRequest, OwnershipLost, OwnershipRenewal, OwnershipSnapshot, OwnershipToken, QueueSequence, RecoverySnapshot, RecoverySnapshotRequest, ReleaseChildBudgetRequest, ReleaseOwnershipRequest, RenewOwnershipRequest, ReservedChildBudget, ReservedSettlement, RevertJoiningRequest, Settlement, SettlementConflict, SettlementFinalization, SettlementReservation, SettlementReservationSnapshot, SubmissionAdmissionFence, SubmissionLedger, SubmissionLookup, SubmissionLookupByKey, SubmissionSnapshot, SuspendRequest, SuspensionSnapshot, UnknownResolution, UnknownResolutionCommand, UnknownResolutionConflict, UnknownResolutionIntent, settlementFailureFromRecord } from "@effect-agent/thread/SubmissionLedger";
|
|
7
|
+
//#region src/MemorySubmissionLedger.ts
|
|
8
|
+
var MemorySubmissionLedger_exports = /* @__PURE__ */ __exportAll({
|
|
9
|
+
MemorySubmissionLedgerLive: () => MemorySubmissionLedgerLive,
|
|
10
|
+
memorySubmissionLedgerLayer: () => memorySubmissionLedgerLayer
|
|
11
|
+
});
|
|
12
|
+
const MAX_SUBMISSIONS = 65536;
|
|
13
|
+
/**
|
|
14
|
+
* Lifecycle ordering used to advance-but-never-regress the operational state marker: a reclaimed
|
|
15
|
+
* Attempt must not erase progress markers (input-applied, terminalizing) that an earlier Attempt
|
|
16
|
+
* already committed.
|
|
17
|
+
*/
|
|
18
|
+
const STATE_RANK = {
|
|
19
|
+
admitted: 0,
|
|
20
|
+
ready: 1,
|
|
21
|
+
joining: 2,
|
|
22
|
+
joined: 3,
|
|
23
|
+
running: 4,
|
|
24
|
+
"input-applied": 5,
|
|
25
|
+
suspended: 6,
|
|
26
|
+
unknown: 7,
|
|
27
|
+
terminalizing: 8,
|
|
28
|
+
settled: 9
|
|
29
|
+
};
|
|
30
|
+
/**
|
|
31
|
+
* States in which `claim` never grants the head: the lane is host-owned (`joining`/`joined`)
|
|
32
|
+
* or durably suspended rather than worker-claimable. Unknown heads are checked against abort
|
|
33
|
+
* intent separately: abort authorizes cleanup and settlement, never ordinary Tool replay.
|
|
34
|
+
*/
|
|
35
|
+
const BLOCKED_HEAD_STATES = /* @__PURE__ */ new Set([
|
|
36
|
+
"joining",
|
|
37
|
+
"joined",
|
|
38
|
+
"suspended"
|
|
39
|
+
]);
|
|
40
|
+
const failure = (error) => ({
|
|
41
|
+
_tag: "failure",
|
|
42
|
+
error
|
|
43
|
+
});
|
|
44
|
+
const success = (value) => ({
|
|
45
|
+
_tag: "success",
|
|
46
|
+
value
|
|
47
|
+
});
|
|
48
|
+
const ledgerError = (operation, message, cause) => cause === void 0 ? LedgerError.make({
|
|
49
|
+
operation,
|
|
50
|
+
message
|
|
51
|
+
}) : LedgerError.make({
|
|
52
|
+
operation,
|
|
53
|
+
message,
|
|
54
|
+
cause
|
|
55
|
+
});
|
|
56
|
+
const validate = Effect.fn("MemorySubmissionLedger.validate")((schema, operation, value) => Schema.encodeUnknownEffect(schema)(value).pipe(Effect.flatMap(Schema.decodeUnknownEffect(schema)), Effect.mapError((error) => ledgerError(operation, `Invalid ${operation} request`, error))));
|
|
57
|
+
const decodeSubmissionId = Schema.decodeSync(SubmissionId);
|
|
58
|
+
const decodeReceiptId = Schema.decodeSync(ReceiptId);
|
|
59
|
+
const decodeAttemptId = Schema.decodeSync(AttemptId);
|
|
60
|
+
const decodeOwnershipToken = Schema.decodeSync(OwnershipToken);
|
|
61
|
+
const decodeQueueSequence = Schema.decodeSync(QueueSequence);
|
|
62
|
+
const decodeProducerEpoch = Schema.decodeSync(ProducerEpoch);
|
|
63
|
+
const equivalentPersistedJson = Schema.toEquivalence(PersistedJson);
|
|
64
|
+
const equivalentUnknownResolution = Schema.toEquivalence(UnknownResolution);
|
|
65
|
+
const utc = (millis) => DateTime.toUtc(DateTime.makeUnsafe(millis));
|
|
66
|
+
const admissionKey = (threadId, principal, idempotencyKey) => JSON.stringify([
|
|
67
|
+
threadId,
|
|
68
|
+
principal,
|
|
69
|
+
idempotencyKey
|
|
70
|
+
]);
|
|
71
|
+
const toSnapshot = (row) => SubmissionSnapshot.make({
|
|
72
|
+
submissionId: row.submissionId,
|
|
73
|
+
threadId: row.threadId,
|
|
74
|
+
queueSequence: row.queueSequence,
|
|
75
|
+
principal: row.principal,
|
|
76
|
+
idempotencyKey: row.idempotencyKey,
|
|
77
|
+
agentId: row.agentId,
|
|
78
|
+
agentDigests: row.agentDigests,
|
|
79
|
+
deploymentId: row.deploymentId,
|
|
80
|
+
inputPayload: row.inputPayload,
|
|
81
|
+
inputDigest: row.inputDigest,
|
|
82
|
+
receiptId: row.receiptId,
|
|
83
|
+
state: row.state,
|
|
84
|
+
createdAt: utc(row.createdAtMillis),
|
|
85
|
+
...row.admissionGroup === void 0 ? {} : { admissionGroup: row.admissionGroup },
|
|
86
|
+
...row.admissionFence === void 0 ? {} : { admissionFence: row.admissionFence },
|
|
87
|
+
...row.workerAdmissionJson === void 0 ? {} : { workerAdmission: Schema.decodeSync(Schema.fromJsonString(WorkerAdmission))(row.workerAdmissionJson) },
|
|
88
|
+
...row.messageAdmissionJson === void 0 ? {} : { messageAdmission: Schema.decodeSync(Schema.fromJsonString(MessageAdmission))(row.messageAdmissionJson) },
|
|
89
|
+
...row.settledOutcome === void 0 ? {} : { settledOutcome: row.settledOutcome },
|
|
90
|
+
...row.readyAtMillis === void 0 ? {} : { readyAt: utc(row.readyAtMillis) },
|
|
91
|
+
...row.parentLinkage === void 0 ? {} : { parentLinkage: row.parentLinkage }
|
|
92
|
+
});
|
|
93
|
+
const toReservationSnapshot = (row) => ChildBudgetReservationSnapshot.make({
|
|
94
|
+
reservationId: row.reservationId,
|
|
95
|
+
parentSubmissionId: row.parentSubmissionId,
|
|
96
|
+
parentToolCallId: row.parentToolCallId,
|
|
97
|
+
status: row.status,
|
|
98
|
+
allocation: row.allocation,
|
|
99
|
+
allocationDigest: row.allocationDigest,
|
|
100
|
+
reservedAt: utc(row.reservedAtMillis),
|
|
101
|
+
...row.childSubmissionId === void 0 ? {} : { childSubmissionId: row.childSubmissionId },
|
|
102
|
+
...row.accounting === void 0 ? {} : { accounting: row.accounting },
|
|
103
|
+
...row.releaseBeganAtMillis === void 0 ? {} : { releaseBeganAt: utc(row.releaseBeganAtMillis) },
|
|
104
|
+
...row.releasedAtMillis === void 0 ? {} : { releasedAt: utc(row.releasedAtMillis) }
|
|
105
|
+
});
|
|
106
|
+
/** Linkage equality: both absent, or both present naming the same parent Tool Call. */
|
|
107
|
+
const sameParentLinkage = (left, right) => left === void 0 ? right === void 0 : right !== void 0 && left.parentSubmissionId === right.parentSubmissionId && left.parentToolCallId === right.parentToolCallId;
|
|
108
|
+
const laneEpoch = (state, threadId) => state.lanes.get(threadId)?.producerEpoch ?? 0;
|
|
109
|
+
const ownershipLost = (state, stored) => OwnershipLost.make({
|
|
110
|
+
submissionId: stored.row.submissionId,
|
|
111
|
+
actualEpoch: decodeProducerEpoch(laneEpoch(state, stored.row.threadId))
|
|
112
|
+
});
|
|
113
|
+
/** The presented token owns the lane only while it matches the live ownership record. */
|
|
114
|
+
const ownsLane = (stored, ownershipToken) => stored.ownership !== void 0 && stored.ownership.ownershipToken === ownershipToken;
|
|
115
|
+
const withSubmission = (state, stored) => ({
|
|
116
|
+
...state,
|
|
117
|
+
submissions: new Map(state.submissions).set(stored.row.submissionId, stored)
|
|
118
|
+
});
|
|
119
|
+
const withChildReservation = (state, reservation) => ({
|
|
120
|
+
...state,
|
|
121
|
+
childReservations: new Map(state.childReservations).set(reservation.reservationId, reservation)
|
|
122
|
+
});
|
|
123
|
+
const findHead = (state, threadId) => {
|
|
124
|
+
let head;
|
|
125
|
+
for (const stored of state.submissions.values()) {
|
|
126
|
+
if (stored.row.threadId !== threadId || stored.row.state === "settled") continue;
|
|
127
|
+
if (head === void 0 || stored.row.queueSequence < head.row.queueSequence) head = stored;
|
|
128
|
+
}
|
|
129
|
+
return head;
|
|
130
|
+
};
|
|
131
|
+
/**
|
|
132
|
+
* Reference in-memory SubmissionLedger. It implements the full port contract — atomic idempotent
|
|
133
|
+
* admission, FIFO-head claims, producer-epoch fencing, Clock-driven ownership leases, idempotent
|
|
134
|
+
* settlement reservation/finalization, and durable abort intent — with every transition applied
|
|
135
|
+
* as one atomic `Ref.modify`, but its state does not survive the process (`non-durable`).
|
|
136
|
+
*
|
|
137
|
+
* Adapter-specific semantics within the port's latitude:
|
|
138
|
+
*
|
|
139
|
+
* - Time comes exclusively from the Effect `Clock` service, so `TestClock` drives lease expiry
|
|
140
|
+
* deterministically; no wall clock is consulted.
|
|
141
|
+
* - The ownership lease is pinned to `DEFAULT_OWNERSHIP_LEASE_DURATION` (D5); durable adapters
|
|
142
|
+
* own the configuration seam.
|
|
143
|
+
* - A live lease blocks claims from other producers only: the same `producerId` may reclaim its
|
|
144
|
+
* own live lease (restart recovery), which supersedes and fences the prior Attempt's token.
|
|
145
|
+
* - Claiming advances `ready` to `running` and otherwise preserves the recorded state, so
|
|
146
|
+
* progress markers from an earlier Attempt survive a reclaim.
|
|
147
|
+
* - `renewOwnership` keeps the token stable (the port allows rotation); a replayed admission
|
|
148
|
+
* reports the Submission's current state alongside the original identities.
|
|
149
|
+
* - `claimJoining` walks the strictly-later queue: rows already `joining`/`joined` to the
|
|
150
|
+
* SAME host extend the claimed prefix and are skipped, and an aborted-settled row is a
|
|
151
|
+
* closed obligation that is also skipped (P7 §7(c)); any other non-`ready` row (an
|
|
152
|
+
* `admitted` gap, a non-aborted settled row, foreign-host linkage) breaks the prefix
|
|
153
|
+
* conservatively.
|
|
154
|
+
* - `markJoined` verifies the token against the HOST's live ownership (the lane is
|
|
155
|
+
* host-owned), so a later host Attempt can repair a lost marker from history (DUR-016). The
|
|
156
|
+
* join marker reuses the input-applied marker: the joined input IS `input:{sid}`.
|
|
157
|
+
* - `suspend` and `markUnknown` refuse when an exact settlement is already reserved
|
|
158
|
+
* (`SettlementConflict` with the reserved outcome) — DUR-011's reservation wins.
|
|
159
|
+
* - `resolveAdmission` derives its answer from the single strongly consistent store, so it
|
|
160
|
+
* never answers `Indeterminate` on its own; the test-only `resolveAdmissionFault` option
|
|
161
|
+
* injects the `Indeterminate` classification so SUB-031 callers can be conformance-tested.
|
|
162
|
+
* - `recordChildSettled` and `suspend(WaitingForChild)` observe child settlement directly from
|
|
163
|
+
* the child rows (single-store latitude); no separate notification marker is stored.
|
|
164
|
+
*/
|
|
165
|
+
const makeSubmissionLedger = (options = {}) => Effect.gen(function* () {
|
|
166
|
+
const state = yield* Ref.make({
|
|
167
|
+
submissions: /* @__PURE__ */ new Map(),
|
|
168
|
+
admissionIndex: /* @__PURE__ */ new Map(),
|
|
169
|
+
lanes: /* @__PURE__ */ new Map(),
|
|
170
|
+
childReservations: /* @__PURE__ */ new Map(),
|
|
171
|
+
mintCounter: 0
|
|
172
|
+
});
|
|
173
|
+
const admissionFence = yield* SubmissionAdmissionFence;
|
|
174
|
+
const leaseMillis = Duration.toMillis(DEFAULT_OWNERSHIP_LEASE_DURATION);
|
|
175
|
+
const capabilities = Effect.succeed(LedgerCapabilities.make({ durability: "non-durable" }));
|
|
176
|
+
const admit = Effect.fn("MemorySubmissionLedger.admit")((unvalidated) => Effect.gen(function* () {
|
|
177
|
+
const request = yield* validate(AdmissionRequest, "admit", unvalidated);
|
|
178
|
+
const workerAdmissionJson = request.workerAdmission === void 0 ? void 0 : yield* Schema.encodeEffect(Schema.fromJsonString(WorkerAdmission))(request.workerAdmission).pipe(Effect.mapError(() => ledgerError("admit", "Invalid worker admission metadata")));
|
|
179
|
+
const messageAdmissionJson = request.messageAdmission === void 0 ? void 0 : yield* Schema.encodeEffect(Schema.fromJsonString(MessageAdmission))(request.messageAdmission).pipe(Effect.mapError(() => ledgerError("admit", "Invalid message admission metadata")));
|
|
180
|
+
const nowMillis = yield* Clock.currentTimeMillis;
|
|
181
|
+
const services = yield* Effect.context();
|
|
182
|
+
const decision = yield* Ref.modify(state, (current) => {
|
|
183
|
+
const key = admissionKey(request.threadId, request.principal, request.idempotencyKey);
|
|
184
|
+
const existingId = current.admissionIndex.get(key);
|
|
185
|
+
if (existingId !== void 0) {
|
|
186
|
+
const existing = current.submissions.get(existingId);
|
|
187
|
+
if (existing === void 0) return [failure(ledgerError("admit", "Admission index references a missing Submission")), current];
|
|
188
|
+
if (existing.row.inputDigest !== request.inputDigest || !sameParentLinkage(existing.row.parentLinkage, request.parentLinkage) || existing.row.admissionGroup !== request.admissionGroup || !Schema.toEquivalence(Schema.optional(WorkerAdmission))(existing.row.workerAdmissionJson === void 0 ? void 0 : Schema.decodeSync(Schema.fromJsonString(WorkerAdmission))(existing.row.workerAdmissionJson), request.workerAdmission) || !Schema.toEquivalence(Schema.optional(MessageAdmission))(existing.row.messageAdmissionJson === void 0 ? void 0 : Schema.decodeSync(Schema.fromJsonString(MessageAdmission))(existing.row.messageAdmissionJson), request.messageAdmission) || !Schema.toEquivalence(Schema.optional(Schema.Json))(existing.row.admissionFence, request.admissionFence)) return [failure(AdmissionConflict.make({
|
|
189
|
+
threadId: request.threadId,
|
|
190
|
+
principal: request.principal,
|
|
191
|
+
idempotencyKey: request.idempotencyKey,
|
|
192
|
+
existingInputDigest: existing.row.inputDigest,
|
|
193
|
+
attemptedInputDigest: request.inputDigest
|
|
194
|
+
})), current];
|
|
195
|
+
return [success(AdmissionResult.make({
|
|
196
|
+
submissionId: existing.row.submissionId,
|
|
197
|
+
receiptId: existing.row.receiptId,
|
|
198
|
+
queueSequence: existing.row.queueSequence,
|
|
199
|
+
state: existing.row.state,
|
|
200
|
+
replayed: true
|
|
201
|
+
})), current];
|
|
202
|
+
}
|
|
203
|
+
const first = [...current.submissions.values()].find(({ row }) => row.threadId === request.threadId);
|
|
204
|
+
if (first !== void 0) {
|
|
205
|
+
const previous = first.row.workerAdmissionJson === void 0 ? void 0 : Schema.decodeSync(Schema.fromJsonString(WorkerAdmission))(first.row.workerAdmissionJson);
|
|
206
|
+
if (!Schema.toEquivalence(Schema.optional(WorkerAdmission.fields.origin))(previous?.origin, request.workerAdmission?.origin)) return [failure(AdmissionPolicyError.make({
|
|
207
|
+
reason: "refused",
|
|
208
|
+
code: "worker-origin-conflict"
|
|
209
|
+
})), current];
|
|
210
|
+
}
|
|
211
|
+
const checked = Effect.runSyncExitWith(services)(admissionFence.check(request));
|
|
212
|
+
if (Exit.isFailure(checked)) return [{
|
|
213
|
+
_tag: "cause",
|
|
214
|
+
cause: checked.cause
|
|
215
|
+
}, current];
|
|
216
|
+
if (request.admissionGroup !== void 0 && [...current.submissions.values()].some(({ row }) => row.threadId === request.threadId && row.admissionGroup === request.admissionGroup && row.state !== "settled")) return [failure(AdmissionPolicyError.make({
|
|
217
|
+
reason: "occupied",
|
|
218
|
+
code: "admission-group"
|
|
219
|
+
})), current];
|
|
220
|
+
if (current.submissions.size >= MAX_SUBMISSIONS) return [failure(ledgerError("admit", `In-memory submission limit ${MAX_SUBMISSIONS} exceeded`)), current];
|
|
221
|
+
const lane = current.lanes.get(request.threadId) ?? {
|
|
222
|
+
nextQueueSequence: 1,
|
|
223
|
+
producerEpoch: 0
|
|
224
|
+
};
|
|
225
|
+
const mintCounter = current.mintCounter + 1;
|
|
226
|
+
const row = {
|
|
227
|
+
submissionId: decodeSubmissionId(`submission-memory-${mintCounter}`),
|
|
228
|
+
threadId: request.threadId,
|
|
229
|
+
queueSequence: decodeQueueSequence(lane.nextQueueSequence),
|
|
230
|
+
principal: request.principal,
|
|
231
|
+
idempotencyKey: request.idempotencyKey,
|
|
232
|
+
agentId: request.agentId,
|
|
233
|
+
agentDigests: request.agentDigests,
|
|
234
|
+
deploymentId: request.deploymentId,
|
|
235
|
+
inputPayload: request.inputPayload,
|
|
236
|
+
inputDigest: request.inputDigest,
|
|
237
|
+
receiptId: decodeReceiptId(`receipt-memory-${mintCounter}`),
|
|
238
|
+
state: "admitted",
|
|
239
|
+
settledOutcome: void 0,
|
|
240
|
+
createdAtMillis: nowMillis,
|
|
241
|
+
readyAtMillis: void 0,
|
|
242
|
+
parentLinkage: request.parentLinkage,
|
|
243
|
+
...workerAdmissionJson === void 0 ? {} : { workerAdmissionJson },
|
|
244
|
+
...messageAdmissionJson === void 0 ? {} : { messageAdmissionJson },
|
|
245
|
+
...request.admissionGroup === void 0 ? {} : { admissionGroup: request.admissionGroup },
|
|
246
|
+
...request.admissionFence === void 0 ? {} : { admissionFence: request.admissionFence }
|
|
247
|
+
};
|
|
248
|
+
const submissions = new Map(current.submissions).set(row.submissionId, {
|
|
249
|
+
row,
|
|
250
|
+
ownership: void 0,
|
|
251
|
+
inputApplied: void 0,
|
|
252
|
+
reservation: void 0,
|
|
253
|
+
abortIntent: void 0,
|
|
254
|
+
joinedHostSubmissionId: void 0,
|
|
255
|
+
suspension: void 0,
|
|
256
|
+
unknownMark: void 0,
|
|
257
|
+
approvalDecisions: /* @__PURE__ */ new Map(),
|
|
258
|
+
unknownResolutions: /* @__PURE__ */ new Map()
|
|
259
|
+
});
|
|
260
|
+
const admissionIndex = new Map(current.admissionIndex).set(key, row.submissionId);
|
|
261
|
+
const lanes = new Map(current.lanes).set(request.threadId, {
|
|
262
|
+
nextQueueSequence: lane.nextQueueSequence + 1,
|
|
263
|
+
producerEpoch: lane.producerEpoch
|
|
264
|
+
});
|
|
265
|
+
return [success(AdmissionResult.make({
|
|
266
|
+
submissionId: row.submissionId,
|
|
267
|
+
receiptId: row.receiptId,
|
|
268
|
+
queueSequence: row.queueSequence,
|
|
269
|
+
state: row.state,
|
|
270
|
+
replayed: false
|
|
271
|
+
})), {
|
|
272
|
+
...current,
|
|
273
|
+
submissions,
|
|
274
|
+
admissionIndex,
|
|
275
|
+
lanes,
|
|
276
|
+
mintCounter
|
|
277
|
+
}];
|
|
278
|
+
});
|
|
279
|
+
if (decision._tag === "failure") return yield* decision.error;
|
|
280
|
+
if (decision._tag === "cause") {
|
|
281
|
+
for (const reason of decision.cause.reasons) if (Cause.isDieReason(reason) && Cause.isAsyncFiberError(reason.defect)) {
|
|
282
|
+
yield* Fiber.interrupt(reason.defect.fiber);
|
|
283
|
+
return yield* AdmissionPolicyError.make({
|
|
284
|
+
reason: "unavailable",
|
|
285
|
+
code: "synchronous-memory-policy-required"
|
|
286
|
+
});
|
|
287
|
+
}
|
|
288
|
+
return yield* Effect.failCause(decision.cause);
|
|
289
|
+
}
|
|
290
|
+
return decision.value;
|
|
291
|
+
}), Effect.uninterruptible);
|
|
292
|
+
const markReady = Effect.fn("MemorySubmissionLedger.markReady")((unvalidated) => Effect.gen(function* () {
|
|
293
|
+
const request = yield* validate(MarkReadyRequest, "markReady", unvalidated);
|
|
294
|
+
const nowMillis = yield* Clock.currentTimeMillis;
|
|
295
|
+
const decision = yield* Ref.modify(state, (current) => {
|
|
296
|
+
const stored = current.submissions.get(request.submissionId);
|
|
297
|
+
if (stored === void 0) return [failure(ledgerError("markReady", `Unknown Submission ${request.submissionId}`)), current];
|
|
298
|
+
if (stored.row.state !== "admitted") return [success(void 0), current];
|
|
299
|
+
return [success(void 0), withSubmission(current, {
|
|
300
|
+
...stored,
|
|
301
|
+
row: {
|
|
302
|
+
...stored.row,
|
|
303
|
+
state: "ready",
|
|
304
|
+
readyAtMillis: nowMillis
|
|
305
|
+
}
|
|
306
|
+
})];
|
|
307
|
+
});
|
|
308
|
+
if (decision._tag === "failure") return yield* decision.error;
|
|
309
|
+
}));
|
|
310
|
+
const lookup = Effect.fn("MemorySubmissionLedger.lookup")((unvalidated) => Effect.gen(function* () {
|
|
311
|
+
const request = yield* validate(SubmissionLookup, "lookup", unvalidated);
|
|
312
|
+
const current = yield* Ref.get(state);
|
|
313
|
+
const submissionId = request._tag === "SubmissionLookupById" ? request.submissionId : current.admissionIndex.get(admissionKey(request.threadId, request.principal, request.idempotencyKey));
|
|
314
|
+
const stored = submissionId === void 0 ? void 0 : current.submissions.get(submissionId);
|
|
315
|
+
return stored === void 0 ? Option.none() : Option.some(toSnapshot(stored.row));
|
|
316
|
+
}));
|
|
317
|
+
const resolveAdmission = Effect.fn("MemorySubmissionLedger.resolveAdmission")((unvalidated) => Effect.gen(function* () {
|
|
318
|
+
const request = yield* validate(SubmissionLookupByKey, "resolveAdmission", unvalidated);
|
|
319
|
+
if (options.resolveAdmissionFault !== void 0) {
|
|
320
|
+
const fault = yield* options.resolveAdmissionFault;
|
|
321
|
+
if (Option.isSome(fault)) return AdmissionIndeterminate.make({ reason: fault.value });
|
|
322
|
+
}
|
|
323
|
+
const current = yield* Ref.get(state);
|
|
324
|
+
const submissionId = current.admissionIndex.get(admissionKey(request.threadId, request.principal, request.idempotencyKey));
|
|
325
|
+
const stored = submissionId === void 0 ? void 0 : current.submissions.get(submissionId);
|
|
326
|
+
return stored === void 0 ? AdmissionNotAdmitted.make() : AdmissionAdmitted.make({ submission: toSnapshot(stored.row) });
|
|
327
|
+
}));
|
|
328
|
+
const claim = Effect.fn("MemorySubmissionLedger.claim")((unvalidated) => Effect.gen(function* () {
|
|
329
|
+
const request = yield* validate(ClaimRequest, "claim", unvalidated);
|
|
330
|
+
const nowMillis = yield* Clock.currentTimeMillis;
|
|
331
|
+
const decision = yield* Ref.modify(state, (current) => {
|
|
332
|
+
const head = findHead(current, request.threadId);
|
|
333
|
+
if (head === void 0) return [success(Option.none()), current];
|
|
334
|
+
if (BLOCKED_HEAD_STATES.has(head.row.state) || head.row.state === "unknown" && head.abortIntent === void 0) return [success(Option.none()), current];
|
|
335
|
+
if (head.ownership !== void 0 && head.ownership.leaseExpiresAtMillis > nowMillis && head.ownership.ownerProducerId !== request.producerId) return [success(Option.none()), current];
|
|
336
|
+
const lane = current.lanes.get(request.threadId);
|
|
337
|
+
if (lane === void 0) return [failure(ledgerError("claim", "Claimable head without a Thread lane")), current];
|
|
338
|
+
const producerEpoch = decodeProducerEpoch(lane.producerEpoch + 1);
|
|
339
|
+
const mintCounter = current.mintCounter + 1;
|
|
340
|
+
const ownership = {
|
|
341
|
+
attemptId: decodeAttemptId(`attempt-memory-${mintCounter}`),
|
|
342
|
+
ownershipToken: decodeOwnershipToken(`ownership-memory-${mintCounter}`),
|
|
343
|
+
producerEpoch,
|
|
344
|
+
ownerProducerId: request.producerId,
|
|
345
|
+
leaseExpiresAtMillis: nowMillis + leaseMillis
|
|
346
|
+
};
|
|
347
|
+
const row = head.row.state === "ready" ? {
|
|
348
|
+
...head.row,
|
|
349
|
+
state: "running"
|
|
350
|
+
} : head.row;
|
|
351
|
+
const next = withSubmission(current, {
|
|
352
|
+
...head,
|
|
353
|
+
row,
|
|
354
|
+
ownership
|
|
355
|
+
});
|
|
356
|
+
const lanes = new Map(next.lanes).set(request.threadId, {
|
|
357
|
+
nextQueueSequence: lane.nextQueueSequence,
|
|
358
|
+
producerEpoch: lane.producerEpoch + 1
|
|
359
|
+
});
|
|
360
|
+
return [success(Option.some(Claim.make({
|
|
361
|
+
submissionId: row.submissionId,
|
|
362
|
+
attemptId: ownership.attemptId,
|
|
363
|
+
ownershipToken: ownership.ownershipToken,
|
|
364
|
+
producerEpoch,
|
|
365
|
+
leaseExpiresAt: utc(ownership.leaseExpiresAtMillis),
|
|
366
|
+
inputPayload: row.inputPayload
|
|
367
|
+
}))), {
|
|
368
|
+
...next,
|
|
369
|
+
lanes,
|
|
370
|
+
mintCounter
|
|
371
|
+
}];
|
|
372
|
+
});
|
|
373
|
+
if (decision._tag === "failure") return yield* decision.error;
|
|
374
|
+
return decision.value;
|
|
375
|
+
}));
|
|
376
|
+
const renewOwnership = Effect.fn("MemorySubmissionLedger.renewOwnership")((unvalidated) => Effect.gen(function* () {
|
|
377
|
+
const request = yield* validate(RenewOwnershipRequest, "renewOwnership", unvalidated);
|
|
378
|
+
const nowMillis = yield* Clock.currentTimeMillis;
|
|
379
|
+
const decision = yield* Ref.modify(state, (current) => {
|
|
380
|
+
const stored = current.submissions.get(request.submissionId);
|
|
381
|
+
if (stored === void 0) return [failure(ledgerError("renewOwnership", `Unknown Submission ${request.submissionId}`)), current];
|
|
382
|
+
if (stored.ownership === void 0 || !ownsLane(stored, request.ownershipToken)) return [failure(ownershipLost(current, stored)), current];
|
|
383
|
+
const ownership = {
|
|
384
|
+
...stored.ownership,
|
|
385
|
+
leaseExpiresAtMillis: nowMillis + leaseMillis
|
|
386
|
+
};
|
|
387
|
+
return [success(OwnershipRenewal.make({
|
|
388
|
+
ownershipToken: ownership.ownershipToken,
|
|
389
|
+
leaseExpiresAt: utc(ownership.leaseExpiresAtMillis)
|
|
390
|
+
})), withSubmission(current, {
|
|
391
|
+
...stored,
|
|
392
|
+
ownership
|
|
393
|
+
})];
|
|
394
|
+
});
|
|
395
|
+
if (decision._tag === "failure") return yield* decision.error;
|
|
396
|
+
return decision.value;
|
|
397
|
+
}));
|
|
398
|
+
const releaseOwnership = Effect.fn("MemorySubmissionLedger.releaseOwnership")((unvalidated) => Effect.gen(function* () {
|
|
399
|
+
const request = yield* validate(ReleaseOwnershipRequest, "releaseOwnership", unvalidated);
|
|
400
|
+
const decision = yield* Ref.modify(state, (current) => {
|
|
401
|
+
const stored = current.submissions.get(request.submissionId);
|
|
402
|
+
if (stored === void 0) return [failure(ledgerError("releaseOwnership", `Unknown Submission ${request.submissionId}`)), current];
|
|
403
|
+
if (!ownsLane(stored, request.ownershipToken)) return [failure(ownershipLost(current, stored)), current];
|
|
404
|
+
return [success(void 0), withSubmission(current, {
|
|
405
|
+
...stored,
|
|
406
|
+
ownership: void 0
|
|
407
|
+
})];
|
|
408
|
+
});
|
|
409
|
+
if (decision._tag === "failure") return yield* decision.error;
|
|
410
|
+
}));
|
|
411
|
+
const markInputApplied = Effect.fn("MemorySubmissionLedger.markInputApplied")((unvalidated) => Effect.gen(function* () {
|
|
412
|
+
const request = yield* validate(MarkInputAppliedRequest, "markInputApplied", unvalidated);
|
|
413
|
+
const decision = yield* Ref.modify(state, (current) => {
|
|
414
|
+
const stored = current.submissions.get(request.submissionId);
|
|
415
|
+
if (stored === void 0) return [failure(ledgerError("markInputApplied", `Unknown Submission ${request.submissionId}`)), current];
|
|
416
|
+
if (!ownsLane(stored, request.ownershipToken)) return [failure(ownershipLost(current, stored)), current];
|
|
417
|
+
if (stored.inputApplied !== void 0) {
|
|
418
|
+
if (stored.inputApplied.recordId === request.recordId && stored.inputApplied.sequence === request.sequence) return [success(void 0), current];
|
|
419
|
+
return [failure(ledgerError("markInputApplied", `A different canonical input marker is already recorded for Submission ${request.submissionId}`)), current];
|
|
420
|
+
}
|
|
421
|
+
const marker = InputAppliedMarker.make({
|
|
422
|
+
recordId: request.recordId,
|
|
423
|
+
sequence: request.sequence
|
|
424
|
+
});
|
|
425
|
+
const row = STATE_RANK[stored.row.state] < STATE_RANK["input-applied"] ? {
|
|
426
|
+
...stored.row,
|
|
427
|
+
state: "input-applied"
|
|
428
|
+
} : stored.row;
|
|
429
|
+
return [success(void 0), withSubmission(current, {
|
|
430
|
+
...stored,
|
|
431
|
+
row,
|
|
432
|
+
inputApplied: marker
|
|
433
|
+
})];
|
|
434
|
+
});
|
|
435
|
+
if (decision._tag === "failure") return yield* decision.error;
|
|
436
|
+
}));
|
|
437
|
+
const reserveSettlement = Effect.fn("MemorySubmissionLedger.reserveSettlement")((unvalidated) => Effect.gen(function* () {
|
|
438
|
+
const request = yield* validate(SettlementReservation, "reserveSettlement", unvalidated);
|
|
439
|
+
const decision = yield* Ref.modify(state, (current) => {
|
|
440
|
+
const stored = current.submissions.get(request.submissionId);
|
|
441
|
+
if (stored === void 0) return [failure(ledgerError("reserveSettlement", `Unknown Submission ${request.submissionId}`)), current];
|
|
442
|
+
const joinedSettlement = stored.row.state === "joined" && stored.joinedHostSubmissionId !== void 0;
|
|
443
|
+
const queuedAbortSettlement = request.outcome === "aborted" && stored.abortIntent !== void 0 && stored.ownership === void 0 && (stored.row.state === "ready" || stored.row.state === "terminalizing");
|
|
444
|
+
if (!joinedSettlement && !queuedAbortSettlement && !ownsLane(stored, request.ownershipToken)) return [failure(ownershipLost(current, stored)), current];
|
|
445
|
+
const existing = stored.reservation;
|
|
446
|
+
if (existing !== void 0) {
|
|
447
|
+
if (existing.settlementId !== request.settlementId || existing.outcome !== request.outcome || existing.recordDigest !== request.recordDigest) return [failure(SettlementConflict.make({
|
|
448
|
+
submissionId: request.submissionId,
|
|
449
|
+
existingOutcome: existing.outcome
|
|
450
|
+
})), current];
|
|
451
|
+
return [success(ReservedSettlement.make({
|
|
452
|
+
submissionId: request.submissionId,
|
|
453
|
+
settlementId: existing.settlementId,
|
|
454
|
+
outcome: existing.outcome,
|
|
455
|
+
record: existing.record,
|
|
456
|
+
recordDigest: existing.recordDigest,
|
|
457
|
+
replayed: true
|
|
458
|
+
})), current];
|
|
459
|
+
}
|
|
460
|
+
const reservation = {
|
|
461
|
+
settlementId: request.settlementId,
|
|
462
|
+
outcome: request.outcome,
|
|
463
|
+
record: request.record,
|
|
464
|
+
recordDigest: request.recordDigest,
|
|
465
|
+
finalizedAtMillis: void 0
|
|
466
|
+
};
|
|
467
|
+
const row = STATE_RANK[stored.row.state] < STATE_RANK.terminalizing ? {
|
|
468
|
+
...stored.row,
|
|
469
|
+
state: "terminalizing"
|
|
470
|
+
} : stored.row;
|
|
471
|
+
return [success(ReservedSettlement.make({
|
|
472
|
+
submissionId: request.submissionId,
|
|
473
|
+
settlementId: reservation.settlementId,
|
|
474
|
+
outcome: reservation.outcome,
|
|
475
|
+
record: reservation.record,
|
|
476
|
+
recordDigest: reservation.recordDigest,
|
|
477
|
+
replayed: false
|
|
478
|
+
})), withSubmission(current, {
|
|
479
|
+
...stored,
|
|
480
|
+
row,
|
|
481
|
+
reservation
|
|
482
|
+
})];
|
|
483
|
+
});
|
|
484
|
+
if (decision._tag === "failure") return yield* decision.error;
|
|
485
|
+
return decision.value;
|
|
486
|
+
}));
|
|
487
|
+
const finalizeSettlement = Effect.fn("MemorySubmissionLedger.finalizeSettlement")((unvalidated) => Effect.gen(function* () {
|
|
488
|
+
const request = yield* validate(SettlementFinalization, "finalizeSettlement", unvalidated);
|
|
489
|
+
const nowMillis = yield* Clock.currentTimeMillis;
|
|
490
|
+
const decision = yield* Ref.modify(state, (current) => {
|
|
491
|
+
const stored = current.submissions.get(request.submissionId);
|
|
492
|
+
if (stored === void 0) return [failure(ledgerError("finalizeSettlement", `Unknown Submission ${request.submissionId}`)), current];
|
|
493
|
+
const reservation = stored.reservation;
|
|
494
|
+
if (reservation === void 0) return [failure(ledgerError("finalizeSettlement", `No settlement reservation for Submission ${request.submissionId}`)), current];
|
|
495
|
+
const settlementFailure = settlementFailureFromRecord(reservation.record);
|
|
496
|
+
if (reservation.outcome === "failed" !== (settlementFailure !== void 0)) return [failure(ledgerError("finalizeSettlement", `Settlement reservation for Submission ${request.submissionId} has contradictory failure evidence`)), current];
|
|
497
|
+
if (reservation.settlementId !== request.settlementId) return [failure(SettlementConflict.make({
|
|
498
|
+
submissionId: request.submissionId,
|
|
499
|
+
existingOutcome: reservation.outcome
|
|
500
|
+
})), current];
|
|
501
|
+
if (reservation.finalizedAtMillis !== void 0) return [success(Settlement.make({
|
|
502
|
+
submissionId: stored.row.submissionId,
|
|
503
|
+
settlementId: reservation.settlementId,
|
|
504
|
+
receiptId: stored.row.receiptId,
|
|
505
|
+
outcome: reservation.outcome,
|
|
506
|
+
...settlementFailure === void 0 ? {} : { failure: settlementFailure },
|
|
507
|
+
settledAt: utc(reservation.finalizedAtMillis)
|
|
508
|
+
})), current];
|
|
509
|
+
const next = withSubmission(current, {
|
|
510
|
+
...stored,
|
|
511
|
+
row: {
|
|
512
|
+
...stored.row,
|
|
513
|
+
state: "settled",
|
|
514
|
+
settledOutcome: reservation.outcome
|
|
515
|
+
},
|
|
516
|
+
ownership: void 0,
|
|
517
|
+
reservation: {
|
|
518
|
+
...reservation,
|
|
519
|
+
finalizedAtMillis: nowMillis
|
|
520
|
+
}
|
|
521
|
+
});
|
|
522
|
+
return [success(Settlement.make({
|
|
523
|
+
submissionId: stored.row.submissionId,
|
|
524
|
+
settlementId: reservation.settlementId,
|
|
525
|
+
receiptId: stored.row.receiptId,
|
|
526
|
+
outcome: reservation.outcome,
|
|
527
|
+
...settlementFailure === void 0 ? {} : { failure: settlementFailure },
|
|
528
|
+
settledAt: utc(nowMillis)
|
|
529
|
+
})), next];
|
|
530
|
+
});
|
|
531
|
+
if (decision._tag === "failure") return yield* decision.error;
|
|
532
|
+
return decision.value;
|
|
533
|
+
}));
|
|
534
|
+
const requestAbort = Effect.fn("MemorySubmissionLedger.requestAbort")((unvalidated) => Effect.gen(function* () {
|
|
535
|
+
const request = yield* validate(AbortCommand, "requestAbort", unvalidated);
|
|
536
|
+
const nowMillis = yield* Clock.currentTimeMillis;
|
|
537
|
+
const decision = yield* Ref.modify(state, (current) => {
|
|
538
|
+
const stored = current.submissions.get(request.submissionId);
|
|
539
|
+
if (stored === void 0) return [failure(ledgerError("requestAbort", `Unknown Submission ${request.submissionId}`)), current];
|
|
540
|
+
if (stored.row.state === "joined") {
|
|
541
|
+
if (stored.joinedHostSubmissionId === void 0) return [failure(ledgerError("requestAbort", `Joined Submission ${request.submissionId} is missing its host linkage`)), current];
|
|
542
|
+
return [failure(JoinedToHost.make({
|
|
543
|
+
submissionId: request.submissionId,
|
|
544
|
+
hostSubmissionId: stored.joinedHostSubmissionId
|
|
545
|
+
})), current];
|
|
546
|
+
}
|
|
547
|
+
if (stored.row.state === "settled") {
|
|
548
|
+
if (stored.row.settledOutcome === void 0) return [failure(ledgerError("requestAbort", `Settled Submission ${request.submissionId} is missing its outcome`)), current];
|
|
549
|
+
return [failure(SettlementConflict.make({
|
|
550
|
+
submissionId: request.submissionId,
|
|
551
|
+
existingOutcome: stored.row.settledOutcome
|
|
552
|
+
})), current];
|
|
553
|
+
}
|
|
554
|
+
if (stored.abortIntent !== void 0) return [success(stored.abortIntent), current];
|
|
555
|
+
const intent = AbortIntent.make({
|
|
556
|
+
submissionId: request.submissionId,
|
|
557
|
+
author: request.author,
|
|
558
|
+
reason: request.reason,
|
|
559
|
+
requestedAt: utc(nowMillis)
|
|
560
|
+
});
|
|
561
|
+
return [success(intent), withSubmission(current, {
|
|
562
|
+
...stored,
|
|
563
|
+
abortIntent: intent
|
|
564
|
+
})];
|
|
565
|
+
});
|
|
566
|
+
if (decision._tag === "failure") return yield* decision.error;
|
|
567
|
+
return decision.value;
|
|
568
|
+
}));
|
|
569
|
+
const claimJoining = Effect.fn("MemorySubmissionLedger.claimJoining")((unvalidated) => Effect.gen(function* () {
|
|
570
|
+
const request = yield* validate(ClaimJoiningRequest, "claimJoining", unvalidated);
|
|
571
|
+
const decision = yield* Ref.modify(state, (current) => {
|
|
572
|
+
const host = current.submissions.get(request.hostSubmissionId);
|
|
573
|
+
if (host === void 0) return [failure(ledgerError("claimJoining", `Unknown Submission ${request.hostSubmissionId}`)), current];
|
|
574
|
+
if (host.row.threadId !== request.threadId) return [failure(ledgerError("claimJoining", `Host Submission ${request.hostSubmissionId} does not belong to Thread ${request.threadId}`)), current];
|
|
575
|
+
if (!ownsLane(host, request.ownershipToken)) return [failure(ownershipLost(current, host)), current];
|
|
576
|
+
const later = [...current.submissions.values()].filter((stored) => stored.row.threadId === request.threadId && stored.row.queueSequence > host.row.queueSequence).sort((left, right) => left.row.queueSequence - right.row.queueSequence);
|
|
577
|
+
const claims = [];
|
|
578
|
+
const submissions = new Map(current.submissions);
|
|
579
|
+
for (const stored of later) {
|
|
580
|
+
if (claims.length >= request.maxCount) break;
|
|
581
|
+
if ((stored.row.state === "joining" || stored.row.state === "joined") && stored.joinedHostSubmissionId === request.hostSubmissionId) continue;
|
|
582
|
+
if (stored.row.state === "settled" && stored.row.settledOutcome === "aborted") continue;
|
|
583
|
+
if (stored.row.state !== "ready") break;
|
|
584
|
+
submissions.set(stored.row.submissionId, {
|
|
585
|
+
...stored,
|
|
586
|
+
row: {
|
|
587
|
+
...stored.row,
|
|
588
|
+
state: "joining"
|
|
589
|
+
},
|
|
590
|
+
joinedHostSubmissionId: request.hostSubmissionId
|
|
591
|
+
});
|
|
592
|
+
claims.push(JoiningClaim.make({
|
|
593
|
+
submissionId: stored.row.submissionId,
|
|
594
|
+
queueSequence: stored.row.queueSequence,
|
|
595
|
+
inputPayload: stored.row.inputPayload
|
|
596
|
+
}));
|
|
597
|
+
}
|
|
598
|
+
return [success(claims), {
|
|
599
|
+
...current,
|
|
600
|
+
submissions
|
|
601
|
+
}];
|
|
602
|
+
});
|
|
603
|
+
if (decision._tag === "failure") return yield* decision.error;
|
|
604
|
+
return decision.value;
|
|
605
|
+
}));
|
|
606
|
+
const markJoined = Effect.fn("MemorySubmissionLedger.markJoined")((unvalidated) => Effect.gen(function* () {
|
|
607
|
+
const request = yield* validate(MarkJoinedRequest, "markJoined", unvalidated);
|
|
608
|
+
const decision = yield* Ref.modify(state, (current) => {
|
|
609
|
+
const stored = current.submissions.get(request.submissionId);
|
|
610
|
+
if (stored === void 0) return [failure(ledgerError("markJoined", `Unknown Submission ${request.submissionId}`)), current];
|
|
611
|
+
if (stored.joinedHostSubmissionId === void 0) return [failure(ledgerError("markJoined", `Submission ${request.submissionId} was never claimed for joining`)), current];
|
|
612
|
+
const host = current.submissions.get(stored.joinedHostSubmissionId);
|
|
613
|
+
if (host === void 0) return [failure(ledgerError("markJoined", `Host Submission ${stored.joinedHostSubmissionId} is missing`)), current];
|
|
614
|
+
if (!ownsLane(host, request.ownershipToken)) return [failure(ownershipLost(current, host)), current];
|
|
615
|
+
if (stored.inputApplied !== void 0) {
|
|
616
|
+
if (stored.inputApplied.recordId === request.recordId && stored.inputApplied.sequence === request.sequence) return [success(void 0), current];
|
|
617
|
+
return [failure(ledgerError("markJoined", `A different join marker is already recorded for Submission ${request.submissionId}`)), current];
|
|
618
|
+
}
|
|
619
|
+
if (stored.row.state !== "joining" && stored.row.state !== "joined") return [failure(ledgerError("markJoined", `Cannot mark Submission ${request.submissionId} joined from state ${stored.row.state}`)), current];
|
|
620
|
+
const marker = InputAppliedMarker.make({
|
|
621
|
+
recordId: request.recordId,
|
|
622
|
+
sequence: request.sequence
|
|
623
|
+
});
|
|
624
|
+
return [success(void 0), withSubmission(current, {
|
|
625
|
+
...stored,
|
|
626
|
+
row: {
|
|
627
|
+
...stored.row,
|
|
628
|
+
state: "joined"
|
|
629
|
+
},
|
|
630
|
+
inputApplied: marker
|
|
631
|
+
})];
|
|
632
|
+
});
|
|
633
|
+
if (decision._tag === "failure") return yield* decision.error;
|
|
634
|
+
}));
|
|
635
|
+
const revertJoining = Effect.fn("MemorySubmissionLedger.revertJoining")((unvalidated) => Effect.gen(function* () {
|
|
636
|
+
const request = yield* validate(RevertJoiningRequest, "revertJoining", unvalidated);
|
|
637
|
+
const decision = yield* Ref.modify(state, (current) => {
|
|
638
|
+
const stored = current.submissions.get(request.submissionId);
|
|
639
|
+
if (stored === void 0) return [failure(ledgerError("revertJoining", `Unknown Submission ${request.submissionId}`)), current];
|
|
640
|
+
if (stored.row.state !== "joining") return [success(void 0), current];
|
|
641
|
+
return [success(void 0), withSubmission(current, {
|
|
642
|
+
...stored,
|
|
643
|
+
row: {
|
|
644
|
+
...stored.row,
|
|
645
|
+
state: "ready"
|
|
646
|
+
},
|
|
647
|
+
joinedHostSubmissionId: void 0
|
|
648
|
+
})];
|
|
649
|
+
});
|
|
650
|
+
if (decision._tag === "failure") return yield* decision.error;
|
|
651
|
+
}));
|
|
652
|
+
const suspend = Effect.fn("MemorySubmissionLedger.suspend")((unvalidated) => Effect.gen(function* () {
|
|
653
|
+
const request = yield* validate(SuspendRequest, "suspend", unvalidated);
|
|
654
|
+
const nowMillis = yield* Clock.currentTimeMillis;
|
|
655
|
+
const decision = yield* Ref.modify(state, (current) => {
|
|
656
|
+
const stored = current.submissions.get(request.submissionId);
|
|
657
|
+
if (stored === void 0) return [failure(ledgerError("suspend", `Unknown Submission ${request.submissionId}`)), current];
|
|
658
|
+
if (stored.row.state === "settled") {
|
|
659
|
+
if (stored.row.settledOutcome === void 0) return [failure(ledgerError("suspend", `Settled Submission ${request.submissionId} is missing its outcome`)), current];
|
|
660
|
+
return [failure(SettlementConflict.make({
|
|
661
|
+
submissionId: request.submissionId,
|
|
662
|
+
existingOutcome: stored.row.settledOutcome
|
|
663
|
+
})), current];
|
|
664
|
+
}
|
|
665
|
+
if (stored.reservation !== void 0) return [failure(SettlementConflict.make({
|
|
666
|
+
submissionId: request.submissionId,
|
|
667
|
+
existingOutcome: stored.reservation.outcome
|
|
668
|
+
})), current];
|
|
669
|
+
if (!ownsLane(stored, request.ownershipToken)) return [failure(ownershipLost(current, stored)), current];
|
|
670
|
+
if (request.reason._tag === "ApprovalPending" ? request.reason.toolCallIds.every((toolCallId) => stored.approvalDecisions.has(toolCallId)) : request.reason.children.every((child) => current.submissions.get(child.childSubmissionId)?.row.state === "settled")) return [success("resume-immediately"), current];
|
|
671
|
+
return [success("suspended"), withSubmission(current, {
|
|
672
|
+
...stored,
|
|
673
|
+
row: {
|
|
674
|
+
...stored.row,
|
|
675
|
+
state: "suspended"
|
|
676
|
+
},
|
|
677
|
+
ownership: void 0,
|
|
678
|
+
suspension: {
|
|
679
|
+
reason: request.reason,
|
|
680
|
+
suspendedAtMillis: nowMillis
|
|
681
|
+
}
|
|
682
|
+
})];
|
|
683
|
+
});
|
|
684
|
+
if (decision._tag === "failure") return yield* decision.error;
|
|
685
|
+
return decision.value;
|
|
686
|
+
}));
|
|
687
|
+
const recordApprovalDecision = Effect.fn("MemorySubmissionLedger.recordApprovalDecision")((unvalidated) => Effect.gen(function* () {
|
|
688
|
+
const command = yield* validate(ApprovalDecisionCommand, "recordApprovalDecision", unvalidated);
|
|
689
|
+
const nowMillis = yield* Clock.currentTimeMillis;
|
|
690
|
+
const decision = yield* Ref.modify(state, (current) => {
|
|
691
|
+
const stored = current.submissions.get(command.submissionId);
|
|
692
|
+
if (stored === void 0) return [failure(ledgerError("recordApprovalDecision", `Unknown Submission ${command.submissionId}`)), current];
|
|
693
|
+
if (stored.row.state === "settled") {
|
|
694
|
+
if (stored.row.settledOutcome === void 0) return [failure(ledgerError("recordApprovalDecision", `Settled Submission ${command.submissionId} is missing its outcome`)), current];
|
|
695
|
+
return [failure(SettlementConflict.make({
|
|
696
|
+
submissionId: command.submissionId,
|
|
697
|
+
existingOutcome: stored.row.settledOutcome
|
|
698
|
+
})), current];
|
|
699
|
+
}
|
|
700
|
+
const existing = stored.approvalDecisions.get(command.toolCallId);
|
|
701
|
+
if (existing !== void 0) {
|
|
702
|
+
if (existing.decision !== command.decision) return [failure(ApprovalConflict.make({
|
|
703
|
+
submissionId: command.submissionId,
|
|
704
|
+
toolCallId: command.toolCallId,
|
|
705
|
+
existingDecision: existing.decision
|
|
706
|
+
})), current];
|
|
707
|
+
return [success(existing), current];
|
|
708
|
+
}
|
|
709
|
+
const intent = ApprovalDecisionIntent.make({
|
|
710
|
+
submissionId: command.submissionId,
|
|
711
|
+
toolCallId: command.toolCallId,
|
|
712
|
+
decision: command.decision,
|
|
713
|
+
resolver: command.resolver,
|
|
714
|
+
reason: command.reason,
|
|
715
|
+
decidedAt: utc(nowMillis)
|
|
716
|
+
});
|
|
717
|
+
const approvalDecisions = new Map(stored.approvalDecisions).set(command.toolCallId, intent);
|
|
718
|
+
const wakes = stored.row.state === "suspended" && stored.suspension !== void 0 && stored.suspension.reason._tag === "ApprovalPending" && stored.suspension.reason.toolCallIds.every((toolCallId) => approvalDecisions.has(toolCallId));
|
|
719
|
+
return [success(intent), withSubmission(current, {
|
|
720
|
+
...stored,
|
|
721
|
+
row: wakes ? {
|
|
722
|
+
...stored.row,
|
|
723
|
+
state: "input-applied"
|
|
724
|
+
} : stored.row,
|
|
725
|
+
suspension: wakes ? void 0 : stored.suspension,
|
|
726
|
+
approvalDecisions
|
|
727
|
+
})];
|
|
728
|
+
});
|
|
729
|
+
if (decision._tag === "failure") return yield* decision.error;
|
|
730
|
+
return decision.value;
|
|
731
|
+
}));
|
|
732
|
+
const markUnknown = Effect.fn("MemorySubmissionLedger.markUnknown")((unvalidated) => Effect.gen(function* () {
|
|
733
|
+
const request = yield* validate(MarkUnknownRequest, "markUnknown", unvalidated);
|
|
734
|
+
const decision = yield* Ref.modify(state, (current) => {
|
|
735
|
+
const stored = current.submissions.get(request.submissionId);
|
|
736
|
+
if (stored === void 0) return [failure(ledgerError("markUnknown", `Unknown Submission ${request.submissionId}`)), current];
|
|
737
|
+
if (stored.row.state === "settled") {
|
|
738
|
+
if (stored.row.settledOutcome === void 0) return [failure(ledgerError("markUnknown", `Settled Submission ${request.submissionId} is missing its outcome`)), current];
|
|
739
|
+
return [failure(SettlementConflict.make({
|
|
740
|
+
submissionId: request.submissionId,
|
|
741
|
+
existingOutcome: stored.row.settledOutcome
|
|
742
|
+
})), current];
|
|
743
|
+
}
|
|
744
|
+
if (stored.reservation !== void 0) return [failure(SettlementConflict.make({
|
|
745
|
+
submissionId: request.submissionId,
|
|
746
|
+
existingOutcome: stored.reservation.outcome
|
|
747
|
+
})), current];
|
|
748
|
+
const existing = stored.unknownMark;
|
|
749
|
+
const known = new Set(existing?.toolCallIds ?? []);
|
|
750
|
+
const merged = [...existing?.toolCallIds ?? [], ...request.toolCallIds.filter((toolCallId) => !known.has(toolCallId))];
|
|
751
|
+
return [success(void 0), withSubmission(current, {
|
|
752
|
+
...stored,
|
|
753
|
+
row: stored.row.state === "unknown" ? stored.row : {
|
|
754
|
+
...stored.row,
|
|
755
|
+
state: "unknown"
|
|
756
|
+
},
|
|
757
|
+
unknownMark: {
|
|
758
|
+
reason: existing?.reason ?? request.reason,
|
|
759
|
+
toolCallIds: merged
|
|
760
|
+
}
|
|
761
|
+
})];
|
|
762
|
+
});
|
|
763
|
+
if (decision._tag === "failure") return yield* decision.error;
|
|
764
|
+
}));
|
|
765
|
+
const recordUnknownResolution = Effect.fn("MemorySubmissionLedger.recordUnknownResolution")((unvalidated) => Effect.gen(function* () {
|
|
766
|
+
const command = yield* validate(UnknownResolutionCommand, "recordUnknownResolution", unvalidated);
|
|
767
|
+
const nowMillis = yield* Clock.currentTimeMillis;
|
|
768
|
+
const decision = yield* Ref.modify(state, (current) => {
|
|
769
|
+
const stored = current.submissions.get(command.submissionId);
|
|
770
|
+
if (stored === void 0) return [failure(ledgerError("recordUnknownResolution", `Unknown Submission ${command.submissionId}`)), current];
|
|
771
|
+
if (stored.row.state === "settled") {
|
|
772
|
+
if (stored.row.settledOutcome === void 0) return [failure(ledgerError("recordUnknownResolution", `Settled Submission ${command.submissionId} is missing its outcome`)), current];
|
|
773
|
+
return [failure(SettlementConflict.make({
|
|
774
|
+
submissionId: command.submissionId,
|
|
775
|
+
existingOutcome: stored.row.settledOutcome
|
|
776
|
+
})), current];
|
|
777
|
+
}
|
|
778
|
+
const existing = stored.unknownResolutions.get(command.toolCallId);
|
|
779
|
+
if (existing !== void 0 && !equivalentUnknownResolution(existing.intent.resolution, command.resolution)) return [failure(UnknownResolutionConflict.make({
|
|
780
|
+
submissionId: command.submissionId,
|
|
781
|
+
toolCallId: command.toolCallId
|
|
782
|
+
})), current];
|
|
783
|
+
const intent = existing?.intent ?? UnknownResolutionIntent.make({
|
|
784
|
+
submissionId: command.submissionId,
|
|
785
|
+
toolCallId: command.toolCallId,
|
|
786
|
+
author: command.author,
|
|
787
|
+
reason: command.reason,
|
|
788
|
+
resolution: command.resolution,
|
|
789
|
+
resolvedAt: utc(nowMillis)
|
|
790
|
+
});
|
|
791
|
+
const unknownResolutions = existing !== void 0 ? stored.unknownResolutions : new Map(stored.unknownResolutions).set(command.toolCallId, { intent });
|
|
792
|
+
const wakes = stored.row.state === "unknown" && stored.unknownMark !== void 0 && stored.unknownMark.toolCallIds.every((toolCallId) => unknownResolutions.has(toolCallId));
|
|
793
|
+
return [success(intent), withSubmission(current, {
|
|
794
|
+
...stored,
|
|
795
|
+
row: wakes ? {
|
|
796
|
+
...stored.row,
|
|
797
|
+
state: "input-applied"
|
|
798
|
+
} : stored.row,
|
|
799
|
+
unknownMark: wakes ? void 0 : stored.unknownMark,
|
|
800
|
+
unknownResolutions
|
|
801
|
+
})];
|
|
802
|
+
});
|
|
803
|
+
if (decision._tag === "failure") return yield* decision.error;
|
|
804
|
+
return decision.value;
|
|
805
|
+
}));
|
|
806
|
+
const recordChildSettled = Effect.fn("MemorySubmissionLedger.recordChildSettled")((unvalidated) => Effect.gen(function* () {
|
|
807
|
+
const request = yield* validate(ChildSettledNotification, "recordChildSettled", unvalidated);
|
|
808
|
+
const decision = yield* Ref.modify(state, (current) => {
|
|
809
|
+
const parent = current.submissions.get(request.parentSubmissionId);
|
|
810
|
+
if (parent === void 0) return [failure(ledgerError("recordChildSettled", `Unknown Submission ${request.parentSubmissionId}`)), current];
|
|
811
|
+
const child = current.submissions.get(request.childSubmissionId);
|
|
812
|
+
if (!(child !== void 0 && (child.row.state === "settled" || child.row.state === "terminalizing" && child.reservation !== void 0))) return [failure(ledgerError("recordChildSettled", `Child Submission ${request.childSubmissionId} has no recorded settlement`)), current];
|
|
813
|
+
if (parent.row.state !== "suspended" || parent.suspension === void 0 || parent.suspension.reason._tag !== "WaitingForChild") return [success("not-waiting"), current];
|
|
814
|
+
const children = parent.suspension.reason.children;
|
|
815
|
+
if (!children.some((entry) => entry.childSubmissionId === request.childSubmissionId)) return [success("not-waiting"), current];
|
|
816
|
+
if (!children.every((entry) => {
|
|
817
|
+
const listed = current.submissions.get(entry.childSubmissionId);
|
|
818
|
+
return listed?.row.state === "settled" || listed?.row.state === "terminalizing" && listed.reservation !== void 0;
|
|
819
|
+
})) return [success("still-waiting"), current];
|
|
820
|
+
return [success("woken"), withSubmission(current, {
|
|
821
|
+
...parent,
|
|
822
|
+
row: {
|
|
823
|
+
...parent.row,
|
|
824
|
+
state: "input-applied"
|
|
825
|
+
},
|
|
826
|
+
suspension: void 0
|
|
827
|
+
})];
|
|
828
|
+
});
|
|
829
|
+
if (decision._tag === "failure") return yield* decision.error;
|
|
830
|
+
return decision.value;
|
|
831
|
+
}));
|
|
832
|
+
const reserveChildBudget = Effect.fn("MemorySubmissionLedger.reserveChildBudget")((unvalidated) => Effect.gen(function* () {
|
|
833
|
+
const request = yield* validate(ChildBudgetReservationRequest, "reserveChildBudget", unvalidated);
|
|
834
|
+
const nowMillis = yield* Clock.currentTimeMillis;
|
|
835
|
+
const decision = yield* Ref.modify(state, (current) => {
|
|
836
|
+
const existing = current.childReservations.get(request.reservationId);
|
|
837
|
+
if (existing !== void 0) {
|
|
838
|
+
if (!(existing.parentSubmissionId === request.parentSubmissionId && existing.parentToolCallId === request.parentToolCallId && existing.allocationDigest === request.allocationDigest && equivalentPersistedJson(existing.allocation, request.allocation))) return [failure(ChildReservationConflict.make({
|
|
839
|
+
reservationId: request.reservationId,
|
|
840
|
+
status: existing.status,
|
|
841
|
+
message: "A reservation with this identity exists with a different parent Tool Call or allocation."
|
|
842
|
+
})), current];
|
|
843
|
+
return [success(ReservedChildBudget.make({
|
|
844
|
+
reservation: toReservationSnapshot(existing),
|
|
845
|
+
replayed: true
|
|
846
|
+
})), current];
|
|
847
|
+
}
|
|
848
|
+
for (const reservation of current.childReservations.values()) if (reservation.parentSubmissionId === request.parentSubmissionId && reservation.parentToolCallId === request.parentToolCallId) return [failure(ChildReservationConflict.make({
|
|
849
|
+
reservationId: request.reservationId,
|
|
850
|
+
status: reservation.status,
|
|
851
|
+
message: `Parent Tool Call ${request.parentToolCallId} already owns reservation ${reservation.reservationId}.`
|
|
852
|
+
})), current];
|
|
853
|
+
const parent = current.submissions.get(request.parentSubmissionId);
|
|
854
|
+
if (parent === void 0) return [failure(ledgerError("reserveChildBudget", `Unknown Submission ${request.parentSubmissionId}`)), current];
|
|
855
|
+
if (!ownsLane(parent, request.ownershipToken)) return [failure(ownershipLost(current, parent)), current];
|
|
856
|
+
const reservation = {
|
|
857
|
+
reservationId: request.reservationId,
|
|
858
|
+
parentSubmissionId: request.parentSubmissionId,
|
|
859
|
+
parentToolCallId: request.parentToolCallId,
|
|
860
|
+
childSubmissionId: void 0,
|
|
861
|
+
status: "reserved",
|
|
862
|
+
allocation: request.allocation,
|
|
863
|
+
allocationDigest: request.allocationDigest,
|
|
864
|
+
accounting: void 0,
|
|
865
|
+
reservedAtMillis: nowMillis,
|
|
866
|
+
releaseBeganAtMillis: void 0,
|
|
867
|
+
releasedAtMillis: void 0
|
|
868
|
+
};
|
|
869
|
+
return [success(ReservedChildBudget.make({
|
|
870
|
+
reservation: toReservationSnapshot(reservation),
|
|
871
|
+
replayed: false
|
|
872
|
+
})), withChildReservation(current, reservation)];
|
|
873
|
+
});
|
|
874
|
+
if (decision._tag === "failure") return yield* decision.error;
|
|
875
|
+
return decision.value;
|
|
876
|
+
}));
|
|
877
|
+
const attachChildToReservation = Effect.fn("MemorySubmissionLedger.attachChildToReservation")((unvalidated) => Effect.gen(function* () {
|
|
878
|
+
const request = yield* validate(AttachChildToReservationRequest, "attachChildToReservation", unvalidated);
|
|
879
|
+
const decision = yield* Ref.modify(state, (current) => {
|
|
880
|
+
const reservation = current.childReservations.get(request.reservationId);
|
|
881
|
+
if (reservation === void 0) return [failure(ledgerError("attachChildToReservation", `Unknown child reservation ${request.reservationId}`)), current];
|
|
882
|
+
if (reservation.childSubmissionId !== void 0) {
|
|
883
|
+
if (reservation.childSubmissionId === request.childSubmissionId) return [success(toReservationSnapshot(reservation)), current];
|
|
884
|
+
return [failure(ChildReservationConflict.make({
|
|
885
|
+
reservationId: request.reservationId,
|
|
886
|
+
status: reservation.status,
|
|
887
|
+
message: `Reservation ${request.reservationId} already records child ${reservation.childSubmissionId}.`
|
|
888
|
+
})), current];
|
|
889
|
+
}
|
|
890
|
+
const parent = current.submissions.get(reservation.parentSubmissionId);
|
|
891
|
+
if (parent === void 0) return [failure(ledgerError("attachChildToReservation", `Unknown Submission ${reservation.parentSubmissionId}`)), current];
|
|
892
|
+
if (!ownsLane(parent, request.ownershipToken)) return [failure(ownershipLost(current, parent)), current];
|
|
893
|
+
if (reservation.status !== "reserved") return [failure(ChildReservationConflict.make({
|
|
894
|
+
reservationId: request.reservationId,
|
|
895
|
+
status: reservation.status,
|
|
896
|
+
message: `Cannot attach a child to a ${reservation.status} reservation.`
|
|
897
|
+
})), current];
|
|
898
|
+
if (!current.submissions.has(request.childSubmissionId)) return [failure(ledgerError("attachChildToReservation", `Unknown child Submission ${request.childSubmissionId}`)), current];
|
|
899
|
+
const attached = {
|
|
900
|
+
...reservation,
|
|
901
|
+
childSubmissionId: request.childSubmissionId
|
|
902
|
+
};
|
|
903
|
+
return [success(toReservationSnapshot(attached)), withChildReservation(current, attached)];
|
|
904
|
+
});
|
|
905
|
+
if (decision._tag === "failure") return yield* decision.error;
|
|
906
|
+
return decision.value;
|
|
907
|
+
}));
|
|
908
|
+
const beginChildBudgetRelease = Effect.fn("MemorySubmissionLedger.beginChildBudgetRelease")((unvalidated) => Effect.gen(function* () {
|
|
909
|
+
const request = yield* validate(BeginChildBudgetReleaseRequest, "beginChildBudgetRelease", unvalidated);
|
|
910
|
+
const nowMillis = yield* Clock.currentTimeMillis;
|
|
911
|
+
const decision = yield* Ref.modify(state, (current) => {
|
|
912
|
+
const reservation = current.childReservations.get(request.reservationId);
|
|
913
|
+
if (reservation === void 0) return [failure(ledgerError("beginChildBudgetRelease", `Unknown child reservation ${request.reservationId}`)), current];
|
|
914
|
+
if (reservation.status !== "reserved") {
|
|
915
|
+
if (reservation.accounting !== void 0 && equivalentPersistedJson(reservation.accounting, request.accounting)) return [success(toReservationSnapshot(reservation)), current];
|
|
916
|
+
return [failure(ChildReservationConflict.make({
|
|
917
|
+
reservationId: request.reservationId,
|
|
918
|
+
status: reservation.status,
|
|
919
|
+
message: "A different accounting decision is already frozen for this reservation."
|
|
920
|
+
})), current];
|
|
921
|
+
}
|
|
922
|
+
const frozen = {
|
|
923
|
+
...reservation,
|
|
924
|
+
status: "releasePending",
|
|
925
|
+
accounting: request.accounting,
|
|
926
|
+
releaseBeganAtMillis: nowMillis
|
|
927
|
+
};
|
|
928
|
+
return [success(toReservationSnapshot(frozen)), withChildReservation(current, frozen)];
|
|
929
|
+
});
|
|
930
|
+
if (decision._tag === "failure") return yield* decision.error;
|
|
931
|
+
return decision.value;
|
|
932
|
+
}));
|
|
933
|
+
const releaseChildBudget = Effect.fn("MemorySubmissionLedger.releaseChildBudget")((unvalidated) => Effect.gen(function* () {
|
|
934
|
+
const request = yield* validate(ReleaseChildBudgetRequest, "releaseChildBudget", unvalidated);
|
|
935
|
+
const nowMillis = yield* Clock.currentTimeMillis;
|
|
936
|
+
const decision = yield* Ref.modify(state, (current) => {
|
|
937
|
+
const reservation = current.childReservations.get(request.reservationId);
|
|
938
|
+
if (reservation === void 0) return [failure(ledgerError("releaseChildBudget", `Unknown child reservation ${request.reservationId}`)), current];
|
|
939
|
+
if (reservation.status === "released") return [success(toReservationSnapshot(reservation)), current];
|
|
940
|
+
if (reservation.status !== "releasePending") return [failure(ChildReservationConflict.make({
|
|
941
|
+
reservationId: request.reservationId,
|
|
942
|
+
status: reservation.status,
|
|
943
|
+
message: "Cannot release a reservation whose accounting decision is not frozen."
|
|
944
|
+
})), current];
|
|
945
|
+
const released = {
|
|
946
|
+
...reservation,
|
|
947
|
+
status: "released",
|
|
948
|
+
releasedAtMillis: nowMillis
|
|
949
|
+
};
|
|
950
|
+
return [success(toReservationSnapshot(released)), withChildReservation(current, released)];
|
|
951
|
+
});
|
|
952
|
+
if (decision._tag === "failure") return yield* decision.error;
|
|
953
|
+
return decision.value;
|
|
954
|
+
}));
|
|
955
|
+
const scanNonterminal = Stream.unwrap(Ref.get(state).pipe(Effect.map((current) => {
|
|
956
|
+
const snapshots = [...current.submissions.values()].filter((stored) => stored.row.state !== "settled").sort((left, right) => left.row.threadId < right.row.threadId ? -1 : left.row.threadId > right.row.threadId ? 1 : left.row.queueSequence - right.row.queueSequence).map((stored) => toSnapshot(stored.row));
|
|
957
|
+
return Stream.fromIterable(snapshots);
|
|
958
|
+
})));
|
|
959
|
+
const readAbortIntent = Effect.fn("MemorySubmissionLedger.readAbortIntent")(function* (unvalidated) {
|
|
960
|
+
const request = yield* validate(AbortIntentRequest, "readAbortIntent", unvalidated);
|
|
961
|
+
const stored = (yield* Ref.get(state)).submissions.get(request.submissionId);
|
|
962
|
+
if (stored === void 0) return yield* ledgerError("readAbortIntent", `Unknown Submission ${request.submissionId}`);
|
|
963
|
+
return stored.abortIntent;
|
|
964
|
+
});
|
|
965
|
+
const loadRecoverySnapshot = Effect.fn("MemorySubmissionLedger.loadRecoverySnapshot")((unvalidated) => Effect.gen(function* () {
|
|
966
|
+
const request = yield* validate(RecoverySnapshotRequest, "loadRecoverySnapshot", unvalidated);
|
|
967
|
+
const current = yield* Ref.get(state);
|
|
968
|
+
const stored = current.submissions.get(request.submissionId);
|
|
969
|
+
if (stored === void 0) return yield* ledgerError("loadRecoverySnapshot", `Unknown Submission ${request.submissionId}`);
|
|
970
|
+
const joins = [...current.submissions.values()].filter((candidate) => candidate.joinedHostSubmissionId === request.submissionId).sort((left, right) => left.row.queueSequence - right.row.queueSequence).map((candidate) => JoinSnapshot.make({
|
|
971
|
+
submissionId: candidate.row.submissionId,
|
|
972
|
+
state: candidate.row.state,
|
|
973
|
+
hostSubmissionId: request.submissionId
|
|
974
|
+
}));
|
|
975
|
+
const byToolCallId = (left, right) => left.toolCallId < right.toolCallId ? -1 : left.toolCallId > right.toolCallId ? 1 : 0;
|
|
976
|
+
const childReservations = [...current.childReservations.values()].filter((reservation) => reservation.parentSubmissionId === request.submissionId).sort((left, right) => left.parentToolCallId < right.parentToolCallId ? -1 : left.parentToolCallId > right.parentToolCallId ? 1 : 0);
|
|
977
|
+
const childAttachments = [];
|
|
978
|
+
for (const reservation of childReservations) {
|
|
979
|
+
if (reservation.childSubmissionId === void 0) continue;
|
|
980
|
+
const child = current.submissions.get(reservation.childSubmissionId);
|
|
981
|
+
if (child === void 0) continue;
|
|
982
|
+
childAttachments.push(ChildAttachmentSnapshot.make({
|
|
983
|
+
toolCallId: reservation.parentToolCallId,
|
|
984
|
+
childSubmissionId: reservation.childSubmissionId,
|
|
985
|
+
childState: child.row.state,
|
|
986
|
+
...child.row.settledOutcome === void 0 ? {} : { childOutcome: child.row.settledOutcome }
|
|
987
|
+
}));
|
|
988
|
+
}
|
|
989
|
+
return RecoverySnapshot.make({
|
|
990
|
+
submission: toSnapshot(stored.row),
|
|
991
|
+
joins,
|
|
992
|
+
approvalDecisions: [...stored.approvalDecisions.values()].sort(byToolCallId),
|
|
993
|
+
unknownResolutions: [...stored.unknownResolutions.values()].map((resolution) => resolution.intent).sort(byToolCallId),
|
|
994
|
+
childReservations: childReservations.map(toReservationSnapshot),
|
|
995
|
+
childAttachments,
|
|
996
|
+
...stored.row.parentLinkage === void 0 ? {} : { parentLinkage: stored.row.parentLinkage },
|
|
997
|
+
...stored.joinedHostSubmissionId === void 0 ? {} : { hostSubmissionId: stored.joinedHostSubmissionId },
|
|
998
|
+
...stored.suspension === void 0 ? {} : { suspension: SuspensionSnapshot.make({
|
|
999
|
+
reason: stored.suspension.reason,
|
|
1000
|
+
suspendedAt: utc(stored.suspension.suspendedAtMillis)
|
|
1001
|
+
}) },
|
|
1002
|
+
...stored.ownership === void 0 ? {} : { ownership: OwnershipSnapshot.make({
|
|
1003
|
+
attemptId: stored.ownership.attemptId,
|
|
1004
|
+
ownerProducerId: stored.ownership.ownerProducerId,
|
|
1005
|
+
producerEpoch: stored.ownership.producerEpoch,
|
|
1006
|
+
leaseExpiresAt: utc(stored.ownership.leaseExpiresAtMillis)
|
|
1007
|
+
}) },
|
|
1008
|
+
...stored.inputApplied === void 0 ? {} : { inputApplied: stored.inputApplied },
|
|
1009
|
+
...stored.reservation === void 0 ? {} : { reservation: SettlementReservationSnapshot.make({
|
|
1010
|
+
settlementId: stored.reservation.settlementId,
|
|
1011
|
+
outcome: stored.reservation.outcome,
|
|
1012
|
+
record: stored.reservation.record,
|
|
1013
|
+
recordDigest: stored.reservation.recordDigest,
|
|
1014
|
+
finalized: stored.reservation.finalizedAtMillis !== void 0
|
|
1015
|
+
}) },
|
|
1016
|
+
...stored.abortIntent === void 0 ? {} : { abortIntent: stored.abortIntent }
|
|
1017
|
+
});
|
|
1018
|
+
}));
|
|
1019
|
+
return SubmissionLedger.of({
|
|
1020
|
+
capabilities,
|
|
1021
|
+
admit,
|
|
1022
|
+
markReady,
|
|
1023
|
+
lookup,
|
|
1024
|
+
resolveAdmission,
|
|
1025
|
+
claim,
|
|
1026
|
+
renewOwnership,
|
|
1027
|
+
releaseOwnership,
|
|
1028
|
+
markInputApplied,
|
|
1029
|
+
reserveSettlement,
|
|
1030
|
+
finalizeSettlement,
|
|
1031
|
+
requestAbort,
|
|
1032
|
+
claimJoining,
|
|
1033
|
+
markJoined,
|
|
1034
|
+
revertJoining,
|
|
1035
|
+
suspend,
|
|
1036
|
+
recordApprovalDecision,
|
|
1037
|
+
markUnknown,
|
|
1038
|
+
recordUnknownResolution,
|
|
1039
|
+
recordChildSettled,
|
|
1040
|
+
reserveChildBudget,
|
|
1041
|
+
attachChildToReservation,
|
|
1042
|
+
beginChildBudgetRelease,
|
|
1043
|
+
releaseChildBudget,
|
|
1044
|
+
scanNonterminal,
|
|
1045
|
+
loadRecoverySnapshot,
|
|
1046
|
+
readAbortIntent
|
|
1047
|
+
});
|
|
1048
|
+
});
|
|
1049
|
+
/**
|
|
1050
|
+
* In-memory reference SubmissionLedger Layer (durability `non-durable`). All state lives in one
|
|
1051
|
+
* `Ref` owned by the Layer's Scope; no daemon fibers are spawned and no wall clock is consulted.
|
|
1052
|
+
*/
|
|
1053
|
+
const memorySubmissionLedgerLayer = (options = {}) => Layer.effect(SubmissionLedger, makeSubmissionLedger(options));
|
|
1054
|
+
const MemorySubmissionLedgerLive = memorySubmissionLedgerLayer();
|
|
1055
|
+
//#endregion
|
|
1056
|
+
export { MemorySubmissionLedgerLive, memorySubmissionLedgerLayer, MemorySubmissionLedger_exports as t };
|
|
1057
|
+
|
|
1058
|
+
//# sourceMappingURL=MemorySubmissionLedger.mjs.map
|