Skip to content

Commit 01193de

Browse files
authored
fix: make task persistence failures explicit
Preserve task and TaskFlow durability by persisting before in-memory registry mutation and surfacing explicit persistence failures instead of reporting fake success. Adds non-throwing try-create runtime helpers while keeping existing throwing public create APIs compatible. Maintainer follow-up keeps task/TaskFlow sync repair bounded, prevents split task/delivery-state writes, and keeps CI green on the current base. Thanks @Feelw00.
1 parent cb98479 commit 01193de

41 files changed

Lines changed: 1685 additions & 309 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎extensions/codex/src/app-server/native-subagent-monitor.test.ts‎

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,8 +52,30 @@ function createRuntime() {
5252
error?: string;
5353
}>;
5454
};
55+
const createRunningTaskRun = vi.fn(
56+
(params): AgentHarnessTaskRecord => ({
57+
taskId: params.sourceId ?? params.runId,
58+
runtime: "subagent",
59+
sourceId: params.sourceId,
60+
requesterSessionKey: "agent:main:main",
61+
ownerKey: "agent:main:main",
62+
scopeKind: "session",
63+
agentId: params.agentId,
64+
runId: params.runId,
65+
label: params.label,
66+
task: params.task,
67+
status: "running",
68+
deliveryStatus: params.deliveryStatus ?? "not_applicable",
69+
notifyPolicy: params.notifyPolicy ?? "silent",
70+
createdAt: params.startedAt ?? Date.now(),
71+
startedAt: params.startedAt,
72+
lastEventAt: params.lastEventAt,
73+
progressSummary: params.progressSummary,
74+
}),
75+
);
5576
const taskRuntime = {
56-
createRunningTaskRun: vi.fn(),
77+
createRunningTaskRun,
78+
tryCreateRunningTaskRun: vi.fn((params) => createRunningTaskRun(params)),
5779
recordTaskRunProgressByRunId: vi.fn(() => []),
5880
finalizeTaskRunByRunId: vi.fn(() => []),
5981
listTaskRecords: vi.fn((): AgentHarnessTaskRecord[] => []),

‎extensions/codex/src/app-server/native-subagent-task-mirror.test.ts‎

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import {
77

88
function createRuntime() {
99
return {
10-
createRunningTaskRun: vi.fn(),
10+
tryCreateRunningTaskRun: vi.fn((params) => ({ taskId: "task-native-subagent", ...params })),
1111
recordTaskRunProgressByRunId: vi.fn(() => []),
1212
finalizeTaskRunByRunId: vi.fn(() => []),
1313
} as unknown as TaskLifecycleRuntime;
@@ -49,7 +49,7 @@ describe("CodexNativeSubagentTaskMirror", () => {
4949
},
5050
});
5151

52-
expect(runtime.createRunningTaskRun).toHaveBeenCalledWith({
52+
expect(runtime.tryCreateRunningTaskRun).toHaveBeenCalledWith({
5353
sourceId: "codex-thread:child-thread",
5454
agentId: "main",
5555
runId: "codex-thread:child-thread",
@@ -62,7 +62,7 @@ describe("CodexNativeSubagentTaskMirror", () => {
6262
lastEventAt: 20_000,
6363
progressSummary: "Codex native subagent started.",
6464
});
65-
expect(vi.mocked(runtime.createRunningTaskRun).mock.calls[0]?.[0]).not.toHaveProperty(
65+
expect(vi.mocked(runtime.tryCreateRunningTaskRun).mock.calls[0]?.[0]).not.toHaveProperty(
6666
"childSessionKey",
6767
);
6868
expect(runtime.recordTaskRunProgressByRunId).toHaveBeenCalledWith({
@@ -99,7 +99,7 @@ describe("CodexNativeSubagentTaskMirror", () => {
9999
},
100100
});
101101

102-
expect(runtime.createRunningTaskRun).not.toHaveBeenCalled();
102+
expect(runtime.tryCreateRunningTaskRun).not.toHaveBeenCalled();
103103
expect(runtime.recordTaskRunProgressByRunId).not.toHaveBeenCalled();
104104
expect(runtime.finalizeTaskRunByRunId).not.toHaveBeenCalled();
105105
});
@@ -133,7 +133,7 @@ describe("CodexNativeSubagentTaskMirror", () => {
133133
mirror.handleNotification(notification);
134134
mirror.handleNotification(notification);
135135

136-
expect(runtime.createRunningTaskRun).toHaveBeenCalledTimes(1);
136+
expect(runtime.tryCreateRunningTaskRun).toHaveBeenCalledTimes(1);
137137
});
138138

139139
it("maps Codex thread status changes onto the mirrored task run", () => {
@@ -228,7 +228,7 @@ describe("CodexNativeSubagentTaskMirror", () => {
228228
},
229229
});
230230

231-
expect(runtime.createRunningTaskRun).toHaveBeenCalledWith({
231+
expect(runtime.tryCreateRunningTaskRun).toHaveBeenCalledWith({
232232
sourceId: "codex-thread:child-thread",
233233
runId: "codex-thread:child-thread",
234234
label: "Codex subagent",
@@ -240,7 +240,7 @@ describe("CodexNativeSubagentTaskMirror", () => {
240240
lastEventAt: 40_000,
241241
progressSummary: "Codex native subagent spawned.",
242242
});
243-
expect(vi.mocked(runtime.createRunningTaskRun).mock.calls[0]?.[0]).not.toHaveProperty(
243+
expect(vi.mocked(runtime.tryCreateRunningTaskRun).mock.calls[0]?.[0]).not.toHaveProperty(
244244
"childSessionKey",
245245
);
246246
expect(runtime.recordTaskRunProgressByRunId).toHaveBeenCalledWith({
@@ -282,7 +282,7 @@ describe("CodexNativeSubagentTaskMirror", () => {
282282
},
283283
});
284284

285-
expect(runtime.createRunningTaskRun).toHaveBeenCalledWith(
285+
expect(runtime.tryCreateRunningTaskRun).toHaveBeenCalledWith(
286286
expect.objectContaining({
287287
runId: "codex-thread:child-thread",
288288
task: "inspect one thing",
@@ -319,7 +319,7 @@ describe("CodexNativeSubagentTaskMirror", () => {
319319
},
320320
});
321321

322-
expect(runtime.createRunningTaskRun).toHaveBeenCalledWith(
322+
expect(runtime.tryCreateRunningTaskRun).toHaveBeenCalledWith(
323323
expect.objectContaining({
324324
runId: "codex-thread:child-thread",
325325
task: "inspect one thing",

‎extensions/codex/src/app-server/native-subagent-task-mirror.ts‎

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ import { isJsonObject } from "./protocol.js";
1515

1616
export type TaskLifecycleRuntime = Pick<
1717
AgentHarnessTaskRuntime,
18-
"createRunningTaskRun" | "recordTaskRunProgressByRunId" | "finalizeTaskRunByRunId"
18+
"tryCreateRunningTaskRun" | "recordTaskRunProgressByRunId" | "finalizeTaskRunByRunId"
1919
>;
2020

2121
export type CodexNativeSubagentTaskMirrorParams = {
@@ -27,6 +27,7 @@ export type CodexNativeSubagentTaskMirrorParams = {
2727

2828
export class CodexNativeSubagentTaskMirror {
2929
private readonly mirroredThreadIds = new Set<string>();
30+
private readonly failedMirrorThreadIds = new Set<string>();
3031
private readonly terminalRunIds = new Set<string>();
3132
private readonly now: () => number;
3233

@@ -81,7 +82,7 @@ export class CodexNativeSubagentTaskMirror {
8182
trimOptional(thread.preview) ??
8283
`Codex native subagent${label === "Codex subagent" ? "" : ` ${label}`}`;
8384
const createdAt = secondsToMillis(thread.createdAt) ?? this.now();
84-
this.runtime.createRunningTaskRun({
85+
const taskRecord = this.runtime.tryCreateRunningTaskRun({
8586
sourceId: runId,
8687
agentId: this.params.agentId,
8788
runId,
@@ -94,6 +95,13 @@ export class CodexNativeSubagentTaskMirror {
9495
lastEventAt: this.now(),
9596
progressSummary: "Codex native subagent started.",
9697
});
98+
if (!taskRecord) {
99+
this.mirroredThreadIds.delete(threadId);
100+
this.failedMirrorThreadIds.add(threadId);
101+
return;
102+
}
103+
this.failedMirrorThreadIds.delete(threadId);
104+
this.terminalRunIds.delete(runId);
97105
this.applyStatus(threadId, thread.status);
98106
}
99107

@@ -106,6 +114,9 @@ export class CodexNativeSubagentTaskMirror {
106114
}
107115

108116
private applyStatus(threadId: string, status: CodexThreadStatus | null | undefined): void {
117+
if (!this.mirroredThreadIds.has(threadId) && this.failedMirrorThreadIds.has(threadId)) {
118+
return;
119+
}
109120
const statusType = status?.type;
110121
if (!statusType) {
111122
return;
@@ -219,7 +230,7 @@ export class CodexNativeSubagentTaskMirror {
219230
const prompt = trimOptional(readString(item, "prompt"));
220231
const runId = codexNativeSubagentRunId(normalizedThreadId);
221232
const createdAt = this.now();
222-
this.runtime.createRunningTaskRun({
233+
const taskRecord = this.runtime.tryCreateRunningTaskRun({
223234
sourceId: runId,
224235
agentId: this.params.agentId,
225236
runId,
@@ -232,13 +243,23 @@ export class CodexNativeSubagentTaskMirror {
232243
lastEventAt: createdAt,
233244
progressSummary: "Codex native subagent spawned.",
234245
});
246+
if (!taskRecord) {
247+
this.mirroredThreadIds.delete(normalizedThreadId);
248+
this.failedMirrorThreadIds.add(normalizedThreadId);
249+
return;
250+
}
251+
this.failedMirrorThreadIds.delete(normalizedThreadId);
252+
this.terminalRunIds.delete(runId);
235253
}
236254

237255
private applyCollabAgentStatus(
238256
threadId: string,
239257
status: string | undefined,
240258
message: string | null | undefined,
241259
): void {
260+
if (!this.mirroredThreadIds.has(threadId) && this.failedMirrorThreadIds.has(threadId)) {
261+
return;
262+
}
242263
const normalizedStatus = normalizeAgentStateStatus(status);
243264
if (!normalizedStatus) {
244265
return;

‎extensions/lobster/src/lobster-taskflow.ts‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ type BoundTaskFlow = ReturnType<
1515
NonNullable<OpenClawPluginApi["runtime"]>["tasks"]["managedFlows"]["bindSession"]
1616
>;
1717

18-
type FlowRecord = ReturnType<BoundTaskFlow["createManaged"]>;
18+
type FlowRecord = NonNullable<ReturnType<BoundTaskFlow["tryCreateManaged"]>>;
1919
type MutationResult = ReturnType<BoundTaskFlow["setWaiting"]>;
2020

2121
type LobsterApprovalWaitState = {
@@ -163,12 +163,21 @@ function buildEnvelopeError(envelope: Extract<LobsterEnvelope, { ok: false }>) {
163163
export async function runManagedLobsterFlow(
164164
params: RunManagedLobsterFlowParams,
165165
): Promise<ManagedLobsterFlowResult> {
166-
const flow = params.taskFlow.createManaged({
166+
const createFlowParams = {
167167
controllerId: params.controllerId,
168168
goal: params.goal,
169169
currentStep: params.currentStep ?? "run_lobster",
170170
...(params.stateJson !== undefined ? { stateJson: params.stateJson } : {}),
171-
});
171+
};
172+
const flow = params.taskFlow.tryCreateManaged
173+
? params.taskFlow.tryCreateManaged(createFlowParams)
174+
: params.taskFlow.createManaged(createFlowParams);
175+
if (!flow) {
176+
return {
177+
ok: false,
178+
error: new Error("TaskFlow persistence failed."),
179+
};
180+
}
172181

173182
try {
174183
const envelope = await params.runner.run(params.runnerParams);

‎extensions/lobster/src/taskflow-test-helpers.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,12 @@ export function createFakeTaskFlow(overrides?: Partial<BoundTaskFlow>): BoundTas
1515
status: "running" as const,
1616
goal: "Run Lobster workflow",
1717
};
18+
const createManaged = vi.fn().mockReturnValue(baseFlow);
1819

1920
return {
2021
sessionKey: "agent:main:main",
21-
createManaged: vi.fn().mockReturnValue(baseFlow),
22+
createManaged,
23+
tryCreateManaged: vi.fn((params) => createManaged(params)),
2224
get: vi.fn(),
2325
list: vi.fn().mockReturnValue([]),
2426
findLatest: vi.fn(),

‎extensions/webhooks/src/http.test.ts‎

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,20 @@ import { afterEach, describe, expect, it, vi } from "vitest";
66
import type { OpenClawConfig } from "../runtime-api.js";
77
import { createTaskFlowWebhookRequestHandler, type TaskFlowWebhookTarget } from "./http.js";
88

9+
type BoundTaskFlow = TaskFlowWebhookTarget["taskFlow"];
10+
type ManagedFlow = NonNullable<ReturnType<BoundTaskFlow["createManaged"]>>;
11+
12+
function createManagedFlow(
13+
target: TaskFlowWebhookTarget,
14+
params: Parameters<BoundTaskFlow["createManaged"]>[0],
15+
): ManagedFlow {
16+
const flow = target.taskFlow.createManaged(params);
17+
if (!flow) {
18+
throw new Error("expected managed TaskFlow creation to succeed");
19+
}
20+
return flow;
21+
}
22+
923
const hoisted = vi.hoisted(() => {
1024
const resolveConfiguredSecretInputStringMock = vi.fn();
1125
return {
@@ -220,7 +234,7 @@ describe("createTaskFlowWebhookRequestHandler", () => {
220234

221235
it("runs child tasks and scrubs task ownership fields from responses", async () => {
222236
const { handler, target, secret } = createHandler();
223-
const flow = target.taskFlow.createManaged({
237+
const flow = createManagedFlow(target, {
224238
controllerId: "webhooks/zapier",
225239
goal: "Triage inbox",
226240
});
@@ -275,7 +289,7 @@ describe("createTaskFlowWebhookRequestHandler", () => {
275289

276290
it("returns 409 for revision conflicts", async () => {
277291
const { handler, target, secret } = createHandler();
278-
const flow = target.taskFlow.createManaged({
292+
const flow = createManagedFlow(target, {
279293
controllerId: "webhooks/zapier",
280294
goal: "Review inbox",
281295
});
@@ -302,7 +316,7 @@ describe("createTaskFlowWebhookRequestHandler", () => {
302316

303317
it("rejects internal runtimes and running-only metadata from external callers", async () => {
304318
const { handler, target, secret } = createHandler();
305-
const flow = target.taskFlow.createManaged({
319+
const flow = createManagedFlow(target, {
306320
controllerId: "webhooks/zapier",
307321
goal: "Review inbox",
308322
});
@@ -346,7 +360,7 @@ describe("createTaskFlowWebhookRequestHandler", () => {
346360

347361
it("reuses the same task record when retried with the same runId", async () => {
348362
const { handler, target, secret } = createHandler();
349-
const flow = target.taskFlow.createManaged({
363+
const flow = createManagedFlow(target, {
350364
controllerId: "webhooks/zapier",
351365
goal: "Triage inbox",
352366
});
@@ -388,7 +402,7 @@ describe("createTaskFlowWebhookRequestHandler", () => {
388402

389403
it("returns 409 when cancellation targets a terminal flow", async () => {
390404
const { handler, target, secret } = createHandler();
391-
const flow = target.taskFlow.createManaged({
405+
const flow = createManagedFlow(target, {
392406
controllerId: "webhooks/zapier",
393407
goal: "Review inbox",
394408
});

0 commit comments

Comments
 (0)