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.

17.7 KB
Raw Blame
// @vitest-environment node
import type { SQL } from 'drizzle-orm';
import { PgDialect } from 'drizzle-orm/pg-core';
import { beforeEach, describe, expect, it, vi } from 'vitest';

import { StaleOperationReaper } from '../StaleOperationReaper';

const claimStaleRedriveMock = vi.fn();
const settleStaleRunningMock = vi.fn();
const releaseStaleRedriveMock = vi.fn();
vi.mock('@/database/models/agentOperation', () => ({
  AgentOperationModel: vi.fn().mockImplementation(function () {
    return {
      claimStaleRedrive: claimStaleRedriveMock,
      releaseStaleRedrive: releaseStaleRedriveMock,
      settleStaleRunning: settleStaleRunningMock,
    };
  }),
}));

const finalizeAbandonedMock = vi.fn().mockResolvedValue({});
vi.mock('../AbandonOperationService', () => ({
  AbandonOperationService: vi.fn().mockImplementation(function () {
    return { finalizeAbandoned: finalizeAbandonedMock };
  }),
}));

/**
 * Minimal drizzle select chains: the stale-candidate query (`orderBy`) returns
 * `rows`, the concurrent-foreground patrol (`groupBy`) returns `overlapRows`.
 * Every WHERE condition is kept so a test can read the SQL it compiles to.
 */
const whereConditions: SQL[] = [];
const buildDb = (rows: any[], overlapRows: any[] = []) =>
  ({
    select: () => ({
      from: () => ({
        where: (condition: SQL) => {
          whereConditions.push(condition);
          return {
            groupBy: () => ({
              having: () => ({ limit: vi.fn().mockResolvedValue(overlapRows) }),
            }),
            orderBy: () => ({ limit: vi.fn().mockResolvedValue(rows) }),
          };
        },
      }),
    }),
  }) as any;

const candidate = (id = 'op_x', overrides: Record<string, any> = {}) => ({
  id,
  provider: 'openai',
  threadId: null,
  updatedAt: new Date(Date.now() - 10 * 60_000),
  topicId: 'tpc_x',
  userId: 'user_x',
  workspaceId: null,
  ...overrides,
});

const buildCoordinator = (
  state: any,
  history: any[] = [],
  isInterrupted: (id: string) => boolean = () => false,
) => ({
  getExecutionHistory: vi.fn().mockResolvedValue(history),
  isInterrupted: vi.fn(async (id: string) => isInterrupted(id)),
  loadAgentState: vi.fn().mockResolvedValue(state),
});
const buildQueue = () => ({ scheduleMessage: vi.fn().mockResolvedValue('msg_1') });

const runningState = (overrides: Record<string, any> = {}) => ({
  metadata: {},
  status: 'running',
  stepCount: 7,
  ...overrides,
});

/** `saveStepResult` files the context for step N+1 under producing step N. */
const historyFor = (stepIndex: number, context: any = { phase: 'tool_result' }) => [
  { context: { phase: 'llm_result' }, stepIndex: stepIndex - 1 },
  { context, stepIndex },
];

const buildReaper = (
  rows: any[],
  state: any,
  queue: any = buildQueue(),
  history: any[] = historyFor(6),
) =>
  new StaleOperationReaper(buildDb(rows), {
    coordinator: buildCoordinator(state, history) as any,
    queueService: queue as any,
  });

describe('StaleOperationReaper', () => {
  beforeEach(() => {
    claimStaleRedriveMock.mockReset().mockResolvedValue(1);
    settleStaleRunningMock.mockReset().mockResolvedValue(true);
    releaseStaleRedriveMock.mockReset().mockResolvedValue(true);
    finalizeAbandonedMock.mockClear();
    whereConditions.length = 0;
    process.env.APP_URL = 'https://app.lobehub.test';
  });

  it('re-queues the unfinished step of a resumable operation', async () => {
    const queue = buildQueue();
    const result = await buildReaper([candidate()], runningState(), queue).sweep();

    expect(queue.scheduleMessage).toHaveBeenCalledWith(
      expect.objectContaining({
        // The context step 6 produced for step 7 — without it `runtime.step`
        // would synthesize a `user_input` context and drop the pending work.
        context: { phase: 'tool_result' },
        // stepCount is the count of COMPLETED steps, so it is also the index
        // of the one that never finished.
        endpoint: 'https://app.lobehub.test/api/agent/run',
        operationId: 'op_x',
        stepIndex: 7,
      }),
    );
    expect(finalizeAbandonedMock).not.toHaveBeenCalled();
    expect(result).toMatchObject({ abandoned: 0, examined: 1, redriven: 1 });
  });

  it('keys deduplication per attempt so a later redrive is not deduped away', async () => {
    const queue = buildQueue();
    claimStaleRedriveMock.mockResolvedValue(2);

    await buildReaper([candidate()], runningState(), queue).sweep();

    expect(queue.scheduleMessage).toHaveBeenCalledWith(
      expect.objectContaining({ deduplicationId: 'stale-redrive:op_x:7:2' }),
    );
  });

  it('redrives step 0 with the context the operation was created with', async () => {
    // Born-dead shape: state exists but is still `idle` at step 0. There is no
    // producing step, so the context comes off the state — the same field the
    // intervention continuation re-publishes from.
    const queue = buildQueue();
    await buildReaper(
      [candidate()],
      runningState({ initialContext: { phase: 'user_input' }, status: 'idle', stepCount: 0 }),
      queue,
      [],
    ).sweep();

    expect(queue.scheduleMessage).toHaveBeenCalledWith(
      expect.objectContaining({ context: { phase: 'user_input' }, stepIndex: 0 }),
    );
  });

  it('skips rather than abandons when the step context cannot be recovered', async () => {
    // `getExecutionHistory` swallows a failed LRANGE and returns [], so an
    // empty result cannot be told apart from a transient Redis failure.
    // Retiring is irreversible, and this operation is otherwise resumable.
    const queue = buildQueue();
    const result = await buildReaper([candidate()], runningState(), queue, []).sweep();

    expect(queue.scheduleMessage).not.toHaveBeenCalled();
    expect(claimStaleRedriveMock).not.toHaveBeenCalled();
    expect(settleStaleRunningMock).not.toHaveBeenCalled();
    expect(finalizeAbandonedMock).not.toHaveBeenCalled();
    expect(result).toMatchObject({ abandoned: 0, redriven: 0, skipped: 1 });
  });

  it('never redrives an operation with no coordinator state', async () => {
    // This is also the shape of a HEALTHY heterogeneous run: an external Claude
    // Code / Codex CLI drives it, it never creates coordinator state, and it
    // only refreshes its lease on `heteroIngest` batches — so one long tool
    // call reads as stale here. Retiring it early would make `heteroIngest`
    // drop every subsequent batch of a live session.
    const queue = buildQueue();
    const result = await buildReaper(
      [candidate('op_x', { provider: 'codex' })],
      null,
      queue,
    ).sweep();

    expect(queue.scheduleMessage).not.toHaveBeenCalled();
    expect(claimStaleRedriveMock).not.toHaveBeenCalled();
    expect(finalizeAbandonedMock).not.toHaveBeenCalled();
    expect(result).toMatchObject({ abandoned: 0, redriven: 0, skipped: 1 });
  });

  it('only scans rows whose lease froze within the lookback window', async () => {
    // Production carries ~21k `running` rows dead for days, none with
    // coordinator state. Unbounded, the oldest-first window was those same 50
    // skipped rows on every tick and never reached a run that just died.
    const before = Date.now();
    await buildReaper([], runningState()).sweep();

    const { params, sql } = new PgDialect().sqlToQuery(whereConditions[0]);
    expect(sql).toMatch(/"updated_at" >= \$\d+/);
    const floor = params.find(
      (p) => typeof p === 'string' && new Date(p).getTime() <= before - 23 * 60 * 60_000,
    );
    expect(floor).toBeDefined();
    expect(new Date(floor as string).getTime()).toBeGreaterThanOrEqual(
      before - 24 * 60 * 60_000 - 1000,
    );
  });

  it('bounds both running scans by creation time so they can use the partial index', async () => {
    // Without a `created_at` floor both scans walked every `running` row
    // through `agent_operations_status_idx` (8.8s mean in production);
    // `agent_operations_running_created_at_idx` only helps when it is bounded.
    const before = Date.now();
    await buildReaper([], runningState()).sweep();

    expect(whereConditions).toHaveLength(2);
    for (const condition of whereConditions) {
      const { params, sql } = new PgDialect().sqlToQuery(condition);
      expect(sql).toMatch(/"created_at" >= \$\d+/);
      const floor = params.find(
        (p) => typeof p === 'string' && new Date(p).getTime() <= before - 6 * 24 * 60 * 60_000,
      );
      expect(floor).toBeDefined();
      expect(new Date(floor as string).getTime()).toBeGreaterThanOrEqual(
        before - 7 * 24 * 60 * 60_000 - 1000,
      );
    }
  });

  it('abandons a stateless heterogeneous run silent past the hetero window', async () => {
    // 2026-10-12: a device-dispatched Codex run went silent when its desktop
    // dropped off, the gateway inactivity watchdog never fired for it, and it
    // stayed `running` — its Task refusing every new message — until a human
    // paused it. Hetero runs never have coordinator state, so the reaper used
    // to skip them unconditionally.
    const queue = buildQueue();
    const before = Date.now();
    const result = await buildReaper(
      [candidate('op_x', { provider: 'codex', updatedAt: new Date(before - 61 * 60_000) })],
      null,
      queue,
    ).sweep();

    const [, staleBefore] = settleStaleRunningMock.mock.calls[0];
    // The CAS re-checks the lease against the hetero window, not the 5-min one,
    // so an ingest batch that lands meanwhile keeps the run alive.
    expect(staleBefore.getTime()).toBeLessThanOrEqual(before - 60 * 60_000 + 5);
    expect(staleBefore.getTime()).toBeGreaterThan(before - 61 * 60_000);
    expect(finalizeAbandonedMock).toHaveBeenCalledWith('op_x', 'stale_lease_hetero_silent', {
      settledAsAbandoned: true,
    });
    expect(queue.scheduleMessage).not.toHaveBeenCalled();
    expect(claimStaleRedriveMock).not.toHaveBeenCalled();
    expect(result).toMatchObject({ abandoned: 1, skipped: 0 });
  });

  it('keeps a heterogeneous run that is quiet but inside the hetero window', async () => {
    // A long shell command inside the CLI reaches the server as silence; the
    // backstop must not be stricter than the gateway's 60-min hetero window.
    const result = await buildReaper(
      [
        candidate('op_x', {
          provider: 'claude-code',
          updatedAt: new Date(Date.now() - 30 * 60_000),
        }),
      ],
      null,
    ).sweep();

    expect(settleStaleRunningMock).not.toHaveBeenCalled();
    expect(finalizeAbandonedMock).not.toHaveBeenCalled();
    expect(result).toMatchObject({ abandoned: 0, skipped: 1 });
  });

  it('leaves a silent heterogeneous run alone when an ingest batch wins the CAS', async () => {
    settleStaleRunningMock.mockResolvedValue(false);

    const result = await buildReaper(
      [candidate('op_x', { provider: 'codex', updatedAt: new Date(Date.now() - 90 * 60_000) })],
      null,
    ).sweep();

    expect(finalizeAbandonedMock).not.toHaveBeenCalled();
    expect(result).toMatchObject({ abandoned: 0, alive: 1 });
  });

  it('still skips a stateless non-heterogeneous run however long it has been quiet', async () => {
    const result = await buildReaper(
      [
        candidate('op_x', {
          provider: 'openai',
          updatedAt: new Date(Date.now() - 3 * 60 * 60_000),
        }),
      ],
      null,
    ).sweep();

    expect(settleStaleRunningMock).not.toHaveBeenCalled();
    expect(finalizeAbandonedMock).not.toHaveBeenCalled();
    expect(result).toMatchObject({ skipped: 1 });
  });

  it.each(['waiting_for_human', 'waiting_for_async_tool'])(
    'never redrives a deliberately parked operation (%s)',
    async (status) => {
      const queue = buildQueue();
      const result = await buildReaper([candidate()], runningState({ status }), queue).sweep();

      expect(queue.scheduleMessage).not.toHaveBeenCalled();
      expect(finalizeAbandonedMock).not.toHaveBeenCalled();
      expect(result).toMatchObject({ skipped: 1 });
    },
  );

  it('leaves an operation alone when a heartbeat wins the claim race', async () => {
    const queue = buildQueue();
    claimStaleRedriveMock.mockResolvedValue(null);
    // The stale CAS finds the row refreshed → the step is alive and owns itself
    // again, so nothing irreversible may happen to it.
    settleStaleRunningMock.mockResolvedValue(false);

    const result = await buildReaper([candidate()], runningState(), queue).sweep();

    expect(queue.scheduleMessage).not.toHaveBeenCalled();
    expect(finalizeAbandonedMock).not.toHaveBeenCalled();
    expect(result).toMatchObject({ abandoned: 0, alive: 1, redriven: 0 });
  });

  it('abandons once the redrive budget is spent', async () => {
    const queue = buildQueue();
    claimStaleRedriveMock.mockResolvedValue(null);
    // CAS still matches → the claim failed on the attempt budget, not a heartbeat.
    settleStaleRunningMock.mockResolvedValue(true);

    const result = await buildReaper([candidate()], runningState(), queue).sweep();

    expect(queue.scheduleMessage).not.toHaveBeenCalled();
    expect(settleStaleRunningMock).toHaveBeenCalledWith('op_x', expect.any(Date));
    // The claim already retired the row, so the lifecycle must be told —
    // otherwise its own completion write is refused and no hooks fire.
    expect(finalizeAbandonedMock).toHaveBeenCalledWith('op_x', 'stale_lease_redrive_exhausted', {
      settledAsAbandoned: true,
    });
    expect(result).toMatchObject({ abandoned: 1 });
  });

  it('gives the attempt back when the redrive fails to publish', async () => {
    // The budget bounds LLM spend; a delivery that never went out spent
    // nothing. Without the release, a brief queue outage walks a healthy
    // operation to its attempt limit and retires it having never recovered.
    const queue = buildQueue();
    queue.scheduleMessage.mockRejectedValue(new Error('qstash down'));
    claimStaleRedriveMock.mockResolvedValue(2);

    const result = await buildReaper([candidate()], runningState(), queue).sweep();

    expect(releaseStaleRedriveMock).toHaveBeenCalledWith('op_x', 2);
    expect(finalizeAbandonedMock).not.toHaveBeenCalled();
    expect(result).toMatchObject({ abandoned: 0, failed: 1, redriven: 0 });
  });

  it('keeps the attempt when the redrive publishes successfully', async () => {
    const result = await buildReaper([candidate()], runningState()).sweep();

    expect(releaseStaleRedriveMock).not.toHaveBeenCalled();
    expect(result).toMatchObject({ redriven: 1 });
  });

  it('keeps sweeping after one operation throws', async () => {
    const queue = buildQueue();
    queue.scheduleMessage
      .mockRejectedValueOnce(new Error('queue down'))
      .mockResolvedValueOnce('msg_2');

    const result = await buildReaper(
      [candidate('op_a'), candidate('op_b')],
      runningState(),
      queue,
    ).sweep();

    expect(result).toMatchObject({ examined: 2, failed: 1, redriven: 1 });
  });

  it('passes the caller stall window through to the claim', async () => {
    const before = Date.now();
    await buildReaper([candidate()], runningState()).sweep({ staleAfterMs: 60_000 });

    const [, staleBefore, maxAttempts] = claimStaleRedriveMock.mock.calls[0];
    expect(maxAttempts).toBe(3);
    expect(staleBefore.getTime()).toBeLessThanOrEqual(before - 60_000 + 5);
  });

  it('reports topics with more than one foreground run live', async () => {
    const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
    const overlap = { operationIds: ['op_a', 'op_b'], topicId: 'tpc_x' };
    const reaper = new StaleOperationReaper(buildDb([], [overlap]), {
      coordinator: buildCoordinator(null) as any,
      queueService: buildQueue() as any,
    });

    const result = await reaper.sweep();

    expect(result.concurrentForegroundTopics).toBe(1);
    expect(warn).toHaveBeenCalledWith(
      '[StaleOperationReaper] concurrent foreground operations on one topic',
      { ...overlap, unstoppedOperationIds: ['op_a'] },
    );
    warn.mockRestore();
  });

  it('only counts foreground runs whose lease moved within the hetero silence window', async () => {
    // Production re-warned the same months-old dead `running` rows on every
    // once-a-minute sweep: nothing settles them, and the patrol had no floor.
    const before = Date.now();
    const reaper = new StaleOperationReaper(buildDb([]), {
      coordinator: buildCoordinator(null) as any,
      queueService: buildQueue() as any,
    });

    await reaper.sweep();

    const { params, sql } = new PgDialect().sqlToQuery(whereConditions[1]);
    expect(sql).toMatch(/"updated_at" >= \$\d+/);
    const floor = params.find(
      (p) => typeof p === 'string' && new Date(p).getTime() <= before - 59 * 60_000,
    );
    expect(floor).toBeDefined();
    expect(new Date(floor as string).getTime()).toBeGreaterThanOrEqual(before - 60 * 60_000 - 1000);
  });

  it('ignores an overlap whose older runs were already asked to stop', async () => {
    const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
    const overlap = { operationIds: ['op_a', 'op_b'], topicId: 'tpc_x' };
    const reaper = new StaleOperationReaper(buildDb([], [overlap]), {
      coordinator: buildCoordinator(null, [], (id) => id === 'op_a') as any,
      queueService: buildQueue() as any,
    });

    const result = await reaper.sweep();

    expect(result.concurrentForegroundTopics).toBe(0);
    expect(warn).not.toHaveBeenCalled();
    warn.mockRestore();
  });

  it('still reports recovery results when the patrol query fails', async () => {
    const db = buildDb([candidate()]);
    const select = db.select;
    let calls = 0;
    db.select = () => {
      calls += 1;
      if (calls === 1) return select();
      throw new Error('db down');
    };
    const reaper = new StaleOperationReaper(db, {
      coordinator: buildCoordinator(runningState(), historyFor(6)) as any,
      queueService: buildQueue() as any,
    });

    const result = await reaper.sweep();

    expect(result).toMatchObject({ concurrentForegroundTopics: 0, redriven: 1 });
  });
});