[Bug]: pi 扩展在关闭 takeover 时,resume / 宿主重启后重发整条历史(watermark 未持久化)
Issue Origin
Observed or reproduced in a real environment
Bug Description
pi 扩展在 plugin.pi.takeoverEnabled: false(关闭上下文接管)时,捕获进度不跨进程持久化:SyncManager 的 syncedEntryCount 只在进程内有效,而唯一把它写进 pi 会话的载体是 takeover 状态条目 ov-takeover,且恢复它的调用被 if (config.takeoverEnabled) 包住。
结果:每个新的 pi 进程首次 turn_end 都会从 0 号 entry 重新提取整条 branch 并再次发送。触发路径包括 pi -c 续接、以及 pi-web(agegr/pi-web 一类宿主)重启后再次打开同一会话——同一批旧消息在 OV 里出现重复副本,并会被再次送去长期记忆抽取。
这与设计文档的承诺不一致。DESIGN.md 写 syncedEntryCount 是 “Pi branch watermark, restored across pi -p / pi -c processes”,并明确 “At startup the extension scans the branch from the end for the newest such entry and restores both the boundary and SyncManager's watermark, so a pi -c continuation does not resend branch entries OpenViking already has”。但该恢复路径只在 takeover 开启时执行(index.ts:189-192);DESIGN.md 的 “Session start” 一节也写了 “With takeover on, restore the boundary … with takeover off, fetch the archive overview instead”,即非接管路径没有等价的进度恢复。
Steps to Reproduce
- 安装 pi 扩展:
bash <(curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/examples/memory-plugin-shared/install.sh) --harness pi - 在
~/.openviking/ovcli.conf写入{"plugin": {"pi": {"takeoverEnabled": false}}}(其余保持默认) - 用 pi 或其主要 web 宿主(如 agegr pi-web)在某条会话里完成若干轮,确认消息已入库(
GET /api/v1/sessions/pi-<id>可见commit_count,history/archive_001/messages.jsonl有内容) - 结束该进程后重新启动(CLI 用
pi -c;systemd 托管的 web 宿主则systemctl --user restart <unit>) - 在同一条会话里再发一条消息,等
turn_end - 检查 OV:同一批旧消息再次入库,
commit_count增加,history/archive_002/messages.jsonl出现与archive_001相同的内容
Expected Behavior
按 DESIGN.md 的承诺:pi -c 续接或宿主重启后,不应重发已经入库的 branch entries;捕获应从上一次的进度继续。
Actual Behavior
整条 branch 被从 0 号 entry 重新提取并再次发送,OV 侧出现重复消息,重复内容还会再次进入长期记忆抽取流程(memory_diff.json 里出现同一段抽取结果)。
实测两端时间戳(同一条消息文本,两次入库):
2026-10-02T13:40:26Z→history/archive_001/messages.jsonl2026-10-02T14:06:10Z→history/archive_002/messages.jsonl(宿主重启后再发消息触发)
CLI 侧同构实测:同一条会话连续三次以新进程续接,OV 里第一条用户消息出现 3 次,message_count 1 → 3 → 6(每次净增 = 当时全部历史)。
Minimal Reproducible Example
// examples/pi-coding-agent-extension/index.ts:189-192
if (config.takeoverEnabled) {
takeover.restore(branch);
sync.restoreWatermark(takeover.state.syncedEntryCount); // ← takeoverEnabled=false 时不会执行
}
// examples/pi-coding-agent-extension/sync.ts:33
private syncedEntryCount = 0; // 仅进程内;新进程从 0 开始
// examples/pi-coding-agent-extension/sync.ts:211
const extracted = extractBranchCapturePayloads(branch, this.syncedEntryCount, this.config);
// examples/pi-coding-agent-extension/takeover.ts:32-33
pi.appendEntry(customType, data); // 唯一的持久化写入(ov-takeover 状态)
另:capture-adapter.mjs 生成的 payload 只含 role / content / parts(可选 peer_id),没有稳定的消息 id,服务端无法据此去重。
Error Logs
无报错(静默发生,只能从 OV 侧的时间戳与条目数看出来)。
OpenViking Version
服务端 0.4.21;客户端扩展 openviking-pi-extension 0.4.9。已确认 v0.4.23 之后 main 上 index.ts:189-192 的守卫未变、扩展版本仍为 0.4.9。
Python Version
3.10.12
Operating System
Linux
Model Backend
Other
Additional Context
- 复现环境:pi 1.0.0(CLI 与 web 宿主各一例),
plugin.pi.takeoverEnabled: false,其余默认。 - 同类先例:#4058(Codex 插件因
capturedTurnCount游标被清导致 resume 重放历史,已修复)。本条是 pi 侧非接管路径上的同类缺陷,且README未提示“关闭 takeover 会失去跨进程进度”。 - 建议修法(供参考):把捕获进度的持久化与 takeover 解耦(例如在非接管模式下同样写入/读取一条
syncedEntryCount记录),或在发送前做服务端去重(需要 payload 带稳定 id)。 - 临时规避:开启 takeover;或避免宿主重启后继续使用旧会话;或用
bypassSessionPatterns排除相关目录。
补充:根因不只是「没持久化」,水位本身需要按 entry id 锚定
复现环境:pi 1.0.0 + 本扩展 0.4.9(= 当前 main),OV 服务端 0.4.21,plugin.pi.takeoverEnabled: false。
1. 除了本 issue 报的重发,还有一个静默漏发,两种模式都有
lib/capture-adapter.mjs:23-27 的水位是数组下标,唯一重置条件是「新分支比水位短」:
const resetWatermark = entries.length < previousCount;
const start = resetWatermark ? 0 : Math.min(previousCount, entries.length);
于是当分支分叉但更长时,start 直接取旧水位 → 水位以下、服务器从未收到的条目被跳过,随后水位推进到新长度,现场无任何痕迹。
直接调用已安装的 extractBranchCapturePayloads 复现(分支 A 33 条、水位 31;切到与 A 共享前 3 条前缀的分支 B,35 条):
分支B长度: 35 | 水位: 31 | resetWatermark: false | start: 31
本次会发送的条数: 4 → B-msg-28 … B-msg-31
水位以下【从未被发送】的条目数: 31
若把水位换成「A 的第 31 条 entry id」锚定:findIndex = -1 → 归零重发 → 发送 22 条(整条 B 的可见消息)
2. 这不是「接管关掉才有的」——接管模式同样中招
lib/takeover-core.mjs里syncedEntryCount只出现在:初始化 0(:373)、从状态条目恢复(:439)、从io.getWatermark()同步(:824/:979/:1002)。没有任何分支变化检测;唯一的分支感知inActiveContext只服务边界(:764/:807)。DESIGN.md:81只写了「变短则归零」这一侧。- 而已开启接管时,同进程切树会把旧水位带进新分支,漏发条件与上面完全一致。
3. 可达路径
漏发需要「同进程内换分支」,触发入口是 pi 的 navigateTree:
- pi TUI 的
/tree; - pi-web / agegr 的「Edit from here」(界面标题即 branches within this session),客户端发出
navigate_tree,服务端直接await this.inner.navigateTree(...)—— 同进程、同一扩展实例; - 而本扩展订阅了 10 个事件,既没有
session_tree也没有session_before_tree(pi 1.0.0 两个事件都存在:dist/core/extensions/types.d.ts:631/:637、:1155/:1156)。
跨进程恢复这条路径是安全的(状态条目挂在分支上,restore() 只扫当前分支),所以问题一直没暴露;只有进程内换分支才踩。
4. 建议的修法
水位是「以某条 entry 结尾的前缀已发过」这个跨分支概念,用下标表达力不够。建议与边界保持一致——边界已经是 entry id,DESIGN.md:119 也写明了理由("entry ids survive compaction and branch navigation"):
- 水位改存 entry id(新增字段或新条目类型),每次同步前在当前分支
findIndex推导下标;找不到 → 归零全量重发(把漏发翻转为有界重复); - 顺势修本 issue 的持久化问题:非接管模式也持久化该锚;
- 可选:订阅
session_tree后立即重锚(有了第 1 条只是提前发现,不是必需)。
我们已按这个形态在本地打了补丁(index.ts + sync.ts,8 处 hunk,isolated 在 takeoverEnabled:false 路径,不干预接管模式),实测连续 3 个新进程的 OV 侧增量为 1/1/1(补丁前同一模式为 1→3→6)。如果这个方向可以,我可以按 CONTRIBUTING_CN.md 提 PR(含测试)。
We also reproduced the same issue locally with Pi's native compaction (takeoverEnabled: false): after exiting and resuming the same session, previously archived messages were uploaded again. A local checkpoint patch stopped the replay in the same reproduction, including a compaction/restart check.
I'd like to take this on and prepare a focused PR. I'll first verify Pi's session-tree, compaction and fork semantics, then decouple capture-progress persistence from takeover and use stable entry IDs so branch navigation cannot silently skip new messages. I'll validate restart/resume, branch changes, compaction, forks and failed capture, while preserving takeover's existing archive/recovery behavior. Server-side idempotency after a lost response (#5667) is outside this PR's scope.
@feel-think Thanks for the reproduction and the branch-navigation analysis. I saw that you also have a local patch; please let me know if you already have a PR in progress so we can coordinate rather than duplicate the work.
已审查 commit d65f5a2。把 ov-capture 检查点独立出来,并按 entry id 而不是数组下标记录进度,这个方向是对的。#5568 里的两个问题都直接解决了:关闭 takeover 后重启会重传,切到更长的兄弟分支会漏传。不过 /tree 相关的路径上还有两种情况会重复上传。两者互相独立,下面分别说明。
图例:Q/A 是一问一答,✓A2 是 ov-capture 检查点(lastEntryId = A2),由 appendEntry 挂在 A2 下面。
问题 1:在较早的位置同步一次,再回到后面时,会从那个位置重传
② /tree 回到这里,/viking commit
▼
Q1 → A1 → ✓A1 → Q2 → A2 → ✓A2 → QB → AB → ✓AB → QB2 → AB2 → ✓AB2 → QB3 → AB3
▲ └ ③ /tree 回到末尾继续对话
① 已同步到这里
② 在 A2 处同步时,syncedEntryId 被设为 A2。③ 回到末尾后,syncBranch 在当前分支上找到了 A2,就直接从 A2 之后开始提取(sync.ts#L251-L255),没有注意到同一分支上还有更新的 ✓AB2。结果 QB AB QB2 AB2 被重新上传。
触发条件:
- 开启了 takeover。关闭时
/viking commit不经过syncBranch。 - 用
/tree回到当前分支上更早的位置。选中回复或问题都会触发,也不需要存在其他分支。 - 在那里执行
/viking commit。 - 不重启,直接回到更靠后的位置继续对话。
回退点之后已经上传过的内容会全部重传。回退得越远,重传越多。
问题 2:从一条已同步的回复处分叉,会重传分叉点那一轮
Q1 → A1 → ✓A1 → Q2 → A2 → ✓A2 → QB → AB → ✓AB 原分支
│
└→ QC → AC /tree 选中 A2 后继续对话
检查点是它所覆盖的那条 entry 的子节点。从 A2 分叉后,✓A2 留在原分支一侧,不在新路径上。restoreCapture 只扫描当前路径,只能找到 ✓A1,于是 Q2 A2 被重传。
触发条件:
- takeover 开或关都会触发。
- 用
/tree选中一条已同步的回复。选中问题不会触发:pi 的navigateTree会把 leaf 设为问题的父节点,也就是检查点本身。 - 之后发生任意一次同步:继续对话、执行
/viking commit,或者停在这里退出、重启后再对话。启动时的restoreCapture同样只看当前路径。
从回复处分叉是 /tree 最常见的用法,所以这个问题出现的频率应该比问题 1 高。
建议的修复
两处改动需要同时做,只改其中一处都覆盖不全:
syncBranch:即使在当前分支上找到了内存锚点,也要再调用一次restoreCapture,取两者中更靠后的位置。这修的是问题 1。restoreCapture:扫描整个会话的ov-capture,而不只是当前分支。pi 里到每个 entry 只有一条路径,所以只要lastEntryId在当前分支上,从根到它的内容就都已上传。原有的校验"检查点只能证明写入它之前的 entry"保留:路径上的检查点要求 anchor 在它之前;挂在路径外的检查点要求父节点在路径上,且 anchor 不晚于父节点。index.ts在session_start里把sessionManager.getEntries交给SyncManager,这样 turn_end、takeover、/viking commit三条同步路径都能用上。这修的是问题 2。
pi 文档建议不要从整个文件重建"随分支变化的状态"。这里是例外:所有分支的消息都写进同一个 OV session,上传进度描述的是 OV session,不随分支变化。另外,这里保存的是 sessionManager 对象而不是 ctx,不会触发 stale ctx 检查。
| 问题 1(选中回复) | 问题 1(选中问题) | 问题 2 | |
|---|---|---|---|
d65f5a2 |
✗ | ✗ | ✗ |
| 只改 1 | ✗ | ✓ | ✗ |
| 只改 2 | ✗ | ✗ | ✓ |
| 1 + 2 | ✓ | ✓ | ✓ |
问题 1 在选中回复时,第 ② 步本身就会先触发问题 2,所以只改 1 不够。
验证:
- 补充的 4 个测试在
d65f5a2上全部失败,加上修复后全部通过。 - pi 扩展全量测试:291 项通过,3 项跳过。跳过的原因是本地缺少 pi-ai transcript 辅助模块,与本次改动无关。
- 用 pi 0.87.1 的真实
SessionManager复现了两个场景,修复后都只上传新消息。
下面两段 diff 都基于 d65f5a2,路径相对于仓库根目录,可以分别 git apply。
建议的改动:sync.ts / index.ts
diff --git a/examples/pi-coding-agent-extension/index.ts b/examples/pi-coding-agent-extension/index.ts
index 07b5bd2..36d3f52 100644
--- a/examples/pi-coding-agent-extension/index.ts
+++ b/examples/pi-coding-agent-extension/index.ts
@@ -189,6 +189,12 @@ export default async function (pi: ExtensionAPI) {
if (config.takeoverEnabled) {
takeover.restore(branch);
}
+ // Upload progress belongs to the OV session, not to one branch: a
+ // checkpoint left on the side by `/tree` still marks what OV has.
+ const sessionManager = ctx.sessionManager;
+ if (typeof sessionManager.getEntries === "function") {
+ sync.bindSession(() => sessionManager.getEntries());
+ }
sync.restoreCapture(branch, !ctx.sessionManager.getHeader?.()?.parentSession);
await sync.replayPending();
diff --git a/examples/pi-coding-agent-extension/sync.ts b/examples/pi-coding-agent-extension/sync.ts
index 3aa4371..458655a 100644
--- a/examples/pi-coding-agent-extension/sync.ts
+++ b/examples/pi-coding-agent-extension/sync.ts
@@ -33,6 +33,8 @@ export class SyncManager {
private syncedEntryCount = 0;
private syncedEntryId: string | null = null;
private persistEntry?: (customType: string, data: unknown) => void;
+ /** Every entry of the pi session, abandoned branches included; see restoreCapture. */
+ private sessionEntries?: () => any[];
/**
* Messages this session lost for good: non-retryable (4xx) rejections and
* queued entries whose retry budget ran out. They are counted as accepted so
@@ -83,22 +85,38 @@ export class SyncManager {
this.syncedEntryId = null;
}
- /** Restore only this OV session's progress on the active Pi branch. */
+ /** Let restoreCapture read checkpoints off the active branch too. */
+ bindSession(entries: () => any[]): void {
+ this.sessionEntries = entries;
+ }
+
+ /**
+ * Restore only this OV session's progress on the active Pi branch.
+ *
+ * A checkpoint is appended under the entry it covers, so forking from that
+ * entry (`/tree` to the reply that ended a turn) leaves the checkpoint on the
+ * abandoned side. Its lastEntryId is still on this branch, and pi has one
+ * path to each entry, so everything up to it reached OV all the same. A
+ * checkpoint therefore counts when it sits on the branch or hangs directly
+ * off it, and only for entries written before it.
+ */
restoreCapture(branch: any[], allowLegacy = false): void {
this.restoreWatermark(0);
- for (let i = branch.length - 1; i >= 0; i--) {
- const entry = branch[i];
- if (entry?.type !== "custom") continue;
- if (entry.customType === "ov-capture" && entry.data?.sessionId === this.ovSessionId
- && typeof entry.data.lastEntryId === "string" && entry.data.lastEntryId) {
- const anchor = branch.findIndex((item) => item.id === entry.data.lastEntryId);
- if (anchor >= 0 && anchor < i) {
- this.syncedEntryCount = anchor + 1;
- this.syncedEntryId = branch[anchor].id;
- return;
- }
+ const position = new Map<string, number>();
+ branch.forEach((entry, i) => entry?.id && position.set(entry.id, i));
+ for (const entry of this.sessionEntries?.() ?? branch) {
+ if (entry?.type !== "custom" || entry.customType !== "ov-capture") continue;
+ if (entry.data?.sessionId !== this.ovSessionId) continue;
+ const anchor = position.get(entry.data.lastEntryId);
+ const own = position.get(entry.id);
+ const writtenAfter = own !== undefined ? own - 1 : position.get(entry.parentId);
+ if (anchor === undefined || writtenAfter === undefined || anchor > writtenAfter) continue;
+ if (anchor + 1 > this.syncedEntryCount) {
+ this.syncedEntryCount = anchor + 1;
+ this.syncedEntryId = branch[anchor].id;
}
}
+ if (this.syncedEntryCount > 0) return;
// Published takeover checkpoints use offsets and have no session id.
// Migrate them only without a modern checkpoint, at unforked startup.
if (!allowLegacy) return;
@@ -249,10 +267,16 @@ export class SyncManager {
}
// Array offsets alone cannot detect switching to a longer sibling branch.
+ // Finding the in-memory anchor is not enough either: syncing while pi sat
+ // on a shared entry (`/tree` back, `/viking commit`) moves it there, and
+ // this branch may hold a later checkpoint. Use whichever is further along.
if (this.syncedEntryId) {
const anchor = branch.findIndex((entry) => entry.id === this.syncedEntryId);
- if (anchor >= 0) this.syncedEntryCount = anchor + 1;
- else this.restoreCapture(branch);
+ this.restoreCapture(branch);
+ if (anchor + 1 > this.syncedEntryCount) {
+ this.syncedEntryCount = anchor + 1;
+ this.syncedEntryId = branch[anchor].id;
+ }
}
const extracted = extractBranchCapturePayloads(branch, this.syncedEntryCount, this.config);
if (extracted.resetWatermark) this.syncedEntryCount = 0;
补充测试:tests/sync-barrier.test.mjs
diff --git a/examples/pi-coding-agent-extension/tests/sync-barrier.test.mjs b/examples/pi-coding-agent-extension/tests/sync-barrier.test.mjs
index 478f4a0..7cc181c 100644
--- a/examples/pi-coding-agent-extension/tests/sync-barrier.test.mjs
+++ b/examples/pi-coding-agent-extension/tests/sync-barrier.test.mjs
@@ -104,6 +104,88 @@ for (const takeoverEnabled of [false, true]) {
});
}
+/** pi's session tree in miniature: each entry hangs under the leaf it was appended at. */
+function sessionTree() {
+ const entries = [];
+ let leaf = null;
+ return {
+ entries,
+ get leaf() { return leaf; },
+ append(entry) {
+ entries.push({ ...entry, parentId: leaf });
+ leaf = entry.id;
+ },
+ moveTo(id) { leaf = id; },
+ branch() {
+ const byId = new Map(entries.map((entry) => [entry.id, entry]));
+ const path = [];
+ for (let id = leaf; id; id = byId.get(id).parentId) path.unshift(byId.get(id));
+ return path;
+ },
+ };
+}
+
+async function treeSync(session, takeoverEnabled, sent) {
+ const c = client({ fetchJSON: async (_path, init) => {
+ sent.push(...JSON.parse(init.body).messages);
+ return { ok: true, result: {} };
+ } });
+ const sync = new SyncManager(c, config({ takeoverEnabled }), (customType, data) => {
+ session.append({ id: `checkpoint-${session.entries.length}`, type: "custom", customType, data });
+ });
+ sync.bindSession(() => session.entries);
+ await sync.ensureSession("tree");
+ return sync;
+}
+
+const timesSent = (sent, id) => sent.filter((p) => JSON.stringify(p).includes(`decision ${id}.`)).length;
+
+for (const takeoverEnabled of [false, true]) {
+ test(`forking from the entry a checkpoint covers resends nothing before it (takeover=${takeoverEnabled})`, async () => {
+ await withPendingDir(async () => {
+ const session = sessionTree();
+ const sent = [];
+ const sync = await treeSync(session, takeoverEnabled, sent);
+ for (const id of ["one", "two", "b"]) {
+ session.append(captureEntry(id));
+ await sync.syncBranch(session.branch());
+ }
+ // `/tree` to "two": its checkpoint stays behind on the abandoned side.
+ session.moveTo("two");
+ const restarted = await treeSync(session, takeoverEnabled, sent);
+ restarted.restoreCapture(session.branch());
+ assert.equal(restarted.syncedCount, session.branch().length, "a restart at the fork keeps its progress");
+ session.append(captureEntry("c"));
+ assert.equal((await sync.syncBranch(session.branch())).added, 1);
+ assert.equal(timesSent(sent, "two"), 1);
+ });
+ });
+}
+
+// Picking the reply in `/tree` lands on it; picking the next question lands on its checkpoint.
+for (const landing of ["reply", "checkpoint"]) {
+ test(`a sync on shared history does not rewind the branch you return to (lands on ${landing})`, async () => {
+ await withPendingDir(async () => {
+ const session = sessionTree();
+ const sent = [];
+ const sync = await treeSync(session, true, sent);
+ for (const id of ["one", "two", "b", "b2"]) {
+ session.append(captureEntry(id));
+ await sync.syncBranch(session.branch());
+ }
+ const branchLeaf = session.leaf;
+ const two = session.entries.findIndex((entry) => entry.id === "two");
+ session.moveTo(session.entries[landing === "reply" ? two : two + 1].id);
+ // `/viking commit` syncs here before it archives.
+ assert.equal((await sync.syncBranch(session.branch())).added, 0);
+ session.moveTo(branchLeaf);
+ session.append(captureEntry("b3"));
+ assert.equal((await sync.syncBranch(session.branch())).added, 1);
+ assert.deepEqual(["two", "b", "b2"].map((id) => timesSent(sent, id)), [1, 1, 1]);
+ });
+ });
+}
+
test("capture migration rejects foreign, invalid and off-branch checkpoints", async () => {
const sync = new SyncManager(client(), config());
await sync.ensureSession("migration");