Skip to content
Merged
2 changes: 1 addition & 1 deletion config/reliability-gates.jsonc
Original file line number Diff line number Diff line change
Expand Up @@ -8856,7 +8856,7 @@
"Windows ConPTY, SSH-hosted PTYs, app-quit killAll, and daemon dispose retain foreground-tree-only teardown.",
"A process born in the capture second is SIGTERMed but not SIGKILLed because ps cannot prove its recycled-PID identity.",
"A descendant orphaned before or during root ownership loss requires the separate crash-orphan sweep and is not recovered from a stale kill-time snapshot.",
"recordTerminalSurfaceRetirement advances the INCOMING session's terminal topology revision, so a tombstoned close whose write carries a revision at or below the store's own is rebased away instead of persisting. Pre-existing for every repo already past revision 0 and unchanged by the host-admitted membership fix, which only makes more repos reach that state sooner; the authoritative close path (persistTerminalSurfaceRetirements) computes from the store's session and is unaffected. Known, unaddressed, and deliberately out of scope here: the safe correction is per-tab rather than per-worktree rebase arbitration, because raising the incoming revision wholesale would re-open the host-tab loss whenever a close coincides with a host create.",
"recordTerminalSurfaceRetirement advances the INCOMING session's terminal topology revision, so a tombstoned close whose write carries a revision at or below the store's own is rebased away instead of persisting. Pre-existing for every repo already past revision 0 and unchanged by the host-admitted membership fix, which only makes more repos reach that state sooner; the authoritative close path (stageTerminalSurfaceRetirements) computes from the store's session and is unaffected. Known, unaddressed, and deliberately out of scope here: the safe correction is per-tab rather than per-worktree rebase arbitration, because raising the incoming revision wholesale would re-open the host-tab loss whenever a close coincides with a host create.",
"The SSH relay reattach binding (src/main/ssh/ssh-relay-session.ts persistPtyBinding) is NOT flagged host-admitted, so a lease rebind that has to mint a missing tab raises no fence. It rebinds an existing lease rather than admitting a new surface, so it is believed not to need one, but that was not established either way. Known, unaddressed, and deliberately out of scope here.",
"The host-created retention journey is macOS-local; the reported incident was on a physical Windows host, which we did not run against."
],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ describe('host-admitted terminal membership survives a stale renderer replay', (
})

// Closing must still work afterwards. Closes are host-driven: the retirement is
// computed from the store's own session (see persistTerminalSurfaceRetirements),
// computed from the store's own session (see stageTerminalSurfaceRetirements),
// which is what outranks the fence this create just raised.
it('still lets the authoritative retirement path close the host-admitted tab', async () => {
const store = await createStore()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,18 @@ export class DelayedAuthority implements AsyncProfileStateAuthority {
| { started: ReturnType<typeof deferred<void>>; finish: ReturnType<typeof deferred<void>> }
| undefined
readonly captures: ProfileStateDomainReplacement[][] = []
private failNext = false
readonly close = vi.fn(async () => {
this.inner.close()
})

constructor(readonly inner: ProfileStateSqliteAuthority) {}

/** Fail the next profile write the way a full disk would, after any paused gate opens. */
failNextWrite() {
this.failNext = true
}

pause() {
const gate = { started: deferred<void>(), finish: deferred<void>() }
this.next = gate
Expand All @@ -51,25 +57,28 @@ export class DelayedAuthority implements AsyncProfileStateAuthority {
}
async writeSerializedState(payload: Buffer) {
const captured = Buffer.from(payload)
await this.dispatch(() => this.inner.writeSerializedState(captured))
await this.dispatch(() => this.inner.writeSerializedState(captured), true)
}
async writeSerializedDomains(replacements: readonly ProfileStateDomainReplacement[]) {
const captured = structuredClone(replacements)
this.captures.push([...captured])
await this.dispatch(() => this.inner.writeSerializedDomains(captured))
await this.dispatch(() => this.inner.writeSerializedDomains(captured), true)
}
async writeCompleteSerializedDomains(replacements: readonly ProfileStateDomainReplacement[]) {
const captured = structuredClone(replacements)
this.captures.push([...captured])
await this.dispatch(() => this.inner.writeCompleteSerializedDomains(captured))
await this.dispatch(() => this.inner.writeCompleteSerializedDomains(captured), true)
}
async writeSerializedAutomationRuns(
replacements: readonly ProfileStateDomainReplacement[],
runs: readonly AutomationRun[]
) {
const captured = structuredClone(replacements)
const capturedRuns = structuredClone(runs)
await this.dispatch(() => this.inner.writeSerializedAutomationRuns(captured, capturedRuns))
await this.dispatch(
() => this.inner.writeSerializedAutomationRuns(captured, capturedRuns),
true
)
}
async writeJsonExport(path: string) {
return this.inner.writeJsonExport(path)
Expand All @@ -83,11 +92,15 @@ export class DelayedAuthority implements AsyncProfileStateAuthority {
async quarantineDatabase(root?: string, reason?: string) {
return this.inner.quarantineDatabase(root, reason)
}
private async dispatch(operation: () => void) {
private async dispatch(operation: () => void, write = false) {
const gate = this.next
this.next = undefined
gate?.started.resolve()
await gate?.finish.promise
if (write && this.failNext) {
this.failNext = false
throw new Error('profile_state_write_failed')
}
operation()
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,6 @@ class RetirementRuntime extends OrcaRuntimeService {
generations(): number {
return this.ptyLifecycleGenerationById.size
}
retirements(): number {
return this.pendingPtySurfaceRetirementsByPtyId.size
}
async closeTab(): Promise<void> {
const snapshot = this.snapshot()
const tab = snapshot?.tabs[0]
Expand Down Expand Up @@ -96,10 +93,8 @@ it.each(['read', 'replacement', 'legacy-replacement'] as const)(
gate.finish.resolve()
await exiting
expect(readState().workspaceSession.terminalLayoutsByTabId[binding.tabId]).toBeUndefined()
expect(runtime.snapshot()?.tabs).toHaveLength(action === 'read' ? 0 : 1)
if (action === 'read') {
expect(runtime.retirements()).toBe(0)
}
// Why every action: the exit retired the leaf in memory before any of them could run.
expect(runtime.snapshot()?.tabs).toHaveLength(0)
}
)

Expand Down
24 changes: 21 additions & 3 deletions src/main/runtime/acknowledged-terminal-tab-retirement-fixture.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { vi } from 'vitest'
import { getDefaultWorkspaceSession } from '../../shared/constants'
import type { PersistedState } from '../../shared/persisted-state-types'
import type { RuntimeSyncWindowGraph } from '../../shared/runtime-types'
import { closeTerminalTabInWorkspaceSession } from '../../shared/workspace-session-terminal-tab-close'
import { ProfileStateSqliteAuthority } from '../persistence/profile-state/profile-state-sqlite-authority'
Expand Down Expand Up @@ -30,8 +31,9 @@ function deferred(): { promise: Promise<void>; resolve: () => void } {

export function createAcknowledgedTabRetirementFixture(bound = false) {
const directory = mkdtempSync(join(tmpdir(), 'orca-close-ack-'))
const databasePath = join(directory, 'profile-state.db')
const authority = new DelayedAuthority(
new ProfileStateSqliteAuthority(join(directory, 'profile-state.db'), 'ack-retirement')
new ProfileStateSqliteAuthority(databasePath, 'ack-retirement')
)
const store = new Store({
dataFile: join(directory, 'orca-data.json'),
Expand Down Expand Up @@ -149,6 +151,7 @@ export function createAcknowledgedTabRetirementFixture(bound = false) {
store.setWorkspaceSession(
advanceTerminalTopologyRevision(store.getWorkspaceSession(), ACK_WORKTREE)
)
let finalFlush: Promise<void> | undefined
const entered = deferred()
const acknowledgement = deferred()
const closeTerminalTab = vi.fn(async () => {
Expand Down Expand Up @@ -184,15 +187,30 @@ export function createAcknowledgedTabRetirementFixture(bound = false) {
acknowledgement,
closeTerminalTab,
publish,
/** Reads what a relaunch would load, independent of the store's in-memory state. */
readDisk: (): PersistedState => {
const reader = new ProfileStateSqliteAuthority(databasePath, 'ack-retirement')
try {
return JSON.parse(reader.readSerializedState() ?? '{}')
} finally {
reader.close()
}
},
hasTab: () =>
store.getWorkspaceSession().tabsByWorktree[ACK_WORKTREE].some((tab) => tab.id === ACK_TAB),
close: (options: { force?: boolean } = {}) =>
runtime.closeMobileSessionTab(`id:${ACK_WORKTREE}`, ACK_TAB, { reason: 'user', ...options }),
/** The app-quit flush; it finalizes persistence, so dispose must not flush again. */
quit: () => (finalFlush ??= store.flushFinalOrThrowAsync()),
dispose: async () => {
runtime.setNotifier(null)
runtime.syncWindowGraph(1, { tabs: [], leaves: [], mobileSessionTabs: [] })
await store.flushPendingOrThrowAsync()
await store.freezeWritesAsync()
if (finalFlush) {
await finalFlush
} else {
await store.flushPendingOrThrowAsync()
await store.freezeWritesAsync()
}
setRuntimeDesktopSurface(null)
rmSync(directory, { recursive: true, force: true })
}
Expand Down
1 change: 0 additions & 1 deletion src/main/runtime/orca-runtime-fit-override-listeners.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,6 @@ export class OrcaRuntimeWithFitOverrideListeners extends OrcaRuntimeWithStopRequ
protected providerSnapshotsWithLiveModeTransition = new WeakSet<PtyProviderBufferSnapshot>()

protected ptyLifecycleGenerationById = new Map<string, number>()
protected pendingPtySurfaceRetirementsByPtyId = new Map<string, object>()

protected nextPtyLifecycleGeneration = 1

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,6 @@ export class OrcaRuntimeWithInvalidateAllHandlesForPty extends OrcaRuntimeWithRe
options: { awaitsRegistration?: boolean } = {}
): void {
this.invalidatePtyControllerInventoryForLifecycle(ptyId)
this.pendingPtySurfaceRetirementsByPtyId.delete(ptyId)
const existingPty = this.ptysById.get(ptyId)
if (
existingPty &&
Expand Down
Loading
Loading