Preserve prepared-save lifecycle and regression coverage

This commit is contained in:
Brennan Benson
2026-11-13 12:28:21 -08:00
parent 73b77ea7dc
commit f5aeb76496
16 changed files with 92 additions and 83 deletions
@@ -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)
@@ -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 {
@@ -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')
})
@@ -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)
@@ -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<string, unknown> = 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<string, unknown>),
...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',
@@ -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<string, unknown> {
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<string, unknown> | 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<object>): void {
function enter(
value: unknown,
ancestors: Set<object>
): asserts value is Record<string, unknown> | unknown[] {
admitObject(value)
if (ancestors.has(value)) {
throw unsupported
@@ -85,7 +80,10 @@ function equalJson(value: unknown, previous: unknown, ancestors: Set<object>): 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)
@@ -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()
}
})
@@ -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({
@@ -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')
@@ -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 }
}
@@ -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
@@ -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
@@ -30,7 +30,10 @@ export function prepareProfileStateDomainPatches(
}
const domains = new Set<string>()
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')
}
@@ -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
@@ -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)
@@ -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')
})