Skip to content

Commit 320c3ad

Browse files
fix(hooks): kill gog process tree on gmail-watcher shutdown (#112452)
* fix(hooks): kill gog process tree on gmail-watcher shutdown * fix(hooks): add curly braces for oxlint curly rule * test(hooks): add integration proof for gmail-watcher process-tree shutdown * test(hooks): fix integration test lint errors * fix(hooks): await Gmail watcher tree escalation --------- Co-authored-by: Vincent Koc <[email protected]>
1 parent 1b6ad8d commit 320c3ad

3 files changed

Lines changed: 251 additions & 38 deletions

File tree

Lines changed: 136 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,136 @@
1+
/**
2+
* Runs startGmailWatcher and stopGmailWatcher with NO mocks for spawn or
3+
* killProcessTree. A fake `gog` binary is placed on PATH; it spawns a
4+
* credential-helper child and deliberately does NOT kill it on SIGTERM,
5+
* simulating the real bug. The test asserts that stopGmailWatcher removes
6+
* both the gog process and its descendant via the process-group signal.
7+
*/
8+
import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
9+
import { tmpdir } from "node:os";
10+
import { join } from "node:path";
11+
import { afterAll, beforeAll, describe, expect, it } from "vitest";
12+
13+
// Only run when explicitly opted in — requires real subprocess spawning.
14+
const RUN = process.platform !== "win32" && process.env["OPENCLAW_INTEGRATION_TEST"] === "1";
15+
16+
function alive(pid: number): boolean {
17+
try {
18+
process.kill(pid, 0);
19+
return true;
20+
} catch {
21+
return false;
22+
}
23+
}
24+
25+
describe.skipIf(!RUN)("gmail-watcher process-tree shutdown (integration)", () => {
26+
let tmpDir: string;
27+
let savedPath: string | undefined;
28+
let gogPid: number | undefined;
29+
let helperPid: number | undefined;
30+
let stopWatcher: (() => Promise<void>) | undefined;
31+
32+
beforeAll(() => {
33+
tmpDir = mkdtempSync(join(tmpdir(), "openclaw-gog-integration-"));
34+
35+
// fake gog: handles `watch start` (exits 0) and `watch serve`
36+
// (spawns a credential-helper that ignores SIGTERM)
37+
const gogScript = join(tmpDir, "gog");
38+
writeFileSync(
39+
gogScript,
40+
[
41+
"#!/bin/bash",
42+
'SCRIPT_DIR="$(cd -- "$(dirname -- "$0")" && pwd)"',
43+
'case "$*" in',
44+
' *"watch start"*) echo "[gog] watch registered"; exit 0 ;;',
45+
' *"watch serve"*)',
46+
' echo "[gog] serve started pid=$$"',
47+
' echo $$ > "$SCRIPT_DIR/gog.pid"',
48+
` /bin/bash -c 'trap "" TERM; while true; do sleep 1; done' &`,
49+
" HELPER=$!",
50+
' echo "[gog] credential-helper spawned pid=$HELPER"',
51+
' echo $HELPER > "$SCRIPT_DIR/helper.pid"',
52+
" trap 'echo \"[gog] SIGTERM (child NOT killed)\"; exit 0' TERM",
53+
" while true; do sleep 0.3; done ;;",
54+
"esac",
55+
].join("\n"),
56+
);
57+
chmodSync(gogScript, 0o755);
58+
59+
savedPath = process.env["PATH"];
60+
process.env["PATH"] = `${tmpDir}:${savedPath ?? ""}`;
61+
});
62+
63+
afterAll(async () => {
64+
try {
65+
await stopWatcher?.();
66+
} catch {
67+
// Force cleanup below; this test must not leave subprocesses behind on failure.
68+
}
69+
if (gogPid !== undefined) {
70+
try {
71+
process.kill(-gogPid, "SIGKILL");
72+
} catch {
73+
// The process group may already be gone.
74+
}
75+
}
76+
if (helperPid !== undefined) {
77+
try {
78+
process.kill(helperPid, "SIGKILL");
79+
} catch {
80+
// The helper may already be gone with its process group.
81+
}
82+
}
83+
if (savedPath !== undefined) {
84+
process.env["PATH"] = savedPath;
85+
}
86+
rmSync(tmpDir, { recursive: true, force: true });
87+
});
88+
89+
it("stopGmailWatcher removes gog and its credential-helper descendant", async () => {
90+
const { startGmailWatcher, stopGmailWatcher } = await import("./gmail-watcher.js");
91+
stopWatcher = stopGmailWatcher;
92+
93+
const result = await startGmailWatcher({
94+
hooks: {
95+
enabled: true,
96+
token: "integration-token",
97+
gmail: {
98+
account: "[email protected]",
99+
topic: "projects/integration/topics/gmail",
100+
pushToken: "integration-push-token",
101+
},
102+
},
103+
} as never);
104+
105+
expect(result.started).toBe(true);
106+
107+
// Wait for both pid files
108+
for (let i = 0; i < 50; i++) {
109+
if (existsSync(join(tmpDir, "helper.pid")) && existsSync(join(tmpDir, "gog.pid"))) {
110+
break;
111+
}
112+
await new Promise<void>((r) => {
113+
setTimeout(r, 100);
114+
});
115+
}
116+
117+
gogPid = Number.parseInt(readFileSync(join(tmpDir, "gog.pid"), "utf8").trim(), 10);
118+
helperPid = Number.parseInt(readFileSync(join(tmpDir, "helper.pid"), "utf8").trim(), 10);
119+
120+
console.log(`\ngog pid=${gogPid}, credential-helper pid=${helperPid}`);
121+
expect(alive(gogPid)).toBe(true);
122+
expect(alive(helperPid)).toBe(true);
123+
124+
console.log("calling stopGmailWatcher...");
125+
await stopGmailWatcher();
126+
await new Promise<void>((r) => {
127+
setTimeout(r, 400);
128+
});
129+
130+
console.log(`gog alive after stop: ${alive(gogPid)}`);
131+
console.log(`credential-helper alive after stop: ${alive(helperPid)}`);
132+
133+
expect(alive(gogPid)).toBe(false);
134+
expect(alive(helperPid)).toBe(false); // descendant must also be gone
135+
}, 15_000);
136+
});

‎src/hooks/gmail-watcher.test.ts‎

Lines changed: 63 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,20 @@ import { EventEmitter } from "node:events";
33
import { expectDefined } from "@openclaw/normalization-core";
44
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
55

6+
// Tracks spawned children by pid so the killProcessTree mock can emit close on them.
7+
const spawnRegistry = new Map<number, EventEmitter>();
8+
69
const mocks = vi.hoisted(() => ({
710
hasBinary: vi.fn(() => true),
811
resolveExecutable: vi.fn((name: string) => name),
912
runCommandWithTimeout: vi.fn(),
1013
spawn: vi.fn(),
14+
killProcessTree: vi.fn((pid: number) => {
15+
const child = spawnRegistry.get(pid);
16+
if (child) {
17+
queueMicrotask(() => child.emit("close", 0, null));
18+
}
19+
}),
1120
}));
1221

1322
vi.mock("node:child_process", async () => {
@@ -30,6 +39,10 @@ vi.mock("../process/exec.js", () => ({
3039
runCommandWithTimeout: mocks.runCommandWithTimeout,
3140
}));
3241

42+
vi.mock("../process/kill-tree.js", () => ({
43+
killProcessTree: mocks.killProcessTree,
44+
}));
45+
3346
const { startGmailWatcher, stopGmailWatcher } = await import("./gmail-watcher.js");
3447

3548
function createGmailConfig(account = "[email protected]", renewEveryMinutes?: number) {
@@ -61,16 +74,23 @@ type MockWatcherChild = EventEmitter & {
6174
stderr: EventEmitter;
6275
};
6376

77+
let nextMockPid = 1234;
78+
6479
function createMockWatcherChild(spawned = true): MockWatcherChild {
6580
const child = new EventEmitter();
66-
return Object.assign(child, {
81+
const pid = spawned ? nextMockPid++ : undefined;
82+
const mockedChild = Object.assign(child, {
6783
stderr: new EventEmitter(),
6884
kill: vi.fn(() => {
6985
queueMicrotask(() => child.emit("exit", null, "SIGTERM"));
7086
return true;
7187
}),
72-
...(spawned ? { pid: 1234 } : {}),
88+
...(pid !== undefined ? { pid } : {}),
7389
});
90+
if (pid !== undefined) {
91+
spawnRegistry.set(pid, mockedChild);
92+
}
93+
return mockedChild;
7494
}
7595

7696
async function startMockWatcher(spawned = true): Promise<MockWatcherChild[]> {
@@ -87,11 +107,21 @@ async function startMockWatcher(spawned = true): Promise<MockWatcherChild[]> {
87107

88108
describe("startGmailWatcher", () => {
89109
beforeEach(async () => {
110+
// stopGmailWatcher uses the killProcessTree mock from the previous beforeEach run,
111+
// which looks up spawnRegistry entries populated by that test's children.
90112
await stopGmailWatcher();
113+
spawnRegistry.clear();
91114
mocks.hasBinary.mockReturnValue(true);
92115
mocks.resolveExecutable.mockImplementation((name: string) => name);
93116
mocks.runCommandWithTimeout.mockReset();
94117
mocks.spawn.mockReset();
118+
mocks.killProcessTree.mockReset();
119+
mocks.killProcessTree.mockImplementation((pid: number) => {
120+
const child = spawnRegistry.get(pid);
121+
if (child) {
122+
queueMicrotask(() => child.emit("close", 0, null));
123+
}
124+
});
95125
mocks.spawn.mockImplementation(() => {
96126
const child = new EventEmitter();
97127
return Object.assign(child, {
@@ -377,19 +407,16 @@ describe("startGmailWatcher", () => {
377407
}
378408
});
379409

380-
it("escalates to SIGKILL and resolves on final timeout when process ignores signals", async () => {
410+
it("uses killProcessTree for gog shutdown and resolves on final timeout when process ignores signals", async () => {
381411
vi.useFakeTimers();
382412
try {
383413
mocks.runCommandWithTimeout.mockResolvedValue({ code: 0, stdout: "", stderr: "" });
384414

385-
// Spawn a process that never emits exit/close/error
415+
// Spawn a process with a known pid that never emits exit/close/error
386416
const stubbornChild = new EventEmitter();
387-
const killCalls: string[] = [];
388417
Object.assign(stubbornChild, {
389-
kill: vi.fn((sig: string) => {
390-
killCalls.push(sig);
391-
return true;
392-
}),
418+
pid: 9999,
419+
kill: vi.fn(() => true),
393420
killed: false,
394421
});
395422
mocks.spawn.mockReturnValueOnce(stubbornChild);
@@ -409,17 +436,17 @@ describe("startGmailWatcher", () => {
409436
});
410437
});
411438

412-
// Re-entry starts settle on stubbornChild
439+
// Re-entry starts settle on stubbornChild; advance past the 8 s final
440+
// timeout (stubbornChild never emits exit), then verify the outcome.
413441
const startPromise = startGmailWatcher(createGmailConfig());
414-
415-
// After 3s the escalation fires SIGKILL
416-
await vi.advanceTimersByTimeAsync(3_000);
417-
expect(killCalls).toContain("SIGTERM");
418-
expect(killCalls).toContain("SIGKILL");
419-
420-
// After 8s total the final timeout resolves even though exit never fired
421-
await vi.advanceTimersByTimeAsync(5_000);
442+
await vi.advanceTimersByTimeAsync(8_000);
422443
await expect(startPromise).resolves.toEqual({ started: true });
444+
445+
// killProcessTree must have been called with stubbornChild's pid before settle gave up.
446+
expect(mocks.killProcessTree).toHaveBeenCalledWith(
447+
9999,
448+
expect.objectContaining({ graceMs: 3_000 }),
449+
);
423450
} finally {
424451
vi.useRealTimers();
425452
}
@@ -463,6 +490,24 @@ describe("startGmailWatcher", () => {
463490
}
464491
});
465492

493+
it("calls killProcessTree (not proc.kill) when stopping the gog watcher", async () => {
494+
mocks.runCommandWithTimeout.mockResolvedValue({ code: 0, stdout: "", stderr: "" });
495+
const child = createMockWatcherChild();
496+
mocks.spawn.mockReturnValueOnce(child);
497+
498+
await startGmailWatcher(createGmailConfig());
499+
expect(mocks.spawn).toHaveBeenCalledTimes(1);
500+
501+
await stopGmailWatcher();
502+
503+
expect(mocks.killProcessTree).toHaveBeenCalledWith(
504+
child.pid,
505+
expect.objectContaining({ graceMs: 3_000 }),
506+
);
507+
// proc.kill should not be called — tree termination replaces the direct kill.
508+
expect(child.kill).not.toHaveBeenCalled();
509+
});
510+
466511
it("swallows stdout and stderr stream errors without crashing", async () => {
467512
mocks.runCommandWithTimeout.mockResolvedValue({ code: 0, stdout: "", stderr: "" });
468513
let stdout: EventEmitter | undefined;

0 commit comments

Comments
 (0)