@bastani/atomic 0.10.10 → 0.10.11-alpha.2
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.
- package/CHANGELOG.md +139 -0
- package/README.md +1 -1
- package/dist/_shared/dist-KOELCESV.js +2 -2
- package/dist/_shared/fork-row-index-UAUAQRD5.js +2 -2
- package/dist/_shared/lib-4PES5P4V.js +2 -2
- package/dist/_shared/mode-interactive-sdk-7KXUFI2F.js +11 -13
- package/dist/_shared/mode-interactive-sdk-7KXUFI2F.js.map +1 -1
- package/dist/_shared/mode-rpc-sdk-IOPGDYR4.js +9 -9
- package/dist/_shared/mode-shared-2QJSCUM6.js +55 -18
- package/dist/_shared/mode-shared-2QJSCUM6.js.map +1 -1
- package/dist/_shared/p1a-prewarm-XIU57JHF.js +3 -3
- package/dist/_shared/runtime-O4KCSG4C.js +5 -5
- package/dist/_shared/{sdk-RRLVN7ER.js → sdk-IQMULKFU.js} +2962 -470
- package/dist/_shared/sdk-IQMULKFU.js.map +1 -0
- package/dist/_shared/session-data-AHTU7IS6.js +4 -4
- package/dist/_shared/session-manager-list-2BLEEZVG.js +1 -1
- package/dist/_shared/settings-startup-8-DNZ2RIHM.js +1 -1
- package/dist/_shared/{settings-startup-4QCVCI53.js → settings-startup-HXQLSUWM.js} +8 -2
- package/dist/_shared/settings-startup-HXQLSUWM.js.map +1 -0
- package/dist/_shared/{startup-0-0-4VG2G44V.js → startup-0-0-3IXNMFM2.js} +482 -53
- package/dist/_shared/startup-0-0-3IXNMFM2.js.map +1 -0
- package/dist/_shared/{startup-0-1-XTIL65D4.js → startup-0-1-7T2IAE7J.js} +121 -251
- package/dist/_shared/startup-0-1-7T2IAE7J.js.map +1 -0
- package/dist/_shared/{startup-0-2-27OWFHV6.js → startup-0-2-5QHPCEON.js} +293 -10
- package/dist/_shared/startup-0-2-5QHPCEON.js.map +1 -0
- package/dist/_shared/{startup-0-3-T4DVFYWX.js → startup-0-3-4ZYBYQNM.js} +273 -14
- package/dist/_shared/startup-0-3-4ZYBYQNM.js.map +1 -0
- package/dist/_shared/startup-0-4-ZMJV547D.js +6 -6
- package/dist/_shared/{startup-0-5-FD2P735I.js → startup-0-5-YDW47QX6.js} +29 -71
- package/dist/_shared/startup-0-5-YDW47QX6.js.map +1 -0
- package/dist/_shared/startup-10-0-TDQNBDDL.js +9 -9
- package/dist/_shared/startup-12-0-55AAXBJZ.js +4 -4
- package/dist/_shared/startup-14-0-MLX36RBG.js +6 -6
- package/dist/_shared/startup-15-0-YUKGAC63.js +34 -10
- package/dist/_shared/startup-15-0-YUKGAC63.js.map +1 -1
- package/dist/_shared/startup-15-1-4S7FLMNG.js +10 -9
- package/dist/_shared/startup-15-1-4S7FLMNG.js.map +1 -1
- package/dist/_shared/startup-8-0-34CBHPZH.js +421 -84
- package/dist/_shared/startup-8-0-34CBHPZH.js.map +1 -1
- package/dist/_shared/{startup-8-1-4KANEHRA.js → startup-8-1-X32CYSXB.js} +1291 -722
- package/dist/_shared/startup-8-1-X32CYSXB.js.map +1 -0
- package/dist/_shared/storage-command-7MGXLJGZ.js +17 -9
- package/dist/_shared/storage-command-7MGXLJGZ.js.map +1 -1
- package/dist/_shared/task-reference-stream-JWMUZSJX.js +1 -1
- package/dist/_shared/task-unsaved-answer-VJ2KTB4V.js +2 -2
- package/dist/_shared/tree-outline-MUEPK5B7.js +3 -3
- package/dist/builtin/intercom/CHANGELOG.md +29 -0
- package/dist/builtin/intercom/broker/broker.bundle.mjs +1138 -384
- package/dist/builtin/intercom/broker/database-wake-up-bus.ts +103 -24
- package/dist/builtin/intercom/broker/multinode-router.ts +42 -21
- package/dist/builtin/intercom/broker/multinode-state-store.ts +22 -1
- package/dist/builtin/intercom/broker/open-broker-state.ts +82 -31
- package/dist/builtin/intercom/broker/paths.ts +8 -4
- package/dist/builtin/intercom/broker/released-asker-remote-replies.ts +18 -6
- package/dist/builtin/intercom/broker/sql-add-column.ts +4 -1
- package/dist/builtin/intercom/broker/sql-ended-child-queue-store.ts +65 -44
- package/dist/builtin/intercom/broker/sql-held-send-store.ts +11 -3
- package/dist/builtin/intercom/broker/sql-known-session-store.ts +24 -12
- package/dist/builtin/intercom/broker/sql-lease-store.ts +386 -65
- package/dist/builtin/intercom/broker/sql-outbox-store.ts +462 -130
- package/dist/builtin/intercom/broker/sql-pending-ask-store.ts +20 -9
- package/dist/builtin/intercom/broker/sql-released-ask-store.ts +14 -6
- package/dist/builtin/intercom/broker/sql-restoring-reservation-store.ts +27 -11
- package/dist/builtin/intercom/broker/sql-schema.ts +198 -5
- package/dist/builtin/intercom/broker/sql-sent-message-authority.ts +97 -34
- package/dist/builtin/intercom/index.bundle.mjs +11 -8
- package/dist/builtin/intercom/package.json +1 -1
- package/dist/builtin/mcp/index.bundle.mjs +1 -1
- package/dist/builtin/mcp/package.json +1 -1
- package/dist/builtin/subagents/CHANGELOG.md +18 -0
- package/dist/builtin/subagents/package.json +1 -1
- package/dist/builtin/subagents/skills/skill-creator/SKILL.md +1 -1
- package/dist/builtin/subagents/src/extension/index.bundle.mjs +62 -23
- package/dist/builtin/web-access/index.bundle.mjs +1 -1
- package/dist/builtin/web-access/package.json +1 -1
- package/dist/cli/args.js +2 -2
- package/dist/cli/auth-cli.code.js +6 -6
- package/dist/cli/auth-cli.impl.js +3 -3
- package/dist/cli/auth-cli.js +3 -3
- package/dist/cli/blueprint-command.code.js +4 -4
- package/dist/cli/blueprint-command.impl.js +3 -3
- package/dist/cli/blueprint-command.js +3 -3
- package/dist/cli/intercom-command.code.js +3 -3
- package/dist/cli/intercom-command.impl.js +3 -3
- package/dist/cli/intercom-command.js +3 -3
- package/dist/cli/list-models.code.js +2 -2
- package/dist/cli/list-models.impl.js +3 -3
- package/dist/cli/list-models.js +3 -3
- package/dist/cli/session-picker.code.js +2 -2
- package/dist/cli/session-picker.impl.js +3 -3
- package/dist/cli/session-picker.js +3 -3
- package/dist/cli/startup-ui.code.js +2 -2
- package/dist/cli/startup-ui.impl.js +3 -3
- package/dist/cli/startup-ui.js +3 -3
- package/dist/cli/storage-command.impl.js +3 -3
- package/dist/cli/storage-command.js +3 -3
- package/dist/cli/storage-search-session.code.js +3 -3
- package/dist/cli/storage-search-session.impl.js +3 -3
- package/dist/cli/storage-search-session.js +3 -3
- package/dist/cli/team-command.code.js +3 -3
- package/dist/cli/team-command.impl.js +3 -3
- package/dist/cli/team-command.js +3 -3
- package/dist/cli.js +2 -2
- package/dist/core/agent-session-methods.d.ts +3 -0
- package/dist/core/agent-session-methods.js.map +1 -1
- package/dist/core/agent-session.d.ts +1 -0
- package/dist/core/compaction/compactor.d.ts +2 -0
- package/dist/core/debug.impl.js +3 -3
- package/dist/core/debug.js +3 -3
- package/dist/core/export-html/card-projection.code.js +1 -1
- package/dist/core/export-html/card-projection.impl.js +3 -3
- package/dist/core/export-html/card-projection.js +3 -3
- package/dist/core/export-html/index.code.js +2 -2
- package/dist/core/export-html/index.impl.js +3 -3
- package/dist/core/export-html/index.js +3 -3
- package/dist/core/export-html/json-spans.impl.js +3 -3
- package/dist/core/export-html/json-spans.js +3 -3
- package/dist/core/export-html/oversized-render-inputs.code.js +2 -2
- package/dist/core/export-html/oversized-render-inputs.impl.js +3 -3
- package/dist/core/export-html/oversized-render-inputs.js +3 -3
- package/dist/core/export-html/tool-renderer.impl.js +3 -3
- package/dist/core/export-html/tool-renderer.js +3 -3
- package/dist/core/extensions/jiti-loader.impl.js +3 -3
- package/dist/core/extensions/jiti-loader.js +3 -3
- package/dist/core/extensions/jiti-static-loader.impl.js +3 -3
- package/dist/core/extensions/jiti-static-loader.js +3 -3
- package/dist/core/extensions/loader-host-modules.code.js +1 -1
- package/dist/core/extensions/loader-host-modules.impl.js +3 -3
- package/dist/core/extensions/loader-host-modules.js +3 -3
- package/dist/core/extensions/loader-virtual-modules.js +2 -2
- package/dist/core/extensions/runner-context.js +4 -4
- package/dist/core/extensions/runner-context.js.map +1 -1
- package/dist/core/intercom-broker-control-host.code.js +1 -1
- package/dist/core/intercom-broker-control-host.impl.js +3 -3
- package/dist/core/intercom-broker-control-host.js +3 -3
- package/dist/core/intercom-broker-control.code.js +3 -3
- package/dist/core/intercom-broker-control.impl.js +3 -3
- package/dist/core/intercom-broker-control.js +3 -3
- package/dist/core/model-registry.js +1 -1
- package/dist/core/model-resolver-defaults.d.ts +3 -2
- package/dist/core/package-manager-storage-adapters.code.js +1 -1
- package/dist/core/package-manager-storage-adapters.impl.js +3 -3
- package/dist/core/package-manager-storage-adapters.js +3 -3
- package/dist/core/sdk.code.js +4 -5
- package/dist/core/sdk.impl.js +3 -3
- package/dist/core/sdk.js +3 -3
- package/dist/core/session-manager-core.d.ts +5 -2
- package/dist/core/session-manager-core.js +39 -23
- package/dist/core/session-manager-core.js.map +1 -1
- package/dist/core/session-manager-list.impl.js +3 -3
- package/dist/core/session-manager-list.js +3 -3
- package/dist/core/session-manager.code.js +3 -3
- package/dist/core/session-manager.impl.js +3 -3
- package/dist/core/session-manager.js +3 -3
- package/dist/core/session-open-markers.js +3 -0
- package/dist/core/session-open-markers.js.map +1 -0
- package/dist/core/session-storage.code.js +1 -1
- package/dist/core/session-storage.impl.js +3 -3
- package/dist/core/session-storage.js +3 -3
- package/dist/core/storage/added-exports.d.ts +6 -0
- package/dist/core/storage/added-exports.js +19 -0
- package/dist/core/storage/added-exports.js.map +1 -0
- package/dist/core/storage/database.d.ts +53 -0
- package/dist/core/storage/database.js.map +1 -1
- package/dist/core/storage/fenced-paths.d.ts +47 -0
- package/dist/core/storage/fenced-paths.js +53 -0
- package/dist/core/storage/fenced-paths.js.map +1 -1
- package/dist/core/storage/file-identity.js +31 -2
- package/dist/core/storage/file-identity.js.map +1 -1
- package/dist/core/storage/index.d.ts +4 -1
- package/dist/core/storage/index.js +5 -2
- package/dist/core/storage/index.js.map +1 -1
- package/dist/core/storage/migrations.d.ts +33 -2
- package/dist/core/storage/migrations.js +73 -5
- package/dist/core/storage/migrations.js.map +1 -1
- package/dist/core/storage/node-sqlite-thread.js +48 -6
- package/dist/core/storage/node-sqlite-thread.js.map +1 -1
- package/dist/core/storage/node-sqlite.js +137 -4
- package/dist/core/storage/node-sqlite.js.map +1 -1
- package/dist/core/storage/offline-snapshot-file.impl.js +3 -3
- package/dist/core/storage/offline-snapshot-file.js +3 -3
- package/dist/core/storage/prefix.d.ts +3 -2
- package/dist/core/storage/prefix.js +23 -2
- package/dist/core/storage/prefix.js.map +1 -1
- package/dist/core/storage/provider.js +2 -2
- package/dist/core/storage/schema-catalog.d.ts +120 -0
- package/dist/core/storage/schema-catalog.js +351 -0
- package/dist/core/storage/schema-catalog.js.map +1 -0
- package/dist/core/storage/selection.js +2 -2
- package/dist/core/storage/session/branch-fork-source.code.js +47 -25
- package/dist/core/storage/session/branch-fork-source.code.js.map +1 -1
- package/dist/core/storage/session/branch-fork-source.impl.js +3 -3
- package/dist/core/storage/session/branch-fork-source.js +3 -3
- package/dist/core/storage/session/card-view.impl.js +3 -3
- package/dist/core/storage/session/card-view.js +3 -3
- package/dist/core/storage/session/child-reader.code.js +4 -4
- package/dist/core/storage/session/child-reader.impl.js +3 -3
- package/dist/core/storage/session/child-reader.js +3 -3
- package/dist/core/storage/session/chunked-resume-projection.code.js +1 -1
- package/dist/core/storage/session/chunked-resume-projection.impl.js +3 -3
- package/dist/core/storage/session/chunked-resume-projection.js +3 -3
- package/dist/core/storage/session/errors.js +1 -1
- package/dist/core/storage/session/expanded-child-details.code.js +4 -4
- package/dist/core/storage/session/expanded-child-details.impl.js +3 -3
- package/dist/core/storage/session/expanded-child-details.js +3 -3
- package/dist/core/storage/session/fork-detach.d.ts +118 -0
- package/dist/core/storage/session/fork-row-bytes.impl.js +3 -3
- package/dist/core/storage/session/fork-row-bytes.js +3 -3
- package/dist/core/storage/session/fork-row-index.impl.js +3 -3
- package/dist/core/storage/session/fork-row-index.js +3 -3
- package/dist/core/storage/session/fork-schema.js +53 -0
- package/dist/core/storage/session/fork-schema.js.map +1 -0
- package/dist/core/storage/session/fork-segments.d.ts +58 -0
- package/dist/core/storage/session/fork-staging.code.js +176 -36
- package/dist/core/storage/session/fork-staging.code.js.map +1 -1
- package/dist/core/storage/session/fork-staging.impl.js +3 -3
- package/dist/core/storage/session/fork-staging.js +3 -3
- package/dist/core/storage/session/fork-sweep.js +61 -0
- package/dist/core/storage/session/fork-sweep.js.map +1 -0
- package/dist/core/storage/session/fork-window.code.js +4 -4
- package/dist/core/storage/session/fork-window.impl.js +3 -3
- package/dist/core/storage/session/fork-window.js +3 -3
- package/dist/core/storage/session/history-pages.impl.js +3 -3
- package/dist/core/storage/session/history-pages.js +3 -3
- package/dist/core/storage/session/jsonl-entry-projection.impl.js +3 -3
- package/dist/core/storage/session/jsonl-entry-projection.js +3 -3
- package/dist/core/storage/session/jsonl-session-store.d.ts +37 -1
- package/dist/core/storage/session/jsonl-session-store.impl.js +3 -3
- package/dist/core/storage/session/jsonl-session-store.js +3 -3
- package/dist/core/storage/session/memory-session-store.impl.js +3 -3
- package/dist/core/storage/session/memory-session-store.js +3 -3
- package/dist/core/storage/session/pinned-branch-resume.code.js +3 -3
- package/dist/core/storage/session/pinned-branch-resume.impl.js +3 -3
- package/dist/core/storage/session/pinned-branch-resume.js +3 -3
- package/dist/core/storage/session/released-history-files.code.js +3 -3
- package/dist/core/storage/session/released-history-files.impl.js +3 -3
- package/dist/core/storage/session/released-history-files.js +3 -3
- package/dist/core/storage/session/resident-fork-rows.code.js +1 -1
- package/dist/core/storage/session/resident-fork-rows.impl.js +3 -3
- package/dist/core/storage/session/resident-fork-rows.js +3 -3
- package/dist/core/storage/session/session-resume.impl.js +3 -3
- package/dist/core/storage/session/session-resume.js +3 -3
- package/dist/core/storage/session/session-search-index.d.ts +5 -0
- package/dist/core/storage/session/snapshot-cut.impl.js +3 -3
- package/dist/core/storage/session/snapshot-cut.js +3 -3
- package/dist/core/storage/session/snapshot-history.code.js +4 -4
- package/dist/core/storage/session/snapshot-history.impl.js +3 -3
- package/dist/core/storage/session/snapshot-history.js +3 -3
- package/dist/core/storage/session/sql-chat-records.d.ts +15 -0
- package/dist/core/storage/session/sql-session-store.code.js +1 -1
- package/dist/core/storage/session/sql-session-store.d.ts +445 -11
- package/dist/core/storage/session/sql-session-store.impl.js +4 -4
- package/dist/core/storage/session/sql-session-store.js +4 -4
- package/dist/core/storage/session/tree-outline.impl.js +3 -3
- package/dist/core/storage/session/tree-outline.js +3 -3
- package/dist/core/storage/session/tree-presentation.code.js +1 -1
- package/dist/core/storage/session/tree-presentation.impl.js +3 -3
- package/dist/core/storage/session/tree-presentation.js +3 -3
- package/dist/core/storage/session/types.d.ts +36 -0
- package/dist/core/storage/sqlite-facade.d.ts +54 -6
- package/dist/core/storage/sqlite-facade.js +384 -18
- package/dist/core/storage/sqlite-facade.js.map +1 -1
- package/dist/core/storage/statement-sequence.d.ts +83 -0
- package/dist/core/storage/statement-sequence.js +21 -0
- package/dist/core/storage/statement-sequence.js.map +1 -1
- package/dist/core/storage/storage-status.code.js +1 -1
- package/dist/core/storage/storage-status.impl.js +3 -3
- package/dist/core/storage/storage-status.js +3 -3
- package/dist/core/storage/team.code.js +1 -1
- package/dist/core/storage/team.impl.js +3 -3
- package/dist/core/storage/team.js +3 -3
- package/dist/core/structured-output/index.code.js +1 -1
- package/dist/core/structured-output/index.impl.js +3 -3
- package/dist/core/structured-output/index.js +3 -3
- package/dist/core/tasks/task-completion-entry.code.js +1 -1
- package/dist/core/tasks/task-completion-entry.impl.js +3 -3
- package/dist/core/tasks/task-completion-entry.js +3 -3
- package/dist/core/tasks/task-file-history.code.js +4 -4
- package/dist/core/tasks/task-file-history.impl.js +3 -3
- package/dist/core/tasks/task-file-history.js +3 -3
- package/dist/core/tasks/task-reference-archive.code.js +5 -5
- package/dist/core/tasks/task-reference-archive.js +3 -3
- package/dist/core/tasks/task-reference-identity.js +3 -3
- package/dist/core/tasks/task-reference-stream.impl.js +3 -3
- package/dist/core/tasks/task-reference-stream.js +3 -3
- package/dist/core/tasks/task-unsaved-answer.impl.js +3 -3
- package/dist/core/tasks/task-unsaved-answer.js +3 -3
- package/dist/core/tasks/task-view-source.code.js +1 -1
- package/dist/core/tasks/task-view-source.impl.js +3 -3
- package/dist/core/tasks/task-view-source.js +3 -3
- package/dist/core/tools/bash.d.ts +8 -4
- package/dist/core/tools/history-session.d.ts +7 -0
- package/dist/core/tools/history-tasks.d.ts +123 -0
- package/dist/core/tools/kill.d.ts +5 -2
- package/dist/core/tools/powershell.d.ts +2 -2
- package/dist/core/tools/read-url.code.js +3 -3
- package/dist/core/tools/read-url.impl.js +3 -3
- package/dist/core/tools/read-url.js +3 -3
- package/dist/core/tools/read.d.ts +12 -2
- package/dist/core/tools/resource-selectors.d.ts +2 -0
- package/dist/core/tools/search.d.ts +12 -2
- package/dist/core/worktree-snapshot/blob-store.d.ts +45 -2
- package/dist/core/worktree-snapshot/blob-store.js +228 -60
- package/dist/core/worktree-snapshot/blob-store.js.map +1 -1
- package/dist/core/worktree-snapshot/errors.code.js +3 -3
- package/dist/core/worktree-snapshot/errors.impl.js +3 -3
- package/dist/core/worktree-snapshot/errors.js +3 -3
- package/dist/core/worktree-snapshot/fork-snapshot-index.js +121 -0
- package/dist/core/worktree-snapshot/fork-snapshot-index.js.map +1 -0
- package/dist/core/worktree-snapshot/session-index-reset.impl.js +3 -3
- package/dist/core/worktree-snapshot/session-index-reset.js +3 -3
- package/dist/extensions/codemode/execute.code.js +3 -3
- package/dist/extensions/codemode/execute.impl.js +3 -3
- package/dist/extensions/codemode/execute.js +3 -3
- package/dist/extensions/codemode/renderer.code.js +2 -2
- package/dist/extensions/codemode/renderer.impl.js +3 -3
- package/dist/extensions/codemode/renderer.js +3 -3
- package/dist/extensions/mcp/cli.code.js +3 -3
- package/dist/extensions/mcp/cli.impl.js +3 -3
- package/dist/extensions/mcp/cli.js +3 -3
- package/dist/extensions/mcp/cli.lazy.code.js +2 -2
- package/dist/extensions/mcp/cli.lazy.impl.js +3 -3
- package/dist/extensions/mcp/cli.lazy.js +3 -3
- package/dist/extensions/mcp/runtime.code.js +1 -1
- package/dist/extensions/mcp/runtime.impl.js +3 -3
- package/dist/extensions/mcp/runtime.js +3 -3
- package/dist/index.js +8 -8
- package/dist/main-first-time-setup.code.js +2 -2
- package/dist/main-first-time-setup.impl.js +3 -3
- package/dist/main-first-time-setup.js +3 -3
- package/dist/main.js +1 -1
- package/dist/modes/interactive/components/agent-panel.d.ts +1 -0
- package/dist/modes/interactive/components/stored-tree-view.code.js +3 -3
- package/dist/modes/interactive/components/stored-tree-view.impl.js +3 -3
- package/dist/modes/interactive/components/stored-tree-view.js +3 -3
- package/dist/modes/interactive/components/task-inspector.d.ts +2 -0
- package/dist/modes/interactive/components/user-message-selector-archive.code.js +1 -1
- package/dist/modes/interactive/components/user-message-selector-archive.impl.js +3 -3
- package/dist/modes/interactive/components/user-message-selector-archive.js +3 -3
- package/dist/modes/interactive/interactive-mode-helpers.d.ts +2 -2
- package/dist/modes/print-mode.js +1 -1
- package/dist/modes/rpc/agent-panel-bridge.d.ts +5 -0
- package/dist/package-manager-cli.code.js +7 -7
- package/dist/package-manager-cli.impl.js +3 -3
- package/dist/package-manager-cli.js +3 -3
- package/dist/rpc-entry.js +1 -1
- package/dist/startup-files.json +1 -1
- package/dist/startup-stages/0.js +1 -1
- package/dist/startup-stages/1.js +1 -1
- package/dist/startup-stages/10.js +1 -1
- package/dist/startup-stages/12.js +1 -1
- package/dist/startup-stages/2.js +9 -1
- package/dist/startup-stages/3.js +1 -6
- package/dist/startup-stages/5.js +1 -1
- package/dist/startup-stages/7.js +1 -1
- package/dist/startup-stages/8.js +2 -2
- package/dist/utils/startup-database-spare.code.js +3 -3
- package/dist/utils/startup-database-spare.impl.js +3 -3
- package/dist/utils/startup-database-spare.js +3 -3
- package/dist/utils/tools-manager.code.js +1 -1
- package/dist/utils/tools-manager.impl.js +3 -3
- package/dist/utils/tools-manager.js +3 -3
- package/docs/background-tasks.md +123 -23
- package/docs/compaction.md +18 -0
- package/docs/docs.json +2 -0
- package/docs/environment-variables.md +1 -1
- package/docs/getting-started/installation.md +9 -2
- package/docs/guides/postgres-pgbouncer.md +346 -0
- package/docs/guides/postgres-tuning.md +311 -0
- package/docs/guides/resume-on-any-machine.md +2 -2
- package/docs/guides.md +2 -0
- package/docs/index.md +1 -1
- package/docs/libraries/agent-core.md +1 -1
- package/docs/libraries/ai.md +2 -2
- package/docs/libraries/codemode.md +1 -1
- package/docs/libraries/storage-libsql.md +6 -1
- package/docs/libraries/storage-postgres.md +11 -6
- package/docs/libraries/tui.md +1 -1
- package/docs/libraries.md +2 -2
- package/docs/programmatic.md +1 -1
- package/docs/quickstart.md +1 -1
- package/docs/sdk/storage.md +1 -1
- package/docs/sdk/web-server.md +1 -3
- package/docs/sdk.md +1 -7
- package/docs/sessions.md +67 -2
- package/docs/settings.md +20 -1
- package/docs/skills/authoring.md +1 -1
- package/docs/skills.md +79 -6
- package/docs/storage.md +305 -14
- package/docs/subagents/reference.md +2 -2
- package/docs/subagents.md +4 -3
- package/docs/tools.md +44 -10
- package/docs/windows.md +1 -1
- package/package.json +9 -9
- package/dist/_shared/sdk-RRLVN7ER.js.map +0 -1
- package/dist/_shared/settings-startup-4QCVCI53.js.map +0 -1
- package/dist/_shared/startup-0-0-4VG2G44V.js.map +0 -1
- package/dist/_shared/startup-0-1-XTIL65D4.js.map +0 -1
- package/dist/_shared/startup-0-2-27OWFHV6.js.map +0 -1
- package/dist/_shared/startup-0-3-T4DVFYWX.js.map +0 -1
- package/dist/_shared/startup-0-5-FD2P735I.js.map +0 -1
- package/dist/_shared/startup-8-1-4KANEHRA.js.map +0 -1
|
@@ -1,16 +1,16 @@
|
|
|
1
1
|
import { __name } from "./rolldown-runtime-BGM3D5V3.js";
|
|
2
2
|
import { APP_NAME, CONFIG_DIR_NAME, createChildProcessEnvironment, findHelperExecutable, getAgentDir, helperLaunch, helperLaunchAsync, missingHelperOptions, startedWithHangupIgnored, stripBom } from "./p0-cli-BB45ZQY6.js";
|
|
3
|
-
import { CONTINUE_AFTER_FAILURE, DynamicBorder, EventSourceError, FramedSelector, LATEST_PROTOCOL_VERSION, SubscriptionClosedError, SubscriptionConfigError, SubscriptionSetupError, SubscriptionTimeoutError, abortFailure, announceHistoryLoad, applySessionSummaryEntries, bindChatEpoch, blueprintBuildsSettled, boundedChatRecord, canonicalEventBusFor, collectDeclaredDisplaySecrets, decodeChatOrder, decodeChatRecord, encodeChatOrder, extractHeaderSecrets, firstChatOrders, flushRawStdout, hasHistoryLoadObserver, isObject, isSensitiveKeyNameForMasking, materializeSessionSummaryMetadata, nativeForkReader, noteSnapshotGeneration, onBlueprintBuildFinished, onBlueprintBuildWaiting, raceWithAbortSignal, redactAuthorizationUrlForDisplay, redactCredentials, redactOAuthErrorText, redactUrlForDisplay, redactUrlForTransportDisplay, registerArchiveLoad, registerForkScope, registerHistorySnapshot, resolveDecisionDeadlineMs, scrubFetchError, sha256Hex, sharedWakeDispatcher, sliceHead, stripUrlUserinfoAndHash, whenAborted, withinDecisionDeadline, writeRawStdout, yieldTurn } from "./startup-0-0-
|
|
4
|
-
import { CommandDeliveries, SqlSessionSearchIndex, WorkspacePublicationError, collectCommandDeliveries, normalizeModelFailureSignal, reportDiagnostics, requireTimerMs } from "./startup-0-1-
|
|
3
|
+
import { CONTINUE_AFTER_FAILURE, DynamicBorder, EventSourceError, ForkSourceIncompleteError, FramedSelector, LATEST_PROTOCOL_VERSION, SubscriptionClosedError, SubscriptionConfigError, SubscriptionSetupError, SubscriptionTimeoutError, abortFailure, announceHistoryLoad, applySessionSummaryEntries, assertForkSegments, bindChatEpoch, blueprintBuildsSettled, boundedChatRecord, canonicalEventBusFor, collectDeclaredDisplaySecrets, decodeChatOrder, decodeChatRecord, dropStoredNotes, encodeChatOrder, extractHeaderSecrets, firstChatOrders, flushRawStdout, forkRunSegments, forkStoreRelation, hasHistoryLoadObserver, isObject, isSensitiveKeyNameForMasking, materializeSessionSummaryMetadata, nativeForkReader, noteSnapshotGeneration, onBlueprintBuildFinished, onBlueprintBuildWaiting, prefixForkSegments, raceWithAbortSignal, redactAuthorizationUrlForDisplay, redactCredentials, redactOAuthErrorText, redactUrlForDisplay, redactUrlForTransportDisplay, registerArchiveLoad, registerForkScope, registerHistorySnapshot, resolveDecisionDeadlineMs, scrubFetchError, segmentLength, sessionWriteTransaction, sha256Hex, sharedHistorySwitchHost, sharedWakeDispatcher, sliceHead, storedEntryNotes, storedRows, stripUrlUserinfoAndHash, whenAborted, withinDecisionDeadline, writeRawStdout, yieldTurn } from "./startup-0-0-3IXNMFM2.js";
|
|
4
|
+
import { CommandDeliveries, SqlSessionSearchIndex, WorkspacePublicationError, collectCommandDeliveries, normalizeModelFailureSignal, reportDiagnostics, requireTimerMs } from "./startup-0-1-7T2IAE7J.js";
|
|
5
5
|
import { getAvailableThemes, keyHint } from "./p2-shell-main-B2WIALFD.js";
|
|
6
6
|
import { releaseLock, reportDebugAsync, waitForLock } from "./p1b-elig-ENCUPKKJ.js";
|
|
7
|
-
import { FileAuthStorageBackend, ResumePreconditionError, STRUCTURED_OUTPUT_TOOL_NAME, asyncAuthStorageReads, classifyRepository, killTrackedDetachedChildren, markNativeMcpToolDefinition, matchesMcpDirectToolSelection, providerRetryHint } from "./startup-0-2-
|
|
8
|
-
import { CODEMODE_TOOL_NAME, assistantRetryAttempt, runWorkspaceProcess } from "./startup-0-3-
|
|
9
|
-
import { DecisionConfigError, DecisionModelUnavailableError, DecisionOutputError, DecisionProviderError, DecisionRequestError, SESSION_HISTORY_CHUNK_BYTES, SESSION_HISTORY_PAGE_BYTES, entrySizeLimit, isDecisionError, isDecisionProviderError } from "./settings-startup-
|
|
7
|
+
import { FileAuthStorageBackend, ResumePreconditionError, STRUCTURED_OUTPUT_TOOL_NAME, asyncAuthStorageReads, classifyRepository, detachForkChildren, detachForkWithin, isTombstoned, killTrackedDetachedChildren, lockedReferrers, markNativeMcpToolDefinition, matchesMcpDirectToolSelection, noteForkCopyRefusal, providerRetryHint, removeStoredRows, resumeForkDetaches } from "./startup-0-2-5QHPCEON.js";
|
|
8
|
+
import { CODEMODE_TOOL_NAME, assistantRetryAttempt, runWorkspaceProcess } from "./startup-0-3-4ZYBYQNM.js";
|
|
9
|
+
import { DecisionConfigError, DecisionModelUnavailableError, DecisionOutputError, DecisionProviderError, DecisionRequestError, SESSION_HISTORY_CHUNK_BYTES, SESSION_HISTORY_PAGE_BYTES, entrySizeLimit, isDecisionError, isDecisionProviderError } from "./settings-startup-HXQLSUWM.js";
|
|
10
10
|
import { RESUME_UPGRADE_SOURCES, branchRanges, childCatalogCut, foldSessionResume, foreignResumeIds, isSessionResumeIndex, isUpgradableSessionResumeIndex, latestCompactionOf, readEarlierCompletionIntents, selectedPagePlan, sessionResumeFrom, sessionResumePlan, sessionResumeUpgrade, sessionTailFrom, snapshotCutOf, stateSeqsBefore, transcriptBranchSpan, validateSessionEntries, validateSessionHeader, validateSessionText } from "./startup-8-0-34CBHPZH.js";
|
|
11
|
-
import { LIST_MCP_RESOURCES_TOOL, LIST_MCP_RESOURCE_TEMPLATES_TOOL, READ_MCP_RESOURCE_TOOL, TOOL_SEARCH_TOOL_NAME, createMcpResourceToolDefinitions, createMcpToolDefinition, createMcpToolName, createMcpToolRenderers, defaultResumePreflightIo, enablePrintModelSelection, gitUnavailableProblem, hasPrintModelSelection, openWorkspaceRepository, ranOnModelLine, removeRestoredWorktree } from "./startup-0-5-
|
|
11
|
+
import { LIST_MCP_RESOURCES_TOOL, LIST_MCP_RESOURCE_TEMPLATES_TOOL, READ_MCP_RESOURCE_TOOL, TOOL_SEARCH_TOOL_NAME, createMcpResourceToolDefinitions, createMcpToolDefinition, createMcpToolName, createMcpToolRenderers, defaultResumePreflightIo, enablePrintModelSelection, gitUnavailableProblem, hasPrintModelSelection, openWorkspaceRepository, ranOnModelLine, removeRestoredWorktree } from "./startup-0-5-YDW47QX6.js";
|
|
12
12
|
import { assertWorkspaceGitAvailable, formatModelLabel, gitOutput, runWorkspaceGit } from "./startup-0-4-ZMJV547D.js";
|
|
13
|
-
import { SettingsManager, checkoutsNeedingRebuild, inheritedRemotes, isInside, pathExists, resumeStoreDir, savedProjectTrustAsync, setUpResumedBlueprints, settingsFileTarget, settingsFileTargetAsync, writeSettingsFile, writeSettingsFileAsync } from "./startup-8-1-
|
|
13
|
+
import { SettingsManager, checkoutsNeedingRebuild, inheritedRemotes, isInside, pathExists, resumeStoreDir, savedProjectTrustAsync, setUpResumedBlueprints, settingsFileTarget, settingsFileTargetAsync, writeSettingsFile, writeSettingsFileAsync } from "./startup-8-1-X32CYSXB.js";
|
|
14
14
|
import "./startup-15-0-YUKGAC63.js";
|
|
15
15
|
import "./startup-10-0-TDQNBDDL.js";
|
|
16
16
|
import "./p1a-prewarm-XIU57JHF.js";
|
|
@@ -40,11 +40,18 @@ import { publishExtensionContextEffect, registerExtensionContextRetirementEffect
|
|
|
40
40
|
import { Type as Type$1 } from "@bastani/atomic-ai/utils/typebox/index";
|
|
41
41
|
import { ModelRegistry } from "../core/model-registry.js";
|
|
42
42
|
import { dialectOf, postgresJsonb } from "../core/storage/dialect.js";
|
|
43
|
+
import { ensureStorageSchema } from "../core/storage/migrations.js";
|
|
44
|
+
import * as schemaCatalog from "../core/storage/schema-catalog.js";
|
|
45
|
+
import { schemaCatalogOf, withStorageSchemaCatalog } from "../core/storage/schema-catalog.js";
|
|
46
|
+
import * as statementSequence from "../core/storage/statement-sequence.js";
|
|
43
47
|
import { sequenceRunner } from "../core/storage/statement-sequence.js";
|
|
44
48
|
import { createServer } from "node:http";
|
|
45
49
|
import { Check, Errors } from "@bastani/atomic-ai/utils/typebox/value";
|
|
50
|
+
import { forkLinkWrites, legacyForkLinksTriggerName } from "../core/worktree-snapshot/fork-snapshot-index.js";
|
|
51
|
+
import { ensureTableFillfactor, storageSchemaCurrent, transactionFinisher } from "../core/storage/added-exports.js";
|
|
46
52
|
import { assertStorageSchemaVersion, assertStoredSchemaVersion } from "../core/storage/schema.js";
|
|
47
53
|
import { applyStorageMigrationsTogether, statementBatch } from "../core/storage/statement-batches.js";
|
|
54
|
+
import { createSharedHistoryTables, sessionForkTables, sharedHistoryTablesScript } from "../core/storage/session/fork-schema.js";
|
|
48
55
|
import { CLOUDFLARE_GATEWAY_BINDING_AUTH_SENTINEL, createGatewayBindingFetch } from "@bastani/atomic-ai/api/cloudflare-gateway-binding";
|
|
49
56
|
import { configuredSecretRedactor } from "../core/storage/sqlite-facade.js";
|
|
50
57
|
import { oauthErrorHtml, oauthSuccessHtml } from "@bastani/atomic-ai/utils/oauth-page";
|
|
@@ -914,6 +921,531 @@ async function restoreRunWorktree(remotes, restore, options = {}) {
|
|
|
914
921
|
}], options);
|
|
915
922
|
return root;
|
|
916
923
|
}
|
|
924
|
+
// dist/core/storage/added-exports-0-10-11.js
|
|
925
|
+
/**
|
|
926
|
+
* `noteStorageSchemaTables` and `refreshStorageSchemaCatalog` of `schema-catalog.ts`, which the copy 0.10.11-alpha.1
|
|
927
|
+
* loaded lacks, and `MAX_SEQUENCE_REQUEST_STATEMENTS` of `statement-sequence.ts`, which the copies 0.10.3 and 0.10.4's
|
|
928
|
+
* prereleases loaded lack. A process that loaded those copies, or 0.10.11-alpha.1's `added-exports.js`, before an
|
|
929
|
+
* in-place update replaced the installation keeps them, and can load the modules that use these from the update: a
|
|
930
|
+
* named import of any of them would fail to link there, so they take them from here, a path no earlier release has
|
|
931
|
+
* (#6560). With 0.10.11-alpha.1's catalog, which knows nothing of fork tables, an open keeps the catalog it read, as
|
|
932
|
+
* there.
|
|
933
|
+
*/
|
|
934
|
+
const catalogUpdates = schemaCatalog;
|
|
935
|
+
const sequences = statementSequence;
|
|
936
|
+
const noteStorageSchemaTables = catalogUpdates.noteStorageSchemaTables ?? (() => {});
|
|
937
|
+
const refreshStorageSchemaCatalog = catalogUpdates.refreshStorageSchemaCatalog ?? (() => {});
|
|
938
|
+
/** The most statements one request of a sequence carries (#6560). */
|
|
939
|
+
const MAX_SEQUENCE_REQUEST_STATEMENTS = sequences.MAX_SEQUENCE_REQUEST_STATEMENTS ?? 256;
|
|
940
|
+
// dist/core/storage/session/fork-row-copy.js
|
|
941
|
+
/** How many entry IDs a run builder holds for lookups before it sends its runs, bounding what a fork holds. */
|
|
942
|
+
const HELD_RUN_ROWS = 4096;
|
|
943
|
+
/** How many hashes one blob statement names, so a statement stays small whatever the session holds. */
|
|
944
|
+
const BLOB_HASHES_PER_STATEMENT = 256;
|
|
945
|
+
/**
|
|
946
|
+
* The chunk rows `INSERT … SELECT` copies of the entries of session `?` at seqs `?` to `?`: only each entry's chunks 0 to
|
|
947
|
+
* `chunks - 1`, as the copy one chunk at a time did, never a row an older version left past them or at an entry stored
|
|
948
|
+
* whole. `incompleteEntryRead` then finds an entry missing any of those.
|
|
949
|
+
*/
|
|
950
|
+
function entryChunkRows(tables, seqs) {
|
|
951
|
+
return `FROM ${tables.entryChunks} c JOIN ${tables.entries} e ON e.session_id = c.session_id AND e.seq = c.seq WHERE c.session_id = ? AND c.seq ${seqs} AND c.idx >= 0 AND c.idx < e.chunks ORDER BY c.seq, c.idx`;
|
|
952
|
+
}
|
|
953
|
+
/**
|
|
954
|
+
* The source's stored rows a fork copies, gathered into runs of consecutive seqs and copied a run at a time, each run in
|
|
955
|
+
* one `INSERT … SELECT` for its entries and one for their chunks (#6560), not one statement per row and chunk. Rows are
|
|
956
|
+
* copied in seq order, so the snapshot index's triggers meet a parent before its children, as they do for an append.
|
|
957
|
+
*/
|
|
958
|
+
var ForkRowRuns = class {
|
|
959
|
+
tables;
|
|
960
|
+
child;
|
|
961
|
+
source;
|
|
962
|
+
runs = [];
|
|
963
|
+
/** The latest child seq of each entry ID among the rows not sent yet, for the fork's lookups. */
|
|
964
|
+
held = /* @__PURE__ */ new Map();
|
|
965
|
+
heldRows = 0;
|
|
966
|
+
constructor(tables, child, source) {
|
|
967
|
+
this.tables = tables;
|
|
968
|
+
this.child = child;
|
|
969
|
+
this.source = source;
|
|
970
|
+
}
|
|
971
|
+
/** Adds the source row at `sourceSeq` as the child's row at `childSeq`, whose entry ID is `entryId`. */
|
|
972
|
+
add(sourceSeq, childSeq, entryId) {
|
|
973
|
+
const last = this.runs.at(-1);
|
|
974
|
+
if (last !== void 0 && last.sourceFrom + last.count === sourceSeq && last.childFrom + last.count === childSeq) last.count++;
|
|
975
|
+
else this.runs.push({
|
|
976
|
+
sourceFrom: sourceSeq,
|
|
977
|
+
childFrom: childSeq,
|
|
978
|
+
count: 1
|
|
979
|
+
});
|
|
980
|
+
this.held.set(entryId, childSeq);
|
|
981
|
+
this.heldRows++;
|
|
982
|
+
}
|
|
983
|
+
/** The latest child seq of `entryId` among the rows added and not taken yet. */
|
|
984
|
+
heldSeq(entryId) {
|
|
985
|
+
return this.held.get(entryId);
|
|
986
|
+
}
|
|
987
|
+
/** Whether the runs hold as many rows as a fork may hold before it sends them. */
|
|
988
|
+
get full() {
|
|
989
|
+
return this.heldRows >= HELD_RUN_ROWS;
|
|
990
|
+
}
|
|
991
|
+
/**
|
|
992
|
+
* The statements that copy the runs added since the last call, in seq order, each with the rows it must copy: a run's
|
|
993
|
+
* entries statement copies one row for each of its seqs, or the source changed under the fork.
|
|
994
|
+
*/
|
|
995
|
+
drain() {
|
|
996
|
+
const { entries, entryChunks } = this.tables;
|
|
997
|
+
const statements = [];
|
|
998
|
+
for (const { sourceFrom, childFrom, count } of this.runs) {
|
|
999
|
+
const params = [
|
|
1000
|
+
this.child,
|
|
1001
|
+
childFrom - sourceFrom,
|
|
1002
|
+
this.source,
|
|
1003
|
+
sourceFrom,
|
|
1004
|
+
sourceFrom + count - 1
|
|
1005
|
+
];
|
|
1006
|
+
statements.push({
|
|
1007
|
+
sql: `INSERT INTO ${entries} (session_id, seq, entry_id, entry_json, chunks) SELECT ?, seq + ?, entry_id, entry_json, chunks FROM ${entries} WHERE session_id = ? AND seq BETWEEN ? AND ? ORDER BY seq`,
|
|
1008
|
+
params,
|
|
1009
|
+
changes: count,
|
|
1010
|
+
mismatch: () => new SessionConflictError$1(this.source, sourceFrom, sourceFrom + count - 1)
|
|
1011
|
+
}, {
|
|
1012
|
+
sql: `INSERT INTO ${entryChunks} (session_id, seq, idx, data) SELECT ?, c.seq + ?, c.idx, c.data ${entryChunkRows(this.tables, "BETWEEN ? AND ?")}`,
|
|
1013
|
+
params
|
|
1014
|
+
});
|
|
1015
|
+
}
|
|
1016
|
+
this.runs = [];
|
|
1017
|
+
this.held = /* @__PURE__ */ new Map();
|
|
1018
|
+
this.heldRows = 0;
|
|
1019
|
+
return statements;
|
|
1020
|
+
}
|
|
1021
|
+
};
|
|
1022
|
+
/**
|
|
1023
|
+
* The read that finds a stored entry of `child` missing any of its chunks, which the fork checks before it commits: an
|
|
1024
|
+
* entry copied from the source names its chunk count, and the chunks were copied in the same statements. It counts the
|
|
1025
|
+
* entry's chunk rows from 0 to `chunks - 1`, keyed by their index, so a count of `chunks` is each of them.
|
|
1026
|
+
*/
|
|
1027
|
+
function incompleteEntryRead(tables, child) {
|
|
1028
|
+
return {
|
|
1029
|
+
sql: `SELECT e.seq FROM ${tables.entries} e WHERE e.session_id = ? AND e.chunks > 0 AND e.chunks <> (SELECT count(*) FROM ${tables.entryChunks} c WHERE c.session_id = e.session_id AND c.seq = e.seq AND c.idx >= 0 AND c.idx < e.chunks) LIMIT 1`,
|
|
1030
|
+
params: [child]
|
|
1031
|
+
};
|
|
1032
|
+
}
|
|
1033
|
+
/**
|
|
1034
|
+
* Copies the blobs `hashes` of session `source` to `child`, with their chunks, a few statements for all of them (#6560):
|
|
1035
|
+
* as `copyForkBlob` copied each one, a blob the child already holds is kept, one in the legacy one-row layout is copied
|
|
1036
|
+
* only with all its bytes, and each chunk only at its full length.
|
|
1037
|
+
*/
|
|
1038
|
+
function forkBlobCopy(tables, options, source, child, hashes) {
|
|
1039
|
+
const { blobs, blobChunks } = tables;
|
|
1040
|
+
const columns = options.legacyBlobData ? ", data" : "";
|
|
1041
|
+
const sourceColumns = options.legacyBlobData ? ", p.data" : "";
|
|
1042
|
+
const whole = options.legacyBlobData ? " AND (p.chunks <> -1 OR length(p.data) = p.bytes)" : "";
|
|
1043
|
+
const statements = [];
|
|
1044
|
+
const checks = [];
|
|
1045
|
+
const groups = [];
|
|
1046
|
+
for (let start = 0; start < hashes.length; start += BLOB_HASHES_PER_STATEMENT) groups.push(hashes.slice(start, start + BLOB_HASHES_PER_STATEMENT));
|
|
1047
|
+
for (const group of groups) {
|
|
1048
|
+
const named = group.map(() => "?").join(", ");
|
|
1049
|
+
statements.push({
|
|
1050
|
+
sql: `INSERT INTO ${blobs} (session_id, hash, bytes, chunks${columns}) SELECT ?, p.hash, p.bytes, p.chunks${sourceColumns} FROM ${blobs} p WHERE p.session_id = ? AND p.hash IN (${named})${whole} AND NOT EXISTS (SELECT 1 FROM ${blobs} c WHERE c.session_id = ? AND c.hash = p.hash) ORDER BY p.hash`,
|
|
1051
|
+
params: [
|
|
1052
|
+
child,
|
|
1053
|
+
source,
|
|
1054
|
+
...group,
|
|
1055
|
+
child
|
|
1056
|
+
]
|
|
1057
|
+
}, {
|
|
1058
|
+
sql: `INSERT INTO ${blobChunks} (session_id, hash, idx, data) SELECT ?, k.hash, k.idx, k.data FROM ${blobChunks} k JOIN ${blobs} p ON p.session_id = k.session_id AND p.hash = k.hash WHERE k.session_id = ? AND k.hash IN (${named}) AND k.idx < p.chunks AND length(k.data) = CASE WHEN k.idx = p.chunks - 1 THEN p.bytes - k.idx * ? ELSE ? END AND NOT EXISTS (SELECT 1 FROM ${blobChunks} x WHERE x.session_id = ? AND x.hash = k.hash AND x.idx = k.idx) ORDER BY k.hash, k.idx`,
|
|
1059
|
+
params: [
|
|
1060
|
+
child,
|
|
1061
|
+
source,
|
|
1062
|
+
...group,
|
|
1063
|
+
options.chunkBytes,
|
|
1064
|
+
options.chunkBytes,
|
|
1065
|
+
child
|
|
1066
|
+
]
|
|
1067
|
+
});
|
|
1068
|
+
checks.push({
|
|
1069
|
+
sql: `SELECT p.hash, p.bytes, p.chunks, (SELECT count(*) FROM ${blobs} c WHERE c.session_id = ? AND c.hash = p.hash) AS copied, (SELECT count(*) FROM ${blobChunks} k WHERE k.session_id = ? AND k.hash = p.hash) AS parts FROM ${blobs} p WHERE p.session_id = ? AND p.hash IN (${named})`,
|
|
1070
|
+
params: [
|
|
1071
|
+
child,
|
|
1072
|
+
child,
|
|
1073
|
+
source,
|
|
1074
|
+
...group
|
|
1075
|
+
]
|
|
1076
|
+
});
|
|
1077
|
+
}
|
|
1078
|
+
return {
|
|
1079
|
+
statements,
|
|
1080
|
+
checks,
|
|
1081
|
+
remaining(answers) {
|
|
1082
|
+
const held = /* @__PURE__ */ new Set();
|
|
1083
|
+
for (const row of answers.flat()) {
|
|
1084
|
+
const hash = String(row.hash);
|
|
1085
|
+
const bytes = Number(row.bytes);
|
|
1086
|
+
const chunks = Number(row.chunks);
|
|
1087
|
+
if (!(Number(row.copied) === 1 && (chunks < 0 || chunks === Math.ceil(bytes / options.chunkBytes) && Number(row.parts) === chunks))) throw new SessionBlobError("blob-incomplete", {
|
|
1088
|
+
sessionId: source,
|
|
1089
|
+
hash,
|
|
1090
|
+
bytes
|
|
1091
|
+
});
|
|
1092
|
+
held.add(hash);
|
|
1093
|
+
}
|
|
1094
|
+
return hashes.filter((hash) => !held.has(hash));
|
|
1095
|
+
}
|
|
1096
|
+
};
|
|
1097
|
+
}
|
|
1098
|
+
// dist/core/storage/session/fork-lineage.js
|
|
1099
|
+
/** Segment rows one statement inserts at most: six parameters each, well under every backend's parameter limit. */
|
|
1100
|
+
const SEGMENT_ROWS_PER_INSERT = 500;
|
|
1101
|
+
/** Session `sessionId`'s segments, in view order, read through `tx`. None for a session that inherits nothing. */
|
|
1102
|
+
async function readForkSegments(tx, tables, sessionId) {
|
|
1103
|
+
return (await tx.all(`SELECT source_id, from_seq, to_seq, base_seq FROM ${tables.forkSegments} WHERE session_id = ? ORDER BY idx`, sessionId)).map((row) => ({
|
|
1104
|
+
sourceId: String(row.source_id),
|
|
1105
|
+
fromSeq: Number(row.from_seq),
|
|
1106
|
+
toSeq: Number(row.to_seq),
|
|
1107
|
+
baseSeq: Number(row.base_seq)
|
|
1108
|
+
}));
|
|
1109
|
+
}
|
|
1110
|
+
/**
|
|
1111
|
+
* The statements that make `segments` session `sessionId`'s segments, in place of any it had, and give its lineage row a
|
|
1112
|
+
* new generation: with `lineage`, the parent and cut-off a new fork records; without, the row keeps them. Throws unless
|
|
1113
|
+
* `segments` are well formed for a view of `length` seqs. The session's own rows must not sit at a seq they cover:
|
|
1114
|
+
* a view is the rows its segments name and the session's own rows, both read.
|
|
1115
|
+
*/
|
|
1116
|
+
function forkSegmentWrites(tables, sessionId, segments, length, lineage) {
|
|
1117
|
+
assertForkSegments(sessionId, segments, length);
|
|
1118
|
+
return [
|
|
1119
|
+
{
|
|
1120
|
+
sql: `DELETE FROM ${tables.forkSegments} WHERE session_id = ?`,
|
|
1121
|
+
params: [sessionId]
|
|
1122
|
+
},
|
|
1123
|
+
...forkSegmentInserts(tables, sessionId, 0, segments),
|
|
1124
|
+
forkLineageWrite(tables, sessionId, lineage)
|
|
1125
|
+
];
|
|
1126
|
+
}
|
|
1127
|
+
/** The statements that insert `segments` as session `sessionId`'s segments from index `firstIndex` on. */
|
|
1128
|
+
function forkSegmentInserts(tables, sessionId, firstIndex, segments) {
|
|
1129
|
+
const statements = [];
|
|
1130
|
+
for (let start = 0; start < segments.length; start += SEGMENT_ROWS_PER_INSERT) {
|
|
1131
|
+
const batch = segments.slice(start, start + SEGMENT_ROWS_PER_INSERT);
|
|
1132
|
+
statements.push({
|
|
1133
|
+
sql: `INSERT INTO ${tables.forkSegments} (session_id, idx, source_id, from_seq, to_seq, base_seq) VALUES ${batch.map(() => "(?, ?, ?, ?, ?, ?)").join(", ")}`,
|
|
1134
|
+
params: batch.flatMap((segment, index) => [
|
|
1135
|
+
sessionId,
|
|
1136
|
+
firstIndex + start + index,
|
|
1137
|
+
segment.sourceId,
|
|
1138
|
+
segment.fromSeq,
|
|
1139
|
+
segment.toSeq,
|
|
1140
|
+
segment.baseSeq
|
|
1141
|
+
])
|
|
1142
|
+
});
|
|
1143
|
+
}
|
|
1144
|
+
return statements;
|
|
1145
|
+
}
|
|
1146
|
+
/**
|
|
1147
|
+
* The statement that gives session `sessionId`'s lineage row a new generation, as every change to its segments must:
|
|
1148
|
+
* with `lineage`, the parent and cut-off a new fork records; without, the row keeps them.
|
|
1149
|
+
*/
|
|
1150
|
+
function forkLineageWrite(tables, sessionId, lineage) {
|
|
1151
|
+
return {
|
|
1152
|
+
sql: `INSERT INTO ${tables.forkLineage} (session_id, parent_id, cut_seq, generation) VALUES (?, ?, ?, ?)
|
|
1153
|
+
ON CONFLICT(session_id) DO UPDATE SET generation = excluded.generation${lineage === void 0 ? "" : ", parent_id = excluded.parent_id, cut_seq = excluded.cut_seq"}`,
|
|
1154
|
+
params: [
|
|
1155
|
+
sessionId,
|
|
1156
|
+
lineage?.parentId ?? null,
|
|
1157
|
+
lineage?.cutSeq ?? null,
|
|
1158
|
+
crypto.randomUUID()
|
|
1159
|
+
]
|
|
1160
|
+
};
|
|
1161
|
+
}
|
|
1162
|
+
/** Runs {@link forkSegmentWrites} through `tx`. */
|
|
1163
|
+
async function writeForkSegments(tx, tables, sessionId, segments, length, lineage) {
|
|
1164
|
+
for (const { sql, params } of forkSegmentWrites(tables, sessionId, segments, length, lineage)) await tx.run(sql, ...params);
|
|
1165
|
+
}
|
|
1166
|
+
/** The sessions with a segment that names `sourceId`, by id: the forks that read rows `sourceId` stores. */
|
|
1167
|
+
async function forkChildren(tx, tables, sourceId) {
|
|
1168
|
+
return (await tx.all(`SELECT DISTINCT session_id FROM ${tables.forkSegments} WHERE source_id = ? ORDER BY session_id`, sourceId)).map((row) => String(row.session_id));
|
|
1169
|
+
}
|
|
1170
|
+
/**
|
|
1171
|
+
* Locks the sessions rows of `ids`, in id order so that two transactions never wait for each other: `key-share` keeps
|
|
1172
|
+
* them from being deleted or locked `update` while the transaction lasts, as a fork that names them in its segments
|
|
1173
|
+
* needs; `update` excludes those. Nothing on SQLite, whose write transactions already run one at a time.
|
|
1174
|
+
*/
|
|
1175
|
+
async function lockForkSources(tx, dialect, tables, ids, mode) {
|
|
1176
|
+
const sorted = [...new Set(ids)].sort();
|
|
1177
|
+
if (dialect.name === "sqlite" || sorted.length === 0) return;
|
|
1178
|
+
await tx.all(`SELECT id FROM ${tables.sessions} WHERE id IN (${sorted.map(() => "?").join(", ")}) ORDER BY id${dialect.lockClause(mode)}`, ...sorted);
|
|
1179
|
+
}
|
|
1180
|
+
/**
|
|
1181
|
+
* The segments of a fork that shares its parent's history, gathered as the fork's rows stream past (#6560): each row the
|
|
1182
|
+
* parent stores unchanged extends a run of the parent's view, and `drain` composes the runs gathered since the last
|
|
1183
|
+
* one with the parent's own segments, so that each segment names the session that stores its rows, and returns the
|
|
1184
|
+
* statements that insert them. Drain before the fork writes a row of its own, so that its segments come first in seq
|
|
1185
|
+
* order. `heldSeq` answers for the rows of runs not yet drained.
|
|
1186
|
+
*/
|
|
1187
|
+
var ForkSegmentRuns = class {
|
|
1188
|
+
segments = [];
|
|
1189
|
+
runs = [];
|
|
1190
|
+
held = /* @__PURE__ */ new Map();
|
|
1191
|
+
tables;
|
|
1192
|
+
child;
|
|
1193
|
+
parent;
|
|
1194
|
+
constructor(tables, child, parent) {
|
|
1195
|
+
this.tables = tables;
|
|
1196
|
+
this.child = child;
|
|
1197
|
+
this.parent = parent;
|
|
1198
|
+
}
|
|
1199
|
+
/** The parent's row at view seq `parentSeq` is the child's row at `childSeq`, entry `id`. */
|
|
1200
|
+
add(parentSeq, childSeq, id) {
|
|
1201
|
+
const run = this.runs.at(-1);
|
|
1202
|
+
if (run && parentSeq === run.toSeq + 1 && childSeq === run.baseSeq + (run.toSeq - run.fromSeq) + 2) run.toSeq++;
|
|
1203
|
+
else this.runs.push({
|
|
1204
|
+
fromSeq: parentSeq,
|
|
1205
|
+
toSeq: parentSeq,
|
|
1206
|
+
baseSeq: childSeq - 1
|
|
1207
|
+
});
|
|
1208
|
+
this.held.set(id, childSeq);
|
|
1209
|
+
}
|
|
1210
|
+
/** The child seq of entry `id` among the rows not yet drained, the latest when several hold it. */
|
|
1211
|
+
heldSeq(id) {
|
|
1212
|
+
return this.held.get(id);
|
|
1213
|
+
}
|
|
1214
|
+
/** Whether enough rows wait that they should be drained before more are added. */
|
|
1215
|
+
get full() {
|
|
1216
|
+
return this.held.size >= 8192;
|
|
1217
|
+
}
|
|
1218
|
+
/** The statements that insert the segments of the runs gathered since the last drain. */
|
|
1219
|
+
drain() {
|
|
1220
|
+
if (this.runs.length === 0) return [];
|
|
1221
|
+
const composed = this.runs.flatMap((run) => forkRunSegments(this.parent.id, this.parent.segments, this.parent.length, run));
|
|
1222
|
+
const first = this.segments.length;
|
|
1223
|
+
this.segments.push(...composed);
|
|
1224
|
+
this.runs.length = 0;
|
|
1225
|
+
this.held.clear();
|
|
1226
|
+
return forkSegmentInserts(this.tables, this.child, first, composed);
|
|
1227
|
+
}
|
|
1228
|
+
};
|
|
1229
|
+
/**
|
|
1230
|
+
* `segments` without the view seqs `pieces` cover: each piece must lie within one segment, naming the same rows of the
|
|
1231
|
+
* same source. Throws otherwise.
|
|
1232
|
+
*/
|
|
1233
|
+
function withoutForkPieces(segments, pieces) {
|
|
1234
|
+
const end = (segment) => segment.baseSeq + segmentLength(segment);
|
|
1235
|
+
const remaining = [];
|
|
1236
|
+
for (const segment of segments) {
|
|
1237
|
+
const inside = pieces.filter((piece) => piece.baseSeq >= segment.baseSeq && end(piece) <= end(segment) && piece.sourceId === segment.sourceId).sort((a, b) => a.baseSeq - b.baseSeq);
|
|
1238
|
+
let view = segment.baseSeq;
|
|
1239
|
+
for (const piece of inside) {
|
|
1240
|
+
if (piece.fromSeq - piece.baseSeq !== segment.fromSeq - segment.baseSeq || piece.baseSeq < view) throw new RangeError(`Fork piece ${JSON.stringify(piece)} does not lie within ${JSON.stringify(segment)}`);
|
|
1241
|
+
if (piece.baseSeq > view) remaining.push({
|
|
1242
|
+
...segment,
|
|
1243
|
+
fromSeq: segment.fromSeq + (view - segment.baseSeq),
|
|
1244
|
+
toSeq: piece.fromSeq - 1,
|
|
1245
|
+
baseSeq: view
|
|
1246
|
+
});
|
|
1247
|
+
view = end(piece);
|
|
1248
|
+
}
|
|
1249
|
+
if (view < end(segment)) remaining.push({
|
|
1250
|
+
...segment,
|
|
1251
|
+
fromSeq: segment.fromSeq + (view - segment.baseSeq),
|
|
1252
|
+
baseSeq: view
|
|
1253
|
+
});
|
|
1254
|
+
}
|
|
1255
|
+
const covered = pieces.reduce((sum, piece) => sum + segmentLength(piece), 0);
|
|
1256
|
+
if (segments.reduce((sum, segment) => sum + segmentLength(segment), 0) - remaining.reduce((sum, segment) => sum + segmentLength(segment), 0) !== covered) throw new RangeError("Fork pieces overlap or lie outside the fork's segments");
|
|
1257
|
+
return remaining;
|
|
1258
|
+
}
|
|
1259
|
+
/** The first seq of `piece` whose entry its source lacks, or holds without one of its chunks: why its copy was refused. */
|
|
1260
|
+
async function firstIncomplete(tx, tables, piece) {
|
|
1261
|
+
const rows = await tx.all(`SELECT e.seq, e.chunks, (SELECT count(*) FROM ${tables.entryChunks} c WHERE c.session_id = e.session_id AND c.seq = e.seq AND c.idx >= 0 AND c.idx < e.chunks) AS held FROM ${tables.entries} e WHERE e.session_id = ? AND e.seq BETWEEN ? AND ? ORDER BY e.seq`, piece.sourceId, piece.fromSeq, piece.toSeq);
|
|
1262
|
+
let expected = piece.fromSeq;
|
|
1263
|
+
for (const row of rows) {
|
|
1264
|
+
if (Number(row.seq) !== expected || Number(row.chunks) > 0 && Number(row.held) !== Number(row.chunks)) return expected;
|
|
1265
|
+
expected++;
|
|
1266
|
+
}
|
|
1267
|
+
return expected;
|
|
1268
|
+
}
|
|
1269
|
+
/**
|
|
1270
|
+
* Copies into session `childId`, a fork that shares history, the rows `pieces` of its segments name, with their chunks,
|
|
1271
|
+
* search texts and the blobs their tool outputs name, and links them in the snapshot index with `links` (see
|
|
1272
|
+
* `materializedForkLinks`), a statement a piece, then writes its segments without them, with a new generation, so
|
|
1273
|
+
* its view stays as it was at every commit (#6560). Each piece lies within one of the child's segments: a sub-range of
|
|
1274
|
+
* it, or all of it. The caller holds the child's row locked `update`, and the sources' rows locked, so neither its
|
|
1275
|
+
* segments nor the rows they name change meanwhile; `length` is the child's last seq.
|
|
1276
|
+
*/
|
|
1277
|
+
async function materializeForkSegments(tx, dialect, tables, blobs, links, childId, length, pieces) {
|
|
1278
|
+
const remaining = withoutForkPieces(await readForkSegments(tx, tables, childId), pieces);
|
|
1279
|
+
const text = (...path) => dialect.jsonText("entry_json", ...path);
|
|
1280
|
+
for (const piece of [...pieces].sort((a, b) => a.baseSeq - b.baseSeq)) {
|
|
1281
|
+
const shift = piece.baseSeq - piece.fromSeq + 1;
|
|
1282
|
+
const range = [
|
|
1283
|
+
piece.sourceId,
|
|
1284
|
+
piece.fromSeq,
|
|
1285
|
+
piece.toSeq
|
|
1286
|
+
];
|
|
1287
|
+
const copied = await tx.run(`INSERT INTO ${tables.entries} (session_id, seq, entry_id, entry_json, chunks) SELECT ?, e.seq + ?, e.entry_id, e.entry_json, e.chunks FROM ${tables.entries} e WHERE e.session_id = ? AND e.seq BETWEEN ? AND ? AND (e.chunks = 0 OR e.chunks = (SELECT count(*) FROM ${tables.entryChunks} c WHERE c.session_id = e.session_id AND c.seq = e.seq AND c.idx >= 0 AND c.idx < e.chunks)) ORDER BY e.seq`, childId, shift, ...range);
|
|
1288
|
+
if (Number(copied.changes) !== segmentLength(piece)) throw new ForkSourceIncompleteError(childId, piece.sourceId, await firstIncomplete(tx, tables, piece));
|
|
1289
|
+
await Promise.all([tx.run(links, childId, shift, ...range, childId), tx.run(`INSERT INTO ${tables.entryChunks} (session_id, seq, idx, data) SELECT ?, c.seq + ?, c.idx, c.data FROM ${tables.entryChunks} c JOIN ${tables.entries} e ON e.session_id = c.session_id AND e.seq = c.seq WHERE c.session_id = ? AND c.seq BETWEEN ? AND ? AND c.idx >= 0 AND c.idx < e.chunks ORDER BY c.seq, c.idx`, childId, shift, ...range)]);
|
|
1290
|
+
await tx.run(`INSERT INTO ${tables.searchTexts} (session_id, seq, text_json) SELECT ?, seq + ?, text_json FROM ${tables.searchTexts} WHERE session_id = ? AND seq BETWEEN ? AND ? ORDER BY seq`, childId, shift, ...range);
|
|
1291
|
+
const named = await tx.all(`SELECT DISTINCT ${text("data", "hash")} AS hash FROM ${tables.entries} WHERE session_id = ? AND seq BETWEEN ? AND ?
|
|
1292
|
+
AND chunks = 0 AND ${text("type")} = 'custom' AND ${text("customType")} = 'atomic.tool-output' AND ${text("data", "hash")} IS NOT NULL`, ...range);
|
|
1293
|
+
const copy = forkBlobCopy(tables, blobs, piece.sourceId, childId, named.map((row) => String(row.hash)));
|
|
1294
|
+
for (const { sql, params } of copy.statements) await tx.run(sql, ...params);
|
|
1295
|
+
const answers = [];
|
|
1296
|
+
for (const { sql, params } of copy.checks) answers.push(await tx.all(sql, ...params));
|
|
1297
|
+
copy.remaining(answers);
|
|
1298
|
+
}
|
|
1299
|
+
await writeForkSegments(tx, tables, childId, remaining, length);
|
|
1300
|
+
}
|
|
1301
|
+
// dist/core/storage/session/fork-detach-host.js
|
|
1302
|
+
/**
|
|
1303
|
+
* The SQL session store's side of detaching and pinning shared fork history (#6560): its fork segments, read and
|
|
1304
|
+
* written through fork-lineage.ts, in transactions of the store.
|
|
1305
|
+
*/
|
|
1306
|
+
/** The fork host of a store whose sessions schema has shared-history forks. */
|
|
1307
|
+
function forkDetachHost(store) {
|
|
1308
|
+
const { dialect, tables, forkTables } = store;
|
|
1309
|
+
const lineage = {
|
|
1310
|
+
sessions: tables.sessions,
|
|
1311
|
+
forkSegments: forkTables.forkSegments,
|
|
1312
|
+
forkLineage: forkTables.forkLineage
|
|
1313
|
+
};
|
|
1314
|
+
const materialize = {
|
|
1315
|
+
...tables,
|
|
1316
|
+
...lineage
|
|
1317
|
+
};
|
|
1318
|
+
/** A session's last seq: the length of its view. A deleted session's tombstone has no row, and no view to keep. */
|
|
1319
|
+
const length = async (tx, sessionId) => {
|
|
1320
|
+
const row = await tx.get(`SELECT last_seq FROM ${tables.sessions} WHERE id = ?`, sessionId);
|
|
1321
|
+
return row === void 0 ? 0 : Number(row.last_seq);
|
|
1322
|
+
};
|
|
1323
|
+
return {
|
|
1324
|
+
forkDetachTable: forkTables.forkDetach,
|
|
1325
|
+
pinTables: {
|
|
1326
|
+
entries: tables.entries,
|
|
1327
|
+
entryChunks: tables.entryChunks,
|
|
1328
|
+
searchTexts: tables.searchTexts,
|
|
1329
|
+
blobs: tables.blobs,
|
|
1330
|
+
blobChunks: tables.blobChunks,
|
|
1331
|
+
tombstones: forkTables.forkTombstones,
|
|
1332
|
+
forkSegments: forkTables.forkSegments,
|
|
1333
|
+
forkLineage: forkTables.forkLineage
|
|
1334
|
+
},
|
|
1335
|
+
forkTransaction: (body) => store.transaction(body),
|
|
1336
|
+
lockClause: (mode) => dialect.lockClause(mode),
|
|
1337
|
+
forkSegments: (tx, sessionId) => readForkSegments(tx, lineage, sessionId),
|
|
1338
|
+
forkChildren: (tx, sourceId) => forkChildren(tx, lineage, sourceId),
|
|
1339
|
+
async materializeForkSegments(tx, childId, pieces) {
|
|
1340
|
+
await materializeForkSegments(tx, dialect, materialize, store.blobs, store.materializedLinks, childId, await length(tx, childId), pieces);
|
|
1341
|
+
},
|
|
1342
|
+
async writeForkSegments(tx, sessionId, segments) {
|
|
1343
|
+
if (segments.length > 0 || (await readForkSegments(tx, lineage, sessionId)).length > 0) await writeForkSegments(tx, lineage, sessionId, segments, await length(tx, sessionId));
|
|
1344
|
+
},
|
|
1345
|
+
async lockForkSources(tx, ids, mode) {
|
|
1346
|
+
await lockForkSources(tx, dialect, lineage, ids, mode);
|
|
1347
|
+
const sorted = [...new Set(ids)].sort();
|
|
1348
|
+
if (dialect.name !== "sqlite" && sorted.length > 0) await tx.all(`SELECT session_id FROM ${forkTables.forkTombstones} WHERE session_id IN (${sorted.map(() => "?").join(", ")}) ORDER BY session_id${dialect.lockClause(mode)}`, ...sorted);
|
|
1349
|
+
},
|
|
1350
|
+
async forkRewriteEpoch(tx, sessionId) {
|
|
1351
|
+
return (await tx.get(`SELECT COALESCE(${dialect.jsonText("summary_state", "epoch")}, ${dialect.jsonText("summary_state", "resume", "epoch")}) AS epoch FROM ${tables.sessions} WHERE id = ?`, sessionId))?.epoch ?? void 0;
|
|
1352
|
+
}
|
|
1353
|
+
};
|
|
1354
|
+
}
|
|
1355
|
+
// dist/core/storage/session/fork-pins.js
|
|
1356
|
+
/**
|
|
1357
|
+
* What deleting, replacing and re-creating a session does when forks read rows it stores. A fork's segments name the
|
|
1358
|
+
* session that stores each row it inherited, so those rows stay for as long as any segment names them:
|
|
1359
|
+
*
|
|
1360
|
+
* - Deleting a session that forks still read removes it from every read (its sessions row and its search texts go)
|
|
1361
|
+
* but keeps the rows they read, its entries, entry chunks and blobs, under a tombstone. The rows go with the
|
|
1362
|
+
* tombstone once nothing names them any more: when the last fork reading them is deleted, replaced or detached.
|
|
1363
|
+
* - Replacing a session that forks still read first gives each of them its own copy of the rows it read (detach),
|
|
1364
|
+
* since the replace deletes those rows.
|
|
1365
|
+
* - Creating a session under the ID of a tombstone first detaches the forks that still read the old rows, then removes
|
|
1366
|
+
* them, so the new session starts empty.
|
|
1367
|
+
*
|
|
1368
|
+
* A session's own segments go when it is deleted or replaced, which may leave a deleted source no fork reads; the caller
|
|
1369
|
+
* sweeps it once its transaction commits (fork-sweep.ts). A delete and a replace lock the session's row for update
|
|
1370
|
+
* before they read anything of its fork history, as the first read of their transaction ({@link forkPinReads}), so
|
|
1371
|
+
* they drop its own segments and list the forks that name it only under that lock. A fork locks every session its
|
|
1372
|
+
* segments name for key share, tombstones included, so a fork being made either commits first and is listed, or waits
|
|
1373
|
+
* and finds the session gone.
|
|
1374
|
+
*/
|
|
1375
|
+
/**
|
|
1376
|
+
* The statements a delete or a replace of `sessionId` reads its fork history with, as the first reads of its
|
|
1377
|
+
* transaction: where writers can run together, the session's row, locked for update so that no fork of it starts
|
|
1378
|
+
* meanwhile, then the listing. Sent with the transaction's start, they cost no round trip of their own.
|
|
1379
|
+
*/
|
|
1380
|
+
function forkPinReads(host, sessions, sessionId) {
|
|
1381
|
+
const { forkSegments, forkLineage } = host.pinTables;
|
|
1382
|
+
const lock = host.lockClause("update");
|
|
1383
|
+
return [...lock === "" ? [] : [{
|
|
1384
|
+
sql: `SELECT id FROM ${sessions} WHERE id = ?${lock}`,
|
|
1385
|
+
params: [sessionId]
|
|
1386
|
+
}], {
|
|
1387
|
+
sql: `SELECT 's' AS kind, source_id AS id FROM ${forkSegments} WHERE session_id = ?
|
|
1388
|
+
UNION SELECT 'r', session_id FROM ${forkSegments} WHERE source_id = ? AND session_id <> ?
|
|
1389
|
+
UNION SELECT 'l', session_id FROM ${forkLineage} WHERE session_id = ?`,
|
|
1390
|
+
params: [
|
|
1391
|
+
sessionId,
|
|
1392
|
+
sessionId,
|
|
1393
|
+
sessionId,
|
|
1394
|
+
sessionId
|
|
1395
|
+
]
|
|
1396
|
+
}];
|
|
1397
|
+
}
|
|
1398
|
+
/** Reads `sessionId`'s fork history through the statements of {@link forkPinReads}, in order. */
|
|
1399
|
+
async function readForkPins(tx, reads) {
|
|
1400
|
+
const listing = reads.at(-1);
|
|
1401
|
+
for (const lock of reads.slice(0, -1)) await tx.get(lock.sql, ...lock.params);
|
|
1402
|
+
const rows = await tx.all(listing.sql, ...listing.params);
|
|
1403
|
+
const of = (kind) => [...new Set(rows.filter((row) => row.kind === kind).map((row) => String(row.id)))].sort();
|
|
1404
|
+
return {
|
|
1405
|
+
sources: of("s"),
|
|
1406
|
+
readers: of("r"),
|
|
1407
|
+
lineage: rows.some((row) => row.kind === "l")
|
|
1408
|
+
};
|
|
1409
|
+
}
|
|
1410
|
+
/**
|
|
1411
|
+
* In `delete`'s transaction, before the session's rows go, given what {@link readForkPins} read. `keepRows` when forks
|
|
1412
|
+
* still read rows the session stores: the caller then removes only its sessions row, and the rows stay under a
|
|
1413
|
+
* tombstone. `released` are the sources the session's own segments named, to sweep once the transaction commits. A
|
|
1414
|
+
* session no fork history names costs no statement.
|
|
1415
|
+
*/
|
|
1416
|
+
async function deleteForkedSessionWithin(host, tx, sessionId, deletedAt, pins) {
|
|
1417
|
+
if (pins.sources.length > 0) await tx.run(`DELETE FROM ${host.pinTables.forkSegments} WHERE session_id = ?`, sessionId);
|
|
1418
|
+
if (pins.lineage) await tx.run(`DELETE FROM ${host.pinTables.forkLineage} WHERE session_id = ?`, sessionId);
|
|
1419
|
+
if (pins.readers.length === 0) return {
|
|
1420
|
+
keepRows: false,
|
|
1421
|
+
released: pins.sources
|
|
1422
|
+
};
|
|
1423
|
+
await tx.run(`INSERT INTO ${host.pinTables.tombstones} (session_id, deleted_at) VALUES (?, ?) ON CONFLICT DO NOTHING`, sessionId, deletedAt);
|
|
1424
|
+
return {
|
|
1425
|
+
keepRows: true,
|
|
1426
|
+
released: pins.sources
|
|
1427
|
+
};
|
|
1428
|
+
}
|
|
1429
|
+
/**
|
|
1430
|
+
* In `replace`'s transaction, before the session's rows go, given what {@link readForkPins} read: each fork reading
|
|
1431
|
+
* them gets its own copy, and the session drops its own segments, as a replaced session holds every row of its view
|
|
1432
|
+
* itself. Resolves with the sources those segments named, to sweep once the transaction commits. A session no fork
|
|
1433
|
+
* history names costs no statement.
|
|
1434
|
+
*/
|
|
1435
|
+
async function replaceForkedSessionWithin(host, tx, sessionId, pins) {
|
|
1436
|
+
if (pins.sources.length > 0) await host.writeForkSegments(tx, sessionId, []);
|
|
1437
|
+
for (const child of pins.readers) await detachForkWithin(host, tx, sessionId, child, false);
|
|
1438
|
+
return pins.sources;
|
|
1439
|
+
}
|
|
1440
|
+
/**
|
|
1441
|
+
* In `create`'s transaction, before the session is written: when a deleted session with this ID left a tombstone,
|
|
1442
|
+
* the forks still reading its rows get their own copy, and the rows go.
|
|
1443
|
+
*/
|
|
1444
|
+
async function createOverTombstoneWithin(host, tx, sessionId) {
|
|
1445
|
+
if (!await isTombstoned(host, tx, sessionId)) return;
|
|
1446
|
+
for (const child of await lockedReferrers(host, tx, sessionId)) await detachForkWithin(host, tx, sessionId, child, false);
|
|
1447
|
+
await removeStoredRows(host, tx, sessionId);
|
|
1448
|
+
}
|
|
917
1449
|
/** Never load the clone writer in an ordinary open. Fence a lapsed transfer before deleting so a paused donor
|
|
918
1450
|
* cannot publish a partially swept transfer. When more rows remain, the new token stays expired. */
|
|
919
1451
|
async function tryCleanupForkStaging(database, dialect, table) {
|
|
@@ -929,6 +1461,90 @@ async function tryCleanupForkStaging(database, dialect, table) {
|
|
|
929
1461
|
if ((await tx.run(`DELETE FROM ${table} WHERE transfer_id=? AND kind>${lease} AND (kind,seq,idx) IN (SELECT kind,seq,idx FROM ${table} WHERE transfer_id=? AND kind>${lease} LIMIT ?)`, id, id, 32)).changes < 32) await tx.run(`DELETE FROM ${table} WHERE transfer_id=? AND kind=${lease}`, id);
|
|
930
1462
|
});
|
|
931
1463
|
}
|
|
1464
|
+
// dist/core/storage/session/fork-view.js
|
|
1465
|
+
/** The largest view seq a range reads when it has no upper bound. */
|
|
1466
|
+
const FORK_VIEW_END = Number.MAX_SAFE_INTEGER;
|
|
1467
|
+
/**
|
|
1468
|
+
* The common table expression `name`: session `sessionId`'s rows of `table`, a table keyed by `(session_id, seq)` and
|
|
1469
|
+
* maybe more, whose view seqs are after `after` and at most `through`, with `columns` and `session_id`, `seq`, `src_id`
|
|
1470
|
+
* and `src_seq`. Bounding the range lets each source's index read only the rows asked for.
|
|
1471
|
+
*/
|
|
1472
|
+
function forkView(tables, view) {
|
|
1473
|
+
const { name, table, sessionId, after, through, match } = view;
|
|
1474
|
+
const int = tables.dialect.types.int;
|
|
1475
|
+
const guard = tables.guard === void 0 ? "" : ` AND ${tables.guard}`;
|
|
1476
|
+
const matching = (alias) => match === void 0 ? "" : ` AND ${alias}${match.column} = ?`;
|
|
1477
|
+
const matched = match === void 0 ? [] : [match.value];
|
|
1478
|
+
const own = `SELECT session_id, seq${view.columns.map((column) => `, ${column}`).join("")}, session_id AS src_id, seq AS src_seq
|
|
1479
|
+
FROM ${table} WHERE session_id = ? AND seq > CAST(? AS ${int}) AND seq <= CAST(? AS ${int})${matching("")}${guard}`;
|
|
1480
|
+
if (tables.segments === void 0) return {
|
|
1481
|
+
cte: `${name} AS NOT MATERIALIZED (${own})`,
|
|
1482
|
+
params: [
|
|
1483
|
+
sessionId,
|
|
1484
|
+
after,
|
|
1485
|
+
through,
|
|
1486
|
+
...matched
|
|
1487
|
+
]
|
|
1488
|
+
};
|
|
1489
|
+
const { greatest, least } = tables.dialect;
|
|
1490
|
+
const rows = sourceRows(tables, table, view.columns, (x) => `${x}.seq >= ${greatest("f.from_seq", `CAST(? AS ${int}) + f.from_seq - f.base_seq`)}
|
|
1491
|
+
AND ${x}.seq <= ${least("f.to_seq", `CAST(? AS ${int}) + f.from_seq - f.base_seq - 1`)}${matching(`${x}.`)}`);
|
|
1492
|
+
return {
|
|
1493
|
+
cte: `${name} AS NOT MATERIALIZED (${`SELECT f.session_id AS session_id, f.base_seq + (x.seq - f.from_seq) + 1 AS seq${view.columns.map((column) => `, x.${column} AS ${column}`).join("")}, x.session_id AS src_id, x.seq AS src_seq
|
|
1494
|
+
FROM ${rows}
|
|
1495
|
+
WHERE f.session_id = ? AND f.base_seq < CAST(? AS ${int})
|
|
1496
|
+
AND f.base_seq + (f.to_seq - f.from_seq) + 1 > CAST(? AS ${int})${guard}`} UNION ALL ${own})`,
|
|
1497
|
+
params: [
|
|
1498
|
+
after,
|
|
1499
|
+
through,
|
|
1500
|
+
...matched,
|
|
1501
|
+
sessionId,
|
|
1502
|
+
through,
|
|
1503
|
+
after,
|
|
1504
|
+
sessionId,
|
|
1505
|
+
after,
|
|
1506
|
+
through,
|
|
1507
|
+
...matched
|
|
1508
|
+
]
|
|
1509
|
+
};
|
|
1510
|
+
}
|
|
1511
|
+
/**
|
|
1512
|
+
* The segments `f` joined with the rows `x` of `table` each names that hold to `condition`, of the rows' alias and
|
|
1513
|
+
* `f`. On PostgreSQL the rows are read per segment through the table's index, as a lateral subquery
|
|
1514
|
+
* behind `OFFSET 0`, rather than by a hash join that would read the whole table; SQLite joins them that way itself.
|
|
1515
|
+
*/
|
|
1516
|
+
function sourceRows(tables, table, columns, condition) {
|
|
1517
|
+
if (tables.dialect.name !== "postgres") return `${tables.segments} f JOIN ${table} x ON x.session_id = f.source_id AND ${condition("x")}`;
|
|
1518
|
+
return `${tables.segments} f CROSS JOIN LATERAL (SELECT r.session_id, r.seq${columns.map((column) => `, r.${column}`).join("")}
|
|
1519
|
+
FROM ${table} r WHERE r.session_id = f.source_id AND ${condition("r")} OFFSET 0) x`;
|
|
1520
|
+
}
|
|
1521
|
+
/**
|
|
1522
|
+
* The rows of `table` through the view of the session that `session`, an SQL expression such as a column of an outer
|
|
1523
|
+
* query, names: a derived table with `columns`, `session_id` and `seq`, and no parameters, for a statement that reads
|
|
1524
|
+
* the rows of many sessions, each in a subquery of its own. Each half of the union looks the session up by its key
|
|
1525
|
+
* itself, so neither reads the rows of every session to find one's.
|
|
1526
|
+
*/
|
|
1527
|
+
function forkViewOf(tables, view, session) {
|
|
1528
|
+
const { table } = view;
|
|
1529
|
+
const guard = tables.guard === void 0 ? "" : ` AND ${tables.guard}`;
|
|
1530
|
+
const own = `SELECT session_id, seq${view.columns.map((column) => `, ${column}`).join("")} FROM ${table} WHERE session_id = ${session}${guard}`;
|
|
1531
|
+
if (tables.segments === void 0) return `(${own})`;
|
|
1532
|
+
return `(SELECT f.session_id AS session_id, f.base_seq + (x.seq - f.from_seq) + 1 AS seq${view.columns.map((column) => `, x.${column} AS ${column}`).join("")}
|
|
1533
|
+
FROM ${sourceRows(tables, table, view.columns, (x) => `${x}.seq >= f.from_seq AND ${x}.seq <= f.to_seq`)}
|
|
1534
|
+
WHERE f.session_id = ${session}${guard}
|
|
1535
|
+
UNION ALL ${own})`;
|
|
1536
|
+
}
|
|
1537
|
+
/** `sql`, a statement that may begin with `WITH`, with `views` first in its `WITH`. */
|
|
1538
|
+
function withForkViews(views, sql) {
|
|
1539
|
+
if (views.length === 0) return sql;
|
|
1540
|
+
const ctes = views.map((view) => view.cte).join(", ");
|
|
1541
|
+
const body = sql.trimStart();
|
|
1542
|
+
return /^WITH\s/i.test(body) ? `WITH ${ctes}, ${body.slice(4).trimStart()}` : `WITH ${ctes} ${body}`;
|
|
1543
|
+
}
|
|
1544
|
+
/** The parameters of `views`, in order, for the start of the statement's parameters. */
|
|
1545
|
+
function forkViewParams(views) {
|
|
1546
|
+
return views.flatMap((view) => view.params);
|
|
1547
|
+
}
|
|
932
1548
|
// dist/core/storage/session/sql-chat-records.js
|
|
933
1549
|
/** Rows one read fetches at most. */
|
|
934
1550
|
const READ_PAGE_ROWS = 64;
|
|
@@ -946,23 +1562,42 @@ const ORDER_BATCH = 128;
|
|
|
946
1562
|
const lineKey = (anchor) => `L${anchor}`;
|
|
947
1563
|
const orderKey = (promptId) => `O${promptId}`;
|
|
948
1564
|
/**
|
|
949
|
-
*
|
|
950
|
-
*
|
|
951
|
-
*
|
|
952
|
-
*
|
|
1565
|
+
* The schema's setup runs in a transaction of its own, on the session writer's connection and in its order. A statement
|
|
1566
|
+
* outside a transaction would wait for another process's write lock in node:sqlite's busy handler, which blocks the
|
|
1567
|
+
* event loop for up to the busy timeout (#5682); a transaction waits for the lock without blocking it. A transient
|
|
1568
|
+
* failure runs it again, as one statement outside a transaction would. Each record's write does the same, as a write
|
|
1569
|
+
* of its session's rows (`sessionWriteTransaction`).
|
|
953
1570
|
*/
|
|
954
1571
|
const SIDE_WRITE = { retryTransientFailures: true };
|
|
955
|
-
/**
|
|
956
|
-
|
|
1572
|
+
/** The chat records' name in the storage ledger: `atomic storage migrate` sets them up as the owner role. */
|
|
1573
|
+
const SESSION_CHAT_DOMAIN = "session-chat";
|
|
1574
|
+
/** The revision of the chat records' table and index: raise it whenever their setup creates anything new. */
|
|
1575
|
+
const SESSION_CHAT_REVISION = 1;
|
|
1576
|
+
/**
|
|
1577
|
+
* A new physical table per format version; the main sessions schema (and all its old readers) stay unchanged. `ledger`
|
|
1578
|
+
* is the prefix's storage ledger, which records the table and index once set up, so a runtime role without DDL
|
|
1579
|
+
* privileges runs no DDL once the owner created them.
|
|
1580
|
+
*/
|
|
1581
|
+
function sqlChatRecords(database, sessions, table, index, ledger) {
|
|
957
1582
|
const dialect = dialectOf(database);
|
|
1583
|
+
const schema = {
|
|
1584
|
+
ledger,
|
|
1585
|
+
domain: SESSION_CHAT_DOMAIN,
|
|
1586
|
+
revision: SESSION_CHAT_REVISION
|
|
1587
|
+
};
|
|
958
1588
|
let initialized;
|
|
959
1589
|
function initialize() {
|
|
960
|
-
const create =
|
|
961
|
-
await
|
|
1590
|
+
const create = async () => {
|
|
1591
|
+
if (await withStorageSchemaCatalog(database, ledger, () => storageSchemaCurrent(database, schema))) return;
|
|
1592
|
+
await database.transaction((tx) => ensureStorageSchema(tx, dialect, schema, async () => {
|
|
1593
|
+
const probe = dialect.schemaObjects([table, index]);
|
|
1594
|
+
if ((await tx.all(probe.sql, ...probe.params)).length === 2) return;
|
|
1595
|
+
await tx.exec(`CREATE TABLE IF NOT EXISTS ${table} (
|
|
962
1596
|
position ${dialect.types.serialKey}, session_id TEXT NOT NULL REFERENCES ${sessions}(id) ON DELETE CASCADE,
|
|
963
1597
|
epoch TEXT NOT NULL, anchor TEXT NOT NULL, data TEXT NOT NULL)`);
|
|
964
|
-
|
|
965
|
-
|
|
1598
|
+
await tx.exec(`CREATE INDEX IF NOT EXISTS ${index} ON ${table}(session_id, epoch, anchor, position)`);
|
|
1599
|
+
}), SIDE_WRITE);
|
|
1600
|
+
};
|
|
966
1601
|
initialized ??= create().catch(() => create()).catch((error) => {
|
|
967
1602
|
initialized = void 0;
|
|
968
1603
|
throw error;
|
|
@@ -972,6 +1607,7 @@ function sqlChatRecords(database, sessions, table, index) {
|
|
|
972
1607
|
const current = dialect.jsonText("summary_state", "epoch");
|
|
973
1608
|
const bytes = (column) => dialect.textByteLength(column);
|
|
974
1609
|
return {
|
|
1610
|
+
initialize,
|
|
975
1611
|
async append(owner, anchor, record) {
|
|
976
1612
|
record = boundedChatRecord(record);
|
|
977
1613
|
await initialize();
|
|
@@ -989,7 +1625,7 @@ function sqlChatRecords(database, sessions, table, index) {
|
|
|
989
1625
|
data,
|
|
990
1626
|
owner.id,
|
|
991
1627
|
owner.epoch
|
|
992
|
-
])),
|
|
1628
|
+
])), sessionWriteTransaction(sessions, owner.id));
|
|
993
1629
|
},
|
|
994
1630
|
async has(owner) {
|
|
995
1631
|
return !!await database.get(`SELECT 1 AS present FROM ${table} WHERE session_id=? AND epoch=? LIMIT 1`, owner.id, owner.epoch).catch(() => void 0);
|
|
@@ -1039,12 +1675,41 @@ function sqlChatRecords(database, sessions, table, index) {
|
|
|
1039
1675
|
* that knows only version 1 would read as stubs. A database stays at version 1, which older builds still open, until
|
|
1040
1676
|
* this build writes its first chunked entry: that transaction moves the sessions meta to 2, and older builds refuse it
|
|
1041
1677
|
* when next opened with `StorageSchemaVersionError`. Builds before 2 check only the meta row, on SQLite and Postgres alike.
|
|
1678
|
+
* Version 3 turns on forks that share their parent's history ({@link SESSION_SCHEMA_VERSION_SHARED_HISTORY}).
|
|
1042
1679
|
*/
|
|
1043
|
-
const SESSION_SCHEMA_VERSION =
|
|
1680
|
+
const SESSION_SCHEMA_VERSION = 3;
|
|
1044
1681
|
/** The sessions schema of a database without chunked entries, which older builds read too. */
|
|
1045
1682
|
const SESSION_SCHEMA_VERSION_UNCHUNKED = 1;
|
|
1683
|
+
/** The sessions schema the first chunked entry raises a version 1 database to, which builds since #4954 read. */
|
|
1684
|
+
const SESSION_SCHEMA_VERSION_CHUNKED = 2;
|
|
1685
|
+
/**
|
|
1686
|
+
* The sessions schema in which a fork shares its parent's history instead of copying it (#6560). A new database's
|
|
1687
|
+
* sessions schema starts at it; a store's open, or `atomic storage migrate`, raises an older one to it by itself once
|
|
1688
|
+
* no session of an older build runs there (`SqlSessionStore.enableSharedHistoryForks`); a fork or any other write never
|
|
1689
|
+
* does. Builds that know only versions 1
|
|
1690
|
+
* and 2 refuse it, at their open and in every transaction, rather than read a fork's own rows as its whole history.
|
|
1691
|
+
* `SqlSessionStore.sharedHistoryForks(tx)` tells a transaction whether its database is there.
|
|
1692
|
+
*/
|
|
1693
|
+
const SESSION_SCHEMA_VERSION_SHARED_HISTORY = 3;
|
|
1046
1694
|
/** The schema domain of the session tables in the prefix's migration ledger. */
|
|
1047
1695
|
const SESSION_DOMAIN = "sessions";
|
|
1696
|
+
/** The ledger step, `schema:session-fillfactor`, that sets the sessions table's fillfactor on PostgreSQL (#6560). */
|
|
1697
|
+
const SESSION_FILLFACTOR_DOMAIN = "session-fillfactor";
|
|
1698
|
+
/** The fillfactor of the sessions table on PostgreSQL: a fifth of each page stays free for head row updates. */
|
|
1699
|
+
const SESSION_ROW_FILLFACTOR = 80;
|
|
1700
|
+
/**
|
|
1701
|
+
* The ledger step, `schema:session-append-function`, that creates the session append function on PostgreSQL (#6599).
|
|
1702
|
+
* Raise its revision whenever the function's body changes: `atomic storage migrate` of an older build then leaves the
|
|
1703
|
+
* newer body in place.
|
|
1704
|
+
*/
|
|
1705
|
+
const SESSION_APPEND_FUNCTION_DOMAIN = "session-append-function";
|
|
1706
|
+
const SESSION_APPEND_FUNCTION_REVISION = 1;
|
|
1707
|
+
/**
|
|
1708
|
+
* The session append function's name under the store's prefix. The version in the name is the function's contract:
|
|
1709
|
+
* its arguments and what it answers. A build that needs another contract creates a function of a new name beside
|
|
1710
|
+
* this one, which builds that call this one keep using.
|
|
1711
|
+
*/
|
|
1712
|
+
const SESSION_APPEND_FUNCTION = "append_v1";
|
|
1048
1713
|
/**
|
|
1049
1714
|
* The most bytes of a chunked session blob one row holds. New blobs use a header row and rows of at most this size,
|
|
1050
1715
|
* so their bound and returned values stay within it: libSQL servers cap a row and a bound value (sqld's default is
|
|
@@ -1092,6 +1757,12 @@ const SESSION_FORK_STAGING_TABLES = Object.freeze({ forkStaging: "fork_staging"
|
|
|
1092
1757
|
/** The schema domain, in the prefix's migration ledger, of the table of open sessions (#4971). */
|
|
1093
1758
|
const SESSION_PRESENCE_DOMAIN = "session-presence";
|
|
1094
1759
|
const SESSION_PRESENCE_TABLES = Object.freeze({ open: "open" });
|
|
1760
|
+
/** The donor's segments name a session the fork did not lock: the fork runs again, locking it too (#6560). */
|
|
1761
|
+
var ForkSourcesMoved = class extends Error {
|
|
1762
|
+
constructor() {
|
|
1763
|
+
super("The fork's source moved its history while the fork read it");
|
|
1764
|
+
}
|
|
1765
|
+
};
|
|
1095
1766
|
function windowIndex(state, seq) {
|
|
1096
1767
|
return isSessionResumeIndex(state.windowResume, seq) ? state.windowResume : isSessionResumeIndex(state.resume, seq) ? state.resume : void 0;
|
|
1097
1768
|
}
|
|
@@ -1119,6 +1790,11 @@ const SESSION_READ_FETCH = {
|
|
|
1119
1790
|
min: 1,
|
|
1120
1791
|
max: 8192
|
|
1121
1792
|
};
|
|
1793
|
+
/**
|
|
1794
|
+
* The seqs of a shared history one page of a selective scan reads at most (#6560): the page then accounts for the range
|
|
1795
|
+
* through them, and the next page reads the next ones.
|
|
1796
|
+
*/
|
|
1797
|
+
const SCAN_SELECT_WINDOW = 4096;
|
|
1122
1798
|
const SESSION_READ_INLINE_BYTES = 4096;
|
|
1123
1799
|
function nextFetch(limit, rows) {
|
|
1124
1800
|
const kept = rows.length;
|
|
@@ -1218,6 +1894,14 @@ const LISTING_SCOPES = 8;
|
|
|
1218
1894
|
* ended before it committed runs again (#4383); `append` and `replace` check `expectSeq` again on each run.
|
|
1219
1895
|
*/
|
|
1220
1896
|
const SESSION_TRANSACTION = { retryTransientFailures: true };
|
|
1897
|
+
/**
|
|
1898
|
+
* A session read: one snapshot that takes no write lock, so it neither waits for writers nor makes them wait. Its
|
|
1899
|
+
* statements all run in that snapshot: split into separate ones, a read could join rows of two generations.
|
|
1900
|
+
*/
|
|
1901
|
+
const SESSION_READ = {
|
|
1902
|
+
retryTransientFailures: true,
|
|
1903
|
+
readOnly: true
|
|
1904
|
+
};
|
|
1221
1905
|
/** The largest content index or suffix length a task-reference query binds, an SQL `INTEGER` on every backend. */
|
|
1222
1906
|
const TASK_REFERENCE_INTEGER = 2 ** 31 - 1;
|
|
1223
1907
|
/**
|
|
@@ -1286,9 +1970,11 @@ async function entryByteLengthOf(database) {
|
|
|
1286
1970
|
}
|
|
1287
1971
|
/**
|
|
1288
1972
|
* The most bytes of statements a session write sends as one batch: an ordinary message's are far fewer. A larger
|
|
1289
|
-
* write, an import or a fork's whole window,
|
|
1973
|
+
* write, an import or a fork's whole window, sends its statements a request's worth at a time as they are made.
|
|
1290
1974
|
*/
|
|
1291
1975
|
const STATEMENT_BATCH_BYTES = 1048576;
|
|
1976
|
+
/** The most sessions whose last written row a store remembers for appends through the append function. */
|
|
1977
|
+
const WRITTEN_ROWS = 64;
|
|
1292
1978
|
/** About how many bytes `statement` carries: its text and its parameters. */
|
|
1293
1979
|
function statementBytes(statement) {
|
|
1294
1980
|
let bytes = statement.sql.length;
|
|
@@ -1297,6 +1983,125 @@ function statementBytes(statement) {
|
|
|
1297
1983
|
else bytes += 8;
|
|
1298
1984
|
return bytes;
|
|
1299
1985
|
}
|
|
1986
|
+
const ENTRY_COLUMNS = [
|
|
1987
|
+
"session_id",
|
|
1988
|
+
"seq",
|
|
1989
|
+
"entry_id",
|
|
1990
|
+
"entry_json",
|
|
1991
|
+
"chunks"
|
|
1992
|
+
];
|
|
1993
|
+
const TEXT_COLUMNS = [
|
|
1994
|
+
"session_id",
|
|
1995
|
+
"seq",
|
|
1996
|
+
"text_json"
|
|
1997
|
+
];
|
|
1998
|
+
/** The most rows one insert of {@link RowInserts} names: 320 parameters for an entry's five, below SQLite's old 999. */
|
|
1999
|
+
const ROWS_PER_INSERT = 64;
|
|
2000
|
+
/** The most bytes of values one insert of {@link RowInserts} takes, unless one row's alone are more. */
|
|
2001
|
+
const ROW_INSERT_BYTES = 262144;
|
|
2002
|
+
/**
|
|
2003
|
+
* Rows of `table` inserted several to a statement (#6560): one statement's SQL prepared, and its triggers compiled, for
|
|
2004
|
+
* up to {@link ROWS_PER_INSERT} rows, not for each, so an append of a burst prepares once on a server that keeps no
|
|
2005
|
+
* prepared statements. The rows go in in the order they are added, each as its own insert would, the triggers firing
|
|
2006
|
+
* for each in turn: the triggers read only what the triggers of the rows before wrote, not the rows themselves.
|
|
2007
|
+
*/
|
|
2008
|
+
var RowInserts = class {
|
|
2009
|
+
table;
|
|
2010
|
+
columns;
|
|
2011
|
+
sqls = [];
|
|
2012
|
+
rows = [];
|
|
2013
|
+
bytes = 0;
|
|
2014
|
+
constructor(table, columns) {
|
|
2015
|
+
this.table = table;
|
|
2016
|
+
this.columns = columns;
|
|
2017
|
+
}
|
|
2018
|
+
/** The insert of `count` rows. */
|
|
2019
|
+
sql(count) {
|
|
2020
|
+
let sql = this.sqls[count];
|
|
2021
|
+
if (sql === void 0) {
|
|
2022
|
+
const row = `(${this.columns.map(() => "?").join(", ")})`;
|
|
2023
|
+
sql = `INSERT INTO ${this.table} (${this.columns.join(", ")}) VALUES ${Array(count).fill(row).join(", ")}`;
|
|
2024
|
+
this.sqls[count] = sql;
|
|
2025
|
+
}
|
|
2026
|
+
return sql;
|
|
2027
|
+
}
|
|
2028
|
+
/** Adds `row`, and yields the inserts of the rows before it once they are as many, or as large, as one takes. */
|
|
2029
|
+
*add(row) {
|
|
2030
|
+
const bytes = statementBytes({
|
|
2031
|
+
sql: "",
|
|
2032
|
+
params: row
|
|
2033
|
+
});
|
|
2034
|
+
if (this.rows.length === ROWS_PER_INSERT || this.rows.length > 0 && this.bytes + bytes > ROW_INSERT_BYTES) yield* this.drain();
|
|
2035
|
+
this.rows.push(row);
|
|
2036
|
+
this.bytes += bytes;
|
|
2037
|
+
}
|
|
2038
|
+
/** The inserts of the rows added and not yet yielded. */
|
|
2039
|
+
*drain() {
|
|
2040
|
+
const rows = this.rows;
|
|
2041
|
+
if (rows.length === 0) return;
|
|
2042
|
+
this.rows = [];
|
|
2043
|
+
this.bytes = 0;
|
|
2044
|
+
yield {
|
|
2045
|
+
sql: this.sql(rows.length),
|
|
2046
|
+
params: rows.flat()
|
|
2047
|
+
};
|
|
2048
|
+
}
|
|
2049
|
+
};
|
|
2050
|
+
/** What `first` yields, then `last`. */
|
|
2051
|
+
function* thenAll(first, last) {
|
|
2052
|
+
yield* first;
|
|
2053
|
+
yield* last;
|
|
2054
|
+
}
|
|
2055
|
+
/** `first`, then what is left of `rest`. */
|
|
2056
|
+
function* withRest(first, rest) {
|
|
2057
|
+
yield* first;
|
|
2058
|
+
for (let next = rest.next(); next.done !== true; next = rest.next()) yield next.value;
|
|
2059
|
+
}
|
|
2060
|
+
/**
|
|
2061
|
+
* Writes of one transaction sent without waiting for each answer: the connection runs them in the order they were
|
|
2062
|
+
* sent, behind the transaction's earlier calls and ahead of its later ones, so a read made after `send` sees them. On a
|
|
2063
|
+
* pipelined connection they share round trips instead of taking one each. At most `STATEMENT_BATCH_BYTES` of them are
|
|
2064
|
+
* unanswered at a time. `settle` waits for every one sent and throws the first that failed.
|
|
2065
|
+
*/
|
|
2066
|
+
var SentWrites = class {
|
|
2067
|
+
tx;
|
|
2068
|
+
sent = [];
|
|
2069
|
+
unansweredBytes = 0;
|
|
2070
|
+
failure;
|
|
2071
|
+
constructor(tx) {
|
|
2072
|
+
this.tx = tx;
|
|
2073
|
+
}
|
|
2074
|
+
/** Sends `statements`; a counted one fails when its answer reports another number of changed rows. */
|
|
2075
|
+
async send(statements) {
|
|
2076
|
+
for (const statement of statements) {
|
|
2077
|
+
const { changes, mismatch } = statement;
|
|
2078
|
+
this.sent.push(this.tx.run(statement.sql, ...statement.params).then((result) => {
|
|
2079
|
+
if (changes !== void 0 && result.changes !== changes) this.failure ??= { error: mismatch?.() ?? new StorageError(`A write changed ${result.changes} rows where ${changes} were expected`) };
|
|
2080
|
+
}, (error) => {
|
|
2081
|
+
this.failure ??= { error };
|
|
2082
|
+
}));
|
|
2083
|
+
this.unansweredBytes += statementBytes(statement);
|
|
2084
|
+
if (this.unansweredBytes > STATEMENT_BATCH_BYTES) await this.settle();
|
|
2085
|
+
}
|
|
2086
|
+
}
|
|
2087
|
+
async settle() {
|
|
2088
|
+
await Promise.all(this.sent.splice(0));
|
|
2089
|
+
this.unansweredBytes = 0;
|
|
2090
|
+
if (this.failure !== void 0) throw this.failure.error;
|
|
2091
|
+
}
|
|
2092
|
+
/** Settles after `body`, and reports the first write that failed before what `body` met, as its cause. */
|
|
2093
|
+
async around(body) {
|
|
2094
|
+
let value;
|
|
2095
|
+
try {
|
|
2096
|
+
value = await body();
|
|
2097
|
+
} catch (error) {
|
|
2098
|
+
await this.settle();
|
|
2099
|
+
throw error;
|
|
2100
|
+
}
|
|
2101
|
+
await this.settle();
|
|
2102
|
+
return value;
|
|
2103
|
+
}
|
|
2104
|
+
};
|
|
1300
2105
|
var SqlSessionStore = class SqlSessionStore {
|
|
1301
2106
|
database;
|
|
1302
2107
|
dialect;
|
|
@@ -1312,6 +2117,26 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
1312
2117
|
openMarkers;
|
|
1313
2118
|
searchIndex;
|
|
1314
2119
|
chatStore;
|
|
2120
|
+
/** The database's reader handle, once a read opened it: see `readerDatabase`. */
|
|
2121
|
+
reader;
|
|
2122
|
+
/** The sessions schema version each transaction read first, by its handle: see `sharedHistoryForks`. */
|
|
2123
|
+
schemaVersions = /* @__PURE__ */ new WeakMap();
|
|
2124
|
+
/** The fork tables under this store's prefix, which exist once its sessions schema is version 3 (#6560). */
|
|
2125
|
+
forkTables;
|
|
2126
|
+
/** See {@link forkLinks}. */
|
|
2127
|
+
forkLinkStatements;
|
|
2128
|
+
/**
|
|
2129
|
+
* Whether a read of this store found its sessions schema at {@link SESSION_SCHEMA_VERSION_SHARED_HISTORY}: one way,
|
|
2130
|
+
* as the switch is. A read outside a transaction reads sessions through their views once it is set, and before that
|
|
2131
|
+
* reads the tables themselves on the condition, checked in the read's own snapshot, that the schema is older.
|
|
2132
|
+
*/
|
|
2133
|
+
sharedHistorySeen = false;
|
|
2134
|
+
/** For each transaction, whether each session whose row it read has fork segments, as that read found (#6560). */
|
|
2135
|
+
forkedIn = /* @__PURE__ */ new WeakMap();
|
|
2136
|
+
/** Whether each recently read session had fork segments: only a first guess, which a read checks (#6560). */
|
|
2137
|
+
forkedSessions = /* @__PURE__ */ new Map();
|
|
2138
|
+
/** The sessions each recently forked session's segments named when this store last read them (#6560). */
|
|
2139
|
+
forkSources = /* @__PURE__ */ new Map();
|
|
1315
2140
|
/**
|
|
1316
2141
|
* Absent on a local libSQL file, which then behaves as before: @libsql/client waits for another process's write
|
|
1317
2142
|
* lock on the calling thread, even to begin a transaction, so a side write would stop the event loop where an
|
|
@@ -1325,7 +2150,7 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
1325
2150
|
rows: "chat_v1",
|
|
1326
2151
|
byAnchor: "chat_v1_anchor"
|
|
1327
2152
|
}, this.prefix);
|
|
1328
|
-
this.chatStore = sqlChatRecords(this.database, this.tables.sessions, names.rows, names.byAnchor);
|
|
2153
|
+
this.chatStore = sqlChatRecords(this.database, this.tables.sessions, names.rows, names.byAnchor, storageMigrationTable(this.prefix));
|
|
1329
2154
|
}
|
|
1330
2155
|
return this.chatStore;
|
|
1331
2156
|
}
|
|
@@ -1344,17 +2169,29 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
1344
2169
|
forkStagingTable;
|
|
1345
2170
|
/** The generation each recently read session's row held at a revision: see `generation`. */
|
|
1346
2171
|
generations = /* @__PURE__ */ new Map();
|
|
1347
|
-
|
|
2172
|
+
/**
|
|
2173
|
+
* The session append function of this store's tables, when the open found it and this role may run it (#6599):
|
|
2174
|
+
* `atomic storage migrate` creates it. Absent elsewhere, where appends take their two round trips as before.
|
|
2175
|
+
*/
|
|
2176
|
+
appendFunction;
|
|
2177
|
+
/** The row each recent write of this store left for its session, which an append through the function plans from. */
|
|
2178
|
+
writtenRows = /* @__PURE__ */ new Map();
|
|
2179
|
+
constructor(database, tables, prefix, cwdMatcher, snapshotBlobs, legacyBlobData, searchIndex, entryByteLength, appendFunction) {
|
|
1348
2180
|
this.database = database;
|
|
2181
|
+
if (appendFunction !== void 0) this.appendFunction = appendFunction;
|
|
1349
2182
|
this.dialect = dialectOf(database);
|
|
1350
2183
|
this.entryByteLength = entryByteLength;
|
|
1351
2184
|
this.tables = tables;
|
|
1352
2185
|
this.prefix = prefix ?? "";
|
|
1353
|
-
registerForkScope(this, () =>
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
2186
|
+
registerForkScope(this, () => {
|
|
2187
|
+
const identity = this.database.databaseIdentity?.();
|
|
2188
|
+
return {
|
|
2189
|
+
kind: "sql",
|
|
2190
|
+
backing: this.database,
|
|
2191
|
+
prefix: this.prefix,
|
|
2192
|
+
...identity === void 0 ? {} : { identity }
|
|
2193
|
+
};
|
|
2194
|
+
});
|
|
1358
2195
|
this.cwdMatcher = cwdMatcher;
|
|
1359
2196
|
this.snapshotBlobs = snapshotBlobs;
|
|
1360
2197
|
this.blobTable = snapshotBlobs;
|
|
@@ -1363,12 +2200,13 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
1363
2200
|
registerHistorySnapshot(this, (sessionId, project) => {
|
|
1364
2201
|
this.assertOpen();
|
|
1365
2202
|
validateSessionText("sessionId", sessionId);
|
|
1366
|
-
return this.
|
|
1367
|
-
const head = await this.historyHead(tx, sessionId);
|
|
2203
|
+
return this.readTransaction(async (tx) => {
|
|
2204
|
+
const head = await this.historyHead(tx, sessionId, true);
|
|
1368
2205
|
return project(head.epoch, head.lastSeq, (from, through, backward) => this.historyPacket(tx, sessionId, head.epoch, from, through, backward));
|
|
1369
|
-
}
|
|
2206
|
+
});
|
|
1370
2207
|
});
|
|
1371
2208
|
this.forkStagingTable = renderStorageIdentifiers("sessions", SESSION_FORK_STAGING_TABLES, prefix).forkStaging;
|
|
2209
|
+
this.forkTables = sessionForkTables(prefix);
|
|
1372
2210
|
}
|
|
1373
2211
|
/** Bind an existing transcript for the storage search command. No schema setup, markers or search index. */
|
|
1374
2212
|
static async openTranscriptReader(database) {
|
|
@@ -1379,8 +2217,13 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
1379
2217
|
}
|
|
1380
2218
|
static async open(database, options = {}) {
|
|
1381
2219
|
validateStoragePrefix(options.prefix, dialectOf(database).name);
|
|
2220
|
+
return withStorageSchemaCatalog(database, storageMigrationTable(options.prefix), () => SqlSessionStore.openWithCatalog(database, options));
|
|
2221
|
+
}
|
|
2222
|
+
static async openWithCatalog(database, options) {
|
|
1382
2223
|
const tables = renderStorageIdentifiers("sessions", SESSION_TABLES, options.prefix);
|
|
1383
2224
|
let legacyBlobData = false;
|
|
2225
|
+
const forkTables = sessionForkTables(options.prefix);
|
|
2226
|
+
let createdShared = false;
|
|
1384
2227
|
const createTables = async (tx, dialect) => {
|
|
1385
2228
|
const { int, text, blob } = dialect.types;
|
|
1386
2229
|
const strict = dialect.tableOptions;
|
|
@@ -1390,7 +2233,7 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
1390
2233
|
return async () => await tx.get(probe.sql, ...probe.params) !== void 0;
|
|
1391
2234
|
};
|
|
1392
2235
|
const [versions] = await statementBatch(tx, [`CREATE TABLE IF NOT EXISTS ${tables.meta} (schema_version ${int} NOT NULL)${strict}`], [() => tx.all(`SELECT schema_version FROM ${tables.meta}`)]);
|
|
1393
|
-
for (const version of versions) assertStorageSchemaVersion("sessions", version.schema_version,
|
|
2236
|
+
for (const version of versions) assertStorageSchemaVersion("sessions", version.schema_version, 3, SESSION_SCHEMA_VERSION_UNCHUNKED);
|
|
1394
2237
|
const tablesScript = `
|
|
1395
2238
|
CREATE TABLE IF NOT EXISTS ${tables.sessions} (
|
|
1396
2239
|
id ${text} PRIMARY KEY, cwd ${text} NOT NULL, created_at ${text} NOT NULL,
|
|
@@ -1418,10 +2261,19 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
1418
2261
|
PRIMARY KEY(session_id, hash, idx)
|
|
1419
2262
|
)${strict};
|
|
1420
2263
|
`;
|
|
1421
|
-
const
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
2264
|
+
const created = versions.length === 0;
|
|
2265
|
+
const [revision, data] = await statementBatch(tx, [
|
|
2266
|
+
created && {
|
|
2267
|
+
sql: `INSERT INTO ${tables.meta} VALUES (?)`,
|
|
2268
|
+
params: [3]
|
|
2269
|
+
},
|
|
2270
|
+
created ? `${tablesScript}\n${sharedHistoryTablesScript(dialect, forkTables)}` : tablesScript,
|
|
2271
|
+
created && dialect.versionedMigrations && {
|
|
2272
|
+
sql: `INSERT INTO ${storageMigrationTable(options.prefix)} (domain, version, applied_at) VALUES (?, ?, ${dialect.nowMs}) ON CONFLICT DO NOTHING`,
|
|
2273
|
+
params: ["sessions", 3]
|
|
2274
|
+
}
|
|
2275
|
+
], [columnExists(tables.sessions, "revision"), columnExists(tables.blobs, "data")]);
|
|
2276
|
+
createdShared = created;
|
|
1425
2277
|
legacyBlobData = data;
|
|
1426
2278
|
const [chunks] = legacyBlobData ? await statementBatch(tx, [], [columnExists(tables.blobs, "chunks")]) : [true];
|
|
1427
2279
|
await statementBatch(tx, [!revision && `ALTER TABLE ${tables.sessions} ADD COLUMN revision ${text} NOT NULL DEFAULT ''`, !chunks && `ALTER TABLE ${tables.blobs} ADD COLUMN chunks ${int} NOT NULL DEFAULT -1`], []);
|
|
@@ -1455,49 +2307,85 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
1455
2307
|
};
|
|
1456
2308
|
const presence = renderStorageIdentifiers("sessions", SESSION_PRESENCE_TABLES, options.prefix);
|
|
1457
2309
|
const current = await SqlSessionStore.currentSchema(database, tables, presence.open, database.readOnly === true ? void 0 : orphanedEntryKeys);
|
|
2310
|
+
let sharedHistory;
|
|
1458
2311
|
if (current !== void 0) {
|
|
1459
2312
|
legacyBlobData = current.legacyBlobData;
|
|
2313
|
+
sharedHistory = current.sharedHistory;
|
|
1460
2314
|
if (current.orphaned) await database.transaction(async (tx) => {
|
|
1461
|
-
await assertStoredSchemaVersion(tx, { sql: `SELECT schema_version FROM ${tables.meta}` }, "sessions",
|
|
2315
|
+
await assertStoredSchemaVersion(tx, { sql: `SELECT schema_version FROM ${tables.meta}` }, "sessions", 3, "schema_version", SESSION_SCHEMA_VERSION_UNCHUNKED);
|
|
1462
2316
|
await tx.run(removeOrphanedEntryChunks.sql);
|
|
1463
2317
|
}).catch((error) => {
|
|
1464
2318
|
if (error instanceof StorageSchemaVersionError) throw error;
|
|
1465
2319
|
});
|
|
1466
|
-
} else
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
up: (tx, dialect) => SqlSessionOpenMarkers.createTable(tx, dialect, presence.open)
|
|
2320
|
+
} else {
|
|
2321
|
+
const [sessionsSchema] = await applyStorageMigrationsTogether(database, [{
|
|
2322
|
+
domain: SESSION_DOMAIN,
|
|
2323
|
+
steps: [{
|
|
2324
|
+
version: 1,
|
|
2325
|
+
up: createTables
|
|
2326
|
+
}, {
|
|
2327
|
+
version: 2,
|
|
2328
|
+
up: addEntryChunks
|
|
2329
|
+
}],
|
|
2330
|
+
options: {
|
|
2331
|
+
table: storageMigrationTable(options.prefix),
|
|
2332
|
+
recordedThrough: 3
|
|
2333
|
+
}
|
|
1481
2334
|
}, {
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
|
|
2335
|
+
domain: SESSION_PRESENCE_DOMAIN,
|
|
2336
|
+
steps: [
|
|
2337
|
+
{
|
|
2338
|
+
version: 1,
|
|
2339
|
+
up: (tx, dialect) => SqlSessionOpenMarkers.createTable(tx, dialect, presence.open)
|
|
2340
|
+
},
|
|
2341
|
+
{
|
|
2342
|
+
version: 2,
|
|
2343
|
+
up: (tx, dialect) => SqlSessionOpenMarkers.addSchemaVersion(tx, dialect, presence.open)
|
|
2344
|
+
},
|
|
2345
|
+
{
|
|
2346
|
+
version: 3,
|
|
2347
|
+
up: (tx, dialect) => SqlSessionOpenMarkers.addBuild(tx, dialect, presence.open)
|
|
2348
|
+
}
|
|
2349
|
+
],
|
|
2350
|
+
options: {
|
|
2351
|
+
table: storageMigrationTable(options.prefix),
|
|
2352
|
+
acceptNewer: true
|
|
2353
|
+
}
|
|
2354
|
+
}]);
|
|
2355
|
+
if (createdShared) {
|
|
2356
|
+
sharedHistory = true;
|
|
2357
|
+
noteStorageSchemaTables(database, Object.values(forkTables));
|
|
2358
|
+
} else if (dialectOf(database).versionedMigrations) sharedHistory = (sessionsSchema?.version ?? 0) >= 3;
|
|
2359
|
+
}
|
|
2360
|
+
await ensureTableFillfactor(database, {
|
|
2361
|
+
ledger: storageMigrationTable(options.prefix),
|
|
2362
|
+
domain: SESSION_FILLFACTOR_DOMAIN,
|
|
2363
|
+
revision: 1,
|
|
2364
|
+
table: tables.sessions,
|
|
2365
|
+
fillfactor: SESSION_ROW_FILLFACTOR
|
|
2366
|
+
});
|
|
2367
|
+
const markers = new SqlSessionOpenMarkers(database, presence.open, () => store.assertOpen());
|
|
2368
|
+
let shared = sharedHistory === true;
|
|
2369
|
+
if (sharedHistory !== true && database.readOnly !== true) {
|
|
2370
|
+
const switched = await SqlSessionStore.switchAtOpen(database, options.prefix ?? "", tables, markers, sharedHistory === false);
|
|
2371
|
+
if (switched) refreshStorageSchemaCatalog(database);
|
|
2372
|
+
shared = switched;
|
|
2373
|
+
}
|
|
1490
2374
|
const staging = renderStorageIdentifiers("sessions", SESSION_FORK_STAGING_TABLES, options.prefix).forkStaging;
|
|
1491
2375
|
const stagingProbe = dialectOf(database).tableExists(staging);
|
|
1492
|
-
const
|
|
2376
|
+
const catalog = await schemaCatalogOf(database);
|
|
2377
|
+
const staged = database.readOnly === true || !database.tryMaintenance ? Promise.resolve(false) : catalog !== void 0 ? Promise.resolve(catalog.hasTable(staging)) : database.get(stagingProbe.sql, ...stagingProbe.params).then((row) => row !== void 0, () => false);
|
|
1493
2378
|
const opening = current === void 0 ? await SqlSnapshotBlobStore$1.open(database, options.prefix) : void 0;
|
|
1494
2379
|
const [blobs, searchIndex, entryByteLength] = await Promise.all([
|
|
1495
2380
|
opening ?? SqlSnapshotBlobStore$1.open(database, options.prefix),
|
|
1496
2381
|
SqlSessionSearchIndex.open(database, tables, options.prefix),
|
|
1497
2382
|
entryByteLengthOf(database)
|
|
1498
2383
|
]);
|
|
1499
|
-
const
|
|
1500
|
-
|
|
2384
|
+
const appendFunction = renderStorageIdentifiers("sessions", { append: SESSION_APPEND_FUNCTION }, options.prefix).append;
|
|
2385
|
+
const appendsThroughFunction = catalog?.hasFunction?.(appendFunction) === true && database.autocommit !== void 0 && typeof blobs.storedBlobsQuery === "function";
|
|
2386
|
+
const store = new SqlSessionStore(database, tables, options.prefix, options.cwdMatcher, blobs, legacyBlobData, searchIndex, entryByteLength, appendsThroughFunction ? appendFunction : void 0);
|
|
2387
|
+
store.openMarkers = markers;
|
|
2388
|
+
if (shared) store.noteSchemaVersion(3);
|
|
1501
2389
|
if (await staged) await store.cleanupForkStaging();
|
|
1502
2390
|
return store;
|
|
1503
2391
|
}
|
|
@@ -1521,23 +2409,37 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
1521
2409
|
static async currentSchema(database, tables, open, orphans) {
|
|
1522
2410
|
const dialect = dialectOf(database);
|
|
1523
2411
|
if (dialect.versionedMigrations) return void 0;
|
|
1524
|
-
const
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
|
|
1529
|
-
|
|
2412
|
+
const required = [...Object.values(tables), open];
|
|
2413
|
+
const columns = [
|
|
2414
|
+
[tables.sessions, "revision"],
|
|
2415
|
+
[tables.entries, "chunks"],
|
|
2416
|
+
[tables.blobs, "chunks"],
|
|
2417
|
+
[open, "schema_version"],
|
|
2418
|
+
[open, "build"]
|
|
1530
2419
|
];
|
|
1531
|
-
const
|
|
1532
|
-
const [legacyFound, ...found] = await Promise.all([legacy, ...probes].map((probe) => database.get(probe.sql, ...probe.params)));
|
|
1533
|
-
if (!found.every((row) => row !== void 0)) return void 0;
|
|
2420
|
+
const reading = schemaCatalogOf(database);
|
|
1534
2421
|
const orphaned = orphans === void 0 ? void 0 : database.get(`SELECT 1 FROM (${orphans}) AS orphaned LIMIT 1`);
|
|
1535
2422
|
orphaned?.catch(() => {});
|
|
1536
|
-
const
|
|
1537
|
-
|
|
2423
|
+
const versionsRead = database.all(`SELECT schema_version FROM ${tables.meta}`);
|
|
2424
|
+
versionsRead.catch(() => {});
|
|
2425
|
+
let legacyBlobs;
|
|
2426
|
+
const catalog = await reading;
|
|
2427
|
+
if (catalog !== void 0) {
|
|
2428
|
+
if (!(required.every((table) => catalog.hasTable(table)) && columns.every(([table, column]) => catalog.hasColumn(table, column)))) return void 0;
|
|
2429
|
+
legacyBlobs = catalog.hasColumn(tables.blobs, "data");
|
|
2430
|
+
} else {
|
|
2431
|
+
const probes = [...required.map((table) => dialect.tableExists(table)), ...columns.map(([table, column]) => dialect.columnExists(table, column))];
|
|
2432
|
+
const legacy = dialect.columnExists(tables.blobs, "data");
|
|
2433
|
+
const [legacyFound, ...found] = await Promise.all([legacy, ...probes].map((probe) => database.get(probe.sql, ...probe.params)));
|
|
2434
|
+
if (!found.every((row) => row !== void 0)) return void 0;
|
|
2435
|
+
legacyBlobs = legacyFound !== void 0;
|
|
2436
|
+
}
|
|
2437
|
+
const versions = await versionsRead;
|
|
2438
|
+
if (versions.length === 0 || versions.some((row) => typeof row.schema_version !== "number" || !Number.isInteger(row.schema_version) || row.schema_version < SESSION_SCHEMA_VERSION_UNCHUNKED || row.schema_version > 3)) return void 0;
|
|
1538
2439
|
return {
|
|
1539
|
-
legacyBlobData:
|
|
1540
|
-
orphaned: await orphaned !== void 0
|
|
2440
|
+
legacyBlobData: legacyBlobs,
|
|
2441
|
+
orphaned: await orphaned !== void 0,
|
|
2442
|
+
sharedHistory: versions.every((row) => Number(row.schema_version) >= 3)
|
|
1541
2443
|
};
|
|
1542
2444
|
}
|
|
1543
2445
|
/**
|
|
@@ -1548,7 +2450,54 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
1548
2450
|
return this.database.transaction(async (tx) => {
|
|
1549
2451
|
await this.assertReadableSchema(tx);
|
|
1550
2452
|
return body(tx);
|
|
1551
|
-
}, options);
|
|
2453
|
+
}, this.checkedFirst(options));
|
|
2454
|
+
}
|
|
2455
|
+
/**
|
|
2456
|
+
* `options` with the schema check its transaction makes first, before the reads `options.leading` names, sent with
|
|
2457
|
+
* the transaction's start where the connection is pipelined.
|
|
2458
|
+
*/
|
|
2459
|
+
checkedFirst(options) {
|
|
2460
|
+
return {
|
|
2461
|
+
...options,
|
|
2462
|
+
leading: [this.schemaCheck(), ...options.leading ?? []]
|
|
2463
|
+
};
|
|
2464
|
+
}
|
|
2465
|
+
/**
|
|
2466
|
+
* `transaction` for a write to the rows of the session `sessionId` only, beside writers of other sessions. `leading`
|
|
2467
|
+
* names the reads the body makes first, after the schema check.
|
|
2468
|
+
*/
|
|
2469
|
+
sessionWrite(sessionId, ...leading) {
|
|
2470
|
+
const options = sessionWriteTransaction(this.tables.sessions, sessionId);
|
|
2471
|
+
return leading.length === 0 ? options : {
|
|
2472
|
+
...options,
|
|
2473
|
+
leading
|
|
2474
|
+
};
|
|
2475
|
+
}
|
|
2476
|
+
/**
|
|
2477
|
+
* `transaction` for a body that only reads, in one read-only snapshot, on the database's reader handle when it
|
|
2478
|
+
* offers one: its reads then wait for neither the writes queued on this store's connection nor their locks.
|
|
2479
|
+
*/
|
|
2480
|
+
async readTransaction(body, leading = []) {
|
|
2481
|
+
return (await this.readerDatabase()).transaction(async (tx) => {
|
|
2482
|
+
await this.assertReadableSchema(tx);
|
|
2483
|
+
return body(tx);
|
|
2484
|
+
}, this.checkedFirst(leading.length === 0 ? SESSION_READ : {
|
|
2485
|
+
...SESSION_READ,
|
|
2486
|
+
leading
|
|
2487
|
+
}));
|
|
2488
|
+
}
|
|
2489
|
+
/**
|
|
2490
|
+
* The database's reader handle, opened at the first read and closed with the store; the database without one. A
|
|
2491
|
+
* reader that cannot open, such as when its file can no longer be opened anew, leaves the read on the store's own
|
|
2492
|
+
* connection, as every read ran before readers, and the next read tries to open one again.
|
|
2493
|
+
*/
|
|
2494
|
+
readerDatabase() {
|
|
2495
|
+
if (this.database.openReader === void 0) return this.database;
|
|
2496
|
+
this.reader ??= this.database.openReader().catch((error) => {
|
|
2497
|
+
this.reader = void 0;
|
|
2498
|
+
throw error;
|
|
2499
|
+
});
|
|
2500
|
+
return this.reader.catch(() => this.database);
|
|
1552
2501
|
}
|
|
1553
2502
|
/**
|
|
1554
2503
|
* `transaction` for a body that only reads and writes the database. The version check is sent first, as there, but on
|
|
@@ -1569,10 +2518,224 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
1569
2518
|
await checked;
|
|
1570
2519
|
if ("failure" in outcome) throw outcome.failure;
|
|
1571
2520
|
return outcome.value;
|
|
1572
|
-
}, options);
|
|
2521
|
+
}, this.checkedFirst(options));
|
|
1573
2522
|
}
|
|
2523
|
+
/** The read that checks the sessions schema version, which every transaction of this store makes first. */
|
|
2524
|
+
schemaCheck() {
|
|
2525
|
+
return {
|
|
2526
|
+
sql: `SELECT schema_version FROM ${this.tables.meta}`,
|
|
2527
|
+
params: []
|
|
2528
|
+
};
|
|
2529
|
+
}
|
|
2530
|
+
/**
|
|
2531
|
+
* Reads the sessions schema version through `executor` and refuses one this build does not read. The answer is kept
|
|
2532
|
+
* for `executor`, a transaction's own handle, so {@link sharedHistoryForks} costs that transaction no read.
|
|
2533
|
+
*/
|
|
1574
2534
|
assertReadableSchema(executor) {
|
|
1575
|
-
|
|
2535
|
+
const check = this.schemaCheck();
|
|
2536
|
+
const version = executor.get(check.sql, ...check.params).then((row) => {
|
|
2537
|
+
const found = row?.schema_version ?? null;
|
|
2538
|
+
assertStorageSchemaVersion("sessions", found, 3, SESSION_SCHEMA_VERSION_UNCHUNKED);
|
|
2539
|
+
this.noteSchemaVersion(found);
|
|
2540
|
+
return found;
|
|
2541
|
+
});
|
|
2542
|
+
this.schemaVersions.set(executor, version);
|
|
2543
|
+
return version.then(() => {});
|
|
2544
|
+
}
|
|
2545
|
+
/**
|
|
2546
|
+
* Whether the database `tx` runs in has forks that share their parent's history turned on: its sessions schema, as
|
|
2547
|
+
* `tx` read it, is {@link SESSION_SCHEMA_VERSION_SHARED_HISTORY} (#6560). Every transaction of this store reads the
|
|
2548
|
+
* version first, so this costs no further read there; `tx` of any other transaction reads it once. Asked again in each
|
|
2549
|
+
* transaction, never kept on the store: another process may turn the forks on at any time, and the switch is one way,
|
|
2550
|
+
* so an answer read before it only means a fork is copied.
|
|
2551
|
+
*/
|
|
2552
|
+
async sharedHistoryForks(tx) {
|
|
2553
|
+
if (!this.schemaVersions.has(tx)) await this.assertReadableSchema(tx);
|
|
2554
|
+
return await this.schemaVersions.get(tx) >= 3;
|
|
2555
|
+
}
|
|
2556
|
+
/** Notes a sessions schema version a read of this store found: see {@link sharedHistorySeen}. */
|
|
2557
|
+
noteSchemaVersion(version) {
|
|
2558
|
+
if (typeof version === "number" && version >= 3) this.sharedHistorySeen = true;
|
|
2559
|
+
}
|
|
2560
|
+
/** How transaction `tx` reads a session's rows: through its view where its database has shared history (#6560). */
|
|
2561
|
+
async viewTables(tx, sessionId) {
|
|
2562
|
+
return {
|
|
2563
|
+
segments: !(sessionId !== void 0 && this.forkedIn.get(tx)?.get(sessionId) === false) && await this.sharedHistoryForks(tx) ? this.forkTables.forkSegments : void 0,
|
|
2564
|
+
dialect: this.dialect
|
|
2565
|
+
};
|
|
2566
|
+
}
|
|
2567
|
+
/**
|
|
2568
|
+
* A column, `forked`, of a read of a sessions row whose id is `id`: 1 when the session has fork segments (#6560),
|
|
2569
|
+
* found by the segments' key. Only where `segments`, the fork segments table, exists.
|
|
2570
|
+
*/
|
|
2571
|
+
forkedColumn(segments, id = "id") {
|
|
2572
|
+
return segments === void 0 ? "" : `, CASE WHEN EXISTS (SELECT 1 FROM ${segments} WHERE session_id = ${id}) THEN 1 ELSE 0 END AS forked`;
|
|
2573
|
+
}
|
|
2574
|
+
/**
|
|
2575
|
+
* Notes what a read of session `sessionId`'s row in transaction `tx` found, `forked` from {@link forkedColumn}: the
|
|
2576
|
+
* transaction's later reads of a session without segments read its tables directly. The store remembers it too, as a
|
|
2577
|
+
* first guess for a read that sends its statements before that row's answer, and checks it against that answer.
|
|
2578
|
+
*/
|
|
2579
|
+
noteForked(tx, sessionId, forked) {
|
|
2580
|
+
if (forked === void 0 || forked === null) return;
|
|
2581
|
+
const value = Number(forked) === 1;
|
|
2582
|
+
if (tx !== void 0) {
|
|
2583
|
+
const known = this.forkedIn.get(tx) ?? /* @__PURE__ */ new Map();
|
|
2584
|
+
this.forkedIn.set(tx, known);
|
|
2585
|
+
known.set(sessionId, value);
|
|
2586
|
+
}
|
|
2587
|
+
this.forkedSessions.delete(sessionId);
|
|
2588
|
+
this.forkedSessions.set(sessionId, value);
|
|
2589
|
+
while (this.forkedSessions.size > 256) this.forkedSessions.delete(this.forkedSessions.keys().next().value);
|
|
2590
|
+
}
|
|
2591
|
+
/**
|
|
2592
|
+
* How a read outside a transaction reads a session's rows: through its view once this store has seen shared history,
|
|
2593
|
+
* and otherwise from the tables themselves, but only while the schema, read in the same statement, is older. Such a
|
|
2594
|
+
* read that finds nothing asks `outsideTransaction` to try again.
|
|
2595
|
+
*/
|
|
2596
|
+
outsideViewTables() {
|
|
2597
|
+
const version = `(SELECT max(schema_version) FROM ${this.tables.meta})`;
|
|
2598
|
+
return this.sharedHistorySeen ? {
|
|
2599
|
+
segments: this.forkTables.forkSegments,
|
|
2600
|
+
dialect: this.dialect,
|
|
2601
|
+
guard: `${version} <= 3`
|
|
2602
|
+
} : {
|
|
2603
|
+
segments: void 0,
|
|
2604
|
+
dialect: this.dialect,
|
|
2605
|
+
guard: `${version} < 3`
|
|
2606
|
+
};
|
|
2607
|
+
}
|
|
2608
|
+
/**
|
|
2609
|
+
* `read`, a read outside a transaction of a session's rows through `outsideViewTables`, once more through the views
|
|
2610
|
+
* when it found nothing (`found` says) before this store had seen shared history, and the schema, read after it, is
|
|
2611
|
+
* now at version 3: the read's own check then held its rows back. The switch is one way, so a schema older than 3
|
|
2612
|
+
* read after the read was older at the read too, and its answer stands.
|
|
2613
|
+
*/
|
|
2614
|
+
async outsideTransaction(read, found) {
|
|
2615
|
+
const seen = this.sharedHistorySeen;
|
|
2616
|
+
const value = await read(this.outsideViewTables());
|
|
2617
|
+
if (found(value)) return value;
|
|
2618
|
+
return await this.schemaNowShared(seen) ? read(this.outsideViewTables()) : value;
|
|
2619
|
+
}
|
|
2620
|
+
/**
|
|
2621
|
+
* `read`, a read outside a transaction of session `sessionId`'s rows that also reads, as `forked`, whether the
|
|
2622
|
+
* session has fork segments, through `outsideTransaction` (#6560): from the tables themselves when this store last
|
|
2623
|
+
* found the session without segments, and through its view again when the read's own answer says it now has them.
|
|
2624
|
+
*/
|
|
2625
|
+
outsideSessionRead(sessionId, read, found, forkedOf) {
|
|
2626
|
+
return this.outsideTransaction(async (tables) => {
|
|
2627
|
+
const plain = tables.segments !== void 0 && this.forkedSessions.get(sessionId) === false;
|
|
2628
|
+
const value = await read(plain ? {
|
|
2629
|
+
...tables,
|
|
2630
|
+
segments: void 0
|
|
2631
|
+
} : tables);
|
|
2632
|
+
const forked = forkedOf(value);
|
|
2633
|
+
this.noteForked(void 0, sessionId, forked);
|
|
2634
|
+
return plain && Number(forked) === 1 ? read(tables) : value;
|
|
2635
|
+
}, found);
|
|
2636
|
+
}
|
|
2637
|
+
/** The `forked` column of a read outside a transaction of the sessions row `id` names: see `outsideSessionRead`. */
|
|
2638
|
+
outsideForkedColumn(id) {
|
|
2639
|
+
return this.forkedColumn(this.sharedHistorySeen ? this.forkTables.forkSegments : void 0, id);
|
|
2640
|
+
}
|
|
2641
|
+
/**
|
|
2642
|
+
* After a read outside a transaction found nothing: reads the sessions schema, refuses one this build does not read,
|
|
2643
|
+
* and tells whether shared history is on now where the read, made with `seen` as it was, read the tables themselves.
|
|
2644
|
+
*/
|
|
2645
|
+
async schemaNowShared(seen) {
|
|
2646
|
+
const row = await this.database.get(`SELECT max(schema_version) AS version FROM ${this.tables.meta}`);
|
|
2647
|
+
const version = row?.version == null ? null : Number(row.version);
|
|
2648
|
+
assertStorageSchemaVersion("sessions", version, 3, SESSION_SCHEMA_VERSION_UNCHUNKED);
|
|
2649
|
+
this.noteSchemaVersion(version);
|
|
2650
|
+
return this.sharedHistorySeen && !seen;
|
|
2651
|
+
}
|
|
2652
|
+
/**
|
|
2653
|
+
* Turns on forks that share their parent's history (#6560), as a store's open does by itself: see
|
|
2654
|
+
* {@link SqlSessionStore.switchSharedHistory}. `live` judges whether the process of an older build's open-session
|
|
2655
|
+
* marker still runs; the application's judge by default.
|
|
2656
|
+
*/
|
|
2657
|
+
enableSharedHistoryForks(options = {}) {
|
|
2658
|
+
this.assertOpen();
|
|
2659
|
+
return SqlSessionStore.switchSharedHistory(this.database, this.prefix, this.tables, this.openMarkers, options.live ?? sharedHistorySwitchHost().live);
|
|
2660
|
+
}
|
|
2661
|
+
/**
|
|
2662
|
+
* The switch to shared-history forks (#6560), in one transaction: creates the fork tables, records version 3 in the
|
|
2663
|
+
* migration ledger where there is one, and raises the sessions schema to it, so that builds which do not read it
|
|
2664
|
+
* refuse the database at their next open or transaction. One way: nothing lowers it again.
|
|
2665
|
+
*
|
|
2666
|
+
* It never leaves an older process reading what it cannot read: while `live` judges any open-session marker of an
|
|
2667
|
+
* older build to be a running process, it changes nothing and is `deferred`, and the next open tries again. The
|
|
2668
|
+
* transaction is the only writer of the whole database while it runs, so every session write either finished before
|
|
2669
|
+
* it, or starts after it and reads the new version first. Two hosts switching at once run one after the other, and
|
|
2670
|
+
* the second finds it `already` done.
|
|
2671
|
+
*/
|
|
2672
|
+
static switchSharedHistory(database, prefix, tables, markers, live) {
|
|
2673
|
+
const dialect = dialectOf(database);
|
|
2674
|
+
return database.transaction(async (tx) => {
|
|
2675
|
+
const [row, older] = await statementBatch(tx, [], [() => tx.get(`SELECT max(schema_version) AS schema_version FROM ${tables.meta}`), () => markers.olderThan(tx, 3)]);
|
|
2676
|
+
const version = row?.schema_version ?? null;
|
|
2677
|
+
assertStorageSchemaVersion("sessions", version, 3, SESSION_SCHEMA_VERSION_UNCHUNKED);
|
|
2678
|
+
if (Number(version) >= 3) return { status: "already" };
|
|
2679
|
+
const holders = await liveMarkers(older, live);
|
|
2680
|
+
if (holders.length > 0) return {
|
|
2681
|
+
status: "deferred",
|
|
2682
|
+
holders
|
|
2683
|
+
};
|
|
2684
|
+
await createSharedHistoryTables(tx, dialect, sessionForkTables(prefix));
|
|
2685
|
+
await statementBatch(tx, [
|
|
2686
|
+
dialect.dropTrigger(legacyForkLinksTriggerName(tables.entries), tables.entries, true),
|
|
2687
|
+
dialect.versionedMigrations && {
|
|
2688
|
+
sql: `INSERT INTO ${storageMigrationTable(prefix)} (domain, version, applied_at) VALUES (?, ?, ${dialect.nowMs}) ON CONFLICT DO NOTHING`,
|
|
2689
|
+
params: ["sessions", 3]
|
|
2690
|
+
},
|
|
2691
|
+
{
|
|
2692
|
+
sql: `UPDATE ${tables.meta} SET schema_version = ? WHERE schema_version < ?`,
|
|
2693
|
+
params: [3, 3]
|
|
2694
|
+
}
|
|
2695
|
+
], []);
|
|
2696
|
+
return { status: "enabled" };
|
|
2697
|
+
}, {
|
|
2698
|
+
retryTransientFailures: true,
|
|
2699
|
+
concurrency: { kind: "serial" }
|
|
2700
|
+
});
|
|
2701
|
+
}
|
|
2702
|
+
/**
|
|
2703
|
+
* An open's switch to shared-history forks, true when it switched the database. With `precheck`, for an open that
|
|
2704
|
+
* read the schema without a lock, it first reads, still without one, the version and the markers of older builds
|
|
2705
|
+
* together, so an open that must leave the switch for later, while an older build runs a session, takes no lock and
|
|
2706
|
+
* writes nothing; an open that set the schema up under the write lock goes straight to the switch. A switch that cannot run, such as for a role without the
|
|
2707
|
+
* privilege to create tables, is left for a later open or `atomic storage migrate`; forks copy meanwhile. Either way
|
|
2708
|
+
* the open goes on, and only the debug log notes it.
|
|
2709
|
+
*/
|
|
2710
|
+
static async switchAtOpen(database, prefix, tables, markers, precheck) {
|
|
2711
|
+
const host = sharedHistorySwitchHost();
|
|
2712
|
+
const deferred = (holders) => host.skipped({
|
|
2713
|
+
reason: "older-sessions-running",
|
|
2714
|
+
prefix,
|
|
2715
|
+
sessions: holders.length,
|
|
2716
|
+
holders: holders.map((holder) => `${holder.host}:${holder.pid}`).join(", ")
|
|
2717
|
+
});
|
|
2718
|
+
try {
|
|
2719
|
+
if (precheck) {
|
|
2720
|
+
const [found, older] = await statementBatch(database, [], [() => database.get(`SELECT max(schema_version) AS schema_version FROM ${tables.meta}`), () => markers.olderThan(database, 3)]);
|
|
2721
|
+
if (Number(found?.schema_version) >= 3) return false;
|
|
2722
|
+
const holders = await liveMarkers(older, host.live);
|
|
2723
|
+
if (holders.length > 0) {
|
|
2724
|
+
deferred(holders);
|
|
2725
|
+
return false;
|
|
2726
|
+
}
|
|
2727
|
+
}
|
|
2728
|
+
const outcome = await SqlSessionStore.switchSharedHistory(database, prefix, tables, markers, host.live);
|
|
2729
|
+
if (outcome.status === "deferred") deferred(outcome.holders);
|
|
2730
|
+
return outcome.status === "enabled";
|
|
2731
|
+
} catch (error) {
|
|
2732
|
+
host.skipped({
|
|
2733
|
+
reason: "switch-failed",
|
|
2734
|
+
prefix,
|
|
2735
|
+
error: error.message
|
|
2736
|
+
});
|
|
2737
|
+
return false;
|
|
2738
|
+
}
|
|
1576
2739
|
}
|
|
1577
2740
|
get descriptor() {
|
|
1578
2741
|
return {
|
|
@@ -1584,24 +2747,45 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
1584
2747
|
this.assertOpen();
|
|
1585
2748
|
validateSessionHeader(header);
|
|
1586
2749
|
validateSessionEntries(entries);
|
|
1587
|
-
|
|
1588
|
-
|
|
2750
|
+
const tombstones = this.sharedHistorySeen;
|
|
2751
|
+
const existing = tombstones ? {
|
|
2752
|
+
sql: `SELECT (SELECT id FROM ${this.tables.sessions} WHERE id = ?) AS id, (SELECT session_id FROM ${this.forkTables.forkTombstones} WHERE session_id = ?) AS tombstone`,
|
|
2753
|
+
params: [header.id, header.id]
|
|
2754
|
+
} : {
|
|
2755
|
+
sql: `SELECT id FROM ${this.tables.sessions} WHERE id = ?`,
|
|
2756
|
+
params: [header.id]
|
|
2757
|
+
};
|
|
2758
|
+
let written = [];
|
|
2759
|
+
let writtenRow;
|
|
2760
|
+
const created = await this.transactionCheckedAlongside(async (tx, checked) => {
|
|
2761
|
+
writtenRow = void 0;
|
|
2762
|
+
const found = await tx.get(existing.sql, ...existing.params);
|
|
2763
|
+
if (found?.id != null) throw new SessionExistsError$1(header.id);
|
|
2764
|
+
if (await this.sharedHistoryForks(tx) && (tombstones ? found?.tombstone != null : await this.hasForkTombstone(tx, header.id))) await createOverTombstoneWithin(this.forkHost(), tx, header.id).catch((error) => {
|
|
2765
|
+
noteForkCopyRefusal(error, "create");
|
|
2766
|
+
throw error;
|
|
2767
|
+
});
|
|
1589
2768
|
const summary = this.summaryWrite(header.id, {
|
|
1590
2769
|
header,
|
|
1591
2770
|
entries,
|
|
1592
2771
|
lastSeq: entries.length
|
|
1593
2772
|
});
|
|
1594
2773
|
await checked;
|
|
1595
|
-
|
|
2774
|
+
written = [];
|
|
2775
|
+
writtenRow = summary.row;
|
|
2776
|
+
await this.writeEntries(tx, summary.statement, this.entryWrites(header.id, entries, 0, summary.texts, true, written));
|
|
1596
2777
|
return {
|
|
1597
2778
|
lastSeq: entries.length,
|
|
1598
2779
|
epoch: summary.epoch
|
|
1599
2780
|
};
|
|
1600
|
-
},
|
|
2781
|
+
}, this.sessionWrite(header.id, existing));
|
|
2782
|
+
this.noteWritten(header.id, created.epoch, written);
|
|
2783
|
+
this.rememberWritten(header.id, writtenRow);
|
|
2784
|
+
return created;
|
|
1601
2785
|
}
|
|
1602
2786
|
async createFork(header, entries, source) {
|
|
1603
2787
|
if (this.create !== SqlSessionStore.prototype.create) return void 0;
|
|
1604
|
-
if (source.store
|
|
2788
|
+
if (!this.sharesTablesWith(source.store)) {
|
|
1605
2789
|
if ("read" in entries) return entries.kind === "complete-session" ? this.createStagedFork(header, entries, source) : void 0;
|
|
1606
2790
|
if (source.receipts.size < 2) return void 0;
|
|
1607
2791
|
return this.createStagedFork(header, { async *read() {
|
|
@@ -1615,37 +2799,241 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
1615
2799
|
this.assertOpen();
|
|
1616
2800
|
validateSessionHeader(header);
|
|
1617
2801
|
validateSessionEntries(entries);
|
|
1618
|
-
|
|
1619
|
-
|
|
1620
|
-
const
|
|
1621
|
-
|
|
1622
|
-
|
|
1623
|
-
|
|
1624
|
-
|
|
1625
|
-
|
|
1626
|
-
|
|
1627
|
-
|
|
1628
|
-
|
|
1629
|
-
|
|
1630
|
-
if (!ref) continue;
|
|
1631
|
-
if (source.sessionId !== ref.sessionId || donor.epoch !== ref.epoch || donor.lastSeq < ref.seq) throw new SessionConflictError$1(ref.sessionId, ref.seq, donor.lastSeq);
|
|
1632
|
-
const original = await tx.get(`SELECT chunks FROM ${this.tables.entries} WHERE session_id=? AND seq=? AND entry_id=?`, ref.sessionId, ref.seq, entry.id);
|
|
1633
|
-
if (!original) throw new SessionConflictError$1(ref.sessionId, ref.seq, donor.lastSeq);
|
|
1634
|
-
await tx.run(`DELETE FROM ${this.tables.entries} WHERE session_id=? AND seq=?`, header.id, i + 1);
|
|
1635
|
-
await tx.run(`INSERT INTO ${this.tables.entries} (session_id, seq, entry_id, entry_json, chunks) SELECT ?, ?, entry_id,entry_json,chunks FROM ${this.tables.entries} WHERE session_id=? AND seq=?`, header.id, i + 1, ref.sessionId, ref.seq);
|
|
1636
|
-
for (let part = 0; part < original.chunks; part++) {
|
|
1637
|
-
const { changes } = await tx.run(`INSERT INTO ${this.tables.entryChunks} (session_id, seq, idx, data) SELECT ?, ?, idx, data FROM ${this.tables.entryChunks} WHERE session_id=? AND seq=? AND idx=?`, header.id, i + 1, ref.sessionId, ref.seq, part);
|
|
1638
|
-
if (changes !== 1) throw new StorageUnavailableError$1(this.descriptor, /* @__PURE__ */ new Error(`Missing chunk of session entry ${ref.seq}`));
|
|
1639
|
-
}
|
|
2802
|
+
if (source.receipts.size === 0 && source.hashes.length === 0 && (!this.sharedHistorySeen || source.epoch === void 0)) return void 0;
|
|
2803
|
+
for (let attempt = 0;; attempt++) {
|
|
2804
|
+
const reads = this.sharedHistorySeen ? this.sharedForkReads(header.id, source.sessionId, false) : void 0;
|
|
2805
|
+
try {
|
|
2806
|
+
return await this.transactionCheckedAlongside((tx, checked) => this.writeEntriesFork(tx, checked, header, entries, source, reads), this.sessionWrite(header.id, ...reads === void 0 ? [] : [
|
|
2807
|
+
reads.exists,
|
|
2808
|
+
reads.lock,
|
|
2809
|
+
reads.tombstones,
|
|
2810
|
+
reads.segments
|
|
2811
|
+
]));
|
|
2812
|
+
} catch (error) {
|
|
2813
|
+
if (!(error instanceof ForkSourcesMoved) || attempt >= 3) throw error;
|
|
1640
2814
|
}
|
|
1641
|
-
|
|
1642
|
-
|
|
2815
|
+
}
|
|
2816
|
+
}
|
|
2817
|
+
/**
|
|
2818
|
+
* A fork from the entries a caller holds. Where the database has shared history (#6560) and the source is still in
|
|
2819
|
+
* the generation the fork read it in, every entry the store read from the source and the caller kept unchanged, and
|
|
2820
|
+
* every receipt, is named by the child's segments, not stored again: the child stores only the entries it changed or
|
|
2821
|
+
* added, and their blobs. Otherwise the entries are stored as `create` stores them, receipts as the source stores
|
|
2822
|
+
* them. Undefined, with nothing written, for entries with neither receipts nor blobs that share nothing: `create`
|
|
2823
|
+
* then stores them, needing nothing of the source, so a source that changed or went away meanwhile does not fail it.
|
|
2824
|
+
*/
|
|
2825
|
+
async writeEntriesFork(tx, checked, header, entries, source, reads) {
|
|
2826
|
+
const needsSource = source.receipts.size > 0 || source.hashes.length > 0;
|
|
2827
|
+
let shared;
|
|
2828
|
+
const unchecked = {
|
|
2829
|
+
...source,
|
|
2830
|
+
epoch: void 0
|
|
2831
|
+
};
|
|
2832
|
+
const sharedRead = this.leadingForkDonor(tx, header.id, unchecked, reads);
|
|
2833
|
+
if (await this.sharedHistoryForks(tx)) try {
|
|
2834
|
+
shared = await (sharedRead ?? this.sharedForkDonor(tx, header.id, unchecked, this.sharedForkReads(header.id, source.sessionId, false)));
|
|
2835
|
+
} catch (error) {
|
|
2836
|
+
if (needsSource || !(error instanceof SessionNotFoundError$1)) throw error;
|
|
2837
|
+
return;
|
|
2838
|
+
}
|
|
2839
|
+
const sharing = shared !== void 0 && source.epoch !== void 0 && shared.epoch === source.epoch;
|
|
2840
|
+
if (!sharing && !needsSource) return void 0;
|
|
2841
|
+
if (shared !== void 0 && source.epoch !== void 0 && shared.epoch !== source.epoch) throw new SessionConflictError$1(source.sessionId, 0, shared.lastSeq);
|
|
2842
|
+
const donor = shared ?? await this.forkDonor(tx, header.id, source);
|
|
2843
|
+
for (const entry of entries) {
|
|
2844
|
+
const ref = source.receipts.get(entry.id);
|
|
2845
|
+
if (ref && (source.sessionId !== ref.sessionId || donor.epoch !== ref.epoch || donor.lastSeq < ref.seq)) throw new SessionConflictError$1(ref.sessionId, ref.seq, donor.lastSeq);
|
|
2846
|
+
}
|
|
2847
|
+
const summary = this.summaryWrite(header.id, {
|
|
2848
|
+
header,
|
|
2849
|
+
entries,
|
|
2850
|
+
lastSeq: entries.length
|
|
2851
|
+
});
|
|
2852
|
+
await checked;
|
|
2853
|
+
const tables = await this.viewTables(tx);
|
|
2854
|
+
const writes = new SentWrites(tx);
|
|
2855
|
+
if (!sharing) {
|
|
2856
|
+
const blobs = this.forkBlobCopy(source.sessionId, header.id, source.hashes);
|
|
2857
|
+
const remainingBlobs = await writes.around(async () => {
|
|
2858
|
+
await writes.send([summary.statement]);
|
|
2859
|
+
await writes.send(this.receiptForkWrites(tables, header.id, entries, source, donor.lastSeq));
|
|
2860
|
+
await writes.send(this.entryWrites(header.id, [], 0, summary.texts, false));
|
|
2861
|
+
return this.finishForkCopy(tx, writes, header.id, blobs, source.hashes);
|
|
2862
|
+
});
|
|
2863
|
+
await this.finishFork(tx, header.id);
|
|
1643
2864
|
return {
|
|
1644
2865
|
lastSeq: entries.length,
|
|
1645
|
-
epoch,
|
|
2866
|
+
epoch: summary.epoch,
|
|
1646
2867
|
remainingBlobs
|
|
1647
2868
|
};
|
|
1648
|
-
}
|
|
2869
|
+
}
|
|
2870
|
+
const places = [];
|
|
2871
|
+
const stored = storedRows(source.sessionId, source.epoch);
|
|
2872
|
+
let sharedThrough = 0;
|
|
2873
|
+
for (const entry of entries) {
|
|
2874
|
+
const seq = source.receipts.get(entry.id)?.seq ?? stored?.seqOf(entry, sharedThrough);
|
|
2875
|
+
const shares = seq !== void 0 && seq > sharedThrough && seq <= donor.lastSeq;
|
|
2876
|
+
if (shares) sharedThrough = seq;
|
|
2877
|
+
places.push(shares ? seq : void 0);
|
|
2878
|
+
}
|
|
2879
|
+
const hashes = /* @__PURE__ */ new Set();
|
|
2880
|
+
let copiesReceipts = false;
|
|
2881
|
+
for (const [index, entry] of entries.entries()) {
|
|
2882
|
+
if (places[index] !== void 0) continue;
|
|
2883
|
+
copiesReceipts ||= source.receipts.has(entry.id);
|
|
2884
|
+
if (entry.type !== "custom" || entry.customType !== "atomic.tool-output") continue;
|
|
2885
|
+
const hash = entry.data?.hash;
|
|
2886
|
+
if (typeof hash === "string" && source.hashes.includes(hash)) hashes.add(hash);
|
|
2887
|
+
}
|
|
2888
|
+
const statements = this.sharedEntriesForkWrites(tables, header, entries, places, source, shared, summary.texts);
|
|
2889
|
+
if (!copiesReceipts && hashes.size === 0) {
|
|
2890
|
+
await this.writeEntries(tx, summary.statement, [...statements, this.forkVersionStep(header.id)]);
|
|
2891
|
+
return {
|
|
2892
|
+
lastSeq: entries.length,
|
|
2893
|
+
epoch: summary.epoch,
|
|
2894
|
+
remainingBlobs: []
|
|
2895
|
+
};
|
|
2896
|
+
}
|
|
2897
|
+
const remainingBlobs = await writes.around(async () => {
|
|
2898
|
+
await writes.send([summary.statement]);
|
|
2899
|
+
await writes.send(statements);
|
|
2900
|
+
return this.finishForkCopy(tx, writes, header.id, this.forkBlobCopy(source.sessionId, header.id, hashes), hashes);
|
|
2901
|
+
});
|
|
2902
|
+
await this.finishFork(tx, header.id);
|
|
2903
|
+
return {
|
|
2904
|
+
lastSeq: entries.length,
|
|
2905
|
+
epoch: summary.epoch,
|
|
2906
|
+
remainingBlobs
|
|
2907
|
+
};
|
|
2908
|
+
}
|
|
2909
|
+
/**
|
|
2910
|
+
* The statements of a fork from `entries` with shared history (#6560), in seq order, after its session row: the
|
|
2911
|
+
* segments that name the rows `places` puts in the source, each entry it does not as {@link entryForkWrites} stores it,
|
|
2912
|
+
* the search texts of those, and the lineage row. Throws, before the last of them, unless the segments are well formed.
|
|
2913
|
+
*/
|
|
2914
|
+
*sharedEntriesForkWrites(tables, header, entries, places, source, donor, texts) {
|
|
2915
|
+
const lineage = this.lineageTables();
|
|
2916
|
+
const runs = new ForkSegmentRuns(lineage, header.id, {
|
|
2917
|
+
id: source.sessionId,
|
|
2918
|
+
segments: donor.segments,
|
|
2919
|
+
length: donor.lastSeq
|
|
2920
|
+
});
|
|
2921
|
+
yield* this.receiptForkWrites(tables, header.id, entries, source, donor.lastSeq, places, runs);
|
|
2922
|
+
yield* runs.drain();
|
|
2923
|
+
yield* this.entryWrites(header.id, [], 0, texts.filter((text) => places[text.index] === void 0), false);
|
|
2924
|
+
assertForkSegments(header.id, runs.segments, entries.length);
|
|
2925
|
+
yield forkLineageWrite(lineage, header.id, {
|
|
2926
|
+
parentId: source.sessionId,
|
|
2927
|
+
cutSeq: donor.lastSeq
|
|
2928
|
+
});
|
|
2929
|
+
if (runs.segments.length > 0) {
|
|
2930
|
+
for (const [index, place] of places.entries()) if (place === void 0) yield this.forkLinks().entry(header.id, index + 1);
|
|
2931
|
+
}
|
|
2932
|
+
}
|
|
2933
|
+
/**
|
|
2934
|
+
* The source session's head, its row locked for share, once the child is known to be new: both reads go out together,
|
|
2935
|
+
* one round trip (#6560). Fails as the source changed when it is no longer the generation the fork read.
|
|
2936
|
+
*/
|
|
2937
|
+
async forkDonor(tx, child, source) {
|
|
2938
|
+
const existing = tx.get(`SELECT id FROM ${this.tables.sessions} WHERE id = ?`, child);
|
|
2939
|
+
const head = this.historyHead(tx, source.sessionId).then((value) => ({ value }), (error) => ({ error }));
|
|
2940
|
+
if (await existing) throw new SessionExistsError$1(child);
|
|
2941
|
+
const read = await head;
|
|
2942
|
+
if ("error" in read) throw read.error;
|
|
2943
|
+
const donor = read.value;
|
|
2944
|
+
if (source.epoch !== void 0 && donor.epoch !== source.epoch) throw new SessionConflictError$1(source.sessionId, 0, donor.lastSeq);
|
|
2945
|
+
return donor;
|
|
2946
|
+
}
|
|
2947
|
+
/**
|
|
2948
|
+
* The statements that store a fork's `entries`, in seq order: an entry with a receipt as the source stores it, its row
|
|
2949
|
+
* and chunks copied in two statements whatever their size, and a run of others as `create` stores them, several rows
|
|
2950
|
+
* a statement. A receipt's row that names another entry fails the fork: the source changed under it. With `places`
|
|
2951
|
+
* and `runs`, an entry `places` puts in the source is named by `runs`' segments instead, and the segments before an
|
|
2952
|
+
* entry the child stores go first, for the snapshot index's triggers.
|
|
2953
|
+
*/
|
|
2954
|
+
*receiptForkWrites(tables, child, entries, source, donorLastSeq, places = [], runs) {
|
|
2955
|
+
let from = 0;
|
|
2956
|
+
let own = 0;
|
|
2957
|
+
for (const [index, entry] of entries.entries()) {
|
|
2958
|
+
const seq = places[index];
|
|
2959
|
+
if (seq === void 0 && !source.receipts.has(entry.id)) {
|
|
2960
|
+
if (own === 0) {
|
|
2961
|
+
if (runs !== void 0) yield* runs.drain();
|
|
2962
|
+
from = index;
|
|
2963
|
+
}
|
|
2964
|
+
own++;
|
|
2965
|
+
continue;
|
|
2966
|
+
}
|
|
2967
|
+
if (own > 0) yield* this.entryWrites(child, entries.slice(from, from + own), from, [], false);
|
|
2968
|
+
own = 0;
|
|
2969
|
+
if (seq !== void 0) {
|
|
2970
|
+
runs.add(seq, index + 1, entry.id);
|
|
2971
|
+
if (runs.full) yield* runs.drain();
|
|
2972
|
+
continue;
|
|
2973
|
+
}
|
|
2974
|
+
if (runs !== void 0) yield* runs.drain();
|
|
2975
|
+
yield* this.entryForkWrites(tables, child, index, entry, source, donorLastSeq);
|
|
2976
|
+
}
|
|
2977
|
+
if (own > 0) yield* this.entryWrites(child, entries.slice(from, from + own), from, [], false);
|
|
2978
|
+
}
|
|
2979
|
+
/** The statements of {@link receiptForkWrites} that store `entry`, at index `index` of the fork's entries. */
|
|
2980
|
+
*entryForkWrites(tables, child, index, entry, source, donorLastSeq) {
|
|
2981
|
+
const ref = source.receipts.get(entry.id);
|
|
2982
|
+
if (ref === void 0) {
|
|
2983
|
+
yield* this.entryWrites(child, [entry], index, [], false);
|
|
2984
|
+
return;
|
|
2985
|
+
}
|
|
2986
|
+
const view = this.entriesView(tables, ref.sessionId, ref.seq - 1, ref.seq);
|
|
2987
|
+
yield {
|
|
2988
|
+
sql: withForkViews([view], `INSERT INTO ${this.tables.entries} (session_id, seq, entry_id, entry_json, chunks) SELECT ?, ?, entry_id, entry_json, chunks FROM ${view.name} WHERE entry_id = ?`),
|
|
2989
|
+
params: [
|
|
2990
|
+
...view.params,
|
|
2991
|
+
child,
|
|
2992
|
+
index + 1,
|
|
2993
|
+
entry.id
|
|
2994
|
+
],
|
|
2995
|
+
changes: 1,
|
|
2996
|
+
mismatch: () => new SessionConflictError$1(ref.sessionId, ref.seq, donorLastSeq)
|
|
2997
|
+
};
|
|
2998
|
+
yield {
|
|
2999
|
+
sql: withForkViews([view], `INSERT INTO ${this.tables.entryChunks} (session_id, seq, idx, data) SELECT ?, ?, c.idx, c.data FROM ${view.name} v JOIN ${this.tables.entryChunks} c ON c.session_id = v.src_id AND c.seq = v.src_seq WHERE c.idx >= 0 AND c.idx < v.chunks ORDER BY c.idx`),
|
|
3000
|
+
params: [
|
|
3001
|
+
...view.params,
|
|
3002
|
+
child,
|
|
3003
|
+
index + 1
|
|
3004
|
+
]
|
|
3005
|
+
};
|
|
3006
|
+
}
|
|
3007
|
+
/**
|
|
3008
|
+
* The blob copy of a fork from session `source` of this store's tables (#6560), or undefined when a subclass stores
|
|
3009
|
+
* blobs its own way: `createForkArchive` then copies every one through it.
|
|
3010
|
+
*/
|
|
3011
|
+
forkBlobCopy(source, child, hashes) {
|
|
3012
|
+
if (this.getBlob !== SqlSessionStore.prototype.getBlob || this.putBlob !== SqlSessionStore.prototype.putBlob) return void 0;
|
|
3013
|
+
return forkBlobCopy(this.tables, {
|
|
3014
|
+
legacyBlobData: this.legacyBlobData,
|
|
3015
|
+
chunkBytes: SESSION_BLOB_CHUNK_BYTES
|
|
3016
|
+
}, source, child, [...new Set(hashes)]);
|
|
3017
|
+
}
|
|
3018
|
+
/**
|
|
3019
|
+
* Sends a fork's blob copy behind its entries, then checks, in one round trip with them, that every stored entry of
|
|
3020
|
+
* the child has all its chunks and which blobs were copied whole. Resolves with the hashes left for
|
|
3021
|
+
* `copySessionBlobs`: those the source does not hold, or all of them where this store does not copy blobs itself.
|
|
3022
|
+
*/
|
|
3023
|
+
async finishForkCopy(tx, writes, child, blobs, hashes) {
|
|
3024
|
+
if (blobs) await writes.send(blobs.statements);
|
|
3025
|
+
const incomplete = incompleteEntryRead(this.tables, child);
|
|
3026
|
+
const [missing, ...answers] = await Promise.all([tx.get(incomplete.sql, ...incomplete.params), ...(blobs?.checks ?? []).map((check) => tx.all(check.sql, ...check.params))]);
|
|
3027
|
+
if (missing !== void 0) throw new StorageUnavailableError$1(this.descriptor, /* @__PURE__ */ new Error(`Missing chunk of session entry ${missing.seq}`));
|
|
3028
|
+
return blobs ? blobs.remaining(answers) : [...new Set(hashes)];
|
|
3029
|
+
}
|
|
3030
|
+
/**
|
|
3031
|
+
* Whether `store` keeps its sessions in this store's very tables, so that this store's transaction reads its rows: this
|
|
3032
|
+
* store, or another session store opened on the same database with the same prefix, such as through another handle
|
|
3033
|
+
* (#6560). A wrapper that serves sessions of its own does not.
|
|
3034
|
+
*/
|
|
3035
|
+
sharesTablesWith(store) {
|
|
3036
|
+
return store === this || store instanceof SqlSessionStore && forkStoreRelation(store, this) === "same";
|
|
1649
3037
|
}
|
|
1650
3038
|
/**
|
|
1651
3039
|
* Clone a complete session, as `create` with every source entry and blob would, from a store on a handle this one
|
|
@@ -1669,6 +3057,82 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
1669
3057
|
await ensureForkStagingTable(this.database, this.dialect, this.forkStagingTable);
|
|
1670
3058
|
await cleanupForkStaging(this.database, this.dialect, this.forkStagingTable, Number.POSITIVE_INFINITY);
|
|
1671
3059
|
}
|
|
3060
|
+
/**
|
|
3061
|
+
* Creates the chat records' table and index unless the ledger records them, as `atomic storage migrate` does as the
|
|
3062
|
+
* owner role: a runtime role without DDL privileges then saves chat records too. Opens never create them; the first
|
|
3063
|
+
* chat record does where `migrate` has not run.
|
|
3064
|
+
*/
|
|
3065
|
+
async prepareChatRecords() {
|
|
3066
|
+
this.assertOpen();
|
|
3067
|
+
await this.chatRecords?.initialize();
|
|
3068
|
+
}
|
|
3069
|
+
/** Whether a deleted session with ID `sessionId` left rows forks still read. */
|
|
3070
|
+
async hasForkTombstone(tx, sessionId) {
|
|
3071
|
+
return await tx.get(`SELECT session_id FROM ${this.forkTables.forkTombstones} WHERE session_id = ?`, sessionId) !== void 0;
|
|
3072
|
+
}
|
|
3073
|
+
/** This store's side of detaching and pinning shared fork history: see fork-detach-host.ts. */
|
|
3074
|
+
forkHost() {
|
|
3075
|
+
return forkDetachHost({
|
|
3076
|
+
dialect: this.dialect,
|
|
3077
|
+
tables: this.tables,
|
|
3078
|
+
forkTables: this.forkTables,
|
|
3079
|
+
blobs: {
|
|
3080
|
+
legacyBlobData: this.legacyBlobData,
|
|
3081
|
+
chunkBytes: SESSION_BLOB_CHUNK_BYTES
|
|
3082
|
+
},
|
|
3083
|
+
materializedLinks: this.forkLinks().materialized,
|
|
3084
|
+
transaction: (body) => this.transaction(body, SESSION_TRANSACTION)
|
|
3085
|
+
});
|
|
3086
|
+
}
|
|
3087
|
+
/** The statements that link the entries a session with fork segments stores, as a copy links them (#6560). */
|
|
3088
|
+
forkLinks() {
|
|
3089
|
+
const index = snapshotIndexTables$1(this.prefix);
|
|
3090
|
+
this.forkLinkStatements ??= forkLinkWrites({
|
|
3091
|
+
entries: this.tables.entries,
|
|
3092
|
+
sessionLinks: index.sessionLinks,
|
|
3093
|
+
sources: index.sources,
|
|
3094
|
+
forkSegments: this.forkTables.forkSegments
|
|
3095
|
+
}, this.dialect);
|
|
3096
|
+
return this.forkLinkStatements;
|
|
3097
|
+
}
|
|
3098
|
+
/**
|
|
3099
|
+
* @internal Gives every fork that shares history with `sessionId` its own copy of what it reads, so the session's
|
|
3100
|
+
* rows no longer stay for them; see fork-detach.ts. Detaches a crash stopped are finished first. Nothing to do where
|
|
3101
|
+
* shared-history forks are off.
|
|
3102
|
+
*/
|
|
3103
|
+
async detachForks(sessionId, options = {}) {
|
|
3104
|
+
this.assertOpen();
|
|
3105
|
+
validateSessionText("sessionId", sessionId);
|
|
3106
|
+
if (!await this.transaction((tx) => this.sharedHistoryForks(tx), SESSION_TRANSACTION)) return {
|
|
3107
|
+
detached: [],
|
|
3108
|
+
reparented: []
|
|
3109
|
+
};
|
|
3110
|
+
const report = await detachForkChildren(this.forkHost(), sessionId, options).catch((error) => {
|
|
3111
|
+
noteForkCopyRefusal(error, "detach");
|
|
3112
|
+
throw error;
|
|
3113
|
+
});
|
|
3114
|
+
await this.sweepReleasedForkRows([sessionId]);
|
|
3115
|
+
return report;
|
|
3116
|
+
}
|
|
3117
|
+
/** @internal Finishes every detach a crash stopped. Nothing to do where shared-history forks are off. */
|
|
3118
|
+
async resumeForkDetaches() {
|
|
3119
|
+
this.assertOpen();
|
|
3120
|
+
if (!await this.transaction((tx) => this.sharedHistoryForks(tx), SESSION_TRANSACTION)) return {
|
|
3121
|
+
detached: [],
|
|
3122
|
+
reparented: []
|
|
3123
|
+
};
|
|
3124
|
+
return resumeForkDetaches(this.forkHost());
|
|
3125
|
+
}
|
|
3126
|
+
/**
|
|
3127
|
+
* @internal Removes the rows of deleted sessions that no fork reads any more, a batch per transaction: `sessionIds`,
|
|
3128
|
+
* and a few any earlier sweep left. Resolves with the sessions whose rows went.
|
|
3129
|
+
*/
|
|
3130
|
+
async sweepForkTombstones(sessionIds = [], batchEntries) {
|
|
3131
|
+
this.assertOpen();
|
|
3132
|
+
if (!await this.transaction((tx) => this.sharedHistoryForks(tx), SESSION_TRANSACTION)) return [];
|
|
3133
|
+
const { sweepForkTombstones } = await import("../core/storage/session/fork-sweep.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
|
|
3134
|
+
return sweepForkTombstones(this.forkHost(), sessionIds, batchEntries === void 0 ? {} : { batchEntries });
|
|
3135
|
+
}
|
|
1672
3136
|
forkStagingTarget() {
|
|
1673
3137
|
return {
|
|
1674
3138
|
database: this.database,
|
|
@@ -1681,8 +3145,8 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
1681
3145
|
unchunkedSchemaVersion: SESSION_SCHEMA_VERSION_UNCHUNKED,
|
|
1682
3146
|
chunkedSchemaVersion: 2,
|
|
1683
3147
|
ownsBlobs: this.getBlob === SqlSessionStore.prototype.getBlob && this.putBlob === SqlSessionStore.prototype.putBlob,
|
|
1684
|
-
transaction: (body) => this.transaction(body,
|
|
1685
|
-
|
|
3148
|
+
transaction: (sessionId, body, leading) => this.transaction(body, this.sessionWrite(sessionId, ...leading)),
|
|
3149
|
+
summaryWrite: (header, lastSeq, summary, index) => this.summaryWrite(header.id, {
|
|
1686
3150
|
header,
|
|
1687
3151
|
entries: [],
|
|
1688
3152
|
lastSeq
|
|
@@ -1704,6 +3168,10 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
1704
3168
|
sourceBlobParts: (source) => {
|
|
1705
3169
|
const store = nativeForkReader(source, "blob");
|
|
1706
3170
|
return store instanceof SqlSessionStore && store.getBlob === SqlSessionStore.prototype.getBlob ? (sessionId, hash, offset, legacyBytes) => store.readBlobPart(sessionId, hash, offset, legacyBytes) : void 0;
|
|
3171
|
+
},
|
|
3172
|
+
sourceBlobFirstParts: (source) => {
|
|
3173
|
+
const store = nativeForkReader(source, "blob");
|
|
3174
|
+
return store instanceof SqlSessionStore && store.getBlob === SqlSessionStore.prototype.getBlob ? (sessionId, hashes, maxBytes) => store.readBlobFirstParts(sessionId, hashes, maxBytes) : void 0;
|
|
1707
3175
|
}
|
|
1708
3176
|
};
|
|
1709
3177
|
}
|
|
@@ -1713,29 +3181,54 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
1713
3181
|
*/
|
|
1714
3182
|
async readStoredEntryChunk(reference, index) {
|
|
1715
3183
|
this.assertOpen();
|
|
1716
|
-
return this.
|
|
3184
|
+
return this.readTransaction(async (tx) => {
|
|
1717
3185
|
const { sessionId, epoch, seq } = reference;
|
|
1718
|
-
const head = await this.historyHead(tx, sessionId);
|
|
3186
|
+
const head = await this.historyHead(tx, sessionId, true);
|
|
1719
3187
|
if (head.epoch !== epoch) throw new SessionConflictError$1(sessionId, seq, head.lastSeq);
|
|
1720
|
-
const
|
|
1721
|
-
|
|
3188
|
+
const view = this.entriesView(await this.viewTables(tx, sessionId), sessionId, seq - 1, seq);
|
|
3189
|
+
const row = await tx.get(withForkViews([view], `SELECT e.chunks, c.data FROM ${view.name} e LEFT JOIN ${this.tables.entryChunks} c
|
|
3190
|
+
ON c.session_id = e.src_id AND c.seq = e.src_seq AND c.idx = ?`), ...view.params, index);
|
|
1722
3191
|
if (!row) throw new StorageUnavailableError$1(this.descriptor, /* @__PURE__ */ new Error(`Missing session entry ${seq}`));
|
|
1723
3192
|
if (Number(row.chunks) === 0) return void 0;
|
|
1724
3193
|
if (row.data == null) throw new StorageUnavailableError$1(this.descriptor, /* @__PURE__ */ new Error(`Missing chunk of session entry ${seq}`));
|
|
1725
3194
|
return row.data;
|
|
1726
|
-
}
|
|
3195
|
+
});
|
|
1727
3196
|
}
|
|
1728
3197
|
/** How many chunks the entry `reference` names is stored in, 0 when it is stored whole, in its generation. */
|
|
1729
3198
|
async readStoredChunks(reference) {
|
|
1730
3199
|
this.assertOpen();
|
|
1731
|
-
return this.
|
|
3200
|
+
return this.readTransaction(async (tx) => {
|
|
1732
3201
|
const { sessionId, epoch, seq } = reference;
|
|
1733
|
-
const head = await this.historyHead(tx, sessionId);
|
|
3202
|
+
const head = await this.historyHead(tx, sessionId, true);
|
|
1734
3203
|
if (head.epoch !== epoch) throw new SessionConflictError$1(sessionId, seq, head.lastSeq);
|
|
1735
|
-
const
|
|
3204
|
+
const view = this.entriesView(await this.viewTables(tx, sessionId), sessionId, seq - 1, seq);
|
|
3205
|
+
const row = await tx.get(withForkViews([view], `SELECT chunks FROM ${view.name}`), ...view.params);
|
|
1736
3206
|
if (!row) throw new StorageUnavailableError$1(this.descriptor, /* @__PURE__ */ new Error(`Missing session entry ${seq}`));
|
|
1737
3207
|
return Number(row.chunks);
|
|
1738
|
-
}
|
|
3208
|
+
});
|
|
3209
|
+
}
|
|
3210
|
+
/**
|
|
3211
|
+
* The headers of the blobs `hashes` of session `sessionId` in one read (#6560), each with its first chunk row when it
|
|
3212
|
+
* is stored in chunks of at most `maxBytes` in all, as `readBlobPart` reads them at offset 0. A blob the session does
|
|
3213
|
+
* not hold is left out; one in the legacy one-row layout comes without its value.
|
|
3214
|
+
*/
|
|
3215
|
+
async readBlobFirstParts(sessionId, hashes, maxBytes) {
|
|
3216
|
+
this.assertOpen();
|
|
3217
|
+
const parts = /* @__PURE__ */ new Map();
|
|
3218
|
+
if (hashes.length === 0) return parts;
|
|
3219
|
+
const rows = await this.outsideTransaction((tables) => this.database.all(`SELECT b.hash, b.bytes, b.chunks, CASE WHEN b.chunks >= 0 AND b.bytes <= ? THEN c.data END AS data,
|
|
3220
|
+
CASE WHEN w.place = 0 THEN 1 ELSE 0 END AS own
|
|
3221
|
+
FROM ${this.blobPlaces(tables)} w JOIN ${this.tables.blobs} b
|
|
3222
|
+
ON b.session_id = w.owner AND b.hash IN (${hashes.map(() => "?").join(", ")})
|
|
3223
|
+
LEFT JOIN ${this.tables.blobChunks} c ON c.session_id = b.session_id AND c.hash = b.hash AND c.idx = 0
|
|
3224
|
+
${tables.guard === void 0 ? "" : `WHERE ${tables.guard}`}
|
|
3225
|
+
ORDER BY own DESC, b.session_id`, maxBytes, ...this.blobPlaceParams(tables, sessionId), ...hashes), (found) => found.length > 0);
|
|
3226
|
+
for (const row of rows) if (!parts.has(String(row.hash))) parts.set(String(row.hash), {
|
|
3227
|
+
bytes: Number(row.bytes),
|
|
3228
|
+
chunks: Number(row.chunks),
|
|
3229
|
+
...row.data == null ? {} : { data: row.data }
|
|
3230
|
+
});
|
|
3231
|
+
return parts;
|
|
1739
3232
|
}
|
|
1740
3233
|
/**
|
|
1741
3234
|
* The bytes of a blob from `offset`, a multiple of {@link SESSION_BLOB_CHUNK_BYTES}, so a staged clone never holds
|
|
@@ -1747,8 +3240,11 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
1747
3240
|
this.assertOpen();
|
|
1748
3241
|
const cut = this.legacyBlobData && legacyBytes > 0;
|
|
1749
3242
|
const legacy = cut ? "CASE WHEN b.chunks = -1 THEN substr(b.data, ?, ?) ELSE c.data END" : "c.data";
|
|
1750
|
-
const row = await this.database.get(`SELECT b.bytes, b.chunks, ${legacy} AS data
|
|
1751
|
-
|
|
3243
|
+
const row = await this.outsideTransaction((tables) => this.database.get(`SELECT b.bytes, b.chunks, ${legacy} AS data
|
|
3244
|
+
FROM ${this.blobPlaces(tables)} w JOIN ${this.tables.blobs} b ON b.session_id = w.owner AND b.hash = ?
|
|
3245
|
+
LEFT JOIN ${this.tables.blobChunks} c ON c.session_id = b.session_id AND c.hash = b.hash AND c.idx = ?
|
|
3246
|
+
${tables.guard === void 0 ? "" : `WHERE ${tables.guard}`}
|
|
3247
|
+
ORDER BY w.place, b.session_id LIMIT 1`, ...cut ? [offset + 1, legacyBytes] : [], ...this.blobPlaceParams(tables, sessionId), hash, Math.floor(offset / SESSION_BLOB_CHUNK_BYTES)), (found) => found !== void 0);
|
|
1752
3248
|
if (row === void 0) return void 0;
|
|
1753
3249
|
return {
|
|
1754
3250
|
bytes: Number(row.bytes),
|
|
@@ -1756,83 +3252,126 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
1756
3252
|
...row.data == null ? {} : { data: row.data }
|
|
1757
3253
|
};
|
|
1758
3254
|
}
|
|
1759
|
-
|
|
1760
|
-
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
const columns = this.legacyBlobData ? ", data" : "";
|
|
1765
|
-
const { changes } = await tx.run(`INSERT INTO ${this.tables.blobs} (session_id,hash,bytes,chunks${columns}) SELECT ?,hash,bytes,chunks${columns} FROM ${this.tables.blobs} WHERE session_id=? AND hash=?${this.legacyBlobData ? " AND (chunks<>-1 OR length(data)=bytes)" : ""}`, childId, sessionId, hash);
|
|
1766
|
-
if (changes !== 1 || blob.chunks >= 0 && blob.chunks !== Math.ceil(blob.bytes / 1048576)) throw new SessionBlobError("blob-incomplete", {
|
|
1767
|
-
sessionId,
|
|
1768
|
-
hash,
|
|
1769
|
-
bytes: blob.bytes
|
|
1770
|
-
});
|
|
1771
|
-
for (let part = 0; part < blob.chunks; part++) if ((await tx.run(`INSERT INTO ${this.tables.blobChunks} (session_id,hash,idx,data) SELECT ?,hash,idx,data FROM ${this.tables.blobChunks} WHERE session_id=? AND hash=? AND idx=? AND length(data)=?`, childId, sessionId, hash, part, Math.min(1048576, blob.bytes - part * 1048576))).changes !== 1) throw new SessionBlobError("blob-incomplete", {
|
|
1772
|
-
sessionId,
|
|
1773
|
-
hash,
|
|
1774
|
-
bytes: blob.bytes
|
|
1775
|
-
});
|
|
1776
|
-
return true;
|
|
1777
|
-
}
|
|
3255
|
+
/**
|
|
3256
|
+
* A fork from a stream of the source's rows. Where the database has shared history (#6560), the child stores no copy
|
|
3257
|
+
* of the rows the source stores unchanged: its segments name them, and it stores only the rows the stream changed or
|
|
3258
|
+
* added. A stream of the source's whole history, as it stands, reads no row at all.
|
|
3259
|
+
*/
|
|
1778
3260
|
async createStreamedFork(header, stream, source) {
|
|
1779
3261
|
this.assertOpen();
|
|
1780
3262
|
validateSessionHeader(header);
|
|
3263
|
+
for (let attempt = 0;; attempt++) {
|
|
3264
|
+
const reads = this.sharedHistorySeen ? this.sharedForkReads(header.id, source.sessionId, stream.prefix !== void 0) : void 0;
|
|
3265
|
+
try {
|
|
3266
|
+
return await this.transactionCheckedAlongside((tx, checked) => this.writeStreamedFork(tx, checked, header, stream, source, reads), this.sessionWrite(header.id, ...reads === void 0 ? [] : [
|
|
3267
|
+
reads.exists,
|
|
3268
|
+
reads.lock,
|
|
3269
|
+
reads.tombstones,
|
|
3270
|
+
reads.segments
|
|
3271
|
+
]));
|
|
3272
|
+
} catch (error) {
|
|
3273
|
+
if (!(error instanceof ForkSourcesMoved) || attempt >= 3) throw error;
|
|
3274
|
+
}
|
|
3275
|
+
}
|
|
3276
|
+
}
|
|
3277
|
+
async writeStreamedFork(tx, checked, header, stream, source, reads) {
|
|
3278
|
+
const sharedRead = this.leadingForkDonor(tx, header.id, source, reads);
|
|
3279
|
+
const shared = await this.sharedHistoryForks(tx) ? await (sharedRead ?? this.sharedForkDonor(tx, header.id, source, this.sharedForkReads(header.id, source.sessionId, stream.prefix !== void 0))) : void 0;
|
|
3280
|
+
const head = shared ?? await this.forkDonor(tx, header.id, source);
|
|
3281
|
+
await checked;
|
|
1781
3282
|
const { encodedForkRow } = await import("../core/storage/session/fork-row-bytes.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
|
|
1782
3283
|
const { foldForkRow } = await import("../core/storage/session/fork-row-index.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
|
|
1783
|
-
|
|
1784
|
-
|
|
1785
|
-
const
|
|
1786
|
-
if (
|
|
1787
|
-
|
|
1788
|
-
|
|
1789
|
-
|
|
1790
|
-
|
|
1791
|
-
|
|
1792
|
-
|
|
1793
|
-
|
|
1794
|
-
|
|
1795
|
-
|
|
1796
|
-
|
|
1797
|
-
|
|
1798
|
-
|
|
1799
|
-
|
|
1800
|
-
|
|
1801
|
-
|
|
1802
|
-
|
|
1803
|
-
|
|
1804
|
-
|
|
1805
|
-
|
|
1806
|
-
|
|
1807
|
-
|
|
1808
|
-
|
|
1809
|
-
|
|
1810
|
-
|
|
1811
|
-
|
|
1812
|
-
|
|
1813
|
-
|
|
1814
|
-
|
|
1815
|
-
|
|
1816
|
-
|
|
1817
|
-
|
|
1818
|
-
|
|
1819
|
-
|
|
1820
|
-
|
|
1821
|
-
|
|
1822
|
-
|
|
3284
|
+
const prefix = stream.prefix;
|
|
3285
|
+
if (shared !== void 0 && prefix !== void 0 && prefix.sessionId === source.sessionId && prefix.through === shared.lastSeq && (prefix.epoch === void 0 || prefix.epoch === shared.epoch)) {
|
|
3286
|
+
const whole = await this.writeSharedPrefixFork(tx, header, source.sessionId, shared);
|
|
3287
|
+
if (whole !== void 0) return whole;
|
|
3288
|
+
}
|
|
3289
|
+
const reader = new SqlSessionStore({
|
|
3290
|
+
descriptor: this.database.descriptor,
|
|
3291
|
+
dialect: this.dialect,
|
|
3292
|
+
readOnly: true,
|
|
3293
|
+
exec: tx.exec.bind(tx),
|
|
3294
|
+
get: tx.get.bind(tx),
|
|
3295
|
+
run: tx.run.bind(tx),
|
|
3296
|
+
all: tx.all.bind(tx),
|
|
3297
|
+
transaction: async (cb) => cb(tx),
|
|
3298
|
+
close: async () => {}
|
|
3299
|
+
}, this.tables, this.prefix, this.cwdMatcher, this.blobTable, this.legacyBlobData, void 0, this.entryByteLength);
|
|
3300
|
+
reader.sharedHistorySeen = await this.sharedHistoryForks(tx);
|
|
3301
|
+
let donorIndex;
|
|
3302
|
+
reader.readBranchSpan = async (id, cut) => {
|
|
3303
|
+
donorIndex ??= reader.prepareResume(source.sessionId).then((prepared) => prepared.index);
|
|
3304
|
+
return transcriptBranchSpan(id, await donorIndex, cut);
|
|
3305
|
+
};
|
|
3306
|
+
reader.readEntryChunk = this.forkChunkReader(tx, await this.viewTables(tx), reader, source.sessionId, head.epoch);
|
|
3307
|
+
const copies = new ForkRowRuns(this.tables, header.id, source.sessionId);
|
|
3308
|
+
const lineage = this.lineageTables();
|
|
3309
|
+
const runs = shared === void 0 ? void 0 : new ForkSegmentRuns(lineage, header.id, {
|
|
3310
|
+
id: source.sessionId,
|
|
3311
|
+
segments: shared.segments,
|
|
3312
|
+
length: shared.lastSeq
|
|
3313
|
+
});
|
|
3314
|
+
const viewTables = await this.viewTables(tx);
|
|
3315
|
+
const lookup = async (id) => (runs ?? copies).heldSeq(id) ?? this.seqOfEntry(tx, viewTables, header.id, id);
|
|
3316
|
+
let summary = applySessionSummaryEntries(void 0, []).state;
|
|
3317
|
+
let index = foldSessionResume(void 0, []);
|
|
3318
|
+
let seq = 0;
|
|
3319
|
+
const hashes = /* @__PURE__ */ new Set();
|
|
3320
|
+
const inlineSnapshot = async (ref) => {
|
|
3321
|
+
const text = (key) => this.dialect.jsonText("entry_json", key);
|
|
3322
|
+
const ty = (key) => this.dialect.jsonType("entry_json", key);
|
|
3323
|
+
const view = this.entriesView(await this.viewTables(tx), ref.sessionId, ref.seq - 1, ref.seq);
|
|
3324
|
+
const s = await tx.get(withForkViews([view], `SELECT entry_id AS id,${text("parentId")} AS parent,${text("timestamp")} AS stamp,${text("root")} AS root,${text("snapshotId")} AS snapshot,${text("captureMs")} AS capture,${ty("snapshot")} AS record,${ty("restore")} AS restore,${ty("unrestored")} AS unrestored,${text("degradedFrom")} AS degraded FROM ${view.name} WHERE chunks=0 AND ${text("type")}='worktree_snapshot'`), ...view.params);
|
|
3325
|
+
if (!s) return void 0;
|
|
3326
|
+
return {
|
|
3327
|
+
type: "worktree_snapshot",
|
|
3328
|
+
id: s.id,
|
|
3329
|
+
parentId: s.parent,
|
|
3330
|
+
timestamp: s.stamp,
|
|
3331
|
+
root: s.root,
|
|
3332
|
+
snapshotId: s.snapshot,
|
|
3333
|
+
...s.capture !== null ? { captureMs: Number(s.capture) } : {},
|
|
3334
|
+
...s.record === "object" ? { snapshot: {} } : {},
|
|
3335
|
+
...s.restore === "object" ? { restore: {} } : {},
|
|
3336
|
+
...s.unrestored === "object" ? { unrestored: {} } : {},
|
|
3337
|
+
...s.degraded ? { degradedFrom: s.degraded } : {}
|
|
1823
3338
|
};
|
|
3339
|
+
};
|
|
3340
|
+
const writes = new SentWrites(tx);
|
|
3341
|
+
const blobs = {};
|
|
3342
|
+
let copiedRows = false;
|
|
3343
|
+
const ownSeqs = [];
|
|
3344
|
+
const remainingBlobs = await writes.around(async () => {
|
|
1824
3345
|
for await (const row of stream.read(reader, async (id) => await lookup(id) !== void 0, inlineSnapshot)) {
|
|
1825
3346
|
index = await foldForkRow(index, row, lookup);
|
|
1826
3347
|
const entry = row.entry;
|
|
1827
3348
|
const listed = applySessionSummaryEntries(summary, [entry]);
|
|
1828
3349
|
summary = listed.state;
|
|
1829
|
-
|
|
3350
|
+
const unchanged = row.stored?.sessionId === source.sessionId && row.edits === void 0;
|
|
3351
|
+
if (entry.type === "custom" && entry.customType === "atomic.tool-output" && !(unchanged && runs)) {
|
|
1830
3352
|
const hash = entry.data?.hash;
|
|
1831
|
-
if (typeof hash === "string"
|
|
3353
|
+
if (typeof hash === "string") hashes.add(hash);
|
|
3354
|
+
}
|
|
3355
|
+
if (unchanged && runs !== void 0) {
|
|
3356
|
+
runs.add(row.stored.seq, seq + 1, entry.id);
|
|
3357
|
+
if (runs.full) await writes.send(runs.drain());
|
|
3358
|
+
seq++;
|
|
3359
|
+
continue;
|
|
3360
|
+
}
|
|
3361
|
+
if (row.stored?.sessionId === source.sessionId && row.edits === void 0) {
|
|
3362
|
+
copiedRows = true;
|
|
3363
|
+
copies.add(row.stored.seq, seq + 1, entry.id);
|
|
3364
|
+
await writes.send(this.entryWrites(header.id, [], seq, listed.texts, false));
|
|
3365
|
+
if (copies.full) await writes.send(copies.drain());
|
|
3366
|
+
seq++;
|
|
3367
|
+
continue;
|
|
1832
3368
|
}
|
|
1833
|
-
|
|
3369
|
+
await writes.send(runs?.drain() ?? copies.drain());
|
|
3370
|
+
if (runs !== void 0) ownSeqs.push(seq + 1);
|
|
3371
|
+
if (!row.reference) await writes.send(this.entryWrites(header.id, [entry], seq, listed.texts, false));
|
|
1834
3372
|
else if (row.inlineSnapshot) await this.writeInlineForkSnapshot(tx, reader, row.reference, header.id, seq, listed.texts, row.edits);
|
|
1835
3373
|
else {
|
|
3374
|
+
copiedRows = true;
|
|
1836
3375
|
const encoded = await encodedForkRow(reader, row);
|
|
1837
3376
|
const chunks = Math.ceil(encoded.size / SESSION_ENTRY_CHUNK_BYTES);
|
|
1838
3377
|
await tx.run(`INSERT INTO ${this.tables.entries} (session_id,seq,entry_id,entry_json,chunks) VALUES (?,?,?,?,?)`, header.id, seq + 1, entry.id, JSON.stringify({
|
|
@@ -1856,22 +3395,231 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
1856
3395
|
}
|
|
1857
3396
|
if (used) await write();
|
|
1858
3397
|
if (n !== chunks) throw new StorageError("Incomplete historical entry in fork");
|
|
1859
|
-
|
|
1860
|
-
await tx.run(`UPDATE ${this.tables.meta} SET schema_version=? WHERE schema_version=?`, 2, SESSION_SCHEMA_VERSION_UNCHUNKED);
|
|
3398
|
+
await writes.send(this.entryWrites(header.id, [], seq, listed.texts, false));
|
|
1861
3399
|
}
|
|
1862
3400
|
seq++;
|
|
1863
3401
|
}
|
|
1864
|
-
const
|
|
3402
|
+
const last = [...runs?.drain() ?? copies.drain()];
|
|
3403
|
+
if (runs !== void 0) {
|
|
3404
|
+
assertForkSegments(header.id, runs.segments, seq);
|
|
3405
|
+
last.push(forkLineageWrite(lineage, header.id, {
|
|
3406
|
+
parentId: source.sessionId,
|
|
3407
|
+
cutSeq: head.lastSeq
|
|
3408
|
+
}));
|
|
3409
|
+
if (runs.segments.length > 0) for (const own of ownSeqs) last.push(this.forkLinks().entry(header.id, own));
|
|
3410
|
+
}
|
|
3411
|
+
const statement = this.summaryWrite(header.id, {
|
|
1865
3412
|
header,
|
|
1866
3413
|
entries: [],
|
|
1867
3414
|
lastSeq: seq
|
|
1868
3415
|
}, summary, index);
|
|
3416
|
+
last.push(statement.statement);
|
|
3417
|
+
if (!copiedRows && hashes.size === 0) {
|
|
3418
|
+
last.push(this.forkVersionStep(header.id));
|
|
3419
|
+
if (transactionFinisher(tx)?.(last) !== true) await writes.send(last);
|
|
3420
|
+
return {
|
|
3421
|
+
remaining: [],
|
|
3422
|
+
epoch: statement.epoch,
|
|
3423
|
+
finished: true
|
|
3424
|
+
};
|
|
3425
|
+
}
|
|
3426
|
+
await writes.send(last);
|
|
3427
|
+
blobs.copy = this.forkBlobCopy(source.sessionId, header.id, hashes);
|
|
1869
3428
|
return {
|
|
1870
|
-
|
|
1871
|
-
epoch,
|
|
1872
|
-
|
|
3429
|
+
remaining: await this.finishForkCopy(tx, writes, header.id, blobs.copy, hashes),
|
|
3430
|
+
epoch: statement.epoch,
|
|
3431
|
+
finished: false
|
|
1873
3432
|
};
|
|
1874
|
-
}
|
|
3433
|
+
});
|
|
3434
|
+
if (!remainingBlobs.finished) await this.finishFork(tx, header.id);
|
|
3435
|
+
return {
|
|
3436
|
+
lastSeq: seq,
|
|
3437
|
+
epoch: remainingBlobs.epoch,
|
|
3438
|
+
remainingBlobs: remainingBlobs.remaining
|
|
3439
|
+
};
|
|
3440
|
+
}
|
|
3441
|
+
/**
|
|
3442
|
+
* The donor `reads` read, when the fork made them, asked for at once: its reads then go out beside the schema check,
|
|
3443
|
+
* in one wait for the connection, as a `create`'s first read does. The fork uses it only once the schema it checks in
|
|
3444
|
+
* this transaction has shared history: a store that saw shared history may meet a database whose schema says
|
|
3445
|
+
* otherwise, and a fork there never names its source's rows. Unused, its failure is nobody's.
|
|
3446
|
+
*/
|
|
3447
|
+
leadingForkDonor(tx, child, source, reads) {
|
|
3448
|
+
if (reads === void 0) return void 0;
|
|
3449
|
+
const read = this.sharedForkDonor(tx, child, source, reads);
|
|
3450
|
+
read.catch(() => {});
|
|
3451
|
+
return read;
|
|
3452
|
+
}
|
|
3453
|
+
/** Notes the sessions session `id`'s segments name, which a fork of it locks. */
|
|
3454
|
+
noteForkSources(id, sources) {
|
|
3455
|
+
this.forkSources.delete(id);
|
|
3456
|
+
this.forkSources.set(id, sources);
|
|
3457
|
+
while (this.forkSources.size > 16) this.forkSources.delete(this.forkSources.keys().next().value);
|
|
3458
|
+
}
|
|
3459
|
+
/** The fork tables of this store's database, which exist once it has shared history (#6560). */
|
|
3460
|
+
lineageTables() {
|
|
3461
|
+
return {
|
|
3462
|
+
sessions: this.tables.sessions,
|
|
3463
|
+
forkSegments: this.forkTables.forkSegments,
|
|
3464
|
+
forkLineage: this.forkTables.forkLineage
|
|
3465
|
+
};
|
|
3466
|
+
}
|
|
3467
|
+
/**
|
|
3468
|
+
* The reads that begin a fork of session `donor` into `child` with shared history (#6560), in order: whether the child
|
|
3469
|
+
* exists; the rows of the donor and of the sessions its segments name, as the statement starts or as this store last
|
|
3470
|
+
* saw them, each locked `key-share` in id order, unless the child exists, with the donor's watermark and generation,
|
|
3471
|
+
* and with `withState` its summary state; then the donor's segments, read once those locks are held.
|
|
3472
|
+
*/
|
|
3473
|
+
sharedForkReads(child, donor, withState) {
|
|
3474
|
+
const ids = [.../* @__PURE__ */ new Set([donor, ...this.forkSources.get(donor) ?? []])].sort();
|
|
3475
|
+
const epoch = `COALESCE(${this.dialect.jsonText("summary_state", "epoch")}, ${this.dialect.jsonText("summary_state", "resume", "epoch")}, revision)`;
|
|
3476
|
+
return {
|
|
3477
|
+
ids,
|
|
3478
|
+
exists: {
|
|
3479
|
+
sql: `SELECT id FROM ${this.tables.sessions} WHERE id = ?`,
|
|
3480
|
+
params: [child]
|
|
3481
|
+
},
|
|
3482
|
+
lock: {
|
|
3483
|
+
sql: `SELECT id, last_seq, CASE WHEN id = ? THEN ${epoch} END AS epoch${withState ? ", CASE WHEN id = ? THEN summary_state END AS summary_state" : ""}
|
|
3484
|
+
FROM ${this.tables.sessions} WHERE (id IN (${ids.map(() => "?").join(", ")})
|
|
3485
|
+
OR id IN (SELECT source_id FROM ${this.forkTables.forkSegments} WHERE session_id = ?))
|
|
3486
|
+
AND NOT EXISTS (SELECT 1 FROM ${this.tables.sessions} c WHERE c.id = ?) ORDER BY id${this.dialect.lockClause("key-share")}`,
|
|
3487
|
+
params: [
|
|
3488
|
+
donor,
|
|
3489
|
+
...withState ? [donor] : [],
|
|
3490
|
+
...ids,
|
|
3491
|
+
donor,
|
|
3492
|
+
child
|
|
3493
|
+
]
|
|
3494
|
+
},
|
|
3495
|
+
tombstones: {
|
|
3496
|
+
sql: `SELECT session_id FROM ${this.forkTables.forkTombstones} WHERE session_id IN (${ids.map(() => "?").join(", ")})
|
|
3497
|
+
OR session_id IN (SELECT source_id FROM ${this.forkTables.forkSegments} WHERE session_id = ?)
|
|
3498
|
+
ORDER BY session_id${this.dialect.lockClause("key-share")}`,
|
|
3499
|
+
params: [...ids, donor]
|
|
3500
|
+
},
|
|
3501
|
+
segments: {
|
|
3502
|
+
sql: `SELECT source_id, from_seq, to_seq, base_seq FROM ${this.forkTables.forkSegments} WHERE session_id = ? ORDER BY idx`,
|
|
3503
|
+
params: [donor]
|
|
3504
|
+
}
|
|
3505
|
+
};
|
|
3506
|
+
}
|
|
3507
|
+
/**
|
|
3508
|
+
* The donor of a fork with shared history (#6560), from `reads`: its watermark, as the locking read found it, is the
|
|
3509
|
+
* fork's cut-off. Throws `ForkSourcesMoved`, for the fork to run again, when the donor's segments name a session the
|
|
3510
|
+
* reads did not lock: the donor's segments changed since this store last forked it.
|
|
3511
|
+
*/
|
|
3512
|
+
async sharedForkDonor(tx, child, source, reads) {
|
|
3513
|
+
const settle = (read) => read.then((value) => ({ value }), (error) => ({ error }));
|
|
3514
|
+
const existing = settle(tx.get(reads.exists.sql, ...reads.exists.params));
|
|
3515
|
+
const locked = settle(tx.all(reads.lock.sql, ...reads.lock.params));
|
|
3516
|
+
const tombstones = settle(tx.all(reads.tombstones.sql, ...reads.tombstones.params));
|
|
3517
|
+
const segmentRows = settle(tx.all(reads.segments.sql, ...reads.segments.params));
|
|
3518
|
+
for (const read of [
|
|
3519
|
+
existing,
|
|
3520
|
+
locked,
|
|
3521
|
+
tombstones,
|
|
3522
|
+
segmentRows
|
|
3523
|
+
]) {
|
|
3524
|
+
const answer = await read;
|
|
3525
|
+
if ("error" in answer) throw answer.error;
|
|
3526
|
+
}
|
|
3527
|
+
const answer = (read) => read.value;
|
|
3528
|
+
if (answer(await existing)) throw new SessionExistsError$1(child);
|
|
3529
|
+
const row = answer(await locked).find((candidate) => String(candidate.id) === source.sessionId);
|
|
3530
|
+
if (row === void 0) throw new SessionNotFoundError$1(source.sessionId);
|
|
3531
|
+
const segments = answer(await segmentRows).map((segment) => ({
|
|
3532
|
+
sourceId: String(segment.source_id),
|
|
3533
|
+
fromSeq: Number(segment.from_seq),
|
|
3534
|
+
toSeq: Number(segment.to_seq),
|
|
3535
|
+
baseSeq: Number(segment.base_seq)
|
|
3536
|
+
}));
|
|
3537
|
+
const sources = [...new Set(segments.map((segment) => segment.sourceId))].sort();
|
|
3538
|
+
this.noteForkSources(source.sessionId, sources);
|
|
3539
|
+
const lockedIds = /* @__PURE__ */ new Set([
|
|
3540
|
+
...reads.ids,
|
|
3541
|
+
...answer(await locked).map((candidate) => String(candidate.id)),
|
|
3542
|
+
...answer(await tombstones).map((candidate) => String(candidate.session_id))
|
|
3543
|
+
]);
|
|
3544
|
+
if (sources.some((id) => !lockedIds.has(id))) throw new ForkSourcesMoved();
|
|
3545
|
+
const lastSeq = Number(row.last_seq);
|
|
3546
|
+
const epoch = String(row.epoch);
|
|
3547
|
+
if (source.epoch !== void 0 && epoch !== source.epoch) throw new SessionConflictError$1(source.sessionId, 0, lastSeq);
|
|
3548
|
+
return {
|
|
3549
|
+
lastSeq,
|
|
3550
|
+
epoch,
|
|
3551
|
+
segments,
|
|
3552
|
+
...typeof row.summary_state === "string" ? { state: JSON.parse(row.summary_state) } : {}
|
|
3553
|
+
};
|
|
3554
|
+
}
|
|
3555
|
+
/**
|
|
3556
|
+
* A fork with shared history of the donor's whole view as it stands (#6560): its segments, its lineage and its
|
|
3557
|
+
* session row, whose summary is the donor's in a generation of its own, and no row of any entry. Undefined, for
|
|
3558
|
+
* the fork to read the donor's rows, when the donor's resume index does not cover its watermark.
|
|
3559
|
+
*/
|
|
3560
|
+
async writeSharedPrefixFork(tx, header, donorId, donor) {
|
|
3561
|
+
const index = donor.state === void 0 ? void 0 : windowIndex(donor.state, donor.lastSeq);
|
|
3562
|
+
if (donor.state === void 0 || index === void 0) return void 0;
|
|
3563
|
+
const epoch = newRevision();
|
|
3564
|
+
const segments = prefixForkSegments(donorId, donor.segments, donor.lastSeq, donor.lastSeq);
|
|
3565
|
+
const { resume: _resume, windowResume: _window, epoch: _epoch, ...listed } = donor.state;
|
|
3566
|
+
const summary = this.summaryWrite(header.id, {
|
|
3567
|
+
header,
|
|
3568
|
+
entries: [],
|
|
3569
|
+
lastSeq: donor.lastSeq
|
|
3570
|
+
}, {
|
|
3571
|
+
...listed,
|
|
3572
|
+
epoch
|
|
3573
|
+
}, {
|
|
3574
|
+
...index,
|
|
3575
|
+
epoch
|
|
3576
|
+
});
|
|
3577
|
+
const lineage = this.lineageTables();
|
|
3578
|
+
assertForkSegments(header.id, segments, donor.lastSeq);
|
|
3579
|
+
const statements = [
|
|
3580
|
+
...forkSegmentInserts(lineage, header.id, 0, segments),
|
|
3581
|
+
forkLineageWrite(lineage, header.id, {
|
|
3582
|
+
parentId: donorId,
|
|
3583
|
+
cutSeq: donor.lastSeq
|
|
3584
|
+
}),
|
|
3585
|
+
summary.statement
|
|
3586
|
+
];
|
|
3587
|
+
if (transactionFinisher(tx)?.(statements) !== true) for (const { sql, params } of statements) await tx.run(sql, ...params);
|
|
3588
|
+
return {
|
|
3589
|
+
lastSeq: donor.lastSeq,
|
|
3590
|
+
epoch: summary.epoch,
|
|
3591
|
+
remainingBlobs: []
|
|
3592
|
+
};
|
|
3593
|
+
}
|
|
3594
|
+
/**
|
|
3595
|
+
* `readEntryChunk` for a fork's reader bound to transaction `tx`, reading session `source` in generation `epoch`: a
|
|
3596
|
+
* read of an entry fetches a whole stored chunk row, or a part as large of an entry stored whole, and answers the next
|
|
3597
|
+
* reads of it from that, so an entry costs a round trip a chunk, not one every 64 KiB (#6560). The fork holds the
|
|
3598
|
+
* source's row, so its generation cannot change meanwhile. Other reads go to `reader` as before.
|
|
3599
|
+
*/
|
|
3600
|
+
forkChunkReader(tx, tables, reader, source, epoch) {
|
|
3601
|
+
const json = this.dialect.name === "sqlite" ? "CAST(e.entry_json AS BLOB)" : "convert_to(e.entry_json, 'UTF8')";
|
|
3602
|
+
let held;
|
|
3603
|
+
return async (reference, offset, bytes = SESSION_HISTORY_CHUNK_BYTES) => {
|
|
3604
|
+
if (reference.sessionId !== source || reference.epoch !== epoch) return SqlSessionStore.prototype.readEntryChunk.call(reader, reference, offset, bytes);
|
|
3605
|
+
const part = Math.floor(offset / SESSION_ENTRY_CHUNK_BYTES);
|
|
3606
|
+
const start = part * SESSION_ENTRY_CHUNK_BYTES;
|
|
3607
|
+
if (held?.seq !== reference.seq || held.start !== start) {
|
|
3608
|
+
const view = this.entriesView(tables, source, reference.seq - 1, reference.seq);
|
|
3609
|
+
const row = await tx.get(withForkViews([view], `SELECT CASE WHEN e.chunks > 0
|
|
3610
|
+
THEN (SELECT c.data FROM ${this.tables.entryChunks} c WHERE c.session_id = e.src_id AND c.seq = e.src_seq AND c.idx = ?)
|
|
3611
|
+
ELSE substr(${json}, CAST(? AS INTEGER), CAST(? AS INTEGER)) END AS data
|
|
3612
|
+
FROM ${view.name} e`), ...view.params, part, start + 1, SESSION_ENTRY_CHUNK_BYTES);
|
|
3613
|
+
if (row?.data == null || row.data.byteLength <= offset - start) return SqlSessionStore.prototype.readEntryChunk.call(reader, reference, offset, bytes);
|
|
3614
|
+
held = {
|
|
3615
|
+
seq: reference.seq,
|
|
3616
|
+
start,
|
|
3617
|
+
data: row.data
|
|
3618
|
+
};
|
|
3619
|
+
}
|
|
3620
|
+
const from = offset - start;
|
|
3621
|
+
return held.data.subarray(from, from + Math.min(Math.max(1, Math.trunc(bytes) || 1), SESSION_HISTORY_PAGE_BYTES));
|
|
3622
|
+
};
|
|
1875
3623
|
}
|
|
1876
3624
|
/** Keep the legacy inline payload outside the iterator's yielded value and the caller's async frame:
|
|
1877
3625
|
* neither may retain this row while the next SQLite result is being delivered. */
|
|
@@ -1881,13 +3629,18 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
1881
3629
|
await this.insertEntries(tx, child, [edits ? {
|
|
1882
3630
|
...original,
|
|
1883
3631
|
...edits
|
|
1884
|
-
} : original], seq, texts);
|
|
3632
|
+
} : original], seq, texts, false);
|
|
1885
3633
|
}
|
|
1886
3634
|
async append(sessionId, entries, options) {
|
|
1887
3635
|
this.assertOpen();
|
|
1888
3636
|
validateSessionText("sessionId", sessionId);
|
|
1889
|
-
|
|
1890
|
-
|
|
3637
|
+
const fast = await this.appendThroughFunction(sessionId, entries, options);
|
|
3638
|
+
if (fast !== void 0) return fast;
|
|
3639
|
+
let written = [];
|
|
3640
|
+
let writtenRow;
|
|
3641
|
+
const appended = await this.transactionCheckedAlongside(async (tx, checked) => {
|
|
3642
|
+
writtenRow = void 0;
|
|
3643
|
+
const { row: previous, state: summaryState } = await this.forWrite(tx, sessionId, options, true, true);
|
|
1891
3644
|
validateSessionEntries(entries);
|
|
1892
3645
|
await this.blobTable.assertStored(tx, entries.flatMap((entry) => entry.type === "worktree_snapshot" && entry.snapshot !== void 0 ? [entry.snapshot] : []));
|
|
1893
3646
|
const lastSeq = previous.last_seq + entries.length;
|
|
@@ -1896,20 +3649,248 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
1896
3649
|
entries,
|
|
1897
3650
|
lastSeq
|
|
1898
3651
|
}, summaryState, await this.appendedResume(tx, sessionId, windowIndex(summaryState, previous.last_seq), previous.last_seq, entries));
|
|
1899
|
-
|
|
3652
|
+
written = [];
|
|
3653
|
+
const statements = this.entryWrites(sessionId, entries, previous.last_seq, summary.texts, true, written);
|
|
1900
3654
|
await checked;
|
|
1901
|
-
await this.
|
|
1902
|
-
|
|
1903
|
-
|
|
3655
|
+
const forked = previous.forked !== void 0 ? Number(previous.forked) === 1 : await this.sharedHistoryForks(tx) && await this.hasForkSegments(tx, sessionId);
|
|
3656
|
+
writtenRow = forked ? void 0 : summary.row;
|
|
3657
|
+
const links = forked ? entries.map((_, index) => this.forkLinks().entry(sessionId, previous.last_seq + index + 1)) : [];
|
|
3658
|
+
await this.writeEntries(tx, summary.statement, links.length === 0 ? statements : thenAll(statements, links));
|
|
3659
|
+
return {
|
|
3660
|
+
lastSeq,
|
|
3661
|
+
epoch: summary.epoch
|
|
3662
|
+
};
|
|
3663
|
+
}, this.sessionWrite(sessionId, this.headRead(sessionId, options, true, true)));
|
|
3664
|
+
this.noteWritten(sessionId, appended.epoch, written);
|
|
3665
|
+
this.rememberWritten(sessionId, writtenRow);
|
|
3666
|
+
return { lastSeq: appended.lastSeq };
|
|
3667
|
+
}
|
|
3668
|
+
/**
|
|
3669
|
+
* Remembers `row`, the session's row a committed write of this store left, for the next append to plan from, where
|
|
3670
|
+
* appends go through the append function; forgets the session's row when `row` is undefined. At most
|
|
3671
|
+
* {@link WRITTEN_ROWS} sessions are remembered, the latest written.
|
|
3672
|
+
*/
|
|
3673
|
+
rememberWritten(sessionId, row) {
|
|
3674
|
+
this.writtenRows.delete(sessionId);
|
|
3675
|
+
if (row === void 0 || this.appendFunction === void 0) return;
|
|
3676
|
+
this.writtenRows.set(sessionId, row);
|
|
3677
|
+
while (this.writtenRows.size > WRITTEN_ROWS) this.writtenRows.delete(this.writtenRows.keys().next().value);
|
|
3678
|
+
}
|
|
3679
|
+
/**
|
|
3680
|
+
* Appends `entries` in one round trip through the session append function, planned from the row this store's last
|
|
3681
|
+
* write of the session left (#6599). The function takes the session's locks as a session write transaction does,
|
|
3682
|
+
* checks the schema version, the session and its expected seq as `forWrite` does, writes nothing unless the stored
|
|
3683
|
+
* row is still the one planned from, checks the snapshot blobs as `assertStored` does, and writes the row, the
|
|
3684
|
+
* entries and their search texts in the order an append's transaction does. Undefined, having written nothing, when
|
|
3685
|
+
* the append is not one it plans (no function, no remembered row, a row other than the stored one, invalid entries,
|
|
3686
|
+
* a chunked entry or more than one batch of writes, an entry that refers back past the resume window): the caller
|
|
3687
|
+
* then appends in a transaction as before, which reads the row itself and reports what fails.
|
|
3688
|
+
*/
|
|
3689
|
+
async appendThroughFunction(sessionId, entries, options) {
|
|
3690
|
+
const fn = this.appendFunction;
|
|
3691
|
+
const autocommit = this.database.autocommit?.bind(this.database);
|
|
3692
|
+
const previous = this.writtenRows.get(sessionId);
|
|
3693
|
+
if (fn === void 0 || autocommit === void 0 || previous === void 0) return void 0;
|
|
3694
|
+
if (previous.last_seq !== options.expectSeq) return void 0;
|
|
3695
|
+
const state = JSON.parse(previous.summary_state);
|
|
3696
|
+
if (options.epoch !== void 0 && state.epoch !== options.epoch) return void 0;
|
|
3697
|
+
try {
|
|
3698
|
+
validateSessionEntries(entries);
|
|
3699
|
+
} catch {
|
|
3700
|
+
return;
|
|
3701
|
+
}
|
|
3702
|
+
const window = windowIndex(state, previous.last_seq);
|
|
3703
|
+
if (isSessionResumeIndex(window, previous.last_seq) && foreignResumeIds(window, entries).length > 0) return void 0;
|
|
3704
|
+
const lastSeq = previous.last_seq + entries.length;
|
|
3705
|
+
const summary = this.summaryWrite(sessionId, {
|
|
3706
|
+
header: JSON.parse(previous.header_json),
|
|
3707
|
+
entries,
|
|
3708
|
+
lastSeq
|
|
3709
|
+
}, state, await this.appendedResume(this.database, sessionId, window, previous.last_seq, entries));
|
|
3710
|
+
const rows = [];
|
|
3711
|
+
const written = [];
|
|
3712
|
+
let bytes = statementBytes(summary.statement);
|
|
3713
|
+
for (const [index, entry] of entries.entries()) {
|
|
3714
|
+
const json = this.encode(entry);
|
|
3715
|
+
const stored = storedEntry(entry, json);
|
|
3716
|
+
bytes += entry.id.length + stored.json.length;
|
|
3717
|
+
if (stored.chunks.length > 0 || bytes > STATEMENT_BATCH_BYTES) return void 0;
|
|
3718
|
+
rows.push([entry.id, stored.json]);
|
|
3719
|
+
written.push({
|
|
3720
|
+
entry,
|
|
3721
|
+
seq: previous.last_seq + index + 1,
|
|
3722
|
+
json
|
|
3723
|
+
});
|
|
3724
|
+
}
|
|
3725
|
+
const texts = summary.texts.map(({ index, text }) => [previous.last_seq + index + 1, this.encode(text)]);
|
|
3726
|
+
const blobs = this.blobTable.storedHashes(entries.flatMap((entry) => entry.type === "worktree_snapshot" && entry.snapshot !== void 0 ? [entry.snapshot] : []));
|
|
3727
|
+
const { concurrency = { kind: "serial" } } = sessionWriteTransaction(this.tables.sessions, sessionId);
|
|
3728
|
+
const [answer] = await autocommit({
|
|
3729
|
+
sql: `SELECT outcome, detail FROM ${fn}(${Array.from({ length: 24 }, () => "?").join(", ")})`,
|
|
3730
|
+
params: [
|
|
3731
|
+
concurrency.kind === "serial" ? concurrency.domain ?? "" : "",
|
|
3732
|
+
SESSION_SCHEMA_VERSION_UNCHUNKED,
|
|
3733
|
+
3,
|
|
3734
|
+
sessionId,
|
|
3735
|
+
previous.last_seq,
|
|
3736
|
+
previous.revision,
|
|
3737
|
+
await sha256Hex(new TextEncoder().encode(`${previous.header_json}\n${previous.summary_state}`)),
|
|
3738
|
+
blobs.length === 0 ? null : JSON.stringify(blobs),
|
|
3739
|
+
...summary.statement.params.slice(1),
|
|
3740
|
+
JSON.stringify(rows),
|
|
3741
|
+
JSON.stringify(texts)
|
|
3742
|
+
]
|
|
3743
|
+
}, concurrency);
|
|
3744
|
+
switch (answer?.outcome) {
|
|
3745
|
+
case "appended":
|
|
3746
|
+
this.noteWritten(sessionId, summary.epoch, written);
|
|
3747
|
+
this.rememberWritten(sessionId, summary.row);
|
|
3748
|
+
return { lastSeq };
|
|
3749
|
+
case "version":
|
|
3750
|
+
assertStorageSchemaVersion("sessions", answer.detail === null ? null : Number(answer.detail), 3, SESSION_SCHEMA_VERSION_UNCHUNKED);
|
|
3751
|
+
break;
|
|
3752
|
+
case "missing": throw new SessionNotFoundError$1(sessionId);
|
|
3753
|
+
case "conflict": throw new SessionConflictError$1(sessionId, options.expectSeq, Number(answer.detail));
|
|
3754
|
+
case "blob": return this.blobTable.refuseCollected(String(answer.detail));
|
|
3755
|
+
}
|
|
3756
|
+
this.writtenRows.delete(sessionId);
|
|
3757
|
+
}
|
|
3758
|
+
/**
|
|
3759
|
+
* The session append function of the store's tables, `<prefix>session_append_v1`: one statement, and so one round
|
|
3760
|
+
* trip, for what an append's transaction does with its two (#6599). Created by `atomic storage migrate` through
|
|
3761
|
+
* {@link prepareAppendFunction}. It runs with the caller's rights, so it lets a role do nothing its table
|
|
3762
|
+
* privileges do not, and in the caller's `search_path`, the schema a transaction of the store sets. It writes no
|
|
3763
|
+
* chunked entry: an append that has one goes through a transaction. Its answer is one row: `appended`, or why it
|
|
3764
|
+
* wrote nothing, with the stored version (`version`), the stored last seq (`conflict`), the first blob that is not
|
|
3765
|
+
* stored (`blob`), no session (`missing`), or a stored row other than the one the caller planned from (`stale`).
|
|
3766
|
+
*/
|
|
3767
|
+
appendFunctionSql(fn) {
|
|
3768
|
+
const t = this.tables;
|
|
3769
|
+
return `CREATE OR REPLACE FUNCTION ${fn}(
|
|
3770
|
+
p_domain text, p_oldest bigint, p_newest bigint, p_session_id text, p_expect_seq bigint, p_revision text,
|
|
3771
|
+
p_digest text, p_blobs text, p_cwd text, p_created_at text, p_header_json text, p_internal bigint, p_last_seq bigint,
|
|
3772
|
+
p_modified_at text, p_message_count bigint, p_first_message text, p_name text, p_has_name bigint, p_summary text,
|
|
3773
|
+
p_summarized_through_id text, p_summary_state text, p_new_revision text, p_entries text, p_texts text
|
|
3774
|
+
) RETURNS TABLE (outcome text, detail text) LANGUAGE plpgsql AS $append$
|
|
3775
|
+
#variable_conflict use_column
|
|
3776
|
+
DECLARE
|
|
3777
|
+
scope text := CASE WHEN current_schema() = 'public' THEN '' ELSE current_schema() || ':' END;
|
|
3778
|
+
stored_version bigint;
|
|
3779
|
+
head record;
|
|
3780
|
+
stored_blobs text[];
|
|
3781
|
+
missing_blob text;
|
|
3782
|
+
BEGIN
|
|
3783
|
+
-- The locks of a session write transaction, waited for as long as one waits: its lock wait is the statement timeout.
|
|
3784
|
+
PERFORM set_config('lock_timeout', current_setting('statement_timeout'), true);
|
|
3785
|
+
PERFORM pg_advisory_xact_lock_shared(hashtextextended(scope || 'atomic', 0)),
|
|
3786
|
+
pg_advisory_xact_lock(hashtextextended(scope || p_domain, 0));
|
|
3787
|
+
SELECT schema_version INTO stored_version FROM ${t.meta};
|
|
3788
|
+
IF stored_version IS NULL OR stored_version < p_oldest OR stored_version > p_newest THEN
|
|
3789
|
+
RETURN QUERY SELECT 'version'::text, stored_version::text;
|
|
3790
|
+
RETURN;
|
|
3791
|
+
END IF;
|
|
3792
|
+
SELECT s.last_seq, s.revision,
|
|
3793
|
+
encode(sha256(convert_to(s.header_json || E'\n' || s.summary_state, 'UTF8')), 'hex') AS digest
|
|
3794
|
+
INTO head FROM ${t.sessions} AS s WHERE s.id = p_session_id;
|
|
3795
|
+
IF NOT FOUND THEN
|
|
3796
|
+
RETURN QUERY SELECT 'missing'::text, NULL::text;
|
|
3797
|
+
RETURN;
|
|
3798
|
+
END IF;
|
|
3799
|
+
IF head.last_seq <> p_expect_seq THEN
|
|
3800
|
+
RETURN QUERY SELECT 'conflict'::text, head.last_seq::text;
|
|
3801
|
+
RETURN;
|
|
3802
|
+
END IF;
|
|
3803
|
+
IF head.revision <> p_revision OR head.digest <> p_digest THEN
|
|
3804
|
+
RETURN QUERY SELECT 'stale'::text, NULL::text;
|
|
3805
|
+
RETURN;
|
|
3806
|
+
END IF;
|
|
3807
|
+
IF p_blobs IS NOT NULL THEN
|
|
3808
|
+
SELECT array_agg(locked.hash) INTO stored_blobs FROM (${this.blobTable.storedBlobsQuery("p_blobs")}) AS locked;
|
|
3809
|
+
SELECT h.value INTO missing_blob FROM json_array_elements_text(p_blobs::json) WITH ORDINALITY AS h(value, ord)
|
|
3810
|
+
WHERE h.value <> ALL (coalesce(stored_blobs, '{}'::text[])) ORDER BY h.ord LIMIT 1;
|
|
3811
|
+
IF missing_blob IS NOT NULL THEN
|
|
3812
|
+
RETURN QUERY SELECT 'blob'::text, missing_blob;
|
|
3813
|
+
RETURN;
|
|
3814
|
+
END IF;
|
|
3815
|
+
END IF;
|
|
3816
|
+
INSERT INTO ${t.sessions}
|
|
3817
|
+
(id, cwd, created_at, header_json, internal, last_seq, modified_at, message_count,
|
|
3818
|
+
first_message, name, has_name, summary, summarized_through_id, summary_state, revision)
|
|
3819
|
+
VALUES (p_session_id, p_cwd, p_created_at, p_header_json, p_internal, p_last_seq, p_modified_at, p_message_count,
|
|
3820
|
+
p_first_message, p_name, p_has_name, p_summary, p_summarized_through_id, p_summary_state, p_new_revision)
|
|
3821
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
3822
|
+
cwd = excluded.cwd, created_at = excluded.created_at, header_json = excluded.header_json,
|
|
3823
|
+
internal = excluded.internal, last_seq = excluded.last_seq, modified_at = excluded.modified_at,
|
|
3824
|
+
message_count = excluded.message_count, first_message = excluded.first_message, name = excluded.name,
|
|
3825
|
+
has_name = excluded.has_name, summary = excluded.summary,
|
|
3826
|
+
summarized_through_id = excluded.summarized_through_id,
|
|
3827
|
+
summary_state = excluded.summary_state, revision = excluded.revision;
|
|
3828
|
+
INSERT INTO ${t.entries} (session_id, seq, entry_id, entry_json, chunks)
|
|
3829
|
+
SELECT p_session_id, p_expect_seq + e.ord, e.value->>0, e.value->>1, 0
|
|
3830
|
+
FROM json_array_elements(p_entries::json) WITH ORDINALITY AS e(value, ord) ORDER BY e.ord;
|
|
3831
|
+
INSERT INTO ${t.searchTexts} (session_id, seq, text_json)
|
|
3832
|
+
SELECT p_session_id, (x.value->>0)::bigint, x.value->>1
|
|
3833
|
+
FROM json_array_elements(p_texts::json) WITH ORDINALITY AS x(value, ord) ORDER BY x.ord;
|
|
3834
|
+
RETURN QUERY SELECT 'appended'::text, NULL::text;
|
|
3835
|
+
END
|
|
3836
|
+
$append$`;
|
|
3837
|
+
}
|
|
3838
|
+
/**
|
|
3839
|
+
* Creates the session append function (#6599), once per revision, as the ledger records it, and lets every role that
|
|
3840
|
+
* may insert into the sessions table execute it: `atomic storage migrate` runs this as the owner role, and a
|
|
3841
|
+
* runtime role appends through the function from its next open on. PostgreSQL only; does nothing elsewhere.
|
|
3842
|
+
*/
|
|
3843
|
+
async prepareAppendFunction() {
|
|
3844
|
+
this.assertOpen();
|
|
3845
|
+
if (this.dialect.name !== "postgres") return;
|
|
3846
|
+
const fn = renderStorageIdentifiers("sessions", { append: SESSION_APPEND_FUNCTION }, this.prefix).append;
|
|
3847
|
+
const ledger = storageMigrationTable(this.prefix);
|
|
3848
|
+
const physical = (name) => this.dialect.identifier(name).replaceAll("'", "''");
|
|
3849
|
+
await this.database.transaction(async (tx) => {
|
|
3850
|
+
await ensureStorageSchema(tx, this.dialect, {
|
|
3851
|
+
ledger,
|
|
3852
|
+
domain: SESSION_APPEND_FUNCTION_DOMAIN,
|
|
3853
|
+
revision: SESSION_APPEND_FUNCTION_REVISION
|
|
3854
|
+
}, () => tx.exec(this.appendFunctionSql(fn)));
|
|
3855
|
+
await tx.exec(`DO $grant$
|
|
3856
|
+
DECLARE grantee text;
|
|
3857
|
+
BEGIN
|
|
3858
|
+
FOR grantee IN SELECT DISTINCT CASE WHEN a.grantee = 0 THEN 'PUBLIC' ELSE quote_ident(pg_catalog.pg_get_userbyid(a.grantee)) END
|
|
3859
|
+
FROM pg_catalog.pg_class c, pg_catalog.aclexplode(c.relacl) AS a
|
|
3860
|
+
WHERE c.relnamespace = current_schema()::regnamespace AND c.relname = '${physical(this.tables.sessions)}'
|
|
3861
|
+
AND a.privilege_type = 'INSERT' AND a.grantee <> c.relowner
|
|
3862
|
+
LOOP
|
|
3863
|
+
EXECUTE format('GRANT EXECUTE ON FUNCTION %I TO %s', '${physical(fn)}', grantee);
|
|
3864
|
+
END LOOP;
|
|
3865
|
+
END
|
|
3866
|
+
$grant$`);
|
|
3867
|
+
}, {
|
|
3868
|
+
retryTransientFailures: true,
|
|
3869
|
+
concurrency: {
|
|
3870
|
+
kind: "serial",
|
|
3871
|
+
domain: ledger
|
|
3872
|
+
}
|
|
3873
|
+
});
|
|
1904
3874
|
}
|
|
1905
3875
|
async replace(sessionId, header, entries, options) {
|
|
1906
3876
|
this.assertOpen();
|
|
1907
3877
|
validateSessionText("sessionId", sessionId);
|
|
1908
|
-
|
|
1909
|
-
|
|
3878
|
+
this.writtenRows.delete(sessionId);
|
|
3879
|
+
let released = [];
|
|
3880
|
+
let entriesWritten = [];
|
|
3881
|
+
const pinReads = this.sharedHistorySeen ? forkPinReads(this.forkHost(), this.tables.sessions, sessionId) : void 0;
|
|
3882
|
+
const written = await this.transactionCheckedAlongside(async (tx, checked) => {
|
|
3883
|
+
released = [];
|
|
3884
|
+
entriesWritten = [];
|
|
3885
|
+
const [, pins] = await Promise.all([this.forWrite(tx, sessionId, options), this.readForkPinsWithin(tx, sessionId, pinReads)]);
|
|
3886
|
+
await checked;
|
|
1910
3887
|
validateSessionHeader(header);
|
|
1911
3888
|
validateSessionEntries(entries);
|
|
1912
3889
|
if (header.id !== sessionId) throw new SessionIdMismatchError$1(sessionId, header.id);
|
|
3890
|
+
if (pins !== void 0) released = await replaceForkedSessionWithin(this.forkHost(), tx, sessionId, pins).catch((error) => {
|
|
3891
|
+
noteForkCopyRefusal(error, "replace");
|
|
3892
|
+
throw error;
|
|
3893
|
+
});
|
|
1913
3894
|
await this.searchIndex?.forgetWithin(tx, sessionId);
|
|
1914
3895
|
await tx.run(`DELETE FROM ${this.tables.searchTexts} WHERE session_id = ?`, sessionId);
|
|
1915
3896
|
await tx.run(`DELETE FROM ${this.tables.entryChunks} WHERE session_id = ?`, sessionId);
|
|
@@ -1919,21 +3900,25 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
1919
3900
|
entries,
|
|
1920
3901
|
lastSeq: entries.length
|
|
1921
3902
|
});
|
|
1922
|
-
await this.insertEntries(tx, sessionId, entries, 0, texts);
|
|
3903
|
+
await this.insertEntries(tx, sessionId, entries, 0, texts, true, entriesWritten);
|
|
1923
3904
|
return {
|
|
1924
3905
|
lastSeq: entries.length,
|
|
1925
3906
|
epoch
|
|
1926
3907
|
};
|
|
1927
|
-
},
|
|
3908
|
+
}, this.sessionWrite(sessionId, ...pinReads === void 0 ? [] : [this.headRead(sessionId, options, false), ...pinReads]));
|
|
3909
|
+
this.noteWritten(sessionId, written.epoch, entriesWritten);
|
|
3910
|
+
await this.sweepReleasedForkRows(released);
|
|
3911
|
+
return written;
|
|
1928
3912
|
}
|
|
1929
3913
|
async updateHeader(header, options) {
|
|
1930
3914
|
this.assertOpen();
|
|
1931
3915
|
validateSessionHeader(header);
|
|
3916
|
+
this.writtenRows.delete(header.id);
|
|
1932
3917
|
return this.transaction(async (tx) => {
|
|
1933
3918
|
const { row, state } = await this.forWrite(tx, header.id, options, true);
|
|
1934
3919
|
const epoch = newRevision();
|
|
1935
3920
|
const resume = windowIndex(state, row.last_seq);
|
|
1936
|
-
|
|
3921
|
+
const { statement } = this.summaryWrite(header.id, {
|
|
1937
3922
|
header,
|
|
1938
3923
|
entries: [],
|
|
1939
3924
|
lastSeq: row.last_seq
|
|
@@ -1944,11 +3929,12 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
1944
3929
|
...resume,
|
|
1945
3930
|
epoch
|
|
1946
3931
|
});
|
|
3932
|
+
if (transactionFinisher(tx)?.([statement]) !== true) await tx.run(statement.sql, ...statement.params);
|
|
1947
3933
|
return {
|
|
1948
3934
|
lastSeq: row.last_seq,
|
|
1949
3935
|
epoch
|
|
1950
3936
|
};
|
|
1951
|
-
},
|
|
3937
|
+
}, this.sessionWrite(header.id, this.headRead(header.id, options, true)));
|
|
1952
3938
|
}
|
|
1953
3939
|
async load(sessionId) {
|
|
1954
3940
|
this.assertOpen();
|
|
@@ -1957,16 +3943,54 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
1957
3943
|
const row = await this.database.get(`SELECT last_seq FROM ${this.tables.sessions} WHERE id = ?`, sessionId);
|
|
1958
3944
|
if (row) announceHistoryLoad(row.last_seq);
|
|
1959
3945
|
}
|
|
1960
|
-
return this.
|
|
3946
|
+
return this.readTransaction((tx) => this.read(tx, sessionId));
|
|
1961
3947
|
}
|
|
1962
3948
|
async readEntryRange(sessionId, query) {
|
|
1963
3949
|
this.assertOpen();
|
|
1964
3950
|
validateSessionText("sessionId", sessionId);
|
|
1965
3951
|
query.signal?.throwIfAborted();
|
|
1966
|
-
const
|
|
3952
|
+
const fromSeq = Math.max(1, query.fromSeq);
|
|
3953
|
+
const skippedSet = query.skipTypes === void 0 ? void 0 : new Set(query.skipTypes);
|
|
3954
|
+
const skippedPrefixes = (query.skipTypes ?? []).map((type) => `{"type":${JSON.stringify(type)},`);
|
|
3955
|
+
const largeBytes = query.largeEntryBytes ?? 0x7fffffff;
|
|
3956
|
+
const selected = query.seqs === void 0 ? "" : ` AND seq IN (SELECT CAST(value AS ${this.dialect.types.int}) FROM ${this.dialect.jsonValues("?")})`;
|
|
3957
|
+
const fitted = query.seqs === void 0 ? "" : " AND (p.before_chars = 0 OR p.before_chars + p.bytes <= ?)";
|
|
3958
|
+
const maxChars = query.maxChars !== void 0 && query.maxChars <= 0 ? 0 : query.maxChars ?? Number.MAX_SAFE_INTEGER;
|
|
3959
|
+
const read = await this.outsideSessionRead(sessionId, (tables) => {
|
|
3960
|
+
const view = this.entriesView(tables, sessionId, fromSeq - 1, Math.min(query.toSeq, FORK_VIEW_END));
|
|
3961
|
+
return this.database.all(withForkViews([view], `WITH sized AS (
|
|
3962
|
+
SELECT seq, chunks, src_id, src_seq, ${this.entryByteLength("entry_json")} AS raw_bytes,
|
|
3963
|
+
${this.entryByteLength("entry_json")} + chunks * ? AS bytes
|
|
3964
|
+
FROM ${view.name}
|
|
3965
|
+
WHERE seq <= (SELECT last_seq FROM ${this.tables.sessions} WHERE id = ?)${selected}
|
|
3966
|
+
),
|
|
3967
|
+
paged AS (
|
|
3968
|
+
SELECT seq, chunks, src_id, src_seq, raw_bytes, bytes, count(*) OVER () AS remaining,
|
|
3969
|
+
sum(bytes) OVER (ORDER BY seq) - bytes AS before_chars
|
|
3970
|
+
FROM sized
|
|
3971
|
+
),
|
|
3972
|
+
page AS (
|
|
3973
|
+
SELECT p.seq, CASE WHEN p.chunks = 0 AND p.raw_bytes <= ? THEN e.entry_json END AS entry_json,
|
|
3974
|
+
substr(e.entry_json, 1, 64) AS entry_head, p.chunks, p.remaining,
|
|
3975
|
+
CASE WHEN p.chunks = 0 AND p.raw_bytes > ? AND substr(e.entry_json, 1, 8) <> '{"type":'
|
|
3976
|
+
THEN ${this.dialect.jsonText("e.entry_json", "type")} END AS entry_type
|
|
3977
|
+
FROM paged p
|
|
3978
|
+
JOIN ${this.tables.entries} e ON e.session_id = p.src_id AND e.seq = p.src_seq
|
|
3979
|
+
WHERE p.before_chars < ?${fitted}
|
|
3980
|
+
)
|
|
3981
|
+
SELECT s.last_seq, page.seq, page.entry_json, page.entry_head, page.chunks, page.remaining, page.entry_type${this.outsideForkedColumn("s.id")}
|
|
3982
|
+
FROM ${this.tables.sessions} s LEFT JOIN page ON 1 = 1
|
|
3983
|
+
WHERE s.id = ?
|
|
3984
|
+
ORDER BY page.seq`), ...view.params, SESSION_ENTRY_CHUNK_BYTES, sessionId, ...query.seqs === void 0 ? [] : [JSON.stringify(query.seqs)], largeBytes, largeBytes, maxChars, ...query.seqs === void 0 ? [] : [maxChars], sessionId);
|
|
3985
|
+
}, (found) => {
|
|
3986
|
+
const session = found[0];
|
|
3987
|
+
if (session === void 0 || maxChars <= 0) return true;
|
|
3988
|
+
if (fromSeq > Math.min(query.toSeq, Number(session.last_seq))) return true;
|
|
3989
|
+
return found.some((row) => row.seq !== null && row.seq !== void 0);
|
|
3990
|
+
}, (found) => found[0]?.forked);
|
|
3991
|
+
const session = read[0];
|
|
1967
3992
|
if (!session) throw new SessionNotFoundError$1(sessionId);
|
|
1968
3993
|
const lastSeq = Number(session.last_seq);
|
|
1969
|
-
const fromSeq = Math.max(1, query.fromSeq);
|
|
1970
3994
|
const toSeq = Math.min(query.toSeq, lastSeq);
|
|
1971
3995
|
if (fromSeq > toSeq) return {
|
|
1972
3996
|
lastSeq,
|
|
@@ -1978,28 +4002,7 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
1978
4002
|
entries: [],
|
|
1979
4003
|
throughSeq: fromSeq - 1
|
|
1980
4004
|
};
|
|
1981
|
-
const
|
|
1982
|
-
const skippedPrefixes = (query.skipTypes ?? []).map((type) => `{"type":${JSON.stringify(type)},`);
|
|
1983
|
-
const largeBytes = query.largeEntryBytes ?? 0x7fffffff;
|
|
1984
|
-
const rows = await this.database.all(`WITH sized AS (
|
|
1985
|
-
SELECT seq, chunks, ${this.entryByteLength("entry_json")} AS raw_bytes,
|
|
1986
|
-
${this.entryByteLength("entry_json")} + chunks * ? AS bytes
|
|
1987
|
-
FROM ${this.tables.entries}
|
|
1988
|
-
WHERE session_id = ? AND seq >= ? AND seq <= ?
|
|
1989
|
-
),
|
|
1990
|
-
paged AS (
|
|
1991
|
-
SELECT seq, chunks, raw_bytes, count(*) OVER () AS remaining,
|
|
1992
|
-
sum(bytes) OVER (ORDER BY seq) - bytes AS before_chars
|
|
1993
|
-
FROM sized
|
|
1994
|
-
)
|
|
1995
|
-
SELECT p.seq, CASE WHEN p.chunks = 0 AND p.raw_bytes <= ? THEN e.entry_json END AS entry_json,
|
|
1996
|
-
substr(e.entry_json, 1, 64) AS entry_head, p.chunks, p.remaining,
|
|
1997
|
-
CASE WHEN p.chunks = 0 AND p.raw_bytes > ? AND substr(e.entry_json, 1, 8) <> '{"type":'
|
|
1998
|
-
THEN ${this.dialect.jsonText("e.entry_json", "type")} END AS entry_type
|
|
1999
|
-
FROM paged p
|
|
2000
|
-
JOIN ${this.tables.entries} e ON e.session_id = ? AND e.seq = p.seq
|
|
2001
|
-
WHERE p.before_chars < ?
|
|
2002
|
-
ORDER BY p.seq`, SESSION_ENTRY_CHUNK_BYTES, sessionId, fromSeq, toSeq, largeBytes, largeBytes, sessionId, query.maxChars ?? Number.MAX_SAFE_INTEGER);
|
|
4005
|
+
const rows = read.filter((row) => row.seq !== null && row.seq !== void 0);
|
|
2003
4006
|
const entries = [];
|
|
2004
4007
|
for (const row of rows) {
|
|
2005
4008
|
query.signal?.throwIfAborted();
|
|
@@ -2007,7 +4010,7 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
2007
4010
|
const seq = Number(row.seq);
|
|
2008
4011
|
const chunks = Number(row.chunks);
|
|
2009
4012
|
if (chunks > 0) {
|
|
2010
|
-
const rawChunks = await this.readRawEntryChunks(this.database, sessionId, seq, chunks, query.signal);
|
|
4013
|
+
const rawChunks = await this.readRawEntryChunks(this.database, void 0, sessionId, seq, chunks, query.signal);
|
|
2011
4014
|
if (rawChunks.reduce((total, chunk) => total + chunk.byteLength, 0) > largeBytes) entries.push({
|
|
2012
4015
|
seq,
|
|
2013
4016
|
entry: STUB_ENTRY,
|
|
@@ -2052,15 +4055,54 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
2052
4055
|
async delete(sessionId) {
|
|
2053
4056
|
this.assertOpen();
|
|
2054
4057
|
validateSessionText("sessionId", sessionId);
|
|
2055
|
-
|
|
4058
|
+
this.writtenRows.delete(sessionId);
|
|
4059
|
+
let released = [];
|
|
4060
|
+
const pinReads = this.sharedHistorySeen ? forkPinReads(this.forkHost(), this.tables.sessions, sessionId) : void 0;
|
|
4061
|
+
await this.transactionCheckedAlongside(async (tx, checked) => {
|
|
4062
|
+
released = [];
|
|
4063
|
+
const pins = await this.readForkPinsWithin(tx, sessionId, pinReads);
|
|
4064
|
+
await checked;
|
|
2056
4065
|
await this.searchIndex?.forgetWithin(tx, sessionId);
|
|
4066
|
+
if (pins !== void 0) {
|
|
4067
|
+
const pinned = await deleteForkedSessionWithin(this.forkHost(), tx, sessionId, (/* @__PURE__ */ new Date()).toISOString(), pins);
|
|
4068
|
+
released = pinned.released;
|
|
4069
|
+
if (pinned.keepRows) {
|
|
4070
|
+
await tx.run(`DELETE FROM ${this.tables.sessions} WHERE id = ?`, sessionId);
|
|
4071
|
+
return;
|
|
4072
|
+
}
|
|
4073
|
+
}
|
|
2057
4074
|
await tx.run(`DELETE FROM ${this.tables.blobChunks} WHERE session_id = ?`, sessionId);
|
|
2058
4075
|
await tx.run(`DELETE FROM ${this.tables.blobs} WHERE session_id = ?`, sessionId);
|
|
2059
4076
|
await tx.run(`DELETE FROM ${this.tables.searchTexts} WHERE session_id = ?`, sessionId);
|
|
2060
4077
|
await tx.run(`DELETE FROM ${this.tables.entryChunks} WHERE session_id = ?`, sessionId);
|
|
2061
4078
|
await tx.run(`DELETE FROM ${this.tables.entries} WHERE session_id = ?`, sessionId);
|
|
2062
4079
|
await tx.run(`DELETE FROM ${this.tables.sessions} WHERE id = ?`, sessionId);
|
|
2063
|
-
}, SESSION_TRANSACTION
|
|
4080
|
+
}, pinReads === void 0 ? SESSION_TRANSACTION : {
|
|
4081
|
+
...SESSION_TRANSACTION,
|
|
4082
|
+
leading: pinReads
|
|
4083
|
+
});
|
|
4084
|
+
await this.sweepReleasedForkRows(released);
|
|
4085
|
+
}
|
|
4086
|
+
/**
|
|
4087
|
+
* The fork history of `sessionId` where the transaction `tx` runs on shared history: through `reads`, the transaction's
|
|
4088
|
+
* leading reads, or, for a store that had not seen shared history when the transaction began, read now.
|
|
4089
|
+
*/
|
|
4090
|
+
async readForkPinsWithin(tx, sessionId, reads) {
|
|
4091
|
+
if (reads !== void 0) return readForkPins(tx, reads);
|
|
4092
|
+
if (!await this.sharedHistoryForks(tx)) return void 0;
|
|
4093
|
+
return readForkPins(tx, forkPinReads(this.forkHost(), this.tables.sessions, sessionId));
|
|
4094
|
+
}
|
|
4095
|
+
/**
|
|
4096
|
+
* Removes the rows of deleted sessions no fork reads any more, among `released` and any an earlier sweep left, in
|
|
4097
|
+
* transactions of their own after the write that released them committed. A sweep that fails leaves tombstones the
|
|
4098
|
+
* next one finishes: the write it follows stands either way.
|
|
4099
|
+
*/
|
|
4100
|
+
async sweepReleasedForkRows(released) {
|
|
4101
|
+
if (released.length === 0) return;
|
|
4102
|
+
const { sweepForkTombstones } = await import("../core/storage/session/fork-sweep.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
|
|
4103
|
+
try {
|
|
4104
|
+
await sweepForkTombstones(this.forkHost(), released);
|
|
4105
|
+
} catch {}
|
|
2064
4106
|
}
|
|
2065
4107
|
/**
|
|
2066
4108
|
* Stores the blob as rows of at most {@link SESSION_BLOB_CHUNK_BYTES}, then publishes its header. Every statement
|
|
@@ -2077,9 +4119,15 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
2077
4119
|
hash: await sha256Hex(stored),
|
|
2078
4120
|
bytes: stored.byteLength
|
|
2079
4121
|
};
|
|
2080
|
-
const
|
|
4122
|
+
const found = await this.database.get(`SELECT (SELECT max(schema_version) FROM ${this.tables.meta}) AS schema_version, b.bytes, b.chunks
|
|
4123
|
+
FROM (SELECT 1 AS one) AS probe LEFT JOIN ${this.tables.blobs} b ON b.session_id = ? AND b.hash = ?`, sessionId, blob.hash);
|
|
4124
|
+
assertStorageSchemaVersion("sessions", found?.schema_version ?? null, 3, SESSION_SCHEMA_VERSION_UNCHUNKED);
|
|
4125
|
+
const previous = found?.bytes === null || found?.bytes === void 0 ? void 0 : {
|
|
4126
|
+
bytes: Number(found.bytes),
|
|
4127
|
+
chunks: Number(found.chunks)
|
|
4128
|
+
};
|
|
2081
4129
|
if (previous) {
|
|
2082
|
-
if (previous.chunks === -1) while (await this.database.transaction((tx) => migrateLegacyBlobBatch(tx, this.tables, sessionId, blob.hash, stored))) await new Promise((resolve) => setTimeout(resolve, 0));
|
|
4130
|
+
if (previous.chunks === -1) while (await this.database.transaction((tx) => migrateLegacyBlobBatch(tx, this.tables, sessionId, blob.hash, stored), this.sessionWrite(sessionId))) await new Promise((resolve) => setTimeout(resolve, 0));
|
|
2083
4131
|
return blob;
|
|
2084
4132
|
}
|
|
2085
4133
|
const chunks = Math.ceil(blob.bytes / SESSION_BLOB_CHUNK_BYTES);
|
|
@@ -2102,36 +4150,68 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
2102
4150
|
async getBlob(sessionId, hash) {
|
|
2103
4151
|
this.assertOpen();
|
|
2104
4152
|
validateSessionText("sessionId", sessionId);
|
|
2105
|
-
let
|
|
2106
|
-
|
|
2107
|
-
if (header.chunks === -1) {
|
|
2108
|
-
const row = await this.database.get(`SELECT data FROM ${this.tables.blobs} WHERE session_id = ? AND hash = ? AND chunks = -1`, sessionId, hash);
|
|
2109
|
-
if (row) {
|
|
2110
|
-
if (row.data.byteLength === header.bytes) return row.data;
|
|
2111
|
-
throw new SessionBlobError("blob-incomplete", {
|
|
2112
|
-
sessionId,
|
|
2113
|
-
hash,
|
|
2114
|
-
bytes: header.bytes
|
|
2115
|
-
});
|
|
2116
|
-
}
|
|
2117
|
-
header = await this.blobHeader(sessionId, hash);
|
|
4153
|
+
for (let attempt = 0;; attempt++) {
|
|
4154
|
+
const header = await this.blobOwner(sessionId, hash);
|
|
2118
4155
|
if (header === void 0) return void 0;
|
|
4156
|
+
const { owner } = header;
|
|
4157
|
+
if (header.chunks === -1) {
|
|
4158
|
+
const row = await this.database.get(`SELECT data FROM ${this.tables.blobs} WHERE session_id = ? AND hash = ? AND chunks = -1`, owner, hash);
|
|
4159
|
+
if (row) {
|
|
4160
|
+
if (row.data.byteLength === header.bytes) return row.data;
|
|
4161
|
+
throw new SessionBlobError("blob-incomplete", {
|
|
4162
|
+
sessionId,
|
|
4163
|
+
hash,
|
|
4164
|
+
bytes: header.bytes
|
|
4165
|
+
});
|
|
4166
|
+
}
|
|
4167
|
+
if (attempt < 2) continue;
|
|
4168
|
+
return;
|
|
4169
|
+
}
|
|
4170
|
+
const data = new Uint8Array(header.bytes);
|
|
4171
|
+
let offset = 0;
|
|
4172
|
+
for (let index = 0; index < header.chunks; index++) {
|
|
4173
|
+
const row = await this.database.get(`SELECT data FROM ${this.tables.blobChunks} WHERE idx = ? AND session_id = ? AND hash = ?`, index, owner, hash);
|
|
4174
|
+
if (row?.data == null || offset + row.data.byteLength > data.byteLength) break;
|
|
4175
|
+
data.set(row.data, offset);
|
|
4176
|
+
offset += row.data.byteLength;
|
|
4177
|
+
}
|
|
4178
|
+
if (offset === data.byteLength) return data;
|
|
4179
|
+
const again = await this.blobOwner(sessionId, hash);
|
|
4180
|
+
if (again === void 0) return void 0;
|
|
4181
|
+
if (again.owner !== owner && attempt < 2) continue;
|
|
4182
|
+
throw new SessionBlobError("blob-incomplete", {
|
|
4183
|
+
sessionId,
|
|
4184
|
+
hash,
|
|
4185
|
+
bytes: header.bytes
|
|
4186
|
+
});
|
|
2119
4187
|
}
|
|
2120
|
-
|
|
2121
|
-
|
|
2122
|
-
|
|
2123
|
-
|
|
2124
|
-
|
|
2125
|
-
|
|
2126
|
-
|
|
2127
|
-
|
|
2128
|
-
|
|
2129
|
-
|
|
2130
|
-
|
|
2131
|
-
|
|
2132
|
-
|
|
2133
|
-
|
|
2134
|
-
}
|
|
4188
|
+
}
|
|
4189
|
+
/**
|
|
4190
|
+
* Where session `sessionId`'s blob `hash` is stored, with its header: its own, or the first of its fork sources' by
|
|
4191
|
+
* id, through the segments of a fork that shares its parent's history (#6560). Read outside a transaction.
|
|
4192
|
+
*/
|
|
4193
|
+
async blobOwner(sessionId, hash) {
|
|
4194
|
+
const row = await this.outsideTransaction((tables) => this.database.get(tables.segments === void 0 ? `SELECT session_id AS owner, bytes, chunks FROM ${this.tables.blobs} WHERE session_id = ? AND hash = ?${tables.guard === void 0 ? "" : ` AND ${tables.guard}`}` : `SELECT b.session_id AS owner, b.bytes, b.chunks
|
|
4195
|
+
FROM ${this.blobPlaces(tables)} w JOIN ${this.tables.blobs} b ON b.session_id = w.owner AND b.hash = ?
|
|
4196
|
+
${tables.guard === void 0 ? "" : `WHERE ${tables.guard}`}
|
|
4197
|
+
ORDER BY w.place, b.session_id LIMIT 1`, ...tables.segments === void 0 ? [sessionId, hash] : [...this.blobPlaceParams(tables, sessionId), hash]), (found) => found !== void 0);
|
|
4198
|
+
return row === void 0 ? void 0 : {
|
|
4199
|
+
owner: String(row.owner),
|
|
4200
|
+
bytes: Number(row.bytes),
|
|
4201
|
+
chunks: Number(row.chunks)
|
|
4202
|
+
};
|
|
4203
|
+
}
|
|
4204
|
+
/**
|
|
4205
|
+
* The sessions whose blobs a session reads (#6560), as a derived table of `owner` and `place`: the session itself,
|
|
4206
|
+
* place 0, and, with shared history, the sources its segments name, place 1. A blob is then looked up by its key in
|
|
4207
|
+
* each, never by a scan of the blobs of every session. Its parameters are {@link blobPlaceParams}.
|
|
4208
|
+
*/
|
|
4209
|
+
blobPlaces(tables) {
|
|
4210
|
+
const own = `SELECT CAST(? AS ${this.dialect.types.text}) AS owner, 0 AS place`;
|
|
4211
|
+
return tables.segments === void 0 ? `(${own})` : `(${own} UNION ALL SELECT source_id, 1 FROM ${tables.segments} WHERE session_id = ?)`;
|
|
4212
|
+
}
|
|
4213
|
+
blobPlaceParams(tables, sessionId) {
|
|
4214
|
+
return tables.segments === void 0 ? [sessionId] : [sessionId, sessionId];
|
|
2135
4215
|
}
|
|
2136
4216
|
async blobHeader(sessionId, hash) {
|
|
2137
4217
|
const row = await this.database.get(`SELECT bytes, chunks FROM ${this.tables.blobs} WHERE session_id = ? AND hash = ?`, sessionId, hash);
|
|
@@ -2201,6 +4281,10 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
2201
4281
|
this.closed = true;
|
|
2202
4282
|
this.scopes.clear();
|
|
2203
4283
|
this.summaries.clear();
|
|
4284
|
+
dropStoredNotes(this);
|
|
4285
|
+
const reader = this.reader;
|
|
4286
|
+
this.reader = void 0;
|
|
4287
|
+
if (reader !== void 0) await (await reader.catch(() => void 0))?.close();
|
|
2204
4288
|
}
|
|
2205
4289
|
/**
|
|
2206
4290
|
* `data_version` moves when another connection commits and `total_changes()` when this one writes, so
|
|
@@ -2382,17 +4466,25 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
2382
4466
|
const order = this.dialect.rowOrder();
|
|
2383
4467
|
const rows = [];
|
|
2384
4468
|
for (let after = 0, limit = SESSION_READ_FETCH.first;;) {
|
|
4469
|
+
const seen = this.sharedHistorySeen;
|
|
4470
|
+
const texts = (session) => forkViewOf({
|
|
4471
|
+
segments: seen ? this.forkTables.forkSegments : void 0,
|
|
4472
|
+
dialect: this.dialect
|
|
4473
|
+
}, {
|
|
4474
|
+
table: this.tables.searchTexts,
|
|
4475
|
+
columns: ["text_json"]
|
|
4476
|
+
}, session);
|
|
2385
4477
|
const page = await this.database.all(`WITH keyed AS MATERIALIZED (
|
|
2386
4478
|
SELECT ${LISTING_COLUMNS}, ${order} AS ord, ${LISTING_SIZE} AS size
|
|
2387
4479
|
FROM ${this.tables.sessions} AS s WHERE (${where}) AND ${order} > ? ORDER BY ord LIMIT ?
|
|
2388
4480
|
), sized AS MATERIALIZED (
|
|
2389
4481
|
SELECT ${LISTING_COLUMNS}, ord, size,
|
|
2390
|
-
(SELECT COALESCE(sum(length(text_json) + 1) + 1, 2) FROM ${
|
|
4482
|
+
(SELECT COALESCE(sum(length(text_json) + 1) + 1, 2) FROM ${texts("keyed.id")} AS t) AS search_size
|
|
2391
4483
|
FROM keyed
|
|
2392
4484
|
) SELECT ${LISTING_COLUMNS}, ord, fetched, batch_chars, page_chars, CASE WHEN search_size <= ? THEN (
|
|
2393
4485
|
SELECT COALESCE('[' || ${this.dialect.orderedConcat("text_json", "','", "seq")} || ']', '[]')
|
|
2394
|
-
FROM (SELECT text_json, seq FROM ${
|
|
2395
|
-
) END AS search_texts_json
|
|
4486
|
+
FROM (SELECT text_json, seq FROM ${texts("page.id")} AS t ORDER BY seq) AS ordered
|
|
4487
|
+
) END AS search_texts_json, (SELECT max(schema_version) FROM ${this.tables.meta}) AS schema_version
|
|
2396
4488
|
FROM (
|
|
2397
4489
|
SELECT ${LISTING_COLUMNS}, ord, search_size, count(*) OVER () AS fetched,
|
|
2398
4490
|
row_number() OVER (ORDER BY ord) AS page_row,
|
|
@@ -2400,6 +4492,11 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
2400
4492
|
sum(size + search_size) OVER (ORDER BY ord) AS page_chars
|
|
2401
4493
|
FROM sized
|
|
2402
4494
|
) AS page WHERE (page_chars <= ? OR page_row = 1) AND page_row <= ? ORDER BY ord`, ...params, after, limit + 1, SESSION_READ_PAGE_CHARS, SESSION_READ_PAGE_CHARS, limit);
|
|
4495
|
+
for (const row of page) {
|
|
4496
|
+
assertStorageSchemaVersion("sessions", row.schema_version, 3, SESSION_SCHEMA_VERSION_UNCHUNKED);
|
|
4497
|
+
this.noteSchemaVersion(row.schema_version);
|
|
4498
|
+
}
|
|
4499
|
+
if (this.sharedHistorySeen !== seen) continue;
|
|
2403
4500
|
for (const row of page) {
|
|
2404
4501
|
const summaryRow = row.search_texts_json === null ? {
|
|
2405
4502
|
...row,
|
|
@@ -2417,12 +4514,31 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
2417
4514
|
limit = next.limit;
|
|
2418
4515
|
}
|
|
2419
4516
|
}
|
|
2420
|
-
/**
|
|
4517
|
+
/**
|
|
4518
|
+
* A session's search texts as one JSON array, read in pages of at most {@link SESSION_READ_PAGE_CHARS}, through its
|
|
4519
|
+
* view (#6560). Only a session with some text is read this way, so a read that finds none was held back.
|
|
4520
|
+
*/
|
|
2421
4521
|
async readSearchTexts(sessionId) {
|
|
2422
|
-
const
|
|
4522
|
+
const textsView = (tables, after, through) => {
|
|
4523
|
+
return forkView(tables, {
|
|
4524
|
+
name: "texts_view",
|
|
4525
|
+
table: this.tables.searchTexts,
|
|
4526
|
+
columns: ["text_json"],
|
|
4527
|
+
sessionId,
|
|
4528
|
+
after,
|
|
4529
|
+
through
|
|
4530
|
+
});
|
|
4531
|
+
};
|
|
4532
|
+
const sizes = await this.outsideTransaction((tables) => {
|
|
4533
|
+
const view = textsView(tables, 0, FORK_VIEW_END);
|
|
4534
|
+
return this.database.all(withForkViews([view], "SELECT seq, length(text_json) AS size FROM texts_view ORDER BY seq"), ...view.params);
|
|
4535
|
+
}, (found) => found.length > 0);
|
|
2423
4536
|
const texts = [];
|
|
2424
4537
|
for (const page of pagesOf(sizes)) {
|
|
2425
|
-
const rows = await this.
|
|
4538
|
+
const rows = await this.outsideTransaction((tables) => {
|
|
4539
|
+
const view = textsView(tables, Number(page[0].seq) - 1, Number(page.at(-1).seq));
|
|
4540
|
+
return this.database.all(withForkViews([view], "SELECT text_json FROM texts_view ORDER BY seq"), ...view.params);
|
|
4541
|
+
}, (found) => found.length > 0);
|
|
2426
4542
|
for (const row of rows) texts.push(row.text_json);
|
|
2427
4543
|
}
|
|
2428
4544
|
return `[${texts.join(",")}]`;
|
|
@@ -2443,45 +4559,69 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
2443
4559
|
query.signal?.throwIfAborted();
|
|
2444
4560
|
}
|
|
2445
4561
|
async read(tx, sessionId) {
|
|
2446
|
-
const
|
|
4562
|
+
const generation = this.generation(sessionId);
|
|
4563
|
+
const shared = await this.viewTables(tx);
|
|
4564
|
+
const head = tx.get(`SELECT header_json, last_seq,CASE WHEN ${this.dialect.jsonValid("summary_state")} THEN ${this.dialect.jsonText("summary_state", "epoch")} END AS chat_epoch,revision,${generation.sql} AS epoch${this.forkedColumn(shared.segments)} FROM ${this.tables.sessions} WHERE id = ?`, ...generation.params, sessionId);
|
|
4565
|
+
const guess = this.forkedSessions.get(sessionId) === false ? {
|
|
4566
|
+
...shared,
|
|
4567
|
+
segments: void 0
|
|
4568
|
+
} : shared;
|
|
4569
|
+
const epoch = head.then((found) => found?.epoch);
|
|
4570
|
+
let [row, rows] = await Promise.all([head, this.readRows(tx, sessionId, void 0, void 0, epoch, guess)]);
|
|
2447
4571
|
if (!row) throw new SessionNotFoundError$1(sessionId);
|
|
4572
|
+
this.noteForked(tx, sessionId, row.forked);
|
|
4573
|
+
if (guess.segments === void 0 && shared.segments !== void 0 && Number(row.forked) === 1) rows = await this.readRows(tx, sessionId, void 0, void 0, epoch, shared);
|
|
2448
4574
|
const snapshot = {
|
|
2449
4575
|
header: JSON.parse(row.header_json),
|
|
2450
|
-
entries:
|
|
4576
|
+
entries: rows.map(({ entry }) => entry),
|
|
2451
4577
|
lastSeq: row.last_seq
|
|
2452
4578
|
};
|
|
2453
4579
|
if (typeof row.chat_epoch === "string") bindChatEpoch(snapshot.header, row.chat_epoch);
|
|
2454
4580
|
return noteSnapshotGeneration(this, snapshot, nativeLoad, row, "revision");
|
|
2455
4581
|
}
|
|
2456
|
-
|
|
4582
|
+
/**
|
|
4583
|
+
* The entries of session `sessionId` from `from` through `through`, in pages, through its view (#6560): only those
|
|
4584
|
+
* whose seq `seqs` lists, when it is given, which then lies in that range. With `epoch`, the session's generation in
|
|
4585
|
+
* the snapshot of `tx`, each entry is noted as stored at its seq in it, for a fork of the session to share its row.
|
|
4586
|
+
*/
|
|
4587
|
+
async readRows(tx, sessionId, range = {}, seqs, epoch, viewTables) {
|
|
4588
|
+
const tables = viewTables ?? await this.viewTables(tx, sessionId);
|
|
4589
|
+
const through = range.through ?? FORK_VIEW_END;
|
|
4590
|
+
const filter = seqs === void 0 ? "" : ` AND seq IN (${seqs.map(() => "?").join(", ")})`;
|
|
2457
4591
|
const entries = [];
|
|
2458
|
-
for (let after = 0, limit = SESSION_READ_FETCH.first;;) {
|
|
2459
|
-
const
|
|
2460
|
-
|
|
4592
|
+
for (let after = Math.max(0, (range.from ?? 1) - 1), limit = SESSION_READ_FETCH.first;;) {
|
|
4593
|
+
const view = this.entriesView(tables, sessionId, after, tables.segments === void 0 || seqs !== void 0 ? through : Math.min(through, after + limit + 1));
|
|
4594
|
+
const rows = await tx.all(withForkViews([view], `WITH sized AS MATERIALIZED (
|
|
4595
|
+
SELECT seq, chunks, src_id, src_seq, length(entry_json) AS size,
|
|
2461
4596
|
CASE WHEN ${this.dialect.textByteLength("entry_json")} <= ? THEN entry_json END AS inline_json
|
|
2462
|
-
FROM ${
|
|
4597
|
+
FROM ${view.name} WHERE seq > ?${filter} ORDER BY seq LIMIT ?
|
|
2463
4598
|
), batch AS MATERIALIZED (
|
|
2464
4599
|
SELECT count(*) AS fetched, COALESCE(sum(size), 0) AS chars FROM sized
|
|
2465
4600
|
), page AS (
|
|
2466
|
-
SELECT seq, chunks, inline_json, fetched, chars AS batch_chars, 0 AS page_chars
|
|
2467
|
-
FROM (SELECT seq, chunks, inline_json FROM sized ORDER BY seq LIMIT ?) AS fitting CROSS JOIN batch
|
|
4601
|
+
SELECT seq, chunks, src_id, src_seq, inline_json, fetched, chars AS batch_chars, 0 AS page_chars
|
|
4602
|
+
FROM (SELECT seq, chunks, src_id, src_seq, inline_json FROM sized ORDER BY seq LIMIT ?) AS fitting CROSS JOIN batch
|
|
2468
4603
|
WHERE batch.chars <= ?
|
|
2469
4604
|
UNION ALL
|
|
2470
|
-
SELECT seq, chunks, inline_json, fetched, batch_chars, page_chars FROM (
|
|
2471
|
-
SELECT seq, chunks, inline_json, batch.fetched, batch.chars AS batch_chars,
|
|
4605
|
+
SELECT seq, chunks, src_id, src_seq, inline_json, fetched, batch_chars, page_chars FROM (
|
|
4606
|
+
SELECT seq, chunks, src_id, src_seq, inline_json, batch.fetched, batch.chars AS batch_chars,
|
|
2472
4607
|
row_number() OVER (ORDER BY seq) AS page_row,
|
|
2473
4608
|
sum(size) OVER (ORDER BY seq) AS page_chars
|
|
2474
4609
|
FROM sized CROSS JOIN batch WHERE batch.chars > ?
|
|
2475
4610
|
) AS windowed WHERE (page_chars <= ? OR page_row = 1) AND page_row <= ?
|
|
2476
4611
|
) SELECT seq, COALESCE(inline_json, (
|
|
2477
|
-
SELECT e.entry_json FROM ${this.tables.entries} AS e WHERE e.session_id =
|
|
2478
|
-
)) AS entry_json, chunks, fetched, batch_chars, page_chars FROM page ORDER BY seq
|
|
4612
|
+
SELECT e.entry_json FROM ${this.tables.entries} AS e WHERE e.session_id = page.src_id AND e.seq = page.src_seq
|
|
4613
|
+
)) AS entry_json, chunks, fetched, batch_chars, page_chars FROM page ORDER BY seq`), ...forkViewParams([view]), SESSION_READ_INLINE_BYTES, after, ...seqs ?? [], limit + 1, limit, SESSION_READ_PAGE_CHARS, SESSION_READ_PAGE_CHARS, SESSION_READ_PAGE_CHARS, limit);
|
|
4614
|
+
const generation = await epoch;
|
|
4615
|
+
const note = generation === void 0 || !this.sharedHistorySeen ? void 0 : storedEntryNotes(this, sessionId, generation);
|
|
2479
4616
|
for (const entry of rows) {
|
|
2480
4617
|
const chunks = Number(entry.chunks);
|
|
2481
|
-
const
|
|
4618
|
+
const seq = Number(entry.seq);
|
|
4619
|
+
const json = chunks === 0 ? entry.entry_json : await this.readEntryChunks(tx, tables, sessionId, seq, chunks);
|
|
4620
|
+
const parsed = JSON.parse(json);
|
|
4621
|
+
note?.(parsed, seq, json);
|
|
2482
4622
|
entries.push({
|
|
2483
|
-
seq
|
|
2484
|
-
entry:
|
|
4623
|
+
seq,
|
|
4624
|
+
entry: parsed
|
|
2485
4625
|
});
|
|
2486
4626
|
}
|
|
2487
4627
|
const next = nextFetch(limit, rows);
|
|
@@ -2490,17 +4630,54 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
2490
4630
|
limit = next.limit;
|
|
2491
4631
|
}
|
|
2492
4632
|
}
|
|
2493
|
-
async readSeqs(tx, sessionId, seqs) {
|
|
4633
|
+
async readSeqs(tx, sessionId, seqs, epoch) {
|
|
2494
4634
|
const entries = [];
|
|
2495
4635
|
for (let start = 0; start < seqs.length; start += SEQ_BATCH) {
|
|
2496
4636
|
const batch = seqs.slice(start, start + SEQ_BATCH);
|
|
2497
|
-
|
|
4637
|
+
const range = {
|
|
4638
|
+
from: Math.min(...batch),
|
|
4639
|
+
through: Math.max(...batch)
|
|
4640
|
+
};
|
|
4641
|
+
entries.push(...await this.readRows(tx, sessionId, range, batch, epoch));
|
|
2498
4642
|
}
|
|
2499
4643
|
return entries;
|
|
2500
4644
|
}
|
|
4645
|
+
/**
|
|
4646
|
+
* The read of the session's row that `resumeSource` makes first: a read transaction that starts with it names it as
|
|
4647
|
+
* a leading read, so a pipelined connection sends it with the transaction's start (#6560).
|
|
4648
|
+
*/
|
|
4649
|
+
resumeRow(sessionId) {
|
|
4650
|
+
return {
|
|
4651
|
+
sql: `SELECT header_json,last_seq,summary_state,revision${this.forkedColumn(this.sharedHistorySeen ? this.forkTables.forkSegments : void 0)} FROM ${this.tables.sessions} WHERE id = ?`,
|
|
4652
|
+
params: [sessionId]
|
|
4653
|
+
};
|
|
4654
|
+
}
|
|
4655
|
+
/**
|
|
4656
|
+
* The view (#6560), as `name`, of session `sessionId`'s entries after seq `after` and through seq `through`, with
|
|
4657
|
+
* `entry_id`, `entry_json` and `chunks`, and where each is stored.
|
|
4658
|
+
*/
|
|
4659
|
+
entriesView(tables, sessionId, after = 0, through = FORK_VIEW_END, name = "entries_view") {
|
|
4660
|
+
return {
|
|
4661
|
+
...forkView(tables, {
|
|
4662
|
+
name,
|
|
4663
|
+
table: this.tables.entries,
|
|
4664
|
+
columns: [
|
|
4665
|
+
"entry_id",
|
|
4666
|
+
"entry_json",
|
|
4667
|
+
"chunks"
|
|
4668
|
+
],
|
|
4669
|
+
sessionId,
|
|
4670
|
+
after,
|
|
4671
|
+
through
|
|
4672
|
+
}),
|
|
4673
|
+
name
|
|
4674
|
+
};
|
|
4675
|
+
}
|
|
2501
4676
|
async resumeSource(tx, sessionId) {
|
|
2502
|
-
const
|
|
4677
|
+
const read = this.resumeRow(sessionId);
|
|
4678
|
+
const row = await tx.get(read.sql, ...read.params);
|
|
2503
4679
|
if (!row) throw new SessionNotFoundError$1(sessionId);
|
|
4680
|
+
this.noteForked(tx, sessionId, row.forked);
|
|
2504
4681
|
const stored = windowIndex(JSON.parse(row.summary_state), Number(row.last_seq));
|
|
2505
4682
|
const remembered = this.resumeIndexes.get(sessionId);
|
|
2506
4683
|
const index = isSessionResumeIndex(stored, Number(row.last_seq)) ? stored : remembered?.revision === row.revision ? remembered.index : void 0;
|
|
@@ -2511,16 +4688,32 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
2511
4688
|
row
|
|
2512
4689
|
};
|
|
2513
4690
|
}
|
|
4691
|
+
/**
|
|
4692
|
+
* Runs `read`, a read transaction that finds the session's index with `resumeSource`, at once; only when that index is
|
|
4693
|
+
* missing or stale (`resumeSource` rejects with `SessionConflictError`) does it compute the index with
|
|
4694
|
+
* `prepareResume` and run `read` again. A current index, the usual case, then costs no read before the transaction:
|
|
4695
|
+
* on a server, one round trip fewer (#6560).
|
|
4696
|
+
*/
|
|
4697
|
+
async withResumeIndex(sessionId, read) {
|
|
4698
|
+
try {
|
|
4699
|
+
return await read();
|
|
4700
|
+
} catch (error) {
|
|
4701
|
+
if (!(error instanceof SessionConflictError$1)) throw error;
|
|
4702
|
+
}
|
|
4703
|
+
await this.prepareResume(sessionId);
|
|
4704
|
+
return read();
|
|
4705
|
+
}
|
|
2514
4706
|
async prepareResume(sessionId, leafId, throughSeq) {
|
|
2515
4707
|
attempts: for (let attempt = 0; attempt < 3; attempt++) {
|
|
2516
|
-
const row = await this.database.get(`SELECT header_json,last_seq,summary_state,revision FROM ${this.tables.sessions} WHERE id = ?`, sessionId);
|
|
4708
|
+
const row = await this.database.get(`SELECT header_json,last_seq,summary_state,revision${this.outsideForkedColumn("id")} FROM ${this.tables.sessions} WHERE id = ?`, sessionId);
|
|
2517
4709
|
if (!row) throw new SessionNotFoundError$1(sessionId);
|
|
4710
|
+
this.noteForked(void 0, sessionId, row.forked);
|
|
2518
4711
|
const state = JSON.parse(row.summary_state);
|
|
2519
4712
|
const remembered = this.resumeIndexes.get(sessionId);
|
|
2520
4713
|
const currentIndex = windowIndex(state, Number(row.last_seq)) ?? (remembered?.revision === row.revision && isSessionResumeIndex(remembered.index, Number(row.last_seq)) ? remembered.index : void 0);
|
|
2521
4714
|
const limit = throughSeq ?? Number(row.last_seq);
|
|
2522
4715
|
if (limit > Number(row.last_seq)) throw new SessionConflictError$1(sessionId, limit, Number(row.last_seq));
|
|
2523
|
-
const selected = leafId === void 0 ? void 0 : await this.seqOfEntry(this.database, sessionId, leafId) ?? 0;
|
|
4716
|
+
const selected = leafId === void 0 ? void 0 : await this.seqOfEntry(this.database, void 0, sessionId, leafId) ?? 0;
|
|
2524
4717
|
const requested = selected !== void 0 && selected > limit ? 0 : selected;
|
|
2525
4718
|
if (currentIndex && limit === currentIndex.seq && (requested === void 0 || requested === currentIndex.leafSeq)) return {
|
|
2526
4719
|
index: currentIndex,
|
|
@@ -2649,12 +4842,18 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
2649
4842
|
const lo = "(SELECT lo FROM bounds)";
|
|
2650
4843
|
const hi = "(SELECT hi FROM bounds)";
|
|
2651
4844
|
const pageWhere = sqlite ? `WHERE session_id = ${owner} AND seq > ${lo} AND seq <= ${hi}${sources}` : where;
|
|
4845
|
+
const viewed = this.outsideViewTables();
|
|
4846
|
+
const tables = Number(row.forked) === 0 ? {
|
|
4847
|
+
...viewed,
|
|
4848
|
+
segments: void 0
|
|
4849
|
+
} : viewed;
|
|
4850
|
+
const shared = tables.segments !== void 0;
|
|
2652
4851
|
const page = `WITH ${sqlite ? "bounds(id,lo,hi) AS NOT MATERIALIZED (VALUES (?,?,?)), " : ""}page AS (
|
|
2653
|
-
SELECT ${sqlite ? "" : "CASE WHEN chunks > 0 THEN
|
|
4852
|
+
SELECT ${sqlite && !shared ? "" : "CASE WHEN chunks > 0 THEN src_id END AS src_id,"}seq,src_seq,entry_id,chunks,entry_json FROM entries_view
|
|
2654
4853
|
${pageWhere} ORDER BY seq LIMIT ${SESSION_RESUME_REBUILD.pageEntries}
|
|
2655
4854
|
)`;
|
|
2656
|
-
const parts = (source) => `FROM ${this.tables.entryChunks} WHERE session_id = ${sqlite ? owner : `${source}.
|
|
2657
|
-
AND seq = ${source}.
|
|
4855
|
+
const parts = (source) => `FROM ${this.tables.entryChunks} WHERE session_id = ${sqlite && !shared ? owner : `${source}.src_id`}
|
|
4856
|
+
AND seq = ${source}.src_seq AND idx >= 0 AND idx < ${source}.chunks`;
|
|
2658
4857
|
const projection = sqlite ? `SELECT seq,entry_id,chunks,${select} FROM payloads ORDER BY seq` : `SELECT seq,entry_id,chunks,${select} FROM payloads
|
|
2659
4858
|
CROSS JOIN LATERAL (SELECT ${postgresJsonb("entry_json")} AS value OFFSET 0) AS parsed ORDER BY seq`;
|
|
2660
4859
|
const fits = sqlite ? "length(zeroblob(sum(length(data)))) IS NOT NULL" : "sum(octet_length(data)) < 1073741824";
|
|
@@ -2669,7 +4868,7 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
2669
4868
|
) ${projection}`;
|
|
2670
4869
|
const keysPerEntry = 64;
|
|
2671
4870
|
const through = `${lo} + ${SESSION_RESUME_REBUILD.pageEntries}`;
|
|
2672
|
-
const wide = sqlite && Number(row.last_seq) > 0 && Buffer.byteLength(sessionId) >= 512;
|
|
4871
|
+
const wide = sqlite && !shared && Number(row.last_seq) > 0 && Buffer.byteLength(sessionId) >= 512;
|
|
2673
4872
|
let inlinePage = wide && this.chunkRowids === void 0 ? `${page}, chunked AS MATERIALIZED (SELECT 1 FROM page WHERE chunks > 0 LIMIT 1),
|
|
2674
4873
|
payloads AS MATERIALIZED (SELECT seq,entry_id,chunks,entry_json FROM page WHERE NOT EXISTS (SELECT 1 FROM chunked)
|
|
2675
4874
|
UNION ALL SELECT 0,'',0,'{}' FROM chunked) ${projection}` : void 0;
|
|
@@ -2696,14 +4895,16 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
2696
4895
|
let topology = currentIndex && requested !== void 0 ? branchRanges(currentIndex, requested) : void 0;
|
|
2697
4896
|
for (let pass = topology === void 0 ? 0 : 1; pass < 2; pass++) {
|
|
2698
4897
|
for (let after = 0; after < limit;) {
|
|
4898
|
+
const view = this.entriesView(tables, sessionId, after, Math.min(limit, after + SESSION_RESUME_REBUILD.pageEntries));
|
|
2699
4899
|
const args = [
|
|
4900
|
+
...view.params,
|
|
2700
4901
|
sessionId,
|
|
2701
4902
|
after,
|
|
2702
4903
|
limit
|
|
2703
4904
|
];
|
|
2704
4905
|
let rows;
|
|
2705
4906
|
try {
|
|
2706
|
-
rows = await this.database.all(inlinePage ?? (this.chunkRowids ? rowidPage : directPage), ...args);
|
|
4907
|
+
rows = await this.database.all(withForkViews([view], inlinePage ?? (this.chunkRowids ? rowidPage : directPage)), ...args);
|
|
2707
4908
|
if (inlinePage && Number(rows[0]?.seq) === 0) {
|
|
2708
4909
|
inlinePage = void 0;
|
|
2709
4910
|
try {
|
|
@@ -2714,12 +4915,15 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
2714
4915
|
}
|
|
2715
4916
|
} catch (error) {
|
|
2716
4917
|
if (!(error instanceof Error && "code" in error && error.code === "payload-too-large")) throw error;
|
|
2717
|
-
if (!await this.database.get(`SELECT 1 FROM ${
|
|
2718
|
-
|
|
2719
|
-
|
|
2720
|
-
rows = await this.database.all(stubPage, ...args);
|
|
4918
|
+
if (!await this.database.get(withForkViews([view], `SELECT 1 FROM (SELECT src_id, src_seq FROM ${view.name} ${where}
|
|
4919
|
+
ORDER BY seq LIMIT ${SESSION_RESUME_REBUILD.pageEntries}) AS p
|
|
4920
|
+
JOIN ${this.tables.entryChunks} c ON c.session_id = p.src_id AND c.seq = p.src_seq LIMIT 1`), ...view.params, sessionId, after, limit).catch(() => void 0)) throw error;
|
|
4921
|
+
rows = await this.database.all(withForkViews([view], stubPage), ...args);
|
|
4922
|
+
}
|
|
4923
|
+
if (rows.length === 0) {
|
|
4924
|
+
if (await this.schemaNowShared(viewed.segments !== void 0)) continue attempts;
|
|
4925
|
+
break;
|
|
2721
4926
|
}
|
|
2722
|
-
if (rows.length === 0) break;
|
|
2723
4927
|
const batch = [];
|
|
2724
4928
|
let toolCalls = 0;
|
|
2725
4929
|
for (const entry of rows) {
|
|
@@ -2793,7 +4997,7 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
2793
4997
|
const old = index ?? foldSessionResume(void 0, []);
|
|
2794
4998
|
const seqs = /* @__PURE__ */ new Map();
|
|
2795
4999
|
for (const id of foreignResumeIds(old, batch)) {
|
|
2796
|
-
const seq = await this.seqOfEntry(this.database, sessionId, id);
|
|
5000
|
+
const seq = await this.seqOfEntry(this.database, void 0, sessionId, id);
|
|
2797
5001
|
if (seq !== void 0) seqs.set(id, seq);
|
|
2798
5002
|
}
|
|
2799
5003
|
index = foldSessionResume(index, batch, (id) => seqs.get(id), (seq) => topology === void 0 || topology.some(([a, b]) => seq >= a && seq <= b));
|
|
@@ -2846,60 +5050,73 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
2846
5050
|
async readTail(sessionId, fromSeq) {
|
|
2847
5051
|
this.assertOpen();
|
|
2848
5052
|
validateSessionText("sessionId", sessionId);
|
|
2849
|
-
await this.prepareResume(sessionId);
|
|
2850
5053
|
const start = Math.max(1, fromSeq);
|
|
2851
|
-
const { tail } = await this.
|
|
5054
|
+
const { tail } = await this.withResumeIndex(sessionId, () => this.readTransaction(async (tx) => {
|
|
2852
5055
|
const source = await this.resumeSource(tx, sessionId);
|
|
2853
5056
|
const stateSeqs = stateSeqsBefore(source.index, start);
|
|
2854
5057
|
if (hasHistoryLoadObserver()) announceHistoryLoad(stateSeqs.length + Math.max(0, source.index.seq - start + 1));
|
|
2855
|
-
const state = await this.readSeqs(tx, sessionId, stateSeqs);
|
|
2856
|
-
const entries =
|
|
5058
|
+
const [state, rows] = await Promise.all([this.readSeqs(tx, sessionId, stateSeqs), this.readRows(tx, sessionId, { from: start })]);
|
|
5059
|
+
const entries = rows.map(({ entry }) => entry);
|
|
2857
5060
|
return {
|
|
2858
5061
|
tail: sessionTailFrom(source.index, source.header, start, state, entries),
|
|
2859
5062
|
source
|
|
2860
5063
|
};
|
|
2861
|
-
},
|
|
5064
|
+
}, [this.resumeRow(sessionId)]));
|
|
2862
5065
|
return tail;
|
|
2863
5066
|
}
|
|
2864
5067
|
async readRange(sessionId, startSeq, endSeq, expectedEpoch) {
|
|
2865
5068
|
this.assertOpen();
|
|
2866
5069
|
validateSessionText("sessionId", sessionId);
|
|
2867
5070
|
const start = Math.max(1, startSeq);
|
|
2868
|
-
return this.
|
|
2869
|
-
const head = await this.historyHead(tx, sessionId);
|
|
5071
|
+
return this.readTransaction(async (tx) => {
|
|
5072
|
+
const head = await this.historyHead(tx, sessionId, true);
|
|
2870
5073
|
if (expectedEpoch !== void 0 && expectedEpoch !== head.epoch) throw new SessionConflictError$1(sessionId, endSeq, head.lastSeq);
|
|
2871
|
-
const entries = endSeq < start ? [] : await this.readRows(tx, sessionId,
|
|
5074
|
+
const entries = endSeq < start ? [] : await this.readRows(tx, sessionId, {
|
|
5075
|
+
from: start,
|
|
5076
|
+
through: endSeq
|
|
5077
|
+
}, void 0, head.epoch);
|
|
2872
5078
|
return {
|
|
2873
5079
|
startSeq: start,
|
|
2874
5080
|
entries: entries.map(({ entry }) => entry),
|
|
2875
5081
|
seqs: entries.map(({ seq }) => seq),
|
|
2876
|
-
|
|
5082
|
+
lastSeq: head.lastSeq,
|
|
5083
|
+
epoch: head.epoch
|
|
2877
5084
|
};
|
|
2878
|
-
}
|
|
5085
|
+
});
|
|
2879
5086
|
}
|
|
5087
|
+
/**
|
|
5088
|
+
* The session's watermark and generation; with `segments`, the fork segments table of a database with shared
|
|
5089
|
+
* history, also whether the session has segments (#6560), in the same statement: a read that leaves a session without
|
|
5090
|
+
* them to its tables' own keyed lookups costs no read of its own to learn it.
|
|
5091
|
+
*/
|
|
2880
5092
|
async historyHead(tx, sessionId, readOnly = false) {
|
|
2881
5093
|
const generation = this.generation(sessionId);
|
|
2882
|
-
const
|
|
5094
|
+
const { segments } = await this.viewTables(tx);
|
|
5095
|
+
const row = await tx.get(`SELECT last_seq, revision, ${generation.sql} AS epoch${this.forkedColumn(segments)} FROM ${this.tables.sessions} WHERE id = ?${readOnly ? "" : this.dialect.lockClause("share")}`, ...generation.params, sessionId);
|
|
2883
5096
|
if (!row) throw new SessionNotFoundError$1(sessionId);
|
|
2884
5097
|
this.noteGeneration(sessionId, row.revision, Number(row.last_seq), row.epoch);
|
|
5098
|
+
this.noteForked(tx, sessionId, row.forked);
|
|
2885
5099
|
return {
|
|
2886
5100
|
lastSeq: Number(row.last_seq),
|
|
2887
|
-
epoch: row.epoch
|
|
5101
|
+
epoch: row.epoch,
|
|
5102
|
+
forked: Number(row.forked) === 1
|
|
2888
5103
|
};
|
|
2889
5104
|
}
|
|
2890
5105
|
/** Size at most one page and return only fitting bodies, in the same snapshot as the header. The first
|
|
2891
5106
|
* oversized row is a chunk reference; its full inline value never crosses the driver boundary. */
|
|
2892
5107
|
async historyPacket(tx, sessionId, epoch, from, through, backward) {
|
|
2893
5108
|
const edge = backward ? through : from;
|
|
2894
|
-
const
|
|
2895
|
-
|
|
2896
|
-
|
|
2897
|
-
|
|
5109
|
+
const tables = await this.viewTables(tx, sessionId);
|
|
5110
|
+
const view = this.entriesView(tables, sessionId, from - 1, through);
|
|
5111
|
+
const rows = await tx.all(withForkViews([view], `WITH sizes AS MATERIALIZED (
|
|
5112
|
+
SELECT e.seq, e.chunks, e.src_id, e.src_seq, CASE WHEN e.chunks = 0 THEN ${this.entryByteLength("e.entry_json")} ELSE (e.chunks - 1) * ? +
|
|
5113
|
+
(SELECT length(c.data) FROM ${this.tables.entryChunks} c WHERE c.session_id = e.src_id AND c.seq = e.src_seq AND c.idx = e.chunks - 1) END AS bytes
|
|
5114
|
+
FROM ${view.name} e
|
|
2898
5115
|
), sized_page AS (
|
|
2899
|
-
SELECT seq, chunks, bytes, sum(bytes) OVER (ORDER BY seq ${backward ? "DESC" : "ASC"}) AS cumulative FROM sizes
|
|
5116
|
+
SELECT seq, chunks, src_id, src_seq, bytes, sum(bytes) OVER (ORDER BY seq ${backward ? "DESC" : "ASC"}) AS cumulative FROM sizes
|
|
2900
5117
|
) SELECT p.seq, p.chunks, p.bytes, CASE WHEN p.chunks = 0 AND p.bytes <= ? THEN e.entry_json END AS body
|
|
2901
|
-
FROM sized_page p JOIN ${this.tables.entries} e ON e.session_id =
|
|
2902
|
-
WHERE p.bytes IS NULL OR p.cumulative <= ? OR p.seq = ? ORDER BY p.seq
|
|
5118
|
+
FROM sized_page p JOIN ${this.tables.entries} e ON e.session_id = p.src_id AND e.seq = p.src_seq
|
|
5119
|
+
WHERE p.bytes IS NULL OR p.cumulative <= ? OR p.seq = ? ORDER BY p.seq`), ...view.params, SESSION_ENTRY_CHUNK_BYTES, SESSION_HISTORY_PAGE_BYTES, SESSION_HISTORY_PAGE_BYTES, edge);
|
|
2903
5120
|
const items = [];
|
|
2904
5121
|
for (const row of rows) {
|
|
2905
5122
|
const seq = Number(row.seq);
|
|
@@ -2914,7 +5131,7 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
2914
5131
|
});
|
|
2915
5132
|
else items.push({
|
|
2916
5133
|
seq,
|
|
2917
|
-
entry: JSON.parse(row.body ?? await this.readEntryChunks(tx, sessionId, seq, Number(row.chunks)))
|
|
5134
|
+
entry: JSON.parse(row.body ?? await this.readEntryChunks(tx, tables, sessionId, seq, Number(row.chunks)))
|
|
2918
5135
|
});
|
|
2919
5136
|
}
|
|
2920
5137
|
return items;
|
|
@@ -2923,14 +5140,23 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
2923
5140
|
const { childDisplayCut } = await import("../core/storage/session/card-view.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
|
|
2924
5141
|
const { index } = await this.prepareResume(sessionId);
|
|
2925
5142
|
if (typeof launch.launchLeafId !== "string") return childDisplayCut(index, launch);
|
|
2926
|
-
return this.
|
|
5143
|
+
return this.readTransaction(async (tx) => {
|
|
2927
5144
|
const head = await this.historyHead(tx, sessionId, true);
|
|
2928
5145
|
if (head.epoch !== index.epoch || head.lastSeq < index.seq) throw new SessionConflictError$1(sessionId, index.seq, head.lastSeq);
|
|
2929
|
-
const
|
|
5146
|
+
const view = forkView(await this.viewTables(tx, sessionId), {
|
|
5147
|
+
name: "launched",
|
|
5148
|
+
table: this.tables.entries,
|
|
5149
|
+
columns: ["entry_id"],
|
|
5150
|
+
sessionId,
|
|
5151
|
+
after: 0,
|
|
5152
|
+
through: index.seq,
|
|
5153
|
+
match: {
|
|
5154
|
+
column: "entry_id",
|
|
5155
|
+
value: launch.launchLeafId
|
|
5156
|
+
}
|
|
5157
|
+
});
|
|
5158
|
+
const row = await tx.get(withForkViews([view], "SELECT seq FROM launched ORDER BY seq DESC LIMIT 1"), ...view.params);
|
|
2930
5159
|
return childDisplayCut(index, launch, row === void 0 ? void 0 : Number(row.seq));
|
|
2931
|
-
}, {
|
|
2932
|
-
...SESSION_TRANSACTION,
|
|
2933
|
-
readOnly: true
|
|
2934
5160
|
});
|
|
2935
5161
|
}
|
|
2936
5162
|
/**
|
|
@@ -2969,8 +5195,8 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
2969
5195
|
* timestamp; its caller streams those fields instead of joining or decoding the stored body. */
|
|
2970
5196
|
async readTreeOutline(sessionId, fromSeq, toSeq, epoch) {
|
|
2971
5197
|
this.assertOpen();
|
|
2972
|
-
return this.
|
|
2973
|
-
const head = await this.historyHead(tx, sessionId);
|
|
5198
|
+
return this.readTransaction(async (tx) => {
|
|
5199
|
+
const head = await this.historyHead(tx, sessionId, true);
|
|
2974
5200
|
if (epoch !== void 0 && head.epoch !== epoch || head.lastSeq < toSeq) throw new SessionConflictError$1(sessionId, toSeq, head.lastSeq);
|
|
2975
5201
|
const sqlite = this.dialect.name === "sqlite";
|
|
2976
5202
|
const j = (...path) => this.dialect.jsonText("entry_json", ...path);
|
|
@@ -2981,12 +5207,13 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
2981
5207
|
const trim = sqlite ? "trim" : "btrim";
|
|
2982
5208
|
const hasText = sqlite ? `EXISTS(SELECT 1 FROM json_each(entry_json,'$.message.content') b WHERE CASE WHEN b.type='object' AND json_extract(b.value,'$.type')='text' THEN length(trim(json_extract(b.value,'$.text'),?))>0 END)` : `EXISTS(SELECT 1 FROM jsonb_array_elements((${content})::jsonb) b WHERE b->>'type'='text' AND length(btrim(b->>'text',?))>0)`;
|
|
2983
5209
|
const callIds = sqlite ? `(SELECT json_group_array(json_extract(b.value,'$.id')) FROM json_each(entry_json,'$.message.content') b WHERE CASE WHEN b.type='object' THEN json_extract(b.value,'$.type')='toolCall' AND json_type(b.value,'$.id')='text' END)` : `(SELECT json_agg(b->>'id')::text FROM jsonb_array_elements((${content})::jsonb) b WHERE b->>'type'='toolCall' AND jsonb_typeof(b->'id')='string')`;
|
|
2984
|
-
|
|
5210
|
+
const view = this.entriesView(await this.viewTables(tx, sessionId), sessionId, fromSeq - 1, toSeq);
|
|
5211
|
+
return (await tx.all(withForkViews([view], `SELECT CASE WHEN ${role}='assistant' AND ${ctype}='array' THEN ${callIds} END calls,seq,entry_id,chunks,${j("type")} kind,${j("parentId")} parent,${j("timestamp")} stamp,${role} role,
|
|
2985
5212
|
CASE WHEN ${role}='assistant' AND COALESCE(${j("message", "stopReason")},'') IN ('','toolUse','stop') AND CASE WHEN ${ctype}='array' THEN NOT ${hasText} WHEN ${ctype}='${sqlite ? "text" : "string"}' THEN length(${trim}(${content},?))=0 ELSE TRUE END THEN 1 ELSE 0 END hidden,
|
|
2986
5213
|
CASE WHEN ${j("type")}='custom' AND ${j("customType")}='atomic.leaf' THEN 1 ELSE 0 END leaf_move,
|
|
2987
5214
|
CASE WHEN ${j("type")}='custom' AND ${j("customType")}='subagent-child' THEN 1 ELSE 0 END child_record,
|
|
2988
5215
|
CASE WHEN ${j("type")}='label' THEN ${j("targetId")} END target,CASE WHEN ${j("type")}='label' THEN substr(${j("label")},1,128) END label
|
|
2989
|
-
FROM ${
|
|
5216
|
+
FROM ${view.name} WHERE session_id=? AND seq BETWEEN ? AND ? ORDER BY seq LIMIT ?`), ...view.params, whites, whites, sessionId, fromSeq, toSeq, 64)).map((row) => Number(row.chunks) > 0 ? {
|
|
2990
5217
|
seq: Number(row.seq),
|
|
2991
5218
|
streamed: true
|
|
2992
5219
|
} : {
|
|
@@ -3005,7 +5232,7 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
3005
5232
|
label: typeof row.label === "string" ? row.label : void 0
|
|
3006
5233
|
} : {}
|
|
3007
5234
|
});
|
|
3008
|
-
}
|
|
5235
|
+
});
|
|
3009
5236
|
}
|
|
3010
5237
|
/** Sparse page of child state in one fenced read, bounded by the same byte and row caps as a transcript page. */
|
|
3011
5238
|
async readSelectedPage(sessionId, seqs, epoch, options = {}) {
|
|
@@ -3013,11 +5240,12 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
3013
5240
|
const limit = entrySizeLimit(options.limit);
|
|
3014
5241
|
const wanted = options.backward ? seqs.slice(-limit) : seqs.slice(0, limit);
|
|
3015
5242
|
if (!wanted.length) return { items: [] };
|
|
3016
|
-
return this.
|
|
3017
|
-
const head = await this.historyHead(tx, sessionId);
|
|
5243
|
+
return this.readTransaction(async (tx) => {
|
|
5244
|
+
const head = await this.historyHead(tx, sessionId, true);
|
|
3018
5245
|
if (head.epoch !== epoch || head.lastSeq < wanted.at(-1)) throw new SessionConflictError$1(sessionId, wanted.at(-1), head.lastSeq);
|
|
3019
|
-
const tail = `(SELECT length(data) FROM ${this.tables.entryChunks} c WHERE c.session_id=e.
|
|
3020
|
-
const
|
|
5246
|
+
const tail = `(SELECT length(data) FROM ${this.tables.entryChunks} c WHERE c.session_id=e.src_id AND c.seq=e.src_seq AND c.idx=e.chunks-1)`;
|
|
5247
|
+
const view = this.entriesView(await this.viewTables(tx, sessionId), sessionId, Math.min(...wanted) - 1, Math.max(...wanted));
|
|
5248
|
+
const rows = await tx.all(withForkViews([view], `SELECT seq,CASE WHEN chunks=0 THEN ${this.entryByteLength("entry_json")} ELSE (chunks-1)*?+${tail} END bytes FROM ${view.name} e WHERE session_id=? AND seq IN (${wanted.map(() => "?").join(",")}) ORDER BY seq`), ...view.params, SESSION_ENTRY_CHUNK_BYTES, sessionId, ...wanted);
|
|
3021
5249
|
const sizes = new Map(rows.map((row) => [Number(row.seq), row.bytes == null ? void 0 : Number(row.bytes)]));
|
|
3022
5250
|
const plan = selectedPagePlan(sessionId, wanted, head.lastSeq, (seq) => {
|
|
3023
5251
|
const bytes = sizes.get(seq);
|
|
@@ -3031,7 +5259,7 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
3031
5259
|
...plan.oversized
|
|
3032
5260
|
}] };
|
|
3033
5261
|
return { items: await this.readSeqs(tx, sessionId, plan.seqs) };
|
|
3034
|
-
}
|
|
5262
|
+
});
|
|
3035
5263
|
}
|
|
3036
5264
|
/**
|
|
3037
5265
|
* The snapshot entries of the session's resume index, read with the index and nothing else: no entry is read, and an
|
|
@@ -3051,12 +5279,16 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
3051
5279
|
async readEntrySizes(sessionId, startSeq, endSeq, limit) {
|
|
3052
5280
|
this.assertOpen();
|
|
3053
5281
|
validateSessionText("sessionId", sessionId);
|
|
3054
|
-
return this.
|
|
3055
|
-
const head = await this.historyHead(tx, sessionId);
|
|
3056
|
-
const lastChunk = `(SELECT length(data) FROM ${this.tables.entryChunks} c WHERE c.session_id = e.
|
|
3057
|
-
const
|
|
5282
|
+
return this.readTransaction(async (tx) => {
|
|
5283
|
+
const head = await this.historyHead(tx, sessionId, true);
|
|
5284
|
+
const lastChunk = `(SELECT length(data) FROM ${this.tables.entryChunks} c WHERE c.session_id = e.src_id AND c.seq = e.src_seq AND c.idx = e.chunks - 1)`;
|
|
5285
|
+
const tables = await this.viewTables(tx, sessionId);
|
|
5286
|
+
const after = Math.max(1, startSeq) - 1;
|
|
5287
|
+
const view = this.entriesView(tables, sessionId, after, tables.segments === void 0 ? endSeq : Math.min(endSeq, after + entrySizeLimit(limit)));
|
|
5288
|
+
const rows = await tx.all(withForkViews([view], `SELECT seq, CASE WHEN chunks = 0 THEN ${this.entryByteLength("entry_json")} ELSE (chunks - 1) * ? + ${lastChunk} END AS bytes FROM ${view.name} e WHERE session_id = ? AND seq BETWEEN ? AND ? ORDER BY seq LIMIT ?`), ...view.params, SESSION_ENTRY_CHUNK_BYTES, sessionId, startSeq, endSeq, entrySizeLimit(limit));
|
|
3058
5289
|
return {
|
|
3059
|
-
|
|
5290
|
+
lastSeq: head.lastSeq,
|
|
5291
|
+
epoch: head.epoch,
|
|
3060
5292
|
sizes: rows.map((row) => {
|
|
3061
5293
|
if (row.bytes === null) throw new StorageUnavailableError$1(this.descriptor, /* @__PURE__ */ new Error(`Missing final chunk of session entry ${row.seq}`));
|
|
3062
5294
|
return {
|
|
@@ -3065,7 +5297,7 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
3065
5297
|
};
|
|
3066
5298
|
})
|
|
3067
5299
|
};
|
|
3068
|
-
}
|
|
5300
|
+
});
|
|
3069
5301
|
}
|
|
3070
5302
|
/**
|
|
3071
5303
|
* One statement, so one snapshot without a transaction: the session row (its generation, watermark and schema version)
|
|
@@ -3081,29 +5313,39 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
3081
5313
|
const { select, trailingReference, referencePrefix } = options;
|
|
3082
5314
|
const generation = this.generation(sessionId);
|
|
3083
5315
|
const count = entrySizeLimit(limit);
|
|
3084
|
-
const
|
|
5316
|
+
const shared = this.sharedHistorySeen;
|
|
5317
|
+
const plain = shared && this.forkedSessions.get(sessionId) === false;
|
|
5318
|
+
const tables = {
|
|
5319
|
+
segments: shared && !plain ? this.forkTables.forkSegments : void 0,
|
|
5320
|
+
dialect: this.dialect
|
|
5321
|
+
};
|
|
5322
|
+
const scanEnd = tables.segments === void 0 ? endSeq : Math.min(endSeq, Math.max(1, startSeq) - 1 + (select === void 0 ? count : SCAN_SELECT_WINDOW));
|
|
5323
|
+
const view = this.entriesView(tables, sessionId, startSeq - 1, scanEnd, "scan_view");
|
|
5324
|
+
const bytes = (row) => `CASE WHEN ${row}.chunks = 0 THEN ${this.entryByteLength(`${row}.entry_json`)} ELSE (${row}.chunks - 1) * ? + (SELECT length(data) FROM ${this.tables.entryChunks} c WHERE c.session_id = ${row}.src_id AND c.seq = ${row}.src_seq AND c.idx = ${row}.chunks - 1) END`;
|
|
5325
|
+
const forked = this.outsideForkedColumn("id");
|
|
5326
|
+
const forkedNull = forked === "" ? "" : ", NULL";
|
|
3085
5327
|
const head = `SELECT 0 AS seq, NULL AS bytes, NULL AS chunks, header_json AS entry_json, last_seq, revision,
|
|
3086
|
-
${generation.sql} AS epoch, (SELECT schema_version FROM ${this.tables.meta} LIMIT 1) AS schema_version`;
|
|
5328
|
+
${generation.sql} AS epoch, (SELECT schema_version FROM ${this.tables.meta} LIMIT 1) AS schema_version${forked}`;
|
|
3087
5329
|
const filter = (row) => select ? ` AND ${this.selected(row, select)}` : "";
|
|
3088
5330
|
const selectParams = select === void 0 ? [] : this.selectedParams(select);
|
|
3089
5331
|
const json = this.dialect.name === "sqlite" ? "CAST(entry_json AS BLOB)" : "convert_to(entry_json, 'UTF8')";
|
|
3090
5332
|
const prefixLength = Math.max(1, Math.trunc(referencePrefix ?? 1) || 1);
|
|
3091
|
-
const rows = !select && !trailingReference && referencePrefix === void 0 ? await this.database.all(`${head} FROM ${this.tables.sessions} WHERE id = ?
|
|
5333
|
+
const rows = !select && !trailingReference && referencePrefix === void 0 ? await this.database.all(withForkViews([view], `${head} FROM ${this.tables.sessions} WHERE id = ?
|
|
3092
5334
|
UNION ALL
|
|
3093
|
-
SELECT seq, bytes, chunks, CASE WHEN bytes <= ? AND chunks = 0 THEN entry_json END, NULL, NULL, NULL, NULL FROM (
|
|
3094
|
-
SELECT e.seq, e.chunks, e.entry_json, ${bytes("e")} AS bytes FROM ${
|
|
5335
|
+
SELECT seq, bytes, chunks, CASE WHEN bytes <= ? AND chunks = 0 THEN entry_json END, NULL, NULL, NULL, NULL${forkedNull} FROM (
|
|
5336
|
+
SELECT e.seq, e.chunks, e.entry_json, ${bytes("e")} AS bytes FROM ${view.name} e
|
|
3095
5337
|
-- The cut bounds the range itself, so the read stops there, however far the range goes.
|
|
3096
5338
|
WHERE e.session_id = ? AND e.seq BETWEEN ? AND (
|
|
3097
5339
|
SELECT COALESCE(max(CASE WHEN total <= ? THEN seq END), min(seq)) FROM (
|
|
3098
5340
|
SELECT seq, sum(bytes) OVER (ORDER BY seq) AS total FROM (
|
|
3099
|
-
SELECT s.seq, ${bytes("s")} AS bytes FROM ${
|
|
5341
|
+
SELECT s.seq, ${bytes("s")} AS bytes FROM ${view.name} s
|
|
3100
5342
|
WHERE s.session_id = ? AND s.seq BETWEEN ? AND ? ORDER BY s.seq LIMIT ?
|
|
3101
5343
|
) AS sized
|
|
3102
5344
|
) AS run
|
|
3103
5345
|
)
|
|
3104
5346
|
) AS page
|
|
3105
|
-
ORDER BY seq
|
|
3106
|
-
SELECT s.seq, ${bytes("s")} AS bytes FROM ${
|
|
5347
|
+
ORDER BY seq`), ...view.params, ...generation.params, sessionId, SESSION_HISTORY_PAGE_BYTES, SESSION_ENTRY_CHUNK_BYTES, sessionId, startSeq, SESSION_HISTORY_PAGE_BYTES, SESSION_ENTRY_CHUNK_BYTES, sessionId, startSeq, scanEnd, count) : await this.database.all(withForkViews([view], `WITH sized AS MATERIALIZED (
|
|
5348
|
+
SELECT s.seq, ${bytes("s")} AS bytes FROM ${view.name} s
|
|
3107
5349
|
WHERE s.session_id = ? AND s.seq BETWEEN ? AND ?${filter("s")} ORDER BY s.seq LIMIT ?
|
|
3108
5350
|
), cut AS (
|
|
3109
5351
|
SELECT COALESCE(
|
|
@@ -3118,26 +5360,28 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
3118
5360
|
${head}, (SELECT count(*) FROM sized) AS sized, (SELECT max(seq) FROM sized) AS sized_last, NULL AS prefix
|
|
3119
5361
|
FROM ${this.tables.sessions} WHERE id = ?
|
|
3120
5362
|
UNION ALL
|
|
3121
|
-
SELECT seq, bytes, chunks, CASE WHEN bytes <= ? AND chunks = 0 THEN entry_json END, NULL, NULL, NULL, NULL, NULL, NULL,
|
|
5363
|
+
SELECT seq, bytes, chunks, CASE WHEN bytes <= ? AND chunks = 0 THEN entry_json END, NULL, NULL, NULL, NULL${forkedNull}, NULL, NULL,
|
|
3122
5364
|
${referencePrefix === void 0 ? "NULL" : `CASE WHEN bytes > ? THEN CASE WHEN chunks > 0
|
|
3123
|
-
THEN (SELECT substr(c.data, 1, CAST(? AS INTEGER)) FROM ${this.tables.entryChunks} c WHERE c.session_id =
|
|
5365
|
+
THEN (SELECT substr(c.data, 1, CAST(? AS INTEGER)) FROM ${this.tables.entryChunks} c WHERE c.session_id = page.src_id AND c.seq = page.src_seq AND c.idx = 0)
|
|
3124
5366
|
ELSE substr(${json}, 1, CAST(? AS INTEGER)) END END`}
|
|
3125
5367
|
FROM (
|
|
3126
|
-
SELECT e.seq, e.chunks, e.entry_json, ${bytes("e")} AS bytes FROM ${
|
|
5368
|
+
SELECT e.seq, e.chunks, e.entry_json, e.src_id, e.src_seq, ${bytes("e")} AS bytes FROM ${view.name} e
|
|
3127
5369
|
WHERE e.session_id = ? AND e.seq BETWEEN ? AND (SELECT seq FROM cut)${filter("e")}
|
|
3128
5370
|
UNION ALL
|
|
3129
|
-
SELECT e.seq, e.chunks, e.entry_json, ${bytes("e")} AS bytes FROM ${
|
|
5371
|
+
SELECT e.seq, e.chunks, e.entry_json, e.src_id, e.src_seq, ${bytes("e")} AS bytes FROM ${view.name} e
|
|
3130
5372
|
WHERE e.session_id = ? AND e.seq = (SELECT seq FROM tail)
|
|
3131
5373
|
) AS page
|
|
3132
|
-
ORDER BY seq
|
|
5374
|
+
ORDER BY seq`), ...view.params, SESSION_ENTRY_CHUNK_BYTES, sessionId, startSeq, scanEnd, ...selectParams, count, SESSION_HISTORY_PAGE_BYTES, SESSION_HISTORY_PAGE_BYTES, SESSION_HISTORY_PAGE_BYTES, ...generation.params, sessionId, SESSION_HISTORY_PAGE_BYTES, ...referencePrefix === void 0 ? [] : [
|
|
3133
5375
|
SESSION_HISTORY_PAGE_BYTES,
|
|
3134
5376
|
prefixLength,
|
|
3135
|
-
sessionId,
|
|
3136
5377
|
prefixLength
|
|
3137
5378
|
], SESSION_ENTRY_CHUNK_BYTES, sessionId, startSeq, ...selectParams, SESSION_ENTRY_CHUNK_BYTES, sessionId);
|
|
3138
5379
|
const first = rows[0];
|
|
3139
5380
|
if (first === void 0 || Number(first.seq) !== 0) throw new SessionNotFoundError$1(sessionId);
|
|
3140
|
-
assertStorageSchemaVersion("sessions", first.schema_version,
|
|
5381
|
+
assertStorageSchemaVersion("sessions", first.schema_version, 3, SESSION_SCHEMA_VERSION_UNCHUNKED);
|
|
5382
|
+
this.noteSchemaVersion(first.schema_version);
|
|
5383
|
+
this.noteForked(void 0, sessionId, first.forked);
|
|
5384
|
+
if (this.sharedHistorySeen !== shared || plain && Number(first.forked) === 1) return SqlSessionStore.prototype.readScanPage.call(this, sessionId, startSeq, endSeq, epoch, limit, options);
|
|
3141
5385
|
const lastSeq = Number(first.last_seq);
|
|
3142
5386
|
this.noteGeneration(sessionId, first.revision, lastSeq, first.epoch);
|
|
3143
5387
|
if (epoch !== void 0 && first.epoch !== epoch) throw new SessionConflictError$1(sessionId, endSeq, lastSeq);
|
|
@@ -3151,10 +5395,10 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
3151
5395
|
const top = page.at(-1);
|
|
3152
5396
|
if (top === void 0) return {
|
|
3153
5397
|
...read,
|
|
3154
|
-
throughSeq:
|
|
5398
|
+
throughSeq: scanEnd,
|
|
3155
5399
|
items: []
|
|
3156
5400
|
};
|
|
3157
|
-
const throughSeq = first.sized !== void 0 && Number(first.sized) < count && Number(first.sized_last) <= Number(top.seq) ?
|
|
5401
|
+
const throughSeq = first.sized !== void 0 && Number(first.sized) < count && Number(first.sized_last) <= Number(top.seq) ? scanEnd : Number(top.seq);
|
|
3158
5402
|
const prefixes = /* @__PURE__ */ new Map();
|
|
3159
5403
|
const reference = (row) => {
|
|
3160
5404
|
if (row.prefix) prefixes.set(Number(row.seq), row.prefix);
|
|
@@ -3229,15 +5473,24 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
3229
5473
|
const length = Math.min(Math.max(1, Math.trunc(bytes) || 1), SESSION_HISTORY_PAGE_BYTES);
|
|
3230
5474
|
const generation = this.generation(sessionId);
|
|
3231
5475
|
const json = this.dialect.name === "sqlite" ? "CAST(e.entry_json AS BLOB)" : "convert_to(e.entry_json, 'UTF8')";
|
|
3232
|
-
const
|
|
5476
|
+
const shared = this.sharedHistorySeen;
|
|
5477
|
+
const plain = shared && this.forkedSessions.get(sessionId) === false;
|
|
5478
|
+
const view = this.entriesView({
|
|
5479
|
+
segments: shared && !plain ? this.forkTables.forkSegments : void 0,
|
|
5480
|
+
dialect: this.dialect
|
|
5481
|
+
}, sessionId, seq - 1, seq);
|
|
5482
|
+
const row = await this.database.get(withForkViews([view], `SELECT s.last_seq, s.revision, ${generation.sql} AS epoch,
|
|
3233
5483
|
(SELECT schema_version FROM ${this.tables.meta} LIMIT 1) AS schema_version, e.chunks,
|
|
3234
5484
|
CASE WHEN e.chunks > 0
|
|
3235
|
-
THEN (SELECT substr(c.data, CAST(? AS INTEGER), CAST(? AS INTEGER)) FROM ${this.tables.entryChunks} c WHERE c.session_id = e.
|
|
3236
|
-
ELSE substr(${json}, CAST(? AS INTEGER), CAST(? AS INTEGER)) END AS data
|
|
3237
|
-
FROM ${this.tables.sessions} s LEFT JOIN ${
|
|
3238
|
-
WHERE s.id =
|
|
5485
|
+
THEN (SELECT substr(c.data, CAST(? AS INTEGER), CAST(? AS INTEGER)) FROM ${this.tables.entryChunks} c WHERE c.session_id = e.src_id AND c.seq = e.src_seq AND c.idx = ?)
|
|
5486
|
+
ELSE substr(${json}, CAST(? AS INTEGER), CAST(? AS INTEGER)) END AS data${this.outsideForkedColumn("s.id")}
|
|
5487
|
+
FROM ${this.tables.sessions} s LEFT JOIN ${view.name} e ON e.session_id = s.id
|
|
5488
|
+
WHERE s.id = ?`), ...view.params, ...generation.params, offset % SESSION_ENTRY_CHUNK_BYTES + 1, length, Math.floor(offset / SESSION_ENTRY_CHUNK_BYTES), offset + 1, length, sessionId);
|
|
3239
5489
|
if (!row) throw new SessionNotFoundError$1(sessionId);
|
|
3240
|
-
assertStorageSchemaVersion("sessions", row.schema_version,
|
|
5490
|
+
assertStorageSchemaVersion("sessions", row.schema_version, 3, SESSION_SCHEMA_VERSION_UNCHUNKED);
|
|
5491
|
+
this.noteSchemaVersion(row.schema_version);
|
|
5492
|
+
this.noteForked(void 0, sessionId, row.forked);
|
|
5493
|
+
if (this.sharedHistorySeen !== shared || plain && Number(row.forked) === 1) return SqlSessionStore.prototype.readEntryChunk.call(this, reference, offset, bytes);
|
|
3241
5494
|
this.noteGeneration(sessionId, row.revision, Number(row.last_seq), row.epoch);
|
|
3242
5495
|
if (row.epoch !== epoch) throw new SessionConflictError$1(sessionId, seq, Number(row.last_seq));
|
|
3243
5496
|
if (row.chunks === null) throw new StorageUnavailableError$1(this.descriptor, /* @__PURE__ */ new Error(`Missing session entry ${seq}`));
|
|
@@ -3249,7 +5502,7 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
3249
5502
|
validateSessionText("sessionId", sessionId);
|
|
3250
5503
|
validateSessionText("entry.id", entryId);
|
|
3251
5504
|
if (!await this.readHeader(sessionId)) throw new SessionNotFoundError$1(sessionId);
|
|
3252
|
-
return this.seqOfEntry(this.database, sessionId, entryId);
|
|
5505
|
+
return this.seqOfEntry(this.database, void 0, sessionId, entryId);
|
|
3253
5506
|
}
|
|
3254
5507
|
/**
|
|
3255
5508
|
* Earlier entries that may save the same task reference as each candidate (#5593), in one statement on the session
|
|
@@ -3260,12 +5513,21 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
3260
5513
|
this.assertOpen();
|
|
3261
5514
|
validateSessionText("sessionId", sessionId);
|
|
3262
5515
|
const { candidates, afterSeq, limit } = taskReferenceDuplicateQuery(query);
|
|
3263
|
-
return this.
|
|
3264
|
-
const
|
|
5516
|
+
return this.readTransaction(async (tx) => {
|
|
5517
|
+
const tables = await this.viewTables(tx, sessionId);
|
|
5518
|
+
const head = await this.historyHead(tx, sessionId, true);
|
|
3265
5519
|
if (head.epoch !== query.epoch || head.lastSeq < query.throughSeq) throw new SessionConflictError$1(sessionId, query.throughSeq, head.lastSeq);
|
|
3266
5520
|
if (candidates.length === 0) return { seqs: [] };
|
|
3267
5521
|
const t = snapshotIndexTables$1(this.prefix);
|
|
3268
|
-
const
|
|
5522
|
+
const view = !head.forked ? void 0 : forkView(tables, {
|
|
5523
|
+
name: "links_view",
|
|
5524
|
+
table: t.sessionLinks,
|
|
5525
|
+
columns: ["entry_id"],
|
|
5526
|
+
sessionId,
|
|
5527
|
+
after: 0,
|
|
5528
|
+
through: query.throughSeq
|
|
5529
|
+
});
|
|
5530
|
+
const links = view === void 0 ? t.sessionLinks : "links_view";
|
|
3269
5531
|
/**
|
|
3270
5532
|
* For each candidate `c`, the links row `s` at its sequence and then, with `earlier`, the rows `e` before it
|
|
3271
5533
|
* under an ID, each found through an index, never by walking the session. Postgres plans a lateral subquery
|
|
@@ -3290,11 +5552,11 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
3290
5552
|
WHEN c.suffix > 0 AND c.suffix <= length(s.entry_id) AND substr(s.entry_id, length(s.entry_id) - c.suffix + 1, 1) = ':'
|
|
3291
5553
|
THEN substr(s.entry_id, 1, length(s.entry_id) - c.suffix) END`;
|
|
3292
5554
|
const values = candidates.map(() => `(CAST(? AS ${this.dialect.types.int}), CAST(? AS INTEGER), CAST(? AS INTEGER))`);
|
|
3293
|
-
const rows = await tx.all(`WITH c(seq, idx, suffix) AS (VALUES ${values.join(", ")}),
|
|
5555
|
+
const rows = await tx.all(withForkViews(view === void 0 ? [] : [view], `WITH c(seq, idx, suffix) AS (VALUES ${values.join(", ")}),
|
|
3294
5556
|
hits AS (SELECT e.seq AS seq FROM ${rowsOf("s.entry_id")} UNION SELECT e.seq FROM ${rowsOf(other)})
|
|
3295
5557
|
SELECT 0 AS kind, (SELECT CASE WHEN backfilled_through >= watermark THEN 1 ELSE 0 END FROM ${t.sources} WHERE source = 'session-entries') AS seq
|
|
3296
5558
|
UNION ALL SELECT 1, count(*) FROM ${rowsOf()}
|
|
3297
|
-
UNION ALL SELECT 2, page.seq FROM (SELECT seq FROM hits ORDER BY seq LIMIT ?) page
|
|
5559
|
+
UNION ALL SELECT 2, page.seq FROM (SELECT seq FROM hits ORDER BY seq LIMIT ?) page`), ...view?.params ?? [], ...candidates.flat(), ...[
|
|
3298
5560
|
sessionId,
|
|
3299
5561
|
sessionId,
|
|
3300
5562
|
afterSeq,
|
|
@@ -3317,18 +5579,42 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
3317
5579
|
seqs: seqs.slice(0, limit),
|
|
3318
5580
|
nextAfterSeq: seqs[limit - 1]
|
|
3319
5581
|
} : { seqs };
|
|
3320
|
-
}
|
|
5582
|
+
});
|
|
3321
5583
|
}
|
|
3322
5584
|
async readForkWindow(sessionId, entryId, options) {
|
|
3323
5585
|
this.assertOpen();
|
|
3324
5586
|
validateSessionText("sessionId", sessionId);
|
|
3325
5587
|
const { indexedForkWindow, forkMetadata, byteMetadata, locateFork } = await import("../core/storage/session/fork-window.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
|
|
3326
|
-
return this.
|
|
5588
|
+
return this.readTransaction(async (tx) => {
|
|
3327
5589
|
const snapshots = snapshotIndexTables$1(this.prefix);
|
|
3328
|
-
const
|
|
5590
|
+
const shared = await this.viewTables(tx);
|
|
5591
|
+
const headRead = (leafTables) => {
|
|
5592
|
+
const leafViews = [snapshots.sessionLinks, this.tables.entries].map((table, index) => forkView(leafTables, {
|
|
5593
|
+
name: `leaf_${index}`,
|
|
5594
|
+
table,
|
|
5595
|
+
columns: ["entry_id"],
|
|
5596
|
+
sessionId,
|
|
5597
|
+
after: 0,
|
|
5598
|
+
through: FORK_VIEW_END,
|
|
5599
|
+
match: {
|
|
5600
|
+
column: "entry_id",
|
|
5601
|
+
value: entryId
|
|
5602
|
+
}
|
|
5603
|
+
}));
|
|
5604
|
+
return tx.get(withForkViews(leafViews, `SELECT header_json,last_seq,summary_state,revision,CASE WHEN EXISTS (SELECT 1 FROM ${snapshots.sources} WHERE source='session-entries' AND backfilled_through>=watermark) THEN (SELECT max(seq) FROM leaf_0) ELSE (SELECT max(seq) FROM leaf_1) END AS leaf_seq${this.forkedColumn(shared.segments, "s.id")} FROM ${this.tables.sessions} s WHERE s.id=?`), ...forkViewParams(leafViews), sessionId);
|
|
5605
|
+
};
|
|
5606
|
+
const guessPlain = shared.segments !== void 0 && this.forkedSessions.get(sessionId) === false;
|
|
5607
|
+
let row = await headRead(guessPlain ? {
|
|
5608
|
+
...shared,
|
|
5609
|
+
segments: void 0
|
|
5610
|
+
} : shared);
|
|
5611
|
+
if (row && guessPlain && Number(row.forked) === 1) row = await headRead(shared);
|
|
5612
|
+
if (row) this.noteForked(tx, sessionId, row.forked);
|
|
5613
|
+
const tables = await this.viewTables(tx, sessionId);
|
|
3329
5614
|
if (!row) throw new SessionNotFoundError$1(sessionId);
|
|
3330
5615
|
const header = JSON.parse(row.header_json);
|
|
3331
5616
|
const state = JSON.parse(row.summary_state);
|
|
5617
|
+
const generation = state.epoch ?? row.revision;
|
|
3332
5618
|
const count = Number(row.last_seq);
|
|
3333
5619
|
const cached = this.resumeIndexes.get(sessionId);
|
|
3334
5620
|
const ready = windowIndex(state, count) ?? (cached?.revision === row.revision ? cached.index : void 0);
|
|
@@ -3339,23 +5625,31 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
3339
5625
|
if (!seqs.length) return result;
|
|
3340
5626
|
const raw = this.dialect.name === "sqlite" ? "CAST(entry_json AS BLOB)" : "convert_to(entry_json,'UTF8')";
|
|
3341
5627
|
const size = this.dialect.textByteLength("entry_json");
|
|
3342
|
-
const
|
|
5628
|
+
const view = this.entriesView(tables, sessionId, Math.min(...seqs) - 1, Math.max(...seqs));
|
|
5629
|
+
const rows = await tx.all(withForkViews([view], `SELECT seq,chunks,${size} AS bytes,CASE WHEN chunks=0 AND ${size}<=512 THEN entry_json END AS body FROM ${view.name} WHERE session_id=? AND seq IN (${seqs.map(() => "?").join(",")}) ORDER BY seq`), ...view.params, sessionId, ...seqs);
|
|
3343
5630
|
for (const row of rows) {
|
|
3344
5631
|
const seq = Number(row.seq);
|
|
3345
5632
|
if (row.body !== null) result.push(forkMetadata(seq, JSON.parse(row.body)));
|
|
3346
5633
|
else if (Number(row.chunks) > 0) {
|
|
3347
5634
|
const { projectForkMetadata } = await import("../core/storage/session/chunked-resume-projection.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
|
|
3348
|
-
result.push(await projectForkMetadata(seq, this.forkEntryChunks(tx, sessionId, seq, Number(row.chunks))));
|
|
5635
|
+
result.push(await projectForkMetadata(seq, this.forkEntryChunks(tx, tables, sessionId, seq, Number(row.chunks))));
|
|
3349
5636
|
} else result.push(await byteMetadata(seq, Number(row.bytes), async (offset, n) => {
|
|
3350
|
-
const
|
|
5637
|
+
const one = this.entriesView(tables, sessionId, seq - 1, seq);
|
|
5638
|
+
const piece = await tx.get(withForkViews([one], `SELECT substr(${raw},?,?) AS part FROM ${one.name}`), ...one.params, offset + 1, n);
|
|
3351
5639
|
if (!piece) throw new StorageError(`Session ${sessionId} entry ${seq} disappeared during its fork`);
|
|
3352
5640
|
return piece.part;
|
|
3353
5641
|
}));
|
|
3354
5642
|
}
|
|
3355
5643
|
return result;
|
|
3356
5644
|
};
|
|
3357
|
-
const entries = this.tables.entries;
|
|
3358
5645
|
const j = (field) => this.dialect.jsonText("entry_json", field);
|
|
5646
|
+
const scanWindow = (from, through) => {
|
|
5647
|
+
const end = tables.segments === void 0 ? through : Math.min(through, from - 1 + SCAN_SELECT_WINDOW);
|
|
5648
|
+
return {
|
|
5649
|
+
end,
|
|
5650
|
+
view: this.entriesView(tables, sessionId, from - 1, end)
|
|
5651
|
+
};
|
|
5652
|
+
};
|
|
3359
5653
|
const selected = ready ? {
|
|
3360
5654
|
index: ready,
|
|
3361
5655
|
leaf,
|
|
@@ -3363,7 +5657,7 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
3363
5657
|
} : await locateFork({
|
|
3364
5658
|
...foldSessionResume(void 0, []),
|
|
3365
5659
|
seq: count,
|
|
3366
|
-
epoch:
|
|
5660
|
+
epoch: generation,
|
|
3367
5661
|
needsBranchRebuild: true
|
|
3368
5662
|
}, entryId, async (seqs) => {
|
|
3369
5663
|
const pg = this.dialect.name === "postgres";
|
|
@@ -3385,7 +5679,8 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
3385
5679
|
} : { column: "entry_json" }, "data", "completionId")} THEN ${key("data", "completionId")} END`,
|
|
3386
5680
|
key("message", "role")
|
|
3387
5681
|
]);
|
|
3388
|
-
const
|
|
5682
|
+
const view = this.entriesView(tables, sessionId, seqs[0] - 1, seqs.at(-1));
|
|
5683
|
+
const parsed = (await tx.all(withForkViews([view], `WITH projected AS MATERIALIZED (SELECT seq,chunks,CAST(${projection} AS TEXT) AS link FROM ${view.name} ${pg ? `CROSS JOIN LATERAL (SELECT ${postgresJsonb("entry_json")} AS value OFFSET 0) AS parsed` : ""} WHERE session_id=? AND seq BETWEEN ? AND ?) SELECT seq,chunks,CASE WHEN ${this.dialect.textByteLength("link")}<=512 THEN link END AS link FROM projected ORDER BY seq`), ...view.params, sessionId, seqs[0], seqs.at(-1))).map((r) => ({
|
|
3389
5684
|
seq: Number(r.seq),
|
|
3390
5685
|
chunked: Number(r.chunks) > 0,
|
|
3391
5686
|
link: r.link === null ? void 0 : JSON.parse(r.link)
|
|
@@ -3396,7 +5691,8 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
3396
5691
|
const { messageRoleIn } = await import("../core/storage/session/chunked-resume-projection.code.js").catch((error) => __atomicOnDemandFailed(error, "session storage"));
|
|
3397
5692
|
for (let i = 0; i < chunkedMessages.length; i += SEQ_BATCH) {
|
|
3398
5693
|
const batch = chunkedMessages.slice(i, i + SEQ_BATCH);
|
|
3399
|
-
const
|
|
5694
|
+
const view = this.entriesView(tables, sessionId, Math.min(...batch) - 1, Math.max(...batch));
|
|
5695
|
+
const prefixes = await tx.all(withForkViews([view], `SELECT v.seq,substr(c.data,1,${FORK_ROLE_PREFIX_BYTES}) AS prefix FROM ${view.name} v JOIN ${this.tables.entryChunks} c ON c.session_id=v.src_id AND c.seq=v.src_seq AND c.idx=0 WHERE v.seq IN (${batch.map(() => "?").join(",")})`), ...view.params, ...batch);
|
|
3400
5696
|
for (const row of prefixes) roles.set(Number(row.seq), messageRoleIn(row.prefix));
|
|
3401
5697
|
}
|
|
3402
5698
|
}
|
|
@@ -3424,14 +5720,18 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
3424
5720
|
return page;
|
|
3425
5721
|
}, true, SESSION_READ_FETCH.max);
|
|
3426
5722
|
const labelBody = `CASE WHEN chunks=0 AND ${this.dialect.textByteLength("entry_json")}<=512 THEN entry_json END`;
|
|
3427
|
-
return indexedForkWindow(header, selected.index, selected.leaf, (lo, hi) => this.readRows(tx, sessionId,
|
|
5723
|
+
return indexedForkWindow(header, selected.index, selected.leaf, (lo, hi) => this.readRows(tx, sessionId, {
|
|
5724
|
+
from: lo,
|
|
5725
|
+
through: hi
|
|
5726
|
+
}, void 0, generation), (seqs) => this.readSeqs(tx, sessionId, seqs, generation), metadata, async function* (ranges, kinds, types = []) {
|
|
3428
5727
|
const filters = [];
|
|
3429
5728
|
if (types.length) filters.push(`${j("type")} IN (${types.map(() => "?").join(",")})`);
|
|
3430
5729
|
if (kinds.length) filters.push(`(${j("type")}='custom' AND (chunks>0 OR ${j("customType")} IN (${kinds.map(() => "?").join(",")})))`);
|
|
3431
5730
|
for (const [lo, hi] of ranges) for (let seq = lo; seq <= hi;) {
|
|
3432
5731
|
const labels = types.length === 1 && types[0] === "label";
|
|
3433
5732
|
const limit = labels ? SESSION_READ_FETCH.first : SESSION_READ_FETCH.max;
|
|
3434
|
-
const
|
|
5733
|
+
const { end, view } = scanWindow(seq, hi);
|
|
5734
|
+
const rows = await tx.all(withForkViews([view], `SELECT seq,${j("type")} AS kind${labels ? `,${labelBody} AS body` : ""} FROM ${view.name} WHERE session_id=? AND seq BETWEEN ? AND ? AND (${filters.join(" OR ")}) ORDER BY seq LIMIT ${limit}`), ...view.params, sessionId, seq, end, ...types, ...kinds);
|
|
3435
5735
|
const deferred = rows.filter((r) => r.kind === "custom" || r.kind === "label" && !r.body).map((r) => Number(r.seq));
|
|
3436
5736
|
const projected = /* @__PURE__ */ new Map();
|
|
3437
5737
|
for (let i = 0; i < deferred.length; i += SEQ_BATCH) for (const m of await metadata(deferred.slice(i, i + SEQ_BATCH))) projected.set(m.seq, m);
|
|
@@ -3439,18 +5739,21 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
3439
5739
|
type: row.kind,
|
|
3440
5740
|
seq: Number(row.seq)
|
|
3441
5741
|
});
|
|
3442
|
-
if (rows.length < limit)
|
|
3443
|
-
|
|
5742
|
+
if (rows.length < limit) {
|
|
5743
|
+
if (end >= hi) break;
|
|
5744
|
+
seq = end + 1;
|
|
5745
|
+
} else seq = Number(rows.at(-1).seq) + 1;
|
|
3444
5746
|
}
|
|
3445
5747
|
}, {
|
|
3446
5748
|
...selected.extras,
|
|
3447
5749
|
...options
|
|
3448
5750
|
});
|
|
3449
|
-
}
|
|
5751
|
+
});
|
|
3450
5752
|
}
|
|
3451
|
-
async *forkEntryChunks(tx, id, seq, count) {
|
|
5753
|
+
async *forkEntryChunks(tx, tables, id, seq, count) {
|
|
3452
5754
|
for (let i = 0; i < count; i++) {
|
|
3453
|
-
const
|
|
5755
|
+
const read = this.entryChunkRead(tables, id, seq, i);
|
|
5756
|
+
const row = await tx.get(read.sql, ...read.params);
|
|
3454
5757
|
if (!row) throw new StorageError(`Session ${id} entry ${seq} is missing chunk ${i} of ${count}`);
|
|
3455
5758
|
yield row.data;
|
|
3456
5759
|
}
|
|
@@ -3469,44 +5772,60 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
3469
5772
|
this.assertOpen();
|
|
3470
5773
|
validateSessionText("sessionId", sessionId);
|
|
3471
5774
|
if (leafId !== void 0) validateSessionText("entry.id", leafId);
|
|
5775
|
+
if (leafId === void 0 && throughSeq === void 0) try {
|
|
5776
|
+
return await this.readTransaction(async (tx) => {
|
|
5777
|
+
const { header, index } = await this.resumeSource(tx, sessionId);
|
|
5778
|
+
return this.resumeIn(tx, sessionId, header, index, options);
|
|
5779
|
+
}, [this.resumeRow(sessionId)]);
|
|
5780
|
+
} catch (error) {
|
|
5781
|
+
if (!(error instanceof SessionConflictError$1)) throw error;
|
|
5782
|
+
}
|
|
3472
5783
|
for (let attempt = 0; attempt < 3; attempt++) {
|
|
3473
5784
|
const { index, revision } = await this.prepareResume(sessionId, leafId, throughSeq);
|
|
3474
|
-
const resume = await this.
|
|
3475
|
-
const
|
|
5785
|
+
const resume = await this.readTransaction(async (tx) => {
|
|
5786
|
+
const { segments } = await this.viewTables(tx);
|
|
5787
|
+
const head = await tx.get(`SELECT header_json,revision${this.forkedColumn(segments)} FROM ${this.tables.sessions} WHERE id = ?`, sessionId);
|
|
3476
5788
|
if (!head) throw new SessionNotFoundError$1(sessionId);
|
|
5789
|
+
this.noteForked(tx, sessionId, head.forked);
|
|
3477
5790
|
if (revision !== head.revision) return void 0;
|
|
3478
|
-
|
|
3479
|
-
|
|
3480
|
-
const plan = sessionResumePlan(index, index.leafSeq, options?.deferChildRecords);
|
|
3481
|
-
announceHistoryLoad(plan.state.length + plan.branch.reduce((sum, [a, b]) => sum + b - a + 1, 0));
|
|
3482
|
-
const branch = [];
|
|
3483
|
-
for (const [start, end] of plan.branch) branch.push(...await this.readRows(tx, sessionId, "seq >= ? AND seq <= ?", [start, end]));
|
|
3484
|
-
const state = await this.readSeqs(tx, sessionId, plan.state);
|
|
3485
|
-
const leaf = leafSeq <= 0 ? void 0 : await tx.get(`SELECT entry_id FROM ${this.tables.entries} WHERE session_id = ? AND seq = ?`, sessionId, leafSeq);
|
|
3486
|
-
const resume = sessionResumeFrom(index, header, branch, state, leaf?.entry_id ?? null, plan.children);
|
|
3487
|
-
if (resume.compaction) await readEarlierCompletionIntents(index, resume, (seqs) => this.readSeqs(tx, sessionId, seqs));
|
|
3488
|
-
return resume;
|
|
3489
|
-
}, SESSION_TRANSACTION);
|
|
5791
|
+
return this.resumeIn(tx, sessionId, JSON.parse(head.header_json), index, options);
|
|
5792
|
+
});
|
|
3490
5793
|
if (resume !== void 0) return resume;
|
|
3491
5794
|
}
|
|
3492
5795
|
throw new SessionConflictError$1(sessionId, 0, 0);
|
|
3493
5796
|
}
|
|
5797
|
+
/** The resume of `index`, the session's index as of the snapshot of `tx`, with `header`. */
|
|
5798
|
+
async resumeIn(tx, sessionId, header, index, options) {
|
|
5799
|
+
const { leafSeq } = index;
|
|
5800
|
+
const plan = sessionResumePlan(index, index.leafSeq, options?.deferChildRecords);
|
|
5801
|
+
announceHistoryLoad(plan.state.length + plan.branch.reduce((sum, [a, b]) => sum + b - a + 1, 0));
|
|
5802
|
+
const [ranges, state, leaf] = await Promise.all([
|
|
5803
|
+
Promise.all(plan.branch.map(([start, end]) => this.readRows(tx, sessionId, {
|
|
5804
|
+
from: start,
|
|
5805
|
+
through: end
|
|
5806
|
+
}, void 0, index.epoch))),
|
|
5807
|
+
this.readSeqs(tx, sessionId, plan.state, index.epoch),
|
|
5808
|
+
leafSeq <= 0 ? void 0 : this.entryIdAt(tx, sessionId, leafSeq)
|
|
5809
|
+
]);
|
|
5810
|
+
const branch = ranges.flat();
|
|
5811
|
+
const resume = sessionResumeFrom(index, header, branch, state, leaf?.entry_id ?? null, plan.children);
|
|
5812
|
+
if (resume.compaction) await readEarlierCompletionIntents(index, resume, (seqs) => this.readSeqs(tx, sessionId, seqs));
|
|
5813
|
+
return resume;
|
|
5814
|
+
}
|
|
3494
5815
|
async findLatestCompaction(sessionId, leafId) {
|
|
3495
5816
|
this.assertOpen();
|
|
3496
5817
|
validateSessionText("sessionId", sessionId);
|
|
3497
5818
|
if (leafId !== void 0) validateSessionText("entry.id", leafId);
|
|
3498
|
-
await this.
|
|
3499
|
-
const { point } = await this.transaction(async (tx) => {
|
|
5819
|
+
const { point } = await this.withResumeIndex(sessionId, () => this.readTransaction(async (tx) => {
|
|
3500
5820
|
const source = await this.resumeSource(tx, sessionId);
|
|
3501
5821
|
const { index } = source;
|
|
3502
|
-
const leafSeq = leafId === void 0 ? index.leafSeq : await this.seqOfEntry(tx, sessionId, leafId) ?? -1;
|
|
5822
|
+
const leafSeq = leafId === void 0 ? index.leafSeq : await this.seqOfEntry(tx, await this.viewTables(tx, sessionId), sessionId, leafId) ?? -1;
|
|
3503
5823
|
const found = latestCompactionOf(index, leafSeq);
|
|
3504
5824
|
if (found === void 0) return {
|
|
3505
5825
|
point: void 0,
|
|
3506
5826
|
source
|
|
3507
5827
|
};
|
|
3508
|
-
const [boundary] = await this.readSeqs(tx, sessionId, [found.seq]);
|
|
3509
|
-
const leaf = await tx.get(`SELECT entry_id FROM ${this.tables.entries} WHERE session_id = ? AND seq = ?`, sessionId, leafSeq);
|
|
5828
|
+
const [[boundary], leaf] = await Promise.all([this.readSeqs(tx, sessionId, [found.seq]), this.entryIdAt(tx, sessionId, leafSeq)]);
|
|
3510
5829
|
if (boundary === void 0 || leaf === void 0) return {
|
|
3511
5830
|
point: void 0,
|
|
3512
5831
|
source
|
|
@@ -3520,18 +5839,47 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
3520
5839
|
},
|
|
3521
5840
|
source
|
|
3522
5841
|
};
|
|
3523
|
-
},
|
|
5842
|
+
}, [this.resumeRow(sessionId)]));
|
|
3524
5843
|
return point;
|
|
3525
5844
|
}
|
|
5845
|
+
/** The ID of the entry at view seq `seq` of session `sessionId`, read in transaction `tx` (#6560). */
|
|
5846
|
+
async entryIdAt(tx, sessionId, seq) {
|
|
5847
|
+
const view = this.entriesView(await this.viewTables(tx, sessionId), sessionId, seq - 1, seq);
|
|
5848
|
+
return tx.get(withForkViews([view], `SELECT entry_id FROM ${view.name}`), ...view.params);
|
|
5849
|
+
}
|
|
3526
5850
|
/** The JSON of a long entry, from its chunks, one statement each. */
|
|
3527
|
-
async readEntryChunks(tx, sessionId, seq, count) {
|
|
3528
|
-
return Buffer.concat(await this.readRawEntryChunks(tx, sessionId, seq, count)).toString("utf8");
|
|
5851
|
+
async readEntryChunks(tx, tables, sessionId, seq, count) {
|
|
5852
|
+
return Buffer.concat(await this.readRawEntryChunks(tx, tables, sessionId, seq, count)).toString("utf8");
|
|
5853
|
+
}
|
|
5854
|
+
/**
|
|
5855
|
+
* The read of chunk `index` of the entry at view seq `seq` of session `sessionId` (#6560), found through the view in
|
|
5856
|
+
* the statement itself, on the condition `condition` with `params` when given.
|
|
5857
|
+
*/
|
|
5858
|
+
entryChunkRead(tables, sessionId, seq, index, condition) {
|
|
5859
|
+
const view = this.entriesView(tables, sessionId, seq - 1, seq);
|
|
5860
|
+
return {
|
|
5861
|
+
sql: withForkViews([view], `SELECT c.data FROM ${view.name} v JOIN ${this.tables.entryChunks} c
|
|
5862
|
+
ON c.session_id = v.src_id AND c.seq = v.src_seq AND c.idx = ?${condition === void 0 ? "" : ` WHERE ${condition.sql}`}`),
|
|
5863
|
+
params: [
|
|
5864
|
+
...view.params,
|
|
5865
|
+
index,
|
|
5866
|
+
...condition?.params ?? []
|
|
5867
|
+
]
|
|
5868
|
+
};
|
|
3529
5869
|
}
|
|
3530
|
-
|
|
5870
|
+
/**
|
|
5871
|
+
* The chunks of the entry at view seq `seq`: in transaction `tx` with `tables`, or, with `tables` undefined, each
|
|
5872
|
+
* read outside a transaction through `outsideTransaction`.
|
|
5873
|
+
*/
|
|
5874
|
+
async readRawEntryChunks(tx, tables, sessionId, seq, count, signal) {
|
|
3531
5875
|
const chunks = [];
|
|
3532
5876
|
for (let index = 0; index < count; index++) {
|
|
3533
5877
|
signal?.throwIfAborted();
|
|
3534
|
-
const
|
|
5878
|
+
const read = (viewTables) => {
|
|
5879
|
+
const statement = this.entryChunkRead(viewTables, sessionId, seq, index);
|
|
5880
|
+
return tx.get(statement.sql, ...statement.params);
|
|
5881
|
+
};
|
|
5882
|
+
const chunk = tables === void 0 ? await this.outsideTransaction(read, (row) => row !== void 0) : await read(tables);
|
|
3535
5883
|
if (chunk === void 0) throw new StorageError(`Session ${sessionId} entry ${seq} is missing chunk ${index} of ${count}`);
|
|
3536
5884
|
chunks.push(chunk.data);
|
|
3537
5885
|
if (signal !== void 0 && index + 1 < count) await yieldTurn();
|
|
@@ -3540,24 +5888,31 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
3540
5888
|
}
|
|
3541
5889
|
async *entryChunks(sessionId, seq, count, revision) {
|
|
3542
5890
|
for (let index = 0; index < count; index++) {
|
|
3543
|
-
const chunk = await this.
|
|
3544
|
-
|
|
5891
|
+
const chunk = await this.outsideTransaction((tables) => {
|
|
5892
|
+
const statement = this.entryChunkRead(tables, sessionId, seq, index, {
|
|
5893
|
+
sql: `EXISTS (SELECT 1 FROM ${this.tables.sessions} WHERE id = ? AND revision = ?)`,
|
|
5894
|
+
params: [sessionId, revision]
|
|
5895
|
+
});
|
|
5896
|
+
return this.database.get(statement.sql, ...statement.params);
|
|
5897
|
+
}, (row) => row !== void 0);
|
|
3545
5898
|
if (chunk === void 0) throw new StorageError(`Session ${sessionId} entry ${seq} is missing chunk ${index} of ${count}`);
|
|
3546
5899
|
yield chunk.data;
|
|
3547
5900
|
if (index + 1 < count) await yieldTurn();
|
|
3548
5901
|
}
|
|
3549
5902
|
}
|
|
5903
|
+
/** The JSON bytes of the entry stored whole at view seq `seq`, read outside a transaction. */
|
|
3550
5904
|
async readInlineEntryBytes(sessionId, seq) {
|
|
3551
|
-
|
|
3552
|
-
|
|
3553
|
-
|
|
3554
|
-
|
|
3555
|
-
|
|
3556
|
-
|
|
3557
|
-
|
|
3558
|
-
|
|
3559
|
-
|
|
3560
|
-
|
|
5905
|
+
const sqlite = this.dialect.name === "sqlite";
|
|
5906
|
+
const row = await this.outsideTransaction((tables) => {
|
|
5907
|
+
const view = this.entriesView(tables, sessionId, seq - 1, seq);
|
|
5908
|
+
return this.database.get(withForkViews([view], `SELECT ${sqlite ? "CAST(entry_json AS BLOB)" : "entry_json"} AS data FROM ${view.name}`), ...view.params);
|
|
5909
|
+
}, (found) => found !== void 0);
|
|
5910
|
+
if (row === void 0) return [];
|
|
5911
|
+
return [typeof row.data === "string" ? new TextEncoder().encode(row.data) : row.data];
|
|
5912
|
+
}
|
|
5913
|
+
async forWrite(tx, sessionId, options, includeSummaryState = false, forked = false) {
|
|
5914
|
+
const read = this.headRead(sessionId, options, includeSummaryState, forked);
|
|
5915
|
+
const row = await tx.get(read.sql, ...read.params);
|
|
3561
5916
|
if (!row) throw new SessionNotFoundError$1(sessionId);
|
|
3562
5917
|
const state = row.summary_state === void 0 ? void 0 : JSON.parse(String(row.summary_state));
|
|
3563
5918
|
if (row.last_seq !== options.expectSeq || options.epoch !== void 0 && state?.epoch !== options.epoch) throw new SessionConflictError$1(sessionId, options.expectSeq, row.last_seq);
|
|
@@ -3566,24 +5921,56 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
3566
5921
|
state
|
|
3567
5922
|
};
|
|
3568
5923
|
}
|
|
5924
|
+
/**
|
|
5925
|
+
* The read of the session's row that `forWrite` checks a write against; with `forked`, once this store has seen
|
|
5926
|
+
* shared history, it also reads whether the session has fork segments (#6560).
|
|
5927
|
+
*/
|
|
5928
|
+
headRead(sessionId, options, includeSummaryState, forked = false) {
|
|
5929
|
+
return {
|
|
5930
|
+
sql: `SELECT header_json, last_seq${includeSummaryState || options.epoch !== void 0 ? ", summary_state" : ""}${forked ? this.outsideForkedColumn("id") : ""}
|
|
5931
|
+
FROM ${this.tables.sessions} WHERE id = ?`,
|
|
5932
|
+
params: [sessionId]
|
|
5933
|
+
};
|
|
5934
|
+
}
|
|
5935
|
+
/** Whether session `sessionId` has fork segments, read in `tx`, whose database has shared history (#6560). */
|
|
5936
|
+
async hasForkSegments(tx, sessionId) {
|
|
5937
|
+
return await tx.get(`SELECT 1 AS found FROM ${this.forkTables.forkSegments} WHERE session_id = ? LIMIT 1`, sessionId) !== void 0;
|
|
5938
|
+
}
|
|
3569
5939
|
async appendedResume(tx, sessionId, previous, lastSeq, entries) {
|
|
3570
5940
|
if (!isSessionResumeIndex(previous, lastSeq)) return void 0;
|
|
3571
5941
|
const seqs = /* @__PURE__ */ new Map();
|
|
3572
5942
|
for (const id of foreignResumeIds(previous, entries)) {
|
|
3573
|
-
const seq = await this.seqOfEntry(tx, sessionId, id);
|
|
5943
|
+
const seq = await this.seqOfEntry(tx, await this.viewTables(tx), sessionId, id);
|
|
3574
5944
|
if (seq !== void 0) seqs.set(id, seq);
|
|
3575
5945
|
}
|
|
3576
5946
|
return foldSessionResume(previous, entries, (id) => seqs.get(id));
|
|
3577
5947
|
}
|
|
3578
|
-
|
|
3579
|
-
|
|
3580
|
-
|
|
3581
|
-
|
|
3582
|
-
|
|
3583
|
-
|
|
3584
|
-
|
|
3585
|
-
const
|
|
3586
|
-
|
|
5948
|
+
/**
|
|
5949
|
+
* The latest seq of session `sessionId` that holds entry `entryId`, through its view (#6560): in transaction
|
|
5950
|
+
* `executor` with `tables`, or, with `tables` undefined, outside a transaction through `outsideTransaction`. A fork's
|
|
5951
|
+
* inherited entries are linked under the sessions that store them, at their seqs there, which the view renumbers.
|
|
5952
|
+
*/
|
|
5953
|
+
async seqOfEntry(executor, tables, sessionId, entryId) {
|
|
5954
|
+
const index = snapshotIndexTables$1(this.prefix);
|
|
5955
|
+
const source = await executor.get(`SELECT CASE WHEN backfilled_through >= watermark THEN 1 ELSE 0 END AS complete FROM ${index.sources} WHERE source = 'session-entries'`);
|
|
5956
|
+
const table = Number(source?.complete) === 1 ? index.sessionLinks : this.tables.entries;
|
|
5957
|
+
const read = (viewTables, forked = "") => {
|
|
5958
|
+
const view = forkView(viewTables, {
|
|
5959
|
+
name: "linked",
|
|
5960
|
+
table,
|
|
5961
|
+
columns: ["entry_id"],
|
|
5962
|
+
sessionId,
|
|
5963
|
+
after: 0,
|
|
5964
|
+
through: FORK_VIEW_END,
|
|
5965
|
+
match: {
|
|
5966
|
+
column: "entry_id",
|
|
5967
|
+
value: entryId
|
|
5968
|
+
}
|
|
5969
|
+
});
|
|
5970
|
+
return executor.get(withForkViews([view], `SELECT (SELECT seq FROM linked ORDER BY seq DESC LIMIT 1) AS seq${forked}`), ...view.params, ...forked === "" ? [] : [sessionId]);
|
|
5971
|
+
};
|
|
5972
|
+
const row = tables === void 0 ? await this.outsideSessionRead(sessionId, (viewTables) => read(viewTables, this.outsideForkedColumn("?")), (found) => found?.seq != null, (found) => found?.forked) : await read(tables);
|
|
5973
|
+
return row?.seq == null ? void 0 : Number(row.seq);
|
|
3587
5974
|
}
|
|
3588
5975
|
async saveSummary(tx, sessionId, snapshot, previous, appendedResume) {
|
|
3589
5976
|
const { statement, texts, epoch } = this.summaryWrite(sessionId, snapshot, previous, appendedResume);
|
|
@@ -3605,6 +5992,12 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
3605
5992
|
epoch
|
|
3606
5993
|
};
|
|
3607
5994
|
const summary = materializeSessionSummaryMetadata(header, state);
|
|
5995
|
+
const row = {
|
|
5996
|
+
header_json: this.encode(header),
|
|
5997
|
+
summary_state: this.encode(state),
|
|
5998
|
+
revision: newRevision(),
|
|
5999
|
+
last_seq: lastSeq
|
|
6000
|
+
};
|
|
3608
6001
|
return {
|
|
3609
6002
|
statement: {
|
|
3610
6003
|
sql: `INSERT INTO ${this.tables.sessions}
|
|
@@ -3622,7 +6015,7 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
3622
6015
|
sessionId,
|
|
3623
6016
|
header.cwd,
|
|
3624
6017
|
header.createdAt,
|
|
3625
|
-
|
|
6018
|
+
row.header_json,
|
|
3626
6019
|
header.internal ? 1 : 0,
|
|
3627
6020
|
lastSeq,
|
|
3628
6021
|
summary.modifiedAt,
|
|
@@ -3632,30 +6025,82 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
3632
6025
|
summary.hasName ? 1 : 0,
|
|
3633
6026
|
summary.summary === void 0 ? null : this.encode(summary.summary),
|
|
3634
6027
|
summary.summarizedThroughId ?? null,
|
|
3635
|
-
|
|
3636
|
-
|
|
6028
|
+
row.summary_state,
|
|
6029
|
+
row.revision
|
|
3637
6030
|
]
|
|
3638
6031
|
},
|
|
3639
6032
|
texts,
|
|
3640
|
-
epoch
|
|
6033
|
+
epoch,
|
|
6034
|
+
row
|
|
3641
6035
|
};
|
|
3642
6036
|
}
|
|
3643
|
-
async insertEntries(tx, sessionId, entries, lastSeq, texts) {
|
|
3644
|
-
|
|
6037
|
+
async insertEntries(tx, sessionId, entries, lastSeq, texts, versionStep = true, written) {
|
|
6038
|
+
const writes = new SentWrites(tx);
|
|
6039
|
+
await writes.around(() => writes.send(this.entryWrites(sessionId, entries, lastSeq, texts, versionStep, written)));
|
|
6040
|
+
}
|
|
6041
|
+
/**
|
|
6042
|
+
* Notes `written`, the entries a committed write of session `sessionId` stored in generation `epoch`, as stored there
|
|
6043
|
+
* (#6560): a manager keeps the very objects it appended, so a fork of it shares their rows without reading them back.
|
|
6044
|
+
* Only where this store has seen shared history, for which alone the notes count.
|
|
6045
|
+
*/
|
|
6046
|
+
noteWritten(sessionId, epoch, written) {
|
|
6047
|
+
if (!this.sharedHistorySeen) return;
|
|
6048
|
+
const note = storedEntryNotes(this, sessionId, epoch);
|
|
6049
|
+
for (const { entry, seq, json } of written) note(entry, seq, json);
|
|
6050
|
+
}
|
|
6051
|
+
/**
|
|
6052
|
+
* A fork's version step, once every entry of the child is in, as the transaction's last write: the same row order as
|
|
6053
|
+
* an append, which takes the snapshot index's progress rows with its entries inserts and the schema row after them,
|
|
6054
|
+
* so the two never deadlock (#6560). The body makes no call after it.
|
|
6055
|
+
*/
|
|
6056
|
+
async finishFork(tx, child) {
|
|
6057
|
+
const step = this.forkVersionStep(child);
|
|
6058
|
+
if (transactionFinisher(tx)?.([step]) !== true) await tx.run(step.sql, ...step.params);
|
|
6059
|
+
}
|
|
6060
|
+
/** The statement of {@link finishFork}. */
|
|
6061
|
+
forkVersionStep(child) {
|
|
6062
|
+
return {
|
|
6063
|
+
sql: `UPDATE ${this.tables.meta} SET schema_version = ? WHERE schema_version = ? AND EXISTS (SELECT 1 FROM ${this.tables.entries} WHERE session_id = ? AND chunks > 0)`,
|
|
6064
|
+
params: [
|
|
6065
|
+
2,
|
|
6066
|
+
SESSION_SCHEMA_VERSION_UNCHUNKED,
|
|
6067
|
+
child
|
|
6068
|
+
]
|
|
6069
|
+
};
|
|
3645
6070
|
}
|
|
3646
6071
|
/**
|
|
3647
6072
|
* The statements that store `entries` after `lastSeq`, in order, each entry encoded only when its statements are
|
|
3648
|
-
* taken:
|
|
3649
|
-
*
|
|
6073
|
+
* taken: the entries' rows, several to a statement (see {@link rowInserts}), each chunked entry's own row and its
|
|
6074
|
+
* chunks in their place among them, the version step a first chunked entry takes unless `versionStep` is false (a
|
|
6075
|
+
* fork takes it once its last entry is in), then the entries' search texts. With `written`, each entry is added to it
|
|
6076
|
+
* with its seq and its JSON as it is encoded, for {@link noteWritten} once the write commits.
|
|
3650
6077
|
*/
|
|
3651
|
-
*entryWrites(sessionId, entries, lastSeq, texts) {
|
|
6078
|
+
*entryWrites(sessionId, entries, lastSeq, texts, versionStep = true, written) {
|
|
3652
6079
|
let chunked = false;
|
|
6080
|
+
const rows = new RowInserts(this.tables.entries, ENTRY_COLUMNS);
|
|
3653
6081
|
for (const [index, entry] of entries.entries()) {
|
|
3654
6082
|
const seq = lastSeq + index + 1;
|
|
3655
|
-
const
|
|
3656
|
-
|
|
6083
|
+
const json = this.encode(entry);
|
|
6084
|
+
written?.push({
|
|
6085
|
+
entry,
|
|
6086
|
+
seq,
|
|
6087
|
+
json
|
|
6088
|
+
});
|
|
6089
|
+
const stored = storedEntry(entry, json);
|
|
6090
|
+
if (stored.chunks.length === 0) {
|
|
6091
|
+
yield* rows.add([
|
|
6092
|
+
sessionId,
|
|
6093
|
+
seq,
|
|
6094
|
+
entry.id,
|
|
6095
|
+
stored.json,
|
|
6096
|
+
0
|
|
6097
|
+
]);
|
|
6098
|
+
continue;
|
|
6099
|
+
}
|
|
6100
|
+
chunked = true;
|
|
6101
|
+
yield* rows.drain();
|
|
3657
6102
|
yield {
|
|
3658
|
-
sql:
|
|
6103
|
+
sql: rows.sql(1),
|
|
3659
6104
|
params: [
|
|
3660
6105
|
sessionId,
|
|
3661
6106
|
seq,
|
|
@@ -3664,7 +6109,7 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
3664
6109
|
stored.chunks.length
|
|
3665
6110
|
]
|
|
3666
6111
|
};
|
|
3667
|
-
|
|
6112
|
+
yield {
|
|
3668
6113
|
sql: `DELETE FROM ${this.tables.entryChunks} WHERE session_id = ? AND seq = ?`,
|
|
3669
6114
|
params: [sessionId, seq]
|
|
3670
6115
|
};
|
|
@@ -3678,38 +6123,53 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
3678
6123
|
]
|
|
3679
6124
|
};
|
|
3680
6125
|
}
|
|
3681
|
-
|
|
6126
|
+
yield* rows.drain();
|
|
6127
|
+
if (chunked && versionStep) yield {
|
|
3682
6128
|
sql: `UPDATE ${this.tables.meta} SET schema_version = ? WHERE schema_version = ?`,
|
|
3683
6129
|
params: [2, SESSION_SCHEMA_VERSION_UNCHUNKED]
|
|
3684
6130
|
};
|
|
3685
|
-
|
|
3686
|
-
|
|
3687
|
-
|
|
3688
|
-
|
|
3689
|
-
|
|
3690
|
-
|
|
3691
|
-
|
|
3692
|
-
};
|
|
6131
|
+
const searchTexts = new RowInserts(this.tables.searchTexts, TEXT_COLUMNS);
|
|
6132
|
+
for (const { index, text } of texts) yield* searchTexts.add([
|
|
6133
|
+
sessionId,
|
|
6134
|
+
lastSeq + index + 1,
|
|
6135
|
+
this.encode(text)
|
|
6136
|
+
]);
|
|
6137
|
+
yield* searchTexts.drain();
|
|
3693
6138
|
}
|
|
3694
6139
|
/**
|
|
3695
|
-
* Runs the session row's statement, then `entries`' statements, in order
|
|
3696
|
-
* {@link STATEMENT_BATCH_BYTES}, as an ordinary message is, goes
|
|
3697
|
-
*
|
|
3698
|
-
*
|
|
6140
|
+
* Runs the session row's statement, then `entries`' statements, in order, as the transaction's last calls: the body
|
|
6141
|
+
* makes none after them. A write of up to {@link STATEMENT_BATCH_BYTES}, as an ordinary message is, goes with the
|
|
6142
|
+
* commit where the connection is pipelined, or to a connection thread as one batch that waits for it once, or a
|
|
6143
|
+
* request's worth at a time when it has more statements than one takes. A larger one is sent as it is made, without
|
|
6144
|
+
* waiting for each statement's answer, so it never holds more than about that much of them, or sends it, at once.
|
|
3699
6145
|
*/
|
|
3700
6146
|
async writeEntries(tx, summary, entries) {
|
|
3701
6147
|
const batch = [summary];
|
|
3702
6148
|
let bytes = statementBytes(summary);
|
|
3703
6149
|
const pending = entries[Symbol.iterator]();
|
|
6150
|
+
let whole = true;
|
|
3704
6151
|
for (let next = pending.next(); next.done !== true; next = pending.next()) {
|
|
3705
6152
|
batch.push(next.value);
|
|
3706
6153
|
bytes += statementBytes(next.value);
|
|
3707
|
-
if (bytes
|
|
3708
|
-
|
|
3709
|
-
|
|
6154
|
+
if (bytes > STATEMENT_BATCH_BYTES) {
|
|
6155
|
+
whole = false;
|
|
6156
|
+
break;
|
|
6157
|
+
}
|
|
6158
|
+
}
|
|
6159
|
+
if (whole) {
|
|
6160
|
+
if (transactionFinisher(tx)?.(batch) === true) return;
|
|
6161
|
+
if (batch.length <= MAX_SEQUENCE_REQUEST_STATEMENTS) {
|
|
6162
|
+
await statementBatch(tx, batch, []);
|
|
6163
|
+
return;
|
|
6164
|
+
}
|
|
6165
|
+
}
|
|
6166
|
+
const runSequence = whole ? sequenceRunner(tx) : void 0;
|
|
6167
|
+
if (runSequence !== void 0) {
|
|
6168
|
+
await runSequence({ statements: batch });
|
|
3710
6169
|
return;
|
|
3711
6170
|
}
|
|
3712
|
-
|
|
6171
|
+
const writes = new SentWrites(tx);
|
|
6172
|
+
await writes.around(() => writes.send(whole ? batch : withRest(batch, pending)));
|
|
3713
6173
|
}
|
|
3714
6174
|
encode(value) {
|
|
3715
6175
|
try {
|
|
@@ -3720,14 +6180,21 @@ var SqlSessionStore = class SqlSessionStore {
|
|
|
3720
6180
|
}
|
|
3721
6181
|
};
|
|
3722
6182
|
const nativeLoad = registerArchiveLoad(SqlSessionStore.prototype.load);
|
|
6183
|
+
/** The markers among `markers` whose processes `live` judges to be running. */
|
|
6184
|
+
async function liveMarkers(markers, live) {
|
|
6185
|
+
const running = [];
|
|
6186
|
+
for (const marker of markers) if (await live(marker)) running.push(marker);
|
|
6187
|
+
return running;
|
|
6188
|
+
}
|
|
3723
6189
|
/** The running sessions that have a SQL store's sessions open, in a table every host sharing the store reads (#4971). */
|
|
3724
6190
|
var SqlSessionOpenMarkers = class {
|
|
6191
|
+
/** A new table already has the columns the later steps add, so on a new database they find them and alter nothing. */
|
|
3725
6192
|
static async createTable(tx, dialect, table) {
|
|
3726
6193
|
const { int, text } = dialect.types;
|
|
3727
6194
|
await tx.exec(`
|
|
3728
6195
|
CREATE TABLE IF NOT EXISTS ${table} (
|
|
3729
6196
|
session_id ${text} NOT NULL, token ${text} NOT NULL, pid ${int} NOT NULL, host ${text} NOT NULL,
|
|
3730
|
-
heartbeat_at ${int} NOT NULL, PRIMARY KEY(session_id, token)
|
|
6197
|
+
heartbeat_at ${int} NOT NULL, schema_version ${int}, build ${text}, PRIMARY KEY(session_id, token)
|
|
3731
6198
|
)${dialect.tableOptions};
|
|
3732
6199
|
`);
|
|
3733
6200
|
}
|
|
@@ -3740,6 +6207,14 @@ var SqlSessionOpenMarkers = class {
|
|
|
3740
6207
|
const probe = dialect.columnExists(table, "schema_version");
|
|
3741
6208
|
if (await tx.get(probe.sql, ...probe.params) === void 0) await tx.exec(`ALTER TABLE ${table} ADD COLUMN schema_version ${dialect.types.int}`);
|
|
3742
6209
|
}
|
|
6210
|
+
/**
|
|
6211
|
+
* Each marker records the Atomic version of its process, so a command refused while older processes run names the
|
|
6212
|
+
* version each must be upgraded from (#6560). Null for markers of builds before it. Additive.
|
|
6213
|
+
*/
|
|
6214
|
+
static async addBuild(tx, dialect, table) {
|
|
6215
|
+
const probe = dialect.columnExists(table, "build");
|
|
6216
|
+
if (await tx.get(probe.sql, ...probe.params) === void 0) await tx.exec(`ALTER TABLE ${table} ADD COLUMN build ${dialect.types.text}`);
|
|
6217
|
+
}
|
|
3743
6218
|
database;
|
|
3744
6219
|
table;
|
|
3745
6220
|
assertOpen;
|
|
@@ -3751,9 +6226,26 @@ var SqlSessionOpenMarkers = class {
|
|
|
3751
6226
|
async put(sessionId, marker) {
|
|
3752
6227
|
this.assertOpen();
|
|
3753
6228
|
const now = dialectOf(this.database).nowMs;
|
|
3754
|
-
await this.database.run(`INSERT INTO ${this.table} (session_id, token, pid, host, heartbeat_at, schema_version) VALUES (?, ?, ?, ?, ${now}, ?)
|
|
6229
|
+
await this.database.run(`INSERT INTO ${this.table} (session_id, token, pid, host, heartbeat_at, schema_version, build) VALUES (?, ?, ?, ?, ${now}, ?, ?)
|
|
3755
6230
|
ON CONFLICT(session_id, token) DO UPDATE SET pid = excluded.pid, host = excluded.host,
|
|
3756
|
-
heartbeat_at = excluded.heartbeat_at, schema_version = excluded.schema_version`, sessionId, marker.token, marker.pid, marker.host,
|
|
6231
|
+
heartbeat_at = excluded.heartbeat_at, schema_version = excluded.schema_version, build = excluded.build`, sessionId, marker.token, marker.pid, marker.host, 3, marker.build ?? null);
|
|
6232
|
+
}
|
|
6233
|
+
/**
|
|
6234
|
+
* The markers, through `tx`, of processes that do not read sessions schema `version`: those that record an older
|
|
6235
|
+
* one, and those of builds that record none.
|
|
6236
|
+
*/
|
|
6237
|
+
async olderThan(tx, version) {
|
|
6238
|
+
const now = dialectOf(this.database).nowMs;
|
|
6239
|
+
return (await tx.all(`SELECT session_id, token, pid, host, ${now} - heartbeat_at AS age_ms, schema_version, build FROM ${this.table}
|
|
6240
|
+
WHERE schema_version IS NULL OR schema_version < ? ORDER BY host, pid, session_id`, version)).map((row) => ({
|
|
6241
|
+
sessionId: row.session_id,
|
|
6242
|
+
token: row.token,
|
|
6243
|
+
pid: Number(row.pid),
|
|
6244
|
+
host: row.host,
|
|
6245
|
+
ageMs: Number(row.age_ms),
|
|
6246
|
+
schemaVersion: row.schema_version === null ? void 0 : Number(row.schema_version),
|
|
6247
|
+
build: row.build ?? void 0
|
|
6248
|
+
}));
|
|
3757
6249
|
}
|
|
3758
6250
|
async remove(sessionId, token) {
|
|
3759
6251
|
this.assertOpen();
|
|
@@ -10277,16 +12769,16 @@ var ThemeSelectorComponent = class extends FramedSelector {
|
|
|
10277
12769
|
* update without an ESM missing-export error.
|
|
10278
12770
|
*/
|
|
10279
12771
|
const COMPACTOR_COMPRESSION_RATIO = .5;
|
|
10280
|
-
export { CLOUDFLARE_GATEWAY_BINDING_AUTH_SENTINEL, COMPACTOR_COMPRESSION_RATIO, ClassifierDecisionError, GITHUB_COPILOT_ERROR_DIAGNOSTIC, GitHubCopilotAuthenticationError, GitHubCopilotContentFilterError, GitHubCopilotEmptyResponseError, GitHubCopilotError, GitHubCopilotInvalidRequestError, GitHubCopilotModelUnavailableError, GitHubCopilotPromptTooLargeError, GitHubCopilotQuotaExhaustedError, GitHubCopilotRateLimitError, GitHubCopilotServiceUnavailableError, GitHubCopilotStreamEndedEarlyError, GitHubCopilotUnrecognizedResponseError, IntercomBrokerError, IntercomBrokerProtocolError, IntercomBrokerStopTimeoutError, IntercomBrokerSuccessorTimeoutError, IntercomBrokerUpgradeError, IntercomRoutingChangedError, IntercomRoutingError, IntercomRoutingMismatchError, IntercomRoutingTimeoutError, IntercomRoutingUnavailableError, LISTING_FETCH_BATCH, MAX_SESSION_START_TIMEOUT_MS, McpOAuthAuthorizationRequiredError, McpOAuthCredentialStore, McpSignInCancelledError, MemorySnapshotBlobStore, ModelRegistry, OAuthRefreshRejectedError, OAuthTemporarilyUnavailableError, OutputRepairExhaustedError, ProjectGroupError, ProviderRequestFailure, RUNTIME_INTERCOM_GROUP_ENV, SESSION_BLOB_CHUNK_BYTES, SESSION_DOMAIN, SESSION_ENTRY_CHUNK_BYTES, SESSION_PRESENCE_DOMAIN, SESSION_PRESENCE_TABLES, SESSION_READ_FETCH, SESSION_READ_PAGE_CHARS, SESSION_RESUME_REBUILD, SESSION_SCHEMA_VERSION, SESSION_TABLES, SNAPSHOT_COLLECTION_BATCH, SessionConflictError, SessionExistsError, SessionFormatVersionError, SessionIdMismatchError, SessionInvalidTextError, SessionInvalidTimestampError, SessionNotFoundError, SessionStartConfigError, SessionStartError, SessionStartTimeoutError, ShowImagesSelectorComponent, SqlSessionStore, SqlSnapshotBlobStore, TerminalDecisionError, ThemeSelectorComponent, addMcpServerConfigAsync, announceBlueprintBuildWaits, clampThinkingLevel, classifyGitHubCopilotFailure, configuredSecretRedactor, createGatewayBindingFetch, createMcpAuthProvider, createMcpExtension, createTranscript, decide, decisionFailure, describeGitHubCopilotModel, deserializeGitHubCopilotError, findGitHubCopilotError, findSessionStartError, generateStructuredOutput, getGitHubCopilotError, getMcpToolExposure, getSupportedThinkingLevels, githubChecks, githubReviews, interval, isGitHubCopilotAuthenticationError, isGitHubCopilotContentFilterError, isGitHubCopilotEmptyResponseError, isGitHubCopilotError, isGitHubCopilotInvalidRequestError, isGitHubCopilotModelUnavailableError, isGitHubCopilotPromptTooLargeError, isGitHubCopilotQuotaExhaustedError, isGitHubCopilotRateLimitError, isGitHubCopilotServiceUnavailableError, isGitHubCopilotStreamEndedEarlyError, isGitHubCopilotUnrecognizedResponseError, isIntercomBrokerError, isIntercomBrokerProtocolError, isIntercomBrokerStopTimeoutError, isIntercomBrokerSuccessorTimeoutError, isIntercomBrokerUpgradeError, isIntercomRoutingChangedError, isIntercomRoutingError, isIntercomRoutingMismatchError, isIntercomRoutingTimeoutError, isIntercomRoutingUnavailableError, isOAuthRefreshRejectedError, isProjectGroupError, isRetryableGitHubCopilotError, isRetryableIntercomBrokerError, isRetryableIntercomRoutingError, isRetryableSessionStartError, isSessionStartConfigError, isSessionStartError, isSessionStartTimeoutError, loadMcpConfigAsync, logTail, mcpNamespace, mcpRequestTimeoutMs, parseFlattenedKeyPath, parseSessionStartTimeoutMs, publishExtensionContextEffect, publishPullRequest, readRuntimeIntercomGroup, reconstructFlattenedKeys, registerExtensionContextRetirementEffect, rehydrateIntercomBrokerError, rehydrateSessionStartError, removeMcpServerConfigAsync, resolveAutoModel, resolveDecisionModel, resolveMcpServerUrl, restoreRunWorktree, runDecision, runPrintMode, runRestorePreconditionError, runtimeIntercomGroupEnvKey, serializeGitHubCopilotError, serializeIntercomBrokerError, serializeSessionStartError, sessionScopedExtensionState, sessionStartStepText, setUpRestoredRunWorktrees, setUpResumedRunWorktrees, signInMcpServer, snapshotBlobHashes, snapshotIndexTables, unflattenArgumentsWithSchema, updateMcpServerConfig, updateMcpServerConfigAsync, validateMcpServerConfig, webhook, workspaceChangeSet, writeBlueprintBuildEvent };
|
|
12772
|
+
export { CLOUDFLARE_GATEWAY_BINDING_AUTH_SENTINEL, COMPACTOR_COMPRESSION_RATIO, ClassifierDecisionError, GITHUB_COPILOT_ERROR_DIAGNOSTIC, GitHubCopilotAuthenticationError, GitHubCopilotContentFilterError, GitHubCopilotEmptyResponseError, GitHubCopilotError, GitHubCopilotInvalidRequestError, GitHubCopilotModelUnavailableError, GitHubCopilotPromptTooLargeError, GitHubCopilotQuotaExhaustedError, GitHubCopilotRateLimitError, GitHubCopilotServiceUnavailableError, GitHubCopilotStreamEndedEarlyError, GitHubCopilotUnrecognizedResponseError, IntercomBrokerError, IntercomBrokerProtocolError, IntercomBrokerStopTimeoutError, IntercomBrokerSuccessorTimeoutError, IntercomBrokerUpgradeError, IntercomRoutingChangedError, IntercomRoutingError, IntercomRoutingMismatchError, IntercomRoutingTimeoutError, IntercomRoutingUnavailableError, LISTING_FETCH_BATCH, MAX_SESSION_START_TIMEOUT_MS, McpOAuthAuthorizationRequiredError, McpOAuthCredentialStore, McpSignInCancelledError, MemorySnapshotBlobStore, ModelRegistry, OAuthRefreshRejectedError, OAuthTemporarilyUnavailableError, OutputRepairExhaustedError, ProjectGroupError, ProviderRequestFailure, RUNTIME_INTERCOM_GROUP_ENV, SESSION_APPEND_FUNCTION_DOMAIN, SESSION_BLOB_CHUNK_BYTES, SESSION_DOMAIN, SESSION_ENTRY_CHUNK_BYTES, SESSION_FILLFACTOR_DOMAIN, SESSION_PRESENCE_DOMAIN, SESSION_PRESENCE_TABLES, SESSION_READ_FETCH, SESSION_READ_PAGE_CHARS, SESSION_RESUME_REBUILD, SESSION_SCHEMA_VERSION, SESSION_SCHEMA_VERSION_CHUNKED, SESSION_SCHEMA_VERSION_SHARED_HISTORY, SESSION_TABLES, SNAPSHOT_COLLECTION_BATCH, SessionConflictError, SessionExistsError, SessionFormatVersionError, SessionIdMismatchError, SessionInvalidTextError, SessionInvalidTimestampError, SessionNotFoundError, SessionStartConfigError, SessionStartError, SessionStartTimeoutError, ShowImagesSelectorComponent, SqlSessionStore, SqlSnapshotBlobStore, TerminalDecisionError, ThemeSelectorComponent, addMcpServerConfigAsync, announceBlueprintBuildWaits, clampThinkingLevel, classifyGitHubCopilotFailure, configuredSecretRedactor, createGatewayBindingFetch, createMcpAuthProvider, createMcpExtension, createTranscript, decide, decisionFailure, describeGitHubCopilotModel, deserializeGitHubCopilotError, findGitHubCopilotError, findSessionStartError, generateStructuredOutput, getGitHubCopilotError, getMcpToolExposure, getSupportedThinkingLevels, githubChecks, githubReviews, interval, isGitHubCopilotAuthenticationError, isGitHubCopilotContentFilterError, isGitHubCopilotEmptyResponseError, isGitHubCopilotError, isGitHubCopilotInvalidRequestError, isGitHubCopilotModelUnavailableError, isGitHubCopilotPromptTooLargeError, isGitHubCopilotQuotaExhaustedError, isGitHubCopilotRateLimitError, isGitHubCopilotServiceUnavailableError, isGitHubCopilotStreamEndedEarlyError, isGitHubCopilotUnrecognizedResponseError, isIntercomBrokerError, isIntercomBrokerProtocolError, isIntercomBrokerStopTimeoutError, isIntercomBrokerSuccessorTimeoutError, isIntercomBrokerUpgradeError, isIntercomRoutingChangedError, isIntercomRoutingError, isIntercomRoutingMismatchError, isIntercomRoutingTimeoutError, isIntercomRoutingUnavailableError, isOAuthRefreshRejectedError, isProjectGroupError, isRetryableGitHubCopilotError, isRetryableIntercomBrokerError, isRetryableIntercomRoutingError, isRetryableSessionStartError, isSessionStartConfigError, isSessionStartError, isSessionStartTimeoutError, loadMcpConfigAsync, logTail, mcpNamespace, mcpRequestTimeoutMs, parseFlattenedKeyPath, parseSessionStartTimeoutMs, publishExtensionContextEffect, publishPullRequest, readRuntimeIntercomGroup, reconstructFlattenedKeys, registerExtensionContextRetirementEffect, rehydrateIntercomBrokerError, rehydrateSessionStartError, removeMcpServerConfigAsync, resolveAutoModel, resolveDecisionModel, resolveMcpServerUrl, restoreRunWorktree, runDecision, runPrintMode, runRestorePreconditionError, runtimeIntercomGroupEnvKey, serializeGitHubCopilotError, serializeIntercomBrokerError, serializeSessionStartError, sessionScopedExtensionState, sessionStartStepText, setUpRestoredRunWorktrees, setUpResumedRunWorktrees, signInMcpServer, snapshotBlobHashes, snapshotIndexTables, unflattenArgumentsWithSchema, updateMcpServerConfig, updateMcpServerConfigAsync, validateMcpServerConfig, webhook, workspaceChangeSet, writeBlueprintBuildEvent };
|
|
10281
12773
|
|
|
10282
|
-
//# sourceMappingURL=sdk-
|
|
12774
|
+
//# sourceMappingURL=sdk-IQMULKFU.js.map
|
|
10283
12775
|
// __atomicOnDemandFailed: written by the build (scripts/in-place-update-gate.mjs). An import of this release's code on
|
|
10284
12776
|
// demand that fails in a process an in-place update left running says to restart.
|
|
10285
12777
|
function __atomicOnDemandFailed(error, feature) {
|
|
10286
12778
|
return (async () => {
|
|
10287
12779
|
const root = new URL("../", import.meta.url);
|
|
10288
12780
|
const releases = (globalThis[Symbol.for("atomic.in-place-update-release.v1")] ??= new Map());
|
|
10289
|
-
const key = `${root.href}#0.10.
|
|
12781
|
+
const key = `${root.href}#0.10.11-alpha.2`;
|
|
10290
12782
|
let release = releases.get(key);
|
|
10291
12783
|
if (release === undefined) {
|
|
10292
12784
|
const current = (async () => {
|
|
@@ -10314,7 +12806,7 @@ function __atomicOnDemandFailed(error, feature) {
|
|
|
10314
12806
|
} catch {
|
|
10315
12807
|
// No installation to read, as in a bundle of the package: the release the process runs decides.
|
|
10316
12808
|
}
|
|
10317
|
-
const updatedTo = typeof installed === "string" && installed !== "0.10.
|
|
12809
|
+
const updatedTo = typeof installed === "string" && installed !== "0.10.11-alpha.2" ? installed : running !== undefined && running.version !== "0.10.11-alpha.2" ? "0.10.11-alpha.2" : undefined;
|
|
10318
12810
|
if (updatedTo === undefined) throw error;
|
|
10319
12811
|
const application = typeof running?.name === "string" ? running.name : "atomic";
|
|
10320
12812
|
const restart = new Error(`${application} was updated to ${updatedTo} while this session was running; restart it to keep using ${feature}.`, {
|