@proofoftech/flowsafe 0.20.0 → 0.21.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/CHANGELOG.md +81 -0
- package/README.md +55 -8
- package/deployment-identity-protocol.d.mts +28 -3
- package/deployment-identity-protocol.mjs +275 -21
- package/dist/agent-host/router.d.ts.map +1 -1
- package/dist/agent-host/router.js +11 -2
- package/dist/agent-host/router.js.map +1 -1
- package/dist/agent-host/thread-host.d.ts +3 -1
- package/dist/agent-host/thread-host.d.ts.map +1 -1
- package/dist/agent-host/thread-host.js +837 -332
- package/dist/agent-host/thread-host.js.map +1 -1
- package/dist/agent-host/thread-topology.d.ts +8 -0
- package/dist/agent-host/thread-topology.d.ts.map +1 -1
- package/dist/agent-host/thread-topology.js +239 -62
- package/dist/agent-host/thread-topology.js.map +1 -1
- package/dist/agent-runner/durable-agent-runner.d.ts +90 -6
- package/dist/agent-runner/durable-agent-runner.d.ts.map +1 -1
- package/dist/agent-runner/durable-agent-runner.js +371 -29
- package/dist/agent-runner/durable-agent-runner.js.map +1 -1
- package/dist/agent-runner/index.d.ts +1 -1
- package/dist/agent-runner/index.d.ts.map +1 -1
- package/dist/agent-runner/index.js.map +1 -1
- package/dist/approval-api/actor-context.d.ts +4 -0
- package/dist/approval-api/actor-context.d.ts.map +1 -1
- package/dist/approval-api/actor-context.js +53 -5
- package/dist/approval-api/actor-context.js.map +1 -1
- package/dist/approval-api/principal.d.ts +1 -1
- package/dist/approval-api/principal.js +1 -1
- package/dist/approval-api/retention.d.ts +1 -2
- package/dist/approval-api/retention.d.ts.map +1 -1
- package/dist/approval-api/retention.js.map +1 -1
- package/dist/approval-api/service.d.ts +10 -14
- package/dist/approval-api/service.d.ts.map +1 -1
- package/dist/approval-api/service.js +49 -22
- package/dist/approval-api/service.js.map +1 -1
- package/dist/audit-export/index.d.ts +2 -2
- package/dist/audit-export/index.js +2 -2
- package/dist/background-tasks/d1-storage.d.ts +4 -3
- package/dist/background-tasks/d1-storage.d.ts.map +1 -1
- package/dist/background-tasks/d1-storage.js +7 -13
- package/dist/background-tasks/d1-storage.js.map +1 -1
- package/dist/do-runner/constants.d.ts +3 -0
- package/dist/do-runner/constants.d.ts.map +1 -0
- package/dist/do-runner/constants.js +3 -0
- package/dist/do-runner/constants.js.map +1 -0
- package/dist/do-runner/d1-storage.d.ts +31 -157
- package/dist/do-runner/d1-storage.d.ts.map +1 -1
- package/dist/do-runner/d1-storage.js +933 -402
- package/dist/do-runner/d1-storage.js.map +1 -1
- package/dist/do-runner/durable-object.d.ts.map +1 -1
- package/dist/do-runner/durable-object.js +462 -175
- package/dist/do-runner/durable-object.js.map +1 -1
- package/dist/do-runner/execution-admission.d.ts +114 -0
- package/dist/do-runner/execution-admission.d.ts.map +1 -0
- package/dist/do-runner/execution-admission.js +206 -0
- package/dist/do-runner/execution-admission.js.map +1 -0
- package/dist/do-runner/execution-context.d.ts.map +1 -1
- package/dist/do-runner/execution-context.js +1 -0
- package/dist/do-runner/execution-context.js.map +1 -1
- package/dist/do-runner/execution-fence.d.ts +74 -30
- package/dist/do-runner/execution-fence.d.ts.map +1 -1
- package/dist/do-runner/execution-fence.js +684 -120
- package/dist/do-runner/execution-fence.js.map +1 -1
- package/dist/do-runner/fenced-workflow-capability.d.ts +64 -0
- package/dist/do-runner/fenced-workflow-capability.d.ts.map +1 -0
- package/dist/do-runner/fenced-workflow-capability.js +3 -0
- package/dist/do-runner/fenced-workflow-capability.js.map +1 -0
- package/dist/do-runner/fenced-workflows-d1.d.ts +15 -0
- package/dist/do-runner/fenced-workflows-d1.d.ts.map +1 -0
- package/dist/do-runner/fenced-workflows-d1.js +894 -0
- package/dist/do-runner/fenced-workflows-d1.js.map +1 -0
- package/dist/do-runner/index.d.ts +13 -8
- package/dist/do-runner/index.d.ts.map +1 -1
- package/dist/do-runner/index.js +6 -2
- package/dist/do-runner/index.js.map +1 -1
- package/dist/do-runner/initial-admission-refusal.d.ts +7 -0
- package/dist/do-runner/initial-admission-refusal.d.ts.map +1 -0
- package/dist/do-runner/initial-admission-refusal.js +41 -0
- package/dist/do-runner/initial-admission-refusal.js.map +1 -0
- package/dist/do-runner/inventory.d.ts +2 -1
- package/dist/do-runner/inventory.d.ts.map +1 -1
- package/dist/do-runner/inventory.js +28 -39
- package/dist/do-runner/inventory.js.map +1 -1
- package/dist/do-runner/notification-predicate.d.ts +7 -7
- package/dist/do-runner/notification-predicate.d.ts.map +1 -1
- package/dist/do-runner/notification-predicate.js +134 -7
- package/dist/do-runner/notification-predicate.js.map +1 -1
- package/dist/do-runner/run-lifecycle.d.ts +20 -1
- package/dist/do-runner/run-lifecycle.d.ts.map +1 -1
- package/dist/do-runner/run-lifecycle.js +67 -13
- package/dist/do-runner/run-lifecycle.js.map +1 -1
- package/dist/do-runner/run-provenance.d.ts +38 -0
- package/dist/do-runner/run-provenance.d.ts.map +1 -0
- package/dist/do-runner/run-provenance.js +152 -0
- package/dist/do-runner/run-provenance.js.map +1 -0
- package/dist/do-runner/run-storage-tables.d.ts +2 -0
- package/dist/do-runner/run-storage-tables.d.ts.map +1 -0
- package/dist/do-runner/run-storage-tables.js +4 -0
- package/dist/do-runner/run-storage-tables.js.map +1 -0
- package/dist/do-runner/run-terminal-state.d.ts +29 -0
- package/dist/do-runner/run-terminal-state.d.ts.map +1 -0
- package/dist/do-runner/run-terminal-state.js +105 -0
- package/dist/do-runner/run-terminal-state.js.map +1 -0
- package/dist/do-runner/runtime.d.ts +108 -46
- package/dist/do-runner/runtime.d.ts.map +1 -1
- package/dist/do-runner/runtime.js +927 -438
- package/dist/do-runner/runtime.js.map +1 -1
- package/dist/do-runner/start-idempotency.d.ts +35 -258
- package/dist/do-runner/start-idempotency.d.ts.map +1 -1
- package/dist/do-runner/start-idempotency.js +602 -494
- package/dist/do-runner/start-idempotency.js.map +1 -1
- package/dist/do-runner/start-reservation-contract.d.ts +103 -0
- package/dist/do-runner/start-reservation-contract.d.ts.map +1 -0
- package/dist/do-runner/start-reservation-contract.js +338 -0
- package/dist/do-runner/start-reservation-contract.js.map +1 -0
- package/dist/do-runner/suspension-deadline.d.ts +4 -11
- package/dist/do-runner/suspension-deadline.d.ts.map +1 -1
- package/dist/do-runner/suspension-deadline.js +8 -12
- package/dist/do-runner/suspension-deadline.js.map +1 -1
- package/dist/do-runner/table-prefix.d.ts.map +1 -1
- package/dist/do-runner/table-prefix.js +2 -1
- package/dist/do-runner/table-prefix.js.map +1 -1
- package/dist/do-runner/testing.d.ts +3 -0
- package/dist/do-runner/testing.d.ts.map +1 -0
- package/dist/do-runner/testing.js +3 -0
- package/dist/do-runner/testing.js.map +1 -0
- package/dist/do-runner/thread-do.d.ts +2 -1
- package/dist/do-runner/thread-do.d.ts.map +1 -1
- package/dist/do-runner/thread-do.js +14 -10
- package/dist/do-runner/thread-do.js.map +1 -1
- package/dist/do-runner/workflow-snapshot-row.d.ts +49 -0
- package/dist/do-runner/workflow-snapshot-row.d.ts.map +1 -0
- package/dist/do-runner/workflow-snapshot-row.js +97 -0
- package/dist/do-runner/workflow-snapshot-row.js.map +1 -0
- package/dist/goals/objective-routes.d.ts +1 -5
- package/dist/goals/objective-routes.d.ts.map +1 -1
- package/dist/goals/objective-routes.js +32 -53
- package/dist/goals/objective-routes.js.map +1 -1
- package/dist/host-kit/approval-bridge.d.ts.map +1 -1
- package/dist/host-kit/approval-bridge.js +10 -7
- package/dist/host-kit/approval-bridge.js.map +1 -1
- package/dist/host-kit/do-response.d.ts +16 -0
- package/dist/host-kit/do-response.d.ts.map +1 -1
- package/dist/host-kit/do-response.js +181 -0
- package/dist/host-kit/do-response.js.map +1 -1
- package/dist/host-kit/do-run-topology.d.ts +2 -14
- package/dist/host-kit/do-run-topology.d.ts.map +1 -1
- package/dist/host-kit/do-run-topology.js +31 -24
- package/dist/host-kit/do-run-topology.js.map +1 -1
- package/dist/host-kit/env-vars.d.ts.map +1 -1
- package/dist/host-kit/env-vars.js +5 -6
- package/dist/host-kit/env-vars.js.map +1 -1
- package/dist/host-kit/flowsafe-worker.d.ts +38 -6
- package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
- package/dist/host-kit/flowsafe-worker.js +110 -93
- package/dist/host-kit/flowsafe-worker.js.map +1 -1
- package/dist/host-kit/host-approval-service.d.ts +4 -14
- package/dist/host-kit/host-approval-service.d.ts.map +1 -1
- package/dist/host-kit/host-approval-service.js +23 -40
- package/dist/host-kit/host-approval-service.js.map +1 -1
- package/dist/host-kit/index.d.ts +7 -1
- package/dist/host-kit/index.d.ts.map +1 -1
- package/dist/host-kit/index.js +4 -0
- package/dist/host-kit/index.js.map +1 -1
- package/dist/host-kit/run-route-error.d.ts +3 -17
- package/dist/host-kit/run-route-error.d.ts.map +1 -1
- package/dist/host-kit/run-route-error.js +4 -24
- package/dist/host-kit/run-route-error.js.map +1 -1
- package/dist/host-kit/run-router.d.ts +6 -2
- package/dist/host-kit/run-router.d.ts.map +1 -1
- package/dist/host-kit/run-router.js +93 -80
- package/dist/host-kit/run-router.js.map +1 -1
- package/dist/host-kit/thread-topology.d.ts +1 -1
- package/dist/host-kit/thread-topology.d.ts.map +1 -1
- package/dist/host-kit/thread-topology.js +7 -3
- package/dist/host-kit/thread-topology.js.map +1 -1
- package/dist/internal-error-response.d.ts.map +1 -1
- package/dist/internal-error-response.js +16 -6
- package/dist/internal-error-response.js.map +1 -1
- package/dist/schedules/index.d.ts +1 -0
- package/dist/schedules/index.d.ts.map +1 -1
- package/dist/schedules/index.js +1 -7
- package/dist/schedules/index.js.map +1 -1
- package/dist/schedules/mutation-contract.d.ts +38 -0
- package/dist/schedules/mutation-contract.d.ts.map +1 -0
- package/dist/schedules/mutation-contract.js +21 -0
- package/dist/schedules/mutation-contract.js.map +1 -0
- package/dist/schedules/router.d.ts +11 -19
- package/dist/schedules/router.d.ts.map +1 -1
- package/dist/schedules/router.js +130 -49
- package/dist/schedules/router.js.map +1 -1
- package/dist/schedules/schedules-d1.d.ts +11 -5
- package/dist/schedules/schedules-d1.d.ts.map +1 -1
- package/dist/schedules/schedules-d1.js +570 -143
- package/dist/schedules/schedules-d1.js.map +1 -1
- package/dist/schedules/storage.d.ts +0 -7
- package/dist/schedules/storage.d.ts.map +1 -1
- package/dist/schedules/storage.js +0 -27
- package/dist/schedules/storage.js.map +1 -1
- package/dist/schedules/tick.d.ts.map +1 -1
- package/dist/schedules/tick.js +7 -1
- package/dist/schedules/tick.js.map +1 -1
- package/dist/signal-providers/webhook-route.d.ts +1 -1
- package/dist/signal-providers/webhook-route.d.ts.map +1 -1
- package/dist/signal-providers/webhook-route.js +99 -109
- package/dist/signal-providers/webhook-route.js.map +1 -1
- package/dist/signals/d1-shared.d.ts +11 -8
- package/dist/signals/d1-shared.d.ts.map +1 -1
- package/dist/signals/d1-shared.js +1 -6
- package/dist/signals/d1-shared.js.map +1 -1
- package/dist/signals/index.d.ts +1 -1
- package/dist/signals/index.d.ts.map +1 -1
- package/dist/signals/index.js +1 -1
- package/dist/signals/index.js.map +1 -1
- package/dist/signals/notification-dispatch.d.ts +96 -5
- package/dist/signals/notification-dispatch.d.ts.map +1 -1
- package/dist/signals/notification-dispatch.js +418 -53
- package/dist/signals/notification-dispatch.js.map +1 -1
- package/dist/signals/notifications-d1.d.ts +6 -1
- package/dist/signals/notifications-d1.d.ts.map +1 -1
- package/dist/signals/notifications-d1.js +215 -10
- package/dist/signals/notifications-d1.js.map +1 -1
- package/dist/signals/router.d.ts +6 -4
- package/dist/signals/router.d.ts.map +1 -1
- package/dist/signals/router.js +49 -84
- package/dist/signals/router.js.map +1 -1
- package/dist/signals/thread-do-routes.d.ts +2 -0
- package/dist/signals/thread-do-routes.d.ts.map +1 -1
- package/dist/signals/thread-do-routes.js +252 -73
- package/dist/signals/thread-do-routes.js.map +1 -1
- package/package.json +6 -3
- package/patches/@mastra__core@1.53.0.patch +54 -0
- package/scripts/seed-deployment-identity.mjs +12 -5
|
@@ -33,27 +33,22 @@
|
|
|
33
33
|
// it is logged, swallowed, and left for the next wake, because a thrown alarm
|
|
34
34
|
// is retried by workerd and would answer a storage incident with a storm.
|
|
35
35
|
//
|
|
36
|
-
//
|
|
36
|
+
// An absent legacy row (or absent TABLE) reads as `open`. That is the 0.19-to-0.20
|
|
37
37
|
// upgrade rule and nothing more: a database seeded before this table existed
|
|
38
38
|
// must keep serving. Provisioning writes an explicit row from 0.20 on, so a
|
|
39
39
|
// deployment that means to start locked says so rather than relying on a
|
|
40
40
|
// default — `seed()` therefore takes the state as a REQUIRED argument.
|
|
41
|
-
import {
|
|
41
|
+
import { decodeExecutionFenceMutationMetadata, EXECUTION_FENCE_CURRENT_SCHEMA_STAGE, EXECUTION_FENCE_ROW_ID, EXECUTION_FENCE_STATES, EXECUTION_FENCE_TABLE, initializeExecutionFenceProtocol, readExecutionFenceSchemaProtocol, } from '#deployment-identity-protocol';
|
|
42
42
|
import { missingTableReadsEmpty } from './cause-chain.js';
|
|
43
43
|
import { DoStatusError } from './do-status-error.js';
|
|
44
|
+
import { ExecutionFenceUnreadableError, InvalidExecutionIdentityError, normalizeD1RunExecutionIdentity, normalizeMutationEpoch, normalizeStartExecutionIdentity, } from './execution-admission.js';
|
|
45
|
+
import { RUN_PROVENANCE_CONTEXT_KEY } from './execution-context.js';
|
|
44
46
|
import { isPathSafeId } from './path-safe-id.js';
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
* @mastra/cloudflare-d1 with it) into their bundle.
|
|
51
|
-
*/
|
|
52
|
-
function changesOf(result) {
|
|
53
|
-
const changes = result?.meta
|
|
54
|
-
?.changes;
|
|
55
|
-
return typeof changes === 'number' ? changes : 0;
|
|
56
|
-
}
|
|
47
|
+
import { decodeProgressRunProvenance, decodeRunStartIdentity, } from './run-provenance.js';
|
|
48
|
+
import { isRunStatus } from './run-terminal-state.js';
|
|
49
|
+
import { captureBoundReservation, decodeStartReservationAdmissionResult, START_IDEMPOTENCY_TABLE, sameReservationIdentity, validateStartReservationAdmissionSchema, } from './start-reservation-contract.js';
|
|
50
|
+
import { decodeRawWorkflowSnapshotResult, prepareRawWorkflowSnapshotRead, } from './workflow-snapshot-row.js';
|
|
51
|
+
export { ExecutionFenceUnreadableError } from './execution-admission.js';
|
|
57
52
|
/**
|
|
58
53
|
* The suspend-payload key the executor backstop stamps on a task it parked
|
|
59
54
|
* because the deployment was fenced mid-dispatch. Namespaced so it cannot
|
|
@@ -72,6 +67,9 @@ export const EXECUTION_FENCE_SUSPEND_KEY = 'flowsafe.executionFenced';
|
|
|
72
67
|
/** The reading every unfenced surface uses — see `ExecutionFenceStore` absence. */
|
|
73
68
|
export const OPEN_EXECUTION_FENCE = Object.freeze({
|
|
74
69
|
state: 'open',
|
|
70
|
+
mutationEpoch: 0,
|
|
71
|
+
requireMutationEpoch: false,
|
|
72
|
+
transitionRevision: 0,
|
|
75
73
|
});
|
|
76
74
|
/**
|
|
77
75
|
* Read the fence a surface was wired with, resolving the typed opt-out.
|
|
@@ -149,25 +147,19 @@ export class ExecutionFencedError extends DoStatusError {
|
|
|
149
147
|
export class FenceTransitionConflictError extends DoStatusError {
|
|
150
148
|
status = 409;
|
|
151
149
|
reason;
|
|
152
|
-
constructor(expected, current) {
|
|
153
|
-
super(
|
|
150
|
+
constructor(expected, current, details) {
|
|
151
|
+
super(details === undefined
|
|
152
|
+
? `execution fence transition expected state '${expected}' but found '${current}'`
|
|
153
|
+
: 'execution fence transition conflicts with the current reading');
|
|
154
154
|
this.name = 'FenceTransitionConflictError';
|
|
155
|
-
this.reason =
|
|
156
|
-
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
*/
|
|
164
|
-
export class ExecutionFenceUnreadableError extends DoStatusError {
|
|
165
|
-
status = 503;
|
|
166
|
-
reason;
|
|
167
|
-
constructor(message, options) {
|
|
168
|
-
super(message, options);
|
|
169
|
-
this.name = 'ExecutionFenceUnreadableError';
|
|
170
|
-
this.reason = { code: 'EXECUTION_FENCE_UNREADABLE' };
|
|
155
|
+
this.reason =
|
|
156
|
+
details === undefined
|
|
157
|
+
? { code: 'FENCE_CAS_CONFLICT', state: current }
|
|
158
|
+
: {
|
|
159
|
+
code: 'FENCE_CAS_CONFLICT',
|
|
160
|
+
...executionFenceReadingPayload(details.reading),
|
|
161
|
+
conflict: details.conflict,
|
|
162
|
+
};
|
|
171
163
|
}
|
|
172
164
|
}
|
|
173
165
|
/**
|
|
@@ -188,17 +180,6 @@ export function executionFencedResponse(state, entry) {
|
|
|
188
180
|
},
|
|
189
181
|
});
|
|
190
182
|
}
|
|
191
|
-
/**
|
|
192
|
-
* A fence reading as the JSON body a control-plane read answers with.
|
|
193
|
-
*
|
|
194
|
-
* Beside `executionFencedResponse` and for the same reason: the published
|
|
195
|
-
* `GET /admin/execution-fence` route and the spike's local control probe both
|
|
196
|
-
* project a reading into this exact shape, and a projection written twice is
|
|
197
|
-
* one an operator's tooling can watch drift. Absent fields are OMITTED rather
|
|
198
|
-
* than sent as null — `proofKey`/`proofRunId` exist only in proof-only, and a
|
|
199
|
-
* null would invite a caller to read "no proof run yet" out of a state that has
|
|
200
|
-
* no proof at all.
|
|
201
|
-
*/
|
|
202
183
|
export function executionFenceReadingPayload(reading) {
|
|
203
184
|
return {
|
|
204
185
|
state: reading.state,
|
|
@@ -206,6 +187,15 @@ export function executionFenceReadingPayload(reading) {
|
|
|
206
187
|
...(reading.proofRunId === undefined
|
|
207
188
|
? {}
|
|
208
189
|
: { proofRunId: reading.proofRunId }),
|
|
190
|
+
...(reading.mutationEpoch === undefined
|
|
191
|
+
? {}
|
|
192
|
+
: { mutationEpoch: reading.mutationEpoch }),
|
|
193
|
+
...(reading.requireMutationEpoch === undefined
|
|
194
|
+
? {}
|
|
195
|
+
: { requireMutationEpoch: reading.requireMutationEpoch }),
|
|
196
|
+
...(reading.transitionRevision === undefined
|
|
197
|
+
? {}
|
|
198
|
+
: { transitionRevision: reading.transitionRevision }),
|
|
209
199
|
};
|
|
210
200
|
}
|
|
211
201
|
/** The two reason codes a fence refusal publishes, whatever carried it. */
|
|
@@ -231,7 +221,7 @@ const FENCE_REFUSAL_CODES = new Set([
|
|
|
231
221
|
*
|
|
232
222
|
* The two codes are matched by name rather than by any structural sniff: only
|
|
233
223
|
* refusals this package authors publish them, and both are declared as literals
|
|
234
|
-
* on the classes
|
|
224
|
+
* on the corresponding error classes, so a code arriving over the wire came from one of them.
|
|
235
225
|
*/
|
|
236
226
|
export function isExecutionFenceRefusal(error) {
|
|
237
227
|
if (error instanceof ExecutionFencedError ||
|
|
@@ -310,14 +300,27 @@ export function admitsRunStart(reading, idempotencyKey) {
|
|
|
310
300
|
* never finish, because finishing is what the suspended runs are waiting for.
|
|
311
301
|
* In proof-only, only the nominated run.
|
|
312
302
|
*/
|
|
313
|
-
export function admitsExistingRun(reading,
|
|
303
|
+
export function admitsExistingRun(reading, candidate) {
|
|
314
304
|
if (reading.state === 'open' || reading.state === 'draining')
|
|
315
305
|
return true;
|
|
316
|
-
if (reading.state !== 'proof-only'
|
|
306
|
+
if (reading.state !== 'proof-only' ||
|
|
307
|
+
typeof candidate !== 'object' ||
|
|
308
|
+
candidate === null ||
|
|
309
|
+
candidate.tablePrefix === null)
|
|
317
310
|
return false;
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
311
|
+
try {
|
|
312
|
+
const execution = normalizeD1RunExecutionIdentity(candidate);
|
|
313
|
+
const proof = reading.proofExecution;
|
|
314
|
+
return (execution.tablePrefix === candidate.tablePrefix &&
|
|
315
|
+
proof !== undefined &&
|
|
316
|
+
proof.tablePrefix === execution.tablePrefix &&
|
|
317
|
+
proof.workflowId === execution.workflowId &&
|
|
318
|
+
proof.runId === execution.runId &&
|
|
319
|
+
proof.startToken === execution.startToken);
|
|
320
|
+
}
|
|
321
|
+
catch {
|
|
322
|
+
return false;
|
|
323
|
+
}
|
|
321
324
|
}
|
|
322
325
|
/**
|
|
323
326
|
* May standing configuration that ARMS future work be authored — a schedule
|
|
@@ -337,27 +340,195 @@ export function admitsWorkAuthoring(reading) {
|
|
|
337
340
|
export function admitsDrainableExecution(reading) {
|
|
338
341
|
return reading.state === 'open' || reading.state === 'draining';
|
|
339
342
|
}
|
|
343
|
+
const FENCE_ADMISSION_FIELDS = [
|
|
344
|
+
'state',
|
|
345
|
+
'mutation_epoch',
|
|
346
|
+
'require_mutation_epoch',
|
|
347
|
+
'transition_revision',
|
|
348
|
+
'last_transition_request',
|
|
349
|
+
'proof_key',
|
|
350
|
+
'proof_run_id',
|
|
351
|
+
'proof_table_prefix',
|
|
352
|
+
'proof_workflow_id',
|
|
353
|
+
'proof_start_token',
|
|
354
|
+
];
|
|
355
|
+
/** @internal */
|
|
356
|
+
export function executionFenceAdmissionValues(observation) {
|
|
357
|
+
const values = FENCE_ADMISSION_FIELDS.map((key) => observation.raw[key]);
|
|
358
|
+
for (const value of values.slice(4)) {
|
|
359
|
+
if (value !== null && typeof value !== 'string') {
|
|
360
|
+
throw new ExecutionFenceUnreadableError('execution fence semantic fields are not readable');
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
return Object.freeze(values);
|
|
364
|
+
}
|
|
365
|
+
/** @internal */
|
|
366
|
+
export function executionFenceAdmissionSql(input) {
|
|
367
|
+
const { callerEpoch, semantic, schema, statePredicate } = input;
|
|
368
|
+
if (semantic.length !== FENCE_ADMISSION_FIELDS.length) {
|
|
369
|
+
throw new Error('execution fence admission parameter frame is invalid');
|
|
370
|
+
}
|
|
371
|
+
const nullable = FENCE_ADMISSION_FIELDS.slice(4)
|
|
372
|
+
.map((key, index) => {
|
|
373
|
+
const parameter = semantic[index + 4];
|
|
374
|
+
return `typeof(f.${key}) IN ('null', 'text')
|
|
375
|
+
AND typeof(f.${key}) = typeof(${parameter})
|
|
376
|
+
AND f.${key} COLLATE BINARY IS ${parameter}`;
|
|
377
|
+
})
|
|
378
|
+
.join(' AND ');
|
|
379
|
+
return `(SELECT json_group_array(json_array(name, type, "notnull", dflt_value, pk, hidden))
|
|
380
|
+
FROM (SELECT name, type, "notnull", dflt_value, pk, hidden
|
|
381
|
+
FROM pragma_table_xinfo('${EXECUTION_FENCE_TABLE}') ORDER BY cid)) COLLATE BINARY = ${schema}
|
|
382
|
+
AND (SELECT COUNT(*) FROM ${EXECUTION_FENCE_TABLE}) = 1
|
|
383
|
+
AND EXISTS (SELECT 1 FROM ${EXECUTION_FENCE_TABLE} AS f
|
|
384
|
+
WHERE typeof(f.id) = 'text' AND f.id COLLATE BINARY = 'deployment'
|
|
385
|
+
AND typeof(f.state) = 'text' AND f.state COLLATE BINARY IS ${semantic[0]}
|
|
386
|
+
AND typeof(f.mutation_epoch) = 'integer' AND f.mutation_epoch IS ${semantic[1]}
|
|
387
|
+
AND typeof(f.require_mutation_epoch) = 'integer' AND f.require_mutation_epoch IS ${semantic[2]}
|
|
388
|
+
AND typeof(f.transition_revision) = 'integer' AND f.transition_revision IS ${semantic[3]}
|
|
389
|
+
AND ${nullable}
|
|
390
|
+
AND (f.require_mutation_epoch = 0 OR f.mutation_epoch = ${callerEpoch})
|
|
391
|
+
AND (${statePredicate}))`;
|
|
392
|
+
}
|
|
393
|
+
function isFenceCounter(value) {
|
|
394
|
+
return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
|
|
395
|
+
}
|
|
396
|
+
function decodeTransitionReceipt(text) {
|
|
397
|
+
const value = JSON.parse(text);
|
|
398
|
+
if (text.length > 512 ||
|
|
399
|
+
!Array.isArray(value) ||
|
|
400
|
+
value.length !== 7 ||
|
|
401
|
+
value[0] !== 1 ||
|
|
402
|
+
!isExecutionFenceState(value[1]) ||
|
|
403
|
+
!isExecutionFenceState(value[2]) ||
|
|
404
|
+
(value[2] === 'proof-only' ? !isPathSafeId(value[3]) : value[3] !== null) ||
|
|
405
|
+
!isFenceCounter(value[4]) ||
|
|
406
|
+
!isFenceCounter(value[5]) ||
|
|
407
|
+
value[5] === Number.MAX_SAFE_INTEGER ||
|
|
408
|
+
typeof value[6] !== 'boolean' ||
|
|
409
|
+
(value[6] && value[4] === Number.MAX_SAFE_INTEGER) ||
|
|
410
|
+
JSON.stringify(value) !== text) {
|
|
411
|
+
throw new Error('execution fence transition receipt is malformed');
|
|
412
|
+
}
|
|
413
|
+
return [1, value[1], value[2], value[3], value[4], value[5], value[6]];
|
|
414
|
+
}
|
|
340
415
|
function readingFromRow(row) {
|
|
416
|
+
row = Object.freeze(Object.fromEntries(Object.getOwnPropertyNames(row).map((key) => [key, row[key]])));
|
|
417
|
+
const metadata = decodeExecutionFenceMutationMetadata(row);
|
|
341
418
|
const { state } = row;
|
|
342
|
-
if (!isExecutionFenceState(state)) {
|
|
343
|
-
|
|
344
|
-
// or a row written by a NEWER flowsafe that added a state. Returning
|
|
345
|
-
// `open` for either would answer "I do not understand this fence" with
|
|
346
|
-
// "there is no fence", which is the one answer that must never be wrong.
|
|
347
|
-
throw new ExecutionFenceUnreadableError(`execution fence row carries an unrecognized state '${String(state)}'`);
|
|
419
|
+
if (row.id !== EXECUTION_FENCE_ROW_ID || !isExecutionFenceState(state)) {
|
|
420
|
+
throw new Error('execution fence row is not a recognized singleton');
|
|
348
421
|
}
|
|
349
422
|
const proofKey = row.proof_key;
|
|
350
423
|
const proofRunId = row.proof_run_id;
|
|
424
|
+
let proofExecution;
|
|
425
|
+
if (metadata.proofStartToken !== null) {
|
|
426
|
+
proofExecution = normalizeD1RunExecutionIdentity({
|
|
427
|
+
tablePrefix: metadata.proofTablePrefix,
|
|
428
|
+
workflowId: metadata.proofWorkflowId,
|
|
429
|
+
runId: proofRunId,
|
|
430
|
+
startToken: metadata.proofStartToken,
|
|
431
|
+
});
|
|
432
|
+
if (proofExecution.tablePrefix !== metadata.proofTablePrefix ||
|
|
433
|
+
!isPathSafeId(proofKey)) {
|
|
434
|
+
throw new Error('execution fence proof identity is not canonical');
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
if (metadata.lastTransitionRequest !== null) {
|
|
438
|
+
const [, , next, key, epoch, revision, advance] = decodeTransitionReceipt(metadata.lastTransitionRequest);
|
|
439
|
+
if (state !== next ||
|
|
440
|
+
metadata.mutationEpoch !== epoch + Number(advance) ||
|
|
441
|
+
metadata.transitionRevision !== revision + 1 ||
|
|
442
|
+
(state === 'proof-only'
|
|
443
|
+
? proofKey !== key || (proofRunId !== null && !isPathSafeId(proofRunId))
|
|
444
|
+
: proofKey !== null || proofRunId !== null)) {
|
|
445
|
+
throw new Error('execution fence row disagrees with its transition receipt');
|
|
446
|
+
}
|
|
447
|
+
}
|
|
351
448
|
return {
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
:
|
|
356
|
-
|
|
357
|
-
? {
|
|
358
|
-
|
|
449
|
+
reading: {
|
|
450
|
+
state,
|
|
451
|
+
mutationEpoch: metadata.mutationEpoch,
|
|
452
|
+
requireMutationEpoch: metadata.requireMutationEpoch,
|
|
453
|
+
transitionRevision: metadata.transitionRevision,
|
|
454
|
+
...(proofExecution === undefined ? {} : { proofExecution }),
|
|
455
|
+
...(typeof proofKey === 'string' && proofKey.length > 0
|
|
456
|
+
? { proofKey }
|
|
457
|
+
: {}),
|
|
458
|
+
...(typeof proofRunId === 'string' && proofRunId.length > 0
|
|
459
|
+
? { proofRunId }
|
|
460
|
+
: {}),
|
|
461
|
+
},
|
|
462
|
+
receipt: metadata.lastTransitionRequest,
|
|
463
|
+
schemaStage: metadata.schemaStage,
|
|
464
|
+
raw: row,
|
|
359
465
|
};
|
|
360
466
|
}
|
|
467
|
+
function fenceResultRows(result) {
|
|
468
|
+
if (result === null ||
|
|
469
|
+
typeof result !== 'object' ||
|
|
470
|
+
('success' in result && result.success !== true) ||
|
|
471
|
+
!('results' in result)) {
|
|
472
|
+
throw new Error('execution fence statement returned an invalid result');
|
|
473
|
+
}
|
|
474
|
+
const rows = result.results;
|
|
475
|
+
if (!Array.isArray(rows))
|
|
476
|
+
throw new Error('execution fence statement returned an invalid result');
|
|
477
|
+
const length = rows.length;
|
|
478
|
+
if (!Number.isSafeInteger(length) || length < 0)
|
|
479
|
+
throw new Error('execution fence statement returned an invalid result');
|
|
480
|
+
return Array.from({ length }, (_, index) => {
|
|
481
|
+
if (!Object.hasOwn(rows, index))
|
|
482
|
+
throw new Error('execution fence statement returned an invalid row');
|
|
483
|
+
const row = rows[index];
|
|
484
|
+
if (row === null || typeof row !== 'object' || Array.isArray(row)) {
|
|
485
|
+
throw new Error('execution fence statement returned an invalid row');
|
|
486
|
+
}
|
|
487
|
+
return row;
|
|
488
|
+
});
|
|
489
|
+
}
|
|
490
|
+
function returningFence(result) {
|
|
491
|
+
const rows = fenceResultRows(result);
|
|
492
|
+
if (rows.length > 1)
|
|
493
|
+
throw new Error('execution fence UPDATE returned multiple rows');
|
|
494
|
+
const row = rows[0];
|
|
495
|
+
if (row === undefined)
|
|
496
|
+
return undefined;
|
|
497
|
+
const stored = readingFromRow(row);
|
|
498
|
+
if (stored.schemaStage !== EXECUTION_FENCE_CURRENT_SCHEMA_STAGE)
|
|
499
|
+
throw new Error('execution fence UPDATE returned a legacy row');
|
|
500
|
+
return stored;
|
|
501
|
+
}
|
|
502
|
+
/** @internal Validate an already-observed current-schema RETURNING row. */
|
|
503
|
+
export function decodeExecutionFenceAdmissionRow(row) {
|
|
504
|
+
const stored = readingFromRow(row);
|
|
505
|
+
if (stored.schemaStage !== 7)
|
|
506
|
+
throw new Error('initial admission requires current fence metadata');
|
|
507
|
+
return Object.freeze({
|
|
508
|
+
reading: Object.freeze(stored.reading),
|
|
509
|
+
schemaStage: 7,
|
|
510
|
+
raw: stored.raw,
|
|
511
|
+
});
|
|
512
|
+
}
|
|
513
|
+
/** @internal Validate actual PRAGMA rows from a consistent readback batch. */
|
|
514
|
+
export async function validateExecutionFenceAdmissionSchema(result) {
|
|
515
|
+
const columns = fenceResultRows(result);
|
|
516
|
+
if ((await readExecutionFenceSchemaProtocol(async () => columns)) !== 7)
|
|
517
|
+
throw new Error('initial admission requires the current fence schema');
|
|
518
|
+
}
|
|
519
|
+
/** @internal */
|
|
520
|
+
export async function captureExecutionFenceAdmissionSchema(result) {
|
|
521
|
+
const rows = fenceResultRows(result).map((row) => Object.freeze(Object.fromEntries(Object.getOwnPropertyNames(row).map((key) => [key, row[key]]))));
|
|
522
|
+
await validateExecutionFenceAdmissionSchema({ results: rows });
|
|
523
|
+
return JSON.stringify(rows.map(({ name, type, notnull, dflt_value, pk, hidden }) => [
|
|
524
|
+
name,
|
|
525
|
+
type,
|
|
526
|
+
notnull,
|
|
527
|
+
dflt_value,
|
|
528
|
+
pk,
|
|
529
|
+
hidden,
|
|
530
|
+
]));
|
|
531
|
+
}
|
|
361
532
|
/**
|
|
362
533
|
* SQLite/D1's "no such table", for THIS store's table: a table that was never
|
|
363
534
|
* created is not a fault here — it is a pre-0.20 database, which reads as
|
|
@@ -373,6 +544,62 @@ function readingFromRow(row) {
|
|
|
373
544
|
function isMissingFenceTable(error) {
|
|
374
545
|
return missingTableReadsEmpty(error, EXECUTION_FENCE_TABLE);
|
|
375
546
|
}
|
|
547
|
+
async function selectedProofObservation(db, address) {
|
|
548
|
+
try {
|
|
549
|
+
const prepared = prepareRawWorkflowSnapshotRead(db, address);
|
|
550
|
+
const raw = decodeRawWorkflowSnapshotResult(await prepared.statement.all(), prepared.address);
|
|
551
|
+
if (raw === undefined)
|
|
552
|
+
return undefined;
|
|
553
|
+
const snapshot = JSON.parse(raw.snapshot);
|
|
554
|
+
if (snapshot === null ||
|
|
555
|
+
typeof snapshot !== 'object' ||
|
|
556
|
+
Array.isArray(snapshot))
|
|
557
|
+
throw new Error('proof snapshot is malformed');
|
|
558
|
+
const state = snapshot;
|
|
559
|
+
if (state.runId !== raw.runId || !isRunStatus(state.status))
|
|
560
|
+
throw new Error('proof snapshot identity or status is malformed');
|
|
561
|
+
for (const key of ['requestContext', 'context', 'steps']) {
|
|
562
|
+
const value = state[key];
|
|
563
|
+
if (value !== undefined &&
|
|
564
|
+
(value === null || typeof value !== 'object' || Array.isArray(value)))
|
|
565
|
+
throw new Error('proof snapshot container is malformed');
|
|
566
|
+
}
|
|
567
|
+
const source = state.requestContext?.[RUN_PROVENANCE_CONTEXT_KEY];
|
|
568
|
+
const start = decodeRunStartIdentity(source);
|
|
569
|
+
if (start === undefined)
|
|
570
|
+
return { raw, status: state.status };
|
|
571
|
+
const provenance = decodeProgressRunProvenance(source);
|
|
572
|
+
const execution = normalizeD1RunExecutionIdentity({
|
|
573
|
+
...prepared.address,
|
|
574
|
+
startToken: provenance.startToken,
|
|
575
|
+
});
|
|
576
|
+
return { raw, status: state.status, execution, provenance };
|
|
577
|
+
}
|
|
578
|
+
catch (cause) {
|
|
579
|
+
throw new ExecutionFenceUnreadableError('proof snapshot is not readable', {
|
|
580
|
+
cause,
|
|
581
|
+
});
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
function reservationValues(row) {
|
|
585
|
+
if (row.binding.kind !== 'bound')
|
|
586
|
+
throw new InvalidExecutionIdentityError('admission');
|
|
587
|
+
return [
|
|
588
|
+
row.key,
|
|
589
|
+
row.owner.kind,
|
|
590
|
+
row.owner.id,
|
|
591
|
+
row.targetKind,
|
|
592
|
+
row.targetId,
|
|
593
|
+
row.runId,
|
|
594
|
+
row.threadId ?? null,
|
|
595
|
+
row.state,
|
|
596
|
+
row.createdAt,
|
|
597
|
+
row.updatedAt,
|
|
598
|
+
row.binding.execution.startToken,
|
|
599
|
+
row.binding.execution.tablePrefix,
|
|
600
|
+
row.binding.execution.workflowId,
|
|
601
|
+
];
|
|
602
|
+
}
|
|
376
603
|
/**
|
|
377
604
|
* The deployment's fence, over one D1 database — the SAME database the runner's
|
|
378
605
|
* snapshots and the deployment sentinel live in, so the fence cannot be
|
|
@@ -393,28 +620,33 @@ export class ExecutionFenceStore {
|
|
|
393
620
|
* question, and would turn a read-only replica or a revoked-write incident
|
|
394
621
|
* into an outage instead of a degrade.
|
|
395
622
|
*
|
|
396
|
-
* A missing table
|
|
397
|
-
*
|
|
398
|
-
* no caller can mistake a storage fault for an open deployment.
|
|
623
|
+
* A missing table or missing legacy row reads as `open`. A missing modern row is
|
|
624
|
+
* unreadable and is never silently recreated.
|
|
399
625
|
*/
|
|
400
626
|
async read() {
|
|
401
|
-
|
|
627
|
+
return (await this.#readStored())?.reading ?? OPEN_EXECUTION_FENCE;
|
|
628
|
+
}
|
|
629
|
+
usesDatabase(binding) {
|
|
630
|
+
return this.#db === binding;
|
|
631
|
+
}
|
|
632
|
+
/** @internal Pure strict observation; seed only on the admission preparation path. */
|
|
633
|
+
async readForAdmission() {
|
|
402
634
|
try {
|
|
403
|
-
rows = (await this.#db
|
|
404
|
-
.prepare(`SELECT
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
635
|
+
const rows = fenceResultRows(await this.#db
|
|
636
|
+
.prepare(`SELECT * FROM ${EXECUTION_FENCE_TABLE} LIMIT 2`)
|
|
637
|
+
.all());
|
|
638
|
+
const row = rows[0];
|
|
639
|
+
if (rows.length !== 1 || row === undefined)
|
|
640
|
+
throw new Error('initial admission requires an exact fence singleton');
|
|
641
|
+
const observation = decodeExecutionFenceAdmissionRow(row);
|
|
642
|
+
await validateExecutionFenceAdmissionSchema(await this.#db
|
|
643
|
+
.prepare(`PRAGMA table_xinfo(${EXECUTION_FENCE_TABLE})`)
|
|
644
|
+
.all());
|
|
645
|
+
return observation;
|
|
408
646
|
}
|
|
409
647
|
catch (error) {
|
|
410
|
-
|
|
411
|
-
return OPEN_EXECUTION_FENCE;
|
|
412
|
-
throw new ExecutionFenceUnreadableError('execution fence state is not readable', { cause: error });
|
|
648
|
+
throw new ExecutionFenceUnreadableError('initial admission requires current fence metadata', { cause: error });
|
|
413
649
|
}
|
|
414
|
-
const row = rows[0];
|
|
415
|
-
if (row === undefined)
|
|
416
|
-
return OPEN_EXECUTION_FENCE;
|
|
417
|
-
return readingFromRow(row);
|
|
418
650
|
}
|
|
419
651
|
/**
|
|
420
652
|
* Provisioning-time seeding: write the deployment's INITIAL fence state.
|
|
@@ -432,13 +664,8 @@ export class ExecutionFenceStore {
|
|
|
432
664
|
*/
|
|
433
665
|
async seed(state) {
|
|
434
666
|
const safeState = assertExecutionFenceState(state, 'seed state');
|
|
435
|
-
await this.#
|
|
436
|
-
await this.#
|
|
437
|
-
.prepare(`INSERT OR IGNORE INTO ${EXECUTION_FENCE_TABLE}
|
|
438
|
-
(id, state, proof_key, proof_run_id, updated_at)
|
|
439
|
-
VALUES (?, ?, NULL, NULL, ?)`)
|
|
440
|
-
.bind(EXECUTION_FENCE_ROW_ID, safeState, this.#now())
|
|
441
|
-
.run();
|
|
667
|
+
await this.#initialize(safeState);
|
|
668
|
+
await this.#readStored();
|
|
442
669
|
}
|
|
443
670
|
/**
|
|
444
671
|
* Move the fence, compare-and-set on the CURRENT state. One conditional
|
|
@@ -455,29 +682,81 @@ export class ExecutionFenceStore {
|
|
|
455
682
|
const expected = assertExecutionFenceState(input.expected, 'expected state');
|
|
456
683
|
const next = assertExecutionFenceState(input.next, 'next state');
|
|
457
684
|
const proofKey = this.#proofKeyFor(next, input.proofKey);
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
685
|
+
const { expectedMutationEpoch: epoch, expectedRevision: revision } = input;
|
|
686
|
+
const rawAdvance = input.advanceMutationEpoch;
|
|
687
|
+
const advance = rawAdvance ?? false;
|
|
688
|
+
const upgraded = epoch !== undefined || revision !== undefined;
|
|
689
|
+
if ((rawAdvance !== undefined && typeof rawAdvance !== 'boolean') ||
|
|
690
|
+
(upgraded && (!isFenceCounter(epoch) || !isFenceCounter(revision))) ||
|
|
691
|
+
(advance && !upgraded) ||
|
|
692
|
+
revision === Number.MAX_SAFE_INTEGER ||
|
|
693
|
+
(advance && epoch === Number.MAX_SAFE_INTEGER)) {
|
|
694
|
+
throw new InvalidExecutionFenceRequestError('fence expectations must be paired safe counters and advanceMutationEpoch must be boolean');
|
|
695
|
+
}
|
|
696
|
+
const receipt = upgraded
|
|
697
|
+
? JSON.stringify([
|
|
698
|
+
1,
|
|
699
|
+
expected,
|
|
700
|
+
next,
|
|
701
|
+
proofKey ?? null,
|
|
702
|
+
epoch,
|
|
703
|
+
revision,
|
|
704
|
+
advance,
|
|
705
|
+
])
|
|
706
|
+
: null;
|
|
707
|
+
await this.#initialize('open');
|
|
708
|
+
await this.#readStored();
|
|
709
|
+
let result;
|
|
710
|
+
try {
|
|
711
|
+
const statement = upgraded
|
|
712
|
+
? this.#db
|
|
713
|
+
.prepare(`UPDATE ${EXECUTION_FENCE_TABLE}
|
|
714
|
+
SET state = ?1, proof_key = ?2, proof_run_id = NULL,
|
|
715
|
+
proof_table_prefix = NULL, proof_workflow_id = NULL, proof_start_token = NULL,
|
|
716
|
+
mutation_epoch = mutation_epoch + ?3,
|
|
717
|
+
require_mutation_epoch = CASE WHEN ?3 = 1 THEN 1 ELSE require_mutation_epoch END,
|
|
718
|
+
transition_revision = transition_revision + 1,
|
|
719
|
+
last_transition_request = ?4, updated_at = ?5
|
|
720
|
+
WHERE id = ?6 AND state = ?7
|
|
721
|
+
AND mutation_epoch = ?8 AND transition_revision = ?9
|
|
722
|
+
AND require_mutation_epoch IN (0, 1)
|
|
723
|
+
AND transition_revision < 9007199254740991
|
|
724
|
+
AND (?3 = 0 OR mutation_epoch < 9007199254740991)
|
|
725
|
+
RETURNING *`)
|
|
726
|
+
.bind(next, proofKey ?? null, Number(advance), receipt, this.#now(), EXECUTION_FENCE_ROW_ID, expected, epoch, revision)
|
|
727
|
+
: this.#db
|
|
728
|
+
.prepare(`UPDATE ${EXECUTION_FENCE_TABLE}
|
|
729
|
+
SET state = ?, proof_key = ?, proof_run_id = NULL,
|
|
730
|
+
proof_table_prefix = NULL, proof_workflow_id = NULL, proof_start_token = NULL,
|
|
731
|
+
transition_revision = transition_revision + 1,
|
|
732
|
+
last_transition_request = NULL, updated_at = ?
|
|
733
|
+
WHERE id = ? AND state = ? AND require_mutation_epoch = 0
|
|
734
|
+
AND mutation_epoch = 0 AND transition_revision < 9007199254740991
|
|
735
|
+
RETURNING *`)
|
|
736
|
+
.bind(next, proofKey ?? null, this.#now(), EXECUTION_FENCE_ROW_ID, expected);
|
|
737
|
+
result = await statement.all();
|
|
738
|
+
}
|
|
739
|
+
catch (error) {
|
|
740
|
+
if (receipt !== null) {
|
|
741
|
+
const stored = await this.#readStored().catch(() => undefined);
|
|
742
|
+
if (stored?.receipt === receipt)
|
|
743
|
+
return stored.reading;
|
|
744
|
+
}
|
|
745
|
+
throw new ExecutionFenceUnreadableError('execution fence transition could not be recorded', { cause: error });
|
|
479
746
|
}
|
|
480
|
-
|
|
747
|
+
const returned = this.#decodeReturned(result);
|
|
748
|
+
if (returned !== undefined)
|
|
749
|
+
return returned.reading;
|
|
750
|
+
const stored = await this.#readStored();
|
|
751
|
+
if (receipt !== null && stored?.receipt === receipt)
|
|
752
|
+
return stored.reading;
|
|
753
|
+
const reading = stored?.reading ?? OPEN_EXECUTION_FENCE;
|
|
754
|
+
throw new FenceTransitionConflictError(expected, reading.state, {
|
|
755
|
+
reading,
|
|
756
|
+
conflict: !upgraded && reading.requireMutationEpoch
|
|
757
|
+
? 'versioned-expectation-required'
|
|
758
|
+
: 'expectation-mismatch',
|
|
759
|
+
});
|
|
481
760
|
}
|
|
482
761
|
/**
|
|
483
762
|
* Bind the proof-only state to the run it admitted, conditionally.
|
|
@@ -489,29 +768,246 @@ export class ExecutionFenceStore {
|
|
|
489
768
|
* Re-writing the SAME runId is admitted so a retry of an interrupted start
|
|
490
769
|
* converges instead of deadlocking on its own earlier write.
|
|
491
770
|
*/
|
|
492
|
-
async recordProofRun(proofKey, runId) {
|
|
771
|
+
async recordProofRun(proofKey, runId, admitted) {
|
|
772
|
+
const epoch = admitted?.mutationEpoch;
|
|
773
|
+
const revision = admitted?.transitionRevision;
|
|
493
774
|
if (!isPathSafeId(proofKey)) {
|
|
494
775
|
throw new InvalidExecutionFenceRequestError('proofKey must be a URL-path-safe identifier');
|
|
495
776
|
}
|
|
496
777
|
if (!isPathSafeId(runId)) {
|
|
497
778
|
throw new InvalidExecutionFenceRequestError('proof runId must be a URL-path-safe identifier');
|
|
498
779
|
}
|
|
780
|
+
if (admitted !== undefined &&
|
|
781
|
+
(admitted === null ||
|
|
782
|
+
typeof admitted !== 'object' ||
|
|
783
|
+
!isFenceCounter(epoch) ||
|
|
784
|
+
!isFenceCounter(revision))) {
|
|
785
|
+
throw new InvalidExecutionFenceRequestError('proof admission must contain safe epoch and revision counters');
|
|
786
|
+
}
|
|
787
|
+
const observed = await this.#readStored();
|
|
788
|
+
if (observed === undefined)
|
|
789
|
+
return false;
|
|
790
|
+
if (observed.schemaStage < EXECUTION_FENCE_CURRENT_SCHEMA_STAGE) {
|
|
791
|
+
await this.#initialize(observed.reading.state);
|
|
792
|
+
await this.#readStored();
|
|
793
|
+
}
|
|
794
|
+
let result;
|
|
499
795
|
try {
|
|
500
|
-
|
|
796
|
+
const statement = this.#db
|
|
501
797
|
.prepare(`UPDATE ${EXECUTION_FENCE_TABLE}
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
798
|
+
SET updated_at = CASE WHEN proof_run_id IS NULL THEN ? ELSE updated_at END,
|
|
799
|
+
proof_run_id = ?
|
|
800
|
+
WHERE id = ? AND state = 'proof-only' AND proof_key = ?
|
|
801
|
+
AND (proof_run_id IS NULL OR proof_run_id = ?)
|
|
802
|
+
AND proof_table_prefix IS NULL AND proof_workflow_id IS NULL AND proof_start_token IS NULL
|
|
803
|
+
AND ${admitted === undefined
|
|
804
|
+
? 'require_mutation_epoch = 0 AND mutation_epoch = 0'
|
|
805
|
+
: 'mutation_epoch = ? AND transition_revision = ?'}
|
|
806
|
+
RETURNING *`)
|
|
807
|
+
.bind(this.#now(), runId, EXECUTION_FENCE_ROW_ID, proofKey, runId, ...(admitted === undefined ? [] : [epoch, revision]));
|
|
808
|
+
result = await statement.all();
|
|
507
809
|
}
|
|
508
810
|
catch (error) {
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
if (
|
|
512
|
-
|
|
811
|
+
const stored = await this.#readStored().catch(() => undefined);
|
|
812
|
+
const reading = stored?.reading;
|
|
813
|
+
if (reading?.state === 'proof-only' &&
|
|
814
|
+
reading.proofKey === proofKey &&
|
|
815
|
+
reading.proofRunId === runId &&
|
|
816
|
+
reading.proofExecution === undefined &&
|
|
817
|
+
stored?.raw.proof_table_prefix === null &&
|
|
818
|
+
stored.raw.proof_workflow_id === null &&
|
|
819
|
+
stored.raw.proof_start_token === null &&
|
|
820
|
+
(admitted === undefined
|
|
821
|
+
? !reading.requireMutationEpoch && reading.mutationEpoch === 0
|
|
822
|
+
: reading.mutationEpoch === epoch &&
|
|
823
|
+
reading.transitionRevision === revision)) {
|
|
824
|
+
return true;
|
|
825
|
+
}
|
|
513
826
|
throw new ExecutionFenceUnreadableError('execution fence proof run could not be recorded', { cause: error });
|
|
514
827
|
}
|
|
828
|
+
const returned = this.#decodeReturned(result);
|
|
829
|
+
if (returned !== undefined) {
|
|
830
|
+
if (returned.reading.proofExecution !== undefined ||
|
|
831
|
+
returned.raw.proof_table_prefix !== null ||
|
|
832
|
+
returned.raw.proof_workflow_id !== null ||
|
|
833
|
+
returned.raw.proof_start_token !== null)
|
|
834
|
+
throw new ExecutionFenceUnreadableError('legacy proof write returned a modern binding');
|
|
835
|
+
return true;
|
|
836
|
+
}
|
|
837
|
+
await this.#readStored();
|
|
838
|
+
return false;
|
|
839
|
+
}
|
|
840
|
+
async readCurrentRunExecution(address) {
|
|
841
|
+
return (await selectedProofObservation(this.#db, address))?.execution;
|
|
842
|
+
}
|
|
843
|
+
async rebindProofRun(options) {
|
|
844
|
+
const { reservation: input, execution: rawExecution, proof: rawProof, mutationEpoch, reservationStore, } = options;
|
|
845
|
+
const reservation = captureBoundReservation(input);
|
|
846
|
+
const { tablePrefix, workflowId, runId, startToken, owner, target } = rawExecution;
|
|
847
|
+
const normalized = normalizeStartExecutionIdentity({
|
|
848
|
+
tablePrefix,
|
|
849
|
+
workflowId,
|
|
850
|
+
runId,
|
|
851
|
+
startToken,
|
|
852
|
+
owner,
|
|
853
|
+
target,
|
|
854
|
+
});
|
|
855
|
+
const execution = normalizeD1RunExecutionIdentity(normalized);
|
|
856
|
+
const { key, mutationEpoch: epoch, transitionRevision: revision, } = rawProof;
|
|
857
|
+
const callerEpoch = normalizeMutationEpoch(mutationEpoch);
|
|
858
|
+
const usesDatabase = reservationStore.usesDatabase;
|
|
859
|
+
const now = this.#now();
|
|
860
|
+
if (tablePrefix !== execution.tablePrefix ||
|
|
861
|
+
key !== reservation.key ||
|
|
862
|
+
!isFenceCounter(epoch) ||
|
|
863
|
+
!isFenceCounter(revision) ||
|
|
864
|
+
typeof now !== 'number' ||
|
|
865
|
+
!Number.isFinite(now) ||
|
|
866
|
+
typeof usesDatabase !== 'function' ||
|
|
867
|
+
!Reflect.apply(usesDatabase, reservationStore, [this.#db]) ||
|
|
868
|
+
reservation.binding.kind !== 'bound' ||
|
|
869
|
+
normalized.owner.kind !== reservation.owner.kind ||
|
|
870
|
+
normalized.owner.id !== reservation.owner.id ||
|
|
871
|
+
normalized.target.kind !== reservation.targetKind ||
|
|
872
|
+
normalized.target.id !== reservation.targetId ||
|
|
873
|
+
(normalized.target.kind === 'agent'
|
|
874
|
+
? normalized.target.threadId
|
|
875
|
+
: undefined) !== reservation.threadId ||
|
|
876
|
+
!admitsExistingRun({ state: 'proof-only', proofExecution: execution }, reservation.binding.execution))
|
|
877
|
+
throw new InvalidExecutionIdentityError('admission');
|
|
878
|
+
try {
|
|
879
|
+
const observed = await this.readForAdmission();
|
|
880
|
+
const requireSchemas = async () => {
|
|
881
|
+
await validateExecutionFenceAdmissionSchema(await this.#db
|
|
882
|
+
.prepare(`PRAGMA table_xinfo(${EXECUTION_FENCE_TABLE})`)
|
|
883
|
+
.all());
|
|
884
|
+
validateStartReservationAdmissionSchema(await this.#db
|
|
885
|
+
.prepare(`PRAGMA table_xinfo(${START_IDEMPOTENCY_TABLE})`)
|
|
886
|
+
.all());
|
|
887
|
+
};
|
|
888
|
+
await requireSchemas();
|
|
889
|
+
const current = decodeStartReservationAdmissionResult(await this.#db
|
|
890
|
+
.prepare(`SELECT * FROM ${START_IDEMPOTENCY_TABLE} WHERE key = ? LIMIT 2`)
|
|
891
|
+
.bind(key)
|
|
892
|
+
.all());
|
|
893
|
+
const selected = await selectedProofObservation(this.#db, execution);
|
|
894
|
+
const reading = observed.reading;
|
|
895
|
+
if (current === undefined ||
|
|
896
|
+
current.binding.kind !== 'bound' ||
|
|
897
|
+
!sameReservationIdentity(current, reservation) ||
|
|
898
|
+
JSON.stringify(reservationValues(current)) !==
|
|
899
|
+
JSON.stringify(reservationValues(reservation)) ||
|
|
900
|
+
selected?.execution === undefined ||
|
|
901
|
+
selected.status === 'pending' ||
|
|
902
|
+
!admitsExistingRun({ state: 'proof-only', proofExecution: execution }, selected.execution) ||
|
|
903
|
+
selected.provenance?.startIdentity?.owner.kind !==
|
|
904
|
+
reservation.owner.kind ||
|
|
905
|
+
selected.provenance.startIdentity.owner.id !== reservation.owner.id ||
|
|
906
|
+
selected.provenance.startIdentity.target.kind !==
|
|
907
|
+
reservation.targetKind ||
|
|
908
|
+
selected.provenance.startIdentity.target.id !== reservation.targetId ||
|
|
909
|
+
(selected.provenance.startIdentity.target.kind === 'agent'
|
|
910
|
+
? selected.provenance.startIdentity.target.threadId
|
|
911
|
+
: undefined) !== reservation.threadId ||
|
|
912
|
+
reading.state !== 'proof-only' ||
|
|
913
|
+
reading.proofKey !== key ||
|
|
914
|
+
reading.mutationEpoch !== epoch ||
|
|
915
|
+
reading.transitionRevision !== revision ||
|
|
916
|
+
(reading.requireMutationEpoch && callerEpoch !== epoch) ||
|
|
917
|
+
(reading.proofRunId !== undefined &&
|
|
918
|
+
!admitsExistingRun(reading, execution)))
|
|
919
|
+
return false;
|
|
920
|
+
const raw = selected.raw;
|
|
921
|
+
const snapshotPredicate = `EXISTS (SELECT 1 FROM "${execution.tablePrefix}mastra_workflow_snapshot"
|
|
922
|
+
WHERE workflow_name = ? AND run_id = ? AND resourceId IS ? AND snapshot = ? AND createdAt = ? AND updatedAt = ?)`;
|
|
923
|
+
const reservationPredicate = `EXISTS (SELECT 1 FROM ${START_IDEMPOTENCY_TABLE}
|
|
924
|
+
WHERE key = ? AND owner_kind = ? AND owner_id = ? AND target_kind = ? AND target_id = ? AND run_id = ?
|
|
925
|
+
AND thread_id IS ? AND state = ? AND created_at = ? AND updated_at = ?
|
|
926
|
+
AND start_token = ? AND start_table_prefix IS ? AND start_workflow_id = ?)`;
|
|
927
|
+
const framePredicate = `id = 'deployment' AND state = 'proof-only' AND proof_key = ?
|
|
928
|
+
AND mutation_epoch = ? AND transition_revision = ? AND require_mutation_epoch = ? AND last_transition_request IS ?
|
|
929
|
+
AND (require_mutation_epoch = 0 OR mutation_epoch = ?)`;
|
|
930
|
+
const exactTuple = 'proof_run_id = ? AND proof_table_prefix = ? AND proof_workflow_id = ? AND proof_start_token = ?';
|
|
931
|
+
const emptyTuple = 'proof_run_id IS NULL AND proof_table_prefix IS NULL AND proof_workflow_id IS NULL AND proof_start_token IS NULL';
|
|
932
|
+
const tuple = [
|
|
933
|
+
execution.runId,
|
|
934
|
+
execution.tablePrefix,
|
|
935
|
+
execution.workflowId,
|
|
936
|
+
execution.startToken,
|
|
937
|
+
];
|
|
938
|
+
const frame = [
|
|
939
|
+
key,
|
|
940
|
+
epoch,
|
|
941
|
+
revision,
|
|
942
|
+
Number(reading.requireMutationEpoch),
|
|
943
|
+
observed.raw.last_transition_request,
|
|
944
|
+
callerEpoch ?? null,
|
|
945
|
+
];
|
|
946
|
+
const rowValues = [
|
|
947
|
+
raw.workflowId,
|
|
948
|
+
raw.runId,
|
|
949
|
+
raw.resourceId,
|
|
950
|
+
raw.snapshot,
|
|
951
|
+
raw.createdAt,
|
|
952
|
+
raw.updatedAt,
|
|
953
|
+
...reservationValues(reservation),
|
|
954
|
+
];
|
|
955
|
+
const expectedTime = reading.proofRunId === undefined ? now : observed.raw.updated_at;
|
|
956
|
+
const validateReturned = (result) => {
|
|
957
|
+
const returned = this.#decodeReturned(result);
|
|
958
|
+
if (returned === undefined)
|
|
959
|
+
return false;
|
|
960
|
+
const next = returned.reading;
|
|
961
|
+
if (next.state !== 'proof-only' ||
|
|
962
|
+
next.proofKey !== key ||
|
|
963
|
+
next.mutationEpoch !== epoch ||
|
|
964
|
+
next.transitionRevision !== revision ||
|
|
965
|
+
next.requireMutationEpoch !== reading.requireMutationEpoch ||
|
|
966
|
+
returned.receipt !== observed.raw.last_transition_request ||
|
|
967
|
+
!admitsExistingRun(next, execution) ||
|
|
968
|
+
returned.raw.updated_at !== expectedTime)
|
|
969
|
+
throw new ExecutionFenceUnreadableError('proof nomination returned an unexpected fence');
|
|
970
|
+
return true;
|
|
971
|
+
};
|
|
972
|
+
let result;
|
|
973
|
+
try {
|
|
974
|
+
result = await this.#db
|
|
975
|
+
.prepare(`UPDATE ${EXECUTION_FENCE_TABLE}
|
|
976
|
+
SET updated_at = CASE WHEN proof_run_id IS NULL THEN ? ELSE updated_at END,
|
|
977
|
+
proof_run_id = ?, proof_table_prefix = ?, proof_workflow_id = ?, proof_start_token = ?
|
|
978
|
+
WHERE ${framePredicate} AND ((${emptyTuple}) OR (${exactTuple}))
|
|
979
|
+
AND ${snapshotPredicate} AND ${reservationPredicate} RETURNING *`)
|
|
980
|
+
.bind(now, ...tuple, ...frame, ...tuple, ...rowValues)
|
|
981
|
+
.all();
|
|
982
|
+
}
|
|
983
|
+
catch (cause) {
|
|
984
|
+
try {
|
|
985
|
+
const converged = await this.#db
|
|
986
|
+
.prepare(`SELECT * FROM ${EXECUTION_FENCE_TABLE}
|
|
987
|
+
WHERE ${framePredicate} AND ${exactTuple} AND ${snapshotPredicate} AND ${reservationPredicate} LIMIT 2`)
|
|
988
|
+
.bind(...frame, ...tuple, ...rowValues)
|
|
989
|
+
.all();
|
|
990
|
+
await requireSchemas();
|
|
991
|
+
if (validateReturned(converged))
|
|
992
|
+
return true;
|
|
993
|
+
}
|
|
994
|
+
catch {
|
|
995
|
+
/* Preserve the failed write's cause. */
|
|
996
|
+
}
|
|
997
|
+
throw new ExecutionFenceUnreadableError('proof nomination could not be recorded', { cause });
|
|
998
|
+
}
|
|
999
|
+
const nominated = validateReturned(result);
|
|
1000
|
+
if (!nominated) {
|
|
1001
|
+
await requireSchemas();
|
|
1002
|
+
await this.readForAdmission();
|
|
1003
|
+
}
|
|
1004
|
+
return nominated;
|
|
1005
|
+
}
|
|
1006
|
+
catch (cause) {
|
|
1007
|
+
if (cause instanceof ExecutionFenceUnreadableError)
|
|
1008
|
+
throw cause;
|
|
1009
|
+
throw new ExecutionFenceUnreadableError('proof nomination is not readable', { cause });
|
|
1010
|
+
}
|
|
515
1011
|
}
|
|
516
1012
|
#proofKeyFor(next, proofKey) {
|
|
517
1013
|
if (next === 'proof-only') {
|
|
@@ -527,8 +1023,76 @@ export class ExecutionFenceStore {
|
|
|
527
1023
|
}
|
|
528
1024
|
return undefined;
|
|
529
1025
|
}
|
|
530
|
-
async
|
|
531
|
-
|
|
1026
|
+
#execute = async (statement) => {
|
|
1027
|
+
const prepared = this.#db
|
|
1028
|
+
.prepare(statement.sql)
|
|
1029
|
+
.bind(...statement.bindings);
|
|
1030
|
+
if (statement.mode === 'write') {
|
|
1031
|
+
await prepared.run();
|
|
1032
|
+
return [];
|
|
1033
|
+
}
|
|
1034
|
+
return fenceResultRows(await prepared.all());
|
|
1035
|
+
};
|
|
1036
|
+
async #initialize(state) {
|
|
1037
|
+
try {
|
|
1038
|
+
await initializeExecutionFenceProtocol(this.#execute, {
|
|
1039
|
+
state,
|
|
1040
|
+
seededAt: this.#now(),
|
|
1041
|
+
});
|
|
1042
|
+
}
|
|
1043
|
+
catch (error) {
|
|
1044
|
+
throw new ExecutionFenceUnreadableError('execution fence could not be initialized', { cause: error });
|
|
1045
|
+
}
|
|
1046
|
+
}
|
|
1047
|
+
#decodeReturned(result) {
|
|
1048
|
+
try {
|
|
1049
|
+
return returningFence(result);
|
|
1050
|
+
}
|
|
1051
|
+
catch (error) {
|
|
1052
|
+
throw new ExecutionFenceUnreadableError('execution fence UPDATE result is not readable', { cause: error });
|
|
1053
|
+
}
|
|
1054
|
+
}
|
|
1055
|
+
async #readStored() {
|
|
1056
|
+
try {
|
|
1057
|
+
let minimumStage = 0;
|
|
1058
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
1059
|
+
let rows;
|
|
1060
|
+
try {
|
|
1061
|
+
rows = await this.#execute({
|
|
1062
|
+
mode: 'read',
|
|
1063
|
+
sql: `SELECT * FROM ${EXECUTION_FENCE_TABLE} LIMIT 2`,
|
|
1064
|
+
bindings: [],
|
|
1065
|
+
});
|
|
1066
|
+
}
|
|
1067
|
+
catch (error) {
|
|
1068
|
+
if (attempt === 0 && isMissingFenceTable(error))
|
|
1069
|
+
return undefined;
|
|
1070
|
+
throw error;
|
|
1071
|
+
}
|
|
1072
|
+
const stage = await readExecutionFenceSchemaProtocol(this.#execute);
|
|
1073
|
+
if (!Array.isArray(rows) ||
|
|
1074
|
+
stage === undefined ||
|
|
1075
|
+
stage < minimumStage) {
|
|
1076
|
+
throw new Error('execution fence row observation has no compatible schema');
|
|
1077
|
+
}
|
|
1078
|
+
if (rows.length === 0 && attempt === 0) {
|
|
1079
|
+
if (stage === 0)
|
|
1080
|
+
return undefined;
|
|
1081
|
+
minimumStage = stage;
|
|
1082
|
+
continue;
|
|
1083
|
+
}
|
|
1084
|
+
if (rows.length !== 1)
|
|
1085
|
+
throw new Error('execution fence row is not an exact singleton');
|
|
1086
|
+
const stored = readingFromRow(rows[0]);
|
|
1087
|
+
if (stored.schemaStage > stage)
|
|
1088
|
+
throw new Error('execution fence schema observation precedes row metadata');
|
|
1089
|
+
return stored;
|
|
1090
|
+
}
|
|
1091
|
+
throw new Error('execution fence row is missing');
|
|
1092
|
+
}
|
|
1093
|
+
catch (error) {
|
|
1094
|
+
throw new ExecutionFenceUnreadableError('execution fence state is not readable', { cause: error });
|
|
1095
|
+
}
|
|
532
1096
|
}
|
|
533
1097
|
}
|
|
534
1098
|
//# sourceMappingURL=execution-fence.js.map
|