Skip to content

Commit 3c8c9d3

Browse files
committed
fix(cron): preserve required delivery completion
Record durable completion independently from payload execution so required delivery failure cannot delete one-shots or report successful waits.\n\nCloses #126163
1 parent 934a32c commit 3c8c9d3

40 files changed

Lines changed: 812 additions & 115 deletions

‎docs/automation/cron-jobs.md‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ Manage automations with the `openclaw automations` CLI; `openclaw cron` remains
4444
- Automations run **inside the Gateway process**, not inside the model. The Gateway must be running for schedules to fire.
4545
- Job definitions, runtime state, and run history persist in OpenClaw's shared SQLite state database, so restarts do not lose schedules.
4646
- Every automation run creates a [background task](/automation/tasks) record.
47-
- One-shot jobs (`--at`) auto-delete after success by default; pass `--keep-after-run` to keep them.
47+
- One-shot jobs (`--at`) auto-delete only when run `completionStatus` is `succeeded`; pass `--keep-after-run` to keep successful jobs. A required-delivery failure or unknown completion keeps the job disabled for inspection and restart recovery without replaying the payload.
4848
- Per-run wall-clock budget: `--timeout-seconds` when set. Otherwise, isolated/detached agent-turn jobs are bounded by the scheduler's own 60-minute watchdog before the underlying agent-turn timeout (`agents.defaults.timeoutSeconds`, default 48 hours) would ever apply; command jobs default to 10 minutes, and script payloads default to 5 minutes.
4949
- On Gateway startup, overdue isolated agent-turn jobs are rescheduled instead of replayed immediately, keeping model/tool bootstrap work out of the channel-connect window.
5050
- If you drive `openclaw agent` from system cron or another external scheduler, wrap it with a hard-kill escalation even though the CLI already handles `SIGTERM`/`SIGINT`. Gateway-backed runs ask the Gateway to abort accepted runs; `--local` runs get the same abort signal. For GNU `timeout`, prefer `timeout -k 60 600 openclaw agent ...` over plain `timeout 600 ...` — the `-k` value is the backstop if the process cannot drain in time. For systemd units, use a `SIGTERM` stop signal with a grace window (`TimeoutStopSec`) before the final kill. Reusing a `--run-id` while the original Gateway run is still active reports the duplicate as in-flight instead of starting a second run.
@@ -510,7 +510,9 @@ openclaw automations edit <jobId> --clear-agent
510510

511511
Archiving a session (Control UI, or `sessions.patch { key, archived: true, expectedSessionId }` using the durable ID from `sessions.list`) disables every enabled automation job bound to that session: its isolated `cron:<jobId>` session, a `session:<key>` target, or a delivery/wake `sessionKey` lane. Restoring the session requires the same observed identity and does not re-enable those jobs; use `openclaw automations enable <jobId>`. Sessions with an enabled bound job show a clock badge in the Control UI sidebar.
512512

513-
`openclaw automations run <jobId>` returns after enqueueing the manual run. Use `--wait` for shutdown hooks, maintenance scripts, or other automation that must block until the queued run finishes; it polls the returned `runId` (default timeout `10m`, poll interval `2s`) and exits `0` for status `ok`, non-zero for `error`, `skipped`, or a wait timeout.
513+
`openclaw automations run <jobId>` returns after enqueueing the manual run. Use `--wait` for shutdown hooks, maintenance scripts, or other automation that must block until the queued run finishes; it polls the returned `runId` (default timeout `10m`, poll interval `2s`) and exits `0` only for `completionStatus: "succeeded"`. Failed or unknown completion and wait timeouts exit non-zero.
514+
515+
Run history keeps payload execution in `status` (`ok`, `error`, or `skipped`) and whole-run completion in `completionStatus` (`succeeded`, `failed`, or `unknown`). Delivery is required only when the admitted job explicitly sets `delivery.bestEffort: false`; delivery-only failure leaves execution `status: "ok"`, does not increment execution error counters or enter retry backoff, and records `completionStatus: "failed"`.
514516

515517
Direct Gateway event sources can use `cron.run` with `mode: "if-enabled"` to run immediately without overriding an operator-disabled or auto-disabled job. Explicit operator run-now commands continue to use `force`.
516518

‎docs/cli/cron.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,7 @@ If an isolated run times out before the first model request, `openclaw automatio
137137
`--at <datetime>` schedules a one-shot run. Offset-less datetimes are treated as UTC unless you also pass `--tz <iana>`, which interprets the wall-clock time in the given timezone.
138138

139139
<Note>
140-
One-shot jobs delete after success by default. Use `--keep-after-run` to preserve them.
140+
One-shot jobs delete only after `completionStatus: "succeeded"`. Required-delivery failure or unknown completion keeps the job disabled, with no next run, so restarts do not replay payload side effects. Use `--keep-after-run` to preserve successful jobs too.
141141
</Note>
142142

143143
### Recurring jobs
@@ -165,7 +165,7 @@ Add `--wait` when a script should block until that exact queued run records a te
165165
openclaw automations run <job-id> --wait --wait-timeout 10m --poll-interval 2s
166166
```
167167

168-
With `--wait`, the CLI still calls `cron.run` first, then polls `cron.runs` for the returned `runId`. The command exits `0` only when the run finishes with status `ok`. It exits non-zero when the run finishes with `error` or `skipped`, when the Gateway response does not include a `runId`, or when `--wait-timeout` expires (default `10m`, polled every `2s` by default). `--poll-interval` must be greater than zero.
168+
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.
169169

170170
<Note>
171171
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.

‎packages/gateway-protocol/src/cron-validators.test.ts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,33 @@ describe("cron protocol validators", () => {
102102
).toBe(false);
103103
});
104104

105+
it.each(["succeeded", "failed", "unknown"] as const)(
106+
"accepts additive cron completion status %s",
107+
(completionStatus) => {
108+
expect(
109+
Value.Check(CronRunLogEntrySchema, {
110+
ts: 1,
111+
jobId: "job-1",
112+
action: "finished",
113+
status: "ok",
114+
completionStatus,
115+
}),
116+
).toBe(true);
117+
},
118+
);
119+
120+
it("rejects unknown cron completion status values", () => {
121+
expect(
122+
Value.Check(CronRunLogEntrySchema, {
123+
ts: 1,
124+
jobId: "job-1",
125+
action: "finished",
126+
status: "ok",
127+
completionStatus: "partial",
128+
}),
129+
).toBe(false);
130+
});
131+
105132
it("rejects client-authored scheduled authority provenance", () => {
106133
const scheduledToolPolicy = { version: 1, mode: "trusted" } as const;
107134
expectCases(validateCronAddParams, false, [add({ scheduledToolPolicy })]);

‎packages/gateway-protocol/src/schema/cron.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,11 @@ function cronRunStatusSchema(options: Record<string, unknown> = {}) {
9797
}
9898

9999
const CronRunStatusSchema = cronRunStatusSchema();
100+
const CronCompletionStatusSchema = Type.Union([
101+
Type.Literal("succeeded"),
102+
Type.Literal("failed"),
103+
Type.Literal("unknown"),
104+
]);
100105
const CronConfigRevisionSchema = Type.String({ minLength: 1, maxLength: 128 });
101106
const DeprecatedCronRunStatusSchema = cronRunStatusSchema({
102107
deprecated: true,
@@ -753,6 +758,7 @@ export const CronRunLogEntrySchema = closedObject({
753758
jobId: NonEmptyString,
754759
action: Type.Literal("finished"),
755760
status: Type.Optional(CronRunStatusSchema),
761+
completionStatus: Type.Optional(CronCompletionStatusSchema),
756762
error: Type.Optional(Type.String()),
757763
errorReason: Type.Optional(FailoverReasonSchema),
758764
summary: Type.Optional(Type.String()),

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

Lines changed: 32 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -314,6 +314,7 @@ async function runCronRunAndCaptureExit(params: {
314314
runId?: string;
315315
runStatus?: "ok" | "error" | "skipped";
316316
runStatuses?: Array<"ok" | "error" | "skipped" | undefined>;
317+
completionStatus?: "succeeded" | "failed" | "unknown";
317318
args?: string[];
318319
}) {
319320
resetGatewayMock();
@@ -336,7 +337,17 @@ async function runCronRunAndCaptureExit(params: {
336337
const runStatus = params.runStatuses?.[runPollCount] ?? params.runStatus;
337338
runPollCount += 1;
338339
return {
339-
entries: runStatus ? [{ status: runStatus }] : [],
340+
entries: runStatus
341+
? [
342+
{
343+
status: runStatus,
344+
completionStatus: params.completionStatus,
345+
...(params.completionStatus === undefined && runStatus === "ok"
346+
? { deliveryStatus: "not-requested" }
347+
: {}),
348+
},
349+
]
350+
: [],
340351
};
341352
}
342353
return { ok: true, params: callParams };
@@ -378,6 +389,18 @@ describe("cron cli", () => {
378389
},
379390
);
380391

392+
it("uses legacy stored delivery for --wait completion", async () => {
393+
const { calls, exitSpy } = await runCronRunAndCaptureExit({
394+
enqueued: true,
395+
runId: "manual:legacy:123:0",
396+
runStatus: "ok",
397+
args: ["cron", "run", "job-1", "--wait", "--wait-timeout", "1s", "--poll-interval", "1ms"],
398+
});
399+
400+
expect(exitSpy).toHaveBeenCalledWith(0);
401+
expect(calls.some((call) => call[0] === "cron.get")).toBe(false);
402+
});
403+
381404
it.each(CRON_GATEWAY_COMMANDS)(
382405
"accepts leaf Gateway options for cron $name",
383406
async ({ name, args }) => {
@@ -454,16 +477,17 @@ describe("cron cli", () => {
454477
});
455478

456479
it.each([
457-
{ status: "ok" as const, expectedExitCode: 0 },
458-
{ status: "error" as const, expectedExitCode: 1 },
459-
{ status: "skipped" as const, expectedExitCode: 1 },
480+
{ status: "ok" as const, completionStatus: "succeeded" as const, expectedExitCode: 0 },
481+
{ status: "ok" as const, completionStatus: "failed" as const, expectedExitCode: 1 },
482+
{ status: "ok" as const, completionStatus: "unknown" as const, expectedExitCode: 1 },
460483
])(
461-
"waits for queued cron run completion with status $status",
462-
async ({ status, expectedExitCode }) => {
484+
"waits for execution $status with completion $completionStatus",
485+
async ({ status, completionStatus, expectedExitCode }) => {
463486
const { calls, exitSpy } = await runCronRunAndCaptureExit({
464487
enqueued: true,
465488
runId: "manual:job-1:123:0",
466489
runStatus: status,
490+
completionStatus,
467491
args: ["cron", "run", "job-1", "--wait", "--wait-timeout", "1s", "--poll-interval", "1ms"],
468492
});
469493

@@ -476,6 +500,8 @@ describe("cron cli", () => {
476500
});
477501
expect(stdoutText()).toContain('"completed": true');
478502
expect(stdoutText()).toContain(`"status": "${status}"`);
503+
expect(stdoutText()).toContain(`"completionStatus": "${completionStatus}"`);
504+
expect(calls.some((call) => call[0] === "cron.get")).toBe(false);
479505
},
480506
);
481507

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

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ import {
55
resolveTimerTimeoutMs,
66
} from "@openclaw/normalization-core/number-coercion";
77
import type { Command } from "commander";
8+
import { resolveCronCompletionStatus } from "../../cron/completion-status.js";
9+
import type { CronRunLogEntry } from "../../cron/run-log-types.js";
810
import { defaultRuntime } from "../../runtime.js";
911
import { sleep } from "../../utils/sleep.js";
1012
import type { GatewayRpcOpts } from "../gateway-rpc.js";
@@ -32,9 +34,10 @@ type CronRunCommandResult = {
3234
runId?: string;
3335
};
3436

35-
type CronRunLogEntryResult = {
36-
status?: "ok" | "error" | "skipped";
37-
};
37+
type CronRunLogEntryResult = Pick<
38+
CronRunLogEntry,
39+
"status" | "completionStatus" | "delivered" | "deliveryStatus"
40+
>;
3841

3942
function parseCronRunWaitDuration(raw: unknown, label: string): number {
4043
const input =
@@ -264,8 +267,22 @@ export function registerCronSimpleCommands(cron: Command) {
264267
timeoutMs: waitTimeoutMs,
265268
pollIntervalMs,
266269
});
267-
printCronJson({ ...res, completed: true, status: run.status, run });
268-
defaultRuntime.exit(run.status === "ok" ? 0 : 1);
270+
const completionStatus =
271+
run.completionStatus ??
272+
resolveCronCompletionStatus({
273+
status: run.status,
274+
delivered: run.delivered,
275+
deliveryStatus: run.deliveryStatus,
276+
});
277+
const completedRun = { ...run, completionStatus };
278+
printCronJson({
279+
...res,
280+
completed: true,
281+
status: run.status,
282+
completionStatus,
283+
run: completedRun,
284+
});
285+
defaultRuntime.exit(completionStatus === "succeeded" ? 0 : 1);
269286
return;
270287
}
271288
printCronJson(res);

‎src/cron/completion-status.ts‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import { isCronDeliveryRequired } from "./delivery-plan.js";
2+
import type { CronCompletionStatus, CronDeliveryStatus, CronJob, CronRunStatus } from "./types.js";
3+
4+
/** Resolves authored completion from an admitted job, or legacy completion from stored facts. */
5+
export function resolveCronCompletionStatus(params: {
6+
status?: CronRunStatus;
7+
delivered?: boolean;
8+
deliveryStatus?: CronDeliveryStatus;
9+
requiredDelivery?: boolean;
10+
}): CronCompletionStatus {
11+
if (params.status === "error" || params.status === "skipped") {
12+
return "failed";
13+
}
14+
if (params.status !== "ok") {
15+
return "unknown";
16+
}
17+
if (params.requiredDelivery === undefined) {
18+
return params.delivered === true ||
19+
params.deliveryStatus === "delivered" ||
20+
params.deliveryStatus === "not-requested"
21+
? "succeeded"
22+
: "unknown";
23+
}
24+
if (!params.requiredDelivery) {
25+
return "succeeded";
26+
}
27+
if (params.deliveryStatus === "delivered") {
28+
return "succeeded";
29+
}
30+
return params.deliveryStatus === "not-delivered" ? "failed" : "unknown";
31+
}
32+
33+
/** Resolves completion from the immutable delivery contract admitted for this run. */
34+
export function resolveAdmittedCronCompletionStatus(
35+
job: CronJob,
36+
status: CronRunStatus,
37+
deliveryStatus: CronDeliveryStatus,
38+
): CronCompletionStatus {
39+
return resolveCronCompletionStatus({
40+
status,
41+
deliveryStatus,
42+
requiredDelivery: isCronDeliveryRequired(job),
43+
});
44+
}

‎src/cron/delivery-plan.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,14 @@ export function resolveCronDeliveryPlan(job: CronJob): CronDeliveryPlan {
124124
};
125125
}
126126

127+
/** Required delivery is an explicit admitted policy, never an inferred default. */
128+
export function isCronDeliveryRequired(job: CronJob): boolean {
129+
const plan = resolveCronDeliveryPlan(job);
130+
return (
131+
job.delivery?.bestEffort === false && (plan.mode === "announce" || plan.mode === "webhook")
132+
);
133+
}
134+
127135
/** Normalized destination for notifying about cron execution failures. */
128136
type CronFailureDeliveryPlan = {
129137
mode: "announce" | "webhook";

‎src/cron/run-log-types.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
/** Stable cron run-history wire shape and legacy JSONL migration input. */
22
import type { FailoverReason } from "../agents/failover/signal.js";
33
import type {
4+
CronCompletionStatus,
45
CronDeliveryStatus,
56
CronDeliveryTrace,
67
CronFailureNotificationDelivery,
@@ -15,6 +16,7 @@ export type CronRunLogEntry = {
1516
jobId: string;
1617
action: "finished";
1718
status?: CronRunStatus;
19+
completionStatus?: CronCompletionStatus;
1820
error?: string;
1921
errorReason?: FailoverReason;
2022
summary?: string;

0 commit comments

Comments
 (0)