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(media): revalidate owner after journal commit

JiangJiahao06fe115ce062
diff --git a/apps/desktop/src/main/cindy-media/__tests__/ingest.test.ts b/apps/desktop/src/main/cindy-media/__tests__/ingest.test.ts
index f71b29205d..89c55d0e88 100644
--- a/apps/desktop/src/main/cindy-media/__tests__/ingest.test.ts
+++ b/apps/desktop/src/main/cindy-media/__tests__/ingest.test.ts
@@ -80,6 +80,32 @@ function compensationScope(): MediaRefCompensationScope {
return refCompensation.captureMediaRefCompensationScope(OWNER_SCOPE_KEY);
}
+function postCommitExpiringScope(
+ journalDir: string,
+ expiration: 'after-commit' | 'after-collection' = 'after-commit',
+): MediaRefCompensationScope {
+ let sawPendingMarker = false;
+ let sawCommittedMarker = false;
+ const scope: MediaRefCompensationScope = {
+ journalDir,
+ ownerStorageKey: OWNER_KEY,
+ assertStillValid: () => {
+ const markers = fs.existsSync(scope.journalDir)
+ ? fs.readdirSync(scope.journalDir).filter((name) => name.endsWith('.json'))
+ : [];
+ if (markers.some((name) => name.endsWith('.pending.json'))) sawPendingMarker = true;
+ if (sawPendingMarker && markers.some((name) => name.endsWith('.committed.json'))) {
+ sawCommittedMarker = true;
+ if (expiration === 'after-commit') throw new Error('owner changed after journal commit');
+ }
+ if (expiration === 'after-collection' && sawCommittedMarker && markers.length === 0) {
+ throw new Error('owner changed after journal commit');
+ }
+ },
+ };
+ return scope;
+}
+
function blobPathOf(hash: string, ext: string): string {
return path.join(tmpUserData, 'cindy-media', 'blobs', hash.slice(0, 2), `${hash}${ext}`);
}
@@ -252,6 +278,72 @@ describe('ingestMedia(崩溃语义:先字节后记账)', () => {
expect(db.select().from(schema.mediaRefs).all()).toHaveLength(0);
});
+ it('补偿日志提交后 owner 失效时仍精确回滚本次引用', async () => {
+ const scope = postCommitExpiringScope(
+ path.join(tmpUserData, 'post-commit-owner-change-journal'),
+ );
+
+ await expect(
+ ingest.ingestMedia(
+ {
+ buffer: PNG_BYTES,
+ mimeType: 'image/png',
+ refs: [{ refKind: 'ghost-gallery', refId: 'stale-owner-art' }],
+ assertStillValid: () => undefined,
+ refCompensationScope: scope,
+ },
+ db,
+ ),
+ ).rejects.toThrow('owner changed after journal commit');
+
+ expect(db.select().from(schema.mediaRefs).all()).toHaveLength(0);
+ expect(fs.readdirSync(scope.journalDir).filter((name) => name.endsWith('.json'))).toHaveLength(
+ 0,
+ );
+ });
+
+ it('补偿日志提交后 owner 失效且即时回滚失败时保留可恢复标记', async () => {
+ const scope = postCommitExpiringScope(compensationScope().journalDir, 'after-collection');
+ const removeRefById = vi
+ .spyOn(ledger, 'removeRefById')
+ .mockRejectedValueOnce(new Error('worker disposed'));
+ try {
+ await expect(
+ ingest.ingestMedia(
+ {
+ buffer: PNG_BYTES,
+ mimeType: 'image/png',
+ refs: [{ refKind: 'ghost-gallery', refId: 'recover-stale-owner-art' }],
+ assertStillValid: () => undefined,
+ refCompensationScope: scope,
+ },
+ db,
+ ),
+ ).rejects.toThrow('owner changed after journal commit');
+
+ expect(db.select().from(schema.mediaRefs).all()).toHaveLength(1);
+ const markerNames = fs
+ .readdirSync(scope.journalDir)
+ .filter((name) => name.endsWith('.committed.json'));
+ expect(markerNames).toHaveLength(1);
+ expect(
+ JSON.parse(fs.readFileSync(path.join(scope.journalDir, markerNames[0]), 'utf8')),
+ ).toMatchObject({ rollbackRequired: true });
+
+ removeRefById.mockRestore();
+ await expect(
+ refCompensation.reconcileMediaRefCompensationsForOwner({
+ ownerId: OWNER_ID,
+ db,
+ isOwnerCurrent: () => true,
+ }),
+ ).resolves.toMatchObject({ recoveredPending: 1 });
+ expect(db.select().from(schema.mediaRefs).all()).toHaveLength(0);
+ } finally {
+ removeRefById.mockRestore();
+ }
+ });
+
it('addRef 已提交但回执丢失时仍用预留 id 精确回滚引用', async () => {
const realAddRef = ledger.addRef;
const addRef = vi.spyOn(ledger, 'addRef').mockImplementationOnce(async (params, targetDb) => {
diff --git a/apps/desktop/src/main/cindy-media/refCompensationJournal.ts b/apps/desktop/src/main/cindy-media/refCompensationJournal.ts
index 8fb4ecfeee..5f0763b1c2 100644
--- a/apps/desktop/src/main/cindy-media/refCompensationJournal.ts
+++ b/apps/desktop/src/main/cindy-media/refCompensationJournal.ts
@@ -196,6 +196,7 @@ async function markRollbackRequired(
} finally {
await handle.close();
}
+ await syncDirectory(path.dirname(paths.committed));
}
async function removeOperationMarkers(paths: JournalPaths, journalDir: string): Promise<void> {
@@ -236,12 +237,6 @@ async function commitRecord(
{ code: 'REF_JOURNAL_COMMIT_UNCERTAIN', cause: error },
);
}
- await removeMarker(paths.committed, scope.journalDir).catch((error) => {
- log.warn('Failed to collect a committed media reference journal', {
- operationId: paths.operationId,
- error: String(error),
- });
- });
}
/**
@@ -278,13 +273,31 @@ export async function withMediaRefCompensation<T>(params: {
}
const record = await writePendingRecord(params.scope, paths, params.refIds);
+ let recordCommitted = false;
try {
params.scope.assertStillValid();
const result = await params.perform();
params.scope.assertStillValid();
await commitRecord(params.scope, paths, record);
+ recordCommitted = true;
+ params.scope.assertStillValid();
+ await removeMarker(paths.committed, params.scope.journalDir).catch((error) => {
+ log.warn('Failed to collect a committed media reference journal', {
+ operationId: paths.operationId,
+ error: String(error),
+ });
+ });
+ params.scope.assertStillValid();
return result;
} catch (error) {
+ if (recordCommitted) {
+ await markRollbackRequired(paths, record).catch((markError) => {
+ log.warn('Failed to preserve an invalidated media reference commit for rollback', {
+ operationId: paths.operationId,
+ error: String(markError),
+ });
+ });
+ }
const rollback = await Promise.allSettled(params.refIds.map(params.compensate));
const rollbackFailed = rollback.some((result) => result.status === 'rejected');
rollback.forEach((result, index) => {