Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(pi): 死锁回收改原子覆盖接管 + 写前复核持有者(review P2×2)
Zhang Yunjinaa4581fe6be6
diff --git a/packages/maker-core/src/agents/pi/__tests__/mcpDisclosureFingerprint.test.ts b/packages/maker-core/src/agents/pi/__tests__/mcpDisclosureFingerprint.test.tsindex 25525ac207..b6a12e198d 100644--- a/packages/maker-core/src/agents/pi/__tests__/mcpDisclosureFingerprint.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/mcpDisclosureFingerprint.test.ts@@ -63,9 +63,11 @@ function loadGateway(options: {const lockFile: { value: string | null } = { value: null };if (options.lockOwner !== undefined) lockFile.value = String(options.lockOwner);- // stale 回收槽:rename(lock→stale) 时锁内容搬到这里。- const staleFile: { value: string | null } = { value: null };-+ // 接管槽:rename(takeover→lock) 覆盖接管时锁内容从这里来。+ const takeoverFile: { value: string | null } = { value: null };+ // 披露文件的 tmp 写入单独保存:只有 rename 到正式路径才算落盘成功。+ const tmpFile: { value: DisclosedFile | null } = { value: null };+const externalWrite = (value: DisclosedFile) => { disk.value = value; };const reclaimed: string[] = [];@@ -95,10 +97,6 @@ function loadGateway(options: {dirname: (file: string) => file.slice(0, file.lastIndexOf('/')),},readFileSync: (file: string) => {- if (file.includes('.stale-')) {- if (staleFile.value === null) throw Object.assign(new Error('missing'), { code: 'ENOENT' });- return staleFile.value;- }if (file.endsWith('.lock')) {if (lockFile.value === null) throw Object.assign(new Error('missing'), { code: 'ENOENT' });return lockFile.value;@@ -112,31 +110,37 @@ function loadGateway(options: {lockFile.value = body; // 记录持锁 pidreturn;}- disk.value = JSON.parse(body) as DisclosedFile;- writes.push(disk.value);+ if (file.includes('.takeover-')) {+ takeoverFile.value = body; // 接管槽内容(持锁 pid)+ return;+ }+ // 披露文件的 tmp 写入:先暂存,rename 到正式路径才算落盘成功。+ tmpFile.value = JSON.parse(body) as DisclosedFile;},renameSync: (from: string, to: string) => {- if (options.reclaimLostRace && from.endsWith('.lock')) {- // 模拟另一个实例先把残留锁回收并重建了新锁:本实例的 rename 失败。+ if (options.reclaimLostRace && from.includes('.takeover-')) {+ // 模拟接管覆盖失败(例如路径刚被另一个接管者占用):本实例的 rename 失败。throw Object.assign(new Error('lock gone'), { code: 'ENOENT' });}- if (from.endsWith('.lock') && to.includes('.stale-')) {- // 回收挪动:锁内容搬进回收槽;外部可同时预置 reclaimReplacesWith,模拟- // 「挪走的其实是另一个实例刚重建的活锁」(内容与读到的死 pid 不一致)。- staleFile.value = options.reclaimReplacesWith !== undefined+ if (from.includes('.takeover-') && to.endsWith('.lock')) {+ // 接管覆盖:锁路径内容换成接管槽内容;外部可预置 reclaimReplacesWith 模拟+ // 「本实例覆盖之后、写前复核之前,另一个接管者又覆盖了一次」。+ lockFile.value = options.reclaimReplacesWith !== undefined? String(options.reclaimReplacesWith)- : lockFile.value;- lockFile.value = null;- } else if (from.endsWith('.stale-') && to.endsWith('.lock')) {- // 放回:回收槽内容回到锁路径。- lockFile.value = staleFile.value;- staleFile.value = null;+ : takeoverFile.value;+ takeoverFile.value = null;+ } else if (from.includes('.tmp') && !to.endsWith('.lock') && !to.includes('.takeover-')) {+ // 披露文件落盘:rename 成功才算保存成功。+ disk.value = tmpFile.value;+ tmpFile.value = null;+ writes.push(disk.value as DisclosedFile);}renames.push(`${from} -> ${to}`);},rmSync: (file: string) => {- if (file.includes('.stale-')) staleFile.value = null;+ if (file.includes('.takeover-')) takeoverFile.value = null;else if (file.endsWith('.lock')) lockFile.value = null;+ else if (file.includes('.tmp')) tmpFile.value = null;reclaimed.push(file);},openSync: (file: string, flags: string) => {@@ -188,11 +192,13 @@ function loadGateway(options: {const listTools = registered.find((t) => t.name === 'cindy_mcp_list_tools');if (!callTool || !listTools) throw new Error('gateway tools not registered');+ const lockOwnerAfter = () => lockFile.value;return {gateway,httpClient,externalWrite,reclaimed,+ lockOwnerAfter,writes,renames,warnings,@@ -325,26 +331,24 @@ describe('MCP gateway schema disclosure', () => {.isSchemaDisclosed(gateway.resolveCall({ server: 'cindy_orca', tool: 'send_to_worker' }))).toBe(true);});- it('skips persisting when another instance reclaimed the stale lock first', async () => {- // 回收必须与重新加锁互斥:rename 失败说明锁已被别人收走/重建,本实例直接放弃,- // 不能继续 rmSync(那会删掉对方刚建的锁,两边都进写入路径互相覆盖记录)。+ it('skips persisting when the takeover rename fails, leaving the existing lock alone', async () => {+ // 接管覆盖失败(另一个实例抢先):不争,放弃本次落盘,不删对方的锁。const { call, requests, disk, reclaimed } = loadGateway({ lockOwner: 999, reclaimLostRace: true });await call();expect(requests).toHaveLength(1);expect(disk.value).toBeNull();- expect(reclaimed.some((file) => file.endsWith('.lock') && !file.includes('.stale-'))).toBe(false);+ expect(reclaimed.some((file) => file.endsWith('.lock'))).toBe(false);});- it('restores the lock and skips persisting when the reclaimed lock was actually a live one', async () => {- // 两个实例同时读到死 pid:A 先回收旧锁并重建;B 的 rename 仍会成功,但掣走的是- // A 的新锁(内容 777,活进程)。校验内容不一致后必须放回并放弃本次落盘,- // 否则 B 会在 A 持锁写披露的同时进入写入路径,后写方覆盖先写方的记录。- const { call, requests, disk, renames } = loadGateway({ lockOwner: 999, reclaimReplacesWith: 777 });+ it('aborts without deleting the lock when another instance won the takeover race', async () => {+ // 接管覆盖成功后、写前复核前,另一个接管者又覆盖了一次(锁内容变成 777)。+ // 本实例必须放弃落盘且**不删锁**——那是赢家的锁;删了会造成新的双写窗口。+ const { call, requests, disk, lockOwnerAfter } = loadGateway({ lockOwner: 999, reclaimReplacesWith: 777 });await call();expect(requests).toHaveLength(1);expect(disk.value).toBeNull();- // 放回:回收槽内容回到锁路径(放回 rename + 原写入 rename 都有记录)- expect(renames.some((r) => r.includes('.stale-4242 -> /runtime/mcp-disclosure-s1.json.lock'))).toBe(true);+ // 赢家的锁保持原样(内容 777,活进程),未被本实例删除或覆盖回自己的 pid。+ expect(lockOwnerAfter()).toBe('777');});it('keeps another instance newer fingerprint when persisting a different tool', async () => {diff --git a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts b/packages/maker-core/src/agents/pi/cindy-bridge-source.tsindex 81fdeb31c2..5e1aacdc14 100644--- a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts+++ b/packages/maker-core/src/agents/pi/cindy-bridge-source.ts@@ -2879,46 +2879,35 @@ function mcpGatewayKey(serverName: string, toolName: string): string {* 跳过这一次落盘——本进程内存里的披露仍然有效。*/function acquireDisclosureLock(lockPath: string): boolean {- for (let attempt = 0; attempt < 2; attempt += 1) {- try {- // fd 只参与 wx 独占创建这一步;锁语义是文件存在性 + pid 内容,写完即可释放。- const fd = openSync(lockPath, 'wx', 0o600);- try { writeFileSync(lockPath, String(process.pid)); } catch { /* pid 写不进去时只当普通锁 */ }- try { closeSync(fd); } catch { /* 关闭失败不影响已持有的锁 */ }- return true;- } catch {- if (attempt === 1) return false;- const owner = readLockOwner(lockPath);- if (owner === undefined || owner === process.pid || isProcessAlive(owner)) return false;- // 回收:把残留锁**原子地挪走**,再验证挪走的确实是自己刚读到的那个死锁。- // 只靠 rename 成功不够:两个实例可能先后读到同一个旧 owner,A 先回收旧锁并重建,- // B 随后的 rename 仍会成功——掣走的是 A 的新锁(活锁)。所以挪走后必须校验- // stale 内容:不是那个死 pid 就说明掣了别人的锁,立即放回并放弃本次落盘。- // 「只有 wx 成功才算拿到锁」的不变量保证 B 全程不会进入写入路径。- const stale = lockPath + '.stale-' + process.pid;- try { rmSync(stale, { force: true }); } catch { /* 上次没清掉的回收槽 */ }- try {- renameSync(lockPath, stale);- } catch {- return false; // 已被另一个实例回收或重建:不争,跳过本次落盘。- }- let stolen: number | undefined;- try {- const parsed = Number.parseInt(readFileSync(stale, 'utf8').trim(), 10);- stolen = Number.isInteger(parsed) && parsed > 0 ? parsed : undefined;- } catch {- stolen = undefined;- }- if (stolen !== owner) {- // 掣走的是别的实例刚建的活锁:放回去(若路径已被占用则丢弃掣走的副本——- // 路径上那个新锁才是有效的),本次不落盘。- try { renameSync(stale, lockPath); } catch { try { rmSync(stale, { force: true }); } catch { /* 忽略 */ } }- return false;- }- try { rmSync(stale, { force: true }); } catch { /* 残留回收槽不影响正确性 */ }- }+ // 1) 常规获取:wx 独占创建(锁路径无文件时)。+ try {+ // fd 只参与 wx 独占创建这一步;锁语义是文件存在性 + pid 内容,写完即可释放。+ const fd = openSync(lockPath, 'wx', 0o600);+ try { writeFileSync(lockPath, String(process.pid)); } catch { /* pid 写不进去时只当普通锁 */ }+ try { closeSync(fd); } catch { /* 关闭失败不影响已持有的锁 */ }+ return true;+ } catch { /* 锁已存在 → 走接管判定 */ }+ const owner = readLockOwner(lockPath);+ if (owner === undefined || owner === process.pid || isProcessAlive(owner)) return false;+ // 2) 死锁接管:用 tmp + rename **原子覆盖**锁文件,路径上的锁从不消失——+ // 「挪走再重建」会让锁路径短暂为空,第三个实例可以趁虚 wx 成功,与被挪走+ // 锁的原持有者同时写入;事后校验 pid 也救不回这个窗口。覆盖式 rename 串行+ // 执行,最后落盘者是唯一候选持有者;persistDisclosures 在写入前还会重读锁+ // 内容复核是自己 pid,被后来者覆盖的候选会放弃且不删锁。+ const takeover = lockPath + '.takeover-' + process.pid;+ try { rmSync(takeover, { force: true }); } catch { /* 上次残留的接管槽 */ }+ try {+ writeFileSync(takeover, String(process.pid), { flag: 'wx' });+ } catch {+ return false; // 接管槽被并发占用:不争。}- return false;+ try {+ renameSync(takeover, lockPath);+ } catch {+ try { rmSync(takeover, { force: true }); } catch { /* 忽略 */ }+ return false;+ }+ return true;}function readLockOwner(lockPath: string): number | undefined {@@ -3013,6 +3002,9 @@ class CindyMcpGateway {try {const lockPath = file + '.lock';if (!acquireDisclosureLock(lockPath)) return;+ // 候选持有者复核:接管式回收的覆盖 rename 可能被另一个接管者再覆盖。锁内容+ // 不是自己 pid 就说明已输掉接管竞态 —— 放弃本次落盘,且**不删锁**(那是赢家的)。+ if (readLockOwner(lockPath) !== process.pid) return;try {// 以**锁内读到的磁盘记录为基础**,只覆盖本次实际披露的那个键。整份内存记录// 优先会把另一个实例刚保存的新指纹改回本进程启动时载入的旧值:A 载入 X=f1,@@ -3038,7 +3030,11 @@ class CindyMcpGateway {writeFileSync(temp, JSON.stringify({ version: 1, entries: merged }), { mode: 0o600 });renameSync(temp, file);} finally {- try { rmSync(lockPath, { force: true }); } catch { /* 残留锁由下次写入回收 */ }+ // 只有确认仍持有(内容是本进程 pid)才释放:被接管者覆盖后删锁会把+ // 赢家的锁一起删掉。+ if (readLockOwner(lockPath) === process.pid) {+ try { rmSync(lockPath, { force: true }); } catch { /* 残留锁由下次写入回收 */ }+ }}} catch {// 落盘失败只影响下次启动的体验,不影响本次门与自愈。