@bastani/atomic 0.10.11-alpha.2 → 0.10.11

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 (447) hide show
  1. package/CHANGELOG.md +307 -0
  2. package/README.md +5 -8
  3. package/dist/_shared/dist-KOELCESV.js +2 -2
  4. package/dist/_shared/fork-row-index-UAUAQRD5.js +2 -2
  5. package/dist/_shared/lib-4PES5P4V.js +2 -2
  6. package/dist/_shared/mode-interactive-sdk-7KXUFI2F.js +6 -6
  7. package/dist/_shared/mode-rpc-sdk-IOPGDYR4.js +5 -5
  8. package/dist/_shared/mode-shared-2QJSCUM6.js +6 -6
  9. package/dist/_shared/p0-cli-BB45ZQY6.js +46 -67
  10. package/dist/_shared/p0-cli-BB45ZQY6.js.map +1 -1
  11. package/dist/_shared/p1a-prewarm-XIU57JHF.js +7 -8
  12. package/dist/_shared/p1a-prewarm-XIU57JHF.js.map +1 -1
  13. package/dist/_shared/{p1b-elig-ENCUPKKJ.js → p1b-elig-TVB5CBLL.js} +36 -8
  14. package/dist/_shared/p1b-elig-TVB5CBLL.js.map +1 -0
  15. package/dist/_shared/p2-shell-main-B2WIALFD.js +6 -3
  16. package/dist/_shared/p2-shell-main-B2WIALFD.js.map +1 -1
  17. package/dist/_shared/runtime-O4KCSG4C.js +3 -3
  18. package/dist/_shared/{sdk-IQMULKFU.js → sdk-B5LEWGGI.js} +1218 -657
  19. package/dist/_shared/sdk-B5LEWGGI.js.map +1 -0
  20. package/dist/_shared/session-data-AHTU7IS6.js +2 -2
  21. package/dist/_shared/session-manager-list-2BLEEZVG.js +1 -1
  22. package/dist/_shared/{startup-0-0-3IXNMFM2.js → startup-0-0-XJJDOIEC.js} +50 -48
  23. package/dist/_shared/startup-0-0-XJJDOIEC.js.map +1 -0
  24. package/dist/_shared/{startup-0-1-7T2IAE7J.js → startup-0-1-M6OWAYHH.js} +540 -136
  25. package/dist/_shared/startup-0-1-M6OWAYHH.js.map +1 -0
  26. package/dist/_shared/startup-0-2-5QHPCEON.js +47 -48
  27. package/dist/_shared/startup-0-2-5QHPCEON.js.map +1 -1
  28. package/dist/_shared/startup-0-3-4ZYBYQNM.js +5 -5
  29. package/dist/_shared/startup-0-4-ZMJV547D.js +12 -7
  30. package/dist/_shared/startup-0-4-ZMJV547D.js.map +1 -1
  31. package/dist/_shared/startup-0-5-YDW47QX6.js +7 -7
  32. package/dist/_shared/startup-0-5-YDW47QX6.js.map +1 -1
  33. package/dist/_shared/startup-10-0-TDQNBDDL.js +6 -6
  34. package/dist/_shared/startup-12-0-55AAXBJZ.js +2 -2
  35. package/dist/_shared/startup-14-0-MLX36RBG.js +4 -5
  36. package/dist/_shared/startup-14-0-MLX36RBG.js.map +1 -1
  37. package/dist/_shared/startup-15-0-YUKGAC63.js +4 -4
  38. package/dist/_shared/startup-15-1-4S7FLMNG.js +19 -27
  39. package/dist/_shared/startup-15-1-4S7FLMNG.js.map +1 -1
  40. package/dist/_shared/startup-8-0-34CBHPZH.js +2144 -249
  41. package/dist/_shared/startup-8-0-34CBHPZH.js.map +1 -1
  42. package/dist/_shared/{startup-8-1-X32CYSXB.js → startup-8-1-LZFXSD3Z.js} +98 -1184
  43. package/dist/_shared/startup-8-1-LZFXSD3Z.js.map +1 -0
  44. package/dist/_shared/storage-command-7MGXLJGZ.js +188 -37
  45. package/dist/_shared/storage-command-7MGXLJGZ.js.map +1 -1
  46. package/dist/_shared/storage-status-K7PX2RXA.js +557 -0
  47. package/dist/_shared/storage-status-K7PX2RXA.js.map +1 -0
  48. package/dist/_shared/task-unsaved-answer-VJ2KTB4V.js +2 -2
  49. package/dist/_shared/team-DOQKICG2.js +376 -0
  50. package/dist/_shared/team-DOQKICG2.js.map +1 -0
  51. package/dist/_shared/tree-outline-MUEPK5B7.js +2 -2
  52. package/dist/builtin/intercom/CHANGELOG.md +88 -0
  53. package/dist/builtin/intercom/README.md +2 -2
  54. package/dist/builtin/intercom/broker/broker.bundle.mjs +1917 -381
  55. package/dist/builtin/intercom/broker/client.ts +8 -0
  56. package/dist/builtin/intercom/broker/database-wake-up-bus.ts +324 -68
  57. package/dist/builtin/intercom/broker/multinode-router.ts +256 -39
  58. package/dist/builtin/intercom/broker/multinode-state-store.ts +71 -5
  59. package/dist/builtin/intercom/broker/open-broker-state.ts +14 -0
  60. package/dist/builtin/intercom/broker/send-order-gate.ts +5 -2
  61. package/dist/builtin/intercom/broker/sql-add-column.ts +50 -5
  62. package/dist/builtin/intercom/broker/sql-ended-child-queue-store.ts +3 -2
  63. package/dist/builtin/intercom/broker/sql-held-send-store.ts +2 -2
  64. package/dist/builtin/intercom/broker/sql-known-session-store.ts +43 -19
  65. package/dist/builtin/intercom/broker/sql-lease-store.ts +473 -121
  66. package/dist/builtin/intercom/broker/sql-outbox-store.ts +821 -79
  67. package/dist/builtin/intercom/broker/sql-pending-ask-store.ts +8 -5
  68. package/dist/builtin/intercom/broker/sql-released-ask-store.ts +12 -5
  69. package/dist/builtin/intercom/broker/sql-restoring-reservation-store.ts +256 -8
  70. package/dist/builtin/intercom/broker/sql-retention.ts +150 -0
  71. package/dist/builtin/intercom/broker/sql-schema.ts +175 -24
  72. package/dist/builtin/intercom/broker/sql-sent-message-authority.ts +74 -19
  73. package/dist/builtin/intercom/broker/wake-up-bus.ts +6 -0
  74. package/dist/builtin/intercom/index.bundle.mjs +14 -4
  75. package/dist/builtin/intercom/package.json +1 -1
  76. package/dist/builtin/mcp/index.bundle.mjs +1 -1
  77. package/dist/builtin/mcp/package.json +1 -1
  78. package/dist/builtin/subagents/CHANGELOG.md +20 -0
  79. package/dist/builtin/subagents/package.json +1 -1
  80. package/dist/builtin/subagents/skills/skill-creator/eval-viewer/generate_review.py +8 -1
  81. package/dist/builtin/subagents/src/extension/index.bundle.mjs +1 -1
  82. package/dist/builtin/web-access/index.bundle.mjs +2 -10
  83. package/dist/builtin/web-access/package.json +1 -1
  84. package/dist/bun/bundled-sqlite.js +41 -0
  85. package/dist/bun/bundled-sqlite.js.map +1 -0
  86. package/dist/cli/args.js +2 -2
  87. package/dist/cli/auth-cli.code.js +4 -4
  88. package/dist/cli/auth-cli.impl.js +3 -3
  89. package/dist/cli/auth-cli.js +3 -3
  90. package/dist/cli/blueprint-command.code.js +3 -3
  91. package/dist/cli/blueprint-command.impl.js +3 -3
  92. package/dist/cli/blueprint-command.js +3 -3
  93. package/dist/cli/intercom-command.code.js +3 -3
  94. package/dist/cli/intercom-command.code.js.map +1 -1
  95. package/dist/cli/intercom-command.impl.js +3 -3
  96. package/dist/cli/intercom-command.js +3 -3
  97. package/dist/cli/list-models.code.js +2 -2
  98. package/dist/cli/list-models.impl.js +3 -3
  99. package/dist/cli/list-models.js +3 -3
  100. package/dist/cli/session-picker.code.js +1 -1
  101. package/dist/cli/session-picker.impl.js +3 -3
  102. package/dist/cli/session-picker.js +3 -3
  103. package/dist/cli/startup-ui.code.js +1 -1
  104. package/dist/cli/startup-ui.impl.js +3 -3
  105. package/dist/cli/startup-ui.js +3 -3
  106. package/dist/cli/storage-command.impl.js +3 -3
  107. package/dist/cli/storage-command.js +3 -3
  108. package/dist/cli/storage-search-session.code.js +3 -3
  109. package/dist/cli/storage-search-session.impl.js +3 -3
  110. package/dist/cli/storage-search-session.js +3 -3
  111. package/dist/cli/team-command.code.js +19 -113
  112. package/dist/cli/team-command.code.js.map +1 -1
  113. package/dist/cli/team-command.impl.js +3 -3
  114. package/dist/cli/team-command.js +3 -3
  115. package/dist/cli.js +5 -18
  116. package/dist/cli.js.map +1 -1
  117. package/dist/core/agent-rehydrate-errors.d.ts +4 -9
  118. package/dist/core/compaction/compactor.d.ts +3 -3
  119. package/dist/core/debug.code.js +1 -1
  120. package/dist/core/debug.impl.js +3 -3
  121. package/dist/core/debug.js +3 -3
  122. package/dist/core/export-html/card-projection.impl.js +3 -3
  123. package/dist/core/export-html/card-projection.js +3 -3
  124. package/dist/core/export-html/index.code.js +4 -4
  125. package/dist/core/export-html/index.code.js.map +1 -1
  126. package/dist/core/export-html/index.impl.js +3 -3
  127. package/dist/core/export-html/index.js +3 -3
  128. package/dist/core/export-html/json-spans.impl.js +3 -3
  129. package/dist/core/export-html/json-spans.js +3 -3
  130. package/dist/core/export-html/oversized-render-inputs.impl.js +3 -3
  131. package/dist/core/export-html/oversized-render-inputs.js +3 -3
  132. package/dist/core/export-html/tool-renderer.impl.js +3 -3
  133. package/dist/core/export-html/tool-renderer.js +3 -3
  134. package/dist/core/extensions/jiti-loader.impl.js +3 -3
  135. package/dist/core/extensions/jiti-loader.js +3 -3
  136. package/dist/core/extensions/jiti-static-loader.impl.js +3 -3
  137. package/dist/core/extensions/jiti-static-loader.js +3 -3
  138. package/dist/core/extensions/loader-host-modules.code.js +1 -1
  139. package/dist/core/extensions/loader-host-modules.impl.js +3 -3
  140. package/dist/core/extensions/loader-host-modules.js +3 -3
  141. package/dist/core/extensions/loader-virtual-modules.js +1 -1
  142. package/dist/core/extensions/runner-context.js +2 -2
  143. package/dist/core/intercom-broker-control-host.code.js +2 -2
  144. package/dist/core/intercom-broker-control-host.impl.js +3 -3
  145. package/dist/core/intercom-broker-control-host.js +3 -3
  146. package/dist/core/intercom-broker-control.code.js +3 -3
  147. package/dist/core/intercom-broker-control.impl.js +3 -3
  148. package/dist/core/intercom-broker-control.js +3 -3
  149. package/dist/core/package-manager-storage-adapters.code.js +1 -1
  150. package/dist/core/package-manager-storage-adapters.impl.js +3 -3
  151. package/dist/core/package-manager-storage-adapters.js +3 -3
  152. package/dist/core/process-start-token.d.ts +12 -3
  153. package/dist/core/process-tree-containment.d.ts +16 -0
  154. package/dist/core/sdk-types.d.ts +1 -2
  155. package/dist/core/sdk-types.js.map +1 -1
  156. package/dist/core/sdk.code.js +3 -3
  157. package/dist/core/sdk.impl.js +3 -3
  158. package/dist/core/sdk.js +3 -3
  159. package/dist/core/session-manager-core.js +5 -5
  160. package/dist/core/session-manager-list.impl.js +3 -3
  161. package/dist/core/session-manager-list.js +3 -3
  162. package/dist/core/session-manager.code.js +1 -1
  163. package/dist/core/session-manager.impl.js +3 -3
  164. package/dist/core/session-manager.js +3 -3
  165. package/dist/core/session-storage.code.js +1 -1
  166. package/dist/core/session-storage.impl.js +3 -3
  167. package/dist/core/session-storage.js +3 -3
  168. package/dist/core/settings-schema.d.ts +0 -3
  169. package/dist/core/storage/added-exports-0-10-11.js +19 -0
  170. package/dist/core/storage/added-exports-0-10-11.js.map +1 -0
  171. package/dist/core/storage/creation-time.js +105 -0
  172. package/dist/core/storage/creation-time.js.map +1 -0
  173. package/dist/core/storage/database.d.ts +25 -5
  174. package/dist/core/storage/database.js.map +1 -1
  175. package/dist/core/storage/dialect.d.ts +1 -1
  176. package/dist/core/storage/dialect.js +1 -1
  177. package/dist/core/storage/dialect.js.map +1 -1
  178. package/dist/core/storage/errors.d.ts +13 -13
  179. package/dist/core/storage/errors.js +10 -16
  180. package/dist/core/storage/errors.js.map +1 -1
  181. package/dist/core/storage/fenced-paths.d.ts +18 -6
  182. package/dist/core/storage/fenced-paths.js +18 -6
  183. package/dist/core/storage/fenced-paths.js.map +1 -1
  184. package/dist/core/storage/file-identity.d.ts +2 -0
  185. package/dist/core/storage/file-identity.js +24 -8
  186. package/dist/core/storage/file-identity.js.map +1 -1
  187. package/dist/core/storage/index.d.ts +3 -2
  188. package/dist/core/storage/index.js +5 -3
  189. package/dist/core/storage/index.js.map +1 -1
  190. package/dist/core/storage/libsql-removed.d.ts +71 -0
  191. package/dist/core/storage/libsql-removed.js +123 -0
  192. package/dist/core/storage/libsql-removed.js.map +1 -0
  193. package/dist/core/storage/migrations.d.ts +78 -14
  194. package/dist/core/storage/migrations.js +375 -49
  195. package/dist/core/storage/migrations.js.map +1 -1
  196. package/dist/core/storage/node-sqlite-file-gate.js +0 -15
  197. package/dist/core/storage/node-sqlite-file-gate.js.map +1 -1
  198. package/dist/core/storage/node-sqlite-thread.js +215 -30
  199. package/dist/core/storage/node-sqlite-thread.js.map +1 -1
  200. package/dist/core/storage/node-sqlite.js +484 -72
  201. package/dist/core/storage/node-sqlite.js.map +1 -1
  202. package/dist/core/storage/offline-snapshot-file.impl.js +3 -3
  203. package/dist/core/storage/offline-snapshot-file.js +3 -3
  204. package/dist/core/storage/prefix.d.ts +1 -1
  205. package/dist/core/storage/prefix.js +9 -2
  206. package/dist/core/storage/prefix.js.map +1 -1
  207. package/dist/core/storage/process-selection.d.ts +5 -5
  208. package/dist/core/storage/provider.js +2 -2
  209. package/dist/core/storage/schema-catalog.d.ts +76 -15
  210. package/dist/core/storage/schema-catalog.js +359 -68
  211. package/dist/core/storage/schema-catalog.js.map +1 -1
  212. package/dist/core/storage/selection.d.ts +7 -82
  213. package/dist/core/storage/selection.js +20 -235
  214. package/dist/core/storage/selection.js.map +1 -1
  215. package/dist/core/storage/session/branch-fork-source.code.js +2 -2
  216. package/dist/core/storage/session/branch-fork-source.impl.js +3 -3
  217. package/dist/core/storage/session/branch-fork-source.js +3 -3
  218. package/dist/core/storage/session/card-view.impl.js +3 -3
  219. package/dist/core/storage/session/card-view.js +3 -3
  220. package/dist/core/storage/session/child-reader.code.js +3 -3
  221. package/dist/core/storage/session/child-reader.impl.js +3 -3
  222. package/dist/core/storage/session/child-reader.js +3 -3
  223. package/dist/core/storage/session/chunked-resume-projection.impl.js +3 -3
  224. package/dist/core/storage/session/chunked-resume-projection.js +3 -3
  225. package/dist/core/storage/session/expanded-child-details.code.js +2 -2
  226. package/dist/core/storage/session/expanded-child-details.impl.js +3 -3
  227. package/dist/core/storage/session/expanded-child-details.js +3 -3
  228. package/dist/core/storage/session/fork-detach.d.ts +11 -1
  229. package/dist/core/storage/session/fork-row-bytes.impl.js +3 -3
  230. package/dist/core/storage/session/fork-row-bytes.js +3 -3
  231. package/dist/core/storage/session/fork-row-index.impl.js +3 -3
  232. package/dist/core/storage/session/fork-row-index.js +3 -3
  233. package/dist/core/storage/session/fork-staging.code.js +4 -7
  234. package/dist/core/storage/session/fork-staging.code.js.map +1 -1
  235. package/dist/core/storage/session/fork-staging.impl.js +3 -3
  236. package/dist/core/storage/session/fork-staging.js +3 -3
  237. package/dist/core/storage/session/fork-sweep.js +31 -7
  238. package/dist/core/storage/session/fork-sweep.js.map +1 -1
  239. package/dist/core/storage/session/fork-window.code.js +3 -3
  240. package/dist/core/storage/session/fork-window.impl.js +3 -3
  241. package/dist/core/storage/session/fork-window.js +3 -3
  242. package/dist/core/storage/session/history-pages.impl.js +3 -3
  243. package/dist/core/storage/session/history-pages.js +3 -3
  244. package/dist/core/storage/session/jsonl-entry-projection.impl.js +3 -3
  245. package/dist/core/storage/session/jsonl-entry-projection.js +3 -3
  246. package/dist/core/storage/session/jsonl-session-lock.d.ts +100 -0
  247. package/dist/core/storage/session/jsonl-session-store.d.ts +46 -24
  248. package/dist/core/storage/session/jsonl-session-store.impl.js +3 -3
  249. package/dist/core/storage/session/jsonl-session-store.js +3 -3
  250. package/dist/core/storage/session/memory-session-store.impl.js +3 -3
  251. package/dist/core/storage/session/memory-session-store.js +3 -3
  252. package/dist/core/storage/session/pinned-branch-resume.code.js +3 -3
  253. package/dist/core/storage/session/pinned-branch-resume.impl.js +3 -3
  254. package/dist/core/storage/session/pinned-branch-resume.js +3 -3
  255. package/dist/core/storage/session/released-history-files.code.js +9 -9
  256. package/dist/core/storage/session/released-history-files.code.js.map +1 -1
  257. package/dist/core/storage/session/released-history-files.impl.js +3 -3
  258. package/dist/core/storage/session/released-history-files.js +3 -3
  259. package/dist/core/storage/session/resident-fork-rows.impl.js +3 -3
  260. package/dist/core/storage/session/resident-fork-rows.js +3 -3
  261. package/dist/core/storage/session/session-resume.impl.js +3 -3
  262. package/dist/core/storage/session/session-resume.js +3 -3
  263. package/dist/core/storage/session/session-search-index.d.ts +52 -5
  264. package/dist/core/storage/session/snapshot-cut.impl.js +3 -3
  265. package/dist/core/storage/session/snapshot-cut.js +3 -3
  266. package/dist/core/storage/session/snapshot-history.code.js +3 -3
  267. package/dist/core/storage/session/snapshot-history.impl.js +3 -3
  268. package/dist/core/storage/session/snapshot-history.js +3 -3
  269. package/dist/core/storage/session/sql-session-store.code.js +1 -1
  270. package/dist/core/storage/session/sql-session-store.d.ts +99 -18
  271. package/dist/core/storage/session/sql-session-store.impl.js +3 -3
  272. package/dist/core/storage/session/sql-session-store.js +3 -3
  273. package/dist/core/storage/session/tree-outline.impl.js +3 -3
  274. package/dist/core/storage/session/tree-outline.js +3 -3
  275. package/dist/core/storage/session/tree-presentation.impl.js +3 -3
  276. package/dist/core/storage/session/tree-presentation.js +3 -3
  277. package/dist/core/storage/sqlite-facade.d.ts +12 -1
  278. package/dist/core/storage/sqlite-facade.js +310 -33
  279. package/dist/core/storage/sqlite-facade.js.map +1 -1
  280. package/dist/core/storage/sqlite-open-batch.js +10 -0
  281. package/dist/core/storage/sqlite-open-batch.js.map +1 -0
  282. package/dist/core/storage/storage-status.code.js +1 -1
  283. package/dist/core/storage/storage-status.impl.js +3 -3
  284. package/dist/core/storage/storage-status.js +3 -3
  285. package/dist/core/storage/team.code.js +1 -1
  286. package/dist/core/storage/team.d.ts +26 -115
  287. package/dist/core/storage/team.impl.js +3 -3
  288. package/dist/core/storage/team.js +3 -3
  289. package/dist/core/structured-output/index.code.js +1 -1
  290. package/dist/core/structured-output/index.impl.js +3 -3
  291. package/dist/core/structured-output/index.js +3 -3
  292. package/dist/core/tasks/task-completion-entry.impl.js +3 -3
  293. package/dist/core/tasks/task-completion-entry.js +3 -3
  294. package/dist/core/tasks/task-file-history.code.js +3 -3
  295. package/dist/core/tasks/task-file-history.impl.js +3 -3
  296. package/dist/core/tasks/task-file-history.js +3 -3
  297. package/dist/core/tasks/task-reference-archive.code.js +4 -4
  298. package/dist/core/tasks/task-reference-archive.js +3 -3
  299. package/dist/core/tasks/task-reference-identity.js +3 -3
  300. package/dist/core/tasks/task-reference-stream.impl.js +3 -3
  301. package/dist/core/tasks/task-reference-stream.js +3 -3
  302. package/dist/core/tasks/task-unsaved-answer.impl.js +3 -3
  303. package/dist/core/tasks/task-unsaved-answer.js +3 -3
  304. package/dist/core/tasks/task-view-source.code.js +1 -1
  305. package/dist/core/tasks/task-view-source.impl.js +3 -3
  306. package/dist/core/tasks/task-view-source.js +3 -3
  307. package/dist/core/tools/history-tasks.d.ts +3 -2
  308. package/dist/core/tools/read-url.code.js +4 -4
  309. package/dist/core/tools/read-url.impl.js +3 -3
  310. package/dist/core/tools/read-url.js +3 -3
  311. package/dist/core/worktree-snapshot/blob-store.d.ts +44 -5
  312. package/dist/core/worktree-snapshot/blob-store.js +553 -30
  313. package/dist/core/worktree-snapshot/blob-store.js.map +1 -1
  314. package/dist/core/worktree-snapshot/errors.code.js +2 -2
  315. package/dist/core/worktree-snapshot/errors.impl.js +3 -3
  316. package/dist/core/worktree-snapshot/errors.js +3 -3
  317. package/dist/core/worktree-snapshot/fork-blob-guard.js +81 -0
  318. package/dist/core/worktree-snapshot/fork-blob-guard.js.map +1 -0
  319. package/dist/core/worktree-snapshot/fork-snapshot-index.js +208 -50
  320. package/dist/core/worktree-snapshot/fork-snapshot-index.js.map +1 -1
  321. package/dist/core/worktree-snapshot/session-index-reset.code.js +4 -0
  322. package/dist/core/worktree-snapshot/session-index-reset.code.js.map +1 -1
  323. package/dist/core/worktree-snapshot/session-index-reset.impl.js +3 -3
  324. package/dist/core/worktree-snapshot/session-index-reset.js +3 -3
  325. package/dist/extensions/codemode/execute.code.js +1 -1
  326. package/dist/extensions/codemode/execute.impl.js +3 -3
  327. package/dist/extensions/codemode/execute.js +3 -3
  328. package/dist/extensions/codemode/renderer.code.js +2 -2
  329. package/dist/extensions/codemode/renderer.impl.js +3 -3
  330. package/dist/extensions/codemode/renderer.js +3 -3
  331. package/dist/extensions/mcp/cli.code.js +3 -3
  332. package/dist/extensions/mcp/cli.impl.js +3 -3
  333. package/dist/extensions/mcp/cli.js +3 -3
  334. package/dist/extensions/mcp/cli.lazy.code.js +2 -2
  335. package/dist/extensions/mcp/cli.lazy.impl.js +3 -3
  336. package/dist/extensions/mcp/cli.lazy.js +3 -3
  337. package/dist/extensions/mcp/runtime.code.js +1 -1
  338. package/dist/extensions/mcp/runtime.impl.js +3 -3
  339. package/dist/extensions/mcp/runtime.js +3 -3
  340. package/dist/index.d.ts +3 -1
  341. package/dist/index.js +5 -5
  342. package/dist/main-first-time-setup.code.js +1 -1
  343. package/dist/main-first-time-setup.impl.js +3 -3
  344. package/dist/main-first-time-setup.js +3 -3
  345. package/dist/main.js +1 -1
  346. package/dist/modes/interactive/components/stored-tree-view.code.js +2 -2
  347. package/dist/modes/interactive/components/stored-tree-view.impl.js +3 -3
  348. package/dist/modes/interactive/components/stored-tree-view.js +3 -3
  349. package/dist/modes/interactive/components/user-message-selector-archive.impl.js +3 -3
  350. package/dist/modes/interactive/components/user-message-selector-archive.js +3 -3
  351. package/dist/modes/interactive/startup-shell-eligibility.js +1 -1
  352. package/dist/modes/interactive-engine/engine-prewarm.d.ts +1 -1
  353. package/dist/modes/print-mode.js +1 -1
  354. package/dist/package-manager-cli.code.js +6 -6
  355. package/dist/package-manager-cli.impl.js +3 -3
  356. package/dist/package-manager-cli.js +3 -3
  357. package/dist/rpc-entry.js +1 -1
  358. package/dist/startup-files.json +1 -1
  359. package/dist/startup-stages/10.js +1 -1
  360. package/dist/startup-stages/11.js +1 -1
  361. package/dist/startup-stages/12.js +1 -1
  362. package/dist/startup-stages/2.js +2 -4
  363. package/dist/startup-stages/3.js +1 -3
  364. package/dist/startup-stages/4.js +1 -2
  365. package/dist/startup-stages/5.js +1 -1
  366. package/dist/startup-stages/6.js +5 -7
  367. package/dist/startup-stages/7.js +3 -10
  368. package/dist/startup-stages/8.js +7 -2
  369. package/dist/startup-stages/9.js +1 -7
  370. package/dist/startup-stages/stages.json +1 -1
  371. package/dist/utils/compile-cache-deferral.js +8 -13
  372. package/dist/utils/compile-cache-deferral.js.map +1 -1
  373. package/dist/utils/compile-cache-warmup-host.js +3 -4
  374. package/dist/utils/compile-cache-warmup-host.js.map +1 -1
  375. package/dist/utils/compile-cache.js +12 -100
  376. package/dist/utils/compile-cache.js.map +1 -1
  377. package/dist/utils/startup-database-spare.code.js +2 -2
  378. package/dist/utils/startup-database-spare.impl.js +3 -3
  379. package/dist/utils/startup-database-spare.js +3 -3
  380. package/dist/utils/tools-manager.code.js +1 -1
  381. package/dist/utils/tools-manager.impl.js +3 -3
  382. package/dist/utils/tools-manager.js +3 -3
  383. package/dist/utils/worker-threads.js +2 -15
  384. package/dist/utils/worker-threads.js.map +1 -1
  385. package/docs/build.md +3 -3
  386. package/docs/changelog.mdx +1498 -69
  387. package/docs/compaction/reference.md +5 -5
  388. package/docs/compaction.md +7 -9
  389. package/docs/containerization.md +2 -2
  390. package/docs/custom-provider/api-reference.md +1 -1
  391. package/docs/docs.json +37 -10
  392. package/docs/environment-variables.md +0 -2
  393. package/docs/extensions/api-reference.md +4 -4
  394. package/docs/getting-started/installation.md +3 -0
  395. package/docs/guides/configuration.md +1 -1
  396. package/docs/guides/non-interactive.md +1 -1
  397. package/docs/guides/resume-on-any-machine.md +14 -22
  398. package/docs/guides/team-setup.md +56 -83
  399. package/docs/guides.md +2 -4
  400. package/docs/herdr.md +1 -1
  401. package/docs/index.md +1 -1
  402. package/docs/intercom/operations.md +26 -21
  403. package/docs/intercom/reference.md +2 -2
  404. package/docs/intercom.md +1 -1
  405. package/docs/libraries/storage-postgres.md +9 -9
  406. package/docs/libraries.md +2 -3
  407. package/docs/models-configuration.md +2 -2
  408. package/docs/models.md +2 -3
  409. package/docs/packages/authoring.md +7 -7
  410. package/docs/packages.md +1 -1
  411. package/docs/programmatic.md +2 -2
  412. package/docs/quickstart.md +1 -1
  413. package/docs/reference/cli.md +6 -11
  414. package/docs/reference.md +2 -2
  415. package/docs/rpc/extension-ui.md +2 -2
  416. package/docs/sdk/reference.md +5 -4
  417. package/docs/sdk/storage.md +8 -92
  418. package/docs/sdk/structured-decisions.md +1 -1
  419. package/docs/sdk/web-server.md +3 -3
  420. package/docs/sdk.md +14 -4
  421. package/docs/security.md +1 -1
  422. package/docs/session-format.md +5 -5
  423. package/docs/sessions.md +29 -49
  424. package/docs/settings.md +7 -8
  425. package/docs/storage/custom-adapters.md +255 -0
  426. package/docs/storage/jsonl.md +117 -0
  427. package/docs/{guides/postgres-pgbouncer.md → storage/postgres/pgbouncer.md} +66 -68
  428. package/docs/storage/postgres/tuning.md +337 -0
  429. package/docs/storage/postgres.md +556 -0
  430. package/docs/storage/sqlite.md +99 -0
  431. package/docs/storage.md +326 -990
  432. package/docs/subagents/authoring.md +1 -1
  433. package/docs/subagents.md +2 -2
  434. package/docs/tools.md +1 -1
  435. package/docs/worktree-snapshots.md +2 -2
  436. package/package.json +9 -9
  437. package/schemas/models.schema.json +2 -2
  438. package/schemas/settings.schema.json +0 -14
  439. package/dist/_shared/p1b-elig-ENCUPKKJ.js.map +0 -1
  440. package/dist/_shared/sdk-IQMULKFU.js.map +0 -1
  441. package/dist/_shared/startup-0-0-3IXNMFM2.js.map +0 -1
  442. package/dist/_shared/startup-0-1-7T2IAE7J.js.map +0 -1
  443. package/dist/_shared/startup-8-1-X32CYSXB.js.map +0 -1
  444. package/dist/core/intercom-broker-control.d.ts +0 -129
  445. package/dist/startup-stages/13.js +0 -1
  446. package/docs/guides/postgres-tuning.md +0 -311
  447. package/docs/libraries/storage-libsql.md +0 -97
@@ -25,17 +25,49 @@ import {
25
25
  type OutboxEnqueueRequest,
26
26
  type OutboxEnqueueResult,
27
27
  type OutboxFrame,
28
+ type OutboxReleaseClaimResult,
29
+ type OutboxRenewClaimResult,
28
30
  type OutboxRow,
29
31
  type OutboxRowState,
30
32
  type OutboxStore,
31
33
  type StateStoreInvalidReason,
32
34
  } from "./multinode-state-store.js";
35
+ import { wakeUpNotices } from "./database-wake-up-bus.js";
33
36
  import { addMissingColumns } from "./sql-add-column.js";
34
- import { ensureBrokerSchema, withBrokerSchemaCatalog } from "./sql-schema.js";
37
+ import { deleteInBatches, SETTLED, storeNow, UNDELIVERED } from "./sql-retention.js";
38
+ import type { OutboxReservation } from "./sql-sent-message-authority.js";
39
+ import { ensureBrokerSchema, RETRY_UNAPPLIED, withBrokerSchemaCatalog } from "./sql-schema.js";
35
40
 
36
- const UNDELIVERED = "state IN ('queued', 'claimed')";
41
+ /**
42
+ * The settings a PostgreSQL send that runs in one round trip (`enqueueAtOnce`) records its decisions in, for the
43
+ * statements after the one that made them: whether the recipient's queue has room for the row, and which reservation
44
+ * of the message the send deletes if its row is not queued.
45
+ */
46
+ const SEND_ROOM = "atomic.intercom_send_room";
47
+ const SEND_FORGET = "atomic.intercom_send_forget";
48
+ /**
49
+ * The settings a one-round-trip send to a recipient its sender found offline records, for the statements after the row's
50
+ * insert: the broker holding the recipient's live presence, read with the insert, the row's sequence and recipient, and whether the
51
+ * hint log took the send's lock without waiting, so its wake-up hint was written.
52
+ */
53
+ const SEND_WAKE = "atomic.intercom_send_wake";
54
+ const SEND_WAKE_VERSION = "atomic.intercom_send_wake_version";
55
+ const SEND_WAKE_TARGET = "atomic.intercom_send_wake_target";
56
+ const SEND_HINT = "atomic.intercom_send_hint";
57
+ /**
58
+ * The settings a one-round-trip PostgreSQL delivery settlement records for the statements after its update: the
59
+ * unmatched claim ids to look up, the distinct remote origin brokers to wake with outcome hints, and whether the hint
60
+ * log took the settlement's lock without waiting (#6715).
61
+ */
62
+ const SETTLE_UNMATCHED = "atomic.intercom_settle_unmatched";
63
+ const SETTLE_WAKE = "atomic.intercom_settle_wake";
64
+ const SETTLE_HINT = "atomic.intercom_settle_hint";
37
65
  /** The setting a PostgreSQL claim transaction records in that its recipient has undelivered rows, and its locks are held. */
38
66
  const CLAIM_GATE = "atomic.intercom_outbox_claim";
67
+ /** The setting a PostgreSQL batched renewal records in when fewer rows renewed than it was given, so its follow-up read runs. */
68
+ const RENEW_MISSES = "atomic.intercom_renew_misses";
69
+ /** The setting a PostgreSQL batch claim release records in when fewer rows matched than were given (#6713). */
70
+ const RELEASE_MISSES = "atomic.intercom_release_misses";
39
71
  /** The most `markDelivered` calls one transaction settles together (#6560). */
40
72
  const MARK_DELIVERED_BATCH_MAX = 100;
41
73
 
@@ -79,6 +111,8 @@ function toRow(record: OutboxRecord): OutboxRow {
79
111
 
80
112
  const isSettled = (record: OutboxRecord): boolean => record.state === "delivered" || record.state === "failed";
81
113
 
114
+ const renewedAnswer = () => ({ status: "renewed" }) as const;
115
+
82
116
  /**
83
117
  * #5607: the wake-up hint written with an offline recipient's row failed, so neither was written. The hint is only a
84
118
  * hint: the caller writes the row again without it (`withoutFailedWake`).
@@ -117,6 +151,16 @@ export interface SqlOutboxStore extends OutboxStore {
117
151
  * connection sends them with the transaction's start instead of a round trip each (#6560).
118
152
  */
119
153
  enqueueLeading(request: OutboxEnqueueRequest): readonly SqliteStatement[];
154
+ /**
155
+ * PostgreSQL: `enqueue`, and with `reservation` a send that reserves its message with it as `enqueueIn` does under
156
+ * its guard, in one transaction of the recipient's domain whose every decision the database makes, so it is one round
157
+ * trip and holds the recipient's lock domain for no round trip at all, a wake-up hint for an offline recipient's host
158
+ * included. Undefined for a request that `enqueueIn` refuses, which takes `enqueueIn`'s way.
159
+ */
160
+ enqueueAtOnce?(
161
+ request: OutboxEnqueueRequest,
162
+ reservation?: OutboxReservation,
163
+ ): Promise<OutboxEnqueueResult> | undefined;
120
164
  }
121
165
 
122
166
  /**
@@ -157,7 +201,15 @@ export async function withoutFailedWake<T>(
157
201
  * The lock domain of one recipient's sends, `<outbox>:<recipient>`: a send reserves its message and queues its row in
158
202
  * one transaction of it (`reserveAndEnqueue`, `enqueue`), so sends to one recipient run one at a time, and commit their
159
203
  * rows in the order of their sequence, and a send's checks of that recipient's queue (its size budget) hold until it
160
- * commits. Sends to other recipients, claims and every write of one row run beside them (#6560).
204
+ * commits. Sends to other recipients, claims and every write of one row run beside them (#6560). A send that a lock
205
+ * timeout ended runs again before the next send to that recipient this process makes starts (`RETRY_UNAPPLIED`).
206
+ *
207
+ * Sends to one recipient deliberately exclude one another, though a send holds the lock only while the database runs its
208
+ * statements, never across a round trip. Letting them share it (with a claim excluding them instead) would let them run
209
+ * side by side, but rows would then commit out of sequence order: a broker of an earlier release, which claims without
210
+ * waiting for sends, could hand a recipient's later message out before an earlier one during a rolling upgrade, and two
211
+ * sends could both see room for the last message the recipient's queue accepts and exceed its size budget. The time it
212
+ * would save, a few milliseconds per send, is not worth either.
161
213
  */
162
214
  export function recipientTransaction(
163
215
  database: SqliteDatabase,
@@ -165,7 +217,7 @@ export function recipientTransaction(
165
217
  targetIdentity: string,
166
218
  ): SqliteTransactionOptions {
167
219
  const outbox = `${validateStoragePrefix(prefix, dialectOf(database).name)}intercom_outbox`;
168
- return { concurrency: { kind: "serial", domain: `${outbox}:${targetIdentity}` } };
220
+ return { ...RETRY_UNAPPLIED, concurrency: { kind: "serial", domain: `${outbox}:${targetIdentity}` } };
169
221
  }
170
222
 
171
223
  /**
@@ -174,7 +226,10 @@ export function recipientTransaction(
174
226
  * transactions an older broker runs on these tables (#6560).
175
227
  */
176
228
  export function rowTransaction(): SqliteTransactionOptions {
177
- return { concurrency: { kind: "fenced", audit: fencedPath("intercom-outbox-row"), excludesSerial: true } };
229
+ return {
230
+ ...RETRY_UNAPPLIED,
231
+ concurrency: { kind: "fenced", audit: fencedPath("intercom-outbox-row"), excludesSerial: true },
232
+ };
178
233
  }
179
234
 
180
235
  /**
@@ -193,7 +248,7 @@ export function openSqlOutboxStore(options: IntercomBrokerStateOptions): Promise
193
248
  async function openOutboxStoreInCatalog(options: IntercomBrokerStateOptions): Promise<SqlOutboxStore> {
194
249
  const { database } = options;
195
250
  const table = `${validateStoragePrefix(options.prefix, dialectOf(database).name)}intercom_outbox`;
196
- const { types, nowMs, greatest, lockClause, name: dialect } = dialectOf(database);
251
+ const { types, nowMs, greatest, lockClause, jsonValues, name: dialect } = dialectOf(database);
197
252
  /** Claim writes and expiry: each decides on the rows it locks (#6560). */
198
253
  const fenced = rowTransaction();
199
254
  const ageSince = (column: string) => greatest("0", `${nowMs} - ${column}`);
@@ -214,18 +269,14 @@ async function openOutboxStoreInCatalog(options: IntercomBrokerStateOptions): Pr
214
269
  failure_reason TEXT,
215
270
  settled_at ${types.int}
216
271
  );
217
- CREATE INDEX IF NOT EXISTS ${table}_target ON ${table}(target_identity, state, sequence);
218
272
  `;
219
273
  await ensureBrokerSchema(database, options.prefix, "outbox", (tx) => tx.exec(schema));
220
274
  // #3983: added later; a table from an older broker gets the column, and an older broker ignores it.
221
275
  await addMissingColumns(database, table, { saving_at: types.int });
222
276
  // #4896: when the row was queued and the size of its frame; rows an older broker wrote have neither.
223
277
  await addMissingColumns(database, table, { queued_at: types.int, frame_bytes: types.int });
224
- // The per-recipient cap is summed from this index alone. Summed from the rows, `frame_bytes`, stored after the
225
- // frame, cost a read of every queued frame (overflow pages and all) on every enqueue. In a serial transaction (#5054).
226
- await ensureBrokerSchema(database, options.prefix, "outbox-indexes", (tx) =>
227
- tx.exec(`CREATE INDEX IF NOT EXISTS ${table}_target_bytes ON ${table}(target_identity, state, frame_bytes)`),
228
- );
278
+ // Its partial indexes, and its fillfactor on PostgreSQL, are set at the end of a broker's open
279
+ // (`ensureRetentionIndexes`), where the other stores' tables are there too.
229
280
 
230
281
  const columns = `sequence, message_id, target_identity, origin_broker_id, digest, frame_json, state,
231
282
  claim_attempts, claimant_id, claim_token, failure_reason,
@@ -270,6 +321,7 @@ async function openOutboxStoreInCatalog(options: IntercomBrokerStateOptions): Pr
270
321
  assignments: string,
271
322
  params: readonly SqliteValue[],
272
323
  answer: (written: OutboxRecord) => Result,
324
+ relaxedDurability = false,
273
325
  ): Promise<Result | OutboxClaimWriteRejection> => {
274
326
  if (claim.messageId.length === 0) return Promise.resolve(invalid("empty-message-id"));
275
327
  if (claim.claimantId.length === 0) return Promise.resolve(invalid("empty-claimant-id"));
@@ -288,67 +340,531 @@ async function openOutboxStoreInCatalog(options: IntercomBrokerStateOptions): Pr
288
340
  if (isSettled(record)) return { status: "settled", row: toRow(record) } as const;
289
341
  return { status: "stale" } as const;
290
342
  },
291
- { ...fenced, leading: [write] },
343
+ { ...fenced, leading: [write], ...(relaxedDurability ? { relaxedDurability } : {}) },
292
344
  );
293
345
  };
294
346
 
295
347
  const settled = `failure_reason = ?, settled_at = ${nowMs},
296
348
  claimant_id = NULL, claim_token = NULL, claim_renewed_at = NULL, saving_at = NULL`;
297
349
 
350
+ // One bound JSON array of `[messageId, token, claimantId]` triples keeps the statement text fixed for any batch size
351
+ // and matches each row against one whole claim rather than separate lists of ids and tokens (#6560).
352
+ const claimsCte =
353
+ dialect === "postgres"
354
+ ? "WITH claims AS (SELECT c ->> 0 AS message_id, c ->> 1 AS claim_token, c ->> 2 AS claimant_id FROM jsonb_array_elements(?::jsonb) AS c)"
355
+ : "WITH claims AS (SELECT json_extract(value, '$[0]') AS message_id, json_extract(value, '$[1]') AS claim_token, json_extract(value, '$[2]') AS claimant_id FROM json_each(?))";
356
+ const claimTriples = (claims: readonly OutboxClaim[]): string =>
357
+ JSON.stringify(claims.map((claim) => [claim.messageId, claim.token, claim.claimantId]));
358
+ const matchesClaim =
359
+ "(message_id, claim_token, claimant_id) IN (SELECT message_id, claim_token, claimant_id FROM claims)";
360
+ const messageIdIn = (subquery: string) =>
361
+ dialect === "postgres" ? `message_id = ANY(ARRAY(${subquery}))` : `message_id IN (${subquery})`;
362
+ const lockedClaimsWhere =
363
+ dialect === "postgres"
364
+ ? `${messageIdIn(
365
+ `SELECT message_id FROM ${table} WHERE state = 'claimed'
366
+ AND ${messageIdIn("SELECT message_id FROM claims")} AND ${matchesClaim}
367
+ ORDER BY sequence${lockClause("update")}`,
368
+ )} AND state = 'claimed' AND ${matchesClaim}`
369
+ : `state = 'claimed' AND ${matchesClaim}`;
370
+
371
+ type MarkDeliveredEntry = {
372
+ readonly claim: OutboxClaim;
373
+ readonly wakeOrigin: boolean;
374
+ };
375
+
376
+ /**
377
+ * Settles each of `entries`, of distinct rows, as delivered, in one transaction: one UPDATE that locks their rows in
378
+ * sequence order on PostgreSQL, as a claim locks a recipient's rows, and changes those whose claim is still current,
379
+ * followed in the same transaction by the optional outcome hints for remote origin brokers (with NOWAIT on
380
+ * PostgreSQL so a contended hint log never fails the settlement) and the lookup of any unmatched rows (#6560, #6715,
381
+ * #6716).
382
+ */
383
+ const markDeliveredTogether = (entries: readonly MarkDeliveredEntry[]): Promise<OutboxDeliveredResult[]> => {
384
+ const wantsWake = entries.some(({ wakeOrigin }) => wakeOrigin);
385
+ if (dialect !== "postgres") {
386
+ const runSqlite = (wakes: boolean): Promise<OutboxDeliveredResult[]> => {
387
+ const claims = entries.map(({ claim }) => claim);
388
+ const write: SqliteStatement = {
389
+ sql: `${claimsCte}
390
+ UPDATE ${table} SET state = 'delivered', ${settled}
391
+ WHERE ${lockedClaimsWhere}
392
+ RETURNING ${columns}`,
393
+ params: [claimTriples(claims), null],
394
+ };
395
+ return database.transaction(
396
+ async (executor) => {
397
+ const written = new Map(
398
+ (await executor.all<OutboxRecord>(write.sql, ...write.params)).map((record) => [
399
+ record.message_id,
400
+ record,
401
+ ]),
402
+ );
403
+ const others = claims.filter((claim) => !written.has(claim.messageId));
404
+ const found =
405
+ others.length === 0
406
+ ? new Map<string, OutboxRecord>()
407
+ : new Map(
408
+ (
409
+ await executor.all<OutboxRecord>(
410
+ `SELECT ${columns} FROM ${table} WHERE ${messageIdIn(`SELECT value FROM ${jsonValues("?")}`)}`,
411
+ JSON.stringify(others.map((claim) => claim.messageId)),
412
+ )
413
+ ).map((record) => [record.message_id, record]),
414
+ );
415
+ const wokenOrigins = new Map<string, number>();
416
+ if (wakes) {
417
+ for (const { claim, wakeOrigin } of entries) {
418
+ if (!wakeOrigin) continue;
419
+ const delivered = written.get(claim.messageId);
420
+ if (delivered === undefined || delivered.origin_broker_id === claim.claimantId) continue;
421
+ const sequence = Number(delivered.sequence);
422
+ const prev = wokenOrigins.get(delivered.origin_broker_id);
423
+ if (prev === undefined || sequence > prev) wokenOrigins.set(delivered.origin_broker_id, sequence);
424
+ }
425
+ if (wokenOrigins.size > 0) {
426
+ const notifications = database.notifications;
427
+ const hintRows = [...wokenOrigins.entries()];
428
+ const statements: SqliteStatement[] = [
429
+ {
430
+ sql: `INSERT INTO ${wakeups}(broker_id, reason, version, created_at)
431
+ SELECT json_extract(value, '$[0]'), 'outcome',
432
+ CAST(json_extract(value, '$[1]') AS ${types.int}), ${nowMs}
433
+ FROM json_each(?)`,
434
+ params: [JSON.stringify(hintRows)],
435
+ },
436
+ ...(notifications === undefined
437
+ ? []
438
+ : hintRows.flatMap(([brokerId]) => wakeUpNotices(notifications, wakeups, leases, brokerId))),
439
+ ];
440
+ await (async () => {
441
+ for (const { sql, params } of statements) await executor.run(sql, ...params);
442
+ })().catch((cause: unknown) => {
443
+ throw new OutboxWakeFailedError(cause);
444
+ });
445
+ }
446
+ }
447
+ return entries.map(({ claim, wakeOrigin }): OutboxDeliveredResult => {
448
+ const delivered = written.get(claim.messageId);
449
+ if (delivered !== undefined) {
450
+ const woke =
451
+ wakes &&
452
+ wakeOrigin &&
453
+ wokenOrigins.has(delivered.origin_broker_id) &&
454
+ delivered.origin_broker_id !== claim.claimantId
455
+ ? delivered.origin_broker_id
456
+ : undefined;
457
+ return { status: "delivered", row: toRow(delivered), ...(woke === undefined ? {} : { woke }) };
458
+ }
459
+ const record = found.get(claim.messageId);
460
+ if (record === undefined) return { status: "unknown" };
461
+ if (isSettled(record)) return { status: "settled", row: toRow(record) };
462
+ return { status: "stale" };
463
+ });
464
+ },
465
+ { ...fenced, leading: [write] },
466
+ );
467
+ };
468
+ return wantsWake
469
+ ? runSqlite(true).catch((error) => {
470
+ if (error instanceof OutboxWakeFailedError) return runSqlite(false);
471
+ throw error;
472
+ })
473
+ : runSqlite(false);
474
+ }
475
+ const run = (wakes: boolean): Promise<OutboxDeliveredResult[]> => {
476
+ // The claims go as one JSON parameter, so the statement's text is the same however many it settles: a server
477
+ // that keeps prepared statements, and pg_stat_statements, see one statement, not one per count (#6560). Each
478
+ // row is found by its key, then checked against its claim.
479
+ const write: SqliteStatement = {
480
+ sql: `WITH claims AS MATERIALIZED (
481
+ SELECT c ->> 0 AS message_id, c ->> 1 AS claim_token, c ->> 2 AS claimant_id,
482
+ (c ->> 3)::int AS wake
483
+ FROM jsonb_array_elements(?::jsonb) AS c
484
+ ), updated AS (
485
+ UPDATE ${table} SET state = 'delivered', ${settled}
486
+ WHERE ${lockedClaimsWhere}
487
+ RETURNING ${columns}
488
+ ), recorded AS MATERIALIZED (
489
+ SELECT
490
+ set_config('${SETTLE_UNMATCHED}', COALESCE((
491
+ SELECT jsonb_agg(c.message_id)::text FROM claims c
492
+ WHERE NOT EXISTS (SELECT 1 FROM updated u WHERE u.message_id = c.message_id)
493
+ ), ''), true) AS unmatched,
494
+ set_config('${SETTLE_WAKE}', COALESCE((
495
+ SELECT jsonb_agg(jsonb_build_array(origin_broker_id, max_sequence))::text
496
+ FROM (
497
+ SELECT u.origin_broker_id, MAX(u.sequence) AS max_sequence
498
+ FROM updated u
499
+ JOIN claims c ON c.message_id = u.message_id
500
+ WHERE c.wake = 1 AND u.origin_broker_id <> c.claimant_id
501
+ GROUP BY u.origin_broker_id
502
+ ) AS origins
503
+ ), ''), true) AS wake_hints
504
+ )
505
+ SELECT updated.*
506
+ FROM recorded LEFT JOIN updated ON TRUE`,
507
+ params: [
508
+ JSON.stringify(
509
+ entries.map(({ claim, wakeOrigin }) => [
510
+ claim.messageId,
511
+ claim.token,
512
+ claim.claimantId,
513
+ wakes && wakeOrigin ? 1 : 0,
514
+ ]),
515
+ ),
516
+ null,
517
+ ],
518
+ };
519
+ // Locks the hint log without waiting and writes one outcome hint per distinct remote origin broker; a hint
520
+ // log held locked by another session leaves the settlement intact without its hints (#6715).
521
+ const writeHints: SqliteStatement = {
522
+ sql: `DO $atomic_settle$ BEGIN
523
+ IF COALESCE(current_setting('${SETTLE_WAKE}', true), '') <> '' THEN
524
+ LOCK TABLE ${wakeups} IN ROW EXCLUSIVE MODE NOWAIT;
525
+ INSERT INTO ${wakeups}(broker_id, reason, version, created_at)
526
+ SELECT h ->> 0, 'outcome', (h ->> 1)::bigint, ${nowMs}
527
+ FROM jsonb_array_elements(current_setting('${SETTLE_WAKE}', true)::jsonb) AS h;
528
+ PERFORM set_config('${SETTLE_HINT}', 'written', true);
529
+ END IF;
530
+ EXCEPTION WHEN lock_not_available THEN NULL;
531
+ END $atomic_settle$`,
532
+ params: [],
533
+ };
534
+ const hintRead: SqliteStatement = {
535
+ sql: `SELECT COALESCE(current_setting('${SETTLE_HINT}', true), '') AS written`,
536
+ params: [],
537
+ };
538
+ const readOthers: SqliteStatement = {
539
+ sql: `SELECT ${columns} FROM ${table}
540
+ WHERE message_id = ANY(ARRAY(
541
+ SELECT jsonb_array_elements_text(
542
+ COALESCE(NULLIF(current_setting('${SETTLE_UNMATCHED}', true), ''), '[]')::jsonb
543
+ )
544
+ ))`,
545
+ params: [],
546
+ };
547
+ const leading = wakes ? [write, writeHints, hintRead, readOthers] : [write, readOthers];
548
+ return database
549
+ .transaction(
550
+ async (executor) => {
551
+ const written = new Map(
552
+ (await executor.all<OutboxRecord>(write.sql, ...write.params))
553
+ .filter((record) => record.message_id !== null)
554
+ .map((record) => [record.message_id, record]),
555
+ );
556
+ let hintWritten = false;
557
+ if (wakes) {
558
+ await executor.run(writeHints.sql).catch((cause: unknown) => {
559
+ throw new OutboxWakeFailedError(cause);
560
+ });
561
+ const hintRow = await executor.get<SqliteRow & { written: string }>(hintRead.sql);
562
+ hintWritten = hintRow?.written === "written";
563
+ }
564
+ const found = new Map(
565
+ (await executor.all<OutboxRecord>(readOthers.sql)).map((record) => [record.message_id, record]),
566
+ );
567
+ return entries.map(({ claim, wakeOrigin }): OutboxDeliveredResult => {
568
+ const delivered = written.get(claim.messageId);
569
+ if (delivered !== undefined) {
570
+ const woke =
571
+ hintWritten && wakeOrigin && delivered.origin_broker_id !== claim.claimantId
572
+ ? delivered.origin_broker_id
573
+ : undefined;
574
+ return { status: "delivered", row: toRow(delivered), ...(woke === undefined ? {} : { woke }) };
575
+ }
576
+ const record = found.get(claim.messageId);
577
+ if (record === undefined) return { status: "unknown" };
578
+ if (isSettled(record)) return { status: "settled", row: toRow(record) };
579
+ return { status: "stale" };
580
+ });
581
+ },
582
+ { ...fenced, leading, leadingOnly: true },
583
+ )
584
+ .then((results) => {
585
+ const notifications = database.notifications;
586
+ if (notifications !== undefined) {
587
+ const brokers = new Set<string>();
588
+ for (const result of results)
589
+ if (result.status === "delivered" && result.woke !== undefined) brokers.add(result.woke);
590
+ for (const brokerId of brokers)
591
+ for (const { sql, params } of wakeUpNotices(notifications, wakeups, leases, brokerId))
592
+ void database.run(sql, ...params).catch(() => {});
593
+ }
594
+ return results;
595
+ });
596
+ };
597
+ return wantsWake
598
+ ? run(true).catch((error) => {
599
+ if (error instanceof OutboxWakeFailedError) return run(false);
600
+ throw error;
601
+ })
602
+ : run(false);
603
+ };
604
+
298
605
  /**
299
- * Settles each of `claims`, of distinct rows, as delivered, in one transaction: one UPDATE, sent with its start, that
300
- * locks their rows in sequence order, as a claim locks a recipient's rows, and changes those whose claim is still
301
- * current. Only when it changed fewer rows than it was given are the others read, to report why (#6560).
606
+ * Renews each of `claims` in one transaction: one UPDATE that matches each row against an exact `(message_id,
607
+ * claim_token, claimant_id)` triple, locks the rows in sequence order on PostgreSQL so it never waits in a cycle with
608
+ * claims or settlements, and updates only claims still current. On PostgreSQL the update, a gated follow-up read for
609
+ * misses, and the commit go in one round trip. Like `renewClaim`, its commit does not wait for the disk: the next
610
+ * renewal repeats one a server crash lost (#6560, #6712).
302
611
  */
303
- const markDeliveredTogether = (claims: readonly OutboxClaim[]): Promise<OutboxDeliveredResult[]> => {
304
- const current = claims.map(() => "(message_id = ? AND claim_token = ? AND claimant_id = ?)").join(" OR ");
305
- const keys = claims.flatMap((claim) => [claim.messageId, claim.token, claim.claimantId]);
612
+ const renewClaims = async (claims: readonly OutboxClaim[]): Promise<OutboxRenewClaimResult[]> => {
613
+ const results: (OutboxRenewClaimResult | undefined)[] = claims.map((claim) =>
614
+ claim.messageId.length === 0
615
+ ? invalid("empty-message-id")
616
+ : claim.claimantId.length === 0
617
+ ? invalid("empty-claimant-id")
618
+ : undefined,
619
+ );
620
+ const valid = claims.filter((_, index) => results[index] === undefined);
621
+ if (valid.length === 0) return results as OutboxRenewClaimResult[];
622
+ const key = (messageId: string, token: string, claimantId: string) =>
623
+ JSON.stringify([messageId, token, claimantId]);
624
+ const answer = (
625
+ renewed: ReadonlySet<string>,
626
+ found: ReadonlyMap<string, OutboxRecord>,
627
+ ): OutboxRenewClaimResult[] =>
628
+ claims.map((claim, index): OutboxRenewClaimResult => {
629
+ const checked = results[index];
630
+ if (checked !== undefined) return checked;
631
+ if (renewed.has(key(claim.messageId, claim.token, claim.claimantId))) return renewedAnswer();
632
+ const record = found.get(claim.messageId);
633
+ if (record === undefined) return { status: "unknown" };
634
+ if (isSettled(record)) return { status: "settled", row: toRow(record) };
635
+ return { status: "stale" };
636
+ });
637
+ if (dialect === "postgres") {
638
+ const write: SqliteStatement = {
639
+ sql: `${claimsCte}, renewed AS (
640
+ UPDATE ${table} SET claim_renewed_at = ${nowMs}
641
+ WHERE ${lockedClaimsWhere}
642
+ RETURNING message_id, claim_token, claimant_id
643
+ ), gate AS MATERIALIZED (
644
+ SELECT set_config('${RENEW_MISSES}', CASE WHEN (SELECT COUNT(*) FROM renewed) < CAST(? AS ${types.int}) THEN '1' ELSE '' END, true) AS misses
645
+ )
646
+ SELECT renewed.message_id, renewed.claim_token, renewed.claimant_id
647
+ FROM gate LEFT JOIN renewed ON TRUE`,
648
+ params: [claimTriples(valid), valid.length],
649
+ };
650
+ const readMisses: SqliteStatement = {
651
+ sql: `SELECT ${columns} FROM ${table}
652
+ WHERE current_setting('${RENEW_MISSES}', true) = '1'
653
+ AND ${messageIdIn(`SELECT value FROM ${jsonValues("?")}`)}`,
654
+ params: [JSON.stringify(valid.map((claim) => claim.messageId))],
655
+ };
656
+ return database.transaction(
657
+ async (executor) => {
658
+ const renewed = new Set<string>();
659
+ for (const row of await executor.all<
660
+ SqliteRow & { message_id: string | null; claim_token: string | null; claimant_id: string | null }
661
+ >(write.sql, ...write.params))
662
+ if (row.message_id !== null && row.claim_token !== null && row.claimant_id !== null)
663
+ renewed.add(key(row.message_id, row.claim_token, row.claimant_id));
664
+ const found = new Map(
665
+ (await executor.all<OutboxRecord>(readMisses.sql, ...readMisses.params)).map((record) => [
666
+ record.message_id,
667
+ record,
668
+ ]),
669
+ );
670
+ return answer(renewed, found);
671
+ },
672
+ { ...fenced, leading: [write, readMisses], leadingOnly: true, relaxedDurability: true },
673
+ );
674
+ }
306
675
  const write: SqliteStatement = {
307
- sql: `UPDATE ${table} SET state = 'delivered', ${settled}
308
- WHERE message_id IN (
309
- SELECT message_id FROM ${table} WHERE state = 'claimed' AND (${current})
310
- ORDER BY sequence${lockClause("update")}
311
- ) AND state = 'claimed' AND (${current})
312
- RETURNING ${columns}`,
313
- params: [null, ...keys, ...keys],
676
+ sql: `${claimsCte}
677
+ UPDATE ${table} SET claim_renewed_at = ${nowMs}
678
+ WHERE ${lockedClaimsWhere}
679
+ RETURNING message_id, claim_token, claimant_id`,
680
+ params: [claimTriples(valid)],
314
681
  };
315
682
  return database.transaction(
316
683
  async (executor) => {
317
- const written = new Map(
318
- (await executor.all<OutboxRecord>(write.sql, ...write.params)).map((record) => [record.message_id, record]),
319
- );
320
- const others = claims.filter((claim) => !written.has(claim.messageId));
684
+ const renewed = new Set<string>();
685
+ for (const row of await executor.all<
686
+ SqliteRow & { message_id: string; claim_token: string; claimant_id: string }
687
+ >(write.sql, ...write.params))
688
+ renewed.add(key(row.message_id, row.claim_token, row.claimant_id));
689
+ const others = valid.filter((claim) => !renewed.has(key(claim.messageId, claim.token, claim.claimantId)));
321
690
  const found =
322
691
  others.length === 0
323
692
  ? new Map<string, OutboxRecord>()
324
693
  : new Map(
325
694
  (
326
695
  await executor.all<OutboxRecord>(
327
- `SELECT ${columns} FROM ${table} WHERE message_id IN (${others.map(() => "?").join(", ")})`,
328
- ...others.map((claim) => claim.messageId),
696
+ `SELECT ${columns} FROM ${table} WHERE ${messageIdIn(`SELECT value FROM ${jsonValues("?")}`)}`,
697
+ JSON.stringify(others.map((claim) => claim.messageId)),
329
698
  )
330
699
  ).map((record) => [record.message_id, record]),
331
700
  );
332
- return claims.map((claim): OutboxDeliveredResult => {
333
- const delivered = written.get(claim.messageId);
334
- if (delivered !== undefined) return { status: "delivered", row: toRow(delivered) };
335
- const record = found.get(claim.messageId);
336
- if (record === undefined) return { status: "unknown" };
337
- if (isSettled(record)) return { status: "settled", row: toRow(record) };
338
- return { status: "stale" };
701
+ return answer(renewed, found);
702
+ },
703
+ { ...fenced, leading: [write], relaxedDurability: true },
704
+ );
705
+ };
706
+
707
+ const claimKey = (messageId: string, token: string, claimantId: string) =>
708
+ JSON.stringify([messageId, token, claimantId]);
709
+ const missColumns = `sequence, message_id, target_identity, origin_broker_id, digest,
710
+ CASE WHEN state IN ('delivered', 'failed') THEN frame_json ELSE '' END AS frame_json,
711
+ state, claim_attempts, claimant_id, claim_token, failure_reason,
712
+ CASE WHEN claim_renewed_at IS NULL THEN NULL ELSE ${ageSince("claim_renewed_at")} END AS claim_age,
713
+ CASE WHEN saving_at IS NULL THEN NULL ELSE ${ageSince("saving_at")} END AS saving_age`;
714
+ const releaseAssignments = (unwritten: boolean) => {
715
+ const attempts = unwritten ? `, claim_attempts = ${greatest("0", "claim_attempts - 1")}` : "";
716
+ return `state = 'queued', claimant_id = NULL, claim_token = NULL, claim_renewed_at = NULL, saving_at = NULL${attempts}`;
717
+ };
718
+
719
+ /**
720
+ * Releases each of `claims` in one durable transaction, locking matching rows in sequence order as claims, renewals
721
+ * and settlements do so none waits for another in a cycle, and matching each row by its full `(message_id,
722
+ * claim_token, claimant_id)` tuple. On PostgreSQL, the update and conditional miss lookup go out together with
723
+ * `BEGIN` and `COMMIT` (`leadingOnly: true`), so releasing any number of claims takes one round trip (#6713).
724
+ */
725
+ const releaseClaims = async (
726
+ claims: readonly OutboxClaim[],
727
+ releaseOptions?: { readonly unwritten?: boolean },
728
+ ): Promise<OutboxReleaseClaimResult[]> => {
729
+ if (claims.length === 0) return [];
730
+ const results: (OutboxReleaseClaimResult | undefined)[] = claims.map((claim) =>
731
+ claim.messageId.length === 0
732
+ ? invalid("empty-message-id")
733
+ : claim.claimantId.length === 0
734
+ ? invalid("empty-claimant-id")
735
+ : undefined,
736
+ );
737
+ const valid: { readonly claim: OutboxClaim; readonly index: number }[] = [];
738
+ claims.forEach((claim, index) => {
739
+ if (results[index] === undefined) valid.push({ claim, index });
740
+ });
741
+ if (valid.length === 0) return results as OutboxReleaseClaimResult[];
742
+ const assignments = releaseAssignments(releaseOptions?.unwritten === true);
743
+ const classifyMiss = (record: OutboxRecord | undefined): OutboxReleaseClaimResult => {
744
+ if (record === undefined) return { status: "unknown" };
745
+ if (isSettled(record)) return { status: "settled", row: toRow(record) };
746
+ return { status: "stale" };
747
+ };
748
+ if (dialect === "postgres") {
749
+ const write: SqliteStatement = {
750
+ sql: `${claimsCte}, released AS (
751
+ UPDATE ${table} AS outbox SET ${assignments}
752
+ FROM (SELECT DISTINCT message_id, claim_token, claimant_id FROM claims) AS matched
753
+ WHERE outbox.message_id = ANY(ARRAY(
754
+ SELECT message_id FROM ${table}
755
+ WHERE state = 'claimed'
756
+ AND ${messageIdIn("SELECT message_id FROM claims")}
757
+ AND ${matchesClaim}
758
+ ORDER BY sequence${lockClause("update")}
759
+ ))
760
+ AND outbox.state = 'claimed'
761
+ AND outbox.message_id = matched.message_id
762
+ AND outbox.claim_token = matched.claim_token
763
+ AND outbox.claimant_id = matched.claimant_id
764
+ RETURNING outbox.message_id, matched.claim_token, matched.claimant_id
765
+ ), gate AS MATERIALIZED (
766
+ SELECT set_config('${RELEASE_MISSES}', CASE WHEN (SELECT COUNT(*) FROM released) < CAST(? AS ${types.int}) THEN '1' ELSE '' END, true) AS misses
767
+ )
768
+ SELECT released.message_id, released.claim_token, released.claimant_id
769
+ FROM gate LEFT JOIN released ON TRUE`,
770
+ params: [claimTriples(valid.map(({ claim }) => claim)), valid.length],
771
+ };
772
+ const readMisses: SqliteStatement = {
773
+ sql: `SELECT ${missColumns} FROM ${table}
774
+ WHERE current_setting('${RELEASE_MISSES}', true) = '1'
775
+ AND ${messageIdIn(`SELECT value FROM ${jsonValues("?")}`)}`,
776
+ params: [JSON.stringify([...new Set(valid.map(({ claim }) => claim.messageId))])],
777
+ };
778
+ return database.transaction(
779
+ async (executor) => {
780
+ const releasedRows = await executor.all<
781
+ SqliteRow & { message_id: string | null; claim_token: string | null; claimant_id: string | null }
782
+ >(write.sql, ...write.params);
783
+ const foundRows = await executor.all<OutboxRecord>(readMisses.sql, ...readMisses.params);
784
+ const releasedKeys = new Set<string>();
785
+ for (const row of releasedRows) {
786
+ if (row.message_id !== null && row.claim_token !== null && row.claimant_id !== null) {
787
+ releasedKeys.add(claimKey(row.message_id, row.claim_token, row.claimant_id));
788
+ }
789
+ }
790
+ const found = new Map(foundRows.map((record) => [record.message_id, record]));
791
+ return claims.map((claim, index): OutboxReleaseClaimResult => {
792
+ const checked = results[index];
793
+ if (checked !== undefined) return checked;
794
+ if (releasedKeys.delete(claimKey(claim.messageId, claim.token, claim.claimantId))) {
795
+ return { status: "released" };
796
+ }
797
+ return classifyMiss(found.get(claim.messageId));
798
+ });
799
+ },
800
+ { ...fenced, leading: [write, readMisses], leadingOnly: true },
801
+ );
802
+ }
803
+ // SQLite: partition into distinct-messageId waves (a single wave for distinct inputs) inside one serialized
804
+ // transaction so RETURNING message_id uniquely identifies the matched input entry even for duplicate message ids.
805
+ const waves: { readonly claim: OutboxClaim; readonly index: number }[][] = [];
806
+ for (const entry of valid) {
807
+ let wave = waves.find((candidate) => !candidate.some((other) => other.claim.messageId === entry.claim.messageId));
808
+ if (wave === undefined) {
809
+ wave = [];
810
+ waves.push(wave);
811
+ }
812
+ wave.push(entry);
813
+ }
814
+ const writeWave = (wave: readonly { readonly claim: OutboxClaim; readonly index: number }[]): SqliteStatement => ({
815
+ sql: `${claimsCte}
816
+ UPDATE ${table} SET ${assignments}
817
+ WHERE ${lockedClaimsWhere}
818
+ RETURNING message_id`,
819
+ params: [claimTriples(wave.map(({ claim }) => claim))],
820
+ });
821
+ const firstWrite = writeWave(waves[0]!);
822
+ return database.transaction(
823
+ async (executor) => {
824
+ const releasedIndices = new Set<number>();
825
+ for (let waveIndex = 0; waveIndex < waves.length; waveIndex++) {
826
+ const wave = waves[waveIndex]!;
827
+ const write = waveIndex === 0 ? firstWrite : writeWave(wave);
828
+ const rows = await executor.all<SqliteRow & { message_id: string }>(write.sql, ...write.params);
829
+ const matchedIds = new Set(rows.map((row) => row.message_id));
830
+ for (const { claim, index } of wave) {
831
+ if (matchedIds.has(claim.messageId)) releasedIndices.add(index);
832
+ }
833
+ }
834
+ const missedIds = [
835
+ ...new Set(valid.filter(({ index }) => !releasedIndices.has(index)).map(({ claim }) => claim.messageId)),
836
+ ];
837
+ const found =
838
+ missedIds.length === 0
839
+ ? new Map<string, OutboxRecord>()
840
+ : new Map(
841
+ (
842
+ await executor.all<OutboxRecord>(
843
+ `SELECT ${missColumns} FROM ${table} WHERE ${messageIdIn(`SELECT value FROM ${jsonValues("?")}`)}`,
844
+ JSON.stringify(missedIds),
845
+ )
846
+ ).map((record) => [record.message_id, record]),
847
+ );
848
+ return claims.map((claim, index): OutboxReleaseClaimResult => {
849
+ const checked = results[index];
850
+ if (checked !== undefined) return checked;
851
+ if (releasedIndices.has(index)) return { status: "released" };
852
+ return classifyMiss(found.get(claim.messageId));
339
853
  });
340
854
  },
341
- { ...fenced, leading: [write] },
855
+ { ...fenced, leading: [firstWrite] },
342
856
  );
343
857
  };
344
858
 
345
859
  /**
346
- * The `markDelivered` calls waiting for the transaction that settles them, in the order they were made. On PostgreSQL
347
- * the calls made while one transaction settles others go together in the next, whose round trips they share, rather
348
- * than two round trips each: one transaction at a time, so each commits after every call made before it (#6560).
860
+ * The `markDelivered` calls waiting for the transaction that settles them, in the order they were made. Calls made
861
+ * while one transaction settles others go together in the next, sharing one transaction and its commit instead of
862
+ * running one transaction each: one transaction at a time, so each commits after every call made before it (#6560,
863
+ * #6716).
349
864
  */
350
865
  const deliveries: {
351
866
  readonly claim: OutboxClaim;
867
+ readonly wakeOrigin: boolean;
352
868
  readonly resolve: (result: OutboxDeliveredResult) => void;
353
869
  readonly reject: (error: unknown) => void;
354
870
  }[] = [];
@@ -369,7 +885,9 @@ async function openOutboxStoreInCatalog(options: IntercomBrokerStateOptions): Pr
369
885
  rows.add(deliveries[count++]!.claim.messageId);
370
886
  const batch = deliveries.splice(0, count);
371
887
  try {
372
- const results = await markDeliveredTogether(batch.map(({ claim }) => claim));
888
+ const results = await markDeliveredTogether(
889
+ batch.map(({ claim, wakeOrigin }) => ({ claim, wakeOrigin })),
890
+ );
373
891
  batch.forEach(({ resolve }, index) => resolve(results[index]!));
374
892
  } catch (error) {
375
893
  for (const { reject } of batch) reject(error);
@@ -379,7 +897,7 @@ async function openOutboxStoreInCatalog(options: IntercomBrokerStateOptions): Pr
379
897
  };
380
898
 
381
899
  /**
382
- * #4896: the recipient's undelivered rows and their frame bytes, read from `<table>_target_bytes` alone. Only rows an
900
+ * #4896: the recipient's undelivered rows and their frame bytes, read from `<table>_undelivered` alone. Only rows an
383
901
  * older broker wrote, without `frame_bytes`, are measured from their frames.
384
902
  */
385
903
  const sizedTotalsStatement = (targetIdentity: string): SqliteStatement => ({
@@ -496,16 +1014,23 @@ async function openOutboxStoreInCatalog(options: IntercomBrokerStateOptions): Pr
496
1014
  const hint = async () => {
497
1015
  // PostgreSQL: never wait behind another session's lock on the hint log; such a hint goes without. The hint
498
1016
  // is a new row, so it needs no lock domain of its own (#6560): see `fencedPath("intercom-wakeup-hint")`.
499
- if (dialect === "postgres") await executor.run(`LOCK TABLE ${wakeups} IN ROW EXCLUSIVE MODE NOWAIT`);
500
- await executor.run(
501
- `INSERT INTO ${wakeups}(broker_id, reason, version, created_at) VALUES (?, 'outbox', ?, ${nowMs})`,
502
- host,
503
- Number(inserted.sequence),
504
- );
505
- // Notified when it commits, as the wake-up bus's own hints are, so the host does not wait for its backup
506
- // poll (#6560).
507
- const notify = database.notifications?.notify(wakeups, host);
508
- if (notify !== undefined) await executor.run(notify.sql, ...notify.params);
1017
+ // Notified once it commits, as the wake-up bus's own hints are, so the host does not wait for its backup
1018
+ // poll (#6560); on Postgres the notifications go right behind the commit, outside it.
1019
+ const notifications = database.notifications;
1020
+ const statements: SqliteStatement[] = [
1021
+ ...(dialect === "postgres" ? [{ sql: `LOCK TABLE ${wakeups} IN ROW EXCLUSIVE MODE NOWAIT`, params: [] }] : []),
1022
+ {
1023
+ sql: `INSERT INTO ${wakeups}(broker_id, reason, version, created_at, target_identity)
1024
+ VALUES (?, 'outbox', ?, ${nowMs}, ?)`,
1025
+ params: [host, Number(inserted.sequence), request.targetIdentity],
1026
+ },
1027
+ ...(notifications === undefined ? [] : wakeUpNotices(notifications, wakeups, leases, host)),
1028
+ ];
1029
+ // Together, in one round trip, on a pipelined transaction's own handle, which sends calls in the order they
1030
+ // are made: a lock refused aborts the transaction, so the insert after it fails too.
1031
+ if (finisherOf?.(executor) !== undefined)
1032
+ await Promise.all(statements.map(({ sql, params }) => executor.run(sql, ...params)));
1033
+ else for (const { sql, params } of statements) await executor.run(sql, ...params);
509
1034
  };
510
1035
  await hint().catch((cause: unknown) => {
511
1036
  throw new OutboxWakeFailedError(cause);
@@ -519,15 +1044,208 @@ async function openOutboxStoreInCatalog(options: IntercomBrokerStateOptions): Pr
519
1044
  ...(request.owed === true ? [] : [sizedTotalsStatement(request.targetIdentity)]),
520
1045
  ];
521
1046
 
1047
+ /**
1048
+ * PostgreSQL: a send in statements that the database decides alone, sent together with the transaction's start and
1049
+ * commit. The recipient's lock domain, taken with the start, is held while the server runs them and never across a
1050
+ * round trip to the broker, so sends to one busy recipient wait for each other only that long. Under the lock, as
1051
+ * `enqueueIn` and the guard decide it across round trips:
1052
+ * 1. `decide` reads the message's row and reservation and the recipient's queue, and records in the transaction whether
1053
+ * the queue has room for the row, and whether the send's earlier reservation goes because it has not.
1054
+ * 2. With a reservation, it is written only while no row of the message with another digest is queued, and either the
1055
+ * queue has room or the send's own row is queued already; a reservation of the message already there is left as it is.
1056
+ * 3. The row is inserted only while the queue has room and the send's digest holds the reservation. For a recipient its
1057
+ * sender found offline (`wakeHostWithinMs`), the insert also reads, and locks shared, the recipient's live presence,
1058
+ * as `enqueueIn` does, and records the broker holding it.
1059
+ * 4. With such a broker, a block locks the hint log without waiting and writes the hint, naming the broker and the row's
1060
+ * sequence, and records that it did: a hint log another session holds locked leaves the send without its hint, as
1061
+ * in `enqueueIn`, and fails nothing.
1062
+ * 5. A read of whether it did.
1063
+ * 6. A reservation the send wrote is deleted again when its row is not queued, and an earlier one when the queue was full.
1064
+ * 7. The message's row is read, to answer a send whose row was not inserted.
1065
+ * Each statement sees what every transaction that committed before it wrote, as each of `enqueueIn`'s does. The hint's
1066
+ * notification goes out after the commit, so the transaction ends without waiting for it.
1067
+ */
1068
+ const enqueueAtOnce = (
1069
+ request: OutboxEnqueueRequest,
1070
+ reservation?: OutboxReservation,
1071
+ ): Promise<OutboxEnqueueResult> | undefined => {
1072
+ const messageId = request.frame.message.id;
1073
+ if (request.targetIdentity.length === 0 || request.originBrokerId.length === 0 || messageId.length === 0)
1074
+ return undefined;
1075
+ const frameJson = JSON.stringify(request.frame);
1076
+ const frameBytes = Buffer.byteLength(frameJson);
1077
+ const queuedTotals =
1078
+ request.owed === true
1079
+ ? { sql: "(SELECT 1) AS totals", params: [] as SqliteValue[] }
1080
+ : {
1081
+ sql: `(SELECT COUNT(*) AS row_count, COALESCE(SUM(frame_bytes), 0) + COALESCE((
1082
+ SELECT SUM(LENGTH(frame_json)) FROM ${table}
1083
+ WHERE target_identity = ? AND ${UNDELIVERED} AND frame_bytes IS NULL
1084
+ ), 0) AS byte_count
1085
+ FROM ${table} WHERE target_identity = ? AND ${UNDELIVERED}) AS totals`,
1086
+ params: [request.targetIdentity, request.targetIdentity],
1087
+ };
1088
+ const room =
1089
+ request.owed === true
1090
+ ? { sql: "1", params: [] as SqliteValue[] }
1091
+ : {
1092
+ sql: "CASE WHEN totals.row_count < ? AND totals.byte_count + ? <= ? THEN 1 ELSE 0 END",
1093
+ params: [OUTBOX_TARGET_MAX_ROWS, frameBytes, OUTBOX_TARGET_MAX_BYTES],
1094
+ };
1095
+ const holder = reservation?.holder ?? { sql: "SELECT CAST(NULL AS TEXT)", params: [] };
1096
+ const decide: SqliteStatement = {
1097
+ sql: `SELECT decided.room, decided.queued_digest, decided.reserved_digest,
1098
+ set_config('${SEND_ROOM}', CASE WHEN decided.room = 1 THEN 'room' ELSE 'full' END, true) AS room_gate,
1099
+ set_config('${SEND_FORGET}', CASE WHEN decided.room = 0 AND decided.queued_digest IS NULL
1100
+ AND decided.reserved_digest = ? THEN 'earlier' ELSE '' END, true) AS forget_gate
1101
+ FROM (
1102
+ SELECT ${room.sql} AS room, (SELECT digest FROM ${table} WHERE message_id = ?) AS queued_digest,
1103
+ (${holder.sql}) AS reserved_digest
1104
+ FROM ${queuedTotals.sql}
1105
+ ) AS decided`,
1106
+ params: [reservation?.digest ?? null, ...room.params, messageId, ...holder.params, ...queuedTotals.params],
1107
+ };
1108
+ const hasRoom = `current_setting('${SEND_ROOM}', true) = 'room'`;
1109
+ const reserve = reservation?.reserveWhere(
1110
+ {
1111
+ sql: `NOT EXISTS (SELECT 1 FROM ${table} WHERE message_id = ? AND digest <> ?)
1112
+ AND (${hasRoom} OR EXISTS (SELECT 1 FROM ${table} WHERE message_id = ? AND digest = ?))`,
1113
+ params: [messageId, request.digest, messageId, request.digest],
1114
+ },
1115
+ `set_config('${SEND_FORGET}', 'new', true) AS reserved`,
1116
+ );
1117
+ const held = reservation?.held ?? { sql: "1 = 1", params: [] };
1118
+ const wakes = request.wakeHostWithinMs !== undefined;
1119
+ // #5607: read in this transaction, under the row's insert, as `enqueueIn` reads it: see there.
1120
+ const presence = wakes
1121
+ ? {
1122
+ sql: `, set_config('${SEND_WAKE}', COALESCE((
1123
+ SELECT presence.holder_id FROM ${leases} presence
1124
+ WHERE presence.kind = 'presence' AND presence.key = ? AND presence.holder_id IS NOT NULL
1125
+ AND ${greatest("0", `${nowMs} - presence.renewed_at`)} <= ?${lockClause("share")}
1126
+ ), ''), true) AS presence_holder, set_config('${SEND_WAKE_VERSION}', CAST(sequence AS TEXT), true) AS hint_version,
1127
+ set_config('${SEND_WAKE_TARGET}', target_identity, true) AS hint_target`,
1128
+ params: [request.targetIdentity, request.wakeHostWithinMs!] as SqliteValue[],
1129
+ }
1130
+ : { sql: "", params: [] as SqliteValue[] };
1131
+ const insert: SqliteStatement = {
1132
+ sql: `INSERT INTO ${table}(message_id, target_identity, origin_broker_id, digest, frame_json, state, queued_at,
1133
+ frame_bytes)
1134
+ SELECT ?, ?, ?, ?, ?, 'queued', ${nowMs}, CAST(? AS ${types.int})
1135
+ WHERE ${hasRoom} AND ${held.sql}
1136
+ ON CONFLICT(message_id) DO NOTHING
1137
+ RETURNING ${columns}${presence.sql}`,
1138
+ params: [
1139
+ messageId,
1140
+ request.targetIdentity,
1141
+ request.originBrokerId,
1142
+ request.digest,
1143
+ frameJson,
1144
+ frameBytes,
1145
+ ...held.params,
1146
+ ...presence.params,
1147
+ ],
1148
+ };
1149
+ const woken = `COALESCE(current_setting('${SEND_WAKE}', true), '')`;
1150
+ // Locks the hint log and writes the hint only with such a broker, and never waits behind another session's lock on
1151
+ // the log: such a send goes without its hint (#5607). A hint is a new row, so it needs no lock domain of its own
1152
+ // (#6560): see `fencedPath("intercom-wakeup-hint")`. Even an insert of no row would wait for the log's lock, so the
1153
+ // insert is made in the block, only once the lock is held.
1154
+ const writeHint: SqliteStatement = {
1155
+ sql: `DO $atomic_send$ BEGIN
1156
+ IF ${woken} <> '' THEN
1157
+ LOCK TABLE ${wakeups} IN ROW EXCLUSIVE MODE NOWAIT;
1158
+ INSERT INTO ${wakeups}(broker_id, reason, version, created_at, target_identity)
1159
+ VALUES (${woken}, 'outbox', CAST(current_setting('${SEND_WAKE_VERSION}') AS BIGINT), ${nowMs},
1160
+ current_setting('${SEND_WAKE_TARGET}'));
1161
+ PERFORM set_config('${SEND_HINT}', 'written', true);
1162
+ END IF;
1163
+ EXCEPTION WHEN lock_not_available THEN NULL;
1164
+ END $atomic_send$`,
1165
+ params: [],
1166
+ };
1167
+ const hint: SqliteStatement = {
1168
+ sql: `SELECT ${woken} AS broker_id WHERE COALESCE(current_setting('${SEND_HINT}', true), '') = 'written'`,
1169
+ params: [],
1170
+ };
1171
+ const forget = reservation?.forgetWhere({
1172
+ sql: `current_setting('${SEND_FORGET}', true) = 'earlier' OR (current_setting('${SEND_FORGET}', true) = 'new'
1173
+ AND NOT EXISTS (SELECT 1 FROM ${table} WHERE message_id = ? AND digest = ?))`,
1174
+ params: [messageId, request.digest],
1175
+ });
1176
+ const queued = selectStatement(messageId);
1177
+ const leading = [
1178
+ decide,
1179
+ ...(reserve === undefined ? [] : [reserve]),
1180
+ insert,
1181
+ ...(wakes ? [writeHint, hint] : []),
1182
+ ...(forget === undefined ? [] : [forget]),
1183
+ queued,
1184
+ ];
1185
+ const answer = async (executor: SqliteExecutor): Promise<OutboxEnqueueResult> => {
1186
+ // In the order of `leading`, each answered with the transaction's start: no call waits for a round trip.
1187
+ const decided = (await executor.get<SqliteRow & { room: SqliteValue; reserved_digest: string | null }>(
1188
+ decide.sql,
1189
+ ...decide.params,
1190
+ ))!;
1191
+ if (reserve !== undefined) await executor.all(reserve.sql, ...reserve.params);
1192
+ const row = await executor.get<OutboxRecord>(insert.sql, ...insert.params);
1193
+ let woke: string | undefined;
1194
+ if (wakes) {
1195
+ // A database that cannot run the block (no PL/pgSQL for this role) writes the send again without its hint.
1196
+ await executor.run(writeHint.sql).catch((cause: unknown) => {
1197
+ throw new OutboxWakeFailedError(cause);
1198
+ });
1199
+ woke = (await executor.get<SqliteRow & { broker_id: string }>(hint.sql, ...hint.params))?.broker_id;
1200
+ }
1201
+ if (forget !== undefined) await executor.run(forget.sql, ...forget.params);
1202
+ const found = await executor.get<OutboxRecord>(queued.sql, ...queued.params);
1203
+ if (row !== undefined)
1204
+ return { status: "inserted", row: toRow(row), ...(woke === undefined ? {} : { woke }) } as const;
1205
+ // Another digest held the message's reservation: the send is refused, as before it wrote anything.
1206
+ if (decided.reserved_digest !== null && decided.reserved_digest !== reservation?.digest)
1207
+ return { status: "conflict", messageId };
1208
+ if (found !== undefined)
1209
+ return found.digest === request.digest
1210
+ ? { status: "duplicate", row: toRow(found) }
1211
+ : { status: "conflict", messageId };
1212
+ if (Number(decided.room) === 0)
1213
+ return { status: "full", limit: OUTBOX_TARGET_MAX_ROWS, byteLimit: OUTBOX_TARGET_MAX_BYTES };
1214
+ return { status: "conflict", messageId };
1215
+ };
1216
+ return database
1217
+ .transaction(answer, {
1218
+ ...recipientTransaction(database, options.prefix, request.targetIdentity),
1219
+ leading,
1220
+ leadingOnly: true,
1221
+ })
1222
+ .then((result) => {
1223
+ // Notified once the hint committed, on the host's own channel (and the shared one only for a host of an
1224
+ // earlier release), as the wake-up bus's own hints are, so the host does not wait for its backup poll
1225
+ // (#6560); the hint is there for its poll if a notification is lost.
1226
+ const notifications = database.notifications;
1227
+ if (result.status === "inserted" && result.woke !== undefined && notifications !== undefined) {
1228
+ const notices = wakeUpNotices(notifications, wakeups, leases, result.woke);
1229
+ if (notifications.send !== undefined) void notifications.send(notices).catch(() => {});
1230
+ else for (const { sql, params } of notices) void database.run(sql, ...params).catch(() => {});
1231
+ }
1232
+ return result;
1233
+ });
1234
+ };
1235
+
1236
+ const enqueueAtOnceIfPostgres = (request: OutboxEnqueueRequest, reservation?: OutboxReservation) =>
1237
+ dialect === "postgres" ? enqueueAtOnce(request, reservation) : undefined;
1238
+
522
1239
  return {
523
1240
  enqueueIn,
524
1241
  enqueueLeading,
1242
+ ...(dialect === "postgres" ? { enqueueAtOnce } : {}),
525
1243
  async enqueue(request) {
526
1244
  if (request.targetIdentity.length === 0) return invalid("empty-target-identity");
527
1245
  if (request.originBrokerId.length === 0) return invalid("empty-broker-id");
528
1246
  if (request.frame.message.id.length === 0) return invalid("empty-message-id");
529
1247
  return withoutFailedWake(request, (attempt) =>
530
- database.transaction((executor) => enqueueIn(executor, attempt), {
1248
+ enqueueAtOnceIfPostgres(attempt) ?? database.transaction((executor) => enqueueIn(executor, attempt), {
531
1249
  ...recipientTransaction(database, options.prefix, attempt.targetIdentity),
532
1250
  leading: enqueueLeading(attempt),
533
1251
  }),
@@ -612,6 +1330,7 @@ async function openOutboxStoreInCatalog(options: IntercomBrokerStateOptions): Pr
612
1330
  return claimed(records.filter((record) => record.message_id !== null));
613
1331
  },
614
1332
  {
1333
+ ...RETRY_UNAPPLIED,
615
1334
  concurrency: { kind: "serial", domain: `${table}_claims:${targetIdentity}` },
616
1335
  leading: [waiting, statement],
617
1336
  leadingOnly: true,
@@ -619,7 +1338,7 @@ async function openOutboxStoreInCatalog(options: IntercomBrokerStateOptions): Pr
619
1338
  },
620
1339
  );
621
1340
  }
622
- // SQLite and libSQL: a write statement takes the database's write lock even when it changes nothing, so a read
1341
+ // SQLite: a write statement takes the database's write lock even when it changes nothing, so a read
623
1342
  // decides first, without it, whether there is anything to claim: empty scans (such as fan-out wake-up polls across
624
1343
  // idle sessions) cost one read. Linearizable: if a row commits after this snapshot, its enqueue writes a new
625
1344
  // wake-up hint. The same read answers a claim another claimant holds, or one of only the claimant's own rows in
@@ -665,23 +1384,29 @@ async function openOutboxStoreInCatalog(options: IntercomBrokerStateOptions): Pr
665
1384
  },
666
1385
 
667
1386
  renewClaim(claim) {
668
- return withClaim(claim, `claim_renewed_at = ${nowMs}`, [], () => ({ status: "renewed" }) as const);
1387
+ // Its claimant renews again within the renewal interval, far inside the claim's staleness limit: a renewal lost
1388
+ // in a crash of the database server leaves the claim a renewal older and still current, so its commit does not
1389
+ // wait for the disk.
1390
+ return withClaim(claim, `claim_renewed_at = ${nowMs}`, [], renewedAnswer, true);
669
1391
  },
670
1392
 
1393
+ renewClaims,
1394
+
671
1395
  reportSaving(claim) {
672
1396
  return withClaim(claim, `saving_at = ${nowMs}`, [], () => ({ status: "renewed" }) as const);
673
1397
  },
674
1398
 
675
1399
  releaseClaim(claim, options) {
676
- const attempts = options?.unwritten === true ? `, claim_attempts = ${greatest("0", "claim_attempts - 1")}` : "";
677
1400
  return withClaim(
678
1401
  claim,
679
- `state = 'queued', claimant_id = NULL, claim_token = NULL, claim_renewed_at = NULL, saving_at = NULL${attempts}`,
1402
+ releaseAssignments(options?.unwritten === true),
680
1403
  [],
681
1404
  () => ({ status: "released" }) as const,
682
1405
  );
683
1406
  },
684
1407
 
1408
+ releaseClaims,
1409
+
685
1410
  async releaseClaimsOf(claimantId) {
686
1411
  // Its rows locked in sequence order, as a claim locks them, so the two never wait for each other (#6560).
687
1412
  const { changes } = await database.run(
@@ -696,14 +1421,12 @@ async function openOutboxStoreInCatalog(options: IntercomBrokerStateOptions): Pr
696
1421
  return changes;
697
1422
  },
698
1423
 
699
- markDelivered(claim) {
700
- if (dialect !== "postgres" || claim.messageId.length === 0 || claim.claimantId.length === 0)
701
- return withClaim(claim, `state = 'delivered', ${settled}`, [null], (written) => ({
702
- status: "delivered" as const,
703
- row: toRow(written),
704
- }));
1424
+ markDelivered(claim, options) {
1425
+ if (claim.messageId.length === 0) return Promise.resolve(invalid("empty-message-id"));
1426
+ if (claim.claimantId.length === 0) return Promise.resolve(invalid("empty-claimant-id"));
1427
+ const wakeOrigin = options?.wakeOrigin === true;
705
1428
  return new Promise<OutboxDeliveredResult>((resolve, reject) => {
706
- deliveries.push({ claim, resolve, reject });
1429
+ deliveries.push({ claim, wakeOrigin, resolve, reject });
707
1430
  if (delivering) return;
708
1431
  delivering = true;
709
1432
  void deliverQueued();
@@ -728,10 +1451,22 @@ async function openOutboxStoreInCatalog(options: IntercomBrokerStateOptions): Pr
728
1451
  return { status: "listed", rows: (await undelivered(database, targetIdentity, limit)).map(toRow) };
729
1452
  },
730
1453
 
1454
+ async withUndelivered(targetIdentities) {
1455
+ if (targetIdentities.length === 0) return new Set<string>();
1456
+ // One lookup of `<outbox>_undelivered` per recipient, its ids as one JSON parameter, so the text is the same however
1457
+ // many there are. No lock, and no row or frame read (#6560).
1458
+ const found = await database.all<SqliteRow & { readonly target_identity: string }>(
1459
+ `SELECT value AS target_identity FROM ${jsonValues("?")}
1460
+ WHERE EXISTS (SELECT 1 FROM ${table} WHERE target_identity = value AND ${UNDELIVERED})`,
1461
+ JSON.stringify(targetIdentities),
1462
+ );
1463
+ return new Set(found.map((row) => row.target_identity));
1464
+ },
1465
+
731
1466
  async undeliveredPosition(targetIdentity, messageId) {
732
1467
  if (targetIdentity.length === 0) return invalid("empty-target-identity");
733
1468
  if (messageId.length === 0) return invalid("empty-message-id");
734
- // Counted on the (target_identity, state, sequence) index: no row, and no frame, is read.
1469
+ // Counted on `<outbox>_undelivered`: no row, and no frame, is read.
735
1470
  const counted = await database.get<{ position: SqliteValue }>(
736
1471
  `SELECT COUNT(*) AS position FROM ${table}
737
1472
  WHERE target_identity = ? AND ${UNDELIVERED} AND sequence <= (
@@ -746,11 +1481,16 @@ async function openOutboxStoreInCatalog(options: IntercomBrokerStateOptions): Pr
746
1481
  },
747
1482
 
748
1483
  async prune(settledOlderThanMs, queuedOlderThanMs) {
1484
+ // Each age compared as `column < now - age`, so an index on the column answers it.
1485
+ const now = storeNow(database);
749
1486
  if (queuedOlderThanMs !== undefined) {
750
1487
  // Every recipient's rows, each locked in sequence order and decided on in its newest version, as a claim
751
- // locks them: a renewal that commits first keeps its row, and expiry waits for no lock domain (#6560).
752
- const lockedWhere = (where: string) =>
753
- `message_id IN (SELECT message_id FROM ${table} WHERE ${where} ORDER BY sequence${lockClause("update")})`;
1488
+ // locks them: a renewal that commits first keeps its row, and expiry waits for no lock domain (#6560). PostgreSQL
1489
+ // takes the locked rows' ids as one array, so the update finds each by its key rather than joining the table.
1490
+ const lockedWhere = (where: string) => {
1491
+ const locked = `SELECT message_id FROM ${table} WHERE ${where} ORDER BY sequence${lockClause("update")}`;
1492
+ return dialect === "postgres" ? `message_id = ANY(ARRAY(${locked}))` : `message_id IN (${locked})`;
1493
+ };
754
1494
  await database.transaction(async (executor) => {
755
1495
  // A row an older broker queued has no time: its retention starts now.
756
1496
  await executor.run(
@@ -759,8 +1499,8 @@ async function openOutboxStoreInCatalog(options: IntercomBrokerStateOptions): Pr
759
1499
  await executor.run(
760
1500
  `UPDATE ${table} SET state = 'failed', ${settled}
761
1501
  WHERE ${lockedWhere(
762
- `${UNDELIVERED} AND ${ageSince("queued_at")} > ?
763
- AND (claim_renewed_at IS NULL OR ${ageSince("claim_renewed_at")} > ?)`,
1502
+ `${UNDELIVERED} AND queued_at < ${now} - ?
1503
+ AND (claim_renewed_at IS NULL OR claim_renewed_at < ${now} - ?)`,
764
1504
  )}`,
765
1505
  JSON.stringify(OUTBOX_EXPIRED_REASON),
766
1506
  queuedOlderThanMs,
@@ -768,12 +1508,14 @@ async function openOutboxStoreInCatalog(options: IntercomBrokerStateOptions): Pr
768
1508
  );
769
1509
  }, fenced);
770
1510
  }
771
- const result = await database.run(
772
- `DELETE FROM ${table}
773
- WHERE state IN ('delivered', 'failed') AND ${ageSince("settled_at")} > ?`,
774
- settledOlderThanMs,
775
- );
776
- return result.changes;
1511
+ // Oldest first, from `<outbox>_settled`, in batches.
1512
+ return deleteInBatches(database, {
1513
+ table,
1514
+ key: "sequence",
1515
+ where: `${SETTLED} AND settled_at < ${now} - ?`,
1516
+ params: [settledOlderThanMs],
1517
+ orderBy: "settled_at",
1518
+ });
777
1519
  },
778
1520
  };
779
1521
  }