@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
137 lines • 8.04 kB
JavaScript
/**
* Which generations of one daemon are still RUNNING, and what a dead one leaves behind.
*
* The daemon directory accumulates a record per generation, and nothing used to remove one: after a
* handoff, an idle exit or a kill, `generations/<instanceId>/host.pid` stayed, the pointer could go
* on naming a process nobody runs, and `reservations/` kept claims of hosts that had been gone for
* days (#1893: the directory described only dead pids while three supervisors were alive). Reading
* it therefore has to mean pruning it - a record that names a pid nobody is running is not history,
* it is a lie about what serves this endpoint.
*
* Both answers come from files rather than from the socket on purpose: a generation that no longer
* answers is exactly what an operator is looking for, and a superseded host holding gigabytes
* cannot be asked how many sessions it has.
*/
import { randomUUID } from "node:crypto";
import { link, readdir, rename, rm } from "node:fs/promises";
import { processIsLive } from "../../utils/process-identity.js";
import { generationPaths } from "./host-daemon-paths.js";
import { parseJson, readFileOrUndefined } from "./host-daemon-state.js";
import { readHostProcessMetrics } from "./host-process-metrics.js";
import { claimOwnerIdentity, readSessionPathClaims } from "./host-reservations.js";
import { hostChildAlive } from "./host-stalled-evidence.js";
/**
* Drops every record of a generation that is no longer running: its directory, the pointer while it
* still names it, and the session-path claims its pid published. A record that cannot be parsed is
* LEFT - an ensure writing one right now must not be mistaken for a generation that ended.
*/
export async function pruneDeadGenerations(paths, options = {}) {
const pointerText = await readFileOrUndefined(paths.pointerFile).catch(() => undefined);
const pointer = parseJson(pointerText);
const pointedAt = typeof pointer?.instance_id === "string" ? pointer.instance_id : undefined;
const generations = [];
for (const instanceId of await readdir(paths.generationsDir).catch(() => [])) {
const record = parseJson(await readFileOrUndefined(generationPaths(paths, instanceId).pidFile));
if (typeof record?.pid !== "number" || processIsLive(record.pid))
continue;
if (await hostChildAlive(generationPaths(paths, instanceId)))
continue;
generations.push(instanceId);
}
// Claims end before the directories go: a prune cut short in between must not leave a claim whose generation
// (and heartbeat) no longer exists to explain it.
const claims = await endClaimsOfEndedGenerations(paths, new Set(generations));
for (const instanceId of generations)
await rm(generationPaths(paths, instanceId).dir, { recursive: true, force: true }).catch(() => undefined);
// The pointer outliving its generation is what makes a client probe a socket nobody serves.
const pointerNamesDead = pointerText !== undefined && pointedAt !== undefined && generations.includes(pointedAt);
if (pointerNamesDead)
await options._test?.beforePointerRemoval?.();
const pointerRemoved = pointerNamesDead && (await removePointerIfUnchanged(paths, pointerText));
return { generations, claims, pointer: pointerRemoved };
}
/**
* Removes the pointer only while it is still the one this prune read (senpi#1911). Prune runs outside the
* ensure lock (`host status`), so a registration may have renamed a new pointer in since: the file is
* moved aside atomically, compared, and a replacement is linked back unless an even newer one landed.
*/
async function removePointerIfUnchanged(paths, read) {
const parked = `${paths.pointerFile}.prune-${process.pid}-${randomUUID()}.tmp`;
const moved = await rename(paths.pointerFile, parked).then(() => true, () => false);
if (!moved)
return false;
const unchanged = (await readFileOrUndefined(parked).catch(() => undefined)) === read;
if (!unchanged)
await link(parked, paths.pointerFile).catch(() => undefined);
await rm(parked, { force: true }).catch(() => undefined);
return unchanged;
}
/**
* Removes every claim whose owner is gone, and every claim of a generation in `ended` (being removed by the caller)
* whose owner identity cannot be proven. Returns the session paths released. Every path that removes a generation
* directory calls this first, so no generation leaves claims behind that its directory no longer explains.
*/
export async function endClaimsOfEndedGenerations(paths, ended) {
const claims = [];
for (const claim of await readSessionPathClaims(paths.reservationsDir)) {
if (!(await claimEnded(claim.owner, ended)))
continue;
await rm(claim.file, { force: true }).catch(() => undefined);
claims.push(claim.owner.sessionPath);
}
return claims;
}
/**
* A claim ends with its owner's pid, or with the generation this prune just removed when the owner's identity
* cannot be proven (desktop#3157: Windows hands the dead host child's pid to another process, and removing the
* generation also removed the heartbeat that would have released the claim). Such an owner might only be frozen,
* so its session file is fenced first; a fence that cannot be written keeps the claim.
*/
async function claimEnded(owner, ended) {
const identity = await claimOwnerIdentity(owner);
if (identity === "gone")
return true;
if (identity === "proven" || !ended.has(owner.instanceId))
return false;
// Documented lazy boundary (AGENTS.md: inline dynamic imports only at documented lazy boundaries): the lifecycle
// supervisor imports this module, and the fence module (whose writers read it synchronously) must stay out of its
// startup graph (test/supervisor-import-graph.test.ts).
return import("../../core/session-write-fence.js")
.then(({ advanceSessionFence }) => advanceSessionFence(owner.sessionPath))
.then(() => true, () => false);
}
function memoryOf(metrics) {
return { rss_mb: metrics.rss_mb, host_rss_mb: metrics.host_rss_mb };
}
/**
* Every generation of this daemon that is still running, newest ordinal last. A record naming a
* dead pid is omitted rather than reported as history: `host status` answers who is alive now.
* `includeDead` is for the reader that must not prune (`host status --all`): a dead record is then
* reported as a row with `alive: false` instead of being dropped, so the stale state stays visible.
*/
export async function readGenerationRows(paths, options = {}) {
const pointer = parseJson(await readFileOrUndefined(paths.pointerFile).catch(() => undefined));
const currentId = typeof pointer?.instance_id === "string" ? pointer.instance_id : undefined;
const claims = await readSessionPathClaims(paths.reservationsDir);
const rows = [];
for (const instanceId of await readdir(paths.generationsDir).catch(() => [])) {
const record = parseJson(await readFileOrUndefined(generationPaths(paths, instanceId).pidFile));
if (typeof record?.pid !== "number")
continue;
const alive = processIsLive(record.pid) || (await hostChildAlive(generationPaths(paths, instanceId))) === true;
if (!alive && options.includeDead !== true)
continue;
rows.push({
instanceId,
generation: typeof record.generation === "number" ? record.generation : 0,
pid: record.pid,
engineVersion: typeof record.engineVersion === "string" ? record.engineVersion : null,
...(alive ? memoryOf(await readHostProcessMetrics(record.pid)) : { rss_mb: null, host_rss_mb: null }),
sessions: claims.filter((claim) => claim.owner.instanceId === instanceId).length,
current: instanceId === currentId,
alive,
});
}
return rows.sort((left, right) => left.generation - right.generation);
}
//# sourceMappingURL=host-generations.js.map