Skip to content

Commit a278231

Browse files
committed
fix(cron): drain one-shot output before exiting
1 parent 0834911 commit a278231

8 files changed

Lines changed: 192 additions & 39 deletions

‎docs/cli/cron.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -169,7 +169,7 @@ Add `--wait` when a script should block until that exact queued run records a te
169169
openclaw automations run <job-id> --wait --wait-timeout 10m --poll-interval 2s
170170
```
171171

172-
With `--wait`, the CLI calls `cron.run` first, then polls the durable `cron.runs` row for the returned `runId`; it does not reread mutable job delivery settings. JSON reports payload execution as `status` and whole-run completion as `completionStatus`. The command exits `0` only for `completionStatus: "succeeded"`; `failed`, `unknown`, execution errors/skips, a missing `runId`, and timeout expiry exit non-zero (default `10m`, polled every `2s` by default). `--poll-interval` must be greater than zero.
172+
With `--wait`, the CLI calls `cron.run` first, then polls the durable `cron.runs` row for the returned `runId`; it does not reread mutable job delivery settings. JSON reports payload execution as `status` and whole-run completion as `completionStatus`. The command exits `0` only for `completionStatus: "succeeded"`; `failed`, `unknown`, execution errors/skips, a missing `runId`, and timeout expiry exit non-zero (default `10m`, polled every `2s` by default). `--poll-interval` must be greater than zero. Completed JSON output, including the run summary, is flushed before the command exits, so it can be piped to a JSON reader.
173173

174174
<Note>
175175
Use `--due` when you want the manual command to run only if the job is currently due. If `--due --wait` does not enqueue a run, the command returns the normal non-run response instead of polling.

‎src/cli/cron-cli.test.ts‎

Lines changed: 29 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import { Command } from "commander";
33
import { afterEach, describe, expect, it, vi } from "vitest";
44
import type { CronJob } from "../cron/types.js";
5+
import { ExitError } from "../runtime.js";
56
import { registerCronCli } from "./cron-cli.js";
67

78
const CRON_CLI_TEST_TIMEOUT_MS = 15_000;
@@ -64,7 +65,8 @@ vi.mock("./gateway-rpc.js", async () => {
6465
};
6566
});
6667

67-
vi.mock("../runtime.js", () => ({
68+
vi.mock("../runtime.js", async (importOriginal) => ({
69+
...(await importOriginal<typeof import("../runtime.js")>()),
6870
defaultRuntime: mocks.defaultRuntime,
6971
}));
7072

@@ -240,7 +242,7 @@ async function runNamedCronAdd(name: string, ...args: string[]): Promise<void> {
240242
}
241243

242244
async function expectCronCommandExit(args: string[]): Promise<void> {
243-
await expect(runCronCommand(args)).rejects.toThrow("__exit__:1");
245+
await expect(runCronCommand(args)).rejects.toMatchObject({ name: "ExitError", code: 1 });
244246
}
245247

246248
async function runCronEditAndGetPatch(editArgs: string[]): Promise<CronUpdatePatch> {
@@ -305,7 +307,7 @@ async function expectCronEditWithScheduleLookupExit(
305307
const program = buildProgram();
306308
await expect(
307309
program.parseAsync(["cron", "edit", "job-1", ...editArgs], { from: "user" }),
308-
).rejects.toThrow("__exit__:1");
310+
).rejects.toMatchObject({ name: "ExitError", code: 1 });
309311
}
310312

311313
async function runCronRunAndCaptureExit(params: {
@@ -354,19 +356,20 @@ async function runCronRunAndCaptureExit(params: {
354356
},
355357
);
356358

357-
const runtime = defaultRuntime as { exit: (code: number) => void };
358-
const originalExit = runtime.exit;
359-
const exitSpy = vi.fn();
360-
runtime.exit = exitSpy;
359+
let exitCode: number | undefined;
361360
try {
362361
const program = buildProgram();
363362
await program.parseAsync(params.args ?? ["cron", "run", "job-1"], { from: "user" });
364-
} finally {
365-
runtime.exit = originalExit;
363+
} catch (error) {
364+
if (!(error instanceof ExitError)) {
365+
throw error;
366+
}
367+
exitCode = error.code;
366368
}
369+
expect(defaultRuntime.error).not.toHaveBeenCalled();
367370
const runCall = callGatewayFromCli.mock.calls.find((call) => call[0] === "cron.run");
368371
return {
369-
exitSpy,
372+
exitCode,
370373
runOpts: (runCall?.[1] ?? {}) as { timeout?: string },
371374
calls: callGatewayFromCli.mock.calls,
372375
};
@@ -390,14 +393,14 @@ describe("cron cli", () => {
390393
);
391394

392395
it("uses legacy stored delivery for --wait completion", async () => {
393-
const { calls, exitSpy } = await runCronRunAndCaptureExit({
396+
const { calls, exitCode } = await runCronRunAndCaptureExit({
394397
enqueued: true,
395398
runId: "manual:legacy:123:0",
396399
runStatus: "ok",
397400
args: ["cron", "run", "job-1", "--wait", "--wait-timeout", "1s", "--poll-interval", "1ms"],
398401
});
399402

400-
expect(exitSpy).toHaveBeenCalledWith(0);
403+
expect(exitCode).toBe(0);
401404
expect(calls.some((call) => call[0] === "cron.get")).toBe(false);
402405
});
403406

@@ -472,8 +475,8 @@ describe("cron cli", () => {
472475
expectedExitCode: 1,
473476
},
474477
])("$name", async ({ ran, enqueued, expectedExitCode }) => {
475-
const { exitSpy } = await runCronRunAndCaptureExit({ ran, enqueued });
476-
expect(exitSpy).toHaveBeenCalledWith(expectedExitCode);
478+
const { exitCode } = await runCronRunAndCaptureExit({ ran, enqueued });
479+
expect(exitCode).toBe(expectedExitCode);
477480
});
478481

479482
it.each([
@@ -483,15 +486,15 @@ describe("cron cli", () => {
483486
])(
484487
"waits for execution $status with completion $completionStatus",
485488
async ({ status, completionStatus, expectedExitCode }) => {
486-
const { calls, exitSpy } = await runCronRunAndCaptureExit({
489+
const { calls, exitCode } = await runCronRunAndCaptureExit({
487490
enqueued: true,
488491
runId: "manual:job-1:123:0",
489492
runStatus: status,
490493
completionStatus,
491494
args: ["cron", "run", "job-1", "--wait", "--wait-timeout", "1s", "--poll-interval", "1ms"],
492495
});
493496

494-
expect(exitSpy).toHaveBeenCalledWith(expectedExitCode);
497+
expect(exitCode).toBe(expectedExitCode);
495498
const runsCall = calls.find((call) => call[0] === "cron.runs");
496499
expect(runsCall?.[2]).toMatchObject({
497500
id: "job-1",
@@ -526,7 +529,10 @@ describe("cron cli", () => {
526529
);
527530

528531
const program = buildProgram();
529-
await expect(program.parseAsync(args, { from: "user" })).rejects.toThrow("__exit__:1");
532+
await expect(program.parseAsync(args, { from: "user" })).rejects.toMatchObject({
533+
name: "ExitError",
534+
code: 1,
535+
});
530536

531537
expectRuntimeErrorContaining(
532538
"Automation not found: missing. Run `openclaw cron list` to see recent automation ids.",
@@ -590,7 +596,7 @@ describe("cron cli", () => {
590596
])(
591597
"$name",
592598
async ({ waitTimeout, rpcTimeout, expectedEnqueueTimeout, expectedMaxPollTimeoutMs }) => {
593-
const { calls, exitSpy, runOpts } = await runCronRunAndCaptureExit({
599+
const { calls, exitCode, runOpts } = await runCronRunAndCaptureExit({
594600
enqueued: true,
595601
runId: "manual:job-1:123:0",
596602
runStatus: "ok",
@@ -611,7 +617,7 @@ describe("cron cli", () => {
611617
const historyOptions = historyCalls[0]?.[1] as { timeout?: string } | undefined;
612618
const pollTimeoutMs = Number(historyOptions?.timeout);
613619

614-
expect(exitSpy).toHaveBeenCalledWith(0);
620+
expect(exitCode).toBe(0);
615621
expect(historyCalls).toHaveLength(1);
616622
expect(runOpts.timeout).toBe(expectedEnqueueTimeout);
617623
expect(Number.isSafeInteger(pollTimeoutMs)).toBe(true);
@@ -657,12 +663,12 @@ describe("cron cli", () => {
657663
vi.setSystemTime(new Date(startedAt.getTime() + clockJumpMs));
658664
await vi.advanceTimersByTimeAsync(25);
659665

660-
const { calls, exitSpy, runOpts } = await pendingRun;
666+
const { calls, exitCode, runOpts } = await pendingRun;
661667
const pollTimeouts = calls
662668
.filter(([method]) => method === "cron.runs")
663669
.map(([, options]) => Number((options as { timeout?: string }).timeout));
664670

665-
expect(exitSpy).toHaveBeenCalledWith(0);
671+
expect(exitCode).toBe(0);
666672
expect(runOpts.timeout).toBe("600000");
667673
expect(pollTimeouts).toHaveLength(2);
668674
expect(pollTimeouts.every(Number.isSafeInteger)).toBe(true);
@@ -723,7 +729,7 @@ describe("cron cli", () => {
723729
expect(callGatewayFromCli.mock.calls.some((call) => call[0] === "cron.runs")).toBe(true);
724730
});
725731

726-
const rejection = expect(run).rejects.toThrow("__exit__:1");
732+
const rejection = expect(run).rejects.toMatchObject({ name: "ExitError", code: 1 });
727733
await vi.advanceTimersByTimeAsync(10);
728734
await rejection;
729735
expectRuntimeErrorContaining("timed out waiting for cron run");
@@ -2263,7 +2269,7 @@ describe("cron cli", () => {
22632269
],
22642270
{ from: "user" },
22652271
),
2266-
).rejects.toThrow("__exit__:1");
2272+
).rejects.toMatchObject({ name: "ExitError", code: 1 });
22672273
expectRuntimeErrorContaining("Use either --failure-alert-include-skipped");
22682274
expect(callGatewayFromCli).not.toHaveBeenCalled();
22692275
});

‎src/cli/cron-cli/cron-pagination.gateway.test.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,10 @@ vi.mock("../gateway-rpc.js", async () => {
3030
};
3131
});
3232

33-
vi.mock("../../runtime.js", () => ({ defaultRuntime: mocks.runtime }));
33+
vi.mock("../../runtime.js", async (importOriginal) => ({
34+
...(await importOriginal<typeof import("../../runtime.js")>()),
35+
defaultRuntime: mocks.runtime,
36+
}));
3437

3538
const { registerCronCli } = await import("../cron-cli.js");
3639

‎src/cli/cron-cli/cron-suppression.gateway.test.ts‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import type { CronJob } from "../../cron/types.js";
1616
import { cronHandlers } from "../../gateway/server-methods/cron.js";
1717
import type { RespondFn } from "../../gateway/server-methods/types.js";
1818
import { getActiveGatewayRootWorkCount } from "../../process/gateway-work-admission.js";
19+
import { ExitError } from "../../runtime.js";
1920
import { resetTaskRegistryForTests } from "../../tasks/task-runtime.test-helpers.js";
2021
import { withOpenClawTestState } from "../../test-utils/openclaw-test-state.js";
2122

@@ -48,12 +49,20 @@ async function runCli(args: string[]) {
4849
const program = new Command();
4950
program.exitOverride();
5051
registerCronCli(program);
51-
await program.parseAsync(["cron", ...args], { from: "user" });
52+
let exitCode: number | undefined;
53+
try {
54+
await program.parseAsync(["cron", ...args], { from: "user" });
55+
} catch (error) {
56+
if (!(error instanceof ExitError)) {
57+
throw error;
58+
}
59+
exitCode = error.code;
60+
}
5261
expect(mocks.runtime.error).not.toHaveBeenCalled();
5362
return {
5463
text: mocks.runtime.log.mock.calls.map(([line]) => String(line)).join("\n"),
5564
json: mocks.runtime.writeJson.mock.calls.at(-1)?.[0],
56-
exitCode: mocks.runtime.exit.mock.calls.at(-1)?.[0],
65+
exitCode,
5766
};
5867
}
5968

‎src/cli/cron-cli/register.cron-simple.ts‎

Lines changed: 5 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import { defaultRuntime } from "../../runtime.js";
1111
import { sleep } from "../../utils/sleep.js";
1212
import type { GatewayRpcOpts } from "../gateway-rpc.js";
1313
import { addGatewayClientOptions, callGatewayFromCli } from "../gateway-rpc.js";
14+
import { exitCliAfterOutput } from "../one-shot-exit.js";
1415
import { parseDurationMs } from "../parse-duration.js";
1516
import { parseTimeoutMs } from "../parse-timeout.js";
1617
import { findCronJobByIdOrName } from "./list-jobs.js";
@@ -34,11 +35,6 @@ type CronRunCommandResult = {
3435
runId?: string;
3536
};
3637

37-
type CronRunLogEntryResult = Pick<
38-
CronRunLogEntry,
39-
"status" | "completionStatus" | "delivered" | "deliveryStatus"
40-
>;
41-
4238
function parseCronRunWaitDuration(raw: unknown, label: string): number {
4339
const input =
4440
typeof raw === "string" || typeof raw === "number" || typeof raw === "bigint"
@@ -65,7 +61,7 @@ async function waitForCronRunCompletion(params: {
6561
runId: string;
6662
timeoutMs: number;
6763
pollIntervalMs: number;
68-
}): Promise<CronRunLogEntryResult> {
64+
}): Promise<CronRunLogEntry> {
6965
// Poll the task ledger rather than cron.run because completion state is written asynchronously.
7066
const startedAt = performance.now();
7167
let hasPolled = false;
@@ -86,7 +82,7 @@ async function waitForCronRunCompletion(params: {
8682
id: params.jobId,
8783
runId: params.runId,
8884
limit: 1,
89-
})) as { entries?: CronRunLogEntryResult[] };
85+
})) as { entries?: CronRunLogEntry[] };
9086
const entry = page.entries?.[0];
9187
if (entry?.status === "ok" || entry?.status === "error" || entry?.status === "skipped") {
9288
return entry;
@@ -282,11 +278,10 @@ export function registerCronSimpleCommands(cron: Command) {
282278
completionStatus,
283279
run: completedRun,
284280
});
285-
defaultRuntime.exit(completionStatus === "succeeded" ? 0 : 1);
286-
return;
281+
exitCliAfterOutput(defaultRuntime, completionStatus === "succeeded" ? 0 : 1);
287282
}
288283
printCronJson(res);
289-
defaultRuntime.exit(result?.ok && (result?.ran || result?.enqueued) ? 0 : 1);
284+
exitCliAfterOutput(defaultRuntime, result?.ok && (result.ran || result.enqueued) ? 0 : 1);
290285
} catch (err) {
291286
handleCronCliError(err);
292287
}

‎src/cli/cron-cli/shared.ts‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,12 +21,13 @@ import {
2121
parseOffsetlessIsoDateTimeInTimeZone,
2222
} from "../../infra/format-time/parse-offsetless-zoned-datetime.js";
2323
import { formatTimestamp } from "../../logging/timestamps.js";
24-
import { defaultRuntime, type RuntimeEnv } from "../../runtime.js";
24+
import { defaultRuntime, ExitError, type RuntimeEnv } from "../../runtime.js";
2525
import { formatLookupMiss } from "../error-format.js";
2626
import { rethrowExpectedCliError } from "../failure-output.js";
2727
import type { GatewayRpcOpts } from "../gateway-rpc.js";
2828
import { callGatewayFromCli } from "../gateway-rpc.js";
2929
import { isJsonOutputModeActive } from "../json-output-mode.js";
30+
import { exitCliAfterOutput } from "../one-shot-exit.js";
3031
import { parseDurationMs as parseSharedDurationMs } from "../parse-duration.js";
3132

3233
function parseCronArgv(value: unknown, flag: string): string[] | undefined {
@@ -228,14 +229,18 @@ function formatCronStatusForDisplay(job: CronJob) {
228229
}
229230

230231
export function handleCronCliError(err: unknown) {
232+
// Completed outcomes must reach CLI cleanup, not become new cron errors.
233+
if (err instanceof ExitError) {
234+
throw err;
235+
}
231236
rethrowExpectedCliError(err);
232237
const missingJob = readCronJobNotFoundError(err);
233238
const message = missingJob ? formatCronLookupMiss(missingJob.jobId) : formatErrorMessage(err);
234239
if (isJsonOutputModeActive(process.argv)) {
235240
throw missingJob ? new Error(message) : err;
236241
}
237242
defaultRuntime.error(danger(message));
238-
defaultRuntime.exit(1);
243+
exitCliAfterOutput(defaultRuntime, 1);
239244
}
240245

241246
export const formatCronLookupMiss = (jobId: string) =>

0 commit comments

Comments
 (0)