From f5aeb76496e9ac8df42cc9cf490a3a23de9fcba5 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 13 Nov 2026 12:28:21 -0800 Subject: [PATCH] Preserve prepared-save lifecycle and regression coverage --- .../durable-settings-write.spec.ts | 4 +- .../profile-state-caller-cancellation.spec.ts | 11 +++--- ...profile-state-maintenance-recovery.spec.ts | 18 ++++----- ...-state-pty-retirement-finalization.spec.ts | 4 +- .../profile-state-split-snapshots.test.ts | 24 ++++++++++-- .../profile-state-split-snapshots.ts | 38 +++++++++---------- .../profile-writing/write-flush-barriers.ts | 2 + ...persistence-split-pane-incarnation.test.ts | 11 +++--- ...cad-catalog-commit-automation-runs.test.ts | 2 +- .../persistence-async-write-syscalls.test.ts | 18 +++------ ...sistence-loading-store-write-risks.test.ts | 4 +- ...stence-protected-secret-write-race.test.ts | 2 +- .../documents/profile-state-domain-patches.ts | 7 +++- .../documents/profile-state-domain-writes.ts | 16 ++++---- ...rofile-state-patched-domain-preparation.ts | 10 ++--- .../profile-state-live-store-factory.test.ts | 4 +- 16 files changed, 92 insertions(+), 83 deletions(-) diff --git a/src/main/persistence/loading-store/profile-writing/durable-settings-write.spec.ts b/src/main/persistence/loading-store/profile-writing/durable-settings-write.spec.ts index 59617bc0f44..97b4f57623e 100644 --- a/src/main/persistence/loading-store/profile-writing/durable-settings-write.spec.ts +++ b/src/main/persistence/loading-store/profile-writing/durable-settings-write.spec.ts @@ -9,8 +9,8 @@ export function registerDurableSettingsWriteTests(): void { const { store, authority, readState } = await createWorkerMaintenanceFixture() const started = maintenanceBarrier() const release = maintenanceBarrier() - const write = authority.writeSerializedDomains.bind(authority) - vi.spyOn(authority, 'writeSerializedDomains').mockImplementationOnce(async (domains) => { + const write = authority.writePreparedState.bind(authority) + vi.spyOn(authority, 'writePreparedState').mockImplementationOnce(async (domains) => { started.resolve() await release.promise await write(domains) diff --git a/src/main/persistence/loading-store/profile-writing/profile-state-caller-cancellation.spec.ts b/src/main/persistence/loading-store/profile-writing/profile-state-caller-cancellation.spec.ts index 23127215bb0..51b3977b09b 100644 --- a/src/main/persistence/loading-store/profile-writing/profile-state-caller-cancellation.spec.ts +++ b/src/main/persistence/loading-store/profile-writing/profile-state-caller-cancellation.spec.ts @@ -25,8 +25,8 @@ export function registerProfileStateCallerCancellationTests(): void { const { store, authority, readState } = await createWorkerMaintenanceFixture() const started = maintenanceBarrier() const release = maintenanceBarrier() - const write = authority.writeSerializedDomains.bind(authority) - vi.spyOn(authority, 'writeSerializedDomains').mockImplementationOnce(async (domains) => { + const write = authority.writePreparedState.bind(authority) + vi.spyOn(authority, 'writePreparedState').mockImplementationOnce(async (domains) => { await write(domains) started.resolve() await release.promise @@ -62,8 +62,8 @@ export function registerProfileStateCallerCancellationTests(): void { const { store, authority, readState } = await createWorkerMaintenanceFixture() const started = maintenanceBarrier() const release = maintenanceBarrier() - const write = authority.writeSerializedDomains.bind(authority) - vi.spyOn(authority, 'writeSerializedDomains').mockImplementationOnce(async (domains) => { + const write = authority.writePreparedState.bind(authority) + vi.spyOn(authority, 'writePreparedState').mockImplementationOnce(async (domains) => { started.resolve() await release.promise await write(domains) @@ -75,7 +75,8 @@ export function registerProfileStateCallerCancellationTests(): void { await started.promise controller.abort() store.getWorkspaceSession().activeTabId = 'shutdown-edit' - const capture = vi.spyOn(authority, 'writeCompleteSerializedDomains') + const capture = vi.spyOn(authority, 'writePreparedState') + capture.mockClear() const final = store.flushFinalOrThrowAsync() const result = final.catch((error: unknown) => error) try { diff --git a/src/main/persistence/loading-store/profile-writing/profile-state-maintenance-recovery.spec.ts b/src/main/persistence/loading-store/profile-writing/profile-state-maintenance-recovery.spec.ts index 6f1966dfcbb..4c920923873 100644 --- a/src/main/persistence/loading-store/profile-writing/profile-state-maintenance-recovery.spec.ts +++ b/src/main/persistence/loading-store/profile-writing/profile-state-maintenance-recovery.spec.ts @@ -11,14 +11,12 @@ export function registerProfileStateMaintenanceRecoveryTests(): void { vi.spyOn(console, 'error').mockImplementation(() => {}) const started = maintenanceBarrier() const release = maintenanceBarrier() - const write = authority.writeCompleteSerializedDomains.bind(authority) - vi.spyOn(authority, 'writeCompleteSerializedDomains').mockImplementationOnce( - async (domains) => { - started.resolve() - await release.promise - await write(domains) - } - ) + const write = authority.writePreparedState.bind(authority) + vi.spyOn(authority, 'writePreparedState').mockImplementationOnce(async (domains) => { + started.resolve() + await release.promise + await write(domains) + }) const abort = vi.spyOn(authority, 'abort') const controller = new AbortController() store.updateSettings({ theme: 'dark' }) @@ -44,9 +42,9 @@ export function registerProfileStateMaintenanceRecoveryTests(): void { const { store, authority, peer, readState } = await createWorkerMaintenanceFixture() vi.spyOn(console, 'error').mockImplementation(() => {}) store.updateSettings({ theme: 'dark' }) - vi.spyOn(authority, 'writeCompleteSerializedDomains').mockImplementationOnce(async () => { + vi.spyOn(authority, 'writePreparedState').mockImplementationOnce(async () => { const writer = peer() - writer.writeSerializedDomains([{ domain: 'peer', payload: '{"preserved":true}' }]) + writer.writePreparedState([{ domain: 'peer', payload: '{"preserved":true}' }]) writer.close() throw new Error('disk refused') }) diff --git a/src/main/persistence/loading-store/profile-writing/profile-state-pty-retirement-finalization.spec.ts b/src/main/persistence/loading-store/profile-writing/profile-state-pty-retirement-finalization.spec.ts index ac7a98c9730..5812017e1c1 100644 --- a/src/main/persistence/loading-store/profile-writing/profile-state-pty-retirement-finalization.spec.ts +++ b/src/main/persistence/loading-store/profile-writing/profile-state-pty-retirement-finalization.spec.ts @@ -10,8 +10,8 @@ export function registerProfileStatePtyRetirementFinalizationTests(): void { vi.spyOn(console, 'error').mockImplementation(() => {}) const started = maintenanceBarrier() const release = maintenanceBarrier() - const write = authority.writeSerializedDomains.bind(authority) - vi.spyOn(authority, 'writeSerializedDomains').mockImplementationOnce(async (domains) => { + const write = authority.writePreparedState.bind(authority) + vi.spyOn(authority, 'writePreparedState').mockImplementationOnce(async (domains) => { started.resolve() await release.promise await write(domains) diff --git a/src/main/persistence/loading-store/profile-writing/profile-state-split-snapshots.test.ts b/src/main/persistence/loading-store/profile-writing/profile-state-split-snapshots.test.ts index cd2329a2048..5a34f2278e8 100644 --- a/src/main/persistence/loading-store/profile-writing/profile-state-split-snapshots.test.ts +++ b/src/main/persistence/loading-store/profile-writing/profile-state-split-snapshots.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import { ProfileStateSplitSnapshots } from './profile-state-split-snapshots' import { capturePreparedProfileStateWrite } from './profile-state-prepared-write' import { @@ -34,7 +34,7 @@ describe('profile state split capture', () => { it('preserves native JSON meaning, own keys and order through logical patches', () => { const snapshots = new ProfileStateSplitSnapshots() snapshots.seed({ workspaceSession: { tabsByWorktree: { a: [], b: [] }, keep: null } }) - const current: unknown = JSON.parse( + const current: Record = JSON.parse( '{"tabsByWorktree":{"b":[],"__proto__":[{"title":"own"}],"a":[]},"keep":{}}' ) const captured = snapshots.capture('workspaceSession', current)! @@ -49,7 +49,7 @@ describe('profile state split capture', () => { snapshots.acknowledge(new Map([['workspaceSession', captured.value]])) expect( snapshots.capture('workspaceSession', { - ...(current as Record), + ...current, optional: undefined })!.patch.operations ).toEqual([]) @@ -107,7 +107,23 @@ describe('profile state split capture', () => { const snapshots = new ProfileStateSplitSnapshots() snapshots.seed({ workspaceSession: { tabsByWorktree } }) tabsByWorktree.w0[0].title = 'changed' - const captured = snapshots.capture('workspaceSession', { tabsByWorktree })! + const nativeStringify = JSON.stringify + const serialized: string[] = [] + const stringify = vi.spyOn(JSON, 'stringify').mockImplementation((value) => { + const payload = nativeStringify(value) + if (payload !== undefined) { + serialized.push(payload) + } + return payload + }) + const captured = (() => { + try { + return snapshots.capture('workspaceSession', { tabsByWorktree })! + } finally { + stringify.mockRestore() + } + })() + expect(serialized).toEqual(['[{"title":"changed"}]']) // One title update needs one small leaf; unrelated row payloads and full key vectors are unnecessary. expect(captured.patch).toEqual({ domain: 'workspaceSession', diff --git a/src/main/persistence/loading-store/profile-writing/profile-state-split-snapshots.ts b/src/main/persistence/loading-store/profile-writing/profile-state-split-snapshots.ts index 9a9c1091bdc..b81a2f1ffe2 100644 --- a/src/main/persistence/loading-store/profile-writing/profile-state-split-snapshots.ts +++ b/src/main/persistence/loading-store/profile-writing/profile-state-split-snapshots.ts @@ -7,15 +7,13 @@ import { } from '../../profile-state/documents/profile-state-domain-patches' const unsupported = Symbol('native domain serialization required') -const lookupGetter = Object.prototype.__lookupGetter__ -const lookupSetter = Object.prototype.__lookupSetter__ function record(value: unknown): value is Record { return value !== null && typeof value === 'object' && !Array.isArray(value) } -function admitObject(value: object): void { - if (types.isProxy(value)) { +function admitObject(value: unknown): asserts value is Record | unknown[] { + if (types.isProxy(value) || (!record(value) && !Array.isArray(value))) { throw unsupported } const prototype: unknown = Object.getPrototypeOf(value) @@ -32,12 +30,10 @@ function admitObject(value: object): void { } } -function admitToJson(value: object): void { - if (Object.hasOwn(value, 'toJSON')) { - const descriptor = Object.getOwnPropertyDescriptor(value, 'toJSON')! - if (!('value' in descriptor) || typeof descriptor.value === 'function') { - throw unsupported - } +function admitToJson(value: unknown): void { + const descriptor = Object.getOwnPropertyDescriptor(value, 'toJSON') + if (descriptor && (!('value' in descriptor) || typeof descriptor.value === 'function')) { + throw unsupported } } @@ -52,19 +48,18 @@ function admitPrototypes(): void { admitToJson(Array.prototype) } -function readDataProperty(value: object, key: string): unknown { - if (lookupGetter.call(value, key) || lookupSetter.call(value, key)) { +function readDataProperty(value: unknown, key: string): unknown { + const descriptor = Object.getOwnPropertyDescriptor(value, key) + if (!descriptor || !('value' in descriptor)) { throw unsupported } - const entry: unknown = Reflect.get(value, key) - // Empty accessors also read undefined; ordinary optional undefined data remains eligible. - if (entry === undefined && !('value' in Object.getOwnPropertyDescriptor(value, key)!)) { - throw unsupported - } - return entry + return descriptor.value } -function enter(value: object, ancestors: Set): void { +function enter( + value: unknown, + ancestors: Set +): asserts value is Record | unknown[] { admitObject(value) if (ancestors.has(value)) { throw unsupported @@ -85,7 +80,10 @@ function equalJson(value: unknown, previous: unknown, ancestors: Set): b return (Number.isFinite(value) ? value : null) === previous case 'object': break - default: + case 'bigint': + case 'function': + case 'symbol': + case 'undefined': throw unsupported } enter(value, ancestors) diff --git a/src/main/persistence/loading-store/profile-writing/write-flush-barriers.ts b/src/main/persistence/loading-store/profile-writing/write-flush-barriers.ts index c6b15485ab7..fc37645fa54 100644 --- a/src/main/persistence/loading-store/profile-writing/write-flush-barriers.ts +++ b/src/main/persistence/loading-store/profile-writing/write-flush-barriers.ts @@ -23,6 +23,7 @@ type WriteFlushBarrierOperationsRuntime = Pick< | 'pendingProfileMaintenance' | 'profileMaintenancePending' | 'profileStateAuthority' + | 'profileStateSplitSnapshots' | 'quitFlushPromise' | 'quitFlushStarted' | 'staleProfileStateTempCleanup' @@ -107,6 +108,7 @@ export class WriteFlushBarrierOperations { .finally(async () => { if (runtime.profileStateAuthority?.asynchronous) { runtime.writesFrozen = true + runtime.profileStateSplitSnapshots.clear() await runtime.profileStateAuthority.close() } }) diff --git a/src/main/persistence/loading-store/terminal-bindings/persistence-split-pane-incarnation.test.ts b/src/main/persistence/loading-store/terminal-bindings/persistence-split-pane-incarnation.test.ts index 56c848a5617..da6c1977ab6 100644 --- a/src/main/persistence/loading-store/terminal-bindings/persistence-split-pane-incarnation.test.ts +++ b/src/main/persistence/loading-store/terminal-bindings/persistence-split-pane-incarnation.test.ts @@ -202,12 +202,11 @@ describe('Store', () => { terminalPtyIncarnationsByPaneKey: { [paneKey]: 'inc-stale' } }) store.flushOrThrow() - vi.spyOn( - ProfileStateSqliteAuthority.prototype, - 'writeSerializedDomains' - ).mockImplementationOnce(() => { - throw new Error('disk full') - }) + vi.spyOn(ProfileStateSqliteAuthority.prototype, 'writePreparedState').mockImplementationOnce( + () => { + throw new Error('disk full') + } + ) await expect( store.persistPtyBinding({ diff --git a/src/main/persistence/migrating-orcad-catalog/catalog-commit/orcad-catalog-commit-automation-runs.test.ts b/src/main/persistence/migrating-orcad-catalog/catalog-commit/orcad-catalog-commit-automation-runs.test.ts index 592b3b70da2..5856b5f0ca2 100644 --- a/src/main/persistence/migrating-orcad-catalog/catalog-commit/orcad-catalog-commit-automation-runs.test.ts +++ b/src/main/persistence/migrating-orcad-catalog/catalog-commit/orcad-catalog-commit-automation-runs.test.ts @@ -31,7 +31,7 @@ describe('catalog commit and automation run saves', () => { const started = maintenanceBarrier() const finish = maintenanceBarrier() - vi.spyOn(authority, 'writeSerializedAutomationRuns').mockImplementationOnce(async () => { + vi.spyOn(authority, 'writePreparedState').mockImplementationOnce(async () => { started.resolve() await finish.promise throw new ProfileStateWriterError('disk-refused', 'disk refused', 'known-failure') diff --git a/src/main/persistence/persistence-async-write-syscalls.test.ts b/src/main/persistence/persistence-async-write-syscalls.test.ts index 9e0f010a874..6e128c2faeb 100644 --- a/src/main/persistence/persistence-async-write-syscalls.test.ts +++ b/src/main/persistence/persistence-async-write-syscalls.test.ts @@ -17,18 +17,12 @@ vi.mock('../ssh/config/ssh-config-parser', () => ({ function pauseCommit(authority: ProfileStateWorkerAuthority) { const started = maintenanceBarrier() const finish = maintenanceBarrier() - let held = false - for (const name of ['writeSerializedDomains', 'writeCompleteSerializedDomains'] as const) { - const original = authority[name].bind(authority) - vi.spyOn(authority, name).mockImplementation(async (replacements) => { - if (!held) { - held = true - started.resolve() - await finish.promise - } - await original(replacements) - }) - } + const original = authority.writePreparedState.bind(authority) + vi.spyOn(authority, 'writePreparedState').mockImplementationOnce(async (write) => { + started.resolve() + await finish.promise + await original(write) + }) return { started: started.promise, release: finish.resolve } } diff --git a/src/main/persistence/persistence-loading-store-write-risks.test.ts b/src/main/persistence/persistence-loading-store-write-risks.test.ts index af3fbcc43c8..e60c3af09cc 100644 --- a/src/main/persistence/persistence-loading-store-write-risks.test.ts +++ b/src/main/persistence/persistence-loading-store-write-risks.test.ts @@ -19,8 +19,8 @@ describe('loading Store write-risk characterization', () => { const committed = maintenanceBarrier() const acknowledge = maintenanceBarrier() // A UI change saves only the ui domain. - const writeDomains = authority.writeSerializedDomains.bind(authority) - vi.spyOn(authority, 'writeSerializedDomains').mockImplementationOnce(async (replacements) => { + const writeDomains = authority.writePreparedState.bind(authority) + vi.spyOn(authority, 'writePreparedState').mockImplementationOnce(async (replacements) => { await writeDomains(replacements) committed.resolve() await acknowledge.promise diff --git a/src/main/persistence/persistence-protected-secret-write-race.test.ts b/src/main/persistence/persistence-protected-secret-write-race.test.ts index 75b73c93730..e41e50e022d 100644 --- a/src/main/persistence/persistence-protected-secret-write-race.test.ts +++ b/src/main/persistence/persistence-protected-secret-write-race.test.ts @@ -40,7 +40,7 @@ describe('protected-secret async write retention', () => { const release = maintenanceBarrier() const writeDomains = authority.writeSerializedDomains.bind(authority) const pendingWrite = vi - .spyOn(authority, 'writeSerializedDomains') + .spyOn(authority, 'writePreparedState') .mockImplementationOnce(async () => { entered.resolve() await release.promise diff --git a/src/main/persistence/profile-state/documents/profile-state-domain-patches.ts b/src/main/persistence/profile-state/documents/profile-state-domain-patches.ts index 691ea124bdb..ee3baa57b53 100644 --- a/src/main/persistence/profile-state/documents/profile-state-domain-patches.ts +++ b/src/main/persistence/profile-state/documents/profile-state-domain-patches.ts @@ -30,7 +30,10 @@ export function prepareProfileStateDomainPatches( } const domains = new Set() return patches.map((patch) => { - const depth = isRecord(patch) ? PROFILE_STATE_SPLIT_DOMAIN_DEPTHS.get(patch.domain) : undefined + const depth = + isRecord(patch) && typeof patch.domain === 'string' + ? PROFILE_STATE_SPLIT_DOMAIN_DEPTHS.get(patch.domain) + : undefined if (depth === undefined || domains.has(patch.domain) || !Array.isArray(patch.operations)) { throw new Error('Profile state patch domain is invalid or repeated') } @@ -42,7 +45,7 @@ export function prepareProfileStateDomainPatches( !Array.isArray(operation.path) || operation.path.length > depth || !operation.path.every((key: unknown) => typeof key === 'string') || - !['set', 'remove', 'order'].includes(operation.kind) + (operation.kind !== 'set' && operation.kind !== 'remove' && operation.kind !== 'order') ) { throw new Error('Profile state patch operation is invalid') } diff --git a/src/main/persistence/profile-state/documents/profile-state-domain-writes.ts b/src/main/persistence/profile-state/documents/profile-state-domain-writes.ts index 82d8a26255a..cb50446e483 100644 --- a/src/main/persistence/profile-state/documents/profile-state-domain-writes.ts +++ b/src/main/persistence/profile-state/documents/profile-state-domain-writes.ts @@ -104,9 +104,16 @@ export function writeProfileStateDomains( if (actualRevision !== transaction.expectedRevision) { throw new ProfileStateRevisionConflictError(transaction.expectedRevision, actualRevision) } + const readLegacyDocument = (domain: string): unknown => + db + .prepare( + `SELECT domain, payload, domain_version, revision, updated_at, content_hash + FROM profile_state_documents WHERE domain = ?` + ) + .get(domain) const mutations = [ ...prepared, - ...preparePatchedProfileStateDomains(db, patches, actualRevision) + ...preparePatchedProfileStateDomains(db, patches, actualRevision, readLegacyDocument) ] if (transaction.complete) { const present = [ @@ -153,12 +160,7 @@ export function writeProfileStateDomains( } return } - const existing = db - .prepare( - `SELECT domain, payload, domain_version, revision, updated_at, content_hash - FROM profile_state_documents WHERE domain = ?` - ) - .get(mutation.domain) + const existing = readLegacyDocument(mutation.domain) const existingRow = existing === undefined ? undefined diff --git a/src/main/persistence/profile-state/documents/profile-state-patched-domain-preparation.ts b/src/main/persistence/profile-state/documents/profile-state-patched-domain-preparation.ts index f144e7d9cbc..f110ff97802 100644 --- a/src/main/persistence/profile-state/documents/profile-state-patched-domain-preparation.ts +++ b/src/main/persistence/profile-state/documents/profile-state-patched-domain-preparation.ts @@ -18,7 +18,8 @@ import { export function preparePatchedProfileStateDomains( db: Database.Database, patches: readonly PreparedProfileStateDomainPatch[], - actualRevision: number + actualRevision: number, + readLegacyDocument: (domain: string) => unknown ): PreparedProfileStateMutation[] { const mutations: PreparedProfileStateMutation[] = [] for (const patch of patches) { @@ -44,12 +45,7 @@ export function preparePatchedProfileStateDomains( } base = JSON.parse(document.payload) } else { - const row = db - .prepare( - `SELECT domain, payload, domain_version, revision, updated_at, content_hash - FROM profile_state_documents WHERE domain = ?` - ) - .get(patch.domain) + const row = readLegacyDocument(patch.domain) if (row !== undefined) { const document = validateProfileStateDocumentRow(row, { retainParsedValue: true }) assertProfileStateDocumentRevision(document.revision, actualRevision, patch.domain) diff --git a/src/main/persistence/profile-state/startup/profile-state-live-store-factory.test.ts b/src/main/persistence/profile-state/startup/profile-state-live-store-factory.test.ts index 0bff598393e..59987c1106f 100644 --- a/src/main/persistence/profile-state/startup/profile-state-live-store-factory.test.ts +++ b/src/main/persistence/profile-state/startup/profile-state-live-store-factory.test.ts @@ -84,14 +84,14 @@ describe('live profile authority admission', () => { first.store.setWorkspaceSession({ ...first.store.getWorkspaceSession(), activeTabId: 'first' }) await first.store.flushPendingOrThrowAsync() first.store.getWorkspaceSession().activeTabId = 'getter-only-final' - await first.store.freezeWritesAsync() + await first.store.flushFinalOrThrowAsync() const reopened = await open(input) expect(reopened.store.getWorkspaceSession().activeTabId).toBe('getter-only-final') reopened.store.setWorkspaceSession({ ...reopened.store.getWorkspaceSession(), activeTabId: 'after-restart' }) - await reopened.store.freezeWritesAsync() + await reopened.store.flushFinalOrThrowAsync() expect(readState(input).workspaceSession.activeTabId).toBe('after-restart') })