Skip to content

Commit 7a0efad

Browse files
authored
improve: speed up lifecycle tests (#106501)
* test: remove fixed waits from lifecycle tests * test: harden cron process liveness probe
1 parent 9619585 commit 7a0efad

3 files changed

Lines changed: 77 additions & 47 deletions

File tree

‎extensions/telegram/src/polling-session.test.ts‎

Lines changed: 44 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -2336,47 +2336,55 @@ describe("TelegramPollingSession", () => {
23362336
});
23372337

23382338
it("replays claimed spooled updates after a crash before adoption", async () => {
2339-
await withTempSpool(async (tempDir) => {
2340-
const abort = new AbortController();
2341-
const participants: TelegramSpooledReplayDeferredParticipant[] = [];
2342-
await writeSpooledTestUpdates(tempDir, [topicUpdate(42, 10, "pre-adoption crash")]);
2339+
vi.useFakeTimers({ shouldAdvanceTime: true });
2340+
try {
2341+
await withTempSpool(async (tempDir) => {
2342+
const abort = new AbortController();
2343+
const participants: TelegramSpooledReplayDeferredParticipant[] = [];
2344+
await writeSpooledTestUpdates(tempDir, [topicUpdate(42, 10, "pre-adoption crash")]);
23432345

2344-
const { runPromise, stopWorker } = startIsolatedIngressSession({
2345-
abort,
2346-
spoolDir: tempDir,
2347-
drainIntervalMs: 10,
2348-
handleUpdate: async (update) => {
2349-
const participant = createTelegramSpooledReplayDeferredParticipant(
2350-
`test-pre-crash:${update.update_id}`,
2351-
);
2352-
if (!participant) {
2353-
throw new Error("expected spooled replay participant");
2354-
}
2355-
participants.push(participant);
2356-
// Never adopt: process dies with claim held.
2357-
},
2358-
});
2346+
const { runPromise, stopWorker } = startIsolatedIngressSession({
2347+
abort,
2348+
spoolDir: tempDir,
2349+
drainIntervalMs: 10,
2350+
handleUpdate: async (update) => {
2351+
const participant = createTelegramSpooledReplayDeferredParticipant(
2352+
`test-pre-crash:${update.update_id}`,
2353+
);
2354+
if (!participant) {
2355+
throw new Error("expected spooled replay participant");
2356+
}
2357+
participants.push(participant);
2358+
// Never adopt: process dies with claim held.
2359+
},
2360+
});
23592361

2360-
await vi.waitFor(() => expect(participants).toHaveLength(1));
2361-
await vi.waitFor(async () =>
2362-
expect(
2363-
(await listTelegramSpooledUpdateClaims({ spoolDir: tempDir })).map((c) => c.updateId),
2364-
).toEqual([42]),
2365-
);
2362+
await vi.waitFor(() => expect(participants).toHaveLength(1));
2363+
await vi.waitFor(async () =>
2364+
expect(
2365+
(await listTelegramSpooledUpdateClaims({ spoolDir: tempDir })).map((c) => c.updateId),
2366+
).toEqual([42]),
2367+
);
23662368

2367-
abort.abort();
2368-
stopWorker();
2369-
await runPromise;
2369+
abort.abort();
2370+
stopWorker();
2371+
// Establish the same post-stop boundary as production without burning
2372+
// the real 15-second graceful-stop ceiling on the abandoned handler.
2373+
await vi.advanceTimersByTimeAsync(15_000);
2374+
await runPromise;
23702375

2371-
// Stale-claim recovery after crash: row is still claimed → replayable.
2372-
const recovered = await recoverStaleTelegramSpooledUpdateClaims({
2373-
spoolDir: tempDir,
2374-
staleMs: 0,
2376+
// Stale-claim recovery after crash: row is still claimed → replayable.
2377+
const recovered = await recoverStaleTelegramSpooledUpdateClaims({
2378+
spoolDir: tempDir,
2379+
staleMs: 0,
2380+
});
2381+
expect(recovered).toBeGreaterThanOrEqual(1);
2382+
expect(await pendingUpdateIds(tempDir, "all")).toEqual([42]);
2383+
expect(await failedUpdateIds(tempDir)).toEqual([]);
23752384
});
2376-
expect(recovered).toBeGreaterThanOrEqual(1);
2377-
expect(await pendingUpdateIds(tempDir, "all")).toEqual([42]);
2378-
expect(await failedUpdateIds(tempDir)).toEqual([]);
2379-
});
2385+
} finally {
2386+
vi.useRealTimers();
2387+
}
23802388
});
23812389

23822390
it("does not replay spooled updates after crash post-adoption (row already tombstoned)", async () => {

‎src/cron/command-runner.test.ts‎

Lines changed: 30 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1+
import { spawnSync } from "node:child_process";
12
import fs from "node:fs/promises";
23
import os from "node:os";
34
import path from "node:path";
4-
import { setTimeout as delay } from "node:timers/promises";
55
import { describe, expect, it } from "vitest";
66
import { runCronCommandJob } from "./command-runner.js";
77
import type { CronJob } from "./types.js";
@@ -22,6 +22,23 @@ function makeCommandJob(payload: Extract<CronJob["payload"], { kind: "command" }
2222
};
2323
}
2424

25+
function isProcessRunning(pid: number): boolean {
26+
const result = spawnSync("ps", ["-o", "state=", "-p", String(pid)], { encoding: "utf8" });
27+
if (result.error) {
28+
throw result.error;
29+
}
30+
const state = result.stdout.trim();
31+
if (result.status === 0) {
32+
return !state.startsWith("Z");
33+
}
34+
if (result.status === 1 && state === "" && result.stderr.trim() === "") {
35+
return false;
36+
}
37+
throw new Error(
38+
`ps failed with status ${result.status ?? "unknown"}: ${result.stderr.trim() || "no output"}`,
39+
);
40+
}
41+
2542
describe("runCronCommandJob", () => {
2643
it("runs command argv and returns stdout as the deliverable summary", async () => {
2744
const result = await runCronCommandJob({
@@ -121,26 +138,29 @@ describe("runCronCommandJob", () => {
121138

122139
it.skipIf(process.platform === "win32")("kills shell process groups on timeout", async () => {
123140
const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-cron-command-"));
124-
const markerPath = path.join(tempDir, "survived");
125-
const childScript = [
126-
`setTimeout(() => require("node:fs").writeFileSync(${JSON.stringify(markerPath)}, "alive"), 350)`,
127-
"setInterval(() => {}, 1000)",
128-
].join(";");
129-
const shellCommand = `${JSON.stringify(process.execPath)} -e ${JSON.stringify(childScript)}`;
141+
const childPidPath = path.join(tempDir, "child.pid");
142+
const childScript = "setInterval(() => {}, 1000)";
143+
const shellCommand = [
144+
`${JSON.stringify(process.execPath)} -e ${JSON.stringify(childScript)} &`,
145+
"child_pid=$!",
146+
`printf '%s' "$child_pid" > ${JSON.stringify(childPidPath)}`,
147+
'wait "$child_pid"',
148+
].join("\n");
130149

131150
const result = await runCronCommandJob({
132151
job: makeCommandJob({
133152
kind: "command",
134153
argv: ["sh", "-lc", shellCommand],
135-
timeoutSeconds: 0.05,
154+
timeoutSeconds: 0.2,
136155
}),
137156
});
138157

139158
expect(result.status).toBe("error");
140159
expect(result.error).toBe("command timed out");
141160

142-
await delay(700);
143-
await expect(fs.access(markerPath)).rejects.toThrow();
161+
const childPid = Number.parseInt(await fs.readFile(childPidPath, "utf8"), 10);
162+
expect(Number.isSafeInteger(childPid)).toBe(true);
163+
await expect.poll(() => isProcessRunning(childPid)).toBe(false);
144164
await fs.rm(tempDir, { recursive: true, force: true });
145165
});
146166

‎test/scripts/pr-operation-lock.test.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -498,6 +498,7 @@ describePosix("scripts/pr per-PR operation lock", () => {
498498
it("serializes the same PR and releases the waiter after SIGTERM", async () => {
499499
const repoDir = createRepo();
500500
const held = join(repoDir, "held");
501+
const blocked = join(repoDir, "blocked");
501502
const acquired = join(repoDir, "acquired");
502503
const holder = spawnHolder(repoDir, held);
503504
let waiter: ChildProcess | undefined;
@@ -510,14 +511,15 @@ describePosix("scripts/pr per-PR operation lock", () => {
510511
"-c",
511512
[
512513
...bashSource(repoDir),
514+
`sleep() { printf 'blocked\\n' >'${blocked}'; command sleep 0.01; }`,
513515
"acquire_pr_operation_lock 42",
514516
`printf 'acquired\\n' >'${acquired}'`,
515517
"release_pr_operation_lock",
516518
].join("\n"),
517519
],
518520
{ cwd: repoDir, stdio: "ignore" },
519521
);
520-
await new Promise((resolve) => setTimeout(resolve, 250));
522+
expect(await waitFor(() => existsSync(blocked))).toBe(true);
521523
expect(existsSync(acquired)).toBe(false);
522524

523525
await stopChild(holder, "SIGTERM");

0 commit comments

Comments
 (0)