[P1] fix(ssh): key the PTY model-migration fence by app pty id (#11617)

* fix(ssh): key the PTY model-migration fence by app pty id

Co-authored-by: Orca <help@stably.ai>

* test(ssh): pin the post-recovery checkpoint rekey

The finishSourceRecovery app-id rekey had no coverage: reverting it left every
suite green while reconnects silently resumed from the stale migration-era
checkpoint.

Co-authored-by: Orca <help@stably.ai>

---------

Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
Neil
2026-07-30 17:49:08 -07:00
committed by GitHub
co-authored by Orca
parent 83af12dc3e
commit 390ae08232
4 changed files with 189 additions and 89 deletions
@@ -1,10 +1,93 @@
import { describe, expect, it, vi } from 'vitest'
import type { SshPtyOutputDataEvent } from './ssh-pty-output-intake'
import {
createSshPtyOutputIntakeHarness as createHarness,
sshPtyOutputEvent as event
} from './ssh-pty-output-intake-test-harness'
// Production-shaped ids: bare relay id on the wire side, prefixed app id in intake.
const APP_ID = 'ssh:conn@@pty-1'
const prodEvent = (overrides: Partial<SshPtyOutputDataEvent> = {}): SshPtyOutputDataEvent =>
event({
id: APP_ID,
source: {
relayPtyId: 'pty-1',
spanId: 'span-a',
clientGeneration: 3,
ownerGeneration: 4,
deliveryToken: 'delivery-token-1',
sourceStartSu: 0,
sourceEndSu: 4
},
...overrides
})
describe('SshPtyOutputModelMigration', () => {
it('fences an in-flight admission when relay and app pty ids differ', async () => {
const harness = createHarness()
const first = harness.intake.acceptData(prodEvent({ data: 'aaaa' }))
harness.completions[0]!.resolve()
await first
const second = harness.intake.acceptData(
prodEvent({
data: 'bbbb',
source: {
relayPtyId: 'pty-1',
spanId: 'span-b',
clientGeneration: 3,
ownerGeneration: 4,
deliveryToken: 'delivery-token-1',
sourceStartSu: 4,
sourceEndSu: 8
}
})
)
const migration = harness.intake.beginGenerationMigration(1)
expect([...migration.byPty.keys()]).toEqual([APP_ID])
const result = migration.byPty.get(APP_ID)
await expect(Promise.race([result, Promise.resolve('pending')])).resolves.toBe('pending')
await expect(Promise.race([migration.completion, Promise.resolve('pending')])).resolves.toBe(
'pending'
)
expect(harness.intake.getAcceptedSourceCheckpoints(1)[0]).toMatchObject({
id: APP_ID,
acceptedSourceEndSu: 4
})
harness.completions[1]!.resolve()
await expect(second).resolves.toMatchObject({ sequence: 8 })
await expect(result).resolves.toMatchObject({
status: 'settled',
checkpoint: { id: APP_ID, acceptedSourceEndSu: 8 }
})
await migration.completion
})
it('targets the real pty on migration timeout with production-shaped ids', async () => {
vi.useFakeTimers()
try {
const resetModelForMigration = vi.fn()
const harness = createHarness({ resetModelForMigration })
const receipt = harness.intake.acceptData(prodEvent())
const migration = harness.intake.beginGenerationMigration(1, 10_000)
await vi.advanceTimersByTimeAsync(10_000)
await expect(migration.byPty.get(APP_ID)).resolves.toEqual({
status: 'checkpoint-unavailable',
reason: 'timeout'
})
await expect(receipt).rejects.toThrow('ssh_model_migration_timeout')
expect(resetModelForMigration).toHaveBeenCalledOnce()
expect(resetModelForMigration).toHaveBeenCalledWith(1, APP_ID)
harness.completions[0]!.resolve()
await migration.completion
} finally {
vi.useRealTimers()
}
})
it('fences a running source span before exporting its migration checkpoint', async () => {
const harness = createHarness()
const first = harness.intake.acceptData(
@@ -41,7 +41,12 @@ export class SshPtyOutputSourceObligations {
private readonly coordinator: SshPtySourceObligationCoordinator
private readonly remoteConsumers: SshPtyRemoteSourceRangeConsumers
private readonly openedTokens = new Set<string>()
private readonly identityByPty = new Map<string, PtySourceDeliveryIdentity>()
// Why: fence/recovery consumers key checkpoints by app pty id, but the wire
// ACK path needs the relay id kept on identity.id — record both.
private readonly identityByPty = new Map<
string,
Readonly<{ appPtyId: string; identity: PtySourceDeliveryIdentity }>
>()
constructor(publish: SshPtyOutputDataEventPublisher | undefined) {
this.coordinator = new SshPtySourceObligationCoordinator({
@@ -68,7 +73,7 @@ export class SshPtyOutputSourceObligations {
if (!this.openedTokens.has(tokenKey)) {
this.coordinator.open(identity, span.sourceStartSu)
this.openedTokens.add(tokenKey)
this.identityByPty.set(this.ptyKey(event), identity)
this.identityByPty.set(this.ptyKey(event), Object.freeze({ appPtyId: event.id, identity }))
}
return Object.freeze({
span,
@@ -132,21 +137,21 @@ export class SshPtyOutputSourceObligations {
}
sealPty(event: SshPtyOutputExitEvent): void {
const identity = this.identityByPty.get(this.ptyKey(event))
const identity = this.identityByPty.get(this.ptyKey(event))?.identity
if (identity) {
this.coordinator.seal(identity)
}
}
markExitPublished(event: SshPtyOutputExitEvent): void {
const identity = this.identityByPty.get(this.ptyKey(event))
const identity = this.identityByPty.get(this.ptyKey(event))?.identity
if (identity) {
this.coordinator.markExitPublished(identity)
}
}
whenPtyTerminal(event: SshPtyOutputExitEvent): Promise<void> {
const identity = this.identityByPty.get(this.ptyKey(event))
const identity = this.identityByPty.get(this.ptyKey(event))?.identity
return identity ? this.coordinator.whenTerminal(identity) : Promise.resolve()
}
@@ -154,7 +159,7 @@ export class SshPtyOutputSourceObligations {
event: SshPtyOutputExitEvent,
cancel: (request: SshPtySourceCancellationRequest) => Promise<SshPtySourceCancellationProof>
): Promise<SshPtySourceCancellationProofCommit | null> {
const identity = this.identityByPty.get(this.ptyKey(event))
const identity = this.identityByPty.get(this.ptyKey(event))?.identity
if (!identity) {
return null
}
@@ -171,7 +176,7 @@ export class SshPtyOutputSourceObligations {
event: SshPtyOutputExitEvent,
proof: SshPtySourceCancellationProof
): boolean {
const identity = this.identityByPty.get(this.ptyKey(event))
const identity = this.identityByPty.get(this.ptyKey(event))?.identity
if (!identity) {
return false
}
@@ -183,7 +188,7 @@ export class SshPtyOutputSourceObligations {
event: SshPtyOutputExitEvent,
proof: SshPtySourceCancellationProof
): void {
const identity = this.identityByPty.get(this.ptyKey(event))
const identity = this.identityByPty.get(this.ptyKey(event))?.identity
if (identity) {
this.coordinator.applyRecoveryCancellationProof(identity, proof)
}
@@ -198,8 +203,8 @@ export class SshPtyOutputSourceObligations {
this.openedTokens.delete(key)
}
}
for (const [key, identity] of this.identityByPty) {
if (identity.providerGeneration === providerGeneration) {
for (const [key, record] of this.identityByPty) {
if (record.identity.providerGeneration === providerGeneration) {
this.identityByPty.delete(key)
}
}
@@ -207,19 +212,20 @@ export class SshPtyOutputSourceObligations {
acceptedCheckpoints(providerGeneration: number): readonly SshPtyAcceptedSourceCheckpoint[] {
const checkpoints: SshPtyAcceptedSourceCheckpoint[] = []
for (const identity of this.identityByPty.values()) {
if (identity.providerGeneration !== providerGeneration) {
for (const record of this.identityByPty.values()) {
if (record.identity.providerGeneration !== providerGeneration) {
continue
}
checkpoints.push(
Object.freeze({
id: identity.id,
providerGeneration: identity.providerGeneration,
clientGeneration: identity.clientGeneration,
ownerGeneration: identity.ownerGeneration,
ptyIncarnation: identity.ptyIncarnation,
deliveryToken: identity.deliveryToken,
acceptedSourceEndSu: this.coordinator.modelAcceptedEnd(identity)
// Why: fence/recovery keys are app pty ids; the bare relay id stays on identity.id.
id: record.appPtyId,
providerGeneration: record.identity.providerGeneration,
clientGeneration: record.identity.clientGeneration,
ownerGeneration: record.identity.ownerGeneration,
ptyIncarnation: record.identity.ptyIncarnation,
deliveryToken: record.identity.deliveryToken,
acceptedSourceEndSu: this.coordinator.modelAcceptedEnd(record.identity)
})
)
}
@@ -284,8 +290,8 @@ export class SshPtyOutputSourceObligations {
private removeIdentity(identity: PtySourceDeliveryIdentity): void {
this.openedTokens.delete(ptySourceDeliveryKey(identity))
for (const [key, candidate] of this.identityByPty) {
if (samePtySourceDelivery(candidate, identity)) {
for (const [key, record] of this.identityByPty) {
if (samePtySourceDelivery(record.identity, identity)) {
this.identityByPty.delete(key)
}
}
@@ -166,6 +166,25 @@ describe('SshRelaySession recovery race fencing', () => {
})
}
function pendingRecovery(recoveryEndSu: number) {
return {
status: 'pending',
clientGeneration: 2,
ownerGeneration: 2,
ptyIncarnation: 'incarnation-1',
deliveryToken: 'new-token',
checkpointSourceEndSu: 4,
recoveryEndSu
}
}
function completeRecovery(params: Record<string, unknown>): void {
const complete = onNotificationByMethodMock.mock.calls.findLast(
([method]) => method === 'pty.recoveryComplete'
)?.[1] as ((params: Record<string, unknown>) => void) | undefined
complete?.(params)
}
async function prepareRecovery(targetId: string): Promise<{
session: SshRelaySession
deps: ReturnType<typeof createMockDeps>
@@ -242,15 +261,7 @@ describe('SshRelaySession recovery race fencing', () => {
})
return {
incarnationId: 'incarnation-1',
sourceRecovery: {
status: 'pending',
clientGeneration: 2,
ownerGeneration: 2,
ptyIncarnation: 'incarnation-1',
deliveryToken: 'new-token',
checkpointSourceEndSu: 4,
recoveryEndSu: 8
},
sourceRecovery: pendingRecovery(8),
sourceActivationLease
}
})
@@ -320,15 +331,7 @@ describe('SshRelaySession recovery race fencing', () => {
})
return {
incarnationId: 'incarnation-1',
sourceRecovery: {
status: 'pending',
clientGeneration: 2,
ownerGeneration: 2,
ptyIncarnation: 'incarnation-1',
deliveryToken: 'new-token',
checkpointSourceEndSu: 4,
recoveryEndSu: 8
},
sourceRecovery: pendingRecovery(8),
sourceActivationLease
}
})
@@ -401,10 +404,7 @@ describe('SshRelaySession recovery race fencing', () => {
const { session, deps } = await prepareRecovery(targetId)
attachForReconnectMock.mockImplementation(async () => {
queueMicrotask(() => {
const complete = onNotificationByMethodMock.mock.calls.findLast(
([method]) => method === 'pty.recoveryComplete'
)?.[1] as ((params: Record<string, unknown>) => void) | undefined
complete?.({
completeRecovery({
id: 'pty-1',
clientGeneration: 2,
ownerGeneration: 2,
@@ -416,15 +416,7 @@ describe('SshRelaySession recovery race fencing', () => {
})
return {
incarnationId: 'incarnation-1',
sourceRecovery: {
status: 'pending',
clientGeneration: 2,
ownerGeneration: 2,
ptyIncarnation: 'incarnation-1',
deliveryToken: 'new-token',
checkpointSourceEndSu: 4,
recoveryEndSu: 4
}
sourceRecovery: pendingRecovery(4)
}
})
await session.reconnect(deps.mockConn)
@@ -463,10 +455,7 @@ describe('SshRelaySession recovery race fencing', () => {
sourceStartSu: 5,
sourceEndSu: 8
})
const complete = onNotificationByMethodMock.mock.calls.findLast(
([method]) => method === 'pty.recoveryComplete'
)?.[1] as ((params: Record<string, unknown>) => void) | undefined
complete?.({
completeRecovery({
id: 'pty-1',
clientGeneration: 2,
ownerGeneration: 2,
@@ -478,15 +467,7 @@ describe('SshRelaySession recovery race fencing', () => {
})
return {
incarnationId: 'incarnation-1',
sourceRecovery: {
status: 'pending',
clientGeneration: 2,
ownerGeneration: 2,
ptyIncarnation: 'incarnation-1',
deliveryToken: 'new-token',
checkpointSourceEndSu: 4,
recoveryEndSu: 8
}
sourceRecovery: pendingRecovery(8)
}
})
await session.reconnect(deps.mockConn)
@@ -559,15 +540,7 @@ describe('SshRelaySession recovery race fencing', () => {
}
attachForReconnectMock.mockResolvedValue({
incarnationId: 'incarnation-1',
sourceRecovery: {
status: 'pending',
clientGeneration: 2,
ownerGeneration: 2,
ptyIncarnation: 'incarnation-1',
deliveryToken: 'new-token',
checkpointSourceEndSu: 4,
recoveryEndSu: 12
},
sourceRecovery: pendingRecovery(12),
sourceActivationLease
})
@@ -651,15 +624,7 @@ describe('SshRelaySession recovery race fencing', () => {
})
return {
incarnationId: 'incarnation-1',
sourceRecovery: {
status: 'pending',
clientGeneration: 2,
ownerGeneration: 2,
ptyIncarnation: 'incarnation-1',
deliveryToken: 'new-token',
checkpointSourceEndSu: 4,
recoveryEndSu: 8
},
sourceRecovery: pendingRecovery(8),
sourceActivationLease: activationLease
}
})
@@ -704,6 +669,51 @@ describe('SshRelaySession recovery race fencing', () => {
}
)
it('overwrites the migration checkpoint with the post-recovery one for the same pty', async () => {
const targetId = 'post-recovery-checkpoint-rekey'
const { session, deps } = await prepareRecovery(targetId)
attachForReconnectMock.mockImplementation(async () => {
queueMicrotask(() => {
emitSourceFrame({
targetId,
token: 'new-token',
clientGeneration: 2,
ownerGeneration: 2,
sourceStartSu: 4,
sourceEndSu: 8
})
completeRecovery({
id: 'pty-1',
clientGeneration: 2,
ownerGeneration: 2,
ptyIncarnation: 'incarnation-1',
deliveryToken: 'new-token',
checkpointSourceEndSu: 4,
recoveryEndSu: 4
})
})
return { incarnationId: 'incarnation-1', sourceRecovery: pendingRecovery(4) }
})
await session.reconnect(deps.mockConn)
expect(acceptOutputDataMock).toHaveBeenCalledOnce()
// The pre-migration identity is gone from the intake, so only the checkpoint
// recorded after recovery can answer the next reconnect.
vi.mocked(getSshPtyAcceptedSourceCheckpoints).mockReturnValue([])
attachForReconnectMock.mockResolvedValue({
incarnationId: 'incarnation-1',
sourceRecovery: { status: 'restoreRequired', reason: 'checkpointUnavailable' }
})
await session.reconnect(deps.mockConn)
expect(attachForReconnectMock).toHaveBeenCalledTimes(2)
expect(attachForReconnectMock.mock.calls.at(-1)?.[2]).toMatchObject({
status: 'checkpoint',
deliveryToken: 'new-token',
acceptedSourceEndSu: 8
})
})
it('keeps a stale overlapping recovery from canceling or mutating its replacement', async () => {
const targetId = 'overlapping-recovery'
const { session, deps } = await prepareRecovery(targetId)
@@ -723,10 +733,7 @@ describe('SshRelaySession recovery race fencing', () => {
const ownerGeneration = openConsumerSessionMock.mock.calls.length
if (ownerGeneration === 3) {
queueMicrotask(() => {
const complete = onNotificationByMethodMock.mock.calls.findLast(
([method]) => method === 'pty.recoveryComplete'
)?.[1] as ((params: Record<string, unknown>) => void) | undefined
complete?.({
completeRecovery({
id: 'pty-1',
clientGeneration: 3,
ownerGeneration: 3,
+6 -2
View File
@@ -2119,6 +2119,8 @@ export class SshRelaySession {
}
const checkpoints = recovery?.checkpointsByAppPtyId
const relayPtyId = toRelaySshPtyId(this.targetId, appPtyId)
// Why: every checkpoint writer records app-id keys now, so the relay-id
// lookup (and its paired delete below) is a legacy guard only.
const checkpoint = checkpoints?.get(appPtyId) ?? checkpoints?.get(relayPtyId)
if (!checkpoint) {
return Object.freeze({ status: 'checkpointUnavailable' })
@@ -2273,10 +2275,12 @@ export class SshRelaySession {
(endSu, payload) => Math.max(endSu, payload.source?.sourceEndSu ?? endSu),
acceptedRecovery.recoveryEndSu
)
// Why: checkpoints are app-id keyed; a relay-id entry here would be shadowed
// by a staler app-id entry on the next sourceRecoveryRequest lookup.
ptyConsumerRecoveryByTarget.get(this.targetId)?.checkpointsByAppPtyId.set(
relayPtyId,
appPtyId,
Object.freeze({
id: relayPtyId,
id: appPtyId,
providerGeneration: this.activePtyProviderGeneration!,
clientGeneration: acceptedRecovery.clientGeneration,
ownerGeneration: acceptedRecovery.ownerGeneration,