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

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 (457) hide show
  1. package/CHANGELOG.md +155 -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 +9 -9
  7. package/dist/_shared/mode-rpc-sdk-IOPGDYR4.js +8 -8
  8. package/dist/_shared/mode-shared-2QJSCUM6.js +9 -9
  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} +14 -2
  14. package/dist/_shared/{p1b-elig-ENCUPKKJ.js.map → p1b-elig-TVB5CBLL.js.map} +1 -1
  15. package/dist/_shared/runtime-O4KCSG4C.js +5 -5
  16. package/dist/_shared/{sdk-AVFII7NK.js → sdk-B5LEWGGI.js} +2633 -488
  17. package/dist/_shared/sdk-B5LEWGGI.js.map +1 -0
  18. package/dist/_shared/session-data-AHTU7IS6.js +3 -3
  19. package/dist/_shared/session-manager-list-2BLEEZVG.js +1 -1
  20. package/dist/_shared/settings-startup-8-DNZ2RIHM.js +1 -1
  21. package/dist/_shared/{settings-startup-4QCVCI53.js → settings-startup-HXQLSUWM.js} +8 -2
  22. package/dist/_shared/settings-startup-HXQLSUWM.js.map +1 -0
  23. package/dist/_shared/{startup-0-0-57KF6LZH.js → startup-0-0-EZUKEP4Q.js} +436 -51
  24. package/dist/_shared/startup-0-0-EZUKEP4Q.js.map +1 -0
  25. package/dist/_shared/{startup-0-1-GIY75K46.js → startup-0-1-RTOHJFDJ.js} +240 -279
  26. package/dist/_shared/startup-0-1-RTOHJFDJ.js.map +1 -0
  27. package/dist/_shared/{startup-0-2-27OWFHV6.js → startup-0-2-5QHPCEON.js} +254 -46
  28. package/dist/_shared/startup-0-2-5QHPCEON.js.map +1 -0
  29. package/dist/_shared/{startup-0-3-T4DVFYWX.js → startup-0-3-4ZYBYQNM.js} +273 -14
  30. package/dist/_shared/startup-0-3-4ZYBYQNM.js.map +1 -0
  31. package/dist/_shared/startup-0-4-ZMJV547D.js +14 -9
  32. package/dist/_shared/startup-0-4-ZMJV547D.js.map +1 -1
  33. package/dist/_shared/startup-0-5-YDW47QX6.js +10 -10
  34. package/dist/_shared/startup-0-5-YDW47QX6.js.map +1 -1
  35. package/dist/_shared/startup-10-0-TDQNBDDL.js +9 -9
  36. package/dist/_shared/startup-12-0-55AAXBJZ.js +3 -3
  37. package/dist/_shared/startup-14-0-MLX36RBG.js +6 -7
  38. package/dist/_shared/startup-14-0-MLX36RBG.js.map +1 -1
  39. package/dist/_shared/startup-15-0-YUKGAC63.js +7 -7
  40. package/dist/_shared/startup-15-1-4S7FLMNG.js +22 -30
  41. package/dist/_shared/startup-15-1-4S7FLMNG.js.map +1 -1
  42. package/dist/_shared/startup-8-0-34CBHPZH.js +455 -102
  43. package/dist/_shared/startup-8-0-34CBHPZH.js.map +1 -1
  44. package/dist/_shared/{startup-8-1-X32CYSXB.js → startup-8-1-LZFXSD3Z.js} +162 -1184
  45. package/dist/_shared/startup-8-1-LZFXSD3Z.js.map +1 -0
  46. package/dist/_shared/storage-command-7MGXLJGZ.js +189 -36
  47. package/dist/_shared/storage-command-7MGXLJGZ.js.map +1 -1
  48. package/dist/_shared/storage-status-K7PX2RXA.js +557 -0
  49. package/dist/_shared/storage-status-K7PX2RXA.js.map +1 -0
  50. package/dist/_shared/task-unsaved-answer-VJ2KTB4V.js +2 -2
  51. package/dist/_shared/team-DOQKICG2.js +376 -0
  52. package/dist/_shared/team-DOQKICG2.js.map +1 -0
  53. package/dist/_shared/tree-outline-MUEPK5B7.js +3 -3
  54. package/dist/builtin/intercom/CHANGELOG.md +34 -0
  55. package/dist/builtin/intercom/README.md +2 -2
  56. package/dist/builtin/intercom/broker/broker.bundle.mjs +1091 -344
  57. package/dist/builtin/intercom/broker/database-wake-up-bus.ts +243 -64
  58. package/dist/builtin/intercom/broker/multinode-router.ts +154 -22
  59. package/dist/builtin/intercom/broker/multinode-state-store.ts +30 -3
  60. package/dist/builtin/intercom/broker/open-broker-state.ts +14 -0
  61. package/dist/builtin/intercom/broker/sql-add-column.ts +29 -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 +208 -101
  66. package/dist/builtin/intercom/broker/sql-outbox-store.ts +516 -102
  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 +24 -7
  70. package/dist/builtin/intercom/broker/sql-retention.ts +141 -0
  71. package/dist/builtin/intercom/broker/sql-schema.ts +199 -27
  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 +2 -3
  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 +6 -0
  79. package/dist/builtin/subagents/package.json +1 -1
  80. package/dist/builtin/subagents/src/extension/index.bundle.mjs +1 -1
  81. package/dist/builtin/web-access/index.bundle.mjs +2 -10
  82. package/dist/builtin/web-access/package.json +1 -1
  83. package/dist/bun/bundled-sqlite.js +41 -0
  84. package/dist/bun/bundled-sqlite.js.map +1 -0
  85. package/dist/cli/args.js +2 -2
  86. package/dist/cli/auth-cli.code.js +6 -6
  87. package/dist/cli/auth-cli.impl.js +3 -3
  88. package/dist/cli/auth-cli.js +3 -3
  89. package/dist/cli/blueprint-command.code.js +4 -4
  90. package/dist/cli/blueprint-command.impl.js +3 -3
  91. package/dist/cli/blueprint-command.js +3 -3
  92. package/dist/cli/intercom-command.code.js +4 -4
  93. package/dist/cli/intercom-command.code.js.map +1 -1
  94. package/dist/cli/intercom-command.impl.js +3 -3
  95. package/dist/cli/intercom-command.js +3 -3
  96. package/dist/cli/list-models.code.js +2 -2
  97. package/dist/cli/list-models.impl.js +3 -3
  98. package/dist/cli/list-models.js +3 -3
  99. package/dist/cli/session-picker.code.js +2 -2
  100. package/dist/cli/session-picker.impl.js +3 -3
  101. package/dist/cli/session-picker.js +3 -3
  102. package/dist/cli/startup-ui.code.js +2 -2
  103. package/dist/cli/startup-ui.impl.js +3 -3
  104. package/dist/cli/startup-ui.js +3 -3
  105. package/dist/cli/storage-command.impl.js +3 -3
  106. package/dist/cli/storage-command.js +3 -3
  107. package/dist/cli/storage-search-session.code.js +3 -3
  108. package/dist/cli/storage-search-session.impl.js +3 -3
  109. package/dist/cli/storage-search-session.js +3 -3
  110. package/dist/cli/team-command.code.js +20 -114
  111. package/dist/cli/team-command.code.js.map +1 -1
  112. package/dist/cli/team-command.impl.js +3 -3
  113. package/dist/cli/team-command.js +3 -3
  114. package/dist/cli.js +5 -18
  115. package/dist/cli.js.map +1 -1
  116. package/dist/core/agent-rehydrate-errors.d.ts +4 -9
  117. package/dist/core/compaction/compactor.d.ts +3 -3
  118. package/dist/core/debug.code.js +1 -1
  119. package/dist/core/debug.impl.js +3 -3
  120. package/dist/core/debug.js +3 -3
  121. package/dist/core/export-html/card-projection.impl.js +3 -3
  122. package/dist/core/export-html/card-projection.js +3 -3
  123. package/dist/core/export-html/index.code.js +2 -2
  124. package/dist/core/export-html/index.impl.js +3 -3
  125. package/dist/core/export-html/index.js +3 -3
  126. package/dist/core/export-html/json-spans.impl.js +3 -3
  127. package/dist/core/export-html/json-spans.js +3 -3
  128. package/dist/core/export-html/oversized-render-inputs.code.js +1 -1
  129. package/dist/core/export-html/oversized-render-inputs.impl.js +3 -3
  130. package/dist/core/export-html/oversized-render-inputs.js +3 -3
  131. package/dist/core/export-html/tool-renderer.impl.js +3 -3
  132. package/dist/core/export-html/tool-renderer.js +3 -3
  133. package/dist/core/extensions/jiti-loader.impl.js +3 -3
  134. package/dist/core/extensions/jiti-loader.js +3 -3
  135. package/dist/core/extensions/jiti-static-loader.impl.js +3 -3
  136. package/dist/core/extensions/jiti-static-loader.js +3 -3
  137. package/dist/core/extensions/loader-host-modules.code.js +1 -1
  138. package/dist/core/extensions/loader-host-modules.impl.js +3 -3
  139. package/dist/core/extensions/loader-host-modules.js +3 -3
  140. package/dist/core/extensions/loader-virtual-modules.js +1 -1
  141. package/dist/core/extensions/runner-context.js +3 -3
  142. package/dist/core/intercom-broker-control-host.code.js +2 -2
  143. package/dist/core/intercom-broker-control-host.impl.js +3 -3
  144. package/dist/core/intercom-broker-control-host.js +3 -3
  145. package/dist/core/intercom-broker-control.code.js +3 -3
  146. package/dist/core/intercom-broker-control.impl.js +3 -3
  147. package/dist/core/intercom-broker-control.js +3 -3
  148. package/dist/core/package-manager-storage-adapters.code.js +1 -1
  149. package/dist/core/package-manager-storage-adapters.impl.js +3 -3
  150. package/dist/core/package-manager-storage-adapters.js +3 -3
  151. package/dist/core/process-start-token.d.ts +8 -0
  152. package/dist/core/process-tree-containment.d.ts +16 -0
  153. package/dist/core/sdk-types.d.ts +1 -2
  154. package/dist/core/sdk-types.js.map +1 -1
  155. package/dist/core/sdk.code.js +4 -4
  156. package/dist/core/sdk.impl.js +3 -3
  157. package/dist/core/sdk.js +3 -3
  158. package/dist/core/session-manager-core.js +27 -15
  159. package/dist/core/session-manager-core.js.map +1 -1
  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 +3 -3
  163. package/dist/core/session-manager.impl.js +3 -3
  164. package/dist/core/session-manager.js +3 -3
  165. package/dist/core/session-open-markers.js +3 -0
  166. package/dist/core/session-open-markers.js.map +1 -0
  167. package/dist/core/session-storage.code.js +1 -1
  168. package/dist/core/session-storage.impl.js +3 -3
  169. package/dist/core/session-storage.js +3 -3
  170. package/dist/core/settings-schema.d.ts +0 -3
  171. package/dist/core/storage/added-exports-0-10-11.js +19 -0
  172. package/dist/core/storage/added-exports-0-10-11.js.map +1 -0
  173. package/dist/core/storage/added-exports.js +3 -0
  174. package/dist/core/storage/added-exports.js.map +1 -1
  175. package/dist/core/storage/creation-time.js +105 -0
  176. package/dist/core/storage/creation-time.js.map +1 -0
  177. package/dist/core/storage/database.d.ts +56 -5
  178. package/dist/core/storage/database.js.map +1 -1
  179. package/dist/core/storage/dialect.d.ts +1 -1
  180. package/dist/core/storage/dialect.js +1 -1
  181. package/dist/core/storage/dialect.js.map +1 -1
  182. package/dist/core/storage/errors.d.ts +13 -13
  183. package/dist/core/storage/errors.js +10 -16
  184. package/dist/core/storage/errors.js.map +1 -1
  185. package/dist/core/storage/fenced-paths.d.ts +11 -0
  186. package/dist/core/storage/fenced-paths.js +11 -0
  187. package/dist/core/storage/fenced-paths.js.map +1 -1
  188. package/dist/core/storage/file-identity.d.ts +2 -0
  189. package/dist/core/storage/file-identity.js +24 -8
  190. package/dist/core/storage/file-identity.js.map +1 -1
  191. package/dist/core/storage/index.d.ts +4 -3
  192. package/dist/core/storage/index.js +5 -3
  193. package/dist/core/storage/index.js.map +1 -1
  194. package/dist/core/storage/libsql-removed.d.ts +71 -0
  195. package/dist/core/storage/libsql-removed.js +123 -0
  196. package/dist/core/storage/libsql-removed.js.map +1 -0
  197. package/dist/core/storage/migrations.d.ts +81 -8
  198. package/dist/core/storage/migrations.js +386 -47
  199. package/dist/core/storage/migrations.js.map +1 -1
  200. package/dist/core/storage/node-sqlite-file-gate.js +0 -15
  201. package/dist/core/storage/node-sqlite-file-gate.js.map +1 -1
  202. package/dist/core/storage/node-sqlite-thread.js +36 -12
  203. package/dist/core/storage/node-sqlite-thread.js.map +1 -1
  204. package/dist/core/storage/node-sqlite.js +135 -3
  205. package/dist/core/storage/node-sqlite.js.map +1 -1
  206. package/dist/core/storage/offline-snapshot-file.impl.js +3 -3
  207. package/dist/core/storage/offline-snapshot-file.js +3 -3
  208. package/dist/core/storage/prefix.d.ts +1 -1
  209. package/dist/core/storage/prefix.js +14 -2
  210. package/dist/core/storage/prefix.js.map +1 -1
  211. package/dist/core/storage/process-selection.d.ts +5 -5
  212. package/dist/core/storage/provider.js +2 -2
  213. package/dist/core/storage/schema-catalog.d.ts +82 -5
  214. package/dist/core/storage/schema-catalog.js +244 -34
  215. package/dist/core/storage/schema-catalog.js.map +1 -1
  216. package/dist/core/storage/selection.d.ts +7 -82
  217. package/dist/core/storage/selection.js +20 -235
  218. package/dist/core/storage/selection.js.map +1 -1
  219. package/dist/core/storage/session/branch-fork-source.code.js +9 -8
  220. package/dist/core/storage/session/branch-fork-source.code.js.map +1 -1
  221. package/dist/core/storage/session/branch-fork-source.impl.js +3 -3
  222. package/dist/core/storage/session/branch-fork-source.js +3 -3
  223. package/dist/core/storage/session/card-view.impl.js +3 -3
  224. package/dist/core/storage/session/card-view.js +3 -3
  225. package/dist/core/storage/session/child-reader.code.js +4 -4
  226. package/dist/core/storage/session/child-reader.impl.js +3 -3
  227. package/dist/core/storage/session/child-reader.js +3 -3
  228. package/dist/core/storage/session/chunked-resume-projection.impl.js +3 -3
  229. package/dist/core/storage/session/chunked-resume-projection.js +3 -3
  230. package/dist/core/storage/session/errors.js +1 -1
  231. package/dist/core/storage/session/expanded-child-details.code.js +3 -3
  232. package/dist/core/storage/session/expanded-child-details.impl.js +3 -3
  233. package/dist/core/storage/session/expanded-child-details.js +3 -3
  234. package/dist/core/storage/session/fork-detach.d.ts +118 -0
  235. package/dist/core/storage/session/fork-row-bytes.impl.js +3 -3
  236. package/dist/core/storage/session/fork-row-bytes.js +3 -3
  237. package/dist/core/storage/session/fork-row-index.impl.js +3 -3
  238. package/dist/core/storage/session/fork-row-index.js +3 -3
  239. package/dist/core/storage/session/fork-schema.js +53 -0
  240. package/dist/core/storage/session/fork-schema.js.map +1 -0
  241. package/dist/core/storage/session/fork-segments.d.ts +58 -0
  242. package/dist/core/storage/session/fork-staging.code.js +5 -8
  243. package/dist/core/storage/session/fork-staging.code.js.map +1 -1
  244. package/dist/core/storage/session/fork-staging.impl.js +3 -3
  245. package/dist/core/storage/session/fork-staging.js +3 -3
  246. package/dist/core/storage/session/fork-sweep.js +61 -0
  247. package/dist/core/storage/session/fork-sweep.js.map +1 -0
  248. package/dist/core/storage/session/fork-window.code.js +4 -4
  249. package/dist/core/storage/session/fork-window.impl.js +3 -3
  250. package/dist/core/storage/session/fork-window.js +3 -3
  251. package/dist/core/storage/session/history-pages.impl.js +3 -3
  252. package/dist/core/storage/session/history-pages.js +3 -3
  253. package/dist/core/storage/session/jsonl-entry-projection.impl.js +3 -3
  254. package/dist/core/storage/session/jsonl-entry-projection.js +3 -3
  255. package/dist/core/storage/session/jsonl-session-store.d.ts +42 -2
  256. package/dist/core/storage/session/jsonl-session-store.impl.js +3 -3
  257. package/dist/core/storage/session/jsonl-session-store.js +3 -3
  258. package/dist/core/storage/session/memory-session-store.impl.js +3 -3
  259. package/dist/core/storage/session/memory-session-store.js +3 -3
  260. package/dist/core/storage/session/pinned-branch-resume.code.js +3 -3
  261. package/dist/core/storage/session/pinned-branch-resume.impl.js +3 -3
  262. package/dist/core/storage/session/pinned-branch-resume.js +3 -3
  263. package/dist/core/storage/session/released-history-files.code.js +4 -4
  264. package/dist/core/storage/session/released-history-files.impl.js +3 -3
  265. package/dist/core/storage/session/released-history-files.js +3 -3
  266. package/dist/core/storage/session/resident-fork-rows.code.js +1 -1
  267. package/dist/core/storage/session/resident-fork-rows.impl.js +3 -3
  268. package/dist/core/storage/session/resident-fork-rows.js +3 -3
  269. package/dist/core/storage/session/session-resume.impl.js +3 -3
  270. package/dist/core/storage/session/session-resume.js +3 -3
  271. package/dist/core/storage/session/session-search-index.d.ts +43 -4
  272. package/dist/core/storage/session/snapshot-cut.impl.js +3 -3
  273. package/dist/core/storage/session/snapshot-cut.js +3 -3
  274. package/dist/core/storage/session/snapshot-history.code.js +4 -4
  275. package/dist/core/storage/session/snapshot-history.impl.js +3 -3
  276. package/dist/core/storage/session/snapshot-history.js +3 -3
  277. package/dist/core/storage/session/sql-session-store.code.js +1 -1
  278. package/dist/core/storage/session/sql-session-store.d.ts +394 -20
  279. package/dist/core/storage/session/sql-session-store.impl.js +4 -4
  280. package/dist/core/storage/session/sql-session-store.js +4 -4
  281. package/dist/core/storage/session/tree-outline.impl.js +3 -3
  282. package/dist/core/storage/session/tree-outline.js +3 -3
  283. package/dist/core/storage/session/tree-presentation.impl.js +3 -3
  284. package/dist/core/storage/session/tree-presentation.js +3 -3
  285. package/dist/core/storage/session/types.d.ts +22 -0
  286. package/dist/core/storage/sqlite-facade.d.ts +23 -2
  287. package/dist/core/storage/sqlite-facade.js +34 -0
  288. package/dist/core/storage/sqlite-facade.js.map +1 -1
  289. package/dist/core/storage/storage-status.code.js +1 -1
  290. package/dist/core/storage/storage-status.impl.js +3 -3
  291. package/dist/core/storage/storage-status.js +3 -3
  292. package/dist/core/storage/team.code.js +1 -1
  293. package/dist/core/storage/team.d.ts +26 -115
  294. package/dist/core/storage/team.impl.js +3 -3
  295. package/dist/core/storage/team.js +3 -3
  296. package/dist/core/structured-output/index.code.js +1 -1
  297. package/dist/core/structured-output/index.impl.js +3 -3
  298. package/dist/core/structured-output/index.js +3 -3
  299. package/dist/core/tasks/task-completion-entry.impl.js +3 -3
  300. package/dist/core/tasks/task-completion-entry.js +3 -3
  301. package/dist/core/tasks/task-file-history.code.js +4 -4
  302. package/dist/core/tasks/task-file-history.impl.js +3 -3
  303. package/dist/core/tasks/task-file-history.js +3 -3
  304. package/dist/core/tasks/task-reference-archive.code.js +5 -5
  305. package/dist/core/tasks/task-reference-archive.js +3 -3
  306. package/dist/core/tasks/task-reference-identity.js +3 -3
  307. package/dist/core/tasks/task-reference-stream.impl.js +3 -3
  308. package/dist/core/tasks/task-reference-stream.js +3 -3
  309. package/dist/core/tasks/task-unsaved-answer.impl.js +3 -3
  310. package/dist/core/tasks/task-unsaved-answer.js +3 -3
  311. package/dist/core/tasks/task-view-source.code.js +1 -1
  312. package/dist/core/tasks/task-view-source.impl.js +3 -3
  313. package/dist/core/tasks/task-view-source.js +3 -3
  314. package/dist/core/tools/history-session.d.ts +2 -0
  315. package/dist/core/tools/history-tasks.d.ts +3 -2
  316. package/dist/core/tools/read-url.code.js +4 -4
  317. package/dist/core/tools/read-url.impl.js +3 -3
  318. package/dist/core/tools/read-url.js +3 -3
  319. package/dist/core/worktree-snapshot/blob-store.d.ts +71 -3
  320. package/dist/core/worktree-snapshot/blob-store.js +575 -67
  321. package/dist/core/worktree-snapshot/blob-store.js.map +1 -1
  322. package/dist/core/worktree-snapshot/errors.code.js +3 -3
  323. package/dist/core/worktree-snapshot/errors.impl.js +3 -3
  324. package/dist/core/worktree-snapshot/errors.js +3 -3
  325. package/dist/core/worktree-snapshot/fork-blob-guard.js +81 -0
  326. package/dist/core/worktree-snapshot/fork-blob-guard.js.map +1 -0
  327. package/dist/core/worktree-snapshot/fork-snapshot-index.js +162 -0
  328. package/dist/core/worktree-snapshot/fork-snapshot-index.js.map +1 -0
  329. package/dist/core/worktree-snapshot/session-index-reset.code.js +4 -0
  330. package/dist/core/worktree-snapshot/session-index-reset.code.js.map +1 -1
  331. package/dist/core/worktree-snapshot/session-index-reset.impl.js +3 -3
  332. package/dist/core/worktree-snapshot/session-index-reset.js +3 -3
  333. package/dist/extensions/codemode/execute.code.js +2 -2
  334. package/dist/extensions/codemode/execute.impl.js +3 -3
  335. package/dist/extensions/codemode/execute.js +3 -3
  336. package/dist/extensions/codemode/renderer.code.js +2 -2
  337. package/dist/extensions/codemode/renderer.impl.js +3 -3
  338. package/dist/extensions/codemode/renderer.js +3 -3
  339. package/dist/extensions/mcp/cli.code.js +3 -3
  340. package/dist/extensions/mcp/cli.impl.js +3 -3
  341. package/dist/extensions/mcp/cli.js +3 -3
  342. package/dist/extensions/mcp/cli.lazy.code.js +2 -2
  343. package/dist/extensions/mcp/cli.lazy.impl.js +3 -3
  344. package/dist/extensions/mcp/cli.lazy.js +3 -3
  345. package/dist/extensions/mcp/runtime.code.js +1 -1
  346. package/dist/extensions/mcp/runtime.impl.js +3 -3
  347. package/dist/extensions/mcp/runtime.js +3 -3
  348. package/dist/index.d.ts +3 -1
  349. package/dist/index.js +8 -8
  350. package/dist/main-first-time-setup.code.js +2 -2
  351. package/dist/main-first-time-setup.impl.js +3 -3
  352. package/dist/main-first-time-setup.js +3 -3
  353. package/dist/main.js +1 -1
  354. package/dist/modes/interactive/components/stored-tree-view.code.js +3 -3
  355. package/dist/modes/interactive/components/stored-tree-view.impl.js +3 -3
  356. package/dist/modes/interactive/components/stored-tree-view.js +3 -3
  357. package/dist/modes/interactive/components/user-message-selector-archive.impl.js +3 -3
  358. package/dist/modes/interactive/components/user-message-selector-archive.js +3 -3
  359. package/dist/modes/interactive/startup-shell-eligibility.js +1 -1
  360. package/dist/modes/interactive-engine/engine-prewarm.d.ts +1 -1
  361. package/dist/modes/print-mode.js +1 -1
  362. package/dist/package-manager-cli.code.js +7 -7
  363. package/dist/package-manager-cli.impl.js +3 -3
  364. package/dist/package-manager-cli.js +3 -3
  365. package/dist/rpc-entry.js +1 -1
  366. package/dist/startup-files.json +1 -1
  367. package/dist/startup-stages/10.js +1 -1
  368. package/dist/startup-stages/11.js +1 -1
  369. package/dist/startup-stages/12.js +1 -1
  370. package/dist/startup-stages/2.js +2 -3
  371. package/dist/startup-stages/3.js +1 -3
  372. package/dist/startup-stages/4.js +1 -2
  373. package/dist/startup-stages/5.js +1 -1
  374. package/dist/startup-stages/6.js +5 -7
  375. package/dist/startup-stages/7.js +3 -6
  376. package/dist/startup-stages/8.js +7 -2
  377. package/dist/startup-stages/9.js +1 -7
  378. package/dist/startup-stages/stages.json +1 -1
  379. package/dist/utils/compile-cache-deferral.js +8 -13
  380. package/dist/utils/compile-cache-deferral.js.map +1 -1
  381. package/dist/utils/compile-cache-warmup-host.js +3 -4
  382. package/dist/utils/compile-cache-warmup-host.js.map +1 -1
  383. package/dist/utils/compile-cache.js +12 -100
  384. package/dist/utils/compile-cache.js.map +1 -1
  385. package/dist/utils/startup-database-spare.code.js +3 -3
  386. package/dist/utils/startup-database-spare.impl.js +3 -3
  387. package/dist/utils/startup-database-spare.js +3 -3
  388. package/dist/utils/tools-manager.code.js +1 -1
  389. package/dist/utils/tools-manager.impl.js +3 -3
  390. package/dist/utils/tools-manager.js +3 -3
  391. package/dist/utils/worker-threads.js +2 -15
  392. package/dist/utils/worker-threads.js.map +1 -1
  393. package/docs/build.md +3 -3
  394. package/docs/changelog.mdx +1421 -69
  395. package/docs/compaction/reference.md +5 -5
  396. package/docs/compaction.md +7 -9
  397. package/docs/containerization.md +2 -2
  398. package/docs/custom-provider/api-reference.md +1 -1
  399. package/docs/docs.json +37 -10
  400. package/docs/environment-variables.md +0 -2
  401. package/docs/extensions/api-reference.md +4 -4
  402. package/docs/getting-started/installation.md +3 -0
  403. package/docs/guides/configuration.md +1 -1
  404. package/docs/guides/non-interactive.md +1 -1
  405. package/docs/guides/resume-on-any-machine.md +14 -22
  406. package/docs/guides/team-setup.md +56 -83
  407. package/docs/guides.md +2 -4
  408. package/docs/herdr.md +1 -1
  409. package/docs/index.md +1 -1
  410. package/docs/intercom/operations.md +26 -21
  411. package/docs/intercom/reference.md +2 -2
  412. package/docs/intercom.md +1 -1
  413. package/docs/libraries/storage-postgres.md +9 -9
  414. package/docs/libraries.md +2 -3
  415. package/docs/models-configuration.md +2 -2
  416. package/docs/models.md +2 -3
  417. package/docs/packages/authoring.md +7 -7
  418. package/docs/packages.md +1 -1
  419. package/docs/programmatic.md +2 -2
  420. package/docs/quickstart.md +1 -1
  421. package/docs/reference/cli.md +6 -11
  422. package/docs/reference.md +2 -2
  423. package/docs/rpc/extension-ui.md +2 -2
  424. package/docs/sdk/reference.md +5 -4
  425. package/docs/sdk/storage.md +8 -92
  426. package/docs/sdk/structured-decisions.md +1 -1
  427. package/docs/sdk/web-server.md +3 -3
  428. package/docs/sdk.md +14 -4
  429. package/docs/security.md +1 -1
  430. package/docs/session-format.md +5 -5
  431. package/docs/sessions.md +31 -42
  432. package/docs/settings.md +7 -8
  433. package/docs/storage/custom-adapters.md +255 -0
  434. package/docs/storage/jsonl.md +117 -0
  435. package/docs/{guides/postgres-pgbouncer.md → storage/postgres/pgbouncer.md} +73 -68
  436. package/docs/storage/postgres/tuning.md +337 -0
  437. package/docs/storage/postgres.md +556 -0
  438. package/docs/storage/sqlite.md +99 -0
  439. package/docs/storage.md +333 -956
  440. package/docs/subagents/authoring.md +1 -1
  441. package/docs/subagents.md +2 -2
  442. package/docs/tools.md +1 -1
  443. package/docs/worktree-snapshots.md +2 -2
  444. package/package.json +9 -9
  445. package/schemas/models.schema.json +2 -2
  446. package/schemas/settings.schema.json +0 -14
  447. package/dist/_shared/sdk-AVFII7NK.js.map +0 -1
  448. package/dist/_shared/settings-startup-4QCVCI53.js.map +0 -1
  449. package/dist/_shared/startup-0-0-57KF6LZH.js.map +0 -1
  450. package/dist/_shared/startup-0-1-GIY75K46.js.map +0 -1
  451. package/dist/_shared/startup-0-2-27OWFHV6.js.map +0 -1
  452. package/dist/_shared/startup-0-3-T4DVFYWX.js.map +0 -1
  453. package/dist/_shared/startup-8-1-X32CYSXB.js.map +0 -1
  454. package/dist/core/intercom-broker-control.d.ts +0 -129
  455. package/dist/startup-stages/13.js +0 -1
  456. package/docs/guides/postgres-tuning.md +0 -311
  457. package/docs/libraries/storage-libsql.md +0 -97
@@ -1,10 +1,13 @@
1
- import { transactionFinisher } from "../storage/added-exports.js";
1
+ import { storageSchemaCurrent, transactionFinisher } from "../storage/added-exports.js";
2
+ import { noteStorageSchemaTables } from "../storage/added-exports-0-10-11.js";
2
3
  import { dialectOf } from "../storage/dialect.js";
3
4
  import { StorageWriteLockTimeoutError } from "../storage/errors.js";
4
- import { applyStorageMigrations, withShortSchemaLockWaits } from "../storage/migrations.js";
5
+ import { applyStorageMigrations, ensureStorageSchema, withShortSchemaLockWaits } from "../storage/migrations.js";
5
6
  import { renderStorageIdentifiers, storageMigrationTable, validateStoragePrefix } from "../storage/prefix.js";
6
7
  import { schemaCatalogOf } from "../storage/schema-catalog.js";
7
8
  import { statementBatch } from "../storage/statement-batches.js";
9
+ import { forkInheritedBlobGuard, forkInheritedBlobGuardName } from "./fork-blob-guard.js";
10
+ import { entriesIndexComplete, forkLinksCheck, forkSegmentsTable, forkSessionLink, legacyForkLinksTriggerName, materializedForkLinks, ownDuplicate, ownParentSeq, parentColumns, snapshotEntryCondition, } from "./fork-snapshot-index.js";
8
11
  /**
9
12
  * The key under which a failed rename's error carries the trigger or view that stopped it, once confirmed in the
10
13
  * database (#5622); `WorkspaceCollectionError` names it in its hint. A `Symbol.for` key, shared without an import.
@@ -208,7 +211,7 @@ export const SNAPSHOT_COLLECTION_DELETE_BATCH = 8;
208
211
  export const SNAPSHOT_COLLECTION_SESSION_REFS = 2_048;
209
212
  /**
210
213
  * The most bytes of legacy blobs one write transaction of a collection stamps or moves. A blob stored before blob ages
211
- * has an unknown age, which collection stamps; changing one column rewrites the whole row on SQLite and libSQL, its
214
+ * has an unknown age, which collection stamps; changing one column rewrites the whole row on SQLite, its
212
215
  * blob included, and holds the writer for as long as that takes, so a stamping transaction stops at this many bytes of
213
216
  * blobs. An in-row blob larger than {@link SNAPSHOT_BLOB_CHUNK_BYTES} is moved to chunks regardless of age,
214
217
  * at most this many bytes per transaction. Publishing frees its old value while holding the writer, with time
@@ -222,7 +225,7 @@ export const SNAPSHOT_LEGACY_STAMP_BYTES = 16 * SNAPSHOT_BLOB_CHUNK_BYTES;
222
225
  */
223
226
  export const SNAPSHOT_CHUNK_MOVE_ROWS = 4;
224
227
  /**
225
- * The free space a chunk table's move to the row layout leaves on the file system of a SQLite or libSQL database file
228
+ * The free space a chunk table's move to the row layout leaves on the file system of a SQLite database file
226
229
  * beyond its copy, at least (#5694): the move starts only when the disk has room for the copy, its write-ahead log and
227
230
  * this much more, so other writes keep room on the disk.
228
231
  */
@@ -428,10 +431,6 @@ function statusCondition(d, column) {
428
431
  const payload = column("payload");
429
432
  return `${column("type")} IN (${STATUS_EVENTS}) AND ${whenValidJson(d, payload, `${d.jsonHasType("text", payload, "workflowId")} AND ${d.jsonHasType("text", payload, "status")} AND ${d.jsonType(payload, "completedCheckpoints")} IN ('integer', 'real') AND ${d.jsonType(payload, "pendingPrompts")} IN ('integer', 'real')`)}`;
430
433
  }
431
- function snapshotEntryCondition(d, column) {
432
- const entry = column("entry_json");
433
- return `${d.contains(entry, `'"worktree_snapshot"'`)} AND ${d.jsonText(entry, "type")} = 'worktree_snapshot' AND ${d.jsonHasType("text", entry, "root")} AND ${d.jsonHasType("text", entry, "snapshotId")}`;
434
- }
435
434
  /**
436
435
  * The SQL form of `isDurableWorkflowResumable` for the status payload `payload`, given that the run has a snapshot
437
436
  * reference and so at least one checkpoint: a root run keeps its snapshots while it is failed or blocked, or running or
@@ -499,7 +498,12 @@ function withMarker(trigger, marker) {
499
498
  const [first, ...rest] = trigger.statements;
500
499
  return { ...trigger, statements: [`/* ${marker} */ ${first}`, ...rest] };
501
500
  }
502
- function indexSources(prefix, t, d) {
501
+ /**
502
+ * The tables whose rows reference snapshot blobs, and how each is indexed. `forkSegments` names the sessions' fork
503
+ * segments table when it exists (#6560): the backfill of the session entries then also links an entry whose parent
504
+ * the session inherits, as the session store does when it writes one (`forkLinkWrites`).
505
+ */
506
+ function indexSources(prefix, t, d, forkSegments) {
503
507
  const { events, runs } = renderStorageIdentifiers("journal", { events: "events", runs: "runs" }, prefix);
504
508
  const { entries } = renderStorageIdentifiers("sessions", { entries: "entries" }, prefix);
505
509
  const payload = { column: "r.payload" };
@@ -518,14 +522,19 @@ function indexSources(prefix, t, d) {
518
522
  const parentType = "r.parent_type";
519
523
  const parentId = "r.parent_id";
520
524
  const isSnapshot = snapshotEntryCondition(d, entryRow);
521
- const parentOf = (rows) => `${rows} AS r LEFT JOIN ${t.sessionLinks} AS parent ON parent.session_id = r.session_id AND parent.entry_id = ${parentId} AND ${parentType} = 'text'`;
525
+ // The parent is the first link before the entry with the parent's id, as `forkSessionLink` finds it (#6560).
526
+ const parentOf = (rows) => `${rows} AS r LEFT JOIN ${t.sessionLinks} AS parent ON parent.session_id = r.session_id AND parent.seq = ${ownParentSeq(t.sessionLinks)}`;
522
527
  /**
523
- * Indexes one session entry's link in the session tree. `rows` yields that one entry as `r`; its parent was indexed
524
- * before it.
528
+ * Indexes one session entry's link in the session tree. `rows` yields that one entry as `r`. Only the links before
529
+ * it count: its parent, an earlier entry of the same id, and the entries whose child it is, whose children it adds
530
+ * to, once. A row linked again gets the same anchor and broken mark, so a session's rows linked in seq order end
531
+ * the same whether a save or the index's rebuild linked them, and whatever links after them were there (#6560).
525
532
  */
526
533
  const sessionLink = (rows) => [
527
- `UPDATE ${t.sessionLinks} SET children = children + 1 FROM ${rows} AS r WHERE ${t.sessionLinks}.session_id = r.session_id AND ${t.sessionLinks}.entry_id = ${parentId} AND ${parentType} = 'text' AND NOT EXISTS (SELECT 1 FROM ${t.sessionLinks} AS own WHERE own.session_id = r.session_id AND own.seq = r.seq)`,
528
- d.insertOrIgnore(t.sessionLinks, ["session_id", "seq", "entry_id", "parent_id", "anchor_seq", "children", "broken"], `SELECT r.session_id, r.seq, r.entry_id, CASE WHEN ${parentType} = 'text' THEN ${parentId} END, CASE WHEN ${isSnapshot} THEN r.seq ELSE parent.anchor_seq END, 0, CASE WHEN EXISTS (SELECT 1 FROM ${t.sessionLinks} AS other WHERE other.session_id = r.session_id AND other.entry_id = r.entry_id AND other.seq <> r.seq) THEN 1 WHEN ${parentType} IS NULL OR ${parentType} = 'null' THEN 0 WHEN ${parentType} = 'text' AND parent.entry_id IS NOT NULL THEN parent.broken ELSE 1 END FROM ${parentOf(rows)}`),
534
+ `UPDATE ${t.sessionLinks} SET children = children + 1 FROM ${rows} AS r WHERE ${t.sessionLinks}.session_id = r.session_id AND ${t.sessionLinks}.entry_id = ${parentId} AND ${parentType} = 'text' AND +${t.sessionLinks}.seq < r.seq AND NOT EXISTS (SELECT 1 FROM ${t.sessionLinks} AS own WHERE own.session_id = r.session_id AND own.seq = r.seq)`,
535
+ `INSERT INTO ${t.sessionLinks} (session_id, seq, entry_id, parent_id, anchor_seq, children, broken)
536
+ SELECT r.session_id, r.seq, r.entry_id, CASE WHEN ${parentType} = 'text' THEN ${parentId} END, CASE WHEN ${isSnapshot} THEN r.seq ELSE parent.anchor_seq END, 0, CASE WHEN ${ownDuplicate(t.sessionLinks)} THEN 1 WHEN ${parentType} IS NULL OR ${parentType} = 'null' THEN 0 WHEN parent.entry_id IS NOT NULL THEN parent.broken ELSE 1 END FROM ${parentOf(rows)} WHERE true
537
+ ON CONFLICT (session_id, seq) DO UPDATE SET anchor_seq = excluded.anchor_seq, broken = excluded.broken`,
529
538
  ];
530
539
  /** Indexes a snapshot entry's reference and the blobs of its record; any other entry adds nothing. */
531
540
  const sessionRecord = (rows) => {
@@ -582,11 +591,15 @@ function indexSources(prefix, t, d) {
582
591
  };
583
592
  const entryColumns = ["session_id", "seq", "entry_id", "entry_json"];
584
593
  /** One entry as `r`, with its parent named once, so that each statement parses the entry's JSON for it only once. */
585
- const parentColumns = (json) => `${d.jsonText(json, "parentId")} AS parent_id, ${d.jsonType(json, "parentId")} AS parent_type`;
586
- const triggerEntry = `(SELECT ${entryColumns.map((name) => `NEW.${name} AS ${name}`).join(", ")}, ${parentColumns("NEW.entry_json")})`;
587
- const storedEntry = `(SELECT ${entryColumns.join(", ")}, ${parentColumns("entry_json")} FROM ${entries} WHERE ${d.rowOrder()} = ?)`;
588
- const indexComplete = `(SELECT backfilled_through >= watermark FROM ${t.sources} WHERE source = 'session-entries')`;
594
+ const triggerEntry = `(SELECT ${entryColumns.map((name) => `NEW.${name} AS ${name}`).join(", ")}, ${parentColumns(d, "NEW.entry_json")})`;
595
+ const storedEntry = `(SELECT ${entryColumns.join(", ")}, ${parentColumns(d, "entry_json")} FROM ${entries} WHERE ${d.rowOrder()} = ?)`;
596
+ /** The rows session `?` stores from seq `?` on, as `storedEntry` yields one. */
597
+ const entriesFrom = `(SELECT ${entryColumns.join(", ")}, ${parentColumns(d, "entry_json")} FROM ${entries} WHERE session_id = ? AND seq >= ?)`;
598
+ /** Sets the previous snapshot of the references of `rows` to their parent's anchor: when a pin began stays. */
599
+ const refsAgain = (rows) => `UPDATE ${t.sessionRefs} SET prev_seq = linked.anchor_seq FROM (SELECT r.session_id, r.seq, parent.anchor_seq FROM ${parentOf(rows)} WHERE ${isSnapshot}) AS linked WHERE ${t.sessionRefs}.session_id = linked.session_id AND ${t.sessionRefs}.seq = linked.seq`;
600
+ const indexComplete = entriesIndexComplete(t.sources);
589
601
  const newRowOrder = d.rowOrder("NEW");
602
+ const forkLink = (rows) => forkSegments === undefined ? [] : [forkSessionLink(t.sessionLinks, forkSegments, rows, isSnapshot)];
590
603
  const entriesSource = {
591
604
  name: "session-entries",
592
605
  table: entries,
@@ -612,7 +625,16 @@ function indexSources(prefix, t, d) {
612
625
  ]),
613
626
  ].map((trigger) => withMarker(trigger, ENTRIES_OWN_PROGRESS)),
614
627
  backfill: [],
615
- rowwise: [...sessionLink(storedEntry), ...sessionRecord(storedEntry)],
628
+ rowwise: [...sessionLink(storedEntry), ...forkLink(storedEntry), ...sessionRecord(storedEntry)],
629
+ ...(forkSegments === undefined ? {} : { segments: forkSegments }),
630
+ entriesFrom,
631
+ relink: {
632
+ link: sessionLink(storedEntry)[1],
633
+ ...(forkSegments === undefined ? {} : { fork: forkLink(storedEntry)[0] }),
634
+ // The reference's previous snapshot only: when a pin began stays as its first indexing recorded it.
635
+ refs: refsAgain(storedEntry),
636
+ refsFrom: refsAgain(entriesFrom),
637
+ },
616
638
  // The triggers that index degraded pins (#4922). Older builds install theirs under the same names (#5065).
617
639
  version: "session-entries@degraded-pins",
618
640
  own: ENTRIES_OWN_PROGRESS,
@@ -641,6 +663,176 @@ function indexSources(prefix, t, d) {
641
663
  });
642
664
  return [eventsSource, runsSource, entriesSource, workSource, rootSource];
643
665
  }
666
+ /** The session entries' {@link EntryLinking} of `source`, with the dialect and links table it runs on. */
667
+ function entryLinking(source, dialect, links) {
668
+ return {
669
+ dialect,
670
+ links,
671
+ entries: source.table,
672
+ segments: source.segments,
673
+ statements: source.rowwise,
674
+ relink: source.relink,
675
+ };
676
+ }
677
+ /**
678
+ * Runs `statements` in order, each sent without waiting for the answer to the one before: a database runs a
679
+ * connection's calls in the order they are made, and a pipelined connection sends them together.
680
+ */
681
+ async function runInOrder(executor, statements) {
682
+ await Promise.all(statements.map(({ sql, params }) => executor.run(sql, ...params)));
683
+ }
684
+ /**
685
+ * Links the rows session `sessionId` stores from seq `fromSeq` on again, in seq order, each behind the rows before it
686
+ * (#6560), then counts their children again: an entry's children are the rows after it in the session whose parent
687
+ * has its id. A materialization runs it once it copied rows in below the rows a fork appended, and the index's rebuild
688
+ * when it meets a row stored before rows below it: both link every row as a save in seq order did.
689
+ */
690
+ async function relinkSessionEntries(executor, linking, sessionId, fromSeq) {
691
+ const { dialect, links, entries, segments, statements, relink } = linking;
692
+ const rows = await executor.all(`SELECT ${dialect.rowOrder("e")} AS id,
693
+ CASE WHEN EXISTS (SELECT 1 FROM ${links} AS l WHERE l.session_id = e.session_id AND l.seq = e.seq) THEN 1 ELSE 0 END AS linked,
694
+ CASE WHEN ${dialect.contains("e.entry_json", `'"worktree_snapshot"'`)} THEN 1 ELSE 0 END AS snapshot
695
+ FROM ${entries} AS e WHERE e.session_id = ? AND e.seq >= ? ORDER BY e.seq`, sessionId, fromSeq);
696
+ const forked = segments !== undefined &&
697
+ relink.fork !== undefined &&
698
+ (await executor.get(`SELECT 1 AS found FROM ${segments} WHERE session_id = ? LIMIT 1`, sessionId)) !== undefined;
699
+ // A row not linked yet gets every statement; one linked already only those that write its link and reference again.
700
+ const again = (snapshot) => [
701
+ relink.link,
702
+ ...(forked ? [relink.fork] : []),
703
+ ...(snapshot ? [relink.refs] : []),
704
+ ];
705
+ await runInOrder(executor, rows.flatMap(({ id, linked, snapshot }) => (Number(linked) === 1 ? again(Number(snapshot) === 1) : statements).map((sql) => ({ sql, params: [id] }))));
706
+ const linked = await executor.all(`SELECT seq, entry_id, parent_id, children FROM ${links} WHERE session_id = ? AND seq >= ? ORDER BY seq DESC`, sessionId, fromSeq);
707
+ const later = new Map();
708
+ const counts = [];
709
+ for (const link of linked) {
710
+ const children = later.get(link.entry_id) ?? 0;
711
+ if (Number(link.children) !== children)
712
+ counts.push({
713
+ sql: `UPDATE ${links} SET children = ? WHERE session_id = ? AND seq = ?`,
714
+ params: [children, sessionId, Number(link.seq)],
715
+ });
716
+ if (link.parent_id !== null)
717
+ later.set(link.parent_id, (later.get(link.parent_id) ?? 0) + 1);
718
+ }
719
+ await runInOrder(executor, counts);
720
+ }
721
+ /**
722
+ * Links, in seq order, every row session `sessionId` stores up to seq `seq` that is not linked yet, behind the rows of
723
+ * its sources that its segments before `seq` name, which are linked first, the same way. Where the session has a row
724
+ * linked already after the first row this links, the rows after it are linked again with it (see
725
+ * {@link relinkSessionEntries}). A session linked this way has every row before a linked row linked, so the link of a
726
+ * segment's last row tells that its source is linked through it.
727
+ */
728
+ async function linkThrough(executor, linking, sessionId, seq) {
729
+ const { dialect, links, entries, segments, statements } = linking;
730
+ const sources = async (through) => {
731
+ if (segments === undefined)
732
+ return;
733
+ const pending = await executor.all(`SELECT seg.source_id, seg.to_seq FROM ${segments} AS seg WHERE seg.session_id = ? AND seg.base_seq < ? AND NOT EXISTS (SELECT 1 FROM ${links} AS l WHERE l.session_id = seg.source_id AND l.seq = seg.to_seq) ORDER BY seg.base_seq`, sessionId, through);
734
+ for (const segment of pending)
735
+ await linkThrough(executor, linking, segment.source_id, Number(segment.to_seq));
736
+ };
737
+ await sources(seq);
738
+ const first = await executor.get(`SELECT f.seq, CASE WHEN EXISTS (SELECT 1 FROM ${links} AS l WHERE l.session_id = ? AND l.seq > f.seq) THEN 1 ELSE 0 END AS later
739
+ FROM (SELECT min(e.seq) AS seq FROM ${entries} AS e WHERE e.session_id = ? AND e.seq <= ? AND NOT EXISTS (SELECT 1 FROM ${links} AS l WHERE l.session_id = e.session_id AND l.seq = e.seq)) AS f`, sessionId, sessionId, seq);
740
+ if (first?.seq === null || first?.seq === undefined)
741
+ return;
742
+ if (Number(first.later) === 1) {
743
+ // The rows after it were linked before it: they are linked again, behind it.
744
+ await relinkFrom(executor, linking, sessionId, Number(first.seq));
745
+ return;
746
+ }
747
+ const rows = await executor.all(`SELECT ${dialect.rowOrder()} AS id FROM ${entries} WHERE session_id = ? AND seq >= ? AND seq <= ? ORDER BY seq`, sessionId, Number(first.seq), seq);
748
+ await runInOrder(executor, rows.flatMap(({ id }) => statements.map((sql) => ({ sql, params: [id] }))));
749
+ }
750
+ /**
751
+ * Links the rows session `sessionId` stores from seq `fromSeq` on again, behind the rows of the sources its segments
752
+ * name, and then the rows of every session that reads them through a segment and has a row linked after them: such a
753
+ * row took its parent's link, or its anchor, from the rows linked again (#6560).
754
+ */
755
+ async function relinkFrom(executor, linking, sessionId, fromSeq) {
756
+ const { links, segments } = linking;
757
+ if (segments !== undefined) {
758
+ const pending = await executor.all(`SELECT seg.source_id, seg.to_seq FROM ${segments} AS seg WHERE seg.session_id = ? AND NOT EXISTS (SELECT 1 FROM ${links} AS l WHERE l.session_id = seg.source_id AND l.seq = seg.to_seq) ORDER BY seg.base_seq`, sessionId);
759
+ for (const segment of pending)
760
+ await linkThrough(executor, linking, segment.source_id, Number(segment.to_seq));
761
+ }
762
+ await relinkSessionEntries(executor, linking, sessionId, fromSeq);
763
+ if (segments === undefined)
764
+ return;
765
+ const readers = await executor.all(`SELECT seg.session_id, min(seg.base_seq + 1 + CASE WHEN seg.from_seq < ? THEN ? - seg.from_seq ELSE 0 END) AS first
766
+ FROM ${segments} AS seg WHERE seg.source_id = ? AND seg.to_seq >= ? GROUP BY seg.session_id ORDER BY seg.session_id`, fromSeq, fromSeq, sessionId, fromSeq);
767
+ for (const reader of readers) {
768
+ const linked = await executor.get(`SELECT 1 AS found FROM ${links} WHERE session_id = ? AND seq >= ? LIMIT 1`, reader.session_id, Number(reader.first));
769
+ if (linked !== undefined)
770
+ await relinkFrom(executor, linking, reader.session_id, Number(reader.first));
771
+ }
772
+ }
773
+ /**
774
+ * Indexes the stored entry at row order `id`, as the index's backfill meets it. The backfill goes in row order, but a
775
+ * fork that copied in the rows it read stores them after the entries it appended, and a fork moved onto another
776
+ * session's copy reads rows stored after its own (#6560): a row with a row before it, of its session or of a source
777
+ * its segments name, not linked yet, or with a row after it linked already, is linked by {@link linkThrough}, so every
778
+ * row is linked behind the rows before it in its view, as a save links it.
779
+ */
780
+ async function linkStoredEntry(executor, linking, id) {
781
+ const { dialect, links, entries, segments, statements } = linking;
782
+ const pendingSource = segments === undefined
783
+ ? "0"
784
+ : `CASE WHEN EXISTS (SELECT 1 FROM ${segments} AS seg WHERE seg.session_id = e.session_id AND seg.base_seq < e.seq AND NOT EXISTS (SELECT 1 FROM ${links} AS l WHERE l.session_id = seg.source_id AND l.seq = seg.to_seq)) THEN 1 ELSE 0 END`;
785
+ const row = await executor.get(`SELECT e.session_id, e.seq,
786
+ CASE WHEN EXISTS (SELECT 1 FROM ${links} AS l WHERE l.session_id = e.session_id AND l.seq = e.seq) THEN 1 ELSE 0 END AS linked,
787
+ CASE WHEN EXISTS (SELECT 1 FROM ${links} AS l WHERE l.session_id = e.session_id AND l.seq > e.seq) THEN 1 ELSE 0 END AS later,
788
+ (SELECT max(p.seq) FROM ${entries} AS p WHERE p.session_id = e.session_id AND p.seq < e.seq) AS previous,
789
+ (SELECT max(l.seq) FROM ${links} AS l WHERE l.session_id = e.session_id AND l.seq < e.seq) AS linked_before,
790
+ ${pendingSource} AS pending_source
791
+ FROM ${entries} AS e WHERE ${dialect.rowOrder("e")} = ?`, id);
792
+ const inOrder = row === undefined ||
793
+ Number(row.linked) === 1 ||
794
+ (Number(row.later) === 0 &&
795
+ Number(row.pending_source) === 0 &&
796
+ (row.previous === null || (row.linked_before !== null && Number(row.linked_before) === Number(row.previous))));
797
+ if (inOrder)
798
+ for (const sql of statements)
799
+ await executor.run(sql, id);
800
+ else
801
+ await linkThrough(executor, linking, row.session_id, Number(row.seq));
802
+ }
803
+ /**
804
+ * The {@link SessionEntryLinks} of a session store under `prefix` whose fork segments table is `forkSegments` (#6560).
805
+ * Until the index's backfill of the session entries is done, which links the rows in seq order itself, `settle` only
806
+ * writes the segments.
807
+ */
808
+ export function sessionEntryLinks(prefix, dialect, forkSegments) {
809
+ const t = snapshotIndexTables(prefix);
810
+ const source = indexSources(prefix, t, dialect, forkSegments).find((source) => source.name === "session-entries");
811
+ const linking = entryLinking(source, dialect, t.sessionLinks);
812
+ const complete = entriesIndexComplete(t.sources);
813
+ // The rows to check, from their links, which name each entry's id and its parent's, so no entry's JSON is parsed. A
814
+ // link without a parent is taken for a root: one whose parent is a value of another type, which no store writes, is
815
+ // linked broken, so the check finds it and the session is linked again row by row, from its JSON. A snapshot entry
816
+ // is its own anchor, as no other entry is.
817
+ const linked = `(SELECT l.session_id, l.seq, l.entry_id, l.parent_id, CASE WHEN l.parent_id IS NOT NULL THEN 'text' ELSE 'null' END AS parent_type, l.anchor_seq AS own_anchor FROM ${t.sessionLinks} AS l WHERE l.session_id = ? AND l.seq >= ?)`;
818
+ const check = forkLinksCheck({ links: t.sessionLinks, segments: forkSegments, refs: t.sessionRefs }, linked, "r.own_anchor = r.seq", complete);
819
+ return {
820
+ materialized: materializedForkLinks(t.sessionLinks, forkSegments, complete, dialect.types.int),
821
+ async settle(executor, sessionId, fromSeq, before) {
822
+ const [, verdict] = await Promise.all([
823
+ runInOrder(executor, before),
824
+ executor.get(check, sessionId, fromSeq, sessionId, fromSeq, sessionId, fromSeq),
825
+ ]);
826
+ if (verdict === undefined)
827
+ return;
828
+ const children = Number(verdict.children) === 1;
829
+ if (verdict.seq !== null || children)
830
+ await relinkFrom(executor, linking, sessionId, children ? fromSeq : Number(verdict.seq));
831
+ if (verdict.seq !== null || children || Number(verdict.refs) === 1)
832
+ await executor.run(linking.relink.refsFrom, sessionId, fromSeq);
833
+ },
834
+ };
835
+ }
644
836
  /**
645
837
  * Creates a chunk table named `table` unless it exists. An ordinary table, whose primary key is an index of its own:
646
838
  * a lookup reads that small index, then only the row it finds. A `WITHOUT ROWID` table, as earlier releases created,
@@ -693,7 +885,9 @@ async function addBlobChunks(transaction, t, dialect) {
693
885
  * Creates the blob table and the tables of its reference index that are missing, reading what each step needs
694
886
  * together, so on a SQLite file connection the setup waits for the connection's thread three times.
695
887
  */
696
- async function createSnapshotIndexTables(transaction, t, prefix, dialect) {
888
+ async function createSnapshotIndexTables(transaction, t, prefix, dialect,
889
+ /** Statements that run with the tables' own, in the same request: such as a ledger record of what they create. */
890
+ after = []) {
697
891
  const { int, text, blob } = dialect.types;
698
892
  const strict = dialect.tableOptions;
699
893
  const keyed = dialect.withoutRowidTableOptions;
@@ -711,7 +905,7 @@ async function createSnapshotIndexTables(transaction, t, prefix, dialect) {
711
905
  CREATE TABLE IF NOT EXISTS ${t.sessionRefs} (session_id ${text} NOT NULL, seq ${int} NOT NULL, root ${text} NOT NULL, snapshot_id ${text} NOT NULL, prev_seq ${int}, restore_from ${text}, restore_to ${text}, degraded_from ${text}, degraded_since ${int}, PRIMARY KEY (session_id, seq))${keyed};
712
906
  CREATE TABLE IF NOT EXISTS ${t.sessionLinks} (session_id ${text} NOT NULL, seq ${int} NOT NULL, entry_id ${text} NOT NULL, parent_id ${text}, anchor_seq ${int}, children ${int} NOT NULL, broken ${int} NOT NULL, PRIMARY KEY (session_id, seq))${strict};
713
907
  CREATE INDEX IF NOT EXISTS ${t.sessionLinks}_entry ON ${t.sessionLinks} (session_id, entry_id);
714
- CREATE INDEX IF NOT EXISTS ${t.sessionLinks}_leaves ON ${t.sessionLinks} (session_id, anchor_seq) WHERE children = 0 AND anchor_seq IS NOT NULL;
908
+ ${sessionLinksLeafIndex(t, dialect)};
715
909
  CREATE INDEX IF NOT EXISTS ${t.sessionLinks}_broken ON ${t.sessionLinks} (session_id) WHERE broken = 1;
716
910
  CREATE TABLE IF NOT EXISTS ${t.sessionRecords} (session_id ${text} NOT NULL, seq ${int} NOT NULL, snapshot_id ${text} NOT NULL, hash ${text} NOT NULL, PRIMARY KEY (session_id, seq, hash))${keyed};
717
911
  CREATE INDEX IF NOT EXISTS ${t.sessionRecords}_hash ON ${t.sessionRecords} (hash);
@@ -720,6 +914,7 @@ async function createSnapshotIndexTables(transaction, t, prefix, dialect) {
720
914
  CREATE TABLE IF NOT EXISTS ${t.collection} (id ${int} PRIMARY KEY CHECK (id = 1), claimed_at ${int}, holder ${text}, finished_at ${int}, deleted ${int}, error_code ${text})${strict};
721
915
  INSERT INTO ${t.collection} (id) VALUES (1) ON CONFLICT DO NOTHING;
722
916
  CREATE TABLE IF NOT EXISTS ${t.sources} (source ${text} PRIMARY KEY, watermark ${int} NOT NULL, backfilled_through ${int} NOT NULL)${keyed};
917
+ ${after.map((statement) => `${statement};`).join("\n")}
723
918
  `,
724
919
  chunkTableDefinition(t.blobChunks, dialect),
725
920
  ], [...blobChunkProbes(transaction, t, dialect), ...sessionRefColumnProbes(transaction, t, dialect)]);
@@ -739,6 +934,124 @@ function blobMaintenanceIndexes(t) {
739
934
  async function addBlobMaintenanceIndexes(transaction, t) {
740
935
  await statementBatch(transaction, blobMaintenanceIndexes(t), []);
741
936
  }
937
+ /**
938
+ * The ledger step, `schema:snapshot-links-hot`, after which the session links table has no index that names
939
+ * `children` on PostgreSQL ({@link hotSessionLinks}).
940
+ */
941
+ const SESSION_LINKS_HOT_DOMAIN = "snapshot-links-hot";
942
+ function sessionLinksHotSchema(prefix) {
943
+ return { ledger: storageMigrationTable(prefix), domain: SESSION_LINKS_HOT_DOMAIN, revision: 1 };
944
+ }
945
+ /**
946
+ * The index the queries for the session tree's leaves read: on PostgreSQL every link with an anchor, whose leaves they
947
+ * pick by `children = 0` ({@link hotSessionLinks}); elsewhere only the leaves with an anchor.
948
+ */
949
+ function sessionLinksLeafIndex(t, dialect) {
950
+ return dialect.name === "postgres"
951
+ ? `CREATE INDEX IF NOT EXISTS ${t.sessionLinks}_anchored ON ${t.sessionLinks} (session_id, anchor_seq) WHERE anchor_seq IS NOT NULL`
952
+ : `CREATE INDEX IF NOT EXISTS ${t.sessionLinks}_leaves ON ${t.sessionLinks} (session_id, anchor_seq) WHERE children = 0 AND anchor_seq IS NOT NULL`;
953
+ }
954
+ /** The ledger record of {@link hotSessionLinks}, for a database whose links table this transaction created with it. */
955
+ function hotSessionLinksRecord(prefix, dialect) {
956
+ const { ledger, domain, revision } = sessionLinksHotSchema(prefix);
957
+ return `INSERT INTO ${ledger} (domain, version, applied_at) VALUES ('schema:${domain}', ${revision}, ${dialect.nowMs}) ON CONFLICT DO NOTHING`;
958
+ }
959
+ /**
960
+ * Makes the update each append writes to its parent's session link a HOT update on PostgreSQL: one that stays on its
961
+ * page and writes no index entry. Each append raises its parent link's `children`, and PostgreSQL updates a row in
962
+ * place only when no index names a changed column, its condition included, which `_leaves` (`WHERE children = 0`)
963
+ * did. So every append wrote the parent link's new version into each of the table's indexes. `_anchored` indexes the
964
+ * same rows without that condition, and the queries for leaves, which only collection runs, check `children = 0` on
965
+ * the rows it finds. Older builds read and write the table as before, and none of them creates `_leaves` again: on
966
+ * PostgreSQL the step that creates it runs once per database. Recorded in the ledger, so it runs once. SQLite keeps
967
+ * `_leaves`, as it updates rows in place whatever their indexes.
968
+ */
969
+ async function hotSessionLinks(transaction, t, prefix, dialect) {
970
+ await ensureStorageSchema(transaction, dialect, sessionLinksHotSchema(prefix), async () => {
971
+ await transaction.exec(sessionLinksLeafIndex(t, dialect));
972
+ await transaction.exec(`DROP INDEX IF EXISTS ${t.sessionLinks}_leaves`);
973
+ });
974
+ }
975
+ /** This process's check of {@link hotSessionLinks} for each database, ledger and links table, while it holds. */
976
+ const hotSessionLinksChecks = new Map();
977
+ /**
978
+ * Runs {@link hotSessionLinks} on a PostgreSQL database whose ledger lacks it, in a transaction of its own. Nothing runs
979
+ * where the catalog the open read records it, or where this role does not own the links table: a runtime role without
980
+ * DDL opens as before, and `atomic storage migrate`, run as the owner, makes the change. A role that does not own the
981
+ * table finds that out once per process, as for the fillfactor steps.
982
+ */
983
+ async function ensureHotSessionLinks(database, t, prefix) {
984
+ const dialect = dialectOf(database);
985
+ if (dialect.name !== "postgres" || database.readOnly === true)
986
+ return;
987
+ const schema = sessionLinksHotSchema(prefix);
988
+ if (await storageSchemaCurrent(database, schema))
989
+ return;
990
+ const identity = database.databaseIdentity?.();
991
+ if (identity === undefined) {
992
+ await checkHotSessionLinks(database, t, prefix);
993
+ return;
994
+ }
995
+ const key = JSON.stringify([identity, schema.ledger, t.sessionLinks]);
996
+ let check = hotSessionLinksChecks.get(key);
997
+ if (check === undefined) {
998
+ const made = checkHotSessionLinks(database, t, prefix);
999
+ check = made;
1000
+ hotSessionLinksChecks.set(key, made);
1001
+ const forget = () => {
1002
+ if (hotSessionLinksChecks.get(key) === made)
1003
+ hotSessionLinksChecks.delete(key);
1004
+ };
1005
+ made.then((settled) => {
1006
+ if (!settled)
1007
+ forget();
1008
+ }, forget);
1009
+ }
1010
+ await check;
1011
+ }
1012
+ /**
1013
+ * The largest links table, in bytes, an open builds {@link hotSessionLinks}'s index for in its own transaction, which
1014
+ * holds the table's writes for the build: about 150,000 links, a fraction of a second. A larger one is left to `atomic
1015
+ * storage migrate`, which builds the index without holding them ({@link SqlSnapshotBlobStore.buildHotSessionLinksIndex}).
1016
+ */
1017
+ const HOT_SESSION_LINKS_OPEN_BUILD_BYTES = 16 * 1024 * 1024;
1018
+ /** How often {@link SqlSnapshotBlobStore.buildHotSessionLinksIndex} looks again at an index build another process runs. */
1019
+ const HOT_SESSION_LINKS_BUILD_POLL_MS = 500;
1020
+ /** The links table's owner, size and `_anchored` index, in one read; `undefined` when the table does not exist. */
1021
+ async function sessionLinksState(database, t, dialect) {
1022
+ const row = await database.get(`SELECT pg_catalog.pg_has_role(current_user, c.relowner, 'USAGE') AS owned, pg_catalog.pg_relation_size(c.oid) AS bytes,
1023
+ (SELECT x.indisvalid FROM pg_catalog.pg_index x JOIN pg_catalog.pg_class i ON i.oid = x.indexrelid
1024
+ WHERE x.indrelid = c.oid AND i.relname = ?) AS anchored,
1025
+ EXISTS (SELECT 1 FROM pg_catalog.pg_stat_progress_create_index p WHERE p.relid = c.oid) AS building
1026
+ FROM pg_catalog.pg_class c WHERE c.relnamespace = current_schema()::regnamespace AND c.relname = ?`, dialect.identifier(`${t.sessionLinks}_anchored`), dialect.identifier(t.sessionLinks));
1027
+ if (row === undefined)
1028
+ return undefined;
1029
+ const yes = (value) => value === true || Number(value) === 1;
1030
+ return {
1031
+ owned: yes(row.owned),
1032
+ bytes: Number(row.bytes),
1033
+ anchored: row.anchored === null ? undefined : yes(row.anchored),
1034
+ building: yes(row.building),
1035
+ };
1036
+ }
1037
+ /**
1038
+ * Runs {@link hotSessionLinks} where this role owns a small links table; true when this process need not check again.
1039
+ * A large table, or one whose `_anchored` index a build of `atomic storage migrate` left unfinished or is making now,
1040
+ * is left to `atomic storage migrate`.
1041
+ */
1042
+ async function checkHotSessionLinks(database, t, prefix) {
1043
+ const dialect = dialectOf(database);
1044
+ const found = await sessionLinksState(database, t, dialect);
1045
+ if (found === undefined)
1046
+ return false;
1047
+ if (!found.owned || found.bytes > HOT_SESSION_LINKS_OPEN_BUILD_BYTES || found.anchored === false || found.building)
1048
+ return true;
1049
+ await database.transaction((transaction) => hotSessionLinks(transaction, t, prefix, dialect), {
1050
+ retryTransientFailures: true,
1051
+ concurrency: { kind: "serial", domain: sessionLinksHotSchema(prefix).ledger },
1052
+ });
1053
+ return false;
1054
+ }
742
1055
  /** The columns of {@link SnapshotIndexTables.sessionRefs} that later builds added, with their types. */
743
1056
  const SESSION_REF_COLUMNS = ["prev_seq", "restore_from", "restore_to", "degraded_from", "degraded_since"];
744
1057
  /** Whether the session references have each of {@link SESSION_REF_COLUMNS}, in its order. */
@@ -793,8 +1106,12 @@ async function installSource(transaction, dialect, t, source, reset) {
793
1106
  ? []
794
1107
  : [
795
1108
  ...(source.reset ?? []).map((sql) => ({ sql, params: [] })),
796
- // Triggers of these names that an older build installed are replaced, not kept (#5065).
797
- ...source.triggers.map((trigger) => dialect.dropTrigger(trigger.name, trigger.table)),
1109
+ // Triggers of these names that an older build installed are replaced, not kept (#5065): dropped in one
1110
+ // script, as they are created, so a source with more triggers costs a driver no more calls.
1111
+ source.triggers.length > 0 &&
1112
+ source.triggers
1113
+ .map((trigger) => `${dialect.dropTrigger(trigger.name, trigger.table)};`)
1114
+ .join("\n"),
798
1115
  ]),
799
1116
  source.triggers.map((trigger) => dialect.renderTrigger(trigger)).join("\n"),
800
1117
  {
@@ -824,7 +1141,7 @@ async function installSource(transaction, dialect, t, source, reset) {
824
1141
  }
825
1142
  /**
826
1143
  * Whether this build writes `source`'s {@link IndexSource.version} row only once its own backfill of the source is done:
827
- * on SQLite and libSQL, which builds before 0.9.88 also open (#5558).
1144
+ * on SQLite, which builds before 0.9.88 also open (#5558).
828
1145
  */
829
1146
  function withholdsVersion(dialect, source) {
830
1147
  return dialect.name === "sqlite" && source.version !== undefined && source.own !== undefined;
@@ -846,10 +1163,23 @@ async function installMissingSources(transaction, t, prefix, dialect, reset) {
846
1163
  await installSource(transaction, dialect, t, source, reset);
847
1164
  }
848
1165
  }
849
- /** Which referencing tables exist, whether each has all its triggers and a source row, and whether its backfill is done. */
850
- async function readSourceStates(executor, dialect, t, sources, listRetired = false) {
851
- const names = sources.flatMap((source) => [source.table, ...source.triggers.map((trigger) => trigger.name)]);
852
- // Builds before 0.9.88 open SQLite and libSQL databases only, so only there can a trigger of this build's name be
1166
+ /** The names of `sources`' tables and triggers, whose presence `readSourceStates` reads. */
1167
+ function sourceObjectNames(sources) {
1168
+ return sources.flatMap((source) => [source.table, ...source.triggers.map((trigger) => trigger.name)]);
1169
+ }
1170
+ /** The read of every source's progress rows. */
1171
+ function sourceProgressRead(t) {
1172
+ return { sql: `SELECT source, watermark, backfilled_through FROM ${t.sources}`, params: [] };
1173
+ }
1174
+ /**
1175
+ * Which referencing tables exist, whether each has all its triggers and a source row, and whether its backfill is done.
1176
+ * `present`, when given, holds every table and trigger of `sources`, as an open's catalog found them: the objects are
1177
+ * not read then (#6560).
1178
+ */
1179
+ async function readSourceStates(executor, dialect, t, sources, listRetired = false, present, also) {
1180
+ // `also` asks, in the same statement, which of other objects exist, as `also.found` tells.
1181
+ const names = [...sourceObjectNames(sources), ...(also?.names ?? [])];
1182
+ // Builds before 0.9.88 open SQLite databases only, so only there can a trigger of this build's name be
853
1183
  // one that indexes less.
854
1184
  const sqlite = dialect.name === "sqlite";
855
1185
  const signatures = sqlite ? sources.flatMap((source) => source.signature ?? []) : [];
@@ -865,12 +1195,18 @@ async function readSourceStates(executor, dialect, t, sources, listRetired = fal
865
1195
  sql: `SELECT name, ${holds(signatures)} AS signed, ${holds(markers)} AS marked FROM sqlite_schema WHERE name IN (${names.map(() => "?").join(", ")})`,
866
1196
  params: [...signatures, ...markers].flatMap((check) => [check.trigger, check.text]).concat(names),
867
1197
  };
1198
+ const progressRead = sourceProgressRead(t);
868
1199
  // Read together: the progress rows do not depend on the objects.
869
1200
  const [objectRows, progressRows] = await statementBatch(executor, [], [
870
- () => executor.all(objects.sql, ...objects.params),
871
- () => executor.all(`SELECT source, watermark, backfilled_through FROM ${t.sources}`),
1201
+ () => present === undefined
1202
+ ? executor.all(objects.sql, ...objects.params)
1203
+ : Promise.resolve(names.filter((name) => present.has(name)).map((name) => ({ name }))),
1204
+ () => executor.all(progressRead.sql, ...progressRead.params),
872
1205
  ]);
873
- const present = new Set(objectRows.map((row) => row.name));
1206
+ const found = new Set(objectRows.map((row) => row.name));
1207
+ for (const name of also?.names ?? [])
1208
+ if (found.has(name))
1209
+ also?.found.add(name);
874
1210
  // Whether each checked trigger's SQL holds this build's text; every other object reads null.
875
1211
  const checked = (column) => new Map(objectRows
876
1212
  .filter((row) => row[column] !== null && row[column] !== undefined)
@@ -889,7 +1225,7 @@ async function readSourceStates(executor, dialect, t, sources, listRetired = fal
889
1225
  return [row.source, row];
890
1226
  }));
891
1227
  return sources
892
- .filter((source) => present.has(source.table))
1228
+ .filter((source) => found.has(source.table))
893
1229
  .map((source) => {
894
1230
  const row = progress.get(source.name);
895
1231
  const version = source.version === undefined ? undefined : progress.get(source.version);
@@ -903,7 +1239,7 @@ async function readSourceStates(executor, dialect, t, sources, listRetired = fal
903
1239
  // Every trigger the source has is this build's. One a build before 0.9.88 installed again after it went
904
1240
  // missing is not, even when its SQL is the same in every build otherwise (#5558).
905
1241
  const mine = source.marker !== undefined &&
906
- source.triggers.every((trigger) => !present.has(trigger.name) || marked.get(trigger.name) === true);
1242
+ source.triggers.every((trigger) => !found.has(trigger.name) || marked.get(trigger.name) === true);
907
1243
  let foreign;
908
1244
  // Whether the backfill is done for this build, besides the source's own progress row.
909
1245
  let trusted;
@@ -926,7 +1262,7 @@ async function readSourceStates(executor, dialect, t, sources, listRetired = fal
926
1262
  const installed = row !== undefined &&
927
1263
  !foreign &&
928
1264
  Number(row.watermark) >= 0 &&
929
- source.triggers.every((trigger) => present.has(trigger.name));
1265
+ source.triggers.every((trigger) => found.has(trigger.name));
930
1266
  const backfilled = row !== undefined &&
931
1267
  !foreign &&
932
1268
  trusted &&
@@ -953,12 +1289,15 @@ export class SqlSnapshotBlobStore {
953
1289
  tables;
954
1290
  sources;
955
1291
  dialect;
1292
+ /** The sessions' fork segments table (#6560), which exists once shared-history forks are on. */
1293
+ forkSegments;
956
1294
  table;
957
- constructor(database, dialect, tables, sources) {
1295
+ constructor(database, dialect, tables, sources, forkSegments = forkSegmentsTable()) {
958
1296
  this.database = database;
959
1297
  this.dialect = dialect;
960
1298
  this.tables = tables;
961
1299
  this.sources = sources;
1300
+ this.forkSegments = forkSegments;
962
1301
  this.table = tables.blobs;
963
1302
  }
964
1303
  /** Which table this store collects, for telling stores of one database and prefix apart from others. */
@@ -984,9 +1323,18 @@ export class SqlSnapshotBlobStore {
984
1323
  ...columns.map(([table, column]) => dialect.columnExists(table, column)),
985
1324
  dialect.schemaObjects(triggers),
986
1325
  ];
1326
+ // One catalog read answers the schema questions where an open read it (#6560): always on Postgres, at the first
1327
+ // question on SQLite.
1328
+ const catalog = await schemaCatalogOf(database);
1329
+ // Whether shared-history forks are on (#6560), from that catalog or asked beside the probes.
1330
+ const segments = forkSegmentsTable(prefix);
1331
+ const segmentsProbe = dialect.tableExists(segments);
1332
+ const shared = catalog !== undefined
1333
+ ? Promise.resolve(catalog.hasTable(segments))
1334
+ : database.get(segmentsProbe.sql, ...segmentsProbe.params).then((row) => row !== undefined);
1335
+ shared.catch(() => { });
987
1336
  // A versioned database checks its ledger whatever the probes find, so it does not ask them. Elsewhere the catalog
988
- // an open read answers them all, in one read instead of a read each (#6560).
989
- const catalog = dialect.versionedMigrations ? undefined : await schemaCatalogOf(database);
1337
+ // answers them all, in one read instead of a read each.
990
1338
  const current = dialect.versionedMigrations
991
1339
  ? false
992
1340
  : catalog !== undefined
@@ -996,9 +1344,27 @@ export class SqlSnapshotBlobStore {
996
1344
  : (await Promise.all(probes.map((probe) => database.get(probe.sql, ...probe.params)))).every((row) => row !== undefined);
997
1345
  // A versioned database always checks its ledger: a newer schema with the same tables is refused, and a step it
998
1346
  // lacks, such as the index triggers, runs even when every table exists.
1347
+ // Whether this open created the tables on PostgreSQL, and with them the links indexes of {@link hotSessionLinks}.
1348
+ let linksHot = false;
999
1349
  if (!current) {
1000
- await applyStorageMigrations(database, SNAPSHOT_BLOB_DOMAIN, [
1001
- { version: 1, up: (transaction, dialect) => createSnapshotIndexTables(transaction, t, prefix, dialect) },
1350
+ const migrated = await applyStorageMigrations(database, SNAPSHOT_BLOB_DOMAIN, [
1351
+ {
1352
+ version: 1,
1353
+ up: async (transaction, dialect) => {
1354
+ // On PostgreSQL the tables come with the links index of {@link hotSessionLinks}, without one an
1355
+ // earlier build made, recorded in the ledger in the same request: a new database takes no extra
1356
+ // round trip for it. Where forks share history, as a new database's do from its first open, the
1357
+ // guard that keeps what they inherit comes with them in that request too (fork-blob-guard.ts).
1358
+ const hot = dialect.name === "postgres";
1359
+ await createSnapshotIndexTables(transaction, t, prefix, dialect, [
1360
+ ...(hot
1361
+ ? [`DROP INDEX IF EXISTS ${t.sessionLinks}_leaves`, hotSessionLinksRecord(prefix, dialect)]
1362
+ : []),
1363
+ ...((await shared) ? [forkInheritedBlobGuard(dialect, t, segments).replace(/;\s*$/, "")] : []),
1364
+ ]);
1365
+ linksHot = hot;
1366
+ },
1367
+ },
1002
1368
  // Where a ledger records the steps, it records the index triggers too, installed under the migration lock.
1003
1369
  // Without one, installIndex below installs each source in a transaction of its own, as it always has.
1004
1370
  ...(dialect.versionedMigrations
@@ -1027,11 +1393,64 @@ export class SqlSnapshotBlobStore {
1027
1393
  ]
1028
1394
  : []),
1029
1395
  ], { table: storageMigrationTable(prefix) });
1396
+ // The session store's open, which asks the catalog for the guard next, finds it without reading the schema again.
1397
+ if (migrated.applied.includes(1) && (await shared))
1398
+ noteStorageSchemaTables(database, [forkInheritedBlobGuardName(t.blobs)]);
1030
1399
  }
1031
- const store = new SqlSnapshotBlobStore(database, dialect, t, indexSources(prefix, t, dialect));
1032
- await store.installIndex();
1400
+ if (!linksHot)
1401
+ await ensureHotSessionLinks(database, t, prefix);
1402
+ const store = new SqlSnapshotBlobStore(database, dialect, t, indexSources(prefix, t, dialect, (await shared) ? segments : undefined), segments);
1403
+ await store.installIndex(undefined, false, await schemaCatalogOf(database));
1033
1404
  return store;
1034
1405
  }
1406
+ /**
1407
+ * Gives a PostgreSQL database's session links the index of {@link hotSessionLinks} without holding the table's writes,
1408
+ * as `atomic storage migrate` does where an open would not ({@link HOT_SESSION_LINKS_OPEN_BUILD_BYTES}). Each step
1409
+ * runs on its own, outside a transaction: `CREATE INDEX CONCURRENTLY` builds `_anchored`, `DROP INDEX CONCURRENTLY`
1410
+ * removes `_leaves`, and only then does the ledger record the step. A build that stopped part way, which leaves an
1411
+ * invalid `_anchored`, is dropped and made again; one another process is making is waited for. Nothing runs where the
1412
+ * ledger records the step, where the table does not exist yet (its first open creates it with the index), or where
1413
+ * this role does not own it. `database` should allow a statement as long as the build takes.
1414
+ */
1415
+ static async buildHotSessionLinksIndex(database, prefix = "") {
1416
+ const dialect = dialectOf(database);
1417
+ if (dialect.name !== "postgres")
1418
+ return "current";
1419
+ const t = snapshotIndexTables(prefix);
1420
+ const schema = sessionLinksHotSchema(prefix);
1421
+ const recorded = async () => {
1422
+ const ledger = dialect.tableExists(schema.ledger);
1423
+ if ((await database.get(ledger.sql, ...ledger.params)) === undefined)
1424
+ return false;
1425
+ return ((await database.get(`SELECT 1 AS found FROM ${schema.ledger} WHERE domain = ? AND version >= ?`, `schema:${schema.domain}`, schema.revision)) !== undefined);
1426
+ };
1427
+ if (await recorded())
1428
+ return "current";
1429
+ for (;;) {
1430
+ const found = await sessionLinksState(database, t, dialect);
1431
+ if (found === undefined)
1432
+ return "absent";
1433
+ if (!found.owned)
1434
+ return "not-owner";
1435
+ if (found.building) {
1436
+ // Another process builds an index of the table, perhaps this one: its outcome decides what is left to do.
1437
+ await new Promise((resolve) => setTimeout(resolve, HOT_SESSION_LINKS_BUILD_POLL_MS));
1438
+ continue;
1439
+ }
1440
+ if (found.anchored === false)
1441
+ await database.exec(`DROP INDEX CONCURRENTLY IF EXISTS ${t.sessionLinks}_anchored`);
1442
+ if (found.anchored !== true)
1443
+ await database.exec(sessionLinksLeafIndex(t, dialect).replace("CREATE INDEX", "CREATE INDEX CONCURRENTLY"));
1444
+ break;
1445
+ }
1446
+ await database.exec(`DROP INDEX CONCURRENTLY IF EXISTS ${t.sessionLinks}_leaves`);
1447
+ // The index is in place, so the record runs no DDL, which would wait for the table's writes.
1448
+ await database.transaction((transaction) => ensureStorageSchema(transaction, dialect, schema, async () => { }), {
1449
+ retryTransientFailures: true,
1450
+ concurrency: { kind: "serial", domain: schema.ledger },
1451
+ });
1452
+ return "built";
1453
+ }
1035
1454
  /** Runs only layout maintenance on the offline command's dedicated, exclusively locked SQLite file connection. */
1036
1455
  static async moveChunksOffline(file, prefix = "") {
1037
1456
  const tables = snapshotIndexTables(prefix);
@@ -1222,11 +1641,26 @@ export class SqlSnapshotBlobStore {
1222
1641
  */
1223
1642
  async assertStored(transaction, snapshots) {
1224
1643
  const missing = await this.missingBlob(transaction, snapshots);
1225
- if (missing === undefined)
1226
- return;
1644
+ if (missing !== undefined)
1645
+ await this.refuseCollected(missing);
1646
+ }
1647
+ /** The `blobs-collected` {@link WorkspaceSnapshotError} `assertStored` rejects with for `hash`. */
1648
+ async refuseCollected(hash) {
1227
1649
  // Loaded only when a write is refused, so the storage entry does not load the workspace error family.
1228
1650
  const { WorkspaceSnapshotError } = await import("./errors.code.js").catch((error) => __atomicOnDemandFailed(error, "worktree snapshots"));
1229
- throw new WorkspaceSnapshotError("blobs-collected", missing);
1651
+ throw new WorkspaceSnapshotError("blobs-collected", hash);
1652
+ }
1653
+ /** The blobs of `snapshots` that `assertStored` checks, each once, in the order it reports the first missing one. */
1654
+ storedHashes(snapshots) {
1655
+ return [...new Set(snapshots.flatMap(wellFormedBlobHashes))];
1656
+ }
1657
+ /**
1658
+ * The query `missingBlob` reads, for the blobs named by `source`, an SQL expression of a JSON array of hashes: the
1659
+ * hashes this table holds in full, locked FOR SHARE in hash order. A statement that checks the blobs on the server,
1660
+ * such as the session append function, runs it as it is (#6599).
1661
+ */
1662
+ storedBlobsQuery(source) {
1663
+ return `SELECT hash FROM ${this.table} AS b WHERE hash IN (SELECT value FROM ${this.dialect.jsonValues(source)}) AND (chunks = 0 OR chunks = (SELECT COUNT(*) FROM ${this.tables.blobChunks} AS c WHERE c.hash = b.hash)) ORDER BY hash${this.dialect.byteOrderCollation}${this.dialect.lockClause("share")}`;
1230
1664
  }
1231
1665
  /**
1232
1666
  * A query that returns a row only while this table holds every blob of `snapshots` in full, for a write planned
@@ -1246,10 +1680,10 @@ export class SqlSnapshotBlobStore {
1246
1680
  * rows it finds stay locked FOR SHARE until the transaction ends, taken in hash order as a blob write takes them.
1247
1681
  */
1248
1682
  async missingBlob(transaction, snapshots) {
1249
- const hashes = [...new Set(snapshots.flatMap(wellFormedBlobHashes))];
1683
+ const hashes = this.storedHashes(snapshots);
1250
1684
  if (hashes.length === 0)
1251
1685
  return undefined;
1252
- const rows = await transaction.all(`SELECT hash FROM ${this.table} AS b WHERE hash IN (SELECT value FROM ${this.dialect.jsonValues("?")}) AND (chunks = 0 OR chunks = (SELECT COUNT(*) FROM ${this.tables.blobChunks} AS c WHERE c.hash = b.hash)) ORDER BY hash${this.dialect.byteOrderCollation}${this.dialect.lockClause("share")}`, JSON.stringify(hashes));
1686
+ const rows = await transaction.all(this.storedBlobsQuery("?"), JSON.stringify(hashes));
1253
1687
  const stored = new Set(rows.map((row) => row.hash));
1254
1688
  return hashes.find((hash) => !stored.has(hash));
1255
1689
  }
@@ -1259,14 +1693,27 @@ export class SqlSnapshotBlobStore {
1259
1693
  * above it, indexed by the triggers. A table that has none yet, an empty one included, costs one watermark of 0.
1260
1694
  * Resolves with the state of every referencing table.
1261
1695
  */
1262
- async installIndex(pace, includeDeferred = false) {
1263
- const states = await readSourceStates(this.database, this.dialect, this.tables, this.sources, includeDeferred);
1696
+ async installIndex(pace, includeDeferred = false, catalog) {
1697
+ // The fork links trigger earlier builds of #6560 installed, asked for in the same read: dropped where found, in the
1698
+ // first write below, so a database that has it runs it no longer once a store of this build opened it.
1699
+ const legacy = this.legacyForkLinks();
1700
+ const found = new Set();
1701
+ const states = await this.readStates(includeDeferred, catalog, legacy && { names: [legacy.name], found });
1702
+ let drop = legacy !== undefined && found.has(legacy.name) ? legacy : undefined;
1703
+ const dropLegacy = async (transaction) => {
1704
+ if (drop === undefined)
1705
+ return;
1706
+ const { name, table } = drop;
1707
+ await withShortSchemaLockWaits(transaction, this.dialect, () => transaction.exec(this.dialect.dropTrigger(name, table, true)));
1708
+ drop = undefined;
1709
+ };
1264
1710
  const missing = states.filter((state) => !state.installed && (includeDeferred || !state.deferred));
1265
1711
  for (const { source } of missing) {
1266
1712
  const reset = source.name === "session-entries"
1267
1713
  ? await SqlSnapshotBlobStore.prepareSessionIndexReset(this.database)
1268
1714
  : undefined;
1269
1715
  await this.write(pace, async (transaction) => {
1716
+ await dropLegacy(transaction);
1270
1717
  const [current] = await readSourceStates(transaction, this.dialect, this.tables, [source]);
1271
1718
  if (current === undefined || current.installed || (current.deferred && !includeDeferred))
1272
1719
  return;
@@ -1274,9 +1721,37 @@ export class SqlSnapshotBlobStore {
1274
1721
  await withShortSchemaLockWaits(transaction, this.dialect, () => installSource(transaction, this.dialect, this.tables, source, reset));
1275
1722
  });
1276
1723
  }
1277
- return missing.length === 0
1278
- ? states
1279
- : readSourceStates(this.database, this.dialect, this.tables, this.sources, includeDeferred);
1724
+ if (drop !== undefined)
1725
+ await this.write(pace, dropLegacy);
1726
+ return missing.length === 0 ? states : this.readStates(includeDeferred);
1727
+ }
1728
+ /** The fork links trigger earlier builds of #6560 installed on the session entries, and its table. */
1729
+ legacyForkLinks() {
1730
+ const entries = this.sources.find((source) => source.name === "session-entries");
1731
+ return entries && { name: legacyForkLinksTriggerName(entries.table), table: entries.table };
1732
+ }
1733
+ /**
1734
+ * The state of every source, read outside a transaction. On PostgreSQL the objects and the progress rows are read in
1735
+ * one read-only transaction whose start carries both, so they cost one round trip, not one each. An open's
1736
+ * `catalog` answers which objects exist only when it found every one: only its positive answers are final, and a
1737
+ * source table it lacks may have been created since (#6560). `also` asks which of other objects exist in the same
1738
+ * read, as `readSourceStates` does.
1739
+ */
1740
+ readStates(includeDeferred, catalog, also) {
1741
+ if (this.dialect.name !== "postgres")
1742
+ return readSourceStates(this.database, this.dialect, this.tables, this.sources, includeDeferred, undefined, also);
1743
+ const names = sourceObjectNames(this.sources);
1744
+ const present = catalog !== undefined && names.every((name) => catalog.hasObject(name))
1745
+ ? new Set([...names, ...(also?.names ?? []).filter((name) => catalog.hasObject(name))])
1746
+ : undefined;
1747
+ return this.database.transaction((transaction) => readSourceStates(transaction, this.dialect, this.tables, this.sources, includeDeferred, present, also), {
1748
+ readOnly: true,
1749
+ retryTransientFailures: true,
1750
+ leading: [
1751
+ ...(present === undefined ? [this.dialect.schemaObjects([...names, ...(also?.names ?? [])])] : []),
1752
+ sourceProgressRead(this.tables),
1753
+ ],
1754
+ });
1280
1755
  }
1281
1756
  /**
1282
1757
  * Indexes the rows that referencing tables held before their triggers were installed, in transactions of
@@ -1381,11 +1856,16 @@ export class SqlSnapshotBlobStore {
1381
1856
  await transaction.run(sql, from, upper);
1382
1857
  if (source.rowwise !== undefined) {
1383
1858
  const rows = await transaction.all(`SELECT ${row} AS id FROM ${source.table} WHERE ${row} > ? AND ${row} <= ? ORDER BY ${row}`, from, upper);
1859
+ // The session entries are linked in each session's seq order, whatever order their rows are stored in (#6560).
1860
+ const linking = source.name === "session-entries" ? entryLinking(source, this.dialect, t.sessionLinks) : undefined;
1384
1861
  for (const { id } of rows) {
1385
1862
  // Stopping between rows rolls the whole batch back, progress included, so the pass stays resumable.
1386
1863
  signal?.throwIfAborted();
1387
- for (const sql of source.rowwise)
1388
- await transaction.run(sql, id);
1864
+ if (linking !== undefined)
1865
+ await linkStoredEntry(transaction, linking, id);
1866
+ else
1867
+ for (const sql of source.rowwise)
1868
+ await transaction.run(sql, id);
1389
1869
  }
1390
1870
  }
1391
1871
  // Indexing rows again behind the source's progress, for this build's own, never moves the progress back.
@@ -1429,9 +1909,11 @@ export class SqlSnapshotBlobStore {
1429
1909
  options.signal?.throwIfAborted();
1430
1910
  const trigger = `${t.blobs}_chunks_delete_all`;
1431
1911
  const required = [trigger, `${t.blobs}_age`, `${t.blobs}_inline_size`];
1432
- const schema = this.dialect.schemaObjects(required);
1912
+ // Asked with them: whether forks share their parents' histories, whose inherited snapshots the sweep keeps (#6560).
1913
+ const schema = this.dialect.schemaObjects([...required, this.forkSegments]);
1433
1914
  const present = new Set((await this.database.all(schema.sql, ...schema.params)).map((row) => row.name));
1434
- if (present.size < required.length) {
1915
+ const forks = present.has(this.forkSegments);
1916
+ if (!required.every((name) => present.has(name))) {
1435
1917
  options.signal?.throwIfAborted();
1436
1918
  await this.write(options.pace, async (transaction) => {
1437
1919
  if (options.holder !== undefined)
@@ -1461,7 +1943,7 @@ export class SqlSnapshotBlobStore {
1461
1943
  renewedAt = performance.now();
1462
1944
  }
1463
1945
  const page = await this.page(minimumAge, cursor);
1464
- const candidates = await this.unretainedOf(page.map((row) => row.hash), sessions, turns);
1946
+ const candidates = await this.unretainedOf(page.map((row) => row.hash), sessions, turns, forks);
1465
1947
  let incomplete = false;
1466
1948
  for (const batch of sessions.batches(candidates)) {
1467
1949
  // Every delete batch starts on a turn of its own and ends with one: never a turn while it holds the write lock.
@@ -1501,7 +1983,7 @@ export class SqlSnapshotBlobStore {
1501
1983
  * references one of them and that `sessions` has not walked yet, in statements of at most
1502
1984
  * {@link SNAPSHOT_COLLECTION_SESSION_REFS} snapshot entries, with a turn between them.
1503
1985
  */
1504
- async unretainedOf(hashes, sessions, turns) {
1986
+ async unretainedOf(hashes, sessions, turns, forks) {
1505
1987
  if (hashes.length === 0)
1506
1988
  return [];
1507
1989
  const t = this.tables;
@@ -1517,7 +1999,7 @@ export class SqlSnapshotBlobStore {
1517
1999
  sessions.cost(costs);
1518
2000
  for (const group of sessionGroups(costs)) {
1519
2001
  await turns.next();
1520
- sessions.retain(group, await this.retainedBySessions(group));
2002
+ sessions.retain(group, await this.retainedBySessions(group, forks));
1521
2003
  turns.held();
1522
2004
  }
1523
2005
  }
@@ -1533,16 +2015,26 @@ export class SqlSnapshotBlobStore {
1533
2015
  * and the sessions that record its blobs now. A blob a session the sweep did not walk records, such as one created
1534
2016
  * since, is kept; the next collection walks that session. Nothing in the transaction waits for a turn of the event
1535
2017
  * loop (#5530).
2018
+ *
2019
+ * It runs as a whole-database transaction on purpose, so no other write runs beside it. With only the blob table's
2020
+ * lock it would not be safe: it decides which blobs sessions still use in one statement and deletes in the next. A
2021
+ * session write that records a blob meanwhile holds the blob's row only until it commits its reference; the delete
2022
+ * waits for it, then goes ahead without looking at the references again, and removes a blob a session has just
2023
+ * recorded. The same goes for the references retaining runs and carried work write.
1536
2024
  */
1537
2025
  deleteUnretained(batch, minimumAge, options) {
1538
2026
  const t = this.tables;
1539
2027
  return this.write(options.pace, async (transaction) => {
1540
- const states = await readSourceStates(transaction, this.dialect, this.tables, this.sources);
2028
+ const found = new Set();
2029
+ const states = await readSourceStates(transaction, this.dialect, this.tables, this.sources, false, undefined, {
2030
+ names: [this.forkSegments],
2031
+ found,
2032
+ });
1541
2033
  if (!states.every((state) => state.installed && state.backfilled))
1542
2034
  return undefined;
1543
2035
  if (options.holder !== undefined)
1544
2036
  await this.renewClaim(transaction, options.holder);
1545
- const kept = new Set(await this.keptBySessions(transaction, batch));
2037
+ const kept = new Set(await this.keptBySessions(transaction, batch, found.has(this.forkSegments)));
1546
2038
  const unretained = batch.hashes.filter((hash) => !kept.has(hash));
1547
2039
  if (unretained.length === 0)
1548
2040
  return [];
@@ -1580,32 +2072,48 @@ export class SqlSnapshotBlobStore {
1580
2072
  * The blobs that the snapshots `sessions` retain reference, in one statement. A session whose tree the index could
1581
2073
  * not follow retains every snapshot it records.
1582
2074
  */
1583
- async retainedBySessions(sessions) {
2075
+ async retainedBySessions(sessions, forks) {
1584
2076
  const t = this.tables;
1585
2077
  const ids = JSON.stringify(sessions);
2078
+ const inherited = this.inheritedRecord(forks);
1586
2079
  const rows = await this.database.all(`SELECT DISTINCT record.hash FROM ${t.sessionRecords} AS record
1587
2080
  WHERE record.session_id IN (SELECT value FROM ${this.dialect.jsonValues("?")})
1588
2081
  AND (
1589
2082
  (record.session_id, record.snapshot_id) IN (${this.sessionHeads(`session_id IN (SELECT value FROM ${this.dialect.jsonValues("?")})`)})
1590
- OR EXISTS (SELECT 1 FROM ${t.sessionLinks} AS broken WHERE broken.session_id = record.session_id AND broken.broken = 1)
2083
+ OR EXISTS (SELECT 1 FROM ${t.sessionLinks} AS broken WHERE broken.session_id = record.session_id AND broken.broken = 1)${inherited}
1591
2084
  )`, ids, ids);
1592
2085
  return rows.map((row) => row.hash);
1593
2086
  }
2087
+ /**
2088
+ * A condition, after `OR`, that another session inherits the session record `record` through a fork segment
2089
+ * (#6560); empty when `forks` says the fork segments table is not there, as while shared-history forks are off. A
2090
+ * fork that shares its parent's history stores none of the entries it inherits, so its own references never name
2091
+ * their snapshots: a record a segment names is kept whatever its session retains, as long as the segment lasts. A
2092
+ * delete batch reads whether the table exists in its own transaction, so it sees the segments that hold when it
2093
+ * commits.
2094
+ */
2095
+ inheritedRecord(forks) {
2096
+ if (!forks)
2097
+ return "";
2098
+ return `
2099
+ OR EXISTS (SELECT 1 FROM ${this.forkSegments} AS segment WHERE segment.source_id = record.session_id AND record.seq BETWEEN segment.from_seq AND segment.to_seq)`;
2100
+ }
1594
2101
  /**
1595
2102
  * The blobs of `batch` that a session records and that the delete must keep, in one statement: those the snapshots
1596
2103
  * of `batch.sessions` retain, and those a session not among them records, whose snapshots the sweep did not walk.
1597
2104
  * Walks only `batch.sessions`, whose snapshot entries the sweep bounded when it made the batch (#5530).
1598
2105
  */
1599
- async keptBySessions(executor, batch) {
2106
+ async keptBySessions(executor, batch, forks) {
1600
2107
  const t = this.tables;
1601
2108
  const ids = JSON.stringify(batch.sessions);
1602
2109
  const walked = `(SELECT value FROM ${this.dialect.jsonValues("?")})`;
2110
+ const inherited = this.inheritedRecord(forks);
1603
2111
  const rows = await executor.all(`SELECT DISTINCT record.hash FROM ${t.sessionRecords} AS record
1604
2112
  WHERE record.hash IN (SELECT value FROM ${this.dialect.jsonValues("?")})
1605
2113
  AND (
1606
2114
  record.session_id NOT IN ${walked}
1607
2115
  OR (record.session_id, record.snapshot_id) IN (${this.sessionHeads(`session_id IN ${walked}`)})
1608
- OR EXISTS (SELECT 1 FROM ${t.sessionLinks} AS broken WHERE broken.session_id = record.session_id AND broken.broken = 1)
2116
+ OR EXISTS (SELECT 1 FROM ${t.sessionLinks} AS broken WHERE broken.session_id = record.session_id AND broken.broken = 1)${inherited}
1609
2117
  )`, JSON.stringify(batch.hashes), ids, ids);
1610
2118
  return rows.map((row) => row.hash);
1611
2119
  }
@@ -1842,7 +2350,7 @@ export class SqlSnapshotBlobStore {
1842
2350
  Reflect.defineProperty(error, RENAME_BLOCKER, { value: { type: only.type, name: only.name } });
1843
2351
  }
1844
2352
  /**
1845
- * Whether the file system of a SQLite or libSQL database file has room to copy what is left of the chunk table to the
2353
+ * Whether the file system of a SQLite database file has room to copy what is left of the chunk table to the
1846
2354
  * row layout (#5694): the copy grows the file by the bytes its free pages do not hold, and the write-ahead log can
1847
2355
  * hold every page the copy writes until a checkpoint moves them into the file, with
1848
2356
  * {@link SNAPSHOT_CHUNK_MOVE_HEADROOM_BYTES} left over; the database's own `freeBytes` says how much the file system
@@ -2046,7 +2554,7 @@ function __atomicOnDemandFailed(error, feature) {
2046
2554
  return (async () => {
2047
2555
  const root = new URL("../../", import.meta.url);
2048
2556
  const releases = (globalThis[Symbol.for("atomic.in-place-update-release.v1")] ??= new Map());
2049
- const key = `${root.href}#0.10.11-alpha.1`;
2557
+ const key = `${root.href}#0.10.11-alpha.3`;
2050
2558
  let release = releases.get(key);
2051
2559
  if (release === undefined) {
2052
2560
  const current = (async () => {
@@ -2074,7 +2582,7 @@ function __atomicOnDemandFailed(error, feature) {
2074
2582
  } catch {
2075
2583
  // No installation to read, as in a bundle of the package: the release the process runs decides.
2076
2584
  }
2077
- const updatedTo = typeof installed === "string" && installed !== "0.10.11-alpha.1" ? installed : running !== undefined && running.version !== "0.10.11-alpha.1" ? "0.10.11-alpha.1" : undefined;
2585
+ 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;
2078
2586
  if (updatedTo === undefined) throw error;
2079
2587
  const application = typeof running?.name === "string" ? running.name : "atomic";
2080
2588
  const restart = new Error(`${application} was updated to ${updatedTo} while this session was running; restart it to keep using ${feature}.`, {