deepline 0.3.550 → 0.3.551
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/release.ts +1 -1
- package/dist/bundling-sources/sdk/src/types.ts +22 -0
- package/dist/bundling-sources/shared_libs/integration-contracts/tool-connection.ts +42 -0
- package/dist/bundling-sources/shared_libs/monitors/snitcher-ip2company.ts +31 -0
- package/dist/bundling-sources/shared_libs/monitors/tracking-provider-guidance.ts +1 -0
- package/dist/bundling-sources/shared_libs/observability/scheduled-jobs.json +19 -0
- package/dist/bundling-sources/shared_libs/play-runtime/activity-observation.ts +2 -0
- package/dist/bundling-sources/shared_libs/play-runtime/durable-runs-rollout.ts +2 -2
- package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/absurd-runtime-worker.ts +187 -16
- package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/postgres-rate-state.ts +70 -19
- package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/postgres.ts +854 -3
- package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/runtime-event-search.ts +15 -1
- package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/runtime-sandbox-capacity.ts +6 -2
- package/dist/bundling-sources/shared_libs/plays/share/static-pipeline-summary.ts +43 -0
- package/dist/bundling-sources/shared_libs/product-notifications/billing-sales.ts +1 -0
- package/dist/bundling-sources/shared_libs/product-notifications/catalog.ts +38 -5
- package/dist/bundling-sources/shared_libs/product-notifications/default-policy.ts +1 -1
- package/dist/bundling-sources/shared_libs/product-notifications/events.ts +16 -0
- package/dist/cli/auth-B4PI7GVY.js +43 -0
- package/dist/cli/{auth-UJCAHGZG.mjs → auth-E7BH4GMJ.mjs} +5 -5
- package/dist/cli/{billing-VO2O5O5O.js → billing-DNQAZGX7.js} +99 -99
- package/dist/cli/{billing-RYWMI7JJ.mjs → billing-OXKU462W.mjs} +10 -10
- package/dist/cli/chunk-2RIKOPIM.mjs +9 -0
- package/dist/cli/{chunk-IZCPOX7X.mjs → chunk-2UXDHFSF.mjs} +1 -1
- package/dist/cli/{chunk-XYIECA7M.js → chunk-2WFPHBR4.js} +30 -8
- package/dist/cli/{chunk-JYUIIDZO.js → chunk-2ZYRBMQM.js} +23 -22
- package/dist/cli/{chunk-TB3WT76F.js → chunk-3G6QZACZ.js} +23 -20
- package/dist/cli/{chunk-LWHWMU4V.js → chunk-3KYBDAR3.js} +7 -7
- package/dist/cli/{chunk-CIBQVA6V.mjs → chunk-3T65J5RG.mjs} +2 -2
- package/dist/cli/{chunk-KSUTNW3X.js → chunk-44I675YK.js} +42 -41
- package/dist/cli/{chunk-4NQWUUOH.mjs → chunk-44KSACJW.mjs} +2 -2
- package/dist/cli/{chunk-GVW5V562.mjs → chunk-4D3WIZST.mjs} +1 -1
- package/dist/cli/{chunk-RS6ZSKX6.js → chunk-4OMAGJ6U.js} +2 -2
- package/dist/cli/{chunk-SZNX3XU3.js → chunk-54EEYLTF.js} +3 -3
- package/dist/cli/{chunk-QD2KT7II.mjs → chunk-5IL7SC45.mjs} +2 -2
- package/dist/cli/{chunk-COHCKZQK.mjs → chunk-5S6PHKRV.mjs} +2 -1
- package/dist/cli/{chunk-SBNNK73L.js → chunk-5VVSEU67.js} +6 -6
- package/dist/cli/{chunk-ZQZOYGDC.mjs → chunk-6PWJKMFQ.mjs} +5 -4
- package/dist/cli/{chunk-MAE3AKDR.mjs → chunk-7DOQ3OEX.mjs} +17 -8
- package/dist/cli/{chunk-3W44AJOE.js → chunk-7RSIFA72.js} +18 -16
- package/dist/cli/{chunk-F2RXBNT5.mjs → chunk-7WQNWJQW.mjs} +7 -5
- package/dist/cli/{chunk-6P7TGCHQ.mjs → chunk-BGBJV26E.mjs} +10 -3
- package/dist/cli/{chunk-UL7HWZO7.mjs → chunk-BIIJATTX.mjs} +2 -2
- package/dist/cli/{chunk-ADWMIZCB.js → chunk-C4CUZH57.js} +20 -11
- package/dist/cli/{chunk-S6XOKGBF.mjs → chunk-CLRAANWH.mjs} +1 -1
- package/dist/cli/{chunk-YSYOQYZE.js → chunk-COGREZAO.js} +48 -44
- package/dist/cli/{chunk-SMLWC7PM.js → chunk-CQ6JYQSW.js} +10 -10
- package/dist/cli/{chunk-7BWMCVYU.mjs → chunk-D6M5HFBB.mjs} +1 -1
- package/dist/cli/{chunk-FMXLQHM2.mjs → chunk-E64HFB4L.mjs} +13 -13
- package/dist/cli/{chunk-E2QVWDDW.mjs → chunk-FOTGUFVK.mjs} +3 -3
- package/dist/cli/{chunk-HCFH2V27.mjs → chunk-GGB3JYCW.mjs} +3 -2
- package/dist/cli/{chunk-7AOFSZJM.mjs → chunk-GGGAEVCX.mjs} +23 -1
- package/dist/cli/{chunk-N2Y2IGNB.mjs → chunk-GVYLCCKN.mjs} +1 -1
- package/dist/cli/{chunk-UV4RU2TE.js → chunk-H4ALLC2X.js} +2 -0
- package/dist/cli/{chunk-LUULRAQB.mjs → chunk-HEHVGEZV.mjs} +10 -7
- package/dist/cli/{chunk-HEVUFICQ.mjs → chunk-I4VKGNAQ.mjs} +9 -5
- package/dist/cli/{chunk-RKF263LR.js → chunk-KWSH5T7K.js} +25 -18
- package/dist/cli/{chunk-XKE2PGZ2.js → chunk-LPJPCGT3.js} +8 -8
- package/dist/cli/{chunk-E4S7OE7B.mjs → chunk-MNSTCJMX.mjs} +3 -3
- package/dist/cli/{chunk-QNWNR6DG.js → chunk-MR5LTVHD.js} +53 -53
- package/dist/cli/{chunk-K7JZV4QW.mjs → chunk-MXGA6JFI.mjs} +2 -2
- package/dist/cli/{chunk-EU23QOJ6.js → chunk-NMWGZD6Y.js} +26 -26
- package/dist/cli/{chunk-MJDQZYKO.js → chunk-PACD5DGC.js} +4 -4
- package/dist/cli/{chunk-EMPXPEIQ.mjs → chunk-PM7MO62Y.mjs} +3 -3
- package/dist/cli/{chunk-JKLDCFY5.js → chunk-POLUE7D5.js} +11 -11
- package/dist/cli/{chunk-DGUTBLXF.js → chunk-PPSDCN6C.js} +3 -2
- package/dist/cli/{chunk-NM3AYEDI.js → chunk-QM6Y6S4E.js} +5 -5
- package/dist/cli/{chunk-2AKS64KJ.mjs → chunk-RE5MJBEV.mjs} +2 -2
- package/dist/cli/{chunk-KLQILE2I.mjs → chunk-S7IZWGUA.mjs} +2 -2
- package/dist/cli/{chunk-2IW5GKB4.js → chunk-T2B5BVZE.js} +13 -13
- package/dist/cli/{chunk-OKNOQRQ3.js → chunk-UDXULACQ.js} +3 -3
- package/dist/cli/{chunk-ECWOIXAV.js → chunk-UPMRIVZB.js} +14 -12
- package/dist/cli/{chunk-72NXIFOT.mjs → chunk-V6SCP4B7.mjs} +1 -1
- package/dist/cli/{chunk-5J3TRWTB.js → chunk-VTGG2RT3.js} +1 -1
- package/dist/cli/{chunk-DJWM5OOY.mjs → chunk-VWLHRZFG.mjs} +4 -4
- package/dist/cli/{chunk-I62PCYU6.js → chunk-W2ZWQUHT.js} +2 -2
- package/dist/cli/{chunk-MXEYNRTZ.mjs → chunk-W425ERWN.mjs} +6 -5
- package/dist/cli/{chunk-GWNYLIF7.mjs → chunk-WEHCBH5R.mjs} +4 -2
- package/dist/cli/{chunk-JLFOQRWM.js → chunk-WKBHUB6R.js} +270 -270
- package/dist/cli/{chunk-3WG2GURT.js → chunk-XYE5XPGF.js} +9 -9
- package/dist/cli/{chunk-R5CYKRA2.js → chunk-Z2FIOG3V.js} +12 -12
- package/dist/cli/{chunk-BJO7ZXAK.js → chunk-ZCDKE4UH.js} +5 -5
- package/dist/cli/{chunk-RINUMR6C.js → chunk-ZDQFBJPO.js} +20 -19
- package/dist/cli/{chunk-TL3WIXDH.mjs → chunk-ZMNGZ6XS.mjs} +1 -1
- package/dist/cli/command-docs.js +3 -3
- package/dist/cli/command-docs.mjs +2 -2
- package/dist/cli/{concurrent-runs-help-766HVJR3.mjs → concurrent-runs-help-C6L6I5OR.mjs} +7 -7
- package/dist/cli/concurrent-runs-help-JEFQZTJI.js +21 -0
- package/dist/cli/{csv-4DZKGYCU.js → csv-QMF4FWE7.js} +19 -14
- package/dist/cli/{csv-VU52KZOX.mjs → csv-SYSDXFEM.mjs} +10 -5
- package/dist/cli/{db-UBGW373S.mjs → db-Q7HURWRZ.mjs} +6 -6
- package/dist/cli/{db-KPIH4HPW.js → db-YSHPPA4H.js} +27 -27
- package/dist/cli/describe-PXTSBJTL.js +50 -0
- package/dist/cli/{describe-NGITP6RA.mjs → describe-YGMQBV44.mjs} +21 -21
- package/dist/cli/describe-core.d.mts +4 -2
- package/dist/cli/describe-core.d.ts +4 -2
- package/dist/cli/describe-core.js +4 -4
- package/dist/cli/describe-core.mjs +3 -3
- package/dist/cli/{executions-CO5UF3CV.mjs → executions-G7U3VUXN.mjs} +6 -6
- package/dist/cli/{executions-G3X25U3V.js → executions-MWBC5TAW.js} +8 -8
- package/dist/cli/{feedback-M2L5DVN2.mjs → feedback-GMHIFLBJ.mjs} +6 -6
- package/dist/cli/{feedback-ZYF65WPH.js → feedback-SD55OY6H.js} +14 -14
- package/dist/cli/{git-AYJD5CLS.mjs → git-HPE45OPD.mjs} +5 -5
- package/dist/cli/git-I3JV7IGH.js +25 -0
- package/dist/cli/index.js +147 -147
- package/dist/cli/index.mjs +46 -46
- package/dist/cli/{integrations-LKEGGTZO.mjs → integrations-2W4MGIQR.mjs} +7 -7
- package/dist/cli/{integrations-GSXXJ4CF.js → integrations-HFKVBY6G.js} +15 -15
- package/dist/cli/{legacy-noops-UF4GKMD4.mjs → legacy-noops-GZYKNU2Z.mjs} +6 -6
- package/dist/cli/{legacy-noops-MZDLLEKN.js → legacy-noops-SXVNDEXN.js} +9 -9
- package/dist/cli/{mcp-NHQ6RMBP.mjs → mcp-BWA6KULG.mjs} +4 -4
- package/dist/cli/{mcp-RTNC6LP3.js → mcp-PJRHQHHU.js} +24 -24
- package/dist/cli/{monitors-WMWB6EKQ.js → monitors-K2WSI6CR.js} +100 -100
- package/dist/cli/{monitors-NC4ZR5DH.mjs → monitors-SYQKCATO.mjs} +7 -7
- package/dist/cli/{org-ZXUSYREQ.mjs → org-5KD7X7IA.mjs} +6 -6
- package/dist/cli/{org-33Q7CXJB.js → org-YQ2CR32B.js} +88 -88
- package/dist/cli/{play-N24XV6TI.js → play-SZXY2F2S.js} +330 -330
- package/dist/cli/{play-IPWFGNRE.mjs → play-TTMABJEI.mjs} +18 -18
- package/dist/cli/{providers-MSVE7UZS.mjs → providers-GQIOMRQO.mjs} +6 -6
- package/dist/cli/{providers-AUI7MMQS.js → providers-YDHCTZAF.js} +9 -9
- package/dist/cli/{quickstart-PSC6VTRI.js → quickstart-BNYOXQXG.js} +6 -6
- package/dist/cli/{quickstart-OME5XMW5.mjs → quickstart-PHSSMKCA.mjs} +4 -4
- package/dist/cli/{run-EYTT2DHO.mjs → run-74C3C75C.mjs} +26 -26
- package/dist/cli/{run-UTIX7CJY.js → run-GFIAZXVL.js} +47 -47
- package/dist/cli/search-2RRRF4LW.js +32 -0
- package/dist/cli/{search-FVE7PM72.mjs → search-3SWUB7KX.mjs} +7 -7
- package/dist/cli/{search-output-O463JNLR.js → search-output-6JF3S4TP.js} +43 -13
- package/dist/cli/{search-output-TQMY6BDG.mjs → search-output-K2SWHVHQ.mjs} +40 -10
- package/dist/cli/{secrets-KCJJAHQB.mjs → secrets-2M4XWEKE.mjs} +6 -6
- package/dist/cli/{secrets-TWZ2GO73.js → secrets-2SAKLH2H.js} +15 -15
- package/dist/cli/{sessions-ZCWAA7QL.mjs → sessions-A64BCXTO.mjs} +6 -6
- package/dist/cli/sessions-SBH27JNW.js +22 -0
- package/dist/cli/{settings-SCR654U7.js → settings-HV64WIJF.js} +85 -85
- package/dist/cli/{settings-4JFKCKII.mjs → settings-SVGEC3FI.mjs} +12 -12
- package/dist/cli/{setup-Q2YOPGOI.mjs → setup-EDC3NEJ3.mjs} +15 -10
- package/dist/cli/{setup-O6GH3UWT.js → setup-FHXOLQGQ.js} +55 -50
- package/dist/cli/{skills-QHPZ6H2G.mjs → skills-3HGHZMXB.mjs} +7 -7
- package/dist/cli/skills-Y3SRLOYD.js +36 -0
- package/dist/cli/tools-OFYPUPUV.js +57 -0
- package/dist/cli/{tools-YO22H46E.mjs → tools-P2QS6A6Q.mjs} +19 -19
- package/dist/cli/{update-WHBC5IHE.mjs → update-552BYQM4.mjs} +9 -9
- package/dist/cli/update-SOUSCLB7.js +34 -0
- package/dist/cli/{views-XNLXV2BT.mjs → views-LD5HXJYY.mjs} +6 -6
- package/dist/cli/{views-4CZJ5BLG.js → views-PA25NAE3.js} +21 -21
- package/dist/cli/{workflow-C4VBARIE.js → workflow-FIDBUQV6.js} +17 -17
- package/dist/cli/{workflow-QUWP2CG2.mjs → workflow-LDYFGBYP.mjs} +7 -7
- package/dist/{client-BEJqhQAj.d.mts → client-DuDFiJDU.d.mts} +1 -1
- package/dist/{client-core-BPYuWfBC.d.ts → client-core-CJRzLanv.d.ts} +93 -4
- package/dist/{client-core-BqetRxx-.d.mts → client-core-DydMQOft.d.mts} +93 -4
- package/dist/{client-Ceo295L2.d.ts → client-t9HZAkFD.d.ts} +1 -1
- package/dist/index.d.mts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +9 -9
- package/dist/index.mjs +6 -6
- package/dist/install-integrity.json +124 -124
- package/dist/plays/play-description.d.mts +1 -1
- package/dist/plays/play-description.d.ts +1 -1
- package/dist/plays/run-request.d.mts +1 -1
- package/dist/plays/run-request.d.ts +1 -1
- 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 +2 -2
- package/dist/server.d.ts +2 -2
- package/dist/server.js +5 -5
- package/dist/server.mjs +3 -3
- package/package.json +1 -1
- package/dist/cli/auth-J4OW5RNJ.js +0 -43
- package/dist/cli/chunk-NIPLY25A.mjs +0 -7
- package/dist/cli/concurrent-runs-help-3XZIHVRP.js +0 -21
- package/dist/cli/describe-4BI6E2CM.js +0 -50
- package/dist/cli/git-QRZP4DNA.js +0 -25
- package/dist/cli/search-CQ6JG2EN.js +0 -32
- package/dist/cli/sessions-LMPXUPUH.js +0 -22
- package/dist/cli/skills-M4CFE65Z.js +0 -36
- package/dist/cli/tools-CV7XA2V6.js +0 -57
- package/dist/cli/update-PUWBKPWJ.js +0 -34
|
@@ -464,7 +464,7 @@ const POSTGRES_SCHEDULER_SCHEMA_INIT_STATEMENT_TIMEOUT_MS = 60_000;
|
|
|
464
464
|
// `vercel` beside `daytona` and `modal`. Expand only: no writer emits it yet,
|
|
465
465
|
// every existing row already satisfies the wider check, and older workers only
|
|
466
466
|
// claim cleanup for their own providers. Nothing reads this marker at runtime.
|
|
467
|
-
export const POSTGRES_SCHEDULER_SCHEMA_VERSION =
|
|
467
|
+
export const POSTGRES_SCHEDULER_SCHEMA_VERSION = 69;
|
|
468
468
|
/**
|
|
469
469
|
* Providers the managed-sandbox tables admit. A new provider is added here
|
|
470
470
|
* (and so to every `provider` CHECK) before any writer records it.
|
|
@@ -2468,6 +2468,192 @@ export async function ensurePostgresSchedulerSandboxCapacityAdmissionFunctions(
|
|
|
2468
2468
|
END;
|
|
2469
2469
|
$runtime_sandbox_capacity_observation$
|
|
2470
2470
|
`);
|
|
2471
|
+
await ensurePostgresSchedulerSandboxCapacityWakeFunctions(client, options);
|
|
2472
|
+
}
|
|
2473
|
+
|
|
2474
|
+
const SANDBOX_CAPACITY_WAKE_TRIGGER =
|
|
2475
|
+
'runtime_sandbox_capacity_lease_released_v1';
|
|
2476
|
+
|
|
2477
|
+
/** `DEFAULT_PLAY_SANDBOX_CONCURRENCY`, installed into the wake function. */
|
|
2478
|
+
export const SANDBOX_CAPACITY_WAKE_DEFAULT_LIMIT = 50;
|
|
2479
|
+
|
|
2480
|
+
/**
|
|
2481
|
+
* Wake the org's oldest live sandbox-capacity waiters (see
|
|
2482
|
+
* `gatePostgresSchedulerSandboxCapacity`): emit each one's Absurd wake event
|
|
2483
|
+
* and advance its `seq`, so the next wait names a fresh event. Waiters are
|
|
2484
|
+
* locked SKIP LOCKED and each emit runs in its own subtransaction, so a busy
|
|
2485
|
+
* row or a retired queue never blocks the caller. The lease-release trigger
|
|
2486
|
+
* calls this with one wake per released lease.
|
|
2487
|
+
*/
|
|
2488
|
+
async function ensurePostgresSchedulerSandboxCapacityWakeFunctions(
|
|
2489
|
+
client: PostgresSchedulerQueryClient,
|
|
2490
|
+
options?: Pick<PostgresSchedulerOptions, 'schema'>,
|
|
2491
|
+
): Promise<void> {
|
|
2492
|
+
const quotedSchema = quoteIdent(schemaName(options));
|
|
2493
|
+
const key = SANDBOX_CAPACITY_WAIT_RECOVERY_KEY;
|
|
2494
|
+
await client.query(`
|
|
2495
|
+
CREATE OR REPLACE FUNCTION ${quotedSchema}.runtime_sandbox_capacity_wake_waiters(
|
|
2496
|
+
requested_org_id text,
|
|
2497
|
+
max_wakes integer
|
|
2498
|
+
) RETURNS integer
|
|
2499
|
+
LANGUAGE plpgsql VOLATILE
|
|
2500
|
+
AS $runtime_sandbox_capacity_wake_waiters$
|
|
2501
|
+
DECLARE
|
|
2502
|
+
now_ms bigint := floor(extract(epoch FROM clock_timestamp()) * 1000)::bigint;
|
|
2503
|
+
can_emit boolean := to_regprocedure('absurd.emit_event(text,text,jsonb)') IS NOT NULL;
|
|
2504
|
+
waiter record;
|
|
2505
|
+
woken integer := 0;
|
|
2506
|
+
slot_limit integer;
|
|
2507
|
+
active_leases integer;
|
|
2508
|
+
in_flight integer;
|
|
2509
|
+
budget integer;
|
|
2510
|
+
prior_lock_timeout text;
|
|
2511
|
+
BEGIN
|
|
2512
|
+
IF NOT can_emit OR coalesce(max_wakes, 0) < 1 THEN
|
|
2513
|
+
RETURN 0;
|
|
2514
|
+
END IF;
|
|
2515
|
+
-- Wake only into free slots, net of waiters already woken and on their
|
|
2516
|
+
-- way to a claim. The limit is resolved as the gate resolves it, with
|
|
2517
|
+
-- the oldest live waiter's launch entitlement.
|
|
2518
|
+
SELECT coalesce(
|
|
2519
|
+
(SELECT override."limit"
|
|
2520
|
+
FROM ${tableName('runtime_org_sandbox_limit_cache', options)} AS override
|
|
2521
|
+
WHERE override.org_id = requested_org_id
|
|
2522
|
+
AND override.expires_at IS NOT NULL
|
|
2523
|
+
AND override.expires_at > clock_timestamp()),
|
|
2524
|
+
(SELECT CASE
|
|
2525
|
+
WHEN jsonb_typeof(oldest.launch_json -> 'concurrentRunsLimit') = 'number'
|
|
2526
|
+
AND (oldest.launch_json ->> 'concurrentRunsLimit')::numeric BETWEEN 1 AND 250
|
|
2527
|
+
THEN (oldest.launch_json ->> 'concurrentRunsLimit')::integer
|
|
2528
|
+
END
|
|
2529
|
+
FROM ${tableName('runs', options)} AS oldest
|
|
2530
|
+
WHERE oldest.org_id = requested_org_id
|
|
2531
|
+
AND ${sandboxCapacityWaiterSql('oldest')}
|
|
2532
|
+
AND ${sandboxCapacityWaiterLiveSql('oldest', 'now_ms')}
|
|
2533
|
+
ORDER BY oldest.created_at, oldest.run_id
|
|
2534
|
+
LIMIT 1),
|
|
2535
|
+
(SELECT CASE
|
|
2536
|
+
WHEN cached.expires_at IS NOT NULL AND cached.expires_at <= clock_timestamp()
|
|
2537
|
+
THEN ${SANDBOX_CAPACITY_WAKE_DEFAULT_LIMIT}
|
|
2538
|
+
ELSE cached."limit"
|
|
2539
|
+
END
|
|
2540
|
+
FROM ${tableName('runtime_org_sandbox_limit_cache', options)} AS cached
|
|
2541
|
+
WHERE cached.org_id = requested_org_id),
|
|
2542
|
+
${SANDBOX_CAPACITY_WAKE_DEFAULT_LIMIT}
|
|
2543
|
+
) INTO slot_limit;
|
|
2544
|
+
SELECT count(*)::integer INTO active_leases
|
|
2545
|
+
FROM ${tableName('runtime_sandbox_capacity_leases', options)} AS lease
|
|
2546
|
+
WHERE lease.org_id = requested_org_id
|
|
2547
|
+
AND lease.released_at IS NULL
|
|
2548
|
+
AND (lease.sandbox_id IS NOT NULL OR lease.expires_at > clock_timestamp());
|
|
2549
|
+
SELECT count(*)::integer INTO in_flight
|
|
2550
|
+
FROM ${tableName('runs', options)} AS run
|
|
2551
|
+
WHERE run.org_id = requested_org_id
|
|
2552
|
+
AND (
|
|
2553
|
+
(${sandboxCapacityWaiterSql('run')}
|
|
2554
|
+
AND coalesce((run.recovery_json #>> '{${key},wokenAtMs}')::bigint, 0)
|
|
2555
|
+
>= now_ms - ${SANDBOX_CAPACITY_WAIT_POLICY.wakeClaimMs}::bigint)
|
|
2556
|
+
OR (${sandboxCapacityAdmittedInFlightSql('run', 'now_ms', options)})
|
|
2557
|
+
);
|
|
2558
|
+
budget := least(max_wakes, slot_limit - active_leases - in_flight);
|
|
2559
|
+
IF budget < 1 THEN
|
|
2560
|
+
RETURN 0;
|
|
2561
|
+
END IF;
|
|
2562
|
+
FOR waiter IN
|
|
2563
|
+
SELECT run.run_id,
|
|
2564
|
+
run.recovery_json #>> '{${key},queue}' AS queue_name,
|
|
2565
|
+
coalesce((run.recovery_json #>> '{${key},seq}')::integer, 0) AS seq
|
|
2566
|
+
FROM ${tableName('runs', options)} AS run
|
|
2567
|
+
WHERE run.org_id = requested_org_id
|
|
2568
|
+
AND ${sandboxCapacityWaiterSql('run')}
|
|
2569
|
+
AND ${sandboxCapacityWaiterLiveSql('run', 'now_ms')}
|
|
2570
|
+
AND coalesce((run.recovery_json #>> '{${key},wokenAtMs}')::bigint, 0)
|
|
2571
|
+
< now_ms - ${SANDBOX_CAPACITY_WAIT_POLICY.wakeClaimMs}::bigint
|
|
2572
|
+
AND (run.recovery_json #>> '{${key},queue}') IS NOT NULL
|
|
2573
|
+
ORDER BY run.created_at, run.run_id
|
|
2574
|
+
LIMIT budget
|
|
2575
|
+
FOR UPDATE OF run SKIP LOCKED
|
|
2576
|
+
LOOP
|
|
2577
|
+
BEGIN
|
|
2578
|
+
-- This runs inside the lease release's transaction. Bound the wait
|
|
2579
|
+
-- on a busy engine row so contention raises 55P03 (caught below)
|
|
2580
|
+
-- instead of holding the release's locks. The subtransaction's
|
|
2581
|
+
-- abort restores the setting; success restores it explicitly.
|
|
2582
|
+
prior_lock_timeout := current_setting('lock_timeout');
|
|
2583
|
+
PERFORM set_config('lock_timeout', '250ms', true);
|
|
2584
|
+
PERFORM absurd.emit_event(
|
|
2585
|
+
waiter.queue_name,
|
|
2586
|
+
'sandbox-capacity-slot:' || waiter.run_id || ':' || waiter.seq::text,
|
|
2587
|
+
'true'::jsonb
|
|
2588
|
+
);
|
|
2589
|
+
UPDATE ${tableName('runs', options)} AS run
|
|
2590
|
+
SET recovery_json = jsonb_set(
|
|
2591
|
+
run.recovery_json, '{${key}}',
|
|
2592
|
+
(run.recovery_json -> '${key}') || jsonb_build_object(
|
|
2593
|
+
'seq', waiter.seq + 1,
|
|
2594
|
+
'wokenAtMs', now_ms
|
|
2595
|
+
)
|
|
2596
|
+
),
|
|
2597
|
+
updated_at = now()
|
|
2598
|
+
WHERE run.run_id = waiter.run_id;
|
|
2599
|
+
PERFORM set_config('lock_timeout', prior_lock_timeout, true);
|
|
2600
|
+
woken := woken + 1;
|
|
2601
|
+
EXCEPTION WHEN OTHERS THEN
|
|
2602
|
+
RAISE WARNING 'runtime sandbox capacity wake skipped run %: %',
|
|
2603
|
+
waiter.run_id, SQLERRM;
|
|
2604
|
+
END;
|
|
2605
|
+
END LOOP;
|
|
2606
|
+
RETURN woken;
|
|
2607
|
+
END;
|
|
2608
|
+
$runtime_sandbox_capacity_wake_waiters$
|
|
2609
|
+
`);
|
|
2610
|
+
await client.query(`
|
|
2611
|
+
CREATE OR REPLACE FUNCTION ${quotedSchema}.runtime_sandbox_capacity_lease_released()
|
|
2612
|
+
RETURNS trigger
|
|
2613
|
+
LANGUAGE plpgsql
|
|
2614
|
+
AS $runtime_sandbox_capacity_lease_released$
|
|
2615
|
+
BEGIN
|
|
2616
|
+
-- A wake is a hint; never fail the release that freed the slot.
|
|
2617
|
+
BEGIN
|
|
2618
|
+
PERFORM ${quotedSchema}.runtime_sandbox_capacity_wake_waiters(NEW.org_id, 1);
|
|
2619
|
+
EXCEPTION WHEN OTHERS THEN
|
|
2620
|
+
RAISE WARNING 'runtime sandbox capacity wake skipped for org %: %',
|
|
2621
|
+
NEW.org_id, SQLERRM;
|
|
2622
|
+
END;
|
|
2623
|
+
RETURN NULL;
|
|
2624
|
+
END;
|
|
2625
|
+
$runtime_sandbox_capacity_lease_released$
|
|
2626
|
+
`);
|
|
2627
|
+
}
|
|
2628
|
+
|
|
2629
|
+
/**
|
|
2630
|
+
* Wake a sandbox-capacity waiter when a lease is released (confirmed delete,
|
|
2631
|
+
* abandoned reservation, reconciliation). Installed by the deploy migration
|
|
2632
|
+
* and fresh bootstraps, never by a worker cold start: creating a trigger
|
|
2633
|
+
* locks the lease table. Without it, waiters still start on their fallback
|
|
2634
|
+
* timer.
|
|
2635
|
+
*/
|
|
2636
|
+
export async function ensurePostgresSchedulerSandboxCapacityWakeTrigger(
|
|
2637
|
+
client: PostgresSchedulerQueryClient,
|
|
2638
|
+
options?: Pick<PostgresSchedulerOptions, 'schema'>,
|
|
2639
|
+
): Promise<void> {
|
|
2640
|
+
const leases = tableName('runtime_sandbox_capacity_leases', options);
|
|
2641
|
+
const present = await client.query<{ present: boolean }>(
|
|
2642
|
+
`SELECT EXISTS (
|
|
2643
|
+
SELECT 1 FROM pg_trigger
|
|
2644
|
+
WHERE tgrelid = $1::regclass AND tgname = $2 AND NOT tgisinternal
|
|
2645
|
+
) AS present`,
|
|
2646
|
+
[leases, SANDBOX_CAPACITY_WAKE_TRIGGER],
|
|
2647
|
+
);
|
|
2648
|
+
if (present.rows[0]?.present === true) return;
|
|
2649
|
+
await ensurePostgresSchedulerSandboxCapacityWakeFunctions(client, options);
|
|
2650
|
+
await client.query(`
|
|
2651
|
+
CREATE TRIGGER ${SANDBOX_CAPACITY_WAKE_TRIGGER}
|
|
2652
|
+
AFTER UPDATE OF released_at ON ${leases}
|
|
2653
|
+
FOR EACH ROW
|
|
2654
|
+
WHEN (OLD.released_at IS NULL AND NEW.released_at IS NOT NULL)
|
|
2655
|
+
EXECUTE FUNCTION ${quoteIdent(schemaName(options))}.runtime_sandbox_capacity_lease_released()
|
|
2656
|
+
`);
|
|
2471
2657
|
}
|
|
2472
2658
|
|
|
2473
2659
|
/**
|
|
@@ -3570,6 +3756,12 @@ export async function ensurePostgresSchedulerSchema(
|
|
|
3570
3756
|
client,
|
|
3571
3757
|
options,
|
|
3572
3758
|
);
|
|
3759
|
+
// v69: the sandbox-capacity waiter wake. Once the marker exists the
|
|
3760
|
+
// deploy migration owns it, so a cold start takes no table lock.
|
|
3761
|
+
await ensurePostgresSchedulerSandboxCapacityWakeTrigger(
|
|
3762
|
+
client,
|
|
3763
|
+
options,
|
|
3764
|
+
);
|
|
3573
3765
|
}
|
|
3574
3766
|
await ensurePostgresSchedulerSandboxCapacityAdmissionFunctions(
|
|
3575
3767
|
client,
|
|
@@ -3957,6 +4149,7 @@ export async function ensurePostgresSchedulerSchema(
|
|
|
3957
4149
|
client,
|
|
3958
4150
|
options,
|
|
3959
4151
|
);
|
|
4152
|
+
await ensurePostgresSchedulerSandboxCapacityWakeTrigger(client, options);
|
|
3960
4153
|
// The operation ledger is authoritative for a physical sandbox lifecycle.
|
|
3961
4154
|
// `resource_json` stays a compatibility/audit projection, never a source
|
|
3962
4155
|
// for capacity admission or reconciliation.
|
|
@@ -4980,6 +5173,10 @@ export async function ensurePostgresSchedulerSchema(
|
|
|
4980
5173
|
ON ${tableName('runs', options)} ((launch_json ->> 'absurdReleaseId'), run_id)
|
|
4981
5174
|
WHERE status IN ('queued', 'running', 'waiting')
|
|
4982
5175
|
`);
|
|
5176
|
+
await client.query(`
|
|
5177
|
+
CREATE INDEX IF NOT EXISTS ${POSTGRES_SCHEDULER_SANDBOX_CAPACITY_WAIT_INDEX_DEFINITION.name}
|
|
5178
|
+
ON ${tableName('runs', options)} ${POSTGRES_SCHEDULER_SANDBOX_CAPACITY_WAIT_INDEX_DEFINITION.definition}
|
|
5179
|
+
`);
|
|
4983
5180
|
await client.query(`
|
|
4984
5181
|
CREATE INDEX IF NOT EXISTS runtime_scheduler_runs_staged_input_expiry_idx
|
|
4985
5182
|
ON ${tableName('runs', options)} (coalesce(array_input_retire_attempted_at, finished_at))
|
|
@@ -5056,8 +5253,21 @@ const POSTGRES_SCHEDULER_LEGACY_CLEANUP_PENDING_INDEX_DEFINITION = {
|
|
|
5056
5253
|
definition: "(sandbox_id) WHERE status <> 'deleted'",
|
|
5057
5254
|
} as const;
|
|
5058
5255
|
|
|
5256
|
+
/**
|
|
5257
|
+
* The org's live sandbox-capacity waiters, oldest first. Absence costs a scan
|
|
5258
|
+
* of queued runs per gate check and lease release, never correctness.
|
|
5259
|
+
*/
|
|
5260
|
+
const POSTGRES_SCHEDULER_SANDBOX_CAPACITY_WAIT_INDEX_DEFINITION = {
|
|
5261
|
+
name: 'runtime_scheduler_runs_sandbox_capacity_idx',
|
|
5262
|
+
table: 'runs',
|
|
5263
|
+
definition: `(org_id, created_at, run_id)
|
|
5264
|
+
WHERE status IN ('queued', 'running')
|
|
5265
|
+
AND (recovery_json -> 'sandboxCapacityWait') IS NOT NULL`,
|
|
5266
|
+
} as const;
|
|
5267
|
+
|
|
5059
5268
|
const POSTGRES_SCHEDULER_RUNTIME_ADMIN_INDEXES = [
|
|
5060
5269
|
POSTGRES_SCHEDULER_SANDBOX_CUSTODY_INDEX_DEFINITION,
|
|
5270
|
+
POSTGRES_SCHEDULER_SANDBOX_CAPACITY_WAIT_INDEX_DEFINITION,
|
|
5061
5271
|
{
|
|
5062
5272
|
name: 'runtime_scheduler_attempts_active_status_created_idx',
|
|
5063
5273
|
table: 'attempts',
|
|
@@ -5333,6 +5543,59 @@ async function ensurePostgresSchedulerIndex(
|
|
|
5333
5543
|
}
|
|
5334
5544
|
}
|
|
5335
5545
|
|
|
5546
|
+
/** Deploy-built: concurrent on shared schemas, never on a request path. */
|
|
5547
|
+
export async function ensurePostgresSchedulerSandboxCapacityWaitIndex(
|
|
5548
|
+
client: PostgresSchedulerQueryClient,
|
|
5549
|
+
options: Pick<PostgresSchedulerOptions, 'schema'> & { concurrently: boolean },
|
|
5550
|
+
): Promise<void> {
|
|
5551
|
+
await ensurePostgresSchedulerIndex(
|
|
5552
|
+
client,
|
|
5553
|
+
POSTGRES_SCHEDULER_SANDBOX_CAPACITY_WAIT_INDEX_DEFINITION,
|
|
5554
|
+
options,
|
|
5555
|
+
options.concurrently,
|
|
5556
|
+
);
|
|
5557
|
+
}
|
|
5558
|
+
|
|
5559
|
+
/**
|
|
5560
|
+
* Whether a schema has everything the sandbox-capacity wake needs: the
|
|
5561
|
+
* release trigger, the wake function, and the waiter index. The deploy
|
|
5562
|
+
* verifier requires all three; the runtime never does, because a waiter
|
|
5563
|
+
* without them still starts on its fallback timer.
|
|
5564
|
+
*/
|
|
5565
|
+
export async function readPostgresSchedulerSandboxCapacityWakeState(
|
|
5566
|
+
client: PostgresSchedulerQueryClient,
|
|
5567
|
+
options?: Pick<PostgresSchedulerOptions, 'schema'>,
|
|
5568
|
+
): Promise<{ trigger: boolean; wakeFunction: boolean; index: boolean }> {
|
|
5569
|
+
const quotedSchema = quoteIdent(schemaName(options));
|
|
5570
|
+
const catalog = await client.query<{
|
|
5571
|
+
trigger: boolean;
|
|
5572
|
+
wake_function: boolean;
|
|
5573
|
+
}>(
|
|
5574
|
+
`SELECT
|
|
5575
|
+
EXISTS (
|
|
5576
|
+
SELECT 1 FROM pg_trigger
|
|
5577
|
+
WHERE tgrelid = to_regclass($1) AND tgname = $2 AND NOT tgisinternal
|
|
5578
|
+
) AS trigger,
|
|
5579
|
+
to_regprocedure($3) IS NOT NULL AS wake_function`,
|
|
5580
|
+
[
|
|
5581
|
+
tableName('runtime_sandbox_capacity_leases', options),
|
|
5582
|
+
SANDBOX_CAPACITY_WAKE_TRIGGER,
|
|
5583
|
+
`${quotedSchema}.runtime_sandbox_capacity_wake_waiters(text, integer)`,
|
|
5584
|
+
],
|
|
5585
|
+
);
|
|
5586
|
+
const index = await readPostgresSchedulerIndexState(
|
|
5587
|
+
client,
|
|
5588
|
+
POSTGRES_SCHEDULER_SANDBOX_CAPACITY_WAIT_INDEX_DEFINITION.name,
|
|
5589
|
+
POSTGRES_SCHEDULER_SANDBOX_CAPACITY_WAIT_INDEX_DEFINITION.table,
|
|
5590
|
+
options,
|
|
5591
|
+
);
|
|
5592
|
+
return {
|
|
5593
|
+
trigger: catalog.rows[0]?.trigger === true,
|
|
5594
|
+
wakeFunction: catalog.rows[0]?.wake_function === true,
|
|
5595
|
+
index: index.kind === 'ready',
|
|
5596
|
+
};
|
|
5597
|
+
}
|
|
5598
|
+
|
|
5336
5599
|
export async function readPostgresSchedulerSandboxCustodyIndexState(
|
|
5337
5600
|
client: PostgresSchedulerQueryClient,
|
|
5338
5601
|
options?: Pick<PostgresSchedulerOptions, 'schema'>,
|
|
@@ -9507,11 +9770,22 @@ export async function deferPostgresSchedulerAttemptForCapacity(
|
|
|
9507
9770
|
* the observed limit changes or an attempt records a sandbox. A long
|
|
9508
9771
|
* unchanged wait does not rewrite the projection every retry.
|
|
9509
9772
|
*/
|
|
9510
|
-
sandboxCapacity?: {
|
|
9773
|
+
sandboxCapacity?: {
|
|
9774
|
+
limit: number;
|
|
9775
|
+
nowMs: number;
|
|
9776
|
+
/**
|
|
9777
|
+
* The Absurd queue of the deferring task. Starts the run's
|
|
9778
|
+
* sandbox-capacity wait (`gatePostgresSchedulerSandboxCapacity`) unless
|
|
9779
|
+
* one is already open, so its next execution parks before allocating an
|
|
9780
|
+
* attempt and a lease release can wake it.
|
|
9781
|
+
*/
|
|
9782
|
+
waitQueueName?: string;
|
|
9783
|
+
};
|
|
9511
9784
|
},
|
|
9512
9785
|
options?: Pick<PostgresSchedulerOptions, 'schema'>,
|
|
9513
9786
|
): Promise<boolean> {
|
|
9514
9787
|
const sandboxCapacity = input.sandboxCapacity ?? null;
|
|
9788
|
+
const waitKey = SANDBOX_CAPACITY_WAIT_RECOVERY_KEY;
|
|
9515
9789
|
const deferred = await client.query<{ run_id: string }>(
|
|
9516
9790
|
`
|
|
9517
9791
|
WITH ${runtimeSandboxCustodyLocksSql('run.run_id = $1', options)}, deferred_attempt AS (
|
|
@@ -9533,6 +9807,18 @@ export async function deferPostgresSchedulerAttemptForCapacity(
|
|
|
9533
9807
|
SET status = 'queued',
|
|
9534
9808
|
suspension_json = NULL,
|
|
9535
9809
|
wait_deadline = NULL,
|
|
9810
|
+
recovery_json = CASE
|
|
9811
|
+
WHEN $7::text IS NOT NULL
|
|
9812
|
+
AND (recovery_json #>> '${SANDBOX_CAPACITY_WAIT_SINCE_SQL}') IS NULL
|
|
9813
|
+
THEN coalesce(recovery_json, '{}'::jsonb) || jsonb_build_object(
|
|
9814
|
+
'${waitKey}', jsonb_build_object(
|
|
9815
|
+
'seq', coalesce((recovery_json #>> '{${waitKey},seq}')::integer, 0) + 1,
|
|
9816
|
+
'sinceMs', $6::bigint,
|
|
9817
|
+
'checkedAtMs', $6::bigint,
|
|
9818
|
+
'queue', $7::text
|
|
9819
|
+
))
|
|
9820
|
+
ELSE recovery_json
|
|
9821
|
+
END,
|
|
9536
9822
|
updated_at = now()
|
|
9537
9823
|
WHERE run_id IN (SELECT run_id FROM deferred_attempt)
|
|
9538
9824
|
AND status IN ('queued', 'running', 'waiting')
|
|
@@ -9573,6 +9859,7 @@ export async function deferPostgresSchedulerAttemptForCapacity(
|
|
|
9573
9859
|
}),
|
|
9574
9860
|
sandboxCapacity?.limit ?? null,
|
|
9575
9861
|
sandboxCapacity?.nowMs ?? null,
|
|
9862
|
+
sandboxCapacity?.waitQueueName?.trim() || null,
|
|
9576
9863
|
],
|
|
9577
9864
|
);
|
|
9578
9865
|
return deferred.rows.length > 0;
|
|
@@ -9624,6 +9911,7 @@ function sandboxCapacityActivityEventSql(
|
|
|
9624
9911
|
stateSql: string,
|
|
9625
9912
|
limitSql: string,
|
|
9626
9913
|
nowSql: string,
|
|
9914
|
+
waitedMsSql = 'NULL::bigint',
|
|
9627
9915
|
): string {
|
|
9628
9916
|
return `jsonb_build_object(
|
|
9629
9917
|
'type', ${RUN_EVENT_KIND_SQL_LITERAL.activityObserved},
|
|
@@ -9636,6 +9924,7 @@ function sandboxCapacityActivityEventSql(
|
|
|
9636
9924
|
'target', jsonb_strip_nulls(jsonb_build_object(
|
|
9637
9925
|
'kind', 'capacity', 'pool', 'runner',
|
|
9638
9926
|
'label', 'a concurrency slot', 'limit', ${limitSql},
|
|
9927
|
+
'waitedMs', ${waitedMsSql},
|
|
9639
9928
|
'limitSource', CASE WHEN ${limitSql} IS NULL THEN NULL
|
|
9640
9929
|
WHEN requeued_run.launch_json->'concurrentRunsLimit' = to_jsonb(${limitSql})
|
|
9641
9930
|
THEN 'admission' ELSE 'workspace' END
|
|
@@ -9683,6 +9972,555 @@ export async function clearPostgresSandboxCapacityActivity(
|
|
|
9683
9972
|
return cleared.rows.length > 0;
|
|
9684
9973
|
}
|
|
9685
9974
|
|
|
9975
|
+
/**
|
|
9976
|
+
* `runs.recovery_json` key for a queued run's wait for an org sandbox slot:
|
|
9977
|
+
* `{ seq, sinceMs, checkedAtMs, wokenAtMs, queue, activitySeq, activityLimit }`
|
|
9978
|
+
* while the run waits, and `{ seq, admittedAtMs }` once it is admitted, so the
|
|
9979
|
+
* next waiters count it against the limit until its lease exists. `seq` only
|
|
9980
|
+
* grows, so every wait names a fresh Absurd event and step.
|
|
9981
|
+
*/
|
|
9982
|
+
export const SANDBOX_CAPACITY_WAIT_RECOVERY_KEY = 'sandboxCapacityWait';
|
|
9983
|
+
|
|
9984
|
+
/**
|
|
9985
|
+
* A run waiting for an org sandbox slot is parked on an Absurd event, not
|
|
9986
|
+
* polled. A lease release wakes the org's oldest live waiter; the fallback
|
|
9987
|
+
* timer only covers a lost wake (an expired, never-bound lease, or a schema
|
|
9988
|
+
* without the release trigger).
|
|
9989
|
+
*/
|
|
9990
|
+
export const SANDBOX_CAPACITY_WAIT_POLICY = {
|
|
9991
|
+
/** Fallback timer: a quarter of the time waited so far, clamped. */
|
|
9992
|
+
minFallbackSeconds: 30,
|
|
9993
|
+
maxFallbackSeconds: 300,
|
|
9994
|
+
fallbackDivisor: 4,
|
|
9995
|
+
/** A fallback re-check records liveness at most this often. */
|
|
9996
|
+
livenessRefreshMs: 60_000,
|
|
9997
|
+
/**
|
|
9998
|
+
* A waiter re-checks at least every `maxFallbackSeconds`. One silent for
|
|
9999
|
+
* this long has lost its engine task, so neither fairness nor a wake waits
|
|
10000
|
+
* for it.
|
|
10001
|
+
*/
|
|
10002
|
+
liveWaiterMs: 15 * 60_000,
|
|
10003
|
+
/** The next wake passes over a waiter woken this recently. */
|
|
10004
|
+
wakeClaimMs: 30_000,
|
|
10005
|
+
/** At most this many waiters are woken by one admission or refusal. */
|
|
10006
|
+
maxChainWakes: 10,
|
|
10007
|
+
} as const;
|
|
10008
|
+
|
|
10009
|
+
export function sandboxCapacityWaitFallbackSeconds(waitedMs: number): number {
|
|
10010
|
+
const policy = SANDBOX_CAPACITY_WAIT_POLICY;
|
|
10011
|
+
const seconds = Math.ceil(
|
|
10012
|
+
Math.max(0, waitedMs) / policy.fallbackDivisor / 1_000,
|
|
10013
|
+
);
|
|
10014
|
+
return Math.min(
|
|
10015
|
+
policy.maxFallbackSeconds,
|
|
10016
|
+
Math.max(policy.minFallbackSeconds, seconds),
|
|
10017
|
+
);
|
|
10018
|
+
}
|
|
10019
|
+
|
|
10020
|
+
/** Queue-scoped and first-emit-wins, so each wait gets its own `seq`. */
|
|
10021
|
+
export function sandboxCapacityWakeEventName(
|
|
10022
|
+
runId: string,
|
|
10023
|
+
seq: number,
|
|
10024
|
+
): string {
|
|
10025
|
+
return `sandbox-capacity-slot:${runId}:${seq}`;
|
|
10026
|
+
}
|
|
10027
|
+
|
|
10028
|
+
const SANDBOX_CAPACITY_WAIT_SINCE_SQL = `{${SANDBOX_CAPACITY_WAIT_RECOVERY_KEY},sinceMs}`;
|
|
10029
|
+
|
|
10030
|
+
/** Matches the partial index; keep the predicate text identical. */
|
|
10031
|
+
function sandboxCapacityWaiterSql(alias: string): string {
|
|
10032
|
+
return `${alias}.status = 'queued'
|
|
10033
|
+
AND (${alias}.recovery_json -> '${SANDBOX_CAPACITY_WAIT_RECOVERY_KEY}') IS NOT NULL
|
|
10034
|
+
AND (${alias}.recovery_json #>> '${SANDBOX_CAPACITY_WAIT_SINCE_SQL}') IS NOT NULL`;
|
|
10035
|
+
}
|
|
10036
|
+
|
|
10037
|
+
/**
|
|
10038
|
+
* A run admitted from a wait in the last `wakeClaimMs` that holds no live
|
|
10039
|
+
* lease yet: it is on its way to its reservation and occupies a slot.
|
|
10040
|
+
*/
|
|
10041
|
+
function sandboxCapacityAdmittedInFlightSql(
|
|
10042
|
+
alias: string,
|
|
10043
|
+
nowMsSql: string,
|
|
10044
|
+
options?: Pick<PostgresSchedulerOptions, 'schema'>,
|
|
10045
|
+
): string {
|
|
10046
|
+
return `${alias}.status IN ('queued', 'running')
|
|
10047
|
+
AND (${alias}.recovery_json -> '${SANDBOX_CAPACITY_WAIT_RECOVERY_KEY}') IS NOT NULL
|
|
10048
|
+
AND coalesce((${alias}.recovery_json #>> '{${SANDBOX_CAPACITY_WAIT_RECOVERY_KEY},admittedAtMs}')::bigint, 0)
|
|
10049
|
+
>= ${nowMsSql} - ${SANDBOX_CAPACITY_WAIT_POLICY.wakeClaimMs}::bigint
|
|
10050
|
+
AND NOT EXISTS (
|
|
10051
|
+
SELECT 1 FROM ${tableName('runtime_sandbox_capacity_leases', options)} AS in_flight_lease
|
|
10052
|
+
WHERE in_flight_lease.run_id = ${alias}.run_id
|
|
10053
|
+
AND in_flight_lease.released_at IS NULL
|
|
10054
|
+
AND (in_flight_lease.sandbox_id IS NOT NULL OR in_flight_lease.expires_at > clock_timestamp())
|
|
10055
|
+
)`;
|
|
10056
|
+
}
|
|
10057
|
+
|
|
10058
|
+
function sandboxCapacityWaiterLiveSql(alias: string, nowMsSql: string): string {
|
|
10059
|
+
const field = (name: string) =>
|
|
10060
|
+
`coalesce((${alias}.recovery_json #>> '{${SANDBOX_CAPACITY_WAIT_RECOVERY_KEY},${name}}')::bigint, 0)`;
|
|
10061
|
+
// Only the waiter's own writes prove its task is alive; a wake is written
|
|
10062
|
+
// by whoever freed the slot.
|
|
10063
|
+
return `greatest(${field('sinceMs')}, ${field('checkedAtMs')})
|
|
10064
|
+
>= ${nowMsSql} - ${SANDBOX_CAPACITY_WAIT_POLICY.liveWaiterMs}::bigint`;
|
|
10065
|
+
}
|
|
10066
|
+
|
|
10067
|
+
export type PostgresSchedulerSandboxCapacityGate =
|
|
10068
|
+
/** The old in-attempt reservation decides: this run is not a fresh start. */
|
|
10069
|
+
| { kind: 'bypass'; reason: 'not_queued' | 'holds_lease' }
|
|
10070
|
+
| {
|
|
10071
|
+
kind: 'admitted';
|
|
10072
|
+
limit: number;
|
|
10073
|
+
activeLeases: number;
|
|
10074
|
+
/** Time this run waited before admission; null when it never waited. */
|
|
10075
|
+
waitedMs: number | null;
|
|
10076
|
+
}
|
|
10077
|
+
| {
|
|
10078
|
+
kind: 'waiting';
|
|
10079
|
+
limit: number;
|
|
10080
|
+
activeLeases: number;
|
|
10081
|
+
/** Live waiters in this org created before this run. */
|
|
10082
|
+
ahead: number;
|
|
10083
|
+
/** Null only when a concurrent writer raced the streak start. */
|
|
10084
|
+
seq: number | null;
|
|
10085
|
+
sinceMs: number;
|
|
10086
|
+
};
|
|
10087
|
+
|
|
10088
|
+
/**
|
|
10089
|
+
* Pre-claim, read-mostly sandbox-capacity gate for a queued run's fresh
|
|
10090
|
+
* attempt. A full org returns `waiting` without allocating an attempt row or
|
|
10091
|
+
* touching any attempt of the run; the caller parks the engine task on
|
|
10092
|
+
* `sandboxCapacityWakeEventName(runId, seq)`. Admission is advisory: the
|
|
10093
|
+
* in-attempt reservation stays the authority, and a race it loses defers
|
|
10094
|
+
* through `deferPostgresSchedulerAttemptForCapacity`, which continues this
|
|
10095
|
+
* same wait. Writes happen only when a wait starts, at most once a minute on
|
|
10096
|
+
* a fallback re-check, and when it ends. Ending a wait moves the pre-code and
|
|
10097
|
+
* post-code recovery deadlines and the pacing start forward by the time
|
|
10098
|
+
* waited, so a capacity wait never spends a recovery or pacing horizon.
|
|
10099
|
+
*/
|
|
10100
|
+
export async function gatePostgresSchedulerSandboxCapacity(
|
|
10101
|
+
client: PostgresSchedulerQueryClient,
|
|
10102
|
+
input: {
|
|
10103
|
+
runId: string;
|
|
10104
|
+
orgId: string;
|
|
10105
|
+
/** The launch-carried `play.concurrent_runs` entitlement, if any. */
|
|
10106
|
+
entitlementLimit: number | null;
|
|
10107
|
+
defaultLimit: number;
|
|
10108
|
+
/** The Absurd queue whose task will await the wake. */
|
|
10109
|
+
queueName: string;
|
|
10110
|
+
nowMs: number;
|
|
10111
|
+
/**
|
|
10112
|
+
* The caller's wait on this `seq` timed out. Absurd ends a later wait on
|
|
10113
|
+
* the same event at once, so a still-waiting run moves to a fresh `seq`.
|
|
10114
|
+
*/
|
|
10115
|
+
retireSeq?: number;
|
|
10116
|
+
},
|
|
10117
|
+
options?: Pick<PostgresSchedulerOptions, 'schema'>,
|
|
10118
|
+
): Promise<PostgresSchedulerSandboxCapacityGate> {
|
|
10119
|
+
const runs = tableName('runs', options);
|
|
10120
|
+
const leases = tableName('runtime_sandbox_capacity_leases', options);
|
|
10121
|
+
const cache = tableName('runtime_org_sandbox_limit_cache', options);
|
|
10122
|
+
const key = SANDBOX_CAPACITY_WAIT_RECOVERY_KEY;
|
|
10123
|
+
const observed = await client.query<{
|
|
10124
|
+
status: string;
|
|
10125
|
+
wait: {
|
|
10126
|
+
seq?: number;
|
|
10127
|
+
sinceMs?: number | null;
|
|
10128
|
+
checkedAtMs?: number | null;
|
|
10129
|
+
wokenAtMs?: number | null;
|
|
10130
|
+
queue?: string | null;
|
|
10131
|
+
activitySeq?: number | null;
|
|
10132
|
+
activityLimit?: number | null;
|
|
10133
|
+
} | null;
|
|
10134
|
+
limit: number;
|
|
10135
|
+
active_leases: number;
|
|
10136
|
+
holds_lease: boolean;
|
|
10137
|
+
ahead: number;
|
|
10138
|
+
admitted_in_flight: number;
|
|
10139
|
+
}>(
|
|
10140
|
+
`
|
|
10141
|
+
WITH me AS MATERIALIZED (
|
|
10142
|
+
SELECT run.status, run.created_at, run.recovery_json -> '${key}' AS wait
|
|
10143
|
+
FROM ${runs} AS run
|
|
10144
|
+
WHERE run.run_id = $1
|
|
10145
|
+
)
|
|
10146
|
+
SELECT me.status, me.wait,
|
|
10147
|
+
coalesce(
|
|
10148
|
+
(SELECT override."limit" FROM ${cache} AS override
|
|
10149
|
+
WHERE override.org_id = $2
|
|
10150
|
+
AND override.expires_at IS NOT NULL
|
|
10151
|
+
AND override.expires_at > clock_timestamp()),
|
|
10152
|
+
$3::integer,
|
|
10153
|
+
(SELECT CASE
|
|
10154
|
+
WHEN cached.expires_at IS NOT NULL AND cached.expires_at <= clock_timestamp()
|
|
10155
|
+
THEN $4::integer
|
|
10156
|
+
ELSE cached."limit"
|
|
10157
|
+
END
|
|
10158
|
+
FROM ${cache} AS cached WHERE cached.org_id = $2),
|
|
10159
|
+
$4::integer
|
|
10160
|
+
) AS "limit",
|
|
10161
|
+
(SELECT count(*)::integer FROM ${leases} AS lease
|
|
10162
|
+
WHERE lease.org_id = $2
|
|
10163
|
+
AND lease.released_at IS NULL
|
|
10164
|
+
AND (lease.sandbox_id IS NOT NULL OR lease.expires_at > clock_timestamp())
|
|
10165
|
+
) AS active_leases,
|
|
10166
|
+
EXISTS (
|
|
10167
|
+
SELECT 1 FROM ${leases} AS own
|
|
10168
|
+
WHERE own.run_id = $1
|
|
10169
|
+
AND own.released_at IS NULL
|
|
10170
|
+
AND (own.sandbox_id IS NOT NULL OR own.expires_at > clock_timestamp())
|
|
10171
|
+
) AS holds_lease,
|
|
10172
|
+
(SELECT count(*)::integer FROM ${runs} AS waiter
|
|
10173
|
+
WHERE waiter.org_id = $2
|
|
10174
|
+
AND ${sandboxCapacityWaiterSql('waiter')}
|
|
10175
|
+
AND waiter.run_id <> $1
|
|
10176
|
+
AND ${sandboxCapacityWaiterLiveSql('waiter', '$5::bigint')}
|
|
10177
|
+
AND (waiter.created_at, waiter.run_id) < (me.created_at, $1::text)
|
|
10178
|
+
) AS ahead,
|
|
10179
|
+
(SELECT count(*)::integer FROM ${runs} AS admitted
|
|
10180
|
+
WHERE admitted.org_id = $2
|
|
10181
|
+
AND admitted.run_id <> $1
|
|
10182
|
+
AND ${sandboxCapacityAdmittedInFlightSql('admitted', '$5::bigint', options)}
|
|
10183
|
+
) AS admitted_in_flight
|
|
10184
|
+
FROM me
|
|
10185
|
+
`,
|
|
10186
|
+
[
|
|
10187
|
+
input.runId,
|
|
10188
|
+
input.orgId,
|
|
10189
|
+
input.entitlementLimit,
|
|
10190
|
+
input.defaultLimit,
|
|
10191
|
+
input.nowMs,
|
|
10192
|
+
],
|
|
10193
|
+
);
|
|
10194
|
+
const row = observed.rows[0];
|
|
10195
|
+
if (!row || row.status !== 'queued') {
|
|
10196
|
+
return { kind: 'bypass', reason: 'not_queued' };
|
|
10197
|
+
}
|
|
10198
|
+
if (row.holds_lease) return { kind: 'bypass', reason: 'holds_lease' };
|
|
10199
|
+
const limit = Number(row.limit);
|
|
10200
|
+
const activeLeases = Number(row.active_leases);
|
|
10201
|
+
const ahead = Number(row.ahead);
|
|
10202
|
+
const admittedInFlight = Number(row.admitted_in_flight);
|
|
10203
|
+
const wait = row.wait;
|
|
10204
|
+
const waitingSinceMs =
|
|
10205
|
+
wait?.sinceMs === null || wait?.sinceMs === undefined
|
|
10206
|
+
? null
|
|
10207
|
+
: Number(wait.sinceMs);
|
|
10208
|
+
// Runs admitted moments ago hold no lease yet but are about to.
|
|
10209
|
+
const occupied = activeLeases + admittedInFlight;
|
|
10210
|
+
const slotsAfterOlderWaiters = limit - occupied - ahead;
|
|
10211
|
+
|
|
10212
|
+
if (slotsAfterOlderWaiters >= 1) {
|
|
10213
|
+
const waitedMs =
|
|
10214
|
+
waitingSinceMs === null
|
|
10215
|
+
? null
|
|
10216
|
+
: await endPostgresSchedulerSandboxCapacityWait(
|
|
10217
|
+
client,
|
|
10218
|
+
{ runId: input.runId, nowMs: input.nowMs },
|
|
10219
|
+
options,
|
|
10220
|
+
);
|
|
10221
|
+
if (slotsAfterOlderWaiters > 1) {
|
|
10222
|
+
await wakePostgresSchedulerSandboxCapacityWaiters(
|
|
10223
|
+
client,
|
|
10224
|
+
{ orgId: input.orgId, maxWakes: slotsAfterOlderWaiters - 1 },
|
|
10225
|
+
options,
|
|
10226
|
+
);
|
|
10227
|
+
}
|
|
10228
|
+
return { kind: 'admitted', limit, activeLeases, waitedMs };
|
|
10229
|
+
}
|
|
10230
|
+
|
|
10231
|
+
// Slots are free but owed to older waiters: make sure they are awake.
|
|
10232
|
+
if (limit - occupied >= 1) {
|
|
10233
|
+
await wakePostgresSchedulerSandboxCapacityWaiters(
|
|
10234
|
+
client,
|
|
10235
|
+
{ orgId: input.orgId, maxWakes: limit - occupied },
|
|
10236
|
+
options,
|
|
10237
|
+
);
|
|
10238
|
+
}
|
|
10239
|
+
|
|
10240
|
+
if (waitingSinceMs === null) {
|
|
10241
|
+
const started = await client.query<{ seq: number | string | null }>(
|
|
10242
|
+
`
|
|
10243
|
+
WITH requeued_run AS (
|
|
10244
|
+
UPDATE ${runs} AS run
|
|
10245
|
+
SET recovery_json = coalesce(run.recovery_json, '{}'::jsonb)
|
|
10246
|
+
|| jsonb_build_object('${key}', jsonb_build_object(
|
|
10247
|
+
'seq', coalesce((run.recovery_json #>> '{${key},seq}')::integer, 0) + 1,
|
|
10248
|
+
'sinceMs', $2::bigint,
|
|
10249
|
+
'checkedAtMs', $2::bigint,
|
|
10250
|
+
'queue', $3::text,
|
|
10251
|
+
'activitySeq', coalesce((run.recovery_json #>> '{${key},seq}')::integer, 0) + 1,
|
|
10252
|
+
'activityLimit', $4::integer
|
|
10253
|
+
)),
|
|
10254
|
+
updated_at = now()
|
|
10255
|
+
WHERE run.run_id = $1
|
|
10256
|
+
AND run.status = 'queued'
|
|
10257
|
+
AND (run.recovery_json #>> '${SANDBOX_CAPACITY_WAIT_SINCE_SQL}') IS NULL
|
|
10258
|
+
RETURNING run.run_id, run.launch_json, run.recovery_json
|
|
10259
|
+
), sandbox_capacity_activity AS (
|
|
10260
|
+
INSERT INTO ${tableName('outbox', options)} (
|
|
10261
|
+
event_id, run_id, event_type, payload_json, created_at
|
|
10262
|
+
)
|
|
10263
|
+
SELECT 'run-sandbox-capacity:' || requeued_run.run_id || ':wait-'
|
|
10264
|
+
|| (requeued_run.recovery_json #>> '{${key},seq}'),
|
|
10265
|
+
requeued_run.run_id,
|
|
10266
|
+
${RUN_SCHEDULER_OUTBOX_EVENT_TYPE_SQL_LITERAL.runEvents},
|
|
10267
|
+
jsonb_build_object('events', jsonb_build_array(
|
|
10268
|
+
${sandboxCapacityActivityEventSql("jsonb_build_object('kind', 'queued', 'reason', 'capacity')", '$4::integer', '$2::bigint')}
|
|
10269
|
+
)),
|
|
10270
|
+
${causalOutboxCreatedAt('requeued_run.run_id', options)}
|
|
10271
|
+
FROM requeued_run
|
|
10272
|
+
ON CONFLICT (event_id) DO NOTHING
|
|
10273
|
+
RETURNING event_id
|
|
10274
|
+
)
|
|
10275
|
+
SELECT (requeued_run.recovery_json #>> '{${key},seq}')::integer AS seq
|
|
10276
|
+
FROM requeued_run
|
|
10277
|
+
LEFT JOIN (SELECT count(*) FROM sandbox_capacity_activity) AS published ON true
|
|
10278
|
+
`,
|
|
10279
|
+
[input.runId, input.nowMs, input.queueName, limit],
|
|
10280
|
+
);
|
|
10281
|
+
const seq = started.rows[0]?.seq;
|
|
10282
|
+
return {
|
|
10283
|
+
kind: 'waiting',
|
|
10284
|
+
limit,
|
|
10285
|
+
activeLeases,
|
|
10286
|
+
ahead,
|
|
10287
|
+
seq: seq === null || seq === undefined ? null : Number(seq),
|
|
10288
|
+
sinceMs: input.nowMs,
|
|
10289
|
+
};
|
|
10290
|
+
}
|
|
10291
|
+
|
|
10292
|
+
let seq = Number(wait?.seq ?? 0);
|
|
10293
|
+
const lastSeenMs = Math.max(
|
|
10294
|
+
waitingSinceMs,
|
|
10295
|
+
Number(wait?.checkedAtMs ?? 0),
|
|
10296
|
+
Number(wait?.wokenAtMs ?? 0),
|
|
10297
|
+
);
|
|
10298
|
+
const retire = input.retireSeq !== undefined && input.retireSeq === seq;
|
|
10299
|
+
// Woken but refused again: it is back in line, so the next release must
|
|
10300
|
+
// wake it again rather than pass over it as already on its way.
|
|
10301
|
+
const rewaitAfterWake =
|
|
10302
|
+
wait?.wokenAtMs !== null && wait?.wokenAtMs !== undefined;
|
|
10303
|
+
// A wait this gate published republishes its activity once per limit change.
|
|
10304
|
+
const limitChanged =
|
|
10305
|
+
wait?.activitySeq !== null &&
|
|
10306
|
+
wait?.activitySeq !== undefined &&
|
|
10307
|
+
Number(wait.activityLimit) !== limit;
|
|
10308
|
+
if (
|
|
10309
|
+
retire ||
|
|
10310
|
+
rewaitAfterWake ||
|
|
10311
|
+
limitChanged ||
|
|
10312
|
+
wait?.queue !== input.queueName ||
|
|
10313
|
+
input.nowMs - lastSeenMs >= SANDBOX_CAPACITY_WAIT_POLICY.livenessRefreshMs
|
|
10314
|
+
) {
|
|
10315
|
+
// Liveness for fairness and wakes, the queue a wake must name, the
|
|
10316
|
+
// current limit, and a fresh event after a timed-out wait. The seq
|
|
10317
|
+
// compare loses to a concurrent wake, which has already advanced it.
|
|
10318
|
+
const refreshed = await client.query<{ seq: number | string }>(
|
|
10319
|
+
`
|
|
10320
|
+
WITH current_wait AS MATERIALIZED (
|
|
10321
|
+
SELECT run.run_id, run.recovery_json -> '${key}' AS wait
|
|
10322
|
+
FROM ${runs} AS run
|
|
10323
|
+
WHERE run.run_id = $1
|
|
10324
|
+
AND run.status = 'queued'
|
|
10325
|
+
AND (run.recovery_json #>> '${SANDBOX_CAPACITY_WAIT_SINCE_SQL}') IS NOT NULL
|
|
10326
|
+
FOR UPDATE OF run
|
|
10327
|
+
), requeued_run AS (
|
|
10328
|
+
UPDATE ${runs} AS run
|
|
10329
|
+
SET recovery_json = jsonb_set(
|
|
10330
|
+
run.recovery_json, '{${key}}',
|
|
10331
|
+
(current_wait.wait - 'wokenAtMs') || jsonb_build_object(
|
|
10332
|
+
'checkedAtMs', $2::bigint,
|
|
10333
|
+
'queue', $3::text,
|
|
10334
|
+
'seq', coalesce((current_wait.wait ->> 'seq')::integer, 0)
|
|
10335
|
+
+ CASE WHEN $4::integer IS NOT NULL
|
|
10336
|
+
AND coalesce((current_wait.wait ->> 'seq')::integer, 0) = $4::integer
|
|
10337
|
+
THEN 1 ELSE 0 END
|
|
10338
|
+
) || CASE WHEN current_wait.wait ? 'activitySeq'
|
|
10339
|
+
THEN jsonb_build_object('activityLimit', $5::integer)
|
|
10340
|
+
ELSE '{}'::jsonb
|
|
10341
|
+
END
|
|
10342
|
+
),
|
|
10343
|
+
updated_at = now()
|
|
10344
|
+
FROM current_wait
|
|
10345
|
+
WHERE run.run_id = current_wait.run_id
|
|
10346
|
+
RETURNING run.run_id, run.launch_json, run.recovery_json,
|
|
10347
|
+
current_wait.wait AS prior_wait
|
|
10348
|
+
), sandbox_capacity_activity AS (
|
|
10349
|
+
INSERT INTO ${tableName('outbox', options)} (
|
|
10350
|
+
event_id, run_id, event_type, payload_json, created_at
|
|
10351
|
+
)
|
|
10352
|
+
SELECT 'run-sandbox-capacity:' || requeued_run.run_id || ':wait-'
|
|
10353
|
+
|| (requeued_run.prior_wait ->> 'activitySeq')
|
|
10354
|
+
|| ':limit-' || $5::text || ':' || $2::text,
|
|
10355
|
+
requeued_run.run_id,
|
|
10356
|
+
${RUN_SCHEDULER_OUTBOX_EVENT_TYPE_SQL_LITERAL.runEvents},
|
|
10357
|
+
jsonb_build_object('events', jsonb_build_array(
|
|
10358
|
+
${sandboxCapacityActivityEventSql("jsonb_build_object('kind', 'queued', 'reason', 'capacity')", '$5::integer', '$2::bigint')}
|
|
10359
|
+
)),
|
|
10360
|
+
${causalOutboxCreatedAt('requeued_run.run_id', options)}
|
|
10361
|
+
FROM requeued_run
|
|
10362
|
+
WHERE requeued_run.prior_wait ? 'activitySeq'
|
|
10363
|
+
AND (requeued_run.prior_wait -> 'activityLimit') IS DISTINCT FROM to_jsonb($5::integer)
|
|
10364
|
+
ON CONFLICT (event_id) DO NOTHING
|
|
10365
|
+
RETURNING event_id
|
|
10366
|
+
)
|
|
10367
|
+
SELECT (requeued_run.recovery_json #>> '{${key},seq}')::integer AS seq
|
|
10368
|
+
FROM requeued_run
|
|
10369
|
+
LEFT JOIN (SELECT count(*) FROM sandbox_capacity_activity) AS published ON true
|
|
10370
|
+
`,
|
|
10371
|
+
[
|
|
10372
|
+
input.runId,
|
|
10373
|
+
input.nowMs,
|
|
10374
|
+
input.queueName,
|
|
10375
|
+
retire ? input.retireSeq : null,
|
|
10376
|
+
limit,
|
|
10377
|
+
],
|
|
10378
|
+
);
|
|
10379
|
+
const refreshedSeq = refreshed.rows[0]?.seq;
|
|
10380
|
+
if (refreshedSeq !== undefined) seq = Number(refreshedSeq);
|
|
10381
|
+
}
|
|
10382
|
+
return {
|
|
10383
|
+
kind: 'waiting',
|
|
10384
|
+
limit,
|
|
10385
|
+
activeLeases,
|
|
10386
|
+
ahead,
|
|
10387
|
+
seq,
|
|
10388
|
+
sinceMs: waitingSinceMs,
|
|
10389
|
+
};
|
|
10390
|
+
}
|
|
10391
|
+
|
|
10392
|
+
/**
|
|
10393
|
+
* End a run's sandbox-capacity wait: keep its `seq`, clear the rest, publish
|
|
10394
|
+
* the cleared activity for a wait this gate published, and move the recovery
|
|
10395
|
+
* deadlines and pacing start forward by the time waited. Returns the time
|
|
10396
|
+
* waited, or null when the run was not waiting.
|
|
10397
|
+
*/
|
|
10398
|
+
async function endPostgresSchedulerSandboxCapacityWait(
|
|
10399
|
+
client: PostgresSchedulerQueryClient,
|
|
10400
|
+
input: { runId: string; nowMs: number },
|
|
10401
|
+
options?: Pick<PostgresSchedulerOptions, 'schema'>,
|
|
10402
|
+
): Promise<number | null> {
|
|
10403
|
+
const key = SANDBOX_CAPACITY_WAIT_RECOVERY_KEY;
|
|
10404
|
+
const shifted = (path: string) =>
|
|
10405
|
+
`CASE WHEN jsonb_typeof(waiting.recovery_json #> '{${path}}') = 'number'
|
|
10406
|
+
THEN to_jsonb((waiting.recovery_json #>> '{${path}}')::bigint + waiting.waited_ms)
|
|
10407
|
+
END`;
|
|
10408
|
+
const ended = await client.query<{ waited_ms: string | number }>(
|
|
10409
|
+
`
|
|
10410
|
+
WITH waiting AS MATERIALIZED (
|
|
10411
|
+
-- An attempt allocated after the wait began (a gate that failed open,
|
|
10412
|
+
-- a bypass, or an older release) ended that wait: count from it.
|
|
10413
|
+
SELECT run.run_id, run.recovery_json,
|
|
10414
|
+
greatest(0, $2::bigint - greatest(
|
|
10415
|
+
(run.recovery_json #>> '${SANDBOX_CAPACITY_WAIT_SINCE_SQL}')::bigint,
|
|
10416
|
+
coalesce((
|
|
10417
|
+
SELECT floor(extract(epoch FROM max(attempt.created_at)) * 1000)::bigint
|
|
10418
|
+
FROM ${tableName('attempts', options)} AS attempt
|
|
10419
|
+
WHERE attempt.run_id = run.run_id
|
|
10420
|
+
), 0)
|
|
10421
|
+
)) AS waited_ms
|
|
10422
|
+
FROM ${tableName('runs', options)} AS run
|
|
10423
|
+
WHERE run.run_id = $1
|
|
10424
|
+
AND run.status = 'queued'
|
|
10425
|
+
AND (run.recovery_json #>> '${SANDBOX_CAPACITY_WAIT_SINCE_SQL}') IS NOT NULL
|
|
10426
|
+
FOR UPDATE OF run
|
|
10427
|
+
), requeued_run AS (
|
|
10428
|
+
UPDATE ${tableName('runs', options)} AS run
|
|
10429
|
+
SET recovery_json = (waiting.recovery_json - '${key}')
|
|
10430
|
+
|| jsonb_build_object(
|
|
10431
|
+
'${key}', jsonb_build_object(
|
|
10432
|
+
'seq', (waiting.recovery_json #>> '{${key},seq}')::integer,
|
|
10433
|
+
'admittedAtMs', $2::bigint
|
|
10434
|
+
),
|
|
10435
|
+
'sandboxCapacityWaitedMs',
|
|
10436
|
+
coalesce((waiting.recovery_json ->> 'sandboxCapacityWaitedMs')::bigint, 0)
|
|
10437
|
+
+ waiting.waited_ms,
|
|
10438
|
+
'sandboxCapacityAdmittedAtMs', $2::bigint
|
|
10439
|
+
)
|
|
10440
|
+
|| CASE WHEN jsonb_typeof(waiting.recovery_json #> '{postCode,deadlineAtMs}') = 'number'
|
|
10441
|
+
THEN jsonb_build_object('postCode',
|
|
10442
|
+
(waiting.recovery_json -> 'postCode')
|
|
10443
|
+
|| jsonb_build_object('deadlineAtMs', ${shifted('postCode,deadlineAtMs')}))
|
|
10444
|
+
ELSE '{}'::jsonb
|
|
10445
|
+
END
|
|
10446
|
+
-- Absent or non-numeric fields stay as they were.
|
|
10447
|
+
|| jsonb_strip_nulls(jsonb_build_object(
|
|
10448
|
+
'pacedSinceMs', ${shifted('pacedSinceMs')},
|
|
10449
|
+
'deadlineAtMs', ${shifted('deadlineAtMs')}
|
|
10450
|
+
)),
|
|
10451
|
+
updated_at = now()
|
|
10452
|
+
FROM waiting
|
|
10453
|
+
WHERE run.run_id = waiting.run_id
|
|
10454
|
+
RETURNING run.run_id, run.launch_json, waiting.recovery_json AS prior_recovery_json,
|
|
10455
|
+
waiting.waited_ms
|
|
10456
|
+
), sandbox_capacity_activity AS (
|
|
10457
|
+
INSERT INTO ${tableName('outbox', options)} (
|
|
10458
|
+
event_id, run_id, event_type, payload_json, created_at
|
|
10459
|
+
)
|
|
10460
|
+
SELECT 'run-sandbox-capacity-cleared:' || requeued_run.run_id || ':wait-'
|
|
10461
|
+
|| (requeued_run.prior_recovery_json #>> '{${key},activitySeq}'),
|
|
10462
|
+
requeued_run.run_id,
|
|
10463
|
+
${RUN_SCHEDULER_OUTBOX_EVENT_TYPE_SQL_LITERAL.runEvents},
|
|
10464
|
+
jsonb_build_object('events', jsonb_build_array(
|
|
10465
|
+
${sandboxCapacityActivityEventSql("jsonb_build_object('kind', 'completed')", `(requeued_run.prior_recovery_json #>> '{${key},activityLimit}')::integer`, '$2::bigint', 'requeued_run.waited_ms')}
|
|
10466
|
+
)),
|
|
10467
|
+
${causalOutboxCreatedAt('requeued_run.run_id', options)}
|
|
10468
|
+
FROM requeued_run
|
|
10469
|
+
WHERE (requeued_run.prior_recovery_json #>> '{${key},activitySeq}') IS NOT NULL
|
|
10470
|
+
ON CONFLICT (event_id) DO NOTHING
|
|
10471
|
+
RETURNING event_id
|
|
10472
|
+
)
|
|
10473
|
+
SELECT requeued_run.waited_ms
|
|
10474
|
+
FROM requeued_run
|
|
10475
|
+
LEFT JOIN (SELECT count(*) FROM sandbox_capacity_activity) AS published ON true
|
|
10476
|
+
`,
|
|
10477
|
+
[input.runId, input.nowMs],
|
|
10478
|
+
);
|
|
10479
|
+
const waited = ended.rows[0]?.waited_ms;
|
|
10480
|
+
return waited === undefined ? null : Number(waited);
|
|
10481
|
+
}
|
|
10482
|
+
|
|
10483
|
+
/**
|
|
10484
|
+
* Wake up to `maxWakes` of the org's oldest live sandbox-capacity waiters
|
|
10485
|
+
* that were not woken in the last `wakeClaimMs`. Best effort: a wake is only
|
|
10486
|
+
* a hint, and every waiter also has a fallback timer. Returns how many were
|
|
10487
|
+
* woken, or null when the schema lacks the wake function.
|
|
10488
|
+
*/
|
|
10489
|
+
export async function wakePostgresSchedulerSandboxCapacityWaiters(
|
|
10490
|
+
client: PostgresSchedulerQueryClient,
|
|
10491
|
+
input: { orgId: string; maxWakes: number },
|
|
10492
|
+
options?: Pick<PostgresSchedulerOptions, 'schema'>,
|
|
10493
|
+
): Promise<number | null> {
|
|
10494
|
+
const maxWakes = Math.min(
|
|
10495
|
+
SANDBOX_CAPACITY_WAIT_POLICY.maxChainWakes,
|
|
10496
|
+
Math.max(0, Math.floor(input.maxWakes)),
|
|
10497
|
+
);
|
|
10498
|
+
if (maxWakes === 0) return 0;
|
|
10499
|
+
const quotedSchema = quoteIdent(schemaName(options));
|
|
10500
|
+
try {
|
|
10501
|
+
const woken = await client.query<{ woken: number | null }>(
|
|
10502
|
+
`SELECT CASE
|
|
10503
|
+
WHEN to_regprocedure($1) IS NULL THEN NULL
|
|
10504
|
+
ELSE ${quotedSchema}.runtime_sandbox_capacity_wake_waiters($2::text, $3::integer)
|
|
10505
|
+
END AS woken`,
|
|
10506
|
+
[
|
|
10507
|
+
`${quotedSchema}.runtime_sandbox_capacity_wake_waiters(text, integer)`,
|
|
10508
|
+
input.orgId,
|
|
10509
|
+
maxWakes,
|
|
10510
|
+
],
|
|
10511
|
+
);
|
|
10512
|
+
const value = woken.rows[0]?.woken;
|
|
10513
|
+
return value === null || value === undefined ? null : Number(value);
|
|
10514
|
+
} catch (error) {
|
|
10515
|
+
console.warn('[runtime.scheduler.sandbox_capacity_wake_failed]', {
|
|
10516
|
+
orgId: input.orgId,
|
|
10517
|
+
maxWakes,
|
|
10518
|
+
error: error instanceof Error ? error.message : String(error),
|
|
10519
|
+
});
|
|
10520
|
+
return null;
|
|
10521
|
+
}
|
|
10522
|
+
}
|
|
10523
|
+
|
|
9686
10524
|
/** `error_json.kind` stamped on an attempt retired by an executor-token
|
|
9687
10525
|
* outage. Consecutive attempts carrying it form one bounded outage. */
|
|
9688
10526
|
export const EXECUTOR_TOKEN_UNAVAILABLE_ATTEMPT_ERROR_KIND =
|
|
@@ -9730,6 +10568,16 @@ export async function deferPostgresSchedulerAttemptForExecutorTokenOutage(
|
|
|
9730
10568
|
WHERE prior.run_id = $1
|
|
9731
10569
|
AND prior.attempt < $2
|
|
9732
10570
|
AND prior.error_json ->> 'kind' = $6
|
|
10571
|
+
-- Time waiting for a sandbox slot is not outage time: a tail
|
|
10572
|
+
-- from before the run's last capacity admission ends there.
|
|
10573
|
+
AND prior.created_at >= coalesce((
|
|
10574
|
+
SELECT to_timestamp(
|
|
10575
|
+
(waited.recovery_json ->> 'sandboxCapacityAdmittedAtMs')::double precision / 1000
|
|
10576
|
+
)
|
|
10577
|
+
FROM custody_runs AS waited
|
|
10578
|
+
WHERE waited.run_id = $1
|
|
10579
|
+
AND jsonb_typeof(waited.recovery_json -> 'sandboxCapacityAdmittedAtMs') = 'number'
|
|
10580
|
+
), '-infinity'::timestamptz)
|
|
9733
10581
|
AND NOT EXISTS (
|
|
9734
10582
|
SELECT 1
|
|
9735
10583
|
FROM ${tableName('attempts', options)} AS gap
|
|
@@ -13909,7 +14757,10 @@ export async function readPostgresSchedulerComputeBillingObligationForOrg(
|
|
|
13909
14757
|
}
|
|
13910
14758
|
const unsettledCount = Number(row.unsettled_count);
|
|
13911
14759
|
const blockedCount = Number(row.blocked_count);
|
|
13912
|
-
if (
|
|
14760
|
+
if (
|
|
14761
|
+
!Number.isSafeInteger(unsettledCount) ||
|
|
14762
|
+
!Number.isSafeInteger(blockedCount)
|
|
14763
|
+
) {
|
|
13913
14764
|
throw new Error('Compute billing obligation read returned invalid counts.');
|
|
13914
14765
|
}
|
|
13915
14766
|
if (unsettledCount === 0) return { state: 'settled' };
|