Skip to content

Commit 2bcc06c

Browse files
authored
fix(cron): required delivery failures no longer report success (#126164)
* 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 * fix(cron): keep completion contracts acyclic * fix(cron): keep delivery predicate private
1 parent d64c1a1 commit 2bcc06c

40 files changed

Lines changed: 827 additions & 116 deletions

‎apps/shared/OpenClawKit/Sources/OpenClawProtocol/GatewayModels.swift‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16541,6 +16541,7 @@ public struct CronRunLogEntry: Codable, Sendable {
1654116541
public let jobid: String
1654216542
public let action: String
1654316543
public let status: AnyCodable?
16544+
public let completionstatus: AnyCodable?
1654416545
public let error: String?
1654516546
public let errorreason: AnyCodable?
1654616547
public let summary: String?
@@ -16567,6 +16568,7 @@ public struct CronRunLogEntry: Codable, Sendable {
1656716568
jobid: String,
1656816569
action: String,
1656916570
status: AnyCodable? = nil,
16571+
completionstatus: AnyCodable? = nil,
1657016572
error: String? = nil,
1657116573
errorreason: AnyCodable? = nil,
1657216574
summary: String? = nil,
@@ -16592,6 +16594,7 @@ public struct CronRunLogEntry: Codable, Sendable {
1659216594
self.jobid = jobid
1659316595
self.action = action
1659416596
self.status = status
16597+
self.completionstatus = completionstatus
1659516598
self.error = error
1659616599
self.errorreason = errorreason
1659716600
self.summary = summary
@@ -16619,6 +16622,7 @@ public struct CronRunLogEntry: Codable, Sendable {
1661916622
case jobid = "jobId"
1662016623
case action
1662116624
case status
16625+
case completionstatus = "completionStatus"
1662216626
case error
1662316627
case errorreason = "errorReason"
1662416628
case summary

‎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: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
type CronCompletionRunStatus = "ok" | "error" | "skipped";
2+
3+
type CronCompletionDeliveryStatus = "delivered" | "not-delivered" | "unknown" | "not-requested";
4+
5+
type CronCompletionJob = {
6+
delivery?: {
7+
mode?: "none" | "announce" | "webhook";
8+
bestEffort?: boolean;
9+
};
10+
};
11+
12+
/** Whole-run completion after execution and any explicitly required delivery settle. */
13+
export type CronCompletionStatus = "succeeded" | "failed" | "unknown";
14+
15+
/** Required delivery is an explicit admitted policy, never an inferred default. */
16+
function isCronDeliveryRequired(job: CronCompletionJob): boolean {
17+
return (
18+
job.delivery?.bestEffort === false &&
19+
(job.delivery.mode === "announce" || job.delivery.mode === "webhook")
20+
);
21+
}
22+
23+
/** Resolves authored completion from an admitted job, or legacy completion from stored facts. */
24+
export function resolveCronCompletionStatus(params: {
25+
status?: CronCompletionRunStatus;
26+
delivered?: boolean;
27+
deliveryStatus?: CronCompletionDeliveryStatus;
28+
requiredDelivery?: boolean;
29+
}): CronCompletionStatus {
30+
if (params.status === "error" || params.status === "skipped") {
31+
return "failed";
32+
}
33+
if (params.status !== "ok") {
34+
return "unknown";
35+
}
36+
if (params.requiredDelivery === undefined) {
37+
return params.delivered === true ||
38+
params.deliveryStatus === "delivered" ||
39+
params.deliveryStatus === "not-requested"
40+
? "succeeded"
41+
: "unknown";
42+
}
43+
if (!params.requiredDelivery) {
44+
return "succeeded";
45+
}
46+
if (params.deliveryStatus === "delivered") {
47+
return "succeeded";
48+
}
49+
return params.deliveryStatus === "not-delivered" ? "failed" : "unknown";
50+
}
51+
52+
/** Resolves completion from the immutable delivery contract admitted for this run. */
53+
export function resolveAdmittedCronCompletionStatus(
54+
job: CronCompletionJob,
55+
status: CronCompletionRunStatus,
56+
deliveryStatus: CronCompletionDeliveryStatus,
57+
): CronCompletionStatus {
58+
return resolveCronCompletionStatus({
59+
status,
60+
deliveryStatus,
61+
requiredDelivery: isCronDeliveryRequired(job),
62+
});
63+
}

‎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)