Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 修复损坏数据库维护锁导致的启动阻塞 #7135
DavidShen2c2ae844b819
diff --git a/apps/desktop/src/main/localDb/__tests__/fatalDialogPolicy.test.ts b/apps/desktop/src/main/localDb/__tests__/fatalDialogPolicy.test.tsindex 23f589bdb0..7521a86b2e 100644--- a/apps/desktop/src/main/localDb/__tests__/fatalDialogPolicy.test.ts+++ b/apps/desktop/src/main/localDb/__tests__/fatalDialogPolicy.test.ts@@ -7,6 +7,10 @@ describe('shouldShowNativeFatalDialog', () => {expect(shouldShowNativeFatalDialog('MIGRATE_FAILED')).toBe(false);});+ it('keeps schema lease failures on the retry screen without a blocking native dialog (#7135)', () => {+ expect(shouldShowNativeFatalDialog('DB_SCHEMA_LOCKED')).toBe(false);+ });+it('其余错误码维持原生对话框语义', () => {expect(shouldShowNativeFatalDialog('DB_INIT_FAILED')).toBe(true);expect(shouldShowNativeFatalDialog('DB_CORRUPT_NO_BACKUP')).toBe(true);diff --git a/apps/desktop/src/main/localDb/__tests__/fixtures/schemaLeaseChild.ts b/apps/desktop/src/main/localDb/__tests__/fixtures/schemaLeaseChild.tsindex 630eeff8a8..c1e038e5d5 100644--- a/apps/desktop/src/main/localDb/__tests__/fixtures/schemaLeaseChild.ts+++ b/apps/desktop/src/main/localDb/__tests__/fixtures/schemaLeaseChild.ts@@ -2,25 +2,59 @@ import {acquireSchemaMigrationReaderLease,acquireSchemaMigrationWriterLease,} from '../../schemaMigrationLease';+import fs from 'node:fs';-const [dbFilePath, kind] = process.argv.slice(2);+const [dbFilePath, kind, mode] = process.argv.slice(2);if (!dbFilePath || (kind !== 'reader' && kind !== 'writer')) {throw new Error('usage: schemaLeaseChild <db-path> <reader|writer>');}-const result =- kind === 'reader'- ? acquireSchemaMigrationReaderLease(dbFilePath)- : acquireSchemaMigrationWriterLease(dbFilePath);-if (!result.acquired) {- process.send?.({ type: 'failed', reason: result.reason });- process.exit(2);-}+async function main() {+ if (mode === 'compete') {+ await new Promise<void>((resolve) => {+ process.once('message', () => resolve());+ process.send?.({ type: 'prepared' });+ });+ }+ if (mode === 'crash-after-gate-publish') {+ const rename = fs.renameSync;+ fs.renameSync = (from, to) => {+ rename(from, to);+ if (to === `${dbFilePath}.schema-transition`) process.exit(17);+ };+ }+ if (mode === 'crash-during-gate-release') {+ const rmdir = fs.rmdirSync;+ fs.rmdirSync = (directory) => {+ if (directory === `${dbFilePath}.schema-transition`) process.exit(17);+ rmdir(directory);+ };+ }+ if (mode === 'crash-before-publish' || mode === 'crash-after-publish') {+ const link = fs.linkSync;+ fs.linkSync = (from, to) => {+ if (to === `${dbFilePath}.schema-writer.lock`) {+ if (mode === 'crash-after-publish') link(from, to);+ process.exit(17);+ }+ link(from, to);+ };+ }+ const result =+ kind === 'reader'+ ? await acquireSchemaMigrationReaderLease(dbFilePath)+ : await acquireSchemaMigrationWriterLease(dbFilePath);+ if (!result.acquired) {+ process.send?.({ type: 'failed', reason: result.reason });+ process.exit(2);+ }-process.send?.({ type: 'ready', kind });-process.on('message', (message) => {- if (message !== 'release') return;- result.lease.release();- process.exit(0);-});-setInterval(() => undefined, 60_000);+ process.send?.({ type: 'ready', kind });+ process.on('message', (message) => {+ if (message !== 'release') return;+ result.lease.release();+ process.exit(0);+ });+ setInterval(() => undefined, 60_000);+}+void main();diff --git a/apps/desktop/src/main/localDb/__tests__/schemaLeaseTakeoverWiring.test.ts b/apps/desktop/src/main/localDb/__tests__/schemaLeaseTakeoverWiring.test.tsindex 337aeb653d..ac4ffbcdc1 100644--- a/apps/desktop/src/main/localDb/__tests__/schemaLeaseTakeoverWiring.test.ts+++ b/apps/desktop/src/main/localDb/__tests__/schemaLeaseTakeoverWiring.test.ts@@ -10,7 +10,24 @@ import {} from '../schemaMigrationLease';describe('shared-passive schema lease worker takeover wiring', () => {- it('wires worker takeover to the preserve-lease close mode', () => {+ // #7135: acquisition is async; logout must also cancel an in-flight reader.+ it('releases a reader acquired after its lifecycle was closed', async () => {+ const dir = mkdtempSync(path.join(tmpdir(), 'cindy-schema-takeover-'));+ const dbFilePath = path.join(dir, 'shared.db');+ const lifecycle = new SchemaMigrationReaderLeaseLifecycle();+ try {+ const pending = lifecycle.ensure(dbFilePath);+ lifecycle.release();+ expect(await pending).toEqual({ acquired: false, reason: 'recovery-busy' });+ const writer = await acquireSchemaMigrationWriterLease(dbFilePath);+ expect(writer.acquired).toBe(true);+ if (writer.acquired) writer.lease.release();+ } finally {+ lifecycle.release();+ rmSync(dir, { recursive: true, force: true });+ }+ });+ it('wires worker takeover to the preserve-lease close mode', async () => {const bootstrap = readFileSync(path.resolve(__dirname, '..', '..', 'bootstrap-electron.ts'),'utf8',@@ -26,28 +43,26 @@ describe('shared-passive schema lease worker takeover wiring', () => {expect(unchangedGuard).toBeGreaterThanOrEqual(0);expect(unchangedReturn).toBeGreaterThan(unchangedGuard);expect(takeoverStart).toBeGreaterThan(unchangedReturn);- expect(takeoverBlock).toContain(- 'localDbCloseDb({ preserveSchemaMigrationLease: true })',- );+ expect(takeoverBlock).toContain('localDbCloseDb({ preserveSchemaMigrationLease: true })');});- it('preserves the real lease across takeover close and releases it on logout/quit close', () => {+ it('preserves the real lease across takeover close and releases it on logout/quit close', async () => {const dir = mkdtempSync(path.join(tmpdir(), 'cindy-schema-takeover-'));const dbFilePath = path.join(dir, 'shared.db');const lifecycle = new SchemaMigrationReaderLeaseLifecycle();try {- expect(lifecycle.ensure(dbFilePath)).toEqual({ acquired: true, newlyAcquired: true });+ expect(await lifecycle.ensure(dbFilePath)).toEqual({ acquired: true, newlyAcquired: true });// worker takeover:main connection closes, worker remains on the DB, writer must stay blocked.lifecycle.closeConnection(true);- expect(acquireSchemaMigrationWriterLease(dbFilePath)).toMatchObject({+ expect(await acquireSchemaMigrationWriterLease(dbFilePath)).toMatchObject({acquired: false,reason: 'readers-active',});// logout / account switch / app quit:the actual DB lifecycle ends, writer may proceed.lifecycle.closeConnection(false);- const writer = acquireSchemaMigrationWriterLease(dbFilePath);+ const writer = await acquireSchemaMigrationWriterLease(dbFilePath);expect(writer.acquired).toBe(true);if (!writer.acquired) throw new Error(writer.reason);writer.lease.release();@@ -57,17 +72,17 @@ describe('shared-passive schema lease worker takeover wiring', () => {}});- it('packaged fallback acquires a reader and does not acquire a writer', () => {+ it('packaged fallback acquires a reader and does not acquire a writer', async () => {const dir = mkdtempSync(path.join(tmpdir(), 'cindy-schema-packaged-fallback-'));const dbFilePath = path.join(dir, 'shared.db');const passiveLifecycle = new SchemaMigrationReaderLeaseLifecycle();const packagedLifecycle = new SchemaMigrationReaderLeaseLifecycle();try {- expect(passiveLifecycle.ensure(dbFilePath)).toEqual({+ expect(await passiveLifecycle.ensure(dbFilePath)).toEqual({acquired: true,newlyAcquired: true,});- const result = acquireSchemaStartupLease({+ const result = await acquireSchemaStartupLease({dbFilePath,packaged: true,sharedPassive: false,@@ -76,13 +91,13 @@ describe('shared-passive schema lease worker takeover wiring', () => {expect(result.acquired).toBe(true);if (!result.acquired) throw new Error(result.reason);expect(result.kind).toBe('reader');- expect(acquireSchemaMigrationWriterLease(dbFilePath)).toMatchObject({+ expect(await acquireSchemaMigrationWriterLease(dbFilePath)).toMatchObject({acquired: false,reason: 'readers-active',activeReaderCount: 2,});result.lease.release();- expect(acquireSchemaMigrationWriterLease(dbFilePath)).toMatchObject({+ expect(await acquireSchemaMigrationWriterLease(dbFilePath)).toMatchObject({acquired: false,reason: 'readers-active',activeReaderCount: 1,@@ -93,21 +108,21 @@ describe('shared-passive schema lease worker takeover wiring', () => {rmSync(dir, { recursive: true, force: true });}});- it('allows another reader to join while preserving writer exclusion', () => {+ it('allows another reader to join while preserving writer exclusion', async () => {const dir = mkdtempSync(path.join(tmpdir(), 'cindy-schema-packaged-reader-'));const dbFilePath = path.join(dir, 'shared.db');const passiveLifecycle = new SchemaMigrationReaderLeaseLifecycle();const packagedLifecycle = new SchemaMigrationReaderLeaseLifecycle();try {- expect(passiveLifecycle.ensure(dbFilePath)).toEqual({+ expect(await passiveLifecycle.ensure(dbFilePath)).toEqual({acquired: true,newlyAcquired: true,});- expect(packagedLifecycle.ensure(dbFilePath)).toEqual({+ expect(await packagedLifecycle.ensure(dbFilePath)).toEqual({acquired: true,newlyAcquired: true,});- expect(acquireSchemaMigrationWriterLease(dbFilePath)).toMatchObject({+ expect(await acquireSchemaMigrationWriterLease(dbFilePath)).toMatchObject({acquired: false,reason: 'readers-active',activeReaderCount: 2,diff --git a/apps/desktop/src/main/localDb/__tests__/schemaMigrationLease.test.ts b/apps/desktop/src/main/localDb/__tests__/schemaMigrationLease.test.tsindex 42210c67e7..c71c28640f 100644--- a/apps/desktop/src/main/localDb/__tests__/schemaMigrationLease.test.ts+++ b/apps/desktop/src/main/localDb/__tests__/schemaMigrationLease.test.ts@@ -1,8 +1,15 @@import { fork, type ChildProcess } from 'node:child_process';-import { mkdtempSync, rmSync } from 'node:fs';+import fs, { mkdtempSync, rmSync } from 'node:fs';import { tmpdir } from 'node:os';import path from 'node:path';-import { afterEach, describe, expect, it } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const boot = vi.hoisted(() => ({+ id: 'test:11111111-1111-1111-1111-111111111111' as string | null,+}));+vi.mock('../schemaMigrationBootIdentity', () => ({+ readSchemaMigrationBootIdentity: async () => boot.id,+}));import {acquireSchemaMigrationReaderLease,@@ -14,7 +21,12 @@ const cleanupDirs: string[] = [];const leases: SchemaMigrationLease[] = [];const children: ChildProcess[] = [];+beforeEach(() => {+ boot.id = 'test:11111111-1111-1111-1111-111111111111';+});+afterEach(async () => {+ vi.restoreAllMocks();await Promise.all(children.splice(0).map(stopChild));for (const lease of leases.splice(0).reverse()) lease.release();for (const dir of cleanupDirs.splice(0)) rmSync(dir, { recursive: true, force: true });@@ -66,7 +78,9 @@ async function waitForExit(child: ChildProcess): Promise<void> {await new Promise<void>((resolve) => child.once('exit', () => resolve()));}-function hold(result: ReturnType<typeof acquireSchemaMigrationReaderLease>): SchemaMigrationLease {+function hold(+ result: Awaited<ReturnType<typeof acquireSchemaMigrationReaderLease>>,+): SchemaMigrationLease {expect(result.acquired).toBe(true);if (!result.acquired) throw new Error(result.reason);leases.push(result.lease);@@ -74,61 +88,368 @@ function hold(result: ReturnType<typeof acquireSchemaMigrationReaderLease>): Sch}describe('schema migration lease', () => {- it('allows arbitrary reader owners and rejects a writer until every reader exits', () => {+ // #7135 / unit: real acquisition APIs and files. Existing coverage only exercised+ // valid owners. Empty/corrupt records, interrupted publication and competing+ // recovery must preserve exclusion and the account DB, without time-based takeover.+ it.each(['', '{', '{}'])(+ 'preserves malformed lock %j until an observed reboot, then backs it up',+ async (bytes) => {+ const filePath = dbPath();+ fs.writeFileSync(filePath, 'account data sentinel');+ const lock = `${filePath}.schema-writer.lock`;+ fs.writeFileSync(lock, bytes);+ fs.utimesSync(lock, new Date(0), new Date(0));+ expect(await acquireSchemaMigrationWriterLease(filePath)).toEqual({+ acquired: false,+ reason: 'lock-corrupt',+ });+ // A second application start within the same OS boot is not recovery authority.+ expect(await acquireSchemaMigrationWriterLease(filePath)).toEqual({+ acquired: false,+ reason: 'lock-corrupt',+ });+ expect(fs.readFileSync(lock, 'utf8')).toBe(bytes);+ boot.id = 'test:22222222-2222-2222-2222-222222222222';+ hold(await acquireSchemaMigrationWriterLease(filePath));+ const backups = fs+ .readdirSync(path.dirname(filePath))+ .filter((name) => name.includes('.schema-lease-backup-'));+ expect(backups).toHaveLength(1);+ expect(fs.readFileSync(path.join(path.dirname(filePath), backups[0]), 'utf8')).toBe(bytes);+ expect(fs.readFileSync(filePath, 'utf8')).toBe('account data sentinel');+ },+ );++ it('does not reuse reboot evidence after a lock changes or when boot identity is unavailable', async () => {+ const filePath = dbPath();+ const lock = `${filePath}.schema-writer.lock`;+ fs.writeFileSync(lock, '{');+ await acquireSchemaMigrationWriterLease(filePath);+ boot.id = 'test:22222222-2222-2222-2222-222222222222';+ fs.writeFileSync(lock, '{"pid":');+ expect(await acquireSchemaMigrationWriterLease(filePath)).toMatchObject({+ acquired: false,+ reason: 'lock-corrupt',+ });+ boot.id = null;+ expect(await acquireSchemaMigrationWriterLease(filePath)).toMatchObject({+ acquired: false,+ reason: 'lock-corrupt',+ });+ expect(fs.readFileSync(lock, 'utf8')).toBe('{"pid":');+ });++ it('distinguishes unreadable locks and never quarantines them', async () => {+ const filePath = dbPath();+ const lock = `${filePath}.schema-writer.lock`;+ fs.writeFileSync(lock, '{');+ vi.spyOn(fs, 'lstatSync').mockImplementationOnce(() => {+ throw Object.assign(new Error('fixture access denied'), { code: 'EACCES' });+ });+ expect(await acquireSchemaMigrationWriterLease(filePath)).toEqual({+ acquired: false,+ reason: 'lock-unreadable',+ });+ expect(fs.readFileSync(lock, 'utf8')).toBe('{');+ expect(fs.readdirSync(path.dirname(filePath))).toEqual([path.basename(lock)]);+ });++ it('leaves the canonical path absent after a failed candidate flush and permits a retry', async () => {+ const filePath = dbPath();+ vi.spyOn(fs, 'fsyncSync').mockImplementationOnce(() => {+ throw Object.assign(new Error('injected publication failure'), { code: 'EIO' });+ });+ expect(await acquireSchemaMigrationWriterLease(filePath)).toEqual({+ acquired: false,+ reason: 'lock-unreadable',+ });+ expect(fs.existsSync(`${filePath}.schema-writer.lock`)).toBe(false);+ expect(fs.readdirSync(path.dirname(filePath))).toEqual([]);+ hold(await acquireSchemaMigrationWriterLease(filePath));+ });++ it.each([+ 'crash-before-publish',+ 'crash-after-publish',+ 'crash-after-gate-publish',+ 'crash-during-gate-release',+ ])('recovers after a publisher exits at %s', async (mode) => {+ const filePath = dbPath();+ const child = fork(+ path.join(__dirname, 'fixtures', 'schemaLeaseChild.ts'),+ [filePath, 'writer', mode],+ {+ execArgv: ['--import', 'tsx'],+ stdio: ['ignore', 'ignore', 'ignore', 'ipc'],+ },+ );+ children.push(child);+ await waitForExit(child);+ expect(child.exitCode).toBe(17);+ expect(fs.existsSync(`${filePath}.schema-writer.lock`)).toBe(+ mode === 'crash-after-publish' || mode === 'crash-during-gate-release',+ );+ hold(await acquireSchemaMigrationWriterLease(filePath));+ expect(await acquireSchemaMigrationReaderLease(filePath)).toMatchObject({+ acquired: false,+ reason: 'writer-active',+ });+ });++ it('allows exactly one competing recovery to acquire a writer and keeps a single backup', async () => {+ const filePath = dbPath();+ fs.writeFileSync(`${filePath}.schema-writer.lock`, '{');+ await acquireSchemaMigrationWriterLease(filePath);+ boot.id = 'test:22222222-2222-2222-2222-222222222222';+ const results = await Promise.all([+ acquireSchemaMigrationWriterLease(filePath),+ acquireSchemaMigrationWriterLease(filePath),+ ]);+ expect(results.filter((result) => result.acquired)).toHaveLength(1);+ for (const result of results) if (result.acquired) leases.push(result.lease);+ expect(results.find((result) => !result.acquired)).toMatchObject({ reason: 'recovery-busy' });+ expect(+ fs+ .readdirSync(path.dirname(filePath))+ .filter((name) => name.includes('.schema-lease-backup-')),+ ).toHaveLength(1);+ expect(await acquireSchemaMigrationReaderLease(filePath)).toEqual({+ acquired: false,+ reason: 'writer-active',+ });+ });++ it('can retry after isolation was interrupted, retaining the original corrupt bytes', async () => {+ const filePath = dbPath();+ const lock = `${filePath}.schema-writer.lock`;+ fs.writeFileSync(lock, '{');+ await acquireSchemaMigrationWriterLease(filePath);+ boot.id = 'test:22222222-2222-2222-2222-222222222222';+ const original = fs.renameSync;+ vi.spyOn(fs, 'renameSync').mockImplementation((from, to) => {+ original(from, to);+ if (from === lock) {+ throw Object.assign(new Error('injected interruption after isolation'), { code: 'EIO' });+ }+ });+ expect(await acquireSchemaMigrationWriterLease(filePath)).toMatchObject({ acquired: false });+ hold(await acquireSchemaMigrationWriterLease(filePath));+ const backup = fs+ .readdirSync(path.dirname(filePath))+ .find((name) => name.includes('.schema-lease-backup-'))!;+ expect(fs.readFileSync(path.join(path.dirname(filePath), backup), 'utf8')).toBe('{');+ });++ it('refuses a writer and restores a legacy live owner replaced during isolation', async () => {+ const filePath = dbPath();+ const lock = `${filePath}.schema-writer.lock`;+ fs.writeFileSync(lock, '{');+ await acquireSchemaMigrationWriterLease(filePath);+ boot.id = 'test:22222222-2222-2222-2222-222222222222';+ const legacy = JSON.stringify({+ pid: process.pid,+ token: 'legacy-live-owner',+ createdAt: new Date().toISOString(),+ });+ const rename = fs.renameSync;+ vi.spyOn(fs, 'renameSync').mockImplementation((from, to) => {+ if (from === lock) {+ fs.unlinkSync(lock);+ fs.writeFileSync(lock, legacy, { flag: 'wx' });+ }+ rename(from, to);+ });+ expect(await acquireSchemaMigrationWriterLease(filePath)).toEqual({+ acquired: false,+ reason: 'recovery-busy',+ });+ expect(fs.readFileSync(lock, 'utf8')).toBe(legacy);+ expect(await acquireSchemaMigrationReaderLease(filePath)).toMatchObject({+ acquired: false,+ reason: 'writer-active',+ });+ });++ it('recovers a corrupt reader without leaving a backup inside the reader directory', async () => {+ const filePath = dbPath();+ const readers = `${filePath}.schema-readers`;+ fs.mkdirSync(readers);+ fs.writeFileSync(path.join(readers, 'legacy.json'), '{');+ expect(await acquireSchemaMigrationWriterLease(filePath)).toMatchObject({+ acquired: false,+ reason: 'lock-corrupt',+ });+ expect(fs.existsSync(`${filePath}.schema-writer.lock`)).toBe(false);+ boot.id = 'test:22222222-2222-2222-2222-222222222222';+ hold(await acquireSchemaMigrationWriterLease(filePath));+ expect(fs.readdirSync(readers)).toEqual([]);+ });++ it('keeps a live gate despite damaged marker bytes and never removes a successor during release', async () => {+ const filePath = dbPath();+ const gate = `${filePath}.schema-transition`;+ const marker = `owner-${process.pid}-00000000-0000-0000-0000-000000000000`;+ fs.mkdirSync(gate);+ fs.writeFileSync(path.join(gate, marker), '{');+ expect(await acquireSchemaMigrationWriterLease(filePath)).toEqual({+ acquired: false,+ reason: 'recovery-busy',+ });+ fs.unlinkSync(path.join(gate, marker));+ fs.rmdirSync(gate);+ const rmdir = fs.rmdirSync;+ let replaced = false;+ vi.spyOn(fs, 'rmdirSync').mockImplementation((directory) => {+ if (directory === gate && !replaced) {+ // Pause releaser after its marker is gone. A successor publishes a full+ // gate before the releaser's final rmdir resumes.+ replaced = true;+ rmdir(gate);+ fs.mkdirSync(gate);+ fs.writeFileSync(path.join(gate, marker), '');+ }+ rmdir(directory);+ });+ const writer = hold(await acquireSchemaMigrationWriterLease(filePath));+ expect(fs.readdirSync(gate)).toEqual([marker]);+ writer.release();+ expect(await acquireSchemaMigrationReaderLease(filePath)).toEqual({+ acquired: false,+ reason: 'recovery-busy',+ });+ });++ it('does not remove a successor when another reclaimer wins the dead-gate race', async () => {+ const filePath = dbPath();+ const gate = `${filePath}.schema-transition`;+ const deadMarker = 'owner-2147483647-00000000-0000-0000-0000-000000000000';+ const liveMarker = `owner-${process.pid}-11111111-1111-1111-1111-111111111111`;+ fs.mkdirSync(gate);+ fs.writeFileSync(path.join(gate, deadMarker), '');+ vi.spyOn(process, 'kill').mockImplementationOnce(() => {+ throw Object.assign(new Error('dead fixture process'), { code: 'ESRCH' });+ });+ const unlink = fs.unlinkSync;+ vi.spyOn(fs, 'unlinkSync').mockImplementation((file) => {+ if (file === path.join(gate, deadMarker)) {+ unlink(file);+ fs.rmdirSync(gate);+ fs.mkdirSync(gate);+ fs.writeFileSync(path.join(gate, liveMarker), '');+ }+ unlink(file);+ });+ expect(await acquireSchemaMigrationWriterLease(filePath)).toEqual({+ acquired: false,+ reason: 'recovery-busy',+ });+ expect(fs.readdirSync(gate)).toEqual([liveMarker]);+ expect(fs.existsSync(`${filePath}.schema-writer.lock`)).toBe(false);+ });++ it('grants only one writer when separate processes recover the same dead owner', async () => {+ const filePath = dbPath();+ const previous = await startChild(filePath, 'writer');+ previous.kill('SIGKILL');+ await waitForExit(previous);+ const contenders = [0, 1].map(() => {+ const child = fork(+ path.join(__dirname, 'fixtures', 'schemaLeaseChild.ts'),+ [filePath, 'writer', 'compete'],+ {+ execArgv: ['--import', 'tsx'],+ stdio: ['ignore', 'ignore', 'ignore', 'ipc'],+ },+ );+ children.push(child);+ return child;+ });+ await Promise.all(+ contenders.map(+ (child) =>+ new Promise<void>((resolve, reject) => {+ child.once('error', reject);+ child.once('exit', (code) =>+ reject(new Error(`contender exited before barrier: ${code}`)),+ );+ child.once('message', () => resolve());+ }),+ ),+ );+ const outcomes = contenders.map(+ (child) =>+ new Promise<string>((resolve, reject) => {+ child.once('error', reject);+ child.once('message', (message) => resolve((message as { type: string }).type));+ }),+ );+ for (const child of contenders) child.send('go');+ expect((await Promise.all(outcomes)).sort()).toEqual(['failed', 'ready']);+ expect(await acquireSchemaMigrationReaderLease(filePath)).toMatchObject({+ acquired: false,+ reason: 'writer-active',+ });+ expect(+ fs+ .readdirSync(path.dirname(filePath))+ .filter((name) => name.includes('.schema-lease-backup-')),+ ).toHaveLength(1);+ });+ it('allows arbitrary reader owners and rejects a writer until every reader exits', async () => {const filePath = dbPath();- const first = hold(acquireSchemaMigrationReaderLease(filePath));- const second = hold(acquireSchemaMigrationReaderLease(filePath));+ const first = hold(await acquireSchemaMigrationReaderLease(filePath));+ const second = hold(await acquireSchemaMigrationReaderLease(filePath));- expect(acquireSchemaMigrationWriterLease(filePath)).toMatchObject({+ expect(await acquireSchemaMigrationWriterLease(filePath)).toMatchObject({acquired: false,reason: 'readers-active',activeReaderCount: 2,});first.release();- expect(acquireSchemaMigrationWriterLease(filePath)).toMatchObject({+ expect(await acquireSchemaMigrationWriterLease(filePath)).toMatchObject({acquired: false,reason: 'readers-active',activeReaderCount: 1,});second.release();- const writer = acquireSchemaMigrationWriterLease(filePath);+ const writer = await acquireSchemaMigrationWriterLease(filePath);expect(writer.acquired).toBe(true);if (!writer.acquired) throw new Error(writer.reason);leases.push(writer.lease);});- it('rejects readers while a writer is active and admits them after release', () => {+ it('rejects readers while a writer is active and admits them after release', async () => {const filePath = dbPath();- const writer = acquireSchemaMigrationWriterLease(filePath);+ const writer = await acquireSchemaMigrationWriterLease(filePath);expect(writer.acquired).toBe(true);if (!writer.acquired) throw new Error(writer.reason);leases.push(writer.lease);- expect(acquireSchemaMigrationReaderLease(filePath)).toEqual({+ expect(await acquireSchemaMigrationReaderLease(filePath)).toEqual({acquired: false,reason: 'writer-active',});writer.lease.release();- hold(acquireSchemaMigrationReaderLease(filePath));+ hold(await acquireSchemaMigrationReaderLease(filePath));});it('enforces reader/writer exclusion across processes', async () => {const filePath = dbPath();const reader = await startChild(filePath, 'reader');- expect(acquireSchemaMigrationWriterLease(filePath)).toMatchObject({+ expect(await acquireSchemaMigrationWriterLease(filePath)).toMatchObject({acquired: false,reason: 'readers-active',});await stopChild(reader);const writer = await startChild(filePath, 'writer');- expect(acquireSchemaMigrationReaderLease(filePath)).toEqual({+ expect(await acquireSchemaMigrationReaderLease(filePath)).toEqual({acquired: false,reason: 'writer-active',});await stopChild(writer);- hold(acquireSchemaMigrationReaderLease(filePath));+ hold(await acquireSchemaMigrationReaderLease(filePath));});it('reclaims a stale reader after its owner exits abnormally', async () => {@@ -137,7 +458,7 @@ describe('schema migration lease', () => {reader.kill('SIGKILL');await waitForExit(reader);- const writer = acquireSchemaMigrationWriterLease(filePath);+ const writer = await acquireSchemaMigrationWriterLease(filePath);expect(writer.acquired).toBe(true);if (!writer.acquired) throw new Error(writer.reason);leases.push(writer.lease);@@ -149,6 +470,6 @@ describe('schema migration lease', () => {writer.kill('SIGKILL');await waitForExit(writer);- hold(acquireSchemaMigrationReaderLease(filePath));+ hold(await acquireSchemaMigrationReaderLease(filePath));});});diff --git a/apps/desktop/src/main/localDb/fatalDialogPolicy.ts b/apps/desktop/src/main/localDb/fatalDialogPolicy.tsindex 1cacf10c82..5786bdb670 100644--- a/apps/desktop/src/main/localDb/fatalDialogPolicy.ts+++ b/apps/desktop/src/main/localDb/fatalDialogPolicy.ts@@ -13,9 +13,10 @@*//** ensureReady 失败结果的稳定错误码集合。 */-export type EnsureReadyErrorCode = 'DB_INIT_FAILED' | 'DB_CORRUPT_NO_BACKUP' | 'MIGRATE_FAILED';+export type EnsureReadyErrorCode =+ 'DB_INIT_FAILED' | 'DB_CORRUPT_NO_BACKUP' | 'MIGRATE_FAILED' | 'DB_SCHEMA_LOCKED';-/** MIGRATE_FAILED 由 renderer 全屏恢复界面接管 UX;其余 code 维持原生对话框。 */+/** 迁移失败与租约阻断由 renderer 恢复界面接管;其余 code 维持原生对话框。 */export function shouldShowNativeFatalDialog(code: EnsureReadyErrorCode): boolean {- return code !== 'MIGRATE_FAILED';+ return code !== 'MIGRATE_FAILED' && code !== 'DB_SCHEMA_LOCKED';}diff --git a/apps/desktop/src/main/localDb/index.ts b/apps/desktop/src/main/localDb/index.tsindex ad02b58536..02d46cfbc9 100644--- a/apps/desktop/src/main/localDb/index.ts+++ b/apps/desktop/src/main/localDb/index.ts@@ -166,27 +166,21 @@ export async function ensureReady(userId: string): Promise<EnsureReadyResult> {let startupWriterLease: SchemaMigrationLease | null = null;let readerLeaseAcquiredThisCall = false;- const startupLease = acquireSchemaStartupLease({+ const startupLease = await acquireSchemaStartupLease({dbFilePath: filePath,packaged: app.isPackaged,sharedPassive: passiveSharedUserData,readerLifecycle: schemaMigrationReaderLeaseLifecycle,});if (!startupLease.acquired) {- const readerHint = startupLease.activeReaderCount- ? `(当前有 ${startupLease.activeReaderCount} 个 passive 实例)`- : '';- const waitingForWriter = startupLease.reason === 'writer-active';- const message = waitingForWriter- ? '另一个实例正在执行数据库 schema migration,当前实例无法同时启动维护。请等待迁移完成后重试,或改用 --isolated 启动独立数据。'- : `当前不能执行数据库 schema 启动维护${readerHint}。` +- '请先关闭共享该 userData 的 passive dev 后重试,或让这些实例使用 --isolated。';+ const message = t(`localDbFatal.schemaLease.${startupLease.reason}`);+ log.warn(JSON.stringify({ event: 'localDb.schemaLease.blocked', reason: startupLease.reason }));showFatalDialog(- waitingForWriter ? '数据库 schema 正在维护' : '数据库 schema 正被其它实例使用',+ t('localDbFatal.schemaLease.title'),message,- 'MIGRATE_FAILED',+ 'DB_SCHEMA_LOCKED',);- return { ready: false, error: { code: 'MIGRATE_FAILED', message } };+ return { ready: false, error: { code: 'DB_SCHEMA_LOCKED', message } };}const schemaMaintenanceReadOnly = startupLease.kind === 'reader' && !passiveSharedUserData;readerLeaseAcquiredThisCall = startupLease.kind === 'reader' && startupLease.newlyAcquired;diff --git a/apps/desktop/src/main/localDb/schemaMigrationBootIdentity.ts b/apps/desktop/src/main/localDb/schemaMigrationBootIdentity.tsnew file mode 100644index 0000000000..bb4379bcb7--- /dev/null+++ b/apps/desktop/src/main/localDb/schemaMigrationBootIdentity.ts@@ -0,0 +1,84 @@+import { execFile } from 'node:child_process';+import fs from 'node:fs/promises';+import path from 'node:path';+import { promisify } from 'node:util';++const run = promisify(execFile);+let identity: string | undefined;+let pending: Promise<string | null> | undefined;++/** A kernel boot generation, never Date.now() - uptime (wall clocks can jump). */+export async function readSchemaMigrationBootIdentity(): Promise<string | null> {+ if (identity) return identity;+ if (pending) return pending;+ pending = probe()+ .then((value) => {+ if (value) identity = value;+ return value;+ })+ .finally(() => {+ pending = undefined;+ });+ return pending;+}++async function probe(): Promise<string | null> {+ try {+ let value: string;+ if (process.platform === 'linux') {+ value = await fs.readFile('/proc/sys/kernel/random/boot_id', 'utf8');+ } else if (process.platform === 'darwin') {+ value = (+ await run('/usr/sbin/sysctl', ['-n', 'kern.bootsessionuuid'], {+ timeout: 5_000,+ encoding: 'utf8',+ })+ ).stdout;+ } else if (process.platform === 'win32') {+ // SystemBootEnvironmentInformation (90) starts with the kernel's boot GUID.+ // Unlike a timestamp, this does not mistake a clock correction for a reboot.+ const script = `Add-Type -TypeDefinition @'+using System;+using System.Runtime.InteropServices;+public static class CindySchemaBootIdentity {+ [DllImport("ntdll.dll")]+ private static extern int NtQuerySystemInformation(int kind, IntPtr buffer, int size, out int returned);+ public static string Read() {+ IntPtr buffer = Marshal.AllocHGlobal(32);+ try {+ int returned;+ if (NtQuerySystemInformation(90, buffer, 32, out returned) != 0) return "";+ return Marshal.PtrToStructure<Guid>(buffer).ToString();+ } finally { Marshal.FreeHGlobal(buffer); }+ }+}+'@; [CindySchemaBootIdentity]::Read()`;+ value = (+ await run(+ path.join(+ process.env.SystemRoot ?? 'C:\\Windows',+ 'System32',+ 'WindowsPowerShell',+ 'v1.0',+ 'powershell.exe',+ ),+ ['-NoProfile', '-NonInteractive', '-Command', script],+ {+ timeout: 5_000,+ encoding: 'utf8',+ windowsHide: true,+ },+ )+ ).stdout;+ } else {+ return null;+ }+ const uuid = value.trim().toLowerCase();+ return /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/.test(uuid) &&+ uuid !== '00000000-0000-0000-0000-000000000000'+ ? `${process.platform}:${uuid}`+ : null;+ } catch {+ return null;+ }+}diff --git a/apps/desktop/src/main/localDb/schemaMigrationLease.ts b/apps/desktop/src/main/localDb/schemaMigrationLease.tsindex ceb9f629cf..4a2bfb4eaf 100644--- a/apps/desktop/src/main/localDb/schemaMigrationLease.ts+++ b/apps/desktop/src/main/localDb/schemaMigrationLease.ts@@ -9,6 +9,11 @@import crypto from 'node:crypto';import fs from 'node:fs';import path from 'node:path';+import { readBoundedFileNoFollowSync } from '../utils/readBoundedFile';+import { readSchemaMigrationBootIdentity } from './schemaMigrationBootIdentity';++export type SchemaLeaseFailureReason =+ 'writer-active' | 'readers-active' | 'lock-corrupt' | 'lock-unreadable' | 'recovery-busy';export interface SchemaMigrationLease {kind: 'reader' | 'writer';@@ -17,10 +22,11 @@ export interface SchemaMigrationLease {export type AcquireSchemaMigrationLeaseResult =| { acquired: true; lease: SchemaMigrationLease }- | { acquired: false; reason: 'writer-active' | 'readers-active'; activeReaderCount?: number };+ | { acquired: false; reason: SchemaLeaseFailureReason; activeReaderCount?: number };export type EnsureSchemaMigrationReaderLeaseResult =- { acquired: true; newlyAcquired: boolean } | { acquired: false; reason: 'writer-active' };+ | { acquired: true; newlyAcquired: boolean }+ | { acquired: false; reason: SchemaLeaseFailureReason };export type SchemaStartupLeaseResult =| {@@ -31,7 +37,7 @@ export type SchemaStartupLeaseResult =}| {acquired: false;- reason: 'writer-active' | 'readers-active';+ reason: SchemaLeaseFailureReason;activeReaderCount?: number;};@@ -47,12 +53,12 @@ export interface AcquireSchemaStartupLeaseOptions {* Packaged instances may join existing readers, but only as a reader; this keeps* the actual fallback branch small and directly testable without Electron.*/-export function acquireSchemaStartupLease(+export async function acquireSchemaStartupLease(options: AcquireSchemaStartupLeaseOptions,-): SchemaStartupLeaseResult {+): Promise<SchemaStartupLeaseResult> {const readerLifecycle = options.readerLifecycle ?? new SchemaMigrationReaderLeaseLifecycle();if (options.sharedPassive) {- const result = readerLifecycle.ensure(options.dbFilePath);+ const result = await readerLifecycle.ensure(options.dbFilePath);return result.acquired? {acquired: true,@@ -63,13 +69,13 @@ export function acquireSchemaStartupLease(: result;}- const writer = acquireSchemaMigrationWriterLease(options.dbFilePath);+ const writer = await acquireSchemaMigrationWriterLease(options.dbFilePath);if (writer.acquired) {return { acquired: true, kind: 'writer', lease: writer.lease, newlyAcquired: true };}if (!options.packaged || writer.reason !== 'readers-active') return writer;- const packagedReader = readerLifecycle.ensure(options.dbFilePath);+ const packagedReader = await readerLifecycle.ensure(options.dbFilePath);return packagedReader.acquired? {acquired: true,@@ -115,14 +121,18 @@ function isProcessAlive(pid: number): boolean {}}-function readOwner(filePath: string): LeaseOwner | null {+function parseOwner(bytes: Buffer): LeaseOwner | null {try {- const parsed = JSON.parse(fs.readFileSync(filePath, 'utf8')) as Partial<LeaseOwner>;+ const parsed = JSON.parse(bytes.toString('utf8')) as Partial<LeaseOwner> | null;if (+ !parsed ||typeof parsed.pid !== 'number' ||!Number.isSafeInteger(parsed.pid) ||+ parsed.pid <= 0 ||typeof parsed.token !== 'string' ||- typeof parsed.createdAt !== 'string'+ parsed.token.length === 0 ||+ typeof parsed.createdAt !== 'string' ||+ !Number.isFinite(Date.parse(parsed.createdAt))) {return null;}@@ -132,30 +142,229 @@ function readOwner(filePath: string): LeaseOwner | null {}}-function removeIfDead(filePath: string): boolean {- if (!fs.existsSync(filePath)) return true;- const owner = readOwner(filePath);- // 内容损坏时 fail closed,避免误删一个正在创建的租约。- if (!owner || isProcessAlive(owner.pid)) return false;+type RecordSnapshot =+ | { state: 'missing' | 'unreadable' }+ | {+ state: 'readable';+ owner: LeaseOwner | null;+ fingerprint: string;+ identity: string;+ bytes: Buffer;+ };++function sidecarPath(filePath: string, suffix: string): string {+ const parent = path.dirname(filePath);+ return path.basename(parent).endsWith('.schema-readers')+ ? path.join(+ path.dirname(parent),+ `${path.basename(parent)}.${path.basename(filePath)}${suffix}`,+ )+ : `${filePath}${suffix}`;+}++function readRecord(filePath: string): RecordSnapshot {try {- fs.unlinkSync(filePath);- return true;- } catch {- return !fs.existsSync(filePath);+ const before = fs.lstatSync(filePath, { bigint: true });+ const bytes = readBoundedFileNoFollowSync(filePath, 16 * 1024);+ const after = fs.lstatSync(filePath, { bigint: true });+ const identity = (stat: fs.BigIntStats) =>+ [stat.dev, stat.ino, stat.size, stat.mtimeNs, stat.ctimeNs, stat.birthtimeNs].join(':');+ if (!bytes || !before.isFile() || identity(before) !== identity(after)) {+ return { state: 'unreadable' };+ }+ return {+ state: 'readable',+ owner: parseOwner(bytes),+ bytes,+ // Rename may change ctime; these fields and the bytes must survive isolation.+ identity: [after.dev, after.ino, after.size, after.mtimeNs, after.birthtimeNs].join(':'),+ fingerprint: crypto.createHash('sha256').update(identity(after)).update(bytes).digest('hex'),+ };+ } catch (error) {+ return { state: (error as NodeJS.ErrnoException).code === 'ENOENT' ? 'missing' : 'unreadable' };}}+/** Flush a private candidate before publishing, without ever replacing an incumbent. */function writeOwnerExclusive(filePath: string, owner: LeaseOwner): boolean {+ // Reader candidates live outside the readers directory: old clients scan every entry there.+ const stagingPath = sidecarPath(filePath, `.candidate-${owner.pid}-${owner.token}`);+ let fd: number | undefined;try {- fs.writeFileSync(filePath, `${JSON.stringify(owner)}\n`, {- encoding: 'utf8',- flag: 'wx',- mode: 0o600,- });+ fd = fs.openSync(stagingPath, 'wx', 0o600);+ fs.writeFileSync(fd, `${JSON.stringify(owner)}\n`, 'utf8');+ fs.fsyncSync(fd);+ fs.closeSync(fd);+ fd = undefined;+ fs.linkSync(stagingPath, filePath);return true;} catch (err) {if ((err as NodeJS.ErrnoException).code === 'EEXIST') return false;throw err;+ } finally {+ if (fd !== undefined) fs.closeSync(fd);+ try {+ fs.unlinkSync(stagingPath);+ } catch {+ /* Private interrupted candidates never grant a lease. */+ }+ }+}++/** Called only under the per-database transition lock. No age-based takeover. */+async function clearInactiveRecord(filePath: string): Promise<SchemaLeaseFailureReason | null> {+ const record = readRecord(filePath);+ if (record.state === 'missing') return null;+ if (record.state !== 'readable') return 'lock-unreadable';+ const observationPath = sidecarPath(filePath, '.recovery-observation');+ if (record.owner) {+ if (isProcessAlive(record.owner.pid)) return 'writer-active';+ } else {+ const boot = await readSchemaMigrationBootIdentity();+ if (!boot) return 'lock-corrupt';+ let previous: { boot?: string; fingerprint?: string } | null = null;+ try {+ const bytes = readBoundedFileNoFollowSync(observationPath, 4096);+ previous = bytes ? JSON.parse(bytes.toString('utf8')) : null;+ } catch {+ /* An absent or unreadable observation is not recovery evidence. */+ }+ if (+ !previous ||+ typeof previous.boot !== 'string' ||+ previous.boot === boot ||+ previous.fingerprint !== record.fingerprint+ ) {+ // An unknown owner could be a suspended legacy publisher. Remember this exact+ // file and require a DIFFERENT kernel boot generation before isolating it.+ const candidate = `${observationPath}.${crypto.randomUUID()}.tmp`;+ let fd: number | undefined;+ try {+ fd = fs.openSync(candidate, 'wx', 0o600);+ fs.writeFileSync(fd, JSON.stringify({ boot, fingerprint: record.fingerprint }), 'utf8');+ fs.fsyncSync(fd);+ fs.closeSync(fd);+ fd = undefined;+ fs.renameSync(candidate, observationPath);+ } catch {+ return 'lock-unreadable';+ } finally {+ if (fd !== undefined) fs.closeSync(fd);+ try {+ fs.unlinkSync(candidate);+ } catch {+ /* best effort */+ }+ }+ return 'lock-corrupt';+ }+ }++ const current = readRecord(filePath);+ if (current.state === 'missing') return null;+ if (current.state !== 'readable' || current.fingerprint !== record.fingerprint) {+ return 'recovery-busy';+ }+ // Retain the bytes for support; reader backups must not be scanned as live readers.+ const backup = sidecarPath(filePath, `.schema-lease-backup-${crypto.randomUUID()}`);+ try {+ fs.renameSync(filePath, backup);+ const isolated = readRecord(backup);+ if (+ isolated.state !== 'readable' ||+ isolated.identity !== record.identity ||+ !isolated.bytes.equals(record.bytes)+ ) {+ // A legacy client does not take our transition gate. Never grant a lease if+ // it replaced the record between our last check and the rename. Restore+ // without overwriting any incumbent, and retain the backup for support.+ try {+ fs.linkSync(backup, filePath);+ } catch {+ /* A competing owner or IO error must not turn this into an acquisition. */+ }+ return 'recovery-busy';+ }+ try {+ fs.unlinkSync(observationPath);+ } catch {+ /* A stale observation cannot match a new inode. */+ }+ return null;+ } catch {+ return 'lock-unreadable';+ }+}++async function withLeaseTransition(+ dbFilePath: string,+ task: () => Promise<AcquireSchemaMigrationLeaseResult>,+): Promise<AcquireSchemaMigrationLeaseResult> {+ const gate = `${dbFilePath}.schema-transition`;+ const marker = `owner-${process.pid}-${crypto.randomUUID()}`;+ const candidate = `${gate}.${marker}.candidate`;+ let held = false;+ try {+ fs.mkdirSync(candidate, { mode: 0o700 });+ fs.writeFileSync(path.join(candidate, marker), '', { flag: 'wx', mode: 0o600 });+ for (let attempt = 0; attempt < 3; attempt++) {+ try {+ // A complete NONEMPTY directory is published atomically. It cannot+ // replace another nonempty gate on Windows, Linux or macOS.+ fs.renameSync(candidate, gate);+ held = true;+ return await task();+ } catch (error) {+ if (held) throw error;+ let entries: string[];+ try {+ if (!fs.lstatSync(gate).isDirectory()) {+ return { acquired: false, reason: 'lock-unreadable' };+ }+ entries = fs.readdirSync(gate);+ } catch (readError) {+ if ((readError as NodeJS.ErrnoException).code === 'ENOENT') continue;+ throw readError;+ }+ if (entries.length > 0) {+ const owner = entries.length === 1 && /^owner-([1-9]\d*)-[a-f0-9-]{36}$/.exec(entries[0]);+ if (!owner) return { acquired: false, reason: 'lock-unreadable' };+ if (isProcessAlive(Number(owner[1]))) {+ return { acquired: false, reason: 'recovery-busy' };+ }+ // Only unlink this unique dead owner's marker. A delayed reclaimer+ // must never delete a successor's marker (even after PID reuse).+ try {+ fs.unlinkSync(path.join(gate, entries[0]));+ } catch (unlinkError) {+ if ((unlinkError as NodeJS.ErrnoException).code !== 'ENOENT') throw unlinkError;+ }+ }+ try {+ fs.rmdirSync(gate);+ } catch (removeError) {+ const code = (removeError as NodeJS.ErrnoException).code;+ if (code !== 'ENOENT' && code !== 'ENOTEMPTY' && code !== 'EEXIST') throw removeError;+ }+ }+ }+ return { acquired: false, reason: 'recovery-busy' };+ } catch {+ return { acquired: false, reason: 'lock-unreadable' };+ } finally {+ // Crashing between unlink and rmdir leaves an empty, safely reclaimable gate.+ // rmdir (never recursive deletion) cannot remove a newly published owner.+ const directory = held ? gate : candidate;+ try {+ fs.unlinkSync(path.join(directory, marker));+ } catch {+ /* best effort */+ }+ try {+ fs.rmdirSync(directory);+ } catch {+ /* A successor's nonempty directory must be left intact. */+ }}}@@ -168,8 +377,13 @@ function createOwner(): LeaseOwner {}function releaseOwnedFile(filePath: string, owner: LeaseOwner): void {- const current = readOwner(filePath);- if (!current || current.token !== owner.token || current.pid !== owner.pid) return;+ const current = readRecord(filePath);+ if (+ current.state !== 'readable' ||+ current.owner?.token !== owner.token ||+ current.owner.pid !== owner.pid+ )+ return;try {fs.unlinkSync(filePath);} catch {@@ -177,77 +391,91 @@ function releaseOwnedFile(filePath: string, owner: LeaseOwner): void {}}-function activeReaderFiles(readersDir: string): string[] {+async function activeReaderFiles(+ readersDir: string,+): Promise<{ count: number; failure?: SchemaLeaseFailureReason }> {let entries: string[];try {entries = fs.readdirSync(readersDir);} catch (err) {- if ((err as NodeJS.ErrnoException).code === 'ENOENT') return [];+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') return { count: 0 };throw err;}- const active: string[] = [];+ let count = 0;for (const entry of entries) {const filePath = path.join(readersDir, entry);- if (!removeIfDead(filePath)) active.push(filePath);+ const failure = await clearInactiveRecord(filePath);+ if (failure === 'writer-active') count++;+ else if (failure) return { count, failure };}- return active;+ return { count };}/** passive 在打开 / 检查共享 DB 前获取,并持有到 `closeDb()`。 */-export function acquireSchemaMigrationReaderLease(+export async function acquireSchemaMigrationReaderLease(dbFilePath: string,-): AcquireSchemaMigrationLeaseResult {- const paths = leasePaths(dbFilePath);- removeIfDead(paths.writer);- if (fs.existsSync(paths.writer)) return { acquired: false, reason: 'writer-active' };-- fs.mkdirSync(paths.readers, { recursive: true, mode: 0o700 });- const owner = createOwner();- const readerPath = path.join(paths.readers, `${owner.pid}-${owner.token}.json`);- if (!writeOwnerExclusive(readerPath, owner)) {- return { acquired: false, reason: 'writer-active' };- }+): Promise<AcquireSchemaMigrationLeaseResult> {+ return withLeaseTransition(dbFilePath, async () => {+ const paths = leasePaths(dbFilePath);+ const failure = await clearInactiveRecord(paths.writer);+ if (failure) return { acquired: false, reason: failure };- // writer 可能在第一次检查与 reader 原子写入之间抢到锁;此时 reader 必须让路。- removeIfDead(paths.writer);- if (fs.existsSync(paths.writer)) {- releaseOwnedFile(readerPath, owner);- return { acquired: false, reason: 'writer-active' };- }+ fs.mkdirSync(paths.readers, { recursive: true, mode: 0o700 });+ const owner = createOwner();+ const readerPath = path.join(paths.readers, `${owner.pid}-${owner.token}.json`);+ if (!writeOwnerExclusive(readerPath, owner)) {+ return { acquired: false, reason: 'writer-active' };+ }- return {- acquired: true,- lease: {- kind: 'reader',- release: () => releaseOwnedFile(readerPath, owner),- },- };+ // writer 可能在第一次检查与 reader 原子写入之间抢到锁;此时 reader 必须让路。+ // Old clients do not take the transition lock, so keep the original double check.+ if (fs.existsSync(paths.writer)) {+ releaseOwnedFile(readerPath, owner);+ return { acquired: false, reason: 'writer-active' };+ }++ return {+ acquired: true,+ lease: {+ kind: 'reader',+ release: () => releaseOwnedFile(readerPath, owner),+ },+ };+ });}/** primary / packaged 在任何 migration 或 schema DDL repair 前获取。 */-export function acquireSchemaMigrationWriterLease(+export async function acquireSchemaMigrationWriterLease(dbFilePath: string,-): AcquireSchemaMigrationLeaseResult {- const paths = leasePaths(dbFilePath);- removeIfDead(paths.writer);- const owner = createOwner();- if (!writeOwnerExclusive(paths.writer, owner)) {- return { acquired: false, reason: 'writer-active' };- }-- const readers = activeReaderFiles(paths.readers);- if (readers.length > 0) {- releaseOwnedFile(paths.writer, owner);- return { acquired: false, reason: 'readers-active', activeReaderCount: readers.length };- }+): Promise<AcquireSchemaMigrationLeaseResult> {+ return withLeaseTransition(dbFilePath, async () => {+ const paths = leasePaths(dbFilePath);+ const failure = await clearInactiveRecord(paths.writer);+ if (failure) return { acquired: false, reason: failure };+ const owner = createOwner();+ if (!writeOwnerExclusive(paths.writer, owner)) {+ return { acquired: false, reason: 'writer-active' };+ }- return {- acquired: true,- lease: {- kind: 'writer',- release: () => releaseOwnedFile(paths.writer, owner),- },- };+ let admitted = false;+ try {+ const readers = await activeReaderFiles(paths.readers);+ if (readers.failure || readers.count > 0) {+ return {+ acquired: false,+ reason: readers.failure ?? 'readers-active',+ activeReaderCount: readers.count,+ };+ }+ admitted = true;+ return {+ acquired: true,+ lease: { kind: 'writer', release: () => releaseOwnedFile(paths.writer, owner) },+ };+ } finally {+ if (!admitted) releaseOwnedFile(paths.writer, owner);+ }+ });}/**@@ -260,17 +488,40 @@ export function acquireSchemaMigrationWriterLease(export class SchemaMigrationReaderLeaseLifecycle {private lease: SchemaMigrationLease | null = null;private dbFilePath: string | null = null;+ private generation = 0;+ private pending: {+ dbFilePath: string;+ result: Promise<EnsureSchemaMigrationReaderLeaseResult>;+ } | null = null;- ensure(dbFilePath: string): EnsureSchemaMigrationReaderLeaseResult {+ async ensure(dbFilePath: string): Promise<EnsureSchemaMigrationReaderLeaseResult> {if (this.lease && this.dbFilePath === dbFilePath) {return { acquired: true, newlyAcquired: false };}+ if (this.pending?.dbFilePath === dbFilePath) {+ const result = await this.pending.result;+ return result.acquired ? { acquired: true, newlyAcquired: false } : result;+ }this.release();- const result = acquireSchemaMigrationReaderLease(dbFilePath);- if (!result.acquired) return { acquired: false, reason: 'writer-active' };- this.lease = result.lease;- this.dbFilePath = dbFilePath;- return { acquired: true, newlyAcquired: true };+ const generation = this.generation;+ const result = acquireSchemaMigrationReaderLease(dbFilePath).then(+ (acquired): EnsureSchemaMigrationReaderLeaseResult => {+ if (generation !== this.generation) {+ if (acquired.acquired) acquired.lease.release();+ return { acquired: false, reason: 'recovery-busy' };+ }+ if (!acquired.acquired) return acquired;+ this.lease = acquired.lease;+ this.dbFilePath = dbFilePath;+ return { acquired: true, newlyAcquired: true };+ },+ );+ this.pending = { dbFilePath, result };+ try {+ return await result;+ } finally {+ if (this.pending?.result === result) this.pending = null;+ }}closeConnection(preserveSchemaMigrationLease = false): void {@@ -278,6 +529,8 @@ export class SchemaMigrationReaderLeaseLifecycle {}release(): void {+ this.generation++;+ this.pending = null;this.lease?.release();this.lease = null;this.dbFilePath = null;diff --git a/apps/desktop/src/renderer/__tests__/localDbFatalView.test.ts b/apps/desktop/src/renderer/__tests__/localDbFatalView.test.tsindex 4daf750ae5..937c9d307f 100644--- a/apps/desktop/src/renderer/__tests__/localDbFatalView.test.ts+++ b/apps/desktop/src/renderer/__tests__/localDbFatalView.test.ts@@ -6,6 +6,9 @@ import {} from '../components/error/localDbFatalView';describe('resolveLocalDbFatalView', () => {+ it.each(['ready', 'downloading', 'idle'] as const)('schema lock failure offers DB retry regardless of update status %s (#7135)', (status) => {+ expect(resolveLocalDbFatalView(status, 'DB_SCHEMA_LOCKED')).toBe('retry-local-db');+ });it('ready → install-update(补丁就绪,可一键重启安装)', () => {expect(resolveLocalDbFatalView('ready')).toBe('install-update');});diff --git a/apps/desktop/src/renderer/components/auth/LocalDbGate.tsx b/apps/desktop/src/renderer/components/auth/LocalDbGate.tsxindex be1193cf79..8b49491e44 100644--- a/apps/desktop/src/renderer/components/auth/LocalDbGate.tsx+++ b/apps/desktop/src/renderer/components/auth/LocalDbGate.tsx@@ -172,6 +172,11 @@ export function LocalDbGate() {<LocalDbFatalScreencode={decision.code}message={decision.message}+ onRetry={() => {+ retryCountRef.current = 0;+ setDecision({ phase: 'checking' });+ setRetryNonce((n) => n + 1);+ }}onBackToLogin={() => {const leave = mode === 'local' ? exitLocalMode() : logout();void leave.then(diff --git a/apps/desktop/src/renderer/components/auth/__tests__/LocalDbGate.retry.test.tsx b/apps/desktop/src/renderer/components/auth/__tests__/LocalDbGate.retry.test.tsxindex b67072b57b..1687682677 100644--- a/apps/desktop/src/renderer/components/auth/__tests__/LocalDbGate.retry.test.tsx+++ b/apps/desktop/src/renderer/components/auth/__tests__/LocalDbGate.retry.test.tsx@@ -6,7 +6,7 @@* transient 失败(如跨睡眠 db RPC 假超时)重试 2 次后成功 → 正常放行;* 持续失败耗尽重试 → 才落 fatal 阻断渲染。*/-import { cleanup, render, screen } from '@testing-library/react';+import { cleanup, fireEvent, render, screen } from '@testing-library/react';import { act } from 'react';import { MemoryRouter, Route, Routes } from 'react-router-dom';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';@@ -116,6 +116,24 @@ describe('LocalDbGate 有限重试', () => {expect(screen.getByTestId('main-content')).toBeTruthy();});+ // #7135 / unit: mount the real gate + fatal screen, retry a failed lease for+ // the original account, and verify admission rather than only callback calls.+ it('reopens the original account after a lease failure instead of installing an available update', async () => {+ const api = stubElectronApi();+ api.getUpdateStatus.mockResolvedValue({ status: 'ready' });+ api.localDb.ensureReady.mockResolvedValueOnce({+ ready: false,+ error: { code: 'DB_SCHEMA_LOCKED', message: 'fixture lock requires recovery' },+ });+ renderGate();+ await flushAsync();+ expect(screen.queryByTestId('main-content')).toBeNull();+ fireEvent.click(screen.getByRole('button', { name: 'localDbFatal.schemaLease.retry' }));+ await flushAsync();+ expect(screen.getByTestId('main-content')).toBeTruthy();+ expect(api.localDb.ensureReady).toHaveBeenNthCalledWith(2, 'user-1');+ });+it('transient 失败 2 次后成功 → 重试后放行,不落 fatal', async () => {const api = stubElectronApi();api.localDb.ensureReadydiff --git a/apps/desktop/src/renderer/components/error/LocalDbFatalScreen.tsx b/apps/desktop/src/renderer/components/error/LocalDbFatalScreen.tsxindex 3c9cc7a7b9..bf18d9637b 100644--- a/apps/desktop/src/renderer/components/error/LocalDbFatalScreen.tsx+++ b/apps/desktop/src/renderer/components/error/LocalDbFatalScreen.tsx@@ -19,19 +19,25 @@ export function LocalDbFatalScreen({code,message,onBackToLogin,+ onRetry,}: {code?: string;message?: string;onBackToLogin?: () => void;+ onRetry?: () => void;}) {const { t } = useTranslation();const { status, progress } = useUpdateStatus();// 点了「重启并安装更新」后应用即将退出重启,期间锁住按钮防止重复触发。const [installing, setInstalling] = useState(false);- const view = resolveLocalDbFatalView(status);+ const view = resolveLocalDbFatalView(status, code);const handleConfirm = () => {+ if (view === 'retry-local-db') {+ onRetry?.();+ return;+ }if (view === 'install-update') {if (installing) return;setInstalling(true);@@ -46,17 +52,25 @@ export function LocalDbFatalScreen({};const title =- view === 'no-update' ? t('localDbFatal.noUpdate.title') : t('localDbFatal.updateReady.title');+ view === 'retry-local-db'+ ? t('localDbFatal.schemaLease.title')+ : view === 'no-update'+ ? t('localDbFatal.noUpdate.title')+ : t('localDbFatal.updateReady.title');const description =- view === 'install-update'- ? t('localDbFatal.updateReady.description')- : view === 'preparing-update'- ? t('localDbFatal.preparing.description')- : t('localDbFatal.noUpdate.description');+ view === 'retry-local-db'+ ? (message ?? t('localDbFatal.schemaLease.lock-unreadable'))+ : view === 'install-update'+ ? t('localDbFatal.updateReady.description')+ : view === 'preparing-update'+ ? t('localDbFatal.preparing.description')+ : t('localDbFatal.noUpdate.description');const confirmText =- view === 'install-update'- ? t('localDbFatal.updateReady.confirm')- : t('localDbFatal.noUpdate.checkUpdate');+ view === 'retry-local-db'+ ? t('localDbFatal.schemaLease.retry')+ : view === 'install-update'+ ? t('localDbFatal.updateReady.confirm')+ : t('localDbFatal.noUpdate.checkUpdate');return (<divdiff --git a/apps/desktop/src/renderer/components/error/localDbFatalView.ts b/apps/desktop/src/renderer/components/error/localDbFatalView.tsindex 7065cf9804..0006e9272b 100644--- a/apps/desktop/src/renderer/components/error/localDbFatalView.ts+++ b/apps/desktop/src/renderer/components/error/localDbFatalView.ts@@ -8,11 +8,16 @@* 与 UpdateBanner 一致此时禁止 relaunch,防止装到旧补丁)——按钮转圈等待。* - `no-update`:无补丁可装(idle/error)——引导「重新检查更新」。*/-export type LocalDbFatalView = 'install-update' | 'preparing-update' | 'no-update';+export type LocalDbFatalView =+ 'install-update' | 'preparing-update' | 'no-update' | 'retry-local-db';export type UpdateStatusValue = UpdateStatusPayload['status'];-export function resolveLocalDbFatalView(status: UpdateStatusValue | undefined): LocalDbFatalView {+export function resolveLocalDbFatalView(+ status: UpdateStatusValue | undefined,+ code?: string,+): LocalDbFatalView {+ if (code === 'DB_SCHEMA_LOCKED') return 'retry-local-db';switch (status) {case 'ready':return 'install-update';diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 20fc73a80f..80ef04e405 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -1056,6 +1056,15 @@"details": "Error details"},"localDbFatal": {+ "schemaLease": {+ "title": "Local data cannot be opened yet",+ "retry": "Reopen Local Data",+ "writer-active": "Another Cindy instance is maintaining the local data. Reopen it after maintenance finishes.",+ "readers-active": "Other Cindy instances are using this local data. Close those instances before reopening it.",+ "lock-corrupt": "The local data maintenance lock is damaged, so Cindy cannot confirm whether it is still in use. Restart your computer, then reopen Cindy. If this continues, contact support. Do not delete database files.",+ "lock-unreadable": "The local data maintenance lock could not be read or saved. Check access to the data directory, then reopen it after access is restored. Contact support if this continues.",+ "recovery-busy": "Another Cindy instance is checking the local data maintenance lock. Reopen the local data shortly."+ },"databaseCleanup": {"interruptedTitle": "Database Cleanup Was Interrupted","interruptedDescription": "Database cleanup stopped unexpectedly. Restart Cindy so it can recover safely from the saved maintenance state.",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 972ba658c3..dfb484ab99 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -1044,6 +1044,15 @@"details": "エラー詳細"},"localDbFatal": {+ "schemaLease": {+ "title": "ローカルデータをまだ開けません",+ "retry": "ローカルデータを開き直す",+ "writer-active": "別の Cindy がローカルデータを保守しています。完了後に開き直してください。",+ "readers-active": "別の Cindy がこのローカルデータを使用しています。そちらを終了してから開き直してください。",+ "lock-corrupt": "ローカルデータの保守ロック記録が破損しているため、使用中か確認できません。パソコンを再起動してから Cindy を開いてください。解決しない場合はサポートにお問い合わせください。データベースファイルは削除しないでください。",+ "lock-unreadable": "ローカルデータの保守ロックを読み取り、または保存できません。データフォルダーへのアクセス権を確認し、アクセスを復旧してから開き直してください。解決しない場合はサポートにお問い合わせください。",+ "recovery-busy": "別の Cindy がローカルデータの保守ロックを確認しています。しばらくしてから開き直してください。"+ },"databaseCleanup": {"interruptedTitle": "データベースのクリーンアップが中断されました","interruptedDescription": "データベースのクリーンアップが予期せず中断されました。Cindy を再起動してください。保存されたメンテナンス状態に基づいて安全に復旧します。",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 5f00cac149..fcf2a23fd3 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -1044,6 +1044,15 @@"details": "오류 정보"},"localDbFatal": {+ "schemaLease": {+ "title": "아직 로컬 데이터를 열 수 없습니다",+ "retry": "로컬 데이터 다시 열기",+ "writer-active": "다른 Cindy 인스턴스가 로컬 데이터를 유지 관리하고 있습니다. 완료된 후 다시 여세요.",+ "readers-active": "다른 Cindy 인스턴스가 이 로컬 데이터를 사용하고 있습니다. 해당 인스턴스를 종료한 후 다시 여세요.",+ "lock-corrupt": "로컬 데이터 유지 관리 잠금 기록이 손상되어 사용 중인지 확인할 수 없습니다. 컴퓨터를 다시 시작한 후 Cindy를 여세요. 문제가 계속되면 지원팀에 문의하세요. 데이터베이스 파일을 삭제하지 마세요.",+ "lock-unreadable": "로컬 데이터 유지 관리 잠금을 읽거나 저장할 수 없습니다. 데이터 폴더 접근 권한을 확인하고 접근이 복원되면 다시 여세요. 문제가 계속되면 지원팀에 문의하세요.",+ "recovery-busy": "다른 Cindy 인스턴스가 로컬 데이터 유지 관리 잠금을 확인하고 있습니다. 잠시 후 다시 여세요."+ },"databaseCleanup": {"interruptedTitle": "데이터베이스 정리가 중단되었습니다","interruptedDescription": "데이터베이스 정리가 예기치 않게 중단되었습니다. Cindy를 다시 시작하면 저장된 유지 관리 상태를 바탕으로 안전하게 복구합니다.",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 68c6b5cf36..b652a479eb 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -1044,6 +1044,15 @@"details": "错误详情"},"localDbFatal": {+ "schemaLease": {+ "title": "本地数据暂时无法打开",+ "retry": "重新打开本地数据",+ "writer-active": "另一个 Cindy 实例正在维护本地数据。请等待维护结束后重新打开。",+ "readers-active": "其他 Cindy 实例正在使用这份本地数据。请退出这些实例后重新打开。",+ "lock-corrupt": "本地数据的维护锁记录损坏,暂时无法确认是否仍有程序在使用它。请重启电脑后重新打开 Cindy;若仍无法打开,请联系支持人员。请勿删除数据库文件。",+ "lock-unreadable": "无法读取或保存本地数据的维护锁。请检查数据目录的访问权限;恢复访问后重新打开。若仍失败,请联系支持人员。",+ "recovery-busy": "另一个 Cindy 实例正在检查本地数据的维护锁。请稍后重新打开。"+ },"databaseCleanup": {"interruptedTitle": "数据库清理中断","interruptedDescription": "数据库清理异常中断。请重新启动 Cindy,系统会根据维护记录安全恢复。",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 938ceba6f3..9ee0968ba6 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -1044,6 +1044,15 @@"details": "錯誤詳情"},"localDbFatal": {+ "schemaLease": {+ "title": "暫時無法開啟本機資料",+ "retry": "重新開啟本機資料",+ "writer-active": "另一個 Cindy 執行個體正在維護本機資料。請等待維護結束後重新開啟。",+ "readers-active": "其他 Cindy 執行個體正在使用這份本機資料。請結束這些執行個體後重新開啟。",+ "lock-corrupt": "本機資料的維護鎖記錄損壞,暫時無法確認是否仍有程式在使用它。請重新啟動電腦後開啟 Cindy;若仍無法開啟,請聯絡支援人員。請勿刪除資料庫檔案。",+ "lock-unreadable": "無法讀取或儲存本機資料的維護鎖。請檢查資料目錄的存取權限;恢復存取後重新開啟。若仍失敗,請聯絡支援人員。",+ "recovery-busy": "另一個 Cindy 執行個體正在檢查本機資料的維護鎖。請稍後重新開啟。"+ },"databaseCleanup": {"interruptedTitle": "資料庫清理中斷","interruptedDescription": "資料庫清理異常中斷。請重新啟動 Cindy,系統會根據維護記錄安全復原。",diff --git a/docs/dev-rules/database-and-migrations.md b/docs/dev-rules/database-and-migrations.mdindex 95925a1ddc..5adcbdb9d1 100644--- a/docs/dev-rules/database-and-migrations.md+++ b/docs/dev-rules/database-and-migrations.md@@ -111,6 +111,35 @@ companion CommonJS 格式和历史 runtime identity 冻结;不能用单独 typ## 运行期数据库访问+### Schema 租约的发布与故障恢复(#7135)++`localDb/schemaMigrationLease.ts` 保留既有 writer 文件与多 reader 目录契约;完整记录先在+目录外的独占候选文件写入并刷盘,再用不覆盖目标的 hard link 发布。reader 候选、恢复记录+和隔离备份不进入 reader 目录,旧客户端仍能识别正式租约。文件系统不支持该发布方式时+明确阻断,不回退到直接写半成品锁。租约获取为异步,退出/切账号必须取消在途 reader。++同一数据库的新版租约获取与回收通过原子发布的非空目录串行化:候选目录先包含唯一+PID+UUID 文件名,再 rename 到正式 gate。释放/回收只删该 owner 的精确 marker,+再非递归 rmdir;暂停的清理者不能删除后继 owner 的非空目录。中断释放留下的空目录可+重试回收,不引入会被原地写坏的辅助 JSON 锁。有效存活 PID 不回收,不可读文件不当作+损坏记录移走。+损坏且未知 owner 的记录可能是暂停中的旧版发布者,因此不得按文件年龄或解析失败抢锁。+首次观察时持久化文件身份/内容指纹和内核 boot generation;只有之后确认系统已跨过一次+启动、且原锁指纹未变,才备份隔离它。应用重启、时间跳变、文件被替换都不授予恢复权限。+Windows 用内核 boot GUID,macOS 用 `kern.bootsessionuuid`,Linux 用 `boot_id`;无法取得+启动标识时保留锁,显示支持指引,不推算启动时间。旧版首次遇到的新损坏记录需要在新版+记录证据后重启电脑一次;不能承诺安装更新后的第一次启动就自动恢复。++保留原 reader/writer 双向检查与旧版记录格式。隔离后再次校验文件身份与内容;若发现被+替换则拒绝新租约,并尝试不覆盖地恢复原路径。但旧版自身的「读死 owner → unlink」+不参与新版 gate,旧进程持有过期检查结果时仍可能删掉后继锁;无法在新版单侧消除该既有+竞态。恢复时应退出共用此数据目录的旧客户端;混合版本不能承诺任意并发恢复安全。++开库前租约故障返回 `DB_SCHEMA_LOCKED`,按真实原因显示重试或重启电脑指引,不归为+schema 版本不兼容,也不触发安装更新。恢复只操作当前账号的租约及其备份,不修改 DB、+WAL 或聊天数据。生产入口、发布中断与竞争回归见 `schemaMigrationLease.test.ts`,界面+重新打开当前账号的回归见 `LocalDbGate.retry.test.tsx`。+- Main 运行期业务代码使用 `DbClient`/`getDbClient()` 的异步 API,并 `await` Drizzle query或使用 `query`、`queryOne`、`exec`、`tx`。- 不把异步 Drizzle proxy 当成同步 `better-sqlite3` 使用,也不在 Main 业务路径新增直接