deepline 0.3.501 → 0.3.503
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/bundling-sources/sdk/src/client-core.ts +26 -0
- package/dist/bundling-sources/sdk/src/index.ts +1 -0
- package/dist/bundling-sources/sdk/src/release.ts +1 -1
- package/dist/bundling-sources/sdk/src/types.ts +9 -0
- package/dist/bundling-sources/shared_libs/monitors/starter-templates.ts +0 -8
- package/dist/bundling-sources/shared_libs/observability/dlq.ts +174 -0
- package/dist/bundling-sources/shared_libs/observability/queue-health.ts +9 -0
- package/dist/bundling-sources/shared_libs/observability/queue-item-connectors.ts +1 -0
- package/dist/bundling-sources/shared_libs/observability/scheduled-jobs.json +20 -2
- package/dist/bundling-sources/shared_libs/play-runtime/activity-observation.ts +20 -0
- package/dist/bundling-sources/shared_libs/play-runtime/app-runtime-api.ts +62 -2
- package/dist/bundling-sources/shared_libs/play-runtime/context.ts +667 -62
- package/dist/bundling-sources/shared_libs/play-runtime/ctx-types.ts +55 -0
- package/dist/bundling-sources/shared_libs/play-runtime/deployment/vercel-fly-rollback-alignment.ts +29 -14
- package/dist/bundling-sources/shared_libs/play-runtime/durable-receipt-execution.ts +20 -2
- package/dist/bundling-sources/shared_libs/play-runtime/durable-runs-rollout.ts +46 -0
- package/dist/bundling-sources/shared_libs/play-runtime/execution-gateway-invocation-fence.ts +80 -4
- package/dist/bundling-sources/shared_libs/play-runtime/fixture-egress-fetch.ts +95 -0
- package/dist/bundling-sources/shared_libs/play-runtime/freshness-receipt-execution.ts +292 -45
- package/dist/bundling-sources/shared_libs/play-runtime/internal-bootstrap-token.ts +15 -0
- package/dist/bundling-sources/shared_libs/play-runtime/launch-identity.ts +3 -0
- package/dist/bundling-sources/shared_libs/play-runtime/play-http-request.ts +7 -3
- package/dist/bundling-sources/shared_libs/play-runtime/play-runtime-semantics.ts +31 -1
- package/dist/bundling-sources/shared_libs/play-runtime/post-code-recovery-policy.ts +231 -0
- package/dist/bundling-sources/shared_libs/play-runtime/prebuilt-result-quality.ts +264 -0
- package/dist/bundling-sources/shared_libs/play-runtime/protocol.ts +9 -0
- package/dist/bundling-sources/shared_libs/play-runtime/run-ending-event.ts +55 -0
- package/dist/bundling-sources/shared_libs/play-runtime/run-ledger.ts +126 -0
- package/dist/bundling-sources/shared_libs/play-runtime/runner-app/index.ts +70 -1
- package/dist/bundling-sources/shared_libs/play-runtime/runner-backends/backends/daytona-launch-transport.ts +2 -9
- package/dist/bundling-sources/shared_libs/play-runtime/runner-backends/backends/daytona-lifecycle.ts +51 -19
- package/dist/bundling-sources/shared_libs/play-runtime/runner-backends/backends/local-process.ts +9 -4
- package/dist/bundling-sources/shared_libs/play-runtime/runner-backends/backends/modal.ts +2 -0
- package/dist/bundling-sources/shared_libs/play-runtime/runner-backends/runtime-sandbox-reconciliation.ts +2 -0
- package/dist/bundling-sources/shared_libs/play-runtime/runtime-actions.ts +12 -1
- package/dist/bundling-sources/shared_libs/play-runtime/runtime-authority.ts +3 -0
- package/dist/bundling-sources/shared_libs/play-runtime/runtime-gateway-oidc.ts +30 -8
- package/dist/bundling-sources/shared_libs/play-runtime/runtime-incident-drills.ts +42 -0
- package/dist/bundling-sources/shared_libs/play-runtime/runtime-operation-contract.ts +7 -0
- package/dist/bundling-sources/shared_libs/play-runtime/runtime-receipt-store-adapter.ts +26 -1
- package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backend.ts +13 -0
- package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/absurd-deadline-reconciliation.ts +53 -0
- package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/absurd-runtime-worker.ts +631 -19
- package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/durable-run-inventory.ts +719 -0
- package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/durable-run-sql.ts +206 -0
- package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/latest-cache-result.ts +83 -0
- package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/postgres.ts +1453 -160
- package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/receipt-gateway.ts +61 -0
- package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/runtime-event-search.ts +29 -8
- package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/runtime-queue-health.ts +27 -2
- package/dist/bundling-sources/shared_libs/play-runtime/test-runtime-seams.ts +45 -0
- package/dist/bundling-sources/shared_libs/play-runtime/tool-cache-policy.ts +18 -0
- package/dist/bundling-sources/shared_libs/play-runtime/tool-execute-retry-policy.ts +129 -14
- package/dist/bundling-sources/shared_libs/play-runtime/workflow-executor-auth.ts +2 -0
- package/dist/bundling-sources/shared_libs/plays/authoring-contract.ts +10 -1
- package/dist/bundling-sources/shared_libs/product-notifications/slack-delivery.ts +2 -0
- package/dist/cli/{auth-6ECHXOI4.mjs → auth-IC4WLSE3.mjs} +5 -5
- package/dist/cli/auth-ZCMSXZO4.js +43 -0
- package/dist/cli/{billing-75NZYRXA.mjs → billing-2VOV64SD.mjs} +6 -6
- package/dist/cli/{billing-QRR7O6BD.js → billing-LWQOII22.js} +79 -79
- package/dist/cli/{chunk-N2TJJNCW.js → chunk-2626LTU3.js} +291 -273
- package/dist/cli/{chunk-VL72UKNW.js → chunk-26RSSTCF.js} +26 -26
- package/dist/cli/{chunk-HDKXSHGA.js → chunk-2K2QBLYO.js} +53 -53
- package/dist/cli/{chunk-463ZOO2L.js → chunk-33JUK73X.js} +7 -7
- package/dist/cli/{chunk-KTOAJP4N.js → chunk-3CXHK4TW.js} +10 -10
- package/dist/cli/{chunk-YPTZJ7LO.js → chunk-4IIYSBEP.js} +70 -13
- package/dist/cli/{chunk-VTDAJZIJ.mjs → chunk-5GI6NKOE.mjs} +20 -1
- package/dist/cli/{chunk-TFFJ2PRN.mjs → chunk-5M5WSFRZ.mjs} +70 -13
- package/dist/cli/{chunk-5S7MLAI7.mjs → chunk-6XTE6C3W.mjs} +41 -23
- package/dist/cli/{chunk-7L6QNHUL.mjs → chunk-7HEDCIR3.mjs} +1 -1
- package/dist/cli/{chunk-C5R3UH5V.mjs → chunk-7MJYZ33I.mjs} +2 -6
- package/dist/cli/{chunk-TOE7LHEA.js → chunk-A2C6ONWA.js} +6 -6
- package/dist/cli/{chunk-QQ3JJYE2.js → chunk-AARF4SOW.js} +17 -13
- package/dist/cli/{chunk-APAHMCGR.js → chunk-B3X4YWQ6.js} +53 -53
- package/dist/cli/{chunk-J74N375S.mjs → chunk-BI2Q45SY.mjs} +4 -4
- package/dist/cli/{chunk-GBICEYUA.js → chunk-BN5VKY4X.js} +141 -20
- package/dist/cli/{chunk-UR7JOSLT.js → chunk-C5RQTTLP.js} +26 -7
- package/dist/cli/{chunk-ZUOKIBLJ.mjs → chunk-D27HP3HS.mjs} +2 -2
- package/dist/cli/{chunk-UJRN6YP6.mjs → chunk-DPI5OYVU.mjs} +10 -6
- package/dist/cli/{chunk-MSLXAVVK.mjs → chunk-EDMV4JT5.mjs} +2 -2
- package/dist/cli/{chunk-ZUQHQGC5.mjs → chunk-EQ3WMKFY.mjs} +5 -5
- package/dist/cli/{chunk-5X4AUFYW.js → chunk-F73PD2XD.js} +7 -7
- package/dist/cli/{chunk-O3DDVP7Z.mjs → chunk-FHJ54BHH.mjs} +2 -2
- package/dist/cli/{chunk-SV2TEZ2M.js → chunk-FIUTDSJX.js} +5 -4
- package/dist/cli/{chunk-W6JTHVPF.js → chunk-FVDTERO2.js} +21 -21
- package/dist/cli/{chunk-CJJ7JBM2.js → chunk-FZHOWPSN.js} +23 -21
- package/dist/cli/{chunk-WJUDAHIQ.mjs → chunk-GIHNEYBG.mjs} +1 -1
- package/dist/cli/{chunk-V5NHEYU7.mjs → chunk-GLZBFBJS.mjs} +5 -5
- package/dist/cli/{chunk-VVEMPC2I.js → chunk-HRTDCXHI.js} +2 -2
- package/dist/cli/{chunk-BOFCF4L7.js → chunk-HS63YBT5.js} +3 -3
- package/dist/cli/{chunk-4OXHLTCP.js → chunk-IIP46RVC.js} +1 -1
- package/dist/cli/{chunk-SAW3FBCA.mjs → chunk-ITJ7NB2D.mjs} +6 -0
- package/dist/cli/{chunk-NA3J3F2Z.mjs → chunk-J6RBOLK7.mjs} +1 -1
- package/dist/cli/{chunk-PXIF74UJ.mjs → chunk-JJVN7OIX.mjs} +4 -4
- package/dist/cli/{chunk-T7E3XEPG.mjs → chunk-JPDD4Y53.mjs} +10 -8
- package/dist/cli/{chunk-OKOXB3LY.mjs → chunk-K7NFFQFU.mjs} +2 -2
- package/dist/cli/{chunk-66XDYH5T.mjs → chunk-KGLVATEB.mjs} +2 -2
- package/dist/cli/{chunk-EHVFBD36.mjs → chunk-KPBBT6OS.mjs} +2 -1
- package/dist/cli/{chunk-MADTHS56.mjs → chunk-L3TZV625.mjs} +1 -1
- package/dist/cli/{chunk-FS7XYDOF.js → chunk-MJQOG4TZ.js} +16 -16
- package/dist/cli/{chunk-JO5FFSR7.js → chunk-NTLBZUHD.js} +6 -0
- package/dist/cli/{chunk-EKZQ5LQO.js → chunk-PVA3MWCO.js} +3 -3
- package/dist/cli/{chunk-PNF2ZU4R.js → chunk-QIEYEY6Z.js} +8 -8
- package/dist/cli/{chunk-KSHAFYYG.mjs → chunk-R2VZVHJP.mjs} +127 -6
- package/dist/cli/{chunk-XEBFJ2PH.js → chunk-RVOBFO7C.js} +41 -41
- package/dist/cli/{chunk-RU5ROUFO.js → chunk-TCQYWZFS.js} +5 -5
- package/dist/cli/{chunk-I42EOZKQ.js → chunk-TMQUMILM.js} +19 -23
- package/dist/cli/{chunk-EOO7OSS4.mjs → chunk-URZNSJE2.mjs} +4 -4
- package/dist/cli/{chunk-Z6AUOV7D.mjs → chunk-VC5B462T.mjs} +2 -2
- package/dist/cli/{chunk-EKF4DKUA.js → chunk-WHP3FJ7T.js} +5 -5
- package/dist/cli/{chunk-VD2374K7.mjs → chunk-WS274KID.mjs} +1 -1
- package/dist/cli/{chunk-T4U245E4.mjs → chunk-XYZZZLN6.mjs} +2 -2
- package/dist/cli/{chunk-J6SVNKRP.js → chunk-YXGPMTAK.js} +2 -2
- package/dist/cli/{chunk-RFV7PPLS.mjs → chunk-ZEQPCEV4.mjs} +3 -3
- package/dist/cli/command-docs.js +2 -2
- package/dist/cli/command-docs.mjs +1 -1
- package/dist/cli/{csv-RZJ4SOIL.mjs → csv-2TXOI3UE.mjs} +4 -4
- package/dist/cli/{csv-JXX2LXK5.js → csv-NEWCNOSZ.js} +13 -13
- package/dist/cli/{db-T2KJNONM.js → db-J3IJS4OG.js} +27 -27
- package/dist/cli/{db-MUTT2NWI.mjs → db-PX7EQEIG.mjs} +6 -6
- package/dist/cli/{describe-K3UMAAVO.mjs → describe-GQHGTZSL.mjs} +20 -21
- package/dist/cli/describe-LE7EZCL4.js +49 -0
- package/dist/cli/describe-core.d.mts +8 -4
- package/dist/cli/describe-core.d.ts +8 -4
- package/dist/cli/describe-core.js +4 -5
- package/dist/cli/describe-core.mjs +3 -4
- package/dist/cli/{executions-PHS4R2OX.mjs → executions-FFKK24RY.mjs} +6 -6
- package/dist/cli/{executions-7HSLDRHR.js → executions-RO3TJUXL.js} +8 -8
- package/dist/cli/{feedback-BJZRM637.js → feedback-XRR4HIS6.js} +8 -8
- package/dist/cli/{feedback-RWMDCIDF.mjs → feedback-ZTO56SRL.mjs} +4 -4
- package/dist/cli/git-26AH4XIO.js +25 -0
- package/dist/cli/{git-YW6VHYZG.mjs → git-FIPBVFYZ.mjs} +5 -5
- package/dist/cli/index.js +142 -142
- package/dist/cli/index.mjs +42 -42
- package/dist/cli/{legacy-noops-5UBSUPGG.mjs → legacy-noops-AMD2NWHF.mjs} +5 -5
- package/dist/cli/{legacy-noops-2WUV2XD7.js → legacy-noops-MTBBGM27.js} +8 -8
- package/dist/cli/{monitors-HWOQO3OK.mjs → monitors-24LDKDJX.mjs} +7 -7
- package/dist/cli/{monitors-YZZRKSTG.js → monitors-42PIGLBF.js} +95 -95
- package/dist/cli/{org-NCXT6RB4.mjs → org-4B7SCFRL.mjs} +6 -6
- package/dist/cli/{org-JY7HLHBA.js → org-GQMCA3MN.js} +72 -72
- package/dist/cli/{pages-QJO53QAT.mjs → pages-PD5EGL2R.mjs} +6 -6
- package/dist/cli/{pages-6ZOHXL6X.js → pages-RL2M62GJ.js} +18 -18
- package/dist/cli/{play-SQRS7JN3.mjs → play-5V54VTUR.mjs} +132 -26
- package/dist/cli/{play-TAYGSR35.js → play-FST6ZAHW.js} +447 -341
- package/dist/cli/{providers-4Q5LOIQ5.js → providers-HBUUPN7J.js} +9 -9
- package/dist/cli/{providers-3IR3N5DT.mjs → providers-N5YVCKPL.mjs} +6 -6
- package/dist/cli/{quickstart-ITNUZENY.js → quickstart-4QIQNSHG.js} +6 -6
- package/dist/cli/{quickstart-KCZCYO6B.mjs → quickstart-NJDDVTQR.mjs} +4 -4
- package/dist/cli/{run-YQ57LMKN.js → run-FGOKCG4J.js} +44 -45
- package/dist/cli/{run-JCWRWDSK.mjs → run-JHI5MTHD.mjs} +25 -26
- package/dist/cli/search-CTKSEVSO.js +32 -0
- package/dist/cli/{search-FUM27HQP.mjs → search-EWIZBIY2.mjs} +7 -7
- package/dist/cli/{search-output-EWEYT34M.mjs → search-output-NAK3MWBH.mjs} +53 -75
- package/dist/cli/{search-output-XAMWKRJH.js → search-output-TMQTRC2W.js} +58 -80
- package/dist/cli/{secrets-2IRRRZBL.js → secrets-5TSUEOJB.js} +15 -15
- package/dist/cli/{secrets-YTI4IAKR.mjs → secrets-ONQVW5SR.mjs} +6 -6
- package/dist/cli/{sessions-EFS4KUPF.mjs → sessions-B7F5O3ZR.mjs} +5 -5
- package/dist/cli/{sessions-HWTRDXBQ.js → sessions-BSGE5EET.js} +6 -6
- package/dist/cli/{settings-FRVEIOKR.js → settings-47LARBRU.js} +78 -78
- package/dist/cli/{settings-NTOO42DY.mjs → settings-SGGFQV5R.mjs} +11 -11
- package/dist/cli/{setup-PAVQPALX.mjs → setup-ATGNXQUK.mjs} +9 -9
- package/dist/cli/{setup-6ZIOAE2V.js → setup-BNFZFXO6.js} +49 -49
- package/dist/cli/skills-6RD25MVM.js +36 -0
- package/dist/cli/{skills-3O3XTPUM.mjs → skills-CIMBRM5R.mjs} +7 -7
- package/dist/cli/{tools-7QSB65UL.mjs → tools-DTDXAULX.mjs} +18 -19
- package/dist/cli/tools-TDZH4XHS.js +56 -0
- package/dist/cli/{update-T6CYS5ZT.mjs → update-EOIJBJCO.mjs} +9 -9
- package/dist/cli/update-Y32VT4VL.js +34 -0
- package/dist/cli/{workflow-OMSXZ73T.mjs → workflow-IWXUJPWY.mjs} +7 -7
- package/dist/cli/{workflow-4KMJBMGX.js → workflow-V5VKPICQ.js} +17 -17
- package/dist/{client-Bn8FwKGO.d.ts → client-CIwenMFS.d.ts} +1 -1
- package/dist/{client-CfNRmjLK.d.mts → client-DYAfJpaN.d.mts} +1 -1
- package/dist/{client-core-B91EV0WS.d.ts → client-core-CRjtyMAI.d.ts} +25 -2
- package/dist/{client-core-BG8Cgrmk.d.mts → client-core-DlzP8vEs.d.mts} +25 -2
- package/dist/{compiler-manifest-DlXDyndN.d.ts → compiler-manifest-DaJrA2KV.d.mts} +1 -1
- package/dist/{compiler-manifest-DlXDyndN.d.mts → compiler-manifest-DaJrA2KV.d.ts} +1 -1
- package/dist/{errors-BtriA2ld.d.mts → errors-BKnSYueU.d.mts} +1 -1
- package/dist/{errors-DmcLykM7.d.ts → errors-KLga4bLr.d.ts} +1 -1
- package/dist/{index-DI0sR_fX.d.mts → index-C-8AFpWy.d.mts} +1 -1
- package/dist/{index--Jw-slHY.d.ts → index-C5nAZ-VS.d.ts} +1 -1
- package/dist/index.d.mts +7 -7
- package/dist/index.d.ts +7 -7
- package/dist/index.js +9 -9
- package/dist/index.mjs +6 -6
- package/dist/install-integrity.json +124 -118
- package/dist/plays/bundle-play-file.d.mts +3 -3
- package/dist/plays/bundle-play-file.d.ts +3 -3
- package/dist/plays/bundle-play-file.mjs +8 -1
- package/dist/plays/play-description.d.mts +2 -2
- package/dist/plays/play-description.d.ts +2 -2
- package/dist/plays/run-request.d.mts +2 -2
- package/dist/plays/run-request.d.ts +2 -2
- package/dist/release.d.mts +1 -1
- package/dist/release.d.ts +1 -1
- package/dist/release.js +2 -2
- package/dist/release.mjs +1 -1
- package/dist/server.d.mts +4 -4
- package/dist/server.d.ts +4 -4
- package/dist/server.js +5 -5
- package/dist/server.mjs +3 -3
- package/package.json +1 -1
- package/dist/cli/auth-VP7PMXKQ.js +0 -43
- package/dist/cli/chunk-XK5DMLZE.js +0 -111
- package/dist/cli/chunk-XRDXNAAY.mjs +0 -111
- package/dist/cli/describe-SEXUJLE4.js +0 -50
- package/dist/cli/git-VNS7UQWN.js +0 -25
- package/dist/cli/search-I425FRTK.js +0 -32
- package/dist/cli/skills-6ZNMO2PR.js +0 -36
- package/dist/cli/tools-DPV2JES6.js +0 -57
- package/dist/cli/update-Q5GUDEAW.js +0 -34
|
@@ -1,9 +1,18 @@
|
|
|
1
|
+
import { PLATFORM_RECOVERY_ACTIVITY_ID } from '../activity-observation';
|
|
2
|
+
import { readPrebuiltResultQuality } from '../prebuilt-result-quality';
|
|
1
3
|
import { resolveRuntimeAppTransport } from '../runtime-app-transport';
|
|
2
4
|
import {
|
|
3
5
|
terminalRuntimePerformanceFromStats,
|
|
4
6
|
normalizeTerminalRuntimePerformance,
|
|
5
7
|
normalizeTerminalRuntimePerformanceUnavailableReason,
|
|
6
8
|
} from '../terminal-runtime-performance';
|
|
9
|
+
import {
|
|
10
|
+
computeBillingSessionId,
|
|
11
|
+
isRunEndingEventId,
|
|
12
|
+
normalizeResumeEpoch,
|
|
13
|
+
runEndingEventEpoch,
|
|
14
|
+
runEndingEventId,
|
|
15
|
+
} from '../run-ending-event';
|
|
7
16
|
import { escapeLiteral } from 'pg';
|
|
8
17
|
import { readRuntimeGatewayLaunchPin } from '../runtime-gateway-profile';
|
|
9
18
|
import { RUNTIME_GATEWAY_OIDC_MAX_AGE_SECONDS } from '../runtime-gateway-oidc';
|
|
@@ -276,6 +285,12 @@ import type {
|
|
|
276
285
|
DurableInvocationResponse,
|
|
277
286
|
DurableInvocationStore,
|
|
278
287
|
} from '../execution-gateway-invocation-fence';
|
|
288
|
+
import { fenceOwnerAttemptSql } from '../execution-gateway-invocation-fence';
|
|
289
|
+
import { DURABLE_RUNS_ROLLOUT } from '../durable-runs-rollout';
|
|
290
|
+
import {
|
|
291
|
+
replayTrackedMarkerReceiptKey,
|
|
292
|
+
replayUnsafeMarkerReceiptKey,
|
|
293
|
+
} from '../post-code-recovery-policy';
|
|
279
294
|
import {
|
|
280
295
|
recordSchedulerLaunchRead,
|
|
281
296
|
type SchedulerLaunchReadCaller,
|
|
@@ -418,8 +433,14 @@ const POSTGRES_SCHEDULER_SCHEMA_INIT_STATEMENT_TIMEOUT_MS = 60_000;
|
|
|
418
433
|
// unexpanded acquires retain their existing operation-local measurement.
|
|
419
434
|
// v64 adds the optional per-run array-input intent used by terminal retirement.
|
|
420
435
|
// Existing runs default to false and older workers ignore the column.
|
|
436
|
+
// v65 lets the ending of a resumed run (`run-ended:*`) re-open its settled
|
|
437
|
+
// compute billing job, so a resumed epoch's compute is settled too. A
|
|
438
|
+
// never-resumed run's single ending keeps the original insert-once behavior.
|
|
439
|
+
// v66 adds the nullable `array_input_kept_for_resume_at` marker: positive
|
|
440
|
+
// evidence, written where a stopped run's staged input is kept for `runs
|
|
441
|
+
// resume`. Absent on older runs, whose input an older build may have deleted.
|
|
421
442
|
// This marker records deployment work, never a runtime schema floor.
|
|
422
|
-
export const POSTGRES_SCHEDULER_SCHEMA_VERSION =
|
|
443
|
+
export const POSTGRES_SCHEDULER_SCHEMA_VERSION = 66;
|
|
423
444
|
const POSTGRES_SCHEDULER_SCHEMA_MIGRATIONS_TABLE =
|
|
424
445
|
'scheduler_schema_migrations';
|
|
425
446
|
export const POSTGRES_SCHEDULER_OPEN_RECOVERY_INDEX =
|
|
@@ -859,27 +880,40 @@ export function createPostgresIntegrationInvocationStore(input: {
|
|
|
859
880
|
response_headers = NULL,
|
|
860
881
|
response_body = NULL,
|
|
861
882
|
updated_at = now()
|
|
862
|
-
WHERE
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
883
|
+
WHERE (
|
|
884
|
+
integration_invocation_receipts.parent_run_id
|
|
885
|
+
IS DISTINCT FROM EXCLUDED.parent_run_id
|
|
886
|
+
AND (
|
|
887
|
+
-- An explicit later Play Run is the recovery boundary for an
|
|
888
|
+
-- indeterminate provider outcome. Transport metadata such as
|
|
889
|
+
-- parent_run_id is part of the wire fingerprint, so the same
|
|
890
|
+
-- semantic invocation necessarily has a different fingerprint
|
|
891
|
+
-- in that later run. The stable invocation_key remains the
|
|
892
|
+
-- semantic identity and same-run callers can never enter here.
|
|
893
|
+
integration_invocation_receipts.state = 'indeterminate'
|
|
894
|
+
OR (
|
|
895
|
+
integration_invocation_receipts.request_fingerprint =
|
|
896
|
+
ANY($6::text[])
|
|
897
|
+
AND
|
|
898
|
+
integration_invocation_receipts.state IN ('completed', 'compacted')
|
|
899
|
+
AND NOT (
|
|
900
|
+
integration_invocation_receipts.response_status
|
|
901
|
+
BETWEEN 200 AND 299
|
|
902
|
+
)
|
|
880
903
|
)
|
|
881
904
|
)
|
|
882
905
|
)
|
|
906
|
+
-- A newer attempt of the same run sends a call an older attempt
|
|
907
|
+
-- abandoned (unknown outcome) again, with the same key and the
|
|
908
|
+
-- same request. A legacy owner ID carries no attempt and is never
|
|
909
|
+
-- taken over.
|
|
910
|
+
OR (
|
|
911
|
+
integration_invocation_receipts.state = 'indeterminate'
|
|
912
|
+
AND integration_invocation_receipts.request_fingerprint =
|
|
913
|
+
ANY($6::text[])
|
|
914
|
+
AND ${fenceOwnerAttemptSql('integration_invocation_receipts.owner_id')}
|
|
915
|
+
< ${fenceOwnerAttemptSql('EXCLUDED.owner_id')}
|
|
916
|
+
)
|
|
883
917
|
RETURNING ${returning}`,
|
|
884
918
|
[
|
|
885
919
|
input.orgId,
|
|
@@ -989,9 +1023,30 @@ export async function compactPostgresIntegrationInvocationResponses(input: {
|
|
|
989
1023
|
SELECT ctid, COALESCE(octet_length(response_body), 0) AS response_bytes
|
|
990
1024
|
FROM ${tableName('integration_invocation_receipts', {
|
|
991
1025
|
schema: input.schema,
|
|
992
|
-
})}
|
|
1026
|
+
})} AS invocation
|
|
993
1027
|
WHERE state = 'completed'
|
|
994
1028
|
AND updated_at < now() - ($1::bigint * interval '1 millisecond')
|
|
1029
|
+
-- A run that is still active or recovering, or that can still be
|
|
1030
|
+
-- resumed, replays these answers; keep them. The fence parent is
|
|
1031
|
+
-- the run id, with a ':resume:N' suffix after a resume.
|
|
1032
|
+
AND NOT EXISTS (
|
|
1033
|
+
SELECT 1
|
|
1034
|
+
FROM ${tableName('runs', { schema: input.schema })} AS runs
|
|
1035
|
+
WHERE runs.run_id = regexp_replace(
|
|
1036
|
+
invocation.parent_run_id,
|
|
1037
|
+
':resume:[0-9]+$',
|
|
1038
|
+
''
|
|
1039
|
+
)
|
|
1040
|
+
AND (
|
|
1041
|
+
runs.status IN ('queued', 'running', 'waiting')
|
|
1042
|
+
OR (
|
|
1043
|
+
$4::boolean
|
|
1044
|
+
AND runs.status IN ('failed', 'cancelled')
|
|
1045
|
+
AND runs.finished_at
|
|
1046
|
+
>= now() - ($3::bigint * interval '1 millisecond')
|
|
1047
|
+
)
|
|
1048
|
+
)
|
|
1049
|
+
)
|
|
995
1050
|
ORDER BY updated_at ASC
|
|
996
1051
|
LIMIT $2
|
|
997
1052
|
FOR UPDATE SKIP LOCKED
|
|
@@ -1007,7 +1062,8 @@ export async function compactPostgresIntegrationInvocationResponses(input: {
|
|
|
1007
1062
|
FROM candidates
|
|
1008
1063
|
WHERE receipts.ctid = candidates.ctid
|
|
1009
1064
|
RETURNING candidates.response_bytes`,
|
|
1010
|
-
|
|
1065
|
+
// A stopped run's answers matter only while it can still be resumed.
|
|
1066
|
+
[olderThanMs, limit, RUN_RESUME_WINDOW_MS, DURABLE_RUNS_ROLLOUT.runsResume],
|
|
1011
1067
|
);
|
|
1012
1068
|
return {
|
|
1013
1069
|
rows: result.rows.length,
|
|
@@ -2428,6 +2484,133 @@ async function ensurePostgresSchedulerArrayInputIntentExpansion(
|
|
|
2428
2484
|
): Promise<void> {
|
|
2429
2485
|
await client.query(`ALTER TABLE ${tableName('runs', options)}
|
|
2430
2486
|
ADD COLUMN IF NOT EXISTS array_input_started boolean NOT NULL DEFAULT false`);
|
|
2487
|
+
// When the run's staged array input was deleted. Absent means it is still
|
|
2488
|
+
// there (or the run never staged any), so `runs resume` can read it.
|
|
2489
|
+
await client.query(`ALTER TABLE ${tableName('runs', options)}
|
|
2490
|
+
ADD COLUMN IF NOT EXISTS array_input_retired_at timestamptz`);
|
|
2491
|
+
// The last failed expiry-sweep attempt, so a run that cannot be retired
|
|
2492
|
+
// moves behind the others instead of holding the head of every pass.
|
|
2493
|
+
await client.query(`ALTER TABLE ${tableName('runs', options)}
|
|
2494
|
+
ADD COLUMN IF NOT EXISTS array_input_retire_attempted_at timestamptz,
|
|
2495
|
+
-- Positive evidence that the staged input was deliberately kept for
|
|
2496
|
+
-- resume. A build that predates the keep decision deletes the input at
|
|
2497
|
+
-- terminal and never writes this, so its absence must not be read as
|
|
2498
|
+
-- "input still there".
|
|
2499
|
+
ADD COLUMN IF NOT EXISTS array_input_kept_for_resume_at timestamptz`);
|
|
2500
|
+
}
|
|
2501
|
+
|
|
2502
|
+
/**
|
|
2503
|
+
* Record, at the point the terminal delivery decides to keep a stopped run's
|
|
2504
|
+
* staged array input, that it was kept for `runs resume`. A scheduler schema
|
|
2505
|
+
* older than the column keeps its previous behavior (resume is refused there).
|
|
2506
|
+
*/
|
|
2507
|
+
export async function markPostgresSchedulerArrayInputKeptForResume(
|
|
2508
|
+
client: PostgresSchedulerQueryClient,
|
|
2509
|
+
input: { orgId: string; runId: string },
|
|
2510
|
+
options?: Pick<PostgresSchedulerOptions, 'schema'>,
|
|
2511
|
+
): Promise<void> {
|
|
2512
|
+
const column = await client.query<{ present: boolean }>(
|
|
2513
|
+
`SELECT EXISTS (
|
|
2514
|
+
SELECT 1 FROM pg_attribute
|
|
2515
|
+
WHERE attrelid = to_regclass($1)
|
|
2516
|
+
AND attname = 'array_input_kept_for_resume_at'
|
|
2517
|
+
AND NOT attisdropped
|
|
2518
|
+
) AS present`,
|
|
2519
|
+
[tableName('runs', options)],
|
|
2520
|
+
);
|
|
2521
|
+
if (column.rows[0]?.present !== true) return;
|
|
2522
|
+
await client.query(
|
|
2523
|
+
`UPDATE ${tableName('runs', options)}
|
|
2524
|
+
SET array_input_kept_for_resume_at =
|
|
2525
|
+
coalesce(array_input_kept_for_resume_at, now())
|
|
2526
|
+
WHERE run_id = $1 AND org_id = $2
|
|
2527
|
+
AND status IN ('failed', 'cancelled')
|
|
2528
|
+
AND array_input_started
|
|
2529
|
+
AND array_input_retired_at IS NULL`,
|
|
2530
|
+
[input.runId, input.orgId],
|
|
2531
|
+
);
|
|
2532
|
+
}
|
|
2533
|
+
|
|
2534
|
+
async function runsArrayInputRetiredColumnPresent(
|
|
2535
|
+
client: PostgresSchedulerQueryClient,
|
|
2536
|
+
options?: Pick<PostgresSchedulerOptions, 'schema'>,
|
|
2537
|
+
): Promise<boolean> {
|
|
2538
|
+
const column = await client.query<{ present: boolean }>(
|
|
2539
|
+
`SELECT (
|
|
2540
|
+
SELECT count(*) FROM pg_attribute
|
|
2541
|
+
WHERE attrelid = to_regclass($1)
|
|
2542
|
+
AND attname IN ('array_input_retired_at', 'array_input_retire_attempted_at')
|
|
2543
|
+
AND NOT attisdropped
|
|
2544
|
+
) = 2 AS present`,
|
|
2545
|
+
[tableName('runs', options)],
|
|
2546
|
+
);
|
|
2547
|
+
return column.rows[0]?.present === true;
|
|
2548
|
+
}
|
|
2549
|
+
|
|
2550
|
+
/**
|
|
2551
|
+
* Record that a stopped run's staged array input was deleted. A scheduler
|
|
2552
|
+
* schema older than the column keeps its previous behavior.
|
|
2553
|
+
*/
|
|
2554
|
+
export async function markPostgresSchedulerArrayInputRetired(
|
|
2555
|
+
client: PostgresSchedulerQueryClient,
|
|
2556
|
+
input: { orgId: string; runId: string },
|
|
2557
|
+
options?: Pick<PostgresSchedulerOptions, 'schema'>,
|
|
2558
|
+
): Promise<void> {
|
|
2559
|
+
if (!(await runsArrayInputRetiredColumnPresent(client, options))) return;
|
|
2560
|
+
await client.query(
|
|
2561
|
+
`UPDATE ${tableName('runs', options)}
|
|
2562
|
+
SET array_input_retired_at = coalesce(array_input_retired_at, now())
|
|
2563
|
+
WHERE run_id = $1 AND org_id = $2
|
|
2564
|
+
AND status IN ('completed', 'failed', 'cancelled')`,
|
|
2565
|
+
[input.runId, input.orgId],
|
|
2566
|
+
);
|
|
2567
|
+
}
|
|
2568
|
+
|
|
2569
|
+
/** Record a failed expiry-sweep attempt for a run's staged input. */
|
|
2570
|
+
export async function recordPostgresSchedulerArrayInputRetireAttempt(
|
|
2571
|
+
client: PostgresSchedulerQueryClient,
|
|
2572
|
+
input: { orgId: string; runId: string },
|
|
2573
|
+
options?: Pick<PostgresSchedulerOptions, 'schema'>,
|
|
2574
|
+
): Promise<void> {
|
|
2575
|
+
if (!(await runsArrayInputRetiredColumnPresent(client, options))) return;
|
|
2576
|
+
await client.query(
|
|
2577
|
+
`UPDATE ${tableName('runs', options)}
|
|
2578
|
+
SET array_input_retire_attempted_at = now()
|
|
2579
|
+
WHERE run_id = $1 AND org_id = $2`,
|
|
2580
|
+
[input.runId, input.orgId],
|
|
2581
|
+
);
|
|
2582
|
+
}
|
|
2583
|
+
|
|
2584
|
+
/**
|
|
2585
|
+
* Stopped runs whose staged array input outlived the resume window, oldest
|
|
2586
|
+
* first. Each is retired and then marked, so a pass never selects it again.
|
|
2587
|
+
*/
|
|
2588
|
+
export async function listPostgresSchedulerExpiredStagedInputRuns(
|
|
2589
|
+
client: PostgresSchedulerQueryClient,
|
|
2590
|
+
input: { limit: number },
|
|
2591
|
+
options?: Pick<PostgresSchedulerOptions, 'schema'>,
|
|
2592
|
+
): Promise<Array<{ runId: string; orgId: string; playName: string }>> {
|
|
2593
|
+
if (!(await runsArrayInputRetiredColumnPresent(client, options))) return [];
|
|
2594
|
+
const result = await client.query<{
|
|
2595
|
+
run_id: string;
|
|
2596
|
+
org_id: string;
|
|
2597
|
+
play_name: string;
|
|
2598
|
+
}>(
|
|
2599
|
+
`SELECT run_id, org_id, play_name
|
|
2600
|
+
FROM ${tableName('runs', options)}
|
|
2601
|
+
WHERE status IN ('failed', 'cancelled')
|
|
2602
|
+
AND array_input_started
|
|
2603
|
+
AND array_input_retired_at IS NULL
|
|
2604
|
+
AND finished_at < now() - ($1::bigint * interval '1 millisecond')
|
|
2605
|
+
ORDER BY coalesce(array_input_retire_attempted_at, finished_at) ASC
|
|
2606
|
+
LIMIT $2`,
|
|
2607
|
+
[RUN_RESUME_WINDOW_MS, Math.max(1, Math.min(500, input.limit))],
|
|
2608
|
+
);
|
|
2609
|
+
return result.rows.map((row) => ({
|
|
2610
|
+
runId: row.run_id,
|
|
2611
|
+
orgId: row.org_id,
|
|
2612
|
+
playName: row.play_name,
|
|
2613
|
+
}));
|
|
2431
2614
|
}
|
|
2432
2615
|
|
|
2433
2616
|
/** Deployment-only expansion; absent values keep legacy storage authoritative. */
|
|
@@ -2547,7 +2730,21 @@ async function ensurePostgresSchedulerTerminalComputeBillingOutboxTrigger(
|
|
|
2547
2730
|
)
|
|
2548
2731
|
)
|
|
2549
2732
|
)
|
|
2550
|
-
|
|
2733
|
+
-- A resumed run's ending re-opens its billing, so the resumed epoch's
|
|
2734
|
+
-- compute is settled too. A settlement still in flight loses its lease:
|
|
2735
|
+
-- its completion write is fenced on that lease and matches nothing,
|
|
2736
|
+
-- and the job settles again. Settlement is idempotent per compute
|
|
2737
|
+
-- session, so nothing is billed twice.
|
|
2738
|
+
ON CONFLICT (run_id) DO UPDATE
|
|
2739
|
+
SET status = 'pending',
|
|
2740
|
+
available_at = now(),
|
|
2741
|
+
lease_owner = NULL,
|
|
2742
|
+
lease_expires_at = NULL,
|
|
2743
|
+
settled_at = NULL,
|
|
2744
|
+
updated_at = now()
|
|
2745
|
+
WHERE ${tableName('compute_billing_jobs_v2', options)}.status
|
|
2746
|
+
IN ('settled', 'settling')
|
|
2747
|
+
AND NEW.event_id LIKE 'run-ended:%';
|
|
2551
2748
|
|
|
2552
2749
|
RETURN NEW;
|
|
2553
2750
|
END
|
|
@@ -2731,6 +2928,9 @@ export async function ensurePostgresSchedulerLaunchAdmissionFunctions(
|
|
|
2731
2928
|
'runtimeApiBaseUrl',
|
|
2732
2929
|
'arrayInputTerminalRetirementSupported',
|
|
2733
2930
|
'arrayInputTerminalProjectionOrigin',
|
|
2931
|
+
'runScopedKeys',
|
|
2932
|
+
'resumeEpoch',
|
|
2933
|
+
'resumeEpochFirstAttempt',
|
|
2734
2934
|
'vercelProtectionBypassToken'
|
|
2735
2935
|
]::text[],
|
|
2736
2936
|
'{maxConcurrentExternalCalls}',
|
|
@@ -3930,6 +4130,9 @@ export async function ensurePostgresSchedulerSchema(
|
|
|
3930
4130
|
'runtimeApiBaseUrl',
|
|
3931
4131
|
'arrayInputTerminalRetirementSupported',
|
|
3932
4132
|
'arrayInputTerminalProjectionOrigin',
|
|
4133
|
+
'runScopedKeys',
|
|
4134
|
+
'resumeEpoch',
|
|
4135
|
+
'resumeEpochFirstAttempt',
|
|
3933
4136
|
'vercelProtectionBypassToken'
|
|
3934
4137
|
]::text[],
|
|
3935
4138
|
'{maxConcurrentExternalCalls}',
|
|
@@ -7672,10 +7875,26 @@ export async function countPostgresSchedulerAdoptableParkedRuns(
|
|
|
7672
7875
|
`
|
|
7673
7876
|
SELECT count(*)::text AS n
|
|
7674
7877
|
FROM ${tableName('runs', options)} AS runs
|
|
7675
|
-
WHERE runs.
|
|
7676
|
-
AND
|
|
7677
|
-
|
|
7678
|
-
|
|
7878
|
+
WHERE runs.launch_json ->> 'absurdReleaseId' = $1
|
|
7879
|
+
AND (
|
|
7880
|
+
(
|
|
7881
|
+
runs.status = 'waiting'
|
|
7882
|
+
AND runs.suspension_json ->> 'kind'
|
|
7883
|
+
IN ('sleep', 'integration_event', 'integration_event_batch')
|
|
7884
|
+
)
|
|
7885
|
+
-- A run waiting out a post-code recovery delay holds no compute;
|
|
7886
|
+
-- a newer lane adopts its wake, so it must not pin this lane for
|
|
7887
|
+
-- the recovery horizon.
|
|
7888
|
+
OR (
|
|
7889
|
+
runs.status = 'queued'
|
|
7890
|
+
AND runs.recovery_json #>> '{postCode,nextRetryAtMs}' IS NOT NULL
|
|
7891
|
+
AND NOT EXISTS (
|
|
7892
|
+
SELECT 1 FROM ${tableName('attempts', options)} AS attempts
|
|
7893
|
+
WHERE attempts.run_id = runs.run_id
|
|
7894
|
+
AND attempts.status IN ('claimed', 'running', 'waiting')
|
|
7895
|
+
)
|
|
7896
|
+
)
|
|
7897
|
+
)
|
|
7679
7898
|
`,
|
|
7680
7899
|
[input.releaseId],
|
|
7681
7900
|
);
|
|
@@ -7845,6 +8064,7 @@ export async function assignPostgresSchedulerRunAttempt(
|
|
|
7845
8064
|
'run-started:' || run_started.run_id,
|
|
7846
8065
|
run_started.run_id,
|
|
7847
8066
|
${RUN_EVENT_KIND_SQL_LITERAL.runStarted},
|
|
8067
|
+
${runResumeEpochPayloadSql('run_started.run_id', options)} ||
|
|
7848
8068
|
jsonb_build_object(
|
|
7849
8069
|
'playName', run_started.launch_json ->> 'playName',
|
|
7850
8070
|
'runtimeBackend', run_started.launch_json ->> 'runtimeBackend',
|
|
@@ -7979,7 +8199,7 @@ export async function resumePostgresSchedulerDetachedRunnerAttempt(
|
|
|
7979
8199
|
INSERT INTO ${tableName('outbox', options)} (
|
|
7980
8200
|
event_id, run_id, event_type, payload_json, created_at
|
|
7981
8201
|
)
|
|
7982
|
-
SELECT $4, run_id, ${RUN_EVENT_KIND_SQL_LITERAL.runWaiting}, jsonb_build_object('kind', 'detached_runner'),
|
|
8202
|
+
SELECT $4, run_id, ${RUN_EVENT_KIND_SQL_LITERAL.runWaiting}, ${runResumeEpochPayloadSql('restored_run.run_id', options)} || jsonb_build_object('kind', 'detached_runner'),
|
|
7983
8203
|
${causalOutboxCreatedAt('restored_run.run_id', options)}
|
|
7984
8204
|
FROM restored_run
|
|
7985
8205
|
RETURNING run_id
|
|
@@ -8120,6 +8340,7 @@ export async function markPostgresSchedulerAttemptWaiting(
|
|
|
8120
8340
|
$6,
|
|
8121
8341
|
waiting_run.run_id,
|
|
8122
8342
|
${RUN_EVENT_KIND_SQL_LITERAL.runWaiting},
|
|
8343
|
+
${runResumeEpochPayloadSql('waiting_run.run_id', options)} ||
|
|
8123
8344
|
jsonb_strip_nulls(jsonb_build_object(
|
|
8124
8345
|
'kind', NULLIF(btrim($4::jsonb ->> 'kind'), ''),
|
|
8125
8346
|
'eventKey', NULLIF($7::text, ''),
|
|
@@ -8266,6 +8487,7 @@ export async function markPostgresSchedulerAttemptRunning(
|
|
|
8266
8487
|
$4,
|
|
8267
8488
|
running_run.run_id,
|
|
8268
8489
|
${RUN_EVENT_KIND_SQL_LITERAL.runResumed},
|
|
8490
|
+
${runResumeEpochPayloadSql('running_run.run_id', options)} ||
|
|
8269
8491
|
jsonb_strip_nulls(jsonb_build_object(
|
|
8270
8492
|
'kind', NULLIF(btrim(running_run.suspension_json ->> 'kind'), ''),
|
|
8271
8493
|
'eventKey',
|
|
@@ -8364,6 +8586,7 @@ export async function claimPostgresSchedulerCompletedDetachedRunnerTerminal(
|
|
|
8364
8586
|
$3,
|
|
8365
8587
|
run_id,
|
|
8366
8588
|
${RUN_EVENT_KIND_SQL_LITERAL.runResumed},
|
|
8589
|
+
${runResumeEpochPayloadSql('running_run.run_id', options)} ||
|
|
8367
8590
|
jsonb_build_object(
|
|
8368
8591
|
'kind', 'detached_runner',
|
|
8369
8592
|
'eventKey', 'detached_runner_terminal'
|
|
@@ -8510,6 +8733,7 @@ export async function claimPostgresSchedulerOverdueDetachedRunnerCeilings(
|
|
|
8510
8733
|
$3 || ':' || running_runs.run_id,
|
|
8511
8734
|
running_runs.run_id,
|
|
8512
8735
|
${RUN_EVENT_KIND_SQL_LITERAL.runResumed},
|
|
8736
|
+
${runResumeEpochPayloadSql('running_runs.run_id', options)} ||
|
|
8513
8737
|
jsonb_build_object(
|
|
8514
8738
|
'kind', 'detached_runner',
|
|
8515
8739
|
'eventKey', 'detached_runner_hard_ceiling'
|
|
@@ -8768,7 +8992,7 @@ export async function failPostgresSchedulerScheduledChildWaits(
|
|
|
8768
8992
|
event_id, run_id, event_type, payload_json, created_at
|
|
8769
8993
|
)
|
|
8770
8994
|
SELECT
|
|
8771
|
-
'
|
|
8995
|
+
${runEndingEventIdSql('terminal_runs.run_id', options)},
|
|
8772
8996
|
terminal_runs.run_id,
|
|
8773
8997
|
${RUN_EVENT_KIND_SQL_LITERAL.runFailed},
|
|
8774
8998
|
jsonb_build_object('error', $2::text),
|
|
@@ -9038,6 +9262,7 @@ export async function claimPostgresSchedulerWaitingDetachedAttemptForTerminal(
|
|
|
9038
9262
|
$4,
|
|
9039
9263
|
running_run.run_id,
|
|
9040
9264
|
${RUN_EVENT_KIND_SQL_LITERAL.runResumed},
|
|
9265
|
+
${runResumeEpochPayloadSql('running_run.run_id', options)} ||
|
|
9041
9266
|
jsonb_build_object(
|
|
9042
9267
|
'kind', 'detached_runner',
|
|
9043
9268
|
'eventKey', 'detached_runner_terminal_salvage'
|
|
@@ -9180,110 +9405,920 @@ export async function claimPostgresSchedulerRecoveryCircuit(
|
|
|
9180
9405
|
RETURNING dependency, probe_token
|
|
9181
9406
|
`,
|
|
9182
9407
|
[
|
|
9183
|
-
input.dependency,
|
|
9408
|
+
input.dependency,
|
|
9409
|
+
input.nowMs,
|
|
9410
|
+
RECOVERY_CIRCUIT_PROBE_LEASE_MS,
|
|
9411
|
+
probeToken,
|
|
9412
|
+
],
|
|
9413
|
+
);
|
|
9414
|
+
if (probe.rows.length > 0) {
|
|
9415
|
+
return { allowed: true, probeToken: probe.rows[0]?.probe_token ?? null };
|
|
9416
|
+
}
|
|
9417
|
+
const current = await client.query<{ state: string }>(
|
|
9418
|
+
`SELECT state
|
|
9419
|
+
FROM ${tableName(POSTGRES_SCHEDULER_DEPENDENCY_CIRCUITS_TABLE, options)}
|
|
9420
|
+
WHERE dependency = $1`,
|
|
9421
|
+
[input.dependency],
|
|
9422
|
+
);
|
|
9423
|
+
return { allowed: current.rows[0]?.state === 'closed', probeToken: null };
|
|
9424
|
+
}
|
|
9425
|
+
|
|
9426
|
+
/** Mark a half-open probe healthy only after its provider resource is durable. */
|
|
9427
|
+
export async function closePostgresSchedulerRecoveryCircuit(
|
|
9428
|
+
client: PostgresSchedulerQueryClient,
|
|
9429
|
+
input: { dependency: string; probeToken: string },
|
|
9430
|
+
options?: Pick<PostgresSchedulerOptions, 'schema'>,
|
|
9431
|
+
): Promise<boolean> {
|
|
9432
|
+
const result = await client.query<{ dependency: string }>(
|
|
9433
|
+
`
|
|
9434
|
+
UPDATE ${tableName(POSTGRES_SCHEDULER_DEPENDENCY_CIRCUITS_TABLE, options)}
|
|
9435
|
+
SET state = 'closed',
|
|
9436
|
+
open_until_ms = 0,
|
|
9437
|
+
probe_until_ms = 0,
|
|
9438
|
+
probe_token = NULL,
|
|
9439
|
+
updated_at = now()
|
|
9440
|
+
WHERE dependency = $1
|
|
9441
|
+
AND state = 'half_open'
|
|
9442
|
+
AND probe_token = $2
|
|
9443
|
+
RETURNING dependency
|
|
9444
|
+
`,
|
|
9445
|
+
[input.dependency, input.probeToken],
|
|
9446
|
+
);
|
|
9447
|
+
return result.rows.length > 0;
|
|
9448
|
+
}
|
|
9449
|
+
|
|
9450
|
+
/** Operator-only recovery after a verified incident; keep an auditable reason. */
|
|
9451
|
+
export async function resetPostgresSchedulerRecoveryCircuit(
|
|
9452
|
+
client: PostgresSchedulerQueryClient,
|
|
9453
|
+
input: { dependency: string; reason: string },
|
|
9454
|
+
options?: Pick<PostgresSchedulerOptions, 'schema'>,
|
|
9455
|
+
): Promise<boolean> {
|
|
9456
|
+
const result = await client.query<{ dependency: string }>(
|
|
9457
|
+
`
|
|
9458
|
+
UPDATE ${tableName(POSTGRES_SCHEDULER_DEPENDENCY_CIRCUITS_TABLE, options)}
|
|
9459
|
+
SET state = 'closed',
|
|
9460
|
+
open_until_ms = 0,
|
|
9461
|
+
probe_until_ms = 0,
|
|
9462
|
+
probe_token = NULL,
|
|
9463
|
+
last_reason = $2,
|
|
9464
|
+
updated_at = now()
|
|
9465
|
+
WHERE dependency = $1
|
|
9466
|
+
RETURNING dependency
|
|
9467
|
+
`,
|
|
9468
|
+
[input.dependency, input.reason],
|
|
9469
|
+
);
|
|
9470
|
+
return result.rows.length > 0;
|
|
9471
|
+
}
|
|
9472
|
+
|
|
9473
|
+
export async function readPostgresSchedulerRecoveryCircuits(
|
|
9474
|
+
client: PostgresSchedulerQueryClient,
|
|
9475
|
+
options?: Pick<PostgresSchedulerOptions, 'schema'>,
|
|
9476
|
+
): Promise<PostgresSchedulerRecoveryCircuit[]> {
|
|
9477
|
+
const result = await client.query<{
|
|
9478
|
+
dependency: string;
|
|
9479
|
+
state: PostgresSchedulerRecoveryCircuit['state'];
|
|
9480
|
+
open_until_ms: string;
|
|
9481
|
+
probe_until_ms: string;
|
|
9482
|
+
last_reason: string | null;
|
|
9483
|
+
updated_at: Date;
|
|
9484
|
+
}>(
|
|
9485
|
+
`SELECT dependency, state, open_until_ms, probe_until_ms, last_reason, updated_at
|
|
9486
|
+
FROM ${tableName(POSTGRES_SCHEDULER_DEPENDENCY_CIRCUITS_TABLE, options)}
|
|
9487
|
+
ORDER BY dependency`,
|
|
9488
|
+
);
|
|
9489
|
+
return result.rows.map((row) => ({
|
|
9490
|
+
dependency: row.dependency,
|
|
9491
|
+
state: row.state,
|
|
9492
|
+
openUntilMs: Number(row.open_until_ms),
|
|
9493
|
+
probeUntilMs: Number(row.probe_until_ms),
|
|
9494
|
+
lastReason: row.last_reason,
|
|
9495
|
+
updatedAt: row.updated_at,
|
|
9496
|
+
}));
|
|
9497
|
+
}
|
|
9498
|
+
|
|
9499
|
+
export type PostgresSchedulerRecoveryDeferral = {
|
|
9500
|
+
deferred: boolean;
|
|
9501
|
+
exhausted: boolean;
|
|
9502
|
+
deferCount: number | null;
|
|
9503
|
+
deadlineAtMs: number | null;
|
|
9504
|
+
};
|
|
9505
|
+
|
|
9506
|
+
/**
|
|
9507
|
+
* Park a proven pre-code platform failure without spending an Absurd engine
|
|
9508
|
+
* attempt. Unlike ordinary capacity parking, this records a finite recovery
|
|
9509
|
+
* horizon on the canonical run row. The task engine owns the wake; this store
|
|
9510
|
+
* owns the fact that another wake is still allowed.
|
|
9511
|
+
*/
|
|
9512
|
+
/**
|
|
9513
|
+
* The outbox event ID of a run's ending. A run that was never resumed keeps
|
|
9514
|
+
* `run-terminal:{runId}`, so its consumers see no change; each ending after
|
|
9515
|
+
* a resume gets `run-ended:{runId}:{epoch}`, so it is a new event instead of
|
|
9516
|
+
* a conflict with the earlier ending. Mirror of `runEndingEventId`.
|
|
9517
|
+
*/
|
|
9518
|
+
function runEndingEventIdSql(
|
|
9519
|
+
runIdExpression: string,
|
|
9520
|
+
options?: Pick<PostgresSchedulerOptions, 'schema'>,
|
|
9521
|
+
): string {
|
|
9522
|
+
return `(
|
|
9523
|
+
SELECT CASE
|
|
9524
|
+
WHEN coalesce(
|
|
9525
|
+
(coalesce(ending_run.admission_json, ending_run.launch_json) ->> 'resumeEpoch')::integer,
|
|
9526
|
+
0
|
|
9527
|
+
) = 0
|
|
9528
|
+
THEN 'run-terminal:' || ending_run.run_id
|
|
9529
|
+
ELSE 'run-ended:' || ending_run.run_id || ':' ||
|
|
9530
|
+
(coalesce(ending_run.admission_json, ending_run.launch_json) ->> 'resumeEpoch')
|
|
9531
|
+
END
|
|
9532
|
+
FROM ${tableName('runs', options)} AS ending_run
|
|
9533
|
+
WHERE ending_run.run_id = ${runIdExpression}
|
|
9534
|
+
)`;
|
|
9535
|
+
}
|
|
9536
|
+
|
|
9537
|
+
/** Freeze the epoch when a lifecycle fact is written, never at delivery. */
|
|
9538
|
+
function runResumeEpochPayloadSql(
|
|
9539
|
+
runIdExpression: string,
|
|
9540
|
+
options?: Pick<PostgresSchedulerOptions, 'schema'>,
|
|
9541
|
+
): string {
|
|
9542
|
+
return `(SELECT CASE WHEN coalesce((coalesce(epoch_run.admission_json, epoch_run.launch_json) ->> 'resumeEpoch')::integer, 0) > 0
|
|
9543
|
+
THEN jsonb_build_object('epoch', (coalesce(epoch_run.admission_json, epoch_run.launch_json) ->> 'resumeEpoch')::integer)
|
|
9544
|
+
ELSE '{}'::jsonb END
|
|
9545
|
+
FROM ${tableName('runs', options)} AS epoch_run
|
|
9546
|
+
WHERE epoch_run.run_id = ${runIdExpression})`;
|
|
9547
|
+
}
|
|
9548
|
+
|
|
9549
|
+
/** The ending event ID for a run at its current resume epoch. */
|
|
9550
|
+
export async function readPostgresSchedulerRunEndingEventId(
|
|
9551
|
+
client: PostgresSchedulerQueryClient,
|
|
9552
|
+
runId: string,
|
|
9553
|
+
options?: Pick<PostgresSchedulerOptions, 'schema'>,
|
|
9554
|
+
): Promise<string> {
|
|
9555
|
+
const result = await client.query<{ event_id: string | null }>(
|
|
9556
|
+
`SELECT ${runEndingEventIdSql('$1::text', options)} AS event_id`,
|
|
9557
|
+
[runId],
|
|
9558
|
+
);
|
|
9559
|
+
return result.rows[0]?.event_id ?? runEndingEventId(runId);
|
|
9560
|
+
}
|
|
9561
|
+
|
|
9562
|
+
/** How long after it ended a failed or cancelled run can be resumed. */
|
|
9563
|
+
export const RUN_RESUME_WINDOW_MS = 14 * 24 * 60 * 60_000;
|
|
9564
|
+
|
|
9565
|
+
export type PostgresSchedulerRunResume =
|
|
9566
|
+
| { resumed: true; epoch: number; taskId: string }
|
|
9567
|
+
| {
|
|
9568
|
+
resumed: false;
|
|
9569
|
+
reason:
|
|
9570
|
+
| 'run_not_found'
|
|
9571
|
+
| 'run_not_stopped'
|
|
9572
|
+
| 'attempt_not_settled'
|
|
9573
|
+
| 'sandbox_cleanup_pending'
|
|
9574
|
+
| 'resume_window_expired'
|
|
9575
|
+
/**
|
|
9576
|
+
* The run made a call with no recorded result (a pre-edition-11
|
|
9577
|
+
* inline child) or predates replay tracking, so continuing it could
|
|
9578
|
+
* repeat work.
|
|
9579
|
+
*/
|
|
9580
|
+
| 'not_replay_safe'
|
|
9581
|
+
/** The Play changed since this run; start over on the new code. */
|
|
9582
|
+
| 'play_revision_changed'
|
|
9583
|
+
/**
|
|
9584
|
+
* The run's staged array input was deleted at its ending, so a
|
|
9585
|
+
* resumed attempt could not read its rows. Start over with
|
|
9586
|
+
* `plays run --from-run`.
|
|
9587
|
+
*/
|
|
9588
|
+
| 'staged_input_retired';
|
|
9589
|
+
};
|
|
9590
|
+
|
|
9591
|
+
/** Scheduler-owned reasons a stopped run cannot continue in place. */
|
|
9592
|
+
export type PostgresSchedulerRunResumeRefusal = Exclude<
|
|
9593
|
+
Extract<PostgresSchedulerRunResume, { resumed: false }>['reason'],
|
|
9594
|
+
'run_not_found'
|
|
9595
|
+
>;
|
|
9596
|
+
|
|
9597
|
+
/** The facts the resume gate reads, one boolean per gate. */
|
|
9598
|
+
export type PostgresSchedulerRunResumeChecks = {
|
|
9599
|
+
stopped: boolean;
|
|
9600
|
+
attempts_settled: boolean;
|
|
9601
|
+
cleanup_settled: boolean;
|
|
9602
|
+
within_window: boolean;
|
|
9603
|
+
input_kept: boolean;
|
|
9604
|
+
replay_safe: boolean;
|
|
9605
|
+
revision_unchanged: boolean;
|
|
9606
|
+
};
|
|
9607
|
+
|
|
9608
|
+
/**
|
|
9609
|
+
* The one resume predicate: the refusal a run's checks produce, in the order
|
|
9610
|
+
* `resumePostgresSchedulerRun` reports it, or null when every gate passes.
|
|
9611
|
+
* Resume and every read-only eligibility reader share this and
|
|
9612
|
+
* `postgresSchedulerRunResumeChecksSql`, so an operator view can never
|
|
9613
|
+
* disagree with what resume would do.
|
|
9614
|
+
*/
|
|
9615
|
+
export function postgresSchedulerRunResumeRefusal(
|
|
9616
|
+
checks: PostgresSchedulerRunResumeChecks,
|
|
9617
|
+
): PostgresSchedulerRunResumeRefusal | null {
|
|
9618
|
+
if (!checks.stopped) return 'run_not_stopped';
|
|
9619
|
+
if (!checks.attempts_settled) return 'attempt_not_settled';
|
|
9620
|
+
if (!checks.cleanup_settled) return 'sandbox_cleanup_pending';
|
|
9621
|
+
if (!checks.replay_safe) return 'not_replay_safe';
|
|
9622
|
+
if (!checks.revision_unchanged) return 'play_revision_changed';
|
|
9623
|
+
if (!checks.input_kept) return 'staged_input_retired';
|
|
9624
|
+
if (!checks.within_window) return 'resume_window_expired';
|
|
9625
|
+
return null;
|
|
9626
|
+
}
|
|
9627
|
+
|
|
9628
|
+
/** Columns of the `target` row the resume checks read, from `runs AS runs`. */
|
|
9629
|
+
function postgresSchedulerRunResumeTargetColumnsSql(): string {
|
|
9630
|
+
return `runs.run_id,
|
|
9631
|
+
runs.status,
|
|
9632
|
+
runs.finished_at,
|
|
9633
|
+
-- Row JSON keeps this optional on historical scheduler schemas.
|
|
9634
|
+
to_jsonb(runs) ->> 'array_input_retired_at'
|
|
9635
|
+
AS array_input_retired_at,
|
|
9636
|
+
to_jsonb(runs) ->> 'array_input_kept_for_resume_at'
|
|
9637
|
+
AS array_input_kept_for_resume_at,
|
|
9638
|
+
runs.array_input_started,
|
|
9639
|
+
runs.launch_json ->> 'revisionId' AS revision_id,
|
|
9640
|
+
coalesce(
|
|
9641
|
+
(coalesce(runs.admission_json, runs.launch_json) ->> 'resumeEpoch')::integer,
|
|
9642
|
+
0
|
|
9643
|
+
) AS epoch`;
|
|
9644
|
+
}
|
|
9645
|
+
|
|
9646
|
+
/**
|
|
9647
|
+
* The resume checks over a `target` row, as SQL select-list columns. Each
|
|
9648
|
+
* input is a SQL expression, so the locking resume statement and the
|
|
9649
|
+
* read-only batch reader evaluate the identical predicate.
|
|
9650
|
+
*/
|
|
9651
|
+
function postgresSchedulerRunResumeChecksSql(
|
|
9652
|
+
input: {
|
|
9653
|
+
orgIdSql: string;
|
|
9654
|
+
windowMsSql: string;
|
|
9655
|
+
revisionIdsSql: string;
|
|
9656
|
+
trackedMarkerKeySql: string;
|
|
9657
|
+
unsafeMarkerKeySql: string;
|
|
9658
|
+
},
|
|
9659
|
+
options?: Pick<PostgresSchedulerOptions, 'schema'>,
|
|
9660
|
+
): string {
|
|
9661
|
+
return `target.status IN ('failed', 'cancelled') AS stopped,
|
|
9662
|
+
NOT EXISTS (
|
|
9663
|
+
SELECT 1 FROM ${tableName('attempts', options)} AS attempts
|
|
9664
|
+
WHERE attempts.run_id = target.run_id
|
|
9665
|
+
AND attempts.status IN ('queued', 'claimed', 'running', 'waiting')
|
|
9666
|
+
)
|
|
9667
|
+
-- The stopped epoch's compute bills against the current
|
|
9668
|
+
-- launch; it must settle before the launch moves to a new one.
|
|
9669
|
+
AND NOT EXISTS (
|
|
9670
|
+
SELECT 1
|
|
9671
|
+
FROM ${tableName('compute_billing_jobs_v2', options)} AS billing
|
|
9672
|
+
WHERE billing.run_id = target.run_id
|
|
9673
|
+
AND billing.status <> 'settled'
|
|
9674
|
+
) AS attempts_settled,
|
|
9675
|
+
NOT EXISTS (
|
|
9676
|
+
SELECT 1
|
|
9677
|
+
FROM ${tableName('sandbox_cleanup_jobs_v2', options)} AS cleanup
|
|
9678
|
+
WHERE cleanup.run_id = target.run_id
|
|
9679
|
+
AND cleanup.status <> 'deleted'
|
|
9680
|
+
) AS cleanup_settled,
|
|
9681
|
+
coalesce(
|
|
9682
|
+
target.finished_at >= now() - (${input.windowMsSql} * interval '1 millisecond'),
|
|
9683
|
+
false
|
|
9684
|
+
) AS within_window,
|
|
9685
|
+
-- Positive evidence only: the run never staged input, or its
|
|
9686
|
+
-- terminal delivery recorded keeping it. A NULL retired marker
|
|
9687
|
+
-- alone is not proof; an older build deletes input unmarked.
|
|
9688
|
+
(
|
|
9689
|
+
target.array_input_retired_at IS NULL
|
|
9690
|
+
AND (
|
|
9691
|
+
NOT coalesce(target.array_input_started, false)
|
|
9692
|
+
OR target.array_input_kept_for_resume_at IS NOT NULL
|
|
9693
|
+
)
|
|
9694
|
+
) AS input_kept,
|
|
9695
|
+
(
|
|
9696
|
+
EXISTS (
|
|
9697
|
+
SELECT 1 FROM ${tableName('receipts', options)} AS marker
|
|
9698
|
+
WHERE marker.org_id = ${input.orgIdSql} AND marker.k = ${input.trackedMarkerKeySql}
|
|
9699
|
+
AND marker.status = 'completed'
|
|
9700
|
+
)
|
|
9701
|
+
AND NOT EXISTS (
|
|
9702
|
+
SELECT 1 FROM ${tableName('receipts', options)} AS marker
|
|
9703
|
+
WHERE marker.org_id = ${input.orgIdSql} AND marker.k = ${input.unsafeMarkerKeySql}
|
|
9704
|
+
)
|
|
9705
|
+
) AS replay_safe,
|
|
9706
|
+
(
|
|
9707
|
+
target.revision_id IS NULL
|
|
9708
|
+
OR target.revision_id = ANY(${input.revisionIdsSql})
|
|
9709
|
+
) AS revision_unchanged`;
|
|
9710
|
+
}
|
|
9711
|
+
|
|
9712
|
+
/** At most this many runs are evaluated by one read-only eligibility read. */
|
|
9713
|
+
export const POSTGRES_SCHEDULER_RESUME_ELIGIBILITY_MAX_RUNS = 100;
|
|
9714
|
+
|
|
9715
|
+
export type PostgresSchedulerRunResumeEligibility = {
|
|
9716
|
+
runId: string;
|
|
9717
|
+
/** False when the run is absent from this org (resume: `run_not_found`). */
|
|
9718
|
+
found: boolean;
|
|
9719
|
+
checks: PostgresSchedulerRunResumeChecks | null;
|
|
9720
|
+
/** Null when resume would continue the run now. */
|
|
9721
|
+
refusal: PostgresSchedulerRunResumeRefusal | 'run_not_found' | null;
|
|
9722
|
+
/** The epoch resume would continue from. */
|
|
9723
|
+
epoch: number | null;
|
|
9724
|
+
};
|
|
9725
|
+
|
|
9726
|
+
/**
|
|
9727
|
+
* Read-only resume eligibility for a bounded batch of runs: the exact
|
|
9728
|
+
* predicate resume evaluates, without its row lock, task spawn or write. A
|
|
9729
|
+
* concurrent writer can still change the answer before a resume runs; the
|
|
9730
|
+
* resume statement re-evaluates the same predicate under its lock.
|
|
9731
|
+
*/
|
|
9732
|
+
export async function readPostgresSchedulerRunResumeEligibility(
|
|
9733
|
+
client: PostgresSchedulerQueryClient,
|
|
9734
|
+
input: {
|
|
9735
|
+
runs: readonly {
|
|
9736
|
+
runId: string;
|
|
9737
|
+
orgId: string;
|
|
9738
|
+
/** The Play's current revisions, as resume passes them. */
|
|
9739
|
+
currentRevisionIds: readonly string[];
|
|
9740
|
+
}[];
|
|
9741
|
+
},
|
|
9742
|
+
options?: Pick<PostgresSchedulerOptions, 'schema'>,
|
|
9743
|
+
): Promise<PostgresSchedulerRunResumeEligibility[]> {
|
|
9744
|
+
if (input.runs.length === 0) return [];
|
|
9745
|
+
if (input.runs.length > POSTGRES_SCHEDULER_RESUME_ELIGIBILITY_MAX_RUNS) {
|
|
9746
|
+
throw new Error(
|
|
9747
|
+
`Resume eligibility reads at most ${POSTGRES_SCHEDULER_RESUME_ELIGIBILITY_MAX_RUNS} runs; received ${input.runs.length}.`,
|
|
9748
|
+
);
|
|
9749
|
+
}
|
|
9750
|
+
const requested = input.runs.map((run) => ({
|
|
9751
|
+
run_id: run.runId,
|
|
9752
|
+
org_id: run.orgId,
|
|
9753
|
+
revision_ids: [...run.currentRevisionIds],
|
|
9754
|
+
tracked_key: replayTrackedMarkerReceiptKey(run.orgId, run.runId),
|
|
9755
|
+
unsafe_key: replayUnsafeMarkerReceiptKey(run.orgId, run.runId),
|
|
9756
|
+
}));
|
|
9757
|
+
const result = await client.query<
|
|
9758
|
+
{
|
|
9759
|
+
run_id: string;
|
|
9760
|
+
epoch: number | string;
|
|
9761
|
+
} & PostgresSchedulerRunResumeChecks
|
|
9762
|
+
>(
|
|
9763
|
+
`
|
|
9764
|
+
WITH requested AS (
|
|
9765
|
+
SELECT *
|
|
9766
|
+
FROM jsonb_to_recordset($1::jsonb) AS requested(
|
|
9767
|
+
run_id text, org_id text, revision_ids jsonb,
|
|
9768
|
+
tracked_key text, unsafe_key text
|
|
9769
|
+
)
|
|
9770
|
+
), target AS (
|
|
9771
|
+
SELECT ${postgresSchedulerRunResumeTargetColumnsSql()},
|
|
9772
|
+
requested.org_id AS requested_org_id,
|
|
9773
|
+
ARRAY(
|
|
9774
|
+
SELECT jsonb_array_elements_text(requested.revision_ids)
|
|
9775
|
+
)::text[] AS requested_revision_ids,
|
|
9776
|
+
requested.tracked_key,
|
|
9777
|
+
requested.unsafe_key
|
|
9778
|
+
FROM requested
|
|
9779
|
+
JOIN ${tableName('runs', options)} AS runs
|
|
9780
|
+
ON runs.run_id = requested.run_id
|
|
9781
|
+
AND runs.org_id = requested.org_id
|
|
9782
|
+
)
|
|
9783
|
+
SELECT target.run_id,
|
|
9784
|
+
target.epoch,
|
|
9785
|
+
${postgresSchedulerRunResumeChecksSql(
|
|
9786
|
+
{
|
|
9787
|
+
orgIdSql: 'target.requested_org_id',
|
|
9788
|
+
windowMsSql: '$2::bigint',
|
|
9789
|
+
revisionIdsSql: 'target.requested_revision_ids',
|
|
9790
|
+
trackedMarkerKeySql: 'target.tracked_key',
|
|
9791
|
+
unsafeMarkerKeySql: 'target.unsafe_key',
|
|
9792
|
+
},
|
|
9793
|
+
options,
|
|
9794
|
+
)}
|
|
9795
|
+
FROM target
|
|
9796
|
+
`,
|
|
9797
|
+
[stringifyPostgresJson(requested), RUN_RESUME_WINDOW_MS],
|
|
9798
|
+
);
|
|
9799
|
+
const byRunId = new Map(result.rows.map((row) => [row.run_id, row]));
|
|
9800
|
+
return input.runs.map((run) => {
|
|
9801
|
+
const row = byRunId.get(run.runId);
|
|
9802
|
+
if (!row) {
|
|
9803
|
+
return {
|
|
9804
|
+
runId: run.runId,
|
|
9805
|
+
found: false,
|
|
9806
|
+
checks: null,
|
|
9807
|
+
refusal: 'run_not_found',
|
|
9808
|
+
epoch: null,
|
|
9809
|
+
};
|
|
9810
|
+
}
|
|
9811
|
+
const checks: PostgresSchedulerRunResumeChecks = {
|
|
9812
|
+
stopped: row.stopped === true,
|
|
9813
|
+
attempts_settled: row.attempts_settled === true,
|
|
9814
|
+
cleanup_settled: row.cleanup_settled === true,
|
|
9815
|
+
within_window: row.within_window === true,
|
|
9816
|
+
input_kept: row.input_kept === true,
|
|
9817
|
+
replay_safe: row.replay_safe === true,
|
|
9818
|
+
revision_unchanged: row.revision_unchanged === true,
|
|
9819
|
+
};
|
|
9820
|
+
return {
|
|
9821
|
+
runId: run.runId,
|
|
9822
|
+
found: true,
|
|
9823
|
+
checks,
|
|
9824
|
+
refusal: postgresSchedulerRunResumeRefusal(checks),
|
|
9825
|
+
epoch: Number(row.epoch),
|
|
9826
|
+
};
|
|
9827
|
+
});
|
|
9828
|
+
}
|
|
9829
|
+
|
|
9830
|
+
/**
|
|
9831
|
+
* Continue a failed or cancelled run as the same run.
|
|
9832
|
+
*
|
|
9833
|
+
* One statement: compare-and-set the run from its ending back to queued,
|
|
9834
|
+
* bump its resume epoch, clear the ending, stamp the caller's current release
|
|
9835
|
+
* lane (a run is pinned to the lane that admitted it, which is usually retired
|
|
9836
|
+
* within a day), spawn a new scheduler task (the finished one cannot restart)
|
|
9837
|
+
* keyed by run and epoch, record it as the run's task, reset the post-code
|
|
9838
|
+
* recovery budget, and append the `run.resumed` event. Its next attempt
|
|
9839
|
+
* replays the Play from its checkpoint and recovers every recorded call.
|
|
9840
|
+
*
|
|
9841
|
+
* The epoch lives in `launch_json.resumeEpoch` (absent means 0) and is not
|
|
9842
|
+
* part of launch identity. Readers order a run's endings by it, so a later
|
|
9843
|
+
* ending supersedes an earlier one instead of being dropped as a duplicate.
|
|
9844
|
+
*/
|
|
9845
|
+
export async function resumePostgresSchedulerRun(
|
|
9846
|
+
client: PostgresSchedulerQueryClient,
|
|
9847
|
+
input: {
|
|
9848
|
+
runId: string;
|
|
9849
|
+
orgId: string;
|
|
9850
|
+
requestedBy: string | null;
|
|
9851
|
+
releaseId: string;
|
|
9852
|
+
releaseEnvironment: string;
|
|
9853
|
+
/**
|
|
9854
|
+
* The Play's current revisions (working and live). A run pinned to a
|
|
9855
|
+
* revision that is neither is refused. A run with no revision (started
|
|
9856
|
+
* from a local file) skips the check. A missing Play cannot establish that
|
|
9857
|
+
* its pinned revision is unchanged.
|
|
9858
|
+
*/
|
|
9859
|
+
currentRevisionIds: readonly string[];
|
|
9860
|
+
task: {
|
|
9861
|
+
queueName: string;
|
|
9862
|
+
taskName: string;
|
|
9863
|
+
params: Record<string, unknown>;
|
|
9864
|
+
options: Record<string, unknown>;
|
|
9865
|
+
};
|
|
9866
|
+
},
|
|
9867
|
+
options?: Pick<PostgresSchedulerOptions, 'schema'>,
|
|
9868
|
+
): Promise<PostgresSchedulerRunResume> {
|
|
9869
|
+
const result = await client.query<
|
|
9870
|
+
{
|
|
9871
|
+
found: boolean;
|
|
9872
|
+
task_id: string | null;
|
|
9873
|
+
epoch: number | null;
|
|
9874
|
+
} & PostgresSchedulerRunResumeChecks
|
|
9875
|
+
>(
|
|
9876
|
+
`
|
|
9877
|
+
WITH target AS (
|
|
9878
|
+
SELECT ${postgresSchedulerRunResumeTargetColumnsSql()}
|
|
9879
|
+
FROM ${tableName('runs', options)} AS runs
|
|
9880
|
+
WHERE runs.run_id = $1
|
|
9881
|
+
AND runs.org_id = $2
|
|
9882
|
+
FOR UPDATE
|
|
9883
|
+
), checks AS (
|
|
9884
|
+
SELECT target.*,
|
|
9885
|
+
${postgresSchedulerRunResumeChecksSql(
|
|
9886
|
+
{
|
|
9887
|
+
orgIdSql: '$2',
|
|
9888
|
+
windowMsSql: '$3::bigint',
|
|
9889
|
+
revisionIdsSql: '$11::text[]',
|
|
9890
|
+
trackedMarkerKeySql: '$12',
|
|
9891
|
+
unsafeMarkerKeySql: '$13',
|
|
9892
|
+
},
|
|
9893
|
+
options,
|
|
9894
|
+
)}
|
|
9895
|
+
FROM target
|
|
9896
|
+
), eligible AS (
|
|
9897
|
+
SELECT * FROM checks
|
|
9898
|
+
WHERE stopped AND attempts_settled AND cleanup_settled AND within_window
|
|
9899
|
+
AND input_kept AND replay_safe AND revision_unchanged
|
|
9900
|
+
), task_spawn AS MATERIALIZED (
|
|
9901
|
+
SELECT spawned.task_id::text AS task_id, eligible.epoch + 1 AS epoch,
|
|
9902
|
+
-- The resumed epoch's attempts start after every earlier one;
|
|
9903
|
+
-- its compute is billed from these alone.
|
|
9904
|
+
(
|
|
9905
|
+
SELECT coalesce(max(attempts.attempt), 0) + 1
|
|
9906
|
+
FROM ${tableName('attempts', options)} AS attempts
|
|
9907
|
+
WHERE attempts.run_id = eligible.run_id
|
|
9908
|
+
) AS first_attempt
|
|
9909
|
+
FROM eligible
|
|
9910
|
+
CROSS JOIN LATERAL absurd.spawn_task(
|
|
9911
|
+
$4::text,
|
|
9912
|
+
$5::text,
|
|
9913
|
+
$6::jsonb,
|
|
9914
|
+
$7::jsonb || jsonb_build_object(
|
|
9915
|
+
'idempotency_key',
|
|
9916
|
+
eligible.run_id || ':resume:' || (eligible.epoch + 1)::text
|
|
9917
|
+
)
|
|
9918
|
+
) AS spawned
|
|
9919
|
+
), resumed AS (
|
|
9920
|
+
UPDATE ${tableName('runs', options)} AS runs
|
|
9921
|
+
SET status = 'queued',
|
|
9922
|
+
terminal_result_json = NULL,
|
|
9923
|
+
terminal_error_json = NULL,
|
|
9924
|
+
finished_at = NULL,
|
|
9925
|
+
suspension_json = NULL,
|
|
9926
|
+
wait_deadline = NULL,
|
|
9927
|
+
absurd_task_id = task_spawn.task_id,
|
|
9928
|
+
recovery_json = coalesce(runs.recovery_json, '{}'::jsonb) - ARRAY[
|
|
9929
|
+
'postCode', 'version', 'kind', 'dependency', 'reason', 'deferCount',
|
|
9930
|
+
'deadlineAtMs', 'nextRetryAtMs', 'updatedAtMs', 'exhaustedAtMs'
|
|
9931
|
+
]::text[],
|
|
9932
|
+
launch_json = runs.launch_json || jsonb_build_object(
|
|
9933
|
+
'resumeEpoch', task_spawn.epoch,
|
|
9934
|
+
'resumeEpochFirstAttempt', task_spawn.first_attempt,
|
|
9935
|
+
'absurdReleaseId', $8::text,
|
|
9936
|
+
'absurdReleaseEnvironment', $9::text
|
|
9937
|
+
),
|
|
9938
|
+
-- Readers use admission_json in place of launch_json when it is
|
|
9939
|
+
-- present, so the epoch and lane must land in both.
|
|
9940
|
+
admission_json = CASE
|
|
9941
|
+
WHEN runs.admission_json IS NULL THEN NULL
|
|
9942
|
+
ELSE runs.admission_json || jsonb_build_object(
|
|
9943
|
+
'resumeEpoch', task_spawn.epoch,
|
|
9944
|
+
'resumeEpochFirstAttempt', task_spawn.first_attempt,
|
|
9945
|
+
'absurdReleaseId', $8::text,
|
|
9946
|
+
'absurdReleaseEnvironment', $9::text
|
|
9947
|
+
)
|
|
9948
|
+
END,
|
|
9949
|
+
updated_at = now()
|
|
9950
|
+
FROM task_spawn
|
|
9951
|
+
WHERE runs.run_id = $1
|
|
9952
|
+
RETURNING runs.run_id, task_spawn.epoch, task_spawn.task_id
|
|
9953
|
+
), resumed_event AS (
|
|
9954
|
+
INSERT INTO ${tableName('outbox', options)} (
|
|
9955
|
+
event_id, run_id, event_type, payload_json
|
|
9956
|
+
)
|
|
9957
|
+
SELECT 'run-resumed:' || resumed.run_id || ':' || resumed.epoch::text,
|
|
9958
|
+
resumed.run_id,
|
|
9959
|
+
'run.resumed',
|
|
9960
|
+
jsonb_build_object(
|
|
9961
|
+
'runId', resumed.run_id,
|
|
9962
|
+
'epoch', resumed.epoch,
|
|
9963
|
+
'requestedBy', $10::text,
|
|
9964
|
+
'resumedAtMs', (extract(epoch from clock_timestamp()) * 1000)::bigint
|
|
9965
|
+
)
|
|
9966
|
+
FROM resumed
|
|
9967
|
+
ON CONFLICT (event_id) DO NOTHING
|
|
9968
|
+
RETURNING event_id
|
|
9969
|
+
)
|
|
9970
|
+
SELECT EXISTS (SELECT 1 FROM checks) AS found,
|
|
9971
|
+
coalesce((SELECT stopped FROM checks), false) AS stopped,
|
|
9972
|
+
coalesce((SELECT attempts_settled FROM checks), false) AS attempts_settled,
|
|
9973
|
+
coalesce((SELECT cleanup_settled FROM checks), false) AS cleanup_settled,
|
|
9974
|
+
coalesce((SELECT within_window FROM checks), false) AS within_window,
|
|
9975
|
+
coalesce((SELECT input_kept FROM checks), false) AS input_kept,
|
|
9976
|
+
coalesce((SELECT replay_safe FROM checks), false) AS replay_safe,
|
|
9977
|
+
coalesce((SELECT revision_unchanged FROM checks), false)
|
|
9978
|
+
AS revision_unchanged,
|
|
9979
|
+
(SELECT task_id FROM resumed) AS task_id,
|
|
9980
|
+
(SELECT epoch FROM resumed) AS epoch
|
|
9981
|
+
`,
|
|
9982
|
+
[
|
|
9983
|
+
input.runId,
|
|
9984
|
+
input.orgId,
|
|
9985
|
+
RUN_RESUME_WINDOW_MS,
|
|
9986
|
+
input.task.queueName,
|
|
9987
|
+
input.task.taskName,
|
|
9988
|
+
stringifyPostgresJson(input.task.params),
|
|
9989
|
+
stringifyPostgresJson(input.task.options),
|
|
9990
|
+
input.releaseId,
|
|
9991
|
+
input.releaseEnvironment,
|
|
9992
|
+
input.requestedBy,
|
|
9993
|
+
[...input.currentRevisionIds],
|
|
9994
|
+
replayTrackedMarkerReceiptKey(input.orgId, input.runId),
|
|
9995
|
+
replayUnsafeMarkerReceiptKey(input.orgId, input.runId),
|
|
9996
|
+
],
|
|
9997
|
+
);
|
|
9998
|
+
const row = result.rows[0];
|
|
9999
|
+
if (!row?.found) return { resumed: false, reason: 'run_not_found' };
|
|
10000
|
+
if (row.task_id && row.epoch !== null) {
|
|
10001
|
+
return { resumed: true, epoch: Number(row.epoch), taskId: row.task_id };
|
|
10002
|
+
}
|
|
10003
|
+
// Every check passed but no task was spawned: report the last gate, as
|
|
10004
|
+
// before this predicate was shared.
|
|
10005
|
+
return {
|
|
10006
|
+
resumed: false,
|
|
10007
|
+
reason: postgresSchedulerRunResumeRefusal(row) ?? 'resume_window_expired',
|
|
10008
|
+
};
|
|
10009
|
+
}
|
|
10010
|
+
|
|
10011
|
+
/** Whether any attempt of the run was retired for post-code recovery. */
|
|
10012
|
+
export async function hasPostgresSchedulerPostCodeRecoveryDeferral(
|
|
10013
|
+
client: PostgresSchedulerQueryClient,
|
|
10014
|
+
input: { runId: string },
|
|
10015
|
+
options?: Pick<PostgresSchedulerOptions, 'schema'>,
|
|
10016
|
+
): Promise<boolean> {
|
|
10017
|
+
const result = await client.query<{ deferred: boolean }>(
|
|
10018
|
+
`SELECT EXISTS (
|
|
10019
|
+
SELECT 1 FROM ${tableName('attempts', options)} AS attempts
|
|
10020
|
+
WHERE attempts.run_id = $1
|
|
10021
|
+
AND attempts.error_json ->> 'kind' = 'platform_post_code_recovery'
|
|
10022
|
+
) AS deferred`,
|
|
10023
|
+
[input.runId],
|
|
10024
|
+
);
|
|
10025
|
+
return result.rows[0]?.deferred === true;
|
|
10026
|
+
}
|
|
10027
|
+
|
|
10028
|
+
export type PostgresSchedulerPostCodeRecoveryDeferral = {
|
|
10029
|
+
/** The attempt was retired and the run requeued for `delayMs`. */
|
|
10030
|
+
deferred: boolean;
|
|
10031
|
+
/** The budget is spent (count, horizon or no progress); fail the run. */
|
|
10032
|
+
exhausted: boolean;
|
|
10033
|
+
deferCount: number | null;
|
|
10034
|
+
delayMs: number | null;
|
|
10035
|
+
deadlineAtMs: number | null;
|
|
10036
|
+
historyRows: number | null;
|
|
10037
|
+
/**
|
|
10038
|
+
* False when the run lacks the runner's replay-tracked marker or carries
|
|
10039
|
+
* the replay-unsafe marker; such a run is never deferred.
|
|
10040
|
+
*/
|
|
10041
|
+
replaySafe: boolean;
|
|
10042
|
+
};
|
|
10043
|
+
|
|
10044
|
+
/** Public progress is committed with the fenced recovery decision, never
|
|
10045
|
+
* inferred from an error string or appended after the attempt becomes stale.
|
|
10046
|
+
* Both callers expose the same bounded activity and existing wire vocabulary.
|
|
10047
|
+
*/
|
|
10048
|
+
function platformRecoveryActivityEventSql(stateSql: string): string {
|
|
10049
|
+
return `jsonb_build_object(
|
|
10050
|
+
'type', ${RUN_EVENT_KIND_SQL_LITERAL.activityObserved},
|
|
10051
|
+
'runId', requeued_run.run_id,
|
|
10052
|
+
'source', 'worker',
|
|
10053
|
+
'occurredAt', $7::bigint,
|
|
10054
|
+
'resumeEpoch', coalesce(requeued_run.launch_json->'resumeEpoch', '0'::jsonb),
|
|
10055
|
+
'observation', jsonb_build_object(
|
|
10056
|
+
'activityId', ${escapeLiteral(PLATFORM_RECOVERY_ACTIVITY_ID)},
|
|
10057
|
+
'target', jsonb_build_object(
|
|
10058
|
+
'kind', 'capacity', 'pool', 'runner', 'label', 'Play execution'
|
|
10059
|
+
),
|
|
10060
|
+
'state', jsonb_build_object(
|
|
10061
|
+
'kind', 'retrying', 'reason', 'transport_error',
|
|
10062
|
+
'retryAt', (${stateSql})->'nextRetryAtMs',
|
|
10063
|
+
'attempt', $2::integer
|
|
10064
|
+
),
|
|
10065
|
+
'observedAt', $7::bigint
|
|
10066
|
+
)
|
|
10067
|
+
)`;
|
|
10068
|
+
}
|
|
10069
|
+
|
|
10070
|
+
/**
|
|
10071
|
+
* Defer a run whose attempt ended in a post-code platform failure.
|
|
10072
|
+
*
|
|
10073
|
+
* Its counters live under `recovery_json.postCode`, beside the pre-code
|
|
10074
|
+
* fields, and are merged rather than rebuilt. The progress rule counts the
|
|
10075
|
+
* run's completed history rows: an attempt that records nothing new raises
|
|
10076
|
+
* the unproductive streak, and reaching `maxUnproductiveAttempts` exhausts
|
|
10077
|
+
* the budget, so a Play that crashes the same way every time stops instead
|
|
10078
|
+
* of looping until the horizon. The caller computes the jittered delay so
|
|
10079
|
+
* the scheduler's actual DeferTask delay and the stored next-retry time are
|
|
10080
|
+
* the same number.
|
|
10081
|
+
*/
|
|
10082
|
+
export async function deferPostgresSchedulerAttemptForPostCodeRecovery(
|
|
10083
|
+
client: PostgresSchedulerQueryClient,
|
|
10084
|
+
input: {
|
|
10085
|
+
runId: string;
|
|
10086
|
+
orgId: string;
|
|
10087
|
+
attempt: number;
|
|
10088
|
+
leaseToken: string;
|
|
10089
|
+
reason: string;
|
|
10090
|
+
nowMs: number;
|
|
10091
|
+
maxDefers: number;
|
|
10092
|
+
horizonMs: number;
|
|
10093
|
+
maxUnproductiveAttempts: number;
|
|
10094
|
+
/**
|
|
10095
|
+
* Whether an attempt that recorded nothing counts toward the no-progress
|
|
10096
|
+
* rule. An outage stops progress through no fault of the Play.
|
|
10097
|
+
*/
|
|
10098
|
+
countsTowardProgress?: boolean;
|
|
10099
|
+
/** Delay for the defer that this call would record, by its defer count. */
|
|
10100
|
+
delayMsForDeferCount: (deferCount: number) => number;
|
|
10101
|
+
replayTrackedMarkerKey: string;
|
|
10102
|
+
replayUnsafeMarkerKey: string;
|
|
10103
|
+
},
|
|
10104
|
+
options?: Pick<PostgresSchedulerOptions, 'schema'>,
|
|
10105
|
+
): Promise<PostgresSchedulerPostCodeRecoveryDeferral> {
|
|
10106
|
+
const probe = await client.query<{
|
|
10107
|
+
defer_count: string | null;
|
|
10108
|
+
history_rows: string;
|
|
10109
|
+
replay_safe: boolean;
|
|
10110
|
+
}>(
|
|
10111
|
+
`
|
|
10112
|
+
SELECT coalesce((runs.recovery_json #>> '{postCode,deferCount}')::integer, 0) + 1
|
|
10113
|
+
AS defer_count,
|
|
10114
|
+
(
|
|
10115
|
+
EXISTS (
|
|
10116
|
+
SELECT 1 FROM ${tableName('receipts', options)} AS marker
|
|
10117
|
+
WHERE marker.org_id = $2 AND marker.k = $3
|
|
10118
|
+
AND marker.status = 'completed'
|
|
10119
|
+
)
|
|
10120
|
+
AND NOT EXISTS (
|
|
10121
|
+
SELECT 1 FROM ${tableName('receipts', options)} AS marker
|
|
10122
|
+
WHERE marker.org_id = $2 AND marker.k = $4
|
|
10123
|
+
)
|
|
10124
|
+
) AS replay_safe,
|
|
10125
|
+
(
|
|
10126
|
+
SELECT count(*)
|
|
10127
|
+
FROM ${tableName('receipts', options)} AS receipts
|
|
10128
|
+
WHERE receipts.org_id = $2
|
|
10129
|
+
AND receipts.run_id = $1
|
|
10130
|
+
AND receipts.status = 'completed'
|
|
10131
|
+
AND receipts.k LIKE 'ctx:' || $2 || ':freshness:operation:%'
|
|
10132
|
+
)::text AS history_rows
|
|
10133
|
+
FROM ${tableName('runs', options)} AS runs
|
|
10134
|
+
WHERE runs.run_id = $1
|
|
10135
|
+
`,
|
|
10136
|
+
[
|
|
10137
|
+
input.runId,
|
|
10138
|
+
input.orgId,
|
|
10139
|
+
input.replayTrackedMarkerKey,
|
|
10140
|
+
input.replayUnsafeMarkerKey,
|
|
10141
|
+
],
|
|
10142
|
+
);
|
|
10143
|
+
const probed = probe.rows[0];
|
|
10144
|
+
if (!probed || probed.replay_safe !== true) {
|
|
10145
|
+
return {
|
|
10146
|
+
deferred: false,
|
|
10147
|
+
exhausted: false,
|
|
10148
|
+
deferCount: null,
|
|
10149
|
+
delayMs: null,
|
|
10150
|
+
deadlineAtMs: null,
|
|
10151
|
+
historyRows: null,
|
|
10152
|
+
replaySafe: false,
|
|
10153
|
+
};
|
|
10154
|
+
}
|
|
10155
|
+
const nextDeferCount = Number(probed.defer_count ?? '1');
|
|
10156
|
+
const delayMs = input.delayMsForDeferCount(nextDeferCount);
|
|
10157
|
+
const historyRows = Number(probed.history_rows);
|
|
10158
|
+
const result = await client.query<{
|
|
10159
|
+
candidate: boolean;
|
|
10160
|
+
deferred: boolean;
|
|
10161
|
+
defer_count: string | null;
|
|
10162
|
+
deadline_at_ms: string | null;
|
|
10163
|
+
}>(
|
|
10164
|
+
`
|
|
10165
|
+
WITH ${runtimeSandboxCustodyLocksSql('run.run_id = $1', options)}, candidate AS (
|
|
10166
|
+
SELECT runs.run_id,
|
|
10167
|
+
coalesce(runs.recovery_json, '{}'::jsonb) AS recovery_json
|
|
10168
|
+
FROM custody_runs AS runs
|
|
10169
|
+
JOIN custody_attempts AS attempts
|
|
10170
|
+
ON attempts.run_id = runs.run_id
|
|
10171
|
+
WHERE attempts.run_id = $1
|
|
10172
|
+
AND attempts.attempt = $2
|
|
10173
|
+
AND attempts.lease_token = $3
|
|
10174
|
+
AND attempts.status IN ('claimed', 'running', 'waiting')
|
|
10175
|
+
AND runs.status IN ('queued', 'running', 'waiting')
|
|
10176
|
+
), computed AS (
|
|
10177
|
+
SELECT run_id,
|
|
10178
|
+
recovery_json,
|
|
10179
|
+
coalesce((recovery_json #>> '{postCode,deferCount}')::integer, 0) + 1
|
|
10180
|
+
AS defer_count,
|
|
10181
|
+
coalesce(
|
|
10182
|
+
(recovery_json #>> '{postCode,deadlineAtMs}')::bigint,
|
|
10183
|
+
$4::bigint
|
|
10184
|
+
) AS deadline_at_ms,
|
|
10185
|
+
CASE
|
|
10186
|
+
WHEN NOT $12::boolean
|
|
10187
|
+
THEN coalesce(
|
|
10188
|
+
(recovery_json #>> '{postCode,unproductiveAttempts}')::integer,
|
|
10189
|
+
0
|
|
10190
|
+
)
|
|
10191
|
+
WHEN coalesce((recovery_json #>> '{postCode,historyRowsAtLastDefer}')::bigint, 0)
|
|
10192
|
+
IS NOT DISTINCT FROM $10::bigint
|
|
10193
|
+
THEN coalesce(
|
|
10194
|
+
(recovery_json #>> '{postCode,unproductiveAttempts}')::integer,
|
|
10195
|
+
0
|
|
10196
|
+
) + 1
|
|
10197
|
+
ELSE 0
|
|
10198
|
+
END AS unproductive_attempts
|
|
10199
|
+
FROM candidate
|
|
10200
|
+
), deferred_attempt AS (
|
|
10201
|
+
UPDATE ${tableName('attempts', options)} AS attempts
|
|
10202
|
+
SET status = 'stale',
|
|
10203
|
+
lease_expires_at = NULL,
|
|
10204
|
+
heartbeat_at = now(),
|
|
10205
|
+
error_json = $5::jsonb,
|
|
10206
|
+
updated_at = now()
|
|
10207
|
+
FROM computed
|
|
10208
|
+
WHERE attempts.run_id = computed.run_id
|
|
10209
|
+
AND attempts.attempt = $2
|
|
10210
|
+
AND attempts.lease_token = $3
|
|
10211
|
+
AND computed.defer_count <= $6
|
|
10212
|
+
AND $7::bigint < computed.deadline_at_ms
|
|
10213
|
+
AND computed.unproductive_attempts < $11
|
|
10214
|
+
RETURNING attempts.run_id
|
|
10215
|
+
), post_code_state AS (
|
|
10216
|
+
SELECT run_id,
|
|
10217
|
+
jsonb_build_object(
|
|
10218
|
+
'kind', 'platform_post_code',
|
|
10219
|
+
'reason', $8::text,
|
|
10220
|
+
'deferCount', defer_count,
|
|
10221
|
+
'deadlineAtMs', deadline_at_ms,
|
|
10222
|
+
'historyRowsAtLastDefer', $10::bigint,
|
|
10223
|
+
'unproductiveAttempts', unproductive_attempts,
|
|
10224
|
+
'updatedAtMs', $7::bigint
|
|
10225
|
+
) AS state
|
|
10226
|
+
FROM computed
|
|
10227
|
+
), requeued_run AS (
|
|
10228
|
+
UPDATE ${tableName('runs', options)} AS runs
|
|
10229
|
+
SET status = 'queued',
|
|
10230
|
+
suspension_json = NULL,
|
|
10231
|
+
wait_deadline = NULL,
|
|
10232
|
+
recovery_json = computed.recovery_json || jsonb_build_object(
|
|
10233
|
+
'postCode',
|
|
10234
|
+
post_code_state.state || jsonb_build_object(
|
|
10235
|
+
'nextRetryAtMs', $7::bigint + $9::bigint
|
|
10236
|
+
)
|
|
10237
|
+
),
|
|
10238
|
+
updated_at = now()
|
|
10239
|
+
FROM computed
|
|
10240
|
+
JOIN post_code_state ON post_code_state.run_id = computed.run_id
|
|
10241
|
+
JOIN deferred_attempt ON deferred_attempt.run_id = computed.run_id
|
|
10242
|
+
WHERE runs.run_id = computed.run_id
|
|
10243
|
+
RETURNING runs.run_id, runs.launch_json, runs.recovery_json
|
|
10244
|
+
), recovery_activity AS (
|
|
10245
|
+
INSERT INTO ${tableName('outbox', options)} (
|
|
10246
|
+
event_id, run_id, event_type, payload_json, created_at
|
|
10247
|
+
)
|
|
10248
|
+
SELECT 'run-platform-recovery:' || requeued_run.run_id || ':' || $2::text,
|
|
10249
|
+
requeued_run.run_id,
|
|
10250
|
+
${RUN_SCHEDULER_OUTBOX_EVENT_TYPE_SQL_LITERAL.runEvents},
|
|
10251
|
+
jsonb_build_object('events', jsonb_build_array(
|
|
10252
|
+
${platformRecoveryActivityEventSql("requeued_run.recovery_json->'postCode'")}
|
|
10253
|
+
)),
|
|
10254
|
+
${causalOutboxCreatedAt('requeued_run.run_id', options)}
|
|
10255
|
+
FROM requeued_run
|
|
10256
|
+
ON CONFLICT (event_id) DO NOTHING
|
|
10257
|
+
RETURNING event_id
|
|
10258
|
+
), exhausted_run AS (
|
|
10259
|
+
UPDATE ${tableName('runs', options)} AS runs
|
|
10260
|
+
SET recovery_json = computed.recovery_json || jsonb_build_object(
|
|
10261
|
+
'postCode',
|
|
10262
|
+
post_code_state.state || jsonb_build_object(
|
|
10263
|
+
'nextRetryAtMs', NULL,
|
|
10264
|
+
'exhaustedAtMs', $7::bigint
|
|
10265
|
+
)
|
|
10266
|
+
),
|
|
10267
|
+
updated_at = now()
|
|
10268
|
+
FROM computed
|
|
10269
|
+
JOIN post_code_state ON post_code_state.run_id = computed.run_id
|
|
10270
|
+
WHERE runs.run_id = computed.run_id
|
|
10271
|
+
AND NOT EXISTS (SELECT 1 FROM deferred_attempt)
|
|
10272
|
+
RETURNING runs.run_id
|
|
10273
|
+
)
|
|
10274
|
+
SELECT EXISTS (SELECT 1 FROM candidate) AS candidate,
|
|
10275
|
+
EXISTS (SELECT 1 FROM requeued_run) AS deferred,
|
|
10276
|
+
(SELECT defer_count::text FROM computed LIMIT 1) AS defer_count,
|
|
10277
|
+
(SELECT deadline_at_ms::text FROM computed LIMIT 1) AS deadline_at_ms
|
|
10278
|
+
`,
|
|
10279
|
+
[
|
|
10280
|
+
input.runId,
|
|
10281
|
+
input.attempt,
|
|
10282
|
+
input.leaseToken,
|
|
10283
|
+
input.nowMs + input.horizonMs,
|
|
10284
|
+
stringifyPostgresJson({
|
|
10285
|
+
kind: 'platform_post_code_recovery',
|
|
10286
|
+
message: input.reason,
|
|
10287
|
+
}),
|
|
10288
|
+
input.maxDefers,
|
|
9184
10289
|
input.nowMs,
|
|
9185
|
-
|
|
9186
|
-
|
|
10290
|
+
input.reason,
|
|
10291
|
+
delayMs,
|
|
10292
|
+
historyRows,
|
|
10293
|
+
input.maxUnproductiveAttempts,
|
|
10294
|
+
input.countsTowardProgress !== false,
|
|
9187
10295
|
],
|
|
9188
10296
|
);
|
|
9189
|
-
|
|
9190
|
-
|
|
10297
|
+
const row = result.rows[0];
|
|
10298
|
+
if (!row?.candidate) {
|
|
10299
|
+
return {
|
|
10300
|
+
deferred: false,
|
|
10301
|
+
exhausted: false,
|
|
10302
|
+
deferCount: null,
|
|
10303
|
+
delayMs: null,
|
|
10304
|
+
deadlineAtMs: null,
|
|
10305
|
+
historyRows,
|
|
10306
|
+
replaySafe: true,
|
|
10307
|
+
};
|
|
9191
10308
|
}
|
|
9192
|
-
const
|
|
9193
|
-
|
|
9194
|
-
|
|
9195
|
-
|
|
9196
|
-
|
|
9197
|
-
|
|
9198
|
-
|
|
9199
|
-
|
|
9200
|
-
|
|
9201
|
-
|
|
9202
|
-
|
|
9203
|
-
client: PostgresSchedulerQueryClient,
|
|
9204
|
-
input: { dependency: string; probeToken: string },
|
|
9205
|
-
options?: Pick<PostgresSchedulerOptions, 'schema'>,
|
|
9206
|
-
): Promise<boolean> {
|
|
9207
|
-
const result = await client.query<{ dependency: string }>(
|
|
9208
|
-
`
|
|
9209
|
-
UPDATE ${tableName(POSTGRES_SCHEDULER_DEPENDENCY_CIRCUITS_TABLE, options)}
|
|
9210
|
-
SET state = 'closed',
|
|
9211
|
-
open_until_ms = 0,
|
|
9212
|
-
probe_until_ms = 0,
|
|
9213
|
-
probe_token = NULL,
|
|
9214
|
-
updated_at = now()
|
|
9215
|
-
WHERE dependency = $1
|
|
9216
|
-
AND state = 'half_open'
|
|
9217
|
-
AND probe_token = $2
|
|
9218
|
-
RETURNING dependency
|
|
9219
|
-
`,
|
|
9220
|
-
[input.dependency, input.probeToken],
|
|
9221
|
-
);
|
|
9222
|
-
return result.rows.length > 0;
|
|
9223
|
-
}
|
|
9224
|
-
|
|
9225
|
-
/** Operator-only recovery after a verified incident; keep an auditable reason. */
|
|
9226
|
-
export async function resetPostgresSchedulerRecoveryCircuit(
|
|
9227
|
-
client: PostgresSchedulerQueryClient,
|
|
9228
|
-
input: { dependency: string; reason: string },
|
|
9229
|
-
options?: Pick<PostgresSchedulerOptions, 'schema'>,
|
|
9230
|
-
): Promise<boolean> {
|
|
9231
|
-
const result = await client.query<{ dependency: string }>(
|
|
9232
|
-
`
|
|
9233
|
-
UPDATE ${tableName(POSTGRES_SCHEDULER_DEPENDENCY_CIRCUITS_TABLE, options)}
|
|
9234
|
-
SET state = 'closed',
|
|
9235
|
-
open_until_ms = 0,
|
|
9236
|
-
probe_until_ms = 0,
|
|
9237
|
-
probe_token = NULL,
|
|
9238
|
-
last_reason = $2,
|
|
9239
|
-
updated_at = now()
|
|
9240
|
-
WHERE dependency = $1
|
|
9241
|
-
RETURNING dependency
|
|
9242
|
-
`,
|
|
9243
|
-
[input.dependency, input.reason],
|
|
9244
|
-
);
|
|
9245
|
-
return result.rows.length > 0;
|
|
9246
|
-
}
|
|
9247
|
-
|
|
9248
|
-
export async function readPostgresSchedulerRecoveryCircuits(
|
|
9249
|
-
client: PostgresSchedulerQueryClient,
|
|
9250
|
-
options?: Pick<PostgresSchedulerOptions, 'schema'>,
|
|
9251
|
-
): Promise<PostgresSchedulerRecoveryCircuit[]> {
|
|
9252
|
-
const result = await client.query<{
|
|
9253
|
-
dependency: string;
|
|
9254
|
-
state: PostgresSchedulerRecoveryCircuit['state'];
|
|
9255
|
-
open_until_ms: string;
|
|
9256
|
-
probe_until_ms: string;
|
|
9257
|
-
last_reason: string | null;
|
|
9258
|
-
updated_at: Date;
|
|
9259
|
-
}>(
|
|
9260
|
-
`SELECT dependency, state, open_until_ms, probe_until_ms, last_reason, updated_at
|
|
9261
|
-
FROM ${tableName(POSTGRES_SCHEDULER_DEPENDENCY_CIRCUITS_TABLE, options)}
|
|
9262
|
-
ORDER BY dependency`,
|
|
9263
|
-
);
|
|
9264
|
-
return result.rows.map((row) => ({
|
|
9265
|
-
dependency: row.dependency,
|
|
9266
|
-
state: row.state,
|
|
9267
|
-
openUntilMs: Number(row.open_until_ms),
|
|
9268
|
-
probeUntilMs: Number(row.probe_until_ms),
|
|
9269
|
-
lastReason: row.last_reason,
|
|
9270
|
-
updatedAt: row.updated_at,
|
|
9271
|
-
}));
|
|
10309
|
+
const deferCount = row.defer_count ? Number(row.defer_count) : null;
|
|
10310
|
+
const deadlineAtMs = row.deadline_at_ms ? Number(row.deadline_at_ms) : null;
|
|
10311
|
+
return {
|
|
10312
|
+
deferred: row.deferred,
|
|
10313
|
+
exhausted: !row.deferred,
|
|
10314
|
+
deferCount: Number.isSafeInteger(deferCount) ? deferCount : null,
|
|
10315
|
+
delayMs: row.deferred ? delayMs : null,
|
|
10316
|
+
deadlineAtMs: Number.isSafeInteger(deadlineAtMs) ? deadlineAtMs : null,
|
|
10317
|
+
historyRows,
|
|
10318
|
+
replaySafe: true,
|
|
10319
|
+
};
|
|
9272
10320
|
}
|
|
9273
10321
|
|
|
9274
|
-
export type PostgresSchedulerRecoveryDeferral = {
|
|
9275
|
-
deferred: boolean;
|
|
9276
|
-
exhausted: boolean;
|
|
9277
|
-
deferCount: number | null;
|
|
9278
|
-
deadlineAtMs: number | null;
|
|
9279
|
-
};
|
|
9280
|
-
|
|
9281
|
-
/**
|
|
9282
|
-
* Park a proven pre-code platform failure without spending an Absurd engine
|
|
9283
|
-
* attempt. Unlike ordinary capacity parking, this records a finite recovery
|
|
9284
|
-
* horizon on the canonical run row. The task engine owns the wake; this store
|
|
9285
|
-
* owns the fact that another wake is still allowed.
|
|
9286
|
-
*/
|
|
9287
10322
|
export async function deferPostgresSchedulerAttemptForRecovery(
|
|
9288
10323
|
client: PostgresSchedulerQueryClient,
|
|
9289
10324
|
input: {
|
|
@@ -9392,7 +10427,9 @@ export async function deferPostgresSchedulerAttemptForRecovery(
|
|
|
9392
10427
|
SET status = 'queued',
|
|
9393
10428
|
suspension_json = NULL,
|
|
9394
10429
|
wait_deadline = NULL,
|
|
9395
|
-
|
|
10430
|
+
-- Post-code recovery state is a separate namespace; keep it.
|
|
10431
|
+
recovery_json =
|
|
10432
|
+
coalesce(runs.recovery_json, '{}'::jsonb) || jsonb_build_object(
|
|
9396
10433
|
'version', 1,
|
|
9397
10434
|
'kind', 'platform_pre_code',
|
|
9398
10435
|
'dependency', $8::text,
|
|
@@ -9410,7 +10447,7 @@ export async function deferPostgresSchedulerAttemptForRecovery(
|
|
|
9410
10447
|
FROM computed
|
|
9411
10448
|
JOIN deferred_attempt ON deferred_attempt.run_id = computed.run_id
|
|
9412
10449
|
WHERE runs.run_id = computed.run_id
|
|
9413
|
-
RETURNING runs.run_id
|
|
10450
|
+
RETURNING runs.run_id, runs.launch_json, runs.recovery_json
|
|
9414
10451
|
), no_code_work_counters AS (
|
|
9415
10452
|
INSERT INTO ${tableName('outbox', options)} (
|
|
9416
10453
|
event_id, run_id, event_type, payload_json, created_at
|
|
@@ -9419,14 +10456,19 @@ export async function deferPostgresSchedulerAttemptForRecovery(
|
|
|
9419
10456
|
$14::text,
|
|
9420
10457
|
requeued_run.run_id,
|
|
9421
10458
|
${RUN_SCHEDULER_OUTBOX_EVENT_TYPE_SQL_LITERAL.runEvents},
|
|
9422
|
-
$15::jsonb,
|
|
10459
|
+
jsonb_set($15::jsonb, '{events}',
|
|
10460
|
+
($15::jsonb->'events') || jsonb_build_array(
|
|
10461
|
+
${platformRecoveryActivityEventSql('requeued_run.recovery_json')}
|
|
10462
|
+
)
|
|
10463
|
+
),
|
|
9423
10464
|
${causalOutboxCreatedAt('requeued_run.run_id', options)}
|
|
9424
10465
|
FROM requeued_run
|
|
9425
10466
|
ON CONFLICT (event_id) DO NOTHING
|
|
9426
10467
|
RETURNING event_id
|
|
9427
10468
|
), exhausted_run AS (
|
|
9428
10469
|
UPDATE ${tableName('runs', options)} AS runs
|
|
9429
|
-
SET recovery_json =
|
|
10470
|
+
SET recovery_json =
|
|
10471
|
+
coalesce(runs.recovery_json, '{}'::jsonb) || jsonb_build_object(
|
|
9430
10472
|
'version', 1,
|
|
9431
10473
|
'kind', 'platform_pre_code',
|
|
9432
10474
|
'dependency', $8::text,
|
|
@@ -9566,6 +10608,7 @@ export async function handoffPostgresSchedulerAttemptContinuation(
|
|
|
9566
10608
|
$6,
|
|
9567
10609
|
continuation_run.run_id,
|
|
9568
10610
|
${RUN_EVENT_KIND_SQL_LITERAL.runResumed},
|
|
10611
|
+
${runResumeEpochPayloadSql('continuation_run.run_id', options)} ||
|
|
9569
10612
|
jsonb_strip_nulls(jsonb_build_object(
|
|
9570
10613
|
'kind', NULLIF(btrim(continuation_run.suspension_json ->> 'kind'), ''),
|
|
9571
10614
|
'eventKey',
|
|
@@ -9931,6 +10974,8 @@ const POSTGRES_SCHEDULER_ATTEMPT_AUTHORITY_FIELDS = [
|
|
|
9931
10974
|
'runtimeTokenOrigin',
|
|
9932
10975
|
'runtimeBackend',
|
|
9933
10976
|
'runtimeAuthority',
|
|
10977
|
+
// Minted onto the attempt token so the gateway scopes operation fences.
|
|
10978
|
+
'resumeEpoch',
|
|
9934
10979
|
// Optional Runtime gateway pin; null on unpinned launches. The executor-token
|
|
9935
10980
|
// issuer reads it to require the reader flag and add the pinned claims.
|
|
9936
10981
|
'runtimeGatewayProfileId',
|
|
@@ -11221,6 +12266,8 @@ export async function readPostgresSchedulerRuntimeResourcesForRun(
|
|
|
11221
12266
|
runId: string;
|
|
11222
12267
|
attempt?: number | null;
|
|
11223
12268
|
throughAttempt?: number;
|
|
12269
|
+
/** The first attempt of the epoch being billed (a resumed run). */
|
|
12270
|
+
fromAttempt?: number | null;
|
|
11224
12271
|
},
|
|
11225
12272
|
options?: Pick<PostgresSchedulerOptions, 'schema'>,
|
|
11226
12273
|
): Promise<unknown[]> {
|
|
@@ -11231,10 +12278,16 @@ export async function readPostgresSchedulerRuntimeResourcesForRun(
|
|
|
11231
12278
|
WHERE run_id = $1
|
|
11232
12279
|
AND ($2::integer IS NULL OR attempt = $2)
|
|
11233
12280
|
AND ($3::integer IS NULL OR attempt <= $3)
|
|
12281
|
+
AND ($4::integer IS NULL OR attempt >= $4)
|
|
11234
12282
|
AND resource_json IS NOT NULL
|
|
11235
12283
|
ORDER BY attempt DESC
|
|
11236
12284
|
`,
|
|
11237
|
-
[
|
|
12285
|
+
[
|
|
12286
|
+
input.runId,
|
|
12287
|
+
input.attempt ?? null,
|
|
12288
|
+
input.throughAttempt ?? null,
|
|
12289
|
+
input.fromAttempt ?? null,
|
|
12290
|
+
],
|
|
11238
12291
|
);
|
|
11239
12292
|
return resources.rows.flatMap((row) =>
|
|
11240
12293
|
Array.isArray(row.resource_json) ? row.resource_json : [row.resource_json],
|
|
@@ -11572,9 +12625,7 @@ export async function directCompletePostgresSchedulerRunnerTerminal(
|
|
|
11572
12625
|
input.result,
|
|
11573
12626
|
{ logMetadata: input.completionLogMetadata ?? 'attach' },
|
|
11574
12627
|
);
|
|
11575
|
-
const resultSummary =
|
|
11576
|
-
(input.result as { rowOutcomes?: unknown }).rowOutcomes,
|
|
11577
|
-
);
|
|
12628
|
+
const resultSummary = completedResultSummary(input.result);
|
|
11578
12629
|
const terminalResult = assertTerminalRunResultWithinLimit(terminalOutput);
|
|
11579
12630
|
const ledgerTerminalResult = terminalRunResultForLedger(terminalResult, {
|
|
11580
12631
|
content: 'full',
|
|
@@ -11847,7 +12898,7 @@ export async function directCompletePostgresSchedulerRunnerTerminal(
|
|
|
11847
12898
|
event_id, run_id, event_type, payload_json, created_at
|
|
11848
12899
|
)
|
|
11849
12900
|
SELECT
|
|
11850
|
-
'
|
|
12901
|
+
${runEndingEventIdSql('run_terminal.run_id', options)},
|
|
11851
12902
|
run_terminal.run_id,
|
|
11852
12903
|
${RUN_EVENT_KIND_SQL_LITERAL.runCompleted},
|
|
11853
12904
|
jsonb_build_object(
|
|
@@ -12631,6 +13682,91 @@ export async function blockPostgresSchedulerComputeBillingJob(
|
|
|
12631
13682
|
);
|
|
12632
13683
|
}
|
|
12633
13684
|
|
|
13685
|
+
/** Read one obligation under its authenticated workspace, without changing it. */
|
|
13686
|
+
export async function readPostgresSchedulerComputeBillingRecovery(
|
|
13687
|
+
client: PostgresSchedulerQueryClient,
|
|
13688
|
+
input: { runId: string; orgId: string },
|
|
13689
|
+
options?: Pick<PostgresSchedulerOptions, 'schema'>,
|
|
13690
|
+
): Promise<{ status: string; blocked: boolean; runStatus: string } | null> {
|
|
13691
|
+
const result = await client.query<{
|
|
13692
|
+
status: string;
|
|
13693
|
+
blocked: boolean;
|
|
13694
|
+
run_status: string;
|
|
13695
|
+
}>(
|
|
13696
|
+
`SELECT job.status, job.blocked_at IS NOT NULL AS blocked,
|
|
13697
|
+
run.status AS run_status
|
|
13698
|
+
FROM ${tableName('compute_billing_jobs_v2', options)} AS job
|
|
13699
|
+
JOIN ${tableName('runs', options)} AS run ON run.run_id = job.run_id
|
|
13700
|
+
WHERE job.run_id = $1 AND run.org_id = $2`,
|
|
13701
|
+
[input.runId, input.orgId],
|
|
13702
|
+
);
|
|
13703
|
+
const row = result.rows[0];
|
|
13704
|
+
return row
|
|
13705
|
+
? { status: row.status, blocked: row.blocked, runStatus: row.run_status }
|
|
13706
|
+
: null;
|
|
13707
|
+
}
|
|
13708
|
+
|
|
13709
|
+
/**
|
|
13710
|
+
* Explicit operator reconciliation takes its own settlement lease atomically.
|
|
13711
|
+
* A retained worker must not win a pending-row race and use the old issuer.
|
|
13712
|
+
* No Play is admitted and no financial obligation is deleted or marked settled.
|
|
13713
|
+
*/
|
|
13714
|
+
export async function claimPostgresSchedulerComputeBillingReconciliation(
|
|
13715
|
+
client: PostgresSchedulerQueryClient,
|
|
13716
|
+
input: { runId: string; orgId: string; reason: string; leaseOwner: string },
|
|
13717
|
+
options?: Pick<PostgresSchedulerOptions, 'schema'>,
|
|
13718
|
+
): Promise<PostgresSchedulerComputeBillingJob | null> {
|
|
13719
|
+
if (!input.reason.trim() || !input.leaseOwner.trim()) {
|
|
13720
|
+
throw new Error(
|
|
13721
|
+
'Compute reconciliation requires an operator reason and lease owner.',
|
|
13722
|
+
);
|
|
13723
|
+
}
|
|
13724
|
+
const result = await client.query<{
|
|
13725
|
+
run_id: string;
|
|
13726
|
+
attempt_count: number;
|
|
13727
|
+
failure_count: number;
|
|
13728
|
+
run_status: string;
|
|
13729
|
+
}>(
|
|
13730
|
+
`WITH approved AS (
|
|
13731
|
+
UPDATE ${tableName('compute_billing_jobs_v2', options)} AS job
|
|
13732
|
+
SET status = 'settling',
|
|
13733
|
+
attempt_count = job.attempt_count + 1,
|
|
13734
|
+
blocked_at = NULL, block_reason = NULL,
|
|
13735
|
+
session_bootstrap_approved_at = clock_timestamp(),
|
|
13736
|
+
session_bootstrap_approval_reason = left($3, 4000),
|
|
13737
|
+
session_bootstrap_completed_at = NULL,
|
|
13738
|
+
session_bootstrap_retry_at = NULL,
|
|
13739
|
+
available_at = 'infinity'::timestamptz,
|
|
13740
|
+
lease_owner = $4,
|
|
13741
|
+
lease_expires_at = clock_timestamp() + interval '5 minutes',
|
|
13742
|
+
updated_at = clock_timestamp()
|
|
13743
|
+
WHERE job.run_id = $1 AND job.status = 'pending'
|
|
13744
|
+
AND job.blocked_at IS NOT NULL AND job.lease_owner IS NULL
|
|
13745
|
+
AND EXISTS (
|
|
13746
|
+
SELECT 1 FROM ${tableName('runs', options)} AS run
|
|
13747
|
+
WHERE run.run_id = job.run_id AND run.org_id = $2
|
|
13748
|
+
AND run.status IN ('completed', 'failed', 'cancelled')
|
|
13749
|
+
)
|
|
13750
|
+
RETURNING job.run_id, job.attempt_count, job.failure_count
|
|
13751
|
+
)
|
|
13752
|
+
SELECT approved.*, run.status AS run_status
|
|
13753
|
+
FROM approved JOIN ${tableName('runs', options)} AS run
|
|
13754
|
+
ON run.run_id = approved.run_id`,
|
|
13755
|
+
[input.runId, input.orgId, input.reason, input.leaseOwner],
|
|
13756
|
+
);
|
|
13757
|
+
const row = result.rows[0];
|
|
13758
|
+
return row
|
|
13759
|
+
? {
|
|
13760
|
+
status: ComputeBillingJobStatus.Settling,
|
|
13761
|
+
runId: row.run_id,
|
|
13762
|
+
attemptCount: row.attempt_count,
|
|
13763
|
+
failureCount: row.failure_count,
|
|
13764
|
+
success: row.run_status === 'completed',
|
|
13765
|
+
bootstrapSessionPending: true,
|
|
13766
|
+
}
|
|
13767
|
+
: null;
|
|
13768
|
+
}
|
|
13769
|
+
|
|
12634
13770
|
/**
|
|
12635
13771
|
* Explicit operator reconciliation approves the missing lifecycle bootstrap
|
|
12636
13772
|
* for one quarantined obligation and re-enables it. The approval is durable
|
|
@@ -13056,6 +14192,51 @@ export async function hasPendingPostgresSchedulerSandboxCleanupForRun(
|
|
|
13056
14192
|
return pending.rows[0]?.pending ?? true;
|
|
13057
14193
|
}
|
|
13058
14194
|
|
|
14195
|
+
/**
|
|
14196
|
+
* Whether any attempt up to `throughAttempt` still owns an unconfirmed sandbox:
|
|
14197
|
+
* a cleanup job not yet `deleted` (including blocked ones), a reserved create,
|
|
14198
|
+
* or a pending ambiguous Modal create. Post-code recovery starts no new
|
|
14199
|
+
* sandbox, and releases no older attempt's claims, until this is false.
|
|
14200
|
+
*/
|
|
14201
|
+
export async function hasPendingPostgresSchedulerSandboxDeletionThroughAttempt(
|
|
14202
|
+
client: PostgresSchedulerQueryClient,
|
|
14203
|
+
input: { runId: string; throughAttempt: number },
|
|
14204
|
+
options?: Pick<PostgresSchedulerOptions, 'schema'>,
|
|
14205
|
+
): Promise<boolean> {
|
|
14206
|
+
const pending = await client.query<{ pending: boolean }>(
|
|
14207
|
+
`
|
|
14208
|
+
SELECT EXISTS (
|
|
14209
|
+
SELECT 1 FROM ${tableName('sandbox_cleanup_jobs_v2', options)}
|
|
14210
|
+
WHERE run_id = $1 AND attempt <= $2 AND status <> 'deleted'
|
|
14211
|
+
) OR EXISTS (
|
|
14212
|
+
SELECT 1 FROM ${tableName('runtime_sandbox_operations', options)}
|
|
14213
|
+
WHERE run_id = $1 AND attempt <= $2 AND state = 'reserved'
|
|
14214
|
+
) OR EXISTS (
|
|
14215
|
+
SELECT 1 FROM ${tableName('ambiguous_modal_creates', options)}
|
|
14216
|
+
WHERE run_id = $1 AND attempt <= $2 AND status = 'pending'
|
|
14217
|
+
) AS pending
|
|
14218
|
+
`,
|
|
14219
|
+
[input.runId, input.throughAttempt],
|
|
14220
|
+
);
|
|
14221
|
+
// A missing answer is not proof of deletion.
|
|
14222
|
+
return pending.rows[0]?.pending ?? true;
|
|
14223
|
+
}
|
|
14224
|
+
|
|
14225
|
+
/** Whether the run is inside an open (not exhausted) post-code recovery. */
|
|
14226
|
+
export async function readPostgresSchedulerPostCodeRecoveryOpen(
|
|
14227
|
+
client: PostgresSchedulerQueryClient,
|
|
14228
|
+
input: { runId: string },
|
|
14229
|
+
options?: Pick<PostgresSchedulerOptions, 'schema'>,
|
|
14230
|
+
): Promise<boolean> {
|
|
14231
|
+
const result = await client.query<{ open: boolean }>(
|
|
14232
|
+
`SELECT coalesce((recovery_json #>> '{postCode,deferCount}')::integer, 0) > 0
|
|
14233
|
+
AND (recovery_json #>> '{postCode,exhaustedAtMs}') IS NULL AS open
|
|
14234
|
+
FROM ${tableName('runs', options)} WHERE run_id = $1`,
|
|
14235
|
+
[input.runId],
|
|
14236
|
+
);
|
|
14237
|
+
return result.rows[0]?.open === true;
|
|
14238
|
+
}
|
|
14239
|
+
|
|
13059
14240
|
/** Exact-resource join; completion never substitutes for the initiating attempt fence. */
|
|
13060
14241
|
export async function readPostgresSchedulerSandboxRetirement(
|
|
13061
14242
|
client: PostgresSchedulerQueryClient,
|
|
@@ -15142,6 +16323,7 @@ export async function completePostgresSchedulerAttempt(
|
|
|
15142
16323
|
leaseToken: string;
|
|
15143
16324
|
output: unknown;
|
|
15144
16325
|
rowOutcomes?: unknown;
|
|
16326
|
+
prebuiltResultQuality?: unknown;
|
|
15145
16327
|
runtimeTiming?: PlayRunnerRuntimeTiming | null;
|
|
15146
16328
|
terminalLogLines?: readonly string[] | null;
|
|
15147
16329
|
terminalLogContexts?: readonly (PlayLogContext | null)[] | null;
|
|
@@ -15162,7 +16344,7 @@ export async function completePostgresSchedulerAttempt(
|
|
|
15162
16344
|
const ledgerTerminalResult = terminalRunResultForLedger(terminalResult, {
|
|
15163
16345
|
content: 'full',
|
|
15164
16346
|
});
|
|
15165
|
-
const resultSummary =
|
|
16347
|
+
const resultSummary = completedResultSummary(input);
|
|
15166
16348
|
if (
|
|
15167
16349
|
input.terminalLogContexts != null &&
|
|
15168
16350
|
input.terminalLogContexts.length !== (input.terminalLogLines ?? []).length
|
|
@@ -15370,7 +16552,7 @@ export async function completePostgresSchedulerAttempt(
|
|
|
15370
16552
|
event_id, run_id, event_type, payload_json, created_at
|
|
15371
16553
|
)
|
|
15372
16554
|
SELECT
|
|
15373
|
-
'
|
|
16555
|
+
${runEndingEventIdSql('run_terminal.run_id', options)},
|
|
15374
16556
|
run_terminal.run_id,
|
|
15375
16557
|
${RUN_EVENT_KIND_SQL_LITERAL.runCompleted},
|
|
15376
16558
|
jsonb_build_object(
|
|
@@ -15783,7 +16965,7 @@ export async function failPostgresSchedulerAttempt(
|
|
|
15783
16965
|
event_id, run_id, event_type, payload_json, created_at
|
|
15784
16966
|
)
|
|
15785
16967
|
SELECT
|
|
15786
|
-
'
|
|
16968
|
+
${runEndingEventIdSql('run_terminal.run_id', options)},
|
|
15787
16969
|
run_terminal.run_id,
|
|
15788
16970
|
${RUN_EVENT_KIND_SQL_LITERAL.runFailed},
|
|
15789
16971
|
jsonb_build_object(
|
|
@@ -16129,7 +17311,7 @@ export async function cancelPostgresSchedulerRun(
|
|
|
16129
17311
|
next_attempt_at, lease_owner, lease_expires_at
|
|
16130
17312
|
)
|
|
16131
17313
|
SELECT
|
|
16132
|
-
'
|
|
17314
|
+
${runEndingEventIdSql('cancelled_run.run_id', options)},
|
|
16133
17315
|
cancelled_run.run_id,
|
|
16134
17316
|
${RUN_EVENT_KIND_SQL_LITERAL.runCancelled},
|
|
16135
17317
|
jsonb_build_object('error', $5::text),
|
|
@@ -16388,7 +17570,7 @@ export async function finalizePostgresSchedulerComputeBilling(
|
|
|
16388
17570
|
});
|
|
16389
17571
|
for (const item of items) {
|
|
16390
17572
|
await recordComputeBillingItemViaAppRuntime(runtimeApi, {
|
|
16391
|
-
sessionId: launch.runId,
|
|
17573
|
+
sessionId: computeBillingSessionId(launch.runId, launch.resumeEpoch),
|
|
16392
17574
|
orgId: launch.orgId,
|
|
16393
17575
|
...(launch.userId ? { userId: launch.userId } : {}),
|
|
16394
17576
|
operation: 'workflow_run',
|
|
@@ -16396,7 +17578,7 @@ export async function finalizePostgresSchedulerComputeBilling(
|
|
|
16396
17578
|
});
|
|
16397
17579
|
}
|
|
16398
17580
|
await finalizeComputeBillingSessionViaAppRuntime(runtimeApi, {
|
|
16399
|
-
sessionId: launch.runId,
|
|
17581
|
+
sessionId: computeBillingSessionId(launch.runId, launch.resumeEpoch),
|
|
16400
17582
|
orgId: launch.orgId,
|
|
16401
17583
|
...(launch.userId ? { userId: launch.userId } : {}),
|
|
16402
17584
|
operation: 'workflow_run',
|
|
@@ -16483,6 +17665,16 @@ function finiteRunnerNumber(value: unknown): number | null {
|
|
|
16483
17665
|
: null;
|
|
16484
17666
|
}
|
|
16485
17667
|
|
|
17668
|
+
function completedResultSummary(value: unknown) {
|
|
17669
|
+
const result = value as {
|
|
17670
|
+
rowOutcomes?: unknown;
|
|
17671
|
+
prebuiltResultQuality?: unknown;
|
|
17672
|
+
} | null;
|
|
17673
|
+
const outcomes = terminalRowOutcomesSummary(result?.rowOutcomes);
|
|
17674
|
+
const quality = readPrebuiltResultQuality(result?.prebuiltResultQuality);
|
|
17675
|
+
return quality ? { ...outcomes, prebuiltResultQuality: quality } : outcomes;
|
|
17676
|
+
}
|
|
17677
|
+
|
|
16486
17678
|
function terminalRowOutcomesSummary(value: unknown): {
|
|
16487
17679
|
rowOutcomes: {
|
|
16488
17680
|
completedRows?: number;
|
|
@@ -17039,6 +18231,9 @@ export async function executePostgresSchedulerClaim(
|
|
|
17039
18231
|
output: terminalOutput,
|
|
17040
18232
|
terminalRuntimeStats: (output as { stats?: unknown } | null)?.stats,
|
|
17041
18233
|
rowOutcomes: (output as { rowOutcomes?: unknown } | null)?.rowOutcomes,
|
|
18234
|
+
prebuiltResultQuality: (
|
|
18235
|
+
output as { prebuiltResultQuality?: unknown } | null
|
|
18236
|
+
)?.prebuiltResultQuality,
|
|
17042
18237
|
runtimeTiming: extractRunnerRuntimeTiming(output),
|
|
17043
18238
|
terminalLogLines: terminalLogProjection.lines,
|
|
17044
18239
|
terminalLogContexts: terminalLogProjection.lineContexts,
|
|
@@ -17333,9 +18528,18 @@ export function buildPostgresSchedulerRunnerContext(
|
|
|
17333
18528
|
playId: launch.playId,
|
|
17334
18529
|
runId: launch.runId,
|
|
17335
18530
|
replayedFromRunId: launch.replayedFromRunId ?? null,
|
|
18531
|
+
...(launch.runScopedKeys === true ? { runScopedKeys: true } : {}),
|
|
18532
|
+
...(typeof launch.resumeEpoch === 'number' && launch.resumeEpoch > 0
|
|
18533
|
+
? { resumeEpoch: launch.resumeEpoch }
|
|
18534
|
+
: {}),
|
|
17336
18535
|
rootRunId,
|
|
17337
18536
|
runAttempt,
|
|
17338
18537
|
playName: launch.playName,
|
|
18538
|
+
...(launch.definitionScope === 'system' &&
|
|
18539
|
+
launch.playReference?.startsWith('prebuilt/') &&
|
|
18540
|
+
rootRunId === launch.runId
|
|
18541
|
+
? { prebuiltQualityReference: launch.playReference }
|
|
18542
|
+
: {}),
|
|
17339
18543
|
userEmail: launch.userEmail,
|
|
17340
18544
|
runActor: playRunActor(launch.runtimeAuthority),
|
|
17341
18545
|
force: launch.force === true,
|
|
@@ -18981,6 +20185,42 @@ export async function releasePostgresSchedulerReceiptsForAttempt(
|
|
|
18981
20185
|
return { released: releasedKeys.length, releasedKeys };
|
|
18982
20186
|
}
|
|
18983
20187
|
|
|
20188
|
+
/**
|
|
20189
|
+
* Release every receipt claim the run's attempts up to `throughAttempt`
|
|
20190
|
+
* still hold. Only for a run whose runner the provider proved gone: its
|
|
20191
|
+
* claims would otherwise block the retry until their leases expire. A fenced
|
|
20192
|
+
* call still in flight on the gateway stays blocked by the gateway's own
|
|
20193
|
+
* fence, never dispatched twice.
|
|
20194
|
+
*/
|
|
20195
|
+
export async function releasePostgresSchedulerReceiptsThroughAttempt(
|
|
20196
|
+
client: PostgresSchedulerQueryClient,
|
|
20197
|
+
input: { runId: string; throughAttempt: number },
|
|
20198
|
+
options: PostgresSchedulerReceiptOptions,
|
|
20199
|
+
): Promise<{ released: number }> {
|
|
20200
|
+
const throughAttempt = normalizePostgresSchedulerReceiptRunAttempt(
|
|
20201
|
+
input.throughAttempt,
|
|
20202
|
+
);
|
|
20203
|
+
const released = await client.query<{ k: string }>(
|
|
20204
|
+
`
|
|
20205
|
+
UPDATE ${tableName('receipts', options)}
|
|
20206
|
+
SET ${RELEASE_RECEIPT_TO_PENDING_SET_CLAUSE}
|
|
20207
|
+
WHERE org_id = $1
|
|
20208
|
+
AND run_id = $2
|
|
20209
|
+
AND status = ANY($4::text[])
|
|
20210
|
+
AND COALESCE(lease_owner_run_id, run_id) = $2
|
|
20211
|
+
AND COALESCE(lease_owner_attempt, 0) <= $3::integer
|
|
20212
|
+
RETURNING k
|
|
20213
|
+
`,
|
|
20214
|
+
[
|
|
20215
|
+
receiptOrgId(options),
|
|
20216
|
+
input.runId,
|
|
20217
|
+
throughAttempt,
|
|
20218
|
+
schedulerWorkReceiptFromStatuses('release_attempt'),
|
|
20219
|
+
],
|
|
20220
|
+
);
|
|
20221
|
+
return { released: released.rows.length };
|
|
20222
|
+
}
|
|
20223
|
+
|
|
18984
20224
|
async function markPostgresSchedulerReceiptsStatus(
|
|
18985
20225
|
client: PostgresSchedulerQueryClient,
|
|
18986
20226
|
input:
|
|
@@ -19971,7 +21211,7 @@ async function appendRunLedgerOutboxFact(
|
|
|
19971
21211
|
), recorded AS (
|
|
19972
21212
|
INSERT INTO ${tableName('outbox', options)}
|
|
19973
21213
|
(event_id, run_id, event_type, payload_json, created_at)
|
|
19974
|
-
SELECT $3, run_id, $5, $4::jsonb,
|
|
21214
|
+
SELECT $3, run_id, $5, $4::jsonb || ${runResumeEpochPayloadSql('admitted.run_id', options)},
|
|
19975
21215
|
${causalOutboxCreatedAt('admitted.run_id', options)}
|
|
19976
21216
|
FROM admitted
|
|
19977
21217
|
ON CONFLICT (event_id) DO NOTHING
|
|
@@ -20066,7 +21306,7 @@ async function appendRunLedgerLiveProgressFact(
|
|
|
20066
21306
|
), recorded AS (
|
|
20067
21307
|
INSERT INTO ${tableName('outbox', options)}
|
|
20068
21308
|
(event_id, run_id, event_type, payload_json, created_at)
|
|
20069
|
-
SELECT $2, run_id, $4, $3::jsonb,
|
|
21309
|
+
SELECT $2, run_id, $4, $3::jsonb || ${runResumeEpochPayloadSql('fenced.run_id', options)},
|
|
20070
21310
|
${causalOutboxCreatedAt('fenced.run_id', options)}
|
|
20071
21311
|
FROM fenced
|
|
20072
21312
|
ON CONFLICT (event_id) DO NOTHING
|
|
@@ -20195,7 +21435,7 @@ export async function readPostgresSchedulerTerminalArrayInputIntent(
|
|
|
20195
21435
|
client: PostgresSchedulerQueryClient,
|
|
20196
21436
|
input: { orgId: string; runId: string },
|
|
20197
21437
|
options?: Pick<PostgresSchedulerOptions, 'schema'>,
|
|
20198
|
-
): Promise<{ playName: string | null; started: boolean }> {
|
|
21438
|
+
): Promise<{ playName: string | null; started: boolean; status?: string }> {
|
|
20199
21439
|
return readTerminalArrayInputIntentForScope(client, input, options);
|
|
20200
21440
|
}
|
|
20201
21441
|
|
|
@@ -20208,7 +21448,7 @@ export async function assertPostgresRunLedgerDeliveryAndReadTerminalArrayInputIn
|
|
|
20208
21448
|
client: PostgresSchedulerQueryClient,
|
|
20209
21449
|
input: Parameters<typeof assertPostgresRunLedgerDelivery>[1],
|
|
20210
21450
|
options?: Pick<PostgresSchedulerOptions, 'schema'>,
|
|
20211
|
-
): Promise<{ playName: string | null; started: boolean }> {
|
|
21451
|
+
): Promise<{ playName: string | null; started: boolean; status?: string }> {
|
|
20212
21452
|
const markerPresent = await provePostgresRunLedgerDelivery(
|
|
20213
21453
|
client,
|
|
20214
21454
|
input,
|
|
@@ -20225,7 +21465,7 @@ async function readTerminalArrayInputIntentForScope(
|
|
|
20225
21465
|
client: PostgresSchedulerQueryClient,
|
|
20226
21466
|
input: { orgId?: string; runId: string },
|
|
20227
21467
|
options?: Pick<PostgresSchedulerOptions, 'schema'>,
|
|
20228
|
-
): Promise<{ playName: string | null; started: boolean }> {
|
|
21468
|
+
): Promise<{ playName: string | null; started: boolean; status?: string }> {
|
|
20229
21469
|
// Historical scheduler schemas have no marker. Inspect only a terminal
|
|
20230
21470
|
// delivery, then read the scalar column directly when it exists. Converting
|
|
20231
21471
|
// the whole wide run tuple to JSON for every outbox fact would copy launch,
|
|
@@ -20249,12 +21489,13 @@ async function readTerminalArrayInputIntentRow(
|
|
|
20249
21489
|
client: PostgresSchedulerQueryClient,
|
|
20250
21490
|
input: { orgId?: string; runId: string },
|
|
20251
21491
|
options?: Pick<PostgresSchedulerOptions, 'schema'>,
|
|
20252
|
-
): Promise<{ playName: string | null; started: boolean }> {
|
|
21492
|
+
): Promise<{ playName: string | null; started: boolean; status?: string }> {
|
|
20253
21493
|
const run = await client.query<{
|
|
20254
21494
|
array_input_started: boolean;
|
|
20255
21495
|
play_name: string;
|
|
21496
|
+
status: string;
|
|
20256
21497
|
}>(
|
|
20257
|
-
`SELECT array_input_started, play_name FROM ${tableName('runs', options)}
|
|
21498
|
+
`SELECT array_input_started, play_name, status FROM ${tableName('runs', options)}
|
|
20258
21499
|
WHERE run_id = $1 ${input.orgId === undefined ? '' : 'AND org_id = $2'}
|
|
20259
21500
|
AND status IN ('completed', 'failed', 'cancelled')`,
|
|
20260
21501
|
input.orgId === undefined ? [input.runId] : [input.runId, input.orgId],
|
|
@@ -20262,6 +21503,7 @@ async function readTerminalArrayInputIntentRow(
|
|
|
20262
21503
|
return {
|
|
20263
21504
|
playName: run.rows[0]?.play_name ?? null,
|
|
20264
21505
|
started: run.rows[0]?.array_input_started === true,
|
|
21506
|
+
...(run.rows[0]?.status ? { status: run.rows[0].status } : {}),
|
|
20265
21507
|
};
|
|
20266
21508
|
}
|
|
20267
21509
|
|
|
@@ -20290,6 +21532,7 @@ async function provePostgresRunLedgerDelivery(
|
|
|
20290
21532
|
readArrayInputMarker = false,
|
|
20291
21533
|
): Promise<boolean> {
|
|
20292
21534
|
const result = await client.query<{
|
|
21535
|
+
event_id: string;
|
|
20293
21536
|
delivery_key: string;
|
|
20294
21537
|
event_type: string;
|
|
20295
21538
|
delivery_batch_started_at: string | null;
|
|
@@ -20302,7 +21545,8 @@ async function provePostgresRunLedgerDelivery(
|
|
|
20302
21545
|
array_input_marker_present?: boolean;
|
|
20303
21546
|
}>(
|
|
20304
21547
|
`
|
|
20305
|
-
SELECT outbox.
|
|
21548
|
+
SELECT outbox.event_id,
|
|
21549
|
+
outbox.delivery_key,
|
|
20306
21550
|
outbox.event_type,
|
|
20307
21551
|
-- Row JSON keeps this optional on historical scheduler schemas.
|
|
20308
21552
|
to_jsonb(outbox)->>'delivery_batch_started_at' AS delivery_batch_started_at,
|
|
@@ -20435,7 +21679,9 @@ async function provePostgresRunLedgerDelivery(
|
|
|
20435
21679
|
for (const prefixRow of prefix) {
|
|
20436
21680
|
prefixEvents.push(
|
|
20437
21681
|
...buildRunLedgerEventsFromPostgresSchedulerOutbox({
|
|
20438
|
-
|
|
21682
|
+
// The event id, not the delivery key, carries a resumed run's
|
|
21683
|
+
// epoch, so the expected projection stamps it as the sender did.
|
|
21684
|
+
eventId: prefixRow.event_id,
|
|
20439
21685
|
runId: input.runId,
|
|
20440
21686
|
eventType: prefixRow.event_type,
|
|
20441
21687
|
payload: prefixRow.payload_json,
|
|
@@ -20691,7 +21937,7 @@ function runLedgerTerminalPendingSql(
|
|
|
20691
21937
|
): string {
|
|
20692
21938
|
return `EXISTS (
|
|
20693
21939
|
SELECT 1 FROM ${tableName('outbox', options)} AS terminal_event
|
|
20694
|
-
WHERE terminal_event.event_id =
|
|
21940
|
+
WHERE terminal_event.event_id = ${runEndingEventIdSql(`${alias}.run_id`, options)}
|
|
20695
21941
|
AND terminal_event.run_id = ${alias}.run_id
|
|
20696
21942
|
AND terminal_event.event_type IN (${RUN_EVENT_KIND_SQL_LITERAL.runCompleted}, ${RUN_EVENT_KIND_SQL_LITERAL.runFailed}, ${RUN_EVENT_KIND_SQL_LITERAL.runCancelled})
|
|
20697
21943
|
AND terminal_event.delivered_at IS NULL
|
|
@@ -22933,8 +24179,31 @@ function normalizeOutboxIngressPreview(
|
|
|
22933
24179
|
return { ...event, progress: { ...progress, nodeIo } };
|
|
22934
24180
|
}
|
|
22935
24181
|
|
|
24182
|
+
/**
|
|
24183
|
+
* Ledger events for one outbox row. A resumed run's endings and its
|
|
24184
|
+
* `run.resumed` carry the run's resume epoch, so the ledger orders them after
|
|
24185
|
+
* the earlier epoch instead of treating them as duplicates or stale.
|
|
24186
|
+
*/
|
|
22936
24187
|
export function buildRunLedgerEventsFromPostgresSchedulerOutbox(
|
|
22937
24188
|
event: PostgresSchedulerOutboxEvent,
|
|
24189
|
+
): PlayRunLedgerIngressEvent[] {
|
|
24190
|
+
const events =
|
|
24191
|
+
buildUnstampedRunLedgerEventsFromPostgresSchedulerOutbox(event);
|
|
24192
|
+
const epoch =
|
|
24193
|
+
event.eventType === RUN_SCHEDULER_OUTBOX_EVENT_TYPE.runResumed
|
|
24194
|
+
? normalizeResumeEpoch(numberPayloadField(event.payload, 'epoch'))
|
|
24195
|
+
: (runEndingEventEpoch(event.eventId, event.runId) ??
|
|
24196
|
+
normalizeResumeEpoch(numberPayloadField(event.payload, 'epoch')));
|
|
24197
|
+
return events.map((ledgerEvent) =>
|
|
24198
|
+
ledgerEvent.type !== RUN_EVENT_KIND.logAppended &&
|
|
24199
|
+
ledgerEvent.type !== RUN_EVENT_KIND.workCounters
|
|
24200
|
+
? { ...ledgerEvent, resumeEpoch: ledgerEvent.resumeEpoch ?? epoch }
|
|
24201
|
+
: ledgerEvent,
|
|
24202
|
+
);
|
|
24203
|
+
}
|
|
24204
|
+
|
|
24205
|
+
function buildUnstampedRunLedgerEventsFromPostgresSchedulerOutbox(
|
|
24206
|
+
event: PostgresSchedulerOutboxEvent,
|
|
22938
24207
|
): PlayRunLedgerIngressEvent[] {
|
|
22939
24208
|
if (
|
|
22940
24209
|
payloadField(event.payload, RUNTIME_EVENT_DEFERRED_PROJECTION_FIELD) ===
|
|
@@ -23815,7 +25084,7 @@ async function dispatchRunLedgerOutboxBatchWithScope(
|
|
|
23815
25084
|
// claim's first-HTTP lease proof. Background discovery can still prioritize
|
|
23816
25085
|
// a terminal after claiming it, but must renew before its first append.
|
|
23817
25086
|
const targetedTerminalRunId =
|
|
23818
|
-
scope && scope.targetEventId
|
|
25087
|
+
scope && isRunEndingEventId(scope.targetEventId, scope.runId)
|
|
23819
25088
|
? scope.runId
|
|
23820
25089
|
: null;
|
|
23821
25090
|
let terminalRunId = targetedTerminalRunId;
|
|
@@ -25564,7 +26833,20 @@ async function acknowledgeRunLedgerPrefixWithContinuation(
|
|
|
25564
26833
|
continuation: RunLedgerOutboxDrainScope | null;
|
|
25565
26834
|
}> {
|
|
25566
26835
|
const runId = input.events[0]!.runId;
|
|
25567
|
-
|
|
26836
|
+
// Without an explicit target, aim for this run's latest ending among the
|
|
26837
|
+
// delivered events; a never-resumed run's ending keeps its original ID.
|
|
26838
|
+
const targetEventId =
|
|
26839
|
+
input.scope?.targetEventId ??
|
|
26840
|
+
input.events
|
|
26841
|
+
.map((event) => event.eventId)
|
|
26842
|
+
.filter((eventId) => isRunEndingEventId(eventId, runId))
|
|
26843
|
+
.sort(
|
|
26844
|
+
(left, right) =>
|
|
26845
|
+
(runEndingEventEpoch(left, runId) ?? 0) -
|
|
26846
|
+
(runEndingEventEpoch(right, runId) ?? 0),
|
|
26847
|
+
)
|
|
26848
|
+
.at(-1) ??
|
|
26849
|
+
runEndingEventId(runId);
|
|
25568
26850
|
const retainContinuation =
|
|
25569
26851
|
!!input.scope ||
|
|
25570
26852
|
(input.input.continueThroughTerminal === true && !input.input.headEventId);
|
|
@@ -26568,6 +27850,7 @@ export async function requestComputeBillingDispatchToken(input: {
|
|
|
26568
27850
|
leaseOwner: string;
|
|
26569
27851
|
attemptCount: number;
|
|
26570
27852
|
schedulerSchema: string | null;
|
|
27853
|
+
tokenIssuerOrigin?: string;
|
|
26571
27854
|
}): Promise<string> {
|
|
26572
27855
|
const internalToken = process.env.DEEPLINE_INTERNAL_TOKEN?.trim();
|
|
26573
27856
|
if (!internalToken || !input.runId || !input.leaseOwner) {
|
|
@@ -26575,15 +27858,25 @@ export async function requestComputeBillingDispatchToken(input: {
|
|
|
26575
27858
|
'Compute-billing recovery requires a valid dispatch lease and DEEPLINE_INTERNAL_TOKEN.',
|
|
26576
27859
|
);
|
|
26577
27860
|
}
|
|
27861
|
+
if (
|
|
27862
|
+
input.tokenIssuerOrigin &&
|
|
27863
|
+
!isImmutableRuntimeExecutionRecoveryOrigin(input.tokenIssuerOrigin)
|
|
27864
|
+
) {
|
|
27865
|
+
throw new Error(
|
|
27866
|
+
'Compute billing recovery requires an immutable Deepline token issuer.',
|
|
27867
|
+
);
|
|
27868
|
+
}
|
|
26578
27869
|
// Signed with the internal token, which is never pinned.
|
|
26579
|
-
const
|
|
26580
|
-
|
|
26581
|
-
|
|
26582
|
-
|
|
26583
|
-
|
|
26584
|
-
|
|
27870
|
+
const issuerOrigin =
|
|
27871
|
+
input.tokenIssuerOrigin ??
|
|
27872
|
+
resolveRuntimeAppTransport({
|
|
27873
|
+
caller: 'direct',
|
|
27874
|
+
launch: input.launch,
|
|
27875
|
+
executorToken: internalToken,
|
|
27876
|
+
}).baseUrl;
|
|
27877
|
+
const url = `${issuerOrigin.replace(/\/$/, '')}/api/v2/internal/play-runtime/compute-billing-dispatch-token`;
|
|
26585
27878
|
const vercelProtectionHeaders = await vercelProtectionBypassHeaders({
|
|
26586
|
-
baseUrl:
|
|
27879
|
+
baseUrl: issuerOrigin,
|
|
26587
27880
|
token: input.launch.vercelProtectionBypassToken,
|
|
26588
27881
|
});
|
|
26589
27882
|
const response = await fetch(url, {
|