deepline 0.3.582 → 0.4.0

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 (196) hide show
  1. package/dist/bundling-sources/sdk/src/client-core.ts +79 -36
  2. package/dist/bundling-sources/sdk/src/index.ts +2 -0
  3. package/dist/bundling-sources/sdk/src/release.ts +7 -3
  4. package/dist/bundling-sources/sdk/src/types.ts +37 -0
  5. package/dist/bundling-sources/shared_libs/observability/scheduled-jobs.json +22 -3
  6. package/dist/bundling-sources/shared_libs/play-runtime/app-runtime-api.ts +94 -5
  7. package/dist/bundling-sources/shared_libs/play-runtime/context.ts +66 -12
  8. package/dist/bundling-sources/shared_libs/play-runtime/ctx-types.ts +10 -0
  9. package/dist/bundling-sources/shared_libs/play-runtime/deployment/runtime-topology.ts +6 -1
  10. package/dist/bundling-sources/shared_libs/play-runtime/deployment/runtime-tuple-recovery.ts +9 -3
  11. package/dist/bundling-sources/shared_libs/play-runtime/docflow-node-io.ts +86 -20
  12. package/dist/bundling-sources/shared_libs/play-runtime/durable-receipt-execution.ts +17 -6
  13. package/dist/bundling-sources/shared_libs/play-runtime/freshness-receipt-execution.ts +22 -6
  14. package/dist/bundling-sources/shared_libs/play-runtime/internal-bootstrap-token.ts +14 -0
  15. package/dist/bundling-sources/shared_libs/play-runtime/output-size-limits.ts +54 -0
  16. package/dist/bundling-sources/shared_libs/play-runtime/play-runs/terminal/postgres-adapter.ts +2 -1
  17. package/dist/bundling-sources/shared_libs/play-runtime/row-failure-summary.ts +1 -0
  18. package/dist/bundling-sources/shared_libs/play-runtime/run-snapshot-stream.ts +4 -1
  19. package/dist/bundling-sources/shared_libs/play-runtime/runner-backends/early-sandbox.ts +62 -6
  20. package/dist/bundling-sources/shared_libs/play-runtime/runtime-operation-contract.ts +14 -0
  21. package/dist/bundling-sources/shared_libs/play-runtime/runtime-receipt-store-adapter.ts +197 -19
  22. package/dist/bundling-sources/shared_libs/play-runtime/runtime-receipt-writer.ts +25 -1
  23. package/dist/bundling-sources/shared_libs/play-runtime/runtime-scheduler-topology.ts +5 -0
  24. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/absurd-runtime-worker.ts +140 -1
  25. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/absurd-wake-policy.ts +419 -0
  26. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/early-sandbox-lane.ts +47 -4
  27. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/postgres-pool.ts +24 -0
  28. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/postgres-rate-scope.ts +1 -1
  29. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/postgres-rate-state.ts +36 -19
  30. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/postgres.ts +380 -51
  31. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/receipt-gateway.ts +21 -10
  32. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/runtime-worker-wake.ts +32 -0
  33. package/dist/bundling-sources/shared_libs/plays/authoring-contract.ts +6 -0
  34. package/dist/bundling-sources/shared_libs/plays/deploy/api-client.ts +3 -1
  35. package/dist/bundling-sources/shared_libs/plays/deploy/run-deployment.ts +34 -4
  36. package/dist/bundling-sources/shared_libs/plays/docflow-recording-lint.ts +512 -0
  37. package/dist/bundling-sources/shared_libs/plays/docflow-requirement.ts +346 -0
  38. package/dist/bundling-sources/shared_libs/plays/docflow-rule-codes.ts +38 -0
  39. package/dist/bundling-sources/shared_libs/plays/docflow-unreached-reason.ts +42 -2
  40. package/dist/bundling-sources/shared_libs/plays/docflow.ts +223 -32
  41. package/dist/bundling-sources/shared_libs/plays/play-check-compact.ts +14 -1
  42. package/dist/bundling-sources/shared_libs/plays/run-result.ts +35 -0
  43. package/dist/cli/{agents-UAXDG4FS.mjs → agents-AHXB7N7Y.mjs} +68 -4
  44. package/dist/cli/{agents-2L73CJHH.js → agents-KBZ7OUZS.js} +95 -31
  45. package/dist/cli/{auth-3B2QB4UH.mjs → auth-3CACO52T.mjs} +5 -5
  46. package/dist/cli/auth-UOHCO5K6.js +44 -0
  47. package/dist/cli/{billing-E7FO622G.js → billing-5KXPGKMO.js} +105 -105
  48. package/dist/cli/{billing-CPBRWG3M.mjs → billing-TSTK63NB.mjs} +9 -9
  49. package/dist/cli/{chunk-3DVWSTAI.mjs → chunk-2GWKBQJZ.mjs} +1 -1
  50. package/dist/cli/{chunk-PNQVB4UD.mjs → chunk-3DJMPID5.mjs} +11 -11
  51. package/dist/cli/{chunk-FBSPHBAF.js → chunk-3ET6NRXP.js} +7 -3
  52. package/dist/cli/{chunk-NZR5PBNP.mjs → chunk-3MWTAM3F.mjs} +3 -3
  53. package/dist/cli/{chunk-ROUNT4NX.mjs → chunk-4ANDW2OT.mjs} +1 -1
  54. package/dist/cli/{chunk-ZH23XGJO.js → chunk-4BSCSQ6I.js} +4 -4
  55. package/dist/cli/{chunk-7QX5PCHP.mjs → chunk-4UEXAMDU.mjs} +2 -2
  56. package/dist/cli/{chunk-3EOET5UB.js → chunk-5XGLDVSD.js} +100 -100
  57. package/dist/cli/{chunk-MRSYC74T.js → chunk-7XXJJVSI.js} +5 -5
  58. package/dist/cli/{chunk-NJGXYYHN.js → chunk-7ZCD7OPO.js} +5 -5
  59. package/dist/cli/{chunk-JF4DUC2F.mjs → chunk-AJJSKKH4.mjs} +2 -2
  60. package/dist/cli/{chunk-XYQMOXP4.mjs → chunk-BHF5UW34.mjs} +1 -1
  61. package/dist/cli/{chunk-POYADK77.js → chunk-BO2TXH5Y.js} +20 -20
  62. package/dist/cli/{chunk-RNZXMOA6.mjs → chunk-BUC2TNF2.mjs} +2 -2
  63. package/dist/cli/{chunk-EGH4JNJP.js → chunk-BUUAFSSN.js} +68 -50
  64. package/dist/cli/{chunk-GZBXN56A.js → chunk-C45E47KC.js} +23 -23
  65. package/dist/cli/{chunk-HP6A3JCX.js → chunk-D4R3AL4F.js} +5 -5
  66. package/dist/cli/{chunk-ABJZQHON.mjs → chunk-DAZRIAXW.mjs} +4 -4
  67. package/dist/cli/{chunk-SKKRESFB.js → chunk-DNOZQGJF.js} +3 -3
  68. package/dist/cli/{chunk-DPLYQITT.js → chunk-DUL6UQ2T.js} +2 -2
  69. package/dist/cli/{chunk-U2QQQNWW.mjs → chunk-ES3S6UXR.mjs} +2 -2
  70. package/dist/cli/{chunk-4TTEAUZV.mjs → chunk-FDAYUP3M.mjs} +3 -3
  71. package/dist/cli/{chunk-V54YQHPV.js → chunk-FEVUIT2U.js} +6 -6
  72. package/dist/cli/{chunk-KDITCSPN.mjs → chunk-FSPEUU3V.mjs} +68 -6
  73. package/dist/cli/{chunk-OUFOJTEJ.mjs → chunk-FZZMCVOS.mjs} +5 -5
  74. package/dist/cli/{chunk-ISN4F6AY.js → chunk-GHOB72U6.js} +13 -13
  75. package/dist/cli/{chunk-LHA45DNY.mjs → chunk-GLYWRTEL.mjs} +3 -3
  76. package/dist/cli/{chunk-LDMCTV2Z.mjs → chunk-HNTIGYRT.mjs} +1 -1
  77. package/dist/cli/{chunk-EB2YLLZJ.js → chunk-IGPHYKEJ.js} +41 -41
  78. package/dist/cli/{chunk-VA35T3AF.js → chunk-ISSYN3DJ.js} +20 -20
  79. package/dist/cli/{chunk-DSHIB2XQ.mjs → chunk-JKQPITEE.mjs} +54 -36
  80. package/dist/cli/{chunk-ZARGHLZZ.mjs → chunk-KMLACXI2.mjs} +7 -3
  81. package/dist/cli/{chunk-DI5MULNX.js → chunk-KQXACHYA.js} +26 -26
  82. package/dist/cli/{chunk-CPZL6Z7D.js → chunk-LW2GKYZW.js} +2 -2
  83. package/dist/cli/{chunk-G5YU6RJ4.mjs → chunk-O2KSPI2M.mjs} +2 -2
  84. package/dist/cli/{chunk-H3KVMALU.js → chunk-O6GT6JD7.js} +9 -9
  85. package/dist/cli/{chunk-4ZAWRCB6.mjs → chunk-OCXWUWUI.mjs} +5 -5
  86. package/dist/cli/{chunk-YPP436NM.js → chunk-QKRDAJ3T.js} +53 -53
  87. package/dist/cli/{chunk-KQEW3EAU.js → chunk-QQESWF6D.js} +16 -16
  88. package/dist/cli/{chunk-CYZSHD66.js → chunk-REX5SUYU.js} +2 -2
  89. package/dist/cli/{chunk-Z3IAEHID.js → chunk-RXIQWG2N.js} +48 -48
  90. package/dist/cli/{chunk-5436ZJPH.js → chunk-S33BN7GZ.js} +3 -3
  91. package/dist/cli/{chunk-JD7P73ZW.mjs → chunk-SGRJJLNV.mjs} +1 -1
  92. package/dist/cli/{chunk-2K6EIL2D.mjs → chunk-TCNYSNVU.mjs} +1 -1
  93. package/dist/cli/{chunk-I5J6HGVR.mjs → chunk-TFPMVSGK.mjs} +2 -2
  94. package/dist/cli/{chunk-6NEMTKTA.mjs → chunk-V73WDQEA.mjs} +5 -5
  95. package/dist/cli/{chunk-Y36SQMSN.js → chunk-VYERVFGB.js} +68 -6
  96. package/dist/cli/{chunk-SYWLWTWM.mjs → chunk-WBRSVML3.mjs} +4 -4
  97. package/dist/cli/{chunk-NVHICORD.mjs → chunk-WW52ANX4.mjs} +2 -2
  98. package/dist/cli/{chunk-3HIJNXRB.js → chunk-XZS35M3Y.js} +10 -10
  99. package/dist/cli/{chunk-ZL3O7F5J.js → chunk-YNYHYL5C.js} +15 -15
  100. package/dist/cli/{chunk-FWB3QR7W.mjs → chunk-ZHE5E2WJ.mjs} +1 -1
  101. package/dist/cli/{chunk-D7J33HTK.mjs → chunk-ZJ2H77VV.mjs} +5 -5
  102. package/dist/cli/{chunk-JUZIMW4S.js → chunk-ZX6UVPGZ.js} +7 -7
  103. package/dist/cli/command-docs.js +2 -2
  104. package/dist/cli/command-docs.mjs +1 -1
  105. package/dist/cli/concurrent-runs-help-H5SZUA5J.js +22 -0
  106. package/dist/cli/{concurrent-runs-help-UFNYQYU2.mjs → concurrent-runs-help-IYELSCHB.mjs} +6 -6
  107. package/dist/cli/{csv-QSDRGLQH.mjs → csv-ENEC3APZ.mjs} +4 -4
  108. package/dist/cli/{csv-ZI5LYFHF.js → csv-X6CP57R4.js} +13 -13
  109. package/dist/cli/{db-ZDL6Q53U.js → db-6HLRSE2M.js} +27 -27
  110. package/dist/cli/{db-WVWXNNMO.mjs → db-YGKRFK4T.mjs} +6 -6
  111. package/dist/cli/{describe-UUQBKUVL.mjs → describe-4SGQEX7K.mjs} +18 -18
  112. package/dist/cli/describe-Q2OYHDVZ.js +50 -0
  113. package/dist/cli/describe-core.d.mts +2 -2
  114. package/dist/cli/describe-core.d.ts +2 -2
  115. package/dist/cli/{executions-SCGHTWTC.js → executions-IC55YJ67.js} +8 -8
  116. package/dist/cli/{executions-QN3OYJKT.mjs → executions-PO2IOSZ7.mjs} +6 -6
  117. package/dist/cli/{feedback-7QPHLXGU.mjs → feedback-6BUD5F4I.mjs} +6 -6
  118. package/dist/cli/{feedback-6QQ7ONLW.js → feedback-BCGQLZ5T.js} +14 -14
  119. package/dist/cli/git-5X3MLBIP.js +26 -0
  120. package/dist/cli/{git-HFPJX573.mjs → git-IN4IBL2K.mjs} +5 -5
  121. package/dist/cli/index.js +148 -148
  122. package/dist/cli/index.mjs +47 -47
  123. package/dist/cli/{integrations-ND2HULSH.js → integrations-R2Z2MDO3.js} +29 -29
  124. package/dist/cli/{integrations-4SZ5O24P.mjs → integrations-ZMGB6NQA.mjs} +7 -7
  125. package/dist/cli/{legacy-noops-WUP3TBR2.mjs → legacy-noops-GIC5OZKP.mjs} +6 -6
  126. package/dist/cli/{legacy-noops-GQF6AYP5.js → legacy-noops-X4JPRPTJ.js} +9 -9
  127. package/dist/cli/{mcp-3GUFYGCQ.mjs → mcp-G4IRJIKK.mjs} +4 -4
  128. package/dist/cli/{mcp-L3YYVEU6.js → mcp-USZKTVL2.js} +24 -24
  129. package/dist/cli/{monitors-OFCVJSH5.mjs → monitors-SNFZPSCY.mjs} +7 -7
  130. package/dist/cli/{monitors-CVZZN5WG.js → monitors-T7LRP7OB.js} +100 -100
  131. package/dist/cli/{org-MQ5AUN7I.js → org-2L2ZZL2P.js} +121 -121
  132. package/dist/cli/{org-3DTAYA52.mjs → org-YTXLKW52.mjs} +6 -6
  133. package/dist/cli/{outcomes-42W24EXG.mjs → outcomes-CJWBIFTA.mjs} +6 -6
  134. package/dist/cli/{outcomes-MGDUYHUD.js → outcomes-O63F57JF.js} +14 -14
  135. package/dist/cli/{play-PD45RNYZ.mjs → play-6UWPUHC6.mjs} +331 -70
  136. package/dist/cli/{play-IMAD7QTV.js → play-T353SULJ.js} +930 -669
  137. package/dist/cli/{providers-DYKHG7NV.mjs → providers-LZABK2UW.mjs} +6 -6
  138. package/dist/cli/{providers-WONHPTRG.js → providers-XORJH2VW.js} +9 -9
  139. package/dist/cli/{quickstart-5QPGHLEX.mjs → quickstart-O4RF7J55.mjs} +4 -4
  140. package/dist/cli/{quickstart-6AAFULGC.js → quickstart-QBNUNPZR.js} +6 -6
  141. package/dist/cli/{run-WOW7QO3W.js → run-2CPMFC6W.js} +44 -44
  142. package/dist/cli/{run-4K6ZU7H7.mjs → run-GBRPFC6P.mjs} +23 -23
  143. package/dist/cli/{search-CKVFWVXQ.mjs → search-G7TS7OFB.mjs} +7 -7
  144. package/dist/cli/search-M3AHFCKQ.js +32 -0
  145. package/dist/cli/{search-output-WWB25JWA.mjs → search-output-BIIJRUCP.mjs} +4 -4
  146. package/dist/cli/{search-output-B5QE7ZNK.js → search-output-NRKLNWSD.js} +6 -6
  147. package/dist/cli/{secrets-SVZB6TSW.mjs → secrets-DN3XEZNH.mjs} +6 -6
  148. package/dist/cli/{secrets-WKIMR346.js → secrets-FUXYSEL5.js} +15 -15
  149. package/dist/cli/{sessions-P3QENG6T.mjs → sessions-PMUTPCTT.mjs} +6 -6
  150. package/dist/cli/sessions-VMBMBGVJ.js +23 -0
  151. package/dist/cli/{settings-V5ABL6D2.mjs → settings-N6GNS2KA.mjs} +12 -12
  152. package/dist/cli/{settings-UIFRGJW3.js → settings-ZDTWCQ6B.js} +85 -85
  153. package/dist/cli/{setup-E67NJTEF.mjs → setup-LJ3KWPSA.mjs} +9 -9
  154. package/dist/cli/{setup-A5MIJU3S.js → setup-PN5TSSJE.js} +49 -49
  155. package/dist/cli/{skills-WLHOQ4DO.mjs → skills-7J42K6VC.mjs} +7 -7
  156. package/dist/cli/skills-CXDENBLF.js +37 -0
  157. package/dist/cli/{tools-EG4KL3BB.mjs → tools-M3S6D6DA.mjs} +17 -17
  158. package/dist/cli/tools-WY2GMOC7.js +57 -0
  159. package/dist/cli/{update-IPFBE6SA.mjs → update-XTVFG74E.mjs} +9 -9
  160. package/dist/cli/update-ZB2IBGXG.js +37 -0
  161. package/dist/cli/{views-ZIBY2RVB.js → views-B4X2FWTF.js} +21 -21
  162. package/dist/cli/{views-XDN6SEWY.mjs → views-UFYRDO4X.mjs} +6 -6
  163. package/dist/cli/{workflow-BLKPBRBT.js → workflow-I2RM2J2J.js} +53 -29
  164. package/dist/cli/{workflow-O2XPMOVL.mjs → workflow-ZLMS3PDE.mjs} +42 -18
  165. package/dist/{client-QznpkWrk.d.ts → client-2QWMJInp.d.ts} +1 -1
  166. package/dist/{client-CmG8MT0x.d.mts → client-7H8TXmLa.d.mts} +1 -1
  167. package/dist/{client-core-CY0jNW0e.d.mts → client-core-BraEuxbg.d.mts} +67 -4
  168. package/dist/{client-core-CXDqfeiB.d.ts → client-core-DRglY5xa.d.ts} +67 -4
  169. package/dist/index.d.mts +3 -3
  170. package/dist/index.d.ts +3 -3
  171. package/dist/index.js +9 -9
  172. package/dist/index.mjs +6 -6
  173. package/dist/install-integrity.json +125 -120
  174. package/dist/plays/bundle-play-file.mjs +5 -0
  175. package/dist/plays/play-description.d.mts +1 -1
  176. package/dist/plays/play-description.d.ts +1 -1
  177. package/dist/plays/run-request.d.mts +1 -1
  178. package/dist/plays/run-request.d.ts +1 -1
  179. package/dist/release.d.mts +3 -3
  180. package/dist/release.d.ts +3 -3
  181. package/dist/release.js +2 -2
  182. package/dist/release.mjs +1 -1
  183. package/dist/server.d.mts +2 -2
  184. package/dist/server.d.ts +2 -2
  185. package/dist/server.js +5 -5
  186. package/dist/server.mjs +3 -3
  187. package/package.json +1 -1
  188. package/dist/cli/auth-ALBG5LF4.js +0 -44
  189. package/dist/cli/concurrent-runs-help-E3YMAO5Q.js +0 -22
  190. package/dist/cli/describe-QB5T47B3.js +0 -50
  191. package/dist/cli/git-4FXTWHXT.js +0 -26
  192. package/dist/cli/search-YZIJS7QU.js +0 -32
  193. package/dist/cli/sessions-VQPGPXMU.js +0 -23
  194. package/dist/cli/skills-GTBK33MV.js +0 -37
  195. package/dist/cli/tools-GPAIPRPQ.js +0 -57
  196. package/dist/cli/update-QLWS32WR.js +0 -37
@@ -0,0 +1,419 @@
1
+ /**
2
+ * Per-queue `absurd_wake` policy for isolated (Preview/dev) release lanes.
3
+ *
4
+ * PostgreSQL takes one cluster-wide lock at commit for every transaction that
5
+ * sent a NOTIFY, listened to or not, and holds it through the commit's WAL
6
+ * flush. On the shared Preview database the engine's unheard queue wakes queued
7
+ * half the active backends behind that lock. An isolated lane normally polls
8
+ * (`shouldUseRuntimeSchedulerDirectNotify`, Preview experiment E5 off), so
9
+ * nobody hears its queue's wakes; polling owns correctness everywhere.
10
+ *
11
+ * The vendored engine (`packages/absurd/sql/absurd.sql`, patch (e)) emits the
12
+ * wake from eight state-owning functions in the one shared `absurd` schema.
13
+ * This Deepline-owned patch rewrites exactly those calls to
14
+ * `absurd.deepline_queue_wake(queue)`, which skips the NOTIFY only for a queue
15
+ * marked in `absurd.deepline_unheard_wake_queues`. A queue without a mark (every
16
+ * Production queue, and every queue on a database where the patch was never
17
+ * installed) notifies exactly as before.
18
+ *
19
+ * The rewrite starts from each function as the database has it installed and
20
+ * swaps only that one call. A branch's own copy of `absurd.sql` never replaces
21
+ * the shared engine's bodies, so one Preview estate's migration cannot move
22
+ * every other estate onto different engine code.
23
+ *
24
+ * The lane's own workers own the mark, from the same decision that decides
25
+ * whether they LISTEN:
26
+ * - a worker that will not LISTEN marks its queue at boot, unless a listener
27
+ * already holds the queue's election lock;
28
+ * - an elected listener clears the mark (retrying until it lands) and then
29
+ * rechecks durable state.
30
+ * Both take one transaction-scoped lock per queue, so a mark can never land
31
+ * after an elected listener cleared it. An engine call that skips its wake
32
+ * holds the same lock shared until it commits, so a listener's clear returns
33
+ * only after every transaction that skipped a wake is visible to the
34
+ * listener's next scan. Only isolated schemas run either step; Production
35
+ * workers never touch the table.
36
+ *
37
+ * The scheduler-schema channels (outbox, terminal, queue) follow the same
38
+ * predicate in `postgresSchedulerNotifySql`.
39
+ */
40
+ import { createHash } from 'node:crypto';
41
+ import { readAbsurdSchemaSql } from './absurd-pool';
42
+
43
+ type QueryClient = {
44
+ query<Row extends Record<string, unknown> = Record<string, unknown>>(
45
+ sql: string,
46
+ params?: unknown[],
47
+ ): Promise<{ rows: Row[] }>;
48
+ };
49
+
50
+ /** Every engine function that emits the patch-(e) queue wake. */
51
+ export const ABSURD_QUEUE_WAKE_FUNCTIONS = [
52
+ 'spawn_task',
53
+ 'complete_run',
54
+ 'schedule_run',
55
+ 'fail_run',
56
+ 'retry_task',
57
+ 'await_event',
58
+ 'emit_event',
59
+ 'cancel_task',
60
+ ] as const;
61
+
62
+ const ENGINE_WAKE_CALL = "perform pg_notify('absurd_wake', p_queue_name);";
63
+ const GUARDED_WAKE_CALL = 'perform absurd.deepline_queue_wake(p_queue_name);';
64
+ const WORKER_WAKE_LEADER_LOCK_PREFIX = 'deepline:absurd-wake:';
65
+ const QUEUE_WAKE_POLICY_LOCK_PREFIX = 'deepline:absurd-wake-policy:';
66
+
67
+ /**
68
+ * The session advisory lock a queue's elected direct listener holds while it
69
+ * LISTENs (`acquirePgNotifyHub` `leaderLockKey`). The mark function reads it.
70
+ */
71
+ export function absurdWorkerWakeLeaderLockKey(queue: string): string {
72
+ return `${WORKER_WAKE_LEADER_LOCK_PREFIX}${queue}`;
73
+ }
74
+
75
+ function countOf(text: string, needle: string): number {
76
+ return text.split(needle).length - 1;
77
+ }
78
+
79
+ function vendoredFunctionSection(sql: string, name: string): string {
80
+ const start = sql.indexOf(`create function absurd.${name} (`);
81
+ if (start < 0) {
82
+ throw new Error(`Absurd wake policy: absurd.${name} is missing.`);
83
+ }
84
+ const end = sql.indexOf('\n$$;', start);
85
+ if (end < 0) {
86
+ throw new Error(`Absurd wake policy: absurd.${name} has no body end.`);
87
+ }
88
+ return sql.slice(start, end);
89
+ }
90
+
91
+ /**
92
+ * The vendored engine must emit its queue wake from exactly the covered
93
+ * functions, once each. A wake added anywhere else, or a covered function that
94
+ * changes how it wakes, fails here and must be reviewed rather than left
95
+ * unguarded.
96
+ */
97
+ export function assertAbsurdEngineWakeCoverage(
98
+ sql: string = readAbsurdSchemaSql(),
99
+ ): void {
100
+ const total = countOf(sql, 'pg_notify(');
101
+ if (total !== ABSURD_QUEUE_WAKE_FUNCTIONS.length) {
102
+ throw new Error(
103
+ `Absurd wake policy covers ${ABSURD_QUEUE_WAKE_FUNCTIONS.length} engine wakes, ` +
104
+ `but absurd.sql calls pg_notify ${total} times. Cover the new call.`,
105
+ );
106
+ }
107
+ for (const name of ABSURD_QUEUE_WAKE_FUNCTIONS) {
108
+ const section = vendoredFunctionSection(sql, name);
109
+ if (
110
+ countOf(section, ENGINE_WAKE_CALL) !== 1 ||
111
+ countOf(section, 'pg_notify(') !== 1
112
+ ) {
113
+ throw new Error(
114
+ `Absurd wake policy: absurd.${name} must emit exactly one queue wake.`,
115
+ );
116
+ }
117
+ }
118
+ }
119
+
120
+ export type AbsurdEngineWakeRewrite = 'guarded' | 'already_guarded';
121
+
122
+ /**
123
+ * Swaps the queue wake in each covered engine function, in the definition the
124
+ * database has installed, for the guarded call. Idempotent. Throws, leaving
125
+ * the caller's transaction to roll back, when an installed function is
126
+ * overloaded or does not emit exactly one wake in the form this rewrite knows.
127
+ */
128
+ async function guardInstalledEngineWakes(
129
+ client: QueryClient,
130
+ ): Promise<Record<string, AbsurdEngineWakeRewrite>> {
131
+ const outcome: Record<string, AbsurdEngineWakeRewrite> = {};
132
+ for (const name of ABSURD_QUEUE_WAKE_FUNCTIONS) {
133
+ const installed = await client.query<{ definition: string }>(
134
+ `SELECT pg_get_functiondef(p.oid) AS definition
135
+ FROM pg_proc p
136
+ JOIN pg_namespace n ON n.oid = p.pronamespace
137
+ WHERE n.nspname = 'absurd' AND p.proname = $1`,
138
+ [name],
139
+ );
140
+ if (installed.rows.length !== 1) {
141
+ throw new Error(
142
+ `Absurd wake policy: expected one installed absurd.${name}, found ${installed.rows.length}.`,
143
+ );
144
+ }
145
+ const definition = installed.rows[0]!.definition;
146
+ const engineWakes = countOf(definition, ENGINE_WAKE_CALL);
147
+ const guardedWakes = countOf(definition, GUARDED_WAKE_CALL);
148
+ const notifies = countOf(definition, 'pg_notify(');
149
+ if (engineWakes === 0 && guardedWakes === 1 && notifies === 0) {
150
+ outcome[name] = 'already_guarded';
151
+ continue;
152
+ }
153
+ if (engineWakes !== 1 || guardedWakes !== 0 || notifies !== 1) {
154
+ throw new Error(
155
+ `Absurd wake policy: installed absurd.${name} does not emit exactly one queue wake (${engineWakes} engine, ${guardedWakes} guarded, ${notifies} pg_notify).`,
156
+ );
157
+ }
158
+ // pg_get_functiondef renders CREATE OR REPLACE with the same signature.
159
+ await client.query(definition.replace(ENGINE_WAKE_CALL, GUARDED_WAKE_CALL));
160
+ outcome[name] = 'guarded';
161
+ }
162
+ return outcome;
163
+ }
164
+
165
+ function quoteLiteral(value: string): string {
166
+ return `'${value.replace(/'/g, "''")}'`;
167
+ }
168
+
169
+ const POLICY_OBJECTS_SQL = `
170
+ create table if not exists absurd.deepline_unheard_wake_queues (
171
+ queue_name text primary key
172
+ references absurd.queues (queue_name) on delete cascade,
173
+ marked_at timestamptz not null default now()
174
+ );
175
+
176
+ create or replace function absurd.deepline_queue_wake (p_queue_name text)
177
+ returns void
178
+ language plpgsql
179
+ as $$
180
+ begin
181
+ if exists (
182
+ select 1
183
+ from absurd.deepline_unheard_wake_queues
184
+ where queue_name = p_queue_name
185
+ ) then
186
+ -- Held until commit: an elected listener's clear takes this lock
187
+ -- exclusively, so it waits for this transaction before it rescans.
188
+ perform pg_advisory_xact_lock_shared(
189
+ hashtextextended(${quoteLiteral(QUEUE_WAKE_POLICY_LOCK_PREFIX)} || p_queue_name, 0)
190
+ );
191
+ -- A clear that committed while this waited restores the wake.
192
+ if exists (
193
+ select 1
194
+ from absurd.deepline_unheard_wake_queues
195
+ where queue_name = p_queue_name
196
+ ) then
197
+ return;
198
+ end if;
199
+ end if;
200
+ perform pg_notify('absurd_wake', p_queue_name);
201
+ end;
202
+ $$;
203
+
204
+ create or replace function absurd.deepline_mark_queue_wake_unheard (p_queue_name text)
205
+ returns text
206
+ language plpgsql
207
+ as $$
208
+ declare
209
+ v_listener_key bigint :=
210
+ hashtextextended(${quoteLiteral(WORKER_WAKE_LEADER_LOCK_PREFIX)} || p_queue_name, 0);
211
+ begin
212
+ perform pg_advisory_xact_lock(
213
+ hashtextextended(${quoteLiteral(QUEUE_WAKE_POLICY_LOCK_PREFIX)} || p_queue_name, 0)
214
+ );
215
+ if exists (
216
+ select 1
217
+ from pg_locks
218
+ where locktype = 'advisory'
219
+ and granted
220
+ and objsubid = 1
221
+ and database = (select oid from pg_database where datname = current_database())
222
+ and classid = ((v_listener_key >> 32) & 4294967295)::oid
223
+ and objid = (v_listener_key & 4294967295)::oid
224
+ ) then
225
+ return 'listener_present';
226
+ end if;
227
+ if not exists (select 1 from absurd.queues where queue_name = p_queue_name) then
228
+ return 'queue_absent';
229
+ end if;
230
+ insert into absurd.deepline_unheard_wake_queues (queue_name)
231
+ values (p_queue_name)
232
+ on conflict (queue_name) do nothing;
233
+ return 'marked';
234
+ end;
235
+ $$;
236
+
237
+ create or replace function absurd.deepline_clear_queue_wake_unheard (p_queue_name text)
238
+ returns boolean
239
+ language plpgsql
240
+ as $$
241
+ begin
242
+ perform pg_advisory_xact_lock(
243
+ hashtextextended(${quoteLiteral(QUEUE_WAKE_POLICY_LOCK_PREFIX)} || p_queue_name, 0)
244
+ );
245
+ delete from absurd.deepline_unheard_wake_queues where queue_name = p_queue_name;
246
+ return found;
247
+ end;
248
+ $$;
249
+ `;
250
+
251
+ /** The mark table and the guard, mark and clear functions. */
252
+ export function readAbsurdQueueWakePolicySql(): string {
253
+ return POLICY_OBJECTS_SQL;
254
+ }
255
+
256
+ /**
257
+ * Identity of the installed policy objects: a digest of their SQL, so a change
258
+ * to them reinstalls. Not a compatibility floor; nothing reads it except the
259
+ * migration deciding whether to reinstall.
260
+ */
261
+ export function absurdQueueWakePolicyMarker(): string {
262
+ return `deepline-queue-wake-policy:${createHash('sha256')
263
+ .update(POLICY_OBJECTS_SQL)
264
+ .digest('hex')
265
+ .slice(0, 16)}`;
266
+ }
267
+
268
+ export function readAbsurdQueueWakePolicyMarkerSql(): string {
269
+ return `
270
+ CREATE OR REPLACE FUNCTION absurd.deepline_queue_wake_policy_marker()
271
+ RETURNS text
272
+ LANGUAGE sql
273
+ AS $marker$
274
+ SELECT ${quoteLiteral(absurdQueueWakePolicyMarker())}::text
275
+ $marker$
276
+ `;
277
+ }
278
+
279
+ /** Reads the installed marker, or null where the patch was never installed. */
280
+ export async function readInstalledAbsurdQueueWakePolicyMarker(
281
+ client: QueryClient,
282
+ ): Promise<string | null> {
283
+ const present = await client.query<{ present: boolean }>(
284
+ `SELECT to_regprocedure('absurd.deepline_queue_wake_policy_marker()') IS NOT NULL AS present`,
285
+ );
286
+ if (present.rows[0]?.present !== true) return null;
287
+ const marker = await client.query<{ marker: string | null }>(
288
+ 'SELECT absurd.deepline_queue_wake_policy_marker() AS marker',
289
+ );
290
+ return marker.rows[0]?.marker ?? null;
291
+ }
292
+
293
+ /**
294
+ * Installs the policy on the database's shared engine; run inside the Absurd
295
+ * bootstrap transaction, under its advisory lock, by an isolated schema's
296
+ * migration only. The objects reinstall when their SQL changed; the engine
297
+ * rewrite is checked on every run and is a no-op once guarded.
298
+ */
299
+ export async function installAbsurdQueueWakePolicy(
300
+ client: QueryClient,
301
+ ): Promise<Record<string, AbsurdEngineWakeRewrite>> {
302
+ assertAbsurdEngineWakeCoverage();
303
+ if (
304
+ (await readInstalledAbsurdQueueWakePolicyMarker(client)) !==
305
+ absurdQueueWakePolicyMarker()
306
+ ) {
307
+ await client.query(POLICY_OBJECTS_SQL);
308
+ await client.query(readAbsurdQueueWakePolicyMarkerSql());
309
+ }
310
+ return guardInstalledEngineWakes(client);
311
+ }
312
+
313
+ async function policyInstalled(
314
+ client: QueryClient,
315
+ fn: string,
316
+ ): Promise<boolean> {
317
+ const present = await client.query<{ present: boolean }>(
318
+ 'SELECT to_regprocedure($1) IS NOT NULL AS present',
319
+ [fn],
320
+ );
321
+ return present.rows[0]?.present === true;
322
+ }
323
+
324
+ export type AbsurdQueueWakeMarkOutcome =
325
+ | 'marked'
326
+ | 'listener_present'
327
+ | 'queue_absent'
328
+ | 'policy_not_installed';
329
+
330
+ /**
331
+ * Marks a queue whose lane does not LISTEN, so its engine wakes stop. Call
332
+ * only from an isolated-schema worker that will not join the queue's LISTEN
333
+ * election. Where the patch is not installed the queue keeps notifying.
334
+ */
335
+ export async function markAbsurdQueueWakeUnheard(
336
+ client: QueryClient,
337
+ queue: string,
338
+ ): Promise<AbsurdQueueWakeMarkOutcome> {
339
+ if (
340
+ !(await policyInstalled(
341
+ client,
342
+ 'absurd.deepline_mark_queue_wake_unheard(text)',
343
+ ))
344
+ ) {
345
+ return 'policy_not_installed';
346
+ }
347
+ const result = await client.query<{ outcome: string }>(
348
+ 'SELECT absurd.deepline_mark_queue_wake_unheard($1) AS outcome',
349
+ [queue],
350
+ );
351
+ const outcome = result.rows[0]?.outcome;
352
+ if (
353
+ outcome !== 'marked' &&
354
+ outcome !== 'listener_present' &&
355
+ outcome !== 'queue_absent'
356
+ ) {
357
+ throw new Error(
358
+ `Absurd queue wake mark returned an unknown outcome: ${String(outcome)}.`,
359
+ );
360
+ }
361
+ return outcome;
362
+ }
363
+
364
+ export type AbsurdQueueWakeClearOutcome =
365
+ | 'cleared'
366
+ | 'not_marked'
367
+ | 'policy_not_installed';
368
+
369
+ /** Restores a queue's engine wakes; called by its elected listener. */
370
+ export async function clearAbsurdQueueWakeUnheard(
371
+ client: QueryClient,
372
+ queue: string,
373
+ ): Promise<AbsurdQueueWakeClearOutcome> {
374
+ if (
375
+ !(await policyInstalled(
376
+ client,
377
+ 'absurd.deepline_clear_queue_wake_unheard(text)',
378
+ ))
379
+ ) {
380
+ return 'policy_not_installed';
381
+ }
382
+ const result = await client.query<{ cleared: boolean }>(
383
+ 'SELECT absurd.deepline_clear_queue_wake_unheard($1) AS cleared',
384
+ [queue],
385
+ );
386
+ return result.rows[0]?.cleared === true ? 'cleared' : 'not_marked';
387
+ }
388
+
389
+ /** Retry cadence for an elected listener whose clear failed. */
390
+ export const ABSURD_QUEUE_WAKE_CLEAR_RETRY_MS = 1_000;
391
+
392
+ /**
393
+ * Run by an isolated lane's worker each time it wins its queue's LISTEN
394
+ * election. Until the clear lands the queue may still be silent, so it retries
395
+ * while this process stays the listener, then wakes the claim loop once to
396
+ * pick up anything submitted while the mark was in place.
397
+ */
398
+ export async function clearAbsurdQueueWakeUnheardForListener(input: {
399
+ clear: () => Promise<AbsurdQueueWakeClearOutcome>;
400
+ stillListening: () => boolean;
401
+ wake: () => void;
402
+ onError: (error: unknown) => void;
403
+ sleep?: (ms: number) => Promise<void>;
404
+ }): Promise<AbsurdQueueWakeClearOutcome | 'listener_lost'> {
405
+ const sleep =
406
+ input.sleep ??
407
+ ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)));
408
+ while (input.stillListening()) {
409
+ try {
410
+ const outcome = await input.clear();
411
+ input.wake();
412
+ return outcome;
413
+ } catch (error) {
414
+ input.onError(error);
415
+ }
416
+ await sleep(ABSURD_QUEUE_WAKE_CLEAR_RETRY_MS);
417
+ }
418
+ return 'listener_lost';
419
+ }
@@ -113,6 +113,22 @@ export type EarlySandboxWorkerCapacity = {
113
113
  readonly draining: boolean;
114
114
  /** Whether the claim loop has a free slot to claim the hinted run with. */
115
115
  hasIdleSlot(): boolean;
116
+ /**
117
+ * Advisory, lock-free read of the hinted org's sandbox capacity
118
+ * (`precheckRuntimeSandboxCapacity`). A full org's run waits for a lease,
119
+ * usually past the adoption window, so its early sandbox would only be
120
+ * reaped (Production 2026-12-01: 73 of 98 capacity-held runs waited 30 s
121
+ * or more). Absent: no check, as before.
122
+ */
123
+ orgSandboxCapacity?(input: {
124
+ orgId: string;
125
+ runId: string;
126
+ /**
127
+ * The hint's carried concurrent-runs entitlement (the launch's
128
+ * `concurrentRunsLimit`). Null: the limit cache or default, as before.
129
+ */
130
+ entitlementLimit: number | null;
131
+ }): Promise<{ full: boolean; limit: number; activeLeases: number }>;
116
132
  };
117
133
 
118
134
  /** A hinted run's early-sandbox switches (E2, PB, CA). */
@@ -269,8 +285,7 @@ export function outstandingEarlySandboxesForOrg(
269
285
  ),
270
286
  );
271
287
  let total = 0;
272
- for (const registry of registries)
273
- total += registry.outstandingForOrg(orgId);
288
+ for (const registry of registries) total += registry.outstandingForOrg(orgId);
274
289
  return total;
275
290
  }
276
291
 
@@ -312,6 +327,11 @@ export function startWorkerLaneEarlySandbox(
312
327
  input: EarlySandboxStartRequest & {
313
328
  /** The hinted run's placement policy id; absent keeps the lane rule. */
314
329
  sandboxPlacementPolicyId?: string | null;
330
+ /**
331
+ * The hint's carried concurrent-runs entitlement; the org capacity check
332
+ * uses it. Absent: the limit cache or default, as before.
333
+ */
334
+ concurrentRunsLimit?: number | null;
315
335
  /** The worker's drain and claim-slot state; absent checks neither. */
316
336
  capacity?: EarlySandboxWorkerCapacity | null;
317
337
  /**
@@ -416,6 +436,29 @@ export function startWorkerLaneEarlySandbox(
416
436
  ? { sandboxRuntimeLimits: input.sandboxRuntimeLimits }
417
437
  : {}),
418
438
  };
439
+ const orgCapacity = input.capacity?.orgSandboxCapacity;
440
+ const startOptions =
441
+ orgCapacity && hintOrgId
442
+ ? {
443
+ createGate: async () => {
444
+ const entitlementLimit = input.concurrentRunsLimit ?? null;
445
+ const capacity = await orgCapacity({
446
+ orgId: hintOrgId,
447
+ runId: input.workflowId,
448
+ entitlementLimit,
449
+ });
450
+ // The limit the check used, so a line shows which one decided.
451
+ const details = {
452
+ limit: capacity.limit,
453
+ activeLeases: capacity.activeLeases,
454
+ entitlementLimit,
455
+ };
456
+ return capacity.full
457
+ ? { reason: 'org_sandbox_capacity_full', ...details }
458
+ : { reason: null, ...details };
459
+ },
460
+ }
461
+ : {};
419
462
  if (
420
463
  !resolveExperimentSwitch(
421
464
  'LH',
@@ -423,7 +466,7 @@ export function startWorkerLaneEarlySandbox(
423
466
  EARLY_SANDBOX_LISTENER_HINT,
424
467
  )
425
468
  ) {
426
- return startEarlySandbox(adapter, request);
469
+ return startEarlySandbox(adapter, request, startOptions);
427
470
  }
428
471
  // LH: admitted only by this worker's desk, bound to the hint's queue,
429
472
  // this worker's current listener generation and one free slot.
@@ -463,7 +506,7 @@ export function startWorkerLaneEarlySandbox(
463
506
  if (refusal) {
464
507
  return refuseEarlySandboxHint({ ...hint, reason: `listener_${refusal}` });
465
508
  }
466
- const started = startEarlySandbox(adapter, request);
509
+ const started = startEarlySandbox(adapter, request, startOptions);
467
510
  if (!started) desk.released(key);
468
511
  return started;
469
512
  }
@@ -143,6 +143,30 @@ export function planetScalePooledSqlRole(connectionString: string): string {
143
143
  return match[1];
144
144
  }
145
145
 
146
+ /**
147
+ * The PlanetScale branch a connection reaches, from its login's suffix
148
+ * (`<role>.<branch id>`), or null for a URL that is not a PlanetScale login.
149
+ * It names the database without its password, so a test route may report it.
150
+ */
151
+ export function planetScaleConnectionBranchId(
152
+ connectionString: string,
153
+ ): string | null {
154
+ try {
155
+ const url = new URL(connectionString);
156
+ if (
157
+ !['postgres:', 'postgresql:'].includes(url.protocol) ||
158
+ !url.hostname.endsWith('.psdb.cloud')
159
+ )
160
+ return null;
161
+ const match = /^[A-Za-z_][A-Za-z0-9_]*\.([A-Za-z0-9_]+)$/.exec(
162
+ decodeURIComponent(url.username),
163
+ );
164
+ return match ? match[1]! : null;
165
+ } catch {
166
+ return null;
167
+ }
168
+ }
169
+
146
170
  /**
147
171
  * Canonical env var for the workflow runtime control-plane Postgres
148
172
  * (scheduler queue, leases, receipts, outbox). Hard-cutover runtime wiring
@@ -126,7 +126,7 @@ export function acquireRateScopeSql(
126
126
  AND h.retry_at_ms > 0
127
127
  AND GREATEST(h.retry_at_ms, h.cool_until_ms) <= nv.now_ms`;
128
128
  return `provider_hold_rows AS (
129
- SELECT * FROM ${table} WHERE bucket_id = $1 FOR UPDATE
129
+ SELECT * FROM ${table} WHERE bucket_id = $1 FOR NO KEY UPDATE
130
130
  ), provider_hold AS (
131
131
  SELECT h.*, ${fastRecovery} AS fast_recovery,
132
132
  ${postHoldProbeDue} AS post_hold_probe_due,
@@ -36,6 +36,23 @@ const RATE_RESERVATION_TABLE = 'rate_reservations';
36
36
  const RATE_RESERVATION_BUCKET_EXPIRY_INDEX =
37
37
  'runtime_scheduler_rate_reservation_bucket_expiry_idx';
38
38
  const RATE_REQUESTER_TABLE = 'rate_requesters';
39
+ /**
40
+ * One hot row per provider bucket. Its lock modes keep dispatch checks off the
41
+ * acquire queue (the table has no key besides `bucket_id`, which nothing
42
+ * updates):
43
+ * - Acquires, grants, refunds and success counts take `FOR NO KEY UPDATE` (a
44
+ * plain UPDATE takes the same). They still queue behind one another.
45
+ * - The provider Retry-After write (penalty) takes `FOR UPDATE`.
46
+ * - Seeding's upsert takes the no-key lock too. It raises `retry_at_ms` only
47
+ * to a legacy rule-row deadline, and the penalty copies its own deadline to
48
+ * those rows in the transaction that writes it here, so seeding never
49
+ * publishes an in-flight Retry-After that checks would need to wait for.
50
+ * - Permit validation and the dispatch claim read with `FOR KEY SHARE`. That
51
+ * conflicts only with `FOR UPDATE`, so a check still waits for an in-flight
52
+ * Retry-After write but never for an acquire, a grant or a success count. A
53
+ * check that does not wait reads the last committed row, the same answer it
54
+ * would get by arriving just before that writer took its lock.
55
+ */
39
56
  const RATE_SCOPE_HOLD_TABLE = 'rate_scope_holds';
40
57
  const PHYSICAL_DISPATCH_RULE_ID = 'runtime:physical-dispatch';
41
58
 
@@ -1933,7 +1950,7 @@ async function acquireWithConcurrency(
1933
1950
  }
1934
1951
  while (true) {
1935
1952
  const lockSql = `SELECT bucket_id FROM ${scopeHoldTableName(input)}
1936
- WHERE bucket_id = $1 FOR UPDATE`;
1953
+ WHERE bucket_id = $1 FOR NO KEY UPDATE`;
1937
1954
  const singleTripOpening = rateStateSingleTripEnabled(requesterId)
1938
1955
  ? renderRateStateStatementForSingleTrip(lockSql, [input.bucketId])
1939
1956
  : null;
@@ -2003,7 +2020,7 @@ async function collapsedGrantWithConcurrency(
2003
2020
  const lock = renderRateStateStatementForSingleTrip(
2004
2021
  `SELECT count(*) AS ${RATE_STATE_SCOPE_LOCK_MARKER} FROM (
2005
2022
  SELECT bucket_id FROM ${scopeHoldTableName(input)}
2006
- WHERE bucket_id = $1 FOR UPDATE
2023
+ WHERE bucket_id = $1 FOR NO KEY UPDATE
2007
2024
  ) AS scope_lock`,
2008
2025
  [input.bucketId],
2009
2026
  );
@@ -2076,17 +2093,14 @@ async function collapsedGrantWithConcurrency(
2076
2093
  [input.bucketId, committedLeaseIds],
2077
2094
  );
2078
2095
  } catch (releaseError) {
2079
- console.error(
2080
- '[rate-state] committed_grant_lease_release_failed',
2081
- {
2082
- bucketId: input.bucketId,
2083
- leases: committedLeaseIds.length,
2084
- error:
2085
- releaseError instanceof Error
2086
- ? releaseError.message
2087
- : String(releaseError),
2088
- },
2089
- );
2096
+ console.error('[rate-state] committed_grant_lease_release_failed', {
2097
+ bucketId: input.bucketId,
2098
+ leases: committedLeaseIds.length,
2099
+ error:
2100
+ releaseError instanceof Error
2101
+ ? releaseError.message
2102
+ : String(releaseError),
2103
+ });
2090
2104
  }
2091
2105
  }
2092
2106
  } else if (open) {
@@ -3030,9 +3044,10 @@ export async function acquirePostgresRateState(
3030
3044
  }
3031
3045
 
3032
3046
  /**
3033
- * Validate a cached permit at the physical dispatch boundary. The shared hold
3034
- * row lock linearizes this check with a concurrent Retry-After write; callers
3035
- * that lose the race return their local slots before reacquiring.
3047
+ * Validate a cached permit at the physical dispatch boundary. The key-share
3048
+ * hold row lock linearizes this check with a concurrent Retry-After write (see
3049
+ * {@link RATE_SCOPE_HOLD_TABLE}); callers that lose the race return their local
3050
+ * slots before reacquiring.
3036
3051
  */
3037
3052
  export async function validatePostgresRateStatePermit(
3038
3053
  client: PostgresSchedulerQueryClient,
@@ -3057,7 +3072,7 @@ export async function validatePostgresRateStatePermit(
3057
3072
  SELECT retry_at_ms
3058
3073
  FROM ${scopeHoldTableName(input)}
3059
3074
  WHERE bucket_id = $1
3060
- FOR SHARE
3075
+ FOR KEY SHARE
3061
3076
  )
3062
3077
  SELECT
3063
3078
  now_value.now_ms AS server_now_ms,
@@ -3125,7 +3140,7 @@ export async function claimPostgresProviderDispatch(
3125
3140
  )
3126
3141
  ) THEN h.refill_per_sec ELSE NULL END AS physical_rps
3127
3142
  FROM ${scopeHoldTableName(input)} h WHERE h.bucket_id = $1
3128
- FOR SHARE OF h
3143
+ FOR KEY SHARE OF h
3129
3144
  ), cadence AS (
3130
3145
  SELECT nv.now_ms,
3131
3146
  GREATEST(COALESCE(s.retry_at_ms, 0), COALESCE(s.cool_until_ms, 0)) AS hold_until_ms,
@@ -4216,7 +4231,7 @@ async function releaseRateStateStatements(
4216
4231
  ) AS now_ms
4217
4232
  ),
4218
4233
  held AS (
4219
- SELECT * FROM ${scopeHoldTableName(input)} WHERE bucket_id = $1 FOR UPDATE
4234
+ SELECT * FROM ${scopeHoldTableName(input)} WHERE bucket_id = $1 FOR NO KEY UPDATE
4220
4235
  ),
4221
4236
  refunded AS (
4222
4237
  DELETE FROM ${reservationTableName(input)}
@@ -4377,6 +4392,8 @@ async function penalizeRateStateStatements(
4377
4392
  FLOOR(EXTRACT(EPOCH FROM clock_timestamp()) * 1000)::bigint
4378
4393
  ) AS now_ms
4379
4394
  ), held AS (
4395
+ -- FOR UPDATE, unlike every other writer: permit checks wait for this
4396
+ -- Retry-After write (see RATE_SCOPE_HOLD_TABLE).
4380
4397
  SELECT * FROM ${scopeHoldTableName(input)} WHERE bucket_id = $1 FOR UPDATE
4381
4398
  ), seeded_hold AS (
4382
4399
  SELECT h.*, CASE WHEN cardinality($6::text[]) > 0