deepline 0.3.527 → 0.3.528

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 (146) hide show
  1. package/dist/bundling-sources/sdk/src/release.ts +1 -1
  2. package/dist/bundling-sources/shared_libs/play-runtime/context.ts +141 -211
  3. package/dist/bundling-sources/shared_libs/play-runtime/ctx-types.ts +5 -0
  4. package/dist/bundling-sources/shared_libs/play-runtime/deployment/fly-machines.ts +66 -1
  5. package/dist/bundling-sources/shared_libs/play-runtime/freshness-receipt-execution.ts +135 -161
  6. package/dist/bundling-sources/shared_libs/play-runtime/play-run-recovery-policy.ts +56 -1
  7. package/dist/bundling-sources/shared_libs/play-runtime/play-runs/sandbox-cleanup/contracts.ts +11 -1
  8. package/dist/bundling-sources/shared_libs/play-runtime/play-runs/sandbox-cleanup/job.ts +36 -6
  9. package/dist/bundling-sources/shared_libs/play-runtime/runner-backends/backends/daytona-lifecycle.ts +35 -5
  10. package/dist/bundling-sources/shared_libs/play-runtime/runner-backends/backends/daytona-start-admission.ts +12 -0
  11. package/dist/bundling-sources/shared_libs/play-runtime/runner-backends/backends/daytona.ts +1 -0
  12. package/dist/bundling-sources/shared_libs/play-runtime/runner-backends/types.ts +16 -0
  13. package/dist/bundling-sources/shared_libs/play-runtime/runtime-capacity-policy.ts +25 -5
  14. package/dist/bundling-sources/shared_libs/play-runtime/runtime-telemetry.ts +6 -0
  15. package/dist/bundling-sources/shared_libs/play-runtime/sandbox-runs/runner-backend-adapter.ts +6 -0
  16. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/absurd-claim-loop-timing.ts +145 -0
  17. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/absurd-pool.ts +48 -5
  18. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/absurd-runtime-worker.ts +281 -66
  19. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/absurd-shared.ts +13 -5
  20. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/play-run-recovery.ts +30 -1
  21. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/postgres.ts +105 -13
  22. package/dist/bundling-sources/shared_libs/play-runtime/tool-call/result-receipt-policy.ts +10 -1
  23. package/dist/cli/auth-CWJZYLTB.js +43 -0
  24. package/dist/cli/{auth-LRMMQFJ4.mjs → auth-PPOTNK4T.mjs} +5 -5
  25. package/dist/cli/{billing-M76MMWZB.js → billing-3C7T7CUQ.js} +79 -79
  26. package/dist/cli/{billing-WZZDXVRJ.mjs → billing-OEZUQ2K6.mjs} +6 -6
  27. package/dist/cli/{chunk-R6IWWPY7.js → chunk-237PKFIQ.js} +14 -14
  28. package/dist/cli/{chunk-YSDPYQBH.js → chunk-36UD7H7Y.js} +41 -41
  29. package/dist/cli/{chunk-M45S7JAY.mjs → chunk-42ZSDTOC.mjs} +2 -2
  30. package/dist/cli/{chunk-YJ4YVFXC.js → chunk-4SBUXDKZ.js} +13 -13
  31. package/dist/cli/{chunk-HB3YUHEL.js → chunk-5MJ4CDAQ.js} +44 -44
  32. package/dist/cli/{chunk-UJHS2O5O.mjs → chunk-6OLQWQU5.mjs} +3 -3
  33. package/dist/cli/{chunk-EOL7PXLW.js → chunk-7WZXUAQW.js} +7 -7
  34. package/dist/cli/{chunk-YUYDP2EG.js → chunk-7X3NLHI7.js} +6 -6
  35. package/dist/cli/{chunk-XYG4IOJK.js → chunk-ADZGTMLU.js} +98 -98
  36. package/dist/cli/{chunk-MIL5YDKZ.mjs → chunk-AFIAVG5T.mjs} +2 -2
  37. package/dist/cli/{chunk-3L2DNG5X.js → chunk-B3HQF2CA.js} +11 -11
  38. package/dist/cli/{chunk-HA2J2OAS.mjs → chunk-B6YWCGVC.mjs} +10 -10
  39. package/dist/cli/{chunk-NVII3RWQ.mjs → chunk-CMTY6SVY.mjs} +2 -2
  40. package/dist/cli/{chunk-AXFHQWGA.mjs → chunk-DCVNL5XN.mjs} +1 -1
  41. package/dist/cli/{chunk-RTPLRMEB.mjs → chunk-FPHAUP55.mjs} +5 -5
  42. package/dist/cli/{chunk-JSEISVAZ.js → chunk-FXYWEKUK.js} +4 -4
  43. package/dist/cli/{chunk-HQZLTK3P.js → chunk-G7RTPKRJ.js} +2 -2
  44. package/dist/cli/{chunk-OKRBGXDI.js → chunk-GCBFSFLA.js} +5 -5
  45. package/dist/cli/{chunk-VTXBV4AX.mjs → chunk-GFGFAAY2.mjs} +1 -1
  46. package/dist/cli/{chunk-JSVHBJE2.mjs → chunk-GP7E4TE4.mjs} +2 -2
  47. package/dist/cli/{chunk-4YN7DZEA.mjs → chunk-GSBKODMU.mjs} +2 -2
  48. package/dist/cli/{chunk-RMCKTV4R.mjs → chunk-HJVNCRXY.mjs} +1 -1
  49. package/dist/cli/{chunk-7DPWGAOU.js → chunk-IJAEYEJM.js} +3 -3
  50. package/dist/cli/{chunk-VV2AFJ3I.mjs → chunk-IM5XQ4DG.mjs} +5 -5
  51. package/dist/cli/{chunk-XI47UAVU.js → chunk-IXEEXYE2.js} +9 -9
  52. package/dist/cli/{chunk-JEIGNX3G.mjs → chunk-IYCRX34W.mjs} +5 -5
  53. package/dist/cli/{chunk-ZHY7AY5V.js → chunk-KHVCHFE3.js} +16 -16
  54. package/dist/cli/{chunk-KDFUQRVU.mjs → chunk-KLGYBOGZ.mjs} +1 -1
  55. package/dist/cli/{chunk-UKOG6PCB.mjs → chunk-KWIKFR7Y.mjs} +1 -1
  56. package/dist/cli/{chunk-ETXQZGQU.js → chunk-LT4IEJ6V.js} +16 -16
  57. package/dist/cli/{chunk-RGL2YGJZ.js → chunk-LU4EA3ET.js} +2 -2
  58. package/dist/cli/{chunk-UAQ7ZWRP.js → chunk-MLNH4DK2.js} +22 -22
  59. package/dist/cli/{chunk-YKPMIJJ2.mjs → chunk-NCOTOGTK.mjs} +2 -2
  60. package/dist/cli/{chunk-MMM2WMTF.mjs → chunk-NZM4KWWV.mjs} +5 -5
  61. package/dist/cli/{chunk-C7A44BZ7.js → chunk-OEI7YUEF.js} +3 -3
  62. package/dist/cli/{chunk-LHMHUA5D.js → chunk-OGVUT2KM.js} +7 -7
  63. package/dist/cli/{chunk-OXHY3LD3.js → chunk-OVZSNBDJ.js} +53 -53
  64. package/dist/cli/{chunk-5YR6CDJ2.mjs → chunk-PS2UYVAE.mjs} +6 -6
  65. package/dist/cli/{chunk-66YLAQ2X.js → chunk-R5ZQVQ3K.js} +26 -26
  66. package/dist/cli/{chunk-QKY3H3HA.mjs → chunk-RC5CG5SE.mjs} +4 -4
  67. package/dist/cli/{chunk-SRQQAUXN.js → chunk-RFTBMEWL.js} +2 -2
  68. package/dist/cli/{chunk-P5ZU5ZHA.mjs → chunk-RML3VSTN.mjs} +1 -1
  69. package/dist/cli/{chunk-2L3HVEBM.mjs → chunk-SP2KZ7SH.mjs} +1 -1
  70. package/dist/cli/{chunk-QKKT5G4K.mjs → chunk-T4QPRL3P.mjs} +3 -3
  71. package/dist/cli/{chunk-GIRMVMXP.mjs → chunk-ULUI2FEM.mjs} +1 -1
  72. package/dist/cli/{chunk-3PQDEBO6.js → chunk-WXHBD6H7.js} +1 -1
  73. package/dist/cli/{chunk-OLSATEDQ.js → chunk-XD2DRBPH.js} +6 -6
  74. package/dist/cli/{chunk-77VNC2KF.mjs → chunk-Z25KC5V2.mjs} +1 -1
  75. package/dist/cli/{chunk-E4TEZE62.mjs → chunk-Z44S7VWO.mjs} +2 -2
  76. package/dist/cli/{chunk-2A6IRSE6.js → chunk-ZFD5FJCZ.js} +5 -5
  77. package/dist/cli/{csv-FEFNXZF7.mjs → csv-K7TRWOFJ.mjs} +4 -4
  78. package/dist/cli/{csv-IRP6VT7Q.js → csv-OTRVTHD2.js} +13 -13
  79. package/dist/cli/{db-IHECMWZ3.mjs → db-C7GQU3TZ.mjs} +6 -6
  80. package/dist/cli/{db-Y5VNPNRD.js → db-UO2ZFLFN.js} +27 -27
  81. package/dist/cli/describe-IK4UYJ5M.js +50 -0
  82. package/dist/cli/{describe-XCVC2WLL.mjs → describe-LG4CPTIV.mjs} +18 -18
  83. package/dist/cli/{executions-QH3KJ6MA.js → executions-LHFVPO7E.js} +8 -8
  84. package/dist/cli/{executions-3FWZYUJV.mjs → executions-P3INNVZE.mjs} +6 -6
  85. package/dist/cli/{feedback-F3OZXOPM.mjs → feedback-H22FWG63.mjs} +6 -6
  86. package/dist/cli/{feedback-BGHWMOLH.js → feedback-M3HZQAWX.js} +14 -14
  87. package/dist/cli/git-72ADWRUQ.js +25 -0
  88. package/dist/cli/{git-RWPH3D75.mjs → git-G2N7PVFI.mjs} +5 -5
  89. package/dist/cli/index.js +141 -141
  90. package/dist/cli/index.mjs +43 -43
  91. package/dist/cli/{legacy-noops-G6CYD5LM.js → legacy-noops-2RVROWBY.js} +9 -9
  92. package/dist/cli/{legacy-noops-5ADSTBJ5.mjs → legacy-noops-LDYSWTL2.mjs} +6 -6
  93. package/dist/cli/{monitors-AFNAU3A2.mjs → monitors-IYT3VON7.mjs} +7 -7
  94. package/dist/cli/{monitors-VZCBZO26.js → monitors-U4RE6KN5.js} +100 -100
  95. package/dist/cli/{org-JVLYTU24.mjs → org-R3JE22GS.mjs} +6 -6
  96. package/dist/cli/{org-X4QRYBC4.js → org-SO52ZGRP.js} +86 -86
  97. package/dist/cli/{pages-VELKZKBL.mjs → pages-5RLT5YTF.mjs} +6 -6
  98. package/dist/cli/{pages-YMM4KBW5.js → pages-SWXJQJXH.js} +18 -18
  99. package/dist/cli/{play-MIY6BYRB.mjs → play-2ELYCSXZ.mjs} +18 -18
  100. package/dist/cli/{play-J7DEBHI7.js → play-J4UXOQOJ.js} +317 -317
  101. package/dist/cli/{providers-2H3W3W7G.mjs → providers-IXITXHTS.mjs} +6 -6
  102. package/dist/cli/{providers-TOUB7Y2A.js → providers-VVUDGV2D.js} +9 -9
  103. package/dist/cli/{quickstart-GKAS5265.mjs → quickstart-HQCGDPPL.mjs} +4 -4
  104. package/dist/cli/{quickstart-LHY2LN3P.js → quickstart-XPH6MT47.js} +6 -6
  105. package/dist/cli/{run-KYGNOWYD.mjs → run-H2HQPWC4.mjs} +23 -23
  106. package/dist/cli/{run-QCAVDPE5.js → run-OR646AC6.js} +41 -41
  107. package/dist/cli/search-D27DZH2D.js +33 -0
  108. package/dist/cli/{search-YPGAIFDX.mjs → search-MBPI5SBW.mjs} +8 -8
  109. package/dist/cli/{search-output-OOC3VK4T.mjs → search-output-CYOMJNRV.mjs} +4 -4
  110. package/dist/cli/{search-output-ASELNQ2U.js → search-output-YGNSHBXX.js} +6 -6
  111. package/dist/cli/{secrets-KX3TQB4R.js → secrets-HVZKNNLZ.js} +15 -15
  112. package/dist/cli/{secrets-VJ4XYSMZ.mjs → secrets-NK2CN7WI.mjs} +6 -6
  113. package/dist/cli/sessions-MTISSOZ4.js +22 -0
  114. package/dist/cli/{sessions-KUN7H7E5.mjs → sessions-NY4G427U.mjs} +6 -6
  115. package/dist/cli/{settings-5NIF4BU7.js → settings-PVJRDEN2.js} +86 -86
  116. package/dist/cli/{settings-JKFYZ2IT.mjs → settings-RC4FGYY2.mjs} +13 -13
  117. package/dist/cli/{setup-MYV3IHPS.js → setup-B7QB4YV2.js} +50 -50
  118. package/dist/cli/{setup-5AX3TN6G.mjs → setup-YT3XSY6X.mjs} +10 -10
  119. package/dist/cli/{skills-JLS4CINQ.mjs → skills-5ILFNAHR.mjs} +8 -8
  120. package/dist/cli/skills-BHF35NLX.js +37 -0
  121. package/dist/cli/{tools-VBYKD3MJ.mjs → tools-7PAY32OZ.mjs} +17 -17
  122. package/dist/cli/tools-W5BZ37L6.js +57 -0
  123. package/dist/cli/update-M65CGK42.js +35 -0
  124. package/dist/cli/{update-QWAIVJRI.mjs → update-Z27QYB6O.mjs} +10 -10
  125. package/dist/cli/{views-TBWGZAVZ.mjs → views-2IANF6KR.mjs} +6 -6
  126. package/dist/cli/{views-ZW56JZB5.js → views-NP2SCMOV.js} +18 -18
  127. package/dist/cli/{workflow-EKSZST6M.js → workflow-2GNQL646.js} +17 -17
  128. package/dist/cli/{workflow-X7UQPJMQ.mjs → workflow-CAMEZLLY.mjs} +7 -7
  129. package/dist/index.js +9 -9
  130. package/dist/index.mjs +6 -6
  131. package/dist/install-integrity.json +105 -104
  132. package/dist/release.d.mts +1 -1
  133. package/dist/release.d.ts +1 -1
  134. package/dist/release.js +2 -2
  135. package/dist/release.mjs +1 -1
  136. package/dist/server.js +5 -5
  137. package/dist/server.mjs +3 -3
  138. package/package.json +1 -1
  139. package/dist/cli/auth-C7BBYIQD.js +0 -43
  140. package/dist/cli/describe-MNJVJHRE.js +0 -50
  141. package/dist/cli/git-MDOHEW5J.js +0 -25
  142. package/dist/cli/search-G67CEHR7.js +0 -33
  143. package/dist/cli/sessions-QILPX4XQ.js +0 -22
  144. package/dist/cli/skills-NG32XTZI.js +0 -37
  145. package/dist/cli/tools-OZG3V77R.js +0 -57
  146. package/dist/cli/update-YL5WVSKU.js +0 -35
@@ -40,6 +40,7 @@ import {
40
40
  TimeoutError,
41
41
  type Absurd,
42
42
  type TaskContext,
43
+ type WorkerClaimSnapshot,
43
44
  type WorkerOptions,
44
45
  } from '@deepline/absurd/sdk';
45
46
  import {
@@ -63,6 +64,7 @@ import { runtimeLimitExceededCause } from '../run-failure';
63
64
  import {
64
65
  playRunRecoveryLogDetail,
65
66
  playRunRecoveryProviderText,
67
+ recoveryForCompiledStartPacing,
66
68
  recoveryForDaytonaSandboxAcquisitionUnavailable,
67
69
  recoveryForRuntimeInitializationTransportFailure,
68
70
  recoveryForRuntimeSchedulerAdmissionFailure,
@@ -83,6 +85,7 @@ import {
83
85
  import {
84
86
  RuntimeResourceFenceLostError,
85
87
  type PlayRunnerRuntimeResource,
88
+ type PlayRunnerWorkerSlot,
86
89
  } from '../runner-backends/types';
87
90
  import { daytonaSandboxMatchesOperationIdentity } from '../runner-backends/backends/daytona-labels';
88
91
  import type { PlayBundleArtifact } from '../../plays/artifact-types';
@@ -267,6 +270,7 @@ import {
267
270
  import {
268
271
  acquirePostgresRateState,
269
272
  penalizePostgresRateState,
273
+ releasePostgresRateState,
270
274
  } from './postgres-rate-state';
271
275
  import { verifyRuntimeReceiptGatewayHealth } from './runtime-receipt-gateway-health';
272
276
  import {
@@ -290,6 +294,10 @@ import {
290
294
  withRuntimeSchedulerClient,
291
295
  } from './postgres-pool';
292
296
  import { runWithAbsurdSchedulerQuerySignal } from './absurd-pool';
297
+ import {
298
+ createAbsurdClaimLoopTiming,
299
+ type AbsurdClaimLoopTiming,
300
+ } from './absurd-claim-loop-timing';
293
301
  import {
294
302
  buildFailedTerminalSettledProgressEvents,
295
303
  collectGatewayRunnerTerminalProgressLedgerEvents,
@@ -439,6 +447,38 @@ function isTransientExecutorTokenStatus(
439
447
  export const ABSURD_RUNTIME_WORKER_SLOTS =
440
448
  RUNTIME_CAPACITY_POLICY.absurd.workerSlotsPerMachine;
441
449
 
450
+ /**
451
+ * Runs whose slot an active worker may lend at once. A run lends its slot when
452
+ * it takes a Daytona start permit (`daytona-start-admission.ts`) and keeps the
453
+ * loan until it gets a slot back after its create, so a loan outlives its
454
+ * permit. Twice the per-process permits covers every create in flight plus as
455
+ * many finished creates waiting for a slot. With loans capped at the permits
456
+ * alone, those waiting runs used up the cap: the next permit holders created
457
+ * inside their slots, and the finished runs waited for those creates to end
458
+ * before they could stage (round 43357298524-2: 16 such creates, up to 3.1 s
459
+ * of waiting with a ready sandbox, and no claims for 4 s on each warm worker).
460
+ * The worker holds at most slots + 2 x permits runs; creates stay bounded by
461
+ * the permits, and pre-create work and staging by `slots`.
462
+ */
463
+ export const ABSURD_RUNTIME_WORKER_MAX_LENT_SLOTS =
464
+ 2 *
465
+ RUNTIME_CAPACITY_POLICY.sandboxAcquisition.daytonaConcurrentStartsPerProcess;
466
+
467
+ /**
468
+ * The engine's lendable slot for a play-run attempt. Undefined when the task
469
+ * context cannot lend, such as a test double without the engine's slot
470
+ * lending patch; the attempt then keeps its slot through the create.
471
+ */
472
+ export function absurdTaskWorkerSlot(
473
+ ctx: TaskContext,
474
+ ): PlayRunnerWorkerSlot | undefined {
475
+ const lendSlot = (ctx as { lendSlot?: unknown }).lendSlot;
476
+ if (typeof lendSlot !== 'function') return undefined;
477
+ return {
478
+ lend: () => (lendSlot as TaskContext['lendSlot']).call(ctx),
479
+ };
480
+ }
481
+
442
482
  /**
443
483
  * Opt-in drain mode. The deploy system sets `DEEPLINE_ABSURD_DRAIN_EXIT=1` on
444
484
  * OLD-lane machines after a new release goes live: the machine keeps finishing
@@ -5137,37 +5177,19 @@ async function executeAssignedAbsurdAttempt(input: {
5137
5177
  policy: trafficPolicy,
5138
5178
  defaultSandboxStartsPerMinute: defaultDaytonaStartRatePerMinute,
5139
5179
  nowMs: Date.now(),
5140
- acquireStartPermit: async (sandboxStartsPerMinute) =>
5141
- await deps.runWithClient((client) =>
5142
- acquirePostgresRateState(client, {
5143
- bucketId: 'runtime:traffic:sandbox-start',
5144
- requested: 1,
5145
- schedulerSchema: options.schema ?? null,
5146
- rules: [
5147
- {
5148
- ruleId: 'runtime:traffic:sandbox-start',
5149
- requestsPerWindow: 1,
5150
- // A capacity of one gives the operator an actual
5151
- // start-rate ceiling rather than a minute-sized burst.
5152
- windowMs: Math.ceil(60_000 / sandboxStartsPerMinute),
5153
- maxConcurrency: null,
5154
- adaptiveMaxRps:
5155
- (daytonaStartRateConfig?.maximumRatePerMinute ??
5156
- sandboxStartsPerMinute) / 60,
5157
- },
5158
- ],
5159
- // The permit itself is the successful admission
5160
- // observation that lets the fleet-wide AIMD controller
5161
- // ramp. Provider pressure is fed back in the catch path.
5162
- observedSuccesses: 1,
5163
- }),
5164
- ),
5180
+ ...sandboxStartPermitStore({
5181
+ runWithClient: deps.runWithClient,
5182
+ schedulerSchema: options.schema ?? null,
5183
+ maximumRatePerMinute:
5184
+ daytonaStartRateConfig?.maximumRatePerMinute ?? null,
5185
+ }),
5165
5186
  });
5166
5187
  }
5167
5188
  const sandboxRuns = createSandboxExecutionJob({
5168
5189
  execution: createPlayRunnerBackendSandboxExecutionAdapter({
5169
5190
  backend,
5170
5191
  cancellationSignal,
5192
+ workerSlot: absurdTaskWorkerSlot(ctx),
5171
5193
  readiness: ({ baselineHeartbeatAt }) =>
5172
5194
  deps.runWithClient((client) =>
5173
5195
  runnerReadiness(
@@ -5692,6 +5714,7 @@ async function executeAssignedAbsurdAttempt(input: {
5692
5714
  deferCount: recovery.deferCount,
5693
5715
  deadlineAtMs: recovery.deadlineAtMs,
5694
5716
  delaySeconds: recovery.delaySeconds,
5717
+ ...(recovery.paced ? { paced: true } : {}),
5695
5718
  ...(detail ? { detail } : {}),
5696
5719
  ...(providerText ? { providerText } : {}),
5697
5720
  });
@@ -5704,7 +5727,8 @@ async function executeAssignedAbsurdAttempt(input: {
5704
5727
  reason: recovery.reason,
5705
5728
  dependency: recovery.dependency,
5706
5729
  deferCount: recovery.deferCount,
5707
- delayMs: recovery.delaySeconds * 1_000,
5730
+ delayMs: recovery.delayMs,
5731
+ paced: recovery.paced === true,
5708
5732
  });
5709
5733
  throw new DeferTask(
5710
5734
  `Platform recovery deferred for ${recovery.dependency}: ${recovery.reason}`,
@@ -6101,23 +6125,124 @@ function throwRetryableRuntimeInitializationFailure(
6101
6125
  throw recoveryForRuntimeInitializationTransportFailure(reason);
6102
6126
  }
6103
6127
 
6128
+ /** A paced start returns no sooner than this: it already lost the bucket for
6129
+ * its whole local wait. */
6130
+ const PACED_START_DEFER_MIN_MS = 1_000;
6131
+ /** Paced starts return spread over the time the bucket needs to grant this
6132
+ * many starts (2 s at 600 a minute), so runs deferred in the same second do
6133
+ * not all come back in the same second. */
6134
+ const PACED_START_DEFER_SPREAD_PERMITS = 20;
6135
+ /** Never spread longer than the outage ladder's first step. */
6136
+ const PACED_START_DEFER_MAX_SPREAD_MS = 15_000;
6137
+ /** How long a run waits for a start it was not granted before deferring. */
6138
+ const UNGRANTED_START_LOCAL_WAIT_MS = 1_000;
6139
+ /**
6140
+ * The longest wait for a start the bucket has already granted. The bucket
6141
+ * books a grant at most one bucket ahead of now (its cursor is clamped to
6142
+ * capacity / refill, 1 s at the compiled 120 to 600 a minute), so at the
6143
+ * compiled rates every grant is used. A grant further out comes only from a
6144
+ * hold, a cooldown, or a slow operator rate; that run releases its slot.
6145
+ */
6146
+ const GRANTED_START_MAX_LOCAL_WAIT_MS = 2_000;
6147
+
6148
+ const SANDBOX_START_BUCKET_ID = 'runtime:traffic:sandbox-start';
6149
+
6150
+ /**
6151
+ * Acquire and refund on the fleet-wide sandbox-start bucket, from one rule
6152
+ * definition so a refund always lands on the bucket that granted the permit.
6153
+ */
6154
+ export function sandboxStartPermitStore(input: {
6155
+ runWithClient: AbsurdRuntimeWorkerDeps['runWithClient'];
6156
+ schedulerSchema: string | null;
6157
+ /** The AIMD ceiling; null holds the bucket at the requested rate. */
6158
+ maximumRatePerMinute: number | null;
6159
+ }): Pick<
6160
+ Parameters<typeof enforceRuntimeTrafficPolicyBeforeSandboxStart>[0],
6161
+ 'acquireStartPermit' | 'refundStartPermit'
6162
+ > {
6163
+ const rules = (sandboxStartsPerMinute: number) => [
6164
+ {
6165
+ ruleId: SANDBOX_START_BUCKET_ID,
6166
+ requestsPerWindow: 1,
6167
+ // A capacity of one gives the operator an actual start-rate ceiling
6168
+ // rather than a minute-sized burst.
6169
+ windowMs: Math.ceil(60_000 / sandboxStartsPerMinute),
6170
+ maxConcurrency: null,
6171
+ adaptiveMaxRps:
6172
+ (input.maximumRatePerMinute ?? sandboxStartsPerMinute) / 60,
6173
+ },
6174
+ ];
6175
+ return {
6176
+ acquireStartPermit: async (sandboxStartsPerMinute) =>
6177
+ await input.runWithClient((client) =>
6178
+ acquirePostgresRateState(client, {
6179
+ bucketId: SANDBOX_START_BUCKET_ID,
6180
+ requested: 1,
6181
+ schedulerSchema: input.schedulerSchema,
6182
+ rules: rules(sandboxStartsPerMinute),
6183
+ // The permit itself is the successful admission observation that
6184
+ // lets the fleet-wide AIMD controller ramp. Provider pressure is fed
6185
+ // back in the attempt's catch path.
6186
+ observedSuccesses: 1,
6187
+ }),
6188
+ ),
6189
+ refundStartPermit: async ({ sandboxStartsPerMinute, reservationIds }) =>
6190
+ await input.runWithClient((client) =>
6191
+ releasePostgresRateState(client, {
6192
+ bucketId: SANDBOX_START_BUCKET_ID,
6193
+ schedulerSchema: input.schedulerSchema,
6194
+ rules: rules(sandboxStartsPerMinute),
6195
+ leaseIds: [],
6196
+ refundReservationIds: reservationIds,
6197
+ }),
6198
+ ),
6199
+ };
6200
+ }
6201
+
6202
+ type SandboxStartPermit = {
6203
+ granted: number;
6204
+ waitMs: number;
6205
+ waitReason?: 'concurrency' | 'rate' | 'hold' | 'fair_share';
6206
+ serverNowMs?: number;
6207
+ scheduledAtMs?: number[];
6208
+ effectiveRequestsPerSecond?: number;
6209
+ coolUntilMs?: number;
6210
+ claimedRetryAtMs?: number;
6211
+ /** One per granted permit; the bucket's ticket for a refund. */
6212
+ reservationIds?: string[];
6213
+ };
6214
+
6104
6215
  /**
6105
6216
  * Consume one global start permit before a first sandbox create. The limiter's
6106
6217
  * durable bucket is used for the compiled Daytona AIMD start ceiling and for
6107
- * any short-lived operator policy. A long wait becomes the same finite
6108
- * recovery ledger used for platform outages.
6218
+ * any short-lived operator policy.
6219
+ *
6220
+ * A granted start is waited for and used, however long the run already
6221
+ * waited: the grant took a token and a dispatch slot from the whole fleet.
6222
+ * Only a run granted nothing within 1 s defers. A grant too far out to wait
6223
+ * for is refunded before the run defers, so its token returns to the fleet.
6224
+ *
6225
+ * A defer under an operator policy, or while the bucket holds for provider
6226
+ * pressure, goes on the same finite recovery ledger used for platform
6227
+ * outages. Under the compiled pacing alone the bucket keeps granting, so the
6228
+ * run is requeued after the bucket's own wait plus jitter, outside the outage
6229
+ * budget.
6109
6230
  */
6110
6231
  export async function enforceRuntimeTrafficPolicyBeforeSandboxStart(input: {
6111
6232
  policy: RuntimeTrafficPolicy;
6112
6233
  defaultSandboxStartsPerMinute?: number | null;
6113
6234
  nowMs: number;
6114
- acquireStartPermit: (sandboxStartsPerMinute: number) => Promise<{
6115
- granted: number;
6116
- waitMs: number;
6117
- serverNowMs?: number;
6118
- scheduledAtMs?: number[];
6119
- }>;
6235
+ acquireStartPermit: (
6236
+ sandboxStartsPerMinute: number,
6237
+ ) => Promise<SandboxStartPermit>;
6238
+ /** Return granted permits this start will not use. */
6239
+ refundStartPermit: (input: {
6240
+ sandboxStartsPerMinute: number;
6241
+ reservationIds: string[];
6242
+ }) => Promise<void>;
6120
6243
  sleep?: (ms: number) => Promise<void>;
6244
+ /** Uniform [0, 1); injectable so tests can pin the jitter. */
6245
+ random?: () => number;
6121
6246
  }): Promise<void> {
6122
6247
  if (input.policy.admissionMode === 'hold_new_sandbox_starts') {
6123
6248
  throw recoveryForRuntimeTrafficPolicy({ mode: 'hold' });
@@ -6127,30 +6252,92 @@ export async function enforceRuntimeTrafficPolicyBeforeSandboxStart(input: {
6127
6252
  input.defaultSandboxStartsPerMinute ??
6128
6253
  null;
6129
6254
  if (sandboxStartsPerMinute === null) return;
6255
+ const deferStart = (
6256
+ permit: SandboxStartPermit,
6257
+ schedulerNowMs: number,
6258
+ delayMs: number,
6259
+ ) => {
6260
+ const bucketHolding =
6261
+ permit.waitReason === 'hold' ||
6262
+ (permit.coolUntilMs ?? 0) > schedulerNowMs ||
6263
+ (permit.claimedRetryAtMs ?? 0) > schedulerNowMs;
6264
+ // Only a reply read from the bucket's state proves it is merely pacing.
6265
+ // A lock-busy reply carries no clock, cooldown or retry facts, so it
6266
+ // cannot rule out a hold and takes the counted ladder.
6267
+ const bucketStateRead = permit.serverNowMs !== undefined;
6268
+ if (
6269
+ input.policy.sandboxStartsPerMinute !== null ||
6270
+ bucketHolding ||
6271
+ !bucketStateRead
6272
+ ) {
6273
+ return recoveryForRuntimeTrafficPolicy({ mode: 'throttle' });
6274
+ }
6275
+ const startsPerSecond =
6276
+ permit.effectiveRequestsPerSecond !== undefined &&
6277
+ permit.effectiveRequestsPerSecond > 0
6278
+ ? permit.effectiveRequestsPerSecond
6279
+ : sandboxStartsPerMinute / 60;
6280
+ const spreadMs = Math.min(
6281
+ PACED_START_DEFER_MAX_SPREAD_MS,
6282
+ (PACED_START_DEFER_SPREAD_PERMITS / startsPerSecond) * 1_000,
6283
+ );
6284
+ return recoveryForCompiledStartPacing({
6285
+ delayMs:
6286
+ Math.max(PACED_START_DEFER_MIN_MS, delayMs) +
6287
+ (input.random ?? Math.random)() * spreadMs,
6288
+ });
6289
+ };
6130
6290
  let locallyWaitedMs = 0;
6131
6291
  for (;;) {
6132
6292
  const permit = await input.acquireStartPermit(sandboxStartsPerMinute);
6133
6293
  const scheduledAtMs = permit.scheduledAtMs?.[0] ?? input.nowMs;
6134
6294
  const schedulerNowMs = permit.serverNowMs ?? input.nowMs;
6135
- const delayMs =
6136
- permit.granted > 0
6137
- ? Math.max(0, scheduledAtMs - schedulerNowMs)
6138
- : Math.max(
6139
- 0,
6140
- permit.waitMs,
6141
- scheduledAtMs > input.nowMs ? scheduledAtMs - schedulerNowMs : 0,
6142
- );
6143
- // A sub-second schedule retains smooth pacing without spending a worker
6144
- // attempt. Longer waits become a durable, bounded defer, allowing the
6145
- // scheduler to serve unrelated traffic during a deliberate shed.
6146
- if (delayMs > 1_000 || locallyWaitedMs + delayMs > 1_000) {
6147
- throw recoveryForRuntimeTrafficPolicy({ mode: 'throttle' });
6148
- }
6149
6295
  if (permit.granted > 0) {
6150
- if (delayMs > 0) {
6151
- await (input.sleep ?? sleep)(delayMs);
6296
+ const delayMs = Math.max(0, scheduledAtMs - schedulerNowMs);
6297
+ if (delayMs <= GRANTED_START_MAX_LOCAL_WAIT_MS) {
6298
+ if (delayMs > 0) {
6299
+ await (input.sleep ?? sleep)(delayMs);
6300
+ }
6301
+ return;
6152
6302
  }
6153
- return;
6303
+ const reservationIds = permit.reservationIds ?? [];
6304
+ if (reservationIds.length !== permit.granted) {
6305
+ throw new Error(
6306
+ `Sandbox-start bucket granted ${permit.granted} permit(s) with ${reservationIds.length} reservation(s) to refund.`,
6307
+ );
6308
+ }
6309
+ try {
6310
+ await input.refundStartPermit({
6311
+ sandboxStartsPerMinute,
6312
+ reservationIds,
6313
+ });
6314
+ } catch (error) {
6315
+ // The reservation then expires unrefunded and the fleet loses one
6316
+ // start. Throwing here would replace the defer below with an
6317
+ // unclassified attempt error.
6318
+ console.error(
6319
+ '[absurd-runtime.worker] sandbox_start_permit_refund_failed',
6320
+ {
6321
+ reservations: reservationIds.length,
6322
+ error: error instanceof Error ? error.message : String(error),
6323
+ },
6324
+ );
6325
+ }
6326
+ throw deferStart(permit, schedulerNowMs, delayMs);
6327
+ }
6328
+ const delayMs = Math.max(
6329
+ 0,
6330
+ permit.waitMs,
6331
+ scheduledAtMs > input.nowMs ? scheduledAtMs - schedulerNowMs : 0,
6332
+ );
6333
+ // A sub-second wait for a token keeps pacing smooth without spending a
6334
+ // worker attempt. A longer one becomes a durable defer, so the scheduler
6335
+ // can serve other traffic during a deliberate shed.
6336
+ if (
6337
+ delayMs > UNGRANTED_START_LOCAL_WAIT_MS ||
6338
+ locallyWaitedMs + delayMs > UNGRANTED_START_LOCAL_WAIT_MS
6339
+ ) {
6340
+ throw deferStart(permit, schedulerNowMs, delayMs);
6154
6341
  }
6155
6342
  const waitMs = Math.max(1, delayMs);
6156
6343
  await (input.sleep ?? sleep)(waitMs);
@@ -7210,6 +7397,8 @@ export function createAbsurdRuntimeTasks(
7210
7397
  absurd: Absurd,
7211
7398
  deps?: Partial<AbsurdRuntimeWorkerDeps>,
7212
7399
  queue: string = ABSURD_RUNS_QUEUE,
7400
+ /** Logs task setup and handler end for each play run. */
7401
+ claimLoopTiming?: AbsurdClaimLoopTiming,
7213
7402
  ): void {
7214
7403
  const resolved: AbsurdRuntimeWorkerDeps = {
7215
7404
  ...buildDefaultDeps(absurd),
@@ -7223,14 +7412,24 @@ export function createAbsurdRuntimeTasks(
7223
7412
  if (deps?.deleteRuntimeSandbox && !deps.deleteRuntimeSandboxWithOutcome) {
7224
7413
  resolved.deleteRuntimeSandboxWithOutcome = undefined;
7225
7414
  }
7226
- absurd.registerTask({ name: ABSURD_PLAY_RUN_TASK, queue }, (params, ctx) =>
7227
- executeAbsurdRuntimeLaunch(
7228
- params as AbsurdPlayRunTaskParams,
7229
- ctx,
7230
- resolved,
7231
- queue,
7232
- ),
7233
- );
7415
+ absurd.registerTask({ name: ABSURD_PLAY_RUN_TASK, queue }, (params, ctx) => {
7416
+ const execute = () =>
7417
+ executeAbsurdRuntimeLaunch(
7418
+ params as AbsurdPlayRunTaskParams,
7419
+ ctx,
7420
+ resolved,
7421
+ queue,
7422
+ );
7423
+ return claimLoopTiming
7424
+ ? claimLoopTiming.playRunHandler(
7425
+ {
7426
+ runId: (params as AbsurdPlayRunTaskParams).runId,
7427
+ taskId: ctx.taskID,
7428
+ },
7429
+ execute,
7430
+ )
7431
+ : execute();
7432
+ });
7234
7433
  // Register on both the current lane and every adopted continuation lane.
7235
7434
  // The task may sleep for days, but its handler schedules children on the
7236
7435
  // current release through `resolved.currentReleaseId` after waking.
@@ -9958,6 +10157,13 @@ async function processPostgresSchedulerSandboxCleanupJob(input: {
9958
10157
  kind: 'pending',
9959
10158
  code: providerOutcome.code,
9960
10159
  detail: `${providerOutcome.code}: ${providerOutcome.detail}`,
10160
+ // Only Daytona reads its acceptance back between claims.
10161
+ deleteAcceptedForMs: deleteProof.acceptance
10162
+ ? Math.max(0, Date.now() - deleteProof.acceptance.acceptedAtMs)
10163
+ : providerOutcome.deleteAccepted &&
10164
+ resource.provider === 'daytona'
10165
+ ? 0
10166
+ : null,
9961
10167
  };
9962
10168
  }
9963
10169
  await recordCleanupEvent('provider_delete_failed', {
@@ -10682,18 +10888,18 @@ export async function hasAbsurdQueueDueWork(
10682
10888
  * that claim.
10683
10889
  */
10684
10890
  export function trackAbsurdClaimLoopCapacity(hooks: {
10685
- afterClaim: () => Promise<void>;
10891
+ afterClaim: (claim: WorkerClaimSnapshot) => Promise<void>;
10686
10892
  saturatedMaintenance: () => Promise<void>;
10687
10893
  }): {
10688
- afterClaim: () => Promise<void>;
10894
+ afterClaim: (claim: WorkerClaimSnapshot) => Promise<void>;
10689
10895
  saturatedMaintenance: () => Promise<void>;
10690
10896
  hasIdleSlot: () => boolean;
10691
10897
  } {
10692
10898
  let saturated = false;
10693
10899
  return {
10694
- afterClaim: () => {
10900
+ afterClaim: (claim) => {
10695
10901
  saturated = false;
10696
- return hooks.afterClaim();
10902
+ return hooks.afterClaim(claim);
10697
10903
  },
10698
10904
  saturatedMaintenance: () => {
10699
10905
  saturated = true;
@@ -11016,11 +11222,18 @@ export async function startRuntimeWorkerHost(
11016
11222
  const workerBase =
11017
11223
  options.workerName?.trim() || `${hostname()}:${process.pid}`;
11018
11224
 
11019
- const absurdClient = createAbsurdRuntimeClient(poolOptions, queue);
11225
+ // Times the claim query, the afterClaim hook, task setup and handler end
11226
+ // on the active lane (`absurd-claim-loop-timing.ts`).
11227
+ const claimLoopTiming = createAbsurdClaimLoopTiming({ queue });
11228
+ const absurdClient = createAbsurdRuntimeClient(
11229
+ poolOptions,
11230
+ queue,
11231
+ claimLoopTiming.observer,
11232
+ );
11020
11233
  const workerDeps: AbsurdRuntimeWorkerDeps = {
11021
11234
  ...buildDefaultDeps(absurdClient),
11022
11235
  };
11023
- createAbsurdRuntimeTasks(absurdClient, workerDeps, queue);
11236
+ createAbsurdRuntimeTasks(absurdClient, workerDeps, queue, claimLoopTiming);
11024
11237
  // Must happen before `startWorker()` can call `claim_task()`: an expired
11025
11238
  // engine claim otherwise retries a task whose signed completed runner
11026
11239
  // terminal has already been durably persisted.
@@ -11088,7 +11301,7 @@ export async function startRuntimeWorkerHost(
11088
11301
  // `claim_task` performs the indexed max_delay sweep. Reconcile after every
11089
11302
  // sweep, including claims that return backlog work, so a saturated queue
11090
11303
  // cannot postpone a cancellation's scheduler/outbox terminal indefinitely.
11091
- afterClaim: reconcileRuntimeCancellations,
11304
+ afterClaim: claimLoopTiming.afterClaim(reconcileRuntimeCancellations),
11092
11305
  // claim_task cannot run while every handler slot is occupied. Keep the
11093
11306
  // enqueue deadline and cancellation lane independent from handler duration
11094
11307
  // by sweeping without claiming, then project cancellation into the
@@ -11098,6 +11311,7 @@ export async function startRuntimeWorkerHost(
11098
11311
  const worker = await absurdClient.startWorker({
11099
11312
  workerId: `${workerBase}:${queue}`,
11100
11313
  concurrency: slots,
11314
+ maxLentSlots: ABSURD_RUNTIME_WORKER_MAX_LENT_SLOTS,
11101
11315
  claimTimeout: HEARTBEAT_CLAIM_TIMEOUT_SECONDS,
11102
11316
  pollInterval: ABSURD_IDLE_POLL_INTERVAL_SECONDS,
11103
11317
  afterClaim: claimLoop.afterClaim,
@@ -11344,6 +11558,7 @@ export async function startRuntimeWorkerHost(
11344
11558
  console.info('[absurd-runtime.worker] started', {
11345
11559
  schema: schedulerOptions.schema ?? null,
11346
11560
  slots,
11561
+ maxLentSlots: ABSURD_RUNTIME_WORKER_MAX_LENT_SLOTS,
11347
11562
  idlePollIntervalSeconds: ABSURD_IDLE_POLL_INTERVAL_SECONDS,
11348
11563
  standbyProbeIntervalMs: standbyProbe
11349
11564
  ? ABSURD_ACTIVE_STANDBY_POLL_INTERVAL_MS
@@ -29,7 +29,10 @@ import {
29
29
  failPostgresSchedulerScheduledChildWaits,
30
30
  type PostgresSchedulerWorkerOnceResult,
31
31
  } from './postgres';
32
- import { createAbsurdForRuntimeScheduler } from './absurd-pool';
32
+ import {
33
+ createAbsurdForRuntimeScheduler,
34
+ type AbsurdSchedulerQueryObserver,
35
+ } from './absurd-pool';
33
36
  import {
34
37
  withRuntimeSchedulerClient,
35
38
  type RuntimeSchedulerPoolOptions,
@@ -539,11 +542,16 @@ const absurdLog: Log = {
539
542
  export function createAbsurdRuntimeClient(
540
543
  poolOptions: RuntimeSchedulerPoolOptions,
541
544
  queueName: string = ABSURD_RUNS_QUEUE,
545
+ observer?: AbsurdSchedulerQueryObserver,
542
546
  ): Absurd {
543
- return createAbsurdForRuntimeScheduler(poolOptions, {
544
- queueName,
545
- log: absurdLog,
546
- });
547
+ return createAbsurdForRuntimeScheduler(
548
+ poolOptions,
549
+ {
550
+ queueName,
551
+ log: absurdLog,
552
+ },
553
+ observer,
554
+ );
547
555
  }
548
556
 
549
557
  const absurdReadyPromises = new Map<string, Promise<void>>();
@@ -25,7 +25,11 @@ export type PlayRunRecoveryOutcome =
25
25
  reason: string;
26
26
  deferCount: number;
27
27
  deadlineAtMs: number | null;
28
+ /** Whole milliseconds until the retry; `delaySeconds` is the same. */
29
+ delayMs: number;
28
30
  delaySeconds: number;
31
+ /** Compiled start pacing: not counted toward the defer budget. */
32
+ paced?: true;
29
33
  }
30
34
  | {
31
35
  kind: 'exhausted';
@@ -53,6 +57,7 @@ export async function transitionPreCodePlayRunRecovery(input: {
53
57
  return { kind: 'not_recoverable' };
54
58
  }
55
59
  const decision = input.error.decision;
60
+ const pacingDelayMs = input.error.pacingDelayMs;
56
61
  const recovery = await deferPostgresSchedulerAttemptForRecovery(
57
62
  input.client,
58
63
  {
@@ -71,17 +76,41 @@ export async function transitionPreCodePlayRunRecovery(input: {
71
76
  horizonMs: PLAY_RUN_RECOVERY_DEFER_POLICY.horizonMs,
72
77
  deferBaseMs: PLAY_RUN_RECOVERY_DEFER_POLICY.deferBaseSeconds * 1_000,
73
78
  deferMaxMs: PLAY_RUN_RECOVERY_DEFER_POLICY.deferMaxSeconds * 1_000,
79
+ ...(pacingDelayMs !== undefined
80
+ ? {
81
+ pacingDelayMs,
82
+ pacingHorizonMs:
83
+ PLAY_RUN_RECOVERY_DEFER_POLICY.startPacingHorizonMs,
84
+ pacingBackoffDivisor:
85
+ PLAY_RUN_RECOVERY_DEFER_POLICY.startPacingBackoffDivisor,
86
+ pacingBackoffMaxMs:
87
+ PLAY_RUN_RECOVERY_DEFER_POLICY.startPacingBackoffMaxMs,
88
+ }
89
+ : {}),
74
90
  },
75
91
  input.schedulerOptions,
76
92
  );
77
93
  if (recovery.deferred && recovery.deferCount !== null) {
94
+ // Past the pacing horizon the store counted this defer on the outage
95
+ // ladder, so it requeues after the ladder's delay, not the pacing delay.
96
+ // A paced defer uses the store's delay, which may be the backoff floor
97
+ // for how long the run has been paced rather than the requested delay.
98
+ const paced =
99
+ pacingDelayMs !== undefined &&
100
+ recovery.paced === true &&
101
+ recovery.pacingDelayMs !== undefined;
102
+ const delayMs = paced
103
+ ? (recovery.pacingDelayMs as number)
104
+ : recoveryDeferDelaySeconds(recovery.deferCount) * 1_000;
78
105
  return {
79
106
  kind: 'deferred',
80
107
  dependency: decision.dependency,
81
108
  reason: decision.reason,
82
109
  deferCount: recovery.deferCount,
83
110
  deadlineAtMs: recovery.deadlineAtMs,
84
- delaySeconds: recoveryDeferDelaySeconds(recovery.deferCount),
111
+ delayMs,
112
+ delaySeconds: delayMs / 1_000,
113
+ ...(paced ? { paced: true as const } : {}),
85
114
  };
86
115
  }
87
116
  if (recovery.exhausted) {