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(goal): stop re-dispatching a delivered Work while verification is judging (#19060)

Arvin Xud51d00928728
diff --git a/apps/server/src/services/goal/index.test.ts b/apps/server/src/services/goal/index.test.ts
index 6982647d291..b70a38b5513 100644
--- a/apps/server/src/services/goal/index.test.ts
+++ b/apps/server/src/services/goal/index.test.ts
@@ -33,6 +33,7 @@ import { VerifyPlanGeneratorService } from '../verify/planGenerator';
import { GoalCriteriaGeneratorService } from './criteriaGenerator';
import { LEASE_EXPIRED_ERROR, VERIFICATION_FAILED_ERROR } from './decideNextMove';
import { GoalService } from './index';
+import { VERIFY_SETTLE_GRACE_MS } from './recoveryPolicy';
import type { GoalTickObservation } from './traceObservation';
const serverDB: LobeChatDatabase = await getTestDB();
@@ -228,6 +229,120 @@ describe('GoalService', () => {
runSpy.mockRestore();
});
+ it('does not re-dispatch a delivered Work while verification is still judging', async () => {
+ // A verify-bound Work keeps its task `running` with a completed topic until
+ // the verify run settles, and that judgment routinely outlives the
+ // operation lease. Treating the window as a dead claim released the task
+ // back to backlog, and the next advance paid for a ghost attempt that the
+ // verify settle path then canceled.
+ const runSpy = vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);
+ const service = new GoalService(serverDB, userId);
+ const taskModel = new TaskModel(serverDB, userId);
+ const graph = await service.create({
+ config: { recovery: { operationLeaseTimeoutMs: 60_000 } },
+ title: 'Deliveries wait for verification',
+ work: ['Deliver and wait'],
+ });
+ const created = await service.tick(graph.goal.id);
+ await serverDB.insert(taskTopics).values({
+ operationId: 'op-delivered',
+ seq: 1,
+ status: 'completed',
+ taskId: created.taskId!,
+ userId,
+ });
+ await taskModel.updateStatus(created.taskId!, 'running');
+ await serverDB
+ .update(tasks)
+ .set({ updatedAt: new Date(Date.now() - 10 * 60 * 1000) })
+ .where(eq(tasks.id, created.taskId!));
+
+ const waiting = await service.tick(graph.goal.id);
+
+ expect(waiting).toMatchObject({
+ message: expect.stringContaining('waiting for verification'),
+ outcome: 'waiting_external',
+ taskId: created.taskId,
+ });
+ expect((await taskModel.findById(created.taskId!))?.status).toBe('running');
+ expect(runSpy).not.toHaveBeenCalled();
+ });
+
+ it('reclaims a delivered Work once the verification grace window lapses', async () => {
+ // The hold-off above cannot be unconditional: a verify run that died
+ // silently would otherwise strand the goal forever, which is exactly the
+ // failure mode the sweep exists to break.
+ const service = new GoalService(serverDB, userId);
+ const taskModel = new TaskModel(serverDB, userId);
+ const graph = await service.create({
+ config: { recovery: { operationLeaseTimeoutMs: 60_000 } },
+ title: 'Dead verification is reclaimed',
+ work: ['Deliver into silence'],
+ });
+ const created = await service.tick(graph.goal.id);
+ await serverDB.insert(taskTopics).values({
+ createdAt: new Date(Date.now() - VERIFY_SETTLE_GRACE_MS - 60_000),
+ operationId: 'op-delivered-stale',
+ seq: 1,
+ status: 'completed',
+ taskId: created.taskId!,
+ userId,
+ });
+ await taskModel.updateStatus(created.taskId!, 'running');
+ await serverDB
+ .update(tasks)
+ .set({ updatedAt: new Date(Date.now() - 10 * 60 * 1000) })
+ .where(eq(tasks.id, created.taskId!));
+
+ const released = await service.tick(graph.goal.id);
+
+ expect(released.outcome).toBe('advanced');
+ expect((await taskModel.findById(created.taskId!))?.status).toBe('backlog');
+ });
+
+ it('synthesizes the finding from the delivered topic, not a canceled retry', async () => {
+ // When verification accepts a delivery, the settle path cancels the ghost
+ // retry it superseded β€” leaving the canceled, handoff-less topic as the
+ // newest row. Reading blindly by seq produced findings titled
+ // "Completed: <work>" with no description.
+ const service = new GoalService(serverDB, userId);
+ const taskModel = new TaskModel(serverDB, userId);
+ const graph = await service.create({ title: 'Consume the delivery', work: ['Deliver me'] });
+ const created = await service.tick(graph.goal.id);
+ await serverDB.insert(taskTopics).values([
+ {
+ handoff: {
+ content: 'Delivered content with the full run summary.',
+ summary: 'Delivered summary',
+ title: 'Delivered title',
+ },
+ operationId: 'op-delivered',
+ seq: 1,
+ status: 'completed',
+ taskId: created.taskId!,
+ userId,
+ },
+ {
+ operationId: 'op-ghost-retry',
+ seq: 2,
+ status: 'canceled',
+ taskId: created.taskId!,
+ userId,
+ },
+ ]);
+ await taskModel.updateStatus(created.taskId!, 'completed');
+
+ await service.tick(graph.goal.id);
+
+ const finding = (await service.graph(graph.goal.id)).nodes.find(
+ (node) => node.kind === 'finding',
+ );
+ expect(finding).toMatchObject({
+ description: 'Delivered content with the full run summary.',
+ title: 'Delivered title',
+ });
+ });
+
it('leaves a fresh dispatch claim alone', async () => {
// The same shape a moment after the claim is just a run about to start.
vi.spyOn(TaskRunnerService.prototype, 'runTask').mockRejectedValue(new Error('worker died'));
diff --git a/apps/server/src/services/goal/index.ts b/apps/server/src/services/goal/index.ts
index 5a8fc1a3628..ec77c6ea048 100644
--- a/apps/server/src/services/goal/index.ts
+++ b/apps/server/src/services/goal/index.ts
@@ -44,6 +44,7 @@ import {
resolveMaxConcurrentTasks,
resolveOperationLeaseTimeout,
resolveTaskMaxSteps,
+ VERIFY_SETTLE_GRACE_MS,
} from './recoveryPolicy';
import { TaskRecoveryCoordinator } from './taskRecoveryCoordinator';
import {
@@ -1120,6 +1121,29 @@ export class GoalService {
const staleBefore = new Date(Date.now() - resolveOperationLeaseTimeout(graph.goal));
if (!operationId || !topicId) {
+ // No running topic covers two very different shapes. A verify-bound Work
+ // that delivered keeps its task `running` with a *completed* topic until
+ // the verify run settles, and that judgment β€” a full agent run β€” outlives
+ // the operation lease routinely. Re-dispatching there pays for a duplicate
+ // attempt the verify settle path will cancel, and the canceled retry then
+ // becomes the newest topic and shadows the delivered one. Hold off while
+ // the delivery is fresh; past the grace window, fall through to the
+ // release below so a verify run that died silently cannot strand the
+ // goal forever.
+ const [lastTopic] = await this.taskTopicModel.findWithHandoff(task.id, 1);
+ if (lastTopic?.status === 'completed') {
+ const deliveredAt = lastTopic.completedAt ?? lastTopic.createdAt;
+ if (new Date(deliveredAt).getTime() >= Date.now() - VERIFY_SETTLE_GRACE_MS) {
+ return {
+ goalId: graph.goal.id,
+ message: `Task ${task.identifier} delivered; waiting for verification to settle`,
+ nodeId,
+ outcome: 'waiting_external',
+ taskId: task.id,
+ };
+ }
+ }
+
// A task claimed for dispatch but with no run behind it. Normally this is
// the sliver between the claim and `runTask` creating the topic; if the
// worker died in there it is permanent, and every later advance would
@@ -1362,7 +1386,16 @@ export class GoalService {
const existingFinding = graph.edges.some(
(edge) => edge.sourceNodeId === nodeId && edge.kind === 'produces',
);
- const [latest] = await this.taskTopicModel.findWithHandoff(taskId, 1);
+ // The newest row by seq can be a retry that was canceled when verification
+ // accepted an earlier delivery β€” the settle path cancels the in-flight
+ // attempt it superseded. The finding must be synthesized from the run that
+ // actually delivered, so prefer the newest completed topic (with a handoff
+ // when one exists) over whatever happens to be last.
+ const recent = await this.taskTopicModel.findWithHandoff(taskId, 10);
+ const latest =
+ recent.find((topic) => topic.status === 'completed' && topic.handoff) ??
+ recent.find((topic) => topic.status === 'completed') ??
+ recent[0];
const completedWork = await this.workModel.registerTask({
changeType: 'updated',
rootOperationId: latest?.operationId,
diff --git a/apps/server/src/services/goal/recoveryPolicy.ts b/apps/server/src/services/goal/recoveryPolicy.ts
index 7c7e8aec7f7..730c4284030 100644
--- a/apps/server/src/services/goal/recoveryPolicy.ts
+++ b/apps/server/src/services/goal/recoveryPolicy.ts
@@ -14,6 +14,15 @@ const DEFAULT_OPERATION_LEASE_TIMEOUT_MS = 5 * 60 * 1000;
// so a transient missed write cannot reclaim a healthy operation.
export const MIN_OPERATION_LEASE_TIMEOUT_MS = 3 * 60 * 1000;
+/**
+ * How long a delivered Work may sit with verification pending before the
+ * coordinator treats the delivery as abandoned and re-dispatches. The verify
+ * judge is a full agent run β€” tens of minutes on a large delivery β€” so this
+ * sits far above the operation lease, which is scaled to heartbeat gaps, not
+ * judgments.
+ */
+export const VERIFY_SETTLE_GRACE_MS = 60 * 60 * 1000;
+
/** How many attempts one Work gets before the coordinator opens a decision gate. */
export const resolveTaskAttemptBudget = (goal: GoalItem): number => {
const configured = goal.config?.recovery?.maxAttemptsPerTask;