Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix(agent-runtime): run the stale-operation sweep without a scheduler (#20291)

Arvin Xub4455393b6be
diff --git a/apps/server/src/router-hono/agent/handlers/__tests__/runStep.test.ts b/apps/server/src/router-hono/agent/handlers/__tests__/runStep.test.ts
index d514ea9492b..4c3f7e4dcc2 100644
--- a/apps/server/src/router-hono/agent/handlers/__tests__/runStep.test.ts
+++ b/apps/server/src/router-hono/agent/handlers/__tests__/runStep.test.ts
@@ -18,6 +18,7 @@ const mockGetServerDB = vi.hoisted(() => vi.fn());
const mockFinalizeAbandoned = vi.hoisted(() => vi.fn());
const mockSettleStaleRunning = vi.hoisted(() => vi.fn());
const mockResumeAbandonedParent = vi.hoisted(() => vi.fn());
+const mockScheduleOpportunisticStaleSweep = vi.hoisted(() => vi.fn());
// Lets a test force the step-boundary flush to report a timeout; undefined
// means use the real implementation.
const flushOverride = vi.hoisted(() => ({ settled: undefined as boolean | undefined }));
@@ -58,6 +59,7 @@ vi.mock('@/server/services/agentRuntime', () => ({
AbandonOperationService: vi.fn().mockImplementation(function () {
return { finalizeAbandoned: mockFinalizeAbandoned };
}),
+ scheduleOpportunisticStaleSweep: mockScheduleOpportunisticStaleSweep,
}));
vi.mock('@/database/core/db-adaptor', () => ({
@@ -354,6 +356,21 @@ describe('runStep handler', () => {
expect(deadlineSeen).toBeLessThanOrEqual(Date.now() + 600_000);
});
+ it('kicks the opportunistic stale-operation sweep on a valid delivery', async () => {
+ mockGetOperationMetadata.mockResolvedValue({ userId: 'user-1' });
+ mockExecuteStep.mockResolvedValue({
+ nextStepScheduled: false,
+ state: { cost: { total: 0 }, status: 'done', stepCount: 1 },
+ success: true,
+ });
+
+ const { ctx } = buildContext({ body: validBody });
+ const res = await runStep(ctx);
+
+ expect(res.status).toBe(200);
+ expect(mockScheduleOpportunisticStaleSweep).toHaveBeenCalledTimes(1);
+ });
+
it('opts the AiAgentService into visitor rows when metadata carries streamOwnerUserId', async () => {
// A shared-agent visitor run: the op executes as the creator `userId`
// (`user-owner`) but the visitor (`visitor-1`) owns the stream. The step
diff --git a/apps/server/src/router-hono/agent/handlers/runStep.ts b/apps/server/src/router-hono/agent/handlers/runStep.ts
index edd786207bb..cbd2a50ef9f 100644
--- a/apps/server/src/router-hono/agent/handlers/runStep.ts
+++ b/apps/server/src/router-hono/agent/handlers/runStep.ts
@@ -10,6 +10,7 @@ import {
AbandonOperationService,
type AgentExecutionResult,
type AgentStepContinuation,
+ scheduleOpportunisticStaleSweep,
} from '@/server/services/agentRuntime';
import { AiAgentService } from '@/server/services/aiAgent';
import { runWithInvocationDeadline } from '@/server/utils/invocationDeadline';
@@ -113,8 +114,13 @@ async function getOperationRowDiagnostic(operationId: string) {
/**
* How long a `running` row may go without a lease refresh before a delivery
* that finds no coordinator metadata treats the run as dead. A live step
- * refreshes the lease every 90s (see `touchRunning`), and this matches the
- * agent-gateway idle watchdog window.
+ * refreshes the lease every 90s (see `touchRunning`).
+ *
+ * This is NOT the gateway's inactivity window and does not track it: the
+ * gateway judges silence in the *event stream* (30 min, see
+ * `INACTIVITY_WATCHDOG_TIMEOUT`), while this judges the outright absence of the
+ * coordinator metadata every step needs. Missing metadata is far stronger
+ * evidence than a quiet stream, so this stays far shorter than that window.
*/
const ORPHANED_RUNNING_LEASE_MS = 10 * 60 * 1000;
@@ -220,6 +226,14 @@ export async function runStep(c: Context): Promise<Response> {
log(`[${operationId}] Starting step ${stepIndex}`);
+ // Ride the always-exercised step path to run the stale-operation sweep, at
+ // most once a minute cluster-wide. The sweep's only other entry point is a
+ // Vercel cron this deployment does not schedule, so without this a run
+ // whose next step never dispatched is left to the gateway's destructive
+ // inactivity watchdog. Fire-and-forget: it is background repair and must
+ // not add latency to, or fail, this delivery.
+ scheduleOpportunisticStaleSweep();
+
// Get userId from operation metadata stored in Redis
const coordinator = new AgentRuntimeCoordinator();
const metadata = await coordinator.getOperationMetadata(operationId);
diff --git a/apps/server/src/services/agentRuntime/__tests__/opportunisticSweep.test.ts b/apps/server/src/services/agentRuntime/__tests__/opportunisticSweep.test.ts
new file mode 100644
index 00000000000..486d5525123
--- /dev/null
+++ b/apps/server/src/services/agentRuntime/__tests__/opportunisticSweep.test.ts
@@ -0,0 +1,153 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ OPPORTUNISTIC_SWEEP_INTERVAL_MS,
+ OPPORTUNISTIC_SWEEP_SLOT_KEY,
+ runOpportunisticSweep,
+ scheduleOpportunisticStaleSweep,
+} from '../opportunisticSweep';
+
+const sweepMock = vi.fn().mockResolvedValue({ abandoned: 0, redriven: 1 });
+vi.mock('../StaleOperationReaper', () => ({
+ StaleOperationReaper: vi.fn().mockImplementation(function () {
+ return { sweep: sweepMock };
+ }),
+}));
+
+const getServerDBMock = vi.fn().mockResolvedValue({ db: 'server' });
+vi.mock('@/database/core/db-adaptor', () => ({
+ getServerDB: (...args: any[]) => getServerDBMock(...args),
+}));
+
+const redisSetMock = vi.fn().mockResolvedValue('OK');
+let redisClient: { set: typeof redisSetMock } | null = { set: redisSetMock };
+vi.mock('@/server/modules/AgentRuntime/redis', () => ({
+ getAgentRuntimeRedisClient: () => redisClient,
+}));
+
+/** Captured `after()` callbacks, so a test can choose when (and whether) to run them. */
+const afterQueue: Array<() => Promise<unknown>> = [];
+vi.mock('@/server/utils/scheduleAfterResponse', () => ({
+ after: (work: () => Promise<unknown>) => {
+ afterQueue.push(work);
+ },
+}));
+
+describe('runOpportunisticSweep', () => {
+ beforeEach(() => {
+ sweepMock.mockReset().mockResolvedValue({ abandoned: 0, redriven: 1 });
+ });
+
+ it('sweeps when it wins the slot', async () => {
+ const onError = vi.fn();
+ const swept = await runOpportunisticSweep({
+ claim: async () => true,
+ onError,
+ sweep: sweepMock,
+ });
+
+ expect(swept).toBe(true);
+ expect(sweepMock).toHaveBeenCalledTimes(1);
+ expect(onError).not.toHaveBeenCalled();
+ });
+
+ it('does not sweep when another caller holds the slot', async () => {
+ const swept = await runOpportunisticSweep({ claim: async () => false, sweep: sweepMock });
+
+ expect(swept).toBe(false);
+ expect(sweepMock).not.toHaveBeenCalled();
+ });
+
+ it('swallows a claim failure instead of failing the delivery that carried it', async () => {
+ const onError = vi.fn();
+ const swept = await runOpportunisticSweep({
+ claim: async () => {
+ throw new Error('redis down');
+ },
+ onError,
+ sweep: sweepMock,
+ });
+
+ expect(swept).toBe(false);
+ expect(sweepMock).not.toHaveBeenCalled();
+ expect(onError).toHaveBeenCalledWith(expect.any(Error), 'claim');
+ });
+
+ it('keeps the claim consumed when the sweep itself throws', async () => {
+ // The slot must not be handed back: a sweep that failed once would then be
+ // retried on every following step delivery, in a hot loop.
+ const onError = vi.fn();
+ sweepMock.mockRejectedValueOnce(new Error('pg down'));
+
+ const swept = await runOpportunisticSweep({
+ claim: async () => true,
+ onError,
+ sweep: sweepMock,
+ });
+
+ expect(swept).toBe(true);
+ expect(onError).toHaveBeenCalledWith(expect.any(Error), 'sweep');
+ });
+});
+
+describe('scheduleOpportunisticStaleSweep', () => {
+ beforeEach(() => {
+ afterQueue.length = 0;
+ sweepMock.mockReset().mockResolvedValue({ abandoned: 0, redriven: 1 });
+ redisSetMock.mockReset().mockResolvedValue('OK');
+ redisClient = { set: redisSetMock };
+ });
+
+ const flush = async () => {
+ const pending = [...afterQueue];
+ afterQueue.length = 0;
+ await Promise.all(pending.map((work) => work()));
+ };
+
+ it('does not claim or sweep when the runtime has no Redis', async () => {
+ redisClient = null;
+
+ scheduleOpportunisticStaleSweep();
+ await flush();
+
+ expect(redisSetMock).not.toHaveBeenCalled();
+ expect(sweepMock).not.toHaveBeenCalled();
+ });
+
+ it('claims one slot per interval and sweeps the stale operations', async () => {
+ scheduleOpportunisticStaleSweep();
+ await flush();
+
+ expect(redisSetMock).toHaveBeenCalledWith(
+ OPPORTUNISTIC_SWEEP_SLOT_KEY,
+ expect.any(String),
+ 'PX',
+ OPPORTUNISTIC_SWEEP_INTERVAL_MS,
+ 'NX',
+ );
+ expect(getServerDBMock).toHaveBeenCalled();
+ expect(sweepMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('skips the sweep while the slot TTL is still held', async () => {
+ // A step path is hot: without the slot every delivery would sweep.
+ redisSetMock.mockResolvedValue(null);
+
+ scheduleOpportunisticStaleSweep();
+ scheduleOpportunisticStaleSweep();
+ await flush();
+
+ expect(redisSetMock).toHaveBeenCalledTimes(2);
+ expect(sweepMock).not.toHaveBeenCalled();
+ });
+
+ it('never rejects, so a hosting delivery is unaffected', async () => {
+ redisSetMock.mockRejectedValue(new Error('redis down'));
+
+ scheduleOpportunisticStaleSweep();
+
+ await expect(flush()).resolves.toBeUndefined();
+ expect(sweepMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/services/agentRuntime/index.ts b/apps/server/src/services/agentRuntime/index.ts
index f53935f86b5..f9f8c442e5b 100644
--- a/apps/server/src/services/agentRuntime/index.ts
+++ b/apps/server/src/services/agentRuntime/index.ts
@@ -1,5 +1,6 @@
export * from './AbandonOperationService';
export * from './AgentRuntimeService';
export * from './foregroundOperation';
+export * from './opportunisticSweep';
export * from './StaleOperationReaper';
export * from './types';
diff --git a/apps/server/src/services/agentRuntime/opportunisticSweep.ts b/apps/server/src/services/agentRuntime/opportunisticSweep.ts
new file mode 100644
index 00000000000..87e492bf0a6
--- /dev/null
+++ b/apps/server/src/services/agentRuntime/opportunisticSweep.ts
@@ -0,0 +1,128 @@
+import debug from 'debug';
+
+import { getServerDB } from '@/database/core/db-adaptor';
+import { getAgentRuntimeRedisClient } from '@/server/modules/AgentRuntime/redis';
+import { after } from '@/server/utils/scheduleAfterResponse';
+
+import { StaleOperationReaper } from './StaleOperationReaper';
+
+const log = debug('lobe-server:agent-runtime:opportunistic-sweep');
+
+/**
+ * Minimum spacing between two opportunistic sweeps, cluster-wide.
+ *
+ * One minute is the granularity the recovery needs: the reaper only considers a
+ * run whose durable lease has been quiet for five minutes, and the gateway's
+ * inactivity watchdog (the destructive path this exists to beat) waits thirty.
+ */
+export const OPPORTUNISTIC_SWEEP_INTERVAL_MS = 60_000;
+
+/**
+ * The Redis slot that decides which caller sweeps. Claimed with
+ * `SET key … PX <interval> NX`: whoever sets it wins exactly one sweep, and no
+ * other caller β€” another instance, another request, another inlined step β€” can
+ * claim again until the TTL expires.
+ */
+export const OPPORTUNISTIC_SWEEP_SLOT_KEY = 'agent_runtime:stale_sweep:slot';
+
+export interface OpportunisticSweepDeps {
+ /** Resolves true for exactly one caller per interval, cluster-wide. */
+ claim: () => Promise<boolean>;
+ onError?: (error: unknown, phase: 'claim' | 'sweep') => void;
+ sweep: () => Promise<unknown>;
+}
+
+/**
+ * Run the stale-operation sweep at most once per interval, best-effort.
+ *
+ * Returns whether this caller won the slot, and therefore swept.
+ *
+ * Never throws: this is background repair riding on someone else's request, so
+ * a sweep that fails (Redis blip, a poisoned row) must not surface as a failure
+ * of the delivery that carried it, and a slot it failed to claim must not
+ * either. `StaleOperationReaper.sweep` already isolates per-candidate failures;
+ * this handles the failures outside that loop.
+ */
+export async function runOpportunisticSweep({
+ claim,
+ sweep,
+ onError,
+}: OpportunisticSweepDeps): Promise<boolean> {
+ let claimed: boolean;
+ try {
+ claimed = await claim();
+ } catch (error) {
+ onError?.(error, 'claim');
+ return false;
+ }
+
+ if (!claimed) return false;
+
+ try {
+ await sweep();
+ } catch (error) {
+ onError?.(error, 'sweep');
+ }
+
+ return true;
+}
+
+/**
+ * Recover operations whose executing host died mid-step, without depending on a
+ * scheduler being configured.
+ *
+ * `StaleOperationReaper` is the correct recovery for a run whose next step
+ * never ran. It is deliberately conservative: it holds no authority over a run
+ * it cannot resume, it prefers re-queueing the next step from Redis state over
+ * reporting a death, and it only abandons once its redrive budget is spent.
+ *
+ * Its only entry point is the Vercel cron `/api/agent/reap-operations`, and the
+ * project that deploys this server has **no `crons` entry** for that route β€” so
+ * in production the sweep exists but is never invoked. That is not a cosmetic
+ * gap. A run whose step-to-step handoff dies leaves its durable row `running`
+ * with a frozen lease; nothing redrives it, and the only thing that eventually
+ * notices is the gateway's *destructive* inactivity watchdog, which rewrites
+ * the turn as `Operation abandoned: inactivity_watchdog` and finalizes the
+ * trace as a failure. Observed 2026-10-02, one user in one afternoon:
+ *
+ * - four such runs, every one of them ending on a step that had asked for a
+ * device `runCommand` (waiting on CI) β€” the largest was 94 minutes and 521
+ * steps, and the watchdog killed it mid-task;
+ * - the same topic was killed twice, hours apart.
+ *
+ * So run the same sweep from a path that is always exercised β€” the agent step
+ * delivery β€” at most once per interval, cluster-wide.
+ *
+ * Deliberately not awaited by the caller. This must never add latency to, or
+ * fail, a step delivery; that is also why it does not join the step loop's
+ * `runWithScheduledWorkScope` (whose boundary flush would then wait on it).
+ */
+export const scheduleOpportunisticStaleSweep = (): void => {
+ const redis = getAgentRuntimeRedisClient();
+ if (!redis) return;
+
+ after(() =>
+ runOpportunisticSweep({
+ claim: async () => {
+ const claimed = await redis.set(
+ OPPORTUNISTIC_SWEEP_SLOT_KEY,
+ String(Date.now()),
+ 'PX',
+ OPPORTUNISTIC_SWEEP_INTERVAL_MS,
+ 'NX',
+ );
+
+ return claimed === 'OK';
+ },
+ onError: (error, phase) => {
+ // A failed tick is invisible by design (the delivery that hosted it
+ // succeeded), so log it loudly enough to be found from the timeline.
+ console.error(`[opportunistic-sweep] ${phase} failed: %O`, error);
+ },
+ sweep: async () => {
+ const result = await new StaleOperationReaper(await getServerDB()).sweep();
+ log('sweep: %O', result);
+ },
+ }),
+ );
+};