@bastani/atomic 0.10.11-alpha.3 → 0.10.11-alpha.4

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 (288) hide show
  1. package/CHANGELOG.md +51 -0
  2. package/dist/_shared/dist-KOELCESV.js +2 -2
  3. package/dist/_shared/fork-row-index-UAUAQRD5.js +2 -2
  4. package/dist/_shared/lib-4PES5P4V.js +2 -2
  5. package/dist/_shared/mode-interactive-sdk-7KXUFI2F.js +4 -4
  6. package/dist/_shared/mode-rpc-sdk-IOPGDYR4.js +4 -4
  7. package/dist/_shared/mode-shared-2QJSCUM6.js +4 -4
  8. package/dist/_shared/p1a-prewarm-XIU57JHF.js +3 -3
  9. package/dist/_shared/p1b-elig-TVB5CBLL.js +22 -6
  10. package/dist/_shared/p1b-elig-TVB5CBLL.js.map +1 -1
  11. package/dist/_shared/p2-shell-main-B2WIALFD.js +6 -3
  12. package/dist/_shared/p2-shell-main-B2WIALFD.js.map +1 -1
  13. package/dist/_shared/runtime-O4KCSG4C.js +2 -2
  14. package/dist/_shared/sdk-B5LEWGGI.js +899 -515
  15. package/dist/_shared/sdk-B5LEWGGI.js.map +1 -1
  16. package/dist/_shared/session-data-AHTU7IS6.js +2 -2
  17. package/dist/_shared/session-manager-list-2BLEEZVG.js +1 -1
  18. package/dist/_shared/{startup-0-0-EZUKEP4Q.js → startup-0-0-XJJDOIEC.js} +6 -12
  19. package/dist/_shared/{startup-0-0-EZUKEP4Q.js.map → startup-0-0-XJJDOIEC.js.map} +1 -1
  20. package/dist/_shared/{startup-0-1-RTOHJFDJ.js → startup-0-1-M6OWAYHH.js} +354 -103
  21. package/dist/_shared/startup-0-1-M6OWAYHH.js.map +1 -0
  22. package/dist/_shared/startup-0-2-5QHPCEON.js +18 -9
  23. package/dist/_shared/startup-0-2-5QHPCEON.js.map +1 -1
  24. package/dist/_shared/startup-0-3-4ZYBYQNM.js +4 -4
  25. package/dist/_shared/startup-0-4-ZMJV547D.js +4 -4
  26. package/dist/_shared/startup-0-5-YDW47QX6.js +4 -4
  27. package/dist/_shared/startup-10-0-TDQNBDDL.js +4 -4
  28. package/dist/_shared/startup-12-0-55AAXBJZ.js +1 -1
  29. package/dist/_shared/startup-14-0-MLX36RBG.js +2 -2
  30. package/dist/_shared/startup-15-0-YUKGAC63.js +2 -2
  31. package/dist/_shared/startup-15-1-4S7FLMNG.js +4 -4
  32. package/dist/_shared/startup-8-0-34CBHPZH.js +2114 -235
  33. package/dist/_shared/startup-8-0-34CBHPZH.js.map +1 -1
  34. package/dist/_shared/startup-8-1-LZFXSD3Z.js +12 -12
  35. package/dist/_shared/storage-command-7MGXLJGZ.js +6 -6
  36. package/dist/_shared/storage-command-7MGXLJGZ.js.map +1 -1
  37. package/dist/_shared/storage-status-K7PX2RXA.js +2 -2
  38. package/dist/_shared/task-unsaved-answer-VJ2KTB4V.js +2 -2
  39. package/dist/_shared/team-DOQKICG2.js +1 -1
  40. package/dist/_shared/tree-outline-MUEPK5B7.js +2 -2
  41. package/dist/builtin/intercom/CHANGELOG.md +19 -0
  42. package/dist/builtin/intercom/broker/broker.bundle.mjs +1020 -108
  43. package/dist/builtin/intercom/broker/client.ts +8 -0
  44. package/dist/builtin/intercom/broker/database-wake-up-bus.ts +91 -14
  45. package/dist/builtin/intercom/broker/multinode-router.ts +102 -17
  46. package/dist/builtin/intercom/broker/multinode-state-store.ts +41 -2
  47. package/dist/builtin/intercom/broker/send-order-gate.ts +5 -2
  48. package/dist/builtin/intercom/broker/sql-add-column.ts +22 -1
  49. package/dist/builtin/intercom/broker/sql-lease-store.ts +304 -48
  50. package/dist/builtin/intercom/broker/sql-outbox-store.ts +541 -50
  51. package/dist/builtin/intercom/broker/sql-restoring-reservation-store.ts +239 -8
  52. package/dist/builtin/intercom/broker/sql-retention.ts +11 -2
  53. package/dist/builtin/intercom/broker/sql-schema.ts +42 -8
  54. package/dist/builtin/intercom/index.bundle.mjs +13 -2
  55. package/dist/builtin/intercom/package.json +1 -1
  56. package/dist/builtin/mcp/index.bundle.mjs +1 -1
  57. package/dist/builtin/mcp/package.json +1 -1
  58. package/dist/builtin/subagents/CHANGELOG.md +6 -0
  59. package/dist/builtin/subagents/package.json +1 -1
  60. package/dist/builtin/subagents/skills/skill-creator/eval-viewer/generate_review.py +8 -1
  61. package/dist/builtin/subagents/src/extension/index.bundle.mjs +1 -1
  62. package/dist/builtin/web-access/index.bundle.mjs +1 -1
  63. package/dist/builtin/web-access/package.json +1 -1
  64. package/dist/cli/args.js +2 -2
  65. package/dist/cli/auth-cli.code.js +2 -2
  66. package/dist/cli/auth-cli.impl.js +3 -3
  67. package/dist/cli/auth-cli.js +3 -3
  68. package/dist/cli/blueprint-command.code.js +1 -1
  69. package/dist/cli/blueprint-command.impl.js +3 -3
  70. package/dist/cli/blueprint-command.js +3 -3
  71. package/dist/cli/intercom-command.code.js +2 -2
  72. package/dist/cli/intercom-command.impl.js +3 -3
  73. package/dist/cli/intercom-command.js +3 -3
  74. package/dist/cli/list-models.code.js +2 -2
  75. package/dist/cli/list-models.impl.js +3 -3
  76. package/dist/cli/list-models.js +3 -3
  77. package/dist/cli/session-picker.code.js +1 -1
  78. package/dist/cli/session-picker.impl.js +3 -3
  79. package/dist/cli/session-picker.js +3 -3
  80. package/dist/cli/startup-ui.code.js +1 -1
  81. package/dist/cli/startup-ui.impl.js +3 -3
  82. package/dist/cli/startup-ui.js +3 -3
  83. package/dist/cli/storage-command.impl.js +3 -3
  84. package/dist/cli/storage-command.js +3 -3
  85. package/dist/cli/storage-search-session.code.js +1 -1
  86. package/dist/cli/storage-search-session.impl.js +3 -3
  87. package/dist/cli/storage-search-session.js +3 -3
  88. package/dist/cli/team-command.code.js +1 -1
  89. package/dist/cli/team-command.impl.js +3 -3
  90. package/dist/cli/team-command.js +3 -3
  91. package/dist/cli.js +2 -2
  92. package/dist/core/debug.impl.js +3 -3
  93. package/dist/core/debug.js +3 -3
  94. package/dist/core/export-html/card-projection.impl.js +3 -3
  95. package/dist/core/export-html/card-projection.js +3 -3
  96. package/dist/core/export-html/index.code.js +4 -4
  97. package/dist/core/export-html/index.code.js.map +1 -1
  98. package/dist/core/export-html/index.impl.js +3 -3
  99. package/dist/core/export-html/index.js +3 -3
  100. package/dist/core/export-html/json-spans.impl.js +3 -3
  101. package/dist/core/export-html/json-spans.js +3 -3
  102. package/dist/core/export-html/oversized-render-inputs.impl.js +3 -3
  103. package/dist/core/export-html/oversized-render-inputs.js +3 -3
  104. package/dist/core/export-html/tool-renderer.impl.js +3 -3
  105. package/dist/core/export-html/tool-renderer.js +3 -3
  106. package/dist/core/extensions/jiti-loader.impl.js +3 -3
  107. package/dist/core/extensions/jiti-loader.js +3 -3
  108. package/dist/core/extensions/jiti-static-loader.impl.js +3 -3
  109. package/dist/core/extensions/jiti-static-loader.js +3 -3
  110. package/dist/core/extensions/loader-host-modules.code.js +1 -1
  111. package/dist/core/extensions/loader-host-modules.impl.js +3 -3
  112. package/dist/core/extensions/loader-host-modules.js +3 -3
  113. package/dist/core/extensions/loader-virtual-modules.js +1 -1
  114. package/dist/core/extensions/runner-context.js +1 -1
  115. package/dist/core/intercom-broker-control-host.impl.js +3 -3
  116. package/dist/core/intercom-broker-control-host.js +3 -3
  117. package/dist/core/intercom-broker-control.code.js +3 -3
  118. package/dist/core/intercom-broker-control.impl.js +3 -3
  119. package/dist/core/intercom-broker-control.js +3 -3
  120. package/dist/core/package-manager-storage-adapters.impl.js +3 -3
  121. package/dist/core/package-manager-storage-adapters.js +3 -3
  122. package/dist/core/process-start-token.d.ts +5 -4
  123. package/dist/core/sdk.code.js +2 -2
  124. package/dist/core/sdk.impl.js +3 -3
  125. package/dist/core/sdk.js +3 -3
  126. package/dist/core/session-manager-core.js +4 -4
  127. package/dist/core/session-manager-list.impl.js +3 -3
  128. package/dist/core/session-manager-list.js +3 -3
  129. package/dist/core/session-manager.code.js +1 -1
  130. package/dist/core/session-manager.impl.js +3 -3
  131. package/dist/core/session-manager.js +3 -3
  132. package/dist/core/session-storage.impl.js +3 -3
  133. package/dist/core/session-storage.js +3 -3
  134. package/dist/core/storage/database.d.ts +6 -0
  135. package/dist/core/storage/database.js.map +1 -1
  136. package/dist/core/storage/fenced-paths.d.ts +7 -6
  137. package/dist/core/storage/fenced-paths.js +7 -6
  138. package/dist/core/storage/fenced-paths.js.map +1 -1
  139. package/dist/core/storage/index.js +2 -2
  140. package/dist/core/storage/node-sqlite-thread.js +209 -19
  141. package/dist/core/storage/node-sqlite-thread.js.map +1 -1
  142. package/dist/core/storage/node-sqlite.js +435 -71
  143. package/dist/core/storage/node-sqlite.js.map +1 -1
  144. package/dist/core/storage/offline-snapshot-file.impl.js +3 -3
  145. package/dist/core/storage/offline-snapshot-file.js +3 -3
  146. package/dist/core/storage/provider.js +2 -2
  147. package/dist/core/storage/schema-catalog.d.ts +69 -7
  148. package/dist/core/storage/schema-catalog.js +352 -61
  149. package/dist/core/storage/schema-catalog.js.map +1 -1
  150. package/dist/core/storage/selection.js +2 -2
  151. package/dist/core/storage/session/branch-fork-source.code.js +2 -2
  152. package/dist/core/storage/session/branch-fork-source.impl.js +3 -3
  153. package/dist/core/storage/session/branch-fork-source.js +3 -3
  154. package/dist/core/storage/session/card-view.impl.js +3 -3
  155. package/dist/core/storage/session/card-view.js +3 -3
  156. package/dist/core/storage/session/child-reader.code.js +3 -3
  157. package/dist/core/storage/session/child-reader.impl.js +3 -3
  158. package/dist/core/storage/session/child-reader.js +3 -3
  159. package/dist/core/storage/session/chunked-resume-projection.impl.js +3 -3
  160. package/dist/core/storage/session/chunked-resume-projection.js +3 -3
  161. package/dist/core/storage/session/expanded-child-details.code.js +2 -2
  162. package/dist/core/storage/session/expanded-child-details.impl.js +3 -3
  163. package/dist/core/storage/session/expanded-child-details.js +3 -3
  164. package/dist/core/storage/session/fork-detach.d.ts +11 -1
  165. package/dist/core/storage/session/fork-row-bytes.impl.js +3 -3
  166. package/dist/core/storage/session/fork-row-bytes.js +3 -3
  167. package/dist/core/storage/session/fork-row-index.impl.js +3 -3
  168. package/dist/core/storage/session/fork-row-index.js +3 -3
  169. package/dist/core/storage/session/fork-staging.code.js +1 -1
  170. package/dist/core/storage/session/fork-staging.impl.js +3 -3
  171. package/dist/core/storage/session/fork-staging.js +3 -3
  172. package/dist/core/storage/session/fork-sweep.js +31 -7
  173. package/dist/core/storage/session/fork-sweep.js.map +1 -1
  174. package/dist/core/storage/session/fork-window.code.js +3 -3
  175. package/dist/core/storage/session/fork-window.impl.js +3 -3
  176. package/dist/core/storage/session/fork-window.js +3 -3
  177. package/dist/core/storage/session/history-pages.impl.js +3 -3
  178. package/dist/core/storage/session/history-pages.js +3 -3
  179. package/dist/core/storage/session/jsonl-entry-projection.impl.js +3 -3
  180. package/dist/core/storage/session/jsonl-entry-projection.js +3 -3
  181. package/dist/core/storage/session/jsonl-session-lock.d.ts +100 -0
  182. package/dist/core/storage/session/jsonl-session-store.d.ts +41 -23
  183. package/dist/core/storage/session/jsonl-session-store.impl.js +3 -3
  184. package/dist/core/storage/session/jsonl-session-store.js +3 -3
  185. package/dist/core/storage/session/memory-session-store.impl.js +3 -3
  186. package/dist/core/storage/session/memory-session-store.js +3 -3
  187. package/dist/core/storage/session/pinned-branch-resume.code.js +3 -3
  188. package/dist/core/storage/session/pinned-branch-resume.impl.js +3 -3
  189. package/dist/core/storage/session/pinned-branch-resume.js +3 -3
  190. package/dist/core/storage/session/released-history-files.code.js +8 -8
  191. package/dist/core/storage/session/released-history-files.code.js.map +1 -1
  192. package/dist/core/storage/session/released-history-files.impl.js +3 -3
  193. package/dist/core/storage/session/released-history-files.js +3 -3
  194. package/dist/core/storage/session/resident-fork-rows.impl.js +3 -3
  195. package/dist/core/storage/session/resident-fork-rows.js +3 -3
  196. package/dist/core/storage/session/session-resume.impl.js +3 -3
  197. package/dist/core/storage/session/session-resume.js +3 -3
  198. package/dist/core/storage/session/session-search-index.d.ts +9 -1
  199. package/dist/core/storage/session/snapshot-cut.impl.js +3 -3
  200. package/dist/core/storage/session/snapshot-cut.js +3 -3
  201. package/dist/core/storage/session/snapshot-history.code.js +3 -3
  202. package/dist/core/storage/session/snapshot-history.impl.js +3 -3
  203. package/dist/core/storage/session/snapshot-history.js +3 -3
  204. package/dist/core/storage/session/sql-session-store.d.ts +51 -7
  205. package/dist/core/storage/session/sql-session-store.impl.js +3 -3
  206. package/dist/core/storage/session/sql-session-store.js +3 -3
  207. package/dist/core/storage/session/tree-outline.impl.js +3 -3
  208. package/dist/core/storage/session/tree-outline.js +3 -3
  209. package/dist/core/storage/session/tree-presentation.impl.js +3 -3
  210. package/dist/core/storage/session/tree-presentation.js +3 -3
  211. package/dist/core/storage/sqlite-facade.d.ts +6 -0
  212. package/dist/core/storage/sqlite-facade.js +309 -33
  213. package/dist/core/storage/sqlite-facade.js.map +1 -1
  214. package/dist/core/storage/sqlite-open-batch.js +10 -0
  215. package/dist/core/storage/sqlite-open-batch.js.map +1 -0
  216. package/dist/core/storage/storage-status.impl.js +3 -3
  217. package/dist/core/storage/storage-status.js +3 -3
  218. package/dist/core/storage/team.impl.js +3 -3
  219. package/dist/core/storage/team.js +3 -3
  220. package/dist/core/structured-output/index.impl.js +3 -3
  221. package/dist/core/structured-output/index.js +3 -3
  222. package/dist/core/tasks/task-completion-entry.impl.js +3 -3
  223. package/dist/core/tasks/task-completion-entry.js +3 -3
  224. package/dist/core/tasks/task-file-history.code.js +3 -3
  225. package/dist/core/tasks/task-file-history.impl.js +3 -3
  226. package/dist/core/tasks/task-file-history.js +3 -3
  227. package/dist/core/tasks/task-reference-archive.code.js +3 -3
  228. package/dist/core/tasks/task-reference-archive.js +3 -3
  229. package/dist/core/tasks/task-reference-identity.js +3 -3
  230. package/dist/core/tasks/task-reference-stream.impl.js +3 -3
  231. package/dist/core/tasks/task-reference-stream.js +3 -3
  232. package/dist/core/tasks/task-unsaved-answer.impl.js +3 -3
  233. package/dist/core/tasks/task-unsaved-answer.js +3 -3
  234. package/dist/core/tasks/task-view-source.impl.js +3 -3
  235. package/dist/core/tasks/task-view-source.js +3 -3
  236. package/dist/core/tools/read-url.code.js +2 -2
  237. package/dist/core/tools/read-url.impl.js +3 -3
  238. package/dist/core/tools/read-url.js +3 -3
  239. package/dist/core/worktree-snapshot/blob-store.d.ts +5 -3
  240. package/dist/core/worktree-snapshot/blob-store.js +151 -21
  241. package/dist/core/worktree-snapshot/blob-store.js.map +1 -1
  242. package/dist/core/worktree-snapshot/errors.code.js +2 -2
  243. package/dist/core/worktree-snapshot/errors.impl.js +3 -3
  244. package/dist/core/worktree-snapshot/errors.js +3 -3
  245. package/dist/core/worktree-snapshot/fork-snapshot-index.js +158 -41
  246. package/dist/core/worktree-snapshot/fork-snapshot-index.js.map +1 -1
  247. package/dist/core/worktree-snapshot/session-index-reset.impl.js +3 -3
  248. package/dist/core/worktree-snapshot/session-index-reset.js +3 -3
  249. package/dist/extensions/codemode/execute.code.js +1 -1
  250. package/dist/extensions/codemode/execute.impl.js +3 -3
  251. package/dist/extensions/codemode/execute.js +3 -3
  252. package/dist/extensions/codemode/renderer.code.js +1 -1
  253. package/dist/extensions/codemode/renderer.impl.js +3 -3
  254. package/dist/extensions/codemode/renderer.js +3 -3
  255. package/dist/extensions/mcp/cli.code.js +1 -1
  256. package/dist/extensions/mcp/cli.impl.js +3 -3
  257. package/dist/extensions/mcp/cli.js +3 -3
  258. package/dist/extensions/mcp/cli.lazy.code.js +2 -2
  259. package/dist/extensions/mcp/cli.lazy.impl.js +3 -3
  260. package/dist/extensions/mcp/cli.lazy.js +3 -3
  261. package/dist/extensions/mcp/runtime.impl.js +3 -3
  262. package/dist/extensions/mcp/runtime.js +3 -3
  263. package/dist/index.js +2 -2
  264. package/dist/main-first-time-setup.code.js +1 -1
  265. package/dist/main-first-time-setup.impl.js +3 -3
  266. package/dist/main-first-time-setup.js +3 -3
  267. package/dist/modes/interactive/components/stored-tree-view.code.js +2 -2
  268. package/dist/modes/interactive/components/stored-tree-view.impl.js +3 -3
  269. package/dist/modes/interactive/components/stored-tree-view.js +3 -3
  270. package/dist/modes/interactive/components/user-message-selector-archive.impl.js +3 -3
  271. package/dist/modes/interactive/components/user-message-selector-archive.js +3 -3
  272. package/dist/package-manager-cli.code.js +4 -4
  273. package/dist/package-manager-cli.impl.js +3 -3
  274. package/dist/package-manager-cli.js +3 -3
  275. package/dist/rpc-entry.js +1 -1
  276. package/dist/startup-files.json +1 -1
  277. package/dist/startup-stages/3.js +1 -1
  278. package/dist/startup-stages/5.js +1 -1
  279. package/dist/utils/startup-database-spare.code.js +2 -2
  280. package/dist/utils/startup-database-spare.impl.js +3 -3
  281. package/dist/utils/startup-database-spare.js +3 -3
  282. package/dist/utils/tools-manager.code.js +1 -1
  283. package/dist/utils/tools-manager.impl.js +3 -3
  284. package/dist/utils/tools-manager.js +3 -3
  285. package/docs/changelog.mdx +49 -0
  286. package/docs/storage/jsonl.md +3 -3
  287. package/package.json +8 -8
  288. package/dist/_shared/startup-0-1-RTOHJFDJ.js.map +0 -1
@@ -12,7 +12,7 @@ import { payloadTooLargeKind, SQLITE_PAYLOAD_LIMITS, StorageAdapterLoadError, St
12
12
  import { fileIdentity, fileIdentityAsync } from "./file-identity.js";
13
13
  import { connectionWaits, currentHoldScope, forgetPlans, heldElsewhere, holdFile, inBacklog, modeOf, releaseHold, runDeferred, runInHold, runTryingFirst, runWhenFree, sqliteBusyError, useFileLock, useWrappedFile, } from "./node-sqlite-file-gate.js";
14
14
  import { STATEMENT_CACHE_SIZE, ThreadConnection, } from "./node-sqlite-thread.js";
15
- import { MAX_SEQUENCE_REQUEST_STATEMENTS, offerSequences, } from "./statement-sequence.js";
15
+ import { MAX_SEQUENCE_REQUEST_STATEMENTS, offerFinish, offerSequences, } from "./statement-sequence.js";
16
16
  import { configureConnection, isSqliteBusy, switchToWriteAheadLogSync } from "./write-ahead-log.js";
17
17
  /** Loaded at the first degradation only, so opening a database does not load debug output. */
18
18
  const loadDebugOutput = memoizeAsync(() => import("../debug.code.js").catch((error) => __atomicOnDemandFailed(error, "this feature")));
@@ -535,6 +535,31 @@ class SqliteHolderRecord {
535
535
  this.unavailable(cause);
536
536
  }
537
537
  }
538
+ /** Open descriptor for writing on the connection thread; undefined once closed or degraded. */
539
+ fd() {
540
+ return this.descriptor;
541
+ }
542
+ /** Records a write failure observed on the connection thread, retiring the descriptor immediately. */
543
+ failed(cause) {
544
+ const descriptor = this.descriptor;
545
+ this.descriptor = undefined;
546
+ this.unavailable(cause);
547
+ if (descriptor === undefined)
548
+ return;
549
+ this.writes = this.writes.then(async () => {
550
+ try {
551
+ await closeFile(descriptor);
552
+ await unlink(this.path);
553
+ }
554
+ catch {
555
+ // Already gone; a leftover record of an exited process is ignored and removed by whoever reads it.
556
+ }
557
+ });
558
+ }
559
+ /** Waits for any queued write or failure cleanup on this record to finish. */
560
+ drain() {
561
+ return this.writes;
562
+ }
538
563
  /** Records that this connection is about to try for the lock; written before its first attempt. */
539
564
  trying() {
540
565
  return this.write(`want ${String(Date.now()).padStart(15, "0")}\n`);
@@ -1028,6 +1053,25 @@ const MAX_GROUP_COMMIT_TRANSACTIONS = 128;
1028
1053
  export const DEFAULT_GROUP_COMMIT_HOLD_MS = 100;
1029
1054
  /** The span `getWriterQueueStats` reports on. */
1030
1055
  const WRITER_QUEUE_STATS_WINDOW_MS = 10_000;
1056
+ /** The `WriteLead` of `options`, or undefined where it names no statement this adapter can send ahead. */
1057
+ function writeLead(options) {
1058
+ const statements = [];
1059
+ for (const { sql, params } of options?.leading ?? []) {
1060
+ if (invalidTextParam(params) !== -1)
1061
+ break;
1062
+ statements.push({ sql, params: snapshotParams(params) });
1063
+ }
1064
+ if (statements.length === 0)
1065
+ return undefined;
1066
+ return { statements, only: options?.leadingOnly === true && statements.length === options.leading?.length };
1067
+ }
1068
+ /**
1069
+ * The COMMIT a transaction's `begin` or last request sends behind its statements: a prepared statement, as every
1070
+ * connection thread since sequences runs one, including one an older build started before an in-place update.
1071
+ */
1072
+ const COMMIT = { sql: "COMMIT", params: [] };
1073
+ /** Sentinel returned by `attemptBegin` when a `checkQueue` probe saw entries in the writers'-queue directory. */
1074
+ const BEGIN_CONTENDED = Symbol("begin-contended");
1031
1075
  /** Samples in time order; those older than the window are dropped as new ones arrive. */
1032
1076
  class WindowSamples {
1033
1077
  items = [];
@@ -1341,6 +1385,8 @@ class NodeSqliteDatabase {
1341
1385
  fileLock;
1342
1386
  /** That this wrapped connection to its file is open, which scopes the holds of threaded ones (see `FileHold`). */
1343
1387
  wrappedUse;
1388
+ /** What the `begin` request that took the lock answered for its leading statements, until `takeLed`. */
1389
+ led;
1344
1390
  /** The ticket of the writer holding the lock, on its way out of the queue while the transaction runs. */
1345
1391
  leaving;
1346
1392
  /** What the writers' queue gave up on, once per reason, in the order it first happened. */
@@ -1432,9 +1478,35 @@ class NodeSqliteDatabase {
1432
1478
  * Callers reach this only through `enqueue` and the transaction gate, so nothing else runs on the connection in
1433
1479
  * between.
1434
1480
  */
1435
- tryBegin() {
1481
+ /** Applies any holder-record write failure the connection thread reported, retiring and unlinking its file. */
1482
+ async flushThreadHolderError() {
1483
+ if (!(this.connection instanceof ThreadConnection))
1484
+ return;
1485
+ const error = this.connection.takeHolderError();
1486
+ if (error === undefined || this.holderRecord === undefined)
1487
+ return;
1488
+ this.holderRecord.failed(error);
1489
+ await this.holderRecord.drain();
1490
+ }
1491
+ /** Whether the connection's worker thread handles holder-record writes and writers'-queue directory checks. */
1492
+ threadManagesLock() {
1493
+ return this.connection instanceof ThreadConnection && this.connection.inTransaction !== undefined;
1494
+ }
1495
+ tryBegin(statements, checkQueue = false) {
1436
1496
  const lock = this.fileLock;
1437
- return this.call(lock === undefined ? { kind: "begin" } : { kind: "begin", lockState: lock.buffer, lockTag: lock.tag });
1497
+ const threadLock = this.threadManagesLock();
1498
+ return this.call({
1499
+ kind: "begin",
1500
+ ...(lock === undefined ? {} : { lockState: lock.buffer, lockTag: lock.tag }),
1501
+ ...(statements === undefined ? {} : { statements }),
1502
+ ...(threadLock
1503
+ ? {
1504
+ holderFd: this.holderRecord?.fd(),
1505
+ ...(this.writeQueue === undefined ? {} : { writersDir: this.writeQueue.directory }),
1506
+ ...(checkQueue ? { checkQueue: true } : {}),
1507
+ }
1508
+ : {}),
1509
+ });
1438
1510
  }
1439
1511
  /** Changes whenever another connection commits to the database: the lock is being used, not held idle. */
1440
1512
  async dataVersion() {
@@ -1450,39 +1522,65 @@ class NodeSqliteDatabase {
1450
1522
  * `StorageWriteLockTimeoutError` of a writer that gives up names the process holding the lock. Every other failure,
1451
1523
  * including a writers' queue that cannot be used, rejects at once with its cause.
1452
1524
  */
1453
- async begin(lockWaitMs = this.lockWaitMs) {
1525
+ async begin(lockWaitMs = this.lockWaitMs, statements) {
1454
1526
  const waitStarted = performance.now();
1455
1527
  let ticket;
1456
1528
  let notices;
1457
1529
  let holding = false;
1530
+ const threadManaged = this.threadManagesLock();
1458
1531
  try {
1459
- // Before its first attempt, so a holder stopped or starved the moment it takes the lock is still named. The writers'
1460
- // queue is looked at meanwhile, so the two file system calls cost one wait for its threads instead of two.
1461
1532
  const queue = this.writeQueue;
1462
1533
  queue?.observe();
1463
- const [, contended] = await Promise.all([this.holderRecord?.trying(), queue?.contendedOffLoop()]);
1464
- // Writers already waiting in other processes go first.
1465
- if (queue !== undefined && contended === true) {
1466
- const waiting = await this.queueFileOp(() => queue.liveTicketsOffLoop());
1467
- if (waiting.length > 0)
1468
- ticket = await this.queueFileOp(() => queue.join(waiting));
1534
+ let lastCause;
1535
+ if (threadManaged) {
1536
+ // Uncontended fast path: the connection thread checks the writers'-queue directory, writes the holder
1537
+ // record, and attempts BEGIN IMMEDIATE (+ leading statements) in one request with zero thread-pool waits.
1538
+ const fast = await this.attemptBegin(statements, true);
1539
+ if (fast === undefined) {
1540
+ holding = true;
1541
+ this.lockUse.acquired(waitStarted);
1542
+ return this.takeLed();
1543
+ }
1544
+ if (fast === BEGIN_CONTENDED && queue !== undefined) {
1545
+ const waiting = await this.queueFileOp(() => queue.liveTicketsOffLoop());
1546
+ if (waiting.length > 0)
1547
+ ticket = await this.queueFileOp(() => queue.join(waiting));
1548
+ }
1549
+ else if (fast !== BEGIN_CONTENDED) {
1550
+ lastCause = fast;
1551
+ if (queue !== undefined)
1552
+ ticket = await this.queueFileOp(async () => queue.join(await queue.liveTicketsOffLoop()));
1553
+ }
1554
+ }
1555
+ else {
1556
+ // Before its first attempt, so a holder stopped or starved the moment it takes the lock is still named. The writers'
1557
+ // queue is looked at meanwhile, so the two file system calls cost one wait for its threads instead of two.
1558
+ const [, contended] = await Promise.all([this.holderRecord?.trying(), queue?.contendedOffLoop()]);
1559
+ // Writers already waiting in other processes go first.
1560
+ if (queue !== undefined && contended === true) {
1561
+ const waiting = await this.queueFileOp(() => queue.liveTicketsOffLoop());
1562
+ if (waiting.length > 0)
1563
+ ticket = await this.queueFileOp(() => queue.join(waiting));
1564
+ }
1469
1565
  }
1470
1566
  // Read only once this writer waits, so an uncontended transaction pays nothing for it.
1471
- let version = ticket === undefined ? undefined : await this.dataVersion();
1567
+ let version = ticket === undefined && lastCause === undefined ? undefined : await this.dataVersion();
1472
1568
  let stalledSince = performance.now();
1473
- let lastCause;
1474
1569
  for (;;) {
1475
1570
  notices?.clear();
1476
1571
  if (ticket !== undefined)
1477
1572
  notices = await this.watchTicket(ticket, notices);
1478
1573
  const behind = ticket !== undefined && (await this.queueFileOp(() => ticket.behindOthers()));
1479
1574
  if (!behind) {
1480
- const attempt = this.attemptBegin();
1575
+ const attempt = this.attemptBegin(statements);
1481
1576
  const refused = attempt instanceof Promise ? await attempt : attempt;
1482
1577
  if (refused === undefined) {
1483
1578
  holding = true;
1484
- this.acquired(waitStarted);
1485
- return;
1579
+ if (threadManaged)
1580
+ this.lockUse.acquired(waitStarted);
1581
+ else
1582
+ this.acquired(waitStarted);
1583
+ return this.takeLed();
1486
1584
  }
1487
1585
  lastCause = refused;
1488
1586
  if (ticket === undefined && queue !== undefined) {
@@ -1503,10 +1601,13 @@ class NodeSqliteDatabase {
1503
1601
  const stalledMs = performance.now() - stalledSince;
1504
1602
  if (stalledMs >= lockWaitMs)
1505
1603
  throw await this.lockWaitTimeout(lockWaitMs, stalledMs, behind, lastCause);
1506
- if (!behind && committed && (await this.attemptThroughRelease())) {
1604
+ if (!behind && committed && (await this.attemptThroughRelease(statements))) {
1507
1605
  holding = true;
1508
- this.acquired(waitStarted);
1509
- return;
1606
+ if (threadManaged)
1607
+ this.lockUse.acquired(waitStarted);
1608
+ else
1609
+ this.acquired(waitStarted);
1610
+ return this.takeLed();
1510
1611
  }
1511
1612
  const recheckMs = notices?.watching === true || stalledMs >= this.lockWaitMs
1512
1613
  ? LOCK_WAIT_RECHECK_MS
@@ -1524,37 +1625,51 @@ class NodeSqliteDatabase {
1524
1625
  this.leaving = { ticket: ticket.name, left: ticket.leave() };
1525
1626
  else
1526
1627
  await ticket?.leave();
1527
- if (!holding)
1628
+ if (!holding) {
1629
+ await this.flushThreadHolderError();
1528
1630
  await this.holderRecord?.free();
1631
+ }
1529
1632
  }
1530
1633
  }
1531
1634
  /**
1532
- * One attempt at the lock: `undefined` once it is taken, or the SQLITE_BUSY that refused it. Anything else fails.
1533
- * Answered at once on the calling thread, and as a promise by a connection on a thread of its own.
1635
+ * One attempt at the lock: `undefined` once it is taken, `BEGIN_CONTENDED` when `checkQueue` found entries in the
1636
+ * writers'-queue directory, or the SQLITE_BUSY that refused it. Anything else fails. Answered at once on the
1637
+ * calling thread, and as a promise by a connection on a thread of its own.
1534
1638
  */
1535
- attemptBegin() {
1639
+ attemptBegin(statements, checkQueue = false) {
1536
1640
  const refusal = (error) => {
1537
1641
  const cause = error instanceof StorageUnavailableError ? error.cause : undefined;
1538
1642
  if (!isSqliteBusy(cause))
1539
1643
  throw error;
1540
1644
  return cause;
1541
1645
  };
1646
+ const isContended = (value) => typeof value === "object" && value !== null && "contended" in value;
1542
1647
  // Open from the moment BEGIN is sent: the connection's thread may take the lock while this thread runs on.
1543
1648
  const hold = this.fileGate?.role === "holds" ? holdFile(this.fileGate.file) : undefined;
1544
1649
  let attempt;
1545
1650
  try {
1546
- attempt = this.tryBegin();
1651
+ attempt = this.tryBegin(statements, checkQueue);
1547
1652
  }
1548
1653
  catch (error) {
1549
1654
  releaseHold(hold);
1550
1655
  return refusal(error);
1551
1656
  }
1552
1657
  if (!(attempt instanceof Promise)) {
1658
+ if (isContended(attempt)) {
1659
+ releaseHold(hold);
1660
+ return BEGIN_CONTENDED;
1661
+ }
1553
1662
  this.current.hold = hold;
1663
+ this.led = attempt;
1554
1664
  return undefined;
1555
1665
  }
1556
- return attempt.then(() => {
1666
+ return attempt.then((led) => {
1667
+ if (isContended(led)) {
1668
+ releaseHold(hold);
1669
+ return BEGIN_CONTENDED;
1670
+ }
1557
1671
  this.current.hold = hold;
1672
+ this.led = led;
1558
1673
  return undefined;
1559
1674
  }, (error) => {
1560
1675
  releaseHold(hold);
@@ -1570,15 +1685,21 @@ class NodeSqliteDatabase {
1570
1685
  * free while that writer kept committing. Trying on every turn for a tick finds the lock the moment such a
1571
1686
  * writer's commit lets go of it.
1572
1687
  */
1573
- async attemptThroughRelease() {
1688
+ async attemptThroughRelease(statements) {
1574
1689
  const until = performance.now() + LOCK_RELEASE_RETRY_MS;
1575
1690
  for (let attempt = 0; attempt < LOCK_RELEASE_RETRY_ATTEMPTS && performance.now() < until; attempt++) {
1576
1691
  await new Promise((resolve) => setImmediate(resolve));
1577
- if ((await this.attemptBegin()) === undefined)
1692
+ if ((await this.attemptBegin(statements)) === undefined)
1578
1693
  return true;
1579
1694
  }
1580
1695
  return false;
1581
1696
  }
1697
+ /** The answer of the `begin` request that took the lock, for the transaction that took it, once. */
1698
+ takeLed() {
1699
+ const led = this.led;
1700
+ this.led = undefined;
1701
+ return led;
1702
+ }
1582
1703
  /**
1583
1704
  * Keeps the ticket live and watched: one watch for the whole wait, started again only when the ticket had to be
1584
1705
  * recreated, since a watch ends with the file it watched.
@@ -1616,16 +1737,20 @@ class NodeSqliteDatabase {
1616
1737
  this.current.hold = undefined;
1617
1738
  releaseHold(hold);
1618
1739
  this.lockUse.released(committed);
1619
- const recorded = this.holderRecord?.free();
1740
+ const release = this.connection instanceof ThreadConnection ? this.connection.takeReleaseState() : undefined;
1741
+ await this.flushThreadHolderError();
1742
+ const recorded = release?.freed === true ? undefined : this.holderRecord?.free();
1620
1743
  const leaving = this.leaving;
1621
1744
  this.leaving = undefined;
1622
1745
  // Gone before the turn is handed on, so the writer it wakes finds no ticket of this one ahead of it.
1623
1746
  await leaving?.left;
1624
- try {
1625
- await this.writeQueue?.wakeNext(leaving?.ticket);
1626
- }
1627
- catch (cause) {
1628
- this.degraded("wake-failed", cause);
1747
+ if (leaving !== undefined || release?.hasWaiters !== false) {
1748
+ try {
1749
+ await this.writeQueue?.wakeNext(leaving?.ticket);
1750
+ }
1751
+ catch (cause) {
1752
+ this.degraded("wake-failed", cause);
1753
+ }
1629
1754
  }
1630
1755
  await recorded;
1631
1756
  }
@@ -1667,10 +1792,34 @@ class NodeSqliteDatabase {
1667
1792
  * Statements on the connection, each sent the moment it is called, so calls a transaction makes without awaiting
1668
1793
  * the ones before run in the order it made them, as on a connection that runs each one as it is called.
1669
1794
  */
1670
- createExecutor(active) {
1671
- const execute = async (request, params = []) => {
1795
+ createExecutor(active, lead, finish, writeTx = false) {
1796
+ /** Whether the transaction takes no more calls: its COMMIT went with its start, or its callback finished it. */
1797
+ const ended = () => lead?.ended === true || finish?.statements !== undefined;
1798
+ /** The next leading statement's answer when `sql` and `params` make it; otherwise the lead ends. */
1799
+ const ledBy = (sql, params) => {
1800
+ if (lead === undefined)
1801
+ return undefined;
1802
+ const next = lead.answered[0];
1803
+ if (next !== undefined && next.sql === sql && sameParams(next.params, params)) {
1804
+ lead.answered.shift();
1805
+ return next;
1806
+ }
1807
+ lead.answered.length = 0;
1808
+ return undefined;
1809
+ };
1810
+ const closedTransactionError = () => unavailable(this.descriptor, new Error("SQLite transaction is no longer active"));
1811
+ const execute = async (request, params = [], answer) => {
1672
1812
  if (!active())
1673
1813
  throw new StorageTransactionClosedError();
1814
+ const led = "sql" in request && answer !== undefined ? ledBy(request.sql, params) : ledBy("", []);
1815
+ if (led !== undefined)
1816
+ return answer(led.rows, led.changes);
1817
+ if (lead?.aborted !== undefined)
1818
+ throw unavailable(this.descriptor, lead.aborted);
1819
+ if (ended())
1820
+ throw new StorageTransactionClosedError();
1821
+ if (writeTx && this.connection instanceof ThreadConnection && this.connection.inTransaction === false)
1822
+ throw closedTransactionError();
1674
1823
  const invalidIndex = invalidTextParam(params);
1675
1824
  if (invalidIndex !== -1)
1676
1825
  throw new StorageInvalidTextError(invalidIndex);
@@ -1679,16 +1828,98 @@ class NodeSqliteDatabase {
1679
1828
  const executor = {
1680
1829
  checkJsonbExtract: () => execute({ kind: "jsonbExtract" }),
1681
1830
  exec: (sql) => execute({ kind: "exec", sql }),
1682
- run: (sql, ...params) => execute({ kind: "run", sql, params }, params),
1683
- get: (sql, ...params) => execute({ kind: "get", sql, params }, params),
1684
- all: (sql, ...params) => execute({ kind: "all", sql, params }, params),
1831
+ run: (sql, ...params) => execute({ kind: "run", sql, params }, params, (_rows, changes) => ({ changes })),
1832
+ get: (sql, ...params) => execute({ kind: "get", sql, params }, params, (rows) => rows[0]),
1833
+ all: (sql, ...params) => execute({ kind: "all", sql, params }, params, (rows) => rows),
1685
1834
  };
1686
1835
  // On the calling thread a sequence would hold the event loop for all of its statements.
1687
1836
  const connection = this.connection;
1688
- if (connection instanceof ThreadConnection)
1689
- offerSequences(executor, (sequence) => this.sendSequence(connection, sequence, active));
1837
+ if (connection instanceof ThreadConnection) {
1838
+ offerSequences(executor, (sequence) => {
1839
+ ledBy("", []);
1840
+ if (active() && lead?.aborted !== undefined)
1841
+ return Promise.reject(unavailable(this.descriptor, lead.aborted));
1842
+ if (active() && ended())
1843
+ return Promise.reject(new StorageTransactionClosedError());
1844
+ if (active() && writeTx && connection.inTransaction === false)
1845
+ return Promise.reject(closedTransactionError());
1846
+ return this.sendSequence(connection, sequence, active);
1847
+ });
1848
+ if (finish !== undefined)
1849
+ offerFinish(executor, (statements) => {
1850
+ // One request carries them with the end: the end is the last of its statements.
1851
+ if (!active() || ended() || lead?.aborted !== undefined)
1852
+ return false;
1853
+ if (writeTx && connection.inTransaction === false)
1854
+ return false;
1855
+ if (statements.some(({ params }) => invalidTextParam(params) !== -1))
1856
+ return false;
1857
+ // Strip any matching prefix already executed by `begin` or `lead` so those statements never run twice.
1858
+ let skip = 0;
1859
+ if (lead !== undefined) {
1860
+ while (skip < statements.length && skip < lead.answered.length) {
1861
+ const next = lead.answered[skip];
1862
+ const statement = statements[skip];
1863
+ if (statement.script === true ||
1864
+ next.sql !== statement.sql ||
1865
+ !sameParams(next.params, statement.params))
1866
+ break;
1867
+ skip += 1;
1868
+ }
1869
+ }
1870
+ const remaining = skip === 0 ? statements : statements.slice(skip);
1871
+ if (remaining.length >= MAX_SEQUENCE_REQUEST_STATEMENTS)
1872
+ return false;
1873
+ ledBy("", []);
1874
+ finish.statements = remaining.map(({ sql, params, script }) => sendableStatement({ sql, params: snapshotParams(params), ...(script === true ? { script } : {}) }));
1875
+ return true;
1876
+ });
1877
+ }
1690
1878
  return executor;
1691
1879
  }
1880
+ /**
1881
+ * The lead a transaction's callback is answered from, out of `led`, the answer of the `begin` or `lead` request that
1882
+ * sent `statements`; undefined when that request sent none. `offset` skips prefix statements such as a `SAVEPOINT`
1883
+ * prepended ahead of `statements`. `withCommit` says the request sent the COMMIT behind them, which ran unless a
1884
+ * statement before it failed.
1885
+ */
1886
+ transactionLead(statements, led, withCommit, offset = 0) {
1887
+ if (led === undefined || statements === undefined)
1888
+ return undefined;
1889
+ const answered = led.answers
1890
+ .slice(offset, offset + statements.length)
1891
+ .map((answer, index) => ({ ...statements[index], ...answer }));
1892
+ const failedAt = led.failure === undefined ? undefined : led.answers.length - offset;
1893
+ const reachedCommit = withCommit && (failedAt === undefined || failedAt === statements.length);
1894
+ return {
1895
+ answered,
1896
+ ended: reachedCommit,
1897
+ ...(reachedCommit && failedAt !== undefined
1898
+ ? { commitFailure: led.failure, commitOpen: led.open === true }
1899
+ : {}),
1900
+ ...(!reachedCommit && failedAt !== undefined && led.open !== true ? { aborted: led.failure } : {}),
1901
+ };
1902
+ }
1903
+ /**
1904
+ * Ends the transaction its callback returned from: sends `end` (COMMIT or a savepoint's RELEASE), behind the statements
1905
+ * the callback finished it with, in one request, or where its `begin` request sent the COMMIT already, reports that
1906
+ * COMMIT's failure. A statement that fails there fails the transaction, as the COMMIT does.
1907
+ */
1908
+ async endTransaction(end, lead, finish) {
1909
+ if (lead?.aborted !== undefined)
1910
+ throw unavailable(this.descriptor, lead.aborted);
1911
+ if (lead?.ended === true) {
1912
+ if (lead.commitFailure !== undefined)
1913
+ throw unavailable(this.descriptor, lead.commitFailure);
1914
+ return;
1915
+ }
1916
+ const statements = finish?.statements;
1917
+ if (statements === undefined || statements.length === 0 || !(this.connection instanceof ThreadConnection)) {
1918
+ await this.executor.exec(end.sql);
1919
+ return;
1920
+ }
1921
+ await this.sendSequence(this.connection, { statements: [...statements, end] }, () => true);
1922
+ }
1692
1923
  /**
1693
1924
  * Sends `sequence` to the connection's thread: `repeat` with the first statements as one request, and the rest in
1694
1925
  * requests of at most `MAX_SEQUENCE_REQUEST_STATEMENTS`, each taken from `statements` and sent once the one before it
@@ -1880,25 +2111,48 @@ class NodeSqliteDatabase {
1880
2111
  // The queue's directory outlives its writers: only a live ticket means a writer is waiting. One that cannot be
1881
2112
  // read counts as a writer waiting.
1882
2113
  const queue = this.writeQueue;
1883
- if (queue !== undefined && (await queue.contendedOffLoop())) {
1884
- const waiting = await queue.liveTicketsOffLoop().catch(() => undefined);
1885
- if (waiting === undefined || waiting.length > 0)
1886
- return false;
1887
- }
1888
2114
  const start = performance.now();
1889
- await this.holderRecord?.trying();
1890
- try {
1891
- const attempt = this.attemptBegin();
1892
- if ((attempt instanceof Promise ? await attempt : attempt) !== undefined) {
2115
+ const threadManaged = this.threadManagesLock();
2116
+ if (threadManaged) {
2117
+ try {
2118
+ let attempt = await this.attemptBegin(undefined, true);
2119
+ if (attempt === BEGIN_CONTENDED && queue !== undefined) {
2120
+ const waiting = await queue.liveTicketsOffLoop().catch(() => undefined);
2121
+ if (waiting === undefined || waiting.length > 0)
2122
+ return false;
2123
+ attempt = await this.attemptBegin();
2124
+ }
2125
+ if (attempt !== undefined) {
2126
+ await this.holderRecord?.free();
2127
+ return false;
2128
+ }
2129
+ }
2130
+ catch (error) {
1893
2131
  await this.holderRecord?.free();
1894
- return false;
2132
+ throw error;
1895
2133
  }
2134
+ this.lockUse.acquired(start);
1896
2135
  }
1897
- catch (error) {
1898
- await this.holderRecord?.free();
1899
- throw error;
2136
+ else {
2137
+ if (queue !== undefined && (await queue.contendedOffLoop())) {
2138
+ const waiting = await queue.liveTicketsOffLoop().catch(() => undefined);
2139
+ if (waiting === undefined || waiting.length > 0)
2140
+ return false;
2141
+ }
2142
+ await this.holderRecord?.trying();
2143
+ try {
2144
+ const attempt = this.attemptBegin();
2145
+ if ((attempt instanceof Promise ? await attempt : attempt) !== undefined) {
2146
+ await this.holderRecord?.free();
2147
+ return false;
2148
+ }
2149
+ }
2150
+ catch (error) {
2151
+ await this.holderRecord?.free();
2152
+ throw error;
2153
+ }
2154
+ this.acquired(start);
1900
2155
  }
1901
- this.acquired(start);
1902
2156
  return new Promise((resolve, reject) => {
1903
2157
  void this.commitAlone({ callback, resolve: () => resolve(true), reject, scope }).catch(reject);
1904
2158
  });
@@ -1941,6 +2195,8 @@ class NodeSqliteDatabase {
1941
2195
  }
1942
2196
  if (this.closing)
1943
2197
  return Promise.reject(new StoreClosedError(this.descriptor));
2198
+ // Only a connection thread takes statements with its BEGIN; one on the calling thread runs each call as it is made.
2199
+ const lead = this.connection instanceof ThreadConnection ? writeLead(options) : undefined;
1944
2200
  return new Promise((resolve, reject) => {
1945
2201
  const queued = {
1946
2202
  callback,
@@ -1948,6 +2204,7 @@ class NodeSqliteDatabase {
1948
2204
  reject,
1949
2205
  lockWaitMs: options?.lockWaitMs,
1950
2206
  scope: currentHoldScope(),
2207
+ ...(lead === undefined ? {} : { lead }),
1951
2208
  };
1952
2209
  const last = this.waitingBatches.at(-1);
1953
2210
  if (last?.open === true && last.members.length < MAX_GROUP_COMMIT_TRANSACTIONS) {
@@ -2045,19 +2302,44 @@ class NodeSqliteDatabase {
2045
2302
  * transactions requested directly behind it while it waited join it: otherwise they would queue for the lock all
2046
2303
  * over again once it lets go. Members left after the hold budget take the lock again with nothing new, so other
2047
2304
  * connections to the file wait for at most one batch of this one's.
2305
+ *
2306
+ * The first member's leading statements go in the request that takes the lock, and so does its COMMIT where it names
2307
+ * only those (`leadingOnly`) and nothing is queued to join it: that transaction is then one request (#6560).
2048
2308
  */
2049
2309
  async runBatch(batch, firstAcquisition) {
2310
+ const first = batch.members[0];
2311
+ const willGroup = batch.members.length > 1 || (firstAcquisition && this.waitingBatches[0]?.position === batch.position + 1);
2312
+ const withCommit = first.lead?.only === true && !willGroup;
2313
+ const withSavepoint = first.lead !== undefined &&
2314
+ willGroup &&
2315
+ this.connection instanceof ThreadConnection &&
2316
+ this.connection.inTransaction !== undefined;
2317
+ const statements = first.lead === undefined
2318
+ ? undefined
2319
+ : withCommit
2320
+ ? [...first.lead.statements, COMMIT]
2321
+ : withSavepoint
2322
+ ? [{ sql: "SAVEPOINT atomic_group_0", params: [] }, ...first.lead.statements]
2323
+ : first.lead.statements;
2324
+ let led;
2050
2325
  try {
2051
- await this.begin(this.lockWait(batch.members));
2326
+ led = await this.begin(this.lockWait(batch.members), statements);
2052
2327
  }
2053
2328
  catch (cause) {
2054
2329
  for (const queued of batch.members.splice(0))
2055
2330
  queued.reject(cause);
2056
2331
  return;
2057
2332
  }
2058
- if (firstAcquisition)
2333
+ const savepointRan = withSavepoint && led !== undefined && led.answers.length >= 1;
2334
+ const lead = withSavepoint && led !== undefined && led.answers.length === 0 && led.failure !== undefined
2335
+ ? { answered: [], ended: false, ...(led.open === true ? {} : { aborted: led.failure }) }
2336
+ : this.transactionLead(first.lead?.statements, led, withCommit, savepointRan ? 1 : 0);
2337
+ // A transaction its start committed takes nobody along: they wait for the lock once more.
2338
+ if (firstAcquisition && lead?.ended !== true)
2059
2339
  this.absorbNext(batch);
2060
- await (batch.members.length === 1 ? this.commitAlone(batch.members.pop()) : this.commitMembers(batch));
2340
+ await (batch.members.length === 1
2341
+ ? this.commitAlone(batch.members.pop(), lead)
2342
+ : this.commitMembers(batch, lead, savepointRan));
2061
2343
  }
2062
2344
  /**
2063
2345
  * Moves the transactions of the batches queued directly behind this one (no statement between them) into this one,
@@ -2075,20 +2357,40 @@ class NodeSqliteDatabase {
2075
2357
  lockWait(batch) {
2076
2358
  return Math.max(...batch.map((queued) => queued.lockWaitMs ?? this.lockWaitMs));
2077
2359
  }
2078
- /** A transaction with nobody queued with it commits on its own, without savepoints. */
2079
- async commitAlone(queued) {
2360
+ /**
2361
+ * A transaction with nobody queued with it commits on its own, without savepoints. `lead` answers its first calls; a
2362
+ * COMMIT its start sent already let go of the lock, which is handed on before the callback reads the answers.
2363
+ */
2364
+ async commitAlone(queued, lead) {
2080
2365
  let active = true;
2366
+ const finish = { end: COMMIT };
2367
+ const executor = () => this.createExecutor(() => active, lead, finish, true);
2368
+ if (lead?.ended === true && lead.commitFailure === undefined) {
2369
+ await this.released(true);
2370
+ try {
2371
+ queued.resolve(await runInHold(undefined, queued.scope, () => queued.callback(executor())));
2372
+ }
2373
+ catch (cause) {
2374
+ queued.reject(cause);
2375
+ }
2376
+ finally {
2377
+ active = false;
2378
+ }
2379
+ return;
2380
+ }
2081
2381
  try {
2082
- const value = await runInHold(this.current.hold, queued.scope, () => queued.callback(this.createExecutor(() => active)));
2382
+ const value = await runInHold(this.current.hold, queued.scope, () => queued.callback(executor()));
2083
2383
  active = false;
2084
- await this.executor.exec("COMMIT");
2384
+ await this.endTransaction(COMMIT, lead, finish);
2085
2385
  await this.released(true);
2086
2386
  queued.resolve(value);
2087
2387
  }
2088
2388
  catch (cause) {
2089
2389
  active = false;
2090
2390
  try {
2091
- await this.executor.exec("ROLLBACK");
2391
+ // A failure of its leading statements, or of a bundled COMMIT that SQLite rolled back itself, left nothing to roll back.
2392
+ if (lead?.aborted === undefined && !(lead?.ended === true && lead.commitOpen !== true))
2393
+ await this.executor.exec("ROLLBACK");
2092
2394
  }
2093
2395
  catch (rollbackCause) {
2094
2396
  await this.released(false);
@@ -2101,21 +2403,83 @@ class NodeSqliteDatabase {
2101
2403
  }
2102
2404
  /**
2103
2405
  * Runs the batch's members in one transaction, for at most `groupCommitHoldMs`: members left when it runs out
2104
- * wait for the lock again, still ahead of anything queued after them.
2406
+ * wait for the lock again, still ahead of anything queued after them. `lead` answers the first member's first calls:
2407
+ * when `firstHasSavepoint` is false, its leading statements ran before any savepoint (later members arrived while
2408
+ * `begin` ran), so its failure rolls back the transaction, in which nothing else has run, and the others take the
2409
+ * lock again. Each member with a savepoint bundles its `SAVEPOINT` with its leading statements in one request when
2410
+ * supported by the connection thread.
2105
2411
  */
2106
- async commitMembers(batch) {
2412
+ async commitMembers(batch, lead, firstHasSavepoint = false) {
2107
2413
  const began = performance.now();
2108
2414
  const outcomes = [];
2109
- for (const queued of batch.members) {
2415
+ if (lead !== undefined && !firstHasSavepoint) {
2416
+ const first = batch.members[0];
2417
+ let active = true;
2418
+ try {
2419
+ const value = await runInHold(this.current.hold, first.scope, () => first.callback(this.createExecutor(() => active, lead, undefined, true)));
2420
+ active = false;
2421
+ // A transaction that already ended runs nobody else, whatever the callback made of the failure.
2422
+ if (lead.aborted !== undefined)
2423
+ throw unavailable(this.descriptor, lead.aborted);
2424
+ if (this.connection instanceof ThreadConnection && this.connection.inTransaction === false)
2425
+ throw unavailable(this.descriptor, new Error("SQLite transaction is no longer active"));
2426
+ outcomes.push({ ok: true, value });
2427
+ }
2428
+ catch (cause) {
2429
+ active = false;
2430
+ let failure = cause;
2431
+ try {
2432
+ if (lead.aborted === undefined)
2433
+ await this.executor.exec("ROLLBACK");
2434
+ }
2435
+ catch (rollbackCause) {
2436
+ failure = new StorageRollbackError(cause, rollbackCause);
2437
+ }
2438
+ await this.released(false);
2439
+ batch.members.shift().reject(failure);
2440
+ if (batch.members.length > 0)
2441
+ await this.runBatch(batch, false);
2442
+ return;
2443
+ }
2444
+ }
2445
+ for (const queued of batch.members.slice(outcomes.length)) {
2110
2446
  if (outcomes.length > 0 && performance.now() - began >= this.groupCommitHoldMs)
2111
2447
  break;
2112
2448
  const savepoint = `atomic_group_${outcomes.length}`;
2449
+ const release = { sql: `RELEASE ${savepoint}`, params: [] };
2450
+ const finish = { end: release };
2113
2451
  let active = true;
2452
+ let memberLead;
2114
2453
  try {
2115
- await this.executor.exec(`SAVEPOINT ${savepoint}`);
2116
- const value = await runInHold(this.current.hold, queued.scope, () => queued.callback(this.createExecutor(() => active)));
2454
+ if (outcomes.length === 0 && firstHasSavepoint) {
2455
+ memberLead = lead;
2456
+ }
2457
+ else if (queued.lead !== undefined &&
2458
+ this.connection instanceof ThreadConnection &&
2459
+ this.connection.inTransaction !== undefined) {
2460
+ const led = (await this.connection
2461
+ .request({
2462
+ kind: "lead",
2463
+ statements: [{ sql: `SAVEPOINT ${savepoint}`, params: [] }, ...queued.lead.statements],
2464
+ })
2465
+ .catch((cause) => {
2466
+ throw unavailable(this.descriptor, cause);
2467
+ }));
2468
+ if (led === undefined) {
2469
+ await this.executor.exec(`SAVEPOINT ${savepoint}`);
2470
+ }
2471
+ else {
2472
+ if (led.answers.length === 0 && led.failure !== undefined)
2473
+ throw unavailable(this.descriptor, led.failure);
2474
+ memberLead = this.transactionLead(queued.lead.statements, led, false, 1);
2475
+ }
2476
+ }
2477
+ else {
2478
+ await this.executor.exec(`SAVEPOINT ${savepoint}`);
2479
+ }
2480
+ const value = await runInHold(this.current.hold, queued.scope, () => queued.callback(this.createExecutor(() => active, memberLead, finish, true)));
2117
2481
  active = false;
2118
- await this.executor.exec(`RELEASE ${savepoint}`);
2482
+ await this.endTransaction(release, memberLead, finish);
2119
2483
  outcomes.push({ ok: true, value });
2120
2484
  }
2121
2485
  catch (cause) {
@@ -2409,7 +2773,7 @@ function __atomicOnDemandFailed(error, feature) {
2409
2773
  return (async () => {
2410
2774
  const root = new URL("../../", import.meta.url);
2411
2775
  const releases = (globalThis[Symbol.for("atomic.in-place-update-release.v1")] ??= new Map());
2412
- const key = `${root.href}#0.10.11-alpha.3`;
2776
+ const key = `${root.href}#0.10.11-alpha.4`;
2413
2777
  let release = releases.get(key);
2414
2778
  if (release === undefined) {
2415
2779
  const current = (async () => {
@@ -2437,7 +2801,7 @@ function __atomicOnDemandFailed(error, feature) {
2437
2801
  } catch {
2438
2802
  // No installation to read, as in a bundle of the package: the release the process runs decides.
2439
2803
  }
2440
- const updatedTo = typeof installed === "string" && installed !== "0.10.11-alpha.3" ? installed : running !== undefined && running.version !== "0.10.11-alpha.3" ? "0.10.11-alpha.3" : undefined;
2804
+ const updatedTo = typeof installed === "string" && installed !== "0.10.11-alpha.4" ? installed : running !== undefined && running.version !== "0.10.11-alpha.4" ? "0.10.11-alpha.4" : undefined;
2441
2805
  if (updatedTo === undefined) throw error;
2442
2806
  const application = typeof running?.name === "string" ? running.name : "atomic";
2443
2807
  const restart = new Error(`${application} was updated to ${updatedTo} while this session was running; restart it to keep using ${feature}.`, {