@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
200 lines • 9.35 kB
JavaScript
import { rm } from "node:fs/promises";
import { releaseGeneration } from "./host-daemon-registration.js";
import { closeServer } from "./host-lifecycle-proxy.js";
import { waitOutStalledChild } from "./host-lifecycle-stall-wait.js";
import { CHILD_KILL_EXIT_TIMEOUT_MS, CHILD_STOP_TIMEOUT_MS, layeredSupervisorIntent, readStopIntent, writeStopIntent, } from "./host-stop-intent.js";
import { errorMessage, supervisorLog, writeStderrLine } from "./host-supervisor-log.js";
import { closeShieldedEndpoint, unlinkOwnedEndpoint } from "./host-endpoint-owner.js";
export { CHILD_STOP_TIMEOUT_MS } from "./host-stop-intent.js";
/** Win32 named-pipe shutdown can leave supervisor handles live after close starts. */
const WINDOWS_SUPERVISOR_SHUTDOWN_HARD_EXIT_MS = 2_000;
export function supervisorSender(instanceId) {
return { pid: process.pid, kind: "supervisor", generation: instanceId };
}
export function childExited(child) {
return child.exitCode !== null || child.signalCode !== null;
}
export async function performShutdown(context, reason, exitCode) {
const { state, child } = context;
state.shuttingDown = true;
state.shutdownReason = reason;
context.admission.stop();
let childStopStarted = false;
let hardExit;
try {
context.drain.stop();
writeStderrLine(`senpi rpc host supervisor: ${reason} shutdown`);
// No fallible socket/metadata cleanup may bypass the child's observed exit.
childStopStarted = true;
await stopChild(context, reason);
await state.childExitRecorded;
// The startup caller reports its failure; this join only waits until its writes have stopped.
await state.startupComplete.then(undefined, () => { });
context.stopWatchers();
await context.admission.flush();
context.activity.clients.destroyAll();
if (process.platform === "win32")
hardExit = setTimeout(() => process.exit(exitCode), WINDOWS_SUPERVISOR_SHUTDOWN_HARD_EXIT_MS);
// libuv unlinks the bound NAME when the listening handle closes - which would delete a newer
// host's entry renamed over this path. Shield the current entry for the close, then let the
// ownership check decide. A drained supervisor already stopped accepting. Both run under the endpoint's
// mutation fence and re-read its owner token, so neither can land over a successor's adoption (senpi#4602).
if (!context.drain.active)
await closeShieldedEndpoint(context.publicSocket, () => closeServer(context.server));
if (context.internalDir)
await rm(context.internalDir, { recursive: true, force: true });
context.activity.stopObserver();
if (state.publicSocketOwned && process.platform !== "win32") {
// Ownership-checked: after a takeover a newer host may have published a fresh entry here.
await unlinkOwnedEndpoint(context.publicSocket, state.publicSocketIdentity, context.instanceId, supervisorLog);
}
// After a handoff the pointer describes the SUCCESSOR, so this drops only the generation
// directory of the process that is leaving, and the pointer only while it still names it. A
// generation whose socket was taken over leaves the pointer and settings to the replacer (#2536).
await releaseGeneration(context.paths, {
instanceId: context.instanceId,
pid: process.pid,
superseded: state.endpointReplaced,
});
}
catch (cause) {
// In particular, an unobserved child exit leaves its generation, pointer and settings intact.
supervisorLog(`shutdown failed for host child pid ${child.pid ?? "unknown"}: ${errorMessage(cause)}`);
exitCode = 1;
try {
if (!childStopStarted)
await reapChildAfterFailure(child);
await state.childExitRecorded;
}
catch (reapCause) {
supervisorLog(`shutdown recovery failed for host child pid ${child.pid ?? "unknown"}: ${errorMessage(reapCause)}`);
}
}
finally {
await context.publicEndpoint?.dispose().catch((cause) => {
supervisorLog(`endpoint key cleanup failed: ${errorMessage(cause)}`);
});
if (hardExit)
clearTimeout(hardExit);
// Windows named-pipe handles can outlive their JavaScript wrappers, so cleanup failure must
// never leave the supervisor resident or the host orphaned.
process.exit(exitCode);
}
}
/**
* SIGTERM, then SIGKILL after `CHILD_STOP_TIMEOUT_MS` - or, for a child that is alive but stalled, after
* the bounded stall wait. The intent is on record BEFORE the signal, layered over any outer sender's
* intent for this generation so the record names who started it, and names a stall-wait escalation.
*/
async function stopChild(context, reason) {
const { child, generation } = context;
const pid = child.pid;
if (childExited(child) || pid === undefined)
return;
let termAttempted = false;
let killAttempted = false;
try {
const outer = await readStopIntent(generation).catch((cause) => {
supervisorLog(`cannot read child stop intent: ${errorMessage(cause)}`);
return undefined;
});
const at = new Date().toISOString();
const intent = layeredSupervisorIntent(outer, supervisorSender(context.instanceId), {
targetPid: pid,
reason,
at,
});
await writeStopIntent(generation, intent, supervisorLog);
const signalledAt = Date.now();
termAttempted = true;
signalChild(pid, "SIGTERM");
if (await waitForChildExit(child, CHILD_STOP_TIMEOUT_MS))
return;
const stallWaitMs = await waitOutStalledChild({
child,
generation,
signalledAt,
waitForExit: waitForChildExit,
});
if (childExited(child))
return;
if (stallWaitMs > 0) {
const escalated = { ...intent, reason: `${intent.reason}; escalated_after_stall_wait=${stallWaitMs}` };
await writeStopIntent(generation, escalated, supervisorLog);
}
killAttempted = true;
signalChild(pid, "SIGKILL");
// SIGKILL cannot be ignored; the bound is only a circuit breaker for an uninterruptible kernel wait.
if (!(await waitForChildExit(child, CHILD_KILL_EXIT_TIMEOUT_MS)))
throw new Error(`host child pid ${pid} exit unobserved ${CHILD_KILL_EXIT_TIMEOUT_MS}ms after SIGKILL`);
}
catch (cause) {
// Metadata/watch failures must not leave a child behind. A fired exit breaker is already
// the final bound: never restart it or enlarge the normal caller's shutdown budget.
if (!killAttempted) {
try {
await reapChildAfterFailure(child, termAttempted);
}
catch (reapCause) {
// Log only the recovery error here: performShutdown logs the original
// failure once when this rethrow reaches it, so logging it here too
// would print the same line twice (#6144 review).
supervisorLog(`shutdown recovery failed for host child pid ${pid ?? "unknown"}: ${errorMessage(reapCause)}`);
}
}
throw cause;
}
}
async function reapChildAfterFailure(child, termAttempted = false) {
const pid = child.pid;
if (childExited(child) || pid === undefined)
return;
if (!termAttempted) {
signalChild(pid, "SIGTERM");
if (await waitForChildExit(child, CHILD_STOP_TIMEOUT_MS))
return;
}
signalChild(pid, "SIGKILL");
if (!(await waitForChildExit(child, CHILD_KILL_EXIT_TIMEOUT_MS)))
throw new Error(`host child pid ${pid} exit unobserved ${CHILD_KILL_EXIT_TIMEOUT_MS}ms after recovery SIGKILL`);
}
function signalChild(pid, signal) {
try {
process.kill(pid, signal);
return true;
}
catch {
return false;
}
}
export function waitForChildExit(child, timeoutMs) {
if (childExited(child))
return Promise.resolve(true);
return new Promise((resolve) => {
const timer = setTimeout(() => {
child.off("exit", onExit);
resolve(false);
}, timeoutMs);
const onExit = () => {
clearTimeout(timer);
resolve(true);
};
child.once("exit", onExit);
});
}
/**
* External stop (ensureHost replacement, tests, QA) must clean up like idle exit; SIGUSR1 is the
* gentler request - finish what you are doing and leave - that a generation handoff and
* `stopHost({ drain: true })` both send to a host from before the drain request. It exists on POSIX
* only: on win32 the drain arrives as a drain request (host-stop-intent.ts), never as a signal.
*/
export function registerSupervisorSignals(shutdown, drain) {
for (const signal of process.platform === "win32" ? ["SIGTERM"] : ["SIGTERM", "SIGHUP"]) {
process.on(signal, () => {
void shutdown(`signal:${signal}`, signal === "SIGHUP" ? 129 : 143);
});
}
if (process.platform !== "win32")
process.on("SIGUSR1", drain);
}
//# sourceMappingURL=host-lifecycle-shutdown.js.map