Skip to content

Commit 810f42d

Browse files
committed
test(cron): cover execution diagnostics
1 parent 665b478 commit 810f42d

2 files changed

Lines changed: 293 additions & 0 deletions

File tree

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
title: Cron execution diagnostics
2+
3+
scenario:
4+
id: cron-execution-diagnostics
5+
surface: automation
6+
category: automation.cron-jobs
7+
coverage:
8+
primary:
9+
- automation.model-provider-preflight
10+
- automation.timeout-and-denial-diagnostics
11+
objective: Prove isolated cron runs persist and expose provider preflight, timeout, and execution-denial diagnostics.
12+
successCriteria:
13+
- A real loopback transport failure is rejected by the production isolated-run model-provider preflight before agent execution.
14+
- The provider-preflight skip is persisted in cron task history and emitted as an operator-visible finished event.
15+
- A terminal command-lane timeout is normalized, persisted, and emitted with its canonical cron diagnostic.
16+
- A fatal typed execution denial is normalized, persisted, and emitted with its tool diagnostic.
17+
docsRefs:
18+
- docs/automation/cron-jobs.md
19+
- docs/cli/cron.md
20+
- docs/gateway/protocol.md
21+
codeRefs:
22+
- src/cron/isolated-agent/model-preflight.runtime.ts
23+
- src/cron/isolated-agent/run.ts
24+
- src/cron/isolated-agent/run-finalize.ts
25+
- src/cron/service/timer-execution.ts
26+
- src/cron/task-run-history.ts
27+
- src/cron/cron-execution-diagnostics.e2e.test.ts
28+
execution:
29+
kind: vitest
30+
path: src/cron/cron-execution-diagnostics.e2e.test.ts
31+
summary: Run real CronService jobs through isolated-run preflight and terminal diagnostic persistence boundaries.
Lines changed: 262 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,262 @@
1+
import { createServer, type Server } from "node:net";
2+
import type { AddressInfo } from "node:net";
3+
import { afterAll, beforeEach, describe, expect, it, vi } from "vitest";
4+
import type { OpenClawConfig } from "../config/config.js";
5+
import { resetTaskRegistryForTests } from "../tasks/task-runtime.test-helpers.js";
6+
import { withOpenClawTestState } from "../test-utils/openclaw-test-state.js";
7+
import {
8+
loadRunCronIsolatedAgentTurn,
9+
mockRunCronFallbackPassthrough,
10+
resetRunCronIsolatedAgentTurnHarness,
11+
resolveAllowedModelRefMock,
12+
resolveConfiguredModelRefMock,
13+
runEmbeddedAgentMock,
14+
runWithModelFallbackMock,
15+
} from "./isolated-agent/run.test-harness.js";
16+
import { CronService, type CronEvent } from "./service.js";
17+
import { createNoopLogger } from "./service.test-harness.js";
18+
import { cronStoreKey } from "./store/key.js";
19+
import { readCronTaskRunHistoryPage } from "./task-run-history.js";
20+
21+
vi.doUnmock("./isolated-agent/model-preflight.runtime.js");
22+
23+
const runCronIsolatedAgentTurn = await loadRunCronIsolatedAgentTurn();
24+
const { resetCronModelProviderPreflightCacheForTest } =
25+
await import("./isolated-agent/model-preflight.runtime.js");
26+
27+
type ModelRef = { provider: string; model: string };
28+
29+
function makeCommandLaneTaskTimeoutError(lane: string, timeoutMs: number): Error {
30+
const error = new Error(`Command lane "${lane}" task timed out after ${timeoutMs}ms`);
31+
error.name = "CommandLaneTaskTimeoutError";
32+
return error;
33+
}
34+
35+
async function listenForBrokenHttpConnections(): Promise<{
36+
baseUrl: string;
37+
server: Server;
38+
}> {
39+
const server = createServer((socket) => socket.destroy());
40+
await new Promise<void>((resolve, reject) => {
41+
server.once("error", reject);
42+
server.listen(0, "127.0.0.1", resolve);
43+
});
44+
const address = server.address() as AddressInfo;
45+
return { baseUrl: `http://127.0.0.1:${address.port}`, server };
46+
}
47+
48+
async function closeServer(server: Server): Promise<void> {
49+
await new Promise<void>((resolve, reject) => {
50+
server.close((error) => (error ? reject(error) : resolve()));
51+
});
52+
}
53+
54+
function configFor(modelRef: ModelRef, localBaseUrl?: string): OpenClawConfig {
55+
return {
56+
agents: {
57+
defaults: {
58+
model: `${modelRef.provider}/${modelRef.model}`,
59+
},
60+
},
61+
...(localBaseUrl
62+
? {
63+
models: {
64+
providers: {
65+
[modelRef.provider]: {
66+
api: "ollama",
67+
baseUrl: localBaseUrl,
68+
models: [],
69+
},
70+
},
71+
},
72+
}
73+
: {}),
74+
};
75+
}
76+
77+
async function runPersistedDiagnosticCase(params: {
78+
cfg: OpenClawConfig;
79+
modelRef: ModelRef;
80+
name: string;
81+
}) {
82+
return await withOpenClawTestState(
83+
{ layout: "state-only", prefix: "openclaw-cron-execution-diagnostics-" },
84+
async (state) => {
85+
resetTaskRegistryForTests();
86+
const events: CronEvent[] = [];
87+
const storePath = state.path("cron", "jobs.json");
88+
const cron = new CronService({
89+
storePath,
90+
cronEnabled: true,
91+
cronConfig: { triggers: { enabled: true } },
92+
log: createNoopLogger(),
93+
enqueueSystemEvent: vi.fn(),
94+
requestHeartbeat: vi.fn(),
95+
onEvent: (event) => events.push(structuredClone(event)),
96+
runIsolatedAgentJob: async (runParams) =>
97+
await runCronIsolatedAgentTurn({
98+
...runParams,
99+
cfg: params.cfg,
100+
deps: {},
101+
sessionKey: `cron:${runParams.job.id}`,
102+
}),
103+
});
104+
try {
105+
await cron.start();
106+
const job = await cron.add({
107+
name: params.name,
108+
enabled: true,
109+
schedule: { kind: "every", everyMs: 60_000 },
110+
sessionTarget: "isolated",
111+
wakeMode: "next-heartbeat",
112+
payload: {
113+
kind: "agentTurn",
114+
message: `run ${params.name}`,
115+
model: `${params.modelRef.provider}/${params.modelRef.model}`,
116+
},
117+
delivery: { mode: "none" },
118+
});
119+
await expect(cron.run(job.id, "force")).resolves.toEqual({ ok: true, ran: true });
120+
121+
const finished = events.find(
122+
(event) => event.action === "finished" && event.jobId === job.id,
123+
);
124+
const history = readCronTaskRunHistoryPage({
125+
storeKey: cronStoreKey(storePath),
126+
jobId: job.id,
127+
limit: 1,
128+
}).entries[0];
129+
expect(finished).toBeDefined();
130+
expect(history).toBeDefined();
131+
return { finished: finished!, history: history! };
132+
} finally {
133+
cron.stop();
134+
resetTaskRegistryForTests({ persist: false });
135+
}
136+
},
137+
);
138+
}
139+
140+
describe.sequential("cron execution diagnostics", () => {
141+
const servers: Server[] = [];
142+
143+
beforeEach(() => {
144+
resetRunCronIsolatedAgentTurnHarness();
145+
resetCronModelProviderPreflightCacheForTest();
146+
});
147+
148+
afterAll(async () => {
149+
await Promise.all(servers.map(closeServer));
150+
});
151+
152+
it("persists and emits a real isolated-run local-provider preflight failure", async () => {
153+
const endpoint = await listenForBrokenHttpConnections();
154+
servers.push(endpoint.server);
155+
const modelRef = { provider: "ollama", model: "diagnostic-model" };
156+
resolveConfiguredModelRefMock.mockReturnValue(modelRef);
157+
resolveAllowedModelRefMock.mockReturnValue({ ref: modelRef });
158+
159+
const { finished, history } = await runPersistedDiagnosticCase({
160+
cfg: configFor(modelRef, endpoint.baseUrl),
161+
modelRef,
162+
name: "unreachable provider",
163+
});
164+
165+
expect(runWithModelFallbackMock).not.toHaveBeenCalled();
166+
expect(runEmbeddedAgentMock).not.toHaveBeenCalled();
167+
for (const outcome of [finished, history]) {
168+
expect(outcome).toMatchObject({
169+
status: "skipped",
170+
provider: "ollama",
171+
model: "diagnostic-model",
172+
error: expect.stringContaining("unavailable"),
173+
diagnostics: {
174+
entries: expect.arrayContaining([
175+
expect.objectContaining({
176+
source: "model-preflight",
177+
severity: "warn",
178+
message: expect.stringContaining("unavailable"),
179+
}),
180+
]),
181+
},
182+
});
183+
}
184+
});
185+
186+
it("persists and emits the canonical terminal timeout diagnostic", async () => {
187+
const modelRef = { provider: "openai", model: "gpt-5.4" };
188+
resolveConfiguredModelRefMock.mockReturnValue(modelRef);
189+
runWithModelFallbackMock.mockRejectedValueOnce(
190+
makeCommandLaneTaskTimeoutError("cron-nested", 330_000),
191+
);
192+
193+
const { finished, history } = await runPersistedDiagnosticCase({
194+
cfg: configFor(modelRef),
195+
modelRef,
196+
name: "nested lane timeout",
197+
});
198+
199+
for (const outcome of [finished, history]) {
200+
expect(outcome).toMatchObject({
201+
status: "error",
202+
provider: "openai",
203+
model: "gpt-5.4",
204+
error: "cron: job execution timed out",
205+
diagnostics: {
206+
entries: expect.arrayContaining([
207+
expect.objectContaining({
208+
source: "cron-setup",
209+
severity: "error",
210+
message: "cron: job execution timed out",
211+
}),
212+
]),
213+
},
214+
});
215+
}
216+
});
217+
218+
it("persists and emits a fatal execution-denial diagnostic", async () => {
219+
const modelRef = { provider: "openai", model: "gpt-5.4" };
220+
resolveConfiguredModelRefMock.mockReturnValue(modelRef);
221+
mockRunCronFallbackPassthrough();
222+
runEmbeddedAgentMock.mockResolvedValueOnce({
223+
payloads: [],
224+
meta: {
225+
agentMeta: {},
226+
failureSignal: {
227+
kind: "execution_denied",
228+
source: "tool",
229+
toolName: "exec",
230+
code: "SYSTEM_RUN_DENIED",
231+
message: "SYSTEM_RUN_DENIED: approval required",
232+
fatalForCron: true,
233+
},
234+
},
235+
});
236+
237+
const { finished, history } = await runPersistedDiagnosticCase({
238+
cfg: configFor(modelRef),
239+
modelRef,
240+
name: "execution denied",
241+
});
242+
243+
for (const outcome of [finished, history]) {
244+
expect(outcome).toMatchObject({
245+
status: "error",
246+
provider: "openai",
247+
model: "gpt-5.4",
248+
error: "SYSTEM_RUN_DENIED: approval required",
249+
summary: "SYSTEM_RUN_DENIED: approval required",
250+
diagnostics: {
251+
entries: expect.arrayContaining([
252+
expect.objectContaining({
253+
source: "tool",
254+
severity: "error",
255+
message: "SYSTEM_RUN_DENIED: approval required",
256+
}),
257+
]),
258+
},
259+
});
260+
}
261+
});
262+
});

0 commit comments

Comments
 (0)