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 the manager claim from re-queuing itself forever (#22209)

Arvin Xu02b4488edee2
diff --git a/apps/server/src/services/goal/advanceGoal.test.ts b/apps/server/src/services/goal/advanceGoal.test.ts
index 6dcfa58b094..c1ea6d6ce7c 100644
--- a/apps/server/src/services/goal/advanceGoal.test.ts
+++ b/apps/server/src/services/goal/advanceGoal.test.ts
@@ -231,8 +231,11 @@ describe('advanceGoal trajectory recording', () => {
// Appending is read-modify-write on one object; without this the settle,
// sweep and manual advances that overlap on a goal would pick the same
// `seq` and the last writer would drop the others.
- expect(mocks.execute).toHaveBeenCalledTimes(1);
- expect(JSON.stringify(mocks.execute.mock.calls[0][0])).toContain('pg_advisory_xact_lock');
+ expect(mocks.execute).toHaveBeenCalledTimes(2);
+ // Bounded first: an advance stuck behind a dead holder gives up instead of
+ // waiting out the function timeout with its transaction open.
+ expect(JSON.stringify(mocks.execute.mock.calls[0][0])).toContain('lock_timeout');
+ expect(JSON.stringify(mocks.execute.mock.calls[1][0])).toContain('pg_advisory_xact_lock');
});
it('writes the observation row while the goal is still running, not only at the end', async () => {
diff --git a/apps/server/src/services/goal/goalTraceRecorder.ts b/apps/server/src/services/goal/goalTraceRecorder.ts
index c9b50dd5953..3fa0e7035b9 100644
--- a/apps/server/src/services/goal/goalTraceRecorder.ts
+++ b/apps/server/src/services/goal/goalTraceRecorder.ts
@@ -24,6 +24,7 @@ const log = debug('lobe-server:goal-trace');
* feature's. `0x676f_616c` is ASCII `goal`, and fits int4.
*/
const GOAL_TRACE_LOCK_NAMESPACE = 0x67_6f_61_6c;
+const GOAL_TRACE_LOCK_TIMEOUT = '10s';
/**
* Collects one advance's ticks and writes them into the goal's trajectory.
@@ -100,6 +101,11 @@ export class GoalAdvanceRecorder {
*/
private async serializedPerGoal<T>(run: (tx: LobeChatDatabase) => Promise<T>): Promise<T> {
return this.db.transaction(async (tx) => {
+ // Bounded: a trajectory write is best-effort, and an advance queued behind
+ // a stuck holder must give up rather than wait out the function timeout.
+ // Unbounded waits piled hundreds of advances onto one goal's lock, each
+ // killed at 300s with its transaction still open, holding the queue shut.
+ await tx.execute(sql.raw(`SET LOCAL lock_timeout = '${GOAL_TRACE_LOCK_TIMEOUT}'`));
await tx.execute(
sql`SELECT pg_advisory_xact_lock(${GOAL_TRACE_LOCK_NAMESPACE}, hashtext(${this.goalId}))`,
);
diff --git a/apps/server/src/services/goal/manager.test.ts b/apps/server/src/services/goal/manager.test.ts
index b3841e53881..a80b2a831f8 100644
--- a/apps/server/src/services/goal/manager.test.ts
+++ b/apps/server/src/services/goal/manager.test.ts
@@ -37,6 +37,7 @@ import { deviceGateway } from '../deviceGateway';
import { GoalCriteriaGeneratorService } from './criteriaGenerator';
import { GoalService } from './index';
import { decideFailedTurn, GoalManagerService, MAX_FAILED_MANAGER_TURNS } from './manager';
+import { withoutGoalReport } from './report';
import * as scheduler from './scheduler';
import { GoalStartService } from './start';
import { answerDistill, pendingRelease as heldRelease } from './testUtils';
@@ -850,6 +851,34 @@ describe('CLI main Agent planning', () => {
expect((await model().findById(id))!.config!.managerState!.turns).toBe(turnsBefore);
});
+ it('claims the next turn on a Goal that carries a wrap-up report node', async () => {
+ // Regression: the coordinator hands the manager its report-free view, but the
+ // claim re-read the full graph and compared their snapshots. With a report
+ // node they never matched, so every advance answered "Another advance owns
+ // the planning turn" and queued itself again five seconds later, forever.
+ const { id, op } = await start();
+ await ops().recordCompletion(op.id, { status: 'done' });
+ expect((await service().tick(id)).outcome).toBe('advanced');
+ const reportNode = await new GoalGraphModel(db, userId).createNode(id, {
+ kind: 'task',
+ title: 'Write the Goal report',
+ });
+ const row = (await model().findById(id))!;
+ await db
+ .update(goals)
+ .set({ config: { ...row.config, report: { nodeId: reportNode.id } } as GoalConfig })
+ .where(eq(goals.id, id));
+ const turnsBefore = (await model().findById(id))!.config!.managerState!.turns;
+
+ const result = await manager().advance(withoutGoalReport(await service().graph(id)), {
+ mayStartTurn: true,
+ });
+
+ expect(result?.message).toBe('Main Agent dispatched with CLI planning access');
+ expect(vi.mocked(AiAgentService.prototype.execAgent)).toHaveBeenCalledTimes(2);
+ expect((await model().findById(id))!.config!.managerState!.turns).toBe(turnsBefore + 1);
+ });
+
it('opens the next planning turn in the new supervisor history after a handoff', async () => {
const { id, state, op } = await start();
await ops().recordCompletion(op.id, { status: 'done' });
diff --git a/apps/server/src/services/goal/manager/index.surface.test.ts b/apps/server/src/services/goal/manager/index.surface.test.ts
index bdbe74d1342..08466c5490f 100644
--- a/apps/server/src/services/goal/manager/index.surface.test.ts
+++ b/apps/server/src/services/goal/manager/index.surface.test.ts
@@ -3,6 +3,7 @@ import { describe, expect, it } from 'vitest';
import type { LobeChatDatabase } from '@/database/type';
+import { withoutGoalReport } from '../report';
import * as managerModule from './index';
import {
answeredProblem,
@@ -97,6 +98,28 @@ describe('goal manager public surface', () => {
).not.toBe(managerSnapshot(graph));
});
+ it('hashes the full graph and the coordinator view of it alike', () => {
+ // The tick hands the manager `withoutGoalReport(graph)`, while the turn claim
+ // re-reads the full graph under the lock. A Goal carrying a report node must
+ // not look changed between the two, or the claim never succeeds.
+ const graph = {
+ decisions: [],
+ edges: [{ kind: 'depends_on', sourceNodeId: 'n1', targetNodeId: 'report' }],
+ goal: {
+ config: { manager: {}, report: { nodeId: 'report' } },
+ maxRounds: 3,
+ maxTotalCost: null,
+ requirement: 'r',
+ },
+ nodes: [
+ { id: 'n1', status: 'resolved', updatedAt: new Date(1) },
+ { id: 'report', status: 'active', updatedAt: new Date(1) },
+ ],
+ workVersions: [{ nodeId: 'report', relation: 'output', workVersionId: 'w1' }],
+ } as unknown as Parameters<typeof managerSnapshot>[0];
+ expect(managerSnapshot(withoutGoalReport(graph))).toBe(managerSnapshot(graph));
+ });
+
it('parses every plan action through one schema', () => {
expect(goalPlanSchema.parse({ action: 'verify', reason: 'done' })).toEqual({
action: 'verify',
diff --git a/apps/server/src/services/goal/manager/turnState.ts b/apps/server/src/services/goal/manager/turnState.ts
index 11e342284df..77572074f26 100644
--- a/apps/server/src/services/goal/manager/turnState.ts
+++ b/apps/server/src/services/goal/manager/turnState.ts
@@ -8,6 +8,8 @@ import { GoalGraphModel } from '@/database/models/goalGraph';
import { goals } from '@/database/schemas/goal';
import type { LobeChatDatabase } from '@/database/type';
+import { withoutGoalReport } from '../report';
+
/** The owner a manager operation runs as; every extracted stage takes it explicitly. */
export interface ManagerContext {
db: LobeChatDatabase;
@@ -40,8 +42,14 @@ export const managerTurnToken = (goalId: string) => `${goalId}_${randomUUID()}`;
* made an in-flight planning turn go stale whenever a background loop rewrote a
* node it did not own (a coordinator retry re-activating an already-active task
* rejected every submit with "Stale planning input" until the turn expired).
+ *
+ * The wrap-up report node is left out too. The coordinator hands the manager its
+ * report-free view, while the claim and the plan admission re-read the full
+ * graph; hashing both as they came made every claim on a Goal with a report
+ * node look stale, so `startTurn` re-queued itself every five seconds forever.
*/
-export const managerSnapshot = (graph: GoalGraphSnapshot) => {
+export const managerSnapshot = (input: GoalGraphSnapshot) => {
+ const graph = withoutGoalReport(input);
// Coordinator receipts are not planning input: arming a Task's quota wake while a
// turn runs must not make that turn's plan stale, and neither may the system
// planner's lease — a hand-over starts the turn while the lease is still held