deepline 0.3.536 → 0.3.538

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 (204) hide show
  1. package/dist/bundling-sources/sdk/src/client-core.ts +22 -5
  2. package/dist/bundling-sources/sdk/src/index.ts +2 -0
  3. package/dist/bundling-sources/sdk/src/plays/client-core.ts +18 -1
  4. package/dist/bundling-sources/sdk/src/release.ts +1 -1
  5. package/dist/bundling-sources/sdk/src/runs/watch-polling.ts +33 -4
  6. package/dist/bundling-sources/shared_libs/integration-contracts/billing-entitlements.ts +1 -1
  7. package/dist/bundling-sources/shared_libs/observability/scheduled-jobs.json +36 -0
  8. package/dist/bundling-sources/shared_libs/play-runtime/app-runtime-api.ts +1 -0
  9. package/dist/bundling-sources/shared_libs/play-runtime/baked-runner-image.ts +330 -0
  10. package/dist/bundling-sources/shared_libs/play-runtime/context.ts +717 -133
  11. package/dist/bundling-sources/shared_libs/play-runtime/coordinator-headers.ts +7 -0
  12. package/dist/bundling-sources/shared_libs/play-runtime/daytona-payload-contract.ts +22 -1
  13. package/dist/bundling-sources/shared_libs/play-runtime/durable-runs-rollout.ts +123 -0
  14. package/dist/bundling-sources/shared_libs/play-runtime/experiment-switches.ts +480 -0
  15. package/dist/bundling-sources/shared_libs/play-runtime/fixture-egress-fetch.ts +24 -16
  16. package/dist/bundling-sources/shared_libs/play-runtime/freshness-receipt-execution.ts +293 -53
  17. package/dist/bundling-sources/shared_libs/play-runtime/governor/block-reserving-budget-state-backend.ts +57 -2
  18. package/dist/bundling-sources/shared_libs/play-runtime/governor/budget-state-backend.ts +43 -0
  19. package/dist/bundling-sources/shared_libs/play-runtime/governor/governor.ts +141 -9
  20. package/dist/bundling-sources/shared_libs/play-runtime/launch-identity.ts +2 -0
  21. package/dist/bundling-sources/shared_libs/play-runtime/modal-runtime-config.ts +6 -0
  22. package/dist/bundling-sources/shared_libs/play-runtime/modal-supervisor-sidecar.ts +556 -0
  23. package/dist/bundling-sources/shared_libs/play-runtime/protocol.ts +27 -0
  24. package/dist/bundling-sources/shared_libs/play-runtime/resource-governor.ts +19 -0
  25. package/dist/bundling-sources/shared_libs/play-runtime/run-ledger.ts +54 -0
  26. package/dist/bundling-sources/shared_libs/play-runtime/run-snapshot-stream.ts +5 -0
  27. package/dist/bundling-sources/shared_libs/play-runtime/runner-app/index.ts +155 -3
  28. package/dist/bundling-sources/shared_libs/play-runtime/runner-app/relay-connection-counter.ts +103 -0
  29. package/dist/bundling-sources/shared_libs/play-runtime/runner-app/runtime-heartbeat.ts +75 -6
  30. package/dist/bundling-sources/shared_libs/play-runtime/runner-app/runtime-terminal-push.ts +59 -0
  31. package/dist/bundling-sources/shared_libs/play-runtime/runner-backends/backends/daytona-payload-transport.ts +544 -73
  32. package/dist/bundling-sources/shared_libs/play-runtime/runner-backends/backends/daytona-runtime-watchdog.ts +8 -1
  33. package/dist/bundling-sources/shared_libs/play-runtime/runner-backends/backends/detached-runner-readiness-pacing.ts +19 -1
  34. package/dist/bundling-sources/shared_libs/play-runtime/runner-backends/backends/modal.ts +2390 -110
  35. package/dist/bundling-sources/shared_libs/play-runtime/runtime-flow.ts +42 -8
  36. package/dist/bundling-sources/shared_libs/play-runtime/runtime-read-through.ts +287 -0
  37. package/dist/bundling-sources/shared_libs/play-runtime/runtime-receipt-finish.ts +606 -0
  38. package/dist/bundling-sources/shared_libs/play-runtime/runtime-receipt-writer.ts +274 -119
  39. package/dist/bundling-sources/shared_libs/play-runtime/runtime-traffic-policy.ts +54 -0
  40. package/dist/bundling-sources/shared_libs/play-runtime/runtime-work-counters.ts +10 -1
  41. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backend.ts +15 -0
  42. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/absurd-play-run-task.ts +18 -1
  43. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/absurd-pool.ts +18 -4
  44. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/absurd-runtime-worker.ts +219 -7
  45. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/absurd-shared.ts +3 -0
  46. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/early-sandbox-claim-affinity.ts +340 -0
  47. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/play-run-recovery.ts +1 -0
  48. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/postgres-progress.ts +10 -1
  49. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/postgres-rate-state.ts +623 -7
  50. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/postgres.ts +340 -5
  51. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/runner-push.ts +61 -0
  52. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/runtime-event-search.ts +2 -1
  53. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/runtime-sandbox-ledger-reconciliation.ts +269 -2
  54. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/runtime-worker-wake.ts +238 -5
  55. package/dist/bundling-sources/shared_libs/play-runtime/startup-read-tool-ids.ts +47 -0
  56. package/dist/bundling-sources/shared_libs/play-runtime/tool-call/runtime-step-receipts-adapter.ts +5 -4
  57. package/dist/bundling-sources/shared_libs/play-runtime/tool-result.ts +6 -0
  58. package/dist/bundling-sources/shared_libs/play-runtime/transient-service-error.ts +11 -0
  59. package/dist/cli/auth-4WEVLYK4.js +43 -0
  60. package/dist/cli/{auth-KCTCUO7P.mjs → auth-KYH7N7RQ.mjs} +5 -5
  61. package/dist/cli/{billing-4VBGZ3CT.js → billing-4KTUVZ4S.js} +114 -90
  62. package/dist/cli/{billing-OOJHKLNS.mjs → billing-WK346KAI.mjs} +31 -7
  63. package/dist/cli/{chunk-4E5JXZ3W.js → chunk-25RGHJQL.js} +15 -15
  64. package/dist/cli/{chunk-MSP4DTSD.js → chunk-34PLG5OE.js} +13 -13
  65. package/dist/cli/{chunk-DQHUJMCL.mjs → chunk-35OCRH5C.mjs} +5 -5
  66. package/dist/cli/{chunk-2B4IOGFD.js → chunk-3I5TU5XE.js} +292 -279
  67. package/dist/cli/{chunk-Z7UIOGW4.mjs → chunk-4KZF6OYY.mjs} +3 -3
  68. package/dist/cli/{chunk-2YWJS76L.mjs → chunk-4NEOGPKD.mjs} +1 -1
  69. package/dist/cli/{chunk-LZXZQPA2.mjs → chunk-4WQR4DG4.mjs} +1 -1
  70. package/dist/cli/{chunk-KWYGWO4Y.js → chunk-5VSPRRTI.js} +7 -7
  71. package/dist/cli/{chunk-ANUKBZ6W.mjs → chunk-6JG3MRTM.mjs} +2 -2
  72. package/dist/cli/{chunk-VBDZIMWD.js → chunk-6SLQLWWL.js} +26 -26
  73. package/dist/cli/{chunk-E24UGPGG.mjs → chunk-7XDJKIM2.mjs} +4 -4
  74. package/dist/cli/{chunk-OUDTOMZC.mjs → chunk-A6E7TCK2.mjs} +5 -5
  75. package/dist/cli/{chunk-ZZ4MF2GI.js → chunk-ADLDU2QG.js} +6 -6
  76. package/dist/cli/{chunk-XVZRJJDS.mjs → chunk-ALARRSMZ.mjs} +3 -3
  77. package/dist/cli/{chunk-HWDKRN7L.js → chunk-B2BTBHX2.js} +3 -3
  78. package/dist/cli/{chunk-ZISEH7OL.js → chunk-BBS2BLPV.js} +16 -16
  79. package/dist/cli/{chunk-YRLAUGQY.mjs → chunk-CLO562KG.mjs} +3 -1
  80. package/dist/cli/{chunk-CXTW7SRW.mjs → chunk-E7D37PLM.mjs} +8 -0
  81. package/dist/cli/{chunk-SLPJ3LXI.js → chunk-ESX3H7Q7.js} +22 -22
  82. package/dist/cli/{chunk-AB2GBOD4.mjs → chunk-FJ5KPGCS.mjs} +10 -10
  83. package/dist/cli/{chunk-DUYAMLOC.mjs → chunk-FWE37N2P.mjs} +1 -1
  84. package/dist/cli/{chunk-3PCYV6ZJ.mjs → chunk-ICTA5ICE.mjs} +1 -1
  85. package/dist/cli/{chunk-ZILSRDIN.js → chunk-IMLFB66A.js} +3 -3
  86. package/dist/cli/{chunk-PNY3BWHP.mjs → chunk-IP3XJTWA.mjs} +2 -2
  87. package/dist/cli/{chunk-6VUGBQZQ.js → chunk-JCLRSMUP.js} +5 -5
  88. package/dist/cli/{chunk-YBMHOH6H.mjs → chunk-JPEBKN3K.mjs} +2 -2
  89. package/dist/cli/{chunk-GF32SBST.mjs → chunk-JTOV5RUA.mjs} +1 -1
  90. package/dist/cli/{chunk-Q5CXV3E3.js → chunk-KCUQNH4K.js} +2 -2
  91. package/dist/cli/{chunk-DA2I2M7D.mjs → chunk-KNIYEZVV.mjs} +2 -2
  92. package/dist/cli/{chunk-CWSLUNA6.js → chunk-LPTBHNGB.js} +7 -5
  93. package/dist/cli/{chunk-WC5M3JXE.mjs → chunk-M3NCXGNN.mjs} +2 -2
  94. package/dist/cli/{chunk-TX5TUHJN.js → chunk-MNBIGX6O.js} +10 -10
  95. package/dist/cli/{chunk-ZEV2Y56V.js → chunk-MYSPQUAO.js} +44 -44
  96. package/dist/cli/{chunk-KPQHUVYW.mjs → chunk-N2BCPZVR.mjs} +5 -5
  97. package/dist/cli/{chunk-XBAH3TKU.js → chunk-N5HSG4OV.js} +5 -5
  98. package/dist/cli/{chunk-GTVZKY3F.js → chunk-O765M4LT.js} +2 -2
  99. package/dist/cli/{chunk-2FCSUOYN.js → chunk-OOLBE6FR.js} +53 -53
  100. package/dist/cli/{chunk-W7AEIGZR.js → chunk-P3DP56HB.js} +41 -41
  101. package/dist/cli/{chunk-LN6RXDTB.js → chunk-PQKD5DMT.js} +19 -19
  102. package/dist/cli/{chunk-GHLDCLSC.mjs → chunk-T6GPTJ5F.mjs} +1 -1
  103. package/dist/cli/{chunk-XJD2GYUP.mjs → chunk-TWWYCJJW.mjs} +5 -5
  104. package/dist/cli/{chunk-BASLYGXK.mjs → chunk-UE7JHAZ2.mjs} +29 -16
  105. package/dist/cli/{chunk-Q4MNUOS4.js → chunk-UEZNIPFO.js} +107 -107
  106. package/dist/cli/{chunk-RVSSQPQO.mjs → chunk-VCHV4LS3.mjs} +1 -1
  107. package/dist/cli/{chunk-LDGZFDUB.js → chunk-VIFLWQXS.js} +2 -2
  108. package/dist/cli/{chunk-6BBGUQJJ.js → chunk-XTYHZEJ2.js} +8 -0
  109. package/dist/cli/{chunk-CIDN5K23.js → chunk-YQURGSRB.js} +1 -1
  110. package/dist/cli/{chunk-Y2NTPYGS.js → chunk-YZ2ZPHWR.js} +9 -9
  111. package/dist/cli/{chunk-HAJQGP5V.mjs → chunk-ZDLDCXY3.mjs} +2 -2
  112. package/dist/cli/{chunk-JUHDJNSI.mjs → chunk-ZU6JBRV5.mjs} +4 -4
  113. package/dist/cli/command-docs.js +2 -2
  114. package/dist/cli/command-docs.mjs +1 -1
  115. package/dist/cli/{csv-P3HLK4GO.mjs → csv-2YKLUKDR.mjs} +4 -4
  116. package/dist/cli/{csv-2V2DIFNG.js → csv-LM7FBECI.js} +13 -13
  117. package/dist/cli/{db-ZYOY3QRQ.mjs → db-234UBWJH.mjs} +6 -6
  118. package/dist/cli/{db-MREAQVW6.js → db-5PMA4IVW.js} +27 -27
  119. package/dist/cli/describe-C7GOSGYB.js +49 -0
  120. package/dist/cli/{describe-IKZFOADR.mjs → describe-W26LW5O7.mjs} +17 -17
  121. package/dist/cli/describe-core.d.mts +3 -3
  122. package/dist/cli/describe-core.d.ts +3 -3
  123. package/dist/cli/{executions-H5IJ7QSQ.js → executions-3S736GXX.js} +8 -8
  124. package/dist/cli/{executions-KTSY5M34.mjs → executions-GD7GXTJM.mjs} +6 -6
  125. package/dist/cli/{feedback-724QK3Z5.js → feedback-BUWTDY4R.js} +14 -14
  126. package/dist/cli/{feedback-WWJRIXEU.mjs → feedback-GBV5HJJZ.mjs} +6 -6
  127. package/dist/cli/git-YG36MROC.js +25 -0
  128. package/dist/cli/{git-R5VRG7X6.mjs → git-YXJGTDQL.mjs} +5 -5
  129. package/dist/cli/index.js +143 -143
  130. package/dist/cli/index.mjs +42 -42
  131. package/dist/cli/{legacy-noops-PWZ5XLAO.mjs → legacy-noops-UJM6GBNP.mjs} +6 -6
  132. package/dist/cli/{legacy-noops-C6GDEGPU.js → legacy-noops-ZSF64V2U.js} +9 -9
  133. package/dist/cli/{monitors-WQSKMHAP.mjs → monitors-UERUQ6CT.mjs} +7 -7
  134. package/dist/cli/{monitors-VAVQ4WCE.js → monitors-XQ2GNH6D.js} +100 -100
  135. package/dist/cli/{org-MAL4QPVF.mjs → org-CP4VLH6M.mjs} +6 -6
  136. package/dist/cli/{org-CWWRWXZQ.js → org-IF6MPVNR.js} +86 -86
  137. package/dist/cli/{play-WJOWK5PQ.js → play-2NHQO5MO.js} +317 -317
  138. package/dist/cli/{play-ILW6MSNG.mjs → play-ZWDYYVPI.mjs} +17 -17
  139. package/dist/cli/{providers-4V2NMLZZ.mjs → providers-2CVIATU4.mjs} +6 -6
  140. package/dist/cli/{providers-W662ANCH.js → providers-LOPXQN56.js} +9 -9
  141. package/dist/cli/{quickstart-C22BR743.mjs → quickstart-KVCFXLID.mjs} +4 -4
  142. package/dist/cli/{quickstart-BW6EBUYX.js → quickstart-N4WDEQZY.js} +6 -6
  143. package/dist/cli/{run-KW7KW4FX.js → run-BDT5LK3I.js} +42 -42
  144. package/dist/cli/{run-SPAU5IMW.mjs → run-RUXHYWLF.mjs} +22 -22
  145. package/dist/cli/search-ATDDVADT.js +32 -0
  146. package/dist/cli/{search-XPC75HLM.mjs → search-BFUTNPA5.mjs} +7 -7
  147. package/dist/cli/{search-output-VJYE7USJ.js → search-output-CTXI2QZU.js} +6 -6
  148. package/dist/cli/{search-output-JKYJSEPM.mjs → search-output-WUGH4PZA.mjs} +4 -4
  149. package/dist/cli/{secrets-YB57KGSB.js → secrets-BZJZYFOU.js} +15 -15
  150. package/dist/cli/{secrets-OJG73GXQ.mjs → secrets-Z4XQVTC6.mjs} +6 -6
  151. package/dist/cli/sessions-HNU35AFM.js +22 -0
  152. package/dist/cli/{sessions-7ZL37BW4.mjs → sessions-VZXR3MQZ.mjs} +6 -6
  153. package/dist/cli/{settings-RKSQB7FA.mjs → settings-VYEZFR4L.mjs} +12 -12
  154. package/dist/cli/{settings-A7DD2ZYE.js → settings-WBYA4JMM.js} +85 -85
  155. package/dist/cli/{setup-S3K5YU62.js → setup-FS2RMSS2.js} +49 -49
  156. package/dist/cli/{setup-NXDUTITY.mjs → setup-H7KCI4SO.mjs} +9 -9
  157. package/dist/cli/skills-VPIURCAZ.js +36 -0
  158. package/dist/cli/{skills-VMFAIDO6.mjs → skills-YQNSJUUG.mjs} +7 -7
  159. package/dist/cli/tools-273GS5HU.js +56 -0
  160. package/dist/cli/{tools-52NTHBSJ.mjs → tools-ZF6SVEGW.mjs} +16 -16
  161. package/dist/cli/{update-SAKBEKMV.mjs → update-RKQNNJM4.mjs} +9 -9
  162. package/dist/cli/update-TOD3XY55.js +34 -0
  163. package/dist/cli/{views-ACRV7MD6.mjs → views-JHHOTWDU.mjs} +6 -6
  164. package/dist/cli/{views-C3GJOBDG.js → views-KN7FEDGT.js} +21 -21
  165. package/dist/cli/{workflow-ZNWCZEGN.js → workflow-2WHSKTTV.js} +17 -17
  166. package/dist/cli/{workflow-CS22E7TC.mjs → workflow-AAYLCLWA.mjs} +7 -7
  167. package/dist/{client-BlLYQDNo.d.mts → client-D0uDBybG.d.mts} +1 -1
  168. package/dist/{client-DSQlkIDO.d.ts → client-DZTnAv4B.d.ts} +1 -1
  169. package/dist/{client-core-rX7n2H8U.d.mts → client-core-BhWf8Y1b.d.mts} +15 -2
  170. package/dist/{client-core-CDwapXy5.d.ts → client-core-og3AP1LL.d.ts} +15 -2
  171. package/dist/{compiler-manifest-BHNC4RL-.d.mts → compiler-manifest-Bes3OVA3.d.mts} +1 -1
  172. package/dist/{compiler-manifest-BHNC4RL-.d.ts → compiler-manifest-Bes3OVA3.d.ts} +1 -1
  173. package/dist/{errors-lhtIWG5Z.d.ts → errors-BJm4lLWc.d.ts} +1 -1
  174. package/dist/{errors-D7sPXrvB.d.mts → errors-Dc5r42ks.d.mts} +1 -1
  175. package/dist/{index-CQTBHXHr.d.ts → index-BfV7mRPF.d.ts} +1 -1
  176. package/dist/{index-NaDZq2xf.d.mts → index-DTkiz_Ur.d.mts} +1 -1
  177. package/dist/index.d.mts +7 -7
  178. package/dist/index.d.ts +7 -7
  179. package/dist/index.js +9 -9
  180. package/dist/index.mjs +6 -6
  181. package/dist/install-integrity.json +120 -112
  182. package/dist/plays/bundle-play-file.d.mts +3 -3
  183. package/dist/plays/bundle-play-file.d.ts +3 -3
  184. package/dist/plays/play-description.d.mts +2 -2
  185. package/dist/plays/play-description.d.ts +2 -2
  186. package/dist/plays/run-request.d.mts +2 -2
  187. package/dist/plays/run-request.d.ts +2 -2
  188. package/dist/release.d.mts +1 -1
  189. package/dist/release.d.ts +1 -1
  190. package/dist/release.js +2 -2
  191. package/dist/release.mjs +1 -1
  192. package/dist/server.d.mts +4 -4
  193. package/dist/server.d.ts +4 -4
  194. package/dist/server.js +5 -5
  195. package/dist/server.mjs +3 -3
  196. package/package.json +1 -1
  197. package/dist/cli/auth-6XQKFOLG.js +0 -43
  198. package/dist/cli/describe-WW3OQRLP.js +0 -49
  199. package/dist/cli/git-PHYRD56H.js +0 -25
  200. package/dist/cli/search-HLE54W5G.js +0 -32
  201. package/dist/cli/sessions-VEBYZIEU.js +0 -22
  202. package/dist/cli/skills-NVQ744CN.js +0 -36
  203. package/dist/cli/tools-SBDUL3WB.js +0 -56
  204. package/dist/cli/update-HHVFZPCV.js +0 -34
@@ -25,6 +25,8 @@ import {
25
25
  import { providerConcurrencyControllerOptions } from '../provider-capacity/provider-concurrency-policy';
26
26
  import { classifyProviderThrottle } from '../provider-capacity/provider-throttle-classifier';
27
27
  import { acquireRateScopeSql, updateRateScopeSql } from './postgres-rate-scope';
28
+ import { escapeLiteral } from 'pg';
29
+ import { DURABLE_RUNS_ROLLOUT } from '../durable-runs-rollout';
28
30
 
29
31
  const DEFAULT_SCHEMA = 'runtime_scheduler';
30
32
  const RATE_BUCKET_TABLE = 'rate_bucket';
@@ -1905,15 +1907,50 @@ async function acquireWithConcurrency(
1905
1907
  requested: number,
1906
1908
  ): Promise<InternalAcquireOutcome> {
1907
1909
  let probeBaselineSupported = true;
1910
+ if (rateStateCollapsedAcquireEnabled()) {
1911
+ while (true) {
1912
+ try {
1913
+ return await collapsedGrantWithConcurrency(
1914
+ client,
1915
+ input,
1916
+ rules,
1917
+ seeds,
1918
+ requested,
1919
+ probeBaselineSupported,
1920
+ );
1921
+ } catch (error) {
1922
+ if (
1923
+ probeBaselineSupported &&
1924
+ isMissingProbeBaselineColumnError(error)
1925
+ ) {
1926
+ probeBaselineSupported = false;
1927
+ continue;
1928
+ }
1929
+ throw error;
1930
+ }
1931
+ }
1932
+ }
1908
1933
  while (true) {
1909
- await client.query('BEGIN ISOLATION LEVEL READ COMMITTED');
1934
+ const lockSql = `SELECT bucket_id FROM ${scopeHoldTableName(input)}
1935
+ WHERE bucket_id = $1 FOR UPDATE`;
1936
+ const singleTripOpening = rateStateSingleTripEnabled()
1937
+ ? renderRateStateStatementForSingleTrip(lockSql, [input.bucketId])
1938
+ : null;
1939
+ if (singleTripOpening === null) {
1940
+ await client.query('BEGIN ISOLATION LEVEL READ COMMITTED');
1941
+ }
1910
1942
  try {
1911
- await boundRateStateTransaction(client);
1912
- await client.query(
1913
- `SELECT bucket_id FROM ${scopeHoldTableName(input)}
1914
- WHERE bucket_id = $1 FOR UPDATE`,
1915
- [input.bucketId],
1916
- );
1943
+ if (singleTripOpening !== null) {
1944
+ // BEGIN, the bounds and the scope lock in one request; the grant below
1945
+ // stays a separate statement, so it still takes a fresh snapshot after
1946
+ // any wait for this lock.
1947
+ await client.query(
1948
+ `BEGIN ISOLATION LEVEL READ COMMITTED;\n${RATE_STATE_BOUNDS_SQL}\n${singleTripOpening};`,
1949
+ );
1950
+ } else {
1951
+ await boundRateStateTransaction(client);
1952
+ await client.query(lockSql, [input.bucketId]);
1953
+ }
1917
1954
  const outcome = await grantWithConcurrency(
1918
1955
  client,
1919
1956
  input,
@@ -1941,6 +1978,95 @@ async function acquireWithConcurrency(
1941
1978
  }
1942
1979
  }
1943
1980
 
1981
+ /** Marks the scope-lock row in a collapsed grant request's flattened rows. */
1982
+ const RATE_STATE_SCOPE_LOCK_MARKER = 'rate_state_scope_lock_marker';
1983
+
1984
+ /**
1985
+ * The concurrency grant as one request: BEGIN, the bounds, the scope lock, the
1986
+ * grant and COMMIT. The lock statement is unchanged in what it locks; it only
1987
+ * reports one marker row so its row can be told apart from the grant's in the
1988
+ * pool's flattened result. The grant stays a separate READ COMMITTED statement
1989
+ * after the lock, so it takes a fresh snapshot after any wait for the lock. A
1990
+ * failure anywhere skips the rest of the request (COMMIT included) and is
1991
+ * rolled back here exactly like the multi-trip path. A grant that cannot be
1992
+ * rendered keeps the single-trip opening plus a bound grant and COMMIT.
1993
+ */
1994
+ async function collapsedGrantWithConcurrency(
1995
+ client: PostgresSchedulerQueryClient,
1996
+ input: RateStateAcquireInput,
1997
+ rules: AcquirePacingRule[],
1998
+ seeds: RateBucketSeed[],
1999
+ requested: number,
2000
+ probeBaselineSupported: boolean,
2001
+ ): Promise<InternalAcquireOutcome> {
2002
+ const lock = renderRateStateStatementForSingleTrip(
2003
+ `SELECT count(*) AS ${RATE_STATE_SCOPE_LOCK_MARKER} FROM (
2004
+ SELECT bucket_id FROM ${scopeHoldTableName(input)}
2005
+ WHERE bucket_id = $1 FOR UPDATE
2006
+ ) AS scope_lock`,
2007
+ [input.bucketId],
2008
+ );
2009
+ if (lock === null) {
2010
+ throw new Error(
2011
+ `Rate-state scope lock for ${input.bucketId} cannot be rendered for one request.`,
2012
+ );
2013
+ }
2014
+ const opening = `BEGIN ISOLATION LEVEL READ COMMITTED;\n${RATE_STATE_BOUNDS_SQL}\n${lock};`;
2015
+ let open = false;
2016
+ let committed = false;
2017
+ const grantClient: PostgresSchedulerQueryClient = {
2018
+ query: async <Row extends Record<string, unknown>>(
2019
+ sql: string,
2020
+ parameters?: unknown[],
2021
+ ) => {
2022
+ const grant = renderRateStateStatementForSingleTrip(
2023
+ sql,
2024
+ parameters,
2025
+ rateStateRenderOptions(),
2026
+ );
2027
+ if (grant === null) {
2028
+ open = true;
2029
+ await client.query(opening);
2030
+ return await client.query<Row>(sql, parameters);
2031
+ }
2032
+ open = true;
2033
+ const result = await client.query<Row>(`${opening}\n${grant};\nCOMMIT;`);
2034
+ committed = true;
2035
+ return {
2036
+ rows: result.rows.filter(
2037
+ (row) => !Object.hasOwn(row, RATE_STATE_SCOPE_LOCK_MARKER),
2038
+ ),
2039
+ };
2040
+ },
2041
+ } as PostgresSchedulerQueryClient;
2042
+ try {
2043
+ const outcome = await grantWithConcurrency(
2044
+ grantClient,
2045
+ input,
2046
+ rules,
2047
+ seeds,
2048
+ requested,
2049
+ probeBaselineSupported,
2050
+ );
2051
+ if (!committed) await client.query('COMMIT');
2052
+ return outcome;
2053
+ } catch (error) {
2054
+ // Same as the multi-trip path. After a committed request this only fails
2055
+ // a post-statement invariant check (lease drift, grant shape) and the
2056
+ // ROLLBACK is a no-op: unlike the multi-trip path, that grant has already
2057
+ // committed and its leases expire by their TTL.
2058
+ if (open) {
2059
+ try {
2060
+ await client.query('ROLLBACK');
2061
+ } catch {
2062
+ // Preserve the original admission/storage error.
2063
+ }
2064
+ }
2065
+ if (isMissingProbeBaselineColumnError(error)) throw error;
2066
+ throw rateStateLockBusyOr(error);
2067
+ }
2068
+ }
2069
+
1944
2070
  /**
1945
2071
  * Bound the current rate-state transaction. `SET LOCAL` keeps the limits inside
1946
2072
  * this transaction: the scheduler pool runs behind PgBouncer transaction
@@ -1956,10 +2082,194 @@ async function boundRateStateTransaction(
1956
2082
  );
1957
2083
  }
1958
2084
 
2085
+ /** The same transaction-local bounds as {@link boundRateStateTransaction}. */
2086
+ const RATE_STATE_BOUNDS_SQL = `SET LOCAL lock_timeout = ${escapeLiteral(`${RATE_STATE_LOCK_TIMEOUT_MS}ms`)};
2087
+ SET LOCAL statement_timeout = ${escapeLiteral(`${RATE_STATE_STATEMENT_TIMEOUT_MS}ms`)};`;
2088
+
2089
+ /**
2090
+ * The one request a bounded single-statement transaction becomes. If any
2091
+ * command fails, PostgreSQL skips the rest of the string (COMMIT included) and
2092
+ * leaves the transaction aborted; the caller then sends ROLLBACK, as the
2093
+ * multi-trip path does. Nothing can commit partway.
2094
+ */
2095
+ export function rateStateSingleTripRequest(renderedStatement: string): string {
2096
+ return `BEGIN;\n${RATE_STATE_BOUNDS_SQL}\n${renderedStatement};\nCOMMIT;`;
2097
+ }
2098
+
2099
+ const RATE_STATE_SQL_TOKEN =
2100
+ /'(?:[^']|'')*'|"(?:[^"]|"")*"|--[^\n]*|\/\*[\s\S]*?\*\/|\$(\d+)\b/g;
2101
+
2102
+ /**
2103
+ * Render a parameterized rate-state statement for a simple-protocol request,
2104
+ * or null when it must keep the extended protocol. Each value becomes the
2105
+ * exact text node-postgres would bind (`String(value)`, `'true'`/`'false'`,
2106
+ * NULL) as an untyped literal, which PostgreSQL resolves from the same context
2107
+ * an untyped parameter is resolved from. A placeholder used more than once is
2108
+ * accepted only when every use carries an explicit cast, so no use can resolve
2109
+ * to a different type than the single parameter type extended protocol
2110
+ * deduces. Non-scalar values, NUL bytes and dollar-quoted bodies fall back.
2111
+ */
2112
+ export function renderRateStateStatementForSingleTrip(
2113
+ sql: string,
2114
+ parameters: readonly unknown[] = [],
2115
+ options: { arrays?: boolean; textParameters?: readonly number[] } = {},
2116
+ ): string | null {
2117
+ if (sql.includes('$$')) return null;
2118
+ const textParameters = new Set(options.textParameters ?? []);
2119
+ for (const position of textParameters) {
2120
+ if (typeof parameters[position - 1] !== 'string') return null;
2121
+ }
2122
+ const literals: string[] = [];
2123
+ for (const value of parameters) {
2124
+ if (value === null || value === undefined) {
2125
+ literals.push('NULL');
2126
+ } else if (Array.isArray(value)) {
2127
+ if (!options.arrays) return null;
2128
+ const array = rateStateArrayParameterText(value);
2129
+ if (array === null) return null;
2130
+ literals.push(escapeLiteral(array));
2131
+ } else if (typeof value === 'string') {
2132
+ if (value.includes('\u0000')) return null;
2133
+ literals.push(escapeLiteral(value));
2134
+ } else if (typeof value === 'number') {
2135
+ if (!Number.isFinite(value)) return null;
2136
+ literals.push(escapeLiteral(String(value)));
2137
+ } else if (typeof value === 'bigint') {
2138
+ literals.push(escapeLiteral(value.toString()));
2139
+ } else if (typeof value === 'boolean') {
2140
+ literals.push(escapeLiteral(value ? 'true' : 'false'));
2141
+ } else {
2142
+ return null;
2143
+ }
2144
+ }
2145
+ const uses = new Map<number, { count: number; uncast: boolean }>();
2146
+ let valid = true;
2147
+ const rendered = sql.replace(
2148
+ RATE_STATE_SQL_TOKEN,
2149
+ (match, index: string | undefined, offset: number) => {
2150
+ if (!index) return match;
2151
+ const position = Number(index);
2152
+ const literal = literals[position - 1];
2153
+ if (literal === undefined) {
2154
+ valid = false;
2155
+ return match;
2156
+ }
2157
+ const use = uses.get(position) ?? { count: 0, uncast: false };
2158
+ use.count += 1;
2159
+ const cast = /^\s*::/.test(sql.slice(offset + match.length));
2160
+ if (!cast && textParameters.has(position)) {
2161
+ // A declared text parameter: every use is the type extended protocol
2162
+ // deduces for it (text), so each uncast use carries that cast.
2163
+ uses.set(position, use);
2164
+ return `${literal}::text`;
2165
+ }
2166
+ if (!cast) use.uncast = true;
2167
+ uses.set(position, use);
2168
+ return literal;
2169
+ },
2170
+ );
2171
+ for (const use of uses.values()) {
2172
+ if (use.count > 1 && use.uncast) return null;
2173
+ }
2174
+ return valid ? rendered : null;
2175
+ }
2176
+
2177
+ /**
2178
+ * The exact array text node-postgres binds for a flat array of scalars
2179
+ * (`prepareValue` -> `arrayString`: every element double-quoted with `\\` and
2180
+ * `"` backslash-escaped, null as NULL), or null for anything else.
2181
+ */
2182
+ function rateStateArrayParameterText(
2183
+ values: readonly unknown[],
2184
+ ): string | null {
2185
+ const elements: string[] = [];
2186
+ for (const value of values) {
2187
+ if (value === null || value === undefined) {
2188
+ elements.push('NULL');
2189
+ continue;
2190
+ }
2191
+ let text: string;
2192
+ if (typeof value === 'string') text = value;
2193
+ else if (typeof value === 'number' && Number.isFinite(value))
2194
+ text = String(value);
2195
+ else if (typeof value === 'bigint') text = value.toString();
2196
+ else if (typeof value === 'boolean') text = value ? 'true' : 'false';
2197
+ else return null;
2198
+ if (text.includes('\u0000')) return null;
2199
+ elements.push(`"${text.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`);
2200
+ }
2201
+ return `{${elements.join(',')}}`;
2202
+ }
2203
+
2204
+ function rateStateCollapsedAcquireEnabled(): boolean {
2205
+ const enabled: boolean =
2206
+ DURABLE_RUNS_ROLLOUT.rateStateCollapsedAcquire &&
2207
+ DURABLE_RUNS_ROLLOUT.rateStateSingleTripTransactions;
2208
+ return enabled;
2209
+ }
2210
+
2211
+ /**
2212
+ * Rendering options for the statements a collapsed acquire sends. Every
2213
+ * rate-state statement binds the bucket id (text) as `$1`; it is compared with
2214
+ * and written to text columns only, so its uses may stay uncast.
2215
+ */
2216
+ function rateStateRenderOptions(): {
2217
+ arrays?: boolean;
2218
+ textParameters?: readonly number[];
2219
+ } {
2220
+ return rateStateCollapsedAcquireEnabled()
2221
+ ? { arrays: true, textParameters: [1] }
2222
+ : {};
2223
+ }
2224
+
2225
+ function rateStateSingleTripEnabled(): boolean {
2226
+ const enabled: boolean = DURABLE_RUNS_ROLLOUT.rateStateSingleTripTransactions;
2227
+ return enabled;
2228
+ }
2229
+
2230
+ /** Rows of the one statement in a single-trip request (BEGIN/SET/COMMIT return none). */
2231
+ function singleTripRows<Row extends Record<string, unknown>>(
2232
+ result: unknown,
2233
+ statementIndex: number,
2234
+ ): { rows: Row[] } {
2235
+ if (Array.isArray(result)) {
2236
+ return {
2237
+ rows: ((result[statementIndex] as { rows?: Row[] })?.rows ?? []) as Row[],
2238
+ };
2239
+ }
2240
+ return { rows: ((result as { rows?: Row[] }).rows ?? []) as Row[] };
2241
+ }
2242
+
1959
2243
  /** Bound one formerly-autocommit statement without leaking session settings. */
1960
2244
  async function queryBoundedRateState<
1961
2245
  Row extends Record<string, unknown> = Record<string, unknown>,
1962
2246
  >(client: PostgresSchedulerQueryClient, sql: string, parameters?: unknown[]) {
2247
+ const singleTrip = rateStateSingleTripEnabled()
2248
+ ? renderRateStateStatementForSingleTrip(
2249
+ sql,
2250
+ parameters,
2251
+ rateStateRenderOptions(),
2252
+ )
2253
+ : null;
2254
+ if (singleTrip !== null) {
2255
+ try {
2256
+ // One request, still four commands in one transaction: BEGIN, the same
2257
+ // transaction-local bounds, the statement (its own snapshot), COMMIT.
2258
+ const result = await client.query(rateStateSingleTripRequest(singleTrip));
2259
+ return singleTripRows<Row>(result, 3) as Awaited<
2260
+ ReturnType<typeof client.query<Row>>
2261
+ >;
2262
+ } catch (error) {
2263
+ // A failed command skips the rest of the request and leaves the
2264
+ // transaction aborted, exactly where the multi-trip path rolls back.
2265
+ try {
2266
+ await client.query('ROLLBACK');
2267
+ } catch {
2268
+ // Preserve the original statement error.
2269
+ }
2270
+ throw rateStateLockBusyOr(error);
2271
+ }
2272
+ }
1963
2273
  await client.query('BEGIN');
1964
2274
  try {
1965
2275
  await boundRateStateTransaction(client);
@@ -3146,6 +3456,17 @@ async function applyConcurrencyObservations(
3146
3456
  };
3147
3457
  }
3148
3458
 
3459
+ if (rateStateCollapsedAcquireEnabled()) {
3460
+ const collapsed = await collapsedApplyConcurrencyObservations(
3461
+ client,
3462
+ input,
3463
+ concurrencyRules,
3464
+ observations,
3465
+ batch,
3466
+ );
3467
+ if (collapsed !== null) return collapsed;
3468
+ }
3469
+
3149
3470
  await client.query('BEGIN');
3150
3471
  try {
3151
3472
  await boundRateStateTransaction(client);
@@ -3361,6 +3682,301 @@ async function applyConcurrencyObservations(
3361
3682
  }
3362
3683
  }
3363
3684
 
3685
+ type ConcurrencyCheckpointRow = {
3686
+ rule_id: string;
3687
+ learned_concurrency_limit: number | null;
3688
+ concurrency_short_rtt_ms: number | null;
3689
+ concurrency_long_rtt_ms: number | null;
3690
+ concurrency_minimum_rtt_ms: number | null;
3691
+ concurrency_successful_samples: number;
3692
+ concurrency_window_limit: number | null;
3693
+ concurrency_has_observed_throttle: boolean;
3694
+ };
3695
+
3696
+ /**
3697
+ * The batched observation fold in one request (two with a controller
3698
+ * checkpoint). One statement upserts the observer watermark, reclaims expired
3699
+ * observers, adds the success count only when the watermark accepted this batch
3700
+ * (the multi-trip path's separate UPDATE after the same check) and, when a
3701
+ * checkpoint is due, locks the batch's rule rows FOR UPDATE in rule order and
3702
+ * returns them. The checkpoint updates then go out with COMMIT. Without a
3703
+ * checkpoint the first request carries COMMIT itself. Returns null, having sent
3704
+ * nothing, when a statement cannot be rendered for one request.
3705
+ */
3706
+ async function collapsedApplyConcurrencyObservations(
3707
+ client: PostgresSchedulerQueryClient,
3708
+ input: Pick<PlayRunnerRateStateAcquireInput, 'bucketId'> & {
3709
+ schema?: string | null;
3710
+ schedulerSchema?: string | null;
3711
+ observedSuccesses?: number;
3712
+ },
3713
+ concurrencyRules: readonly AcquirePacingRule[],
3714
+ observations: readonly ConcurrencyObservation[],
3715
+ batch: ConcurrencyObservationBatch,
3716
+ ): Promise<Awaited<ReturnType<typeof applyConcurrencyObservations>> | null> {
3717
+ const successes = Math.max(
3718
+ 0,
3719
+ Math.min(1_000_000, Math.trunc(input.observedSuccesses ?? 0)),
3720
+ );
3721
+ const checkpoint = concurrencyRules.length > 0 && observations.length > 0;
3722
+ const fold = renderRateStateStatementForSingleTrip(
3723
+ `
3724
+ WITH now_value AS (
3725
+ SELECT FLOOR(EXTRACT(EPOCH FROM clock_timestamp()) * 1000)::bigint AS now_ms
3726
+ ),
3727
+ accepted AS (
3728
+ INSERT INTO ${concurrencyObserverTableName(input)} AS observer (
3729
+ bucket_id,
3730
+ observer_id,
3731
+ lane_id,
3732
+ last_sequence,
3733
+ updated_at_ms,
3734
+ expires_at_ms
3735
+ )
3736
+ SELECT
3737
+ $1::text,
3738
+ $2::text,
3739
+ $3::text,
3740
+ $4::bigint,
3741
+ now_ms,
3742
+ now_ms + $5::bigint
3743
+ FROM now_value
3744
+ ON CONFLICT (bucket_id, observer_id, lane_id) DO UPDATE
3745
+ SET
3746
+ last_sequence = EXCLUDED.last_sequence,
3747
+ updated_at_ms = EXCLUDED.updated_at_ms,
3748
+ expires_at_ms = EXCLUDED.expires_at_ms
3749
+ WHERE observer.last_sequence < EXCLUDED.last_sequence
3750
+ RETURNING last_sequence
3751
+ ), expired AS (
3752
+ DELETE FROM ${concurrencyObserverTableName(input)} AS observer
3753
+ WHERE (SELECT COUNT(*) FROM accepted) >= 0
3754
+ AND (observer.bucket_id, observer.observer_id, observer.lane_id) IN (
3755
+ SELECT stale.bucket_id, stale.observer_id, stale.lane_id
3756
+ FROM ${concurrencyObserverTableName(input)} AS stale
3757
+ WHERE stale.expires_at_ms <= (SELECT now_ms FROM now_value)
3758
+ AND NOT (stale.bucket_id = $1::text AND stale.observer_id = $2::text AND stale.lane_id = $3::text)
3759
+ ORDER BY stale.expires_at_ms
3760
+ LIMIT ${CONCURRENCY_OBSERVER_CLEANUP_BATCH_SIZE}
3761
+ FOR UPDATE OF stale SKIP LOCKED
3762
+ )
3763
+ )${
3764
+ successes > 0
3765
+ ? `, counted AS (
3766
+ UPDATE ${scopeHoldTableName(input)}
3767
+ SET rate_successes = rate_successes + $6::bigint,
3768
+ refill_per_sec = CASE
3769
+ WHEN rate_observation_started_at_ms IS NULL
3770
+ AND rate_throttle_ceiling_rps IS NOT NULL
3771
+ AND rate_recovery_interval_ms > 0
3772
+ THEN GREATEST(refill_per_sec, LEAST(
3773
+ rate_throttle_ceiling_rps,
3774
+ (rate_successes + $6::bigint) * 1000.0 / rate_recovery_interval_ms
3775
+ ))
3776
+ ELSE refill_per_sec END
3777
+ WHERE bucket_id = $1::text AND EXISTS (SELECT 1 FROM accepted)
3778
+ RETURNING 1
3779
+ )`
3780
+ : ''
3781
+ }${
3782
+ checkpoint
3783
+ ? `, locked AS (
3784
+ SELECT
3785
+ rule_id,
3786
+ learned_concurrency_limit,
3787
+ concurrency_short_rtt_ms,
3788
+ concurrency_long_rtt_ms,
3789
+ concurrency_minimum_rtt_ms,
3790
+ concurrency_successful_samples,
3791
+ concurrency_window_limit,
3792
+ concurrency_has_observed_throttle
3793
+ FROM ${bucketTableName(input)}
3794
+ WHERE bucket_id = $1::text
3795
+ AND rule_id = ANY($7::text[])
3796
+ AND EXISTS (SELECT 1 FROM accepted)
3797
+ ORDER BY rule_id
3798
+ FOR UPDATE
3799
+ )`
3800
+ : ''
3801
+ }
3802
+ SELECT
3803
+ (SELECT COUNT(*) FROM accepted)::int AS accepted_rows,
3804
+ ${successes > 0 ? '(SELECT COUNT(*) FROM counted)::int' : '0'} AS counted_rows,
3805
+ ${
3806
+ checkpoint
3807
+ ? `(SELECT COALESCE(json_agg(locked ORDER BY rule_id), '[]'::json) FROM locked)`
3808
+ : `'[]'::json`
3809
+ } AS rule_rows
3810
+ `,
3811
+ [
3812
+ input.bucketId,
3813
+ batch.observerId,
3814
+ batch.laneId,
3815
+ batch.sequence,
3816
+ CONCURRENCY_OBSERVATION_DEDUP_RETENTION_MS,
3817
+ successes,
3818
+ concurrencyRules.map((rule) => rule.ruleId),
3819
+ ],
3820
+ { arrays: true },
3821
+ );
3822
+ if (fold === null) return null;
3823
+ const notApplied = {
3824
+ ruleCount: 0,
3825
+ changedRuleCount: 0,
3826
+ limitMinBefore: null,
3827
+ limitMaxBefore: null,
3828
+ limitMinAfter: null,
3829
+ limitMaxAfter: null,
3830
+ };
3831
+ let committed = false;
3832
+ try {
3833
+ const result = await client.query<{
3834
+ accepted_rows: number;
3835
+ counted_rows: number;
3836
+ rule_rows: ConcurrencyCheckpointRow[] | string | null;
3837
+ }>(
3838
+ `BEGIN;\n${RATE_STATE_BOUNDS_SQL}\n${fold};${checkpoint ? '' : '\nCOMMIT;'}`,
3839
+ );
3840
+ committed = !checkpoint;
3841
+ const row = result.rows[0];
3842
+ if (!row) {
3843
+ throw new Error(
3844
+ `Rate-state observation fold returned no row for ${input.bucketId}.`,
3845
+ );
3846
+ }
3847
+ if (Number(row.accepted_rows) === 0) {
3848
+ if (!committed) {
3849
+ await client.query('COMMIT');
3850
+ committed = true;
3851
+ }
3852
+ return { disposition: 'already_applied', ...notApplied };
3853
+ }
3854
+ if (!checkpoint) return { disposition: 'applied', ...notApplied };
3855
+ const ruleRows: ConcurrencyCheckpointRow[] =
3856
+ typeof row.rule_rows === 'string'
3857
+ ? (JSON.parse(row.rule_rows) as ConcurrencyCheckpointRow[])
3858
+ : (row.rule_rows ?? []);
3859
+ const ruleById = new Map(
3860
+ concurrencyRules.map((rule) => [rule.ruleId, rule]),
3861
+ );
3862
+ const limitsBefore: number[] = [];
3863
+ const limitsAfter: number[] = [];
3864
+ const updates: string[] = [];
3865
+ const updateParameters: unknown[][] = [];
3866
+ let changedRuleCount = 0;
3867
+ for (const ruleRow of ruleRows) {
3868
+ const rule = ruleById.get(ruleRow.rule_id);
3869
+ if (!rule?.maxConcurrency) continue;
3870
+ const maximumLimit = Math.max(1, Math.trunc(rule.maxConcurrency));
3871
+ const initialLimit = Math.min(
3872
+ maximumLimit,
3873
+ Math.max(
3874
+ 1,
3875
+ ruleRow.learned_concurrency_limit ??
3876
+ (rule.ruleId === 'default:provider-scope'
3877
+ ? UNKNOWN_PROVIDER_CONCURRENCY_DISCOVERY_LIMIT
3878
+ : maximumLimit),
3879
+ ),
3880
+ );
3881
+ limitsBefore.push(initialLimit);
3882
+ const controller = new Gradient2ConcurrencyController(
3883
+ providerConcurrencyControllerOptions({
3884
+ initialLimit,
3885
+ maximumLimit,
3886
+ unknownProvider: rule.ruleId === 'default:provider-scope',
3887
+ }),
3888
+ ruleRow.learned_concurrency_limit == null
3889
+ ? undefined
3890
+ : {
3891
+ limit: initialLimit,
3892
+ shortRttMs: ruleRow.concurrency_short_rtt_ms,
3893
+ longRttMs: ruleRow.concurrency_long_rtt_ms,
3894
+ minimumRttMs: ruleRow.concurrency_minimum_rtt_ms,
3895
+ successfulSamplesInWindow: Math.max(
3896
+ 0,
3897
+ Math.trunc(ruleRow.concurrency_successful_samples ?? 0),
3898
+ ),
3899
+ windowStartedAtLimit: Math.max(
3900
+ 1,
3901
+ ruleRow.concurrency_window_limit ?? initialLimit,
3902
+ ),
3903
+ hasObservedThrottle:
3904
+ ruleRow.concurrency_has_observed_throttle === true,
3905
+ },
3906
+ );
3907
+ for (const observation of observations) controller.observe(observation);
3908
+ const next = controller.checkpoint();
3909
+ limitsAfter.push(next.limit);
3910
+ if (next.limit !== initialLimit) changedRuleCount += 1;
3911
+ const parameters = [
3912
+ input.bucketId,
3913
+ ruleRow.rule_id,
3914
+ next.limit,
3915
+ next.shortRttMs,
3916
+ next.longRttMs,
3917
+ next.minimumRttMs,
3918
+ next.successfulSamplesInWindow,
3919
+ next.windowStartedAtLimit,
3920
+ next.hasObservedThrottle === true,
3921
+ ];
3922
+ updateParameters.push(parameters);
3923
+ updates.push(concurrencyCheckpointUpdateSql(input));
3924
+ }
3925
+ const rendered = updates.map((sql, index) =>
3926
+ renderRateStateStatementForSingleTrip(sql, updateParameters[index]),
3927
+ );
3928
+ if (rendered.every((sql): sql is string => sql !== null)) {
3929
+ await client.query(
3930
+ [...rendered.map((sql) => `${sql};`), 'COMMIT;'].join('\n'),
3931
+ );
3932
+ } else {
3933
+ for (const [index, sql] of updates.entries()) {
3934
+ await client.query(sql, updateParameters[index]);
3935
+ }
3936
+ await client.query('COMMIT');
3937
+ }
3938
+ committed = true;
3939
+ const beforeRange = numberRange(limitsBefore);
3940
+ const afterRange = numberRange(limitsAfter);
3941
+ return {
3942
+ disposition: 'applied',
3943
+ ruleCount: limitsBefore.length,
3944
+ changedRuleCount,
3945
+ limitMinBefore: beforeRange.min,
3946
+ limitMaxBefore: beforeRange.max,
3947
+ limitMinAfter: afterRange.min,
3948
+ limitMaxAfter: afterRange.max,
3949
+ };
3950
+ } catch (error) {
3951
+ if (!committed) {
3952
+ try {
3953
+ await client.query('ROLLBACK');
3954
+ } catch {
3955
+ // Preserve the original controller/storage error.
3956
+ }
3957
+ }
3958
+ throw rateStateLockBusyOr(error);
3959
+ }
3960
+ }
3961
+
3962
+ function concurrencyCheckpointUpdateSql(options: {
3963
+ schema?: string | null;
3964
+ schedulerSchema?: string | null;
3965
+ }): string {
3966
+ return `
3967
+ UPDATE ${bucketTableName(options)}
3968
+ SET
3969
+ learned_concurrency_limit = $3,
3970
+ concurrency_short_rtt_ms = $4,
3971
+ concurrency_long_rtt_ms = $5,
3972
+ concurrency_minimum_rtt_ms = $6,
3973
+ concurrency_successful_samples = $7,
3974
+ concurrency_window_limit = $8,
3975
+ concurrency_has_observed_throttle = $9
3976
+ WHERE bucket_id = $1 AND rule_id = $2
3977
+ `;
3978
+ }
3979
+
3364
3980
  async function acquireRateStateStatements(
3365
3981
  client: PostgresSchedulerQueryClient,
3366
3982
  input: RateStateAcquireInput,