@crazx/dsh-session-persistence 0.1.1-rc.2.zw.1 → 0.1.2-alpha.3.zw.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/README.i18n.yaml +2 -2
- package/README.md +105 -43
- package/README.zh.md +111 -49
- package/lib/index.js +150 -9
- package/lib/types/coordinator.d.ts +19 -5
- package/lib/types/errors.d.ts +9 -0
- package/lib/types/index.d.ts +41 -7
- package/lib/types/preparations.d.ts +14 -0
- package/package.json +15 -12
package/README.i18n.yaml
CHANGED
|
@@ -2,5 +2,5 @@
|
|
|
2
2
|
# side as of the last confirmed-consistent state. Both languages carry equal authority;
|
|
3
3
|
# after editing either side, bring the other along and re-record with:
|
|
4
4
|
# pnpm run verify-translation-pairing --write packages/session/session-persistence/README.md
|
|
5
|
-
README.md:
|
|
6
|
-
README.zh.md:
|
|
5
|
+
README.md: ae44ec5b7603f4b36b0f32f040cf9d685b7c08e9
|
|
6
|
+
README.zh.md: 44112d6aad80b39e169561cce509e2012722f5e7
|
package/README.md
CHANGED
|
@@ -1,74 +1,121 @@
|
|
|
1
|
+
---
|
|
2
|
+
description: "The durable session-storage seam for users and maintainers choosing a persistence backend, resuming sessions, or building a backend against the shared service contract."
|
|
3
|
+
kind: "package-reference"
|
|
4
|
+
---
|
|
5
|
+
|
|
1
6
|
# @deepseek-ai/dsh-session-persistence
|
|
2
7
|
|
|
3
8
|
English | [中文](README.zh.md)
|
|
4
9
|
|
|
5
|
-
|
|
10
|
+
## Summary
|
|
6
11
|
|
|
7
|
-
|
|
12
|
+
`dsh-session-persistence` stores a session's event log durably, reloads it on resume, and lists stored sessions through the backend-neutral `ctx.sessionPersistence` service. The persisted unit is the existing `SessionEvent` log — there is no parallel stored message type — and non-replayable metadata (format version, working directory, lineage, seed boundary) travels separately as `SessionHeader`. A backend owns its storage, while the service owns append-only logs, contiguous sequence numbers, crash recovery that preserves an interrupted turn instead of truncating it, and durable writes that resolve only after the batch is safe. The shipped JSONL provider implements this service with one artifact per Session; third-party providers may implement the same contract without changing the loop or model.
|
|
8
13
|
|
|
9
|
-
##
|
|
14
|
+
## Table of Contents
|
|
10
15
|
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
16
|
+
- [Use this package](#use-this-package)
|
|
17
|
+
- [Understand the implementation](#understand-the-implementation)
|
|
18
|
+
- [Further Exploration](#further-exploration)
|
|
19
|
+
- [Model Experience](#model-experience)
|
|
20
|
+
- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work)
|
|
21
|
+
- [Dev Note](#dev-note)
|
|
22
|
+
|
|
23
|
+
-----
|
|
24
|
+
|
|
25
|
+
<a id="use-this-package"></a>
|
|
26
|
+
## Use this package
|
|
27
|
+
|
|
28
|
+
Mount one persistence backend to make sessions durable. The backend registers itself as `ctx.sessionPersistence`; nothing else in the composition changes — the loop, resume, and replay all call the same service.
|
|
29
|
+
|
|
30
|
+
### Choosing a backend
|
|
31
|
+
|
|
32
|
+
The seam ships the [JSONL](../session-persistence-jsonl/README.md) backend. It stores one append-only `.jsonl.zstd` artifact per Session and returns its absolute path from `locate(meta)`. A third-party backend may implement the service directly; the [backend contract](#understand-the-implementation) below is what it must honor.
|
|
33
|
+
|
|
34
|
+
### What the service provides
|
|
35
|
+
|
|
36
|
+
With a backend mounted, you can store a session's events durably, reload the stored log, and list what is stored:
|
|
37
|
+
|
|
38
|
+
```text
|
|
39
|
+
await ctx.sessionPersistence.create(meta) // register a session
|
|
40
|
+
await ctx.sessionPersistence.ensureMaterialized(session) // persist an empty resumable session
|
|
41
|
+
await ctx.sessionPersistence.append(id, events) // durably persist a batch
|
|
42
|
+
const { meta, events } = await ctx.sessionPersistence.load(id) // reload on resume
|
|
43
|
+
const headers = await ctx.sessionPersistence.list() // every stored session
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
`append` resolves only after the batch is durable, so a resolved write survives an OS crash or power loss. Ordinary `create` remains lazy; a lifecycle frontend calls `ensureMaterialized` only when an empty session must itself appear in durable listing without inventing an event. `load` returns an immutable balanced log and commits any needed crash recovery; `inspect` reads the same view without committing recovery. Consumers that resume from a watermark can read only the events at or past a sequence number, and a session's artifact location (`locate`) resolves without filesystem I/O.
|
|
47
|
+
|
|
48
|
+
### Resuming and crash recovery
|
|
49
|
+
|
|
50
|
+
Resume is `load` plus session preparation: the stored log comes back with its header lineage intact, so a resumed agent sees the same history and composition. A session that crashed mid-turn reloads with its interrupted final turn preserved and balanced: `load` appends synthetic `tool/result` and `turn/end {interrupted}` closers for unanswered calls instead of dropping the events — a single turn can be large, and those events were durably written before the crash. Only a never-fully-written torn tail fragment is discarded.
|
|
51
|
+
|
|
52
|
+
### Failures and recovery
|
|
24
53
|
|
|
25
|
-
|
|
54
|
+
A stored log the current build cannot faithfully interpret is refused with a direction-aware error, never misread. `SESSION_FORMAT_VERSION` remains v0 and this build provides no format-migration path; a newer version instructs the operator to upgrade the harness. The decoder accepts only the bounded same-version record variants named below. An event type unknown to this build refuses unless its envelope marks it `ignorable`, and committed-prefix corruption rejects as `SessionPersistenceCorruptionError`. A `load` on an id still bound to a live session first flushes its snapshot and rejects while its turn is open; a cold load applies recovery.
|
|
26
55
|
|
|
27
|
-
|
|
28
|
-
- **Contiguous seq.** `load` rejects a `seq` gap/parse error in the MIDDLE of the log; `append`'s first `seq` must equal the stored next-seq.
|
|
29
|
-
- **JSON-serializable data.** `append` materializes each direct/replay batch through the shared one-pass lossless-JSON boundary. Live `Session` events are already deep-frozen, but the write coordinator still copies each event into a persistence-owned buffer.
|
|
30
|
-
- **Durability.** `append` returns only once the batch is durable.
|
|
56
|
+
-----
|
|
31
57
|
|
|
32
|
-
|
|
58
|
+
<a id="understand-the-implementation"></a>
|
|
59
|
+
## Understand the implementation
|
|
33
60
|
|
|
34
|
-
|
|
61
|
+
<details>
|
|
62
|
+
<summary>Implementation internals — click to expand</summary>
|
|
35
63
|
|
|
36
|
-
|
|
64
|
+
This section explains how the seam realizes durable storage and how backends plug in; the observable contract is covered in [Use this package](#use-this-package) and the generated [Cordis API](../../../docs/subsystems/persistence.md#cordis-surface).
|
|
37
65
|
|
|
38
|
-
|
|
66
|
+
### Design concept
|
|
39
67
|
|
|
40
|
-
|
|
68
|
+
The package is the Service Definition of a capability seam with two halves. The abstract `SessionPersistence` service is the public contract; a `PersistenceCoordinator` provides backend-neutral orchestration for buffering, serialization, materialization, repair, adoption, and quiescent disposal. The JSONL provider implements the small durable primitives for stored reads, append, repair, and listing; a third-party provider may reuse the same coordinator or implement the service directly.
|
|
41
69
|
|
|
42
|
-
|
|
70
|
+
### The invariants every backend honors
|
|
43
71
|
|
|
44
|
-
|
|
72
|
+
- **Append-only; a crashed turn is closed, not truncated.** Flushed events are never rewritten; `load` preserves an interrupted final turn and durably appends synthetic closers.
|
|
73
|
+
- **Contiguous `seq`.** A gap in the middle of the log rejects; `append`'s first `seq` must equal the stored next-seq.
|
|
74
|
+
- **Lossless JSON data.** Batches pass the shared one-pass lossless-JSON boundary; non-serializable payloads reject at the append site.
|
|
75
|
+
- **Durability.** `append` resolves only once the batch is durable.
|
|
45
76
|
|
|
46
|
-
|
|
77
|
+
### Source map
|
|
47
78
|
|
|
48
|
-
|
|
|
79
|
+
| File | Role |
|
|
49
80
|
|---|---|
|
|
50
|
-
| `
|
|
51
|
-
| `
|
|
52
|
-
| `
|
|
53
|
-
| `
|
|
54
|
-
| `
|
|
55
|
-
| `
|
|
56
|
-
| `list(signal?)` | List all stored metadata, observing optional cancellation. |
|
|
57
|
-
| `close?()` | Optional lifecycle teardown (e.g. close a db handle), awaited after the dispose drain. |
|
|
81
|
+
| [`src/index.ts`](src/index.ts) | Plugin entry: the abstract `SessionPersistence` service and re-exported metadata types |
|
|
82
|
+
| [`src/coordinator.ts`](src/coordinator.ts) | Shared write orchestration: batching, serialization, repair, adoption, disposal, format refusal |
|
|
83
|
+
| [`src/write-behind.ts`](src/write-behind.ts) | The per-session bounded write controller and flush barrier |
|
|
84
|
+
| [`src/preparations.ts`](src/preparations.ts) | Bounded retention of unpublished Session preparations for resume reuse |
|
|
85
|
+
| [`src/revision.ts`](src/revision.ts) | The branded opaque revision token |
|
|
86
|
+
| [`src/invariant.ts`](src/invariant.ts) | Invariant companion (no runtime invariant; the coordinator asserts stored/live identity and cwd) |
|
|
58
87
|
|
|
59
|
-
The
|
|
88
|
+
### The write path at a glance
|
|
60
89
|
|
|
61
|
-
|
|
90
|
+
Each `session/event` copies the event into its session's controller. The first pending event starts a fixed batching window; later events join without resetting its deadline. Expiry starts one durable append; events admitted during that write form a separately bounded follow-up batch. `session/flush` cancels the wait and drains through quiescence, so the loop uses it as the ordering and error-observation checkpoint before the next turn. A rejected background write retains its events and pauses automatic retry; a new event starts a fresh window, while explicit flush or backend teardown retries immediately.
|
|
62
91
|
|
|
63
|
-
|
|
92
|
+
### Stored-record compatibility
|
|
64
93
|
|
|
94
|
+
Backend reads normalize only the explicitly supported v0 record variants before validating current records. The coordinator uses the same normalized view for `load`, `inspect`, `readFrom`, ownerless-state claims, and HMR adoption. Reads do not rewrite stored records, and later appends use current v0. The [pre-identity message](../../../.agents/notes/implemented/bug-fix/2026-07-28-load-pre-identity-session-messages.md) and [pre-react-loop session](../../../.agents/notes/implemented/bug-fix/2026-08-04-load-pre-react-loop-sessions.md) notes own these bounded exceptions; they are not a general format-migration promise.
|
|
95
|
+
|
|
96
|
+
</details>
|
|
97
|
+
-----
|
|
98
|
+
|
|
99
|
+
<a id="further-exploration"></a>
|
|
100
|
+
## Further Exploration
|
|
101
|
+
|
|
102
|
+
Read these pages when the package-level contract is not enough. They move from the shared durability model to the shipped backends and the decision evidence.
|
|
103
|
+
|
|
104
|
+
- [Session persistence subsystem](../../../docs/subsystems/persistence.md) — the full service contract, flush checkpoint, crash recovery, and generated Cordis API.
|
|
105
|
+
- [JSONL persistence backend](../session-persistence-jsonl/README.md) — the shipped per-session-file backend.
|
|
106
|
+
- [Session checkpoint policy](../session-checkpoint-policy/README.md) — the plugin that flushes through this service at semantic boundaries.
|
|
107
|
+
- [Session package map](../README.md) — adjacent persistence, projection, title, and telemetry packages.
|
|
108
|
+
|
|
109
|
+
-----
|
|
110
|
+
|
|
111
|
+
<a id="model-experience"></a>
|
|
65
112
|
## Model Experience
|
|
66
113
|
|
|
67
114
|
### Resumed conversation history
|
|
68
115
|
|
|
69
116
|
#### What the model sees
|
|
70
117
|
|
|
71
|
-
|
|
118
|
+
The seam adds no prompt or schema. Resume restores stored surface events as message history; stored request headers reconstruct earlier calls, while the new loop composes the current system prompt, tools, and session prefix for its next request. Crash repair marks an assistant request without a durable call as `TOOL_NOT_STARTED`; a durable call without a result becomes `TOOL_OUTCOME_UNKNOWN`, whose text lets the model retry read-only or idempotent work but directs it to verify side effects or ask the user instead of retrying blindly.
|
|
72
119
|
|
|
73
120
|
#### Token effect
|
|
74
121
|
|
|
@@ -80,7 +127,22 @@ Persistence does not mutate live request prefixes. A resumed loop can reuse prov
|
|
|
80
127
|
|
|
81
128
|
## Known Limitations and Deferred Work
|
|
82
129
|
|
|
130
|
+
<a id="known-limitations-and-deferred-work"></a>
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
These limits define where the seam's guarantees stop. They are current package constraints, not a task backlog.
|
|
134
|
+
|
|
83
135
|
- **No deletion or retention API** — pruning stored sessions is out-of-band backend maintenance.
|
|
84
136
|
- **`list()` is unpaginated and unfiltered** — it returns every stored session's header; fine for local stores, unindexed at scale.
|
|
85
|
-
- **
|
|
137
|
+
- **Synthetic closers are the only crash story** — a backend must synthesize `tool/result`/`step/end`/`turn/end` closers on load; there is no partial-turn resume that continues an interrupted turn instead of closing it.
|
|
86
138
|
- **Cross-process writer exclusion is batch-granular** — the append-time revision check refuses a log another process advanced between batches, but two writers racing inside one batch can still interleave; full exclusion would require a cross-process lock.
|
|
139
|
+
|
|
140
|
+
<a id="dev-note"></a>
|
|
141
|
+
### Dev Note
|
|
142
|
+
|
|
143
|
+
<details>
|
|
144
|
+
<summary>Working context for maintainers — click to expand</summary>
|
|
145
|
+
|
|
146
|
+
None.
|
|
147
|
+
|
|
148
|
+
</details>
|
package/README.zh.md
CHANGED
|
@@ -1,74 +1,121 @@
|
|
|
1
|
+
---
|
|
2
|
+
description: "面向用户与维护者的持久会话存储 seam 说明,用于选择持久化后端、恢复会话,或按共享服务约定构建后端。"
|
|
3
|
+
kind: "package-reference"
|
|
4
|
+
---
|
|
5
|
+
|
|
1
6
|
# @deepseek-ai/dsh-session-persistence
|
|
2
7
|
|
|
3
8
|
[English](README.md) | 中文
|
|
4
9
|
|
|
5
|
-
|
|
10
|
+
## 概述
|
|
6
11
|
|
|
7
|
-
|
|
12
|
+
`dsh-session-persistence` 通过后端无关的 `ctx.sessionPersistence` 服务持久存储会话的事件日志、在恢复时重新加载并列出已存储会话。持久化单元就是现有 `SessionEvent` 日志——不存在另一套并行的存储消息类型——不可回放的元数据(格式版本、工作目录、血缘、种子边界)作为 `SessionHeader` 单独传输。后端拥有自己的存储,而服务拥有仅追加日志、连续序列号、保留中断轮次而非截断的崩溃恢复,以及只在批次安全后才返回的持久写入。随产品交付的 JSONL provider 用每个 Session 一份产物实现该服务;第三方 provider 可以实现同一约定,而不改变 loop 或模型。
|
|
8
13
|
|
|
9
|
-
##
|
|
14
|
+
## 目录
|
|
10
15
|
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
16
|
+
- [使用本包](#use-this-package)
|
|
17
|
+
- [理解实现](#understand-the-implementation)
|
|
18
|
+
- [进一步探索](#further-exploration)
|
|
19
|
+
- [模型体验](#model-experience)
|
|
20
|
+
- [已知限制与延期工作](#known-limitations-and-deferred-work)
|
|
21
|
+
- [开发备注](#dev-note)
|
|
22
|
+
|
|
23
|
+
-----
|
|
24
|
+
|
|
25
|
+
<a id="use-this-package"></a>
|
|
26
|
+
## 使用本包
|
|
27
|
+
|
|
28
|
+
挂载一个持久化后端即可让会话持久化。后端把自己注册为 `ctx.sessionPersistence`;组合中的其他部分不变——loop、恢复与回放调用的是同一个服务。
|
|
29
|
+
|
|
30
|
+
### 选择后端
|
|
31
|
+
|
|
32
|
+
seam 随产品交付 [JSONL](../session-persistence-jsonl/README.zh.md) 后端。它把每个 Session 存为一份仅追加 `.jsonl.zstd` 产物,并由 `locate(meta)` 返回绝对路径。第三方后端可以直接实现该服务;必须遵守的[后端约定](#understand-the-implementation)见下文。
|
|
33
|
+
|
|
34
|
+
### 服务提供什么
|
|
35
|
+
|
|
36
|
+
挂载后端后,你可以持久存储会话事件、重新加载已存储日志并列出已存储内容:
|
|
37
|
+
|
|
38
|
+
```text
|
|
39
|
+
await ctx.sessionPersistence.create(meta) // register a session
|
|
40
|
+
await ctx.sessionPersistence.ensureMaterialized(session) // persist an empty resumable session
|
|
41
|
+
await ctx.sessionPersistence.append(id, events) // durably persist a batch
|
|
42
|
+
const { meta, events } = await ctx.sessionPersistence.load(id) // reload on resume
|
|
43
|
+
const headers = await ctx.sessionPersistence.list() // every stored session
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
`append` 只在批次持久后返回,因此成功返回的写入在操作系统崩溃或断电后依然存在。普通 `create` 保持惰性;只有当空会话本身必须出现在持久列表中时,生命周期前端才调用 `ensureMaterialized`,且不会虚构事件。`load` 返回不可变的平衡日志并提交任何需要的崩溃恢复;`inspect` 读取同一视图但不提交恢复。从水位恢复的消费方可以只读取该序列号及之后的已存储事件,会话的产物位置(`locate`)不经文件系统 I/O 即可解析。
|
|
47
|
+
|
|
48
|
+
### 恢复与崩溃恢复
|
|
49
|
+
|
|
50
|
+
恢复就是 `load` 加会话准备:存储日志连同其头部血缘一起返回,因此恢复后的 agent(智能体)看到相同的历史与组装。中途崩溃的会话重新加载时,其被中断的最终轮次会保留并保持平衡:`load` 为未获回答的调用追加合成 `tool/result` 与 `turn/end {interrupted}` closer,而不是丢弃事件——单个轮次可能很大,而这些事件在崩溃前已持久写入。只有从未完整写入的撕裂尾部碎片会被丢弃。
|
|
51
|
+
|
|
52
|
+
### 失败与恢复
|
|
24
53
|
|
|
25
|
-
|
|
54
|
+
当前构建无法忠实解读的存储日志会以方向感知的错误被拒绝,绝不错读。`SESSION_FORMAT_VERSION` 保持 v0,本构建不提供格式迁移路径;更高版本会要求操作者升级 harness。解码器只接受下文点名的有限同版本记录变体。本构建不认识的事件类型会被拒绝,除非其信封标记为 `ignorable`;已提交前缀中的损坏以 `SessionPersistenceCorruptionError` 拒绝。对仍绑定到活动会话的 id 执行 `load`,会先刷新其快照并在轮次开放时拒绝;冷 load 应用恢复。
|
|
26
55
|
|
|
27
|
-
|
|
28
|
-
- **连续 seq。**`load` 拒绝日志中间的 `seq` 缺口/解析错误;`append` 的第一个 `seq` 必须等于已存储 next-seq。
|
|
29
|
-
- **JSON 可序列化数据。**`append` 通过共享单遍无损 JSON 边界实体化每个直接/回放批次。活动 `Session` 事件已深度冻结,但写入协调器仍将每个事件复制到持久化自有缓冲区。
|
|
30
|
-
- **持久性。**`append` 只在批次持久后返回。
|
|
56
|
+
-----
|
|
31
57
|
|
|
32
|
-
|
|
58
|
+
<a id="understand-the-implementation"></a>
|
|
59
|
+
## 理解实现
|
|
33
60
|
|
|
34
|
-
|
|
61
|
+
<details>
|
|
62
|
+
<summary>实现细节——点击展开</summary>
|
|
35
63
|
|
|
36
|
-
|
|
64
|
+
本节说明 seam 如何实现持久存储以及后端如何接入;可观察约定见[使用本包](#use-this-package)与生成的 [Cordis API](../../../docs/subsystems/persistence.zh.md#cordis-surface)。
|
|
37
65
|
|
|
38
|
-
|
|
66
|
+
### 设计理念
|
|
39
67
|
|
|
40
|
-
|
|
68
|
+
本包是能力 seam 的 Service Definition,分两半。抽象的 `SessionPersistence` 服务是公开约定;`PersistenceCoordinator` 为缓冲、串行化、物化、修复、接管与完全停稳的 dispose 提供后端无关编排。JSONL provider 实现存储读取、追加、修复与列出所需的小型持久原语;第三方 provider 可以复用同一 coordinator,也可以直接实现该服务。
|
|
41
69
|
|
|
42
|
-
|
|
70
|
+
### 每个后端必须遵守的不变量
|
|
43
71
|
|
|
44
|
-
|
|
72
|
+
- **仅追加;崩溃轮次会被关闭,而非截断。** 已 flush 事件绝不重写;`load` 保留中断的最终轮次并持久追加合成 closer。
|
|
73
|
+
- **连续 `seq`。** 日志中间的缺口会被拒绝;`append` 的第一个 `seq` 必须等于已存储 next-seq。
|
|
74
|
+
- **无损 JSON 数据。** 批次经过共享单遍无损 JSON 边界;无法序列化的载荷在 append 处被拒绝。
|
|
75
|
+
- **持久性。** `append` 只在批次持久后返回。
|
|
45
76
|
|
|
46
|
-
|
|
77
|
+
### 源码地图
|
|
47
78
|
|
|
48
|
-
|
|
|
79
|
+
| 文件 | 职责 |
|
|
49
80
|
|---|---|
|
|
50
|
-
| `
|
|
51
|
-
| `
|
|
52
|
-
| `
|
|
53
|
-
| `
|
|
54
|
-
| `
|
|
55
|
-
| `
|
|
56
|
-
| `list(signal?)` | 列出全部已存储元数据,并遵循可选的取消信号。 |
|
|
57
|
-
| `close?()` | 可选生命周期拆卸(例如关闭 db 句柄),在 dispose drain 后等待其完成。 |
|
|
81
|
+
| [`src/index.ts`](src/index.ts) | 插件入口:抽象 `SessionPersistence` 服务与重新导出的元数据类型 |
|
|
82
|
+
| [`src/coordinator.ts`](src/coordinator.ts) | 共享写入编排:批处理、串行化、修复、接管、dispose、格式拒绝 |
|
|
83
|
+
| [`src/write-behind.ts`](src/write-behind.ts) | 每会话有界写入控制器与 flush 屏障 |
|
|
84
|
+
| [`src/preparations.ts`](src/preparations.ts) | 为恢复复用而有界保留的未发布 Session 准备结果 |
|
|
85
|
+
| [`src/revision.ts`](src/revision.ts) | 带品牌类型的不透明修订值 token |
|
|
86
|
+
| [`src/invariant.ts`](src/invariant.ts) | 不变式伴生插件(无运行时不变式;协调器断言存储/活动身份与 cwd) |
|
|
58
87
|
|
|
59
|
-
|
|
88
|
+
### 写入路径概览
|
|
60
89
|
|
|
61
|
-
|
|
90
|
+
每个 `session/event` 把事件复制到其会话的 controller。第一个待处理事件开启固定批处理窗口;后续事件加入但不重置截止时间。窗口到期后启动一次持久追加;该次写入期间接纳的事件形成另一个独立有界的后续批次。`session/flush` 取消等待并排空至完全停稳,因此 loop 在下一轮次前把它用作排序与错误观察检查点。被拒绝的后台写入保留其事件并暂停自动重试;新事件开启新窗口,而显式 flush 或后端拆卸会立即重试。
|
|
62
91
|
|
|
63
|
-
|
|
92
|
+
### 存储记录兼容
|
|
64
93
|
|
|
94
|
+
后端读取只会在校验当前记录之前,规范化明确支持的 v0 记录变体。协调器对 `load`、`inspect`、`readFrom`、无所有者状态认领与 HMR 接管使用同一份规范化视图。读取不会重写已存记录,后续追加使用当前 v0。[消息标识机制引入前的消息](../../../.agents/notes/implemented/bug-fix/2026-07-28-load-pre-identity-session-messages.zh.md)与 [react-loop 引入前会话](../../../.agents/notes/implemented/bug-fix/2026-08-04-load-pre-react-loop-sessions.zh.md)笔记规定这些有限例外;它们不构成通用格式迁移承诺。
|
|
95
|
+
|
|
96
|
+
</details>
|
|
97
|
+
-----
|
|
98
|
+
|
|
99
|
+
<a id="further-exploration"></a>
|
|
100
|
+
## 进一步探索
|
|
101
|
+
|
|
102
|
+
当包级约定不够用时阅读以下页面。它们从共享持久性模型逐步进入随产品交付的后端与决策证据。
|
|
103
|
+
|
|
104
|
+
- [会话持久化子系统](../../../docs/subsystems/persistence.zh.md)——完整服务约定、flush 检查点、崩溃恢复与生成的 Cordis API。
|
|
105
|
+
- [JSONL 持久化后端](../session-persistence-jsonl/README.zh.md)——随产品交付、按会话存储文件的后端。
|
|
106
|
+
- [会话检查点策略](../session-checkpoint-policy/README.zh.md)——在语义边界上经由本服务刷新的插件。
|
|
107
|
+
- [会话包映射](../README.zh.md)——相邻的持久化、投影、标题与遥测包。
|
|
108
|
+
|
|
109
|
+
-----
|
|
110
|
+
|
|
111
|
+
<a id="model-experience"></a>
|
|
65
112
|
## 模型体验
|
|
66
113
|
|
|
67
114
|
### 恢复的对话历史
|
|
68
115
|
|
|
69
|
-
####
|
|
116
|
+
#### 模型看到什么
|
|
70
117
|
|
|
71
|
-
|
|
118
|
+
seam 不添加提示词或 schema。恢复会将已存储的表层事件还原为消息历史;已存储请求 header 重建较早调用,新 loop 则为下一次请求组合当前系统提示词、工具与会话前缀。崩溃修复将没有持久调用的 assistant 请求标记为 `TOOL_NOT_STARTED`;有持久调用但无结果时变为 `TOOL_OUTCOME_UNKNOWN`,其文本允许模型重试只读或幂等工作,但要求验证副作用或询问用户,而不是盲目重试。
|
|
72
119
|
|
|
73
120
|
#### Token 影响
|
|
74
121
|
|
|
@@ -76,11 +123,26 @@
|
|
|
76
123
|
|
|
77
124
|
#### KV Cache 影响
|
|
78
125
|
|
|
79
|
-
|
|
126
|
+
持久化不修改实时请求前缀。只有当重建历史、当前 envelope 与模型路由匹配时,恢复 loop 才能重用提供方缓存;崩溃修复结果仅追加,不重写较早历史。
|
|
127
|
+
|
|
128
|
+
## 已知限制与延期工作
|
|
129
|
+
|
|
130
|
+
<a id="known-limitations-and-deferred-work"></a>
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
这些限制界定 seam 保证的终点。它们是当前包约束,不是任务积压。
|
|
134
|
+
|
|
135
|
+
- **无删除或保留接口**——剪枝已存储会话属于带外后端维护。
|
|
136
|
+
- **`list()` 无分页且无过滤**——它返回每个已存储会话的 header;适合本地存储,大规模时无索引。
|
|
137
|
+
- **合成 closer 是唯一崩溃方案**——后端必须在 load 时合成 `tool/result`/`step/end`/`turn/end` closer;没有继续中断轮次而不先关闭它的部分轮次恢复。
|
|
138
|
+
- **跨进程写者排他为批次粒度**——append 时的修订值校验能拒绝在两批之间被其他进程推进的日志,但在同一批次内竞速的两个写者仍可能交错;完全排他需要跨进程锁。
|
|
139
|
+
|
|
140
|
+
<a id="dev-note"></a>
|
|
141
|
+
### 开发备注
|
|
142
|
+
|
|
143
|
+
<details>
|
|
144
|
+
<summary>维护者的工作上下文——点击展开</summary>
|
|
80
145
|
|
|
81
|
-
|
|
146
|
+
无。
|
|
82
147
|
|
|
83
|
-
|
|
84
|
-
- **`list()` 无分页且无过滤**:它返回每个已存储会话的 header;适合本地存储,大规模时无索引。
|
|
85
|
-
- **修复时合成 closer 是唯一崩溃方案**:后端必须在 load 时合成 `tool/result`/`step/end`/`turn/end` closer;没有继续中断轮次而不先关闭它的部分轮次恢复。
|
|
86
|
-
- **跨进程写者排他为批次粒度**:append 时的修订值校验能拒绝在两批之间被其他进程推进的日志,但在同一批次内竞速的两个写者仍可能交错;完全排他需要跨进程锁。
|
|
148
|
+
</details>
|
package/lib/index.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { Service } from "@deepseek-ai/cordis";
|
|
2
|
-
import { KNOWN_SESSION_EVENT_TYPES, SESSION_FORMAT_VERSION, SessionPreparation, adoptSessionEvent, interruptedTurnClosers,
|
|
2
|
+
import { KNOWN_SESSION_EVENT_TYPES, SESSION_FORMAT_VERSION, SessionPreparation, adoptSessionEvent, interruptedTurnClosers, snapshotSessionEvent } from "@deepseek-ai/dsh-session";
|
|
3
3
|
import { MAX_TIMER_DELAY_MS } from "@deepseek-ai/dsh-timeout";
|
|
4
|
+
import { snapshotJsonValue } from "@deepseek-ai/dsh-util-values";
|
|
4
5
|
//#region lib/types/revision.js
|
|
5
6
|
/** Opaque revision identity for lightweight persistence observations. */
|
|
6
7
|
/**
|
|
@@ -12,6 +13,19 @@ function SessionPersistenceRevision(value) {
|
|
|
12
13
|
return value;
|
|
13
14
|
}
|
|
14
15
|
//#endregion
|
|
16
|
+
//#region lib/types/errors.js
|
|
17
|
+
/** Stable failures exposed by the session-persistence service. */
|
|
18
|
+
/** The requested Session identity has no materialized durable log. */
|
|
19
|
+
var SessionPersistenceNotFoundError = class extends Error {
|
|
20
|
+
sessionId;
|
|
21
|
+
/** @param sessionId - absent durable Session identity. */
|
|
22
|
+
constructor(sessionId) {
|
|
23
|
+
super(`session "${sessionId}" not found`);
|
|
24
|
+
this.sessionId = sessionId;
|
|
25
|
+
this.name = "SessionPersistenceNotFoundError";
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
//#endregion
|
|
15
29
|
//#region lib/types/preparations.js
|
|
16
30
|
/**
|
|
17
31
|
* Bounded sharing and exclusive reservation of unpublished Sessions.
|
|
@@ -47,6 +61,45 @@ var SessionPreparations = class {
|
|
|
47
61
|
return source;
|
|
48
62
|
}
|
|
49
63
|
/**
|
|
64
|
+
* Borrow one prepared source and pin its ready entry against LRU eviction.
|
|
65
|
+
* @param id - session identity.
|
|
66
|
+
* @param load - cold loader used when no entry exists.
|
|
67
|
+
* @param signal - optional cancellation signal while waiting.
|
|
68
|
+
* @returns a caller-owned observation lease.
|
|
69
|
+
*/
|
|
70
|
+
async borrow(id, load, signal) {
|
|
71
|
+
const entry = this.entryFor(id, load);
|
|
72
|
+
const pinned = this.entries.get(id) === entry;
|
|
73
|
+
if (pinned) entry.pins += 1;
|
|
74
|
+
let loaded;
|
|
75
|
+
try {
|
|
76
|
+
loaded = signal === void 0 ? await entry.result : await observeQueuedAbort(entry.result, signal);
|
|
77
|
+
} catch (error) {
|
|
78
|
+
if (pinned && this.entries.get(id) === entry) {
|
|
79
|
+
entry.pins -= 1;
|
|
80
|
+
if (entry.phase === "ready") this.touch(entry);
|
|
81
|
+
}
|
|
82
|
+
throw error;
|
|
83
|
+
}
|
|
84
|
+
const source = entry.source ?? loaded;
|
|
85
|
+
if (this.entries.get(id) !== entry) return {
|
|
86
|
+
source,
|
|
87
|
+
[Symbol.dispose]: () => {}
|
|
88
|
+
};
|
|
89
|
+
if (entry.phase === "ready") this.touch(entry);
|
|
90
|
+
let released = false;
|
|
91
|
+
return {
|
|
92
|
+
source,
|
|
93
|
+
[Symbol.dispose]: () => {
|
|
94
|
+
if (released) return;
|
|
95
|
+
released = true;
|
|
96
|
+
if (this.entries.get(id) !== entry) return;
|
|
97
|
+
entry.pins -= 1;
|
|
98
|
+
if (entry.phase === "ready") this.touch(entry);
|
|
99
|
+
}
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
50
103
|
* Reserve one ready source after committing its pending durable repair.
|
|
51
104
|
* @param id - session identity.
|
|
52
105
|
* @param load - cold loader used when no entry exists.
|
|
@@ -189,7 +242,8 @@ var SessionPreparations = class {
|
|
|
189
242
|
const entry = {
|
|
190
243
|
id,
|
|
191
244
|
result: deferred.promise,
|
|
192
|
-
phase: "loading"
|
|
245
|
+
phase: "loading",
|
|
246
|
+
pins: 0
|
|
193
247
|
};
|
|
194
248
|
this.entries.set(id, entry);
|
|
195
249
|
let loading;
|
|
@@ -236,7 +290,7 @@ var SessionPreparations = class {
|
|
|
236
290
|
for (const candidate of this.entries.values()) if (candidate.phase === "ready") readyCount += 1;
|
|
237
291
|
if (readyCount <= this.capacity) return;
|
|
238
292
|
for (const [id, candidate] of this.entries) {
|
|
239
|
-
if (candidate.phase !== "ready") continue;
|
|
293
|
+
if (candidate.phase !== "ready" || candidate.pins > 0) continue;
|
|
240
294
|
this.entries.delete(id);
|
|
241
295
|
return;
|
|
242
296
|
}
|
|
@@ -472,7 +526,7 @@ var SessionFormatUnsupportedError = class extends Error {
|
|
|
472
526
|
* Direction-aware refusal text for a stored session whose format version this
|
|
473
527
|
* build does not read. Shared by the coordinator's load-time check and by
|
|
474
528
|
* backends that must refuse BEFORE decoding version-dependent structure (a
|
|
475
|
-
* future format may not satisfy
|
|
529
|
+
* future format may not satisfy this build's structural checks at all, and the
|
|
476
530
|
* user must see "upgrade the harness", never "corrupt").
|
|
477
531
|
* @param id - the stored session id, for message context.
|
|
478
532
|
* @param version - the stored format version.
|
|
@@ -805,6 +859,23 @@ var PersistenceCoordinator = class {
|
|
|
805
859
|
if (!Number.isSafeInteger(snapshot.createdAt) || snapshot.createdAt < 0) return Promise.reject(/* @__PURE__ */ new TypeError("session metadata createdAt must be a non-negative safe integer"));
|
|
806
860
|
return this.serialize(snapshot.id, () => this.createCore(snapshot));
|
|
807
861
|
}
|
|
862
|
+
/**
|
|
863
|
+
* Materialize one exact live session without inventing a session event.
|
|
864
|
+
* @param session - live session already registered through the write path.
|
|
865
|
+
*/
|
|
866
|
+
async ensureMaterialized(session) {
|
|
867
|
+
await this.flush(session);
|
|
868
|
+
await this.serialize(session.id, async () => {
|
|
869
|
+
const state = this.states.get(session.id);
|
|
870
|
+
/* v8 ignore next -- successful live flush always initializes the exact session state. */
|
|
871
|
+
if (state === void 0) throw new Error(`session "${session.id}" is not registered for persistence`);
|
|
872
|
+
if (state.materialized) return;
|
|
873
|
+
if (this.backend.materializeHeader === void 0) throw new Error("session persistence backend cannot materialize an empty session");
|
|
874
|
+
await this.backend.materializeHeader(state.meta);
|
|
875
|
+
state.materialized = true;
|
|
876
|
+
this.preparations.invalidate(session.id);
|
|
877
|
+
});
|
|
878
|
+
}
|
|
808
879
|
async createCore(meta) {
|
|
809
880
|
if (this.states.has(meta.id) || this.preparations.has(meta.id)) throw new Error(`session "${meta.id}" already exists in this backend`);
|
|
810
881
|
if (await this.backend.loadStored(meta.id) !== void 0) throw new Error(`session "${meta.id}" already has a persisted log on disk; load/resume it instead of creating`);
|
|
@@ -945,6 +1016,67 @@ var PersistenceCoordinator = class {
|
|
|
945
1016
|
}
|
|
946
1017
|
}
|
|
947
1018
|
/**
|
|
1019
|
+
* Borrow one exact logical view while pinning its reusable prepared Session.
|
|
1020
|
+
* @param id - persisted session to observe.
|
|
1021
|
+
* @param signal - optional cancellation for preparation work.
|
|
1022
|
+
* @returns a disposable observation retaining the prepared source.
|
|
1023
|
+
*/
|
|
1024
|
+
async borrowSession(id, signal) {
|
|
1025
|
+
for (;;) {
|
|
1026
|
+
signal?.throwIfAborted();
|
|
1027
|
+
if (this.retirements.has(id)) await this.waitForRetirement(id, signal);
|
|
1028
|
+
const live = this.ctx.sessions.get(id);
|
|
1029
|
+
if (live !== void 0) return {
|
|
1030
|
+
source: "live",
|
|
1031
|
+
inspection: this.inspectLive(live),
|
|
1032
|
+
[Symbol.dispose]: () => {}
|
|
1033
|
+
};
|
|
1034
|
+
const observation = await this.preparations.borrow(id, () => this.serialize(id, () => this.prepareCore(id)), signal);
|
|
1035
|
+
const source = observation.source;
|
|
1036
|
+
try {
|
|
1037
|
+
const attached = this.ctx.sessions.get(id);
|
|
1038
|
+
if (attached !== void 0) {
|
|
1039
|
+
observation[Symbol.dispose]();
|
|
1040
|
+
return {
|
|
1041
|
+
source: "live",
|
|
1042
|
+
inspection: this.inspectLive(attached),
|
|
1043
|
+
[Symbol.dispose]: () => {}
|
|
1044
|
+
};
|
|
1045
|
+
}
|
|
1046
|
+
const current = await this.serialize(id, () => this.isPreparedSourceCurrent(source, signal), signal);
|
|
1047
|
+
const published = this.ctx.sessions.get(id);
|
|
1048
|
+
if (published !== void 0) {
|
|
1049
|
+
observation[Symbol.dispose]();
|
|
1050
|
+
return {
|
|
1051
|
+
source: "live",
|
|
1052
|
+
inspection: this.inspectLive(published),
|
|
1053
|
+
[Symbol.dispose]: () => {}
|
|
1054
|
+
};
|
|
1055
|
+
}
|
|
1056
|
+
if (current || this.preparations.discardReady(id, source) === "retained") return {
|
|
1057
|
+
source: "prepared",
|
|
1058
|
+
inspection: source.inspection,
|
|
1059
|
+
revision: source.revision,
|
|
1060
|
+
preparedSession: source.session,
|
|
1061
|
+
[Symbol.dispose]: () => {
|
|
1062
|
+
observation[Symbol.dispose]();
|
|
1063
|
+
}
|
|
1064
|
+
};
|
|
1065
|
+
} catch (error) {
|
|
1066
|
+
observation[Symbol.dispose]();
|
|
1067
|
+
signal?.throwIfAborted();
|
|
1068
|
+
const attached = this.ctx.sessions.get(id);
|
|
1069
|
+
if (attached !== void 0) return {
|
|
1070
|
+
source: "live",
|
|
1071
|
+
inspection: this.inspectLive(attached),
|
|
1072
|
+
[Symbol.dispose]: () => {}
|
|
1073
|
+
};
|
|
1074
|
+
throw error;
|
|
1075
|
+
}
|
|
1076
|
+
observation[Symbol.dispose]();
|
|
1077
|
+
}
|
|
1078
|
+
}
|
|
1079
|
+
/**
|
|
948
1080
|
* Read the stored events from `fromSeq` onward, detached and non-mutating
|
|
949
1081
|
* (the read-from-seq primitive behind the service's `readFrom`). Runs on
|
|
950
1082
|
* the same per-id chain as writes; a backend with the seek-capable
|
|
@@ -971,7 +1103,7 @@ var PersistenceCoordinator = class {
|
|
|
971
1103
|
throw error;
|
|
972
1104
|
}
|
|
973
1105
|
signal?.throwIfAborted();
|
|
974
|
-
if (suffix === void 0) throw new
|
|
1106
|
+
if (suffix === void 0) throw new SessionPersistenceNotFoundError(id);
|
|
975
1107
|
this.assertStoredId(id, suffix.meta);
|
|
976
1108
|
this.assertVersion(suffix.meta);
|
|
977
1109
|
if (suffix.events.some(needsLegacyPrefix)) {
|
|
@@ -999,7 +1131,7 @@ var PersistenceCoordinator = class {
|
|
|
999
1131
|
signal?.throwIfAborted();
|
|
1000
1132
|
const stored = await this.backend.loadStored(id, signal);
|
|
1001
1133
|
signal?.throwIfAborted();
|
|
1002
|
-
if (stored === void 0) throw new
|
|
1134
|
+
if (stored === void 0) throw new SessionPersistenceNotFoundError(id);
|
|
1003
1135
|
this.assertStoredId(id, stored.meta);
|
|
1004
1136
|
this.assertVersion(stored.meta);
|
|
1005
1137
|
const events = snapshotStoredEvents(stored.events, id);
|
|
@@ -1012,7 +1144,7 @@ var PersistenceCoordinator = class {
|
|
|
1012
1144
|
/** Read, repair in memory, validate, and freeze one cold source once. */
|
|
1013
1145
|
async prepareCore(id) {
|
|
1014
1146
|
const stored = await this.backend.loadStored(id);
|
|
1015
|
-
if (stored === void 0) throw new
|
|
1147
|
+
if (stored === void 0) throw new SessionPersistenceNotFoundError(id);
|
|
1016
1148
|
try {
|
|
1017
1149
|
const { meta, events, revision, tornMarker } = stored;
|
|
1018
1150
|
this.assertStoredId(id, meta);
|
|
@@ -1079,7 +1211,7 @@ var PersistenceCoordinator = class {
|
|
|
1079
1211
|
const state = this.states.get(session.id);
|
|
1080
1212
|
/* v8 ignore next -- successful flush always publishes this live session's durable state */
|
|
1081
1213
|
if (state === void 0) throw new Error(`session "${session.id}" lost persistence state during load`);
|
|
1082
|
-
if (events.length === 0) throw new Error(`session "${session.id}" not found`);
|
|
1214
|
+
if (events.length === 0 && !state.materialized) throw new Error(`session "${session.id}" not found`);
|
|
1083
1215
|
if (interruptedTurnClosers(events).length > 0) throw new Error(`cannot load session "${session.id}" while its live turn is open; use the live Session or wait for the turn to close`);
|
|
1084
1216
|
return Object.freeze({
|
|
1085
1217
|
meta: state.meta,
|
|
@@ -1401,6 +1533,15 @@ var SessionPersistence = class extends Service {
|
|
|
1401
1533
|
return Promise.reject(/* @__PURE__ */ new Error("this session persistence backend does not expose raw artifacts"));
|
|
1402
1534
|
}
|
|
1403
1535
|
/**
|
|
1536
|
+
* Ensure a live session has a durable header even when it has no events.
|
|
1537
|
+
* Ordinary sessions remain lazily materialized; lifecycle frontends call
|
|
1538
|
+
* this only when an empty session itself is a durable resumable resource.
|
|
1539
|
+
* @param _session - exact live session whose registered header is materialized.
|
|
1540
|
+
*/
|
|
1541
|
+
ensureMaterialized(_session) {
|
|
1542
|
+
return Promise.reject(/* @__PURE__ */ new Error("this session persistence backend cannot materialize an empty session"));
|
|
1543
|
+
}
|
|
1544
|
+
/**
|
|
1404
1545
|
* Prepare the exact unpublished Session used by resume. Implementations may
|
|
1405
1546
|
* reuse object graphs retained by an earlier {@link inspect} after confirming
|
|
1406
1547
|
* their durable revision is still current; disposal releases an unpublished
|
|
@@ -1424,4 +1565,4 @@ var SessionPersistence = class extends Service {
|
|
|
1424
1565
|
}
|
|
1425
1566
|
};
|
|
1426
1567
|
//#endregion
|
|
1427
|
-
export { DEFAULT_PREPARED_SESSION_CACHE_SIZE, DEFAULT_WRITE_BATCH_MAX_DELAY_MS, MAX_WRITE_BATCH_DELAY_MS, PersistenceCoordinator, SessionFormatUnsupportedError, SessionPersistence, SessionPersistence as default, SessionPersistenceCorruptionError, SessionPersistenceRevision, sessionFormatVersionRefusal };
|
|
1568
|
+
export { DEFAULT_PREPARED_SESSION_CACHE_SIZE, DEFAULT_WRITE_BATCH_MAX_DELAY_MS, MAX_WRITE_BATCH_DELAY_MS, PersistenceCoordinator, SessionFormatUnsupportedError, SessionPersistence, SessionPersistence as default, SessionPersistenceCorruptionError, SessionPersistenceNotFoundError, SessionPersistenceRevision, sessionFormatVersionRefusal };
|
|
@@ -6,8 +6,8 @@
|
|
|
6
6
|
*/
|
|
7
7
|
import { Context } from '@deepseek-ai/cordis';
|
|
8
8
|
import { SessionPreparation } from '@deepseek-ai/dsh-session';
|
|
9
|
-
import type { SessionEvent, SessionId, SessionHeader } from '@deepseek-ai/dsh-session';
|
|
10
|
-
import type { SessionInspection, SessionLocation } from './index.ts';
|
|
9
|
+
import type { Session, SessionEvent, SessionId, SessionHeader } from '@deepseek-ai/dsh-session';
|
|
10
|
+
import type { BorrowedSessionSource, SessionInspection, SessionLocation } from './index.ts';
|
|
11
11
|
import type { SessionPersistenceRevision } from './revision.ts';
|
|
12
12
|
/** Default number of detached session preparations retained by a coordinator. */
|
|
13
13
|
export declare const DEFAULT_PREPARED_SESSION_CACHE_SIZE = 5;
|
|
@@ -44,7 +44,7 @@ export declare class SessionFormatUnsupportedError extends Error {
|
|
|
44
44
|
* Direction-aware refusal text for a stored session whose format version this
|
|
45
45
|
* build does not read. Shared by the coordinator's load-time check and by
|
|
46
46
|
* backends that must refuse BEFORE decoding version-dependent structure (a
|
|
47
|
-
* future format may not satisfy
|
|
47
|
+
* future format may not satisfy this build's structural checks at all, and the
|
|
48
48
|
* user must see "upgrade the harness", never "corrupt").
|
|
49
49
|
* @param id - the stored session id, for message context.
|
|
50
50
|
* @param version - the stored format version.
|
|
@@ -122,8 +122,8 @@ export interface PersistenceBackend<TornMarker = unknown> {
|
|
|
122
122
|
/**
|
|
123
123
|
* Optional seek-capable suffix read behind the service's `readFrom`: return
|
|
124
124
|
* the header plus the stored events with `seq >= fromSeq` without reading
|
|
125
|
-
* the whole log. A backend whose medium can address events by seq
|
|
126
|
-
*
|
|
125
|
+
* the whole log. A backend whose medium can address events by seq implements
|
|
126
|
+
* this so `readFrom` scales with the suffix; sequential backends
|
|
127
127
|
* omit it and the coordinator falls back to {@link loadStored} plus a
|
|
128
128
|
* forward skip. Non-mutating (no truncation, no closers). Validation of the
|
|
129
129
|
* region strictly below `fromSeq` is limited to seq contiguity — the
|
|
@@ -142,6 +142,8 @@ export interface PersistenceBackend<TornMarker = unknown> {
|
|
|
142
142
|
* @param signal - optional cancellation for backend read work.
|
|
143
143
|
*/
|
|
144
144
|
loadStoredFrom?(id: SessionId, fromSeq: number, signal?: AbortSignal): Promise<StoredSuffix | undefined>;
|
|
145
|
+
/** Durably create an empty header-only session artifact. */
|
|
146
|
+
materializeHeader?(meta: SessionHeader): Promise<void>;
|
|
145
147
|
/**
|
|
146
148
|
* Durably append a CONTIGUOUS batch, lazily materializing the session first
|
|
147
149
|
* when `!isMaterialized`. The materialize-write and the first event batch MUST
|
|
@@ -215,6 +217,11 @@ export declare class PersistenceCoordinator<TornMarker = unknown> {
|
|
|
215
217
|
* @param meta - header to snapshot; duplicate tracked or persisted ids reject.
|
|
216
218
|
*/
|
|
217
219
|
create(meta: SessionHeader): Promise<void>;
|
|
220
|
+
/**
|
|
221
|
+
* Materialize one exact live session without inventing a session event.
|
|
222
|
+
* @param session - live session already registered through the write path.
|
|
223
|
+
*/
|
|
224
|
+
ensureMaterialized(session: Session): Promise<void>;
|
|
218
225
|
private createCore;
|
|
219
226
|
/**
|
|
220
227
|
* Durably persist a batch of events. Honors the append-only and contiguous-seq
|
|
@@ -259,6 +266,13 @@ export declare class PersistenceCoordinator<TornMarker = unknown> {
|
|
|
259
266
|
* @returns immutable prepared metadata and events; a live view may have an open turn.
|
|
260
267
|
*/
|
|
261
268
|
inspect(id: SessionId, signal?: AbortSignal): Promise<SessionInspection>;
|
|
269
|
+
/**
|
|
270
|
+
* Borrow one exact logical view while pinning its reusable prepared Session.
|
|
271
|
+
* @param id - persisted session to observe.
|
|
272
|
+
* @param signal - optional cancellation for preparation work.
|
|
273
|
+
* @returns a disposable observation retaining the prepared source.
|
|
274
|
+
*/
|
|
275
|
+
borrowSession(id: SessionId, signal?: AbortSignal): Promise<BorrowedSessionSource>;
|
|
262
276
|
/**
|
|
263
277
|
* Read the stored events from `fromSeq` onward, detached and non-mutating
|
|
264
278
|
* (the read-from-seq primitive behind the service's `readFrom`). Runs on
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/** Stable failures exposed by the session-persistence service. */
|
|
2
|
+
import type { SessionId } from '@deepseek-ai/dsh-session';
|
|
3
|
+
/** The requested Session identity has no materialized durable log. */
|
|
4
|
+
export declare class SessionPersistenceNotFoundError extends Error {
|
|
5
|
+
readonly sessionId: SessionId;
|
|
6
|
+
/** @param sessionId - absent durable Session identity. */
|
|
7
|
+
constructor(sessionId: SessionId);
|
|
8
|
+
}
|
|
9
|
+
//# sourceMappingURL=errors.d.ts.map
|
package/lib/types/index.d.ts
CHANGED
|
@@ -6,10 +6,11 @@
|
|
|
6
6
|
*/
|
|
7
7
|
import { Context, Service } from '@deepseek-ai/cordis';
|
|
8
8
|
import { SessionPreparation } from '@deepseek-ai/dsh-session';
|
|
9
|
-
import type { SessionEvent, SessionId, SessionHeader } from '@deepseek-ai/dsh-session';
|
|
9
|
+
import type { Session, SessionEvent, SessionId, SessionHeader } from '@deepseek-ai/dsh-session';
|
|
10
10
|
import type { SessionPersistenceRevision } from './revision.ts';
|
|
11
11
|
export type { SessionHeader } from '@deepseek-ai/dsh-session';
|
|
12
12
|
export { SessionPersistenceRevision } from './revision.ts';
|
|
13
|
+
export { SessionPersistenceNotFoundError } from './errors.ts';
|
|
13
14
|
/** Lightweight immutable source identity returned without loading a full log. */
|
|
14
15
|
export interface SessionPersistenceSnapshot {
|
|
15
16
|
/** Detached metadata for one materialized session. */
|
|
@@ -24,6 +25,22 @@ export interface SessionInspection {
|
|
|
24
25
|
/** Validated contiguous logical event log. */
|
|
25
26
|
readonly events: readonly SessionEvent[];
|
|
26
27
|
}
|
|
28
|
+
/** A borrowed exact Session source returned from a cold materialization or concurrent live owner. */
|
|
29
|
+
export type BorrowedSessionSource = Disposable & ({
|
|
30
|
+
/** A reusable unpublished Session is pinned until this observation is disposed. */
|
|
31
|
+
readonly source: 'prepared';
|
|
32
|
+
/** Immutable header and logical event prefix observed together. */
|
|
33
|
+
readonly inspection: SessionInspection;
|
|
34
|
+
/** Durable revision represented by the prepared source. */
|
|
35
|
+
readonly revision: SessionPersistenceRevision;
|
|
36
|
+
/** Exact unpublished Session retained for a later {@link prepare}. */
|
|
37
|
+
readonly preparedSession: Session;
|
|
38
|
+
} | {
|
|
39
|
+
/** A live Session won source resolution while the persistence read was starting. */
|
|
40
|
+
readonly source: 'live';
|
|
41
|
+
/** Immutable live header and event prefix observed together. */
|
|
42
|
+
readonly inspection: SessionInspection;
|
|
43
|
+
});
|
|
27
44
|
/** A backend's own raw artifact text for one session, verbatim. */
|
|
28
45
|
export interface SessionRawArtifact {
|
|
29
46
|
/** The session header parsed from the artifact's own first line. */
|
|
@@ -61,8 +78,8 @@ export declare abstract class SessionPersistence extends Service {
|
|
|
61
78
|
constructor(ctx: Context);
|
|
62
79
|
/**
|
|
63
80
|
* Resolve this backend's independent local artifact for a session without
|
|
64
|
-
* reading, creating, flushing, or otherwise materializing it.
|
|
65
|
-
*
|
|
81
|
+
* reading, creating, flushing, or otherwise materializing it. A backend
|
|
82
|
+
* that does not own one artifact per Session returns `undefined`.
|
|
66
83
|
* @param meta - the immutable session header whose artifact is requested.
|
|
67
84
|
* @returns the backend-specific absolute location, when one exists.
|
|
68
85
|
*/
|
|
@@ -96,6 +113,13 @@ export declare abstract class SessionPersistence extends Service {
|
|
|
96
113
|
* @param meta - the immutable header (id, version, cwd, lineage) to record.
|
|
97
114
|
*/
|
|
98
115
|
abstract create(meta: SessionHeader): Promise<void>;
|
|
116
|
+
/**
|
|
117
|
+
* Ensure a live session has a durable header even when it has no events.
|
|
118
|
+
* Ordinary sessions remain lazily materialized; lifecycle frontends call
|
|
119
|
+
* this only when an empty session itself is a durable resumable resource.
|
|
120
|
+
* @param _session - exact live session whose registered header is materialized.
|
|
121
|
+
*/
|
|
122
|
+
ensureMaterialized(_session: Session): Promise<void>;
|
|
99
123
|
/**
|
|
100
124
|
* Durably persist a batch of events. Honors the append-only and contiguous-
|
|
101
125
|
* seq contracts: the first event's `seq` MUST equal the stored next-seq
|
|
@@ -149,6 +173,16 @@ export declare abstract class SessionPersistence extends Service {
|
|
|
149
173
|
* @returns the validated header and current logical event log.
|
|
150
174
|
*/
|
|
151
175
|
abstract inspect(id: SessionId, signal?: AbortSignal): Promise<SessionInspection>;
|
|
176
|
+
/**
|
|
177
|
+
* Borrow one exact inspection while retaining any reusable prepared source.
|
|
178
|
+
* A cold observation must pin the exact prepared Session that a later
|
|
179
|
+
* {@link prepare} reserves. Implementations must not degrade this operation
|
|
180
|
+
* to a detached {@link inspect} result.
|
|
181
|
+
* @param id - persisted session to observe.
|
|
182
|
+
* @param signal - optional cancellation for preparation work.
|
|
183
|
+
* @returns a disposable immutable observation.
|
|
184
|
+
*/
|
|
185
|
+
abstract borrowSession(id: SessionId, signal?: AbortSignal): Promise<BorrowedSessionSource>;
|
|
152
186
|
/**
|
|
153
187
|
* Read the stored events from `fromSeq` onward — the read-from-seq
|
|
154
188
|
* primitive for read models that resume from a watermark (e.g. a persisted
|
|
@@ -158,10 +192,10 @@ export declare abstract class SessionPersistence extends Service {
|
|
|
158
192
|
* publication. Only events from the valid contiguous stored prefix are
|
|
159
193
|
* returned, so a torn fragment never reaches the caller. `fromSeq` at or
|
|
160
194
|
* beyond the stored prefix returns an empty event list (never an error).
|
|
161
|
-
*
|
|
162
|
-
*
|
|
163
|
-
*
|
|
164
|
-
*
|
|
195
|
+
* A backend whose medium can seek by seq may read only the suffix;
|
|
196
|
+
* sequential media such as JSONL still parse the whole artifact and skip
|
|
197
|
+
* forward. The primitive bounds what is returned and refolded, not every
|
|
198
|
+
* backend's physical read.
|
|
165
199
|
* @param id - the persisted session to read.
|
|
166
200
|
* @param fromSeq - first event seq to include; a non-negative safe integer.
|
|
167
201
|
* @param signal - optional cancellation for queued and backend read work.
|
|
@@ -15,6 +15,12 @@ interface PreparationEntry<Source, CommitState> {
|
|
|
15
15
|
reservation?: SessionPreparationReservation<Source, CommitState>;
|
|
16
16
|
reservationSettled?: Promise<void>;
|
|
17
17
|
settleReservation?: () => void;
|
|
18
|
+
pins: number;
|
|
19
|
+
}
|
|
20
|
+
/** A borrowed prepared source that remains outside ready-entry eviction until released. */
|
|
21
|
+
export interface PreparationLease<Source> extends Disposable {
|
|
22
|
+
/** Shared immutable prepared source. */
|
|
23
|
+
readonly source: Source;
|
|
18
24
|
}
|
|
19
25
|
/** One exclusively held prepared source and its committed persistence state. */
|
|
20
26
|
export interface SessionPreparationReservation<Source, CommitState> {
|
|
@@ -41,6 +47,14 @@ export declare class SessionPreparations<Source extends PreparedSource, CommitSt
|
|
|
41
47
|
* @returns the shared prepared source.
|
|
42
48
|
*/
|
|
43
49
|
inspect(id: SessionId, load: () => Promise<Source>, signal?: AbortSignal): Promise<Source>;
|
|
50
|
+
/**
|
|
51
|
+
* Borrow one prepared source and pin its ready entry against LRU eviction.
|
|
52
|
+
* @param id - session identity.
|
|
53
|
+
* @param load - cold loader used when no entry exists.
|
|
54
|
+
* @param signal - optional cancellation signal while waiting.
|
|
55
|
+
* @returns a caller-owned observation lease.
|
|
56
|
+
*/
|
|
57
|
+
borrow(id: SessionId, load: () => Promise<Source>, signal?: AbortSignal): Promise<PreparationLease<Source>>;
|
|
44
58
|
/**
|
|
45
59
|
* Reserve one ready source after committing its pending durable repair.
|
|
46
60
|
* @param id - session identity.
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@crazx/dsh-session-persistence",
|
|
3
3
|
"description": "Abstract durable session persistence seam (ctx.sessionPersistence) for the DeepSeek Harness",
|
|
4
|
-
"version": "0.1.
|
|
4
|
+
"version": "0.1.2-alpha.3.zw.2",
|
|
5
5
|
"publishConfig": {
|
|
6
6
|
"access": "public"
|
|
7
7
|
},
|
|
@@ -32,18 +32,21 @@
|
|
|
32
32
|
],
|
|
33
33
|
"license": "MIT",
|
|
34
34
|
"peerDependencies": {
|
|
35
|
-
"@deepseek-ai/
|
|
36
|
-
"@deepseek-ai/dsh-
|
|
37
|
-
"@deepseek-ai/dsh-
|
|
38
|
-
"@deepseek-ai/dsh-
|
|
39
|
-
"@deepseek-ai/
|
|
35
|
+
"@deepseek-ai/cordis": "^4.0.2",
|
|
36
|
+
"@deepseek-ai/dsh-brand": "^0.1.2-alpha.3",
|
|
37
|
+
"@deepseek-ai/dsh-invariants": "^0.1.2-alpha.3",
|
|
38
|
+
"@deepseek-ai/dsh-session": "^0.1.2-alpha.3",
|
|
39
|
+
"@deepseek-ai/dsh-timeout": "^0.1.2-alpha.3"
|
|
40
40
|
},
|
|
41
41
|
"devDependencies": {
|
|
42
|
-
"@deepseek-ai/
|
|
43
|
-
"@deepseek-ai/dsh-
|
|
44
|
-
"@deepseek-ai/dsh-
|
|
45
|
-
"@deepseek-ai/dsh-
|
|
46
|
-
"@deepseek-ai/dsh-
|
|
47
|
-
"@deepseek-ai/
|
|
42
|
+
"@deepseek-ai/cordis": "^4.0.2",
|
|
43
|
+
"@deepseek-ai/dsh-brand": "^0.1.2-alpha.3",
|
|
44
|
+
"@deepseek-ai/dsh-invariants": "^0.1.2-alpha.3",
|
|
45
|
+
"@deepseek-ai/dsh-scope": "^0.1.2-alpha.3",
|
|
46
|
+
"@deepseek-ai/dsh-session": "^0.1.2-alpha.3",
|
|
47
|
+
"@deepseek-ai/dsh-timeout": "^0.1.2-alpha.3"
|
|
48
|
+
},
|
|
49
|
+
"dependencies": {
|
|
50
|
+
"@deepseek-ai/dsh-util-values": "^0.1.2-alpha.3"
|
|
48
51
|
}
|
|
49
52
|
}
|