Skip to content

Commit 4bb2e0d

Browse files
committed
fix(agents): count runtime acquisition as lane progress and stop retrying terminal auth-migration reviews
1 parent 7e08953 commit 4bb2e0d

6 files changed

Lines changed: 204 additions & 20 deletions

File tree

‎src/agents/embedded-agent-runner/run-orchestrator.ts‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ import type {
6060
RunEmbeddedAgentParamsWithSessionFile,
6161
} from "./run/internal-params.js";
6262
import { createEmbeddedRunLaneController } from "./run/lane-controller.js";
63+
import { withEmbeddedRunLaneProgressHeartbeat } from "./run/lane-runtime.js";
6364
import type { RunEmbeddedAgentParams } from "./run/params.js";
6465
import { bindRunToPreparedModelRuntime } from "./run/prepared-runtime-context.js";
6566
import { createEmbeddedRunProgressController } from "./run/progress-controller.js";
@@ -213,10 +214,15 @@ async function runEmbeddedAgentInternal(
213214
};
214215
// Configless direct hosts reuse one bounded idle generation. Gateway and explicitly
215216
// configured runs release dynamic workspaces so one-off paths cannot accumulate owners.
216-
const preparedModelRuntimeLease =
217-
params.preparedModelRuntimeMode === "isolated-read-only"
218-
? await acquireReadOnlyPreparedModelRuntime(preparedInput)
219-
: await acquireAgentRunPreparedModelRuntime(preparedInput, { retainIdleRunOwner });
217+
// Cold plugin loading and provider discovery can exceed the lane no-progress budget.
218+
// Active runtime acquisition is progress, not a hung lane task.
219+
const preparedModelRuntimeLease = await withEmbeddedRunLaneProgressHeartbeat(
220+
noteLaneTaskProgress,
221+
() =>
222+
params.preparedModelRuntimeMode === "isolated-read-only"
223+
? acquireReadOnlyPreparedModelRuntime(preparedInput)
224+
: acquireAgentRunPreparedModelRuntime(preparedInput, { retainIdleRunOwner }),
225+
);
220226
const preparedModelRuntimeOwnerSnapshot = preparedModelRuntimeLease.snapshot;
221227
try {
222228
// A reload may complete while admission waits. The committed generation owns config,

‎src/agents/embedded-agent-runner/run/lane-runtime.test.ts‎

Lines changed: 91 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,19 @@
1-
import { afterEach, describe, expect, it } from "vitest";
1+
import { afterEach, describe, expect, it, vi } from "vitest";
22
import { enqueueCommandInLane, setCommandLaneConcurrency } from "../../../process/command-queue.js";
33
import { resetCommandQueueStateForTest } from "../../../process/command-queue.test-support.js";
44
import { MAIN_SESSION_RESTART_RECOVERY_SOURCE_TOOL } from "../../../sessions/input-provenance.js";
5-
import { resolveEmbeddedRunSessionQueuePriority } from "./lane-runtime.js";
5+
import {
6+
EMBEDDED_RUN_LANE_HEARTBEAT_MS,
7+
resolveEmbeddedRunSessionQueuePriority,
8+
withEmbeddedRunLaneProgressHeartbeat,
9+
} from "./lane-runtime.js";
610

7-
describe("embedded run lane priority", () => {
8-
afterEach(() => {
9-
resetCommandQueueStateForTest();
10-
});
11+
afterEach(() => {
12+
vi.useRealTimers();
13+
resetCommandQueueStateForTest();
14+
});
1115

16+
describe("embedded run lane priority", () => {
1217
it("runs a foreground user turn before queued restart recovery", async () => {
1318
const lane = "test:restart-recovery-priority";
1419
setCommandLaneConcurrency(lane, 1);
@@ -46,3 +51,83 @@ describe("embedded run lane priority", () => {
4651
expect(order).toEqual(["foreground-user", "restart-recovery"]);
4752
});
4853
});
54+
55+
describe("embedded run lane progress heartbeat", () => {
56+
it("notes progress immediately and at the heartbeat cadence", async () => {
57+
vi.useFakeTimers();
58+
const noteLaneTaskProgress = vi.fn();
59+
let finish: ((value: string) => void) | undefined;
60+
const task = withEmbeddedRunLaneProgressHeartbeat(
61+
noteLaneTaskProgress,
62+
() =>
63+
new Promise<string>((resolve) => {
64+
finish = resolve;
65+
}),
66+
);
67+
68+
expect(noteLaneTaskProgress).toHaveBeenCalledTimes(1);
69+
await vi.advanceTimersByTimeAsync(EMBEDDED_RUN_LANE_HEARTBEAT_MS - 1);
70+
expect(noteLaneTaskProgress).toHaveBeenCalledTimes(1);
71+
await vi.advanceTimersByTimeAsync(EMBEDDED_RUN_LANE_HEARTBEAT_MS * 2 + 1);
72+
expect(noteLaneTaskProgress).toHaveBeenCalledTimes(4);
73+
74+
finish?.("done");
75+
await expect(task).resolves.toBe("done");
76+
expect(noteLaneTaskProgress).toHaveBeenCalledTimes(5);
77+
78+
await vi.advanceTimersByTimeAsync(EMBEDDED_RUN_LANE_HEARTBEAT_MS * 2);
79+
expect(noteLaneTaskProgress).toHaveBeenCalledTimes(5);
80+
});
81+
82+
it("clears the heartbeat after rejection and propagates the error", async () => {
83+
vi.useFakeTimers();
84+
const noteLaneTaskProgress = vi.fn();
85+
const expectedError = new Error("runtime acquisition failed");
86+
let fail: ((error: Error) => void) | undefined;
87+
const task = withEmbeddedRunLaneProgressHeartbeat(
88+
noteLaneTaskProgress,
89+
() =>
90+
new Promise<never>((_resolve, reject) => {
91+
fail = reject;
92+
}),
93+
);
94+
95+
await vi.advanceTimersByTimeAsync(EMBEDDED_RUN_LANE_HEARTBEAT_MS);
96+
expect(noteLaneTaskProgress).toHaveBeenCalledTimes(2);
97+
fail?.(expectedError);
98+
await expect(task).rejects.toBe(expectedError);
99+
expect(noteLaneTaskProgress).toHaveBeenCalledTimes(3);
100+
101+
await vi.advanceTimersByTimeAsync(EMBEDDED_RUN_LANE_HEARTBEAT_MS * 2);
102+
expect(noteLaneTaskProgress).toHaveBeenCalledTimes(3);
103+
});
104+
105+
it("keeps a slow lane task alive while runtime acquisition makes progress", async () => {
106+
vi.useFakeTimers();
107+
vi.setSystemTime(new Date("2026-07-29T00:00:00.000Z"));
108+
const lane = `test:embedded-run-runtime-heartbeat:${Date.now()}`;
109+
setCommandLaneConcurrency(lane, 1);
110+
let progressAtMs = Date.now();
111+
112+
const task = enqueueCommandInLane(
113+
lane,
114+
() =>
115+
withEmbeddedRunLaneProgressHeartbeat(
116+
() => {
117+
progressAtMs = Date.now();
118+
},
119+
() =>
120+
new Promise<string>((resolve) => {
121+
setTimeout(() => resolve("completed"), 52_000);
122+
}),
123+
),
124+
{
125+
taskTimeoutMs: 25_000,
126+
taskTimeoutProgressAtMs: () => progressAtMs,
127+
},
128+
);
129+
130+
await vi.advanceTimersByTimeAsync(52_000);
131+
await expect(task).resolves.toBe("completed");
132+
});
133+
});

‎src/agents/embedded-agent-runner/run/lane-runtime.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,21 @@ import type { RunEmbeddedAgentParams } from "./params.js";
1010
export const EMBEDDED_RUN_LANE_TIMEOUT_GRACE_MS = 30_000;
1111
export const EMBEDDED_RUN_LANE_HEARTBEAT_MS = EMBEDDED_RUN_LANE_TIMEOUT_GRACE_MS / 2;
1212

13+
export async function withEmbeddedRunLaneProgressHeartbeat<T>(
14+
noteLaneTaskProgress: () => void,
15+
fn: () => Promise<T>,
16+
): Promise<T> {
17+
noteLaneTaskProgress();
18+
const progressInterval = setInterval(noteLaneTaskProgress, EMBEDDED_RUN_LANE_HEARTBEAT_MS);
19+
progressInterval.unref?.();
20+
try {
21+
return await fn();
22+
} finally {
23+
clearInterval(progressInterval);
24+
noteLaneTaskProgress();
25+
}
26+
}
27+
1328
export function resolveEmbeddedRunLaneTimeoutMs(timeoutMs: number): number {
1429
const defaultLaneTimeoutMs = DEFAULT_AGENT_TIMEOUT_MS + EMBEDDED_RUN_LANE_TIMEOUT_GRACE_MS;
1530
// "No timeout" resolves to the timer-safe MAX_TIMER sentinel upstream.

‎src/agents/embedded-agent-runner/run/settled-turn-finalization.ts‎

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import {
1010
mergeUsageIntoAccumulator,
1111
} from "../usage-accumulator.js";
1212
import { runEmbeddedSettledTurnFinalizationWithBackend } from "./backend.js";
13-
import { EMBEDDED_RUN_LANE_HEARTBEAT_MS } from "./lane-runtime.js";
13+
import { withEmbeddedRunLaneProgressHeartbeat } from "./lane-runtime.js";
1414
import {
1515
resolveEmbeddedRunAttemptTerminalOutcome,
1616
type EmbeddedRunTerminalState,
@@ -167,10 +167,7 @@ async function runPreparedSettledTurnFinalization(input: {
167167
prompt: string;
168168
noteLaneTaskProgress: () => void;
169169
}): Promise<EmbeddedRunAttemptResult> {
170-
input.noteLaneTaskProgress();
171-
const progressInterval = setInterval(input.noteLaneTaskProgress, EMBEDDED_RUN_LANE_HEARTBEAT_MS);
172-
progressInterval.unref?.();
173-
try {
170+
return await withEmbeddedRunLaneProgressHeartbeat(input.noteLaneTaskProgress, async () => {
174171
const result = await runEmbeddedSettledTurnFinalizationWithBackend(
175172
{
176173
...input.attempt,
@@ -189,10 +186,7 @@ async function runPreparedSettledTurnFinalization(input: {
189186
prompt: input.prompt,
190187
agentHarnessId: input.attempt.agentHarnessId,
191188
});
192-
} finally {
193-
clearInterval(progressInterval);
194-
input.noteLaneTaskProgress();
195-
}
189+
});
196190
}
197191

198192
function buildSettledTurnFinalizationAttemptResult(input: {

‎src/skills/workshop/experience-review.test.ts‎

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,13 @@ function completedRun(
7272
};
7373
}
7474

75+
async function flushMicrotasks(): Promise<void> {
76+
await Promise.resolve();
77+
await Promise.resolve();
78+
await Promise.resolve();
79+
await Promise.resolve();
80+
}
81+
7582
afterEach(() => {
7683
vi.useRealTimers();
7784
});
@@ -368,6 +375,65 @@ describe("skill experience review scheduler", () => {
368375
scheduler.clear();
369376
});
370377

378+
it("drops terminal auth-migration failures without re-arming", async () => {
379+
const callbacks: Array<() => void> = [];
380+
const setTimer = vi.fn((callback: () => void) => {
381+
callbacks.push(callback);
382+
return { unref: vi.fn() } as unknown as ReturnType<typeof setTimeout>;
383+
});
384+
const clearTimer = vi.fn();
385+
const runReview = vi.fn().mockRejectedValue(
386+
Object.assign(new Error("Auth migration required; run openclaw doctor --fix."), {
387+
code: "AUTH_PROFILE_MIGRATION_REQUIRED" as const,
388+
}),
389+
);
390+
const scheduler = createSkillExperienceReviewScheduler({
391+
isSystemActive: () => false,
392+
runReview,
393+
setTimer,
394+
clearTimer,
395+
});
396+
397+
scheduler.schedule(completedRun());
398+
callbacks[0]?.();
399+
await flushMicrotasks();
400+
401+
expect(runReview).toHaveBeenCalledTimes(1);
402+
expect(setTimer).toHaveBeenCalledTimes(1);
403+
expect(clearTimer).not.toHaveBeenCalled();
404+
405+
scheduler.schedule(completedRun());
406+
expect(setTimer).toHaveBeenCalledTimes(2);
407+
expect(clearTimer).not.toHaveBeenCalled();
408+
scheduler.clear();
409+
});
410+
411+
it("re-arms after a generic review failure", async () => {
412+
const callbacks: Array<() => void> = [];
413+
const setTimer = vi.fn((callback: () => void, _delayMs: number) => {
414+
callbacks.push(callback);
415+
return { unref: vi.fn() } as unknown as ReturnType<typeof setTimeout>;
416+
});
417+
const clearTimer = vi.fn();
418+
const runReview = vi.fn().mockRejectedValue(new Error("provider unavailable"));
419+
const scheduler = createSkillExperienceReviewScheduler({
420+
isSystemActive: () => false,
421+
runReview,
422+
setTimer,
423+
clearTimer,
424+
});
425+
426+
scheduler.schedule(completedRun());
427+
callbacks[0]?.();
428+
await flushMicrotasks();
429+
430+
expect(runReview).toHaveBeenCalledTimes(1);
431+
expect(setTimer).toHaveBeenCalledTimes(2);
432+
expect(setTimer).toHaveBeenLastCalledWith(expect.any(Function), 30_000);
433+
expect(clearTimer).not.toHaveBeenCalled();
434+
scheduler.clear();
435+
});
436+
371437
it("serializes reviews across sessions", async () => {
372438
vi.useFakeTimers();
373439
let finishFirst: (() => void) | undefined;

‎src/skills/workshop/experience-review.ts‎

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,16 @@ type PendingExperienceReview = {
9999
timer?: ExperienceReviewTimer;
100100
};
101101

102+
function isAuthProfileMigrationRequiredError(
103+
error: unknown,
104+
): error is { code: "AUTH_PROFILE_MIGRATION_REQUIRED" } {
105+
return (
106+
typeof error === "object" &&
107+
error !== null &&
108+
(error as { code?: unknown }).code === "AUTH_PROFILE_MIGRATION_REQUIRED"
109+
);
110+
}
111+
102112
function isEligibleContext(ctx: ExperienceReviewAgentContext): boolean {
103113
// Only harnesses that report both the resolved model and actual host-side
104114
// Workshop availability may schedule. Other runtimes fail closed here.
@@ -254,14 +264,22 @@ export function createSkillExperienceReviewScheduler(deps: ExperienceReviewSched
254264
if (pendingBySession.get(sessionKey) !== pending || pending.generation !== generation) {
255265
return;
256266
}
257-
pendingBySession.delete(sessionKey);
258267
await deps.runReview(candidate);
268+
if (pendingBySession.get(sessionKey) === pending && pending.generation === generation) {
269+
pendingBySession.delete(sessionKey);
270+
}
259271
} finally {
260272
reviewInFlight = false;
261273
}
262274
})
263275
.catch((error: unknown) => {
264276
log.warn(`skill experience review failed: ${String(error)}`);
277+
if (isAuthProfileMigrationRequiredError(error)) {
278+
if (pendingBySession.get(sessionKey) === pending && pending.generation === generation) {
279+
pendingBySession.delete(sessionKey);
280+
}
281+
return;
282+
}
265283
if (pendingBySession.get(sessionKey) === pending && pending.generation === generation) {
266284
arm(sessionKey, pending, EXPERIENCE_REVIEW_RETRY_IDLE_MS);
267285
}

0 commit comments

Comments
 (0)