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(verify): stop stranding runs in `verifying` (#18164)

Arvin Xueadf98d22294
diff --git a/apps/server/src/router-hono/workflows/verify/handlers/sweep.ts b/apps/server/src/router-hono/workflows/verify/handlers/sweep.ts
new file mode 100644
index 00000000000..e18ddc2932a
--- /dev/null
+++ b/apps/server/src/router-hono/workflows/verify/handlers/sweep.ts
@@ -0,0 +1,34 @@
+import debug from 'debug';
+import type { Context } from 'hono';
+
+import { getServerDB } from '@/database/server';
+import { sweepStuckVerifyRuns } from '@/server/services/verify';
+
+const log = debug('lobe-server:workflows:verify:sweep');
+
+/**
+ * Cron-style sweep for verification runs stranded in `verifying` β€” see
+ * {@link sweepStuckVerifyRuns} for what strands them and how each shape is
+ * recovered.
+ *
+ * No per-user authentication: this is a global scan registered as a QStash
+ * Schedule (cron). Signature verification is handled by the `qstashAuth`
+ * middleware mounted on the route.
+ */
+export async function sweep(c: Context) {
+ try {
+ const db = await getServerDB();
+ const outcome = await sweepStuckVerifyRuns(db);
+
+ log(
+ 'Verify sweep: settled=%d abandoned=%d skipped=%d',
+ outcome.settled.length,
+ outcome.abandoned.length,
+ outcome.skipped,
+ );
+ return c.json({ ...outcome, success: true });
+ } catch (error) {
+ console.error('[verify/sweep] Error:', error);
+ return c.json({ error: error instanceof Error ? error.message : 'Internal error' }, 500);
+ }
+}
diff --git a/apps/server/src/router-hono/workflows/verify/index.ts b/apps/server/src/router-hono/workflows/verify/index.ts
index 175801fd056..514f7ba8a94 100644
--- a/apps/server/src/router-hono/workflows/verify/index.ts
+++ b/apps/server/src/router-hono/workflows/verify/index.ts
@@ -2,9 +2,11 @@ import { Hono } from 'hono';
import { qstashAuth } from '../middlewares/qstashAuth';
import { onVerifierComplete } from './handlers/onVerifierComplete';
+import { sweep } from './handlers/sweep';
const app = new Hono();
app.post('/on-verifier-complete', qstashAuth(), onVerifierComplete);
+app.post('/sweep', qstashAuth(), sweep);
export default app;
diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle.ts
index 3b6bf08dd9c..07c4145ab04 100644
--- a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts
+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle.ts
@@ -19,6 +19,7 @@ import { emitAgentSignalSourceEvent } from '@/server/services/agentSignal';
import { toAgentSignalTraceEvents } from '@/server/services/agentSignal/observability/traceEvents';
import { extractSelfIterationCompletionPayload } from '@/server/services/agentSignal/services/selfIteration/completion';
import { instantiateVerifyPlanOnStart, runVerifyOnCompletion } from '@/server/services/verify';
+import { after } from '@/server/utils/scheduleAfterResponse';
import { CriticalHookDeliveryError, hookDispatcher, type SerializedHook } from './hooks';
import { registerWorksForOperation } from './workRegistration';
@@ -691,15 +692,24 @@ export class CompletionLifecycle {
metadata?.assistantMessageId,
metadata?.userId || this.userId,
);
- void runVerifyOnCompletion(
- this.serverDB,
- metadata?.userId || this.userId,
- {
- deliverable: event.lastAssistantContent ?? '',
- goal,
- operationId,
- },
- this.workspaceId,
+ // `after`, not a bare `void`: judging is minutes of LLM calls and the
+ // step handler must not wait for it, but a detached promise has nobody
+ // keeping it scheduled β€” on the serverless path the instance is free to
+ // stop running it the moment this response returns. That is not merely a
+ // lost verification: entering `verifying` is a durable write, so a run
+ // cut off mid-judge stays `verifying` forever. `after` hands the work to
+ // the host as post-response work instead (no-op fallback off Next).
+ after(() =>
+ runVerifyOnCompletion(
+ this.serverDB,
+ metadata?.userId || this.userId,
+ {
+ deliverable: event.lastAssistantContent ?? '',
+ goal,
+ operationId,
+ },
+ this.workspaceId,
+ ),
);
}
diff --git a/apps/server/src/services/agentRuntime/__tests__/completionVerifyScheduling.test.ts b/apps/server/src/services/agentRuntime/__tests__/completionVerifyScheduling.test.ts
new file mode 100644
index 00000000000..19159877ab1
--- /dev/null
+++ b/apps/server/src/services/agentRuntime/__tests__/completionVerifyScheduling.test.ts
@@ -0,0 +1,55 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import * as verifyServices from '@/server/services/verify';
+
+import { CompletionLifecycle } from '../CompletionLifecycle';
+import { hookDispatcher } from '../hooks';
+
+const { after } = vi.hoisted(() => ({ after: vi.fn() }));
+
+vi.mock('@/server/utils/scheduleAfterResponse', () => ({ after }));
+vi.mock('@/business/server/agent-run/notifyAgentRunCompleted', () => ({
+ notifyAgentRunCompleted: vi.fn(async () => {}),
+}));
+vi.mock('../workRegistration', () => ({ registerWorksForOperation: vi.fn() }));
+
+/**
+ * Regression: the completion-time verify gate used to be launched with a bare
+ * `void`. Nobody held that promise, so on the serverless path the instance was
+ * free to stop scheduling it as soon as the step response returned β€” and since
+ * entering `verifying` is a durable write, a run cut off mid-judge stayed
+ * `verifying` forever (acceptance and goal card stuck with it). It must be
+ * handed to the host as post-response work instead.
+ */
+describe('CompletionLifecycle β€” verify gate scheduling', () => {
+ beforeEach(() => {
+ after.mockReset();
+ });
+
+ it('schedules the verify gate as post-response work, not a detached promise', async () => {
+ const lifecycle = new CompletionLifecycle({} as any, 'user-1');
+ vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(undefined);
+ vi.spyOn(lifecycle as any, 'createVerifyMessage').mockResolvedValue(undefined);
+ vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);
+ vi.spyOn(hookDispatcher, 'unregister').mockImplementation(() => {});
+ const runVerify = vi
+ .spyOn(verifyServices, 'runVerifyOnCompletion')
+ .mockResolvedValue(undefined);
+
+ await lifecycle.dispatchHooks(
+ 'op-1',
+ { metadata: { _hooks: [], agentId: 'a' }, status: 'done' },
+ 'done',
+ );
+
+ // Handed over, and not started behind the scheduler's back.
+ expect(after).toHaveBeenCalledTimes(1);
+ expect(runVerify).not.toHaveBeenCalled();
+
+ // What was handed over is the gate itself.
+ await after.mock.calls[0][0]();
+ expect(runVerify).toHaveBeenCalledTimes(1);
+ expect(runVerify.mock.calls[0][2]).toMatchObject({ operationId: 'op-1' });
+ });
+});
diff --git a/apps/server/src/services/verify/__tests__/lifecycleClaim.test.ts b/apps/server/src/services/verify/__tests__/lifecycleClaim.test.ts
new file mode 100644
index 00000000000..0eb365d777f
--- /dev/null
+++ b/apps/server/src/services/verify/__tests__/lifecycleClaim.test.ts
@@ -0,0 +1,85 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { runVerifyOnCompletion } from '../lifecycle';
+import { VERIFY_ABANDONED_MS } from '../staleness';
+
+const { claimVerifying, execute, findByOperation, operationFindById, finalizeVerifyRun } =
+ vi.hoisted(() => ({
+ claimVerifying: vi.fn(),
+ execute: vi.fn(),
+ finalizeVerifyRun: vi.fn(),
+ findByOperation: vi.fn(),
+ operationFindById: vi.fn(),
+ }));
+
+vi.mock('@/database/models/verifyRun', () => ({
+ VerifyRunModel: vi.fn(() => ({ findByOperation })),
+}));
+vi.mock('@/database/models/agentOperation', () => ({
+ AgentOperationModel: vi.fn(() => ({ findById: operationFindById })),
+}));
+vi.mock('@/database/models/document', () => ({ DocumentModel: vi.fn(() => ({})) }));
+vi.mock('@/database/models/task', () => ({
+ TaskModel: vi.fn(() => ({
+ getPinnedDocuments: vi.fn().mockResolvedValue([]),
+ resolveVerifyConfig: vi.fn().mockResolvedValue(null),
+ })),
+}));
+vi.mock('../statusService', () => ({
+ VerifyStatusService: vi.fn(() => ({ claimVerifying })),
+}));
+vi.mock('../executor', () => ({ VerifyExecutorService: vi.fn(() => ({ execute })) }));
+vi.mock('../agentVerifier', () => ({ createVerifierAgentRunner: vi.fn(() => vi.fn()) }));
+vi.mock('../modelConfig', () => ({
+ resolveVerifyModelConfig: vi.fn().mockResolvedValue({ model: 'm', provider: 'p' }),
+}));
+vi.mock('../settle', () => ({ finalizeVerifyRun }));
+
+const db = {} as any;
+const params = { deliverable: 'done', goal: 'ship it', operationId: 'op-1' };
+
+const confirmedRun = { id: 'run-1', plan: [{ id: 'c1' }], planConfirmedAt: new Date() };
+
+describe('runVerifyOnCompletion β€” verification claim', () => {
+ beforeEach(() => {
+ [claimVerifying, execute, finalizeVerifyRun, findByOperation, operationFindById].forEach((m) =>
+ m.mockReset(),
+ );
+ findByOperation.mockResolvedValue(confirmedRun);
+ operationFindById.mockResolvedValue({ id: 'op-1', model: 'm', provider: 'p', taskId: null });
+ claimVerifying.mockResolvedValue(true);
+ });
+
+ it('claims the run with the abandoned bound rather than reading its status', async () => {
+ const before = Date.now();
+ await runVerifyOnCompletion(db, 'u1', params);
+
+ expect(execute).toHaveBeenCalledTimes(1);
+ const [operationId, staleBefore] = claimVerifying.mock.calls[0];
+ expect(operationId).toBe('op-1');
+ // The window the claim treats as abandoned, not "now".
+ expect(staleBefore.getTime()).toBeGreaterThanOrEqual(before - VERIFY_ABANDONED_MS - 1000);
+ expect(staleBefore.getTime()).toBeLessThanOrEqual(Date.now() - VERIFY_ABANDONED_MS + 1000);
+ });
+
+ it('does not judge when another completion already holds the claim', async () => {
+ // A redelivered terminal step: the first one is mid-judge, this one must not
+ // start a second pass over the same plan.
+ claimVerifying.mockResolvedValue(false);
+
+ await runVerifyOnCompletion(db, 'u1', params);
+
+ expect(execute).not.toHaveBeenCalled();
+ expect(finalizeVerifyRun).not.toHaveBeenCalled();
+ });
+
+ it('still skips runs that never opted in', async () => {
+ findByOperation.mockResolvedValue({ id: 'run-1', plan: [{ id: 'c1' }], planConfirmedAt: null });
+
+ await runVerifyOnCompletion(db, 'u1', params);
+
+ expect(claimVerifying).not.toHaveBeenCalled();
+ expect(execute).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/services/verify/__tests__/sweep.test.ts b/apps/server/src/services/verify/__tests__/sweep.test.ts
new file mode 100644
index 00000000000..42bff672385
--- /dev/null
+++ b/apps/server/src/services/verify/__tests__/sweep.test.ts
@@ -0,0 +1,286 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { VERIFY_ABANDONED_MS, VERIFY_ROLLUP_GRACE_MS } from '../staleness';
+import { sweepStuckVerifyRuns } from '../sweep';
+
+const {
+ claimVerifying,
+ findStuckVerifying,
+ operationFindById,
+ recompute,
+ resultListByRun,
+ upsertByCheckItem,
+ finalizeVerifyRun,
+} = vi.hoisted(() => ({
+ claimVerifying: vi.fn(),
+ finalizeVerifyRun: vi.fn(),
+ findStuckVerifying: vi.fn(),
+ operationFindById: vi.fn(),
+ recompute: vi.fn(),
+ resultListByRun: vi.fn(),
+ upsertByCheckItem: vi.fn(),
+}));
+
+vi.mock('@/database/models/verifyRun', () => ({
+ VerifyRunModel: Object.assign(
+ vi.fn(() => ({})),
+ { findStuckVerifying },
+ ),
+}));
+vi.mock('@/database/models/verifyCheckResult', () => ({
+ VerifyCheckResultModel: vi.fn(() => ({ listByRun: resultListByRun, upsertByCheckItem })),
+}));
+vi.mock('@/database/models/agentOperation', () => ({
+ AgentOperationModel: vi.fn(() => ({ findById: operationFindById })),
+}));
+vi.mock('../statusService', () => ({
+ VerifyStatusService: vi.fn(() => ({ claimVerifying, recompute })),
+}));
+vi.mock('../settle', () => ({ finalizeVerifyRun }));
+
+const db = {} as any;
+const NOW = new Date('2026-08-10T00:00:00Z');
+
+const stuckRun = (overrides?: Partial<Record<string, unknown>>) => ({
+ id: 'run-1',
+ operationId: 'op-1',
+ plan: [
+ { id: 'c1', required: true },
+ { id: 'c2', required: true },
+ ],
+ updatedAt: new Date(NOW.getTime() - VERIFY_ROLLUP_GRACE_MS - 1000),
+ userId: 'u1',
+ workspaceId: null,
+ ...overrides,
+});
+
+/** Answer the first page and then an empty one, so the keyset loop terminates. */
+const singlePage = (runs: unknown[]) => {
+ findStuckVerifying.mockResolvedValueOnce(runs).mockResolvedValue([]);
+};
+
+describe('sweepStuckVerifyRuns', () => {
+ beforeEach(() => {
+ [
+ claimVerifying,
+ finalizeVerifyRun,
+ findStuckVerifying,
+ operationFindById,
+ recompute,
+ resultListByRun,
+ upsertByCheckItem,
+ ].forEach((m) => m.mockReset());
+ findStuckVerifying.mockResolvedValue([]);
+ resultListByRun.mockResolvedValue([]);
+ claimVerifying.mockResolvedValue(true);
+ });
+
+ it('recomputes a run whose checks all landed but whose rollup was lost', async () => {
+ // The exact state a killed post-response judge leaves behind: every verdict
+ // is on disk, only `verify_runs.status` never caught up.
+ singlePage([stuckRun()]);
+ resultListByRun.mockResolvedValue([
+ { checkItemId: 'c1', status: 'failed', verdict: 'uncertain' },
+ { checkItemId: 'c2', status: 'passed', verdict: 'passed' },
+ ]);
+
+ const outcome = await sweepStuckVerifyRuns(db, { now: NOW });
+
+ expect(outcome.settled).toEqual(['run-1']);
+ // Nothing is re-judged β€” the sweep only derives.
+ expect(upsertByCheckItem).not.toHaveBeenCalled();
+ expect(recompute).toHaveBeenCalledWith('op-1');
+ expect(finalizeVerifyRun).toHaveBeenCalledWith(db, 'u1', 'op-1', {}, undefined);
+ });
+
+ it('leaves a run alone until the rollup grace elapses', async () => {
+ findStuckVerifying.mockResolvedValue([]);
+
+ await sweepStuckVerifyRuns(db, { now: NOW });
+
+ expect(findStuckVerifying).toHaveBeenCalledWith(
+ db,
+ new Date(NOW.getTime() - VERIFY_ROLLUP_GRACE_MS),
+ expect.objectContaining({ after: undefined }),
+ );
+ });
+
+ it('holds off on a run with checks still pending until the abandoned bound', async () => {
+ singlePage([stuckRun()]);
+ resultListByRun.mockResolvedValue([
+ { checkItemId: 'c1', status: 'pending', verdict: null },
+ { checkItemId: 'c2', status: 'passed', verdict: 'passed' },
+ ]);
+
+ const outcome = await sweepStuckVerifyRuns(db, { now: NOW });
+
+ expect(outcome.skipped).toBe(1);
+ expect(upsertByCheckItem).not.toHaveBeenCalled();
+ expect(recompute).not.toHaveBeenCalled();
+ });
+
+ it('errors out checks left pending past the abandoned bound, then rolls up', async () => {
+ singlePage([stuckRun({ updatedAt: new Date(NOW.getTime() - VERIFY_ABANDONED_MS - 1000) })]);
+ resultListByRun.mockResolvedValue([
+ { checkItemId: 'c1', status: 'running', verdict: null },
+ { checkItemId: 'c2', status: 'passed', verdict: 'passed' },
+ ]);
+
+ const outcome = await sweepStuckVerifyRuns(db, { now: NOW });
+
+ expect(outcome.abandoned).toEqual(['run-1']);
+ expect(upsertByCheckItem).toHaveBeenCalledTimes(1);
+ // `errored`, not `failed`: the verifier never judged, so this must not gate
+ // delivery or seed auto-repair.
+ expect(upsertByCheckItem).toHaveBeenCalledWith(
+ expect.objectContaining({ checkItemId: 'c1', status: 'errored', verifyRunId: 'run-1' }),
+ );
+ expect(recompute).toHaveBeenCalledWith('op-1');
+ });
+
+ it('never touches a check whose verifier operation is still live', async () => {
+ singlePage([stuckRun({ updatedAt: new Date(NOW.getTime() - VERIFY_ABANDONED_MS - 1000) })]);
+ resultListByRun.mockResolvedValue([
+ { checkItemId: 'c1', status: 'running', verifierOperationId: 'verifier-op', verdict: null },
+ { checkItemId: 'c2', status: 'passed', verdict: 'passed' },
+ ]);
+ operationFindById.mockResolvedValue({ id: 'verifier-op', status: 'running' });
+
+ const outcome = await sweepStuckVerifyRuns(db, { now: NOW });
+
+ expect(outcome.skipped).toBe(1);
+ expect(upsertByCheckItem).not.toHaveBeenCalled();
+ expect(recompute).not.toHaveBeenCalled();
+ });
+
+ it('closes a check whose verifier operation already died', async () => {
+ singlePage([stuckRun({ updatedAt: new Date(NOW.getTime() - VERIFY_ABANDONED_MS - 1000) })]);
+ resultListByRun.mockResolvedValue([
+ { checkItemId: 'c1', status: 'running', verifierOperationId: 'verifier-op', verdict: null },
+ { checkItemId: 'c2', status: 'passed', verdict: 'passed' },
+ ]);
+ operationFindById.mockResolvedValue({ id: 'verifier-op', status: 'error' });
+
+ const outcome = await sweepStuckVerifyRuns(db, { now: NOW });
+
+ expect(outcome.abandoned).toEqual(['run-1']);
+ });
+
+ it('ignores optional checks when deciding whether anything is outstanding', async () => {
+ singlePage([
+ stuckRun({
+ plan: [
+ { id: 'c1', required: true },
+ { id: 'c2', required: false },
+ ],
+ }),
+ ]);
+ resultListByRun.mockResolvedValue([
+ { checkItemId: 'c1', status: 'passed', verdict: 'passed' },
+ { checkItemId: 'c2', status: 'pending', verdict: null },
+ ]);
+
+ const outcome = await sweepStuckVerifyRuns(db, { now: NOW });
+
+ expect(outcome.settled).toEqual(['run-1']);
+ });
+
+ it('keeps sweeping after one run throws', async () => {
+ singlePage([
+ stuckRun({ id: 'run-bad' }),
+ stuckRun({ id: 'run-2', operationId: 'op-2', plan: [{ id: 'c1', required: true }] }),
+ ]);
+ resultListByRun
+ .mockRejectedValueOnce(new Error('boom'))
+ .mockResolvedValue([{ checkItemId: 'c1', status: 'passed', verdict: 'passed' }]);
+
+ const outcome = await sweepStuckVerifyRuns(db, { now: NOW });
+
+ expect(outcome.skipped).toBe(1);
+ expect(outcome.settled).toEqual(['run-2']);
+ });
+
+ it('creates the missing rows for a run interrupted before its results existed', async () => {
+ // Entering `verifying` happens before the pending rows are written, so a run
+ // can be stranded with plan items that have no row at all. Updating in place
+ // would touch nothing and leave the run stuck while reporting it recovered.
+ singlePage([stuckRun({ updatedAt: new Date(NOW.getTime() - VERIFY_ABANDONED_MS - 1000) })]);
+ resultListByRun.mockResolvedValue([]);
+
+ const outcome = await sweepStuckVerifyRuns(db, { now: NOW });
+
+ expect(outcome.abandoned).toEqual(['run-1']);
+ expect(upsertByCheckItem).toHaveBeenCalledTimes(2);
+ expect(upsertByCheckItem).toHaveBeenCalledWith(
+ expect.objectContaining({ checkItemId: 'c1', status: 'errored', verifyRunId: 'run-1' }),
+ );
+ expect(recompute).toHaveBeenCalledWith('op-1');
+ });
+
+ it('drops a run whose lease another delivery already holds', async () => {
+ // `finalizeVerifyRun` spawns the repair round and `triggerAutoRepair` has no
+ // claim of its own, so two overlapping sweeps must not both reach it.
+ singlePage([stuckRun()]);
+ resultListByRun.mockResolvedValue([
+ { checkItemId: 'c1', status: 'passed', verdict: 'passed' },
+ { checkItemId: 'c2', status: 'passed', verdict: 'passed' },
+ ]);
+ claimVerifying.mockResolvedValue(false);
+
+ const outcome = await sweepStuckVerifyRuns(db, { now: NOW });
+
+ expect(outcome.skipped).toBe(1);
+ expect(recompute).not.toHaveBeenCalled();
+ expect(finalizeVerifyRun).not.toHaveBeenCalled();
+ });
+
+ it('never leases a run it is going to skip', async () => {
+ // Claiming re-stamps `updated_at`; doing that to a run we leave alone would
+ // push its abandoned deadline forward every tick, so it would never age out.
+ singlePage([stuckRun()]);
+ resultListByRun.mockResolvedValue([
+ { checkItemId: 'c1', status: 'pending', verdict: null },
+ { checkItemId: 'c2', status: 'passed', verdict: 'passed' },
+ ]);
+
+ await sweepStuckVerifyRuns(db, { now: NOW });
+
+ expect(claimVerifying).not.toHaveBeenCalled();
+ });
+
+ it('pages past runs it cannot recover instead of re-reading the oldest slice', async () => {
+ // A run whose verifier is still live keeps its timestamp, so it stays at the
+ // head of the ordered scan. Without a cursor it would starve everything newer.
+ const live = stuckRun({
+ id: 'run-live',
+ updatedAt: new Date(NOW.getTime() - VERIFY_ABANDONED_MS - 2000),
+ });
+ findStuckVerifying
+ .mockResolvedValueOnce([live])
+ .mockResolvedValueOnce([
+ stuckRun({
+ id: 'run-newer',
+ operationId: 'op-newer',
+ plan: [{ id: 'c1', required: true }],
+ }),
+ ])
+ .mockResolvedValue([]);
+ resultListByRun
+ .mockResolvedValueOnce([
+ { checkItemId: 'c1', status: 'running', verifierOperationId: 'verifier-op', verdict: null },
+ { checkItemId: 'c2', status: 'passed', verdict: 'passed' },
+ ])
+ .mockResolvedValue([{ checkItemId: 'c1', status: 'passed', verdict: 'passed' }]);
+ operationFindById.mockResolvedValue({ id: 'verifier-op', status: 'running' });
+
+ const outcome = await sweepStuckVerifyRuns(db, { now: NOW, pageSize: 1 });
+
+ // The second read resumes after the run it could not touch.
+ expect(findStuckVerifying.mock.calls[1][2]).toMatchObject({
+ after: { id: 'run-live', updatedAt: live.updatedAt },
+ });
+ expect(outcome.skipped).toBe(1);
+ expect(outcome.settled).toEqual(['run-newer']);
+ });
+});
diff --git a/apps/server/src/services/verify/index.ts b/apps/server/src/services/verify/index.ts
index 598ca7b9c75..abfff3f248e 100644
--- a/apps/server/src/services/verify/index.ts
+++ b/apps/server/src/services/verify/index.ts
@@ -38,5 +38,7 @@ export {
} from './repairService';
export { type GenerateReportParams, VerifyReporterService } from './reporter';
export { driveTaskFromVerify, finalizeVerifyRun } from './settle';
+export { VERIFY_ABANDONED_MS, VERIFY_ROLLUP_GRACE_MS } from './staleness';
export { VerifyStatusService } from './statusService';
+export { sweepStuckVerifyRuns, type VerifySweepOutcome } from './sweep';
export { settleVerifierCheckFromTerminal } from './verifierTerminal';
diff --git a/apps/server/src/services/verify/lifecycle.ts b/apps/server/src/services/verify/lifecycle.ts
index 90419919db9..42df7e90167 100644
--- a/apps/server/src/services/verify/lifecycle.ts
+++ b/apps/server/src/services/verify/lifecycle.ts
@@ -10,6 +10,8 @@ import { createVerifierAgentRunner } from './agentVerifier';
import { VerifyExecutorService } from './executor';
import { resolveVerifyModelConfig } from './modelConfig';
import { finalizeVerifyRun } from './settle';
+import { VERIFY_ABANDONED_MS } from './staleness';
+import { VerifyStatusService } from './statusService';
const log = debug('lobe-server:verify-lifecycle');
const MAX_TASK_DOCUMENT_CHARS = 80_000;
@@ -82,9 +84,20 @@ export const runVerifyOnCompletion = async (
params.operationId,
);
- // Opt-in gate: only runs with a confirmed plan that hasn't been verified yet.
+ // Opt-in gate: only runs with a confirmed plan.
if (!run?.plan?.length || !run.planConfirmedAt) return;
- if (run.status !== 'planned') return;
+
+ // Then claim it. Not a `status !== 'planned'` read: that let two completions
+ // landing together both start judging, and β€” the worse half β€” permanently
+ // shut the gate behind an attempt that entered `verifying` and then died,
+ // since every later attempt read the status it had already written. The
+ // claim is one conditional UPDATE, so exactly one caller proceeds and an
+ // abandoned attempt is re-enterable.
+ const claimed = await new VerifyStatusService(db, userId, workspaceId).claimVerifying(
+ params.operationId,
+ new Date(Date.now() - VERIFY_ABANDONED_MS),
+ );
+ if (!claimed) return;
const op = await new AgentOperationModel(db, userId, workspaceId).findById(params.operationId);
if (!op) {
diff --git a/apps/server/src/services/verify/staleness.ts b/apps/server/src/services/verify/staleness.ts
new file mode 100644
index 00000000000..b1a29d7ebe2
--- /dev/null
+++ b/apps/server/src/services/verify/staleness.ts
@@ -0,0 +1,31 @@
+/**
+ * How long a run may sit in `verifying` before we treat the attempt that put it
+ * there as gone.
+ *
+ * Verification is started as post-response work (see `runVerifyOnCompletion`'s
+ * caller): the run is flipped to `verifying` by a durable write, but the judging
+ * that would flip it back lives in a promise the host may stop scheduling at any
+ * point. That asymmetry is what strands a run β€” `verifying` forever, with no
+ * retry able to re-enter and no watchdog looking. Both the re-entry claim and
+ * the sweep read the same two thresholds so "abandoned" means one thing.
+ */
+
+/**
+ * Grace before the sweep touches a run whose required checks have all landed.
+ *
+ * Nothing needs judging in that state β€” only the rollup was lost β€” so the sweep
+ * could act immediately. It waits anyway: the finalizer of a still-live attempt
+ * runs within seconds of the last verdict, and letting the sweep in during that
+ * window would race it into spawning a second repair round.
+ */
+export const VERIFY_ROLLUP_GRACE_MS = 5 * 60 * 1000;
+
+/**
+ * How long a run with checks still pending/running is given before its verifier
+ * is presumed dead and the outstanding checks are closed as `errored`.
+ *
+ * Generous on purpose: an agent verifier is a full sub-agent run. Checks bound
+ * to a verifier operation that is still live are skipped regardless of age, so
+ * this bound only has to cover inline (LLM / program) judging.
+ */
+export const VERIFY_ABANDONED_MS = 30 * 60 * 1000;
diff --git a/apps/server/src/services/verify/statusService.ts b/apps/server/src/services/verify/statusService.ts
index 80690ce4992..7ef25317b8d 100644
--- a/apps/server/src/services/verify/statusService.ts
+++ b/apps/server/src/services/verify/statusService.ts
@@ -92,6 +92,29 @@ export class VerifyStatusService {
return status;
}
+ /**
+ * Claim the verification of an Agent Run and enter `verifying`, exactly once.
+ *
+ * This is the re-entrant form of {@link markVerifying}: the completion-time
+ * gate uses it so a redelivered completion cannot start a second judge pass,
+ * while an attempt that entered `verifying` and then died (its post-response
+ * work stopped being scheduled) can still be picked up by a later one.
+ *
+ * @returns false when someone else holds the verification.
+ */
+ async claimVerifying(operationId: string, staleBefore: Date): Promise<boolean> {
+ const run = await this.runModel.findByOperation(operationId);
+ if (!run) return false;
+
+ const claimed = await this.runModel.claimVerifying(run.id, staleBefore);
+ if (claimed && run.acceptanceId) {
+ await new AcceptanceService(this.db, this.userId, this.workspaceId).recomputeStatus(
+ run.acceptanceId,
+ );
+ }
+ return claimed;
+ }
+
/** Explicit transitions that aren't derivable from results alone. */
async markVerifying(operationId: string) {
await this.setStatus(operationId, 'verifying');
diff --git a/apps/server/src/services/verify/sweep.ts b/apps/server/src/services/verify/sweep.ts
new file mode 100644
index 00000000000..2ff7d10c36d
--- /dev/null
+++ b/apps/server/src/services/verify/sweep.ts
@@ -0,0 +1,203 @@
+import type { VerifyCheckItem } from '@lobechat/types';
+import debug from 'debug';
+
+import { AgentOperationModel } from '@/database/models/agentOperation';
+import { VerifyCheckResultModel } from '@/database/models/verifyCheckResult';
+import { VerifyRunModel } from '@/database/models/verifyRun';
+import type { VerifyRunItem } from '@/database/schemas/verify';
+import type { LobeChatDatabase } from '@/database/type';
+
+import { planItemToPendingResult } from './resultSnapshot';
+import { finalizeVerifyRun } from './settle';
+import { VERIFY_ABANDONED_MS, VERIFY_ROLLUP_GRACE_MS } from './staleness';
+import { VerifyStatusService } from './statusService';
+
+const log = debug('lobe-server:verify-sweep');
+
+/** An operation in any of these can still produce a verdict. */
+const LIVE_OPERATION_STATUSES = new Set([
+ 'idle',
+ 'running',
+ 'waiting_for_human',
+ 'waiting_for_async_tool',
+]);
+
+const PENDING_RESULT_STATUSES = new Set(['pending', 'running']);
+
+const SWEEP_PAGE_SIZE = 100;
+/** Bound one tick's work; whatever is left is still there on the next one. */
+const SWEEP_MAX_RUNS = 1000;
+
+export interface VerifySweepOutcome {
+ /** Runs whose outstanding checks were closed as `errored` before the rollup. */
+ abandoned: string[];
+ /** Runs whose checks had all landed and only needed the missing rollup. */
+ settled: string[];
+ /** Runs left alone β€” still plausibly mid-flight. */
+ skipped: number;
+}
+
+/**
+ * Recover verification runs stranded in `verifying`.
+ *
+ * Entering `verifying` is a durable write; the judging that leaves it runs as
+ * post-response work, so any host-level interruption β€” instance recycled,
+ * deploy, OOM, provider hang β€” strands the run. Nothing downstream re-reads it:
+ * the rollup is denormalized, the read paths trust it, and the task watchdog
+ * only looks at tasks carrying a heartbeat timeout. Without this sweep such a
+ * run is stuck for good, and so is the acceptance and goal card above it.
+ *
+ * Two shapes, deliberately treated differently:
+ *
+ * - **the rollup was lost** β€” every required check already holds a terminal
+ * verdict, so the truth is on disk and only the denormalized status disagrees.
+ * Recomputing is pure derivation; the only reason to wait out
+ * {@link VERIFY_ROLLUP_GRACE_MS} first is to stay clear of a live finalizer.
+ * - **the verifier died mid-flight** β€” checks are still pending/running. Those
+ * carry no verdict and never will, so after {@link VERIFY_ABANDONED_MS} they
+ * are closed as `errored` (an infra failure, not a delivery judgment, so they
+ * neither gate delivery nor seed auto-repair) and the rollup follows.
+ *
+ * A check bound to a verifier operation that is still live keeps the whole run
+ * out of the sweep however old it is β€” an agent verifier is a full sub-agent run
+ * and its own terminal hook is what settles it.
+ *
+ * Recovery is leased per run (see {@link recoverRun}) so overlapping deliveries
+ * of the cron cannot both drive the same run's finalizer.
+ */
+export const sweepStuckVerifyRuns = async (
+ db: LobeChatDatabase,
+ options?: { now?: Date; pageSize?: number },
+): Promise<VerifySweepOutcome> => {
+ const now = options?.now ?? new Date();
+ const pageSize = options?.pageSize ?? SWEEP_PAGE_SIZE;
+ const staleBefore = new Date(now.getTime() - VERIFY_ROLLUP_GRACE_MS);
+ const outcome: VerifySweepOutcome = { abandoned: [], settled: [], skipped: 0 };
+
+ // Walk the whole stranded set, not just its oldest page: rows the sweep leaves
+ // alone keep their timestamp, so a single fixed-size read would return the same
+ // untouchable rows forever and never reach the runs behind them.
+ let after: { id: string; updatedAt: Date } | undefined;
+ let scanned = 0;
+
+ while (scanned < SWEEP_MAX_RUNS) {
+ const page = await VerifyRunModel.findStuckVerifying(db, staleBefore, {
+ after,
+ limit: pageSize,
+ });
+ if (page.length === 0) break;
+
+ for (const run of page) {
+ scanned += 1;
+ try {
+ const action = await recoverRun(db, run, now);
+ if (action === 'skipped') outcome.skipped += 1;
+ else outcome[action].push(run.id);
+ } catch (error) {
+ // One poisoned run must not stop the sweep for the rest.
+ log('recovering run %s failed (non-fatal): %O', run.id, error);
+ outcome.skipped += 1;
+ }
+ }
+
+ const last = page.at(-1)!;
+ after = { id: last.id, updatedAt: last.updatedAt };
+ if (page.length < pageSize) break;
+ }
+
+ if (scanned >= SWEEP_MAX_RUNS) {
+ log('sweep hit the per-run cap (%d) β€” the tail is left for the next tick', SWEEP_MAX_RUNS);
+ }
+
+ return outcome;
+};
+
+const recoverRun = async (
+ db: LobeChatDatabase,
+ run: VerifyRunItem,
+ now: Date,
+): Promise<'abandoned' | 'settled' | 'skipped'> => {
+ const operationId = run.operationId;
+ if (!operationId) return 'skipped';
+
+ const workspaceId = run.workspaceId ?? undefined;
+ const plan = (run.plan ?? []) as VerifyCheckItem[];
+ if (plan.length === 0) return 'skipped';
+
+ const resultModel = new VerifyCheckResultModel(db, run.userId, workspaceId);
+ const results = await resultModel.listByRun(run.id);
+ const byItem = new Map(results.map((result) => [result.checkItemId, result]));
+
+ // Only required items decide the rollup β€” the same gate `recompute` applies.
+ const outstanding = plan
+ .filter((item) => item.required)
+ .filter((item) => {
+ const result = byItem.get(item.id);
+ return !result || PENDING_RESULT_STATUSES.has(result.status);
+ });
+
+ if (outstanding.length > 0) {
+ if (now.getTime() - run.updatedAt.getTime() < VERIFY_ABANDONED_MS) return 'skipped';
+
+ const operationModel = new AgentOperationModel(db, run.userId, workspaceId);
+ for (const item of outstanding) {
+ const verifierOperationId = byItem.get(item.id)?.verifierOperationId;
+ if (!verifierOperationId) continue;
+ const verifierOp = await operationModel.findById(verifierOperationId);
+ // Its verifier is still working β€” `settleVerifierCheckFromTerminal` owns
+ // this row's ending, and stamping it `errored` now would discard a verdict
+ // that is still coming.
+ if (verifierOp && LIVE_OPERATION_STATUSES.has(verifierOp.status)) return 'skipped';
+ }
+ }
+
+ // Committed to acting β€” take the lease first. Everything below has side effects
+ // beyond this run: `finalizeVerifyRun` spawns the repair round, and
+ // `triggerAutoRepair` has no claim of its own, so two overlapping sweep
+ // deliveries reaching it would launch duplicate repair agents against the same
+ // failures. The claim re-stamps `updated_at`, which is exactly what a
+ // concurrent sweep's CAS tests against, so the loser drops the run.
+ //
+ // Deliberately after the skip decisions: claiming a run we then leave alone
+ // would push its `updated_at` forward every tick and it would never reach the
+ // abandoned bound.
+ const statusService = new VerifyStatusService(db, run.userId, workspaceId);
+ if (
+ !(await statusService.claimVerifying(
+ operationId,
+ new Date(now.getTime() - VERIFY_ROLLUP_GRACE_MS),
+ ))
+ )
+ return 'skipped';
+
+ if (outstanding.length > 0) {
+ await Promise.all(
+ outstanding.map((item) =>
+ // Upsert, not update: a run interrupted between entering `verifying` and
+ // creating its pending rows has plan items with no row at all. Updating
+ // would touch nothing, `recompute` would still read them as pending, and
+ // the run would stay stranded while the sweep reported it recovered.
+ resultModel.upsertByCheckItem({
+ ...planItemToPendingResult(run.id, operationId, item),
+ // Re-asserted after the spread: the upsert key is required, and the
+ // snapshot's own fields are optional-nullable.
+ checkItemId: item.id,
+ verifyRunId: run.id,
+ completedAt: now,
+ status: 'errored',
+ suggestion: 'Rerun verification for this delivery.',
+ toulmin: { limitation: 'Verification was interrupted before this check was judged.' },
+ }),
+ ),
+ );
+ }
+
+ await statusService.recompute(operationId);
+ // No report context β€” the sweep holds no deliverable. The task is still driven,
+ // which is the whole point: the goal has been waiting on this verdict.
+ await finalizeVerifyRun(db, run.userId, operationId, {}, workspaceId);
+
+ const action = outstanding.length > 0 ? 'abandoned' : 'settled';
+ log('recovered run %s (op %s) as %s', run.id, operationId, action);
+ return action;
+};
diff --git a/packages/database/src/models/__tests__/verifyRun.test.ts b/packages/database/src/models/__tests__/verifyRun.test.ts
new file mode 100644
index 00000000000..3b982f4dcb5
--- /dev/null
+++ b/packages/database/src/models/__tests__/verifyRun.test.ts
@@ -0,0 +1,220 @@
+// @vitest-environment node
+import { eq, sql } from 'drizzle-orm';
+import { beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import { users, verifyRuns } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { AgentOperationModel } from '../agentOperation';
+import { VerifyRunModel } from '../verifyRun';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'verify-run-test-user';
+const otherUserId = 'verify-run-test-other';
+
+const buildRun = async (operationId: string, owner = userId) => {
+ await new AgentOperationModel(serverDB, owner).recordStart({ operationId });
+ const run = await new VerifyRunModel(serverDB, owner).ensureForOperation(operationId);
+ await new VerifyRunModel(serverDB, owner).setPlan(run.id, [
+ {
+ id: 'item-1',
+ index: 0,
+ onFail: 'manual',
+ required: true,
+ title: 'goal met',
+ verifierConfig: {},
+ verifierType: 'llm',
+ },
+ ]);
+ return run.id;
+};
+
+/**
+ * Move a run's `updated_at` back without tripping the `$onUpdate` stamp.
+ *
+ * Deliberately lands on a sub-millisecond remainder (`.xxx456`). `timestamptz`
+ * holds microseconds while a cursor read back through a JS `Date` carries only
+ * milliseconds, so a keyset that compares the raw column against the cursor
+ * fails exactly on rows like these β€” and `now()` produces one only by chance,
+ * which is how the bug reached CI green locally.
+ */
+const backdate = async (runId: string, ms: number) => {
+ await serverDB.execute(
+ sql`update ${verifyRuns}
+ set updated_at = date_trunc('second', now())
+ - make_interval(secs => ${ms / 1000})
+ + interval '123456 microseconds'
+ where id = ${runId}`,
+ );
+};
+
+const statusOf = async (runId: string) => {
+ const [row] = await serverDB
+ .select({ status: verifyRuns.status })
+ .from(verifyRuns)
+ .where(eq(verifyRuns.id, runId));
+ return row?.status ?? null;
+};
+
+beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
+});
+
+describe('VerifyRunModel.claimVerifying', () => {
+ const staleBefore = () => new Date(Date.now() - 30 * 60 * 1000);
+
+ it('claims a planned run and enters verifying', async () => {
+ const runId = await buildRun('op-claim-1');
+
+ await expect(
+ new VerifyRunModel(serverDB, userId).claimVerifying(runId, staleBefore()),
+ ).resolves.toBe(true);
+ expect(await statusOf(runId)).toBe('verifying');
+ });
+
+ it('refuses a second claim while the first is still working', async () => {
+ const runId = await buildRun('op-claim-2');
+ const model = new VerifyRunModel(serverDB, userId);
+ await model.claimVerifying(runId, staleBefore());
+
+ // A redelivered completion must not start a second judge pass over the same plan.
+ await expect(model.claimVerifying(runId, staleBefore())).resolves.toBe(false);
+ });
+
+ it('re-claims a verifying run abandoned before the stale bound', async () => {
+ // The bug this exists for: an attempt entered `verifying` and died mid-judge.
+ // The old `status === 'planned'` gate read its own leftover write and shut
+ // out every retry, stranding the run in `verifying` for good.
+ const runId = await buildRun('op-claim-3');
+ const model = new VerifyRunModel(serverDB, userId);
+ await model.claimVerifying(runId, staleBefore());
+ await backdate(runId, 31 * 60 * 1000);
+
+ await expect(model.claimVerifying(runId, staleBefore())).resolves.toBe(true);
+ });
+
+ it('never claims a settled run', async () => {
+ const runId = await buildRun('op-claim-4');
+ const model = new VerifyRunModel(serverDB, userId);
+ await model.updateStatus(runId, 'failed');
+ await backdate(runId, 31 * 60 * 1000);
+
+ await expect(model.claimVerifying(runId, staleBefore())).resolves.toBe(false);
+ expect(await statusOf(runId)).toBe('failed');
+ });
+
+ it('does not claim another owner’s run', async () => {
+ const runId = await buildRun('op-claim-5', otherUserId);
+
+ await expect(
+ new VerifyRunModel(serverDB, userId).claimVerifying(runId, staleBefore()),
+ ).resolves.toBe(false);
+ expect(await statusOf(runId)).toBe('planned');
+ });
+});
+
+/**
+ * `findStuckVerifying` is deliberately global β€” no user or workspace scope, since
+ * it backs a cross-owner cron. The test database is shared with every other suite,
+ * so these assertions state what must be true of *our* rows (present / absent /
+ * ordered) and never that a page equals exactly them: any stranded row another
+ * suite left behind is legitimately part of the same result.
+ */
+describe('VerifyRunModel.findStuckVerifying', () => {
+ it('returns verifying runs older than the bound, across owners', async () => {
+ const mine = await buildRun('op-stuck-1');
+ const theirs = await buildRun('op-stuck-2', otherUserId);
+ await new VerifyRunModel(serverDB, userId).updateStatus(mine, 'verifying');
+ await new VerifyRunModel(serverDB, otherUserId).updateStatus(theirs, 'verifying');
+ await backdate(mine, 10 * 60 * 1000);
+ await backdate(theirs, 10 * 60 * 1000);
+
+ const stuck = await VerifyRunModel.findStuckVerifying(
+ serverDB,
+ new Date(Date.now() - 5 * 60 * 1000),
+ { limit: 500 },
+ );
+
+ // Both owners' runs, from a query given neither owner.
+ expect(stuck.map((r) => r.id)).toEqual(expect.arrayContaining([mine, theirs]));
+ });
+
+ it('leaves a freshly-entered run alone', async () => {
+ const runId = await buildRun('op-stuck-3');
+ await new VerifyRunModel(serverDB, userId).updateStatus(runId, 'verifying');
+
+ const stuck = await VerifyRunModel.findStuckVerifying(
+ serverDB,
+ new Date(Date.now() - 5 * 60 * 1000),
+ );
+
+ expect(stuck.map((r) => r.id)).not.toContain(runId);
+ });
+
+ it('ignores runs in any other status', async () => {
+ const runId = await buildRun('op-stuck-4');
+ await new VerifyRunModel(serverDB, userId).updateStatus(runId, 'repairing');
+ await backdate(runId, 10 * 60 * 1000);
+
+ const stuck = await VerifyRunModel.findStuckVerifying(
+ serverDB,
+ new Date(Date.now() - 5 * 60 * 1000),
+ );
+
+ expect(stuck.map((r) => r.id)).not.toContain(runId);
+ });
+
+ it('resumes after the cursor so unrecoverable rows cannot starve newer ones', async () => {
+ // The sweep leaves some rows untouched, and an untouched row keeps its
+ // timestamp. Paging past it is the only thing that lets the scan reach the
+ // runs behind it.
+ const first = await buildRun('op-page-1');
+ const second = await buildRun('op-page-2');
+ // A third stranded run belonging to someone else, landing between the two β€”
+ // the scan is global, so the cursor has to be right about ours regardless of
+ // what else shares the window.
+ const interloper = await buildRun('op-page-3', otherUserId);
+ await new VerifyRunModel(serverDB, userId).updateStatus(first, 'verifying');
+ await new VerifyRunModel(serverDB, userId).updateStatus(second, 'verifying');
+ await new VerifyRunModel(serverDB, otherUserId).updateStatus(interloper, 'verifying');
+ await backdate(first, 20 * 60 * 1000);
+ await backdate(interloper, 15 * 60 * 1000);
+ await backdate(second, 10 * 60 * 1000);
+
+ const olderThan = new Date(Date.now() - 5 * 60 * 1000);
+ const scan = await VerifyRunModel.findStuckVerifying(serverDB, olderThan, { limit: 500 });
+ const ids = scan.map((r) => r.id);
+ expect(ids).toEqual(expect.arrayContaining([first, second]));
+ // Oldest first, so the cursor has something to advance past.
+ expect(ids.indexOf(first)).toBeLessThan(ids.indexOf(second));
+
+ const cursor = scan[ids.indexOf(first)];
+ const rest = await VerifyRunModel.findStuckVerifying(serverDB, olderThan, {
+ after: { id: cursor.id, updatedAt: cursor.updatedAt },
+ limit: 500,
+ });
+ const restIds = rest.map((r) => r.id);
+
+ // The whole point: the cursor drops what it already saw and still reaches
+ // everything behind it β€” the row it advanced past cannot starve the rest.
+ expect(restIds).not.toContain(first);
+ expect(restIds).toContain(second);
+ // Guards the guard: if the interloper stopped landing inside the window this
+ // test would quietly stop covering the contaminated case it exists for.
+ expect(restIds).toContain(interloper);
+ });
+
+ it('ignores operation-less rounds β€” there is no rollup to address', async () => {
+ const run = await new VerifyRunModel(serverDB, userId).create({ status: 'verifying' });
+ await backdate(run.id, 10 * 60 * 1000);
+
+ const stuck = await VerifyRunModel.findStuckVerifying(
+ serverDB,
+ new Date(Date.now() - 5 * 60 * 1000),
+ );
+
+ expect(stuck.map((r) => r.id)).not.toContain(run.id);
+ });
+});
diff --git a/packages/database/src/models/verifyRun.ts b/packages/database/src/models/verifyRun.ts
index b304babba83..73cb7753f6e 100644
--- a/packages/database/src/models/verifyRun.ts
+++ b/packages/database/src/models/verifyRun.ts
@@ -6,7 +6,20 @@ import type {
VerifyRunSource,
VerifyRunStatus,
} from '@lobechat/types';
-import { and, asc, desc, eq, ilike, inArray, isNull, lt, or, sql } from 'drizzle-orm';
+import {
+ and,
+ asc,
+ desc,
+ eq,
+ gt,
+ ilike,
+ inArray,
+ isNotNull,
+ isNull,
+ lt,
+ or,
+ sql,
+} from 'drizzle-orm';
import { agentOperations } from '../schemas/agentOperations';
import type { NewVerifyRun, VerifyRunItem } from '../schemas/verify';
@@ -494,6 +507,101 @@ export class VerifyRunModel {
.where(and(eq(verifyRuns.id, runId), this.ownership()));
};
+ /**
+ * Claim the right to run the completion-time verify gate on this run, and
+ * flip it to `verifying` in the same statement. Always go through the
+ * service-layer chokepoint ({@link VerifyStatusService.claimVerifying}).
+ *
+ * The gate used to be a plain `status === 'planned'` read followed by a
+ * separate `verifying` write, which failed in two directions at once: two
+ * completions landing together (a queue redelivery of the terminal step) could
+ * both pass the read, and an attempt that flipped the run and then died left
+ * the gate permanently shut β€” no later attempt could re-enter, so the rollup
+ * was never finished and the run stayed `verifying` forever.
+ *
+ * One conditional UPDATE answers both: exactly one caller wins, and a
+ * `verifying` run untouched since `staleBefore` is read as abandoned and
+ * handed to the new caller.
+ *
+ * @returns true when this caller owns the verification.
+ */
+ claimVerifying = async (runId: string, staleBefore: Date): Promise<boolean> => {
+ const claimed = await this.db
+ .update(verifyRuns)
+ .set({ status: 'verifying' })
+ .where(
+ and(
+ eq(verifyRuns.id, runId),
+ or(
+ eq(verifyRuns.status, 'planned'),
+ and(eq(verifyRuns.status, 'verifying'), lt(verifyRuns.updatedAt, staleBefore)),
+ ),
+ this.ownership(),
+ ),
+ )
+ .returning({ id: verifyRuns.id });
+
+ return claimed.length > 0;
+ };
+
+ /**
+ * One page of runs stranded in `verifying` since before `olderThan`, across
+ * all owners β€” the sweep's input (see `sweepStuckVerifyRuns`).
+ *
+ * No per-user scope, like `TaskModel.findStuckTasks`: this backs a global
+ * cron, and each row carries the owner the recovery is then performed as.
+ * Operation-less rounds are excluded β€” the rollup is addressed by operation,
+ * so there is nothing to recompute for them.
+ *
+ * Paged on the `(updatedAt, id)` keyset rather than returning a fixed oldest-N
+ * slice. The sweep deliberately leaves some rows untouched (a check whose
+ * verifier is still live), and an untouched row keeps its timestamp β€” so a
+ * single oldest-N read would hand back the same unrecoverable rows every tick
+ * and starve every newer stranded run behind them. `id` breaks ties so rows
+ * sharing a timestamp can't be skipped or repeated at a page boundary.
+ *
+ * `updatedAt` is compared/ordered at **millisecond** precision, for the same
+ * reason {@link queryPage} does it: the cursor is read back off a row as a JS
+ * `Date` and so carries only milliseconds, while the column is `timestamptz`
+ * and holds microseconds. Comparing the raw column against the truncated
+ * cursor makes a row with a sub-millisecond remainder satisfy its own
+ * `>` bound β€” it is returned again on the next page, the cursor never gets
+ * past it, and the scan spins on that row instead of reaching the ones behind
+ * it. Truncating both sides keeps the keyset lossless.
+ */
+ static findStuckVerifying = async (
+ db: LobeChatDatabase,
+ olderThan: Date,
+ options?: { after?: { id: string; updatedAt: Date }; limit?: number },
+ ): Promise<VerifyRunItem[]> => {
+ const { after, limit = 200 } = options ?? {};
+
+ // Millisecond-truncated updatedAt β€” the precision the cursor round-trips at.
+ const updatedAtMs = sql`date_trunc('milliseconds', ${verifyRuns.updatedAt})`;
+
+ const conditions = [
+ eq(verifyRuns.status, 'verifying'),
+ lt(verifyRuns.updatedAt, olderThan),
+ isNotNull(verifyRuns.operationId),
+ ];
+
+ if (after) {
+ conditions.push(
+ or(
+ gt(updatedAtMs, after.updatedAt),
+ and(eq(updatedAtMs, after.updatedAt), gt(verifyRuns.id, after.id)),
+ )!,
+ );
+ }
+
+ return db
+ .select()
+ .from(verifyRuns)
+ .where(and(...conditions))
+ .orderBy(asc(updatedAtMs), asc(verifyRuns.id))
+ .limit(limit);
+ };
+
/** Update the denormalized rollup. Always go through the service-layer chokepoint. */
updateStatus = async (runId: string, status: VerifyRunStatus | null): Promise<void> => {
await this.db