feat(opencode): fork and rewind OpenCode v2 conversations (#2424)

This commit is contained in:
Junmo Kim
2026-11-13 08:35:45 +08:00
committed by GitHub
parent 06d9e51f5c
commit cad21ec6d0
72 changed files with 11236 additions and 575 deletions
+4
View File
@@ -40,6 +40,8 @@ export class MessageQueue2<T> {
private closed = false;
private onMessageHandler: ((message: string, mode: T) => void) | null = null;
onBatchConsumed: ((localIds: string[]) => void) | null = null;
/** Optional synchronous admission, before removing or acknowledging a batch. */
beforeDequeue: (() => void) | null = null;
modeHasher: (mode: T) => string;
private readonly reservations = new Map<string, QueueReservation<T>>();
private readonly consumedReservations = new Set<string>();
@@ -625,6 +627,8 @@ export class MessageQueue2<T> {
return null;
}
this.beforeDequeue?.();
const firstItem = this.queue[0];
const sameModeMessages: string[] = [];
const consumedLocalIds: string[] = [];
+75 -1
View File
@@ -10,7 +10,12 @@ vi.mock('cross-spawn', () => ({
}
}))
import { getHapiRunnerProcessIdentity, killProcess } from './process'
import { getHapiRunnerProcessIdentity, killProcess, killProcessTreeByPid } from './process'
import { monotonicTimeMs } from './time'
vi.mock('@/utils/time', async (original) => ({
...await original<typeof import('@/utils/time')>(), monotonicTimeMs: () => Date.now()
}))
const originalPlatformDescriptor = Object.getOwnPropertyDescriptor(process, 'platform')
@@ -40,6 +45,31 @@ function unavailable(command: string) {
}
}
describe('preparation signal deadline on POSIX', () => {
beforeEach(() => {
setPlatform('linux')
vi.useFakeTimers()
spawnSyncMock.mockReset()
spawnSyncMock.mockReturnValue({ status: 1, stdout: '', stderr: '' })
vi.spyOn(process, 'kill').mockReturnValue(true)
})
afterEach(() => {
vi.useRealTimers()
vi.restoreAllMocks()
if (originalPlatformDescriptor) Object.defineProperty(process, 'platform', originalPlatformDescriptor)
})
it('does not signal a tree after its preparation authorization expired', async () => {
expect(await killProcessTreeByPid(5544, false, undefined, monotonicTimeMs() - 1)).toBe(false)
expect(vi.mocked(process.kill).mock.calls.filter(([, signal]) => signal !== 0)).toEqual([])
})
it('does not escalate to SIGKILL after the lease expires during the graceful wait', async () => {
const stopped = killProcess(5544, false, monotonicTimeMs() + 100)
await vi.advanceTimersByTimeAsync(2500)
expect(await stopped).toBe(false)
expect(vi.mocked(process.kill).mock.calls.filter(([, signal]) => signal !== 0)).toEqual([[5544, 'SIGTERM']])
})
})
describe('getHapiRunnerProcessIdentity on Windows', () => {
it.each(['', '[]', '{}', '{broken', JSON.stringify([{ ProcessId: 100, CreationDate: 'generation' }]),
JSON.stringify([{ ProcessId: process.pid }, { ProcessId: process.pid }]),
@@ -293,6 +323,50 @@ describe('killProcess on Windows (orphanReap / stopSession)', () => {
}
})
it('retains the upstream stop report while an expired lease prevents signalling', async () => {
const reports: Array<import('./windowsProcessStop').WindowsStopReport> = []
spawnSyncMock.mockImplementation((cmd: string, args: string[] = []) => {
if (cmd === 'tasklist') return completed('hapi.exe 5544 Console')
if (cmd === 'powershell') return completed(args.join(' ').includes('$children=') ? 'OK:5544' : 'generation')
return completed('')
})
const stopped = killProcessTreeByPid(5544, false, (report) => reports.push(report), monotonicTimeMs() - 1)
await vi.advanceTimersByTimeAsync(2500)
expect(await stopped).toBe(false)
expect(spawnSyncMock.mock.calls.filter(([cmd]) => cmd === 'taskkill')).toHaveLength(0)
expect(reports).toHaveLength(1)
expect(reports[0]).toMatchObject({ confirmed: false, phase: 'initial-snapshot' })
})
it.each([false, true])('does not invoke taskkill when authority expires inside its liveness probe (force=%s)', async (force) => {
const deadline = monotonicTimeMs() + 100
let delayed = false
spawnSyncMock.mockImplementation((cmd: string) => {
if (cmd === 'tasklist') {
if (!delayed) { delayed = true; vi.advanceTimersByTime(100) }
return completed('hapi.exe 5544 Console')
}
return completed('')
})
const stopped = killProcess(5544, force, deadline)
await vi.advanceTimersByTimeAsync(2500)
expect(await stopped).toBe(false)
expect(spawnSyncMock.mock.calls.filter(([cmd]) => cmd === 'taskkill')).toHaveLength(0)
})
it('does not force taskkill when preparation expires during a refused soft signal', async () => {
const deadline = monotonicTimeMs() + 100
spawnSyncMock.mockImplementation((cmd: string) => {
if (cmd === 'tasklist') return completed('hapi.exe 5544 Console')
if (cmd === 'taskkill') { vi.advanceTimersByTime(100); return completed('', 1) }
return completed('')
})
const stopped = killProcess(5544, false, deadline)
await vi.advanceTimersByTimeAsync(2500)
expect(await stopped).toBe(false)
expect(spawnSyncMock.mock.calls.filter(([cmd]) => cmd === 'taskkill')).toHaveLength(1)
})
it('escalates soft taskkill to /F when the process stays alive (mirrors SIGTERM→SIGKILL)', async () => {
// Soft taskkill on win32 console trees often fails with
// "can only be terminated forcefully" — orphanReap must escalate.
+52 -36
View File
@@ -1,6 +1,7 @@
import type { ChildProcess } from 'node:child_process';
import spawn from 'cross-spawn';
import { readFileSync } from 'node:fs';
import { monotonicTimeMs } from '@/utils/time';
import { stopWindowsProcessTree, type WindowsStopReport } from './windowsProcessStop';
export const isWindows = (): boolean => process.platform === 'win32';
@@ -233,10 +234,11 @@ function getPosixProcessCommandLine(pid: number): string | null {
return commandLine.trim() ? commandLine : null;
}
function killProcessWindows(pid: number, force: boolean): boolean {
function killProcessWindows(pid: number, force: boolean, deadlineMs?: number): boolean {
if (!isProcessAlive(pid)) {
return true;
}
if (!signalAllowed(deadlineMs)) return false;
const args = ['/T', '/PID', pid.toString()];
if (force) {
@@ -343,22 +345,27 @@ export function collectWindowsProcessTree(pid: number): number[] | 'scan_failed'
return parseWindowsProcessTreeStdout((result.stdout ?? '').toString(), n)
}
async function signalAndWaitWindowsRoot(pid: number, force: boolean): Promise<void> {
if (force) {
killProcessWindows(pid, true);
await waitForProcessToDie(pid, true);
return;
}
const softOk = killProcessWindows(pid, false);
if (!softOk && isProcessAlive(pid)) {
killProcessWindows(pid, true);
await waitForProcessToDie(pid, true);
return;
}
await waitForProcessToDie(pid, false);
function signalAllowed(deadlineMs?: number): boolean {
return deadlineMs === undefined || monotonicTimeMs() < deadlineMs;
}
export async function killProcess(pid: number, force: boolean = false): Promise<boolean> {
async function signalAndWaitWindowsRoot(pid: number, force: boolean, deadlineMs?: number): Promise<void> {
if (!signalAllowed(deadlineMs)) return;
if (force) {
killProcessWindows(pid, true, deadlineMs);
await waitForProcessToDie(pid, true, deadlineMs);
return;
}
const softOk = killProcessWindows(pid, false, deadlineMs);
if (!softOk && isProcessAlive(pid) && signalAllowed(deadlineMs)) {
killProcessWindows(pid, true, deadlineMs);
await waitForProcessToDie(pid, true, deadlineMs);
return;
}
await waitForProcessToDie(pid, false, deadlineMs);
}
export async function killProcess(pid: number, force: boolean = false, deadlineMs?: number): Promise<boolean> {
const n = typeof pid === 'number' ? pid : Number(pid)
if (!Number.isFinite(n) || n <= 0) {
return false;
@@ -371,14 +378,15 @@ export async function killProcess(pid: number, force: boolean = false): Promise<
// but the PID is still draining, honor the grace wait before /F so archive
// flush can finish.
// Root-only verify — callers that need full-tree proof use killProcessTreeByPid.
await signalAndWaitWindowsRoot(n, force);
await signalAndWaitWindowsRoot(n, force, deadlineMs);
return !isProcessAlive(n);
}
try {
if (!signalAllowed(deadlineMs)) return !isProcessAlive(n);
process.kill(n, force ? 'SIGKILL' : 'SIGTERM');
await waitForProcessToDie(n, force);
return true;
await waitForProcessToDie(n, force, deadlineMs);
return deadlineMs === undefined || !isProcessAlive(n);
} catch {
return false;
}
@@ -425,11 +433,8 @@ function collectProcessTree(pid: number): number[] | 'scan_failed' {
* Signals are sent synchronously (children first) to work in exit handlers,
* then waits asynchronously for processes to die.
*/
async function killProcessTree(
pid: number,
force: boolean,
signal: NodeJS.Signals = 'SIGTERM'
): Promise<boolean> {
async function killProcessTree(pid: number, force: boolean, deadlineMs?: number,
signal: NodeJS.Signals = 'SIGTERM'): Promise<boolean> {
// Collect all PIDs first (sync) - returns in child-first order
const pids = collectProcessTree(pid);
if (pids === 'scan_failed') {
@@ -437,11 +442,12 @@ async function killProcessTree(
// stopped without a full-tree verify (#1911 Opus Major / debian-slim no pgrep).
const killSignal = force ? 'SIGKILL' : signal;
try {
if (!signalAllowed(deadlineMs)) return false;
process.kill(pid, killSignal);
} catch {
// already gone
}
await waitForProcessToDie(pid, force);
await waitForProcessToDie(pid, force, deadlineMs);
return false;
}
@@ -451,6 +457,7 @@ async function killProcessTree(
const killSignal = force ? 'SIGKILL' : signal;
for (const p of pids) {
try {
if (!signalAllowed(deadlineMs)) return false;
process.kill(p, killSignal);
} catch {
// Process may have already exited
@@ -459,7 +466,7 @@ async function killProcessTree(
// Wait for processes to die (async) - wait for root last
for (const p of pids) {
await waitForProcessToDie(p, force);
await waitForProcessToDie(p, force, deadlineMs);
}
return pids.every((candidate) => !isProcessAlive(candidate));
@@ -471,23 +478,29 @@ export async function killProcessTreeByPid(
force: boolean = false,
// 3rd arg: soft POSIX signal (#1424 job Ctrl-C → exit 130) OR Windows stop report (#1911).
signalOrReport: NodeJS.Signals | ((report: WindowsStopReport) => void) = 'SIGTERM',
onReportMaybe?: (report: WindowsStopReport) => void
// 4th arg: stop deadline (signal-lease budget) when numeric, else the Windows
// report fallback used when the 3rd arg is a signal (#1911).
deadlineOrFallbackReport?: number | ((report: WindowsStopReport) => void),
fallbackReport?: (report: WindowsStopReport) => void
): Promise<boolean> {
const signal: NodeJS.Signals = typeof signalOrReport === 'function' ? 'SIGTERM' : signalOrReport
const onReport = typeof signalOrReport === 'function' ? signalOrReport : onReportMaybe
const deadlineMs = typeof deadlineOrFallbackReport === 'number' ? deadlineOrFallbackReport : undefined;
const onReport = typeof signalOrReport === 'function' ? signalOrReport
: typeof deadlineOrFallbackReport === 'function' ? deadlineOrFallbackReport
: fallbackReport;
const signal: NodeJS.Signals = typeof signalOrReport === 'function' ? 'SIGTERM' : signalOrReport;
const n = typeof pid === 'number' ? pid : Number(pid)
if (!Number.isFinite(n) || n <= 0) return false;
if (isWindows()) {
return stopWindowsProcessTree(n, force, onReport);
return stopWindowsProcessTree(n, force, onReport, deadlineMs);
}
return killProcessTree(n, force, signal);
return killProcessTree(n, force, deadlineMs, signal);
}
/**
* Waits for a process to die, escalating if the graceful signal didn't work.
* POSIX: SIGTERM → SIGKILL. Windows: taskkill /T → taskkill /F /T.
*/
async function waitForProcessToDie(pid: number, force: boolean): Promise<void> {
async function waitForProcessToDie(pid: number, force: boolean, deadlineMs?: number): Promise<void> {
const maxWait = 2000;
// Windows isProcessAlive shells out to tasklist; keep the poll coarse so a
// stop cannot burn the runner event loop for seconds (#1911 Overseer).
@@ -504,10 +517,10 @@ async function waitForProcessToDie(pid: number, force: boolean): Promise<void> {
}
// Graceful kill didn't finish — escalate (same structure on both platforms).
if (!force && isProcessAlive(pid)) {
if (!force && isProcessAlive(pid) && signalAllowed(deadlineMs)) {
try {
if (isWindows()) {
killProcessWindows(pid, true);
killProcessWindows(pid, true, deadlineMs);
} else {
process.kill(pid, 'SIGKILL');
}
@@ -527,13 +540,16 @@ export async function killProcessByChildProcess(
child: ChildProcess,
force: boolean = false,
signalOrReport: NodeJS.Signals | ((report: WindowsStopReport) => void) = 'SIGTERM',
onReportMaybe?: (report: WindowsStopReport) => void
deadlineOrFallbackReport?: number | ((report: WindowsStopReport) => void),
fallbackReport?: (report: WindowsStopReport) => void
): Promise<boolean> {
const pid = child.pid;
if (!pid) {
return false;
}
// Soft signal forwarded on POSIX so job Ctrl-C stays exit 130 (#1424).
return killProcessTreeByPid(pid, force, signalOrReport, onReportMaybe);
// Both platforms: tree-kill + full-tree verify (win32 must not trust
// root-only). The soft signal rides along on POSIX so job Ctrl-C stays
// exit 130 (#1424).
return killProcessTreeByPid(pid, force, signalOrReport, deadlineOrFallbackReport, fallbackReport);
}
+8 -1
View File
@@ -1,3 +1,10 @@
import { uptime } from 'node:os';
/** OS-wide clock; whole seconds also match Bun's uptime precision across processes. */
export function monotonicTimeMs(): number {
return Math.floor(uptime()) * 1000;
}
export async function delay(ms: number) {
return new Promise(resolve => setTimeout(resolve, ms));
}
@@ -105,4 +112,4 @@ export async function withRetry<T>(
await delay(nextDelayMs)
}
}
}
}
+97
View File
@@ -1,8 +1,10 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
const { execFileMock, syncMock } = vi.hoisted(() => ({ execFileMock: vi.fn(), syncMock: vi.fn() }))
const authority = vi.hoisted(() => ({ now: 0 }))
vi.mock('node:child_process', () => ({ execFile: execFileMock }))
vi.mock('cross-spawn', () => ({ default: { sync: syncMock } }))
vi.mock('./time', () => ({ monotonicTimeMs: () => authority.now }))
import { killProcessTreeByPid } from './process'
import { readWindowsProcessTable, windowsGenerationMayBeAlive } from './windowsProcessStop'
@@ -20,6 +22,7 @@ describe('Windows asynchronous tree stop', () => {
beforeEach(() => {
Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' })
rows = [row(0, 0, null), row(100), row(200, 100)]
authority.now = 0
kills = []
rejectSoft = false
onKill = pid => { rows = rows.filter(p => p.ProcessId !== pid) }
@@ -50,6 +53,100 @@ describe('Windows asynchronous tree stop', () => {
expect(syncMock).not.toHaveBeenCalled()
})
it('retains the upstream stop report while an expired lease prevents signalling', async () => {
const reports: Array<import('./windowsProcessStop').WindowsStopReport> = []
authority.now = 100
expect(await killProcessTreeByPid(100, true, report => reports.push(report), 100)).toBe(false)
expect(kills).toEqual([])
expect(reports).toEqual([expect.objectContaining({ confirmed: false, phase: 'initial-snapshot' })])
expect(syncMock).not.toHaveBeenCalled()
})
it.each([1, 2])('does not signal after caller authority expires during async snapshot %s', async scan => {
let scans = 0
const implementation = execFileMock.getMockImplementation()!
execFileMock.mockImplementation((file, ...args) => {
if (file === 'powershell' && ++scans === scan) authority.now = 100
return implementation(file, ...args)
})
expect(await killProcessTreeByPid(100, true, undefined, 100)).toBe(false)
expect(kills).toEqual([])
})
it.each([false, true])('rejects a deferred generation snapshot completed after lease expiry (force=%s)', async force => {
let scans = 0
let snapshotBudget = 0
let resumeSnapshot!: () => void
let snapshotStarted!: () => void
const pendingSnapshot = new Promise<void>(resolve => { snapshotStarted = resolve })
const implementation = execFileMock.getMockImplementation()!
execFileMock.mockImplementation((file, args, options, callback) => {
if (file === 'powershell' && ++scans === 2) {
snapshotBudget = options.timeout
resumeSnapshot = () => callback(null, JSON.stringify({ complete: true, processes: rows }), '')
snapshotStarted()
return { kill: vi.fn() }
}
return implementation(file, args, options, callback)
})
const operation = killProcessTreeByPid(100, force, undefined, 100)
await pendingSnapshot
expect(authority.now).toBe(0)
expect(execFileMock.mock.calls.filter(([file]) => file === 'taskkill')).toEqual([])
authority.now = 100
resumeSnapshot()
expect(await operation).toBe(false)
expect(snapshotBudget).toBeLessThanOrEqual(100)
expect(execFileMock.mock.calls.filter(([file]) => file === 'taskkill')).toEqual([])
expect(kills).toEqual([])
expect(syncMock).not.toHaveBeenCalled()
})
it('caps async OS query budgets by remaining caller authority', async () => {
const budgets: number[] = []
const implementation = execFileMock.getMockImplementation()!
execFileMock.mockImplementation((file, args, options, callback) => {
budgets.push(options.timeout)
return implementation(file, args, options, callback)
})
expect(await killProcessTreeByPid(100, true, undefined, 100)).toBe(true)
expect(budgets.length).toBeGreaterThan(0)
expect(budgets.every(budget => budget > 0 && budget <= 100)).toBe(true)
})
it('does not escalate a refused soft stop after its caller lease expires', async () => {
rejectSoft = true
onKill = (_pid, force) => {
if (!force) { authority.now = 100; rows.push(row(300, 100)) }
else rows = [row(0, 0, null)]
}
expect(await killProcessTreeByPid(100, false, undefined, 100)).toBe(false)
expect(kills).toEqual([{ pid: 100, force: false, tree: true }])
})
it('does not signal surviving descendants after authority expires following root exit', async () => {
onKill = pid => {
rows = rows.filter(p => p.ProcessId !== pid)
if (pid === 100) authority.now = 100
}
expect(await killProcessTreeByPid(100, true, undefined, 100)).toBe(false)
expect(kills).toEqual([{ pid: 100, force: true, tree: true }])
})
it('does not use the CIM fallback root probe after its caller lease expires', async () => {
execFileMock.mockImplementation((file, args, _options, callback) => {
queueMicrotask(() => {
if (file === 'powershell') {
if (String(args.at(-1)).includes('Get-CimInstance')) callback(new Error('CIM failed'), '', '')
else { authority.now = 100; callback(null, JSON.stringify({ complete: true, processes: [row(100)] }), '') }
} else { kills.push({ pid: 100, force: true, tree: true }); callback(null, '', '') }
})
return { kill: vi.fn() }
})
expect(await killProcessTreeByPid(100, true, undefined, 100)).toBe(false)
expect(kills).toEqual([])
})
it('does not terminate a PID reused after the original descendant exits', async () => {
onKill = pid => {
rows = rows.filter(p => p.ProcessId !== pid)
+9 -3
View File
@@ -1,4 +1,5 @@
import { execFile } from 'node:child_process'
import { monotonicTimeMs } from './time'
export type WindowsProcessEntry = { parentPid: number; marker: string | null; name: string; commandLine: string }
export type WindowsProcessTable = Map<number, WindowsProcessEntry>
@@ -76,7 +77,8 @@ export function windowsGenerationMayBeAlive(table: WindowsProcessTable | null, p
}
export type WindowsStopReport = { confirmed: boolean; phase: string; elapsedMs: number; snapshots: number }
export async function stopWindowsProcessTree(rootPid: number, force: boolean, report?: (result: WindowsStopReport) => void): Promise<boolean> {
export async function stopWindowsProcessTree(rootPid: number, force: boolean, report?: (result: WindowsStopReport) => void,
callerDeadlineMs?: number): Promise<boolean> {
// Includes command startup, queries, signalling and verification, independent
// of tree size. Each async child is killed when its remaining budget expires.
const started = performance.now()
@@ -86,13 +88,17 @@ export async function stopWindowsProcessTree(rootPid: number, force: boolean, re
report?.({ confirmed, phase, elapsedMs: Math.round(performance.now() - started), snapshots })
return confirmed
}
const remaining = () => Math.max(0, deadline - performance.now())
// The cross-process preparation lease uses the OS-wide clock, not this
// process's performance origin. Cap budgets without comparing origins.
const remaining = () => Math.max(0, Math.min(deadline - performance.now(),
callerDeadlineMs === undefined ? Infinity : callerDeadlineMs - monotonicTimeMs()))
const signal = async (pid: number, hard: boolean, tree: boolean) => {
phase = 'signal'
return execute('taskkill', [
...(hard ? ['/F'] : []), ...(tree ? ['/T'] : []), '/PID', String(pid),
], Math.min(5_000, remaining()))
}
if (!remaining()) return finish(false)
const initial = await readWindowsProcessTable(Math.min(15_000, remaining()))
if (!initial) {
// A transient CIM failure must not leave the cancellation path with no
@@ -137,7 +143,7 @@ export async function stopWindowsProcessTree(rootPid: number, force: boolean, re
if (unresolved.has(rootPid) && rootMarker && current.get(rootPid)?.marker === rootMarker) {
const softAccepted = await signal(rootPid, force, true)
if (!force && softAccepted !== null) {
const graceDeadline = Math.min(deadline, performance.now() + 2_000)
const graceDeadline = performance.now() + Math.min(2_000, remaining())
while (unresolved.size && performance.now() < graceDeadline) {
current = await snapshot()
if (!current) return finish(false)