Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): 按启动代次回收残留 schema transition gate

DavidShen0b861b349683
diff --git a/apps/desktop/src/main/localDb/__tests__/fixtures/schemaLeaseChild.ts b/apps/desktop/src/main/localDb/__tests__/fixtures/schemaLeaseChild.ts
index c1e038e5d5..5580fb311e 100644
--- a/apps/desktop/src/main/localDb/__tests__/fixtures/schemaLeaseChild.ts
+++ b/apps/desktop/src/main/localDb/__tests__/fixtures/schemaLeaseChild.ts
@@ -1,8 +1,21 @@
-import {
+import fs from 'node:fs';
+import Module, { createRequire } from 'node:module';
+
+// Bootstrap the child with the parent's simulated boot generation. Keep real
+// filesystem/process leases without repeatedly launching OS probes per child.
+// Install this one dependency before loading the production lease module once.
+const fixtureRequire = createRequire(__filename);
+const bootModulePath = fixtureRequire.resolve('../../schemaMigrationBootIdentity');
+const bootModule = new Module(bootModulePath);
+bootModule.exports = {
+ readSchemaMigrationBootIdentity: async () => 'test:11111111-1111-1111-1111-111111111111',
+};
+bootModule.loaded = true;
+fixtureRequire.cache[bootModulePath] = bootModule;
+const {
acquireSchemaMigrationReaderLease,
acquireSchemaMigrationWriterLease,
-} from '../../schemaMigrationLease';
-import fs from 'node:fs';
+}: typeof import('../../schemaMigrationLease') = fixtureRequire('../../schemaMigrationLease');
const [dbFilePath, kind, mode] = process.argv.slice(2);
if (!dbFilePath || (kind !== 'reader' && kind !== 'writer')) {
diff --git a/apps/desktop/src/main/localDb/__tests__/schemaMigrationLease.test.ts b/apps/desktop/src/main/localDb/__tests__/schemaMigrationLease.test.ts
index c71c28640f..af4c1f134a 100644
--- a/apps/desktop/src/main/localDb/__tests__/schemaMigrationLease.test.ts
+++ b/apps/desktop/src/main/localDb/__tests__/schemaMigrationLease.test.ts
@@ -319,6 +319,56 @@ describe('schema migration lease', () => {
});
});
+ // PR #7146 / unit: crash leftovers were tested only with dead PIDs. A reboot
+ // can reuse the PID; compare boot generations without weakening live-owner exclusion.
+ it.each([
+ { name: 'same boot', published: 'boot-a', current: 'boot-a', acquired: false },
+ {
+ name: 'previous boot with reused live PID',
+ published: 'boot-a',
+ current: 'boot-b',
+ acquired: true,
+ },
+ { name: 'unavailable current boot', published: 'boot-a', current: null, acquired: false },
+ {
+ name: 'legacy marker without boot evidence',
+ published: null,
+ current: 'boot-b',
+ acquired: false,
+ },
+ ])('handles a gate from $name', async ({ published, current, acquired }) => {
+ const filePath = dbPath();
+ const gate = `${filePath}.schema-transition`;
+ boot.id = published;
+ const rename = fs.renameSync;
+ // Leave the real published gate behind, before acquiring any schema lease.
+ const interrupted = vi.spyOn(fs, 'renameSync').mockImplementationOnce((from, to) => {
+ rename(from, to);
+ throw Object.assign(new Error('interrupted after gate publication'), { code: 'EIO' });
+ });
+ expect(await acquireSchemaMigrationWriterLease(filePath)).toEqual({
+ acquired: false,
+ reason: 'recovery-busy',
+ });
+ interrupted.mockRestore();
+ const originalMarker = fs.readdirSync(gate);
+ // process.pid remains alive: only evidence of another boot may reclaim it.
+ boot.id = current;
+ const result = await acquireSchemaMigrationWriterLease(filePath);
+ if (acquired) {
+ hold(result);
+ expect(fs.existsSync(gate)).toBe(false);
+ expect(await acquireSchemaMigrationReaderLease(filePath)).toEqual({
+ acquired: false,
+ reason: 'writer-active',
+ });
+ } else {
+ expect(result).toEqual({ acquired: false, reason: 'recovery-busy' });
+ expect(fs.readdirSync(gate)).toEqual(originalMarker);
+ expect(fs.existsSync(`${filePath}.schema-writer.lock`)).toBe(false);
+ }
+ });
+
it('does not remove a successor when another reclaimer wins the dead-gate race', async () => {
const filePath = dbPath();
const gate = `${filePath}.schema-transition`;
diff --git a/apps/desktop/src/main/localDb/schemaMigrationLease.ts b/apps/desktop/src/main/localDb/schemaMigrationLease.ts
index 4a2bfb4eaf..1885fe1a57 100644
--- a/apps/desktop/src/main/localDb/schemaMigrationLease.ts
+++ b/apps/desktop/src/main/localDb/schemaMigrationLease.ts
@@ -301,7 +301,11 @@ async function withLeaseTransition(
task: () => Promise<AcquireSchemaMigrationLeaseResult>,
): Promise<AcquireSchemaMigrationLeaseResult> {
const gate = `${dbFilePath}.schema-transition`;
- const marker = `owner-${process.pid}-${crypto.randomUUID()}`;
+ // Put the boot generation in the immutable directory entry, not mutable JSON.
+ // A live PID in another boot cannot belong to the crashed gate publisher.
+ const boot = await readSchemaMigrationBootIdentity();
+ const bootTag = boot ? crypto.createHash('sha256').update(boot).digest('hex') : null;
+ const marker = `owner-${process.pid}-${crypto.randomUUID()}${bootTag ? `-boot-${bootTag}` : ''}`;
const candidate = `${gate}.${marker}.candidate`;
let held = false;
try {
@@ -327,9 +331,12 @@ async function withLeaseTransition(
throw readError;
}
if (entries.length > 0) {
- const owner = entries.length === 1 && /^owner-([1-9]\d*)-[a-f0-9-]{36}$/.exec(entries[0]);
+ const owner =
+ entries.length === 1 &&
+ /^owner-([1-9]\d*)-[a-f0-9-]{36}(?:-boot-([a-f0-9]{64}))?$/.exec(entries[0]);
if (!owner) return { acquired: false, reason: 'lock-unreadable' };
- if (isProcessAlive(Number(owner[1]))) {
+ const fromPreviousBoot = Boolean(bootTag && owner[2] && owner[2] !== bootTag);
+ if (!fromPreviousBoot && isProcessAlive(Number(owner[1]))) {
return { acquired: false, reason: 'recovery-busy' };
}
// Only unlink this unique dead owner's marker. A delayed reclaimer
diff --git a/docs/dev-rules/database-and-migrations.md b/docs/dev-rules/database-and-migrations.md
index 5adcbdb9d1..91bf29d029 100644
--- a/docs/dev-rules/database-and-migrations.md
+++ b/docs/dev-rules/database-and-migrations.md
@@ -119,10 +119,12 @@ companion CommonJS 格式和历史 runtime identity 冻结;不能用单独 typ
明确阻断,不回退到直接写半成品锁。租约获取为异步,退出/切账号必须取消在途 reader。
同一数据库的新版租约获取与回收通过原子发布的非空目录串行化:候选目录先包含唯一
-PID+UUID 文件名,再 rename 到正式 gate。释放/回收只删该 owner 的精确 marker,
+PID+UUID 文件名及可信内核启动代次的摘要,再 rename 到正式 gate。不同启动代次的
+残留 gate 可回收,即使旧 PID 已被其他进程复用;同一代次、旧格式 marker 或无法取得
+当前启动代次时,继续保守检查 PID。释放/回收只删该 owner 的精确 marker,
再非递归 rmdir;暂停的清理者不能删除后继 owner 的非空目录。中断释放留下的空目录可
-重试回收,不引入会被原地写坏的辅助 JSON 锁。有效存活 PID 不回收,不可读文件不当作
-损坏记录移走。
+重试回收,不引入会被原地写坏的辅助 JSON 锁。未证实跨启动的存活 PID 不回收,不可读文件
+不当作损坏记录移走。
损坏且未知 owner 的记录可能是暂停中的旧版发布者,因此不得按文件年龄或解析失败抢锁。
首次观察时持久化文件身份/内容指纹和内核 boot generation;只有之后确认系统已跨过一次
启动、且原锁指纹未变,才备份隔离它。应用重启、时间跳变、文件被替换都不授予恢复权限。