opencode-model-router 2.10.0 → 2.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +306 -0
- package/README.md +3 -2
- package/package.json +8 -1
- package/src/compat/background.ts +5 -0
- package/src/compat/session-lookup.ts +21 -0
- package/src/compat/v2-hooks.ts +256 -88
- package/src/compat/v2-observations.ts +1 -0
- package/src/compat/v2-vocabulary.ts +14 -0
- package/src/executor/create.ts +3 -0
- package/src/executor/git.ts +110 -26
- package/src/executor/integrate/checks.ts +29 -11
- package/src/executor/integrate/queue.ts +95 -13
- package/src/executor/ledger.ts +16 -12
- package/src/executor/lfs-restore.ts +492 -0
- package/src/executor/paths.ts +7 -2
- package/src/executor/recovery.ts +2 -1
- package/src/executor/runtime.ts +1010 -226
- package/src/executor/slots/pool.ts +120 -19
- package/src/executor/slots/provision.ts +111 -23
- package/src/executor/slots/root.ts +81 -0
- package/src/executor/types.ts +28 -2
- package/src/executor/unattended.ts +6 -1
- package/src/executor/verify-trees.ts +507 -0
- package/src/guard/enforce.ts +2 -1
- package/src/guard/fingerprint.ts +9 -0
- package/src/guard/guards.ts +7 -1
- package/src/index.ts +107 -27
- package/src/router/answer-dedup.ts +198 -0
- package/src/router/common-dir.ts +241 -0
- package/src/router/config.ts +71 -12
- package/src/router/diff-handles.ts +322 -0
- package/src/router/diff-summary.ts +318 -0
- package/src/router/git-metadata-guard.ts +144 -7
- package/src/router/git-tools.ts +930 -73
- package/src/router/role-agents.ts +100 -36
- package/src/router/run-summary.ts +253 -0
- package/src/router/run-tools.ts +145 -23
- package/src/router/sessions.ts +14 -1
- package/src/routing/classify/rules.ts +93 -14
- package/src/routing/wire/hint.ts +9 -2
- package/src/v2.ts +3 -1
- package/src/verify/exec.ts +454 -2
- package/src/verify/plan-task.ts +86 -26
- package/src/verify/runner.ts +14 -6
- package/src/verify/tree.ts +5 -1
- package/src/verify/types.ts +44 -0
- package/src/verify/wiring.ts +87 -10
package/src/verify/exec.ts
CHANGED
|
@@ -40,13 +40,16 @@
|
|
|
40
40
|
* Not covered: death by an unhandled signal (the host's SIGTERM/SIGHUP/Ctrl-C
|
|
41
41
|
* policy), which skips `exit` hooks and remains opencode's concern, and on
|
|
42
42
|
* Windows what an already-exited direct child left running (only the sweep
|
|
43
|
-
* reaches that).
|
|
43
|
+
* reaches that). #189 R2-pre-2: for v2 plan-task verifications the executor
|
|
44
|
+
* records each root through `onSpawn`/`onSettle` and, at the next activation,
|
|
45
|
+
* ends what a dead server left running with `killRecordedTrees`.
|
|
44
46
|
*/
|
|
45
47
|
import { execFile, spawn, spawnSync, type ChildProcess, type SpawnOptions } from "node:child_process";
|
|
48
|
+
import { readFileSync } from "node:fs";
|
|
46
49
|
import { constants as osConstants, setPriority, tmpdir } from "node:os";
|
|
47
50
|
import { join } from "node:path";
|
|
48
51
|
import type { SlotEnv } from "../executor/slots/env";
|
|
49
|
-
import type { ArgvSeam, ExecOptions, ExecSeam } from "./types";
|
|
52
|
+
import type { ArgvSeam, ExecOptions, ExecSeam, SpawnedProcess } from "./types";
|
|
50
53
|
|
|
51
54
|
export interface ShellResult {
|
|
52
55
|
code: number;
|
|
@@ -86,6 +89,13 @@ function observeProcess(opts: RunOptions, event: "prepare" | "start" | "end", re
|
|
|
86
89
|
} catch { /* Diagnostics only. */ }
|
|
87
90
|
}
|
|
88
91
|
|
|
92
|
+
/** #189 R2-pre-2: the spawn hooks follow the same rule as the diagnostic hooks: a throw never reaches the run. */
|
|
93
|
+
function reportProcess(opts: RunOptions, event: "onSpawn" | "onSettle", root: SpawnedProcess): void {
|
|
94
|
+
try {
|
|
95
|
+
opts[event]?.(root);
|
|
96
|
+
} catch { /* A journal failure never affects the run. */ }
|
|
97
|
+
}
|
|
98
|
+
|
|
89
99
|
export const DEFAULT_TIMEOUT_MS = 120_000;
|
|
90
100
|
/** After a kill, the longest the result waits for the output pipes to close. */
|
|
91
101
|
export const KILL_GRACE_MS = 2000;
|
|
@@ -247,6 +257,11 @@ function run(file: string, args: string[], shell: boolean, opts: RunOptions, nic
|
|
|
247
257
|
// After the priority call, which must follow the spawn as closely as possible.
|
|
248
258
|
const trackToken = Symbol("run");
|
|
249
259
|
if (pid) track(pid, trackToken);
|
|
260
|
+
// #189 R2-pre-2: the root is reported before any output is read, so a journal holds it before the run can settle.
|
|
261
|
+
const spawned: SpawnedProcess | undefined = pid
|
|
262
|
+
? { pid, startedAtMs: spawnedAt, pgid: isWin ? null : pid, deadlineMs: deadline ?? null }
|
|
263
|
+
: undefined;
|
|
264
|
+
if (spawned !== undefined) reportProcess(opts, "onSpawn", spawned);
|
|
250
265
|
// A StringDecoder per stream, so a multi-byte character split across two
|
|
251
266
|
// chunks is not turned into U+FFFD.
|
|
252
267
|
child.stdout?.setEncoding("utf8");
|
|
@@ -280,6 +295,7 @@ function run(file: string, args: string[], shell: boolean, opts: RunOptions, nic
|
|
|
280
295
|
// (QA-1.2-19); one that is only armed is released.
|
|
281
296
|
if (sweeper && sweepPending) sweeper.unref();
|
|
282
297
|
else sweeper?.dispose();
|
|
298
|
+
if (spawned !== undefined) reportProcess(opts, "onSettle", spawned);
|
|
283
299
|
let finalCode = killed ? code || 1 : code ?? 1;
|
|
284
300
|
let stderr = err.text;
|
|
285
301
|
if (niceTarget && !killed && (code === 126 || code === 127) && stderr.startsWith("nice:")) {
|
|
@@ -369,6 +385,12 @@ function run(file: string, args: string[], shell: boolean, opts: RunOptions, nic
|
|
|
369
385
|
exited = true;
|
|
370
386
|
exitCode = code;
|
|
371
387
|
exitedAt = Date.now();
|
|
388
|
+
// #189 R2-pre-2: nothing the root started can be created after this (a journal bounds its children by it).
|
|
389
|
+
if (spawned !== undefined) {
|
|
390
|
+
try {
|
|
391
|
+
opts.onExit?.(spawned, exitedAt);
|
|
392
|
+
} catch { /* A journal failure never affects the run. */ }
|
|
393
|
+
}
|
|
372
394
|
// Windows: libuv has closed the child's handle, so its PID may be recycled from here on.
|
|
373
395
|
if (isWin && pid) untrack(pid, trackToken);
|
|
374
396
|
if (!isWin && pid && !groupAlive(pid)) {
|
|
@@ -752,3 +774,433 @@ function armSweeper(pid: number, spawnedAt: number, exitedAt: number): Sweeper {
|
|
|
752
774
|
},
|
|
753
775
|
};
|
|
754
776
|
}
|
|
777
|
+
|
|
778
|
+
// ---- #189 R2-pre-2: the trees a dead server's verification left running --------------------------------------
|
|
779
|
+
|
|
780
|
+
/** One root a dead server's plan-task verification recorded through `onSpawn` (and `onExit`). */
|
|
781
|
+
export interface RecordedRoot {
|
|
782
|
+
readonly pid: number;
|
|
783
|
+
readonly startedAtMs: number;
|
|
784
|
+
readonly pgid: number | null;
|
|
785
|
+
/** Text the root's command line contains: the shell command of a shell run, the executable of an argv run. */
|
|
786
|
+
readonly command: string;
|
|
787
|
+
/** The run's deadline after `startedAtMs` (SpawnedProcess.deadlineMs); null without one. */
|
|
788
|
+
readonly deadlineMs: number | null;
|
|
789
|
+
/** When the root was seen exiting (`onExit`); null when its server died first. */
|
|
790
|
+
readonly exitedAtMs: number | null;
|
|
791
|
+
/** POSIX: the root's /proc start time in clock ticks, read at spawn; null when not read (Windows, or already gone). */
|
|
792
|
+
readonly startTicks: number | null;
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
/** The roots one journal (one attempt in one slot) recorded, and the server that recorded them. */
|
|
796
|
+
export interface RecordedTreeGroup {
|
|
797
|
+
readonly serverPid: number;
|
|
798
|
+
/** The server's process start (ms epoch). */
|
|
799
|
+
readonly serverStartedAtMs: number;
|
|
800
|
+
/** POSIX: the server's /proc start ticks; null when not recorded. */
|
|
801
|
+
readonly serverStartTicks: number | null;
|
|
802
|
+
/**
|
|
803
|
+
* The server pid answered a liveness probe. The sweep then checks the process holding it by its start (Windows: its
|
|
804
|
+
* creation time within SERVER_START_SLACK_MS of `serverStartedAtMs`; POSIX: its start ticks) and leaves the group alone
|
|
805
|
+
* when that is the server; any other process holding the pid is a later owner, so the server is dead (L8).
|
|
806
|
+
*/
|
|
807
|
+
readonly serverPidLive: boolean;
|
|
808
|
+
/**
|
|
809
|
+
* The newest time the server was seen alive through its journal's heartbeat (the file's mtime plus the heartbeat
|
|
810
|
+
* interval and its slack); null when unknown. A dead root's child created after it is reported, never killed: nothing
|
|
811
|
+
* recorded the root past that time, so such a child may belong to a later owner of the root's pid.
|
|
812
|
+
*/
|
|
813
|
+
readonly recordedUntilMs: number | null;
|
|
814
|
+
/**
|
|
815
|
+
* When the process now holding the server's pid was created, when the caller knows it (this process reuses the dead
|
|
816
|
+
* server's pid); null otherwise. The sweep also reads it from its process snapshot. A process created after it is not
|
|
817
|
+
* the dead server's child, so it is never matched as a recorded root.
|
|
818
|
+
*/
|
|
819
|
+
readonly serverPidHeldSinceMs: number | null;
|
|
820
|
+
/** The slot the verification ran in; a dead root's child is attributed by naming it on its command line. */
|
|
821
|
+
readonly slotPath: string;
|
|
822
|
+
readonly roots: readonly RecordedRoot[];
|
|
823
|
+
}
|
|
824
|
+
|
|
825
|
+
export interface RecordedTreeKillInput {
|
|
826
|
+
/** Every journal of one plan sweep: one PowerShell and one process snapshot for all of them (M2). */
|
|
827
|
+
readonly groups: readonly RecordedTreeGroup[];
|
|
828
|
+
/** Windows: the newest creation time a dead root's child may have (the sweeping process's start). */
|
|
829
|
+
readonly until: number;
|
|
830
|
+
/** Aborts the sweep (dispose): what it has not confirmed stays unconfirmed. */
|
|
831
|
+
readonly signal?: AbortSignal;
|
|
832
|
+
/** The bound of the whole sweep; default SWEEP_TIMEOUT_MS. */
|
|
833
|
+
readonly timeoutMs?: number;
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
/** What `killRecordedTrees` proved for one group: confirmed exactly when the server is dead and `alive` is empty. */
|
|
837
|
+
export interface RecordedGroupKill {
|
|
838
|
+
/** The recorded server is alive (its pid answered with its recorded start): nothing of the group was looked at. */
|
|
839
|
+
serverAlive: boolean;
|
|
840
|
+
/** Processes this call ended (with their trees) and saw exit. */
|
|
841
|
+
killed: number[];
|
|
842
|
+
/** Processes that may still run; the recorded roots themselves when the group was not checked to its end. */
|
|
843
|
+
alive: number[];
|
|
844
|
+
/**
|
|
845
|
+
* The part of `alive` created where a recorded root's child would be, but after the recorded run could still start
|
|
846
|
+
* processes: maybe the user's own (a launcher that reused the root's pid). Present only when non-empty.
|
|
847
|
+
*/
|
|
848
|
+
late?: number[];
|
|
849
|
+
/** Set with a non-empty `alive`: why the kill is not confirmed. */
|
|
850
|
+
reason?: string;
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
/** Index-aligned with `RecordedTreeKillInput.groups`. */
|
|
854
|
+
export interface RecordedTreeKill {
|
|
855
|
+
groups: RecordedGroupKill[];
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
/** Test seams of `killRecordedTrees`; each defaults to the real one. */
|
|
859
|
+
export interface RecordedTreeKillDeps {
|
|
860
|
+
platform?: NodeJS.Platform;
|
|
861
|
+
/** POSIX: `process.kill`. */
|
|
862
|
+
signal?: (pid: number, signal: NodeJS.Signals | 0) => void;
|
|
863
|
+
/** POSIX: reads a /proc file; throws when it does not exist. */
|
|
864
|
+
readProc?: (path: string) => string;
|
|
865
|
+
sleep?: (ms: number) => Promise<void>;
|
|
866
|
+
}
|
|
867
|
+
|
|
868
|
+
/**
|
|
869
|
+
* The longest a spawn may take between the recorded `startedAtMs` and the root's creation: the window a root's creation
|
|
870
|
+
* time (Windows) or /proc start time (POSIX) must fall in to be the recorded root. Exported for tests.
|
|
871
|
+
*/
|
|
872
|
+
export const RECORDED_ROOT_SPAWN_MS = 10_000;
|
|
873
|
+
/**
|
|
874
|
+
* M1: a process the root started was created before the root's run ended: before its recorded exit (+ clock slack), else
|
|
875
|
+
* before its deadline plus KILL_GRACE_MS and this slack (the most a taskkill of its tree may take). A child of the root's
|
|
876
|
+
* pid created later was started by a later owner of that pid: reported, never killed.
|
|
877
|
+
*/
|
|
878
|
+
const DEAD_ROOT_CHILD_SLACK_MS = TASKKILL_TIMEOUT_MS;
|
|
879
|
+
/** Windows: how far the recorded server start may lie from the creation time of the process holding its pid (L8). */
|
|
880
|
+
export const SERVER_START_SLACK_MS = 5000;
|
|
881
|
+
/** POSIX: how long a SIGKILLed process group may take to be seen empty. */
|
|
882
|
+
const GROUP_GONE_MS = 2000;
|
|
883
|
+
/** Printed by the dead-tree sweep once it ran to its end. */
|
|
884
|
+
const DEAD_SWEEP_MARKER = "swept";
|
|
885
|
+
|
|
886
|
+
function validRoot(r: RecordedRoot): boolean {
|
|
887
|
+
const id = (n: unknown): boolean => typeof n === "number" && Number.isSafeInteger(n) && n > 0;
|
|
888
|
+
const time = (n: unknown): boolean => typeof n === "number" && Number.isFinite(n) && n >= 0;
|
|
889
|
+
return id(r.pid) && Number.isFinite(r.startedAtMs) && (r.pgid === null || id(r.pgid)) && typeof r.command === "string"
|
|
890
|
+
&& (r.deadlineMs === null || time(r.deadlineMs)) && (r.exitedAtMs === null || time(r.exitedAtMs))
|
|
891
|
+
&& (r.startTicks === null || (Number.isSafeInteger(r.startTicks) && r.startTicks >= 0));
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
/** /proc/<pid>/stat: the process group (field 5) and the start time in clock ticks (field 22); null when malformed. */
|
|
895
|
+
export function parseProcStat(stat: string): { pgrp: number; ticks: number } | null {
|
|
896
|
+
// The command name (field 2) may itself contain spaces and parentheses: the fields after the last ")".
|
|
897
|
+
const fields = stat.slice(stat.lastIndexOf(")") + 2).trim().split(/\s+/);
|
|
898
|
+
const pgrp = Number(fields[2]);
|
|
899
|
+
const ticks = Number(fields[19]);
|
|
900
|
+
return Number.isSafeInteger(pgrp) && Number.isSafeInteger(ticks) && ticks >= 0 ? { pgrp, ticks } : null;
|
|
901
|
+
}
|
|
902
|
+
|
|
903
|
+
/** POSIX: `parseProcStat` of `pid`, or null when it cannot be read. Never throws. */
|
|
904
|
+
export function readProcStart(readProc: (path: string) => string, pid: number): { pgrp: number; ticks: number } | null {
|
|
905
|
+
try {
|
|
906
|
+
return parseProcStat(readProc(`/proc/${pid}/stat`));
|
|
907
|
+
} catch {
|
|
908
|
+
return null;
|
|
909
|
+
}
|
|
910
|
+
}
|
|
911
|
+
|
|
912
|
+
/** A group that was not checked to its end: whatever of its roots was not seen ended may still run. */
|
|
913
|
+
function unconfirmedGroup(g: RecordedTreeGroup, killed: readonly number[], others: readonly number[], why: string): RecordedGroupKill {
|
|
914
|
+
const alive = [...new Set([...g.roots.map((r) => r.pid), ...others])].filter((pid) => !killed.includes(pid));
|
|
915
|
+
return alive.length === 0 ? { serverAlive: false, killed: [...killed], alive } : { serverAlive: false, killed: [...killed], alive, reason: `the sweep did not finish (${why})` };
|
|
916
|
+
}
|
|
917
|
+
|
|
918
|
+
/**
|
|
919
|
+
* #189 R2-pre-2: ends what dead servers' plan-task verifications left running, killing only what is proven to be a
|
|
920
|
+
* recorded tree. One call per plan sweep (every journal of the plan is one group); never rejects.
|
|
921
|
+
*
|
|
922
|
+
* - Windows (`sweepDeadWindows`, armSweeper's technique, one PowerShell and one process snapshot for every group): a
|
|
923
|
+
* recorded root still running is killed with its tree only when its creation time lies in its spawn window, its parent
|
|
924
|
+
* is the dead server and its command line names its command or the slot. A root that exited is gone, so its PID may be
|
|
925
|
+
* recycled: only its children are looked at, those created after its start, before `until` and before a later owner
|
|
926
|
+
* of the PID was created. Of these, a child created after the root's run ended (its recorded exit, else its deadline
|
|
927
|
+
* plus the kill grace and taskkill's bound: M1) is reported, never killed; one created before is killed with its tree
|
|
928
|
+
* only when its command line names the slot, else reported. Each target is pinned by a handle and its start time
|
|
929
|
+
* re-checked before taskkill, and seen exited after it. Processes whose parent died before the sweep (a grandchild of
|
|
930
|
+
* an exited child) cannot be attributed and are not reached.
|
|
931
|
+
* - POSIX (`killDeadGroups`): `kill(-pgid)` only when /proc shows the group's leader with the recorded start ticks (L5).
|
|
932
|
+
* A group id is not reused while its group has a member, so a leader with other ticks means the recorded group is
|
|
933
|
+
* gone. A group whose leader exited, a root without recorded ticks or a system without /proc cannot be confirmed:
|
|
934
|
+
* reported in `alive`.
|
|
935
|
+
*/
|
|
936
|
+
export function killRecordedTrees(input: RecordedTreeKillInput, deps: RecordedTreeKillDeps = {}): Promise<RecordedTreeKill> {
|
|
937
|
+
const groups = input.groups.map((g) => ({ ...g, roots: g.roots.filter(validRoot) }));
|
|
938
|
+
if (!groups.some((g) => g.roots.length > 0)) return Promise.resolve({ groups: groups.map(() => ({ serverAlive: false, killed: [], alive: [] })) });
|
|
939
|
+
if ((deps.platform ?? process.platform) === "win32") return sweepDeadWindows(input, groups);
|
|
940
|
+
return killDeadGroups(input, groups, deps);
|
|
941
|
+
}
|
|
942
|
+
|
|
943
|
+
async function killDeadGroups(input: RecordedTreeKillInput, groups: readonly RecordedTreeGroup[], deps: RecordedTreeKillDeps): Promise<RecordedTreeKill> {
|
|
944
|
+
const signal = deps.signal ?? ((pid: number, sig: NodeJS.Signals | 0) => { process.kill(pid, sig); });
|
|
945
|
+
const readProc = deps.readProc ?? ((path: string) => readFileSync(path, "utf8"));
|
|
946
|
+
const sleep = deps.sleep ?? ((ms: number) => new Promise<void>((resolve) => { setTimeout(resolve, ms); }));
|
|
947
|
+
const timeoutMs = input.timeoutMs ?? SWEEP_TIMEOUT_MS;
|
|
948
|
+
const endAt = Date.now() + timeoutMs;
|
|
949
|
+
/** Why the sweep must stop here (M2), or undefined. */
|
|
950
|
+
const stopped = (): string | undefined =>
|
|
951
|
+
input.signal?.aborted === true ? "aborted" : Date.now() > endAt ? `timed out after ${timeoutMs} ms` : undefined;
|
|
952
|
+
const groupAlive = (pgid: number): boolean => {
|
|
953
|
+
try {
|
|
954
|
+
signal(-pgid, 0);
|
|
955
|
+
return true;
|
|
956
|
+
} catch (e) {
|
|
957
|
+
return (e as NodeJS.ErrnoException).code === "EPERM";
|
|
958
|
+
}
|
|
959
|
+
};
|
|
960
|
+
const out: RecordedGroupKill[] = [];
|
|
961
|
+
for (const g of groups) {
|
|
962
|
+
if (g.roots.length === 0) {
|
|
963
|
+
out.push({ serverAlive: false, killed: [], alive: [] });
|
|
964
|
+
continue;
|
|
965
|
+
}
|
|
966
|
+
if (g.serverPidLive) {
|
|
967
|
+
// L8: the live pid is the server only with its recorded start ticks; unknown ticks keep it a live server.
|
|
968
|
+
const ticks = readProcStart(readProc, g.serverPid)?.ticks;
|
|
969
|
+
if (g.serverStartTicks === null || ticks === undefined || ticks === g.serverStartTicks) {
|
|
970
|
+
out.push({ serverAlive: true, killed: [], alive: [] });
|
|
971
|
+
continue;
|
|
972
|
+
}
|
|
973
|
+
}
|
|
974
|
+
const killed: number[] = [];
|
|
975
|
+
const alive: number[] = [];
|
|
976
|
+
const reasons = new Set<string>();
|
|
977
|
+
for (const root of g.roots) {
|
|
978
|
+
const pgid = root.pgid ?? root.pid;
|
|
979
|
+
const why = stopped();
|
|
980
|
+
if (why !== undefined) {
|
|
981
|
+
alive.push(pgid);
|
|
982
|
+
reasons.add(`the sweep did not finish (${why})`);
|
|
983
|
+
continue;
|
|
984
|
+
}
|
|
985
|
+
if (!groupAlive(pgid)) continue;
|
|
986
|
+
const leader = leaderOf(readProc, pgid);
|
|
987
|
+
if (typeof leader === "string") {
|
|
988
|
+
alive.push(pgid);
|
|
989
|
+
reasons.add(leader);
|
|
990
|
+
continue;
|
|
991
|
+
}
|
|
992
|
+
if (root.startTicks === null) {
|
|
993
|
+
alive.push(pgid);
|
|
994
|
+
reasons.add(`process group ${pgid} cannot be confirmed: its start was not recorded`);
|
|
995
|
+
continue;
|
|
996
|
+
}
|
|
997
|
+
if (leader.pgrp !== pgid) {
|
|
998
|
+
alive.push(pgid);
|
|
999
|
+
reasons.add(`process ${pgid} does not lead its process group as recorded`);
|
|
1000
|
+
continue;
|
|
1001
|
+
}
|
|
1002
|
+
// L5: other start ticks: the group id was reused, which it never is while the recorded group has a member.
|
|
1003
|
+
if (leader.ticks !== root.startTicks) continue;
|
|
1004
|
+
try {
|
|
1005
|
+
signal(-pgid, "SIGKILL");
|
|
1006
|
+
} catch {
|
|
1007
|
+
// Emptied meanwhile: checked below like any other group.
|
|
1008
|
+
}
|
|
1009
|
+
let gone = !groupAlive(pgid);
|
|
1010
|
+
for (let waited = 0; !gone && waited < GROUP_GONE_MS && stopped() === undefined; waited += 50) {
|
|
1011
|
+
await sleep(50);
|
|
1012
|
+
gone = !groupAlive(pgid);
|
|
1013
|
+
}
|
|
1014
|
+
if (gone) killed.push(pgid);
|
|
1015
|
+
else {
|
|
1016
|
+
alive.push(pgid);
|
|
1017
|
+
reasons.add(`process group ${pgid} survived SIGKILL`);
|
|
1018
|
+
}
|
|
1019
|
+
}
|
|
1020
|
+
out.push(reasons.size === 0 ? { serverAlive: false, killed, alive } : { serverAlive: false, killed, alive, reason: [...reasons].join("; ") });
|
|
1021
|
+
}
|
|
1022
|
+
return { groups: out };
|
|
1023
|
+
}
|
|
1024
|
+
|
|
1025
|
+
/** The leader of process group `pgid` as /proc shows it, or why it cannot be read. */
|
|
1026
|
+
function leaderOf(readProc: (path: string) => string, pgid: number): { pgrp: number; ticks: number } | string {
|
|
1027
|
+
try {
|
|
1028
|
+
readProc("/proc/stat");
|
|
1029
|
+
} catch {
|
|
1030
|
+
return `process group ${pgid} cannot be confirmed: /proc is unavailable`;
|
|
1031
|
+
}
|
|
1032
|
+
let stat: string;
|
|
1033
|
+
try {
|
|
1034
|
+
stat = readProc(`/proc/${pgid}/stat`);
|
|
1035
|
+
} catch {
|
|
1036
|
+
return `the leader of process group ${pgid} exited; its remaining members cannot be attributed`;
|
|
1037
|
+
}
|
|
1038
|
+
return parseProcStat(stat) ?? `process ${pgid} does not lead its process group as recorded`;
|
|
1039
|
+
}
|
|
1040
|
+
|
|
1041
|
+
/**
|
|
1042
|
+
* The fixed head of the dead-tree sweep script: its preference, language-mode check and functions. Single quotes only.
|
|
1043
|
+
* `Sweep` reads `$byId`, `$byParent`, `$snap` (DEAD_SWEEP_SNAPSHOT) and `$slot` (set per group) when it runs.
|
|
1044
|
+
*/
|
|
1045
|
+
const DEAD_SWEEP_FUNCTIONS: readonly string[] = [
|
|
1046
|
+
"$ErrorActionPreference = 'Stop'",
|
|
1047
|
+
"if ($ExecutionContext.SessionState.LanguageMode -ne 'FullLanguage') { exit 3 }",
|
|
1048
|
+
// A match must end at a path or argument boundary: the slot slot-1 is not named by a path in slot-10.
|
|
1049
|
+
"$stops = @([char]32, [char]34, [char]39, [char]92)",
|
|
1050
|
+
"function Say($s) { [Console]::Out.WriteLine($s) }",
|
|
1051
|
+
"function Ms($d) { if ($null -eq $d) { return [long]-1 }; ([DateTimeOffset]$d).ToUnixTimeMilliseconds() }",
|
|
1052
|
+
"function Norm($s) { ([string]$s).ToLowerInvariant().Replace([char]47, [char]92) }",
|
|
1053
|
+
"function Text($b) { Norm ([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($b))) }",
|
|
1054
|
+
"function Has($line, $needle) { if ($null -eq $line -or $needle.Length -eq 0) { return $false }; $l = Norm $line; $i = $l.IndexOf($needle); while ($i -ge 0) { $j = $i + $needle.Length; if ($j -ge $l.Length -or $stops -contains $l[$j]) { return $true }; $i = $l.IndexOf($needle, $i + 1) }; return $false }",
|
|
1055
|
+
"function ServerAlive($id, $from, $to) { $s = $byId[[int]$id]; if ($null -eq $s) { return $false }; $t = Ms $s.CreationDate; return ($t -ge $from -and $t -le $to) }",
|
|
1056
|
+
// L4: `gone` only when no process holds the pid any more (ArgumentException), or the one holding it started outside the
|
|
1057
|
+
// window; any other failure (access denied) is `alive`. It runs under the script's own preference ('Stop').
|
|
1058
|
+
"function Pin($id, $from, $to) { try { $p = [Diagnostics.Process]::GetProcessById([int]$id); $null = $p.Handle; $s = Ms $p.StartTime; if ($s -ge $from -and $s -le $to) { return $p }; return 'gone' } catch [ArgumentException] { return 'gone' } catch { try { $null = [Diagnostics.Process]::GetProcessById([int]$id); return 'alive' } catch [ArgumentException] { return 'gone' } catch { return 'alive' } } }",
|
|
1059
|
+
// Not `Kill`: that is PowerShell's alias of Stop-Process, which wins over a function of that name. PowerShell 5.1 turns
|
|
1060
|
+
// a redirected native stderr line into an error record, which 'Stop' would make terminating: only the taskkill call runs
|
|
1061
|
+
// under 'SilentlyContinue' (its own script block), and only the target's exit decides `killed`.
|
|
1062
|
+
"function EndTree($g, $id, $from, $to) { $p = Pin $id $from $to; if ($p -isnot [Diagnostics.Process]) { Say ($p + ' ' + $g + ' ' + $id); return }; & { $ErrorActionPreference = 'SilentlyContinue'; & taskkill.exe /pid $p.Id /T /F *> $null }; $null = $p.WaitForExit(5000); $p.Refresh(); if ($p.HasExited) { Say ('killed ' + $g + ' ' + $p.Id) } else { Say ('alive ' + $g + ' ' + $p.Id) } }",
|
|
1063
|
+
// The console host Windows started for a dead cmd.exe root: no work of the verification, it exits with its last client.
|
|
1064
|
+
"$conhost = Norm ([Environment]::SystemDirectory + '\\conhost.exe')",
|
|
1065
|
+
// A root is created before the current holder of the server's pid (a later owner of that pid is no parent of it), and
|
|
1066
|
+
// before the snapshot (a pid reused since is never pinned as the root).
|
|
1067
|
+
"function Sweep($g, $id, $from, $rootTo, $bound, $until, $server, $cmd) { $h = $byId[[int]$server]; if ($null -ne $h) { $ht = Ms $h.CreationDate; if ($ht -ge 0 -and $ht -lt $rootTo) { $rootTo = $ht } }; $r = $byId[[int]$id]; if ($null -ne $r) { $t = Ms $r.CreationDate; if ($t -ge $from -and $t -le $rootTo -and $r.ParentProcessId -eq $server) { if ((Has $r.CommandLine (Text $cmd)) -or (Has $r.CommandLine $slot)) { EndTree $g $id $from ([Math]::Min($rootTo, $snap)) } else { Say ('unattributed ' + $g + ' ' + $id) }; return }; if ($t -ge 0 -and $t -lt $until) { $until = $t }; if ($bound -gt $until) { $bound = $until } }; $kids = $byParent[[int]$id]; if ($null -eq $kids) { return }; foreach ($c in $kids) { try { $t = Ms $c.CreationDate; if ($t -lt $from -or $t -gt $until) { continue }; if ($null -ne $c.ExecutablePath -and (Norm $c.ExecutablePath) -eq $conhost) { continue }; if ($t -gt $bound) { Say ('late ' + $g + ' ' + $c.ProcessId); continue }; if (Has $c.CommandLine $slot) { EndTree $g $c.ProcessId $from $bound } else { Say ('unattributed ' + $g + ' ' + $c.ProcessId) } } catch { Say ('unattributed ' + $g + ' ' + $c.ProcessId) } } }",
|
|
1068
|
+
];
|
|
1069
|
+
|
|
1070
|
+
/** M2: the one process snapshot of a sweep, and its time (taken first: every process in the snapshot was created before). */
|
|
1071
|
+
const DEAD_SWEEP_SNAPSHOT: readonly string[] = [
|
|
1072
|
+
"$snap = Ms (Get-Date)",
|
|
1073
|
+
"$byId = @{}; $byParent = @{}",
|
|
1074
|
+
"foreach ($q in @(Get-CimInstance -ClassName Win32_Process -Property ProcessId,ParentProcessId,CreationDate,CommandLine,ExecutablePath)) { $byId[[int]$q.ProcessId] = $q; $k = [int]$q.ParentProcessId; if (-not $byParent.ContainsKey($k)) { $byParent[$k] = New-Object System.Collections.ArrayList }; $null = $byParent[$k].Add($q) }",
|
|
1075
|
+
];
|
|
1076
|
+
|
|
1077
|
+
/** Test-only: the sweep script's head (preference, language-mode check, functions), without its snapshot or groups. */
|
|
1078
|
+
export function deadSweepFunctionsForTests(): string {
|
|
1079
|
+
return DEAD_SWEEP_FUNCTIONS.join("; ");
|
|
1080
|
+
}
|
|
1081
|
+
|
|
1082
|
+
/**
|
|
1083
|
+
* Windows PowerShell sweep of every group (see `killRecordedTrees`), in the style of `armSweeper`: Windows PowerShell 5.1
|
|
1084
|
+
* at normal priority, FullLanguage mode required (exit 3 otherwise), single quotes only in the script (every caller
|
|
1085
|
+
* text is base64), ONE process snapshot filtered in memory, bounded by `timeoutMs` and `signal` (M2). Per process it looked
|
|
1086
|
+
* at it prints `killed|alive|unattributed|late|gone <group> <pid>`, per group `server-alive <group>` (its server lives) and
|
|
1087
|
+
* `group <group>` once the group is done, and `swept` at its end. A group without its marker confirms nothing.
|
|
1088
|
+
*/
|
|
1089
|
+
function sweepDeadWindows(input: RecordedTreeKillInput, groups: readonly RecordedTreeGroup[]): Promise<RecordedTreeKill> {
|
|
1090
|
+
const timeoutMs = input.timeoutMs ?? SWEEP_TIMEOUT_MS;
|
|
1091
|
+
if (input.signal?.aborted === true) return Promise.resolve(readDeadSweep("", groups, "aborted"));
|
|
1092
|
+
const b64 = (s: string): string => Buffer.from(s, "utf8").toString("base64");
|
|
1093
|
+
const lines: string[] = [];
|
|
1094
|
+
groups.forEach((g, gi) => {
|
|
1095
|
+
const server = Number.isSafeInteger(g.serverPid) && g.serverPid > 0 ? g.serverPid : 0;
|
|
1096
|
+
const sweeps = g.roots.map((r) => {
|
|
1097
|
+
const from = Math.floor(r.startedAtMs - SWEEP_CLOCK_SLACK_MS);
|
|
1098
|
+
// A process created after the current holder of the server's pid is not the dead server's child (the script also
|
|
1099
|
+
// caps this by the holder its snapshot finds).
|
|
1100
|
+
const rootTo = Math.ceil(Math.min(r.startedAtMs + RECORDED_ROOT_SPAWN_MS, g.serverPidHeldSinceMs ?? Infinity));
|
|
1101
|
+
const until = Math.ceil(Math.max(input.until, r.startedAtMs) + SWEEP_CLOCK_SLACK_MS);
|
|
1102
|
+
// M1: the newest creation time of a process the root itself started: its exit, its deadline, and (re-review 1) the
|
|
1103
|
+
// server's last heartbeat, past which nothing recorded the root.
|
|
1104
|
+
const ends = [until];
|
|
1105
|
+
if (r.deadlineMs !== null) ends.push(Math.ceil(r.startedAtMs + r.deadlineMs + KILL_GRACE_MS + DEAD_ROOT_CHILD_SLACK_MS));
|
|
1106
|
+
if (r.exitedAtMs !== null) ends.push(Math.ceil(r.exitedAtMs + SWEEP_CLOCK_SLACK_MS));
|
|
1107
|
+
if (g.recordedUntilMs !== null) ends.push(Math.ceil(g.recordedUntilMs));
|
|
1108
|
+
return `Sweep ${gi} ${r.pid} ${from} ${rootTo} ${Math.min(...ends)} ${until} ${server} '${b64(r.command)}'`;
|
|
1109
|
+
});
|
|
1110
|
+
if (sweeps.length > 0) {
|
|
1111
|
+
lines.push(`$slot = Text '${b64(g.slotPath.replace(/[\\/]+$/, ""))}'`);
|
|
1112
|
+
const body = sweeps.join("; ");
|
|
1113
|
+
if (g.serverPidLive) {
|
|
1114
|
+
const from = Math.floor(g.serverStartedAtMs - SERVER_START_SLACK_MS);
|
|
1115
|
+
const to = Math.ceil(g.serverStartedAtMs + SERVER_START_SLACK_MS);
|
|
1116
|
+
lines.push(`if (ServerAlive ${server} ${from} ${to}) { Say ('server-alive ${gi}') } else { ${body} }`);
|
|
1117
|
+
} else {
|
|
1118
|
+
lines.push(body);
|
|
1119
|
+
}
|
|
1120
|
+
}
|
|
1121
|
+
lines.push(`Say ('group ${gi}')`);
|
|
1122
|
+
});
|
|
1123
|
+
const script = [...DEAD_SWEEP_FUNCTIONS, ...DEAD_SWEEP_SNAPSHOT, ...lines, `Say ('${DEAD_SWEEP_MARKER}')`].join("; ");
|
|
1124
|
+
return new Promise((resolve) => {
|
|
1125
|
+
let output = "";
|
|
1126
|
+
let settled = false;
|
|
1127
|
+
let limit: ReturnType<typeof setTimeout> | undefined;
|
|
1128
|
+
let onAbort = (): void => {};
|
|
1129
|
+
const done = (failure: string | undefined): void => {
|
|
1130
|
+
if (settled) return;
|
|
1131
|
+
settled = true;
|
|
1132
|
+
clearTimeout(limit);
|
|
1133
|
+
input.signal?.removeEventListener("abort", onAbort);
|
|
1134
|
+
resolve(readDeadSweep(output, groups, failure));
|
|
1135
|
+
};
|
|
1136
|
+
let ps: ChildProcess;
|
|
1137
|
+
try {
|
|
1138
|
+
ps = spawn(powershell, ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", script], {
|
|
1139
|
+
// QA-G-9: never the host's cwd (the user's project).
|
|
1140
|
+
cwd: tmpdir(),
|
|
1141
|
+
windowsHide: true,
|
|
1142
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
1143
|
+
});
|
|
1144
|
+
} catch (e) {
|
|
1145
|
+
done(`spawn error: ${String(e)}`);
|
|
1146
|
+
return;
|
|
1147
|
+
}
|
|
1148
|
+
const sweeper = ps;
|
|
1149
|
+
sweeper.stdout?.setEncoding("utf8");
|
|
1150
|
+
sweeper.stdout?.on("data", (s: string) => { output += s; });
|
|
1151
|
+
sweeper.on("error", (e) => done(`spawn error: ${e.message}`));
|
|
1152
|
+
sweeper.on("close", (code, sig) => done(
|
|
1153
|
+
code === 0 ? undefined : code === 3 ? "PowerShell is not in FullLanguage mode (exit 3)" : code === null ? `killed by ${sig}` : `exit ${code}`,
|
|
1154
|
+
));
|
|
1155
|
+
onAbort = () => {
|
|
1156
|
+
sweeper.kill();
|
|
1157
|
+
done("aborted");
|
|
1158
|
+
};
|
|
1159
|
+
input.signal?.addEventListener("abort", onAbort, { once: true });
|
|
1160
|
+
limit = setTimeout(() => {
|
|
1161
|
+
sweeper.kill();
|
|
1162
|
+
done(`timed out after ${timeoutMs} ms`);
|
|
1163
|
+
}, timeoutMs);
|
|
1164
|
+
// The sweeper process keeps the loop alive while it runs; its bound never does.
|
|
1165
|
+
limit.unref();
|
|
1166
|
+
});
|
|
1167
|
+
}
|
|
1168
|
+
|
|
1169
|
+
function readDeadSweep(output: string, groups: readonly RecordedTreeGroup[], failure: string | undefined): RecordedTreeKill {
|
|
1170
|
+
const seen = groups.map(() => ({
|
|
1171
|
+
serverAlive: false, done: false, killed: [] as number[], notEnded: [] as number[], unattributed: [] as number[], late: [] as number[],
|
|
1172
|
+
}));
|
|
1173
|
+
// Each group's own marker decides; the final DEAD_SWEEP_MARKER only shows the script ran to its end.
|
|
1174
|
+
for (const line of output.split(/\r?\n/)) {
|
|
1175
|
+
const marker = /^(server-alive|group) (\d+)$/.exec(line);
|
|
1176
|
+
if (marker !== null) {
|
|
1177
|
+
const s = seen[Number(marker[2])];
|
|
1178
|
+
if (s !== undefined && marker[1] === "group") s.done = true;
|
|
1179
|
+
else if (s !== undefined) s.serverAlive = true;
|
|
1180
|
+
continue;
|
|
1181
|
+
}
|
|
1182
|
+
const m = /^(killed|alive|unattributed|late) (\d+) (\d+)$/.exec(line);
|
|
1183
|
+
const s = m === null ? undefined : seen[Number(m[2])];
|
|
1184
|
+
if (m === null || s === undefined) continue;
|
|
1185
|
+
(m[1] === "killed" ? s.killed : m[1] === "alive" ? s.notEnded : m[1] === "unattributed" ? s.unattributed : s.late).push(Number(m[3]));
|
|
1186
|
+
}
|
|
1187
|
+
const why = failure ?? "no marker";
|
|
1188
|
+
return {
|
|
1189
|
+
groups: groups.map((g, i): RecordedGroupKill => {
|
|
1190
|
+
const s = seen[i];
|
|
1191
|
+
if (s === undefined || !s.done) {
|
|
1192
|
+
const unconfirmed = unconfirmedGroup(g, s?.killed ?? [], s === undefined ? [] : [...s.notEnded, ...s.unattributed, ...s.late], why);
|
|
1193
|
+
return s === undefined || s.late.length === 0 ? unconfirmed : { ...unconfirmed, late: s.late };
|
|
1194
|
+
}
|
|
1195
|
+
if (s.serverAlive) return { serverAlive: true, killed: [], alive: [] };
|
|
1196
|
+
const reasons = [
|
|
1197
|
+
...(s.notEnded.length > 0 ? [`taskkill did not end pid ${s.notEnded.join(", ")}`] : []),
|
|
1198
|
+
...(s.unattributed.length > 0 ? [`pid ${s.unattributed.join(", ")} started by a recorded root does not name the slot`] : []),
|
|
1199
|
+
...(s.late.length > 0 ? [`pid ${s.late.join(", ")} was started after the recorded run could still start processes (a later owner of its pid?), never killed`] : []),
|
|
1200
|
+
];
|
|
1201
|
+
const alive = [...new Set([...s.notEnded, ...s.unattributed, ...s.late])];
|
|
1202
|
+
const late = s.late.length === 0 ? {} : { late: s.late };
|
|
1203
|
+
return reasons.length === 0 ? { serverAlive: false, killed: s.killed, alive, ...late } : { serverAlive: false, killed: s.killed, alive, ...late, reason: reasons.join("; ") };
|
|
1204
|
+
}),
|
|
1205
|
+
};
|
|
1206
|
+
}
|