deepline 0.3.285 → 0.3.286

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.
Files changed (33) hide show
  1. package/dist/bundling-sources/sdk/src/client.ts +1 -2
  2. package/dist/bundling-sources/sdk/src/release.ts +1 -1
  3. package/dist/bundling-sources/shared_libs/play-runtime/context.ts +21 -0
  4. package/dist/bundling-sources/shared_libs/play-runtime/play-runs/sandbox-cleanup/job.ts +18 -0
  5. package/dist/bundling-sources/shared_libs/play-runtime/play-runtime-semantics.ts +16 -0
  6. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/absurd-runtime-worker.ts +9 -0
  7. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/postgres.ts +240 -89
  8. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/runtime-sandbox-capacity.ts +40 -7
  9. package/dist/bundling-sources/shared_libs/play-runtime/test-async-batching.ts +4 -1
  10. package/dist/bundling-sources/shared_libs/play-runtime/tool-result.ts +68 -0
  11. package/dist/bundling-sources/shared_libs/plays/authoring-contract.ts +10 -1
  12. package/dist/bundling-sources/shared_libs/plays/enrich-compat-adapter.ts +2 -0
  13. package/dist/cli/index.js +30130 -33940
  14. package/dist/cli/index.mjs +30166 -33987
  15. package/dist/{client-T2jVnZrq.d.ts → client-B7ic-kY5.d.ts} +2 -3
  16. package/dist/{client-Cl-zj2oS.d.mts → client-Dzf_KovW.d.mts} +2 -3
  17. package/dist/{compiler-manifest-B1zo3igW.d.mts → compiler-manifest-9SQtUuKb.d.mts} +1 -1
  18. package/dist/{compiler-manifest-B1zo3igW.d.ts → compiler-manifest-9SQtUuKb.d.ts} +1 -1
  19. package/dist/index.d.mts +4 -4
  20. package/dist/index.d.ts +4 -4
  21. package/dist/index.js +10 -4
  22. package/dist/index.mjs +10 -4
  23. package/dist/install-integrity.json +4 -4
  24. package/dist/plays/bundle-play-file.d.mts +2 -2
  25. package/dist/plays/bundle-play-file.d.ts +2 -2
  26. package/dist/plays/bundle-play-file.mjs +8 -1
  27. package/dist/plays/run-request.d.mts +2 -2
  28. package/dist/plays/run-request.d.ts +2 -2
  29. package/dist/release.d.mts +1 -1
  30. package/dist/release.d.ts +1 -1
  31. package/dist/release.js +1 -1
  32. package/dist/release.mjs +1 -1
  33. package/package.json +1 -1
@@ -7400,7 +7400,7 @@ export async function markPostgresSchedulerAttemptWaiting(
7400
7400
  );
7401
7401
  const waiting = await client.query<{ run_id: string; event_id: string }>(
7402
7402
  `
7403
- WITH waiting_attempt AS (
7403
+ WITH ${runtimeSandboxCustodyLocksSql('run.run_id = $1', options)}, waiting_attempt AS (
7404
7404
  UPDATE ${tableName('attempts', options)}
7405
7405
  SET status = 'waiting',
7406
7406
  resource_json = CASE
@@ -7436,6 +7436,7 @@ export async function markPostgresSchedulerAttemptWaiting(
7436
7436
  END,
7437
7437
  heartbeat_at = CASE WHEN $8::boolean THEN heartbeat_at ELSE now() END,
7438
7438
  updated_at = now()
7439
+ FROM (SELECT count(*) FROM custody_attempts) AS attempt_locks
7439
7440
  WHERE run_id = $1
7440
7441
  AND attempt = $2
7441
7442
  AND status = 'running'
@@ -8164,13 +8165,14 @@ export async function deferPostgresSchedulerAttemptForCapacity(
8164
8165
  ): Promise<boolean> {
8165
8166
  const deferred = await client.query<{ run_id: string }>(
8166
8167
  `
8167
- WITH deferred_attempt AS (
8168
+ WITH ${runtimeSandboxCustodyLocksSql('run.run_id = $1', options)}, deferred_attempt AS (
8168
8169
  UPDATE ${tableName('attempts', options)}
8169
8170
  SET status = 'stale',
8170
8171
  lease_expires_at = NULL,
8171
8172
  heartbeat_at = now(),
8172
8173
  error_json = $4::jsonb,
8173
8174
  updated_at = now()
8175
+ FROM (SELECT count(*) FROM custody_attempts) AS attempt_locks
8174
8176
  WHERE run_id = $1
8175
8177
  AND attempt = $2
8176
8178
  AND status IN ('claimed', 'running', 'waiting')
@@ -8232,9 +8234,9 @@ export async function deferPostgresSchedulerAttemptForExecutorTokenOutage(
8232
8234
  deferred: boolean;
8233
8235
  }>(
8234
8236
  `
8235
- WITH current_attempt AS (
8237
+ WITH ${runtimeSandboxCustodyLocksSql('run.run_id = $1', options)}, current_attempt AS (
8236
8238
  SELECT created_at
8237
- FROM ${tableName('attempts', options)}
8239
+ FROM custody_attempts
8238
8240
  WHERE run_id = $1
8239
8241
  AND attempt = $2
8240
8242
  AND lease_token = $3
@@ -8267,6 +8269,7 @@ export async function deferPostgresSchedulerAttemptForExecutorTokenOutage(
8267
8269
  heartbeat_at = now(),
8268
8270
  error_json = $4::jsonb,
8269
8271
  updated_at = now()
8272
+ FROM (SELECT count(*) FROM custody_attempts) AS attempt_locks
8270
8273
  WHERE run_id = $1
8271
8274
  AND attempt = $2
8272
8275
  AND status IN ('claimed', 'running')
@@ -8326,10 +8329,10 @@ export async function claimPostgresSchedulerWaitingDetachedAttemptForTerminal(
8326
8329
  ): Promise<boolean> {
8327
8330
  const claimed = await client.query<{ run_id: string }>(
8328
8331
  `
8329
- WITH candidate AS MATERIALIZED (
8332
+ WITH ${runtimeSandboxCustodyLocksSql('run.run_id = $1', options)}, candidate AS MATERIALIZED (
8330
8333
  SELECT runs.run_id, attempts.attempt
8331
- FROM ${tableName('runs', options)} AS runs
8332
- JOIN ${tableName('attempts', options)} AS attempts
8334
+ FROM custody_runs AS runs
8335
+ JOIN custody_attempts AS attempts
8333
8336
  ON attempts.run_id = runs.run_id
8334
8337
  AND attempts.attempt = (runs.suspension_json ->> 'runnerAttempt')::integer
8335
8338
  WHERE runs.run_id = $1
@@ -8349,7 +8352,6 @@ export async function claimPostgresSchedulerWaitingDetachedAttemptForTerminal(
8349
8352
  AND newer.attempt > attempts.attempt
8350
8353
  AND newer.status IN ('claimed', 'running', 'waiting', 'completed', 'failed')
8351
8354
  )
8352
- FOR UPDATE OF runs, attempts
8353
8355
  ),
8354
8356
  running_attempt AS (
8355
8357
  UPDATE ${tableName('attempts', options)} AS target
@@ -8588,19 +8590,18 @@ export async function deferPostgresSchedulerAttemptForRecovery(
8588
8590
  deadline_at_ms: string | null;
8589
8591
  }>(
8590
8592
  `
8591
- WITH candidate AS (
8593
+ WITH ${runtimeSandboxCustodyLocksSql('run.run_id = $1', options)}, candidate AS (
8592
8594
  SELECT runs.run_id,
8593
8595
  runs.recovery_json,
8594
8596
  attempts.run_id AS attempt_run_id
8595
- FROM ${tableName('runs', options)} AS runs
8596
- JOIN ${tableName('attempts', options)} AS attempts
8597
+ FROM custody_runs AS runs
8598
+ JOIN custody_attempts AS attempts
8597
8599
  ON attempts.run_id = runs.run_id
8598
8600
  WHERE attempts.run_id = $1
8599
8601
  AND attempts.attempt = $2
8600
8602
  AND attempts.lease_token = $3
8601
8603
  AND attempts.status IN ('claimed', 'running', 'waiting')
8602
8604
  AND runs.status IN ('queued', 'running', 'waiting')
8603
- FOR UPDATE OF runs, attempts
8604
8605
  ), computed AS (
8605
8606
  SELECT run_id,
8606
8607
  coalesce((recovery_json ->> 'deferCount')::integer, 0) + 1
@@ -9322,20 +9323,24 @@ export async function recordPostgresSchedulerManagedSandboxOperationLive(
9322
9323
  'production';
9323
9324
  const recorded = await client.query<{ operation_key: string }>(
9324
9325
  `
9325
- WITH eligible_attempt AS (
9326
+ WITH ${runtimeSandboxCustodyLocksSql('run.run_id = $1', options)}, eligible_attempt AS (
9326
9327
  SELECT run_id
9327
- FROM ${tableName('attempts', options)}
9328
+ FROM custody_attempts
9328
9329
  WHERE run_id = $1
9329
9330
  AND attempt = $2
9330
9331
  AND lease_token = $3
9331
9332
  AND status IN ('claimed', 'running', 'waiting')
9333
+ AND EXISTS (SELECT 1 FROM custody_runs WHERE status IN ('queued', 'running', 'waiting'))
9334
+ AND NOT EXISTS (SELECT 1 FROM custody_attempts AS newer WHERE newer.attempt > $2)
9332
9335
  ), eligible_lease AS MATERIALIZED (
9333
9336
  SELECT lease_id
9334
- FROM ${tableName('runtime_sandbox_capacity_leases', options)}
9337
+ FROM custody_leases
9338
+ CROSS JOIN (SELECT count(*) FROM custody_operations) AS operation_locks
9335
9339
  WHERE lease_id = $5
9340
+ AND run_id = $1 AND provider = $10
9341
+ AND (sandbox_id IS NULL OR (sandbox_id = $6 AND routing_domain IS NOT DISTINCT FROM $7))
9336
9342
  AND released_at IS NULL
9337
9343
  AND expires_at > clock_timestamp()
9338
- FOR UPDATE
9339
9344
  ), live_operation AS (
9340
9345
  UPDATE ${tableName('runtime_sandbox_operations', options)} AS operation
9341
9346
  SET sandbox_id = $6,
@@ -9378,7 +9383,6 @@ export async function recordPostgresSchedulerManagedSandboxOperationLive(
9378
9383
  JOIN recorded_attempt ON TRUE
9379
9384
  WHERE lease.lease_id = live_operation.operation_key
9380
9385
  AND lease.released_at IS NULL
9381
- AND lease.expires_at > clock_timestamp()
9382
9386
  RETURNING lease.lease_id
9383
9387
  )
9384
9388
  SELECT live_operation.operation_key
@@ -9413,42 +9417,52 @@ export async function recordPostgresSchedulerManagedSandboxOperationLive(
9413
9417
  return false;
9414
9418
  }
9415
9419
  const updated = await client.query<{ run_id: string }>(
9416
- `UPDATE ${tableName('attempts', options)} AS attempt
9417
- SET resource_json = (
9418
- SELECT jsonb_agg(
9419
- CASE
9420
- WHEN resource->>'sandboxCapacityLeaseId' = $5
9421
- AND resource->>'sandboxId' = $6
9422
- AND resource->>'kind' = $4::jsonb->>'kind'
9423
- THEN resource || jsonb_build_object(
9424
- 'billingEndedAt', $4::jsonb->'billingEndedAt'
9425
- )
9426
- ELSE resource
9427
- END ORDER BY ordinal
9428
- )
9429
- FROM jsonb_array_elements(attempt.resource_json)
9430
- WITH ORDINALITY AS resources(resource, ordinal)
9431
- ),
9432
- updated_at = clock_timestamp()
9433
- FROM ${tableName('runtime_sandbox_operations', options)} AS operation
9434
- JOIN ${tableName('runtime_sandbox_capacity_leases', options)} AS lease
9435
- ON lease.lease_id = operation.operation_key
9436
- WHERE attempt.run_id = $1
9437
- AND attempt.attempt = $2
9438
- AND attempt.lease_token = $3
9439
- AND attempt.status IN ('claimed', 'running', 'waiting')
9440
- AND operation.operation_key = $5
9441
- AND operation.run_id = attempt.run_id
9442
- AND operation.attempt = attempt.attempt
9443
- AND operation.sandbox_id = $6
9444
- AND operation.provider = $7
9445
- AND operation.state = $8
9446
- AND operation.environment = $9
9447
- AND operation.routing_domain IS NOT DISTINCT FROM $10
9448
- AND lease.sandbox_id = $6
9449
- AND lease.released_at IS NULL
9450
- AND lease.expires_at > clock_timestamp()
9451
- RETURNING attempt.run_id`,
9420
+ `WITH ${runtimeSandboxCustodyLocksSql('run.run_id = $1', options)}, eligible_retirement AS MATERIALIZED (
9421
+ SELECT operation.operation_key, operation.run_id, operation.attempt
9422
+ FROM custody_operations AS operation
9423
+ JOIN custody_attempts AS attempt ON attempt.run_id = operation.run_id AND attempt.attempt = operation.attempt
9424
+ JOIN custody_leases AS lease ON lease.lease_id = operation.operation_key
9425
+ WHERE attempt.run_id = $1 AND attempt.attempt = $2 AND attempt.lease_token = $3
9426
+ AND attempt.status IN ('claimed', 'running', 'waiting')
9427
+ AND NOT EXISTS (SELECT 1 FROM custody_attempts AS newer WHERE newer.attempt > $2)
9428
+ AND EXISTS (SELECT 1 FROM custody_runs WHERE status IN ('queued', 'running', 'waiting'))
9429
+ AND operation.operation_key = $5 AND operation.sandbox_id = $6
9430
+ AND operation.provider = $7 AND operation.state IN ($8, 'deleting')
9431
+ AND operation.environment = $9 AND operation.routing_domain IS NOT DISTINCT FROM $10
9432
+ AND lease.sandbox_id = $6 AND lease.released_at IS NULL
9433
+ AND EXISTS (
9434
+ SELECT 1 FROM jsonb_array_elements(attempt.resource_json) AS fact
9435
+ WHERE fact->>'sandboxCapacityLeaseId' = $5 AND fact->>'sandboxId' = $6
9436
+ AND fact->>'kind' = $4::jsonb->>'kind'
9437
+ )
9438
+ ), retiring_operation AS (
9439
+ UPDATE ${tableName('runtime_sandbox_operations', options)} AS operation
9440
+ SET state = 'deleting', updated_at = clock_timestamp()
9441
+ FROM eligible_retirement
9442
+ WHERE operation.operation_key = eligible_retirement.operation_key
9443
+ RETURNING operation.operation_key
9444
+ ), closed_resource AS (
9445
+ UPDATE ${tableName('attempts', options)} AS attempt
9446
+ SET resource_json = (
9447
+ SELECT jsonb_agg(
9448
+ CASE
9449
+ WHEN resource->>'sandboxCapacityLeaseId' = $5 AND resource->>'sandboxId' = $6
9450
+ AND resource->>'kind' = $4::jsonb->>'kind'
9451
+ AND (resource->'billingEndedAt' IS NULL OR resource->'billingEndedAt' = 'null'::jsonb)
9452
+ THEN resource || jsonb_build_object('billingEndedAt', $4::jsonb->'billingEndedAt')
9453
+ ELSE resource END ORDER BY ordinal
9454
+ ) FROM jsonb_array_elements(attempt.resource_json) WITH ORDINALITY AS resources(resource, ordinal)
9455
+ ), updated_at = clock_timestamp()
9456
+ FROM retiring_operation
9457
+ WHERE attempt.run_id = $1 AND attempt.attempt = $2 AND attempt.lease_token = $3
9458
+ RETURNING attempt.run_id
9459
+ ), queued AS (
9460
+ INSERT INTO ${tableName('sandbox_cleanup_jobs_v2', options)} (
9461
+ provider, sandbox_id, run_id, attempt, environment, routing_domain
9462
+ ) SELECT $7, $6, $1, $2, $9, $10 FROM closed_resource
9463
+ ON CONFLICT (provider, sandbox_id, routing_domain_key) DO NOTHING
9464
+ )
9465
+ SELECT run_id FROM closed_resource`,
9452
9466
  [
9453
9467
  input.runId,
9454
9468
  input.attempt,
@@ -9492,14 +9506,17 @@ export async function readPostgresSchedulerManagedSandboxOperationAlreadyLive(
9492
9506
  operationKey: string;
9493
9507
  provider: RuntimeSandboxProvider;
9494
9508
  sandboxId: string;
9509
+ environment?: 'preview' | 'production';
9510
+ routingDomain?: string | null;
9495
9511
  },
9496
9512
  options?: Pick<PostgresSchedulerOptions, 'schema'>,
9497
9513
  ): Promise<boolean> {
9498
9514
  const found = await client.query<{ operation_key: string }>(
9499
9515
  `
9516
+ WITH ${runtimeSandboxCustodyLocksSql('run.run_id = $1', options)}
9500
9517
  SELECT operation.operation_key
9501
- FROM ${tableName('runtime_sandbox_operations', options)} AS operation
9502
- JOIN ${tableName('attempts', options)} AS attempt
9518
+ FROM custody_operations AS operation
9519
+ JOIN custody_attempts AS attempt
9503
9520
  ON attempt.run_id = operation.run_id
9504
9521
  AND attempt.attempt = operation.attempt
9505
9522
  WHERE operation.operation_key = $4
@@ -9508,8 +9525,12 @@ export async function readPostgresSchedulerManagedSandboxOperationAlreadyLive(
9508
9525
  AND operation.provider = $5
9509
9526
  AND operation.state = $6
9510
9527
  AND operation.sandbox_id = $7
9528
+ AND ($8::text IS NULL OR operation.environment = $8)
9529
+ AND (NOT $9::boolean OR operation.routing_domain IS NOT DISTINCT FROM $10::text)
9511
9530
  AND attempt.lease_token = $3
9512
9531
  AND attempt.status IN ('claimed', 'running', 'waiting')
9532
+ AND NOT EXISTS (SELECT 1 FROM custody_attempts AS newer WHERE newer.attempt > $2)
9533
+ AND EXISTS (SELECT 1 FROM custody_runs WHERE status IN ('queued', 'running', 'waiting'))
9513
9534
  `,
9514
9535
  [
9515
9536
  input.runId,
@@ -9519,6 +9540,9 @@ export async function readPostgresSchedulerManagedSandboxOperationAlreadyLive(
9519
9540
  input.provider,
9520
9541
  RuntimeSandboxOperationState.Live,
9521
9542
  input.sandboxId,
9543
+ input.environment ?? null,
9544
+ input.routingDomain !== undefined,
9545
+ input.routingDomain?.trim() || null,
9522
9546
  ],
9523
9547
  );
9524
9548
  return found.rows.length === 1;
@@ -9671,9 +9695,10 @@ export async function resolvePostgresSchedulerAmbiguousModalCreateIntentFromProv
9671
9695
  ): Promise<boolean> {
9672
9696
  const resolved = await client.query<{ run_id: string }>(
9673
9697
  `
9674
- WITH resolved AS (
9698
+ WITH ${runtimeSandboxCustodyLocksSql('run.run_id = $1', options)}, resolved AS (
9675
9699
  UPDATE ${tableName('ambiguous_modal_creates', options)}
9676
9700
  SET status = 'resolved', resolved_at = clock_timestamp()
9701
+ FROM (SELECT count(*) FROM custody_operations) AS operation_locks
9677
9702
  WHERE run_id = $1
9678
9703
  AND attempt = $2
9679
9704
  AND modal_app_id = $3
@@ -9726,9 +9751,10 @@ export async function recordPostgresSchedulerReconciledModalResourcesForCleanup(
9726
9751
  const payload = stringifyPostgresJson(resources);
9727
9752
  const recorded = await client.query<{ run_id: string }>(
9728
9753
  `
9729
- WITH claimed_intent AS (
9754
+ WITH ${runtimeSandboxCustodyLocksSql('run.run_id = $1', options)}, claimed_intent AS (
9730
9755
  UPDATE ${tableName('ambiguous_modal_creates', options)}
9731
9756
  SET status = 'resolved', resolved_at = clock_timestamp()
9757
+ FROM (SELECT count(*) FROM custody_operations) AS operation_locks
9732
9758
  WHERE run_id = $1
9733
9759
  AND attempt = $2
9734
9760
  AND modal_app_id = $3
@@ -9951,16 +9977,16 @@ export async function recordPostgresSchedulerLateManagedSandboxOperationForClean
9951
9977
  'production';
9952
9978
  const result = await client.query<{ operation_key: string }>(
9953
9979
  `
9954
- WITH eligible_lease AS MATERIALIZED (
9980
+ WITH ${runtimeSandboxCustodyLocksSql('run.run_id = $1', options)}, eligible_lease AS MATERIALIZED (
9955
9981
  SELECT lease_id
9956
- FROM ${tableName('runtime_sandbox_capacity_leases', options)}
9982
+ FROM custody_leases
9983
+ CROSS JOIN (SELECT count(*) FROM custody_operations) AS operation_locks
9957
9984
  WHERE lease_id = $4
9958
9985
  AND released_at IS NULL
9959
9986
  AND expires_at > clock_timestamp()
9960
- FOR UPDATE
9961
9987
  ), eligible_attempt AS (
9962
9988
  SELECT run_id
9963
- FROM ${tableName('attempts', options)}
9989
+ FROM custody_attempts
9964
9990
  WHERE run_id = $1
9965
9991
  AND attempt = $2
9966
9992
  AND lease_token = $3
@@ -10215,12 +10241,14 @@ export async function settlePostgresSchedulerRuntimeResources(
10215
10241
  ): Promise<number> {
10216
10242
  const stamped = await client.query<{ run_id: string }>(
10217
10243
  `
10244
+ WITH ${runtimeSandboxCustodyLocksSql('run.run_id = $1', options)}
10218
10245
  UPDATE ${tableName('attempts', options)}
10219
10246
  SET resource_json = (
10220
10247
  SELECT COALESCE(
10221
10248
  jsonb_agg(
10222
10249
  CASE
10223
10250
  WHEN elem->>'kind' IN ('daytona_sandbox', 'modal_sandbox')
10251
+ AND NOT ${protectedManagedSandboxSql({ runId: '$1', provider: "(CASE elem->>'kind' WHEN 'modal_sandbox' THEN 'modal' ELSE 'daytona' END)", sandboxId: "elem->>'sandboxId'", routingDomain: "(CASE elem->>'kind' WHEN 'modal_sandbox' THEN NULLIF(elem->>'modalAppId', '') ELSE NULLIF(elem->>'daytonaOrganizationId', '') END)" }, options, true)}
10224
10252
  AND (
10225
10253
  elem->'billingEndedAt' IS NULL
10226
10254
  OR elem->'billingEndedAt' = 'null'::jsonb
@@ -10241,6 +10269,7 @@ export async function settlePostgresSchedulerRuntimeResources(
10241
10269
  FROM jsonb_array_elements(resource_json) AS elem
10242
10270
  ),
10243
10271
  updated_at = now()
10272
+ FROM (SELECT count(*) FROM custody_operations) AS operation_locks
10244
10273
  WHERE run_id = $1
10245
10274
  AND ($4::integer IS NULL OR attempt <= $4)
10246
10275
  AND resource_json IS NOT NULL
@@ -11539,6 +11568,79 @@ export async function completePostgresSchedulerComputeBillingSessionBootstrap(
11539
11568
  return completed.rows.length > 0;
11540
11569
  }
11541
11570
 
11571
+ function runtimeSandboxCustodyLocksSql(
11572
+ runPredicate: string,
11573
+ options?: Pick<PostgresSchedulerOptions, 'schema'>,
11574
+ skipLocked = false,
11575
+ ): string {
11576
+ return `custody_runs AS MATERIALIZED (
11577
+ SELECT run.* FROM ${tableName('runs', options)} AS run
11578
+ WHERE ${runPredicate}
11579
+ ORDER BY run.run_id FOR NO KEY UPDATE ${skipLocked ? 'SKIP LOCKED' : ''}
11580
+ ), custody_attempts AS MATERIALIZED (
11581
+ SELECT attempt.* FROM ${tableName('attempts', options)} AS attempt
11582
+ WHERE attempt.run_id IN (SELECT run_id FROM custody_runs)
11583
+ ORDER BY attempt.run_id, attempt.attempt FOR UPDATE
11584
+ ), custody_leases AS MATERIALIZED (
11585
+ SELECT lease.* FROM ${tableName('runtime_sandbox_capacity_leases', options)} AS lease
11586
+ CROSS JOIN (SELECT count(*) FROM custody_attempts) AS attempt_locks
11587
+ WHERE lease.run_id IN (SELECT run_id FROM custody_runs)
11588
+ ORDER BY lease.run_id, lease.lease_id FOR UPDATE OF lease
11589
+ ), custody_operations AS MATERIALIZED (
11590
+ SELECT operation.* FROM ${tableName('runtime_sandbox_operations', options)} AS operation
11591
+ CROSS JOIN (SELECT count(*) FROM custody_leases) AS lease_locks
11592
+ WHERE operation.run_id IN (SELECT run_id FROM custody_runs)
11593
+ ORDER BY operation.run_id, operation.operation_key FOR UPDATE OF operation
11594
+ )`;
11595
+ }
11596
+
11597
+ function protectedManagedSandboxSql(
11598
+ identity: {
11599
+ runId: string;
11600
+ provider: string;
11601
+ sandboxId: string;
11602
+ routingDomain: string;
11603
+ },
11604
+ options?: Pick<PostgresSchedulerOptions, 'schema'>,
11605
+ locked = false,
11606
+ ): string {
11607
+ const runs = locked ? 'custody_runs' : tableName('runs', options);
11608
+ const attempts = locked ? 'custody_attempts' : tableName('attempts', options);
11609
+ const operations = locked
11610
+ ? 'custody_operations'
11611
+ : tableName('runtime_sandbox_operations', options);
11612
+ const leases = locked
11613
+ ? 'custody_leases'
11614
+ : tableName('runtime_sandbox_capacity_leases', options);
11615
+ return `EXISTS (
11616
+ SELECT 1 FROM ${runs} AS managed_run
11617
+ JOIN ${operations} AS managed_operation ON managed_operation.run_id = managed_run.run_id
11618
+ JOIN ${leases} AS managed_lease ON managed_lease.lease_id = managed_operation.operation_key
11619
+ WHERE managed_run.run_id = ${identity.runId}
11620
+ AND managed_run.status IN ('queued', 'running', 'waiting')
11621
+ AND managed_operation.provider = ${identity.provider}
11622
+ AND COALESCE(managed_operation.sandbox_id, managed_lease.sandbox_id) = ${identity.sandboxId}
11623
+ AND COALESCE(managed_operation.routing_domain, managed_lease.routing_domain)
11624
+ IS NOT DISTINCT FROM ${identity.routingDomain}
11625
+ AND managed_lease.released_at IS NULL
11626
+ AND NOT EXISTS (SELECT 1 FROM ${tableName('control', options)} AS cancel
11627
+ WHERE cancel.key = 'runtime_cancel:' || managed_run.run_id)
11628
+ AND (
11629
+ (managed_operation.state = 'reserved' AND managed_lease.expires_at > clock_timestamp())
11630
+ OR (managed_operation.state = 'live' AND EXISTS (
11631
+ SELECT 1 FROM ${attempts} AS owner_attempt
11632
+ WHERE owner_attempt.run_id = managed_run.run_id
11633
+ AND owner_attempt.attempt = managed_operation.attempt
11634
+ AND owner_attempt.status IN ('claimed', 'running', 'waiting')
11635
+ AND owner_attempt.runner_result_json IS NULL
11636
+ AND NOT EXISTS (SELECT 1 FROM ${attempts} AS newer
11637
+ WHERE newer.run_id = owner_attempt.run_id AND newer.attempt > owner_attempt.attempt)
11638
+ AND (owner_attempt.lease_expires_at IS NULL OR owner_attempt.lease_expires_at > clock_timestamp())
11639
+ ))
11640
+ )
11641
+ )`;
11642
+ }
11643
+
11542
11644
  /** Deletion needs terminal/cancellation/retired-resource authority. An old
11543
11645
  * worker error (including a billing end) is not evidence the runner stopped. */
11544
11646
  function protectedDetachedSandboxSql(
@@ -11549,10 +11651,11 @@ function protectedDetachedSandboxSql(
11549
11651
  routingDomain: string;
11550
11652
  },
11551
11653
  options?: Pick<PostgresSchedulerOptions, 'schema'>,
11654
+ locked = false,
11552
11655
  ): string {
11553
- return `EXISTS (
11554
- SELECT 1 FROM ${tableName('runs', options)} AS detached_run
11555
- JOIN ${tableName('attempts', options)} AS detached_attempt
11656
+ return `(${protectedManagedSandboxSql(identity, options, locked)} OR EXISTS (
11657
+ SELECT 1 FROM ${locked ? 'custody_runs' : tableName('runs', options)} AS detached_run
11658
+ JOIN ${locked ? 'custody_attempts' : tableName('attempts', options)} AS detached_attempt
11556
11659
  ON detached_attempt.run_id = detached_run.run_id
11557
11660
  CROSS JOIN LATERAL jsonb_array_elements(
11558
11661
  CASE WHEN jsonb_typeof(detached_attempt.resource_json) = 'array'
@@ -11580,18 +11683,19 @@ function protectedDetachedSandboxSql(
11580
11683
  AND detached_resource -> 'executionDetachedAt' IS NOT NULL
11581
11684
  AND detached_resource -> 'executionDetachedAt' <> 'null'::jsonb)
11582
11685
  )
11583
- AND NOT EXISTS (SELECT 1 FROM ${tableName('attempts', options)} AS newer
11686
+ AND NOT EXISTS (SELECT 1 FROM ${locked ? 'custody_attempts' : tableName('attempts', options)} AS newer
11584
11687
  WHERE newer.run_id = detached_run.run_id
11585
11688
  AND newer.attempt > detached_attempt.attempt
11586
11689
  AND newer.status IN ('claimed', 'running', 'waiting', 'completed', 'failed'))
11587
11690
  AND NOT EXISTS (SELECT 1 FROM ${tableName('control', options)} AS cancel
11588
11691
  WHERE cancel.key = 'runtime_cancel:' || detached_run.run_id)
11589
- )`;
11692
+ ))`;
11590
11693
  }
11591
11694
 
11592
11695
  function protectedDetachedResourceSql(
11593
11696
  runId: string,
11594
11697
  options?: Pick<PostgresSchedulerOptions, 'schema'>,
11698
+ locked = false,
11595
11699
  ): string {
11596
11700
  return protectedDetachedSandboxSql(
11597
11701
  {
@@ -11603,6 +11707,7 @@ function protectedDetachedResourceSql(
11603
11707
  "(CASE resource->>'kind' WHEN 'modal_sandbox' THEN NULLIF(resource->>'modalAppId', '') ELSE NULLIF(resource->>'daytonaOrganizationId', '') END)",
11604
11708
  },
11605
11709
  options,
11710
+ locked,
11606
11711
  );
11607
11712
  }
11608
11713
 
@@ -11632,9 +11737,10 @@ export async function enqueuePostgresSchedulerSandboxCleanupForAttempt(
11632
11737
  ): Promise<number> {
11633
11738
  const enqueued = await client.query<{ sandbox_id: string }>(
11634
11739
  `
11635
- WITH attempt_resources AS (
11740
+ WITH ${runtimeSandboxCustodyLocksSql('run.run_id = $1', options)}, attempt_resources AS (
11636
11741
  SELECT run_id, attempt, resource_json
11637
- FROM ${tableName('attempts', options)}
11742
+ FROM custody_attempts
11743
+ CROSS JOIN (SELECT count(*) FROM custody_operations) AS operation_locks
11638
11744
  WHERE run_id = $1
11639
11745
  AND attempt = $2
11640
11746
  AND resource_json IS NOT NULL
@@ -11669,7 +11775,7 @@ export async function enqueuePostgresSchedulerSandboxCleanupForAttempt(
11669
11775
  ) AS resource
11670
11776
  WHERE resource->>'kind' IN ('daytona_sandbox', 'modal_sandbox')
11671
11777
  AND NULLIF(resource->>'sandboxId', '') IS NOT NULL
11672
- AND NOT ${protectedDetachedResourceSql('$1', options)}
11778
+ AND NOT ${protectedDetachedResourceSql('$1', options, true)}
11673
11779
  ON CONFLICT (provider, sandbox_id, routing_domain_key) DO NOTHING
11674
11780
  RETURNING sandbox_id
11675
11781
  )
@@ -11689,6 +11795,7 @@ export async function enqueuePostgresSchedulerSandboxCleanupForRun(
11689
11795
  ): Promise<void> {
11690
11796
  await client.query(
11691
11797
  `
11798
+ WITH ${runtimeSandboxCustodyLocksSql('run.run_id = $1', options)}
11692
11799
  INSERT INTO ${tableName('sandbox_cleanup_jobs_v2', options)} (
11693
11800
  provider, sandbox_id, run_id, attempt, environment, routing_domain
11694
11801
  )
@@ -11709,7 +11816,8 @@ export async function enqueuePostgresSchedulerSandboxCleanupForRun(
11709
11816
  WHEN 'modal_sandbox' THEN NULLIF(resource->>'modalAppId', '')
11710
11817
  ELSE NULLIF(resource->>'daytonaOrganizationId', '')
11711
11818
  END
11712
- FROM ${tableName('attempts', options)} AS attempt
11819
+ FROM custody_attempts AS attempt
11820
+ CROSS JOIN (SELECT count(*) FROM custody_operations) AS operation_locks
11713
11821
  CROSS JOIN LATERAL jsonb_array_elements(
11714
11822
  CASE
11715
11823
  WHEN jsonb_typeof(attempt.resource_json) = 'array'
@@ -11722,16 +11830,16 @@ export async function enqueuePostgresSchedulerSandboxCleanupForRun(
11722
11830
  AND attempt.resource_json IS NOT NULL
11723
11831
  AND resource->>'kind' IN ('daytona_sandbox', 'modal_sandbox')
11724
11832
  AND NULLIF(resource->>'sandboxId', '') IS NOT NULL
11725
- AND NOT ${protectedDetachedResourceSql('$1', options)}
11833
+ AND NOT ${protectedDetachedResourceSql('$1', options, true)}
11726
11834
  UNION ALL
11727
11835
  SELECT operation.provider, operation.sandbox_id, operation.run_id,
11728
11836
  operation.attempt, operation.environment, operation.routing_domain
11729
- FROM ${tableName('runtime_sandbox_operations', options)} AS operation
11837
+ FROM custody_operations AS operation
11730
11838
  WHERE operation.run_id = $1
11731
11839
  AND ($2::integer IS NULL OR operation.attempt <= $2)
11732
11840
  AND operation.state IN ('live', 'deleting')
11733
11841
  AND operation.sandbox_id IS NOT NULL
11734
- AND NOT ${protectedDetachedSandboxSql({ runId: 'operation.run_id', provider: 'operation.provider', sandboxId: 'operation.sandbox_id', routingDomain: 'operation.routing_domain' }, options)}
11842
+ AND NOT ${protectedDetachedSandboxSql({ runId: 'operation.run_id', provider: 'operation.provider', sandboxId: 'operation.sandbox_id', routingDomain: 'operation.routing_domain' }, options, true)}
11735
11843
  ON CONFLICT (provider, sandbox_id, routing_domain_key) DO NOTHING
11736
11844
  `,
11737
11845
  [input.runId, input.throughAttempt ?? null],
@@ -11746,9 +11854,10 @@ export async function abandonUnstartedModalCancellationReservations(
11746
11854
  options?: Pick<PostgresSchedulerOptions, 'schema'>,
11747
11855
  ): Promise<void> {
11748
11856
  await client.query(
11749
- `WITH abandoned AS (
11857
+ `WITH ${runtimeSandboxCustodyLocksSql('run.run_id = $1', options)}, abandoned AS (
11750
11858
  UPDATE ${tableName('runtime_sandbox_operations', options)} AS operation
11751
11859
  SET state = 'abandoned', updated_at = clock_timestamp()
11860
+ FROM (SELECT count(*) FROM custody_operations) AS operation_locks
11752
11861
  WHERE operation.run_id = $1
11753
11862
  AND operation.provider = 'modal'
11754
11863
  AND operation.state = 'reserved'
@@ -11890,7 +11999,21 @@ export async function claimPostgresSchedulerSandboxCleanupJobs(
11890
11999
  diagnostic_json: unknown | null;
11891
12000
  }>(
11892
12001
  `
11893
- WITH candidates AS (
12002
+ WITH candidate_jobs AS MATERIALIZED (
12003
+ SELECT cleanup.provider, cleanup.sandbox_id, cleanup.routing_domain_key, cleanup.run_id
12004
+ FROM ${tableName('sandbox_cleanup_jobs_v2', options)} AS cleanup
12005
+ WHERE cleanup.status <> 'deleted' AND cleanup.blocked_at IS NULL
12006
+ AND (cleanup.available_at <= now() OR cleanup.diagnostic_json IS NOT NULL)
12007
+ AND (cleanup.lease_expires_at IS NULL OR cleanup.lease_expires_at <= now())
12008
+ AND ($4::text IS NULL OR cleanup.environment = $4)
12009
+ AND ($5::text[] IS NULL OR cleanup.provider = ANY($5::text[]))
12010
+ AND ($8::text IS NULL OR cleanup.run_id = $8)
12011
+ AND ($9::integer IS NULL OR cleanup.attempt <= $9)
12012
+ AND NOT ${protectedDetachedSandboxSql({ runId: 'cleanup.run_id', provider: 'cleanup.provider', sandboxId: 'cleanup.sandbox_id', routingDomain: 'cleanup.routing_domain' }, options)}
12013
+ ORDER BY CASE WHEN cleanup.diagnostic_json IS NOT NULL THEN 0 ELSE 1 END,
12014
+ cleanup.available_at, cleanup.created_at, cleanup.provider, cleanup.sandbox_id, cleanup.routing_domain_key
12015
+ LIMIT $2
12016
+ ), ${runtimeSandboxCustodyLocksSql('EXISTS (SELECT 1 FROM candidate_jobs WHERE candidate_jobs.run_id = run.run_id)', options, true)}, candidates AS (
11894
12017
  SELECT
11895
12018
  cleanup.provider,
11896
12019
  cleanup.sandbox_id,
@@ -11898,9 +12021,14 @@ export async function claimPostgresSchedulerSandboxCleanupJobs(
11898
12021
  cleanup.routing_domain_key,
11899
12022
  run.status AS terminal_status
11900
12023
  FROM ${tableName('sandbox_cleanup_jobs_v2', options)} AS cleanup
11901
- JOIN ${tableName('runs', options)} AS run
12024
+ JOIN custody_runs AS run
11902
12025
  ON run.run_id = cleanup.run_id
11903
- WHERE cleanup.status <> 'deleted'
12026
+ CROSS JOIN (SELECT count(*) FROM custody_operations) AS operation_locks
12027
+ WHERE EXISTS (SELECT 1 FROM candidate_jobs AS selected
12028
+ WHERE selected.provider = cleanup.provider
12029
+ AND selected.sandbox_id = cleanup.sandbox_id
12030
+ AND selected.routing_domain_key = cleanup.routing_domain_key)
12031
+ AND cleanup.status <> 'deleted'
11904
12032
  AND cleanup.blocked_at IS NULL
11905
12033
  AND (
11906
12034
  cleanup.available_at <= now()
@@ -11911,7 +12039,7 @@ export async function claimPostgresSchedulerSandboxCleanupJobs(
11911
12039
  AND ($5::text[] IS NULL OR cleanup.provider = ANY($5::text[]))
11912
12040
  AND ($8::text IS NULL OR cleanup.run_id = $8)
11913
12041
  AND ($9::integer IS NULL OR cleanup.attempt <= $9)
11914
- AND NOT ${protectedDetachedSandboxSql({ runId: 'cleanup.run_id', provider: 'cleanup.provider', sandboxId: 'cleanup.sandbox_id', routingDomain: 'cleanup.routing_domain' }, options)}
12042
+ AND NOT ${protectedDetachedSandboxSql({ runId: 'cleanup.run_id', provider: 'cleanup.provider', sandboxId: 'cleanup.sandbox_id', routingDomain: 'cleanup.routing_domain' }, options, true)}
11915
12043
  ORDER BY
11916
12044
  CASE WHEN cleanup.diagnostic_json IS NOT NULL THEN 0 ELSE 1 END ASC,
11917
12045
  cleanup.available_at ASC,
@@ -11948,12 +12076,28 @@ export async function claimPostgresSchedulerSandboxCleanupJobs(
11948
12076
  operation_claimed AS (
11949
12077
  UPDATE ${tableName('runtime_sandbox_operations', options)} AS operation
11950
12078
  SET state = $6,
12079
+ sandbox_id = claimed.sandbox_id,
12080
+ routing_domain = claimed.routing_domain,
12081
+ provider_created_at = COALESCE(operation.provider_created_at, clock_timestamp()),
11951
12082
  updated_at = clock_timestamp()
11952
12083
  FROM claimed
11953
- WHERE operation.provider = claimed.provider
11954
- AND operation.sandbox_id = claimed.sandbox_id
11955
- AND operation.routing_domain IS NOT DISTINCT FROM claimed.routing_domain
11956
- AND operation.state = $7
12084
+ WHERE operation.run_id = claimed.run_id
12085
+ AND operation.provider = claimed.provider
12086
+ AND (
12087
+ (operation.state = $7
12088
+ AND operation.sandbox_id = claimed.sandbox_id
12089
+ AND operation.routing_domain IS NOT DISTINCT FROM claimed.routing_domain)
12090
+ OR (operation.state = 'reserved'
12091
+ AND operation.sandbox_id IS NULL
12092
+ AND EXISTS (
12093
+ SELECT 1 FROM custody_leases AS lease
12094
+ WHERE lease.lease_id = operation.operation_key
12095
+ AND lease.run_id = claimed.run_id
12096
+ AND lease.provider = claimed.provider
12097
+ AND lease.sandbox_id = claimed.sandbox_id
12098
+ AND lease.routing_domain IS NOT DISTINCT FROM claimed.routing_domain
12099
+ ))
12100
+ )
11957
12101
  RETURNING operation.operation_key
11958
12102
  ),
11959
12103
  claim_events AS (
@@ -12165,12 +12309,14 @@ export async function completePostgresSchedulerSandboxCleanupJob(
12165
12309
  > {
12166
12310
  const completed = await client.query<{ outcome: string }>(
12167
12311
  `
12168
- WITH current_job AS MATERIALIZED (
12312
+ WITH ${runtimeSandboxCustodyLocksSql('run.run_id = $3', options)}, current_job AS MATERIALIZED (
12169
12313
  SELECT status, attempt_count, lease_owner, routing_domain
12170
- FROM ${tableName('sandbox_cleanup_jobs_v2', options)}
12314
+ FROM ${tableName('sandbox_cleanup_jobs_v2', options)} AS sandbox_cleanup_jobs_v2
12315
+ CROSS JOIN (SELECT count(*) FROM custody_operations) AS operation_locks
12171
12316
  WHERE provider = $8
12172
12317
  AND sandbox_id = $1
12173
12318
  AND routing_domain IS NOT DISTINCT FROM $9
12319
+ FOR UPDATE OF sandbox_cleanup_jobs_v2
12174
12320
  ),
12175
12321
  completed AS (
12176
12322
  UPDATE ${tableName('sandbox_cleanup_jobs_v2', options)} AS target
@@ -12246,7 +12392,8 @@ export async function completePostgresSchedulerSandboxCleanupJob(
12246
12392
  SET resource_json = (
12247
12393
  SELECT jsonb_agg(
12248
12394
  CASE
12249
- WHEN resource->>'kind' = 'modal_sandbox'
12395
+ WHEN resource->>'kind' = CASE $8::text WHEN 'modal' THEN 'modal_sandbox' ELSE 'daytona_sandbox' END
12396
+ AND (CASE $8::text WHEN 'modal' THEN NULLIF(resource->>'modalAppId', '') ELSE NULLIF(resource->>'daytonaOrganizationId', '') END) IS NOT DISTINCT FROM $9::text
12250
12397
  AND resource->>'sandboxId' = $1
12251
12398
  AND resource->>'lateAcquired' = 'true'
12252
12399
  AND (
@@ -12287,7 +12434,8 @@ export async function completePostgresSchedulerSandboxCleanupJob(
12287
12434
  ELSE jsonb_build_array(attempt.resource_json)
12288
12435
  END
12289
12436
  ) AS candidate
12290
- WHERE candidate->>'kind' = 'modal_sandbox'
12437
+ WHERE candidate->>'kind' = CASE $8::text WHEN 'modal' THEN 'modal_sandbox' ELSE 'daytona_sandbox' END
12438
+ AND (CASE $8::text WHEN 'modal' THEN NULLIF(candidate->>'modalAppId', '') ELSE NULLIF(candidate->>'daytonaOrganizationId', '') END) IS NOT DISTINCT FROM $9::text
12291
12439
  AND candidate->>'sandboxId' = $1
12292
12440
  AND candidate->>'lateAcquired' = 'true'
12293
12441
  )
@@ -13014,7 +13162,7 @@ export async function completePostgresSchedulerAttempt(
13014
13162
  );
13015
13163
  const completed = await client.query<{ run_id: string }>(
13016
13164
  `
13017
- WITH completed AS (
13165
+ WITH ${runtimeSandboxCustodyLocksSql('run.run_id = $1', options)}, completed AS (
13018
13166
  UPDATE ${tableName('attempts', options)}
13019
13167
  SET status = 'completed',
13020
13168
  terminalization_mode = 'compatibility_wake',
@@ -13051,6 +13199,7 @@ export async function completePostgresSchedulerAttempt(
13051
13199
  )
13052
13200
  END,
13053
13201
  updated_at = now()
13202
+ FROM (SELECT count(*) FROM custody_attempts) AS attempt_locks
13054
13203
  WHERE run_id = $1
13055
13204
  AND attempt = $2
13056
13205
  AND status = 'running'
@@ -13291,7 +13440,7 @@ export async function failPostgresSchedulerAttempt(
13291
13440
  );
13292
13441
  const failed = await client.query<{ run_id: string }>(
13293
13442
  `
13294
- WITH failed AS (
13443
+ WITH ${runtimeSandboxCustodyLocksSql('run.run_id = $1', options)}, failed AS (
13295
13444
  UPDATE ${tableName('attempts', options)}
13296
13445
  SET status = 'failed',
13297
13446
  lease_expires_at = NULL,
@@ -13338,6 +13487,7 @@ export async function failPostgresSchedulerAttempt(
13338
13487
  )
13339
13488
  END,
13340
13489
  updated_at = now()
13490
+ FROM (SELECT count(*) FROM custody_attempts) AS attempt_locks
13341
13491
  WHERE run_id = $1
13342
13492
  AND attempt = $2
13343
13493
  AND status = 'running'
@@ -13625,7 +13775,7 @@ export async function cancelPostgresSchedulerRun(
13625
13775
  launch_json: PlaySchedulerSubmitInput;
13626
13776
  }>(
13627
13777
  `
13628
- WITH cancelled_run AS (
13778
+ WITH ${runtimeSandboxCustodyLocksSql('run.run_id = $1', options)}, cancelled_run AS (
13629
13779
  UPDATE ${tableName('runs', options)} AS target
13630
13780
  SET status = 'cancelled',
13631
13781
  terminal_result_json = NULL,
@@ -13634,6 +13784,7 @@ export async function cancelPostgresSchedulerRun(
13634
13784
  wait_deadline = NULL,
13635
13785
  finished_at = now(),
13636
13786
  updated_at = now()
13787
+ FROM (SELECT count(*) FROM custody_attempts) AS attempt_locks
13637
13788
  WHERE target.run_id = $1
13638
13789
  AND target.status IN ('queued', 'running', 'waiting')
13639
13790
  ${strandedEligibility}