Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 87 additions & 0 deletions src/server/workerControl.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -493,6 +493,93 @@ describe('WorkerControlPlane', () => {
expect(events).toEqual(['from-owner'])
})

it('takes over a half-open socket when the reconnect hello claims the active run (pause client read so ping gets no pong)', async () => {
// Short lease + probe so we can prove takeover beats lease expiry without waiting 75s.
await ctx.close()
ctx = await startServer({ leaseMs: 250, socketProbeTimeoutMs: 80 })

const owner = await connectWorker(ctx, { workerId: 'fargate-run-1' })
const events: string[] = []
let exit: { status: string; exitCode: number | null | undefined } | undefined
const handlePromise = ctx.controlPlane.assignTo('fargate-run-1', SPEC, {
onEvent: (ev) => events.push(ev.text ?? ev.stream),
onExit: (status, exitCode) => {
exit = { status, exitCode }
},
})
expect(await owner.next()).toMatchObject({ type: 'run:assign', spec: SPEC })
owner.ws.send(JSON.stringify({ type: 'run:started', runId: SPEC.runId, workspacePath: '/tmp/owner' }))
await handlePromise

// Half-open: TCP still up (server readyState OPEN, no `close`), but the client
// no longer reads — so the server's probe ping never gets a pong.
const ownerRaw = (owner.ws as unknown as { _socket: { pause: () => void } })._socket
ownerRaw.pause()

const replacement = await connectSocket(ctx)
const inbound: ServerToWorkerMessage[] = []
replacement.on('message', (data) => {
inbound.push(JSON.parse(data.toString()) as ServerToWorkerMessage)
})
sendJson(replacement, {
type: 'worker:hello',
workerId: 'fargate-run-1',
capabilities: { runners: ['claude'], version: 'test' },
activeRunIds: [SPEC.runId],
pendingRunIds: [SPEC.runId],
})

await vi.waitFor(() => {
expect(inbound.some((m) => m.type === 'run:resume' && m.runId === SPEC.runId)).toBe(true)
})
expect(replacement.readyState).toBe(WebSocket.OPEN)
expect(ctx.controlPlane.connectedWorkerCount).toBe(1)

sendJson(replacement, {
type: 'worker:heartbeat',
workerId: 'fargate-run-1',
activeRunIds: [SPEC.runId],
})
sendJson(replacement, {
type: 'run:event',
runId: SPEC.runId,
events: [{ kind: 'raw', stream: 'stdout', text: 'after-takeover' }],
})
await vi.waitFor(() => {
expect(events).toEqual(['after-takeover'])
})

// Keep the new socket's lease warm across several check intervals. Without
// takeover the half-open peer cannot heartbeat and checkLeases would fail
// the run; with takeover, heartbeats on the replacement socket keep it alive.
const keepAlive = setInterval(() => {
if (replacement.readyState === WebSocket.OPEN) {
sendJson(replacement, {
type: 'worker:heartbeat',
workerId: 'fargate-run-1',
activeRunIds: [SPEC.runId],
})
}
}, 50)
try {
await new Promise((r) => setTimeout(r, 400))
expect(exit).toBeUndefined()
expect(ctx.controlPlane.activeAssignmentCount).toBe(1)
} finally {
clearInterval(keepAlive)
}

sendJson(replacement, {
type: 'run:exit',
runId: SPEC.runId,
status: 'completed',
exitCode: 0,
})
await vi.waitFor(() => {
expect(exit).toEqual({ status: 'completed', exitCode: 0 })
})
})

it('does not deliver events from one run onto another run\'s sink', async () => {
const a = await connectWorker(ctx, { workerId: 'wa' })
const b = await connectWorker(ctx, { workerId: 'wb' })
Expand Down
116 changes: 113 additions & 3 deletions src/server/workerControl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,14 @@ const DEFAULT_EXIT_RETRY_INITIAL_DELAY_MS = 500
/** Ceiling for the exponential backoff between those re-drives. */
const DEFAULT_EXIT_RETRY_MAX_DELAY_MS = 15_000

/**
* How long to wait for a WebSocket pong when probing whether a socket that still
* holds assignments is alive. A half-open peer never answers; a live `ws` client
* pongs immediately. Kept short so a reconnecting worker can take over well
* inside `WORKER_LEASE_MS`. Tests may override via `socketProbeTimeoutMs`.
*/
const DEFAULT_SOCKET_PROBE_TIMEOUT_MS = 300

function parsePositiveMs(raw: string | undefined, fallback: number): number {
const n = Number(raw)
return Number.isFinite(n) && n > 0 ? n : fallback
Expand Down Expand Up @@ -85,6 +93,11 @@ export interface WorkerControlPlaneOptions {
exitRetryInitialDelayMs?: number
/** Ceiling for that backoff (default 15000). */
exitRetryMaxDelayMs?: number
/**
* Ping/pong wait when deciding whether a duplicate-identity hello may take
* over a socket that still holds assignments. Tests inject a short value.
*/
socketProbeTimeoutMs?: number
/** Reconstruct a binding when a reconnecting worker reports a run this process does not hold. */
recoverRun?: RecoverRun
/** Tests inject a gated writer to prove per-run serialize-during-fsync. */
Expand Down Expand Up @@ -205,6 +218,7 @@ export class WorkerControlPlane {
private readonly runLogMaxBytes: number
private readonly exitRetryInitialDelayMs: number
private readonly exitRetryMaxDelayMs: number
private readonly socketProbeTimeoutMs: number
private readonly recoverRun?: RecoverRun
private readonly openLog: OpenDeliveryLog
private nextAssignmentGeneration = 1
Expand All @@ -228,6 +242,7 @@ export class WorkerControlPlane {
this.exitRetryInitialDelayMs =
options?.exitRetryInitialDelayMs ?? DEFAULT_EXIT_RETRY_INITIAL_DELAY_MS
this.exitRetryMaxDelayMs = options?.exitRetryMaxDelayMs ?? DEFAULT_EXIT_RETRY_MAX_DELAY_MS
this.socketProbeTimeoutMs = options?.socketProbeTimeoutMs ?? DEFAULT_SOCKET_PROBE_TIMEOUT_MS
this.recoverRun = options?.recoverRun
this.openLog = options?.openDeliveryLog ?? openDeliveryLog
this.wss.on('connection', (ws) => this.onConnection(ws))
Expand Down Expand Up @@ -543,10 +558,42 @@ export class WorkerControlPlane {
const existing = this.workers.get(msg.workerId)
if (existing && existing.ws !== ws) {
if (this.hasAssignmentsOn(existing.ws)) {
ctx.rejectSocket(4002, 'duplicate identity with active assignment')
break
const claimed = [...msg.activeRunIds, ...(msg.pendingRunIds ?? [])]
const mayTakeOver = this.claimsIntersectWorkerAssignments(msg.workerId, claimed)
if (!mayTakeOver) {
ctx.rejectSocket(4002, 'duplicate identity with active assignment')
break
}
const oldWs = existing.ws
const alive = await this.probeSocketAlive(oldWs)
if (ctx.closed()) break
// Re-read after the probe await — another hello may have moved the binding.
const current = this.workers.get(msg.workerId)
if (current?.ws === ws) {
// Already bound to this socket (racing hello completed); refresh below.
} else if (
alive &&
oldWs.readyState === WebSocket.OPEN &&
current?.ws === oldWs
) {
ctx.rejectSocket(4002, 'duplicate identity with active assignment')
break
} else if (current?.ws === oldWs || !current) {
// Half-open / dead peer: move the identity onto this socket. Do not
// failRunsOfWorker — the reconnecting worker still owns the runs.
this.seizeWorkerSocket(msg.workerId, oldWs, ws)
console.warn(
`[worker-control] Worker ${msg.workerId} reclaimed half-open socket ` +
`(claimed ${claimed.length} run id(s))`
)
} else {
// A different live socket already holds this identity.
ctx.rejectSocket(4002, 'duplicate identity with active assignment')
break
}
} else {
existing.ws.close(4000, 'replaced by new connection')
}
existing.ws.close(4000, 'replaced by new connection')
}
ctx.workerId = msg.workerId
this.workers.set(msg.workerId, {
Expand Down Expand Up @@ -1147,6 +1194,69 @@ export class WorkerControlPlane {
return false
}

/** True when any claimed run id is currently assigned to this workerId. */
private claimsIntersectWorkerAssignments(workerId: string, claimed: string[]): boolean {
if (claimed.length === 0) return false
const assigned = new Set<string>()
for (const a of this.runs.values()) {
if (a.workerId === workerId) assigned.add(a.spec.runId)
}
for (const id of claimed) {
if (assigned.has(id)) return true
}
return false
}

/**
* Ping the peer and wait briefly for a pong. Half-open TCP leaves readyState
* OPEN but never answers; live Node `ws` clients auto-pong.
*/
private probeSocketAlive(ws: WebSocket): Promise<boolean> {
if (ws.readyState !== WebSocket.OPEN) return Promise.resolve(false)
return new Promise((resolve) => {
let settled = false
const finish = (alive: boolean): void => {
if (settled) return
settled = true
clearTimeout(timer)
ws.off('pong', onPong)
resolve(alive)
}
const onPong = (): void => finish(true)
const timer = setTimeout(() => finish(false), this.socketProbeTimeoutMs)
ws.once('pong', onPong)
try {
ws.ping()
} catch {
finish(false)
}
})
}

/**
* Bind a reconnecting socket over a dead/half-open peer that still owns this
* workerId's assignments. Updates the registry before tearing down the old
* socket so its `close` handler does not detach or fail the runs.
*/
private seizeWorkerSocket(workerId: string, oldWs: WebSocket, newWs: WebSocket): void {
for (const a of this.runs.values()) {
if (a.workerId !== workerId) continue
this.clearReconnectTimer(a)
a.ws = newWs
}
const worker = this.workers.get(workerId)
if (worker && worker.ws === oldWs) {
worker.ws = newWs
worker.lastHeartbeat = Date.now()
}
try {
// terminate: a half-open peer may never complete a clean close handshake.
oldWs.terminate()
} catch {
// already destroyed
}
}

/** True when a prior attempt on this socket timed out (different generation). */
private hasStaleSuppression(runId: string, ws: WebSocket, generation: number): boolean {
for (const entry of this.ignoreNextStarted) {
Expand Down
Loading