Skip to content

Commit 383363e

Browse files
steipetePeter Steinberger
andauthored
fix(cron): preserve lazy ownership and bounded notification lifetimes (#117018)
* fix(cron): preserve lazy ownership and bound notification lifetimes * fix(cron): respect fs-safe policy boundary --------- Co-authored-by: Peter Steinberger <[email protected]>
1 parent 21fba83 commit 383363e

11 files changed

Lines changed: 339 additions & 65 deletions

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

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,15 @@ describe("system-cli", () => {
6969
expect(runtimeLogs).toEqual([JSON.stringify({ id: "wake-1" }, null, 2)]);
7070
});
7171

72+
it("reports a rejected system event instead of claiming it was enqueued", async () => {
73+
callGatewayFromCli.mockResolvedValueOnce({ ok: false, reason: "unwakeable-session-key" });
74+
75+
await runCli(["system", "event", "--text", "hello"]);
76+
77+
expect(runtimeLogs).toEqual([]);
78+
expect(runtimeErrors[0]).toContain("unwakeable-session-key");
79+
});
80+
7281
it("handles invalid wake mode as runtime error", async () => {
7382
await runCli(["system", "event", "--text", "hello", "--mode", "later"]);
7483

‎src/cli/system-cli.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,12 +83,20 @@ export function registerSystemCli(program: Command) {
8383
}
8484
const mode = normalizeWakeMode(opts.mode);
8585
const sessionKey = normalizeOptionalString(opts.sessionKey);
86-
return await callGatewayFromCli(
86+
const result = await callGatewayFromCli(
8787
"wake",
8888
opts,
8989
sessionKey ? { mode, text, sessionKey } : { mode, text },
9090
{ expectFinal: false },
9191
);
92+
if (typeof result === "object" && result !== null && "ok" in result && !result.ok) {
93+
const reason =
94+
"reason" in result && typeof result.reason === "string"
95+
? result.reason
96+
: "Gateway did not accept the system event";
97+
throw new Error(reason);
98+
}
99+
return result;
92100
},
93101
"ok",
94102
);

‎src/cron/delivery.failure-notify.test.ts‎

Lines changed: 160 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,8 @@ vi.mock("../logging.js", () => ({
3737
})),
3838
}));
3939

40-
const { sendFailureNotificationAnnounce } = await import("./delivery.js");
40+
const { sendCronAnnouncePayloadStrict, sendFailureNotificationAnnounce } =
41+
await import("./delivery.js");
4142

4243
type DeliveryRequest = {
4344
abortSignal?: unknown;
@@ -184,6 +185,39 @@ describe("sendFailureNotificationAnnounce", () => {
184185
);
185186
});
186187

188+
it("does not begin strict delivery when target resolution settles after cancellation", async () => {
189+
let resolvePendingTarget: (value: unknown) => void = () => {};
190+
mocks.resolveDeliveryTarget.mockImplementationOnce(
191+
() =>
192+
new Promise((resolve) => {
193+
resolvePendingTarget = resolve;
194+
}),
195+
);
196+
const abortController = new AbortController();
197+
198+
const delivery = sendCronAnnouncePayloadStrict({
199+
deps: {} as never,
200+
cfg: {} as never,
201+
agentId: "main",
202+
jobId: "job-1",
203+
target: { channel: "telegram", to: "123" },
204+
message: "Cron failed",
205+
abortSignal: abortController.signal,
206+
});
207+
208+
abortController.abort(new Error("delivery deadline exceeded"));
209+
resolvePendingTarget({
210+
ok: true,
211+
channel: "telegram",
212+
to: "123",
213+
accountId: "bot-a",
214+
mode: "explicit",
215+
});
216+
217+
await expect(delivery).rejects.toThrow("delivery deadline exceeded");
218+
expect(mocks.deliverOutboundPayloads).not.toHaveBeenCalled();
219+
});
220+
187221
it("does not send when target resolution fails", async () => {
188222
mocks.resolveDeliveryTarget.mockResolvedValue({
189223
ok: false,
@@ -206,6 +240,131 @@ describe("sendFailureNotificationAnnounce", () => {
206240
);
207241
});
208242

243+
it("logs thrown target-resolution failures without masking the failed cron run", async () => {
244+
mocks.resolveDeliveryTarget.mockRejectedValueOnce(new Error("target lookup failed"));
245+
246+
await expect(
247+
sendFailureNotificationAnnounce(
248+
{} as never,
249+
{} as never,
250+
"main",
251+
"job-1",
252+
{ channel: "telegram", to: "123" },
253+
"Cron failed",
254+
),
255+
).resolves.toBeUndefined();
256+
257+
expect(mocks.deliverOutboundPayloads).not.toHaveBeenCalled();
258+
expect(mocks.warn).toHaveBeenCalledWith(
259+
{ err: "target lookup failed", channel: "telegram", to: "123" },
260+
"cron: failure destination announce failed",
261+
);
262+
});
263+
264+
it("bounds stalled target resolution without starting a late channel send", async () => {
265+
vi.useFakeTimers();
266+
let resolvePendingTarget: (value: unknown) => void = () => {};
267+
mocks.resolveDeliveryTarget.mockImplementationOnce(
268+
() =>
269+
new Promise((resolve) => {
270+
resolvePendingTarget = resolve;
271+
}),
272+
);
273+
274+
const notification = sendFailureNotificationAnnounce(
275+
{} as never,
276+
{} as never,
277+
"main",
278+
"job-1",
279+
{ channel: "telegram", to: "123" },
280+
"Cron failed",
281+
);
282+
283+
await vi.advanceTimersByTimeAsync(29_999);
284+
expect(mocks.warn).not.toHaveBeenCalled();
285+
expect(mocks.deliverOutboundPayloads).not.toHaveBeenCalled();
286+
287+
await vi.advanceTimersByTimeAsync(1);
288+
await expect(notification).resolves.toBeUndefined();
289+
expect(mocks.warn).toHaveBeenCalledWith(
290+
{
291+
err: "cron: failure destination announcement timed out",
292+
channel: "telegram",
293+
to: "123",
294+
},
295+
"cron: failure destination announce failed",
296+
);
297+
298+
resolvePendingTarget({
299+
ok: true,
300+
channel: "telegram",
301+
to: "123",
302+
accountId: "bot-a",
303+
mode: "explicit",
304+
});
305+
await vi.advanceTimersByTimeAsync(0);
306+
expect(mocks.deliverOutboundPayloads).not.toHaveBeenCalled();
307+
expect(vi.getTimerCount()).toBe(0);
308+
});
309+
310+
it.each([
311+
{ description: "honors cancellation", honorsCancellation: true },
312+
{ description: "ignores cancellation", honorsCancellation: false },
313+
])(
314+
"bounds a stalled failure notification when its channel $description",
315+
async ({ honorsCancellation }) => {
316+
vi.useFakeTimers();
317+
let deliverySignal: AbortSignal | undefined;
318+
mocks.deliverOutboundPayloads.mockImplementationOnce(
319+
({ abortSignal }: { abortSignal: AbortSignal }) =>
320+
new Promise<void>((_resolve, reject) => {
321+
deliverySignal = abortSignal;
322+
if (honorsCancellation) {
323+
abortSignal.addEventListener(
324+
"abort",
325+
() =>
326+
reject(
327+
abortSignal.reason instanceof Error
328+
? abortSignal.reason
329+
: new Error("failure notification was aborted"),
330+
),
331+
{ once: true },
332+
);
333+
}
334+
}),
335+
);
336+
337+
const notification = sendFailureNotificationAnnounce(
338+
{} as never,
339+
{} as never,
340+
"main",
341+
"job-1",
342+
{ channel: "telegram", to: "123" },
343+
"Cron failed",
344+
);
345+
346+
await vi.advanceTimersByTimeAsync(0);
347+
expect(mocks.deliverOutboundPayloads).toHaveBeenCalledOnce();
348+
expect(deliverySignal?.aborted).toBe(false);
349+
350+
await vi.advanceTimersByTimeAsync(29_999);
351+
expect(deliverySignal?.aborted).toBe(false);
352+
353+
await vi.advanceTimersByTimeAsync(1);
354+
await expect(notification).resolves.toBeUndefined();
355+
expect(deliverySignal?.aborted).toBe(true);
356+
expect(mocks.warn).toHaveBeenCalledWith(
357+
{
358+
err: "cron: failure destination announcement timed out",
359+
channel: "telegram",
360+
to: "123",
361+
},
362+
"cron: failure destination announce failed",
363+
);
364+
expect(vi.getTimerCount()).toBe(0);
365+
},
366+
);
367+
209368
it("swallows outbound delivery errors after logging", async () => {
210369
mocks.deliverOutboundPayloads.mockRejectedValue(new Error("send failed"));
211370

‎src/cron/delivery.ts‎

Lines changed: 41 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import type { CliDeps } from "../cli/deps.types.js";
44
import { createOutboundSendDeps } from "../cli/outbound-send-deps.js";
55
import type { OpenClawConfig } from "../config/types.js";
66
import { formatErrorMessage } from "../infra/errors.js";
7+
import { withTimeout } from "../infra/fs-safe.js";
78
import { resolveAgentOutboundIdentity } from "../infra/outbound/identity.js";
89
import { buildOutboundSessionContext } from "../infra/outbound/session-context.js";
910
import { getChildLogger } from "../logging.js";
@@ -130,6 +131,9 @@ export async function sendCronAnnouncePayloadStrict(params: {
130131
if (!delivery.ok) {
131132
throw delivery.error;
132133
}
134+
// Resolution can settle after its caller's deadline; never start plugin
135+
// delivery once the Gateway has released ownership of the timed-out work.
136+
params.abortSignal.throwIfAborted();
133137
await deliverCronAnnouncePayload({
134138
deps: params.deps,
135139
cfg: params.cfg,
@@ -148,42 +152,52 @@ export async function sendFailureNotificationAnnounce(
148152
target: CronAnnounceTarget,
149153
message: string,
150154
): Promise<void> {
151-
const delivery = await resolveCronAnnounceDelivery({ cfg, agentId, jobId, target });
152-
153-
if (!delivery.ok) {
154-
// Failure alerts must not mask the original cron run failure.
155-
cronDeliveryLogger.warn(
156-
{ error: delivery.error.message },
157-
"cron: failed to resolve failure destination target",
158-
);
159-
return;
160-
}
161-
162155
const abortController = new AbortController();
163-
const timeout = setTimeout(() => {
164-
// Failure notifications are secondary; timeout prevents a stuck channel send
165-
// from extending an already-failed cron run.
166-
abortController.abort();
167-
}, FAILURE_NOTIFICATION_TIMEOUT_MS);
156+
let resolvedTarget: SuccessfulDeliveryTarget | undefined;
168157

169158
try {
170-
await deliverCronAnnouncePayload({
171-
deps,
172-
cfg,
173-
delivery,
174-
message,
175-
abortSignal: abortController.signal,
176-
});
159+
// Bound resolution and transport together; either owner can stall while
160+
// retaining the detached Gateway work admission.
161+
await withTimeout(
162+
(async () => {
163+
const delivery = await resolveCronAnnounceDelivery({ cfg, agentId, jobId, target });
164+
if (!delivery.ok) {
165+
// Failure alerts must not mask the original cron run failure.
166+
cronDeliveryLogger.warn(
167+
{ error: delivery.error.message },
168+
"cron: failed to resolve failure destination target",
169+
);
170+
return;
171+
}
172+
resolvedTarget = delivery.resolvedTarget;
173+
// A resolver can settle after its deadline; never start a late send
174+
// after detached work ownership has already been released.
175+
abortController.signal.throwIfAborted();
176+
await deliverCronAnnouncePayload({
177+
deps,
178+
cfg,
179+
delivery,
180+
message,
181+
abortSignal: abortController.signal,
182+
});
183+
})(),
184+
FAILURE_NOTIFICATION_TIMEOUT_MS,
185+
{
186+
createError: () => {
187+
const error = new Error("cron: failure destination announcement timed out");
188+
abortController.abort(error);
189+
return error;
190+
},
191+
},
192+
);
177193
} catch (err) {
178194
cronDeliveryLogger.warn(
179195
{
180196
err: formatErrorMessage(err),
181-
channel: delivery.resolvedTarget.channel,
182-
to: delivery.resolvedTarget.to,
197+
channel: resolvedTarget?.channel ?? target.channel,
198+
to: resolvedTarget?.to ?? target.to,
183199
},
184200
"cron: failure destination announce failed",
185201
);
186-
} finally {
187-
clearTimeout(timeout);
188202
}
189203
}

‎src/gateway/server-cron-contract.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@ export type GatewayCronServiceContract = CronServiceContract & {
2222
resumeScheduling(): void;
2323
/** Scheduler-owned work not represented by active cron run markers. */
2424
getSuspensionBlockerCount?(): number;
25+
/** Materialize lazy cron dependencies before a synchronous operator wake. */
26+
prepareWake?(): Promise<void>;
2527
/** Stop cron and await scheduler-owned child process teardown. */
2628
stopAndDrain?(): Promise<void>;
2729
};

‎src/gateway/server-cron-lazy.test.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,30 @@ describe("createLazyGatewayCronState", () => {
9999
expect(cron["run"]).toHaveBeenCalledWith("demo", "force", { payload });
100100
});
101101

102+
it("preserves system-owned removal authority across lazy cron loading", async () => {
103+
const cron = createCronService();
104+
hoisted.setState(createCronState(cron));
105+
106+
const lazy = createLazyGatewayCronState(createParams());
107+
await lazy.cron.remove("heartbeat-monitor", { systemOwned: true });
108+
109+
expect(cron["remove"]).toHaveBeenCalledExactlyOnceWith("heartbeat-monitor", {
110+
systemOwned: true,
111+
});
112+
});
113+
114+
it("prepares a lazy scheduler before an operator wake without starting it", async () => {
115+
const cron = createCronService();
116+
hoisted.setState(createCronState(cron));
117+
118+
const lazy = createLazyGatewayCronState(createParams());
119+
await lazy.cron.prepareWake?.();
120+
121+
expect(lazy.cron.wake({ mode: "now", text: "ping" })).toEqual({ ok: true });
122+
expect(cron["start"]).not.toHaveBeenCalled();
123+
expect(cron["wake"]).toHaveBeenCalledExactlyOnceWith({ mode: "now", text: "ping" });
124+
});
125+
102126
it("starts the loaded cron service once", async () => {
103127
const cron = createCronService();
104128
hoisted.setState(createCronState(cron));

‎src/gateway/server-cron-lazy.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -259,8 +259,8 @@ export function createLazyGatewayCronState(params: LazyGatewayCronParams): Gatew
259259
async updateWithPrecondition(id, patch, precondition) {
260260
return await (await load()).state.cron.updateWithPrecondition(id, patch, precondition);
261261
},
262-
async remove(id) {
263-
return await (await load()).state.cron.remove(id);
262+
async remove(id, opts) {
263+
return await (await load()).state.cron.remove(id, opts);
264264
},
265265
async removeStaleJobFamily(family) {
266266
return await (await load()).state.cron.removeStaleJobFamily(family);
@@ -295,6 +295,9 @@ export function createLazyGatewayCronState(params: LazyGatewayCronParams): Gatew
295295
}
296296
return loaded.state.cron.getDefaultAgentId();
297297
},
298+
async prepareWake() {
299+
await load();
300+
},
298301
wake(opts) {
299302
if (!loaded) {
300303
// A wake should kick off lazy loading but cannot claim success before

0 commit comments

Comments
 (0)