fix(workflow): distinguish watch completion from timeout and cancellation

This commit is contained in:
gitea committed 2026-10-20 18:06:53 +08:00
1 parent fac81b08e8
commit 98ceb85a5c
9 files changed
+187 -124

No files matched your search

@@ -0,0 +1,15 @@
import { expect, spyOn, test } from "bun:test";
import { parseArgs } from "../../parser.js";
import * as shared from "./shared.js";
import { handleWorkflowTailCommand } from "./tail.js";
test("CLI tail exits nonzero and emits timeout for a job still running at the deadline", async () => {
const client = { get: async (path: string) => Response.json({ data: path.includes("/execution") ? [] : { id: "job", pipelineId: "wf", status: "RUNNING" } }) };
const spy = spyOn(shared, "createWorkflowDetailClient").mockResolvedValue({ client } as any);
try {
const result = await handleWorkflowTailCommand(parseArgs(["workflow", "tail", "wf", "--job", "job", "--timeout", "0.005"]), { jsonMode: true } as any);
expect(result.exitCode).toBe(1);
const events = result.stdout.trim().split("\n").map(line => JSON.parse(line));
expect(events.some(e => e.type === "timeout")).toBe(true);
expect(events.some(e => e.type === "job_completed")).toBe(false);
} finally { spy.mockRestore(); }
});
+3 -3
View File
@@ -94,19 +94,19 @@ export async function handleWorkflowTailCommand(
return {
stdout: printJson(report, runtime.outputOptions),
stderr: "",
exitCode: report.hasFailures ? 1 : 0,
exitCode: report.hasFailures || report.timedOut || report.cancelled ? 1 : 0,
};
}
return {
stdout: runtime.writeStdout ? "" : outputChunks.join(""),
stderr: "",
exitCode: report.hasFailures ? 1 : 0,
exitCode: report.hasFailures || report.timedOut || report.cancelled ? 1 : 0,
};
}
return {
stdout: runtime.writeStdout ? "" : outputChunks.join(""),
stderr: "",
exitCode: report.hasFailures ? 1 : 0,
exitCode: report.hasFailures || report.timedOut || report.cancelled ? 1 : 0,
};
}
@@ -128,3 +128,5 @@ hose-use workflow eval-script --code="return a + b;" --input='{"a":1,"b":2}'
- 借助 Kimi 网桥(`kimi-webbridge`)建立真实微前端会话,自动探测并解析不同应用类型下的非费用类表单元数据;
- 提取出动态列、关联实体 ID 与系统字段字典,在 CLI 层面提供对非费用类业务对象的只读探针与结构化校验能力。
监听结果区分完成、超时、快照和取消:只有到达终态才发送 `job_completed`;超时发送 `timeout` 并设置 `timedOut`,取消设置 `cancelled`。CLI 超时或取消返回非零退出码;`--once` 的运行中快照仍可成功返回,且不冒充完成。持续监听的总超时预算覆盖正在跟踪的 Job。
@@ -39,6 +39,9 @@ export function formatWatchEvent(event: WorkflowWatchEvent): string {
case "timeout":
return `${tag} ⏱️ 监听超时,未在指定时间内捕获到新的任务状态变更。`;
case "cancelled":
return `${tag} 监听已取消,未宣称 Job 执行完成。`;
case "idle":
return `${tag} 💤 暂无新运行实例,继续等待中...`;
@@ -25,7 +25,7 @@ export async function watchWorkflowPipeline(
event.type !== "task_failed" &&
!(event.type === "task_skipped" && event.error) &&
event.type !== "job_completed" &&
event.type !== "timeout"
event.type !== "timeout" && event.type !== "cancelled"
) {
return;
}
@@ -46,7 +46,8 @@ export async function watchWorkflowPipeline(
pipelineId,
totalJobsWatched: 1,
jobs: watchedJobs,
timedOut: false,
timedOut: Boolean(jobResult.timedOut),
cancelled: jobResult.cancelled,
hasFailures: jobResult.hasError || jobResult.status === "FAILED",
};
}
@@ -182,10 +183,13 @@ export async function watchWorkflowPipeline(
// 实时跟踪该 Job 执行
const jobResult = await watchSingleJob(client, candidateJob.id, {
...options,
timeoutMs: Math.max(1, timeoutMs - (Date.now() - startTime)),
onEvent: emit,
});
watchedJobs.push(jobResult);
if (jobResult.timedOut) { timedOut = true; break; }
if (jobResult.cancelled) break;
if (watchedJobs.length >= maxJobs) {
break;
@@ -202,14 +206,12 @@ export async function watchWorkflowPipeline(
await new Promise((resolve) => setTimeout(resolve, Math.min(intervalMs, remaining)));
}
if (Date.now() - startTime >= timeoutMs && watchedJobs.length === 0) {
const cancelled = options.signal?.aborted === true;
if (!cancelled && Date.now() - startTime >= timeoutMs && watchedJobs.length < maxJobs) {
timedOut = true;
await emit({
type: "timeout",
pipelineId,
timestamp: Date.now(),
});
if (!watchedJobs.at(-1)?.timedOut) await emit({ type: "timeout", pipelineId, timestamp: Date.now() });
}
if (cancelled && !watchedJobs.at(-1)?.cancelled) await emit({ type: "cancelled", pipelineId, timestamp: Date.now() });
const hasFailures = watchedJobs.some((j) => j.hasError || j.status === "FAILED");
@@ -218,6 +220,7 @@ export async function watchWorkflowPipeline(
totalJobsWatched: watchedJobs.length,
jobs: watchedJobs,
timedOut,
cancelled,
hasFailures,
};
}
@@ -25,7 +25,7 @@ export async function watchSingleJob(
event.type !== "task_failed" &&
!(event.type === "task_skipped" && event.error) &&
event.type !== "job_completed" &&
event.type !== "timeout"
event.type !== "timeout" && event.type !== "cancelled"
) {
return;
}
@@ -77,11 +77,15 @@ export async function watchSingleJob(
await new Promise((resolve) => setTimeout(resolve, Math.min(intervalMs, remaining)));
}
const cancelled = options.signal?.aborted === true;
const timedOut = !options.once && !isTerminal && !cancelled;
// 终态最后同步一次失败节点信息
let failureItems: WorkflowTaskExecution[] = [];
try {
const failedPage = await api.getJobFailedExecutions(client, jobId);
failureItems = failedPage.items || [];
if (!cancelled) {
const failedPage = await api.getJobFailedExecutions(client, jobId);
failureItems = failedPage.items || [];
}
} catch {
// 忽略
}
@@ -106,9 +110,12 @@ export async function watchSingleJob(
hasError,
},
};
await emit(completionEvent);
if (isTerminal) await emit(completionEvent);
else if (timedOut || cancelled) await emit({ type: cancelled ? "cancelled" : "timeout", jobId, status: finalStatus, timestamp: Date.now() });
return {
timedOut,
cancelled,
jobId,
pipelineId: latestJob?.pipelineId || "",
status: finalStatus,
@@ -0,0 +1,29 @@
import { expect, mock, test } from "bun:test";
import { watchSingleJob } from "./single-job.js";
import { watchWorkflowPipeline } from "./pipeline-watcher.js";
function client(status = "RUNNING") {
return { get: mock(async (path: string) => Response.json({ data: path.includes("/execution") ? [] : { id: "job", pipelineId: "wf", status } })) } as any;
}
test("a running job times out without a completion event or false success report", async () => {
const report = await watchWorkflowPipeline(client(), "wf", { jobId: "job", timeoutMs: 5 });
expect(report.timedOut).toBe(true);
expect(report.jobs[0].status).toBe("RUNNING");
expect(report.jobs[0].events.map(e => e.type)).toContain("timeout");
expect(report.jobs[0].events.some(e => e.type === "job_completed")).toBe(false);
});
test("once snapshots are not timeouts and completed jobs still emit completion", async () => {
const snapshot = await watchSingleJob(client(), "job", { once: true });
expect(snapshot.timedOut).toBe(false);
expect(snapshot.events.some(e => e.type === "job_completed")).toBe(false);
const completed = await watchSingleJob(client("COMPLETED"), "job", { timeoutMs: 100 });
expect(completed.timedOut).toBe(false);
expect(completed.events.at(-1)?.type).toBe("job_completed");
});
test("cancellation is distinct from timeout and completion", async () => {
const controller = new AbortController(); controller.abort();
const c = client();
const result = await watchSingleJob(c, "job", { signal: controller.signal });
expect(result.cancelled).toBe(true); expect(result.timedOut).toBe(false);
expect(result.events.map(e => e.type)).toEqual(["cancelled"]);
expect(c.get).not.toHaveBeenCalled();
});
+5 -1
View File
@@ -9,7 +9,8 @@ export type WorkflowWatchEventType =
| "task_skipped"
| "job_completed"
| "idle"
| "timeout";
| "timeout"
| "cancelled";
export interface WorkflowWatchEvent {
type: WorkflowWatchEventType;
@@ -50,6 +51,8 @@ export interface WatchWorkflowOptions {
}
export interface WatchedJobResult {
timedOut?: boolean;
cancelled?: boolean;
jobId: string;
pipelineId: string;
status: string;
@@ -62,6 +65,7 @@ export interface WatchedJobResult {
}
export interface WorkflowWatchReport {
cancelled?: boolean;
pipelineId: string;
totalJobsWatched: number;
jobs: WatchedJobResult[];