perf(ai): defer backup JSON.stringify in writeSessionsForStorage and fix mirror no-op guard (#4376)

This commit is contained in:
陈大猫 authored and GitHub committed 2026-11-25 21:39:31 +08:00
1 parent 32b1b633db
commit 412f6c4ec6
4 files changed
+147 -16

No files matched your search

@@ -138,6 +138,52 @@ test('DebouncedBackupMirror flushNow writes the pending payload immediately', ()
assert.deepEqual(writes, ['{"gen":1}']);
});
test('DebouncedBackupMirror defers lazy serializer execution until debounce timer or flushNow fires', async () => {
const writes: string[] = [];
const serialized: number[] = [];
const mirror = new DebouncedBackupMirror((json) => writes.push(json), 15);
mirror.schedule(() => {
serialized.push(1);
return '{"gen":1}';
});
mirror.schedule(() => {
serialized.push(2);
return '{"gen":2}';
});
// Neither producer runs synchronously during burst scheduling.
assert.deepEqual(serialized, []);
assert.deepEqual(writes, []);
await new Promise((resolve) => setTimeout(resolve, 35));
// Only the final producer in the burst is invoked when the timer fires.
assert.deepEqual(serialized, [2]);
assert.deepEqual(writes, ['{"gen":2}']);
// flushNow invokes only the pending lazy producer immediately; reset discards without calling it.
mirror.schedule(() => {
serialized.push(3);
return '{"gen":3}';
});
mirror.schedule(() => {
serialized.push(4);
return '{"gen":4}';
});
assert.deepEqual(serialized, [2]);
mirror.flushNow();
assert.deepEqual(serialized, [2, 4]);
assert.deepEqual(writes, ['{"gen":2}', '{"gen":4}']);
mirror.schedule(() => {
serialized.push(5);
return '{"gen":5}';
});
mirror.reset();
await new Promise((resolve) => setTimeout(resolve, 30));
assert.deepEqual(serialized, [2, 4]);
assert.deepEqual(writes, ['{"gen":2}', '{"gen":4}']);
});
test('readLiveSessionsArray treats non-array JSON as empty (corrupt)', () => {
assert.deepEqual(readLiveSessionsArray(null), []);
assert.deepEqual(readLiveSessionsArray(''), []);
+19 -10
View File
@@ -119,28 +119,37 @@ export function mergeImportedSessions(current: AISession[], imported: AISession[
return Array.from(byId.values()).sort((a, b) => (b.updatedAt ?? 0) - (a.updatedAt ?? 0));
}
export type BackupMirrorInput = string | (() => string);
/**
* Debounced mirror scheduler. One rolling timer per process: the last
* mutation batch wins, and the write happens `debounceMs` after the batch
* settles (at most once per batch, per the durability spec).
* Accepts either a pre-serialized JSON string or a lazy serializer invoked
* only when the debounce timer or `flushNow()` actually runs.
*/
export class DebouncedBackupMirror {
private timer: ReturnType<typeof setTimeout> | null = null;
private pendingJson: string | null = null;
private pendingInput: BackupMirrorInput | null = null;
constructor(
private readonly write: (json: string) => void,
private readonly debounceMs: number = AI_SESSIONS_BACKUP_DEBOUNCE_MS,
) {}
schedule(json: string) {
this.pendingJson = json;
private emit(input: BackupMirrorInput) {
const json = typeof input === 'function' ? input() : input;
this.write(json);
}
schedule(input: BackupMirrorInput) {
this.pendingInput = input;
if (this.timer) clearTimeout(this.timer);
this.timer = setTimeout(() => {
this.timer = null;
const json = this.pendingJson;
this.pendingJson = null;
if (json != null) this.write(json);
const pending = this.pendingInput;
this.pendingInput = null;
if (pending != null) this.emit(pending);
}, this.debounceMs);
}
@@ -149,14 +158,14 @@ export class DebouncedBackupMirror {
clearTimeout(this.timer);
this.timer = null;
}
const json = this.pendingJson;
this.pendingJson = null;
if (json != null) this.write(json);
const pending = this.pendingInput;
this.pendingInput = null;
if (pending != null) this.emit(pending);
}
reset() {
if (this.timer) clearTimeout(this.timer);
this.timer = null;
this.pendingJson = null;
this.pendingInput = null;
}
}
@@ -847,3 +847,75 @@ test('rewriting the same sessions array skips re-serialization and store writes'
__resetIdbPersistenceForTests();
}
});
test('writeSessionsForStorage defers backup JSON.stringify during bursts and skips unchanged rewrites when sync is disabled', async (t) => {
const {
writeSessionsForStorage,
flushBackupMirror,
__flushIdbWritesForTests,
__resetBackupMirrorForTests,
__resetIdbPersistenceForTests,
} = await import('./aiStateSnapshots');
__resetBackupMirrorForTests();
__resetIdbPersistenceForTests();
const idb = installFakeIndexedDb();
const backupWrites: string[] = [];
const previousWindow = globalThis.window;
Object.defineProperty(globalThis, 'window', {
configurable: true,
value: {
netcatty: {
aiSessionsBackupWrite: async (payload: { json: string }) => {
backupWrites.push(payload.json);
return { ok: true };
},
},
},
});
// Default syncEnabled=false path: pruneSessionsForStorage allocates a new array each call.
t.mock.method(localStorageAdapter, 'read', () => null);
t.mock.method(localStorageAdapter, 'writeString', () => true);
try {
const stringify = t.mock.method(JSON, 'stringify');
const a1 = makeSession('chat-a', 1, [{ id: 'm1', role: 'assistant', content: 'chunk 1', timestamp: 1 }]);
const b = makeSession('chat-b', 0, []);
const a2 = makeSession('chat-a', 2, [{ id: 'm1', role: 'assistant', content: 'chunk 1+2', timestamp: 2 }]);
const a3 = makeSession('chat-a', 3, [{ id: 'm1', role: 'assistant', content: 'chunk 1+2+3', timestamp: 3 }]);
// Streaming persist burst: 3 consecutive writes must perform 0 eager JSON.stringify calls.
assert.equal(writeSessionsForStorage([a1, b]), true);
assert.equal(writeSessionsForStorage([a2, b]), true);
assert.equal(writeSessionsForStorage([a3, b]), true);
assert.equal(stringify.mock.callCount(), 0, 'JSON.stringify must not run eagerly on writeSessionsForStorage');
assert.equal(backupWrites.length, 0);
// Flushing the debounced mirror serializes only the latest persisted snapshot once.
flushBackupMirror();
assert.equal(stringify.mock.callCount(), 1);
assert.equal(backupWrites.length, 1);
const flushed = JSON.parse(backupWrites[0]) as AISession[];
assert.equal(flushed.find((s) => s.id === 'chat-a')?.messages[0]?.content, 'chunk 1+2+3');
// Rewriting unchanged sessions with syncEnabled=false (fresh array from pruneSessionsForStorage)
// must NOT schedule a redundant mirror or run JSON.stringify on flush.
assert.equal(writeSessionsForStorage([a3, b]), true);
flushBackupMirror();
assert.equal(stringify.mock.callCount(), 1, 'unchanged sessions must not re-schedule mirror when sync is disabled');
assert.equal(backupWrites.length, 1);
// Removing a session still schedules and mirrors the updated set.
assert.equal(writeSessionsForStorage([a3], { deletedSessionIds: ['chat-b'] }), true);
assert.equal(stringify.mock.callCount(), 1, 'deletion backup serialization is also deferred until flush/debounce');
flushBackupMirror();
assert.equal(stringify.mock.callCount(), 2);
assert.equal(backupWrites.length, 2);
assert.deepEqual((JSON.parse(backupWrites[1]) as AISession[]).map((s) => s.id), ['chat-a']);
await __flushIdbWritesForTests();
} finally {
idb.restore();
__resetBackupMirrorForTests();
__resetIdbPersistenceForTests();
Object.defineProperty(globalThis, 'window', { configurable: true, value: previousWindow });
}
});
+10 -6
View File
@@ -29,7 +29,7 @@ import {
import { emitAIStateChanged } from './aiStateEvents';
import { peekAgentRuntimeCleanup } from '../../infrastructure/ai/harness/agentRuntimeHandle';
import { setReversibleModelPrivacy } from '../../infrastructure/ai/harness/modelSecretRedaction';
import { DebouncedBackupMirror, readLiveSessionsArray } from './aiSessionsBackup';
import { DebouncedBackupMirror, readLiveSessionsArray, type BackupMirrorInput } from './aiSessionsBackup';
import {
idbDeleteSessionIds,
idbPutMeta,
@@ -305,6 +305,7 @@ let idbWriteQueue: Promise<void> = Promise.resolve();
/** Test hook: reset diff state between tests. */
export function __resetIdbPersistenceForTests() {
lastPersistedSessionsById = new Map();
lastMirroredSessions = null;
idbWriteQueue = Promise.resolve();
// Tests swap the fake indexedDB factory between cases; the cached open
// handle must not survive the swap.
@@ -429,12 +430,13 @@ export function flushBackupMirror() {
export function __resetBackupMirrorForTests() {
backupMirror.reset();
aiSessionsBackupRecoveryPending = false;
lastMirroredSessions = null;
}
export function scheduleBackupMirror(json: string) {
export function scheduleBackupMirror(input: BackupMirrorInput) {
if (aiSessionsBackupRecoveryPending) return;
try {
backupMirror.schedule(json);
backupMirror.schedule(input);
} catch {
// ignore
}
@@ -503,9 +505,11 @@ export function writeSessionsForStorage(
const removedIds = Array.from(prevById.keys()).filter(id => !persistedIds.has(id));
lastPersistedSessionsById = new Map(persisted.map(session => [session.id, session]));
if (changed.length > 0 || removedIds.length > 0 || lastMirroredSessions !== persisted) {
scheduleBackupMirror(JSON.stringify(persisted));
lastMirroredSessions = persisted;
if (changed.length > 0 || removedIds.length > 0 || lastMirroredSessions === null) {
if (!aiSessionsBackupRecoveryPending) {
scheduleBackupMirror(() => JSON.stringify(persisted));
lastMirroredSessions = persisted;
}
}
queueIdbSessionSync(changed, removedIds, prevById, persisted);
return true;